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
Writers Room: Read view, cross-linked storyboard, objects bible, render dock (#203)
[._.]/ Adam Eivy9177d3c02185
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..44ea5ff3b9--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,21 @@+# Unreleased++## Added++### Writers Room — Read view + cross-linked storyboard++A new `?view=read` mode for the Writers Room editor renders prose with scene anchors, inline character/setting/object highlighting, and hover tooltips that show extracted profile details. Hovering a token in the prose rings the matching chip on its scene card and the matching row in the bible; clicking jumps the sidebar to the right tab. Hovering a scene card flashes the matching scene marker in the prose.++Scene cards now use a stronger visual treatment when active (accent ring + tint + faint glow), and "jump to scene" smoothly tweens the textarea (220ms easeInOutCubic) instead of snapping.++A new third extraction kind, **Objects**, extracts recurring symbolic items (the letter, the fedora) alongside Characters and Settings. Editable in a new Objects tab in the storyboard sidebar, with the same AI-fills-blanks merge rule as the other bibles.++### Live render dock++A page-level run dock now slides up from the bottom of the Writers Room while image-gen jobs are queued or rendering. Each row shows the scene label, status, progress bar, ETA, and a per-job stop button; "Stop all" cancels every queued and in-flight render. The dock auto-hides one second after the last job completes.++## Changed++- The "Rendering N scenes…" inline banner inside the Boards tab has been removed; the new run dock subsumes it and is visible from any tab.+- `STORYBOARD_TAB` enum now includes `OBJECTS` between `WORLD` and `SCENES`.+- `ANALYSIS_KINDS` server enum now includes `'objects'`.diff --git a/client/src/components/writers-room/CharactersBible.jsx b/client/src/components/writers-room/CharactersBible.jsxindex d83d1e55ec..6038ac0b62 100644--- a/client/src/components/writers-room/CharactersBible.jsx+++ b/client/src/components/writers-room/CharactersBible.jsx@@ -24,7 +24,7 @@ const CHARACTER_FIELDS = [// Controlled vs. uncontrolled: caller may pass `characters` to keep multiple// mounts in sync (e.g. drawer + storyboard chip count). When omitted we fetch// and own the list so this can stand alone.-export default function CharactersBible({ workId, characters: charactersProp, onCharactersChange, readingTheme = 'dark' }) {+export default function CharactersBible({ workId, characters: charactersProp, onCharactersChange, readingTheme = 'dark', hotRefId = null }) {const [internalCharacters, setInternalCharacters] = useState(charactersProp || []);const characters = charactersProp ?? internalCharacters;const [editingId, setEditingId] = useState(null);@@ -110,8 +110,16 @@ export default function CharactersBible({ workId, characters: charactersProp, on</li>);}+ const isHot = hotRefId === c.id;return (- <li key={c.id} className="border border-port-border rounded">+ <li+ key={c.id}+ className={`border rounded transition-all ${+ isHot+ ? 'border-port-accent ring-2 ring-port-accent/40 shadow-[0_0_0_3px_rgba(59,130,246,0.08)]'+ : 'border-port-border'+ }`}+ ><CharacterRow character={c} onEdit={() => setEditingId(c.id)} readingTheme={readingTheme} /></li>);diff --git a/client/src/components/writers-room/ObjectsBible.jsx b/client/src/components/writers-room/ObjectsBible.jsxnew file mode 100644index 0000000000..60d6def59a--- /dev/null+++ b/client/src/components/writers-room/ObjectsBible.jsx@@ -0,0 +1,289 @@+import { useEffect, useState } from 'react';+import { AlertTriangle, Check, Loader2, Package, Pencil, Plus, Trash2, X } from 'lucide-react';+import toast from '../ui/Toast';+import {+ listWritersRoomObjects,+ createWritersRoomObject,+ updateWritersRoomObject,+ deleteWritersRoomObject,+} from '../../services/apiWritersRoom';+import useMounted from '../../hooks/useMounted';++const OBJECT_FIELDS = [+ { key: 'description', label: 'Description', placeholder: 'Material, color, condition, distinguishing marks. Used in image-gen prompts when this object appears in a scene.', kind: 'multiline', rows: 3 },+ { key: 'significance', label: 'Significance', placeholder: 'Why does this object matter? What does it represent? How does its meaning evolve across scenes?', kind: 'multiline', rows: 2 },+ { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },+];++// Editable recurring-objects bible. Mirrors CharactersBible / SettingsBible.+// Distinct from analysis snapshots — this is the canonical roster that+// survives across `objects` analysis runs and accepts hand-edits.+export default function ObjectsBible({ workId, objects: objectsProp, onObjectsChange, readingTheme = 'dark', hotRefId = null }) {+ const [internalObjects, setInternalObjects] = useState(objectsProp || []);+ const objects = objectsProp ?? internalObjects;+ const [editingId, setEditingId] = useState(null);+ const [creating, setCreating] = useState(false);+ const [loading, setLoading] = useState(false);+ const mountedRef = useMounted();++ useEffect(() => {+ if (objectsProp) return;+ if (!workId) return;+ setLoading(true);+ listWritersRoomObjects(workId)+ .then((list) => { if (mountedRef.current) setInternalObjects(list); })+ .catch(() => { if (mountedRef.current) setInternalObjects([]); })+ .finally(() => { if (mountedRef.current) setLoading(false); });+ }, [workId, objectsProp, mountedRef]);++ const upsert = (next) => {+ const update = (prev) => {+ const idx = prev.findIndex((o) => o.id === next.id);+ const sorted = (arr) => arr.sort((a, b) => (a.name || '').localeCompare(b.name || ''));+ if (idx < 0) return sorted([...prev, next]);+ const copy = [...prev];+ copy[idx] = next;+ return sorted(copy);+ };+ setInternalObjects(update);+ onObjectsChange?.(update(objects));+ };++ const removeOne = (id) => {+ const next = objects.filter((o) => o.id !== id);+ setInternalObjects(next);+ onObjectsChange?.(next);+ };++ return (+ <div className="text-xs">+ <div className="flex items-center justify-between mb-2">+ <div className="text-[11px] text-gray-500">+ {objects.length} object{objects.length === 1 ? '' : 's'} · Recurring symbolic items extracted from prose.+ </div>+ <button+ onClick={() => { setCreating(true); setEditingId(null); }}+ className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-port-accent"+ >+ <Plus size={12} /> Add+ </button>+ </div>++ {loading && objects.length === 0 && (+ <div className="text-gray-500 italic">Loading…</div>+ )}++ {!loading && objects.length === 0 && !creating && (+ <div className="text-gray-500 italic px-1 mb-2">+ No recurring objects yet. Click "Refresh from prose" above to extract them, or add one manually.+ </div>+ )}++ {creating && (+ <ObjectEditor+ workId={workId}+ object={null}+ onSaved={(o) => { upsert(o); setCreating(false); }}+ onCancel={() => setCreating(false)}+ />+ )}++ <ul className="space-y-1.5">+ {objects.map((o) => {+ const isEditing = editingId === o.id;+ if (isEditing) {+ return (+ <li key={o.id}>+ <ObjectEditor+ workId={workId}+ object={o}+ onSaved={(updated) => { upsert(updated); setEditingId(null); }}+ onDeleted={() => { removeOne(o.id); setEditingId(null); }}+ onCancel={() => setEditingId(null)}+ />+ </li>+ );+ }+ const isHot = hotRefId === o.id;+ return (+ <li+ key={o.id}+ className={`border rounded transition-all ${+ isHot+ ? 'border-port-accent ring-2 ring-port-accent/40 shadow-[0_0_0_3px_rgba(59,130,246,0.08)]'+ : 'border-port-border'+ }`}+ >+ <ObjectRow object={o} onEdit={() => setEditingId(o.id)} readingTheme={readingTheme} />+ </li>+ );+ })}+ </ul>+ </div>+ );+}++function ObjectRow({ object, onEdit, readingTheme }) {+ const light = readingTheme === 'light';+ const blanks = OBJECT_FIELDS.filter((f) => {+ if (f.key === 'notes') return false;+ return !String(object[f.key] || '').trim();+ });+ return (+ <div className="px-3 py-2">+ <div className="flex items-start gap-2">+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <Package size={11} className="text-amber-400 shrink-0" />+ <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{object.name}</span>+ {object.aliases?.length > 0 && (+ <span className="text-[10px] text-gray-500 truncate">aka {object.aliases.join(', ')}</span>+ )}+ {object.source === 'ai' && (+ <span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">ai</span>+ )}+ </div>+ {object.description ? (+ <div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>+ {object.description}+ </div>+ ) : (+ <div className="text-[11px] mt-0.5 text-port-warning italic">No description yet</div>+ )}+ {object.significance && (+ <div className="text-[10px] text-gray-500 mt-1">+ <span className="uppercase tracking-wider text-[9px]">Significance:</span> {object.significance}+ </div>+ )}+ {blanks.length > 0 && (+ <div className="text-[10px] text-port-warning mt-1 flex items-center gap-1">+ <AlertTriangle size={9} /> Missing: {blanks.map((f) => f.label.toLowerCase()).join(', ')}+ </div>+ )}+ {object.missingFromProse?.length > 0 && (+ <div className="text-[10px] text-gray-500 mt-1">+ <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {object.missingFromProse.join(', ')}+ </div>+ )}+ </div>+ <button+ onClick={onEdit}+ className="text-gray-500 hover:text-port-accent shrink-0"+ title="Edit object"+ aria-label={`Edit ${object.name}`}+ >+ <Pencil size={11} />+ </button>+ </div>+ </div>+ );+}++function ObjectEditor({ workId, object, onSaved, onDeleted, onCancel }) {+ const isCreate = !object;+ const [draft, setDraft] = useState(() => {+ const seed = {+ name: object?.name || '',+ aliases: (object?.aliases || []).join(', '),+ };+ for (const f of OBJECT_FIELDS) seed[f.key] = object?.[f.key] || '';+ return seed;+ });+ const [saving, setSaving] = useState(false);++ const set = (field) => (e) => setDraft((d) => ({ ...d, [field]: e.target.value }));++ const save = async () => {+ if (!draft.name.trim()) {+ toast.error('Name is required');+ return;+ }+ setSaving(true);+ const payload = {+ name: draft.name.trim(),+ aliases: draft.aliases.split(',').map((a) => a.trim()).filter(Boolean),+ };+ for (const f of OBJECT_FIELDS) payload[f.key] = draft[f.key];+ const result = await (isCreate+ ? createWritersRoomObject(workId, payload)+ : updateWritersRoomObject(workId, object.id, payload)+ ).catch((err) => {+ toast.error(`Save failed: ${err.message}`);+ return null;+ });+ setSaving(false);+ if (!result) return;+ toast.success(`${result.name} saved`);+ onSaved?.(result);+ };++ const remove = async () => {+ if (!object) return;+ setSaving(true);+ const ok = await deleteWritersRoomObject(workId, object.id).then(() => true).catch((err) => {+ toast.error(`Delete failed: ${err.message}`);+ return false;+ });+ setSaving(false);+ if (ok) {+ toast.success(`${object.name} removed`);+ onDeleted?.();+ }+ };++ const inputCls = 'w-full bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200 focus:border-port-accent outline-none';++ return (+ <div className="border border-port-accent/40 rounded p-2 bg-port-card/40 space-y-1.5">+ <div className="flex items-center justify-between gap-2">+ <input+ value={draft.name}+ onChange={set('name')}+ placeholder="the letter, the fedora, her grandmother's locket…"+ className={inputCls}+ autoFocus+ />+ <button+ onClick={onCancel}+ className="text-gray-500 hover:text-white shrink-0"+ aria-label="Cancel edit"+ title="Cancel"+ >+ <X size={12} />+ </button>+ </div>+ <label className="block">+ <span className="text-[9px] uppercase tracking-wider text-gray-500">Aliases (comma-separated)</span>+ <input value={draft.aliases} onChange={set('aliases')} placeholder="the envelope, the note" className={inputCls} />+ </label>+ {OBJECT_FIELDS.map((f) => (+ <label key={f.key} className="block">+ <span className="text-[9px] uppercase tracking-wider text-gray-500">{f.label}</span>+ {f.kind === 'multiline' ? (+ <textarea value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} rows={f.rows || 2} className={`${inputCls} font-sans resize-y`} />+ ) : (+ <input value={draft[f.key]} onChange={set(f.key)} placeholder={f.placeholder} className={inputCls} />+ )}+ </label>+ ))}+ <div className="flex items-center justify-between pt-1">+ {!isCreate ? (+ <button+ onClick={remove}+ disabled={saving}+ className="flex items-center gap-1 text-[10px] text-port-error hover:underline disabled:opacity-50"+ >+ <Trash2 size={10} /> Delete+ </button>+ ) : <span />}+ <button+ onClick={save}+ disabled={saving}+ className="flex items-center gap-1 px-2 py-1 bg-port-accent text-white rounded text-[10px] hover:bg-port-accent/80 disabled:opacity-50"+ >+ {saving ? <Loader2 size={10} className="animate-spin" /> : <Check size={10} />} Save+ </button>+ </div>+ </div>+ );+}diff --git a/client/src/components/writers-room/ProseReader.jsx b/client/src/components/writers-room/ProseReader.jsxnew file mode 100644index 0000000000..d3e1f072cf--- /dev/null+++ b/client/src/components/writers-room/ProseReader.jsx@@ -0,0 +1,162 @@+import { useMemo } from 'react';+import { renderTokenized, useTokenEntries } from './proseTokenizer';++// Splits a markdown-flavored body into a flat list of nodes:+// { kind: 'heading', level, text } ← lines that start with #, ##, ###+// { kind: 'paragraph', text } ← prose (blank-line-separated)+// The Reader walks these into sections; each heading opens a new section.+function splitBody(body) {+ const lines = (body || '').split('\n');+ const out = [];+ let buf = [];+ const flush = () => {+ if (!buf.length) return;+ const text = buf.join('\n').trim();+ buf = [];+ if (text) out.push({ kind: 'paragraph', text });+ };+ for (const line of lines) {+ const m = /^(#{1,3})\s+(.+)$/.exec(line);+ if (m) {+ flush();+ out.push({ kind: 'heading', level: m[1].length, text: m[2].trim() });+ } else if (line.trim() === '') {+ flush();+ } else {+ buf.push(line);+ }+ }+ flush();+ return out;+}++// Group nodes into scene sections. Each top-level heading (# or ##) opens a+// new section; ### become subheadings inside the current section. The first+// content before any heading lives in a synthetic "prologue" section.+function groupIntoSections(nodes, scenes) {+ const sections = [];+ let current = null;+ const findSceneId = (headingText) => {+ const match = scenes.find((s) => (s.heading || '').trim() === headingText);+ return match?.id || null;+ };+ const ensure = () => {+ if (!current) {+ current = { sceneId: null, heading: null, level: 0, blocks: [] };+ sections.push(current);+ }+ };+ for (const n of nodes) {+ if (n.kind === 'heading' && n.level <= 2) {+ current = {+ sceneId: findSceneId(n.text),+ heading: n.text,+ level: n.level,+ blocks: [],+ };+ sections.push(current);+ } else {+ ensure();+ current.blocks.push(n);+ }+ }+ return sections;+}++export default function ProseReader({+ body,+ scenes = [],+ characters = [],+ settings = [],+ objects = [],+ readingTheme = 'dark',+ activeSceneId = null,+ hotRef = null,+ hotScene = null,+ onTokenEnter,+ onTokenLeave,+ onTokenClick,+ onSceneEnter,+ onSceneLeave,+}) {+ const sections = useMemo(() => {+ const nodes = splitBody(body);+ return groupIntoSections(nodes, scenes);+ }, [body, scenes]);++ // Build the token-match index once per (characters, settings, objects)+ // change instead of rebuilding per paragraph. ProseReader passes the+ // pre-built `entries` to renderTokenized so each paragraph only pays the+ // O(text × entries) scan cost, not the index-build cost.+ const entries = useTokenEntries({ characters, settings, objects });++ const light = readingTheme === 'light';++ return (+ <div+ className={`w-full h-full overflow-auto px-6 py-6 font-serif text-base leading-relaxed ${+ light ? 'bg-[var(--wr-reading-paper)] text-gray-900' : 'bg-port-bg text-gray-200'+ }`}+ >+ <div className="max-w-[68ch] mx-auto">+ {sections.length === 0 && (+ <div className={`italic ${light ? 'text-gray-500' : 'text-gray-500'}`}>+ Nothing to read yet — switch back to Edit and start writing.+ </div>+ )}+ {sections.map((sec, i) => {+ const isActive = sec.sceneId && sec.sceneId === activeSceneId;+ const isHot = sec.sceneId && sec.sceneId === hotScene;+ return (+ <section+ key={`${i}-${sec.sceneId || 'pre'}`}+ id={sec.sceneId ? `scene-anchor-${sec.sceneId}` : undefined}+ data-scene-id={sec.sceneId || undefined}+ onMouseEnter={sec.sceneId ? () => onSceneEnter?.(sec.sceneId) : undefined}+ onMouseLeave={sec.sceneId ? () => onSceneLeave?.(sec.sceneId) : undefined}+ className={`mb-8 transition-colors ${+ isHot ? 'bg-port-accent/[0.05] -mx-3 px-3 py-2 rounded' : ''+ }`}+ >+ {sec.heading && (+ <h2+ className={`uppercase tracking-[0.14em] text-[12px] font-medium pb-2 mb-4 border-b ${+ light ? 'border-gray-300 text-gray-600' : 'border-port-border text-gray-400'+ } ${isActive ? '!text-port-accent !border-port-accent/40' : ''}`}+ >+ {sec.heading}+ </h2>+ )}+ {sec.blocks.map((b, j) => {+ if (b.kind === 'heading') {+ return (+ <h3+ key={j}+ className={`text-sm font-semibold mt-4 mb-2 ${+ light ? 'text-gray-700' : 'text-gray-300'+ }`}+ >+ {b.text}+ </h3>+ );+ }+ return (+ <p key={j} className="mb-4 whitespace-pre-wrap text-pretty">+ {renderTokenized(b.text, {+ entries,+ hotRef,+ onTokenEnter,+ onTokenLeave,+ onTokenClick,+ light,+ })}+ </p>+ );+ })}+ </section>+ );+ })}+ </div>+ </div>+ );+}diff --git a/client/src/components/writers-room/ProseTokenPopover.jsx b/client/src/components/writers-room/ProseTokenPopover.jsxnew file mode 100644index 0000000000..03d9b64cd2--- /dev/null+++ b/client/src/components/writers-room/ProseTokenPopover.jsx@@ -0,0 +1,256 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { ExternalLink, X } from 'lucide-react';++// ProseTokenPopover — single fixed-position card driven by hover events from+// inline tokens in ProseReader. Stateless w.r.t. open/close: WorkEditor passes+// `anchorEl` (the token's DOM element-or-null), `kind`, `refId`. The popover+// re-reads getBoundingClientRect on every reflow (scroll, resize, content+// height change) so the card stays attached to the token rather than+// freezing at the rect captured on hover. We resolve refId against the+// characters/settings/objects lists prop'd in.+//+// Hover semantics: 200ms open delay, 150ms close grace handled by the parent+// (WorkEditor) — this component just renders or doesn't.++// Conservative height estimate for the popover. The actual rendered height+// varies (rows/missing/aliases) but is bounded by a hard CSS ceiling on+// content; using a single number keeps the math simple and avoids a+// measure→reposition flicker. A ResizeObserver in the component body+// refines the position any time the popover's actual height changes+// post-mount (font load, dynamic content, viewport changes).+const POPOVER_EST_HEIGHT = 220;+const POPOVER_WIDTH = 320;+const GAP = 6;+const EDGE_PAD = 8;++function clampToViewport(rect, measuredHeight) {+ if (!rect) return null;+ const W = window.innerWidth;+ const H = window.innerHeight;+ const w = POPOVER_WIDTH;+ const h = measuredHeight && measuredHeight > 0 ? measuredHeight : POPOVER_EST_HEIGHT;+ const left = Math.max(EDGE_PAD, Math.min(W - w - EDGE_PAD, rect.left));+ // Flip above the token when there isn't room below for the popover height+ // (was incorrectly comparing against w/2).+ const wouldOverflowBelow = rect.bottom + GAP + h > H - EDGE_PAD;+ const flipped = wouldOverflowBelow && rect.top - GAP - h >= EDGE_PAD;+ const top = flipped+ ? rect.top - GAP - h+ : Math.min(rect.bottom + GAP, Math.max(EDGE_PAD, H - EDGE_PAD - h));+ return { left, top, width: w };+}++function resolveProfile({ kind, refId, characters, settings, objects }) {+ if (kind === 'char') return characters.find((c) => c.id === refId) || null;+ if (kind === 'place') return settings.find((s) => s.id === refId) || null;+ if (kind === 'object') return objects.find((o) => o.id === refId) || null;+ return null;+}++function fieldRows(kind, profile) {+ if (!profile) return [];+ if (kind === 'char') {+ return [+ ['Role', profile.role],+ ['Appearance', profile.physicalDescription],+ ['Personality', profile.personality],+ ['Background', profile.background],+ ].filter(([, v]) => v && String(v).trim());+ }+ if (kind === 'place') {+ return [+ ['Slugline', profile.slugline],+ ['Era', profile.era],+ ['Weather', profile.weather],+ ['Description', profile.description],+ ['Recurring', profile.recurringDetails],+ ].filter(([, v]) => v && String(v).trim());+ }+ if (kind === 'object') {+ return [+ ['Description', profile.description],+ ['Significance', profile.significance],+ ].filter(([, v]) => v && String(v).trim());+ }+ return [];+}++const KIND_DOT = {+ char: 'bg-port-accent',+ place: 'bg-blue-400',+ object: 'bg-amber-400',+};+const KIND_LABEL = {+ char: 'Character',+ place: 'Setting',+ object: 'Object',+};++export default function ProseTokenPopover({+ open,+ pinned,+ anchorEl,+ kind,+ refId,+ characters = [],+ settings = [],+ objects = [],+ onOpenProfile,+ onClose,+ onPopoverEnter,+ onPopoverLeave,+}) {+ const [pos, setPos] = useState(null);+ const cardRef = useRef(null);++ useEffect(() => {+ if (!open || !anchorEl) { setPos(null); return; }+ setPos(clampToViewport(anchorEl.getBoundingClientRect()));+ }, [open, anchorEl]);++ // Once the popover has rendered, observe its actual size and reposition+ // whenever the height changes (font load, dynamic content, viewport+ // resize). The initial estimate-based pos avoids a first-paint flicker.+ // Also re-reads the anchor's live getBoundingClientRect on every reflow so+ // scroll-induced position drift is corrected. Listens for window scroll+ // (capture, so any scrolling ancestor triggers it) and resize so a pinned+ // popover stays attached to its token even as the user scrolls the prose.+ // Reflow is throttled via requestAnimationFrame so a fast scrollwheel+ // can't queue dozens of layout reads per frame; the scroll listener is+ // passive so it doesn't block scrolling itself.+ useEffect(() => {+ if (!open || !anchorEl || !cardRef.current) return undefined;+ const el = cardRef.current;+ const doReflow = () => {+ const rect = anchorEl.getBoundingClientRect();+ const measured = el.offsetHeight;+ const next = clampToViewport(rect, measured);+ if (!next) return;+ setPos((prev) => (+ prev && next.top === prev.top && next.left === prev.left && next.width === prev.width+ ? prev+ : next+ ));+ };+ let rafHandle = 0;+ const reflow = () => {+ if (rafHandle) return;+ rafHandle = requestAnimationFrame(() => {+ rafHandle = 0;+ doReflow();+ });+ };+ doReflow();+ let ro = null;+ if (typeof ResizeObserver !== 'undefined') {+ ro = new ResizeObserver(reflow);+ ro.observe(el);+ }+ const scrollOpts = { capture: true, passive: true };+ window.addEventListener('scroll', reflow, scrollOpts);+ window.addEventListener('resize', reflow);+ return () => {+ if (rafHandle) cancelAnimationFrame(rafHandle);+ if (ro) ro.disconnect();+ window.removeEventListener('scroll', reflow, scrollOpts);+ window.removeEventListener('resize', reflow);+ };+ }, [open, anchorEl, refId, kind]);++ const handleMouseEnter = useCallback(() => {+ onPopoverEnter?.();+ }, [onPopoverEnter]);+ const handleMouseLeave = useCallback(() => {+ if (pinned) return;+ onPopoverLeave?.();+ }, [pinned, onPopoverLeave]);++ // Close on Escape when pinned (mirrors the dropdown patterns in this folder).+ useEffect(() => {+ if (!pinned) return undefined;+ const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [pinned, onClose]);++ if (!open || !pos) return null;++ const profile = resolveProfile({ kind, refId, characters, settings, objects });+ if (!profile) return null;++ const rows = fieldRows(kind, profile);+ const missing = Array.isArray(profile.missingFromProse) ? profile.missingFromProse : [];+ const aliases = Array.isArray(profile.aliases) ? profile.aliases.filter(Boolean) : [];++ // Use role="dialog" because the popover contains interactive controls+ // (Close button when pinned, Open profile button always). role="tooltip"+ // is only correct for non-interactive descriptive content.+ // aria-modal=false: this popover doesn't trap focus or block the page; it's+ // a non-modal floating panel.+ const a11yLabel = `${KIND_LABEL[kind] || 'Profile'}: ${profile.name || profile.slugline || ''}`;+ return (+ <div+ ref={cardRef}+ role="dialog"+ aria-modal="false"+ aria-label={a11yLabel}+ style={{ left: pos.left, top: pos.top, width: pos.width, position: 'fixed' }}+ className="z-40 bg-port-card border border-port-border rounded-lg shadow-2xl p-3 text-xs text-gray-200"+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}+ >+ <div className="flex items-center gap-2 mb-2">+ <span className={`w-2 h-2 rounded-full ${KIND_DOT[kind] || 'bg-gray-400'}`} />+ <span className="font-semibold text-white text-[13px] truncate">{profile.name || profile.slugline}</span>+ <span className="ml-auto text-[10px] uppercase tracking-wider text-gray-500">{KIND_LABEL[kind]}</span>+ {pinned && (+ <button+ type="button"+ onClick={onClose}+ className="text-gray-500 hover:text-gray-200"+ aria-label="Close"+ >+ <X size={12} />+ </button>+ )}+ </div>++ {aliases.length > 0 && (+ <div className="mb-2 text-[10px] text-gray-400">+ a.k.a. {aliases.join(', ')}+ </div>+ )}++ {rows.length === 0 && (+ <div className="text-gray-500 italic mb-2">No profile details yet.</div>+ )}+ {rows.map(([k, v]) => (+ <div key={k} className="flex gap-2 py-1 border-t border-port-border/60 first:border-t-0">+ <span className="text-[10px] uppercase tracking-wider text-gray-500 w-20 shrink-0 pt-0.5">{k}</span>+ <span className="text-gray-200 flex-1 leading-snug">{v}</span>+ </div>+ ))}++ {missing.length > 0 && (+ <div className="mt-2 pt-2 border-t border-port-border/60">+ <div className="text-[10px] uppercase tracking-wider text-port-warning mb-1">Missing from prose</div>+ <div className="flex flex-wrap gap-1">+ {missing.slice(0, 6).map((m, i) => (+ <span key={i} className="text-[10px] px-1.5 py-0.5 rounded bg-port-warning/15 text-port-warning">+ {m}+ </span>+ ))}+ </div>+ </div>+ )}++ <button+ type="button"+ onClick={() => onOpenProfile?.({ kind, refId })}+ className="mt-3 w-full flex items-center justify-center gap-1 px-2 py-1 rounded text-[11px] bg-port-bg hover:bg-port-bg/60 border border-port-border text-gray-300 hover:text-white"+ >+ <ExternalLink size={11} /> Open profile+ </button>+ </div>+ );+}diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsxindex 1dfa562392..c0ca5bf289 100644--- a/client/src/components/writers-room/SceneCard.jsx+++ b/client/src/components/writers-room/SceneCard.jsx@@ -25,6 +25,7 @@ import {const SceneCard = forwardRef(function SceneCard({scene,+ sceneNumber = null,workId,analysisId,workTitle,@@ -37,7 +38,10 @@ const SceneCard = forwardRef(function SceneCard({isActive = false,onJumpToProse = null,onDebug = null,- onRunningChange = null,+ hotRef = null,+ onHoverEnter = null,+ onHoverLeave = null,+ onRenderStart = null,}, ref) {const light = readingTheme === 'light';const matchedCharacters = useMemo(@@ -48,15 +52,19 @@ const SceneCard = forwardRef(function SceneCard({() => matchSceneSetting(scene.slugline, settingByKey),[scene.slugline, settingByKey]);- const matchedNameKeys = useMemo(() => {- const keys = new Set();- for (const c of matchedCharacters) {- keys.add(normCharKey(c.name));- for (const a of c.aliases || []) keys.add(normCharKey(a));+ // Per-chip lookup map — name/alias keys → matched character profile. Built+ // once so the chip render is O(1) per chip instead of an O(chars × aliases)+ // .find()+.some() scan for every chip on every render. Big casts can have+ // dozens of aliases per character; the inner double-loop showed up in+ // perf traces.+ const chipProfileByKey = useMemo(() => {+ const map = new Map();+ for (const profile of matchedCharacters) {+ map.set(normCharKey(profile.name), profile);+ for (const alias of profile.aliases || []) map.set(normCharKey(alias), profile);}- return keys;+ return map;}, [matchedCharacters]);-const [genStatus, setGenStatus] = useState(initialImage ? 'done' : 'idle');const [generated, setGenerated] = useState(initialImage? { path: `/data/images/${initialImage.filename}`, jobId: initialImage.jobId, prompt: initialImage.prompt }@@ -81,14 +89,6 @@ const SceneCard = forwardRef(function SceneCard({useClickOutside(debugMenuRef, showDebugMenu, () => setShowDebugMenu(false));- useEffect(() => {- onRunningChange?.(scene.id, genStatus === 'running');- // Unmount cleanup — without this a card that disappears while running- // (e.g. scene removed from a re-Adapt) leaves a stale entry in the- // parent's running-scene set, which inflates the "Rendering N…" count.- return () => onRunningChange?.(scene.id, false);- }, [scene.id, genStatus, onRunningChange]);-useEffect(() => {const onStarted = (data) => {if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;@@ -177,6 +177,22 @@ const SceneCard = forwardRef(function SceneCard({});if (!res) return;jobIdRef.current = res.jobId || res.generationId || null;+ if (jobIdRef.current && onRenderStart) {+ // The script-shaper output doesn't include a `number` field; the+ // canonical 1-based index is passed from StoryboardPanel as+ // sceneNumber. Fall back to scene.number for any external caller+ // that does set it, then to a generic label.+ const num = scene.number ?? sceneNumber;+ const numLabel = Number.isFinite(num) ? `S${String(num).padStart(2, '0')}` : '';+ const sceneLabel = `${numLabel} ${scene.heading || ''}`.trim()+ || scene.heading+ || 'Scene';+ onRenderStart({+ jobId: jobIdRef.current,+ sceneId: scene.id,+ sceneLabel,+ });+ }setGenerated({ path: res.path, jobId: res.jobId, prompt });if (res.status !== 'queued' && res.status !== 'running') {setGenStatus('done');@@ -214,15 +230,26 @@ const SceneCard = forwardRef(function SceneCard({: 'placeholder';const cardBorder = isActive- ? 'border-port-accent shadow-[0_0_0_1px_rgba(59,130,246,0.5)]'+ ? 'border-port-accent ring-2 ring-port-accent/20 shadow-[0_0_0_3px_rgba(59,130,246,0.08)]': light ? 'border-gray-300' : 'border-port-border';+ const cardBg = isActive+ ? (light ? 'bg-port-accent/10 text-gray-900' : 'bg-port-accent/[0.06]')+ : (light ? 'bg-[var(--wr-reading-paper)] text-gray-900' : 'bg-port-card/40');++ // hotRef shape: {kind, refId} or null. Char hot state rings the matching+ // name chip; place hot state rings the slugline. Object hot state has no+ // SceneCard surface today (no per-scene object chip) — it only highlights+ // the matching ObjectsBible row in the sidebar; if a scene-card object+ // affordance is added later, plumb a hotObjectId here.+ const hotCharId = hotRef?.kind === 'char' ? hotRef.refId : null;+ const hotPlaceId = hotRef?.kind === 'place' ? hotRef.refId : null;return (<divdata-scene-id={scene.id}- className={`border rounded-lg p-2 space-y-1.5 transition-colors ${cardBorder} ${- light ? 'bg-[var(--wr-reading-paper)] text-gray-900' : 'bg-port-card/40'- }`}+ onMouseEnter={onHoverEnter || undefined}+ onMouseLeave={onHoverLeave || undefined}+ className={`border rounded-lg p-2 space-y-1.5 transition-colors ${cardBorder} ${cardBg}`}><div className="flex items-start gap-2"><button@@ -236,7 +263,13 @@ const SceneCard = forwardRef(function SceneCard({{scene.heading}</div>{scene.slugline && (- <div className="text-[10px] text-port-accent uppercase tracking-wide truncate">+ <div+ className={`text-[10px] uppercase tracking-wide truncate transition-all ${+ hotPlaceId && matchedSetting?.id === hotPlaceId+ ? 'text-white bg-port-accent/30 ring-1 ring-port-accent rounded px-1 -mx-1'+ : 'text-port-accent'+ }`}+ >{scene.slugline}</div>)}@@ -333,15 +366,19 @@ const SceneCard = forwardRef(function SceneCard({{scene.characters?.length > 0 && (<div className="flex flex-wrap gap-1">{scene.characters.map((c, i) => {- const isMatched = matchedNameKeys.has(normCharKey(c));+ const matchedProfile = chipProfileByKey.get(normCharKey(c)) || null;+ const isMatched = !!matchedProfile;+ const isHot = isMatched && hotCharId && matchedProfile.id === hotCharId;return (<spankey={i}title={isMatched ? 'Profile linked' : 'No matching profile'}- className={`px-1.5 py-0.5 border rounded text-[9px] uppercase tracking-wider ${- isMatched- ? 'border-port-accent text-port-accent bg-port-accent/10'- : light ? 'bg-white border-gray-300 text-gray-700' : 'bg-port-bg border-port-border'+ className={`px-1.5 py-0.5 border rounded text-[9px] uppercase tracking-wider transition-all ${+ isHot+ ? 'border-port-accent text-white bg-port-accent/30 ring-1 ring-port-accent'+ : isMatched+ ? 'border-port-accent text-port-accent bg-port-accent/10'+ : light ? 'bg-white border-gray-300 text-gray-700' : 'bg-port-bg border-port-border'}`}>{c}</span>diff --git a/client/src/components/writers-room/SettingsBible.jsx b/client/src/components/writers-room/SettingsBible.jsxindex d291dde486..45f8e73b71 100644--- a/client/src/components/writers-room/SettingsBible.jsx+++ b/client/src/components/writers-room/SettingsBible.jsx@@ -24,7 +24,7 @@ const SETTING_FIELDS = [// Controlled vs. uncontrolled: caller may pass `settings` to keep multiple// mounts in sync (e.g. drawer + storyboard chip count). When omitted we fetch// and own the list so this can stand alone.-export default function SettingsBible({ workId, settings: settingsProp, onSettingsChange, readingTheme = 'dark' }) {+export default function SettingsBible({ workId, settings: settingsProp, onSettingsChange, readingTheme = 'dark', hotRefId = null }) {const [internalSettings, setInternalSettings] = useState(settingsProp || []);const settings = settingsProp ?? internalSettings;const [editingId, setEditingId] = useState(null);@@ -110,8 +110,16 @@ export default function SettingsBible({ workId, settings: settingsProp, onSettin</li>);}+ const isHot = hotRefId === s.id;return (- <li key={s.id} className="border border-port-border rounded">+ <li+ key={s.id}+ className={`border rounded transition-all ${+ isHot+ ? 'border-port-accent ring-2 ring-port-accent/40 shadow-[0_0_0_3px_rgba(59,130,246,0.08)]'+ : 'border-port-border'+ }`}+ ><SettingRow setting={s} onEdit={() => setEditingId(s.id)} readingTheme={readingTheme} /></li>);diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsxindex dc7b0a745e..5a4f110c52 100644--- a/client/src/components/writers-room/StoryboardPanel.jsx+++ b/client/src/components/writers-room/StoryboardPanel.jsx@@ -2,8 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useSearchParams } from 'react-router-dom';import {Clapperboard, Loader2, RefreshCcw, AlertTriangle, Palette, Check, Dice5, Cpu,- Users, MapPin as MapPinIcon, ArrowRight, ListTree, SlidersHorizontal, Square,- Settings as SettingsIcon,+ Users, MapPin as MapPinIcon, ArrowRight, ListTree, SlidersHorizontal,+ Settings as SettingsIcon, Package,} from 'lucide-react';import { randomSeed } from '../../lib/genUtils';import toast from '../ui/Toast';@@ -12,7 +12,7 @@ import {getWritersRoomAnalysis,} from '../../services/apiWritersRoom';import { getSettings, updateSettings, listImageStylePresets } from '../../services/apiSystem';-import { listImageModels, cancelImageGen } from '../../services/apiImageVideo';+import { listImageModels } from '../../services/apiImageVideo';import BackendChipStrip from '../media/BackendChipStrip';import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../../lib/imageGenBackends';import { timeAgo } from '../../utils/formatters';@@ -23,6 +23,7 @@ import SceneCard from './SceneCard';import StagePromptModelPicker from './StagePromptModelPicker';import CharactersBible from './CharactersBible';import SettingsBible from './SettingsBible';+import ObjectsBible from './ObjectsBible';import {WR_IMAGE_DEFAULTS,buildCharByKey,@@ -47,6 +48,7 @@ function groupPresetsByCategory(presets) {export const STORYBOARD_TAB = {CHARACTERS: 'characters',WORLD: 'world',+ OBJECTS: 'objects',SCENES: 'scenes',BOARDS: 'boards',CONFIG: 'config',@@ -57,6 +59,7 @@ export const STORYBOARD_TAB_VALUES = Object.values(TAB);const RUN_LABEL = {characters: 'Refreshing characters',settings: 'Refreshing world',+ objects: 'Refreshing objects',script: 'Running Adapt',evaluate: 'Editorial pass',format: 'Format pass',@@ -79,6 +82,13 @@ export default function StoryboardPanel({onStyleChange,onCharactersChange,onSettingsChange,+ onScenesChange,+ objects = [],+ onObjectsChange,+ onRunObjects,+ hotRef = null,+ onSceneHover,+ onSceneRenderStart,tab,onTabChange,}) {@@ -203,47 +213,6 @@ export default function StoryboardPanel({// Map keyed by sceneId — replaced wholesale on each script load.const sceneRefs = useRef({});- // Track which scenes are actively rendering so the Boards tab can show a- // "Cancel renders" CTA. SceneCard fires onRunningChange when its local- // genStatus toggles. Storing the Set as state (not ref) so the count- // re-renders the cancel button reactively.- const [runningSceneIds, setRunningSceneIds] = useState(() => new Set());- const handleSceneRunningChange = useCallback((sceneId, running) => {- setRunningSceneIds((prev) => {- const has = prev.has(sceneId);- if (running === has) return prev;- const next = new Set(prev);- if (running) next.add(sceneId);- else next.delete(sceneId);- return next;- });- }, []);- // Drop stale running-scene entries when the script reloads — old sceneIds- // may not exist in the new render.- useEffect(() => {- setRunningSceneIds(new Set());- }, [latestScript?.id]);-- const cancelAllRenders = useCallback(async () => {- if (runningSceneIds.size === 0) return;- // Issue server cancel first so background work actually stops, then wipe- // local state on every running card so the UI returns to idle without- // waiting for the cancellation socket events to round-trip.- await cancelImageGen({ all: true }).catch((err) => {- toast.error(`Cancel failed: ${err.message}`);- });- // Reset every previously-running card unconditionally — if a- // cancellation 'failed' socket event raced ahead and flipped the card to- // 'error', isRunning() would return false, but we still want the card- // back at idle so the user can retry. cancel() is idempotent.- const total = runningSceneIds.size;- for (const sceneId of runningSceneIds) {- sceneRefs.current[sceneId]?.cancel?.();- }- setRunningSceneIds(new Set());- if (total > 0) toast(`Stopped ${total} render${total === 1 ? '' : 's'}`, { icon: '🛑' });- }, [runningSceneIds]);-// Auto-queue every missing image when latestScript updates *because* of a// just-finished Adapt run. requestAnimationFrame defers until the cards// have actually mounted with the new scenes — useImperativeHandle has to@@ -295,6 +264,16 @@ export default function StoryboardPanel({const scenes = latestScript?.result?.scenes || [];const sceneImages = latestScript?.sceneImages || {};+ // Surface the scene list up to WorkEditor (for ProseReader anchors). Fires+ // every time latestScript changes, including the initial null load.+ useEffect(() => {+ onScenesChange?.(scenes);+ // We intentionally key on latestScript identity rather than scenes (which+ // is recreated each render) — array identity changes coincide with the+ // analysis snapshot changing.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [latestScript]);+return (<div className="flex flex-col h-full"><TabNav@@ -303,6 +282,7 @@ export default function StoryboardPanel({runningKind={runningKind}charactersCount={characters.length}settingsCount={settings.length}+ objectsCount={objects.length}scenesCount={scenesCount}boardsCount={scenes.length}/>@@ -325,6 +305,7 @@ export default function StoryboardPanel({running={runningKind === 'characters'}anyRunning={!!runningKind}readingTheme={readingTheme}+ hotRefId={hotRef?.kind === 'char' ? hotRef.refId : null}/>)}{tab === TAB.WORLD && (@@ -337,6 +318,20 @@ export default function StoryboardPanel({running={runningKind === 'settings'}anyRunning={!!runningKind}readingTheme={readingTheme}+ hotRefId={hotRef?.kind === 'place' ? hotRef.refId : null}+ />+ )}+ {tab === TAB.OBJECTS && (+ <BibleTab+ kind="objects"+ workId={work.id}+ items={objects}+ onItemsChange={onObjectsChange}+ onRefresh={onRunObjects}+ running={runningKind === 'objects'}+ anyRunning={!!runningKind}+ readingTheme={readingTheme}+ hotRefId={hotRef?.kind === 'object' ? hotRef.refId : null}/>)}{tab === TAB.SCENES && (@@ -361,7 +356,6 @@ export default function StoryboardPanel({sceneRefs={sceneRefs}onJumpToScene={onJumpToScene}onDebug={onDebug}- onSceneRunningChange={handleSceneRunningChange}onRunAdapt={onRunAdapt}onRunCharacters={onRunCharacters}onRunSettings={onRunSettings}@@ -371,8 +365,9 @@ export default function StoryboardPanel({readingTheme={readingTheme}activeSceneId={activeSceneId}onOpenConfig={() => setTab(TAB.CONFIG)}- runningRenderCount={runningSceneIds.size}- onCancelRenders={cancelAllRenders}+ hotRef={hotRef}+ onSceneHover={onSceneHover}+ onSceneRenderStart={onSceneRenderStart}/>)}{tab === TAB.CONFIG && (@@ -402,12 +397,14 @@ function TabNav({runningKind,charactersCount,settingsCount,+ objectsCount,scenesCount,boardsCount,}) {const tabs = [{ id: TAB.CHARACTERS, label: 'Characters', icon: Users, count: charactersCount, runningWhen: 'characters' },{ id: TAB.WORLD, label: 'World', icon: MapPinIcon, count: settingsCount, runningWhen: 'settings' },+ { id: TAB.OBJECTS, label: 'Objects', icon: Package, count: objectsCount, runningWhen: 'objects' },{ id: TAB.SCENES, label: 'Scenes', icon: ListTree, count: scenesCount, runningWhen: null },{ id: TAB.BOARDS, label: 'Boards', icon: Clapperboard, count: boardsCount, runningWhen: 'script' },{ id: TAB.CONFIG, label: 'Config', icon: SlidersHorizontal, count: null, runningWhen: null },@@ -465,9 +462,17 @@ const BIBLE_KINDS = {propName: 'settings',changeProp: 'onSettingsChange',},+ objects: {+ label: 'Recurring objects',+ sub: 'Symbolic / recurring items the prose returns to',+ refreshNoun: 'objects',+ Component: ObjectsBible,+ propName: 'objects',+ changeProp: 'onObjectsChange',+ },};-function BibleTab({ kind, workId, items, onItemsChange, onRefresh, running, anyRunning, readingTheme }) {+function BibleTab({ kind, workId, items, onItemsChange, onRefresh, running, anyRunning, readingTheme, hotRefId = null }) {const meta = BIBLE_KINDS[kind];const Bible = meta.Component;const bibleProps = {@@ -475,6 +480,7 @@ function BibleTab({ kind, workId, items, onItemsChange, onRefresh, running, anyR[meta.propName]: items,[meta.changeProp]: onItemsChange,readingTheme,+ hotRefId,};return (<div className="px-3 py-3 space-y-3">@@ -571,7 +577,6 @@ function BoardsTab({sceneRefs,onJumpToScene,onDebug,- onSceneRunningChange,onRunAdapt,onRunCharacters,onRunSettings,@@ -581,29 +586,14 @@ function BoardsTab({readingTheme,activeSceneId,onOpenConfig,- runningRenderCount = 0,- onCancelRenders,+ hotRef = null,+ onSceneHover,+ onSceneRenderStart,}) {return (<div className="px-3 py-3 space-y-2">- {runningRenderCount > 0 && (- <div className="flex items-center justify-between gap-2 px-2.5 py-1.5 mb-1 border border-port-warning/40 bg-port-warning/5 rounded text-[11px]">- <div className="flex items-center gap-2 min-w-0">- <Loader2 size={11} className="animate-spin text-port-warning shrink-0" />- <span className="text-port-warning truncate">- Rendering {runningRenderCount} scene{runningRenderCount === 1 ? '' : 's'}…- </span>- </div>- <button- type="button"- onClick={onCancelRenders}- className="shrink-0 flex items-center gap-1 px-2 py-1 bg-port-error/15 border border-port-error/40 text-port-error rounded text-[10px] hover:bg-port-error/25"- title="Cancel every queued and in-flight scene render"- >- <Square size={10} /> Stop all- </button>- </div>- )}+ {/* Live rendering status moved to the page-level WritersRoomDock so it's+ visible from any tab, not just Boards. */}{latestScript && (<div className="flex items-center gap-2 pb-2 text-[10px] text-gray-500"><span>{scenes.length} scene{scenes.length === 1 ? '' : 's'} · {timeAgo(latestScript.completedAt || latestScript.createdAt, 'never')}</span>@@ -678,6 +668,7 @@ function BoardsTab({else delete sceneRefs.current[sceneId];}}scene={{ ...scene, id: sceneId }}+ sceneNumber={i + 1}workId={work.id}analysisId={latestScript.id}workTitle={work.title}@@ -690,7 +681,10 @@ function BoardsTab({isActive={sceneId === activeSceneId}onJumpToProse={onJumpToScene ? () => onJumpToScene(scene, i, scenes.length) : null}onDebug={onDebug}- onRunningChange={onSceneRunningChange}+ hotRef={hotRef}+ onHoverEnter={onSceneHover ? () => onSceneHover(sceneId) : null}+ onHoverLeave={onSceneHover ? () => onSceneHover(null) : null}+ onRenderStart={onSceneRenderStart}/>);})}diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex e9a13892cf..d19de6cc5f 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -1,4 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useSearchParams } from 'react-router-dom';import {Save,GitCommit,@@ -16,6 +17,8 @@ import {PenLine,Check,Loader2,+ BookOpen,+ Pencil,} from 'lucide-react';import toast from '../ui/Toast';import Drawer from '../Drawer';@@ -29,13 +32,18 @@ import {runWritersRoomAnalysis,listWritersRoomCharacters,listWritersRoomSettings,+ listWritersRoomObjects,} from '../../services/apiWritersRoom';import { STATUS_LABELS } from './labels';import { countWords } from '../../utils/formatters';import StoryboardPanel, { STORYBOARD_TAB, STORYBOARD_TAB_VALUES } from './StoryboardPanel';import AnalysisHistory from './AnalysisHistory';+import ProseReader from './ProseReader';+import ProseTokenPopover from './ProseTokenPopover';+import WritersRoomDock from './WritersRoomDock';+import useImageGenQueue from '../../hooks/useImageGenQueue';-const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', SETTINGS: 'settings', EVALUATE: 'evaluate', FORMAT: 'format' };+const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', SETTINGS: 'settings', OBJECTS: 'objects', EVALUATE: 'evaluate', FORMAT: 'format' };const DRAWER = { VERSIONS: 'versions', HISTORY: 'history' };const MOBILE_TAB = { WRITING: 'writing', STORYBOARD: 'storyboard' };@@ -43,6 +51,7 @@ const ANALYSIS_LABELS = {[ANALYSIS_KIND.SCRIPT]: 'Adapt',[ANALYSIS_KIND.CHARACTERS]: 'Characters',[ANALYSIS_KIND.SETTINGS]: 'Settings',+ [ANALYSIS_KIND.OBJECTS]: 'Objects',[ANALYSIS_KIND.EVALUATE]: 'Editorial pass',[ANALYSIS_KIND.FORMAT]: 'Format pass',};@@ -87,19 +96,203 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOconst [readingTheme, setReadingTheme] = useState(readReadingTheme);const [characters, setCharacters] = useState([]);const [settings, setSettings] = useState([]);+ const [objects, setObjects] = useState([]);const [runningKind, setRunningKind] = useState(null);const [drawer, setDrawer] = useState(null);const [overflowOpen, setOverflowOpen] = useState(false);const [mobileTab, setMobileTab] = useState(MOBILE_TAB.WRITING);const [activeSceneId, setActiveSceneId] = useState(null);const [sidebarTab, setSidebarTab] = useState(readSidebarTab);+ // 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);+ 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+ // can label rows; the hook subscribes to image-gen:* socket events globally.+ const {+ queue: renderQueue,+ renderingCount: renderRenderingCount,+ cancelingCount: renderCancelingCount,+ activeCount: renderActiveCount,+ register: queueRegister,+ stopAll: queueStopAll,+ stopOne: queueStopOne,+ } = useImageGenQueue();++ // View mode (Edit | Read) is URL-driven so it deep-links and survives reloads.+ // ?view=read switches to ProseReader; default is the existing textarea.+ const [searchParams, setSearchParams] = useSearchParams();+ const viewMode = searchParams.get('view') === 'read' ? 'read' : 'edit';+ const setViewMode = useCallback((mode) => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ if (mode === 'read') next.set('view', 'read'); else next.delete('view');+ return next;+ }, { replace: true });+ }, [setSearchParams]);useEffect(() => {try { window.localStorage.setItem(SIDEBAR_TAB_KEY, sidebarTab); } catch { /* sandboxed storage */ }}, [sidebarTab]);const textareaRef = useRef(null);+ 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]);+ const handleOpenProfile = useCallback(({ kind }) => {+ clearPopTimers();+ setPop(null);+ setHotRef(null);+ 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);+ }, []);++ const smoothScrollTextarea = useCallback((ta, targetTop, ms = 220) => {+ if (!ta) return;+ if (scrollAnimRef.current) {+ cancelAnimationFrame(scrollAnimRef.current);+ scrollAnimRef.current = null;+ }+ const startTop = ta.scrollTop;+ const delta = targetTop - startTop;+ if (Math.abs(delta) < 1) { ta.scrollTop = targetTop; return; }+ const startTs = performance.now();+ const ease = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);+ const step = (ts) => {+ const elapsed = ts - startTs;+ const t = Math.min(1, elapsed / ms);+ ta.scrollTop = startTop + delta * ease(t);+ if (t < 1) {+ scrollAnimRef.current = requestAnimationFrame(step);+ } else {+ scrollAnimRef.current = null;+ }+ };+ scrollAnimRef.current = requestAnimationFrame(step);+ }, []);++ useEffect(() => () => {+ if (scrollAnimRef.current) cancelAnimationFrame(scrollAnimRef.current);+ }, []);// Rehydrate body/title when the parent swaps the active work OR switches to// a different draft version of the same work.@@ -123,9 +316,11 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOPromise.all([listWritersRoomCharacters(work.id).catch(() => []),listWritersRoomSettings(work.id).catch(() => []),- ]).then(([chars, sets]) => {+ listWritersRoomObjects(work.id).catch(() => []),+ ]).then(([chars, sets, objs]) => {setCharacters(chars || []);setSettings(sets || []);+ setObjects(objs || []);});}, [work.id]);@@ -261,6 +456,9 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOif (kind === 'settings' && Array.isArray(snapshot.result?.mergedProfiles)) {setSettings(snapshot.result.mergedProfiles);}+ if (kind === 'objects' && Array.isArray(snapshot.result?.mergedProfiles)) {+ setObjects(snapshot.result.mergedProfiles);+ }if (kind === 'format' && snapshot.result?.formattedBody) {setBody(snapshot.result.formattedBody);toast('Format applied to draft buffer — save to persist', { icon: '💾' });@@ -296,10 +494,24 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO// always re-scroll on focus alone if the caret was already visible, so we// always set scrollTop explicitly after focusing.const jumpToScene = useCallback((scene, sceneIndex = -1, totalScenes = 0) => {- const ta = textareaRef.current;- if (!ta || !scene || !body) return;+ if (!scene) return;setActiveSceneId(scene.id || null);setMobileTab(MOBILE_TAB.WRITING);++ // Read view: each scene section has a stable DOM anchor — scrollIntoView+ // is the natural fit and animates by default in modern browsers.+ if (viewMode === 'read' && scene.id) {+ const reader = readerRef.current;+ const el = reader?.querySelector?.(`#scene-anchor-${CSS.escape(scene.id)}`);+ if (el) {+ el.scrollIntoView({ behavior: 'smooth', block: 'start' });+ return;+ }+ // Fall through to the textarea path if the section wasn't found.+ }++ const ta = textareaRef.current;+ if (!ta || !body) return;const heading = scene.heading || '';let idx = -1;for (const prefix of ['## ', '### ', '# ', '']) {@@ -328,8 +540,8 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO} else {return;}- ta.scrollTop = target;- }, [body]);+ smoothScrollTextarea(ta, target);+ }, [body, viewMode, smoothScrollTextarea]);// Per-scene Debug menu actions — until scoped tools land, route to the// most relevant tab/drawer.@@ -416,6 +628,33 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO>{Object.entries(STATUS_LABELS).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select>+ {/* Two-state toggle, not a true tablist (no separate panels keyed off+ tab id, no roving tabindex, no arrow-key cycling). aria-pressed is+ the semantically correct primitive for an on/off-style toggle pair. */}+ <div className="flex items-center bg-port-bg border border-port-border rounded p-0.5" role="group" aria-label="View mode">+ <button+ type="button"+ aria-pressed={viewMode === 'edit'}+ onClick={() => setViewMode('edit')}+ className={`flex items-center gap-1 px-2 py-0.5 text-[11px] rounded ${+ viewMode === 'edit' ? 'bg-port-card text-white' : 'text-gray-400 hover:text-gray-200'+ }`}+ title="Edit prose (textarea)"+ >+ <Pencil size={11} /> Edit+ </button>+ <button+ type="button"+ aria-pressed={viewMode === 'read'}+ onClick={() => setViewMode('read')}+ className={`flex items-center gap-1 px-2 py-0.5 text-[11px] rounded ${+ viewMode === 'read' ? 'bg-port-card text-white' : 'text-gray-400 hover:text-gray-200'+ }`}+ title="Read view with scene anchors"+ >+ <BookOpen size={11} /> Read+ </button>+ </div><buttononClick={handleSave}disabled={!dirty || saving}@@ -483,21 +722,53 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO<MobileTab active={mobileTab === MOBILE_TAB.STORYBOARD} onClick={() => setMobileTab(MOBILE_TAB.STORYBOARD)} icon={Clapperboard} label="Storyboard" /></div>- <div ref={splitRef} className="flex-1 flex flex-col lg:flex-row min-h-0">+ {/*+ When the render dock is visible (queue non-empty) it's `position: fixed`+ at the bottom of the viewport. Add a conservative bottom inset to the+ split so the dock doesn't overlap the textarea, the Read view, the+ word-count overlay, or the storyboard scroll area. Tracks the dock's+ own measured height (~52px); a few px of slack is fine.+ */}+ <div+ ref={splitRef}+ className="flex-1 flex flex-col lg:flex-row min-h-0"+ style={renderQueue.length ? { paddingBottom: 56 } : undefined}+ ><div className={`relative min-h-0 flex-1 ${mobileTab === MOBILE_TAB.STORYBOARD ? 'hidden lg:block' : 'block'}`}>- <textarea- ref={textareaRef}- value={body}- onChange={(e) => setBody(e.target.value)}- placeholder="Start writing… Use # Chapter, ## Scene, ### Beat headings to outline."- style={readingTheme === 'light'- ? { '--port-input-bg': 'var(--wr-reading-paper)', color: '#1a1a1a' }- : undefined}- className="w-full h-full resize-none px-6 py-6 font-serif text-base leading-relaxed focus:outline-none"- spellCheck- />+ {viewMode === 'read' ? (+ <div ref={readerRef} className="w-full h-full">+ <ProseReader+ body={body}+ scenes={latestScenes}+ characters={characters}+ settings={settings}+ objects={objects}+ readingTheme={readingTheme}+ activeSceneId={activeSceneId}+ hotRef={hotRef}+ hotScene={hotScene}+ onTokenEnter={handleTokenEnter}+ onTokenLeave={handleTokenLeave}+ onTokenClick={handleTokenClick}+ onSceneEnter={setHotScene}+ onSceneLeave={() => setHotScene(null)}+ />+ </div>+ ) : (+ <textarea+ ref={textareaRef}+ value={body}+ onChange={(e) => setBody(e.target.value)}+ placeholder="Start writing… Use # Chapter, ## Scene, ### Beat headings to outline."+ style={readingTheme === 'light'+ ? { '--port-input-bg': 'var(--wr-reading-paper)', color: '#1a1a1a' }+ : undefined}+ className="w-full h-full resize-none px-6 py-6 font-serif text-base leading-relaxed focus:outline-none"+ spellCheck+ />+ )}<div- className={`absolute bottom-2 right-3 flex items-center gap-3 text-[11px] px-2 py-1 rounded ${+ className={`absolute bottom-2 right-3 flex items-center gap-3 text-[11px] px-2 py-1 rounded pointer-events-none ${readingTheme === 'light' ? 'text-gray-700 bg-[var(--wr-reading-paper)]/85' : 'text-gray-500 bg-port-bg/80'}`}>@@ -529,8 +800,12 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOwork={work}characters={characters}settings={settings}+ objects={objects}onCharactersChange={setCharacters}onSettingsChange={setSettings}+ onObjectsChange={setObjects}+ onRunObjects={() => runAnalysis(ANALYSIS_KIND.OBJECTS)}+ onScenesChange={setLatestScenes}onJumpToScene={jumpToScene}onDebug={handleDebug}onRunAdapt={() => runAnalysis(ANALYSIS_KIND.SCRIPT)}@@ -542,12 +817,39 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOreadingTheme={readingTheme}activeSceneId={activeSceneId}onStyleChange={commitImageStyle}+ hotRef={hotRef}+ onSceneHover={setHotScene}+ onSceneRenderStart={queueRegister}tab={sidebarTab}onTabChange={setSidebarTab}/></aside></div>+ <ProseTokenPopover+ open={!!pop}+ pinned={!!pop?.pinned}+ anchorEl={pop?.anchorEl || null}+ kind={pop?.kind}+ refId={pop?.refId}+ characters={characters}+ settings={settings}+ objects={objects}+ onOpenProfile={handleOpenProfile}+ onClose={handlePopClose}+ onPopoverEnter={handlePopoverEnter}+ onPopoverLeave={handlePopoverLeave}+ />++ <WritersRoomDock+ queue={renderQueue}+ renderingCount={renderRenderingCount}+ cancelingCount={renderCancelingCount}+ activeCount={renderActiveCount}+ onStopAll={queueStopAll}+ onStopOne={queueStopOne}+ />+<Drawer open={drawer === DRAWER.VERSIONS} onClose={() => setDrawer(null)} title="Versions"><VersionsList work={work} dirty={dirty} onSwitch={(id) => { switchToDraft(id); setDrawer(null); }} /></Drawer>diff --git a/client/src/components/writers-room/WritersRoomDock.jsx b/client/src/components/writers-room/WritersRoomDock.jsxnew file mode 100644index 0000000000..b8ea2aee08--- /dev/null+++ b/client/src/components/writers-room/WritersRoomDock.jsx@@ -0,0 +1,111 @@+import { Loader2, Square, Check, AlertTriangle } from 'lucide-react';++// WritersRoomDock — fixed-bottom run queue strip. Renders only when there are+// active or recently-finished jobs in `queue`; auto-hides otherwise.+// `queue` shape: [{ jobId, sceneId, sceneLabel, status, progress, eta }].+//+// Mounted at WritersRoom layer (per page) — NOT in the global Layout footer.+// Kept narrow so it doesn't dominate the page when one or two scenes are+// rendering, expands inline as more queue up.+export default function WritersRoomDock({+ queue = [],+ renderingCount = 0,+ cancelingCount = 0,+ activeCount = renderingCount + cancelingCount,+ onStopAll,+ onStopOne,+}) {+ if (!queue.length) return null;+ // Three distinct user-facing states, in priority order: actively rendering+ // → canceling → done. Showing "Rendering N" while N jobs are canceling+ // would be misleading.+ const statusLabel = renderingCount > 0+ ? `Rendering ${renderingCount} scene${renderingCount === 1 ? '' : 's'}`+ : cancelingCount > 0+ ? `Canceling ${cancelingCount} scene${cancelingCount === 1 ? '' : 's'}…`+ : 'Renders complete';+ return (+ <section+ aria-label="Image render queue"+ className="fixed bottom-0 left-0 right-0 z-30 border-t border-port-border bg-port-card/95 backdrop-blur-sm shadow-[0_-4px_18px_-8px_rgba(0,0,0,0.6)]"+ >+ <div className="flex items-center gap-3 px-3 py-2 max-w-7xl mx-auto">+ <div className="flex items-center gap-2 shrink-0">+ {activeCount > 0+ ? <Loader2 size={12} className="animate-spin text-port-accent" />+ : <Check size={12} className="text-port-success" />+ }+ {/* aria-live lives on this small non-interactive label only — putting+ it on the dock container made screen readers re-announce the+ cancel buttons every progress tick. */}+ <span+ role="status"+ aria-live="polite"+ className="text-[11px] font-semibold text-white"+ >+ {statusLabel}+ </span>+ </div>+ <div className="flex-1 min-w-0 flex items-center gap-2 overflow-x-auto">+ {queue.map((q) => <DockItem key={q.jobId} item={q} onStop={onStopOne} />)}+ </div>+ {/* Only offer Stop-all while rows are still actively rendering — once+ everything is canceling there's nothing left to stop. */}+ {renderingCount > 0 && (+ <button+ type="button"+ onClick={onStopAll}+ className="shrink-0 flex items-center gap-1 px-2.5 py-1 bg-port-error/15 border border-port-error/40 text-port-error rounded text-[11px] hover:bg-port-error/25"+ title="Cancel every queued and in-flight render"+ >+ <Square size={11} /> Stop all+ </button>+ )}+ </div>+ </section>+ );+}++function DockItem({ item, onStop }) {+ const { sceneLabel, status, progress, eta } = item;+ const pct = typeof progress === 'number' ? Math.round(progress * 100) : 0;+ const tone =+ status === 'error' ? 'border-port-error/60 text-port-error'+ : status === 'done' ? 'border-port-success/60 text-port-success'+ : status === 'canceling' ? 'border-port-warning/60 text-port-warning'+ : status === 'running' ? 'border-port-accent/60 text-gray-200'+ : 'border-port-border text-gray-300';+ return (+ <div className={`relative shrink-0 flex items-center gap-2 px-2.5 py-1 rounded-md border ${tone} bg-port-bg/40 text-[11px] min-w-[180px] max-w-[280px]`}>+ <span className="truncate flex-1" title={sceneLabel}>{sceneLabel}</span>+ {status === 'queued' && <span className="text-[9px] uppercase tracking-wider text-gray-500">Queued</span>}+ {status === 'running' && (+ <>+ <span className="text-[10px] tabular-nums text-gray-400">{pct}%</span>+ {eta != null && <span className="text-[10px] text-gray-500">~{Math.max(0, Math.round(eta))}s</span>}+ </>+ )}+ {status === 'canceling' && (+ <span className="text-[9px] uppercase tracking-wider text-port-warning">Canceling…</span>+ )}+ {status === 'done' && <Check size={10} />}+ {status === 'error' && <AlertTriangle size={10} />}+ {(status === 'queued' || status === 'running') && (+ <button+ type="button"+ onClick={() => onStop?.(item.jobId)}+ className="ml-1 text-gray-500 hover:text-port-error"+ title="Cancel this render"+ aria-label={`Cancel ${sceneLabel}`}+ >+ <Square size={10} />+ </button>+ )}+ {status === 'running' && (+ <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-port-accent/20 rounded-b-md overflow-hidden">+ <div className="h-full bg-port-accent transition-all" style={{ width: `${pct}%` }} />+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/writers-room/proseTokenizer.jsx b/client/src/components/writers-room/proseTokenizer.jsxnew file mode 100644index 0000000000..cba8244fe3--- /dev/null+++ b/client/src/components/writers-room/proseTokenizer.jsx@@ -0,0 +1,160 @@+import { Fragment, useMemo } from 'react';++// proseTokenizer — finds character / setting / object name occurrences in a+// paragraph and wraps them in styled spans.+//+// Algorithm: leftmost-longest greedy match.+// 1. Flatten characters/settings/objects into a list of {term, kind, refId, label}+// entries. Drop terms < 3 chars to avoid pronoun spam ("It", "An").+// 2. For each entry, find every case-insensitive occurrence in the paragraph+// via a sliding indexOf.+// 3. Validate word boundaries (the char immediately before start and at end+// must NOT be part of [A-Za-z0-9']) — kills "Mira" matching inside "miracle".+// 4. Sort candidates by [start asc, length desc]; sweep left→right, dropping+// any whose start < cursor (i.e. overlapping with a previously-kept,+// longer match).+// 5. Splice the paragraph into [text, span, text, span, ...] React nodes.++const WORD = /[A-Za-z0-9']/;++const TOKEN_CLASS = {+ char: {+ dark: 'text-port-accent border-b border-dotted border-port-accent/40 hover:bg-port-accent/10 cursor-pointer transition-colors',+ light: 'text-purple-700 border-b border-dotted border-purple-700/50 hover:bg-purple-200/30 cursor-pointer transition-colors',+ },+ place: {+ dark: 'text-blue-400 border-b border-dotted border-blue-400/40 hover:bg-blue-500/10 cursor-pointer transition-colors',+ light: 'text-blue-700 border-b border-dotted border-blue-700/50 hover:bg-blue-200/30 cursor-pointer transition-colors',+ },+ object: {+ dark: 'text-amber-400 border-b border-dotted border-amber-400/40 hover:bg-amber-500/10 cursor-pointer transition-colors',+ light: 'text-amber-700 border-b border-dotted border-amber-700/50 hover:bg-amber-200/30 cursor-pointer transition-colors',+ },+};++export function buildTokenIndex({ characters = [], settings = [], objects = [] } = {}) {+ const entries = [];+ const push = (kind, refId, label, term) => {+ if (!term || typeof term !== 'string') return;+ const t = term.trim();+ if (t.length < 3) return;+ entries.push({ kind, refId, label, term: t, lower: t.toLowerCase() });+ };+ for (const c of characters) {+ if (!c?.id) continue;+ push('char', c.id, c.name || '', c.name);+ for (const a of c.aliases || []) push('char', c.id, c.name || a, a);+ }+ for (const s of settings) {+ if (!s?.id) continue;+ const label = s.name || s.slugline || '';+ if (s.name) push('place', s.id, label, s.name);+ if (s.slugline && s.slugline !== s.name) push('place', s.id, label, s.slugline);+ }+ for (const o of objects) {+ if (!o?.id) continue;+ push('object', o.id, o.name || '', o.name);+ for (const a of o.aliases || []) push('object', o.id, o.name || a, a);+ }+ return entries;+}++export function tokenizeParagraph(text, entries) {+ if (!text || !entries?.length) return [];+ const lower = text.toLowerCase();+ const candidates = [];+ for (const e of entries) {+ let from = 0;+ while (from <= lower.length - e.lower.length) {+ const idx = lower.indexOf(e.lower, from);+ if (idx < 0) break;+ const end = idx + e.lower.length;+ const before = idx === 0 ? '' : text[idx - 1];+ const after = end >= text.length ? '' : text[end];+ if (!WORD.test(before) && !WORD.test(after)) {+ candidates.push({ start: idx, end, kind: e.kind, refId: e.refId, label: e.label });+ }+ from = idx + 1;+ }+ }+ if (!candidates.length) return [];+ candidates.sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start));+ const out = [];+ let cursor = 0;+ for (const c of candidates) {+ if (c.start < cursor) continue;+ out.push(c);+ cursor = c.end;+ }+ return out;+}++export function renderTokenized(text, {+ entries = null,+ characters = [],+ settings = [],+ objects = [],+ hotRef = null,+ onTokenEnter,+ onTokenLeave,+ onTokenClick,+ light = false,+} = {}) {+ // Prefer the caller's pre-built index (paid once per bibles change). Fall+ // back to building per-call when only raw bible arrays are passed — handy+ // for ad-hoc renders, but not what ProseReader does.+ const idx = entries || buildTokenIndex({ characters, settings, objects });+ const annotations = tokenizeParagraph(text, idx);+ if (!annotations.length) return <Fragment>{text}</Fragment>;+ const out = [];+ let pos = 0;+ for (let i = 0; i < annotations.length; i += 1) {+ const a = annotations[i];+ if (a.start > pos) out.push(<Fragment key={`t${i}-pre`}>{text.slice(pos, a.start)}</Fragment>);+ const tone = light ? 'light' : 'dark';+ const baseClass = TOKEN_CLASS[a.kind][tone] || '';+ const isHot = hotRef && hotRef.refId === a.refId && hotRef.kind === a.kind;+ const hotClass = isHot ? (light ? 'bg-port-accent/20' : 'bg-port-accent/15') : '';+ out.push(+ // Inline interactive token: rendered as a focusable span with role=button+ // (a real <button> would break inline text flow / paragraph wrapping in+ // some browsers). Keyboard users can Tab to it and press Enter/Space to+ // open the popover (same effect as a click), and Escape closes it via+ // the existing window-level handler in ProseTokenPopover.+ <span+ key={`t${i}`}+ data-wr-token={a.kind}+ data-wr-ref={a.refId}+ role="button"+ tabIndex={0}+ aria-label={`${a.kind === 'char' ? 'Character' : a.kind === 'place' ? 'Setting' : 'Object'}: ${a.label}`}+ className={`${baseClass} ${hotClass} px-px rounded-sm cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-port-accent focus-visible:ring-offset-1`}+ onMouseEnter={(ev) => onTokenEnter?.({ kind: a.kind, refId: a.refId, label: a.label, anchor: ev.currentTarget })}+ onMouseLeave={() => onTokenLeave?.()}+ onFocus={(ev) => onTokenEnter?.({ kind: a.kind, refId: a.refId, label: a.label, anchor: ev.currentTarget })}+ onBlur={() => onTokenLeave?.()}+ onClick={(ev) => {+ ev.stopPropagation();+ onTokenClick?.({ kind: a.kind, refId: a.refId, label: a.label, anchor: ev.currentTarget });+ }}+ onKeyDown={(ev) => {+ if (ev.key !== 'Enter' && ev.key !== ' ') return;+ ev.preventDefault();+ ev.stopPropagation();+ onTokenClick?.({ kind: a.kind, refId: a.refId, label: a.label, anchor: ev.currentTarget });+ }}+ >+ {text.slice(a.start, a.end)}+ </span>+ );+ pos = a.end;+ }+ if (pos < text.length) out.push(<Fragment key="tail">{text.slice(pos)}</Fragment>);+ return <Fragment>{out}</Fragment>;+}++// Convenience hook: memoize the entries so paragraphs don't rebuild the index+// on every render. Pair with paragraph-level useMemo for the annotation pass.+export function useTokenEntries({ characters, settings, objects }) {+ return useMemo(() => buildTokenIndex({ characters, settings, objects }), [characters, settings, objects]);+}diff --git a/client/src/hooks/useImageGenQueue.js b/client/src/hooks/useImageGenQueue.jsnew file mode 100644index 0000000000..205505cac3--- /dev/null+++ b/client/src/hooks/useImageGenQueue.js@@ -0,0 +1,283 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import socket from '../services/socket';+import { cancelImageGen } from '../services/apiImageVideo';+import toast from '../components/ui/Toast';++// useImageGenQueue — work-scoped live queue of in-flight image renders.+//+// Subscribes once to the global image-gen:* socket events. SceneCard calls+// `register({jobId, sceneId, sceneLabel})` after kicking off a render so the+// hook can label rows; the hook then matches incoming events by jobId. The+// queue auto-prunes terminal jobs after 1s so the dock briefly flashes "done"+// before disappearing.+//+// Returns { queue, runningCount, register, stopAll, stopOne }.+//+// Orphan-event buffer hygiene: image-gen:* events are emitted globally+// (server only knows generationId, not which page issued it), so any image+// render anywhere in the app would otherwise pile up entries here. We cap+// the buffer to ORPHAN_MAX_ENTRIES and evict each entry ORPHAN_TTL_MS after+// last write — preventing unbounded memory growth on long-lived sessions.+const ORPHAN_TTL_MS = 30_000;+const ORPHAN_MAX_ENTRIES = 64;++export default function useImageGenQueue() {+ const [queue, setQueue] = useState([]);+ // Authoritative copy lives in a ref so socket callbacks don't see stale+ // closures. setQueue is only called via patch().+ const queueRef = useRef([]);+ const pruneTimersRef = useRef(new Map());+ // Race-buffer: image-gen:* events can arrive BEFORE register() — the+ // server emits started/progress while the HTTP response is still in+ // flight, so SceneCard learns the jobId after the events. Stash the+ // latest state for unknown jobIds so register() can replay it.+ //+ // Bounded by both a TTL (per-entry expiry timer) and a hard size cap+ // (LRU eviction) so unrelated global image-gen events don't accumulate.+ const orphanEventsRef = useRef(new Map());+ const orphanTimersRef = useRef(new Map());+ // Tracks the post-cancel fallback prune timers. Stored so unmount can+ // clear them (avoids "setState on unmounted hook" warnings) and so a real+ // terminal socket event can supersede the fallback. Keyed: 'all' for+ // Stop-all, jobId for Stop-one.+ const cancelFallbackTimersRef = useRef(new Map());++ const patch = useCallback((updater) => {+ const next = updater(queueRef.current);+ queueRef.current = next;+ setQueue(next);+ }, []);++ const schedulePrune = useCallback((jobId) => {+ const existing = pruneTimersRef.current.get(jobId);+ if (existing) clearTimeout(existing);+ const t = setTimeout(() => {+ pruneTimersRef.current.delete(jobId);+ patch((prev) => prev.filter((q) => q.jobId !== jobId));+ }, 1000);+ pruneTimersRef.current.set(jobId, t);+ }, [patch]);++ const clearOrphan = useCallback((jobId) => {+ const t = orphanTimersRef.current.get(jobId);+ if (t) {+ clearTimeout(t);+ orphanTimersRef.current.delete(jobId);+ }+ orphanEventsRef.current.delete(jobId);+ }, []);++ const stashOrphan = useCallback((jobId, delta) => {+ // Refresh the entry by re-inserting it last so the Map's iteration order+ // gives us a cheap LRU for the size-cap eviction below.+ const prior = orphanEventsRef.current.get(jobId) || {};+ orphanEventsRef.current.delete(jobId);+ orphanEventsRef.current.set(jobId, { ...prior, ...delta });+ // (Re)arm TTL timer.+ const existingTimer = orphanTimersRef.current.get(jobId);+ if (existingTimer) clearTimeout(existingTimer);+ const t = setTimeout(() => {+ orphanTimersRef.current.delete(jobId);+ orphanEventsRef.current.delete(jobId);+ }, ORPHAN_TTL_MS);+ orphanTimersRef.current.set(jobId, t);+ // Hard cap: drop the oldest entry if we're over budget.+ while (orphanEventsRef.current.size > ORPHAN_MAX_ENTRIES) {+ const oldest = orphanEventsRef.current.keys().next().value;+ if (oldest === undefined) break;+ const oldTimer = orphanTimersRef.current.get(oldest);+ if (oldTimer) clearTimeout(oldTimer);+ orphanTimersRef.current.delete(oldest);+ orphanEventsRef.current.delete(oldest);+ }+ }, []);++ const register = useCallback(({ jobId, sceneId, sceneLabel }) => {+ if (!jobId) return;+ // Replay any events that arrived before this jobId was registered, so+ // the row starts in its true current state (often already 'running' or+ // even 'done' for fast renders) instead of stale 'queued'.+ const orphan = orphanEventsRef.current.get(jobId);+ clearOrphan(jobId);+ patch((prev) => {+ const idx = prev.findIndex((q) => q.jobId === jobId);+ const base = {+ jobId,+ sceneId: sceneId || null,+ sceneLabel: sceneLabel || 'Scene',+ status: 'queued',+ progress: 0,+ eta: null,+ registeredAt: Date.now(),+ };+ const entry = orphan ? { ...base, ...orphan } : base;+ if (idx < 0) return [...prev, entry];+ const copy = [...prev];+ copy[idx] = { ...copy[idx], ...entry };+ return copy;+ });+ // If the orphan stream already saw a terminal event, prune the row+ // shortly so the dock doesn't pin a phantom done/error indefinitely.+ if (orphan && (orphan.status === 'done' || orphan.status === 'error')) {+ schedulePrune(jobId);+ }+ }, [patch, schedulePrune, clearOrphan]);++ // Apply an event's state delta to the queue. If the matching jobId hasn't+ // been registered yet, stash the merged delta in orphanEventsRef so the+ // eventual register() call can replay it.+ //+ // We probe the ref FIRST (no array allocation, no setState) and only call+ // patch() when there's a match. Without this guard, every global+ // `image-gen:*` event from anywhere in the app would force a rerender of+ // the Writers Room page even when the jobId is irrelevant.+ const applyEvent = useCallback((jobId, delta, terminal = false) => {+ if (!jobId) return;+ const idx = queueRef.current.findIndex((q) => q.jobId === jobId);+ if (idx < 0) {+ stashOrphan(jobId, delta);+ return;+ }+ patch((prev) => {+ const i = prev.findIndex((q) => q.jobId === jobId);+ if (i < 0) return prev;+ const copy = prev.slice();+ copy[i] = { ...copy[i], ...delta };+ return copy;+ });+ if (terminal) {+ // A real terminal event supersedes any post-cancel fallback timer for+ // this job.+ const fallback = cancelFallbackTimersRef.current.get(jobId);+ if (fallback) {+ clearTimeout(fallback);+ cancelFallbackTimersRef.current.delete(jobId);+ }+ schedulePrune(jobId);+ }+ }, [patch, schedulePrune, stashOrphan]);++ useEffect(() => {+ const onStarted = (data) => {+ applyEvent(data.generationId, { status: 'running', totalSteps: data.totalSteps ?? null });+ };+ const onProgress = (data) => {+ applyEvent(data.generationId, {+ status: 'running',+ progress: data.progress ?? 0,+ eta: data.eta ?? null,+ step: data.step ?? 0,+ totalSteps: data.totalSteps ?? null,+ });+ };+ const onCompleted = (data) => {+ applyEvent(data.generationId, { status: 'done', progress: 1 }, true);+ };+ const onFailed = (data) => {+ applyEvent(data.generationId, { status: 'error', error: data.error || data.message || null }, true);+ };+ socket.on('image-gen:started', onStarted);+ socket.on('image-gen:progress', onProgress);+ socket.on('image-gen:completed', onCompleted);+ socket.on('image-gen:failed', onFailed);+ return () => {+ socket.off('image-gen:started', onStarted);+ socket.off('image-gen:progress', onProgress);+ socket.off('image-gen:completed', onCompleted);+ socket.off('image-gen:failed', onFailed);+ };+ }, [applyEvent]);++ useEffect(() => () => {+ for (const t of pruneTimersRef.current.values()) clearTimeout(t);+ pruneTimersRef.current.clear();+ for (const t of orphanTimersRef.current.values()) clearTimeout(t);+ orphanTimersRef.current.clear();+ orphanEventsRef.current.clear();+ for (const t of cancelFallbackTimersRef.current.values()) clearTimeout(t);+ cancelFallbackTimersRef.current.clear();+ }, []);++ // Hard cutoff: if the server never confirms cancellation with a terminal+ // event, fall back to pruning the canceling row so the dock doesn't pin a+ // phantom row indefinitely.+ const CANCEL_FALLBACK_MS = 5000;++ // Mark a row as canceling, then issue cancel to the server. On a successful+ // cancel HTTP response, KEEP the row in 'canceling' state and let the+ // eventual image-gen:failed/completed terminal event prune it via+ // schedulePrune — that way a still-actively-canceling job stays visible to+ // the user, and the terminal event isn't treated as an orphan (which would+ // otherwise buffer it for 30s in the orphan map).+ // On HTTP failure, surface the error and restore each row's PRIOR status+ // (stashed on the entry as `_prevStatus`) so a queued job doesn't get+ // incorrectly flipped to running, and an already-completed job doesn't get+ // resurrected. Only revert rows that are still 'canceling' — a real socket+ // event arriving in the interim wins.+ const stopOne = useCallback(async (jobId) => {+ if (!jobId) return;+ patch((prev) => prev.map((q) => (+ q.jobId === jobId+ ? { ...q, status: 'canceling', _prevStatus: q.status }+ : q+ )));+ const err = await cancelImageGen({ jobId }).then(() => null).catch((e) => e);+ if (err) {+ toast.error(`Cancel failed: ${err.message || err}`);+ patch((prev) => prev.map((q) => {+ if (q.jobId !== jobId || q.status !== 'canceling') return q;+ const restored = { ...q, status: q._prevStatus || 'running' };+ delete restored._prevStatus;+ return restored;+ }));+ return;+ }+ // Server accepted; arm a fallback prune in case the terminal event+ // never arrives. Tracked in cancelFallbackTimersRef so unmount cleans+ // it up — without that we could setState on an unmounted hook if the+ // user navigates away within the 5s window.+ const existing = cancelFallbackTimersRef.current.get(jobId);+ if (existing) clearTimeout(existing);+ const t = setTimeout(() => {+ cancelFallbackTimersRef.current.delete(jobId);+ patch((prev) => prev.filter((q) => !(q.jobId === jobId && q.status === 'canceling')));+ }, CANCEL_FALLBACK_MS);+ cancelFallbackTimersRef.current.set(jobId, t);+ }, [patch]);++ const stopAll = useCallback(async () => {+ patch((prev) => prev.map((q) => (+ q.status === 'queued' || q.status === 'running'+ ? { ...q, status: 'canceling', _prevStatus: q.status }+ : q+ )));+ const err = await cancelImageGen({ all: true }).then(() => null).catch((e) => e);+ if (err) {+ toast.error(`Cancel all failed: ${err.message || err}`);+ patch((prev) => prev.map((q) => {+ if (q.status !== 'canceling') return q;+ const restored = { ...q, status: q._prevStatus || 'running' };+ delete restored._prevStatus;+ return restored;+ }));+ return;+ }+ // One fallback timer for the whole batch — repeated Stop-all clicks+ // shouldn't pile up timeouts.+ const existing = cancelFallbackTimersRef.current.get('all');+ if (existing) clearTimeout(existing);+ const t = setTimeout(() => {+ cancelFallbackTimersRef.current.delete('all');+ patch((prev) => prev.filter((q) => q.status !== 'canceling'));+ }, CANCEL_FALLBACK_MS);+ cancelFallbackTimersRef.current.set('all', t);+ }, [patch]);++ // Decouple status counts from any specific UI string. Consumers compute+ // their own labels — the dock distinguishes "Rendering N" vs "Canceling N".+ const renderingCount = queue.filter((q) => q.status === 'queued' || q.status === 'running').length;+ const cancelingCount = queue.filter((q) => q.status === 'canceling').length;+ const activeCount = renderingCount + cancelingCount;++ return { queue, renderingCount, cancelingCount, activeCount, register, stopOne, stopAll };+}diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.jsindex 97e87e32a3..542a3a7d95 100644--- a/client/src/services/apiWritersRoom.js+++ b/client/src/services/apiWritersRoom.js@@ -93,6 +93,25 @@ export const deleteWritersRoomSetting = (workId, settingId) =>method: 'DELETE',});+// Objects bible (editable; recurring symbolic / physical items extracted by+// the Adapt+Objects pass — letters, hats, keepsakes, McGuffins).+export const listWritersRoomObjects = (workId) =>+ request(`/writers-room/works/${enc(workId)}/objects`);+export const createWritersRoomObject = (workId, data) =>+ request(`/writers-room/works/${enc(workId)}/objects`, {+ method: 'POST',+ body: JSON.stringify(data),+ });+export const updateWritersRoomObject = (workId, objectId, patch) =>+ request(`/writers-room/works/${enc(workId)}/objects/${enc(objectId)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+ });+export const deleteWritersRoomObject = (workId, objectId) =>+ request(`/writers-room/works/${enc(workId)}/objects/${enc(objectId)}`, {+ method: 'DELETE',+ });+// Exercisesexport const listWritersRoomExercises = (workId) => {const qs = workId ? `?workId=${enc(workId)}` : '';diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.jsonindex 9778fab86a..ca1cc59b80 100644--- a/data.sample/prompts/stage-config.json+++ b/data.sample/prompts/stage-config.json@@ -35,6 +35,13 @@"returnsJson": true,"variables": []},+ "writers-room-objects": {+ "name": "Writers Room — Recurring Objects",+ "description": "Extract a recurring-objects bible from a Writers Room draft: symbolic or physically significant items that appear across multiple scenes (the letter, the fedora, a keepsake). Captures description and narrative significance so the writer can validate continuity.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"cd-treatment": {"name": "Creative Director — Treatment","description": "Plan a long-form generated-video project: write the logline, synopsis, and scene-by-scene treatment.",diff --git a/data.sample/prompts/stages/writers-room-objects.md b/data.sample/prompts/stages/writers-room-objects.mdnew file mode 100644index 0000000000..3b9eba37aa--- /dev/null+++ b/data.sample/prompts/stages/writers-room-objects.md@@ -0,0 +1,63 @@+# Writers Room — Recurring Object Extraction++You are a story analyst surfacing the recurring symbolic and physical objects in a piece of prose. Objects matter when they recur across scenes, change hands, change meaning, or carry weight beyond their literal function — "the letter", "the fedora", "her grandmother's locket". You are NOT cataloging every prop; you are identifying objects whose continuity is meaningful to the story.++## Work being analyzed++- Title: {{work.title}}+- Kind: {{work.kind}}+- Word count: {{work.wordCount}}++## Existing object entries (preserve user edits — DO NOT contradict these)++The writer may have already edited some entries. Treat any non-empty field below as authoritative — if you would describe an object differently, defer to the existing value. Your job is to FILL IN the empty fields from prose evidence and ADD any recurring objects the writer hasn't captured yet.++```json+{{existingObjectsJson}}+```++## Source prose++```+{{draftBody}}+```++## Task++For each recurring or symbolically significant object in the prose:++1. Extract or refine these fields:+ - `name` — canonical reference as it appears in the prose, including the article when natural ("the letter", "the fedora", "her father's watch"). Use the form a reader would recognize.+ - `aliases` — other ways the object is referred to ("the envelope", "the hat", "Dad's old watch").+ - `description` — 20–60 words, image-gen-ready. What does it look like? Material, color, condition, distinguishing marks. Stay grounded in what the prose says.+ - `significance` — 1–2 sentences on why it matters to the story: what it represents, who it ties together, how its meaning evolves across scenes.+ - `firstAppearance` — short quote (≤ 120 chars) from the prose where the object is first introduced, or null if not clear.+ - `evidence` — array of 1–3 short verbatim quotes (≤ 120 chars each) from the prose that support the description and significance.++2. **Respect existing edits.** If a field in the existing entry is already filled in, keep that value verbatim. Only populate empty / missing fields.++3. **Recurrence threshold.** Only include objects that appear in two or more scenes OR that are explicitly framed as significant (a final-line object, a McGuffin, a keepsake explicitly described). Do not catalog one-off props.++4. **Identify gaps.** For every object (existing AND new), list which fields the prose does not yet support — return them as `missingFromProse`. The writer uses this to decide whether to add detail to the prose or fill the field manually.++5. Do not invent details the prose does not support. If the prose never describes the object's color, leave that out of `description` rather than guessing — and call it out in `missingFromProse`.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:++```json+{+ "objects": [+ {+ "name": "string",+ "aliases": ["string", ...],+ "description": "string",+ "significance": "string",+ "firstAppearance": "string or null",+ "evidence": ["string", ...],+ "missingFromProse": ["description.color", "significance", ...]+ }+ ]+}+```diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 777de4ae6f..5119b6d136 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -583,6 +583,22 @@ export const writersRoomSettingUpdateSchema = z.object({notes: wrSettingTextField.optional(),}).strict();+const wrObjectTextField = z.string().max(2000);+export const writersRoomObjectCreateSchema = z.object({+ name: z.string().trim().min(1).max(200),+ aliases: z.array(z.string().trim().min(1).max(200)).max(20).optional(),+ description: wrObjectTextField.optional(),+ significance: wrObjectTextField.optional(),+ notes: wrObjectTextField.optional(),+}).strict();+export const writersRoomObjectUpdateSchema = z.object({+ name: z.string().trim().min(1).max(200).optional(),+ aliases: z.array(z.string().trim().min(1).max(200)).max(20).optional(),+ description: wrObjectTextField.optional(),+ significance: wrObjectTextField.optional(),+ notes: wrObjectTextField.optional(),+}).strict();+// =============================================================================// FEATURE AGENT SCHEMAS// =============================================================================diff --git a/server/lib/writersRoomPresets.js b/server/lib/writersRoomPresets.jsindex bc4c83e029..cb62dae5ec 100644--- a/server/lib/writersRoomPresets.js+++ b/server/lib/writersRoomPresets.js@@ -5,4 +5,4 @@export const WORK_KINDS = ['novel', 'short-story', 'screenplay', 'essay', 'treatment', 'other'];export const WORK_STATUSES = ['idea', 'drafting', 'revision', 'adaptation', 'rendering', 'complete', 'archived'];export const EXERCISE_STATUSES = ['running', 'finished', 'discarded'];-export const ANALYSIS_KINDS = ['evaluate', 'format', 'script', 'characters', 'settings'];+export const ANALYSIS_KINDS = ['evaluate', 'format', 'script', 'characters', 'settings', 'objects'];diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.jsindex ea73c59b4d..a4454871da 100644--- a/server/routes/writersRoom.js+++ b/server/routes/writersRoom.js@@ -19,6 +19,8 @@ import {writersRoomCharacterUpdateSchema,writersRoomSettingCreateSchema,writersRoomSettingUpdateSchema,+ writersRoomObjectCreateSchema,+ writersRoomObjectUpdateSchema,} from '../lib/validation.js';import {listFolders, createFolder, deleteFolder,@@ -36,6 +38,9 @@ import {import {listSettings, createSetting, updateSetting, deleteSetting,} from '../services/writersRoom/settings.js';+import {+ listObjects, createObject, updateObject, deleteObject,+} from '../services/writersRoom/objects.js';import { addItem as addCollectionItem, ERR_DUPLICATE } from '../services/mediaCollections.js';const router = Router();@@ -192,6 +197,26 @@ router.delete('/works/:id/settings/:settingId', asyncHandler(async (req, res) =>res.json(await deleteSetting(req.params.id, req.params.settingId));}));+// ---------- objects (recurring symbolic items) ----------++router.get('/works/:id/objects', asyncHandler(async (req, res) => {+ res.json(await listObjects(req.params.id));+}));++router.post('/works/:id/objects', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomObjectCreateSchema, req.body || {});+ res.status(201).json(await createObject(req.params.id, data));+}));++router.patch('/works/:id/objects/:objectId', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomObjectUpdateSchema, req.body || {});+ res.json(await updateObject(req.params.id, req.params.objectId, data));+}));++router.delete('/works/:id/objects/:objectId', asyncHandler(async (req, res) => {+ res.json(await deleteObject(req.params.id, req.params.objectId));+}));+// Persist a scene→generated-image link on the analysis snapshot, AND mirror// the image into the work's auto-collection so it appears in MediaGen's// Collections view. Called by SceneCard when image-gen:completed fires.diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.jsindex 6e3496ee6e..f5f701f76d 100644--- a/server/services/writersRoom/evaluator.js+++ b/server/services/writersRoom/evaluator.js@@ -16,6 +16,7 @@ import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';import { getWorkWithBody } from './local.js';import { listCharacters, mergeExtractedCharacters } from './characters.js';import { listSettings, mergeExtractedSettings } from './settings.js';+import { listObjects, mergeExtractedObjects } from './objects.js';import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';export { ANALYSIS_KINDS };@@ -26,6 +27,7 @@ const KIND_META = {script: { stage: 'writers-room-script', returnsJson: true },characters: { stage: 'writers-room-characters', returnsJson: true },settings: { stage: 'writers-room-settings', returnsJson: true },+ objects: { stage: 'writers-room-objects', returnsJson: true },};// Analysis id == kind. Each work keeps at most one snapshot per kind on disk@@ -288,6 +290,23 @@ const SHAPERS = {})),};},+ objects: (raw) => {+ const parsed = extractJson(raw);+ const list = Array.isArray(parsed.objects) ? parsed.objects : [];+ return {+ objects: list+ .filter((o) => o && typeof o === 'object' && typeof o.name === 'string' && o.name.trim())+ .map((o) => ({+ name: o.name.trim(),+ aliases: Array.isArray(o.aliases) ? o.aliases.filter((a) => typeof a === 'string') : [],+ description: typeof o.description === 'string' ? o.description : '',+ significance: typeof o.significance === 'string' ? o.significance : '',+ firstAppearance: typeof o.firstAppearance === 'string' ? o.firstAppearance : null,+ evidence: Array.isArray(o.evidence) ? o.evidence.filter((e) => typeof e === 'string') : [],+ missingFromProse: Array.isArray(o.missingFromProse) ? o.missingFromProse.filter((m) => typeof m === 'string') : [],+ })),+ };+ },};// ---------- storage ----------@@ -518,12 +537,20 @@ export async function runAnalysis(workId, { kind } = {}) {// pipeline doesn't pay two sequential disk reads. For 'characters' or// 'settings' alone Promise.all is degenerate (one element) but the shape// keeps the call site uniform.- const [existingChars, existingSets] = await Promise.all([+ const trimObject = (o) => ({+ name: o.name,+ aliases: o.aliases,+ description: o.description,+ significance: o.significance,+ });+ const [existingChars, existingSets, existingObjs] = await Promise.all([(kind === 'characters' || kind === 'script') ? listCharacters(workId) : null,(kind === 'settings' || kind === 'script') ? listSettings(workId) : null,+ (kind === 'objects' || kind === 'script') ? listObjects(workId) : null,]);if (existingChars) variables.existingCharactersJson = JSON.stringify(existingChars.map(trimCharacter));if (existingSets) variables.existingSettingsJson = JSON.stringify(existingSets.map(trimSetting));+ if (existingObjs) variables.existingObjectsJson = JSON.stringify(existingObjs.map(trimObject));const temperature = kind === 'format' ? 0.2 : 0.4;const { content, model: usedModel, providerId: usedProvider } = await callAI(stage, variables, temperature);@@ -533,6 +560,8 @@ export async function runAnalysis(workId, { kind } = {}) {mergedProfiles = await mergeExtractedCharacters(workId, result.characters || []);} else if (kind === 'settings') {mergedProfiles = await mergeExtractedSettings(workId, result.settings || []);+ } else if (kind === 'objects') {+ mergedProfiles = await mergeExtractedObjects(workId, result.objects || []);}const finished = {...baseSnapshot,diff --git a/server/services/writersRoom/objects.js b/server/services/writersRoom/objects.jsnew file mode 100644index 0000000000..0f956d7190--- /dev/null+++ b/server/services/writersRoom/objects.js@@ -0,0 +1,204 @@+/**+ * Writers Room — editable recurring-objects bible.+ *+ * Mirrors the characters/settings bible pattern (per-work canonical roster+ * stored at data/writers-room/works/<workId>/objects.json). Distinct from the+ * immutable analysis snapshot — the snapshot is history; this is the working+ * bible that survives across runs and accepts hand-edits.+ *+ * Merge rule: a re-run of `objects` analysis fills empty fields and adds new+ * objects, but never overwrites a non-empty field on an existing profile. The+ * writer's edits are authoritative.+ */++import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../../lib/fileUtils.js';+import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';++const OBJECT_ID_RE = /^wr-object-[0-9a-f-]+$/i;++const root = () => join(PATHS.data, 'writers-room');+const objectsFile = (workId) => {+ assertValidWorkId(workId);+ return join(root(), 'works', workId, 'objects.json');+};++const EDITABLE_FIELDS = ['name', 'aliases', 'description', 'significance', 'notes'];++function emptyProfile() {+ return {+ id: '',+ name: '',+ aliases: [],+ description: '',+ significance: '',+ notes: '',+ firstAppearance: null,+ evidence: [],+ missingFromProse: [],+ source: 'user',+ createdAt: nowIso(),+ updatedAt: nowIso(),+ };+}++function normalizeName(name) {+ return String(name || '').trim().toLowerCase();+}++function isBlank(v) {+ if (v == null) return true;+ if (Array.isArray(v)) return v.length === 0;+ if (typeof v === 'string') return v.trim() === '';+ return false;+}++async function loadFile(workId) {+ const fallback = { objects: [], updatedAt: null };+ const parsed = await readJSONFile(objectsFile(workId), fallback);+ return parsed && Array.isArray(parsed.objects) ? parsed : fallback;+}++async function saveFile(workId, state) {+ assertValidWorkId(workId);+ await ensureDir(join(root(), 'works', workId));+ await atomicWrite(objectsFile(workId), { ...state, updatedAt: nowIso() });+}++export async function listObjects(workId) {+ const state = await loadFile(workId);+ return state.objects.sort((a, b) => (a.name || '').localeCompare(b.name || ''));+}++export async function getObject(workId, objectId) {+ if (!OBJECT_ID_RE.test(objectId)) throw badRequest('Invalid object id');+ const state = await loadFile(workId);+ const found = state.objects.find((o) => o.id === objectId);+ if (!found) throw notFound('Object');+ return found;+}++export async function createObject(workId, patch = {}) {+ const name = String(patch.name || '').trim();+ if (!name) throw badRequest('Object name required');+ const state = await loadFile(workId);+ if (state.objects.some((o) => normalizeName(o.name) === normalizeName(name))) {+ throw badRequest(`An object named "${name}" already exists`);+ }+ const profile = {+ ...emptyProfile(),+ id: `wr-object-${randomUUID()}`,+ name,+ source: 'user',+ };+ for (const field of EDITABLE_FIELDS) {+ if (field === 'name') continue;+ if (patch[field] !== undefined) profile[field] = patch[field];+ }+ state.objects.push(profile);+ await saveFile(workId, state);+ return profile;+}++export async function updateObject(workId, objectId, patch = {}) {+ if (!OBJECT_ID_RE.test(objectId)) throw badRequest('Invalid object id');+ const state = await loadFile(workId);+ const idx = state.objects.findIndex((o) => o.id === objectId);+ if (idx < 0) throw notFound('Object');+ const next = { ...state.objects[idx] };+ for (const field of EDITABLE_FIELDS) {+ if (patch[field] === undefined) continue;+ if (field === 'name') {+ const newName = String(patch.name || '').trim();+ if (!newName) throw badRequest('Object name cannot be blank');+ const conflict = state.objects.some((o) => o.id !== objectId && normalizeName(o.name) === normalizeName(newName));+ if (conflict) throw badRequest(`An object named "${newName}" already exists`);+ next.name = newName;+ } else if (field === 'aliases') {+ next.aliases = Array.isArray(patch.aliases)+ ? patch.aliases.map((a) => String(a).trim()).filter(Boolean)+ : [];+ } else {+ next[field] = patch[field];+ }+ }+ next.source = 'user';+ next.updatedAt = nowIso();+ state.objects[idx] = next;+ await saveFile(workId, state);+ return next;+}++export async function deleteObject(workId, objectId) {+ if (!OBJECT_ID_RE.test(objectId)) throw badRequest('Invalid object id');+ const state = await loadFile(workId);+ const before = state.objects.length;+ state.objects = state.objects.filter((o) => o.id !== objectId);+ if (state.objects.length === before) throw notFound('Object');+ await saveFile(workId, state);+ return { ok: true };+}++/**+ * Merge an AI-extracted object set into the editable bible.+ * Mirrors the characters merge: existing entries (by case-insensitive name OR+ * alias) keep every non-blank field, only blanks fill from incoming. New+ * objects are inserted with source: 'ai'. firstAppearance/evidence/+ * missingFromProse always refresh from the latest analysis.+ */+export async function mergeExtractedObjects(workId, extracted) {+ if (!Array.isArray(extracted)) return listObjects(workId);+ const state = await loadFile(workId);+ const byKey = new Map();+ const indexObject = (o) => {+ const nameKey = normalizeName(o.name);+ if (nameKey) byKey.set(nameKey, o);+ for (const alias of o.aliases || []) {+ const aliasKey = normalizeName(alias);+ if (aliasKey) byKey.set(aliasKey, o);+ }+ };+ for (const o of state.objects) indexObject(o);+ for (const incoming of extracted) {+ if (!incoming || !incoming.name) continue;+ const key = normalizeName(incoming.name);+ const existing = byKey.get(key);+ if (existing) {+ for (const field of ['description', 'significance']) {+ if (isBlank(existing[field]) && !isBlank(incoming[field])) {+ existing[field] = incoming[field];+ }+ }+ if (isBlank(existing.aliases) && Array.isArray(incoming.aliases)) {+ existing.aliases = incoming.aliases.map((a) => String(a).trim()).filter(Boolean);+ indexObject(existing);+ }+ // firstAppearance is prose-derived metadata that the latest analysis+ // run is authoritative for: replace verbatim, including explicit null+ // (the object may no longer have a clear first scene after edits, and+ // pinning the stale value would mislead the bible).+ existing.firstAppearance = incoming.firstAppearance ?? null;+ existing.evidence = Array.isArray(incoming.evidence) ? incoming.evidence : (existing.evidence || []);+ existing.missingFromProse = Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [];+ existing.updatedAt = nowIso();+ } else {+ const profile = {+ ...emptyProfile(),+ id: `wr-object-${randomUUID()}`,+ name: String(incoming.name).trim(),+ aliases: Array.isArray(incoming.aliases) ? incoming.aliases.map((a) => String(a).trim()).filter(Boolean) : [],+ description: String(incoming.description || '').trim(),+ significance: String(incoming.significance || '').trim(),+ firstAppearance: incoming.firstAppearance ?? null,+ evidence: Array.isArray(incoming.evidence) ? incoming.evidence : [],+ missingFromProse: Array.isArray(incoming.missingFromProse) ? incoming.missingFromProse : [],+ source: 'ai',+ };+ state.objects.push(profile);+ indexObject(profile);+ }+ }+ await saveFile(workId, state);+ return state.objects.sort((a, b) => (a.name || '').localeCompare(b.name || ''));+}diff --git a/server/services/writersRoom/objects.test.js b/server/services/writersRoom/objects.test.jsnew file mode 100644index 0000000000..5eda67eea0--- /dev/null+++ b/server/services/writersRoom/objects.test.js@@ -0,0 +1,112 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++let tempRoot;++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return new Proxy(actual, {+ get(target, prop) {+ if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };+ return target[prop];+ },+ });+});++const local = await import('./local.js');+const objects = await import('./objects.js');+const { createWork } = local;+const {+ listObjects, createObject, updateObject, deleteObject,+ mergeExtractedObjects,+} = objects;++beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-objects-test-'));+});++afterEach(() => {+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });+});++async function newWork() {+ const w = await createWork({ title: 'Test Work', kind: 'short-story' });+ return w.id;+}++describe('writers room — objects CRUD', () => {+ it('starts with an empty bible', async () => {+ const id = await newWork();+ expect(await listObjects(id)).toEqual([]);+ });++ it('rejects path-traversal-shaped work ids', async () => {+ await expect(listObjects('../../etc')).rejects.toThrow(/work id/i);+ await expect(createObject('../../etc', { name: 'X' })).rejects.toThrow(/work id/i);+ await expect(mergeExtractedObjects('../../etc', [{ name: 'X' }])).rejects.toThrow(/work id/i);+ });++ it('rejects creating without a name', async () => {+ const id = await newWork();+ await expect(createObject(id, { name: ' ' })).rejects.toThrow(/name required/i);+ });++ it('rejects duplicate names (case-insensitive)', async () => {+ const id = await newWork();+ await createObject(id, { name: 'the letter', description: 'sealed' });+ await expect(createObject(id, { name: 'The Letter' })).rejects.toThrow(/already exists/i);+ });++ it('creates, updates, deletes', async () => {+ const id = await newWork();+ const o = await createObject(id, { name: 'the fedora', description: 'wide-brimmed' });+ expect(o.name).toBe('the fedora');+ expect(o.id).toMatch(/^wr-object-/);+ const upd = await updateObject(id, o.id, { significance: 'his father wore one' });+ expect(upd.significance).toBe('his father wore one');+ expect(upd.source).toBe('user');+ await deleteObject(id, o.id);+ expect(await listObjects(id)).toEqual([]);+ });+});++describe('writers room — objects merge', () => {+ it('inserts new ai-extracted objects', async () => {+ const id = await newWork();+ const merged = await mergeExtractedObjects(id, [+ { name: 'the letter', description: 'cream paper, blue ink', significance: 'unsent confession' },+ ]);+ expect(merged).toHaveLength(1);+ expect(merged[0].source).toBe('ai');+ expect(merged[0].description).toBe('cream paper, blue ink');+ });++ it('preserves user edits — only fills blank fields', async () => {+ const id = await newWork();+ // User-created object with a manual description.+ const userOne = await createObject(id, {+ name: 'the locket',+ description: 'her grandmother\'s, silver',+ });+ // AI tries to "improve" the description — must be ignored.+ const merged = await mergeExtractedObjects(id, [+ { name: 'the locket', description: 'tarnished gold pendant', significance: 'family heirloom' },+ ]);+ const o = merged.find((x) => x.id === userOne.id);+ expect(o.description).toBe('her grandmother\'s, silver'); // user wins+ expect(o.significance).toBe('family heirloom'); // blank → filled+ });++ it('matches by alias to avoid duplicates across runs', async () => {+ const id = await newWork();+ await createObject(id, { name: 'the fedora', aliases: ['the hat'] });+ const merged = await mergeExtractedObjects(id, [+ { name: 'the hat', description: 'felt, dark grey' },+ ]);+ expect(merged).toHaveLength(1); // matched via alias, not duplicated+ expect(merged[0].name).toBe('the fedora');+ expect(merged[0].description).toBe('felt, dark grey');+ });+});