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([extract-use-universe-load-hook]): extract useUniverse load hook

[._.]/ Adam Eivyd21590b1a758
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsx
index 6fa4f251b7..b8ff973b4a 100644
--- a/client/src/components/pipeline/stages/NounsStage.jsx
+++ b/client/src/components/pipeline/stages/NounsStage.jsx
@@ -20,7 +20,7 @@ import {
} from 'lucide-react';
import toast from '../../ui/Toast';
import {
- getUniverse, updateUniverse,
+ updateUniverse,
refineUniverseCharacter,
getUniverseSeriesNames,
} from '../../../services/apiUniverseBuilder';
@@ -35,6 +35,7 @@ import { composeStyledPrompt } from '../../../lib/composeStyledPrompt';
import { composeCleanPlatePrompt } from '../../../lib/cleanPlatePrompt';
import { universeStylePreset } from '../../../lib/universeStylePreset';
import useMounted from '../../../hooks/useMounted';
+import useUniverse from '../../../hooks/useUniverse';
import usePreviewRoute from '../../../hooks/usePreviewRoute';
import CanonCard from '../CanonCard';
import MediaPreview from '../../media/MediaPreview';
@@ -80,7 +81,10 @@ export default function NounsStage({ issue, series, onStageUpdate }) {
const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);
const [imageModels, setImageModels] = useState([]);
const [sysSettings, setSysSettings] = useState(null);
- const [universe, setUniverse] = useState(null);
+ // Linked universe — reference renders inherit its stylePrompt + negativePrompt
+ // so ref images stay visually coherent with the comic-page renderer. `setUniverse`
+ // applies optimistic updates after canon patches / refines / extracts.
+ const [universe, setUniverse] = useUniverse(series?.universeId);
// Per-entry in-flight render: { [entryId]: jobId }. NounCard subscribes to
// job progress and surfaces MediaJobThumb until completion — the entry's
// imageRefs[] is only PATCHed onto the series when the job actually
@@ -142,20 +146,6 @@ export default function NounsStage({ issue, series, onStageUpdate }) {
return () => { cancelled = true; };
}, [mountedRef]);
- // Fetch the linked universe so reference renders inherit the same
- // stylePrompt + negativePrompt the comic-page renderer uses. Codex can't
- // accept reference images, so a consistent aesthetic is the only knob
- // keeping ref images and comic pages visually coherent.
- useEffect(() => {
- if (!series?.universeId) { setUniverse(null); return; }
- let cancelled = false;
- getUniverse(series.universeId).then((w) => {
- if (cancelled || !mountedRef.current) return;
- setUniverse(w || null);
- }).catch(() => { if (mountedRef.current) setUniverse(null); });
- return () => { cancelled = true; };
- }, [series?.universeId, mountedRef]);
-
// Sibling-series name lookup for the canon-card "from <series>" chip.
// The current series is in `series.name`; everything else (including the
// entries that surface in the "Other series canon" details panel) needs the
@@ -250,7 +240,7 @@ export default function NounsStage({ issue, series, onStageUpdate }) {
if (result.universe) setUniverse(result.universe);
const summary = result.rationale || (result.changes?.[0] ? result.changes[0] : 'description rewritten');
toast.success(`Refined description — ${summary.slice(0, 140)}`);
- }, [universe, series, refiningCharacterId, mountedRef]);
+ }, [universe, setUniverse, series, refiningCharacterId, mountedRef]);
const handleExtract = async () => {
if (!universe || !proseReady) return;
@@ -379,7 +369,7 @@ export default function NounsStage({ issue, series, onStageUpdate }) {
const updated = await updateUniverse(universe.id, { [kindKey]: list })
.catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });
if (updated && mountedRef.current) setUniverse(updated);
- }, [universe, mountedRef]);
+ }, [universe, setUniverse, mountedRef]);
// Inline-edit channel for canon fields the user picks directly (today:
// setting intExt + timeOfDay chips). Optimistic — UI updates before the
@@ -394,7 +384,7 @@ export default function NounsStage({ issue, series, onStageUpdate }) {
const updated = await updateUniverse(universe.id, { [kindKey]: list })
.catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });
if (updated && mountedRef.current) setUniverse(updated);
- }, [universe, mountedRef]);
+ }, [universe, setUniverse, mountedRef]);
const handleRefFailed = useCallback((entryId, errMsg) => {
setRenderingJobs((prev) => {
diff --git a/client/src/components/pipeline/stages/StoryboardsStage.jsx b/client/src/components/pipeline/stages/StoryboardsStage.jsx
index e4e062c398..d17bd96b77 100644
--- a/client/src/components/pipeline/stages/StoryboardsStage.jsx
+++ b/client/src/components/pipeline/stages/StoryboardsStage.jsx
@@ -16,7 +16,7 @@
* extractor against the corresponding text stage and replace the list.
*/
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { Plus, Trash2, Sparkles, Loader2, Wand2, Film, WandSparkles, Shirt } from 'lucide-react';
import toast from '../../ui/Toast';
import {
@@ -26,9 +26,8 @@ import {
refinePipelineSceneImagePrompt,
updatePipelineIssue,
extractPipelineStoryboardScenes,
- getUniverse,
} from '../../../services/api';
-import useMounted from '../../../hooks/useMounted';
+import useUniverse from '../../../hooks/useUniverse';
import { matchCharactersInText } from '../../../lib/scenePrompt';
import MediaJobThumb from '../MediaJobThumb';
import { genConfigToImageOptions, genConfigToRefineOptions } from './VisualGenSettings';
@@ -54,21 +53,14 @@ export default function StoryboardsStage({ issue, series, onStageUpdate, actions
if (armTimerRef.current) clearTimeout(armTimerRef.current);
}, []);
- // Canon characters (with wardrobes) live on the linked universe — load them
- // once so each scene can offer a per-character wardrobe picker. Only
- // characters that own at least one wardrobe are pickable.
- const mountedRef = useMounted();
- const [wardrobeChars, setWardrobeChars] = useState([]);
- useEffect(() => {
- if (!series?.universeId) { setWardrobeChars([]); return undefined; }
- let cancelled = false;
- getUniverse(series.universeId).then((w) => {
- if (cancelled || !mountedRef.current) return;
- const chars = Array.isArray(w?.characters) ? w.characters : [];
- setWardrobeChars(chars.filter((c) => Array.isArray(c?.wardrobes) && c.wardrobes.length > 0));
- }).catch(() => { if (mountedRef.current) setWardrobeChars([]); });
- return () => { cancelled = true; };
- }, [series?.universeId, mountedRef]);
+ // Canon characters (with wardrobes) live on the linked universe — load it
+ // and derive the pickable set so each scene can offer a per-character
+ // wardrobe picker. Only characters that own at least one wardrobe are pickable.
+ const [universe] = useUniverse(series?.universeId);
+ const wardrobeChars = useMemo(() => {
+ const chars = Array.isArray(universe?.characters) ? universe.characters : [];
+ return chars.filter((c) => Array.isArray(c?.wardrobes) && c.wardrobes.length > 0);
+ }, [universe]);
const teleplayReady = !!(issue.stages?.teleplay?.output || '').trim();
const proseReady = !!(issue.stages?.prose?.output || '').trim();
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index bb503044ee..d6097fea7d 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -109,6 +109,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. |
| `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |
| `useSyncIntegrity` | Fetches per-kind integrity diff from every eligible online peer; reduces to worst-case `statusById` + `byPeer` breakdown maps. | Federated media sync integrity UI — badges, drawers, peer breakdown. |
+| `useUniverse` | Loads the universe record for a `universeId` with mount/cancel guards; returns `[universe, setUniverse, loading, error]` (setter exposed for optimistic post-mutation updates). | Any surface that loads a linked universe (pipeline stages, etc.) — use instead of re-rolling the getUniverse-on-mount effect. |
| `useUniverseAction` | LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |
| `useUniverseNav` | `goToWorld(id)` → navigate to `/universes/:id`, preserve `location.search`. | Any Universe Builder caller that needs to switch worlds via URL. |
| `useVoiceUiSync` | Keeps voice server's UI index in sync with current page. | Wire once at root for voice agent support. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 0858e1e1d2..7683bb725c 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -25,6 +25,7 @@ export { default as usePreviewRoute } from './usePreviewRoute.js';
export { default as useProviderModels } from './useProviderModels.js';
export { default as useRowDraft } from './useRowDraft.js';
export { default as useTheme } from './useTheme.js';
+export { default as useUniverse } from './useUniverse.js';
export { default as useUniverseAction } from './useUniverseAction.js';
// === Mixed (both default and named) — surface both ===
diff --git a/client/src/hooks/useUniverse.js b/client/src/hooks/useUniverse.js
new file mode 100644
index 0000000000..9a687d174f
--- /dev/null
+++ b/client/src/hooks/useUniverse.js
@@ -0,0 +1,49 @@
+import { useEffect, useState } from 'react';
+import { getUniverse } from '../services/apiUniverseBuilder.js';
+import useMounted from './useMounted.js';
+
+// Load the universe record for a given id (typically `series.universeId`).
+// Collapses the `useMounted` + `let cancelled` + `getUniverse(id).then/.catch`
+// effect that pipeline stages were each hand-rolling. Returns a tuple shaped
+// like `useState` plus load metadata:
+// [universe, setUniverse, loading, error]
+// - universe: the record, or null when unloaded / not-found / failed.
+// - setUniverse: the underlying state setter, so callers can apply optimistic
+// updates after a mutation (canon patch, refine, extract) without a refetch.
+// A change to `universeId` re-fetches and overwrites, but same-id optimistic
+// writes are preserved (the effect only re-runs when the id changes).
+// - loading: true while a fetch is in flight.
+// - error: the rejection reason, or null. Errors still toast via the shared
+// request helper (behavior unchanged); this just exposes the reason too.
+// A falsy `universeId` clears state to [null, …, false, null] without fetching.
+export default function useUniverse(universeId) {
+ const mountedRef = useMounted();
+ const [universe, setUniverse] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(null);
+
+ useEffect(() => {
+ if (!universeId) {
+ setUniverse(null);
+ setLoading(false);
+ setError(null);
+ return undefined;
+ }
+ let cancelled = false;
+ setLoading(true);
+ setError(null);
+ getUniverse(universeId).then((w) => {
+ if (cancelled || !mountedRef.current) return;
+ setUniverse(w || null);
+ setLoading(false);
+ }).catch((err) => {
+ if (cancelled || !mountedRef.current) return;
+ setUniverse(null);
+ setError(err);
+ setLoading(false);
+ });
+ return () => { cancelled = true; };
+ }, [universeId, mountedRef]);
+
+ return [universe, setUniverse, loading, error];
+}
diff --git a/client/src/hooks/useUniverse.test.jsx b/client/src/hooks/useUniverse.test.jsx
new file mode 100644
index 0000000000..2319ddcbf8
--- /dev/null
+++ b/client/src/hooks/useUniverse.test.jsx
@@ -0,0 +1,81 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act, waitFor } from '@testing-library/react';
+
+// ---------------------------------------------------------------------------
+// Module mocks — must be at the top level before any imports.
+// ---------------------------------------------------------------------------
+vi.mock('../services/apiUniverseBuilder.js', () => ({
+ getUniverse: vi.fn(),
+}));
+
+let useUniverse;
+let getUniverse;
+
+beforeEach(async () => {
+ vi.resetModules();
+ ({ getUniverse } = await import('../services/apiUniverseBuilder.js'));
+ useUniverse = (await import('./useUniverse.js')).default;
+ getUniverse.mockReset();
+});
+
+const UNIVERSE = { id: 'u1', name: 'Alpha', characters: [{ name: 'A', wardrobes: [{}] }] };
+
+describe('useUniverse', () => {
+ it('does not fetch and stays cleared for a falsy id', () => {
+ const { result } = renderHook(() => useUniverse(null));
+ const [universe, setUniverse, loading, error] = result.current;
+ expect(universe).toBeNull();
+ expect(typeof setUniverse).toBe('function');
+ expect(loading).toBe(false);
+ expect(error).toBeNull();
+ expect(getUniverse).not.toHaveBeenCalled();
+ });
+
+ it('loads the universe and clears loading on success', async () => {
+ getUniverse.mockResolvedValue(UNIVERSE);
+ const { result } = renderHook(() => useUniverse('u1'));
+ // loading flips true synchronously once the effect runs
+ await waitFor(() => expect(result.current[0]).toEqual(UNIVERSE));
+ expect(getUniverse).toHaveBeenCalledWith('u1');
+ expect(result.current[2]).toBe(false); // loading
+ expect(result.current[3]).toBeNull(); // error
+ });
+
+ it('exposes the rejection reason and nulls the record on failure', async () => {
+ const err = new Error('boom');
+ getUniverse.mockRejectedValue(err);
+ const { result } = renderHook(() => useUniverse('u1'));
+ await waitFor(() => expect(result.current[3]).toBe(err));
+ expect(result.current[0]).toBeNull();
+ expect(result.current[2]).toBe(false); // loading
+ });
+
+ it('exposes setUniverse for optimistic post-mutation updates', async () => {
+ getUniverse.mockResolvedValue(UNIVERSE);
+ const { result } = renderHook(() => useUniverse('u1'));
+ await waitFor(() => expect(result.current[0]).toEqual(UNIVERSE));
+ const patched = { ...UNIVERSE, name: 'Beta' };
+ act(() => { result.current[1](patched); });
+ expect(result.current[0]).toEqual(patched);
+ });
+
+ it('re-fetches when the id changes', async () => {
+ getUniverse.mockResolvedValue(UNIVERSE);
+ const { result, rerender } = renderHook(({ id }) => useUniverse(id), {
+ initialProps: { id: 'u1' },
+ });
+ await waitFor(() => expect(result.current[0]).toEqual(UNIVERSE));
+ const other = { id: 'u2', name: 'Gamma' };
+ getUniverse.mockResolvedValue(other);
+ rerender({ id: 'u2' });
+ await waitFor(() => expect(result.current[0]).toEqual(other));
+ expect(getUniverse).toHaveBeenCalledWith('u2');
+ });
+
+ it('treats a null payload as not-found', async () => {
+ getUniverse.mockResolvedValue(null);
+ const { result } = renderHook(() => useUniverse('u1'));
+ await waitFor(() => expect(result.current[2]).toBe(false));
+ expect(result.current[0]).toBeNull();
+ });
+});