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
fix: wait for universe writes before Markdown export (#5031)
[._.]/ Adam Eivy06b75d704e57
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsxindex 4e40df57bb..a81877a2c6 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx@@ -8,7 +8,7 @@* panel modules.*/-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Link, useLocation, useParams } from 'react-router';import {ArrowLeft, BookOpen, FolderTree, ImagePlus, Layers, Loader2,@@ -16,7 +16,11 @@ import {} from 'lucide-react';import InlineConfirmRow from '../ui/InlineConfirmRow';import toast from '../ui/Toast';-import { exportUniverseMarkdown, WORLD_CATEGORY_KEY_MAX } from '../../services/api';+import {+ exportUniverseMarkdown,+ waitForUniverseWrites,+ WORLD_CATEGORY_KEY_MAX,+} from '../../services/api';import useUniverseBucketActions from '../../hooks/useUniverseBucketActions';import useUniverseDraft from '../../hooks/useUniverseDraft';import useUniverseExpand from '../../hooks/useUniverseExpand';@@ -111,6 +115,8 @@ export default function UniverseBuilder() {// treat the `new` sentinel as "no id" (blank draft). Real universe ids are// UUIDs, so this can never shadow an actual record.const selectedId = params.universeId && params.universeId !== 'new' ? params.universeId : null;+ const selectedIdRef = useRef(selectedId);+ selectedIdRef.current = selectedId;const [exporting, setExporting] = useState(false);// `goToWorld` preserves `location.search` (e.g. `?tab=&bucket=&series=`) so// the auto-save → create path doesn't snap the user back to the Bible tab@@ -223,23 +229,34 @@ export default function UniverseBuilder() {});const handleExportMarkdown = useCallback(async () => {- if (!selectedId || exporting) return;+ const exportIsReady = () => selectedIdRef.current === selectedId && draftRef.current?.id === selectedId;+ if (!selectedId || exporting || saving || !exportIsReady()) return;setExporting(true);+ await waitForUniverseWrites(selectedId);+ if (!exportIsReady()) {+ setExporting(false);+ return;+ }const flushed = await flushDraftIfDirty();if (!flushed) {setExporting(false);return;}+ await waitForUniverseWrites(selectedId);+ if (!exportIsReady()) {+ setExporting(false);+ return;+ }const markdown = await exportUniverseMarkdown(selectedId, { silent: true }).catch((error) => {toast.error(error?.message || 'Failed to export universe');return null;});setExporting(false);if (markdown === null) return;- const filename = `${downloadSlug(draft.name)}.md`;+ const filename = `${downloadSlug(draftRef.current?.name || draft.name)}.md`;downloadBlob(markdown, filename, 'text/markdown');toast.success(`Downloaded ${filename}`);- }, [draft.name, exporting, flushDraftIfDirty, selectedId]);+ }, [draft.name, draftRef, exporting, flushDraftIfDirty, saving, selectedId]);// Page-level lightbox + gallery-metadata concern. A single MediaPreview at// this level covers EVERY thumb on the page: variations, composite sheets,@@ -378,7 +395,7 @@ export default function UniverseBuilder() {<><buttononClick={handleExportMarkdown}- disabled={exporting}+ disabled={exporting || saving || draft.id !== selectedId}className="px-3 py-2 rounded flex items-center gap-2 min-h-[40px] border border-port-border hover:bg-port-card-hover disabled:opacity-50"title="Export universe as Markdown">diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex 8ecd73b81f..fe4bfc1353 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -15,6 +15,34 @@ export const WORLD_INFLUENCE_ENTRY_MAX = 120;export const WORLD_INFLUENCES_PER_LIST_MAX = 30;export const WORLD_STYLE_REFERENCES_MAX = 20;+// Targeted canon/style-reference editors persist outside the general draft+// snapshot. Keep their requests visible to actions that immediately read the+// persisted universe, such as Markdown export.+const pendingUniverseWrites = new Map();++const trackUniverseWrite = (universeId, promise) => {+ if (!universeId) return promise;+ const writes = pendingUniverseWrites.get(universeId) || new Set();+ writes.add(promise);+ pendingUniverseWrites.set(universeId, writes);+ const remove = () => {+ writes.delete(promise);+ if (writes.size === 0 && pendingUniverseWrites.get(universeId) === writes) {+ pendingUniverseWrites.delete(universeId);+ }+ };+ // Attach both settlement handlers so a failed request is observed here+ // without changing the rejection delivered to the caller.+ promise.then(remove, remove);+ return promise;+};++export const waitForUniverseWrites = async (universeId) => {+ while (pendingUniverseWrites.get(universeId)?.size) {+ await Promise.allSettled([...pendingUniverseWrites.get(universeId)]);+ }+};+// `options` lets a caller that owns its own error toast pass `{ silent: true }`// so request() doesn't also toast — see AGENTS.md "Custom catch ⇒ silent: true".export const listUniverses = (options = {}) => request('/universe-builder', options);@@ -36,11 +64,11 @@ export const createUniverse = (data, options = {}) => request('/universe-builder...options,});-export const updateUniverse = (id, patch, options = {}) => request(`/universe-builder/${encodeURIComponent(id)}`, {+export const updateUniverse = (id, patch, options = {}) => trackUniverseWrite(id, request(`/universe-builder/${encodeURIComponent(id)}`, {method: 'PATCH',body: JSON.stringify(patch),...options,-});+}));// `options` lets callers that own their own error toast (a custom `.catch`)// pass `{ silent: true }` so the request() helper doesn't also toast — see@@ -55,24 +83,24 @@ export const deleteUniverse = (id, options = {}) => request(`/universe-builder/$// 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(+export const addUniverseStyleReference = (id, { reference, adopt } = {}, options = {}) => trackUniverseWrite(id, request(`/universe-builder/${encodeURIComponent(id)}/style-references`,{ method: 'POST', body: JSON.stringify({ reference, ...(adopt ? { adopt } : {}) }), ...options },-);+));-export const removeUniverseStyleReference = (id, referenceId, options = {}) => request(+export const removeUniverseStyleReference = (id, referenceId, options = {}) => trackUniverseWrite(id, request(`/universe-builder/${encodeURIComponent(id)}/style-references/${encodeURIComponent(referenceId)}`,{ method: 'DELETE', ...options },-);+));// Adopt a proposed style guide with no reference record attached (#4188// Phase 4 — mood-board synthesis). Server-side queued write; locks are// re-checked against the freshest persisted record. Resolves with the full// updated universe.-export const adoptUniverseStyleGuide = (id, { styleNotes, influences } = {}, options = {}) => request(+export const adoptUniverseStyleGuide = (id, { styleNotes, influences } = {}, options = {}) => trackUniverseWrite(id, request(`/universe-builder/${encodeURIComponent(id)}/adopt-style`,{ method: 'POST', body: JSON.stringify({ styleNotes, influences }), ...options },-);+));export const expandUniverse = ({starterPrompt, influences,@@ -157,14 +185,14 @@ export const correctEntityFromImage = (universeId, kind, entryId, {// entry's `primaryImageRef` in one atomic write.export const applyCanonImageCorrection = (universeId, kind, entryId, {description, imageFilename,-} = {}, options = {}) => request(+} = {}, options = {}) => trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}/apply-image-correction`,{method: 'POST',body: JSON.stringify({ description, imageFilename }),...options,},-);+));// Caller should dedupe the returned variations against its local list before// appending — the local list may have changed during the request.@@ -282,29 +310,29 @@ export const listWorldRuns = (id) => request(`/universe-builder/${encodeURICompo// canon arrays. The corpus is usually an issue's prose stage output but can// be anything text-shaped.export const extractUniverseCanon = (universeId, { corpus, kinds, parallel, providerOverride } = {}, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/extract-canon`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/extract-canon`, {method: 'POST',body: JSON.stringify({ corpus, kinds, parallel, providerOverride }),...options,- });+ }));export const refineUniverseCharacter = (universeId, entryId, { providerId, model } = {}, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/refine`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/refine`, {method: 'POST',body: JSON.stringify({ providerId, model }),...options,- });+ }));// One LLM call fills BLANK extended character fields (pronouns / age / stats /// motivations / colorPalette / expressions / hand gestures / ...). No-clobber// on populated fields. Locked characters return `{ locked: true }` instead of// a 4xx — the UI surfaces this as a "Locked" badge.export const expandUniverseCharacter = (universeId, entryId, { providerId, model } = {}, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/expand`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/expand`, {method: 'POST',body: JSON.stringify({ providerId, model }),...options,- });+ }));// Catalog of every registered reference-sheet variant. The panel iterates// this on mount to render one row per variant. New variants light up@@ -320,30 +348,30 @@ export const fetchReferenceSheetVariants = (options = {}) =>export const renderCharacterReferenceSheet = (universeId, entryId, {variant, overridePrompt, overrideNegativePrompt, modelId,} = {}, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/render-reference-sheet`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/render-reference-sheet`, {method: 'POST',body: JSON.stringify({ variant, overridePrompt, overrideNegativePrompt, modelId }),...options,- });+ }));// Delete the character's reference sheet of the given variant. Variant// defaults server-side to 'standard'. Returns `{ filename, fileDeleted, cleared }`.export const deleteCharacterReferenceSheet = (universeId, entryId, { variant, ...requestOpts } = {}) => {const qs = variant ? `?variant=${encodeURIComponent(variant)}` : '';- return request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/reference-sheet${qs}`, {+ return trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/reference-sheet${qs}`, {method: 'DELETE',...requestOpts,- });+ }));};// Cast-wide differentiate — single LLM call rewrites every character so the// whole cast has no visually-colliding pairs.export const differentiateUniverseCast = (universeId, { providerId, model } = {}, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/characters/differentiate-cast`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/differentiate-cast`, {method: 'POST',body: JSON.stringify({ providerId, model }),...options,- });+ }));// Cross-reference: where each canon entry appears across the universe's// linked series. Returns `{ characters: { [entryId]: [{seriesId, seriesName,@@ -363,39 +391,39 @@ export const getUniverseSeriesNames = (universeId) =>// them at apply time; re-extract appends evidence only). `kind` must be// 'character' | 'place' | 'object' (the singular BIBLE_KIND values).export const setUniverseCanonLock = (universeId, kind, entryId, locked, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}/lock`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}/lock`, {method: 'PATCH',body: JSON.stringify({ locked }),...options,- });+ }));// Remove one canon entry from its universe bucket. Returns// `{ universe, entry }`. Scoped to the canon array ONLY — the entry's rendered// images / reference sheets stay in the gallery and the shared Catalog// ingredient it may point at is left untouched.export const removeUniverseCanonEntry = (universeId, kind, entryId, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/${encodeURIComponent(entryId)}`, {method: 'DELETE',...options,- });+ }));// Bulk lock/unlock every canon entry of a single kind. Returns// `{ universe, kind, locked, changed, total }`.export const setUniverseCanonLockAll = (universeId, kind, locked, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/lock-all`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/canon/${encodeURIComponent(kind)}/lock-all`, {method: 'PATCH',body: JSON.stringify({ locked }),...options,- });+ }));// Bulk lock/unlock variations across one bucket (`category`) or every bucket// (`category: null`). Pass `includeSheets: true` to also flip composite// sheets in the same call.export const setUniverseVariationsLockAll = (universeId, { locked, category = null, includeSheets = false } = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/variations/lock-all`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/variations/lock-all`, {method: 'PATCH',body: JSON.stringify({ locked, category, includeSheets }),- });+ }));// Promote a category variation into a full canon entry. `targetKind` is// required only when the source bucket's `kind` is 'other' (otherwise the@@ -404,18 +432,18 @@ export const setUniverseVariationsLockAll = (universeId, { locked, category = nuexport const promoteVariationToCanon = (universeId, {category, label, targetKind, providerId, model,} = {}, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/promote-variation`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/promote-variation`, {method: 'POST',body: JSON.stringify({ category, label, targetKind, providerId, model }),...options,- });+ }));// Bulk-classify every `kind: 'other'` bucket on a universe. Server returns// `{ universe, results: [{ sourceKey, kind, suggestedKey? }], llm, runId }`.// Pass `{ silent: true }` when the caller owns its own error toast.export const autoSortBuckets = (universeId, { providerId, model } = {}, options = {}) =>- request(`/universe-builder/${encodeURIComponent(universeId)}/auto-sort`, {+ trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/auto-sort`, {method: 'POST',body: JSON.stringify({ providerId, model }),...options,- });+ }));