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: memoize StoryboardPanel so WorkEditor keystrokes stop re-rendering the sidebar (#3387)

[._.]/ Adam Eivy30b90003ca21
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7f5e0acf68..fb23a622c9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -20,6 +20,7 @@
- `handleAgentCompletion` bails when the persisted record is already terminal — the same check its post-restart branch has always had — so any double-completion path is a no-op rather than a clobbering re-finalize.
- **The Music Video page is a composition, not a 1,492-line component.** Its seven co-located concerns are now six named hooks in `client/src/hooks/` (`useMusicVideoYoutubeImport`, `useMusicVideoMidiJob`, `useMusicVideoRenderJob`, `useMusicVideoModelSettings`, `useMusicVideoSceneMedia`, `useMusicVideoManualTempo`) plus seven presentational components in `client/src/components/musicVideo/`, leaving `MusicVideo.jsx` at 529 lines of project/scene CRUD and page shell. Behavior is unchanged — same polling flows, settings persistence, and render lifecycle. (#3386)
- **`/api/universe-builder` is a directory of sub-routers, not one 987-line file.** The 36 endpoints split along the service seams they already delegated to — `expand.js`, `vision.js`, `styleReferences.js`, `referenceSheets.js`, `merge.js`, `crud.js`, `render.js`, `canon.js` — behind a thin `routes/universeBuilder/index.js`, with the zod fragments and image resolvers more than one router composes moved to `shared.js`. Mount order is the load-bearing part and is documented at the mount: every sub-router owning a single-segment static path (`/expand`, `/duplicates`, `/merge*`, …) mounts ahead of `crud.js`, whose `GET /:id` would otherwise swallow it. Verified by resolving 520 method+URL combinations against the old and new routers and confirming every one lands on the same handler. (#3392)
+- **Typing in the Writers Room no longer re-renders the storyboard sidebar.** `WorkEditor`'s body textarea shared a render with `<StoryboardPanel>` — a heavy tree of bibles, boards, scene cards, and image config with zero dependency on the prose — so every keystroke re-rendered the whole sidebar. The panel is now memoized and every prop it receives is referentially stable across keystrokes (the run/style handlers are `useCallback`s and `onJumpToScene` reads the body through a ref instead of a dep), leaving one re-render on the clean → dirty flip and none after. Three hooks came out with it — `useLiveSuggest`, `useSidebarResize`, `useTokenPopover` — plus `WorkEditorVersions` / `WorkEditorVoicePanel` as their own files. Behavior is unchanged. (#3387)
- `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.
## Better audit 2026-08-03 (UX, City scene, game/music/writing focus) — PRs #3401–#3404
diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsx
index 9c0fb999fd..f68ce9c858 100644
--- a/client/src/components/writers-room/StoryboardPanel.jsx
+++ b/client/src/components/writers-room/StoryboardPanel.jsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
import {
Clapperboard, Loader2, Users, MapPin as MapPinIcon,
@@ -43,7 +43,13 @@ const RUN_LABEL = {
format: 'Format pass',
};
-export default function StoryboardPanel({
+// Memoized (#3387): this is a heavy sibling of the WorkEditor prose textarea
+// with no dependency on the body text, so a per-keystroke `setBody` in the
+// parent would otherwise re-render the whole storyboard tree. The memo boundary
+// only pays off while every prop stays referentially stable across keystrokes —
+// WorkEditor wraps its handlers in useCallback and reads `body` through a ref
+// for exactly that reason, and `WorkEditor.perf.test.jsx` guards the invariant.
+function StoryboardPanel({
work,
characters = [],
places = [],
@@ -413,3 +419,5 @@ export default function StoryboardPanel({
</div>
);
}
+
+export default memo(StoryboardPanel);
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index 9cd4017635..7fd41abc6c 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -15,7 +15,6 @@ import {
History,
Timer,
PenLine,
- Check,
Loader2,
BookOpen,
Pencil,
@@ -43,7 +42,6 @@ import {
listWritersRoomObjects,
promoteWritersRoomWorkToPipeline,
} from '../../services/apiWritersRoom';
-import { listCatalogIngredientsForRef } from '../../services/apiCatalog';
import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';
import { STATUS_LABELS } from './labels';
import { countWords, formatDurationSec } from '../../utils/formatters';
@@ -57,8 +55,12 @@ import ProseReader from './ProseReader';
import SyncedReview from './SyncedReview';
import ProseTokenPopover from './ProseTokenPopover';
import WritersRoomDock from './WritersRoomDock';
-import VoiceExemplarEditor, { VOICE_EXEMPLARS_MAX } from '../VoiceExemplarEditor';
+import WorkEditorVersions from './WorkEditorVersions';
+import WorkEditorVoicePanel from './WorkEditorVoicePanel';
import useImageGenQueue from '../../hooks/useImageGenQueue';
+import useLiveSuggest from '../../hooks/useLiveSuggest';
+import useSidebarResize from '../../hooks/useSidebarResize';
+import useTokenPopover from '../../hooks/useTokenPopover';
const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', PLACES: 'places', OBJECTS: 'objects', EVALUATE: 'evaluate', FORMAT: 'format' };
const DRAWER = { VERSIONS: 'versions', HISTORY: 'history', POLISH: 'polish', VOICE: 'voice' };
@@ -84,16 +86,6 @@ function readReadingTheme() {
return safeReadStorage(READING_THEME_KEY) === 'light' ? 'light' : 'dark';
}
-function readSidebarWidth() {
- const raw = safeReadStorage(SIDEBAR_WIDTH_KEY);
- const n = raw ? parseInt(raw, 10) : NaN;
- return Number.isFinite(n) && n >= SIDEBAR_MIN ? n : SIDEBAR_DEFAULT;
-}
-
-function persistSidebarWidth(width) {
- safeWriteStorage(SIDEBAR_WIDTH_KEY, String(Math.round(width)));
-}
-
function readSidebarTab() {
const stored = safeReadStorage(SIDEBAR_TAB_KEY);
return STORYBOARD_TAB_VALUES.includes(stored) ? stored : STORYBOARD_TAB.BOARDS;
@@ -123,17 +115,19 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// Scenes from the latest script analysis — populated by StoryboardPanel via
// onScenesChange so ProseReader can mark scene boundaries in Read view.
const [latestScenes, setLatestScenes] = useState([]);
- // Token popover state. `pop.kind`/`pop.refId` identify the hovered token,
- // `pop.anchorEl` is the DOM ELEMENT (not a frozen DOMRect) — the popover
- // re-reads getBoundingClientRect on each reflow so it tracks the token
- // through scrolling and viewport resizes. `pinned` keeps the popover
- // open after click so the user can move into it (e.g. to click
- // "Open profile") without it dismissing.
- const [pop, setPop] = useState(null);
- // Cross-link hot states: `hotRef` ({kind,refId}) ties prose tokens to
- // SceneCard chips and to bible rows; `hotScene` ties SceneCard hover to
- // the matching ProseReader section. Both are nullable.
- const [hotRef, setHotRef] = useState(null);
+ // Prose-token popover state machine (hover/click/pin + the cross-link
+ // `hotRef` that lights SceneCard chips and bible rows). See useTokenPopover.
+ const {
+ pop,
+ hotRef,
+ onTokenEnter: handleTokenEnter,
+ onTokenLeave: handleTokenLeave,
+ onTokenClick: handleTokenClick,
+ onPopoverEnter: handlePopoverEnter,
+ onPopoverLeave: handlePopoverLeave,
+ closePopover,
+ } = useTokenPopover();
+ // `hotScene` ties SceneCard hover to the matching ProseReader section.
const [hotScene, setHotScene] = useState(null);
// Live image-gen queue scoped to this page. SceneCard calls
// queueRegister({jobId, sceneId, sceneLabel}) on render kickoff so the dock
@@ -150,8 +144,8 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// Phase 5 live mode — opt-in, per-work Creative Director continuation
// suggestions. Optimistic mirror of work.liveMode so the toggle flips
- // instantly; re-synced from the prop. `liveTriggerRef` holds the panel's
- // imperative suggest fn; `liveTimerRef` is the post-typing debounce.
+ // instantly; re-synced from the prop. The panel's imperative suggest fn and
+ // the post-typing debounce live in useLiveSuggest (below).
const [liveMode, setLiveMode] = useState(work.liveMode || null);
useEffect(() => { setLiveMode(work.liveMode || null); }, [work.liveMode]);
// Shared live text-suggest usage counter. The continuation panel and the CD
@@ -173,9 +167,6 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const [savingVoice, setSavingVoice] = useState(false);
useEffect(() => { setVoiceExemplars(work.voiceExemplars || []); }, [work.id, work.voiceExemplars]);
useEffect(() => { setVoiceAntiExemplars(work.voiceAntiExemplars || []); }, [work.id, work.voiceAntiExemplars]);
- const liveTriggerRef = useRef(null);
- const liveTimerRef = useRef(null);
- const registerLiveTrigger = useCallback((fn) => { liveTriggerRef.current = fn; }, []);
// Phase 5 live render preview — the scene/analysis/image context the storyboard
// surfaces, fed into LiveRenderPanel so it can render the scene at the cursor
// using the existing image-gen route + the shared render queue (queueRegister).
@@ -210,120 +201,16 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const readerRef = useRef(null);
const overflowRef = useRef(null);
const scrollAnimRef = useRef(null);
- // Hover-delay timers for the prose-token popover. 200ms open, 150ms close
- // so the popover doesn't flicker when the cursor crosses a token.
- const popOpenTimerRef = useRef(null);
- const popCloseTimerRef = useRef(null);
- // Mirror of `pop?.pinned` so callbacks can read pinned state without
- // re-binding (and so setPop updaters stay pure — StrictMode replays the
- // updater and would emit duplicate setHotRef side effects otherwise).
- const popPinnedRef = useRef(false);
- useEffect(() => { popPinnedRef.current = !!pop?.pinned; }, [pop?.pinned]);
-
- // Pass the anchor ELEMENT down (not a frozen DOMRect) so the popover can
- // re-read getBoundingClientRect on scroll/resize and stay attached to its
- // token. A captured rect goes stale the moment the user scrolls.
- // While pinned, hover-driven opens are ignored — the user explicitly
- // pinned the popover and shouldn't see it ripped out from under them as
- // the cursor crosses other tokens. They have to click the X (or press
- // Escape) before another token can open a new popover.
- const handleTokenEnter = useCallback(({ kind, refId, anchor }) => {
- if (popPinnedRef.current) return;
- if (popCloseTimerRef.current) {
- clearTimeout(popCloseTimerRef.current);
- popCloseTimerRef.current = null;
- }
- if (popOpenTimerRef.current) clearTimeout(popOpenTimerRef.current);
- setHotRef({ kind, refId });
- popOpenTimerRef.current = setTimeout(() => {
- setPop({ kind, refId, anchorEl: anchor, pinned: false });
- }, 200);
- }, []);
- // Schedule the 150ms grace close. Idempotent: clears any existing close
- // timer first so rapid enter/leave events can't pile up multiple pending
- // timeouts that fire later and clear pop/hotRef unexpectedly. The timer
- // also nulls its own ref after firing so external clearTimeouts on a stale
- // id are a no-op.
- //
- // hotRef is only cleared when the popover actually closes (i.e. it wasn't
- // pinned). When pinned, the popover stays visible and the cross-link
- // highlights (SceneCard chips / bible rows) must stay lit too — clearing
- // hotRef there would leave the popover orphaned from its visual targets.
- const scheduleClose = useCallback(() => {
- if (popCloseTimerRef.current) {
- clearTimeout(popCloseTimerRef.current);
- popCloseTimerRef.current = null;
- }
- popCloseTimerRef.current = setTimeout(() => {
- popCloseTimerRef.current = null;
- const isPinned = popPinnedRef.current;
- if (isPinned) return;
- setPop(null);
- setHotRef(null);
- }, 150);
- }, []);
- const handleTokenLeave = useCallback(() => {
- if (popOpenTimerRef.current) {
- clearTimeout(popOpenTimerRef.current);
- popOpenTimerRef.current = null;
- }
- scheduleClose();
- }, [scheduleClose]);
- // Cursor crossed from token onto the popover itself: cancel the pending
- // close so the user can click links inside without it dismissing on them.
- const handlePopoverEnter = useCallback(() => {
- if (popCloseTimerRef.current) {
- clearTimeout(popCloseTimerRef.current);
- popCloseTimerRef.current = null;
- }
- if (popOpenTimerRef.current) {
- clearTimeout(popOpenTimerRef.current);
- popOpenTimerRef.current = null;
- }
- }, []);
- // Cursor left the popover (and didn't go back to a token): schedule the
- // same 150ms grace close as token-leave.
- const handlePopoverLeave = useCallback(() => {
- scheduleClose();
- }, [scheduleClose]);
- const handleTokenClick = useCallback(({ kind, refId, anchor }) => {
- if (popOpenTimerRef.current) clearTimeout(popOpenTimerRef.current);
- if (popCloseTimerRef.current) clearTimeout(popCloseTimerRef.current);
- setPop({ kind, refId, anchorEl: anchor, pinned: true });
- }, []);
- // Closing the popover (whether by Escape, X click, or auto-leave) must also
- // drop the hot-state and any pending hover timers; otherwise SceneCard chips
- // and bible rows can stay highlighted indefinitely after the cursor has
- // moved on.
- const clearPopTimers = useCallback(() => {
- if (popOpenTimerRef.current) {
- clearTimeout(popOpenTimerRef.current);
- popOpenTimerRef.current = null;
- }
- if (popCloseTimerRef.current) {
- clearTimeout(popCloseTimerRef.current);
- popCloseTimerRef.current = null;
- }
- }, []);
- const handlePopClose = useCallback(() => {
- clearPopTimers();
- setPop(null);
- setHotRef(null);
- }, [clearPopTimers]);
+ // Popover open/close callbacks come from useTokenPopover above.
+ // `handleOpenProfile` is the one that isn't purely popover-local: it closes
+ // the popover AND swings the sidebar/mobile tab to the matching bible section.
const handleOpenProfile = useCallback(({ kind }) => {
- clearPopTimers();
- setPop(null);
- setHotRef(null);
+ closePopover();
if (kind === 'char') setSidebarTab(STORYBOARD_TAB.CHARACTERS);
else if (kind === 'place') setSidebarTab(STORYBOARD_TAB.WORLD);
else if (kind === 'object' && STORYBOARD_TAB.OBJECTS) setSidebarTab(STORYBOARD_TAB.OBJECTS);
setMobileTab(MOBILE_TAB.STORYBOARD);
- }, [clearPopTimers]);
-
- useEffect(() => () => {
- if (popOpenTimerRef.current) clearTimeout(popOpenTimerRef.current);
- if (popCloseTimerRef.current) clearTimeout(popCloseTimerRef.current);
- }, []);
+ }, [closePopover]);
const smoothScrollTextarea = useCallback((ta, targetTop, ms = 220) => {
if (!ta) return;
@@ -386,6 +273,17 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const dirty = body !== savedBody;
const wordCount = useMemo(() => countWords(body), [body]);
+ // Live mirror of `body` for callbacks that only READ the prose (#3387).
+ // Typing is the hot path here: `setBody` re-renders WorkEditor on every
+ // keystroke, and any handler with `body` in its useCallback deps would get a
+ // fresh identity each time — which defeats the memo boundary on the heavy
+ // <StoryboardPanel> sibling and re-renders the whole storyboard tree per
+ // character. Reading through the ref keeps those handlers referentially
+ // stable. Assigned during render (same pattern as `handleSaveRef` below) so
+ // the value is current before any child effect or event handler runs.
+ const bodyRef = useRef(body);
+ bodyRef.current = body;
+
const mountedRef = useMounted();
// savingRef gates parallel saves synchronously — `saving` state lags React
@@ -487,16 +385,18 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
onChange?.({ ...updated, activeDraftBody: body });
};
- const commitImageStyle = async (next) => {
+ // useCallback + bodyRef: this is a StoryboardPanel prop, and the panel is
+ // memoized — a fresh identity per keystroke would defeat the memo boundary.
+ const commitImageStyle = useCallback(async (next) => {
const updated = await updateWritersRoomWork(work.id, { imageStyle: next }, { silent: true }).catch((err) => {
if (mountedRef.current) toast.error(`Style save failed: ${err.message}`);
return null;
});
if (updated && mountedRef.current) {
- onChange?.({ ...updated, activeDraftBody: body });
+ onChange?.({ ...updated, activeDraftBody: bodyRef.current });
toast.success(next.presetId === 'none' ? 'World style cleared' : 'World style saved');
}
- };
+ }, [work.id, onChange, mountedRef]);
// Persist the voice exemplars (#2179). Drop rows with a blank passage before
// sending (the server prunes them too, but this keeps the round-tripped state
@@ -536,25 +436,26 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const getCursorContext = useCallback(() => {
const ta = textareaRef.current;
if (!ta) return null;
- const start = ta.selectionStart ?? body.length;
+ const text = bodyRef.current;
+ const start = ta.selectionStart ?? text.length;
const end = ta.selectionEnd ?? start;
const WINDOW = 4000;
// Clamp each slice to the server's per-field caps (before/after 12k,
// selection 8k) so a huge selection can't 400 the request — the schema
// would reject it and surface as a red toast instead of a graceful notice.
return {
- before: body.slice(Math.max(0, start - WINDOW), start),
- after: body.slice(end, end + WINDOW),
- selection: body.slice(start, end).slice(0, 8000),
+ before: text.slice(Math.max(0, start - WINDOW), start),
+ after: text.slice(end, end + WINDOW),
+ selection: text.slice(start, end).slice(0, 8000),
};
- }, [body]);
+ }, []);
// Caret offset into the body for the live render preview's scene resolution.
// Falls back to end-of-body when the textarea isn't mounted (e.g. Read view).
const getCursorOffset = useCallback(() => {
const ta = textareaRef.current;
- return ta?.selectionStart ?? body.length;
- }, [body]);
+ return ta?.selectionStart ?? bodyRef.current.length;
+ }, []);
// Insert a suggested snippet at the caret (replacing any selection), then
// restore focus + caret after the inserted text so the writer keeps flowing.
@@ -562,12 +463,13 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const ta = textareaRef.current;
const snippet = opt?.text || '';
if (!snippet) return;
- const start = ta?.selectionStart ?? body.length;
+ const text = bodyRef.current;
+ const start = ta?.selectionStart ?? text.length;
const end = ta?.selectionEnd ?? start;
// Space-pad so an inserted snippet doesn't weld onto the preceding word.
- const needsLeadingSpace = start > 0 && !/\s$/.test(body.slice(0, start));
+ const needsLeadingSpace = start > 0 && !/\s$/.test(text.slice(0, start));
const piece = (needsLeadingSpace ? ' ' : '') + snippet;
- const next = body.slice(0, start) + piece + body.slice(end);
+ const next = text.slice(0, start) + piece + text.slice(end);
setBody(next);
const caret = start + piece.length;
requestAnimationFrame(() => {
@@ -577,21 +479,15 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
el.setSelectionRange(caret, caret);
});
toast('Inserted — save to persist', { icon: '✍️' });
- }, [body]);
+ }, []);
// Debounce a suggest after the writer pauses typing. Only arms while live
// mode is on and we're in the edit textarea; cleared on every keystroke and
// on unmount so a deferred fire can't hit a dead/closed editor.
- const scheduleLiveSuggest = useCallback(() => {
- if (!liveEnabled || viewMode !== 'edit') return;
- if (liveTimerRef.current) clearTimeout(liveTimerRef.current);
- liveTimerRef.current = setTimeout(() => {
- liveTimerRef.current = null;
- if (mountedRef.current) liveTriggerRef.current?.();
- }, liveDebounceMs);
- }, [liveEnabled, viewMode, liveDebounceMs, mountedRef]);
-
- useEffect(() => () => { if (liveTimerRef.current) clearTimeout(liveTimerRef.current); }, []);
+ const { registerTrigger: registerLiveTrigger, scheduleSuggest: scheduleLiveSuggest } = useLiveSuggest({
+ enabled: liveEnabled && viewMode === 'edit',
+ debounceMs: liveDebounceMs,
+ });
const toggleLiveMode = useCallback(async () => {
const nextEnabled = !liveEnabled;
@@ -737,12 +633,13 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
}
const ta = textareaRef.current;
- if (!ta || !body) return;
+ const text = bodyRef.current;
+ if (!ta || !text) return;
const heading = scene.heading || '';
let idx = -1;
for (const prefix of ['## ', '### ', '# ', '']) {
if (!heading) break;
- idx = body.indexOf(prefix + heading);
+ idx = text.indexOf(prefix + heading);
if (idx >= 0) break;
}
if (idx < 0) {
@@ -750,7 +647,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
if (!candidate) continue;
const snippet = String(candidate).trim().slice(0, 40);
if (!snippet) continue;
- idx = body.indexOf(snippet);
+ idx = text.indexOf(snippet);
if (idx >= 0) break;
}
}
@@ -758,7 +655,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
if (idx >= 0) {
ta.focus();
ta.setSelectionRange(idx, idx);
- const fraction = idx / body.length;
+ const fraction = idx / text.length;
target = Math.max(0, fraction * (ta.scrollHeight - ta.clientHeight));
} else if (totalScenes > 0 && sceneIndex >= 0) {
const fraction = sceneIndex / totalScenes;
@@ -767,7 +664,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
return;
}
smoothScrollTextarea(ta, target);
- }, [body, viewMode, smoothScrollTextarea]);
+ }, [viewMode, smoothScrollTextarea]);
// Per-scene Debug menu actions — until scoped tools land, route to the
// most relevant tab/drawer.
@@ -781,48 +678,19 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
else if (kind === 'why-image') setDrawer(DRAWER.HISTORY);
}, []);
- // Drag-to-resize sidebar (desktop only).
- const splitRef = useRef(null);
- const [sidebarWidth, setSidebarWidth] = useState(readSidebarWidth);
- const sidebarWidthRef = useRef(sidebarWidth);
- useEffect(() => { sidebarWidthRef.current = sidebarWidth; }, [sidebarWidth]);
- const dragStartRef = useRef(null);
-
- const onSplitMouseDown = useCallback((e) => {
- e.preventDefault();
- const containerWidth = splitRef.current?.getBoundingClientRect().width ?? 0;
- dragStartRef.current = { startX: e.clientX, startWidth: sidebarWidthRef.current, containerWidth };
- document.body.style.cursor = 'col-resize';
- document.body.style.userSelect = 'none';
- }, []);
-
- useEffect(() => {
- const onMove = (e) => {
- if (!dragStartRef.current) return;
- const { startX, startWidth, containerWidth } = dragStartRef.current;
- const max = Math.max(SIDEBAR_MIN + 1, containerWidth * SIDEBAR_MAX_FRACTION);
- const next = Math.min(max, Math.max(SIDEBAR_MIN, startWidth - (e.clientX - startX)));
- setSidebarWidth(next);
- };
- const onUp = () => {
- if (!dragStartRef.current) return;
- dragStartRef.current = null;
- document.body.style.cursor = '';
- document.body.style.userSelect = '';
- persistSidebarWidth(sidebarWidthRef.current);
- };
- window.addEventListener('mousemove', onMove);
- window.addEventListener('mouseup', onUp);
- return () => {
- window.removeEventListener('mousemove', onMove);
- window.removeEventListener('mouseup', onUp);
- if (dragStartRef.current) {
- document.body.style.cursor = '';
- document.body.style.userSelect = '';
- dragStartRef.current = null;
- }
- };
- }, []);
+ // Drag-to-resize sidebar (desktop only). `splitRef` goes on the flex
+ // container so the drag can cap the sidebar at SIDEBAR_MAX_FRACTION of it.
+ const {
+ containerRef: splitRef,
+ width: sidebarWidth,
+ onMouseDown: onSplitMouseDown,
+ reset: resetSidebarWidth,
+ } = useSidebarResize({
+ storageKey: SIDEBAR_WIDTH_KEY,
+ defaultWidth: SIDEBAR_DEFAULT,
+ minWidth: SIDEBAR_MIN,
+ maxFraction: SIDEBAR_MAX_FRACTION,
+ });
const toggleReadingTheme = useCallback(() => {
setReadingTheme((prev) => {
@@ -834,6 +702,16 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const closeOverflowAnd = (fn) => () => { setOverflowOpen(false); fn?.(); };
+ // StoryboardPanel is memoized (#3387) — it only skips a re-render while every
+ // prop it receives is referentially stable, so its handlers cannot be inline
+ // arrows. These four are the ones that used to be recreated per render (and
+ // therefore per keystroke); the rest are state setters, refs, or callbacks
+ // already keyed on non-typing deps.
+ const runAdapt = useCallback(() => runAnalysis(ANALYSIS_KIND.SCRIPT), [runAnalysis]);
+ const runCharacters = useCallback(() => runAnalysis(ANALYSIS_KIND.CHARACTERS), [runAnalysis]);
+ const runPlaces = useCallback(() => runAnalysis(ANALYSIS_KIND.PLACES), [runAnalysis]);
+ const runObjects = useCallback(() => runAnalysis(ANALYSIS_KIND.OBJECTS), [runAnalysis]);
+
return (
<div className="flex flex-col h-full">
{/* Header — title + status on left, primary actions + overflow on right */}
@@ -1041,10 +919,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
{viewMode !== 'review' && (
<div
onMouseDown={onSplitMouseDown}
- onDoubleClick={() => {
- setSidebarWidth(SIDEBAR_DEFAULT);
- persistSidebarWidth(SIDEBAR_DEFAULT);
- }}
+ onDoubleClick={resetSidebarWidth}
role="separator"
aria-label="Resize storyboard sidebar"
aria-orientation="vertical"
@@ -1101,15 +976,15 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
onCharactersChange={setCharacters}
onPlacesChange={setPlaces}
onObjectsChange={setObjects}
- onRunObjects={() => runAnalysis(ANALYSIS_KIND.OBJECTS)}
+ onRunObjects={runObjects}
onScenesChange={setLatestScenes}
onLiveRenderContextChange={setLiveRenderContext}
registerSceneImageMerge={registerSceneImageMerge}
onJumpToScene={jumpToScene}
onDebug={handleDebug}
- onRunAdapt={() => runAnalysis(ANALYSIS_KIND.SCRIPT)}
- onRunCharacters={() => runAnalysis(ANALYSIS_KIND.CHARACTERS)}
- onRunPlaces={() => runAnalysis(ANALYSIS_KIND.PLACES)}
+ onRunAdapt={runAdapt}
+ onRunCharacters={runCharacters}
+ onRunPlaces={runPlaces}
onRunFullPipeline={runFullPipeline}
runningAdapt={runningKind === ANALYSIS_KIND.SCRIPT}
runningKind={runningKind}
@@ -1137,7 +1012,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
places={places}
objects={objects}
onOpenProfile={handleOpenProfile}
- onClose={handlePopClose}
+ onClose={closePopover}
onPopoverEnter={handlePopoverEnter}
onPopoverLeave={handlePopoverLeave}
/>
@@ -1152,7 +1027,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
/>
<Drawer open={drawer === DRAWER.VERSIONS} onClose={() => setDrawer(null)} title="Versions">
- <VersionsList work={work} dirty={dirty} onSwitch={(id) => { switchToDraft(id); setDrawer(null); }} />
+ <WorkEditorVersions work={work} dirty={dirty} onSwitch={(id) => { switchToDraft(id); setDrawer(null); }} />
</Drawer>
<Drawer open={drawer === DRAWER.HISTORY} onClose={() => setDrawer(null)} title="Analysis history">
<AnalysisHistory work={work} activeHash={activeHash} onApplyFormat={applyFormatText} />
@@ -1161,38 +1036,14 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<PolishPanel work={work} dirty={dirty} onBodyChanged={reloadBodyFromServer} />
</Drawer>
<Drawer open={drawer === DRAWER.VOICE} onClose={() => setDrawer(null)} title="Voice exemplars" size="md">
- <div className="p-3">
- <p className="text-[11px] text-gray-500 mb-2">
- Concrete prose passages anchor this work&rsquo;s voice far better than adjectives. Exemplars are injected into live continuation suggestions and the Polish revision brief as &ldquo;MATCH this voice&rdquo;; anti-exemplars as &ldquo;NEVER drift toward this.&rdquo; Up to {VOICE_EXEMPLARS_MAX} of each.
- </p>
- <VoiceExemplarEditor
- idPrefix="wr-voice-exemplar"
- title="Voice exemplars (the tuning fork)"
- hint="1–3 short passages (~150–300 words) that nail this work's voice. Injected as “MATCH this voice.”"
- notePlaceholder="what this demonstrates (e.g. spare, close-psychic)"
- entries={voiceExemplars}
- onChange={setVoiceExemplars}
- />
- <VoiceExemplarEditor
- idPrefix="wr-voice-anti"
- title="Anti-exemplars (never drift toward this)"
- hint="Passages in the wrong register, kept as negative examples. Injected as “NEVER drift toward this.”"
- notePlaceholder="what's wrong (e.g. too ornate, wrong temperature)"
- entries={voiceAntiExemplars}
- onChange={setVoiceAntiExemplars}
- />
- <div className="mt-4 flex justify-end">
- <button
- type="button"
- onClick={saveVoice}
- disabled={savingVoice}
- className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"
- >
- {savingVoice ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
- {savingVoice ? 'Saving…' : 'Save voice'}
- </button>
- </div>
- </div>
+ <WorkEditorVoicePanel
+ exemplars={voiceExemplars}
+ antiExemplars={voiceAntiExemplars}
+ onExemplarsChange={setVoiceExemplars}
+ onAntiExemplarsChange={setVoiceAntiExemplars}
+ saving={savingVoice}
+ onSave={saveVoice}
+ />
</Drawer>
</div>
);
@@ -1283,80 +1134,3 @@ function MobileTab({ active, onClick, icon: Icon, label }) {
</button>
);
}
-
-function VersionsList({ work, dirty, onSwitch }) {
- const drafts = (work.drafts || []).slice().reverse();
-
- // Resolve referenced ingredient ids (stored per draft version) into display
- // names from the work's linked catalog cast. Only fetch when at least one
- // version actually carries refs — most works have none and we shouldn't hit
- // the catalog for them. The map is id → name; ids that no longer resolve
- // (unlinked since the version was saved) fall back to a short id chip.
- const hasRefs = drafts.some((d) => Array.isArray(d.referencedIngredientIds) && d.referencedIngredientIds.length > 0);
- const [nameById, setNameById] = useState({});
- useEffect(() => {
- if (!hasRefs || !work.id) return undefined;
- let cancelled = false;
- listCatalogIngredientsForRef('work', work.id, { silent: true })
- .then((rows) => {
- if (cancelled) return;
- const map = {};
- for (const row of rows || []) {
- const ing = row?.ingredient;
- if (ing?.id) map[ing.id] = ing.name || ing.id;
- }
- setNameById(map);
- })
- .catch(() => { if (!cancelled) setNameById({}); });
- return () => { cancelled = true; };
- }, [hasRefs, work.id]);
-
- if (drafts.length === 0) {
- return <div className="text-xs text-gray-500 italic">No versions yet. Click Snapshot in the header to create one.</div>;
- }
- return (
- <>
- {dirty && (
- <div className="mb-2 px-2 py-1.5 text-[11px] border border-port-warning/40 bg-port-warning/5 text-port-warning rounded">
- Save or snapshot before switching versions — unsaved edits will be lost.
- </div>
- )}
- <ul className="space-y-1 text-xs">
- {drafts.map((draft) => {
- const isActive = draft.id === work.activeDraftVersionId;
- const refIds = Array.isArray(draft.referencedIngredientIds) ? draft.referencedIngredientIds : [];
- return (
- <li key={draft.id}>
- <button
- onClick={() => onSwitch(draft.id)}
- disabled={isActive}
- className={`w-full flex items-center justify-between gap-2 px-2 py-1.5 rounded text-left ${
- isActive ? 'bg-port-accent/20 text-port-accent cursor-default' : 'text-gray-400 hover:bg-port-bg hover:text-white'
- }`}
- >
- <span className="flex items-center gap-2 truncate">
- {isActive ? <Check size={11} /> : <Clock size={11} />}
- {draft.label}
- </span>
- <span className="text-[10px] text-gray-500">{draft.wordCount}w</span>
- </button>
- {refIds.length > 0 && (
- <div className="flex flex-wrap gap-1 px-2 pt-1 pb-0.5">
- {refIds.map((id) => (
- <span
- key={id}
- className="px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-[10px] text-gray-400 truncate max-w-[10rem]"
- title={nameById[id] || id}
- >
- {nameById[id] || `${id.slice(0, 12)}…`}
- </span>
- ))}
- </div>
- )}
- </li>
- );
- })}
- </ul>
- </>
- );
-}
diff --git a/client/src/components/writers-room/WorkEditor.perf.test.jsx b/client/src/components/writers-room/WorkEditor.perf.test.jsx
new file mode 100644
index 0000000000..9f0fb58bb3
--- /dev/null
+++ b/client/src/components/writers-room/WorkEditor.perf.test.jsx
@@ -0,0 +1,138 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { act, render } from '@testing-library/react';
+import { fireEvent } from '@testing-library/dom';
+import { MemoryRouter } from 'react-router';
+
+// Regression guard for #3387: typing in the WorkEditor body must NOT re-render
+// the <StoryboardPanel> sidebar. The panel is a heavy tree (bibles, boards,
+// scene cards, image config) with zero dependency on the prose text, so a
+// per-keystroke re-render of it was the editor's dominant typing cost.
+//
+// Two halves, because either alone is a false green:
+// 1. The panel is wrapped in React.memo (asserted against the REAL module).
+// 2. Every prop WorkEditor hands it stays referentially stable across
+// keystrokes — otherwise memo compares unequal and re-renders anyway.
+// A memoized stub proves this: it only skips a render when the props it
+// receives are identical.
+
+const probe = vi.hoisted(() => ({ renders: 0, props: null }));
+
+vi.mock('./StoryboardPanel', async () => {
+ const { memo } = await import('react');
+ const StoryboardPanelStub = memo(function StoryboardPanelStub(props) {
+ probe.renders += 1;
+ probe.props = props;
+ return <div data-testid="storyboard-panel" />;
+ });
+ return {
+ default: StoryboardPanelStub,
+ STORYBOARD_TAB: {
+ CHARACTERS: 'characters',
+ WORLD: 'world',
+ OBJECTS: 'objects',
+ SCENES: 'scenes',
+ BOARDS: 'boards',
+ CONFIG: 'config',
+ },
+ STORYBOARD_TAB_VALUES: ['characters', 'world', 'objects', 'scenes', 'boards', 'config'],
+ };
+});
+
+// Socket.IO auto-connects on import (useImageGenQueue / LiveRenderPanel).
+vi.mock('../../services/socket', () => ({
+ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn(), connected: false },
+}));
+
+// Keep every other export real so a signature drift still breaks the suite;
+// only the three mount-effect fetches are stubbed.
+vi.mock('../../services/apiWritersRoom', async (importOriginal) => ({
+ ...(await importOriginal()),
+ listWritersRoomCharacters: vi.fn(async () => []),
+ listWritersRoomPlaces: vi.fn(async () => []),
+ listWritersRoomObjects: vi.fn(async () => []),
+}));
+
+import WorkEditor from './WorkEditor';
+
+const work = {
+ id: 'wr-work-1',
+ title: 'Example Work',
+ status: 'drafting',
+ kind: 'novel',
+ activeDraftBody: 'The hero wakes.',
+ activeDraftVersionId: 'wr-draft-1',
+ drafts: [{ id: 'wr-draft-1', label: 'v1', wordCount: 3 }],
+};
+
+async function renderEditor() {
+ const view = render(
+ <MemoryRouter>
+ <WorkEditor work={work} onChange={() => {}} />
+ </MemoryRouter>
+ );
+ // Settle the mount-effect bible fetches before asserting render counts.
+ await act(async () => {});
+ return view;
+}
+
+beforeEach(() => {
+ probe.renders = 0;
+ probe.props = null;
+});
+
+describe('WorkEditor typing does not re-render StoryboardPanel (#3387)', () => {
+ it('leaves the panel untouched across a burst of keystrokes', async () => {
+ const { container } = await renderEditor();
+ const textarea = container.querySelector('textarea');
+ expect(textarea).toBeTruthy();
+ expect(probe.renders).toBeGreaterThan(0);
+
+ // The FIRST keystroke legitimately re-renders the panel once: `dirty`
+ // flips false → true and the panel renders a save-first warning from it.
+ fireEvent.change(textarea, { target: { value: 'The hero wakes. A' } });
+ expect(probe.props.dirty).toBe(true);
+
+ const rendersAfterDirty = probe.renders;
+ const propsAfterDirty = probe.props;
+
+ // Every subsequent keystroke must be free.
+ for (const next of ['Ab', 'Abc', 'Abcd', 'Abcde', 'Abcdef']) {
+ fireEvent.change(textarea, { target: { value: `The hero wakes. ${next}` } });
+ }
+
+ expect(textarea.value).toBe('The hero wakes. Abcdef');
+ expect(probe.renders).toBe(rendersAfterDirty);
+ // Same props object identity — nothing WorkEditor passes down churned.
+ expect(probe.props).toBe(propsAfterDirty);
+ });
+
+ it('keeps every StoryboardPanel handler referentially stable while typing', async () => {
+ const { container } = await renderEditor();
+ const textarea = container.querySelector('textarea');
+ // Get past the dirty flip first so the comparison isolates typing churn.
+ fireEvent.change(textarea, { target: { value: 'x' } });
+ const before = probe.props;
+
+ fireEvent.change(textarea, { target: { value: 'xy' } });
+
+ // These are the props that used to be rebuilt per render — inline arrows
+ // (onRunAdapt / onRunCharacters / onRunPlaces / onRunObjects), a plain
+ // async fn (onStyleChange), and a useCallback with `body` in its deps
+ // (onJumpToScene). Each one alone defeats the memo boundary.
+ for (const key of [
+ 'onRunAdapt', 'onRunCharacters', 'onRunPlaces', 'onRunObjects',
+ 'onRunFullPipeline', 'onStyleChange', 'onJumpToScene', 'onDebug',
+ 'onScenesChange', 'onLiveRenderContextChange', 'registerSceneImageMerge',
+ 'onCharactersChange', 'onPlacesChange', 'onObjectsChange',
+ 'onSceneHover', 'onSceneRenderStart', 'onTabChange',
+ ]) {
+ expect(typeof before[key], `${key} should be a function`).toBe('function');
+ expect(probe.props[key], `${key} changed identity on a keystroke`).toBe(before[key]);
+ }
+ });
+
+ it('ships StoryboardPanel behind a real memo boundary', async () => {
+ const actual = await vi.importActual('./StoryboardPanel');
+ expect(actual.default.$$typeof).toBe(Symbol.for('react.memo'));
+ });
+});
diff --git a/client/src/components/writers-room/WorkEditorVersions.jsx b/client/src/components/writers-room/WorkEditorVersions.jsx
new file mode 100644
index 0000000000..ebe731a946
--- /dev/null
+++ b/client/src/components/writers-room/WorkEditorVersions.jsx
@@ -0,0 +1,83 @@
+import { useEffect, useState } from 'react';
+import { Check, Clock } from 'lucide-react';
+import { listCatalogIngredientsForRef } from '../../services/apiCatalog';
+
+// WorkEditorVersions — the Versions drawer body for WorkEditor: the draft
+// version list with the referenced-ingredient chips under each row.
+// Extracted from WorkEditor (#3387).
+export default function WorkEditorVersions({ work, dirty, onSwitch }) {
+ const drafts = (work.drafts || []).slice().reverse();
+
+ // Resolve referenced ingredient ids (stored per draft version) into display
+ // names from the work's linked catalog cast. Only fetch when at least one
+ // version actually carries refs — most works have none and we shouldn't hit
+ // the catalog for them. The map is id → name; ids that no longer resolve
+ // (unlinked since the version was saved) fall back to a short id chip.
+ const hasRefs = drafts.some((d) => Array.isArray(d.referencedIngredientIds) && d.referencedIngredientIds.length > 0);
+ const [nameById, setNameById] = useState({});
+ useEffect(() => {
+ if (!hasRefs || !work.id) return undefined;
+ let cancelled = false;
+ listCatalogIngredientsForRef('work', work.id, { silent: true })
+ .then((rows) => {
+ if (cancelled) return;
+ const map = {};
+ for (const row of rows || []) {
+ const ing = row?.ingredient;
+ if (ing?.id) map[ing.id] = ing.name || ing.id;
+ }
+ setNameById(map);
+ })
+ .catch(() => { if (!cancelled) setNameById({}); });
+ return () => { cancelled = true; };
+ }, [hasRefs, work.id]);
+
+ if (drafts.length === 0) {
+ return <div className="text-xs text-gray-500 italic">No versions yet. Click Snapshot in the header to create one.</div>;
+ }
+ return (
+ <>
+ {dirty && (
+ <div className="mb-2 px-2 py-1.5 text-[11px] border border-port-warning/40 bg-port-warning/5 text-port-warning rounded">
+ Save or snapshot before switching versions — unsaved edits will be lost.
+ </div>
+ )}
+ <ul className="space-y-1 text-xs">
+ {drafts.map((draft) => {
+ const isActive = draft.id === work.activeDraftVersionId;
+ const refIds = Array.isArray(draft.referencedIngredientIds) ? draft.referencedIngredientIds : [];
+ return (
+ <li key={draft.id}>
+ <button
+ onClick={() => onSwitch(draft.id)}
+ disabled={isActive}
+ className={`w-full flex items-center justify-between gap-2 px-2 py-1.5 rounded text-left ${
+ isActive ? 'bg-port-accent/20 text-port-accent cursor-default' : 'text-gray-400 hover:bg-port-bg hover:text-white'
+ }`}
+ >
+ <span className="flex items-center gap-2 truncate">
+ {isActive ? <Check size={11} /> : <Clock size={11} />}
+ {draft.label}
+ </span>
+ <span className="text-[10px] text-gray-500">{draft.wordCount}w</span>
+ </button>
+ {refIds.length > 0 && (
+ <div className="flex flex-wrap gap-1 px-2 pt-1 pb-0.5">
+ {refIds.map((id) => (
+ <span
+ key={id}
+ className="px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-[10px] text-gray-400 truncate max-w-[10rem]"
+ title={nameById[id] || id}
+ >
+ {nameById[id] || `${id.slice(0, 12)}…`}
+ </span>
+ ))}
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </>
+ );
+}
diff --git a/client/src/components/writers-room/WorkEditorVoicePanel.jsx b/client/src/components/writers-room/WorkEditorVoicePanel.jsx
new file mode 100644
index 0000000000..9defa8c45f
--- /dev/null
+++ b/client/src/components/writers-room/WorkEditorVoicePanel.jsx
@@ -0,0 +1,52 @@
+import { Loader2, Save } from 'lucide-react';
+import VoiceExemplarEditor, { VOICE_EXEMPLARS_MAX } from '../VoiceExemplarEditor';
+
+// WorkEditorVoicePanel — the Voice exemplars drawer body for WorkEditor (#2179).
+// Extracted from WorkEditor (#3387).
+//
+// State stays hoisted in WorkEditor (the Drawer body can remount freely, and
+// switching works must re-seed it) — this component is presentational and takes
+// the entries + the save handler as props.
+export default function WorkEditorVoicePanel({
+ exemplars,
+ antiExemplars,
+ onExemplarsChange,
+ onAntiExemplarsChange,
+ saving,
+ onSave,
+}) {
+ return (
+ <div className="p-3">
+ <p className="text-[11px] text-gray-500 mb-2">
+ Concrete prose passages anchor this work&rsquo;s voice far better than adjectives. Exemplars are injected into live continuation suggestions and the Polish revision brief as &ldquo;MATCH this voice&rdquo;; anti-exemplars as &ldquo;NEVER drift toward this.&rdquo; Up to {VOICE_EXEMPLARS_MAX} of each.
+ </p>
+ <VoiceExemplarEditor
+ idPrefix="wr-voice-exemplar"
+ title="Voice exemplars (the tuning fork)"
+ hint="1–3 short passages (~150–300 words) that nail this work's voice. Injected as “MATCH this voice.”"
+ notePlaceholder="what this demonstrates (e.g. spare, close-psychic)"
+ entries={exemplars}
+ onChange={onExemplarsChange}
+ />
+ <VoiceExemplarEditor
+ idPrefix="wr-voice-anti"
+ title="Anti-exemplars (never drift toward this)"
+ hint="Passages in the wrong register, kept as negative examples. Injected as “NEVER drift toward this.”"
+ notePlaceholder="what's wrong (e.g. too ornate, wrong temperature)"
+ entries={antiExemplars}
+ onChange={onAntiExemplarsChange}
+ />
+ <div className="mt-4 flex justify-end">
+ <button
+ type="button"
+ onClick={onSave}
+ disabled={saving}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"
+ >
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
+ {saving ? 'Saving…' : 'Save voice'}
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 684a1bb13d..b1109eb4a8 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -107,10 +107,13 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useKeyboardShortcuts` | `useKeyboardShortcuts(active, bindings, opts?)` — fire a `{ key: handler }` map while `active`; ignores events from editable fields (`isEditableTarget` also exported), ⌘/Ctrl/Alt chords, OS key auto-repeat (`{ ignoreRepeat: false }` to opt back in), and any keystroke while an `aria-modal` dialog is open (`{ enabledInDialog: true }` for a modal-owned shortcut); a falsy handler disables that key. | Single-surface action shortcuts (editorial comment card prev/next + accept/dismiss/generate, #1603). Not for held-key/game input (that's `useKeyboardControls`). |
| `useHfTokenStatus` | Reads the central HuggingFace token status (`GET /image-gen/setup/hf-token-status` → `server/lib/hfToken.js`: stored → env → `hf auth login`). Returns `{ present, source, refresh }` where `present` is TRI-state — `null` means "unknown/failed", not "absent" — so a slow fetch can't flash a token nag at a user who has one. `{ enabled }` gates the fetch (false resets to unknown, so a modal re-checks per open); `{ errorAs: 'absent' }` opts a surface into offering the paste form when the status call fails. | Any gated-HuggingFace surface (3D page, MIDI gated modal, Image Gen banners) — use this instead of re-rolling the fetch, or the same blip renders differently per page. |
| `useKeyboardHelp` | Esc closes, even from inputs/textareas. | Help/cheatsheet modals. |
+| `useLiveSuggest` | Post-typing debounce for an imperative panel trigger: `{ registerTrigger, scheduleSuggest }` re-arms one `debounceMs` timer per keystroke and fires the registered fn only while `enabled` and still mounted. | An editor that asks a sibling AI panel to suggest once the writer pauses (WorkEditor ↔ LiveContinuationPanel). |
| `useLockToggle` | Optimistic-PATCH lock toggle. | New "lock this field/stage/arc" button — use this, do not re-implement. |
| `usePopoverPosition` | Viewport-clamped `{ left, top, width }` for a fixed-position portal popover anchored to a trigger; re-measures on open and rAF-coalesced on capture-phase scroll/resize. Returns `{ triggerRef, popoverRef, style, reposition }`; pass `anchorRef` to follow a parent-owned trigger. | Any portal-into-`<body>` menu/popover placed relative to a button (ThemeSwitcher, CollectionPickerShell) — use this instead of re-rolling the measure/flip/clamp/reflow plumbing. |
| `useScrollLock` | Body-scroll lock with ref-count. | Modals, drawers, lightboxes. |
+| `useSidebarResize` | Drag-to-resize split-pane width persisted to `localStorage`; returns `{ containerRef, width, onMouseDown, reset }` and caps the drag at `maxFraction` of the measured container. | A desktop sidebar/split pane with a draggable divider (WorkEditor's storyboard sidebar). |
| `useSwipeNav` | Horizontal swipe prev/next. | Mobile swipe between siblings. |
+| `useTokenPopover` | Hover/click/pin state machine for an anchored token popover (200ms open, 150ms grace close) plus the `hotRef` cross-link highlight; returns `{ pop, hotRef, onTokenEnter/Leave/Click, onPopoverEnter/Leave, closePopover }`. | Prose (or any) tokens that open a detail popover on hover and pin on click (WorkEditor ↔ ProseTokenPopover). |
| `useUrlParams` | `[searchParams, updateParams]` — `updateParams(patch, { replace })` merges a patch into the query string and deletes keys set to `null`/`undefined`/`''` so a cleared filter leaves the URL clean. Reads the live params off a ref (react-router's functional updater is closure-stale) and is referentially stable. | Any page whose filter/sort/selection state lives in the URL (Catalog, MediaCollections, Media3D) — don't re-roll the merge-and-prune loop. |
| `useValidTab` | Resolve the active tab from the `:tab` URL param against a TABS list, falling back to a default on invalid/missing. | Any tabbed page whose tab lives in the URL — don't re-roll the `new Set(TABS.map(...))` guard. |
| `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 2359cf46b0..bc22c68ead 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -76,6 +76,9 @@ export { default as useMidiNotes } from './useMidiNotes.js';
export { default as useMidiPlayer } from './useMidiPlayer.js';
export { default as useCanvasDprSize } from './useCanvasDprSize.js';
export { default as useCanvasRollPalette } from './useCanvasRollPalette.js';
+export { default as useLiveSuggest } from './useLiveSuggest.js';
+export { default as useSidebarResize } from './useSidebarResize.js';
+export { default as useTokenPopover } from './useTokenPopover.js';
// === Mixed (both default and named) — surface both ===
export { default as useAsyncAction } from './useAsyncAction.js';
diff --git a/client/src/hooks/useLiveSuggest.js b/client/src/hooks/useLiveSuggest.js
new file mode 100644
index 0000000000..2dd3776344
--- /dev/null
+++ b/client/src/hooks/useLiveSuggest.js
@@ -0,0 +1,34 @@
+import { useCallback, useEffect, useRef } from 'react';
+import useMounted from './useMounted';
+
+// useLiveSuggest — post-typing debounce for a live AI suggestion panel.
+//
+// Extracted from WorkEditor (#3387). The panel registers its imperative
+// suggest fn via `registerTrigger`; the editor calls `scheduleSuggest()` on
+// every keystroke, which (re)arms a single `debounceMs` timer so the trigger
+// only fires once the writer pauses.
+//
+// `enabled` gates arming entirely — pass `liveMode.enabled && viewMode === 'edit'`
+// so a deferred fire can't hit a closed panel or a non-typing view. The timer is
+// cleared on unmount and the mounted guard is re-checked before firing, so a
+// pending suggest can never land on a dead editor.
+export default function useLiveSuggest({ enabled, debounceMs = 2500 }) {
+ const mountedRef = useMounted();
+ const triggerRef = useRef(null);
+ const timerRef = useRef(null);
+
+ const registerTrigger = useCallback((fn) => { triggerRef.current = fn; }, []);
+
+ const scheduleSuggest = useCallback(() => {
+ if (!enabled) return;
+ if (timerRef.current) clearTimeout(timerRef.current);
+ timerRef.current = setTimeout(() => {
+ timerRef.current = null;
+ if (mountedRef.current) triggerRef.current?.();
+ }, debounceMs);
+ }, [enabled, debounceMs, mountedRef]);
+
+ useEffect(() => () => { if (timerRef.current) clearTimeout(timerRef.current); }, []);
+
+ return { registerTrigger, scheduleSuggest };
+}
diff --git a/client/src/hooks/useSidebarResize.js b/client/src/hooks/useSidebarResize.js
new file mode 100644
index 0000000000..85c859fb39
--- /dev/null
+++ b/client/src/hooks/useSidebarResize.js
@@ -0,0 +1,87 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage';
+
+// useSidebarResize — drag-to-resize state for a desktop split pane whose width
+// is persisted to localStorage.
+//
+// Extracted from WorkEditor (#3387). The caller renders the drag handle and
+// wires `onMouseDown` / `onDoubleClick` (→ `reset`) to it, spreads `width` onto
+// the sidebar, and attaches `containerRef` to the flex container the sidebar
+// lives in — the container's measured width is what caps the drag, so the
+// sidebar can never eat more than `maxFraction` of the split.
+//
+// The window mousemove/mouseup listeners bind ONCE (empty deps) and read the
+// live config out of a ref. Re-binding them mid-drag would run the cleanup,
+// which drops `dragStartRef` and strips the body cursor override — i.e. the
+// drag would silently die if any option identity changed while the mouse was
+// down.
+export default function useSidebarResize({
+ storageKey,
+ defaultWidth,
+ minWidth,
+ maxFraction = 0.6,
+}) {
+ const [width, setWidth] = useState(() => {
+ const raw = safeReadStorage(storageKey);
+ const n = raw ? parseInt(raw, 10) : NaN;
+ return Number.isFinite(n) && n >= minWidth ? n : defaultWidth;
+ });
+
+ const containerRef = useRef(null);
+ const widthRef = useRef(width);
+ useEffect(() => { widthRef.current = width; }, [width]);
+ const dragStartRef = useRef(null);
+
+ // Live mirror of the options so the window listeners can stay bound once.
+ const configRef = useRef({ storageKey, minWidth, maxFraction });
+ configRef.current = { storageKey, minWidth, maxFraction };
+
+ const persist = useCallback((next) => {
+ safeWriteStorage(configRef.current.storageKey, String(Math.round(next)));
+ }, []);
+
+ const onMouseDown = useCallback((e) => {
+ e.preventDefault();
+ const containerWidth = containerRef.current?.getBoundingClientRect().width ?? 0;
+ dragStartRef.current = { startX: e.clientX, startWidth: widthRef.current, containerWidth };
+ document.body.style.cursor = 'col-resize';
+ document.body.style.userSelect = 'none';
+ }, []);
+
+ useEffect(() => {
+ const onMove = (e) => {
+ if (!dragStartRef.current) return;
+ const { startX, startWidth, containerWidth } = dragStartRef.current;
+ const { minWidth: min, maxFraction: frac } = configRef.current;
+ const max = Math.max(min + 1, containerWidth * frac);
+ const next = Math.min(max, Math.max(min, startWidth - (e.clientX - startX)));
+ setWidth(next);
+ };
+ const onUp = () => {
+ if (!dragStartRef.current) return;
+ dragStartRef.current = null;
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ safeWriteStorage(configRef.current.storageKey, String(Math.round(widthRef.current)));
+ };
+ window.addEventListener('mousemove', onMove);
+ window.addEventListener('mouseup', onUp);
+ return () => {
+ window.removeEventListener('mousemove', onMove);
+ window.removeEventListener('mouseup', onUp);
+ if (dragStartRef.current) {
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ dragStartRef.current = null;
+ }
+ };
+ }, []);
+
+ // Double-click the handle to restore the default width.
+ const reset = useCallback(() => {
+ setWidth(defaultWidth);
+ persist(defaultWidth);
+ }, [defaultWidth, persist]);
+
+ return { containerRef, width, onMouseDown, reset };
+}
diff --git a/client/src/hooks/useTokenPopover.js b/client/src/hooks/useTokenPopover.js
new file mode 100644
index 0000000000..6155aa430e
--- /dev/null
+++ b/client/src/hooks/useTokenPopover.js
@@ -0,0 +1,120 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+// useTokenPopover — hover/click state machine for the prose-token popover.
+//
+// Extracted from WorkEditor (#3387). Owns two pieces of state:
+//
+// `pop` — the open popover: `{ kind, refId, anchorEl, pinned }`, or null.
+// `anchorEl` is the DOM ELEMENT (not a frozen DOMRect) so the
+// popover can re-read getBoundingClientRect on each reflow and
+// stay attached to its token through scrolling and resizes.
+// `hotRef` — `{ kind, refId }` cross-link hot state that ties prose tokens to
+// SceneCard chips and bible rows. Lit on hover BEFORE the popover
+// opens, and cleared only when the popover actually closes.
+//
+// Timing: 200ms to open, 150ms grace to close, so the popover doesn't flicker
+// as the cursor crosses a token. While pinned (opened by click), hover-driven
+// opens are ignored — the user explicitly pinned it and shouldn't see it ripped
+// out from under them; they close it first (X or Escape) before another token
+// can take over.
+export default function useTokenPopover() {
+ const [pop, setPop] = useState(null);
+ const [hotRef, setHotRef] = useState(null);
+
+ const openTimerRef = useRef(null);
+ const closeTimerRef = useRef(null);
+ // Mirror of `pop?.pinned` so callbacks can read pinned state without
+ // re-binding (and so setPop updaters stay pure — StrictMode replays the
+ // updater and would emit duplicate setHotRef side effects otherwise).
+ const pinnedRef = useRef(false);
+ useEffect(() => { pinnedRef.current = !!pop?.pinned; }, [pop?.pinned]);
+
+ const clearTimers = useCallback(() => {
+ if (openTimerRef.current) {
+ clearTimeout(openTimerRef.current);
+ openTimerRef.current = null;
+ }
+ if (closeTimerRef.current) {
+ clearTimeout(closeTimerRef.current);
+ closeTimerRef.current = null;
+ }
+ }, []);
+
+ const onTokenEnter = useCallback(({ kind, refId, anchor }) => {
+ if (pinnedRef.current) return;
+ if (closeTimerRef.current) {
+ clearTimeout(closeTimerRef.current);
+ closeTimerRef.current = null;
+ }
+ if (openTimerRef.current) clearTimeout(openTimerRef.current);
+ setHotRef({ kind, refId });
+ openTimerRef.current = setTimeout(() => {
+ setPop({ kind, refId, anchorEl: anchor, pinned: false });
+ }, 200);
+ }, []);
+
+ // Schedule the 150ms grace close. Idempotent: clears any existing close timer
+ // first so rapid enter/leave events can't pile up multiple pending timeouts
+ // that fire later and clear pop/hotRef unexpectedly. The timer also nulls its
+ // own ref after firing so external clearTimeouts on a stale id are a no-op.
+ //
+ // hotRef is only cleared when the popover actually closes (i.e. it wasn't
+ // pinned). When pinned, the popover stays visible and the cross-link
+ // highlights (SceneCard chips / bible rows) must stay lit too — clearing
+ // hotRef there would leave the popover orphaned from its visual targets.
+ const scheduleClose = useCallback(() => {
+ if (closeTimerRef.current) {
+ clearTimeout(closeTimerRef.current);
+ closeTimerRef.current = null;
+ }
+ closeTimerRef.current = setTimeout(() => {
+ closeTimerRef.current = null;
+ if (pinnedRef.current) return;
+ setPop(null);
+ setHotRef(null);
+ }, 150);
+ }, []);
+
+ const onTokenLeave = useCallback(() => {
+ if (openTimerRef.current) {
+ clearTimeout(openTimerRef.current);
+ openTimerRef.current = null;
+ }
+ scheduleClose();
+ }, [scheduleClose]);
+
+ // Cursor crossed from token onto the popover itself: cancel the pending close
+ // so the user can click links inside without it dismissing on them.
+ const onPopoverEnter = useCallback(() => {
+ clearTimers();
+ }, [clearTimers]);
+
+ // Cursor left the popover (and didn't go back to a token): schedule the same
+ // 150ms grace close as token-leave.
+ const onPopoverLeave = useCallback(() => {
+ scheduleClose();
+ }, [scheduleClose]);
+
+ const onTokenClick = useCallback(({ kind, refId, anchor }) => {
+ if (openTimerRef.current) clearTimeout(openTimerRef.current);
+ if (closeTimerRef.current) clearTimeout(closeTimerRef.current);
+ setPop({ kind, refId, anchorEl: anchor, pinned: true });
+ }, []);
+
+ // Closing the popover (whether by Escape, X click, or auto-leave) must also
+ // drop the hot state and any pending hover timers; otherwise SceneCard chips
+ // and bible rows can stay highlighted indefinitely after the cursor has moved
+ // on.
+ const closePopover = useCallback(() => {
+ clearTimers();
+ setPop(null);
+ setHotRef(null);
+ }, [clearTimers]);
+
+ useEffect(() => () => {
+ if (openTimerRef.current) clearTimeout(openTimerRef.current);
+ if (closeTimerRef.current) clearTimeout(closeTimerRef.current);
+ }, []);
+
+ return { pop, hotRef, onTokenEnter, onTokenLeave, onTokenClick, onPopoverEnter, onPopoverLeave, closePopover };
+}