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

fix: bound and test Markdown export handoff (#5031)

[._.]/ Adam Eivy3f572e83e64f
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
index e67624a028..83118ea342 100644
--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx
+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
@@ -41,6 +41,7 @@ import { OtherTab, TrunkView } from './UniverseTrunkPanels';
import { appendImageRefById } from '../../lib/bibleLimits';
import { downloadBlob } from '../../lib/downloadBlob';
import { totalVariationCount } from '../../lib/universeBuilderCounts';
+import { universeMarkdownFilename } from '../../lib/universeMarkdownFilename';
import {
TAB_BIBLE,
TAB_CAST,
@@ -56,14 +57,6 @@ import {
export { CategoryEditor } from './UniverseCategoryEditor';
export { OtherTab, TrunkView };
-const downloadSlug = (name) => String(name || 'universe')
- .normalize('NFKD')
- .replace(/[\u0300-\u036f]/g, '')
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-+|-+$/g, '') || 'universe';
-
-
// Universe autocomplete combobox: search existing universes or create one when
// the trimmed query doesn't exactly match any. `onCreate` is wired to a
// dedicated create path (not handleSave) so typing a new name while an existing
@@ -118,6 +111,7 @@ export default function UniverseBuilder() {
const selectedIdRef = useRef(selectedId);
selectedIdRef.current = selectedId;
const [exporting, setExporting] = useState(false);
+ const [waitingForWrites, setWaitingForWrites] = 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
// after they triggered Generate From Idea from inside Cast/Places/Objects.
@@ -229,10 +223,19 @@ export default function UniverseBuilder() {
});
const handleExportMarkdown = useCallback(async () => {
- const exportIsReady = () => selectedIdRef.current === selectedId && draftRef.current?.id === selectedId;
+ const exportIsReady = () => mountedRef.current
+ && selectedIdRef.current === selectedId
+ && draftRef.current?.id === selectedId;
if (!selectedId || exporting || saving || !exportIsReady()) return;
setExporting(true);
- await waitForUniverseWrites(selectedId);
+ setWaitingForWrites(true);
+ const writesReady = await waitForUniverseWrites(selectedId);
+ setWaitingForWrites(false);
+ if (!writesReady) {
+ setExporting(false);
+ toast.error('Changes are still saving — try the export again in a moment');
+ return;
+ }
if (!exportIsReady()) {
setExporting(false);
return;
@@ -242,7 +245,14 @@ export default function UniverseBuilder() {
setExporting(false);
return;
}
- await waitForUniverseWrites(selectedId);
+ setWaitingForWrites(true);
+ const flushedWritesReady = await waitForUniverseWrites(selectedId);
+ setWaitingForWrites(false);
+ if (!flushedWritesReady) {
+ setExporting(false);
+ toast.error('Changes are still saving — try the export again in a moment');
+ return;
+ }
if (!exportIsReady()) {
setExporting(false);
return;
@@ -260,7 +270,7 @@ export default function UniverseBuilder() {
return;
}
setExporting(false);
- const filename = `${downloadSlug(draftRef.current?.name || draft.name)}.md`;
+ const filename = universeMarkdownFilename(draftRef.current?.name || draft.name);
downloadBlob(markdown, filename, 'text/markdown');
toast.success(`Downloaded ${filename}`);
}, [draft.name, draftRef, exporting, flushDraftIfDirty, saving, selectedId]);
@@ -407,7 +417,7 @@ export default function UniverseBuilder() {
title="Export universe as Markdown"
>
{exporting ? <Loader2 size={16} className="animate-spin" /> : <BookOpen size={16} />}
- {exporting ? 'Exporting…' : 'Export .md'}
+ {waitingForWrites ? 'Saving changes…' : exporting ? 'Exporting…' : 'Export .md'}
</button>
<ShareToButton kind="universe" ids={[selectedId]} label="Share" />
<SyncToPeerButton recordKind="universe" recordId={selectedId} label="Sync" />
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.test.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.test.jsx
new file mode 100644
index 0000000000..2f9bac4a62
--- /dev/null
+++ b/client/src/components/universeBuilder/UniverseBuilderPage.test.jsx
@@ -0,0 +1,183 @@
+import { fireEvent, render, screen, waitFor, act } from '@testing-library/react';
+import { MemoryRouter, Route, Routes, useNavigate } from 'react-router';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const apiMocks = vi.hoisted(() => ({
+ exportUniverseMarkdown: vi.fn(),
+ waitForUniverseWrites: vi.fn(),
+}));
+const downloadMock = vi.hoisted(() => ({ downloadBlob: vi.fn() }));
+const toastMock = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+const hookMocks = vi.hoisted(() => ({
+ useUniverseDraft: vi.fn(),
+ useUniverseExpand: vi.fn(),
+ useUniverseGallery: vi.fn(),
+ useUniverseRender: vi.fn(),
+ useUniverseTabs: vi.fn(),
+ useUniverseBucketActions: vi.fn(),
+ useUniverseNav: vi.fn(),
+}));
+
+vi.mock('../../services/api', () => ({
+ ...apiMocks,
+ WORLD_CATEGORY_KEY_MAX: 64,
+}));
+vi.mock('../../lib/downloadBlob', () => downloadMock);
+vi.mock('../ui/Toast', () => ({ default: toastMock }));
+vi.mock('../../hooks/useUniverseDraft', () => ({ default: hookMocks.useUniverseDraft }));
+vi.mock('../../hooks/useUniverseExpand', () => ({ default: hookMocks.useUniverseExpand }));
+vi.mock('../../hooks/useUniverseGallery', () => ({ default: hookMocks.useUniverseGallery }));
+vi.mock('../../hooks/useUniverseRender', () => ({ default: hookMocks.useUniverseRender }));
+vi.mock('../../hooks/useUniverseTabs', () => ({ default: hookMocks.useUniverseTabs }));
+vi.mock('../../hooks/useUniverseBucketActions', () => ({ default: hookMocks.useUniverseBucketActions }));
+vi.mock('../../hooks/useUniverseNav', () => ({ useUniverseNav: hookMocks.useUniverseNav }));
+vi.mock('../EntityCombobox', () => ({ default: () => null }));
+vi.mock('../ui/InlineConfirmRow', () => ({ default: () => null }));
+vi.mock('../media/MediaPreview', () => ({ default: () => null }));
+vi.mock('../sharing/OriginBadge', () => ({ default: () => null }));
+vi.mock('../sharing/ShareToButton', () => ({ default: () => null }));
+vi.mock('../sharing/SyncToPeerButton', () => ({ default: () => null }));
+vi.mock('../ui/TabPills', () => ({ default: () => null }));
+vi.mock('./CompositeSheetsEditor', () => ({ default: () => null }));
+vi.mock('./RenderTab', () => ({ default: () => null }));
+vi.mock('./UniverseBibleTab', () => ({ default: () => null }));
+vi.mock('./UniverseCategoryEditor', () => ({ CategoryEditor: () => null }));
+vi.mock('./UniverseTrunkPanels', () => ({ OtherTab: () => null, TrunkView: () => null }));
+vi.mock('lucide-react', () => {
+ const Icon = () => null;
+ return {
+ ArrowLeft: Icon, BookOpen: Icon, FolderTree: Icon, ImagePlus: Icon, Layers: Icon,
+ Loader2: Icon, MapPin: Icon, Package: Icon, Plus: Icon, Save: Icon, Trash2: Icon, Users: Icon,
+ };
+});
+
+import UniverseBuilderPage from './UniverseBuilderPage.jsx';
+
+const navigateRef = { current: null };
+
+function NavigationProbe() {
+ navigateRef.current = useNavigate();
+ return null;
+}
+
+const makeDraft = (id) => ({
+ id,
+ name: id === 'u1' ? 'First World' : 'Second World',
+ categories: {},
+ compositeSheets: [],
+ characters: [],
+ places: [],
+ objects: [],
+ influences: { embrace: [], avoid: [] },
+ styleReferences: [],
+ origin: null,
+});
+
+const fn = () => vi.fn();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ navigateRef.current = null;
+ apiMocks.waitForUniverseWrites.mockResolvedValue(true);
+ hookMocks.useUniverseNav.mockReturnValue(vi.fn());
+ hookMocks.useUniverseDraft.mockImplementation(({ selectedId }) => {
+ const draft = makeDraft(selectedId);
+ return {
+ activeProviderId: null,
+ addCategory: fn(),
+ assignBucketKind: fn(),
+ availableBackends: [],
+ availableLoras: [],
+ clearPendingCanonAdditions: fn(),
+ draft,
+ draftRef: { current: draft },
+ effectiveDefaultMode: null,
+ flushDraftIfDirty: vi.fn().mockResolvedValue(true),
+ handleCanonChange: fn(),
+ handleCreateNamed: fn(),
+ handleDelete: fn(),
+ handleSave: fn(),
+ imageCfg: {},
+ imageModels: [],
+ loading: false,
+ markDraftSaved: fn(),
+ mountedRef: { current: true },
+ newCategoryName: '',
+ pendingCanonAdditionsRef: { current: {} },
+ pendingDeleteId: null,
+ providerLabel: '',
+ providerModels: [],
+ providers: [],
+ adoptStyleGuideFromBoard: fn(),
+ persistStyleReference: fn(),
+ removeCategory: fn(),
+ removeStyleReference: fn(),
+ runs: [],
+ saving: false,
+ setCanonDirty: fn(),
+ setDraft: fn(),
+ setNewCategoryName: fn(),
+ setPendingDeleteId: fn(),
+ setRenderPin: fn(),
+ setRuns: fn(),
+ setSaving: fn(),
+ setWorlds: fn(),
+ styleProbeDirty: false,
+ syncEntryIdsFromServer: fn(),
+ toggleLock: fn(),
+ universes: [],
+ updateCategory: fn(),
+ updateCompositeSheets: fn(),
+ updateDraft: fn(),
+ };
+ });
+ hookMocks.useUniverseExpand.mockReturnValue({
+ expanding: false, handleExpand: fn(), refine: fn(),
+ });
+ hookMocks.useUniverseGallery.mockReturnValue({
+ previewItems: [], preview: null, setPreview: fn(), previewActions: {
+ handleClean: fn(), handleContinue: fn(), handleRemix: fn(),
+ handleRemoveWatermark: fn(), handleSendToImage: fn(), handleSendToVideo: fn(),
+ }, openPreviewByFilename: fn(), openVariationPreview: fn(), annotations: {},
+ updateAnnotation: fn(), bumpGalleryRefresh: fn(),
+ });
+ hookMocks.useUniverseRender.mockReturnValue({
+ canRender: false, clearPendingForEntry: fn(), handleRender: fn(),
+ pendingHeadByEntryId: {}, renderOpts: {}, rendering: false, runRender: fn(), setRenderOpts: fn(),
+ });
+ hookMocks.useUniverseTabs.mockReturnValue({
+ activeBucket: null, activeTab: 'bible', bucketsByKind: {
+ characters: [], places: [], objects: [], other: [],
+ }, hasOtherBuckets: false, setBucket: fn(), setTab: fn(),
+ });
+ hookMocks.useUniverseBucketActions.mockReturnValue({
+ autoSorting: false, handleAutoSort: fn(), handleGenerateInCategory: fn(),
+ handlePromoteVariation: fn(), promoting: false,
+ });
+});
+
+describe('UniverseBuilderPage Markdown export', () => {
+ it('does not download a response after navigating to another universe', async () => {
+ let resolveExport;
+ apiMocks.exportUniverseMarkdown.mockReturnValueOnce(new Promise((resolve) => {
+ resolveExport = resolve;
+ }));
+
+ render(
+ <MemoryRouter initialEntries={['/universes/u1']}>
+ <NavigationProbe />
+ <Routes>
+ <Route path="/universes/:universeId" element={<UniverseBuilderPage />} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Export .md' }));
+ await waitFor(() => expect(apiMocks.exportUniverseMarkdown).toHaveBeenCalledWith('u1', { silent: true }));
+
+ act(() => { navigateRef.current('/universes/u2'); });
+ await act(async () => { resolveExport('# First World\n'); });
+
+ expect(downloadMock.downloadBlob).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 31c26ab37c..ec297bffc9 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -204,3 +204,4 @@ grep -i "what you want to do" client/src/lib/README.md
| `videoTimelineModel.js` | Pure model helpers for the layered video timeline, mirroring `server/services/videoTimeline/segments.js` so the browser preview and the ffmpeg export make the same cut/geometry/mix decisions: `segmentDuration`/`timelineDuration`/`findSegmentAt` (project-time ↔ segment mapping), `fadeMultiplier` (linear, matching ffmpeg's default `tri` curve), `overlayOpacityAt`, `audioTrackStateAt`, `segmentVolumeAt` (clipVolume × segment volume × fade — the product the export writes into each segment audio chain, so the preview auditions the mix that renders), `assetUrl(assetKind, assetFile)`, the edit clamps `clampTrim` (keeps ≥ 1 frame, matching the server's CLIP_TOO_SHORT floor) and `fitFadePatch` (shrinks an over-long fade pair proportionally instead of letting the PATCH 400), the index summary `projectSummary(project, thumbnailFor)` (block count / duration / card thumbnail — reads the `segments` lane, NEVER the derived `clips` mirror, which omits stills), and the save helpers `stripKey`/`withKeys`/`timelinePatch`. Change a rule here and in the server module in the same commit. |
| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
| `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |
+| `universeMarkdownFilename.js` | `slugifyUniverseName` / `universeMarkdownFilename` — client-side safe filename helpers for Universe Markdown world-bible downloads, kept in step with the server attachment name. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index f00871929f..ab37d7c447 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -14,6 +14,7 @@ export * from './shotContinuity.js';
export * from './shotGrammar.js';
export * from './universeBuilderCounts.js';
export * from './universeBuilderShared.js';
+export * from './universeMarkdownFilename.js';
export * from './universeRunTag.js';
export * from './universeStylePreset.js';
diff --git a/client/src/lib/universeMarkdownFilename.js b/client/src/lib/universeMarkdownFilename.js
new file mode 100644
index 0000000000..105827c7da
--- /dev/null
+++ b/client/src/lib/universeMarkdownFilename.js
@@ -0,0 +1,15 @@
+/**
+ * Build the client-side filename for a Universe Markdown world-bible export.
+ *
+ * This mirrors the server's `universeMarkdownFilename` contract so a file
+ * saved by the browser has the same safe name as the response attachment.
+ */
+
+export const slugifyUniverseName = (name) => String(name ?? '')
+ .normalize('NFKD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '') || 'universe';
+
+export const universeMarkdownFilename = (name) => `${slugifyUniverseName(name)}.md`;
diff --git a/client/src/lib/universeMarkdownFilename.test.js b/client/src/lib/universeMarkdownFilename.test.js
new file mode 100644
index 0000000000..5e05a20596
--- /dev/null
+++ b/client/src/lib/universeMarkdownFilename.test.js
@@ -0,0 +1,11 @@
+import { describe, expect, it } from 'vitest';
+import { slugifyUniverseName, universeMarkdownFilename } from './universeMarkdownFilename.js';
+
+describe('universeMarkdownFilename', () => {
+ it('matches the server-safe filename contract', () => {
+ expect(slugifyUniverseName('The Bright World / V2!')).toBe('the-bright-world-v2');
+ expect(slugifyUniverseName('Café')).toBe('cafe');
+ expect(universeMarkdownFilename('The Bright World')).toBe('the-bright-world.md');
+ expect(universeMarkdownFilename('!!!')).toBe('universe.md');
+ });
+});
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index fe4bfc1353..740e1b5d1b 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -37,10 +37,17 @@ const trackUniverseWrite = (universeId, promise) => {
return promise;
};
-export const waitForUniverseWrites = async (universeId) => {
+export const waitForUniverseWrites = async (universeId, { timeoutMs = 15000 } = {}) => {
+ const deadline = Date.now() + timeoutMs;
while (pendingUniverseWrites.get(universeId)?.size) {
- await Promise.allSettled([...pendingUniverseWrites.get(universeId)]);
+ const remainingMs = deadline - Date.now();
+ if (remainingMs <= 0) return false;
+ const writes = [...pendingUniverseWrites.get(universeId)];
+ const settled = Promise.allSettled(writes).then(() => true);
+ const timeout = new Promise((resolve) => setTimeout(() => resolve(false), remainingMs));
+ if (!(await Promise.race([settled, timeout]))) return false;
}
+ return true;
};
// `options` lets a caller that owns its own error toast pass `{ silent: true }`
@@ -310,29 +317,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 = {}) =>
- trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/extract-canon`, {
+ 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 = {}) =>
- trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/refine`, {
+ 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 = {}) =>
- trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/expand`, {
+ 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
@@ -348,11 +355,11 @@ export const fetchReferenceSheetVariants = (options = {}) =>
export const renderCharacterReferenceSheet = (universeId, entryId, {
variant, overridePrompt, overrideNegativePrompt, modelId,
} = {}, options = {}) =>
- trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/render-reference-sheet`, {
+ 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 }`.
@@ -367,11 +374,11 @@ export const deleteCharacterReferenceSheet = (universeId, entryId, { variant, ..
// 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 = {}) =>
- trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/characters/differentiate-cast`, {
+ 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,
@@ -432,18 +439,18 @@ export const setUniverseVariationsLockAll = (universeId, { locked, category = nu
export const promoteVariationToCanon = (universeId, {
category, label, targetKind, providerId, model,
} = {}, options = {}) =>
- trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/promote-variation`, {
+ 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 = {}) =>
- trackUniverseWrite(universeId, request(`/universe-builder/${encodeURIComponent(universeId)}/auto-sort`, {
+ request(`/universe-builder/${encodeURIComponent(universeId)}/auto-sort`, {
method: 'POST',
body: JSON.stringify({ providerId, model }),
...options,
- }));
+ });
diff --git a/client/src/services/apiUniverseBuilder.test.js b/client/src/services/apiUniverseBuilder.test.js
new file mode 100644
index 0000000000..3a7a1d33df
--- /dev/null
+++ b/client/src/services/apiUniverseBuilder.test.js
@@ -0,0 +1,56 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { request } = vi.hoisted(() => ({ request: vi.fn() }));
+vi.mock('./apiCore.js', () => ({ request }));
+
+import { updateUniverse, waitForUniverseWrites } from './apiUniverseBuilder.js';
+
+const deferred = () => {
+ let resolve;
+ let reject;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+};
+
+describe('Universe Builder write tracking', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('waits for a tracked write to settle before resolving', async () => {
+ const pending = deferred();
+ request.mockReturnValueOnce(pending.promise);
+ const write = updateUniverse('u-1', { name: 'Example World' });
+ let waited = false;
+ const wait = waitForUniverseWrites('u-1').then((ready) => {
+ waited = true;
+ return ready;
+ });
+
+ await Promise.resolve();
+ expect(waited).toBe(false);
+ pending.resolve({ id: 'u-1' });
+ await expect(write).resolves.toEqual({ id: 'u-1' });
+ await expect(wait).resolves.toBe(true);
+ expect(waited).toBe(true);
+ });
+
+ it('clears rejected writes so a later export is not left waiting forever', async () => {
+ const pending = deferred();
+ request.mockReturnValueOnce(pending.promise);
+ const write = updateUniverse('u-1', { name: 'Example World' });
+ const wait = waitForUniverseWrites('u-1');
+ pending.reject(new Error('write failed'));
+
+ await expect(write).rejects.toThrow('write failed');
+ await expect(wait).resolves.toBe(true);
+ await expect(waitForUniverseWrites('u-1')).resolves.toBe(true);
+ });
+
+ it('resolves immediately when no universe id is supplied', async () => {
+ await expect(waitForUniverseWrites()).resolves.toBe(true);
+ });
+});
diff --git a/server/lib/universeMarkdown.js b/server/lib/universeMarkdown.js
index 3dcd97cc63..1c436e1fc1 100644
--- a/server/lib/universeMarkdown.js
+++ b/server/lib/universeMarkdown.js
@@ -49,8 +49,6 @@ const compareNames = (left, right) => {
return rawA < rawB ? -1 : rawA > rawB ? 1 : 0;
};
-const asTrimmedText = (value) => (typeof value === 'string' ? value.trim() : '');
-
const hasContent = (value) => {
if (value === null || value === undefined) return false;
if (typeof value === 'string') return Boolean(value.trim());
@@ -67,7 +65,7 @@ const formatFieldLabel = (key) => String(key)
const formatInlineValue = (value) => {
if (value === null || value === undefined) return '';
- if (typeof value === 'string') return value.trim();
+ if (typeof value === 'string') return value.trim().replace(/\s*[\r\n]+\s*/g, ' ');
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
if (Array.isArray(value)) {
return value.map(formatInlineValue).filter(Boolean).join(', ');
@@ -112,7 +110,7 @@ const renderEntry = (kind, entry, fallback) => {
if (!rendered) continue;
lines.push(`**${formatFieldLabel(key)}:** ${rendered}`);
}
- return lines.join('\n');
+ return lines.join('\n\n');
};
const renderCanonSection = (key, title, record) => {
@@ -135,8 +133,8 @@ const renderCategory = (name, category) => {
continue;
}
if (!variation || typeof variation !== 'object') continue;
- const label = asTrimmedText(variation.label || variation.name);
- const prompt = asTrimmedText(variation.prompt || variation.description);
+ const label = formatInlineValue(variation.label || variation.name);
+ const prompt = formatInlineValue(variation.prompt || variation.description);
if (!label && !prompt) continue;
if (label && prompt) lines.push(`- **${label}** — ${prompt}`);
else lines.push(`- ${label || prompt}`);
@@ -154,7 +152,7 @@ const renderCategories = (record) => {
};
const listValues = (value) => (Array.isArray(value) ? value : [])
- .map((item) => (typeof item === 'string' ? item.trim() : ''))
+ .map((item) => formatInlineValue(item))
.filter(Boolean);
const renderInfluences = (record) => {
@@ -170,14 +168,14 @@ const renderInfluences = (record) => {
const filenamesFor = (item) => [
...(Array.isArray(item?.imageRefs) ? item.imageRefs : []),
...(typeof item?.filename === 'string' ? [item.filename] : []),
-].map((filename) => filename.trim()).filter(Boolean);
+].map((filename) => formatInlineValue(filename)).filter(Boolean);
const renderNamedFileList = (title, values, nameKeys) => {
if (!Array.isArray(values) || values.length === 0) return '';
const lines = values.map((item) => {
if (typeof item === 'string') return item.trim();
if (!item || typeof item !== 'object') return '';
- const name = nameKeys.map((key) => asTrimmedText(item[key])).find(Boolean) || '';
+ const name = nameKeys.map((key) => formatInlineValue(item[key])).find(Boolean) || '';
const filenames = filenamesFor(item);
return [name, ...filenames].filter(Boolean).join(' — ');
}).filter(Boolean);
@@ -213,7 +211,7 @@ export function universeToMarkdown(record) {
const source = record && typeof record === 'object' ? record : {};
const sections = [`# ${headingText(source.name, 'Untitled Universe')}`];
const prose = ['logline', 'premise', 'styleNotes']
- .map((key) => asTrimmedText(source[key]))
+ .map((key) => formatInlineValue(source[key]))
.filter(Boolean);
if (prose.length) sections.push(prose.join('\n\n'));
diff --git a/server/lib/universeMarkdown.test.js b/server/lib/universeMarkdown.test.js
index 22dc29416e..3ed5e48f1a 100644
--- a/server/lib/universeMarkdown.test.js
+++ b/server/lib/universeMarkdown.test.js
@@ -23,6 +23,7 @@ describe('universeToMarkdown', () => {
expect(markdown).toContain('# The Bright World');
expect(markdown).toContain('A world beneath two suns.\n\nEvery map changes when the second sun rises.');
expect(markdown).toContain('## Characters\n\n### Mira');
+ expect(markdown).toContain('### Mira\n\n**Role:** Cartographer');
expect(markdown).toContain('**Physical Description:** Patient and precise.');
expect(markdown).toContain('## Places\n\n### The Archive');
expect(markdown).toContain('## Objects\n\n### Sun Compass');
@@ -81,6 +82,18 @@ describe('universeToMarkdown', () => {
expect(first).not.toContain('prop-old');
expect(first).not.toContain('2020-01-01');
});
+
+ it('keeps multiline values inside their Markdown field', () => {
+ const markdown = universeToMarkdown({
+ name: 'Safe World',
+ logline: 'A world\n## Not a heading',
+ characters: [{ name: 'Aster', notes: 'a note\n## Not a heading' }],
+ });
+
+ expect(markdown).toContain('A world ## Not a heading');
+ expect(markdown).toContain('**Notes:** a note ## Not a heading');
+ expect(markdown).not.toMatch(/^## Not a heading$/m);
+ });
});
describe('universe markdown filenames', () => {