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([issue-3109]): add/remove universe style references as server-side deltas
[._.]/ Adam Eivy8cebc5996a39
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bfc3efb415..16c2209ccc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -32,6 +32,8 @@## Universe art references+- **[issue-3109] Adding and removing art references is now reliable no matter what else is changing them.** Each add or remove sends just that one change instead of re-sending the whole list, and the change is applied to the universe's current, saved state. So two removals in quick succession both stick, an add between them survives, and — new here — a change made by another machine you sync with, or by deleting the underlying image from your gallery, can no longer be undone by a reference edit that started before it. The 20-reference limit is now checked against what's actually saved rather than what your browser last saw.+- **[issue-3099] Adding or removing an art reference no longer flickers back when you navigate away and return mid-save** — if you changed a universe's art references and switched to another universe and back before the change finished saving, a slower page refresh could briefly restore the pre-change list on screen, making the next add or remove operate on the wrong set. The saved change now always wins over the older refresh it raced.## CoS quick task templatesdiff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.jsindex e9a2250c93..bc5f3c65de 100644--- a/client/src/hooks/useUniverseDraft.js+++ b/client/src/hooks/useUniverseDraft.js@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import toast from '../components/ui/Toast';import {+ addUniverseStyleReference,createUniverse,deleteUniverse,getProviders,@@ -10,9 +11,9 @@ import {listLorasFull,listUniverses,listWorldRuns,+ removeUniverseStyleReference,updateUniverse,WORLD_LOCKABLE_FIELDS,- WORLD_STYLE_REFERENCES_MAX,ensureInfluences,} from '../services/api';import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';@@ -90,66 +91,33 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {const savedDraftSnapshotRef = useRef(universeDraftSnapshot(createEmptyUniverseDraft()));const savedStyleSnapshotRef = useRef(ensureInfluences(createEmptyUniverseDraft().influences));const pendingCanonAdditionsRef = useRef(emptyPendingCanon());- // Authoritative per-universe styleReferences state, keyed by universe id —- // both persistStyleReference (add) and removeStyleReference (remove) read- // their base array from and write their result back to the entry for the- // universe they're actually mutating (`targetId`, captured at call time),- // never a single shared slot. draftRef only syncs after a React effect,- // which can still be one render behind when two mutations fire before- // either PATCH resolves — reading a single shared "current" snapshot would- // let the slower response's wholesale-replace PATCH undo the other- // mutation's change, and — the reason this is keyed by id rather than a- // single ref reset on every selection change — a switch away and back- // (A → B → A) would otherwise permanently lose A's in-flight state instead- // of correctly reconciling with it once it resolves. removeStyleReference- // additionally serializes same-universe calls through the matching queue- // entry so back-to-back removals on one universe never overlap; different- // universes' queues are independent.- //- // Each entry is `{ references, guidance, epoch }`, where `epoch` counts the- // MUTATION responses folded in so far. The epoch version-gates the other- // writer — the hydration effect's `getUniverse` — against the last reordering- // race: a mutation M issued before the user navigates away and back, and the- // re-hydration GET G issued on the return. When M resolves first, G's body is- // a PRE-mutation read, so letting it write would silently revert M- // client-side. G captures the epoch when it is ISSUED and keeps its own body- // only if no mutation landed while it was in flight.- //- // `guidance` is `{ styleNotes, influences }` when the mutation was an ADOPT —- // that PATCH writes the style guide in the SAME request as the references, so- // both halves are equally stale in a losing G. Overriding only the references- // would let G revert the adopted guidance AND (via markDraftSaved) bank the- // reverted values as the saved baseline, so the draft reads clean and the- // next general Save pushes the stale guidance back server-side — a worse- // outcome than the client-only revert this guard exists to stop. The override- // is scoped to exactly the fields the winning PATCH wrote; every other field- // still comes from G, which may legitimately be fresher (peer sync, canon).- //- // The guide carries its OWN `guidanceEpoch` rather than riding the reference- // epoch, because the two move independently: a plain add/remove bumps `epoch`- // without writing the guide. Overlaying on the reference epoch alone would- // let such a mutation resurrect a long-settled adopt over a newer peer edit- // that G legitimately carries. Overlay only when a PATCH wrote the guide- // AFTER G was issued.- //- // The guard is deliberately "a mutation always beats a concurrent GET", not a- // monotonic issued-at sequence shared by all writers: G is issued AFTER M yet- // reads state the server may not have written M into yet, so ordering by- // issue time would make a late-resolving M lose to an earlier-issued G —- // reintroducing the A → B → A loss fixed above. Keeping `epoch` in the same- // record as the values it guards is what makes "the epoch moves whenever- // those values do" structural rather than a convention writers must remember.- const styleReferenceQueuesRef = useRef(new Map());- const styleReferenceStatesRef = useRef(new Map());// Mirrors `selectedId` synchronously during render (not via a passive// effect, which runs one tick later and would leave a window where a- // resolving PATCH still sees the OLD selection as current). Mutators- // compare against this — not the `selectedId` closure value — to decide- // whether their result should still touch the currently DISPLAYED draft;- // the per-id snapshot/queue writes above always apply regardless, so a- // save for a universe the user has navigated away from is never lost.+ // resolving request still sees the OLD selection as current). The style+ // reference mutators compare against this — not the `selectedId` closure+ // value — to decide whether their result should still touch the currently+ // DISPLAYED draft, so a response for a universe the user has navigated away+ // from is dropped from the view instead of poisoning a different universe's+ // draft. Nothing is lost by dropping it: the mutation is already persisted+ // server-side, and returning to that universe re-reads it (#3109 — the+ // client no longer caches a base array that would need reconciling).const selectedIdRef = useRef(selectedId);selectedIdRef.current = selectedId;+ // Per-universe count of style-reference mutations that have landed. The+ // hydration GET captures it before it is issued and RE-READS if it moved+ // while the GET was in flight, because such a GET may carry a body the+ // server read before that mutation committed — applying it would blank the+ // reference the user just added (client-side only; the server has it).+ //+ // This is a read-again gate, not the value cache it replaced: the client+ // holds no references array of its own, so "who wins" is never decided+ // locally — the re-read simply asks the server again, which is why it also+ // covers writers the client can't see (peer sync, the image-delete purge).+ const styleMutationSeqRef = useRef(new Map());+ const styleMutationSeq = useCallback((id) => styleMutationSeqRef.current.get(id) || 0, []);+ const bumpStyleMutationSeq = useCallback((id) => {+ styleMutationSeqRef.current.set(id, styleMutationSeq(id) + 1);+ }, [styleMutationSeq]);useEffect(() => () => { mountedRef.current = false; }, []);useEffect(() => { draftRef.current = draft; }, [draft]);@@ -158,54 +126,6 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {pendingCanonAdditionsRef.current = emptyPendingCanon();}, []);- const styleReferenceState = useCallback(- (id) => styleReferenceStatesRef.current.get(id)- ?? { references: null, guidance: null, guidanceEpoch: 0, epoch: 0 },- [],- );-- // Record a mutation's confirmed values for `id`, bumping its epoch so any- // hydration GET still in flight for that universe knows its body is stale.- // `guidance` is null for a mutation that didn't write the style guide; the- // previous entry's guidance carries forward (so an adopt followed by a plain- // add/remove during one GET doesn't drop the adopted values) but keeps its- // ORIGINAL `guidanceEpoch` — the epoch at which a PATCH last actually wrote- // the style guide. That stamp is what lets the hydration arbiter tell "this- // guidance is newer than the GET" from "the GET already contains it."- const applyStyleReferenceMutation = useCallback((id, references, guidance = null) => {- const previous = styleReferenceState(id);- const epoch = previous.epoch + 1;- styleReferenceStatesRef.current.set(id, {- references,- epoch,- guidance: guidance ?? previous.guidance,- guidanceEpoch: guidance ? epoch : previous.guidanceEpoch,- });- }, [styleReferenceState]);-- // Fold a hydration GET's styleReferences into `id`'s state, unless a mutation- // resolved while the GET was in flight (epoch moved) — in which case that- // mutation's values stand. Returns the draft fields the winning writer owns,- // to be spread LAST over the hydrated draft so they override the server read.- const applyStyleReferenceHydration = useCallback((id, issuedEpoch, references) => {- const state = styleReferenceState(id);- if (state.epoch !== issuedEpoch) {- // References always come from the winning mutation. The style guide only- // does when a PATCH actually wrote it AFTER this GET was issued- // (`guidanceEpoch > issuedEpoch`) — otherwise this GET already read that- // guidance back from the server, and overlaying the stashed copy would- // clobber a genuinely newer value the GET carries (a peer edit made while- // the user was on another universe) and — via markDraftSaved — bank the- // clobbered value so a later general Save pushes it back server-side.- return {- styleReferences: state.references,- ...(state.guidanceEpoch > issuedEpoch ? state.guidance : null),- };- }- styleReferenceStatesRef.current.set(id, { ...state, references });- return { styleReferences: references };- }, [styleReferenceState]);-const markDraftSaved = useCallback((snapshotSource) => {savedDraftSnapshotRef.current = universeDraftSnapshot(snapshotSource);savedStyleSnapshotRef.current = ensureInfluences(snapshotSource?.influences);@@ -255,10 +175,6 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {setPendingDeleteId(null);setCanonDirty(false);clearPendingCanonAdditions();- // No styleReference queue/snapshot reset needed here — both are keyed by- // universe id (see styleReferenceQueuesRef/styleReferenceStatesRef- // above), so switching away and back naturally finds each universe's own- // state exactly as it left it.if (!selectedId) {const empty = createEmptyUniverseDraft();setDraft(empty);@@ -267,12 +183,20 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {return undefined;}let cancelled = false;- // Captured BEFORE the fetch is issued — see styleReferenceStatesRef.- const issuedEpoch = styleReferenceState(selectedId).epoch;+ // Captured before the fetch is issued — see styleMutationSeqRef.+ const issuedSeq = styleMutationSeq(selectedId);Promise.all([getUniverse(selectedId).catch(() => null),listWorldRuns(selectedId).catch(() => []),- ]).then(([universe, nextRuns]) => {+ ]).then(async ([fetched, nextRuns]) => {+ if (cancelled) return;+ // A style-reference mutation landed while this GET was in flight, so its+ // body may predate that write. Re-read instead of applying it — the+ // second read is issued after the mutation's response, so it necessarily+ // reflects the committed write.+ const universe = (fetched && styleMutationSeq(selectedId) !== issuedSeq)+ ? await getUniverse(selectedId).catch(() => fetched)+ : fetched;if (cancelled) return;if (universe) {const hydrated = {@@ -286,18 +210,6 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {styleReferences: universe.styleReferences || [],locked: universe.locked || {},llm: universe.llm || { provider: null, model: null },- // Refresh this universe's styleReferences snapshot from the server on- // every successful hydration — a stale map entry from an earlier- // local mutation (or absence of one, on first visit) must not shadow- // changes made while this universe wasn't selected (peer sync, the- // image-delete purge route). The next add/remove needs this fresh- // baseline, not a leftover cache (codex review finding) — except when- // a mutation resolved while this GET was in flight, in which case- // this spread overrides the fields THAT PATCH wrote with its newer- // confirmed values (see styleReferenceStatesRef). Spread LAST so it- // wins over the server read above; markDraftSaved then banks the- // overridden values, not the stale ones.- ...applyStyleReferenceHydration(selectedId, issuedEpoch, universe.styleReferences || []),};setDraft(hydrated);markDraftSaved(hydrated);@@ -305,7 +217,7 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {setRuns(nextRuns);});return () => { cancelled = true; };- }, [selectedId, applyStyleReferenceHydration, styleReferenceState]);+ }, [selectedId, styleMutationSeq]);const handleSave = async () => {if (!draft.name?.trim()) {@@ -414,60 +326,23 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {const updateDraft = useCallback((patch) => setDraft((current) => ({ ...current, ...patch })), []);- const persistStyleReference = useCallback(async ({ reference, proposed, adopt }) => {- if (!selectedId || !reference) return false;- const targetId = selectedId;- const current = draftRef.current || draft;- const capturedStyle = {- styleNotes: current.styleNotes || '',- influences: ensureInfluences(current.influences),- };- // Per-universe snapshot removeStyleReference also reads/writes — reading- // draftRef here instead would miss a removal still settling for the same- // universe and could resurrect the item it just removed once this add's- // wholesale-replace PATCH lands.- const baseStyleReferences = styleReferenceState(targetId).references- ?? (targetId === current.id && Array.isArray(current.styleReferences) ? current.styleReferences : []);- if (baseStyleReferences.length >= WORLD_STYLE_REFERENCES_MAX) {- toast.error(`A universe can hold up to ${WORLD_STYLE_REFERENCES_MAX} art references`);- return false;- }- const styleReferences = [...baseStyleReferences, reference];- const patch = {- styleReferences,- ...(adopt ? {- styleNotes: proposed?.styleNotes || '',- influences: ensureInfluences(proposed?.influences),- } : {}),- };- const updated = await updateUniverse(targetId, patch, { silent: true }).catch((error) => {- toast.error(`Reference save failed: ${error.message}`);- return null;- });- if (!updated) return false;- // Keep targetId's own snapshot current regardless of what's currently- // selected — a later add/remove for targetId (including one after the- // user navigates away and back) must build from this result, not a- // pre-save list (codex review finding: an A→B→A round trip must not lose- // A's in-flight save). The epoch bump invalidates any re-hydration GET for- // targetId still in flight — see styleReferenceStatesRef. On the adopt- // path the SAME PATCH wrote the style guide, so hand that over too or a- // losing GET reverts the adopted guidance while the references survive.- applyStyleReferenceMutation(targetId, updated.styleReferences || [], adopt ? {- styleNotes: updated.styleNotes || '',- influences: ensureInfluences(updated.influences),- } : null);- // But only touch the currently DISPLAYED draft if the user is still on- // targetId — applying it otherwise would poison a DIFFERENT, now-selected- // universe's state with targetId's references (codex review finding).- // selectedIdRef mirrors selectedId synchronously during render (not via a- // passive effect), so there is no timing window where a resolving PATCH- // sees a stale "current selection".+ // Fold one style-reference mutation's response (the full updated universe)+ // into the DISPLAYED draft — but only when the user is still on the universe+ // that was mutated; otherwise applying it would poison a different,+ // now-selected universe's draft. Nothing is lost by dropping it: the change+ // is already persisted, and the server owns the array now.+ //+ // `adopt` is true when the same request also wrote the style guide, in which+ // case the guide fields are folded in too (and banked as saved) unless the+ // user edited them while the request was in flight.+ const applyStyleReferenceResult = useCallback((targetId, updated, { adopt = false, capturedStyle = null } = {}) => {+ bumpStyleMutationSeq(targetId);if (selectedIdRef.current === targetId) {if (adopt) markStyleGuidanceSaved(updated);setDraft((latest) => {- const styleUnchangedDuringSave = latest.styleNotes === capturedStyle.styleNotes- && sameJsonShape(ensureInfluences(latest.influences), capturedStyle.influences);+ const styleUnchangedDuringSave = !capturedStyle+ || (latest.styleNotes === capturedStyle.styleNotes+ && sameJsonShape(ensureInfluences(latest.influences), capturedStyle.influences));return {...latest,styleReferences: updated.styleReferences || [],@@ -480,57 +355,53 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {});}setWorlds((previous) => upsertByIdPrepend(previous, updated));+ }, [bumpStyleMutationSeq, markStyleGuidanceSaved]);++ // Add one art reference. The request carries ONLY the addition — the server+ // appends it to the freshest persisted list inside the universe record's+ // write queue (#3109), so this never needs a base array and can't lose a+ // concurrent removal, a peer edit, or the image-delete purge. The cap is+ // enforced there too, against real state rather than a client cache.+ const persistStyleReference = useCallback(async ({ reference, proposed, adopt }) => {+ if (!selectedId || !reference) return false;+ const targetId = selectedId;+ const current = draftRef.current || draft;+ const capturedStyle = {+ styleNotes: current.styleNotes || '',+ influences: ensureInfluences(current.influences),+ };+ const updated = await addUniverseStyleReference(targetId, {+ reference,+ adopt: adopt ? {+ styleNotes: proposed?.styleNotes || '',+ influences: ensureInfluences(proposed?.influences),+ } : undefined,+ }, { silent: true }).catch((error) => {+ toast.error(`Reference save failed: ${error.message}`);+ return null;+ });+ if (!updated) return false;+ applyStyleReferenceResult(targetId, updated, { adopt: !!adopt, capturedStyle });toast.success(adopt ? 'Art reference added and style guide updated' : 'Art reference added');return true;- }, [applyStyleReferenceMutation, draft, markStyleGuidanceSaved, selectedId, styleReferenceState]);+ }, [applyStyleReferenceResult, draft, selectedId]);- const removeStyleReference = useCallback((referenceId) => {- if (!selectedId) return Promise.resolve(false);+ // Remove one art reference by id. Also a delta, so back-to-back removals on+ // one universe no longer need a client-side queue — the server's record+ // write queue serializes them and each filters the freshest persisted list.+ const removeStyleReference = useCallback(async (referenceId) => {+ if (!selectedId) return false;const targetId = selectedId;- const current = draftRef.current || draft;- // Chain onto targetId's OWN queue (not a shared one) so two removals on- // the SAME universe never overlap, while removals on a DIFFERENT- // universe are unaffected — this task can be dequeued well after the user- // has switched away from and even back to targetId, so it must resolve- // its base from targetId's own tracked state, never from whatever- // universe happens to be selected when its turn comes up.- const queue = styleReferenceQueuesRef.current.get(targetId) ?? Promise.resolve();- const task = queue.then(async () => {- const base = styleReferenceState(targetId).references- ?? (targetId === current.id && Array.isArray(current.styleReferences) ? current.styleReferences : []);- const styleReferences = base.filter((item) => item.id !== referenceId);- const updated = await updateUniverse(targetId, { styleReferences }, { silent: true }).catch((error) => {+ const updated = await removeUniverseStyleReference(targetId, referenceId, { silent: true })+ .catch((error) => {toast.error(`Reference removal failed: ${error.message}`);return null;});- if (!updated) return false;- // Keep targetId's own snapshot current regardless of what's currently- // selected (codex review finding: an A→B→A round trip must not lose- // A's in-flight removal). The epoch bump invalidates any re-hydration- // GET for targetId still in flight — see styleReferenceStatesRef.- applyStyleReferenceMutation(targetId, updated.styleReferences || []);- // Only touch the currently DISPLAYED draft if the user is still on- // targetId — selectedIdRef mirrors selectedId synchronously during- // render, so there is no passive-effect timing window where a- // resolving PATCH sees a stale "current selection" (codex review- // finding).- if (selectedIdRef.current === targetId) {- setDraft((latest) => ({- ...latest,- styleReferences: updated.styleReferences || [],- updatedAt: updated.updatedAt,- }));- }- setWorlds((previous) => upsertByIdPrepend(previous, updated));- toast.success('Art reference removed');- return true;- });- // Keep targetId's queue alive even if this removal failed, so the NEXT- // removal on the SAME universe still runs (in its turn) rather than- // inheriting a rejected chain.- styleReferenceQueuesRef.current.set(targetId, task.catch(() => {}));- return task;- }, [applyStyleReferenceMutation, draft, selectedId, styleReferenceState]);+ if (!updated) return false;+ applyStyleReferenceResult(targetId, updated);+ toast.success('Art reference removed');+ return true;+ }, [applyStyleReferenceResult, selectedId]);const handleCanonChange = useCallback((updated) => {if (!updated) return;diff --git a/client/src/hooks/useUniverseDraft.test.jsx b/client/src/hooks/useUniverseDraft.test.jsxindex d0b2f48d5e..9343636011 100644--- a/client/src/hooks/useUniverseDraft.test.jsx+++ b/client/src/hooks/useUniverseDraft.test.jsx@@ -2,6 +2,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';const apiMocks = vi.hoisted(() => ({+ addUniverseStyleReference: vi.fn(),createUniverse: vi.fn(),deleteUniverse: vi.fn(),getProviders: vi.fn(),@@ -11,6 +12,7 @@ const apiMocks = vi.hoisted(() => ({listLorasFull: vi.fn(),listUniverses: vi.fn(),listWorldRuns: vi.fn(),+ removeUniverseStyleReference: vi.fn(),updateUniverse: vi.fn(),WORLD_CATEGORY_KEY_MAX: 64,WORLD_CATEGORIES: ['characters', 'places', 'objects'],@@ -46,8 +48,16 @@ const universe = {objects: [],};+// Stand-in for the server's authoritative styleReferences list, keyed by+// universe id. The delta endpoints append/filter THIS — not a client-held base+// array — which is the whole point of #3109: the client sends only the change,+// so two mutations compose no matter what order their responses arrive in.+let serverReferences;+const serverRefsFor = (id) => serverReferences.get(id) ?? [];+beforeEach(() => {vi.clearAllMocks();+ serverReferences = new Map();apiMocks.listUniverses.mockResolvedValue([universe]);apiMocks.getProviders.mockResolvedValue({ providers: [], activeProvider: null });apiMocks.listImageModels.mockResolvedValue([]);@@ -56,6 +66,16 @@ beforeEach(() => {apiMocks.getUniverse.mockResolvedValue(universe);apiMocks.listWorldRuns.mockResolvedValue([{ id: 'run-1' }]);apiMocks.updateUniverse.mockImplementation(async (id, payload) => ({ ...universe, id, ...payload }));+ apiMocks.addUniverseStyleReference.mockImplementation(async (id, { reference, adopt } = {}) => {+ const next = [...serverRefsFor(id), reference];+ serverReferences.set(id, next);+ return { ...universe, id, styleReferences: next, ...(adopt || {}) };+ });+ apiMocks.removeUniverseStyleReference.mockImplementation(async (id, referenceId) => {+ const next = serverRefsFor(id).filter((ref) => ref.id !== referenceId);+ serverReferences.set(id, next);+ return { ...universe, id, styleReferences: next };+ });});const renderDraft = () => {@@ -126,7 +146,20 @@ describe('useUniverseDraft', () => {expect(payload.characters).not.toContainEqual({ name: 'Stale Draft Character' });});- it('atomically adds a reference and adopted guidance without clearing unrelated dirty edits', async () => {+ // ---- Art style references (#3109) ----+ //+ // These now assert the DELTA contract: each mutation sends only the change+ // and the server applies it to the freshest persisted list inside the+ // universe record's write queue. That removes the client-side base array+ // whose staleness the previous six review-driven fixes were guarding —+ // sequential-remove ordering, add/remove interleaving, cross-universe+ // corruption, and the A→B→A round trip are all structurally impossible when+ // the client never holds the array. What remains worth pinning is the+ // request SHAPE, the display-side reconciliation (which universe's draft a+ // response is allowed to touch), and the one race the server can't see: a+ // hydration GET that raced a mutation and may carry a pre-write body.++ it('adds a reference and adopted guidance in one request, without clearing unrelated dirty edits', async () => {const { result } = renderDraft();await waitFor(() => expect(result.current.draft.id).toBe('u1'));act(() => result.current.updateDraft({ premise: 'Unsaved concurrent premise' }));@@ -148,12 +181,15 @@ describe('useUniverseDraft', () => {});});- const payload = apiMocks.updateUniverse.mock.calls.at(-1)[1];- expect(payload).toEqual({- styleReferences: [reference],- styleNotes: 'Tactile and muted',- influences: { embrace: ['ink wash'], avoid: ['gloss'] },- });+ // The request carries the ADDITION plus the guidance the same write+ // adopts — never a whole-array replace.+ expect(apiMocks.addUniverseStyleReference).toHaveBeenCalledWith('u1', {+ reference,+ adopt: {+ styleNotes: 'Tactile and muted',+ influences: { embrace: ['ink wash'], avoid: ['gloss'] },+ },+ }, { silent: true });expect(result.current.draft).toMatchObject({premise: 'Unsaved concurrent premise',styleNotes: 'Tactile and muted',@@ -162,365 +198,207 @@ describe('useUniverseDraft', () => {expect(result.current.isDraftDirty()).toBe(true);});- it('removes one style reference through its targeted patch', async () => {- const reference = {- id: 'style-ref-1',- title: 'Ink wash',- prompt: 'Granular ink wash',- imageRefs: ['reference.png'],- };+ it('adds a reference without adopting guidance when the user declines the style guide', async () => {+ const { result } = renderDraft();+ await waitFor(() => expect(result.current.draft.id).toBe('u1'));++ const reference = { id: 'style-ref-1', title: 'Ink wash', prompt: 'wash', imageRefs: ['a.png'] };+ await act(async () => {+ await result.current.persistStyleReference({+ reference,+ proposed: { styleNotes: 'Ignored', influences: { embrace: ['ignored'], avoid: [] } },+ adopt: false,+ });+ });++ // No `adopt` key at all — a reference-only add must not carry style+ // guidance the user explicitly declined.+ expect(apiMocks.addUniverseStyleReference).toHaveBeenCalledWith(+ 'u1',+ { reference, adopt: undefined },+ { silent: true },+ );+ expect(result.current.draft.styleNotes).toBe('');+ });++ it('removes one reference by id rather than patching the surviving list', async () => {+ const reference = { id: 'style-ref-1', title: 'Ink wash', prompt: 'wash', imageRefs: ['a.png'] };+ serverReferences.set('u1', [reference]);apiMocks.getUniverse.mockResolvedValueOnce({ ...universe, styleReferences: [reference] });const { result } = renderDraft();await waitFor(() => expect(result.current.draft.styleReferences).toEqual([reference]));await act(async () => { await result.current.removeStyleReference(reference.id); });- expect(apiMocks.updateUniverse.mock.calls.at(-1)[1]).toEqual({ styleReferences: [] });+ expect(apiMocks.removeUniverseStyleReference).toHaveBeenCalledWith('u1', reference.id, { silent: true });expect(result.current.draft.styleReferences).toEqual([]);});- it('removes both references when two removals are triggered before either PATCH resolves', async () => {+ it('removes both references when two removals fire before either request resolves', async () => {const refA = { id: 'style-ref-a', title: 'Ref A', prompt: 'moody', imageRefs: ['a.png'] };const refB = { id: 'style-ref-b', title: 'Ref B', prompt: 'bright', imageRefs: ['b.png'] };+ serverReferences.set('u1', [refA, refB]);apiMocks.getUniverse.mockResolvedValueOnce({ ...universe, styleReferences: [refA, refB] });const { result } = renderDraft();await waitFor(() => expect(result.current.draft.styleReferences).toEqual([refA, refB]));- // Both removals derive their PATCH from the ARRAY THE SERVER LAST CONFIRMED- // (the queue's tracked snapshot), not from a shared stale `draft` read at- // call time — otherwise the second request's wholesale-replace payload- // would still include refA (or refB) and silently restore it on resolve.+ // No client-side queue serializes these anymore — each request names only+ // the id it removes, so whichever order the server applies them in, both+ // removals survive. (Previously each had to carry the surviving array,+ // which is what made ordering load-bearing.)await act(async () => {- const first = result.current.removeStyleReference(refA.id);- const second = result.current.removeStyleReference(refB.id);- await Promise.all([first, second]);+ await Promise.all([+ result.current.removeStyleReference(refA.id),+ result.current.removeStyleReference(refB.id),+ ]);});- expect(apiMocks.updateUniverse).toHaveBeenCalledTimes(2);- expect(apiMocks.updateUniverse.mock.calls[0][1]).toEqual({ styleReferences: [refB] });- expect(apiMocks.updateUniverse.mock.calls[1][1]).toEqual({ styleReferences: [] });+ expect(apiMocks.removeUniverseStyleReference.mock.calls.map((call) => call[1]))+ .toEqual([refA.id, refB.id]);+ expect(serverRefsFor('u1')).toEqual([]);expect(result.current.draft.styleReferences).toEqual([]);});- it('keeps a reference added between two removals (remove A, add C, remove B)', async () => {- const refA = { id: 'style-ref-a', title: 'Ref A', prompt: 'moody', imageRefs: ['a.png'] };- const refB = { id: 'style-ref-b', title: 'Ref B', prompt: 'bright', imageRefs: ['b.png'] };- const refC = { id: 'style-ref-c', title: 'Ref C', prompt: 'sunlit', imageRefs: ['c.png'] };- apiMocks.getUniverse.mockResolvedValueOnce({ ...universe, styleReferences: [refA, refB] });- const { result } = renderDraft();- await waitFor(() => expect(result.current.draft.styleReferences).toEqual([refA, refB]));-- await act(async () => { await result.current.removeStyleReference(refA.id); });- expect(apiMocks.updateUniverse.mock.calls.at(-1)[1]).toEqual({ styleReferences: [refB] });-- await act(async () => {- await result.current.persistStyleReference({ reference: refC, adopt: false });- });- // persistStyleReference must build its PATCH from the post-removal- // snapshot (refB), not a stale pre-removal draft read.- expect(apiMocks.updateUniverse.mock.calls.at(-1)[1]).toEqual({ styleReferences: [refB, refC] });-- await act(async () => { await result.current.removeStyleReference(refB.id); });- // Regression: removeStyleReference's snapshot must have picked up refC- // from the add above, or this PATCH would silently drop refC too.- expect(apiMocks.updateUniverse.mock.calls.at(-1)[1]).toEqual({ styleReferences: [refC] });- expect(result.current.draft.styleReferences).toEqual([refC]);- });-- it('does not let a stale in-flight save for one universe overwrite a different, now-selected universe (codex review finding)', async () => {- const universeTwoWithRef = {- ...universeTwo,- styleReferences: [{ id: 'style-ref-b2', title: 'Ref B2', prompt: 'b2', imageRefs: ['b2.png'] }],- };+ it('does not let an in-flight mutation for one universe touch a different, now-selected universe', async () => {+ const refB2 = { id: 'style-ref-b2', title: 'Ref B2', prompt: 'b2', imageRefs: ['b2.png'] };+ const universeTwoWithRef = { ...universeTwo, styleReferences: [refB2] };+ serverReferences.set('u2', [refB2]);apiMocks.getUniverse.mockImplementation(async (id) => (id === 'u2' ? universeTwoWithRef : universe));const { result, rerender } = renderSelectable();await waitFor(() => expect(result.current.draft.id).toBe('u1'));- // Start a save for u1 but hold its PATCH response open — simulates the- // user switching universes before this request resolves. Not wrapped in- // act(): nothing synchronous before its first await touches React state.- let resolveU1Save;- apiMocks.updateUniverse.mockImplementationOnce(() => new Promise((resolve) => { resolveU1Save = resolve; }));+ // Start an add for u1 and hold its response open — simulates the user+ // switching universes before it resolves.+ let resolveU1Add;+ apiMocks.addUniverseStyleReference.mockImplementationOnce(+ () => new Promise((resolve) => { resolveU1Add = resolve; }),+ );const referenceForU1 = { id: 'style-ref-stale', title: 'Stale', prompt: 'stale', imageRefs: ['stale.png'] };const staleSave = result.current.persistStyleReference({ reference: referenceForU1, adopt: false });- // Switch to u2 while u1's save is still pending.await act(async () => { rerender({ selectedId: 'u2' }); });await waitFor(() => expect(result.current.draft.id).toBe('u2'));- expect(result.current.draft.styleReferences).toEqual(universeTwoWithRef.styleReferences);+ expect(result.current.draft.styleReferences).toEqual([refB2]);- // Now let u1's stale save resolve.await act(async () => {- resolveU1Save({ ...universe, styleReferences: [referenceForU1] });+ resolveU1Add({ ...universe, styleReferences: [referenceForU1] });await staleSave;});- // u2's displayed draft must be untouched by u1's stale, now-resolved response.+ // u2's displayed draft is untouched by u1's now-resolved response.expect(result.current.draft.id).toBe('u2');- expect(result.current.draft.styleReferences).toEqual(universeTwoWithRef.styleReferences);-- // A subsequent removal on u2 must build its PATCH from u2's OWN- // references, not from u1's stale snapshot.- await act(async () => {- await result.current.removeStyleReference(universeTwoWithRef.styleReferences[0].id);- });- expect(apiMocks.updateUniverse.mock.calls.at(-1)).toEqual(['u2', { styleReferences: [] }, { silent: true }]);- });-- it('reconciles a save that resolves after an A -> B -> A round trip, instead of losing it (codex review finding)', async () => {- apiMocks.getUniverse.mockImplementation(async (id) => (id === 'u2' ? universeTwo : { ...universe, styleReferences: [] }));-- const { result, rerender } = renderSelectable();- await waitFor(() => expect(result.current.draft.id).toBe('u1'));-- // Start a save on u1 and hold its response open.- let resolveU1Save;- apiMocks.updateUniverse.mockImplementationOnce(() => new Promise((resolve) => { resolveU1Save = resolve; }));- const refX = { id: 'style-ref-x', title: 'Ref X', prompt: 'x', imageRefs: ['x.png'] };- const pendingSave = result.current.persistStyleReference({ reference: refX, adopt: false });-- // u1 -> u2 -> u1, all before the save resolves.- await act(async () => { rerender({ selectedId: 'u2' }); });- await waitFor(() => expect(result.current.draft.id).toBe('u2'));- await act(async () => { rerender({ selectedId: 'u1' }); });- await waitFor(() => expect(result.current.draft.id).toBe('u1'));- // Re-hydration reflects the server's pre-save state (the save is still- // in flight from the server's perspective too).- expect(result.current.draft.styleReferences).toEqual([]);+ expect(result.current.draft.styleReferences).toEqual([refB2]);- // Now the save resolves — since the user is back on u1, its result must- // be reconciled into the displayed draft, not discarded.- await act(async () => {- resolveU1Save({ ...universe, styleReferences: [refX] });- await pendingSave;- });- expect(result.current.draft.id).toBe('u1');- expect(result.current.draft.styleReferences).toEqual([refX]);-- // The next mutation on u1 must build from the reconciled [refX], not from- // a stale empty snapshot left over from before the round trip.- await act(async () => { await result.current.removeStyleReference(refX.id); });- expect(apiMocks.updateUniverse.mock.calls.at(-1)).toEqual(['u1', { styleReferences: [] }, { silent: true }]);- expect(result.current.draft.styleReferences).toEqual([]);+ // And a removal on u2 targets u2's own reference — no cross-universe leak.+ await act(async () => { await result.current.removeStyleReference(refB2.id); });+ expect(apiMocks.removeUniverseStyleReference).toHaveBeenLastCalledWith('u2', refB2.id, { silent: true });});- it('refreshes the cached snapshot from the server on re-hydration, so an external change is not shadowed (codex review finding)', async () => {- const refOld = { id: 'style-ref-old', title: 'Old', prompt: 'old', imageRefs: ['old.png'] };- const refExternal = { id: 'style-ref-external', title: 'External', prompt: 'external', imageRefs: ['external.png'] };- // First visit to u1 returns refOld; a peer sync / image-delete purge then- // changes u1's references server-side WHILE the user is on u2, so the- // second fetch of u1 returns refExternal instead.- let u1FetchCount = 0;- apiMocks.getUniverse.mockImplementation(async (id) => {- if (id === 'u2') return universeTwo;- u1FetchCount += 1;- return { ...universe, styleReferences: u1FetchCount === 1 ? [refOld] : [refExternal] };- });-- const { result, rerender } = renderSelectable();- await waitFor(() => expect(result.current.draft.styleReferences).toEqual([refOld]));-- await act(async () => { rerender({ selectedId: 'u2' }); });- await waitFor(() => expect(result.current.draft.id).toBe('u2'));-- await act(async () => { rerender({ selectedId: 'u1' }); });- await waitFor(() => expect(result.current.draft.styleReferences).toEqual([refExternal]));-- // A removal now must target the freshly re-hydrated refExternal, not the- // stale cached refOld from before the external change.- await act(async () => { await result.current.removeStyleReference(refExternal.id); });- expect(apiMocks.updateUniverse.mock.calls.at(-1)).toEqual(['u1', { styleReferences: [] }, { silent: true }]);- });-- it('keeps a mutation that resolves BEFORE the re-hydration GET it raced (codex review finding)', async () => {- // u1 starts with refA already saved, so the post-mutation list ([refA, refX])- // and G's stale list ([refA]) differ in a way the FINAL removal payload can- // discriminate — with an empty starting list both branches would emit the- // same `{ styleReferences: [] }` and the assertion would prove nothing.+ it('re-reads instead of applying a hydration GET that raced a mutation (would blank the new reference)', async () => {const refA = { id: 'style-ref-a', title: 'Ref A', prompt: 'a', imageRefs: ['a.png'] };const refX = { id: 'style-ref-x', title: 'Ref X', prompt: 'x', imageRefs: ['x.png'] };- // The re-hydration fetch on the return to u1 is held open so it can be- // resolved AFTER the mutation, with the PRE-mutation body the server would- // have returned had it read before the PATCH landed.+ serverReferences.set('u1', [refA]);+ // The re-hydration fetch on the return to u1 is held open so it can resolve+ // AFTER the mutation, carrying the PRE-mutation body the server would have+ // returned had it read before the add landed. The client can't tell that+ // from the response alone — hence the re-read.+ let serverStyleNotes = '';let u1Fetches = 0;let resolveU1Hydration;apiMocks.getUniverse.mockImplementation(async (id) => {if (id === 'u2') return universeTwo;u1Fetches += 1;if (u1Fetches === 2) return new Promise((resolve) => { resolveU1Hydration = resolve; });- return { ...universe, styleReferences: [refA] };+ return { ...universe, styleReferences: serverRefsFor('u1'), styleNotes: serverStyleNotes };});const { result, rerender } = renderSelectable();await waitFor(() => expect(result.current.draft.styleReferences).toEqual([refA]));- // Adopt mutation M on u1, held open — adopt so the assertions also cover the- // style guide the same PATCH writes, not just the references.- let resolveU1Save;- apiMocks.updateUniverse.mockImplementationOnce(() => new Promise((resolve) => { resolveU1Save = resolve; }));- const pendingSave = result.current.persistStyleReference({+ let resolveU1Add;+ apiMocks.addUniverseStyleReference.mockImplementationOnce(+ () => new Promise((resolve) => { resolveU1Add = resolve; }),+ );+ const pendingAdd = result.current.persistStyleReference({reference: refX,proposed: { styleNotes: 'Adopted notes', influences: { embrace: ['ink'], avoid: [] } },adopt: true,});- // u1 -> u2 -> u1; the return issues re-hydration GET G, which stays pending.+ // u1 -> u2 -> u1; the return issues re-hydration GET G, held pending.await act(async () => { rerender({ selectedId: 'u2' }); });await waitFor(() => expect(result.current.draft.id).toBe('u2'));await act(async () => { rerender({ selectedId: 'u1' }); });await waitFor(() => expect(resolveU1Hydration).toBeTypeOf('function'));- // M resolves FIRST — the reordering this guard exists for.+ // The add resolves first — the reordering this guard exists for.await act(async () => {- resolveU1Save({+ serverReferences.set('u1', [refA, refX]);+ serverStyleNotes = 'Adopted notes';+ resolveU1Add({...universe,styleReferences: [refA, refX],styleNotes: 'Adopted notes',influences: { embrace: ['ink'], avoid: [] },});- await pendingSave;+ await pendingAdd;});- // ...then G resolves carrying the stale, pre-mutation body.+ // ...then G resolves carrying the stale, pre-mutation body. The hook+ // re-reads (fetch 3, which sees the committed write) rather than applying+ // it, so both the reference AND the guidance the same write adopted stand.await act(async () => {resolveU1Hydration({ ...universe, styleReferences: [refA], styleNotes: '' });await Promise.resolve();});- // G must not have reverted M: the displayed draft still shows refX, and the- // style guide the SAME adopt PATCH wrote survives alongside it.- await waitFor(() => expect(result.current.draft.id).toBe('u1'));- expect(result.current.draft.styleReferences).toEqual([refA, refX]);+ await waitFor(() => expect(result.current.draft.styleReferences).toEqual([refA, refX]));expect(result.current.draft.styleNotes).toBe('Adopted notes');- // markDraftSaved banked the overridden values, so the adopted guidance is- // not silently re-saved as the stale '' on the next general Save.+ // markDraftSaved banked the re-read values, so the adopted guidance is not+ // silently re-saved as the stale '' on the next general Save.expect(result.current.isDraftDirty()).toBe(false);-- // The next mutation builds from [refA, refX], not G's stale [refA] — with a- // stale base this PATCH would emit `{ styleReferences: [] }` and leave refX- // lingering server-side.- await act(async () => { await result.current.removeStyleReference(refA.id); });- expect(apiMocks.updateUniverse.mock.calls.at(-1)).toEqual(['u1', { styleReferences: [refX] }, { silent: true }]);- expect(result.current.draft.styleReferences).toEqual([refX]);});- it('drops an adopt\'s stashed guidance once an un-raced hydration supersedes it (agy review finding)', async () => {- const refX = { id: 'style-ref-x', title: 'Ref X', prompt: 'x', imageRefs: ['x.png'] };- // u1's server body after the adopt, then again after a peer changes the- // style guide externally while the user is away.+ it('lets an un-raced hydration carry a peer edit the client never wrote', async () => {+ // The mirror of the test above: with no mutation in flight, the GET is+ // authoritative — including for writers the client can't see (peer sync,+ // the image-delete purge). The old design cached a base array here and+ // needed an epoch to avoid shadowing them; now there is nothing to shadow.+ const refPeer = { id: 'style-ref-peer', title: 'Peer', prompt: 'peer', imageRefs: ['peer.png'] };let u1Fetches = 0;- let resolveLateHydration;apiMocks.getUniverse.mockImplementation(async (id) => {if (id === 'u2') return universeTwo;u1Fetches += 1;- if (u1Fetches === 1) return { ...universe, styleReferences: [], styleNotes: '' };- // Fetch 2 is the un-raced hydration that confirms the adopt server-side.- if (u1Fetches === 2) return { ...universe, styleReferences: [refX], styleNotes: 'Adopted notes' };- // Fetch 3 races a later plain mutation and carries a PEER's newer notes.- return new Promise((resolve) => { resolveLateHydration = resolve; });+ return u1Fetches === 1+ ? { ...universe, styleReferences: [], styleNotes: '' }+ : { ...universe, styleReferences: [refPeer], styleNotes: 'Peer notes' };});const { result, rerender } = renderSelectable();- await waitFor(() => expect(result.current.draft.id).toBe('u1'));-- // Adopt on u1 — stashes { styleNotes: 'Adopted notes', … } as guidance.- await act(async () => {- await result.current.persistStyleReference({- reference: refX,- proposed: { styleNotes: 'Adopted notes', influences: { embrace: [], avoid: [] } },- adopt: true,- });- });+ await waitFor(() => expect(result.current.draft.styleReferences).toEqual([]));- // u1 -> u2 -> u1, with nothing in flight: hydration fetch 2 wins un-raced,- // so the server has confirmed the adopt and the stash is spent.await act(async () => { rerender({ selectedId: 'u2' }); });await waitFor(() => expect(result.current.draft.id).toBe('u2'));await act(async () => { rerender({ selectedId: 'u1' }); });- await waitFor(() => expect(result.current.draft.styleNotes).toBe('Adopted notes'));-- // Now: a plain removal races hydration fetch 3, which carries a peer's- // newer notes. The removal writes no guidance of its own.- await act(async () => { rerender({ selectedId: 'u2' }); });- await waitFor(() => expect(result.current.draft.id).toBe('u2'));- await act(async () => { rerender({ selectedId: 'u1' }); });- await waitFor(() => expect(resolveLateHydration).toBeTypeOf('function'));-- let resolveRemoval;- apiMocks.updateUniverse.mockImplementationOnce(() => new Promise((resolve) => { resolveRemoval = resolve; }));- // removeStyleReference chains onto the per-universe queue, so its PATCH is- // issued a microtask later — wait for the mock to be entered before resolving.- const pendingRemoval = result.current.removeStyleReference(refX.id);- await waitFor(() => expect(resolveRemoval).toBeTypeOf('function'));- await act(async () => {- resolveRemoval({ ...universe, styleReferences: [], styleNotes: 'Peer notes' });- await pendingRemoval;- });- await act(async () => {- resolveLateHydration({ ...universe, styleReferences: [refX], styleNotes: 'Peer notes' });- await Promise.resolve();- });- // The removal still wins on references (it wrote them)...- await waitFor(() => expect(result.current.draft.id).toBe('u1'));- expect(result.current.draft.styleReferences).toEqual([]);- // ...but must NOT resurrect the spent 'Adopted notes' over the peer's newer- // value, which the removal's PATCH never wrote.+ await waitFor(() => expect(result.current.draft.styleReferences).toEqual([refPeer]));expect(result.current.draft.styleNotes).toBe('Peer notes');});- it('does not let a plain mutation resurrect an older adopt over a newer peer edit the GET carries (codex review finding)', async () => {- const refX = { id: 'style-ref-x', title: 'Ref X', prompt: 'x', imageRefs: ['x.png'] };- // Same class as the test above, but with NO hydration landing between the- // adopt and the racing mutation — so the guard cannot rely on a winning- // hydration to retire the stashed guidance. Only the guidance's own epoch- // stamp distinguishes "written after this GET" from "the GET already has it."- let u1Fetches = 0;- let resolveLateHydration;- apiMocks.getUniverse.mockImplementation(async (id) => {- if (id === 'u2') return universeTwo;- u1Fetches += 1;- if (u1Fetches === 1) return { ...universe, styleReferences: [], styleNotes: '' };- return new Promise((resolve) => { resolveLateHydration = resolve; });- });-- const { result, rerender } = renderSelectable();+ it('surfaces a failed add without touching the draft', async () => {+ const { result } = renderDraft();await waitFor(() => expect(result.current.draft.id).toBe('u1'));+ apiMocks.addUniverseStyleReference.mockRejectedValueOnce(new Error('at capacity'));- // Adopt on u1 — stashes guidance at the epoch it was written.+ let ok;await act(async () => {- await result.current.persistStyleReference({- reference: refX,- proposed: { styleNotes: 'Adopted notes', influences: { embrace: [], avoid: [] } },- adopt: true,+ ok = await result.current.persistStyleReference({+ reference: { id: 'style-ref-1', title: 'T', prompt: 'p', imageRefs: ['a.png'] },+ adopt: false,});});-- // u1 -> u2 -> u1 with the adopt already settled. The return's GET reads a- // peer's newer style notes; it is issued AFTER the adopt, so it already- // contains the adopted state plus the peer's later edit.- await act(async () => { rerender({ selectedId: 'u2' }); });- await waitFor(() => expect(result.current.draft.id).toBe('u2'));- await act(async () => { rerender({ selectedId: 'u1' }); });- await waitFor(() => expect(resolveLateHydration).toBeTypeOf('function'));-- // A plain removal races that GET and wins on references — but it wrote no- // style guide, so it must not drag the older adopt's notes along with it.- let resolveRemoval;- apiMocks.updateUniverse.mockImplementationOnce(() => new Promise((resolve) => { resolveRemoval = resolve; }));- const pendingRemoval = result.current.removeStyleReference(refX.id);- await waitFor(() => expect(resolveRemoval).toBeTypeOf('function'));- await act(async () => {- resolveRemoval({ ...universe, styleReferences: [], styleNotes: 'Peer notes' });- await pendingRemoval;- });- await act(async () => {- resolveLateHydration({ ...universe, styleReferences: [refX], styleNotes: 'Peer notes' });- await Promise.resolve();- });-- await waitFor(() => expect(result.current.draft.id).toBe('u1'));+ expect(ok).toBe(false);+ expect(toastMock.error).toHaveBeenCalledWith('Reference save failed: at capacity');expect(result.current.draft.styleReferences).toEqual([]);- expect(result.current.draft.styleNotes).toBe('Peer notes');});});diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex afd41e3166..b9296cb17b 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -46,6 +46,23 @@ export const deleteUniverse = (id, options = {}) => request(`/universe-builder/$...options,});+// Add / remove ONE art style reference. These are deltas, not a wholesale+// array replace — the server applies them inside the universe record's write+// queue against the freshest persisted list, so the browser never has to hold+// a base array that a concurrent mutation, a peer sync, or the image-delete+// purge can invalidate under it. Both resolve with the full updated universe.+// `adopt` is `{ styleNotes, influences }` when the user chose "Adopt style ++// add" — the server writes it in the same queued write as the reference.+export const addUniverseStyleReference = (id, { reference, adopt } = {}, options = {}) => request(+ `/universe-builder/${encodeURIComponent(id)}/style-references`,+ { method: 'POST', body: JSON.stringify({ reference, ...(adopt ? { adopt } : {}) }), ...options },+);++export const removeUniverseStyleReference = (id, referenceId, options = {}) => request(+ `/universe-builder/${encodeURIComponent(id)}/style-references/${encodeURIComponent(referenceId)}`,+ { method: 'DELETE', ...options },+);+export const expandUniverse = ({starterPrompt, influences,preservedVariations, preservedCompositeSheets,diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 417a83c5a8..fdc78f0db7 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -14,6 +14,8 @@* POST /api/universe-builder/:id/canon/:kind/:entryId/apply-image-correction → { universe, entry }* POST /api/universe-builder/:id/render → { runId, collectionId, jobIds, promptCount }* GET /api/universe-builder/:id/runs → Run[]+ * POST /api/universe-builder/:id/style-references → Universe+ * DELETE /api/universe-builder/:id/style-references/:referenceId → Universe*/import { Router } from 'express';@@ -889,6 +891,39 @@ router.get('/:id/series-names', asyncHandler(async (req, res) => {res.json(result);}));+// ---- Art style references (delta endpoints, #3109) ----+//+// Add/remove one reference at a time instead of PATCHing the whole array. The+// wholesale-replace `{ styleReferences: [...] }` field on PATCH /:id stays+// accepted (older clients, peer imports, the sharing importer) — these routes+// just move the read half of the read-modify-write inside the record's write+// queue, so a client no longer has to own a base array that a concurrent+// mutation, peer sync, or the image-delete purge can invalidate under it.+const addStyleReferenceSchema = z.object({+ // `id` is required here (unlike the wholesale-replace field, where the+ // sanitizer mints one): the id is what makes a re-sent add idempotent+ // server-side, and /analyze-style-reference always returns one.+ reference: styleReferenceSchema.extend({ id: z.string().trim().min(1).max(80) }),+ // Present when the user chose "Adopt style + add" — written in the SAME+ // queued write as the reference so the pair can't half-land.+ adopt: z.object({+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),+ influences: influencesSchema.optional(),+ }).optional(),+});+router.post('/:id/style-references', asyncHandler(async (req, res) => {+ const body = validateRequest(addStyleReferenceSchema, req.body ?? {});+ const w = await svc.addStyleReference(req.params.id, body.reference, { adopt: body.adopt || null })+ .catch((err) => { throw mapServiceError(err); });+ res.json(w);+}));++router.delete('/:id/style-references/:referenceId', asyncHandler(async (req, res) => {+ const w = await svc.removeStyleReference(req.params.id, req.params.referenceId)+ .catch((err) => { throw mapServiceError(err); });+ res.json(w);+}));+// Lock toggle for canon entries. Locked entries are protected from AI rewrite// paths (refine, differentiate, re-extract field overwrites).const setLockSchema = z.object({diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.jsindex 0cab0ed9aa..3ac5b81057 100644--- a/server/routes/universeBuilder.test.js+++ b/server/routes/universeBuilder.test.js@@ -500,6 +500,82 @@ describe('universe-builder routes', () => {expect(res.body.objects[0].name).toBe('Gold pocket watch');});+ // ---- Art style reference deltas (#3109) ----++ it('POST /:id/style-references appends one reference and can adopt guidance in the same write', async () => {+ const app = buildApp();+ const c = await request(app).post('/api/universe-builder').send({ name: 'Refs' });+ const first = await request(app)+ .post(`/api/universe-builder/${c.body.id}/style-references`)+ .send({+ reference: { id: 'style-ref-1', title: 'Ink wash', prompt: 'Granular ink wash', imageRefs: ['a.png'] },+ });+ expect(first.status).toBe(200);+ expect(first.body.styleReferences.map((r) => r.id)).toEqual(['style-ref-1']);++ const second = await request(app)+ .post(`/api/universe-builder/${c.body.id}/style-references`)+ .send({+ reference: { id: 'style-ref-2', title: 'Sunlit', prompt: 'Warm sunlit haze', imageRefs: ['b.png'] },+ adopt: { styleNotes: 'Warm and hazy', influences: { embrace: ['sunlit'], avoid: ['gloss'] } },+ });+ expect(second.status).toBe(200);+ // The addition composed onto the persisted list — it did not replace it.+ expect(second.body.styleReferences.map((r) => r.id)).toEqual(['style-ref-1', 'style-ref-2']);+ expect(second.body.styleNotes).toBe('Warm and hazy');+ expect(second.body.influences).toEqual({ embrace: ['sunlit'], avoid: ['gloss'] });+ });++ it('POST /:id/style-references rejects a reference missing an id or a prompt', async () => {+ const app = buildApp();+ const c = await request(app).post('/api/universe-builder').send({ name: 'Refs' });+ // The delta path requires an explicit id (it's what makes a re-send+ // idempotent), unlike the wholesale-replace field where the sanitizer mints one.+ const noId = await request(app)+ .post(`/api/universe-builder/${c.body.id}/style-references`)+ .send({ reference: { title: 'No id', prompt: 'Prompt', imageRefs: ['a.png'] } });+ expect(noId.status).toBe(400);+ const noPrompt = await request(app)+ .post(`/api/universe-builder/${c.body.id}/style-references`)+ .send({ reference: { id: 'style-ref-1', title: 'No prompt', imageRefs: ['a.png'] } });+ expect(noPrompt.status).toBe(400);+ });++ it('DELETE /:id/style-references/:referenceId removes one and no-ops on an unknown id', async () => {+ const app = buildApp();+ const c = await request(app).post('/api/universe-builder').send({+ name: 'Refs',+ styleReferences: [+ { id: 'style-ref-a', title: 'A', prompt: 'a', imageRefs: ['a.png'] },+ { id: 'style-ref-b', title: 'B', prompt: 'b', imageRefs: ['b.png'] },+ ],+ });+ const removed = await request(app)+ .delete(`/api/universe-builder/${c.body.id}/style-references/style-ref-a`);+ expect(removed.status).toBe(200);+ expect(removed.body.styleReferences.map((r) => r.id)).toEqual(['style-ref-b']);++ // A duplicate delete (or one that raced the image-delete purge) is a+ // no-op, not a 404 — the caller's intent is already satisfied.+ const again = await request(app)+ .delete(`/api/universe-builder/${c.body.id}/style-references/style-ref-a`);+ expect(again.status).toBe(200);+ expect(again.body.styleReferences.map((r) => r.id)).toEqual(['style-ref-b']);+ });++ it('PATCH /:id still accepts a wholesale styleReferences replace (older clients + peer imports)', async () => {+ const app = buildApp();+ const c = await request(app).post('/api/universe-builder').send({+ name: 'Back-compat',+ styleReferences: [{ id: 'style-ref-a', title: 'A', prompt: 'a', imageRefs: ['a.png'] }],+ });+ const res = await request(app)+ .patch(`/api/universe-builder/${c.body.id}`)+ .send({ styleReferences: [{ id: 'style-ref-b', title: 'B', prompt: 'b', imageRefs: ['b.png'] }] });+ expect(res.status).toBe(200);+ expect(res.body.styleReferences.map((r) => r.id)).toEqual(['style-ref-b']);+ });+it('DELETE /:id removes the universe', async () => {const app = buildApp();const c = await request(app).post('/api/universe-builder').send({ name: 'A' });diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex d84c90d179..d6f99d003d 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -405,6 +405,103 @@ describe("universeBuilder service", () => {expect((await svc.getUniverse(w.id)).styleReferences).toEqual([reference]);});+ it("addStyleReference appends inside the queued mutator so concurrent adds compose (#3109)", async () => {+ const refFor = (n) => ({+ id: `style-ref-${n}`,+ title: `Ref ${n}`,+ prompt: `Prompt ${n}`,+ imageRefs: [`ref-${n}.png`],+ createdAt: "2026-01-01T00:00:00.000Z",+ });+ const w = await svc.createUniverse({ name: "Delta Adds" });++ // Fired without awaiting the first — the record write queue serializes+ // them and each reads the freshest persisted list, so neither is lost.+ // A wholesale-replace PATCH pair built from the same base would drop one.+ await Promise.all([+ svc.addStyleReference(w.id, refFor(1)),+ svc.addStyleReference(w.id, refFor(2)),+ ]);+ const fresh = await svc.getUniverse(w.id);+ expect(fresh.styleReferences.map((r) => r.id).sort()).toEqual([+ "style-ref-1",+ "style-ref-2",+ ]);+ });++ it("addStyleReference writes adopted style guidance in the SAME queued write", async () => {+ const w = await svc.createUniverse({ name: "Adopt", influences: { embrace: ["old"], avoid: [] } });+ const updated = await svc.addStyleReference(w.id, {+ id: "style-ref-adopt",+ title: "Ink wash",+ prompt: "Granular ink wash",+ imageRefs: ["adopt.png"],+ }, {+ adopt: { styleNotes: "Tactile and muted", influences: { embrace: ["ink wash"], avoid: ["gloss"] } },+ });+ expect(updated.styleReferences).toHaveLength(1);+ expect(updated.styleNotes).toBe("Tactile and muted");+ expect(updated.influences).toEqual({ embrace: ["ink wash"], avoid: ["gloss"] });+ // Persisted together — the pair can't half-land.+ const fresh = await svc.getUniverse(w.id);+ expect(fresh.styleNotes).toBe("Tactile and muted");+ expect(fresh.styleReferences).toHaveLength(1);+ });++ it("addStyleReference is idempotent on a re-sent id and rejects an invalid reference", async () => {+ const reference = {+ id: "style-ref-once",+ title: "Once",+ prompt: "Prompt",+ imageRefs: ["once.png"],+ };+ const w = await svc.createUniverse({ name: "Idempotent" });+ await svc.addStyleReference(w.id, reference);+ // A retried request / double-click is a no-op, not a duplicate.+ const again = await svc.addStyleReference(w.id, reference);+ expect(again.styleReferences).toHaveLength(1);+ await expect(svc.addStyleReference(w.id, { title: "No prompt", imageRefs: ["x.png"] }))+ .rejects.toThrow(/Invalid style reference/);+ });++ it("addStyleReference enforces the cap against the PERSISTED list", async () => {+ const w = await svc.createUniverse({+ name: "At Cap",+ styleReferences: Array.from({ length: svc.STYLE_REFERENCES_MAX }, (_, i) => ({+ id: `style-ref-${i}`,+ title: `Ref ${i}`,+ prompt: `Prompt ${i}`,+ imageRefs: [`ref-${i}.png`],+ })),+ });+ expect(w.styleReferences).toHaveLength(svc.STYLE_REFERENCES_MAX);+ await expect(svc.addStyleReference(w.id, {+ id: "style-ref-overflow",+ title: "Overflow",+ prompt: "Prompt",+ imageRefs: ["overflow.png"],+ })).rejects.toThrow(/up to 20 art references/);+ });++ it("removeStyleReference drops one by id and no-ops on an id that is already gone", async () => {+ const refA = { id: "style-ref-a", title: "A", prompt: "a", imageRefs: ["a.png"] };+ const refB = { id: "style-ref-b", title: "B", prompt: "b", imageRefs: ["b.png"] };+ const w = await svc.createUniverse({ name: "Delta Removes", styleReferences: [refA, refB] });++ // Concurrent removals: each filters the freshest list, so both land — the+ // case a pair of wholesale-replace PATCHes needed client-side queuing for.+ await Promise.all([+ svc.removeStyleReference(w.id, refA.id),+ svc.removeStyleReference(w.id, refB.id),+ ]);+ expect((await svc.getUniverse(w.id)).styleReferences).toEqual([]);++ // Already gone (a duplicate delete, or one that raced the image-delete+ // purge) resolves with the unchanged record instead of throwing.+ const noop = await svc.removeStyleReference(w.id, refA.id);+ expect(noop.styleReferences).toEqual([]);+ });+it("drops invalid style references and defaults the field to an empty list", async () => {const w = await svc.createUniverse({name: "Reference Validation",diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.jsindex c5ee7ee47a..5eedc23e29 100644--- a/server/services/universeBuilder/crud.js+++ b/server/services/universeBuilder/crud.js@@ -18,9 +18,11 @@ import {import { store } from './storeFacade.js';import {sanitizeTemplate, sanitizeRun, sanitizeImageRefFilename, resolveInfluences,+ sanitizeStyleReference,makeErr, UNIVERSE_ID_RE,ERR_NOT_FOUND, ERR_VALIDATION, ERR_DUPLICATE, ERR_HAS_LIVE_SERIES,NAME_MAX_LENGTH, CURRENT_SCHEMA_VERSION, ENTRY_REF_KIND, IMAGE_REFS_PER_ENTRY_MAX,+ STYLE_REFERENCES_MAX,} from './sanitize.js';import {emitRecordUpdated, emitRecordDeleted,@@ -632,6 +634,62 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {return merged;}+/**+ * Append one analyzed art reference to a universe's `styleReferences`, and+ * optionally adopt the style guidance the same analysis proposed — as a DELTA,+ * inside `updateUniverse`'s queued mutator.+ *+ * This exists because the wholesale-replace `{ styleReferences: [...] }` PATCH+ * forces the caller to own a base array, which means a browser doing+ * read-modify-write races every other writer: its own second mutation, a peer+ * sync, and `universeCanon.js`'s image-delete purge (which mutates+ * `styleReferences` directly and is invisible to any client-side version+ * counter). Sending just the addition moves the read half of the RMW inside the+ * record's write queue, where the freshest persisted list is the base — so+ * concurrent adds/removes/purges compose instead of clobbering (#3109).+ *+ * `adopt` writes `styleNotes` + `influences` in the SAME queued write as the+ * reference, so the pair can't half-land. Cap enforcement lives here now+ * (`STYLE_REFERENCES_MAX` against the persisted list), which is stricter than+ * a client checking its own possibly-stale cache.+ */+export async function addStyleReference(id, reference, { adopt = null } = {}) {+ const sanitized = sanitizeStyleReference(reference);+ if (!sanitized) throw makeErr('Invalid style reference payload', ERR_VALIDATION);+ return updateUniverse(id, (cur) => {+ const current = Array.isArray(cur.styleReferences) ? cur.styleReferences : [];+ // Idempotent on re-send (a retried request, a double-click): an id already+ // present is a no-op rather than a duplicate or a cap-exceeded error.+ if (current.some((ref) => ref?.id === sanitized.id)) return null;+ if (current.length >= STYLE_REFERENCES_MAX) {+ throw makeErr(`A universe can hold up to ${STYLE_REFERENCES_MAX} art references`, ERR_VALIDATION);+ }+ return {+ styleReferences: [...current, sanitized],+ ...(adopt ? {+ styleNotes: isStr(adopt.styleNotes) ? adopt.styleNotes : '',+ influences: resolveInfluences(adopt),+ } : {}),+ };+ });+}++/**+ * Remove one art reference by id — the delta counterpart to+ * `addStyleReference`, for the same reason (see its doc comment). Resolves with+ * the unchanged record when the id isn't present, so a duplicate delete or a+ * removal that raced the image-delete purge is a no-op rather than an error.+ */+export async function removeStyleReference(id, referenceId) {+ if (!isStr(referenceId)) throw makeErr('referenceId is required', ERR_VALIDATION);+ return updateUniverse(id, (cur) => {+ const current = Array.isArray(cur.styleReferences) ? cur.styleReferences : [];+ const next = current.filter((ref) => ref?.id !== referenceId);+ if (next.length === current.length) return null;+ return { styleReferences: next };+ });+}+export async function deleteUniverse(id) {// Soft-delete: mark the record with `deleted: true` + `deletedAt` and bump// `updatedAt` so federated peers learn about the deletion via the existing