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
refactor: extract expand/refine hooks from UniverseBuilderPage (#3391)
[._.]/ Adam Eivy9f2ff0fbaf94
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8ca3e62abd..00742336b8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -25,6 +25,7 @@- **A canon trunk's wiring travels by context, not a 36-prop bag.** `KindSection` inside `UniverseCanonSection.jsx` took every handler, spinner id, and job map as an individually threaded prop, so adding one capability meant editing the call site, the signature, and its defaults. The bag is now published once per kind through `KindSectionContext` and read where it's used, and the inline add-entry mini-form moved to `CanonAddEntryForm.jsx` as a controlled leaf — the typed draft stays with the section, because the toolbar "Add" button is a toggle and collapsing the form has to bring the draft back on reopen. `KindSection` takes zero props; behavior, markup, and classes are unchanged. (#3388)- **The Round editor is a composition, not a 1,326-line component.** `RoundEditor.jsx` drops to 164 lines of page shell — header chrome plus the pick between its three body surfaces — with the state split into four named hooks (`useRoundViewParams` for the `?mode`/`?stack`/`?analyze` views, `useRoundDraft` for load/save/refresh-from-template/AI-merge and the `baseDirty` saved-state gate, `useRoundRows` for section/layer/reference/proposed-part edits, `useRoundPartners` for the quodlibet pick list) and the markup into five components in `client/src/components/songs/` (`RoundEditForm`, `RoundReadView`, `RoundSheetMusic`, `RoundReferenceCard`, `RoundBuiltInBanner`). The draft rules the page, hooks, and form all shared — server caps, the temp-id contract, the tempo band, and the save patch builder — are now `client/src/lib/roundDraft.js`, and the host-anchored TikTok embed-id helpers moved to `utils/urlNormalize.js` with tests. Behavior is unchanged. (#3389)- `agentLifecycle.js` imported `getAgent` aliased as `getAgentRecord`, shadowing the real transcript-free reader that was split out in #3368 for exactly this purpose. Both call sites read only `.status`/`.metadata`, but the alias made them hydrate the record: reading and line-splitting a completed run's whole `output.txt` (megabytes on a long TUI run) and potentially rewriting `metadata.json` via `repairCodexTaskSummary`. Now imports the real `getAgentRecord`, read once and shared.+- **Universe Builder is a composition shell again.** `UniverseBuilderPage.jsx` drops from 778 to ~530 lines: the URL-backed tab/sub-bucket state (plus the two effects that strip a `?tab=`/`?bucket=` the current categories no longer support) is now `useUniverseTabs`, and generate-in-bucket / promote-to-canon / auto-sort — each with its own in-flight gate and stale-snapshot merge rules — is now `useUniverseBucketActions`. The render-completion handler that was copy-pasted between the trunk tabs and the Other tab is one shared callback. Expand/refine already lived in `useUniverseExpand`, so it stayed put. Behavior, markup, and API calls are unchanged; `useUniverseTabs` picks up 11 tests. (#3391)## Better audit 2026-08-03 (UX, City scene, game/music/writing focus) — PRs #3401–#3404diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsxindex 5f9191b9eb..41d490fe42 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx@@ -1,32 +1,28 @@/*** Universe Builder editor composition (Media Gen → Universe Builder).*- * Stateful record, expansion, gallery, and render concerns live in hooks.- * Tab-specific presentation lives in the sibling panel modules.+ * Stateful record, expansion, gallery, render, URL tab/bucket, and bucket-+ * mutation concerns live in hooks (useUniverseDraft / useUniverseExpand /+ * useUniverseGallery / useUniverseRender / useUniverseTabs /+ * useUniverseBucketActions). Tab-specific presentation lives in the sibling+ * panel modules.*/-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Link, useLocation, useParams, useSearchParams } from 'react-router';+import { useCallback, useEffect, useMemo } from 'react';+import { Link, useLocation, useParams } from 'react-router';import {ArrowLeft, BookOpen, FolderTree, ImagePlus, Layers, Loader2,MapPin, Package, Plus, Save, Trash2, Users,} from 'lucide-react';-import toast from '../ui/Toast';import InlineConfirmRow from '../ui/InlineConfirmRow';-import {- WORLD_CATEGORY_KEY_MAX,- autoSortBuckets,- ensureInfluences,- generateCategoryVariations,- promoteVariationToCanon,- updateUniverse,-} from '../../services/api';-import useUniverseAction from '../../hooks/useUniverseAction';+import { WORLD_CATEGORY_KEY_MAX } from '../../services/api';+import useUniverseBucketActions from '../../hooks/useUniverseBucketActions';import useUniverseDraft from '../../hooks/useUniverseDraft';import useUniverseExpand from '../../hooks/useUniverseExpand';import useUniverseGallery from '../../hooks/useUniverseGallery';import { useUniverseNav } from '../../hooks/useUniverseNav';import useUniverseRender from '../../hooks/useUniverseRender';+import useUniverseTabs from '../../hooks/useUniverseTabs';import EntityCombobox from '../EntityCombobox';import MediaPreview from '../media/MediaPreview';import OriginBadge from '../sharing/OriginBadge';@@ -38,11 +34,8 @@ import RenderTab from './RenderTab';import UniverseBibleTab from './UniverseBibleTab';import { OtherTab, TrunkView } from './UniverseTrunkPanels';import { capImageRefs } from '../../lib/bibleLimits';-import { upsertByIdPrepend } from '../../lib/upsertByIdPrepend';-import { mergeVariations } from '../../lib/universeBuilderExpand';import { totalVariationCount } from '../../lib/universeBuilderCounts';import {- BUCKET_CANON,TAB_BIBLE,TAB_CAST,TAB_COMPOSITES,@@ -50,11 +43,8 @@ import {TAB_OTHER,TAB_PLACES,TAB_RENDER,- TRUNK_BY_ID,TRUNK_TABS,getCategoryKeys,- groupBucketsByKind,- humanizeCategory,} from '../../lib/universeBuilderShared';export { CategoryEditor } from './UniverseCategoryEditor';@@ -202,20 +192,27 @@ export default function UniverseBuilder() {clearPendingCanonAdditions,setRenderOpts,});- // Page-level in-flight gate for the promote action. Ref + state pair so- // the disable check stays synchronous (ref) while still triggering renders- // (state). Promote writes to `universe[bibleField]` and `categories[key]`- // as wholesale replacements from a stale snapshot — letting two run in- // parallel against the same universe would let the second clobber the- // first's canon append.- const [promoting, setPromoting] = useState(false);- const promotingRef = useRef(false);- const [autoSorting, setAutoSorting] = useState(false);- const autoSortingRef = useRef(false);- // Scaffolding shared by handlePromoteVariation + handleAutoSort:- // selectedId guard, ref re-entrancy, capturedId + toast lifecycle,- // setWorlds always-update, stale-write detection. See the hook header.- const runUniverseAction = useUniverseAction({ selectedId, mountedRef, setWorlds });+ // URL-driven tab + bucket state (per CLAUDE.md "Linkable routes for all+ // views"), including the self-healing effects that strip a `?tab=`/`?bucket=`+ // the current categories no longer support.+ const {+ activeBucket, activeTab, bucketsByKind, hasOtherBuckets, setBucket, setTab,+ } = useUniverseTabs(draft.categories);+ // Generate-in-bucket / promote-to-canon / auto-sort, each with its own+ // in-flight gate so two writes built from the same stale snapshot can't+ // clobber each other's canon append.+ const {+ autoSorting, handleAutoSort, handleGenerateInCategory, handlePromoteVariation, promoting,+ } = useUniverseBucketActions({+ selectedId,+ draft,+ draftRef,+ setDraft,+ setWorlds,+ markDraftSaved,+ mountedRef,+ flushDraftIfDirty,+ });// Page-level lightbox + gallery-metadata concern. A single MediaPreview at// this level covers EVERY thumb on the page: variations, composite sheets,@@ -251,225 +248,35 @@ export default function UniverseBuilder() {return () => clearTimeout(t);}, [location.hash, selectedId, draft.id]);- // Auto-sort with AI — one LLM call classifies every Other-tab bucket into- // characters/places/objects. Each bucket's `kind` is reassigned via a- // single atomic patch server-side so the universe ends up consistent or- // unchanged. Renames the LLM suggests are surfaced in the toast but not- // auto-applied (the user can rename manually if they want it).- const handleAutoSort = () => runUniverseAction({- ref: autoSortingRef,- setBusy: setAutoSorting,- loadingMessage: 'Auto-sorting buckets with AI…',- errorPrefix: 'Auto-sort failed',- notSavedMessage: 'Save the universe first — auto-sort needs the persisted record',- preflight: flushDraftIfDirty,- action: (capturedId) => autoSortBuckets(capturedId, {- providerId: draft.llm?.provider || undefined,- model: draft.llm?.model || undefined,- }, { silent: true }),- onFreshResult: (result) => {- const updated = result.universe;- // Merge only the reclassified buckets into the draft — wholesale-- // replacing `categories` with the server snapshot would discard any- // user edits to OTHER buckets made while the LLM call was in flight.- // Compute the merge from draftRef so React strict-mode's double-fire- // of state updaters doesn't double-stringify the dirty baseline.- const sortedKeys = new Set((result.results || []).map((r) => r.sourceKey));- const baseDraft = draftRef.current || draft;- const nextCategories = { ...(baseDraft.categories || {}) };- for (const key of sortedKeys) {- if (updated.categories?.[key]) nextCategories[key] = updated.categories[key];- }- const newDraft = {- ...baseDraft,- categories: nextCategories,- schemaVersion: updated.schemaVersion,- updatedAt: updated.updatedAt,- };- setDraft(newDraft);- markDraftSaved(newDraft);- const sortedCount = result.results?.length || 0;- const renames = (result.results || []).filter((r) => r.suggestedKey);- const summary = sortedCount- ? `Sorted ${sortedCount} bucket${sortedCount === 1 ? '' : 's'} into canon trunks`- : 'No buckets were classified';- const renameHint = renames.length- ? ` — ${renames.length} rename suggestion${renames.length === 1 ? '' : 's'} available`- : '';- return `${summary}${renameHint}`;- },- });-- const handleGenerateInCategory = async (cat, count) => {- // Match the runUniverseAction-based handlers — flush dirty draft so the- // subsequent auto-save can't clobber unrelated fields with a stale spread.- const flushed = await flushDraftIfDirty();- if (!flushed) return;- const current = draft.categories?.[cat]?.variations || [];- const existingLabels = current.map((v) => v.label).filter(Boolean);- const result = await generateCategoryVariations({- category: cat,- count,- existingLabels,- influences: ensureInfluences(draft.influences),- logline: draft.logline || '',- premise: draft.premise || '',- styleNotes: draft.styleNotes || '',- providerId: draft.llm?.provider || undefined,- model: draft.llm?.model || undefined,- }, { silent: true }).catch((e) => { toast.error(`Generate failed: ${e.message}`); return null; });- if (!result) return;- const fresh = Array.isArray(result.variations) ? result.variations : [];- const merged = mergeVariations(current, fresh);- const additionCount = merged.length - current.length;- if (additionCount === 0) {- toast.error('LLM returned no new variations — try again or adjust the universe context');- return;- }- const nextDraft = {- ...draft,- // Preserve the bucket's `kind` (mirror of updateCategory's behavior;- // see comment there). Generate-more is the second write path that- // could silently reset the trunk to default/other.- categories: { ...draft.categories, [cat]: { ...(draft.categories?.[cat] || {}), variations: merged } },- };- setDraft(nextDraft);- if (selectedId && nextDraft.name?.trim()) {- const updated = await updateUniverse(selectedId, { categories: nextDraft.categories }, { silent: true })- .catch((e) => { toast.error(`Auto-save after generate failed: ${e.message}`); return null; });- if (updated) {- setWorlds((prev) => upsertByIdPrepend(prev, updated));- markDraftSaved(nextDraft);- toast.success(`Added ${additionCount} variation${additionCount === 1 ? '' : 's'} to ${humanizeCategory(cat)} — saved`);- return;- }- }- toast.success(`Added ${additionCount} variation${additionCount === 1 ? '' : 's'} to ${humanizeCategory(cat)} — review then Save`);- };- // Requires `selectedId` — the server action reads the persisted record,- // so an unsaved draft can't be promoted from. The page-level `promoting`- // gate prevents two promotes (across buckets or trunks) from racing each- // other to stale-snapshot writes against the same universe.- const handlePromoteVariation = (category, variation, { targetKind } = {}) => {- if (!variation?.label) return Promise.resolve(null);- return runUniverseAction({- ref: promotingRef,- setBusy: setPromoting,- loadingMessage: `Promoting "${variation.label}" to canon…`,- errorPrefix: 'Promote failed',- notSavedMessage: 'Save the universe first — promote needs the persisted record',- preflight: flushDraftIfDirty,- action: (capturedId) => promoteVariationToCanon(capturedId, {- category,- label: variation.label,- targetKind,- providerId: draft.llm?.provider || undefined,- model: draft.llm?.model || undefined,- }, { silent: true }),- onFreshResult: (result) => {- const updated = result.universe;- // Selective merge: only the canon array + the affected category bucket- // changed server-side. Preserve every other draft field (the user may- // have typed into logline/premise/influences during the LLM call).- // Compute outside setDraft so strict-mode's double-invoke doesn't- // re-stringify the dirty baseline.- const baseDraft = draftRef.current || draft;- const newDraft = {- ...baseDraft,- characters: updated.characters,- places: updated.places,- objects: updated.objects,- categories: { ...baseDraft.categories, [result.removed.category]: updated.categories?.[result.removed.category] },- schemaVersion: updated.schemaVersion,- updatedAt: updated.updatedAt,- };- setDraft(newDraft);- markDraftSaved(newDraft);- return `Promoted "${variation.label}" → ${result.targetKind} canon`;- },- });- };const categoryKeys = getCategoryKeys(draft.categories);const totalVariations = totalVariationCount(draft);const totalSheets = draft.compositeSheets?.length || 0;- // URL-driven tab + bucket state (per CLAUDE.md "Linkable routes for all- // views"). `?tab=cast&bucket=heroes` deep-links into a sub-bucket; both fall- // back to bible / "" (All) on first load. We also forward existing params- // (e.g. `?series=` on the embedded Canon section) untouched.- const [searchParams, setSearchParams] = useSearchParams();- const bucketsByKind = useMemo(() => groupBucketsByKind(draft.categories), [draft.categories]);- const hasOtherBuckets = bucketsByKind.other.length > 0;- const requestedTab = searchParams.get('tab');- const isValidTab = (tab) => (- tab === TAB_BIBLE || tab === TAB_CAST || tab === TAB_PLACES || tab === TAB_OBJECTS- || tab === TAB_COMPOSITES || tab === TAB_RENDER- || (tab === TAB_OTHER && hasOtherBuckets)- );- const activeTab = isValidTab(requestedTab) ? requestedTab : TAB_BIBLE;- const activeBucket = searchParams.get('bucket') || '';- const setTab = useCallback((tab, opts = {}) => {- const currentTab = searchParams.get('tab') || TAB_BIBLE;- const isSameTab = tab === currentTab;- const next = new URLSearchParams(searchParams);- if (tab === TAB_BIBLE) next.delete('tab');- else next.set('tab', tab);- // Bucket behavior:- // - explicit `opts.bucket` value (string) → set- // - explicit `opts.bucket: null` → clear (callers that want to drop the- // filter on the same tab pass null intentionally)- // - omitted + same tab → preserve current bucket (re-clicking the- // active tab shouldn't drop the user's chip/canon filter)- // - omitted + tab transition → clear (the old bucket is meaningless on- // the new tab's bucket namespace)- if (opts.bucket === null) next.delete('bucket');- else if (opts.bucket) next.set('bucket', opts.bucket);- else if (!isSameTab) next.delete('bucket');- setSearchParams(next, { replace: !!opts.replace });- }, [searchParams, setSearchParams]);- // Explicit user bucket clicks push a history entry so back/forward actually- // walks tab+bucket navigation (the PR's headline deep-link promise). The- // stale-bucket-cleanup effect below uses `replace: true` directly so an- // implicit URL fix-up doesn't fork the history stack.- const setBucket = useCallback((bucket, opts = {}) => {- const next = new URLSearchParams(searchParams);- if (bucket) next.set('bucket', bucket);- else next.delete('bucket');- setSearchParams(next, { replace: !!opts.replace });- }, [searchParams, setSearchParams]);-- // Drop a stale `?tab=` if it points to an unknown value or `tab=other`- // when the user has emptied the Other bucket bin. Without this, the URL- // and UI disagree: `activeTab` silently falls back to Bible but the param- // stays in the address bar — breaking the deep-link promise and confusing- // back/forward.- useEffect(() => {- if (!requestedTab) return;- if (isValidTab(requestedTab)) return;- const next = new URLSearchParams(searchParams);- next.delete('tab');- setSearchParams(next, { replace: true });- }, [requestedTab, hasOtherBuckets]);-- // Drop a stale `?bucket=` if the bucket no longer exists under the current- // tab (e.g. user deleted the bucket, or auto-sort moved it to another kind).- // `BUCKET_CANON` is a valid pseudo-bucket on every trunk tab — without an- // explicit allow, the chip's `setBucket(BUCKET_CANON)` flashed in the URL- // then immediately got stripped by this effect, hiding the canon-only view.- // Other tab buckets must validate against `bucketsByKind.other`; non-trunk- // non-Other tabs (Bible / Composites / Render) have no valid bucket scope.- useEffect(() => {- if (!activeBucket) return;- const trunk = TRUNK_BY_ID[activeTab];- if (trunk && activeBucket === BUCKET_CANON) return;- const validBuckets = trunk- ? (bucketsByKind[trunk.kind] || [])- : (activeTab === TAB_OTHER ? bucketsByKind.other : []);- if (validBuckets.includes(activeBucket)) return;- const next = new URLSearchParams(searchParams);- next.delete('bucket');- setSearchParams(next, { replace: true });- }, [activeTab, activeBucket, bucketsByKind, searchParams, setSearchParams]);+ // Shared by every bucket grid (trunk tabs + Other). Optimistically append the+ // new filename to the variation's imageRefs[] so the row swaps from spinner →+ // rendered image without a roundtrip. Server already stamped this via the+ // collection hook; the next universe refetch will agree. Then pull the fresh+ // sidecar into galleryByFilename so the lightbox opens with the real+ // prompt/settings rather than label-only metadata.+ const handleEntryJobCompleted = useCallback((entryId, filename, bucket, completedJobId = null) => {+ if (!filename || !bucket) {+ clearPendingForEntry(entryId, completedJobId);+ return;+ }+ setDraft((d) => {+ const cat = d.categories?.[bucket];+ if (!cat?.variations) return d;+ const variations = cat.variations.map((v) => {+ if (v.id !== entryId) return v;+ const refs = Array.isArray(v.imageRefs) ? v.imageRefs : [];+ if (refs.includes(filename)) return v;+ return { ...v, imageRefs: capImageRefs([...refs, filename]) };+ });+ return { ...d, categories: { ...d.categories, [bucket]: { ...cat, variations } } };+ });+ clearPendingForEntry(entryId, completedJobId);+ bumpGalleryRefresh();+ }, [clearPendingForEntry, setDraft, bumpGalleryRefresh]);return (<div className="flex flex-col h-full">@@ -599,32 +406,7 @@ export default function UniverseBuilder() {pendingByEntryId={pendingHeadByEntryId}externalPendingByEntryId={pendingHeadByEntryId}onPendingCleared={clearPendingForEntry}- onJobCompletedForEntry={(entryId, filename, bucket, completedJobId = null) => {- if (!filename || !bucket) {- clearPendingForEntry(entryId, completedJobId);- return;- }- // Optimistically append the new filename to the variation's- // imageRefs[] so the row swaps from spinner → rendered image- // without a roundtrip. Server already stamped this via the- // collection hook; the next universe refetch will agree.- setDraft((d) => {- const cat = d.categories?.[bucket];- if (!cat?.variations) return d;- const variations = cat.variations.map((v) => {- if (v.id !== entryId) return v;- const refs = Array.isArray(v.imageRefs) ? v.imageRefs : [];- if (refs.includes(filename)) return v;- return { ...v, imageRefs: capImageRefs([...refs, filename]) };- });- return { ...d, categories: { ...d.categories, [bucket]: { ...cat, variations } } };- });- clearPendingForEntry(entryId, completedJobId);- // The new sidecar exists now — pull it into galleryByFilename- // so the lightbox opens with the real prompt/settings rather- // than label-only metadata.- bumpGalleryRefresh();- }}+ onJobCompletedForEntry={handleEntryJobCompleted}onBulkRenderTrunk={() => {const selection = Object.fromEntries((bucketsByKind[trunk.kind] || []).map((b) => [b, 'all']),@@ -666,28 +448,7 @@ export default function UniverseBuilder() {autoSorting={autoSorting}pendingByEntryId={pendingHeadByEntryId}onPendingCleared={clearPendingForEntry}- onJobCompletedForEntry={(entryId, filename, bucket, completedJobId = null) => {- if (!filename || !bucket) {- clearPendingForEntry(entryId, completedJobId);- return;- }- setDraft((d) => {- const cat = d.categories?.[bucket];- if (!cat?.variations) return d;- const variations = cat.variations.map((v) => {- if (v.id !== entryId) return v;- const refs = Array.isArray(v.imageRefs) ? v.imageRefs : [];- if (refs.includes(filename)) return v;- return { ...v, imageRefs: capImageRefs([...refs, filename]) };- });- return { ...d, categories: { ...d.categories, [bucket]: { ...cat, variations } } };- });- clearPendingForEntry(entryId, completedJobId);- // Pull the new sidecar into galleryByFilename so the lightbox- // opens with the real prompt/settings (mirrors the Cast/Places- // path's onJobCompletedForEntry above).- bumpGalleryRefresh();- }}+ onJobCompletedForEntry={handleEntryJobCompleted}/>)}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 4a35f2f90a..4240d5f2ba 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -173,10 +173,12 @@ grep -i "what you want to do" client/src/hooks/README.md| `useRenderJobQueue` | Per-entry render-job queue for the Universe Builder — `pendingByEntryId` (entryId → jobId[]), `pendingHeadByEntryId` (first jobId per entry for single-subscription thumbs), `enqueueEntryJobs` (append variation/canon jobs), `clearPendingForEntry` (shift a jobId out, or drop the entry). | Universe Builder render orchestration. Don't re-roll the per-entry pending-jobs reducer. || `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. |+| `useUniverseBucketActions` | The Universe Builder's three bucket-scoped LLM mutations — `handleGenerateInCategory` (eager local merge then best-effort save), `handlePromoteVariation`, `handleAutoSort` (both via `useUniverseAction`) — each with its own ref+state in-flight gate. Returns `{ autoSorting, handleAutoSort, handleGenerateInCategory, handlePromoteVariation, promoting }`. | Universe Builder composition shell; keep the stale-snapshot merge rules out of the page and the trunk/Other panels. || `useUniverseDraft` | Universe Builder editable-record lifecycle: initial catalog/provider/image settings load, selected-universe hydration, create/save/delete, saved-draft dirty baseline, pending-canon addition merge ledger, keyed category mutations, and lock persistence. | Universe Builder composition shell; expansion/refinement and rendering consume this hook's draft contract instead of owning persistence themselves. || `useUniverseExpand` | Universe Builder LLM expansion + holistic refine lifecycle, including lock-preserving request payloads, deletion-wins pending-canon auto-save, provider selection, and refine-panel state. | Universe Builder Bible panel; keep provider calls and canon-aware auto-save out of presentation components. || `useUniverseGallery` | Page-level lightbox + gallery-metadata concern for the Universe Builder. Takes `{ draft, runsLength }`; hydrates a filename→sidecar map (prompt/seed/model), derives `previewItems` across variations, composite sheets, style probes, and canon/character-sheet refs (namespaced-key dedupe), and wires `usePreviewRoute` + `useMediaPreviewActions` + `useMediaAnnotations`. Returns `{ previewItems, preview, setPreview, previewActions, openPreviewByFilename, openVariationPreview, annotations, updateAnnotation, bumpGalleryRefresh }`. | Universe Builder image lightbox — don't re-roll the gallery-sidecar/previewItems derivation. || `useUniverseRender` | Universe Builder batch-render settings, scoped render payload compilation, canon-selection defaults, per-entry job queue, and run-list refresh. Returns the shared `runRender`/`handleRender` action used by the Render tab and inline bucket/canon controls. | Universe Builder composition shell and presentational panels; don't fork render payload semantics per tab. |+| `useUniverseTabs` | `useUniverseTabs(categories)` → `{ activeTab, activeBucket, bucketsByKind, hasOtherBuckets, setTab, setBucket }`. URL-backed (`?tab=&bucket=`) tab + sub-bucket state for the Universe Builder, including the self-healing effects that `replace`-strip a tab/bucket the current categories no longer support. | Universe Builder composition shell — don't re-roll the tab/bucket search-param plumbing or the stale-param cleanup. || `useUniverseNav` | `goToWorld(id)` → navigate to `/universes/:id`, preserve `location.search`. | Any Universe Builder caller that needs to switch worlds via URL. || `useVideoFileSrc` | `useVideoFileSrc(jobId, { enabled })` → `{ src, resolving }`. Resolves a video-history **id** to the file it really points at (`/data/videos/<filename>`) via the history lookup. | Any surface rendering a video by history id where the id is NOT the filename stem — notably a CD `finalVideoId` (the timeline renderer mints `timeline-*.mp4` beside a `randomUUID()` id, so `/data/videos/<id>.mp4` 404s while `<id>.jpg` poster loads). Pass the result to `<ScenePreview src=…>`. Gate autoplay on `resolving`. || `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.jsindex 814b0db706..9e23b8aa52 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -66,11 +66,13 @@ 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';+export { default as useUniverseBucketActions } from './useUniverseBucketActions.js';export { default as useUniverseDraft } from './useUniverseDraft.js';export * from './useUniverseDraft.js';export { default as useUniverseExpand } from './useUniverseExpand.js';export { default as useUniverseGallery } from './useUniverseGallery.js';export { default as useUniverseRender } from './useUniverseRender.js';+export { default as useUniverseTabs } from './useUniverseTabs.js';export { default as useVideoDownload } from './useVideoDownload.js';export { default as useWakeLock } from './useWakeLock.js';export { default as useYoutubeTrackImport } from './useYoutubeTrackImport.js';diff --git a/client/src/hooks/useUniverseBucketActions.js b/client/src/hooks/useUniverseBucketActions.jsnew file mode 100644index 0000000000..0dd27b830b--- /dev/null+++ b/client/src/hooks/useUniverseBucketActions.js@@ -0,0 +1,194 @@+import { useRef, useState } from 'react';+import toast from '../components/ui/Toast';+import {+ autoSortBuckets,+ ensureInfluences,+ generateCategoryVariations,+ promoteVariationToCanon,+ updateUniverse,+} from '../services/api';+import useUniverseAction from './useUniverseAction';+import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';+import { mergeVariations } from '../lib/universeBuilderExpand';+import { humanizeCategory } from '../lib/universeBuilderShared';++/**+ * Owns the Universe Builder's three bucket-scoped LLM mutations: generate more+ * variations inside a bucket, promote a variation into canon, and auto-sort+ * the Other-tab buckets into canon trunks.+ *+ * Promote + auto-sort run through `useUniverseAction` (guard → loading toast →+ * setWorlds → stale-write check); generate keeps its own eager-merge-then-+ * best-effort-save shape, which the scaffolding deliberately doesn't cover.+ *+ * Each action carries a page-level in-flight gate (ref for the synchronous+ * disable check, state to trigger renders) so two writes built from the same+ * stale snapshot can't clobber each other's canon append.+ */+export default function useUniverseBucketActions({+ selectedId,+ draft,+ draftRef,+ setDraft,+ setWorlds,+ markDraftSaved,+ mountedRef,+ flushDraftIfDirty,+}) {+ const [promoting, setPromoting] = useState(false);+ const promotingRef = useRef(false);+ const [autoSorting, setAutoSorting] = useState(false);+ const autoSortingRef = useRef(false);+ // Scaffolding shared by handlePromoteVariation + handleAutoSort:+ // selectedId guard, ref re-entrancy, capturedId + toast lifecycle,+ // setWorlds always-update, stale-write detection. See the hook header.+ const runUniverseAction = useUniverseAction({ selectedId, mountedRef, setWorlds });++ // Auto-sort with AI — one LLM call classifies every Other-tab bucket into+ // characters/places/objects. Each bucket's `kind` is reassigned via a+ // single atomic patch server-side so the universe ends up consistent or+ // unchanged. Renames the LLM suggests are surfaced in the toast but not+ // auto-applied (the user can rename manually if they want it).+ const handleAutoSort = () => runUniverseAction({+ ref: autoSortingRef,+ setBusy: setAutoSorting,+ loadingMessage: 'Auto-sorting buckets with AI…',+ errorPrefix: 'Auto-sort failed',+ notSavedMessage: 'Save the universe first — auto-sort needs the persisted record',+ preflight: flushDraftIfDirty,+ action: (capturedId) => autoSortBuckets(capturedId, {+ providerId: draft.llm?.provider || undefined,+ model: draft.llm?.model || undefined,+ }, { silent: true }),+ onFreshResult: (result) => {+ const updated = result.universe;+ // Merge only the reclassified buckets into the draft — wholesale-+ // replacing `categories` with the server snapshot would discard any+ // user edits to OTHER buckets made while the LLM call was in flight.+ // Compute the merge from draftRef so React strict-mode's double-fire+ // of state updaters doesn't double-stringify the dirty baseline.+ const sortedKeys = new Set((result.results || []).map((r) => r.sourceKey));+ const baseDraft = draftRef.current || draft;+ const nextCategories = { ...(baseDraft.categories || {}) };+ for (const key of sortedKeys) {+ if (updated.categories?.[key]) nextCategories[key] = updated.categories[key];+ }+ const newDraft = {+ ...baseDraft,+ categories: nextCategories,+ schemaVersion: updated.schemaVersion,+ updatedAt: updated.updatedAt,+ };+ setDraft(newDraft);+ markDraftSaved(newDraft);+ const sortedCount = result.results?.length || 0;+ const renames = (result.results || []).filter((r) => r.suggestedKey);+ const summary = sortedCount+ ? `Sorted ${sortedCount} bucket${sortedCount === 1 ? '' : 's'} into canon trunks`+ : 'No buckets were classified';+ const renameHint = renames.length+ ? ` — ${renames.length} rename suggestion${renames.length === 1 ? '' : 's'} available`+ : '';+ return `${summary}${renameHint}`;+ },+ });++ const handleGenerateInCategory = async (cat, count) => {+ // Match the runUniverseAction-based handlers — flush dirty draft so the+ // subsequent auto-save can't clobber unrelated fields with a stale spread.+ const flushed = await flushDraftIfDirty();+ if (!flushed) return;+ const current = draft.categories?.[cat]?.variations || [];+ const existingLabels = current.map((v) => v.label).filter(Boolean);+ const result = await generateCategoryVariations({+ category: cat,+ count,+ existingLabels,+ influences: ensureInfluences(draft.influences),+ logline: draft.logline || '',+ premise: draft.premise || '',+ styleNotes: draft.styleNotes || '',+ providerId: draft.llm?.provider || undefined,+ model: draft.llm?.model || undefined,+ }, { silent: true }).catch((e) => { toast.error(`Generate failed: ${e.message}`); return null; });+ if (!result) return;+ const fresh = Array.isArray(result.variations) ? result.variations : [];+ const merged = mergeVariations(current, fresh);+ const additionCount = merged.length - current.length;+ if (additionCount === 0) {+ toast.error('LLM returned no new variations — try again or adjust the universe context');+ return;+ }+ const nextDraft = {+ ...draft,+ // Preserve the bucket's `kind` (mirror of updateCategory's behavior;+ // see comment there). Generate-more is the second write path that+ // could silently reset the trunk to default/other.+ categories: { ...draft.categories, [cat]: { ...(draft.categories?.[cat] || {}), variations: merged } },+ };+ setDraft(nextDraft);+ if (selectedId && nextDraft.name?.trim()) {+ const updated = await updateUniverse(selectedId, { categories: nextDraft.categories }, { silent: true })+ .catch((e) => { toast.error(`Auto-save after generate failed: ${e.message}`); return null; });+ if (updated) {+ setWorlds((prev) => upsertByIdPrepend(prev, updated));+ markDraftSaved(nextDraft);+ toast.success(`Added ${additionCount} variation${additionCount === 1 ? '' : 's'} to ${humanizeCategory(cat)} — saved`);+ return;+ }+ }+ toast.success(`Added ${additionCount} variation${additionCount === 1 ? '' : 's'} to ${humanizeCategory(cat)} — review then Save`);+ };++ // Requires `selectedId` — the server action reads the persisted record,+ // so an unsaved draft can't be promoted from. The page-level `promoting`+ // gate prevents two promotes (across buckets or trunks) from racing each+ // other to stale-snapshot writes against the same universe.+ const handlePromoteVariation = (category, variation, { targetKind } = {}) => {+ if (!variation?.label) return Promise.resolve(null);+ return runUniverseAction({+ ref: promotingRef,+ setBusy: setPromoting,+ loadingMessage: `Promoting "${variation.label}" to canon…`,+ errorPrefix: 'Promote failed',+ notSavedMessage: 'Save the universe first — promote needs the persisted record',+ preflight: flushDraftIfDirty,+ action: (capturedId) => promoteVariationToCanon(capturedId, {+ category,+ label: variation.label,+ targetKind,+ providerId: draft.llm?.provider || undefined,+ model: draft.llm?.model || undefined,+ }, { silent: true }),+ onFreshResult: (result) => {+ const updated = result.universe;+ // Selective merge: only the canon array + the affected category bucket+ // changed server-side. Preserve every other draft field (the user may+ // have typed into logline/premise/influences during the LLM call).+ // Compute outside setDraft so strict-mode's double-invoke doesn't+ // re-stringify the dirty baseline.+ const baseDraft = draftRef.current || draft;+ const newDraft = {+ ...baseDraft,+ characters: updated.characters,+ places: updated.places,+ objects: updated.objects,+ categories: { ...baseDraft.categories, [result.removed.category]: updated.categories?.[result.removed.category] },+ schemaVersion: updated.schemaVersion,+ updatedAt: updated.updatedAt,+ };+ setDraft(newDraft);+ markDraftSaved(newDraft);+ return `Promoted "${variation.label}" → ${result.targetKind} canon`;+ },+ });+ };++ return {+ autoSorting,+ handleAutoSort,+ handleGenerateInCategory,+ handlePromoteVariation,+ promoting,+ };+}diff --git a/client/src/hooks/useUniverseTabs.js b/client/src/hooks/useUniverseTabs.jsnew file mode 100644index 0000000000..e7954be2a3--- /dev/null+++ b/client/src/hooks/useUniverseTabs.js@@ -0,0 +1,110 @@+import { useCallback, useEffect, useMemo } from 'react';+import { useSearchParams } from 'react-router';+import {+ BUCKET_CANON,+ TAB_BIBLE,+ TAB_CAST,+ TAB_COMPOSITES,+ TAB_OBJECTS,+ TAB_OTHER,+ TAB_PLACES,+ TAB_RENDER,+ TRUNK_BY_ID,+ groupBucketsByKind,+} from '../lib/universeBuilderShared';++/**+ * URL-driven tab + bucket state for the Universe Builder (per CLAUDE.md+ * "Linkable routes for all views"). `?tab=cast&bucket=heroes` deep-links into+ * a sub-bucket; both fall back to bible / "" (All) on first load. Existing+ * params (e.g. `?series=` on the embedded Canon section) are forwarded+ * untouched.+ *+ * Also owns the two self-healing effects that strip a `?tab=`/`?bucket=` the+ * current categories no longer support, so the URL and the rendered view can't+ * disagree.+ */+export default function useUniverseTabs(categories) {+ const [searchParams, setSearchParams] = useSearchParams();+ const bucketsByKind = useMemo(() => groupBucketsByKind(categories), [categories]);+ const hasOtherBuckets = bucketsByKind.other.length > 0;+ const requestedTab = searchParams.get('tab');+ const isValidTab = (tab) => (+ tab === TAB_BIBLE || tab === TAB_CAST || tab === TAB_PLACES || tab === TAB_OBJECTS+ || tab === TAB_COMPOSITES || tab === TAB_RENDER+ || (tab === TAB_OTHER && hasOtherBuckets)+ );+ const activeTab = isValidTab(requestedTab) ? requestedTab : TAB_BIBLE;+ const activeBucket = searchParams.get('bucket') || '';+ const setTab = useCallback((tab, opts = {}) => {+ const currentTab = searchParams.get('tab') || TAB_BIBLE;+ const isSameTab = tab === currentTab;+ const next = new URLSearchParams(searchParams);+ if (tab === TAB_BIBLE) next.delete('tab');+ else next.set('tab', tab);+ // Bucket behavior:+ // - explicit `opts.bucket` value (string) → set+ // - explicit `opts.bucket: null` → clear (callers that want to drop the+ // filter on the same tab pass null intentionally)+ // - omitted + same tab → preserve current bucket (re-clicking the+ // active tab shouldn't drop the user's chip/canon filter)+ // - omitted + tab transition → clear (the old bucket is meaningless on+ // the new tab's bucket namespace)+ if (opts.bucket === null) next.delete('bucket');+ else if (opts.bucket) next.set('bucket', opts.bucket);+ else if (!isSameTab) next.delete('bucket');+ setSearchParams(next, { replace: !!opts.replace });+ }, [searchParams, setSearchParams]);+ // Explicit user bucket clicks push a history entry so back/forward actually+ // walks tab+bucket navigation (the PR's headline deep-link promise). The+ // stale-bucket-cleanup effect below uses `replace: true` directly so an+ // implicit URL fix-up doesn't fork the history stack.+ const setBucket = useCallback((bucket, opts = {}) => {+ const next = new URLSearchParams(searchParams);+ if (bucket) next.set('bucket', bucket);+ else next.delete('bucket');+ setSearchParams(next, { replace: !!opts.replace });+ }, [searchParams, setSearchParams]);++ // Drop a stale `?tab=` if it points to an unknown value or `tab=other`+ // when the user has emptied the Other bucket bin. Without this, the URL+ // and UI disagree: `activeTab` silently falls back to Bible but the param+ // stays in the address bar — breaking the deep-link promise and confusing+ // back/forward.+ useEffect(() => {+ if (!requestedTab) return;+ if (isValidTab(requestedTab)) return;+ const next = new URLSearchParams(searchParams);+ next.delete('tab');+ setSearchParams(next, { replace: true });+ }, [requestedTab, hasOtherBuckets]);++ // Drop a stale `?bucket=` if the bucket no longer exists under the current+ // tab (e.g. user deleted the bucket, or auto-sort moved it to another kind).+ // `BUCKET_CANON` is a valid pseudo-bucket on every trunk tab — without an+ // explicit allow, the chip's `setBucket(BUCKET_CANON)` flashed in the URL+ // then immediately got stripped by this effect, hiding the canon-only view.+ // Other tab buckets must validate against `bucketsByKind.other`; non-trunk+ // non-Other tabs (Bible / Composites / Render) have no valid bucket scope.+ useEffect(() => {+ if (!activeBucket) return;+ const trunk = TRUNK_BY_ID[activeTab];+ if (trunk && activeBucket === BUCKET_CANON) return;+ const validBuckets = trunk+ ? (bucketsByKind[trunk.kind] || [])+ : (activeTab === TAB_OTHER ? bucketsByKind.other : []);+ if (validBuckets.includes(activeBucket)) return;+ const next = new URLSearchParams(searchParams);+ next.delete('bucket');+ setSearchParams(next, { replace: true });+ }, [activeTab, activeBucket, bucketsByKind, searchParams, setSearchParams]);++ return {+ activeBucket,+ activeTab,+ bucketsByKind,+ hasOtherBuckets,+ setBucket,+ setTab,+ };+}diff --git a/client/src/hooks/useUniverseTabs.test.jsx b/client/src/hooks/useUniverseTabs.test.jsxnew file mode 100644index 0000000000..2709b97111--- /dev/null+++ b/client/src/hooks/useUniverseTabs.test.jsx@@ -0,0 +1,112 @@+import { describe, it, expect } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import { MemoryRouter, useLocation } from 'react-router';+import useUniverseTabs from './useUniverseTabs';++// The contract here is URL transitions, so pair the hook with `useLocation`+// and assert on the query string each call produces (mirrors+// useUniverseNav.test.jsx).+const renderTabs = (initial, categories) => {+ const wrapper = ({ children }) => (+ <MemoryRouter initialEntries={[initial]}>{children}</MemoryRouter>+ );+ return renderHook(({ cats }) => ({+ tabs: useUniverseTabs(cats),+ location: useLocation(),+ }), { wrapper, initialProps: { cats: categories } });+};++const CATEGORIES = {+ heroes: { kind: 'characters', variations: [] },+ cities: { kind: 'places', variations: [] },+ factions: { kind: 'other', variations: [] },+};++describe('useUniverseTabs', () => {+ it('defaults to the bible tab with no bucket', () => {+ const { result } = renderTabs('/universes/u-1', CATEGORIES);++ expect(result.current.tabs.activeTab).toBe('bible');+ expect(result.current.tabs.activeBucket).toBe('');+ });++ it('reads the tab + bucket out of the query string', () => {+ const { result } = renderTabs('/universes/u-1?tab=cast&bucket=heroes', CATEGORIES);++ expect(result.current.tabs.activeTab).toBe('cast');+ expect(result.current.tabs.activeBucket).toBe('heroes');+ });++ it('groups buckets by kind and flags the Other bin', () => {+ const { result } = renderTabs('/universes/u-1', CATEGORIES);++ expect(result.current.tabs.bucketsByKind.characters).toEqual(['heroes']);+ expect(result.current.tabs.bucketsByKind.other).toEqual(['factions']);+ expect(result.current.tabs.hasOtherBuckets).toBe(true);+ });++ it('drops ?tab= when switching back to bible and preserves unrelated params', () => {+ const { result } = renderTabs('/universes/u-1?tab=cast&series=s-1', CATEGORIES);++ act(() => result.current.tabs.setTab('bible'));++ expect(result.current.location.search).toBe('?series=s-1');+ });++ it('clears the bucket on a tab transition but preserves it on the same tab', () => {+ const { result } = renderTabs('/universes/u-1?tab=cast&bucket=heroes', CATEGORIES);++ act(() => result.current.tabs.setTab('cast'));+ expect(result.current.tabs.activeBucket).toBe('heroes');++ act(() => result.current.tabs.setTab('places'));+ expect(result.current.tabs.activeBucket).toBe('');+ });++ it('honors an explicit null bucket as a clear on the same tab', () => {+ const { result } = renderTabs('/universes/u-1?tab=cast&bucket=heroes', CATEGORIES);++ act(() => result.current.tabs.setTab('cast', { bucket: null }));++ expect(result.current.tabs.activeBucket).toBe('');+ });++ it('setBucket sets then clears the bucket param', () => {+ const { result } = renderTabs('/universes/u-1?tab=cast', CATEGORIES);++ act(() => result.current.tabs.setBucket('heroes'));+ expect(result.current.tabs.activeBucket).toBe('heroes');++ act(() => result.current.tabs.setBucket(''));+ expect(result.current.location.search).toBe('?tab=cast');+ });++ it('strips an unknown ?tab= from the URL instead of silently falling back', () => {+ const { result } = renderTabs('/universes/u-1?tab=bogus', CATEGORIES);++ expect(result.current.tabs.activeTab).toBe('bible');+ expect(result.current.location.search).toBe('');+ });++ it('strips ?tab=other when there are no Other buckets', () => {+ const { result } = renderTabs('/universes/u-1?tab=other', {+ heroes: { kind: 'characters', variations: [] },+ });++ expect(result.current.tabs.activeTab).toBe('bible');+ expect(result.current.location.search).toBe('');+ });++ it('strips a ?bucket= that does not exist under the active tab', () => {+ const { result } = renderTabs('/universes/u-1?tab=cast&bucket=cities', CATEGORIES);++ expect(result.current.location.search).toBe('?tab=cast');+ expect(result.current.tabs.activeBucket).toBe('');+ });++ it('keeps the canon pseudo-bucket on a trunk tab', () => {+ const { result } = renderTabs('/universes/u-1?tab=cast&bucket=canon', CATEGORIES);++ expect(result.current.tabs.activeBucket).toBe('canon');+ });+});