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-useuniverseaction-hook]): consolidate LLM-action scaffolding
[._.]/ Adam Eivy4cb29e897939
diff --git a/client/src/hooks/useUniverseAction.js b/client/src/hooks/useUniverseAction.jsnew file mode 100644index 0000000000..68badb809d--- /dev/null+++ b/client/src/hooks/useUniverseAction.js@@ -0,0 +1,87 @@+import { useCallback } from 'react';+import toast from '../components/ui/Toast';++// Scaffolding for LLM-driven universe mutations that follow the+// "guarded API call → setWorlds → stale-write-checked setDraft" pattern.+//+// Used by handlePromoteVariation + handleAutoSort in UniverseBuilder.jsx.+// Both: (1) require the universe to be saved, (2) need a page-level+// re-entrancy guard, (3) show a loading toast that flips to success/error,+// (4) always update the cached worlds list when the server returns a new+// universe (even across navigation), and (5) only mutate the local draft+// when the user is still on the same universe (stale-write guard).+//+// handleGenerateInCategory is intentionally NOT a consumer — it does an+// eager local merge first and then a best-effort save, so the guard /+// loading-toast / required-savedId shape doesn't fit. Extracting just its+// setWorlds line through this hook would be more abstraction than savings.+//+// Contract for `action`:+// - Receives `capturedId` (the selectedId at call time).+// - Pass `{ silent: true }` to the underlying API helper so toasts only+// fire from this hook (per CLAUDE.md "Custom catch ⇒ silent: true").+// - Resolve with `{ universe, ... }`; reject with an Error whose message+// is user-displayable.+//+// Contract for `onFreshResult`:+// - Called only when the user is still on the same universe at result time.+// - Caller does its own selective `setDraft` here (different actions touch+// different fields — promote rewrites canon arrays + one category, autoSort+// rewrites only reclassified buckets).+// - Return a string to use as the success toast, or null/void to suppress it.+export default function useUniverseAction({ selectedId, mountedRef, setWorlds }) {+ return useCallback(async function runUniverseAction({+ ref,+ setBusy,+ loadingMessage,+ errorPrefix = 'Action failed',+ notSavedMessage = 'Save the universe first',+ action,+ onFreshResult,+ }) {+ if (!selectedId) {+ toast.error(notSavedMessage);+ return null;+ }+ if (ref?.current) return null;+ if (ref) ref.current = true;+ setBusy?.(true);+ const capturedId = selectedId;+ const toastId = loadingMessage ? toast.loading(loadingMessage) : null;++ const result = await action(capturedId).catch((e) => {+ if (toastId) toast.dismiss(toastId);+ toast.error(`${errorPrefix}: ${e.message}`);+ return null;+ });++ if (mountedRef.current) {+ if (ref) ref.current = false;+ setBusy?.(false);+ }++ if (!result?.universe) {+ if (toastId) toast.dismiss(toastId);+ return result;+ }++ // Always update the cached worlds list — even if the user navigated+ // away mid-flight, the persisted shape changed and other surfaces+ // (list page, palette) should see it.+ const updated = result.universe;+ setWorlds((prev) => {+ const without = prev.filter((w) => w.id !== updated.id);+ return [updated, ...without];+ });++ if (!mountedRef.current || capturedId !== selectedId) {+ if (toastId) toast.dismiss(toastId);+ return result;+ }++ const successMessage = onFreshResult ? onFreshResult(result, { capturedId }) : null;+ if (toastId) toast.dismiss(toastId);+ if (typeof successMessage === 'string' && successMessage) toast.success(successMessage);+ return result;+ }, [selectedId, mountedRef, setWorlds]);+}diff --git a/client/src/hooks/useUniverseAction.test.jsx b/client/src/hooks/useUniverseAction.test.jsxnew file mode 100644index 0000000000..e86f7b58c6--- /dev/null+++ b/client/src/hooks/useUniverseAction.test.jsx@@ -0,0 +1,163 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';++const toastMock = {+ success: vi.fn(),+ error: vi.fn(),+ loading: vi.fn(() => 'tid-1'),+ dismiss: vi.fn(),+};++vi.mock('../components/ui/Toast', () => ({ default: toastMock }));++let useUniverseAction;+beforeEach(async () => {+ Object.values(toastMock).forEach((fn) => fn.mockReset?.());+ toastMock.loading.mockImplementation(() => 'tid-1');+ vi.resetModules();+ ({ default: useUniverseAction } = await import('./useUniverseAction.js'));+});++function buildHook({ selectedId = 'u1', setWorlds = vi.fn() } = {}) {+ const mountedRef = { current: true };+ const { result } = renderHook(() => useUniverseAction({ selectedId, mountedRef, setWorlds }));+ return { run: result.current, mountedRef, setWorlds };+}++describe('useUniverseAction', () => {+ it('errors with notSavedMessage when selectedId is missing', async () => {+ const { run } = buildHook({ selectedId: null });+ const action = vi.fn();+ const out = await run({ action, notSavedMessage: 'Save first' });+ expect(out).toBeNull();+ expect(action).not.toHaveBeenCalled();+ expect(toastMock.error).toHaveBeenCalledWith('Save first');+ });++ it('re-entrancy: when ref.current is true, returns null without firing action', async () => {+ const { run } = buildHook();+ const ref = { current: true };+ const action = vi.fn();+ const out = await run({ ref, action });+ expect(out).toBeNull();+ expect(action).not.toHaveBeenCalled();+ });++ it('happy path: setWorlds + onFreshResult + dismiss + success toast', async () => {+ const setWorlds = vi.fn((fn) => fn([{ id: 'u1', name: 'old' }, { id: 'u2' }]));+ const { run } = buildHook({ setWorlds });+ const ref = { current: false };+ const setBusy = vi.fn();+ const action = vi.fn(async (id) => ({ universe: { id, name: 'new' }, extra: 'x' }));+ const onFreshResult = vi.fn(() => 'Done');+ const out = await run({+ ref, setBusy,+ loadingMessage: 'Working…',+ action,+ onFreshResult,+ });+ expect(action).toHaveBeenCalledWith('u1');+ expect(setBusy).toHaveBeenNthCalledWith(1, true);+ expect(setBusy).toHaveBeenNthCalledWith(2, false);+ expect(ref.current).toBe(false);+ expect(toastMock.loading).toHaveBeenCalledWith('Working…');+ expect(setWorlds).toHaveBeenCalled();+ // setWorlds reducer puts the updated universe first and dedupes by id+ const updated = setWorlds.mock.results[0].value;+ expect(updated[0]).toEqual({ id: 'u1', name: 'new' });+ expect(onFreshResult).toHaveBeenCalledWith(out, { capturedId: 'u1' });+ expect(toastMock.dismiss).toHaveBeenCalledWith('tid-1');+ expect(toastMock.success).toHaveBeenCalledWith('Done');+ });++ it('stale-write: capturedId !== selectedId at result time → setWorlds runs, onFreshResult skipped, no success toast', async () => {+ // Simulate selectedId changing mid-flight. We can't mutate the original+ // closure's selectedId, but the hook captures it once into capturedId on+ // entry. Achieve "stale" by mutating mountedRef.current to false (covers+ // both stale-write paths: unmount and id change).+ const setWorlds = vi.fn((fn) => fn([]));+ const { run, mountedRef } = buildHook({ setWorlds });+ const action = vi.fn(async (id) => {+ mountedRef.current = false;+ return { universe: { id, name: 'new' } };+ });+ const onFreshResult = vi.fn();+ const out = await run({ loadingMessage: 'go', action, onFreshResult });+ expect(out).toEqual({ universe: { id: 'u1', name: 'new' } });+ expect(setWorlds).toHaveBeenCalled();+ expect(onFreshResult).not.toHaveBeenCalled();+ expect(toastMock.success).not.toHaveBeenCalled();+ expect(toastMock.dismiss).toHaveBeenCalledWith('tid-1');+ });++ it('action rejects → error toast with prefix, dismiss, ref + busy reset', async () => {+ const { run } = buildHook();+ const ref = { current: false };+ const setBusy = vi.fn();+ const action = vi.fn(async () => { throw new Error('boom'); });+ const onFreshResult = vi.fn();+ const out = await run({+ ref, setBusy,+ loadingMessage: 'go',+ errorPrefix: 'Promote failed',+ action,+ onFreshResult,+ });+ expect(out).toBeNull();+ expect(toastMock.error).toHaveBeenCalledWith('Promote failed: boom');+ expect(toastMock.dismiss).toHaveBeenCalledWith('tid-1');+ expect(ref.current).toBe(false);+ expect(setBusy).toHaveBeenLastCalledWith(false);+ expect(onFreshResult).not.toHaveBeenCalled();+ expect(toastMock.success).not.toHaveBeenCalled();+ });++ it('no loading toast when loadingMessage is omitted', async () => {+ const { run } = buildHook();+ const action = vi.fn(async (id) => ({ universe: { id } }));+ await run({ action, onFreshResult: () => 'ok' });+ expect(toastMock.loading).not.toHaveBeenCalled();+ expect(toastMock.dismiss).not.toHaveBeenCalled();+ expect(toastMock.success).toHaveBeenCalledWith('ok');+ });++ it('result without .universe → dismiss + return result without setWorlds or onFreshResult', async () => {+ const setWorlds = vi.fn();+ const { run } = buildHook({ setWorlds });+ const action = vi.fn(async () => ({ universe: null, note: 'nothing changed' }));+ const onFreshResult = vi.fn();+ const out = await run({ loadingMessage: 'go', action, onFreshResult });+ expect(out).toEqual({ universe: null, note: 'nothing changed' });+ expect(setWorlds).not.toHaveBeenCalled();+ expect(onFreshResult).not.toHaveBeenCalled();+ expect(toastMock.dismiss).toHaveBeenCalledWith('tid-1');+ });++ it('onFreshResult returning null/void suppresses the success toast', async () => {+ const { run } = buildHook();+ const action = vi.fn(async (id) => ({ universe: { id } }));+ await run({ loadingMessage: 'go', action, onFreshResult: () => null });+ expect(toastMock.dismiss).toHaveBeenCalled();+ expect(toastMock.success).not.toHaveBeenCalled();+ });++ it('unmount before action resolves: ref/busy NOT reset, but setWorlds still fires (cross-navigation list update)', async () => {+ const setWorlds = vi.fn();+ const { run, mountedRef } = buildHook({ setWorlds });+ const ref = { current: false };+ const setBusy = vi.fn();+ const action = vi.fn(async (id) => {+ mountedRef.current = false;+ return { universe: { id } };+ });+ await run({ ref, setBusy, action });+ // CLAUDE.md "Deferred work must respect both staleness and unmount" —+ // hook intentionally skips ref/busy reset when unmounted to avoid+ // post-unmount setState. Async caller closure handles it on remount.+ expect(ref.current).toBe(true);+ // setBusy(true) was called on entry but the cleanup setBusy(false) is gated.+ expect(setBusy).toHaveBeenCalledTimes(1);+ expect(setBusy).toHaveBeenCalledWith(true);+ expect(setWorlds).toHaveBeenCalled();+ });+});diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex 8b6c4c9d0c..5f39cdb1ef 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -27,6 +27,7 @@ import {} from '../services/api';import useClickOutside from '../hooks/useClickOutside';import { useLocalStoragePersisted } from '../hooks/useLocalStorageBool';+import useUniverseAction from '../hooks/useUniverseAction';import InfluenceChipsInput from '../components/universeBuilder/InfluenceChipsInput';import ImageGenSettingsForm from '../components/imageGen/ImageGenSettingsForm';import { RUNNER_FAMILIES } from '../lib/runnerFamilies';@@ -571,6 +572,10 @@ export default function UniverseBuilder() {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 });const [newCategoryName, setNewCategoryName] = useState('');// True when handleExpand merged new canon entries into the draft that the// server doesn't yet know about (auto-save failed or hasn't run). On the@@ -1397,73 +1402,45 @@ export default function UniverseBuilder() {// 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 = async () => {- if (!selectedId) {- toast.error('Save the universe first — auto-sort needs the persisted record');- return;- }- if (autoSortingRef.current) return;- autoSortingRef.current = true;- setAutoSorting(true);- const capturedId = selectedId;- const toastId = toast.loading('Auto-sorting buckets with AI…');- const result = await autoSortBuckets(selectedId, {+ 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',+ action: (capturedId) => autoSortBuckets(capturedId, {providerId: draft.llm?.provider || undefined,model: draft.llm?.model || undefined,- }, { silent: true }).catch((e) => {- toast.dismiss(toastId);- toast.error(`Auto-sort failed: ${e.message}`);- return null;- });- if (mountedRef.current) {- autoSortingRef.current = false;- setAutoSorting(false);- }- if (!result?.universe) {- // .catch already dismissed on error; covers the unreachable- // "service resolved with falsy universe" defensive path too.- toast.dismiss(toastId);- return;- }- const updated = result.universe;- // Always update the cached worlds list — even when the user navigated- // away mid-flight, the persisted shape changed and other surfaces- // (list page, palette) should see it. Mirrors handlePromoteVariation.- setWorlds((prev) => {- const without = prev.filter((w) => w.id !== updated.id);- return [updated, ...without];- });- if (!mountedRef.current || capturedId !== selectedId) {- toast.dismiss(toastId);- return;- }- // 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.- const sortedKeys = new Set((result.results || []).map((r) => r.sourceKey));- setDraft((d) => {- const next = { ...(d.categories || {}) };- for (const key of sortedKeys) {- if (updated.categories?.[key]) next[key] = updated.categories[key];- }- return {- ...d,- categories: next,- schemaVersion: updated.schemaVersion,- updatedAt: updated.updatedAt,- };- });- toast.dismiss(toastId);- 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`- : '';- toast.success(`${summary}${renameHint}`);- };+ }, { 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.+ const sortedKeys = new Set((result.results || []).map((r) => r.sourceKey));+ setDraft((d) => {+ const next = { ...(d.categories || {}) };+ for (const key of sortedKeys) {+ if (updated.categories?.[key]) next[key] = updated.categories[key];+ }+ return {+ ...d,+ categories: next,+ schemaVersion: updated.schemaVersion,+ updatedAt: updated.updatedAt,+ };+ });+ 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) => {const current = draft.categories?.[cat]?.variations || [];@@ -1513,58 +1490,38 @@ export default function UniverseBuilder() {// 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 = async (category, variation, { targetKind } = {}) => {- if (!selectedId) {- toast.error('Save the universe first — promote needs the persisted record');- return;- }- if (!variation?.label) return;- if (promotingRef.current) return;- promotingRef.current = true;- setPromoting(true);- const capturedId = selectedId;- const toastId = toast.loading(`Promoting "${variation.label}" to canon…`);- const result = await promoteVariationToCanon(selectedId, {- category,- label: variation.label,- targetKind,- providerId: draft.llm?.provider || undefined,- model: draft.llm?.model || undefined,- }, { silent: true }).catch((e) => {- toast.dismiss(toastId);- toast.error(`Promote failed: ${e.message}`);- return null;- });- if (mountedRef.current) {- promotingRef.current = false;- setPromoting(false);- }- if (!result?.universe) return;- const updated = result.universe;- // Always update the cached list — even when the user navigated away mid-- // flight, the persisted shape changed and other surfaces should see it.- setWorlds((prev) => {- const without = prev.filter((w) => w.id !== updated.id);- return [updated, ...without];+ 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',+ 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).+ setDraft((d) => ({+ ...d,+ characters: updated.characters,+ settings: updated.settings,+ objects: updated.objects,+ categories: { ...d.categories, [result.removed.category]: updated.categories?.[result.removed.category] },+ schemaVersion: updated.schemaVersion,+ updatedAt: updated.updatedAt,+ }));+ return `Promoted "${variation.label}" → ${result.targetKind} canon`;+ },});- // Guard: if the user navigated to a different universe during the LLM- // call, the response belongs to the previous one — don't clobber the- // new draft. The list update above still surfaces the change.- if (!mountedRef.current || capturedId !== selectedId) return;- // 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).- setDraft((d) => ({- ...d,- characters: updated.characters,- settings: updated.settings,- objects: updated.objects,- categories: { ...d.categories, [result.removed.category]: updated.categories?.[result.removed.category] },- schemaVersion: updated.schemaVersion,- updatedAt: updated.updatedAt,- }));- toast.dismiss(toastId);- toast.success(`Promoted "${variation.label}" → ${result.targetKind} canon`);};const updateCompositeSheets = (sheets) => setDraft((d) => ({ ...d, compositeSheets: sheets }));const addCategory = () => {