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([issue-718]): extract shared useCanonPatch hook

[._.]/ Adam Eivy31c33cbecb9c
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsx
index b8ff973b4a..e1326b035c 100644
--- a/client/src/components/pipeline/stages/NounsStage.jsx
+++ b/client/src/components/pipeline/stages/NounsStage.jsx
@@ -36,6 +36,7 @@ import { composeCleanPlatePrompt } from '../../../lib/cleanPlatePrompt';
import { universeStylePreset } from '../../../lib/universeStylePreset';
import useMounted from '../../../hooks/useMounted';
import useUniverse from '../../../hooks/useUniverse';
+import { useCanonPatch } from '../../../hooks/useCanonPatch';
import usePreviewRoute from '../../../hooks/usePreviewRoute';
import CanonCard from '../CanonCard';
import MediaPreview from '../../media/MediaPreview';
@@ -374,17 +375,9 @@ export default function NounsStage({ issue, series, onStageUpdate }) {
// Inline-edit channel for canon fields the user picks directly (today:
// setting intExt + timeOfDay chips). Optimistic — UI updates before the
// server roundtrip so chip clicks feel instant.
- const handlePatchEntry = useCallback(async (kind, entryId, patch) => {
- if (!universe || !patch || typeof patch !== 'object') return;
- const kindKey = kind.key;
- const list = (universe[kindKey] || []).map((e) =>
- e.id === entryId ? { ...e, ...patch } : e,
- );
- setUniverse((prev) => prev ? { ...prev, [kindKey]: list } : prev);
- 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, setUniverse, mountedRef]);
+ const { patchEntry: handlePatchEntry } = useCanonPatch({
+ universe, universeId: series?.universeId, apply: setUniverse, mountedRef,
+ });
const handleRefFailed = useCallback((entryId, errMsg) => {
setRenderingJobs((prev) => {
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index 183b369faf..fd62e2b552 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -34,6 +34,7 @@ import { composeStyledPrompt, composeCanonStyledPrompt } from '../../lib/compose
import { composeCleanPlatePrompt } from '../../lib/cleanPlatePrompt';
import { useAsyncAction } from '../../hooks/useAsyncAction';
import useMounted from '../../hooks/useMounted';
+import { useCanonPatch } from '../../hooks/useCanonPatch';
import CanonCard from '../pipeline/CanonCard';
import { pipelineImageCfgToRenderOpts } from '../../lib/pipelineImageDefaults';
import { universeStylePreset } from '../../lib/universeStylePreset';
@@ -593,18 +594,9 @@ export default function UniverseCanonSection({
// (setting intExt + timeOfDay chips, primaryImageRef pinning, wardrobe
// edits). Optimistic — UI updates before the server roundtrip so chip
// clicks feel instant.
- const handlePatchEntry = useCallback(async (kind, entryId, patch) => {
- if (!universe || !patch || typeof patch !== 'object') return;
- const capturedId = universeId;
- const kindKey = kind.key;
- const list = (universe[kindKey] || []).map((e) =>
- e.id === entryId ? { ...e, ...patch } : e
- );
- onUniverseChange({ ...universe, [kindKey]: list });
- const updated = await updateUniverse(universeId, { [kindKey]: list })
- .catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });
- if (updated && mountedRef.current && currentUniverseIdRef.current === capturedId) onUniverseChange(updated);
- }, [universe, universeId, onUniverseChange, mountedRef]);
+ const { patchEntry: handlePatchEntry } = useCanonPatch({
+ universe, universeId, apply: onUniverseChange, mountedRef,
+ });
if (!universe) return null;
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 3c28a58f74..3b9683bb91 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -106,6 +106,7 @@ grep -i "what you want to do" client/src/hooks/README.md
|---|---|---|
| `useAppDeploy` | Stream `deploy.sh` output via Socket.IO. | App deployment surfaces only. |
| `useAppOperation` | Socket-based app ops (update, standardize) with step tracking. | App operations UI. |
+| `useCanonPatch` | Optimistic canon-entry patch: rebuild the kind list with one entry mutated, apply locally, PATCH the universe, re-apply the server copy (with a captured-id staleness guard). `apply` is `setUniverse` or `onUniverseChange`. | Inline canon-field edits on a universe (UniverseCanonSection, NounsStage). Don't re-roll the optimistic-then-confirm dance. |
| `useCityAudio` | CyberCity ambient audio. | CyberCity only. |
| `useCityData` | CyberCity environment data + physics. | CyberCity only. |
| `useCitySettings` | CyberCity quality presets + persistence. | CyberCity only. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index d6299ca1d7..da56d36492 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -92,6 +92,7 @@ export * from './useLocalStorageBool.js';
// === Domain: City / Voice / Mortality / Universe / Apps / Sessions ===
export * from './useAppDeploy.js';
export * from './useAppOperation.js';
+export * from './useCanonPatch.js';
export * from './useCityData.js';
export * from './useDeathClock.js';
export * from './usePostSession.js';
diff --git a/client/src/hooks/useCanonPatch.js b/client/src/hooks/useCanonPatch.js
new file mode 100644
index 0000000000..33d1884c6b
--- /dev/null
+++ b/client/src/hooks/useCanonPatch.js
@@ -0,0 +1,43 @@
+import { useCallback, useEffect, useRef } from 'react';
+import toast from '../components/ui/Toast';
+import { updateUniverse } from '../services/apiUniverseBuilder';
+
+// Shared optimistic canon-entry patch handler. `UniverseCanonSection` and
+// `NounsStage` had ~95%-identical inline handlers: rebuild the kind list with
+// one entry mutated, apply it to local state immediately so the edit feels
+// instant, PATCH the universe, then re-apply the server's authoritative copy.
+//
+// `apply` is the optimistic-state setter — `setUniverse` (when the caller owns
+// `universe` via `useUniverse`) or `onUniverseChange` (when a parent owns the
+// draft). It's called with the full next universe object.
+//
+// Staleness guard: the captured `universeId` is compared against the live id on
+// completion, so a slow PATCH from a previous universe can't repopulate state
+// after the caller navigates to a different world.
+//
+// Usage:
+// const { patchEntry } = useCanonPatch({ universe, universeId, apply: setUniverse, mountedRef });
+// <Card onPatchEntry={(entryId, patch) => patchEntry(kind, entryId, patch)} />
+export function useCanonPatch({ universe, universeId, apply, mountedRef }) {
+ const currentUniverseIdRef = useRef(universeId);
+ useEffect(() => { currentUniverseIdRef.current = universeId; }, [universeId]);
+
+ const patchEntry = useCallback(async (kind, entryId, patch) => {
+ if (!universe || !patch || typeof patch !== 'object') return;
+ const capturedId = universeId;
+ const kindKey = kind.key;
+ const list = (universe[kindKey] || []).map((e) =>
+ e.id === entryId ? { ...e, ...patch } : e
+ );
+ apply({ ...universe, [kindKey]: list });
+ const updated = await updateUniverse(universeId, { [kindKey]: list })
+ .catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });
+ if (updated && mountedRef.current && currentUniverseIdRef.current === capturedId) {
+ apply(updated);
+ }
+ }, [universe, universeId, apply, mountedRef]);
+
+ return { patchEntry };
+}
+
+export default useCanonPatch;
diff --git a/client/src/hooks/useCanonPatch.test.jsx b/client/src/hooks/useCanonPatch.test.jsx
new file mode 100644
index 0000000000..2f0184cf8e
--- /dev/null
+++ b/client/src/hooks/useCanonPatch.test.jsx
@@ -0,0 +1,117 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act, waitFor } from '@testing-library/react';
+
+const updateUniverse = vi.fn();
+vi.mock('../services/apiUniverseBuilder', () => ({
+ updateUniverse: (...args) => updateUniverse(...args),
+}));
+const toastError = vi.fn();
+vi.mock('../components/ui/Toast', () => ({ default: { error: (...a) => toastError(...a) } }));
+
+import { useCanonPatch } from './useCanonPatch.js';
+
+const KIND = { key: 'characters' };
+const baseUniverse = {
+ id: 'u1',
+ characters: [
+ { id: 'c1', name: 'Alice', intExt: 'INT' },
+ { id: 'c2', name: 'Bob' },
+ ],
+};
+
+function setup(overrides = {}) {
+ const apply = vi.fn();
+ const mountedRef = { current: true };
+ const props = {
+ universe: baseUniverse,
+ universeId: 'u1',
+ apply,
+ mountedRef,
+ ...overrides,
+ };
+ const { result } = renderHook(() => useCanonPatch(props));
+ return { result, apply, mountedRef };
+}
+
+beforeEach(() => {
+ updateUniverse.mockReset();
+ toastError.mockReset();
+});
+
+describe('useCanonPatch', () => {
+ it('optimistically applies the patched kind list, then re-applies the server copy', async () => {
+ const serverCopy = { id: 'u1', characters: [{ id: 'c1', name: 'Alice', intExt: 'EXT' }] };
+ updateUniverse.mockResolvedValue(serverCopy);
+ const { result, apply } = setup();
+
+ await act(async () => {
+ await result.current.patchEntry(KIND, 'c1', { intExt: 'EXT' });
+ });
+
+ // Optimistic apply mutates only the targeted entry.
+ expect(apply).toHaveBeenNthCalledWith(1, {
+ ...baseUniverse,
+ characters: [
+ { id: 'c1', name: 'Alice', intExt: 'EXT' },
+ { id: 'c2', name: 'Bob' },
+ ],
+ });
+ // PATCH sends the full kind list.
+ expect(updateUniverse).toHaveBeenCalledWith('u1', {
+ characters: [
+ { id: 'c1', name: 'Alice', intExt: 'EXT' },
+ { id: 'c2', name: 'Bob' },
+ ],
+ });
+ // Server response re-applied.
+ expect(apply).toHaveBeenNthCalledWith(2, serverCopy);
+ });
+
+ it('no-ops on a missing universe or a non-object patch', async () => {
+ const { result, apply } = setup({ universe: null });
+ await act(async () => {
+ await result.current.patchEntry(KIND, 'c1', { intExt: 'EXT' });
+ });
+ expect(apply).not.toHaveBeenCalled();
+ expect(updateUniverse).not.toHaveBeenCalled();
+ });
+
+ it('toasts and skips the re-apply when the PATCH fails', async () => {
+ updateUniverse.mockRejectedValue(new Error('boom'));
+ const { result, apply } = setup();
+ await act(async () => {
+ await result.current.patchEntry(KIND, 'c1', { intExt: 'EXT' });
+ });
+ expect(apply).toHaveBeenCalledTimes(1); // optimistic only
+ expect(toastError).toHaveBeenCalledWith('Save failed: boom');
+ });
+
+ it('does not re-apply the server copy after unmount', async () => {
+ let resolveUpdate;
+ updateUniverse.mockReturnValue(new Promise((res) => { resolveUpdate = res; }));
+ const { result, apply, mountedRef } = setup();
+ let pending;
+ act(() => { pending = result.current.patchEntry(KIND, 'c1', { intExt: 'EXT' }); });
+ expect(apply).toHaveBeenCalledTimes(1); // optimistic apply fired
+ mountedRef.current = false;
+ await act(async () => { resolveUpdate({ id: 'u1', characters: [] }); await pending; });
+ expect(apply).toHaveBeenCalledTimes(1); // server copy NOT re-applied
+ });
+
+ it('does not re-apply when the universe id changed mid-flight', async () => {
+ let resolveUpdate;
+ updateUniverse.mockReturnValue(new Promise((res) => { resolveUpdate = res; }));
+ const apply = vi.fn();
+ const mountedRef = { current: true };
+ const props = { universe: baseUniverse, universeId: 'u1', apply, mountedRef };
+ const { result, rerender } = renderHook((p) => useCanonPatch(p), { initialProps: props });
+
+ let pending;
+ act(() => { pending = result.current.patchEntry(KIND, 'c1', { intExt: 'EXT' }); });
+ // Navigate to a different world before the PATCH settles.
+ rerender({ ...props, universeId: 'u2' });
+ await waitFor(() => {}); // flush the id-sync effect
+ await act(async () => { resolveUpdate({ id: 'u1', characters: [] }); await pending; });
+ expect(apply).toHaveBeenCalledTimes(1); // stale server copy dropped
+ });
+});