Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-3109]): key the stale-GET guard on updatedAt and skip the canon projection for scalar mutators

[._.]/ Adam Eivya19e63b09c95
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 16c2209ccc..62061ca26f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -33,7 +33,6 @@
## 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 templates
diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.js
index bc5f3c65de..481a99584f 100644
--- a/client/src/hooks/useUniverseDraft.js
+++ b/client/src/hooks/useUniverseDraft.js
@@ -92,32 +92,47 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
const savedStyleSnapshotRef = useRef(ensureInfluences(createEmptyUniverseDraft().influences));
const pendingCanonAdditionsRef = useRef(emptyPendingCanon());
// Mirrors `selectedId` synchronously during render (not via a passive
- // effect, which runs one tick later and would leave a window where a
- // 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).
+ // effect, which runs one tick later and would leave a window where a resolving
+ // request still sees the OLD selection as current). Mutators compare against
+ // this — not the `selectedId` closure — 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 instead of poisoning a different
+ // universe's draft. Dropping it loses nothing: the write is already persisted
+ // and returning re-reads it.
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).
+ // The freshest `updatedAt` this hook has seen CONFIRMED for each universe —
+ // stamped from every mutation response, whatever field it wrote. The hydration
+ // GET compares its own body against it and re-reads when the body is older,
+ // because a GET issued before a write's response landed can still carry the
+ // pre-write record: applying it would visibly revert the change the user just
+ // made (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]);
+ // Keyed on the server's own clock rather than a per-feature counter so it
+ // covers every writer that stamps through `noteUniverseUpdated`, not just
+ // style references — a mutation added to this hook is protected by recording
+ // its response, with no separate marker to remember. And because it decides
+ // only "re-ask the server", never "use my cached value", it also covers
+ // writers the client cannot see at all (peer sync, the image-delete purge) —
+ // which is exactly what the per-universe value cache it replaced could not
+ // do (#3109).
+ const lastSeenUpdatedAtRef = useRef(new Map());
+ const universeIsStale = useCallback((id, updatedAt) => {
+ const seen = lastSeenUpdatedAtRef.current.get(id);
+ if (!seen) return false;
+ // A body with no `updatedAt` is unorderable — treat it as stale so the
+ // re-read decides, rather than letting it silently win.
+ if (!updatedAt) return true;
+ return Date.parse(updatedAt) < Date.parse(seen);
+ }, []);
+ const noteUniverseUpdated = useCallback((id, updatedAt) => {
+ if (!id || !updatedAt) return;
+ const seen = lastSeenUpdatedAtRef.current.get(id);
+ // Monotonic — a slow response that resolves after a newer one must not roll
+ // the watermark backwards.
+ if (seen && Date.parse(seen) >= Date.parse(updatedAt)) return;
+ lastSeenUpdatedAtRef.current.set(id, updatedAt);
+ }, []);
useEffect(() => () => { mountedRef.current = false; }, []);
useEffect(() => { draftRef.current = draft; }, [draft]);
@@ -183,22 +198,24 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
return undefined;
}
let cancelled = false;
- // Captured before the fetch is issued — see styleMutationSeqRef.
- const issuedSeq = styleMutationSeq(selectedId);
Promise.all([
getUniverse(selectedId).catch(() => null),
listWorldRuns(selectedId).catch(() => []),
]).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)
+ // This body predates a mutation we already have confirmed — re-read rather
+ // than apply it. The second read is issued after that mutation's response,
+ // so it necessarily reflects the committed write. Comparing the body's own
+ // clock (not merely "did a write happen") means the common case where the
+ // GET already contains the write costs no extra request. On a re-read
+ // failure, keep the draft as the mutation left it rather than applying the
+ // body we just judged stale.
+ const universe = (fetched && universeIsStale(selectedId, fetched.updatedAt))
+ ? await getUniverse(selectedId).catch(() => null)
: fetched;
if (cancelled) return;
if (universe) {
+ noteUniverseUpdated(selectedId, universe.updatedAt);
const hydrated = {
...universe,
categories: ensureDraftCategories(universe.categories),
@@ -217,7 +234,7 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
setRuns(nextRuns);
});
return () => { cancelled = true; };
- }, [selectedId, styleMutationSeq]);
+ }, [selectedId, universeIsStale, noteUniverseUpdated]);
const handleSave = async () => {
if (!draft.name?.trim()) {
@@ -273,6 +290,11 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
clearPendingCanonAdditions();
}
markDraftSaved(payload);
+ // Watermark this save so a re-hydration GET it raced (navigate away and back
+ // mid-save) re-reads instead of showing the pre-save record — the same guard
+ // the style-reference mutators get, which is why it keys on the server's
+ // clock rather than on anything style-reference-specific.
+ noteUniverseUpdated(result.id, result.updatedAt);
toast.success(selectedId ? 'World updated' : 'World created');
setWorlds((previous) => upsertByIdPrepend(previous, result));
if (result.id !== selectedId) goToWorld(result.id);
@@ -335,19 +357,22 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
// `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);
+ // `capturedStyle` is the style guide as it read when an ADOPT request was
+ // issued; passing it is what marks the response as an adopt. A plain add or
+ // remove passes nothing, because it wrote no guidance to fold in.
+ const applyStyleReferenceResult = useCallback((targetId, updated, capturedStyle = null) => {
+ noteUniverseUpdated(targetId, updated.updatedAt);
if (selectedIdRef.current === targetId) {
- if (adopt) markStyleGuidanceSaved(updated);
+ if (capturedStyle) markStyleGuidanceSaved(updated);
setDraft((latest) => {
- const styleUnchangedDuringSave = !capturedStyle
- || (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 || [],
updatedAt: updated.updatedAt,
- ...(adopt && styleUnchangedDuringSave ? {
+ ...(styleUnchangedDuringSave ? {
styleNotes: updated.styleNotes || '',
influences: ensureInfluences(updated.influences),
} : {}),
@@ -355,13 +380,11 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
});
}
setWorlds((previous) => upsertByIdPrepend(previous, updated));
- }, [bumpStyleMutationSeq, markStyleGuidanceSaved]);
+ }, [noteUniverseUpdated, 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.
+ // Add one art reference. Sends ONLY the addition — see `addStyleReference` in
+ // server/services/universeBuilder/crud.js for why (#3109). The cap is enforced
+ // there too, against persisted state rather than a client cache.
const persistStyleReference = useCallback(async ({ reference, proposed, adopt }) => {
if (!selectedId || !reference) return false;
const targetId = selectedId;
@@ -381,14 +404,13 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
return null;
});
if (!updated) return false;
- applyStyleReferenceResult(targetId, updated, { adopt: !!adopt, capturedStyle });
+ applyStyleReferenceResult(targetId, updated, adopt ? capturedStyle : null);
toast.success(adopt ? 'Art reference added and style guide updated' : 'Art reference added');
return true;
}, [applyStyleReferenceResult, draft, selectedId]);
- // 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.
+ // Remove one art reference by id. Also a delta, so back-to-back removals need
+ // no client-side queue — the server's record write queue serializes them.
const removeStyleReference = useCallback(async (referenceId) => {
if (!selectedId) return false;
const targetId = selectedId;
diff --git a/client/src/hooks/useUniverseDraft.test.jsx b/client/src/hooks/useUniverseDraft.test.jsx
index 9343636011..5356bc2794 100644
--- a/client/src/hooks/useUniverseDraft.test.jsx
+++ b/client/src/hooks/useUniverseDraft.test.jsx
@@ -17,7 +17,6 @@ const apiMocks = vi.hoisted(() => ({
WORLD_CATEGORY_KEY_MAX: 64,
WORLD_CATEGORIES: ['characters', 'places', 'objects'],
WORLD_LOCKABLE_FIELDS: ['starterPrompt', 'logline', 'premise', 'styleNotes'],
- WORLD_STYLE_REFERENCES_MAX: 20,
ensureInfluences: (value) => ({
embrace: Array.isArray(value?.embrace) ? value.embrace : [],
avoid: Array.isArray(value?.avoid) ? value.avoid : [],
@@ -46,6 +45,7 @@ const universe = {
characters: [{ name: 'Stale Draft Character' }],
places: [],
objects: [],
+ updatedAt: '2026-01-01T00:00:00.000Z',
};
// Stand-in for the server's authoritative styleReferences list, keyed by
@@ -55,9 +55,19 @@ const universe = {
let serverReferences;
const serverRefsFor = (id) => serverReferences.get(id) ?? [];
+// The server's `updatedAt` clock. Every write bumps it, and the hook keys its
+// "is this GET body older than a write I already saw?" watermark on it — so the
+// mock has to advance it or the ordering under test isn't modelled at all.
+let serverClock;
+const tickServerClock = () => {
+ serverClock += 1;
+ return `2026-01-01T00:00:${String(serverClock).padStart(2, '0')}.000Z`;
+};
+
beforeEach(() => {
vi.clearAllMocks();
serverReferences = new Map();
+ serverClock = 0;
apiMocks.listUniverses.mockResolvedValue([universe]);
apiMocks.getProviders.mockResolvedValue({ providers: [], activeProvider: null });
apiMocks.listImageModels.mockResolvedValue([]);
@@ -65,16 +75,20 @@ beforeEach(() => {
apiMocks.getSettings.mockResolvedValue({ imageGen: {} });
apiMocks.getUniverse.mockResolvedValue(universe);
apiMocks.listWorldRuns.mockResolvedValue([{ id: 'run-1' }]);
- apiMocks.updateUniverse.mockImplementation(async (id, payload) => ({ ...universe, id, ...payload }));
+ apiMocks.updateUniverse.mockImplementation(async (id, payload) => ({
+ ...universe, id, ...payload, updatedAt: tickServerClock(),
+ }));
apiMocks.addUniverseStyleReference.mockImplementation(async (id, { reference, adopt } = {}) => {
const next = [...serverRefsFor(id), reference];
serverReferences.set(id, next);
- return { ...universe, id, styleReferences: next, ...(adopt || {}) };
+ return {
+ ...universe, id, styleReferences: next, ...(adopt || {}), updatedAt: tickServerClock(),
+ };
});
apiMocks.removeUniverseStyleReference.mockImplementation(async (id, referenceId) => {
const next = serverRefsFor(id).filter((ref) => ref.id !== referenceId);
serverReferences.set(id, next);
- return { ...universe, id, styleReferences: next };
+ return { ...universe, id, styleReferences: next, updatedAt: tickServerClock() };
});
});
@@ -261,7 +275,6 @@ describe('useUniverseDraft', () => {
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();
@@ -303,13 +316,19 @@ describe('useUniverseDraft', () => {
// 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 serverUpdatedAt = universe.updatedAt;
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: serverRefsFor('u1'), styleNotes: serverStyleNotes };
+ return {
+ ...universe,
+ styleReferences: serverRefsFor('u1'),
+ styleNotes: serverStyleNotes,
+ updatedAt: serverUpdatedAt,
+ };
});
const { result, rerender } = renderSelectable();
@@ -331,15 +350,19 @@ describe('useUniverseDraft', () => {
await act(async () => { rerender({ selectedId: 'u1' }); });
await waitFor(() => expect(resolveU1Hydration).toBeTypeOf('function'));
- // The add resolves first — the reordering this guard exists for.
+ // The add resolves first — the reordering this guard exists for. It advances
+ // the server clock, which is what makes G's older body detectable.
+ const addUpdatedAt = tickServerClock();
await act(async () => {
serverReferences.set('u1', [refA, refX]);
serverStyleNotes = 'Adopted notes';
+ serverUpdatedAt = addUpdatedAt;
resolveU1Add({
...universe,
styleReferences: [refA, refX],
styleNotes: 'Adopted notes',
influences: { embrace: ['ink'], avoid: [] },
+ updatedAt: addUpdatedAt,
});
await pendingAdd;
});
@@ -348,7 +371,9 @@ describe('useUniverseDraft', () => {
// 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: '' });
+ resolveU1Hydration({
+ ...universe, styleReferences: [refA], styleNotes: '', updatedAt: universe.updatedAt,
+ });
await Promise.resolve();
});
@@ -359,6 +384,84 @@ describe('useUniverseDraft', () => {
expect(result.current.isDraftDirty()).toBe(false);
});
+ it('does not re-read when the hydration GET already contains the mutation', async () => {
+ // The other half of the gate: it compares the BODY's clock against the newest
+ // write seen, not merely "did a write happen" — so the common overlap, where
+ // the GET was served after the write committed, costs no extra round-trip.
+ const refX = { id: 'style-ref-x', title: 'Ref X', prompt: 'x', imageRefs: ['x.png'] };
+ let serverUpdatedAt = universe.updatedAt;
+ apiMocks.getUniverse.mockImplementation(async (id) => (id === 'u2'
+ ? universeTwo
+ : { ...universe, styleReferences: serverRefsFor('u1'), updatedAt: serverUpdatedAt }));
+
+ const { result, rerender } = renderSelectable();
+ await waitFor(() => expect(result.current.draft.id).toBe('u1'));
+ apiMocks.addUniverseStyleReference.mockImplementationOnce(async (id, { reference }) => {
+ serverReferences.set(id, [...serverRefsFor(id), reference]);
+ serverUpdatedAt = tickServerClock();
+ return { ...universe, id, styleReferences: serverRefsFor(id), updatedAt: serverUpdatedAt };
+ });
+ await act(async () => {
+ await result.current.persistStyleReference({ reference: refX, adopt: false });
+ });
+
+ const fetchesBefore = apiMocks.getUniverse.mock.calls.length;
+ 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([refX]));
+
+ // One GET for u2, one for u1 — no third (re-read) call.
+ expect(apiMocks.getUniverse.mock.calls.length).toBe(fetchesBefore + 2);
+ });
+
+ it('re-reads after a general Save that a hydration GET raced, not just a reference mutation', async () => {
+ // The stale-GET guard keys on the server's clock rather than on anything
+ // style-reference-specific, so every writer that stamps its response is
+ // covered — including handleSave. Without that, a save → navigate away →
+ // back round trip could show the pre-save record.
+ let serverPremise = 'Original premise';
+ let serverUpdatedAt = universe.updatedAt;
+ 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, premise: serverPremise, updatedAt: serverUpdatedAt };
+ });
+
+ const { result, rerender } = renderSelectable();
+ await waitFor(() => expect(result.current.draft.id).toBe('u1'));
+ act(() => result.current.updateDraft({ premise: 'Saved premise' }));
+
+ // handleSave sets `saving` synchronously before its first await, so the call
+ // itself has to be inside act() (unlike the reference mutators).
+ let resolveSave;
+ let pendingSave;
+ apiMocks.updateUniverse.mockImplementationOnce(() => new Promise((resolve) => { resolveSave = resolve; }));
+ await act(async () => { pendingSave = result.current.handleSave(); });
+
+ 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'));
+
+ const savedAt = tickServerClock();
+ await act(async () => {
+ serverPremise = 'Saved premise';
+ serverUpdatedAt = savedAt;
+ resolveSave({ ...universe, premise: 'Saved premise', updatedAt: savedAt });
+ await pendingSave;
+ });
+ await act(async () => {
+ resolveU1Hydration({ ...universe, premise: 'Original premise', updatedAt: universe.updatedAt });
+ await Promise.resolve();
+ });
+
+ await waitFor(() => expect(result.current.draft.premise).toBe('Saved premise'));
+ });
+
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,
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index b9296cb17b..19cdfc32ba 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -46,13 +46,11 @@ 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.
+// Add / remove ONE art style reference — deltas, not a wholesale array replace
+// (see `addStyleReference` in server/services/universeBuilder/crud.js for why).
+// 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 },
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index fdc78f0db7..d137955c47 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -893,27 +893,30 @@ router.get('/:id/series-names', asyncHandler(async (req, res) => {
// ---- 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.
+// Add/remove one reference at a time instead of PATCHing the whole array; see
+// `addStyleReference` in services/universeBuilder/crud.js for the rationale.
+// The wholesale-replace `{ styleReferences: [...] }` field on PATCH /:id stays
+// accepted (older clients, peer imports, the sharing importer).
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) }),
+ // server-side, and /analyze-style-reference always returns one. `required`
+ // only drops the `.optional()` — the trim/length rules stay defined once, on
+ // the shared `entryIdField`.
+ reference: styleReferenceSchema.required({ id: true }),
// Present when the user chose "Adopt style + add" — written in the SAME
- // queued write as the reference so the pair can't half-land.
+ // queued write as the reference so the pair can't half-land. Both fields
+ // default, so `adopt: {}` reads as "adopt an empty guide" (an explicit clear)
+ // instead of reaching the service as `undefined` and clearing influences by
+ // accident — matching analyzeStyleReferenceSchema's choice for the same pair.
adopt: z.object({
styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),
- influences: influencesSchema.optional(),
+ influences: influencesSchema.optional().default({ embrace: [], avoid: [] }),
}).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 })
+ const w = await svc.addStyleReference(req.params.id, body.reference, { adopt: body.adopt })
.catch((err) => { throw mapServiceError(err); });
res.json(w);
}));
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index d6f99d003d..a684184cd0 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -483,6 +483,25 @@ describe("universeBuilder service", () => {
})).rejects.toThrow(/up to 20 art references/);
});
+ it("style-reference deltas leave canon untouched (so the projection opt-out is sound)", async () => {
+ // Guard for `touchesCanon: false`: these deltas skip the per-entry
+ // canon→catalog projection the mutator path normally runs, which is only
+ // sound because their patch carries no canon key. If either ever starts
+ // writing one, this fails and the opt-out has to go.
+ const w = await svc.createUniverse({
+ name: "Canon Untouched",
+ characters: [{ name: "Jean", physicalDescription: "tall" }],
+ });
+ const before = (await svc.getUniverse(w.id)).characters;
+ expect(before).toHaveLength(1);
+
+ const reference = { id: "style-ref-x", title: "X", prompt: "x", imageRefs: ["x.png"] };
+ const added = await svc.addStyleReference(w.id, reference);
+ expect(added.characters).toEqual(before);
+ const removed = await svc.removeStyleReference(w.id, reference.id);
+ expect(removed.characters).toEqual(before);
+ });
+
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"] };
diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.js
index 5eedc23e29..da4e205fff 100644
--- a/server/services/universeBuilder/crud.js
+++ b/server/services/universeBuilder/crud.js
@@ -22,7 +22,7 @@ import {
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,
+ STYLE_REFERENCES_MAX, STYLE_NOTES_MAX,
} from './sanitize.js';
import {
emitRecordUpdated, emitRecordDeleted,
@@ -347,7 +347,20 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
// "restore mine" path so a faithful restore of the archived snapshot drops a
// category the live record gained since the conflict, rather than resurrecting
// it under the normal additive-PATCH semantics (see `mergedCategories` below).
- const { silent = false, canonProjectionGuard = null, replaceCategories = false } = options;
+ // `options.touchesCanon: false` asserts this write cannot have changed the canon
+ // arrays, so the (per-entry, serial) catalog projection and the removed-character
+ // diff below are skipped. Needed because those are gated on `isMutator` — a
+ // conservative "a mutator could have touched anything" — while projectToCatalog
+ // issues one catalog SELECT per canon entry INSIDE the queued critical section, so
+ // on a 50-character universe a scalar-only mutator would stall the record's write
+ // queue behind 50 round-trips for no reason. Only set it from a mutator whose patch
+ // provably carries no canon key (see addStyleReference / removeStyleReference); a
+ // literal-object PATCH doesn't need it, its own `'characters' in patch` checks are
+ // already precise.
+ const {
+ silent = false, canonProjectionGuard = null, replaceCategories = false,
+ touchesCanon = true,
+ } = options;
const s = store();
const { merged, nameChanged, skipped, removedCharacterIds, prevEphemeral, nextEphemeral } = await s.queueRecordWrite(id, async () => {
const cur = await s.loadOne(id);
@@ -553,7 +566,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
// the import/call anyway — this runs inside the queued write critical
// section and an uncaught throw here would reject the whole save. Skipped
// when the patch can't have touched canon arrays (rename/scalar PATCH).
- if (isMutator || 'characters' in patch || 'places' in patch || 'objects' in patch) {
+ if (touchesCanon && (isMutator || 'characters' in patch || 'places' in patch || 'objects' in patch)) {
try {
const { projectToCatalog } = await import('../catalogCanonProjection.js');
await projectToCatalog(id, mergedRecord, { guardToken: canonProjectionGuard });
@@ -566,7 +579,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
// literal-PATCH carrying `characters`) — rename/scalar PATCHes are the
// common case and skip the Set construction entirely.
let removedCharacterIds = null;
- if (isMutator || 'characters' in patch) {
+ if (touchesCanon && (isMutator || 'characters' in patch)) {
const idsOf = (arr) => (Array.isArray(arr)
? arr.filter((c) => c?.id).map((c) => c.id) : []);
const prevIds = new Set(idsOf(cur.characters));
@@ -667,11 +680,13 @@ export async function addStyleReference(id, reference, { adopt = null } = {}) {
return {
styleReferences: [...current, sanitized],
...(adopt ? {
- styleNotes: isStr(adopt.styleNotes) ? adopt.styleNotes : '',
+ styleNotes: trimTo(adopt.styleNotes, STYLE_NOTES_MAX),
influences: resolveInfluences(adopt),
} : {}),
};
- });
+ // A styleReferences (+ style-guide) patch carries no canon key, so skip the
+ // per-entry catalog projection the mutator path would otherwise run.
+ }, { touchesCanon: false });
}
/**
@@ -687,7 +702,7 @@ export async function removeStyleReference(id, referenceId) {
const next = current.filter((ref) => ref?.id !== referenceId);
if (next.length === current.length) return null;
return { styleReferences: next };
- });
+ }, { touchesCanon: false });
}
export async function deleteUniverse(id) {