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
feat(writers-room): vertical storyboard companion + UX cleanup
Adam Eivybd995960da2b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ec06fe6605..6f20d157d5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Writers Room — vertical Storyboard companion + UX cleanup.** The AI/Outline/Versions tabbed sidebar is replaced with an always-on `StoryboardPanel` that shows the latest Adapt analysis as a vertical column of scene cards (heading, slugline, image, summary, character chips, visual prompt). Each card has a per-scene image regenerate button and a "Debug" overflow menu that scopes follow-up tools (Why this image / Check characters / Editorial pass / Jump to prose) to that one scene. Stale banner appears when the active draft's `contentHash` differs from the analysis's `sourceContentHash`, with a one-click re-run. Click a card heading to jump the prose textarea to that scene — falls back to scene-summary substring or scene-index proportional scroll when the LLM heading doesn't match the user's prose verbatim. The header collapses to title + status + Save + Snapshot + a single `(•••)` overflow menu (AI section: Run Adapt / Refresh characters / Editorial pass / Format pass · Open section: Outline / Versions / Characters [badge count] / Analysis history · View section: reading-theme toggle / Write-for-10 toggle). Outline, Versions, Characters, and Analysis history each open as a slide-over `Drawer` instead of competing with the storyboard for sidebar real estate. Mobile (<lg): a Writing/Storyboard segmented toggle replaces the previous stacked layout, fixing the double-scroll problem. The page-level Write-for-10 button moves into the work overflow menu so the Writers Room shell header is now title-only. New files: `StoryboardPanel.jsx`, `SceneCard.jsx`, `CharactersBible.jsx`, `AnalysisHistory.jsx`, `sceneCardHelpers.js`. Removed: `AiPanel.jsx` (decomposed into the above). Touched: `client/src/components/writers-room/WorkEditor.jsx`, `client/src/pages/WritersRoom.jsx`.+- **Writers Room — character bible with image-gen prompt injection.** New `Characters` AI action extracts a per-work character roster (name, aliases, role, image-gen-ready physical description, personality, background) and merges it into an editable bible at `data/writers-room/works/<id>/characters.json`. Re-running the pass preserves any field the writer has already filled in (matched by canonical name OR alias, case-insensitive) and only fills blanks; prose-derived metadata (`firstAppearance`, `evidence`, `missingFromProse`) refreshes every run so the writer can see which fields the prose still doesn't support. Inline editor in the AI panel for create/edit/delete. The script-stage `SceneCard` now matches each scene's `characters` list against the bible and prepends `Featuring — <Name>: <physical description>` to the image-gen prompt before render, so the same character looks consistent across scenes. Matched character chips on the scene card show a port-accent border so the writer can see at a glance which characters in a scene have linked profiles. New routes: `GET/POST /api/writers-room/works/:id/characters`, `PATCH/DELETE /api/writers-room/works/:id/characters/:characterId`. New prompt stage `writers-room-characters` (sample + live). Touched: `server/services/writersRoom/{characters.js,evaluator.js}`, `server/routes/writersRoom.js`, `server/lib/{validation,writersRoomPresets}.js`, `client/src/components/writers-room/AiPanel.jsx`, `client/src/services/apiWritersRoom.js`, `data{,sample}/prompts/{stages/writers-room-characters.md,stage-config.json}`, `server/services/writersRoom/characters.test.js`.- **Collapsed-sidebar section flyout.** Hovering or focusing any multi-child section icon (Brain, Calendar, Chief of Staff, Comms, Create, Dev Tools, Digital Twin, MeatSpace, POST, Settings, System, Wiki) while the sidebar is collapsed opens a fixed-position popover to its right listing the section's children — so siblings (e.g. **Writers Room** under **Create**, which defaults to Media Gen) stay reachable without expanding the whole sidebar. Clicking a child navigates and closes the flyout; a 180 ms grace period lets the user move from icon → popover without it snapping shut. Renders via `position: fixed` so it escapes the nav scroller's `overflow-x-hidden` clipping. ARIA: `role="menu"` + `aria-haspopup="menu"` + `aria-expanded` on the trigger; keyboard focus on the icon also opens the flyout.diff --git a/client/src/components/writers-room/AiPanel.jsx b/client/src/components/writers-room/AiPanel.jsxdeleted file mode 100644index 8aaf5cd668..0000000000--- a/client/src/components/writers-room/AiPanel.jsx+++ /dev/null@@ -1,1035 +0,0 @@-import { useEffect, useState, useCallback, useRef, useMemo } from 'react';-import { Sparkles, FileSignature, Clapperboard, Users, Loader2, RotateCcw, AlertTriangle, Image as ImageIcon, Check, Settings as SettingsIcon, Pencil, Trash2, Plus, X } from 'lucide-react';-import toast from '../ui/Toast';-import {- listWritersRoomAnalyses,- runWritersRoomAnalysis,- getWritersRoomAnalysis,- attachWritersRoomSceneImage,- listWritersRoomCharacters,- createWritersRoomCharacter,- updateWritersRoomCharacter,- deleteWritersRoomCharacter,-} from '../../services/apiWritersRoom';-import { generateImage, getSettings, updateSettings } from '../../services/apiSystem';-import { listImageModels } from '../../services/apiImageVideo';-import { timeAgo } from '../../utils/formatters';-import socket from '../../services/socket';--// Defaults for the per-scene image gen pipe. The user picked Klein-4B because-// it's the fastest of the FLUX.2 variants on Apple Silicon, and 768×512 is a-// 3:2 aspect that suits scene/storyboard work better than a square.-const WR_IMAGE_DEFAULTS = {- modelId: 'flux2-klein-4b',- mode: 'local',- width: 768,- height: 512,-};--function readWrImageSettings(settings) {- const stored = settings?.writersRoom?.imageGen || {};- return {- modelId: stored.modelId || WR_IMAGE_DEFAULTS.modelId,- mode: stored.mode || WR_IMAGE_DEFAULTS.mode,- width: Number.isFinite(stored.width) ? stored.width : WR_IMAGE_DEFAULTS.width,- height: Number.isFinite(stored.height) ? stored.height : WR_IMAGE_DEFAULTS.height,- };-}--const KIND_META = {- evaluate: { label: 'Evaluate', icon: Sparkles, hint: 'Editorial critique: logline, themes, issues, suggestions' },- format: { label: 'Format', icon: FileSignature, hint: 'Tidy prose: paragraphing, dialogue, whitespace, typos' },- script: { label: 'Adapt', icon: Clapperboard, hint: 'Adapt prose into scene-by-scene script with visual prompts' },- characters: { label: 'Characters', icon: Users, hint: 'Build/refresh character profiles with image-gen-ready physical descriptions. Preserves your edits — fills gaps from prose.' },-};--const SEVERITY_COLOR = {- major: 'text-port-error border-port-error/40',- moderate: 'text-port-warning border-port-warning/40',- minor: 'text-gray-400 border-port-border',-};--export default function AiPanel({ work, onApplyFormat, readingTheme = 'dark' }) {- const [analyses, setAnalyses] = useState([]);- const [loadingList, setLoadingList] = useState(false);- const [running, setRunning] = useState(null);- const [expanded, setExpanded] = useState(null);- const [details, setDetails] = useState({});- const [characters, setCharacters] = useState([]);-- const mountedRef = useRef(true);- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- const activeDraft = (work.drafts || []).find((d) => d.id === work.activeDraftVersionId);- const activeHash = activeDraft?.contentHash || null;-- const refresh = useCallback(async () => {- setLoadingList(true);- const [list, chars] = await Promise.all([- listWritersRoomAnalyses(work.id).catch((err) => {- if (mountedRef.current) toast.error(`Failed to list analyses: ${err.message}`);- return [];- }),- listWritersRoomCharacters(work.id).catch(() => []),- ]);- if (!mountedRef.current) return;- setLoadingList(false);- setAnalyses(list);- setCharacters(chars);- }, [work.id]);-- useEffect(() => {- // Clear synchronously so a work-switch doesn't briefly render the previous- // work's analyses while the new fetch is in flight.- setAnalyses([]);- setExpanded(null);- setDetails({});- setCharacters([]);- refresh();- }, [work.id, refresh]);-- const runKind = async (kind) => {- if (running) return;- setRunning(kind);- const snapshot = await runWritersRoomAnalysis(work.id, { kind }).catch((err) => {- if (mountedRef.current) toast.error(`${KIND_META[kind].label} failed: ${err.message}`);- return null;- });- if (!mountedRef.current) return;- setRunning(null);- if (!snapshot) return;- if (snapshot.status === 'failed') {- toast.error(`${KIND_META[kind].label} failed: ${snapshot.error || 'unknown error'}`);- } else {- toast.success(`${KIND_META[kind].label} complete`);- }- // Splice into the local list instead of refetching — the snapshot already- // carries every field listAnalyses returns.- setDetails((d) => ({ ...d, [snapshot.id]: snapshot }));- setExpanded(snapshot.id);- setAnalyses((prev) => [snapshot, ...prev.filter((a) => a.id !== snapshot.id)]);- if (kind === 'characters' && snapshot.status === 'succeeded' && Array.isArray(snapshot.result?.mergedProfiles)) {- setCharacters(snapshot.result.mergedProfiles);- }- };-- const upsertCharacterLocal = (next) => {- setCharacters((prev) => {- const idx = prev.findIndex((c) => c.id === next.id);- if (idx < 0) return [...prev, next].sort((a, b) => (a.name || '').localeCompare(b.name || ''));- const copy = [...prev];- copy[idx] = next;- return copy.sort((a, b) => (a.name || '').localeCompare(b.name || ''));- });- };-- const removeCharacterLocal = (id) => {- setCharacters((prev) => prev.filter((c) => c.id !== id));- };-- const expand = async (analysis) => {- if (expanded === analysis.id) {- setExpanded(null);- return;- }- setExpanded(analysis.id);- if (details[analysis.id]) return;- const full = await getWritersRoomAnalysis(work.id, analysis.id).catch((err) => {- if (mountedRef.current) toast.error(`Failed to load analysis: ${err.message}`);- return null;- });- if (full && mountedRef.current) setDetails((d) => ({ ...d, [analysis.id]: full }));- };-- return (- <div className="space-y-3 text-xs">- <div>- <h3 className="text-[10px] uppercase tracking-wider text-gray-500 mb-1.5">AI Actions</h3>- <div className="grid grid-cols-2 sm:grid-cols-4 gap-1">- {Object.entries(KIND_META).map(([kind, meta]) => {- const Icon = meta.icon;- const isRunning = running === kind;- return (- <button- key={kind}- onClick={() => runKind(kind)}- disabled={!!running}- title={meta.hint}- className={`flex flex-col items-center gap-1 px-2 py-2 rounded border text-[11px] transition-colors ${- isRunning- ? 'border-port-accent bg-port-accent/20 text-port-accent'- : running- ? 'border-port-border bg-port-bg text-gray-600 cursor-not-allowed'- : 'border-port-border bg-port-bg text-gray-300 hover:border-port-accent hover:text-white'- }`}- >- {isRunning ? <Loader2 size={14} className="animate-spin" /> : <Icon size={14} />}- <span>{meta.label}</span>- </button>- );- })}- </div>- </div>-- <CharactersBible- workId={work.id}- characters={characters}- onLocalChange={upsertCharacterLocal}- onLocalDelete={removeCharacterLocal}- readingTheme={readingTheme}- />-- <div>- <div className="flex items-center justify-between mb-1.5">- <h3 className="text-[10px] uppercase tracking-wider text-gray-500">History</h3>- <button- onClick={refresh}- disabled={loadingList}- className="text-gray-500 hover:text-white disabled:opacity-50"- title="Refresh analyses"- aria-label="Refresh analyses"- >- <RotateCcw size={11} className={loadingList ? 'animate-spin' : ''} />- </button>- </div>- {analyses.length === 0 && !loadingList && (- <div className="text-gray-600 italic px-1">No analyses yet — try one above.</div>- )}- <ul className="space-y-1">- {analyses.map((a) => {- const meta = KIND_META[a.kind] || { label: a.kind, icon: Sparkles };- const Icon = meta.icon;- const stale = a.sourceContentHash && activeHash && a.sourceContentHash !== activeHash;- const isOpen = expanded === a.id;- const full = details[a.id];- return (- <li key={a.id} className="border border-port-border rounded">- <button- onClick={() => expand(a)}- className="w-full flex items-center gap-2 px-2 py-1.5 text-left hover:bg-port-bg"- >- <Icon size={12} className="text-gray-400 shrink-0" />- <span className="flex-1 truncate">- {meta.label}- {a.status === 'failed' && <span className="text-port-error"> · failed</span>}- {a.status === 'running' && <span className="text-port-accent"> · running…</span>}- </span>- {stale && (- <span title="Source draft has changed since this analysis ran" className="text-port-warning">- <AlertTriangle size={10} />- </span>- )}- <span className="text-[10px] text-gray-500 shrink-0">{timeAgo(a.completedAt || a.createdAt, '')}</span>- </button>- {isOpen && (- <div className="border-t border-port-border bg-port-bg/40 p-2 space-y-2">- {!full && <div className="text-gray-500">Loading…</div>}- {full?.status === 'failed' && (- <div className="text-port-error text-[11px] whitespace-pre-wrap">{full.error || 'Unknown error'}</div>- )}- {full?.status === 'succeeded' && full.kind === 'evaluate' && (- <EvaluateResult result={full.result} readingTheme={readingTheme} />- )}- {full?.status === 'succeeded' && full.kind === 'format' && (- <FormatResult result={full.result} onApply={(text) => onApplyFormat?.(text)} readingTheme={readingTheme} />- )}- {full?.status === 'succeeded' && full.kind === 'script' && (- <ScriptResult- result={full.result}- workId={work.id}- analysisId={full.id}- sceneImages={full.sceneImages || {}}- workTitle={work.title}- readingTheme={readingTheme}- characters={characters}- />- )}- {full?.status === 'succeeded' && full.kind === 'characters' && (- <CharactersAnalysisResult result={full.result} readingTheme={readingTheme} />- )}- </div>- )}- </li>- );- })}- </ul>- </div>- </div>- );-}--function EvaluateResult({ result, readingTheme = 'dark' }) {- if (!result) return null;- const light = readingTheme === 'light';- const labelCls = `uppercase text-[9px] ${light ? 'text-gray-600' : 'text-gray-500'}`;- return (- <div className={`space-y-2 text-[11px] rounded p-2 ${light ? 'bg-[var(--wr-reading-paper)] text-gray-900' : 'text-gray-300'}`}>- {result.logline && <div><span className={labelCls}>Logline</span><div className="italic">{result.logline}</div></div>}- {result.summary && <div><span className={labelCls}>Summary</span><div>{result.summary}</div></div>}- {result.themes?.length > 0 && (- <div>- <span className={labelCls}>Themes</span>- <div className="flex flex-wrap gap-1 mt-0.5">- {result.themes.map((t, i) => (- <span key={i} className={`px-1.5 py-0.5 border rounded text-[10px] ${light ? 'bg-white border-gray-300 text-gray-800' : 'bg-port-card border-port-border'}`}>{t}</span>- ))}- </div>- </div>- )}- {result.strengths?.length > 0 && (- <div>- <span className={labelCls}>Strengths</span>- <ul className={`list-disc list-inside space-y-0.5 mt-0.5 ${light ? 'text-gray-800' : 'text-gray-400'}`}>- {result.strengths.map((s, i) => <li key={i}>{s}</li>)}- </ul>- </div>- )}- {result.issues?.length > 0 && (- <div>- <span className={labelCls}>Issues</span>- <ul className="space-y-1 mt-0.5">- {result.issues.map((iss, i) => (- <li key={i} className={`pl-2 border-l-2 ${SEVERITY_COLOR[iss.severity] || SEVERITY_COLOR.minor}`}>- <div className="text-[10px] uppercase tracking-wide opacity-80">{iss.severity || 'minor'} · {iss.category || 'note'}</div>- <div>{iss.note}</div>- {iss.excerpt && <div className={`italic mt-0.5 ${light ? 'text-gray-700' : 'text-gray-500'}`}>"{iss.excerpt}"</div>}- </li>- ))}- </ul>- </div>- )}- {result.suggestions?.length > 0 && (- <div>- <span className={labelCls}>Suggestions</span>- <ul className="space-y-1 mt-0.5">- {result.suggestions.map((s, i) => (- <li key={i} className="pl-2 border-l-2 border-port-accent/40">- <div className="text-[10px] uppercase tracking-wide opacity-80 text-port-accent">{s.target}</div>- <div>{s.recommendation}</div>- </li>- ))}- </ul>- </div>- )}- </div>- );-}--function FormatResult({ result, onApply, readingTheme = 'dark' }) {- const text = result?.formattedBody || '';- if (!text) return <div className="text-gray-500">Format pass returned no text.</div>;- const light = readingTheme === 'light';- const labelCls = `uppercase text-[9px] ${light ? 'text-gray-600' : 'text-gray-500'}`;- return (- <div className="space-y-2 text-[11px]">- <div className="flex items-center justify-between">- <span className={labelCls}>Cleaned prose ({text.length.toLocaleString()} chars)</span>- <button- onClick={() => onApply?.(text)}- className="flex items-center gap-1 px-2 py-1 bg-port-accent text-white rounded text-[10px] hover:bg-port-accent/80"- title="Replace the current draft buffer with this cleaned text (you can still cancel by not saving)"- >- <Check size={10} /> Apply to draft- </button>- </div>- <pre className={`whitespace-pre-wrap font-serif border rounded p-2 max-h-64 overflow-y-auto ${- light ? 'text-gray-900 bg-[var(--wr-reading-paper)] border-gray-300' : 'text-gray-300 bg-port-bg border-port-border'- }`}>{text}</pre>- </div>- );-}--function ScriptResult({ result, workId, analysisId, sceneImages = {}, workTitle, readingTheme = 'dark', characters = [] }) {- const charByKey = useMemo(() => buildCharByKey(characters), [characters]);- // Image-gen settings are scoped to the Writers Room (not the global Image Gen- // page) so a writer can pick a fast/small model + 3:2 aspect without- // disrupting the dedicated Image Gen workflow.- const [imageCfg, setImageCfg] = useState(WR_IMAGE_DEFAULTS);- const [models, setModels] = useState([]);- const [showSettings, setShowSettings] = useState(false);-- useEffect(() => {- let cancelled = false;- Promise.all([- getSettings().catch(() => ({})),- listImageModels().catch(() => []),- ]).then(([settings, modelList]) => {- if (cancelled) return;- setImageCfg(readWrImageSettings(settings));- setModels(Array.isArray(modelList) ? modelList : []);- });- return () => { cancelled = true; };- }, []);-- const persistCfg = useCallback(async (next) => {- setImageCfg(next); // optimistic- const current = await getSettings().catch(() => ({}));- await updateSettings({- ...current,- writersRoom: { ...(current.writersRoom || {}), imageGen: next },- }).catch((err) => toast.error(`Settings save failed: ${err.message}`));- }, []);-- if (!result || !result.scenes?.length) return <div className="text-gray-500">No scenes returned.</div>;- return (- <div className="space-y-2 text-[11px] text-gray-300">- <div className="flex items-center justify-between gap-2 px-1">- {result.logline ? <div className="italic text-gray-400 truncate">"{result.logline}"</div> : <div />}- <button- onClick={() => setShowSettings((v) => !v)}- className="flex items-center gap-1 text-[10px] text-gray-500 hover:text-white shrink-0"- title="Image-gen settings for this Writers Room"- >- <SettingsIcon size={10} /> {imageCfg.modelId} · {imageCfg.width}×{imageCfg.height}- </button>- </div>- {showSettings && (- <ImageGenSettingsRow cfg={imageCfg} models={models} onChange={persistCfg} />- )}- {result.scenes.map((scene, i) => {- const sceneId = scene.id || `scene-${i}`;- return (- <SceneCard- key={sceneId}- scene={{ ...scene, id: sceneId }}- workId={workId}- analysisId={analysisId}- workTitle={workTitle}- imageCfg={imageCfg}- initialImage={sceneImages[sceneId] || null}- readingTheme={readingTheme}- charByKey={charByKey}- />- );- })}- </div>- );-}--function ImageGenSettingsRow({ cfg, models, onChange }) {- // Resolution presets that match common scene/storyboard aspects. Free-form- // numeric inputs would invite invalid sizes (the FLUX.2 runner needs 64-px- // multiples) so we expose a curated dropdown instead. "Custom" reveals the- // raw inputs for power users who edit settings.json directly anyway.- const RES_PRESETS = [- { label: '768×512 (3:2)', width: 768, height: 512 },- { label: '512×512 (1:1)', width: 512, height: 512 },- { label: '512×768 (2:3)', width: 512, height: 768 },- { label: '1024×576 (16:9)', width: 1024, height: 576 },- { label: '1024×1024 (1:1)', width: 1024, height: 1024 },- ];- const presetMatch = RES_PRESETS.find((p) => p.width === cfg.width && p.height === cfg.height);- return (- <div className="border border-port-border rounded p-2 bg-port-bg/40 space-y-1.5">- <label className="block">- <span className="text-[9px] uppercase tracking-wider text-gray-500">Model</span>- <select- value={cfg.modelId}- onChange={(e) => onChange({ ...cfg, modelId: e.target.value })}- className="w-full mt-0.5 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200"- >- {models.length === 0 && <option value={cfg.modelId}>{cfg.modelId}</option>}- {models.map((m) => (- <option key={m.id} value={m.id}>{m.name || m.id}</option>- ))}- </select>- </label>- <label className="block">- <span className="text-[9px] uppercase tracking-wider text-gray-500">Resolution</span>- <select- value={presetMatch ? `${cfg.width}x${cfg.height}` : 'custom'}- onChange={(e) => {- if (e.target.value === 'custom') return;- const [w, h] = e.target.value.split('x').map(Number);- onChange({ ...cfg, width: w, height: h });- }}- className="w-full mt-0.5 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200"- >- {RES_PRESETS.map((p) => (- <option key={p.label} value={`${p.width}x${p.height}`}>{p.label}</option>- ))}- {!presetMatch && <option value="custom">Custom ({cfg.width}×{cfg.height})</option>}- </select>- </label>- </div>- );-}--// LLM scene lists use bare names ("ARIA"), profiles may use full names-// ("Aria Reyes") or "the bartender" — strip leading "the " and lowercase so-// either side resolves to the same key.-const normCharKey = (s) => String(s || '').trim().toLowerCase().replace(/^the\s+/, '');--// Build a name+alias → profile lookup. One pass at the panel level so chip-// rendering is O(1) per chip instead of O(N) per render.-function buildCharByKey(allCharacters) {- const map = new Map();- for (const profile of allCharacters) {- map.set(normCharKey(profile.name), profile);- for (const alias of profile.aliases || []) map.set(normCharKey(alias), profile);- }- return map;-}--function matchSceneCharacters(sceneCharacterNames = [], charByKey) {- if (!Array.isArray(sceneCharacterNames) || !sceneCharacterNames.length) return [];- const matched = [];- const seen = new Set();- for (const name of sceneCharacterNames) {- const profile = charByKey?.get(normCharKey(name));- if (profile && !seen.has(profile.id)) {- matched.push(profile);- seen.add(profile.id);- }- }- return matched;-}--const PROMPT_MAX = 1900;--// The scene's visualPrompt is the load-bearing part of the image-gen prompt-// (location, action, mood) — it must always survive truncation. Reserve room-// for title + visual prompt first, then fit the "Featuring" block into-// whatever is left, dropping characters one-by-one if needed.-function buildScenePromptWithCharacters(workTitle, scene, matchedCharacters) {- const titlePart = workTitle ? `${workTitle}. ` : '';- const visual = scene.visualPrompt || '';- const featuringFragments = matchedCharacters- .filter((c) => c.physicalDescription && c.physicalDescription.trim())- .map((c) => `${c.name}: ${c.physicalDescription.trim()}`);- const PREFIX = 'Featuring — ';- const reserveForVisual = titlePart.length + visual.length + 1; // +1 for the join space- let budget = PROMPT_MAX - reserveForVisual - PREFIX.length;- const fitFragments = [];- for (const frag of featuringFragments) {- const cost = (fitFragments.length === 0 ? 0 : 1) + frag.length; // +1 for join space- if (cost > budget) break;- fitFragments.push(frag);- budget -= cost;- }- const segs = [titlePart.trim()];- if (fitFragments.length > 0) segs.push(`${PREFIX}${fitFragments.join(' ')}`);- if (visual) segs.push(visual);- return segs.filter(Boolean).join(' ').slice(0, PROMPT_MAX);-}--function SceneCard({ scene, workId, analysisId, workTitle, imageCfg = WR_IMAGE_DEFAULTS, initialImage = null, readingTheme = 'dark', charByKey = null }) {- const light = readingTheme === 'light';- const matchedCharacters = useMemo(- () => matchSceneCharacters(scene.characters, charByKey),- [scene.characters, charByKey]- );- 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));- }- return keys;- }, [matchedCharacters]);- // genStatus drives the button + preview overlay:- // idle → no preview area shown- // running → preview area shows spinner / live diffusion frame from socket- // done → preview area shows the final rendered image- // error → preview area shows the error- // Seed from initialImage so a previously-rendered scene shows its image- // immediately on remount (e.g. after navigating back to the work).- const [genStatus, setGenStatus] = useState(initialImage ? 'done' : 'idle');- const [generated, setGenerated] = useState(initialImage- ? { path: `/data/images/${initialImage.filename}`, jobId: initialImage.jobId, prompt: initialImage.prompt }- : null);- const [error, setError] = useState(null);- // Live diffusion progress for THIS scene's job, filtered by the jobId we- // got back from generateImage. Each SceneCard tracks its own job, so two- // cards rendering at once don't fight over a shared progress hook.- const [progress, setProgress] = useState(null);- const jobIdRef = useRef(null);-- useEffect(() => {- const onStarted = (data) => {- if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;- setProgress((prev) => ({- ...(prev || {}),- progress: 0,- step: 0,- totalSteps: data.totalSteps ?? prev?.totalSteps ?? null,- currentImage: null,- }));- };- const onProgress = (data) => {- if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;- setProgress((prev) => ({- ...(prev || {}),- progress: data.progress ?? prev?.progress ?? 0,- step: data.step ?? prev?.step ?? 0,- totalSteps: data.totalSteps ?? prev?.totalSteps ?? null,- eta: data.eta ?? prev?.eta ?? null,- currentImage: data.currentImage ?? prev?.currentImage ?? null,- }));- };- const onCompleted = (data) => {- if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;- const completedJobId = jobIdRef.current;- setGenerated((prev) => prev ? { ...prev, path: data.path || prev.path } : prev);- setGenStatus('done');- setProgress(null);- jobIdRef.current = null;- // Persist the scene→image link so the user sees the same image when- // they navigate back. The image filename is `<jobId>.png` per the local- // image-gen route's response shape.- if (workId && analysisId && scene.id) {- attachWritersRoomSceneImage(workId, analysisId, {- sceneId: scene.id,- filename: `${completedJobId}.png`,- jobId: completedJobId,- prompt: data.prompt || null,- }).catch((err) => {- console.warn(`scene-image persist failed: ${err.message}`);- });- }- };- const onFailed = (data) => {- if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;- setError(data.error || data.message || 'Generation failed');- setGenStatus('error');- setProgress(null);- jobIdRef.current = null;- };- 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);- };- }, [workId, analysisId, scene.id]);-- const generate = async () => {- if (genStatus === 'running') return;- if (!scene.visualPrompt?.trim()) {- toast('No visual prompt for this scene', { icon: '⚠️' });- return;- }- setGenStatus('running');- setError(null);- setProgress(null);- setGenerated(null);- const prompt = buildScenePromptWithCharacters(workTitle, scene, matchedCharacters);- const res = await generateImage({- prompt,- modelId: imageCfg.modelId,- mode: imageCfg.mode,- width: imageCfg.width,- height: imageCfg.height,- }).catch((err) => {- setError(err.message);- setGenStatus('error');- return null;- });- if (!res) return;- // Local mode returns a queued/running status and the canonical path; the- // PNG lands there once the queue worker emits `image-gen:completed`.- // External/codex modes return synchronously with the image already on disk.- jobIdRef.current = res.jobId || res.generationId || null;- setGenerated({ path: res.path, jobId: res.jobId, prompt });- if (res.status !== 'queued' && res.status !== 'running') {- setGenStatus('done');- }- };-- const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;- // `view` collapses the (genStatus, progress, generated) tuple to a single- // discriminator so the preview-area JSX is one switch instead of nested- // ternaries.- const view = progress?.currentImage ? 'live'- : genStatus === 'done' && generated?.path ? 'final'- : genStatus === 'running' ? 'spinner'- : genStatus === 'error' ? 'error'- : null;- const showPreviewArea = view !== null;-- return (- <div className={`border rounded p-2 space-y-1.5 ${- light ? 'border-gray-300 bg-[var(--wr-reading-paper)] text-gray-900' : 'border-port-border bg-port-card/40'- }`}>- <div className="flex items-start gap-2">- <div className="flex-1 min-w-0">- <div className={`font-semibold truncate ${light ? 'text-gray-900' : 'text-white'}`}>{scene.heading}</div>- {scene.slugline && <div className="text-[10px] text-port-accent uppercase tracking-wide">{scene.slugline}</div>}- </div>- <button- onClick={generate}- disabled={genStatus === 'running'}- className="flex items-center gap-1 px-2 py-1 bg-port-bg border border-port-border rounded text-[10px] text-gray-300 hover:border-port-accent hover:text-white disabled:opacity-50"- title="Queue an image render using this scene's visual prompt"- >- {genStatus === 'running' ? <Loader2 size={10} className="animate-spin" /> : <ImageIcon size={10} />}- {genStatus === 'running' ? 'Rendering…' : genStatus === 'done' ? 'Re-render' : 'Image'}- </button>- </div>-- {showPreviewArea && (- <div- style={{ aspectRatio: `${imageCfg.width} / ${imageCfg.height}` }}- className="w-full bg-port-bg border border-port-border rounded-lg overflow-hidden flex items-center justify-center relative">- {view === 'live' && (- <img- src={`data:image/png;base64,${progress.currentImage}`}- alt="Diffusing…"- decoding="async"- className="w-full h-full object-contain"- />- )}- {view === 'final' && (- <a href={generated.path} target="_blank" rel="noreferrer" className="block w-full h-full">- <img- src={generated.path}- alt={scene.heading}- loading="lazy"- className="w-full h-full object-contain"- onError={(e) => { e.currentTarget.style.display = 'none'; }}- />- </a>- )}- {view === 'spinner' && (- <div className="text-gray-500 text-xs flex flex-col items-center gap-2 px-3 text-center">- <Loader2 size={20} className="animate-spin text-port-accent" />- <span className="font-medium text-gray-300">- {progress?.step != null && progress?.totalSteps- ? `Step ${progress.step}/${progress.totalSteps}`- : 'Queued — waiting for first preview…'}- </span>- {progress?.eta != null && (- <span className="text-[10px] text-gray-500">~{Math.max(0, Math.round(progress.eta))}s remaining</span>- )}- </div>- )}- {view === 'error' && (- <div className="text-port-error text-xs px-3 text-center break-words">- {error || 'Generation failed'}- </div>- )}-- {genStatus === 'running' && progressPct != null && (- <div className="absolute bottom-0 left-0 right-0 h-1 bg-black/50">- <div className="h-full bg-port-accent transition-all" style={{ width: `${progressPct}%` }} />- </div>- )}- </div>- )}- {genStatus === 'done' && generated?.jobId && (- <div className="text-[9px] text-gray-500 truncate">job {generated.jobId}</div>- )}-- {scene.summary && <div className={light ? 'text-gray-700' : 'text-gray-400'}>{scene.summary}</div>}- {scene.characters?.length > 0 && (- <div className="flex flex-wrap gap-1">- {scene.characters.map((c, i) => {- const isMatched = matchedNameKeys.has(normCharKey(c));- return (- <span- key={i}- title={isMatched ? 'Profile linked — physical description injected into image prompt' : 'No matching profile — run Characters to add'}- 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'- }`}>- {c}- </span>- );- })}- </div>- )}- {scene.action && (- <div className={`whitespace-pre-wrap font-serif ${light ? 'text-gray-900' : 'text-gray-300'}`}>{scene.action}</div>- )}- {scene.dialogue?.length > 0 && (- <div className={`space-y-1 pl-3 border-l ${light ? 'border-gray-400' : 'border-port-border'}`}>- {scene.dialogue.map((d, i) => (- <div key={i}>- <div className={`text-[9px] uppercase tracking-wider ${light ? 'text-gray-600' : 'text-gray-500'}`}>{d.character}</div>- <div className={`italic ${light ? 'text-gray-900' : 'text-gray-300'}`}>"{d.line}"</div>- </div>- ))}- </div>- )}- {scene.visualPrompt && (- <details className="text-[10px] text-gray-500">- <summary className="cursor-pointer hover:text-white">Visual prompt</summary>- <div className="mt-1 italic">{scene.visualPrompt}</div>- </details>- )}- </div>- );-}--// ---------- character bible (editable, persistent across analysis runs) ------------const CHARACTER_FIELDS = [- { key: 'aliases', label: 'Aliases', placeholder: 'nicknames, titles (comma-separated)', kind: 'csv' },- { key: 'role', label: 'Role', placeholder: 'protagonist, mentor, antagonist…', kind: 'text' },- { key: 'physicalDescription', label: 'Physical description', placeholder: 'Age, build, hair, eyes, distinctive features, signature wardrobe. Used directly in image-gen prompts.', kind: 'multiline' },- { key: 'personality', label: 'Personality', placeholder: 'Temperament, voice, quirks', kind: 'multiline' },- { key: 'background', label: 'Background', placeholder: 'Who they are, where they come from', kind: 'multiline' },- { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline' },-];--function CharactersBible({ workId, characters, onLocalChange, onLocalDelete, readingTheme }) {- const [editingId, setEditingId] = useState(null);- const [creating, setCreating] = useState(false);-- return (- <div>- <div className="flex items-center justify-between mb-1.5">- <h3 className="text-[10px] uppercase tracking-wider text-gray-500">Characters</h3>- <button- onClick={() => { setCreating(true); setEditingId(null); }}- className="flex items-center gap-1 text-[10px] text-gray-500 hover:text-port-accent"- title="Add a character profile manually"- >- <Plus size={11} /> Add- </button>- </div>-- {characters.length === 0 && !creating && (- <div className="text-gray-600 italic px-1 mb-2">- No profiles yet. Run <span className="text-gray-400">Characters</span> to extract from prose, or add one manually.- </div>- )}-- {creating && (- <CharacterEditor- workId={workId}- character={null}- onSaved={(c) => { onLocalChange(c); setCreating(false); }}- onCancel={() => setCreating(false)}- readingTheme={readingTheme}- />- )}-- <ul className="space-y-1">- {characters.map((c) => {- const isEditing = editingId === c.id;- if (isEditing) {- return (- <li key={c.id}>- <CharacterEditor- workId={workId}- character={c}- onSaved={(updated) => { onLocalChange(updated); setEditingId(null); }}- onDeleted={() => { onLocalDelete(c.id); setEditingId(null); }}- onCancel={() => setEditingId(null)}- readingTheme={readingTheme}- />- </li>- );- }- return (- <li key={c.id} className="border border-port-border rounded">- <CharacterRow character={c} onEdit={() => setEditingId(c.id)} readingTheme={readingTheme} />- </li>- );- })}- </ul>- </div>- );-}--function CharacterRow({ character, onEdit, readingTheme }) {- const light = readingTheme === 'light';- const blanks = CHARACTER_FIELDS.filter((f) => {- if (f.key === 'notes' || f.key === 'aliases') return false;- return !String(character[f.key] || '').trim();- });- return (- <div className="px-2 py-1.5">- <div className="flex items-start gap-2">- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 flex-wrap">- <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{character.name}</span>- {character.role && (- <span className="text-[9px] uppercase tracking-wider text-port-accent">{character.role}</span>- )}- {character.source === 'ai' && (- <span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">ai</span>- )}- {character.aliases?.length > 0 && (- <span className="text-[10px] text-gray-500 truncate">aka {character.aliases.join(', ')}</span>- )}- </div>- {character.physicalDescription ? (- <div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>- {character.physicalDescription}- </div>- ) : (- <div className="text-[11px] mt-0.5 text-port-warning italic">No physical description — image gen will use scene context only</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>- )}- {character.missingFromProse?.length > 0 && (- <div className="text-[10px] text-gray-500 mt-1">- <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {character.missingFromProse.join(', ')}- </div>- )}- </div>- <button- onClick={onEdit}- className="text-gray-500 hover:text-port-accent shrink-0"- title="Edit profile"- aria-label={`Edit ${character.name}`}- >- <Pencil size={11} />- </button>- </div>- </div>- );-}--function CharacterEditor({ workId, character, onSaved, onDeleted, onCancel, readingTheme }) {- const isCreate = !character;- const [draft, setDraft] = useState(() => {- const seed = { name: character?.name || '' };- for (const f of CHARACTER_FIELDS) {- seed[f.key] = f.kind === 'csv' ? (character?.[f.key] || []).join(', ') : (character?.[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() };- for (const f of CHARACTER_FIELDS) {- payload[f.key] = f.kind === 'csv'- ? draft[f.key].split(',').map((s) => s.trim()).filter(Boolean)- : draft[f.key];- }- const result = await (isCreate- ? createWritersRoomCharacter(workId, payload)- : updateWritersRoomCharacter(workId, character.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 (!character) return;- setSaving(true);- const ok = await deleteWritersRoomCharacter(workId, character.id).then(() => true).catch((err) => {- toast.error(`Delete failed: ${err.message}`);- return false;- });- setSaving(false);- if (ok) {- toast.success(`${character.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="Character name"- className={`${inputCls} font-semibold`}- />- <button- onClick={onCancel}- className="text-gray-500 hover:text-white shrink-0"- aria-label="Cancel edit"- title="Cancel"- >- <X size={12} />- </button>- </div>- {CHARACTER_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.key === 'physicalDescription' ? 3 : 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>- );-}--// Read-only summary of the most recent characters analysis snapshot, shown in-// the History expander. The editable bible above is the source of truth for-// scene-image injection — this view exists so the user can compare what came-// back from this specific run against what's now in the bible.-function CharactersAnalysisResult({ result, readingTheme }) {- const light = readingTheme === 'light';- const list = result?.characters || [];- if (!list.length) return <div className="text-gray-500">No characters returned.</div>;- return (- <div className={`space-y-2 text-[11px] ${light ? 'text-gray-900' : 'text-gray-300'}`}>- <div className="text-[10px] text-gray-500">- {list.length} character{list.length === 1 ? '' : 's'} extracted. Edits to the bible above persist across re-runs.- </div>- <ul className="space-y-1.5">- {list.map((c, i) => (- <li key={i} className={`border rounded p-2 ${light ? 'border-gray-300 bg-white' : 'border-port-border bg-port-bg/40'}`}>- <div className="flex items-center gap-2 flex-wrap">- <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{c.name}</span>- {c.role && <span className="text-[9px] uppercase tracking-wider text-port-accent">{c.role}</span>}- </div>- {c.physicalDescription && (- <div className={`mt-1 ${light ? 'text-gray-700' : 'text-gray-400'}`}>{c.physicalDescription}</div>- )}- {c.missingFromProse?.length > 0 && (- <div className="text-[10px] text-port-warning mt-1">- Prose gaps: {c.missingFromProse.join(', ')}- </div>- )}- </li>- ))}- </ul>- </div>- );-}diff --git a/client/src/components/writers-room/AnalysisHistory.jsx b/client/src/components/writers-room/AnalysisHistory.jsxnew file mode 100644index 0000000000..645963912c--- /dev/null+++ b/client/src/components/writers-room/AnalysisHistory.jsx@@ -0,0 +1,224 @@+import { useEffect, useRef, useState } from 'react';+import { AlertTriangle, Check, Clapperboard, FileSignature, Loader2, RotateCcw, Sparkles, Users } from 'lucide-react';+import toast from '../ui/Toast';+import { listWritersRoomAnalyses, getWritersRoomAnalysis } from '../../services/apiWritersRoom';+import { timeAgo } from '../../utils/formatters';++const KIND_ICON = { evaluate: Sparkles, format: FileSignature, script: Clapperboard, characters: Users };+const KIND_LABEL = { evaluate: 'Evaluate', format: 'Format', script: 'Adapt', characters: 'Characters' };++const SEVERITY_COLOR = {+ major: 'text-port-error border-port-error/40',+ moderate: 'text-port-warning border-port-warning/40',+ minor: 'text-gray-400 border-port-border',+};++// Read-only history of past Evaluate / Format / Adapt / Characters runs.+// "Apply" actions for Format pass go through onApplyFormat — caller hooks+// this to the prose buffer (currently only WorkEditor needs that).+export default function AnalysisHistory({ work, activeHash, onApplyFormat }) {+ const [analyses, setAnalyses] = useState([]);+ const [loading, setLoading] = useState(false);+ const [details, setDetails] = useState({});+ const [expanded, setExpanded] = useState(null);+ const mountedRef = useRef(true);++ useEffect(() => {+ mountedRef.current = true;+ return () => { mountedRef.current = false; };+ }, []);++ const refresh = async () => {+ setLoading(true);+ const list = await listWritersRoomAnalyses(work.id).catch(() => []);+ if (!mountedRef.current) return;+ setLoading(false);+ setAnalyses(list);+ };++ useEffect(() => {+ setAnalyses([]);+ setExpanded(null);+ setDetails({});+ refresh();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [work.id]);++ const expand = async (analysis) => {+ if (expanded === analysis.id) {+ setExpanded(null);+ return;+ }+ setExpanded(analysis.id);+ if (details[analysis.id]) return;+ const full = await getWritersRoomAnalysis(work.id, analysis.id).catch((err) => {+ if (mountedRef.current) toast.error(`Failed to load analysis: ${err.message}`);+ return null;+ });+ if (full && mountedRef.current) setDetails((d) => ({ ...d, [analysis.id]: full }));+ };++ return (+ <div className="text-xs">+ <div className="flex items-center justify-between mb-2">+ <div className="text-[11px] text-gray-500">{analyses.length} run{analyses.length === 1 ? '' : 's'}</div>+ <button+ onClick={refresh}+ disabled={loading}+ className="text-gray-500 hover:text-white disabled:opacity-50"+ aria-label="Refresh"+ >+ <RotateCcw size={12} className={loading ? 'animate-spin' : ''} />+ </button>+ </div>+ {analyses.length === 0 && !loading && (+ <div className="text-gray-500 italic">No analyses yet — run one from the work menu.</div>+ )}+ <ul className="space-y-1.5">+ {analyses.map((a) => {+ const Icon = KIND_ICON[a.kind] || Sparkles;+ const stale = a.sourceContentHash && activeHash && a.sourceContentHash !== activeHash;+ const isOpen = expanded === a.id;+ const full = details[a.id];+ return (+ <li key={a.id} className="border border-port-border rounded">+ <button+ onClick={() => expand(a)}+ className="w-full flex items-center gap-2 px-2 py-1.5 text-left hover:bg-port-bg"+ >+ <Icon size={12} className="text-gray-400 shrink-0" />+ <span className="flex-1 truncate">+ {KIND_LABEL[a.kind] || a.kind}+ {a.status === 'failed' && <span className="text-port-error"> · failed</span>}+ {a.status === 'running' && <span className="text-port-accent"> · running…</span>}+ </span>+ {stale && (+ <span title="Source draft has changed since this analysis ran" className="text-port-warning">+ <AlertTriangle size={10} />+ </span>+ )}+ <span className="text-[10px] text-gray-500 shrink-0">{timeAgo(a.completedAt || a.createdAt, '')}</span>+ </button>+ {isOpen && (+ <div className="border-t border-port-border bg-port-bg/40 p-2 space-y-2">+ {!full && <div className="text-gray-500">Loading…</div>}+ {full?.status === 'failed' && (+ <div className="text-port-error text-[11px] whitespace-pre-wrap">{full.error || 'Unknown error'}</div>+ )}+ {full?.status === 'succeeded' && full.kind === 'evaluate' && (+ <EvaluateResult result={full.result} />+ )}+ {full?.status === 'succeeded' && full.kind === 'format' && (+ <FormatResult result={full.result} onApply={onApplyFormat} />+ )}+ {full?.status === 'succeeded' && full.kind === 'script' && (+ <ScriptSummary result={full.result} count={full.result?.scenes?.length || 0} />+ )}+ {full?.status === 'succeeded' && full.kind === 'characters' && (+ <CharactersSummary result={full.result} />+ )}+ </div>+ )}+ </li>+ );+ })}+ </ul>+ </div>+ );+}++function EvaluateResult({ result }) {+ if (!result) return null;+ const labelCls = 'uppercase text-[9px] text-gray-500';+ return (+ <div className="space-y-2 text-[11px] text-gray-300">+ {result.logline && <div><span className={labelCls}>Logline</span><div className="italic">{result.logline}</div></div>}+ {result.summary && <div><span className={labelCls}>Summary</span><div>{result.summary}</div></div>}+ {result.themes?.length > 0 && (+ <div>+ <span className={labelCls}>Themes</span>+ <div className="flex flex-wrap gap-1 mt-0.5">+ {result.themes.map((t, i) => (+ <span key={i} className="px-1.5 py-0.5 border rounded text-[10px] bg-port-card border-port-border">{t}</span>+ ))}+ </div>+ </div>+ )}+ {result.strengths?.length > 0 && (+ <div>+ <span className={labelCls}>Strengths</span>+ <ul className="list-disc list-inside space-y-0.5 mt-0.5 text-gray-400">+ {result.strengths.map((s, i) => <li key={i}>{s}</li>)}+ </ul>+ </div>+ )}+ {result.issues?.length > 0 && (+ <div>+ <span className={labelCls}>Issues</span>+ <ul className="space-y-1 mt-0.5">+ {result.issues.map((iss, i) => (+ <li key={i} className={`pl-2 border-l-2 ${SEVERITY_COLOR[iss.severity] || SEVERITY_COLOR.minor}`}>+ <div className="text-[10px] uppercase tracking-wide opacity-80">{iss.severity || 'minor'} · {iss.category || 'note'}</div>+ <div>{iss.note}</div>+ {iss.excerpt && <div className="italic mt-0.5 text-gray-500">"{iss.excerpt}"</div>}+ </li>+ ))}+ </ul>+ </div>+ )}+ {result.suggestions?.length > 0 && (+ <div>+ <span className={labelCls}>Suggestions</span>+ <ul className="space-y-1 mt-0.5">+ {result.suggestions.map((s, i) => (+ <li key={i} className="pl-2 border-l-2 border-port-accent/40">+ <div className="text-[10px] uppercase tracking-wide opacity-80 text-port-accent">{s.target}</div>+ <div>{s.recommendation}</div>+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ );+}++function FormatResult({ result, onApply }) {+ const text = result?.formattedBody || '';+ if (!text) return <div className="text-gray-500">Format pass returned no text.</div>;+ return (+ <div className="space-y-2 text-[11px]">+ <div className="flex items-center justify-between">+ <span className="uppercase text-[9px] text-gray-500">Cleaned prose ({text.length.toLocaleString()} chars)</span>+ {onApply && (+ <button+ onClick={() => onApply(text)}+ className="flex items-center gap-1 px-2 py-1 bg-port-accent text-white rounded text-[10px] hover:bg-port-accent/80"+ >+ <Check size={10} /> Apply to draft+ </button>+ )}+ </div>+ <pre className="whitespace-pre-wrap font-serif text-gray-300 bg-port-bg border border-port-border rounded p-2 max-h-64 overflow-y-auto">{text}</pre>+ </div>+ );+}++function ScriptSummary({ result, count }) {+ return (+ <div className="text-[11px] text-gray-400">+ {count} scene{count === 1 ? '' : 's'} captured. The storyboard sidebar shows them — scene-level images live there.+ {result?.logline && <div className="italic text-gray-500 mt-1">"{result.logline}"</div>}+ </div>+ );+}++function CharactersSummary({ result }) {+ const list = result?.characters || [];+ if (!list.length) return <div className="text-gray-500">No characters returned.</div>;+ return (+ <div className="text-[11px] text-gray-400">+ {list.length} character{list.length === 1 ? '' : 's'} extracted. Open the Characters drawer to edit the bible.+ </div>+ );+}diff --git a/client/src/components/writers-room/CharactersBible.jsx b/client/src/components/writers-room/CharactersBible.jsxnew file mode 100644index 0000000000..d912edbb32--- /dev/null+++ b/client/src/components/writers-room/CharactersBible.jsx@@ -0,0 +1,281 @@+import { useEffect, useRef, useState } from 'react';+import { AlertTriangle, Check, Loader2, Pencil, Plus, Trash2, X } from 'lucide-react';+import toast from '../ui/Toast';+import {+ listWritersRoomCharacters,+ createWritersRoomCharacter,+ updateWritersRoomCharacter,+ deleteWritersRoomCharacter,+} from '../../services/apiWritersRoom';++const CHARACTER_FIELDS = [+ { key: 'aliases', label: 'Aliases', placeholder: 'nicknames, titles (comma-separated)', kind: 'csv' },+ { key: 'role', label: 'Role', placeholder: 'protagonist, mentor, antagonist…', kind: 'text' },+ { key: 'physicalDescription', label: 'Physical description', placeholder: 'Age, build, hair, eyes, distinctive features, signature wardrobe. Used directly in image-gen prompts.', kind: 'multiline' },+ { key: 'personality', label: 'Personality', placeholder: 'Temperament, voice, quirks', kind: 'multiline' },+ { key: 'background', label: 'Background', placeholder: 'Who they are, where they come from', kind: 'multiline' },+ { key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline' },+];++// Character bible — editable, persistent across analysis runs. Used by image+// gen to inject physicalDescription into per-scene prompts.+export default function CharactersBible({ workId, characters: charactersProp, onCharactersChange, readingTheme = 'dark' }) {+ // Internal vs. controlled: caller can pass `characters` to keep multiple+ // mounts in sync (e.g. drawer + storyboard chip count). When omitted we+ // fetch and own the list ourselves so this can stand alone.+ const [internalCharacters, setInternalCharacters] = useState(charactersProp || []);+ const characters = charactersProp ?? internalCharacters;+ const [editingId, setEditingId] = useState(null);+ const [creating, setCreating] = useState(false);+ const [loading, setLoading] = useState(false);+ const mountedRef = useRef(true);+ useEffect(() => {+ mountedRef.current = true;+ return () => { mountedRef.current = false; };+ }, []);++ useEffect(() => {+ if (charactersProp) return; // controlled — caller is fetching+ if (!workId) return;+ setLoading(true);+ listWritersRoomCharacters(workId)+ .then((list) => { if (mountedRef.current) setInternalCharacters(list); })+ .catch(() => { if (mountedRef.current) setInternalCharacters([]); })+ .finally(() => { if (mountedRef.current) setLoading(false); });+ }, [workId, charactersProp]);++ const upsert = (next) => {+ const update = (prev) => {+ const idx = prev.findIndex((c) => c.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);+ };+ setInternalCharacters(update);+ onCharactersChange?.(update(characters));+ };++ const removeOne = (id) => {+ const next = characters.filter((c) => c.id !== id);+ setInternalCharacters(next);+ onCharactersChange?.(next);+ };++ return (+ <div className="text-xs">+ <div className="flex items-center justify-between mb-2">+ <div className="text-[11px] text-gray-500">+ {characters.length} character{characters.length === 1 ? '' : 's'} · Edits persist across re-runs and feed image gen.+ </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 && characters.length === 0 && (+ <div className="text-gray-500 italic">Loading…</div>+ )}++ {!loading && characters.length === 0 && !creating && (+ <div className="text-gray-500 italic px-1 mb-2">+ No profiles yet. Run "Refresh Characters" from the work menu, or add one manually.+ </div>+ )}++ {creating && (+ <CharacterEditor+ workId={workId}+ character={null}+ onSaved={(c) => { upsert(c); setCreating(false); }}+ onCancel={() => setCreating(false)}+ />+ )}++ <ul className="space-y-1.5">+ {characters.map((c) => {+ const isEditing = editingId === c.id;+ if (isEditing) {+ return (+ <li key={c.id}>+ <CharacterEditor+ workId={workId}+ character={c}+ onSaved={(updated) => { upsert(updated); setEditingId(null); }}+ onDeleted={() => { removeOne(c.id); setEditingId(null); }}+ onCancel={() => setEditingId(null)}+ />+ </li>+ );+ }+ return (+ <li key={c.id} className="border border-port-border rounded">+ <CharacterRow character={c} onEdit={() => setEditingId(c.id)} readingTheme={readingTheme} />+ </li>+ );+ })}+ </ul>+ </div>+ );+}++function CharacterRow({ character, onEdit, readingTheme }) {+ const light = readingTheme === 'light';+ const blanks = CHARACTER_FIELDS.filter((f) => {+ if (f.key === 'notes' || f.key === 'aliases') return false;+ return !String(character[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">+ <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{character.name}</span>+ {character.role && (+ <span className="text-[9px] uppercase tracking-wider text-port-accent">{character.role}</span>+ )}+ {character.source === 'ai' && (+ <span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">ai</span>+ )}+ {character.aliases?.length > 0 && (+ <span className="text-[10px] text-gray-500 truncate">aka {character.aliases.join(', ')}</span>+ )}+ </div>+ {character.physicalDescription ? (+ <div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>+ {character.physicalDescription}+ </div>+ ) : (+ <div className="text-[11px] mt-0.5 text-port-warning italic">No physical description — image gen will use scene context only</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>+ )}+ {character.missingFromProse?.length > 0 && (+ <div className="text-[10px] text-gray-500 mt-1">+ <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {character.missingFromProse.join(', ')}+ </div>+ )}+ </div>+ <button+ onClick={onEdit}+ className="text-gray-500 hover:text-port-accent shrink-0"+ title="Edit profile"+ aria-label={`Edit ${character.name}`}+ >+ <Pencil size={11} />+ </button>+ </div>+ </div>+ );+}++function CharacterEditor({ workId, character, onSaved, onDeleted, onCancel }) {+ const isCreate = !character;+ const [draft, setDraft] = useState(() => {+ const seed = { name: character?.name || '' };+ for (const f of CHARACTER_FIELDS) {+ seed[f.key] = f.kind === 'csv' ? (character?.[f.key] || []).join(', ') : (character?.[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() };+ for (const f of CHARACTER_FIELDS) {+ payload[f.key] = f.kind === 'csv'+ ? draft[f.key].split(',').map((s) => s.trim()).filter(Boolean)+ : draft[f.key];+ }+ const result = await (isCreate+ ? createWritersRoomCharacter(workId, payload)+ : updateWritersRoomCharacter(workId, character.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 (!character) return;+ setSaving(true);+ const ok = await deleteWritersRoomCharacter(workId, character.id).then(() => true).catch((err) => {+ toast.error(`Delete failed: ${err.message}`);+ return false;+ });+ setSaving(false);+ if (ok) {+ toast.success(`${character.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="Character name"+ className={`${inputCls} font-semibold`}+ />+ <button+ onClick={onCancel}+ className="text-gray-500 hover:text-white shrink-0"+ aria-label="Cancel edit"+ title="Cancel"+ >+ <X size={12} />+ </button>+ </div>+ {CHARACTER_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.key === 'physicalDescription' ? 3 : 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/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsxnew file mode 100644index 0000000000..683aaad172--- /dev/null+++ b/client/src/components/writers-room/SceneCard.jsx@@ -0,0 +1,340 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import {+ Image as ImageIcon,+ Loader2,+ MoreHorizontal,+ Sparkles,+ Users,+ FileSignature,+ Crosshair,+} from 'lucide-react';+import toast from '../ui/Toast';+import { generateImage } from '../../services/apiSystem';+import {+ attachWritersRoomSceneImage,+} from '../../services/apiWritersRoom';+import socket from '../../services/socket';+import {+ WR_IMAGE_DEFAULTS,+ buildScenePromptWithCharacters,+ matchSceneCharacters,+ normCharKey,+} from './sceneCardHelpers';++// One scene in the storyboard. Renders heading, image (or empty/in-progress+// state), characters, action/dialogue snippets, and a per-card Debug menu that+// scopes AI tools (re-extract scene, check characters, why this image) to this+// one scene.+export default function SceneCard({+ scene,+ workId,+ analysisId,+ workTitle,+ imageCfg = WR_IMAGE_DEFAULTS,+ initialImage = null,+ readingTheme = 'dark',+ charByKey = null,+ isActive = false,+ onJumpToProse = null,+ onDebug = null,+}) {+ const light = readingTheme === 'light';+ const matchedCharacters = useMemo(+ () => matchSceneCharacters(scene.characters, charByKey),+ [scene.characters, charByKey]+ );+ 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));+ }+ return keys;+ }, [matchedCharacters]);++ const [genStatus, setGenStatus] = useState(initialImage ? 'done' : 'idle');+ const [generated, setGenerated] = useState(initialImage+ ? { path: `/data/images/${initialImage.filename}`, jobId: initialImage.jobId, prompt: initialImage.prompt }+ : null);+ const [error, setError] = useState(null);+ const [progress, setProgress] = useState(null);+ const [showDebugMenu, setShowDebugMenu] = useState(false);+ const jobIdRef = useRef(null);+ const debugMenuRef = useRef(null);++ // initialImage prop changes when the parent reloads analyses (e.g. after a+ // re-Adapt). Sync the local rendered state so a fresh image actually appears+ // without needing the user to re-click Generate.+ useEffect(() => {+ if (!initialImage) return;+ setGenerated({+ path: `/data/images/${initialImage.filename}`,+ jobId: initialImage.jobId,+ prompt: initialImage.prompt,+ });+ setGenStatus('done');+ }, [initialImage?.filename]);++ useEffect(() => {+ if (!showDebugMenu) return;+ const onClick = (e) => {+ if (!debugMenuRef.current?.contains(e.target)) setShowDebugMenu(false);+ };+ window.addEventListener('mousedown', onClick);+ return () => window.removeEventListener('mousedown', onClick);+ }, [showDebugMenu]);++ useEffect(() => {+ const onStarted = (data) => {+ if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;+ setProgress((prev) => ({+ ...(prev || {}),+ progress: 0,+ step: 0,+ totalSteps: data.totalSteps ?? prev?.totalSteps ?? null,+ currentImage: null,+ }));+ };+ const onProgress = (data) => {+ if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;+ setProgress((prev) => ({+ ...(prev || {}),+ progress: data.progress ?? prev?.progress ?? 0,+ step: data.step ?? prev?.step ?? 0,+ totalSteps: data.totalSteps ?? prev?.totalSteps ?? null,+ eta: data.eta ?? prev?.eta ?? null,+ currentImage: data.currentImage ?? prev?.currentImage ?? null,+ }));+ };+ const onCompleted = (data) => {+ if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;+ const completedJobId = jobIdRef.current;+ setGenerated((prev) => prev ? { ...prev, path: data.path || prev.path } : prev);+ setGenStatus('done');+ setProgress(null);+ jobIdRef.current = null;+ if (workId && analysisId && scene.id) {+ attachWritersRoomSceneImage(workId, analysisId, {+ sceneId: scene.id,+ filename: `${completedJobId}.png`,+ jobId: completedJobId,+ prompt: data.prompt || null,+ }).catch((err) => {+ console.warn(`scene-image persist failed: ${err.message}`);+ });+ }+ };+ const onFailed = (data) => {+ if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;+ setError(data.error || data.message || 'Generation failed');+ setGenStatus('error');+ setProgress(null);+ jobIdRef.current = null;+ };+ 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);+ };+ }, [workId, analysisId, scene.id]);++ const generate = async () => {+ if (genStatus === 'running') return;+ if (!scene.visualPrompt?.trim()) {+ toast('No visual prompt for this scene', { icon: '⚠️' });+ return;+ }+ setGenStatus('running');+ setError(null);+ setProgress(null);+ setGenerated(null);+ const prompt = buildScenePromptWithCharacters(workTitle, scene, matchedCharacters);+ const res = await generateImage({+ prompt,+ modelId: imageCfg.modelId,+ mode: imageCfg.mode,+ width: imageCfg.width,+ height: imageCfg.height,+ }).catch((err) => {+ setError(err.message);+ setGenStatus('error');+ return null;+ });+ if (!res) return;+ jobIdRef.current = res.jobId || res.generationId || null;+ setGenerated({ path: res.path, jobId: res.jobId, prompt });+ if (res.status !== 'queued' && res.status !== 'running') {+ setGenStatus('done');+ }+ };++ const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;+ const view = progress?.currentImage ? 'live'+ : genStatus === 'done' && generated?.path ? 'final'+ : genStatus === 'running' ? 'spinner'+ : genStatus === 'error' ? 'error'+ : 'placeholder';++ const cardBorder = isActive+ ? 'border-port-accent shadow-[0_0_0_1px_rgba(59,130,246,0.5)]'+ : light ? 'border-gray-300' : 'border-port-border';++ return (+ <div+ data-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'+ }`}+ >+ <div className="flex items-start gap-2">+ <button+ type="button"+ onClick={onJumpToProse}+ disabled={!onJumpToProse}+ className="flex-1 min-w-0 text-left disabled:cursor-default"+ title={onJumpToProse ? 'Jump to this scene in the prose' : undefined}+ >+ <div className={`font-semibold truncate text-[12px] ${light ? 'text-gray-900' : 'text-white'}`}>+ {scene.heading}+ </div>+ {scene.slugline && (+ <div className="text-[10px] text-port-accent uppercase tracking-wide truncate">+ {scene.slugline}+ </div>+ )}+ </button>+ <button+ onClick={generate}+ disabled={genStatus === 'running'}+ className="flex items-center gap-1 px-2 py-1 bg-port-bg border border-port-border rounded text-[10px] text-gray-300 hover:border-port-accent hover:text-white disabled:opacity-50"+ title="Queue an image render using this scene's visual prompt"+ >+ {genStatus === 'running' ? <Loader2 size={10} className="animate-spin" /> : <ImageIcon size={10} />}+ {genStatus === 'running' ? '…' : genStatus === 'done' ? '↻' : 'Image'}+ </button>+ {onDebug && (+ <div className="relative" ref={debugMenuRef}>+ <button+ onClick={() => setShowDebugMenu((v) => !v)}+ className="p-1 text-gray-500 hover:text-white"+ aria-label="Debug this scene"+ title="Debug this scene"+ >+ <MoreHorizontal size={14} />+ </button>+ {showDebugMenu && (+ <div className="absolute right-0 top-full mt-1 z-30 w-48 rounded-md border border-port-border bg-port-card shadow-lg py-1 text-[11px]">+ <DebugMenuItem icon={Sparkles} label="Why this image?" onClick={() => { setShowDebugMenu(false); onDebug({ kind: 'why-image', scene }); }} />+ <DebugMenuItem icon={Users} label="Check characters" onClick={() => { setShowDebugMenu(false); onDebug({ kind: 'check-characters', scene }); }} />+ <DebugMenuItem icon={FileSignature} label="Editorial pass" onClick={() => { setShowDebugMenu(false); onDebug({ kind: 'editorial', scene }); }} />+ <DebugMenuItem icon={Crosshair} label="Jump to prose" onClick={() => { setShowDebugMenu(false); onJumpToProse?.(); }} />+ </div>+ )}+ </div>+ )}+ </div>++ <div+ style={{ aspectRatio: `${imageCfg.width} / ${imageCfg.height}` }}+ className="w-full bg-port-bg/60 border border-port-border rounded-lg overflow-hidden flex items-center justify-center relative">+ {view === 'live' && (+ <img+ src={`data:image/png;base64,${progress.currentImage}`}+ alt="Diffusing…"+ decoding="async"+ className="w-full h-full object-contain"+ />+ )}+ {view === 'final' && (+ <a href={generated.path} target="_blank" rel="noreferrer" className="block w-full h-full">+ <img+ src={generated.path}+ alt={scene.heading}+ loading="lazy"+ className="w-full h-full object-contain"+ onError={(e) => { e.currentTarget.style.display = 'none'; }}+ />+ </a>+ )}+ {view === 'spinner' && (+ <div className="text-gray-500 text-[11px] flex flex-col items-center gap-2 px-3 text-center">+ <Loader2 size={20} className="animate-spin text-port-accent" />+ <span className="font-medium text-gray-300">+ {progress?.step != null && progress?.totalSteps+ ? `Step ${progress.step}/${progress.totalSteps}`+ : 'Queued…'}+ </span>+ {progress?.eta != null && (+ <span className="text-[10px] text-gray-500">~{Math.max(0, Math.round(progress.eta))}s</span>+ )}+ </div>+ )}+ {view === 'error' && (+ <div className="text-port-error text-[11px] px-3 text-center break-words">+ {error || 'Generation failed'}+ </div>+ )}+ {view === 'placeholder' && (+ <div className="text-gray-500 text-[10px] flex flex-col items-center gap-1 px-3 text-center">+ <ImageIcon size={18} className="opacity-40" />+ <span>No image yet — click Image</span>+ </div>+ )}++ {genStatus === 'running' && progressPct != null && (+ <div className="absolute bottom-0 left-0 right-0 h-1 bg-black/50">+ <div className="h-full bg-port-accent transition-all" style={{ width: `${progressPct}%` }} />+ </div>+ )}+ </div>++ {scene.summary && (+ <div className={`text-[11px] ${light ? 'text-gray-700' : 'text-gray-400'}`}>{scene.summary}</div>+ )}++ {scene.characters?.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {scene.characters.map((c, i) => {+ const isMatched = matchedNameKeys.has(normCharKey(c));+ return (+ <span+ key={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'+ }`}>+ {c}+ </span>+ );+ })}+ </div>+ )}++ {scene.visualPrompt && (+ <details className="text-[10px] text-gray-500">+ <summary className="cursor-pointer hover:text-white">Visual prompt</summary>+ <div className="mt-1 italic">{scene.visualPrompt}</div>+ </details>+ )}+ </div>+ );+}++function DebugMenuItem({ icon: Icon, label, onClick }) {+ return (+ <button+ type="button"+ onClick={onClick}+ className="w-full flex items-center gap-2 px-3 py-1.5 text-left text-gray-300 hover:bg-port-bg hover:text-white"+ >+ <Icon size={11} className="text-gray-500" /> {label}+ </button>+ );+}diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsxnew file mode 100644index 0000000000..41e883f98b--- /dev/null+++ b/client/src/components/writers-room/StoryboardPanel.jsx@@ -0,0 +1,262 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { Clapperboard, Loader2, RefreshCcw, Settings as SettingsIcon, AlertTriangle } from 'lucide-react';+import toast from '../ui/Toast';+import {+ listWritersRoomAnalyses,+ getWritersRoomAnalysis,+} from '../../services/apiWritersRoom';+import { getSettings, updateSettings } from '../../services/apiSystem';+import { listImageModels } from '../../services/apiImageVideo';+import { timeAgo } from '../../utils/formatters';+import SceneCard from './SceneCard';+import {+ WR_IMAGE_DEFAULTS,+ buildCharByKey,+ readWrImageSettings,+} from './sceneCardHelpers';++// Vertical storyboard companion — the scene-by-scene visual interpretation of+// the active draft. Renders cards from the latest successful Adapt analysis.+// When the Adapt is older than the current draft hash, surfaces a stale+// banner inviting a re-run.+export default function StoryboardPanel({+ work,+ characters = [],+ onJumpToScene,+ onDebug,+ onRunAdapt,+ runningAdapt = false,+ readingTheme = 'dark',+ activeSceneId = null,+}) {+ const [latestScript, setLatestScript] = useState(null);+ const [loading, setLoading] = useState(false);+ const [imageCfg, setImageCfg] = useState(WR_IMAGE_DEFAULTS);+ const [models, setModels] = useState([]);+ const [showSettings, setShowSettings] = useState(false);+ const mountedRef = useRef(true);++ useEffect(() => {+ mountedRef.current = true;+ return () => { mountedRef.current = false; };+ }, []);++ // Image-gen settings + model catalog — fetched once per mount, persisted to+ // settings.json so the user's resolution + model choice sticks.+ useEffect(() => {+ let cancelled = false;+ Promise.all([+ getSettings().catch(() => ({})),+ listImageModels().catch(() => []),+ ]).then(([settings, modelList]) => {+ if (cancelled) return;+ setImageCfg(readWrImageSettings(settings));+ setModels(Array.isArray(modelList) ? modelList : []);+ });+ return () => { cancelled = true; };+ }, []);++ const loadLatestScript = useCallback(async () => {+ setLoading(true);+ const list = await listWritersRoomAnalyses(work.id).catch(() => []);+ if (!mountedRef.current) return;+ const latest = list.find((a) => a.kind === 'script' && a.status === 'succeeded');+ if (!latest) {+ setLatestScript(null);+ setLoading(false);+ return;+ }+ // We need the full snapshot (scenes + sceneImages) — list returns metadata+ // only.+ const full = await getWritersRoomAnalysis(work.id, latest.id).catch(() => null);+ if (!mountedRef.current) return;+ setLatestScript(full);+ setLoading(false);+ }, [work.id]);++ useEffect(() => {+ setLatestScript(null);+ loadLatestScript();+ }, [loadLatestScript]);++ // After Adapt finishes the parent will toggle runningAdapt false — that's+ // our cue to refetch the latest.+ const prevRunning = useRef(runningAdapt);+ useEffect(() => {+ if (prevRunning.current && !runningAdapt) {+ loadLatestScript();+ }+ prevRunning.current = runningAdapt;+ }, [runningAdapt, loadLatestScript]);++ const persistCfg = useCallback(async (next) => {+ setImageCfg(next);+ const current = await getSettings().catch(() => ({}));+ await updateSettings({+ ...current,+ writersRoom: { ...(current.writersRoom || {}), imageGen: next },+ }).catch((err) => toast.error(`Settings save failed: ${err.message}`));+ }, []);++ const charByKey = useMemo(() => buildCharByKey(characters), [characters]);+ const activeDraft = (work.drafts || []).find((d) => d.id === work.activeDraftVersionId);+ const activeHash = activeDraft?.contentHash || null;+ const isStale = !!latestScript?.sourceContentHash && !!activeHash && latestScript.sourceContentHash !== activeHash;+ const scenes = latestScript?.result?.scenes || [];+ const sceneImages = latestScript?.sceneImages || {};++ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center gap-2 px-3 py-2 border-b border-port-border bg-port-bg/40 shrink-0">+ <Clapperboard size={13} className="text-port-accent" />+ <span className="text-[11px] font-semibold text-gray-200 uppercase tracking-wider">Storyboard</span>+ {latestScript && (+ <span className="text-[10px] text-gray-500 truncate">+ {scenes.length} scene{scenes.length === 1 ? '' : 's'} · {timeAgo(latestScript.completedAt || latestScript.createdAt, 'never')}+ </span>+ )}+ <button+ onClick={() => setShowSettings((v) => !v)}+ className="ml-auto text-gray-500 hover:text-white"+ title={`Image gen: ${imageCfg.modelId} · ${imageCfg.width}×${imageCfg.height}`}+ aria-label="Image gen settings"+ >+ <SettingsIcon size={12} />+ </button>+ </div>++ {showSettings && (+ <div className="px-3 py-2 border-b border-port-border bg-port-card/30 shrink-0">+ <ImageGenSettingsRow cfg={imageCfg} models={models} onChange={persistCfg} />+ </div>+ )}++ <div className="flex-1 overflow-y-auto px-3 py-3 space-y-2">+ {loading && (+ <div className="flex items-center justify-center text-[11px] text-gray-500 gap-2 py-6">+ <Loader2 size={14} className="animate-spin" /> Loading storyboard…+ </div>+ )}++ {!loading && !latestScript && (+ <EmptyAdaptCTA onRunAdapt={onRunAdapt} runningAdapt={runningAdapt} />+ )}++ {!loading && latestScript && isStale && (+ <StaleBanner onRunAdapt={onRunAdapt} runningAdapt={runningAdapt} />+ )}++ {!loading && latestScript && scenes.length === 0 && (+ <div className="text-[11px] text-gray-500 italic px-1">+ Adapt finished but produced no scenes. Try adding `## Scene` headings to your prose, then re-run.+ </div>+ )}++ {!loading && scenes.map((scene, i) => {+ const sceneId = scene.id || `scene-${i}`;+ return (+ <SceneCard+ key={sceneId}+ scene={{ ...scene, id: sceneId }}+ workId={work.id}+ analysisId={latestScript.id}+ workTitle={work.title}+ imageCfg={imageCfg}+ initialImage={sceneImages[sceneId] || null}+ readingTheme={readingTheme}+ charByKey={charByKey}+ isActive={sceneId === activeSceneId}+ onJumpToProse={onJumpToScene ? () => onJumpToScene(scene, i, scenes.length) : null}+ onDebug={onDebug}+ />+ );+ })}+ </div>+ </div>+ );+}++function EmptyAdaptCTA({ onRunAdapt, runningAdapt }) {+ return (+ <div className="text-center px-3 py-8 space-y-3">+ <Clapperboard size={28} className="mx-auto text-gray-600" />+ <div className="text-[12px] text-gray-300 font-medium">No storyboard yet</div>+ <div className="text-[11px] text-gray-500 max-w-[28ch] mx-auto">+ Run Adapt to break your prose into scenes and start visualizing how the AI is reading your story.+ </div>+ <button+ onClick={onRunAdapt}+ disabled={runningAdapt || !onRunAdapt}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-port-accent text-white text-[11px] rounded hover:bg-port-accent/80 disabled:opacity-50"+ >+ {runningAdapt ? <Loader2 size={12} className="animate-spin" /> : <Clapperboard size={12} />}+ {runningAdapt ? 'Running Adapt…' : 'Run Adapt'}+ </button>+ </div>+ );+}++function StaleBanner({ onRunAdapt, runningAdapt }) {+ return (+ <div className="flex items-start gap-2 p-2 mb-1 border border-port-warning/40 bg-port-warning/5 rounded text-[11px]">+ <AlertTriangle size={12} className="text-port-warning mt-0.5 shrink-0" />+ <div className="flex-1">+ <div className="text-port-warning">Storyboard is older than your current draft.</div>+ <div className="text-gray-500">Re-run Adapt to refresh scenes against the latest prose.</div>+ </div>+ <button+ onClick={onRunAdapt}+ disabled={runningAdapt || !onRunAdapt}+ className="flex items-center gap-1 px-2 py-1 bg-port-warning/20 border border-port-warning/40 text-port-warning rounded text-[10px] hover:bg-port-warning/30 disabled:opacity-50"+ >+ {runningAdapt ? <Loader2 size={10} className="animate-spin" /> : <RefreshCcw size={10} />}+ Re-run+ </button>+ </div>+ );+}++function ImageGenSettingsRow({ cfg, models, onChange }) {+ const RES_PRESETS = [+ { label: '768×512 (3:2)', width: 768, height: 512 },+ { label: '512×512 (1:1)', width: 512, height: 512 },+ { label: '512×768 (2:3)', width: 512, height: 768 },+ { label: '1024×576 (16:9)', width: 1024, height: 576 },+ { label: '1024×1024 (1:1)', width: 1024, height: 1024 },+ ];+ const presetMatch = RES_PRESETS.find((p) => p.width === cfg.width && p.height === cfg.height);+ return (+ <div className="space-y-1.5">+ <label className="block">+ <span className="text-[9px] uppercase tracking-wider text-gray-500">Image model</span>+ <select+ value={cfg.modelId}+ onChange={(e) => onChange({ ...cfg, modelId: e.target.value })}+ className="w-full mt-0.5 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200"+ >+ {models.length === 0 && <option value={cfg.modelId}>{cfg.modelId}</option>}+ {models.map((m) => (+ <option key={m.id} value={m.id}>{m.name || m.id}</option>+ ))}+ </select>+ </label>+ <label className="block">+ <span className="text-[9px] uppercase tracking-wider text-gray-500">Resolution</span>+ <select+ value={presetMatch ? `${cfg.width}x${cfg.height}` : 'custom'}+ onChange={(e) => {+ if (e.target.value === 'custom') return;+ const [w, h] = e.target.value.split('x').map(Number);+ onChange({ ...cfg, width: w, height: h });+ }}+ className="w-full mt-0.5 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-200"+ >+ {RES_PRESETS.map((p) => (+ <option key={p.label} value={`${p.width}x${p.height}`}>{p.label}</option>+ ))}+ {!presetMatch && <option value="custom">Custom ({cfg.width}×{cfg.height})</option>}+ </select>+ </label>+ </div>+ );+}diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex 2dd012e086..b81f0a7805 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -1,31 +1,47 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Save, GitCommit, Clock, FileText, Sparkles, ListTree, Sun, Moon } from 'lucide-react';+import {+ Save,+ GitCommit,+ Sun,+ Moon,+ MoreHorizontal,+ Clapperboard,+ Sparkles,+ FileSignature,+ Users,+ ListTree,+ Clock,+ History,+ Timer,+ PenLine,+ Check,+ Loader2,+} from 'lucide-react';import toast from '../ui/Toast';+import Drawer from '../Drawer';import {saveWritersRoomDraft,snapshotWritersRoomDraft,setWritersRoomActiveDraft,updateWritersRoomWork,+ runWritersRoomAnalysis,+ listWritersRoomCharacters,} from '../../services/apiWritersRoom';-import { KIND_LABELS, STATUS_LABELS } from './labels';+import { STATUS_LABELS } from './labels';import { countWords } from '../../utils/formatters';-import AiPanel from './AiPanel';--const SIDEBAR_TABS = [- { id: 'ai', label: 'AI', Icon: Sparkles },- { id: 'outline', label: 'Outline', Icon: ListTree },- { id: 'versions', label: 'Versions', Icon: Clock },-];+import StoryboardPanel from './StoryboardPanel';+import CharactersBible from './CharactersBible';+import AnalysisHistory from './AnalysisHistory';const SIDEBAR_WIDTH_KEY = 'wr.sidebarWidth';const SIDEBAR_DEFAULT = 480;-const SIDEBAR_MIN = 280;-const SIDEBAR_MAX_FRACTION = 0.7; // never let the sidebar eat more than 70% of the work area+const SIDEBAR_MIN = 320;+const SIDEBAR_MAX_FRACTION = 0.6;const READING_THEME_KEY = 'wr.readingTheme';+function readReadingTheme() {if (typeof window === 'undefined') return 'dark';- const v = window.localStorage.getItem(READING_THEME_KEY);- return v === 'light' ? 'light' : 'dark';+ return window.localStorage.getItem(READING_THEME_KEY) === 'light' ? 'light' : 'dark';}function readSidebarWidth() {@@ -39,22 +55,32 @@ function persistSidebarWidth(width) {try { window.localStorage.setItem(SIDEBAR_WIDTH_KEY, String(Math.round(width))); } catch {}}-export default function WorkEditor({ work, onChange }) {+const ANALYSIS_LABELS = {+ script: 'Adapt',+ characters: 'Characters',+ evaluate: 'Editorial pass',+ format: 'Format pass',+};++export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOpen }) {const [body, setBody] = useState(work.activeDraftBody || '');const [title, setTitle] = useState(work.title);- const [sidebarTab, setSidebarTab] = useState('ai');- // Optimistic mirror of work.status — the dropdown reads this so a status- // change shows immediately, even before the PATCH round-trip resolves and- // the parent re-renders with the new prop. Synced from the prop whenever- // the prop changes (both work-id swap AND any time the parent updates).const [status, setStatus] = useState(work.status);const [savedBody, setSavedBody] = useState(work.activeDraftBody || '');const [saving, setSaving] = useState(false);+ const [readingTheme, setReadingTheme] = useState(readReadingTheme);+ const [characters, setCharacters] = useState([]);+ const [runningKind, setRunningKind] = useState(null); // 'script' | 'characters' | 'evaluate' | 'format'+ const [drawer, setDrawer] = useState(null); // 'outline' | 'versions' | 'characters' | 'history' | null+ const [overflowOpen, setOverflowOpen] = useState(false);+ const [mobileTab, setMobileTab] = useState('writing'); // 'writing' | 'storyboard'+ const [activeSceneId, setActiveSceneId] = useState(null);+const textareaRef = useRef(null);+ const overflowRef = useRef(null);// Rehydrate body/title when the parent swaps the active work OR switches to- // a different draft version of the same work. Both can change without the- // work id changing (version-switch keeps work.id, swaps activeDraftVersionId).+ // a different draft version of the same work.const prevKey = useRef({ id: work.id, draftId: work.activeDraftVersionId });useEffect(() => {const key = { id: work.id, draftId: work.activeDraftVersionId };@@ -65,31 +91,30 @@ export default function WorkEditor({ work, onChange }) {setTitle(work.title);}, [work.id, work.activeDraftVersionId, work.activeDraftBody, work.title]);- // Keep the optimistic status + title in sync with the source of truth —- // separate from the rehydration effect so a PATCH that comes back via the- // parent's onChange still updates the input even if no other field moved.- // The "is the user actively editing" guard isn't needed for status (single- // click) but title commits on blur, so the user can never be mid-edit when- // a title prop change arrives.useEffect(() => { setStatus(work.status); }, [work.status]);useEffect(() => { setTitle(work.title); }, [work.title]);+ // Load character bible for the active work — passed into the storyboard so+ // physicalDescription gets injected into per-scene image prompts. The+ // CharactersBible drawer is the canonical editor; we re-fetch when it+ // notifies us via onCharactersChange.+ useEffect(() => {+ listWritersRoomCharacters(work.id)+ .then((list) => setCharacters(list || []))+ .catch(() => setCharacters([]));+ }, [work.id]);+const dirty = body !== savedBody;const wordCount = useMemo(() => countWords(body), [body]);- // Skip post-await setState if the editor unmounted (rapid work-switch or- // page nav while a save / snapshot / status PATCH is in flight).const mountedRef = useRef(true);useEffect(() => {mountedRef.current = true;return () => { mountedRef.current = false; };}, []);- // Refs let the once-bound keydown listener read the freshest body/saving- // values without re-registering on every keystroke. The savingRef gate is- // synchronous (unlike the `saving` state which only updates after React- // re-renders), so rapid Cmd+S key-repeats can't slip past the guard and- // queue overlapping save requests.+ // Saving uses refs so the once-bound key listener reads fresh values+ // without re-registering on every keystroke.const savingRef = useRef(false);const handleSaveRef = useRef(null);handleSaveRef.current = async () => {@@ -121,6 +146,17 @@ export default function WorkEditor({ work, onChange }) {return () => window.removeEventListener('keydown', onKey);}, []);+ // Close the overflow menu on outside click — keeping it open while the+ // user clicks something else would feel sticky.+ useEffect(() => {+ if (!overflowOpen) return;+ const onClick = (e) => {+ if (!overflowRef.current?.contains(e.target)) setOverflowOpen(false);+ };+ window.addEventListener('mousedown', onClick);+ return () => window.removeEventListener('mousedown', onClick);+ }, [overflowOpen]);+const handleSnapshot = async () => {if (dirty) {toast('Save before snapshotting', { icon: '⚠️' });@@ -142,20 +178,17 @@ export default function WorkEditor({ work, onChange }) {return null;});if (!updated || !mountedRef.current) return;- // Adopt the server-normalized title (e.g. trim() applied by the Zod- // schema) — otherwise `title !== work.title` stays true on every blur- // and the next focus-out re-PATCHes with the same un-normalized value.if (updated.title !== title) setTitle(updated.title);onChange?.({ ...updated, activeDraftBody: body });};const commitStatus = async (next) => {if (next === status) return;- setStatus(next); // optimistic — survives a re-render before the PATCH resolves+ setStatus(next);const updated = await updateWritersRoomWork(work.id, { status: next }).catch((err) => {if (mountedRef.current) {toast.error(`Status save failed: ${err.message}`);- setStatus(work.status); // roll back on failure+ setStatus(work.status);}return null;});@@ -165,9 +198,6 @@ export default function WorkEditor({ work, onChange }) {const switchToDraft = async (draftId) => {if (draftId === work.activeDraftVersionId) return;if (dirty) {- // Switching versions while the editor has unsaved edits would discard- // them when the rehydration effect replaces `body` with the server- // version. Block the switch and ask the user to settle the buffer.toast('Save or snapshot before switching versions', { icon: '⚠️' });return;}@@ -176,32 +206,118 @@ export default function WorkEditor({ work, onChange }) {return null;});if (!updated || !mountedRef.current) return;- // PATCH /works/:id/versions/:draftId now returns manifest + activeDraftBody- // in one round-trip, so no separate reload is needed.onChange?.(updated);};+ // Shared analysis runner — the storyboard, overflow menu, and per-scene+ // debug menu all funnel through here so we get one toast + state pattern.+ // Format pass replaces the prose buffer (apply-on-success) — the user can+ // back out by simply not saving. Characters refreshes the bible cache so+ // the storyboard's prompt enrichment picks up new profiles immediately.+ const runAnalysis = useCallback(async (kind) => {+ if (runningKind) return;+ setRunningKind(kind);+ const snapshot = await runWritersRoomAnalysis(work.id, { kind }).catch((err) => {+ if (mountedRef.current) toast.error(`${ANALYSIS_LABELS[kind] || kind} failed: ${err.message}`);+ return null;+ });+ if (!mountedRef.current) {+ setRunningKind(null);+ return;+ }+ setRunningKind(null);+ if (!snapshot) return;+ if (snapshot.status === 'failed') {+ toast.error(`${ANALYSIS_LABELS[kind] || kind} failed: ${snapshot.error || 'unknown'}`);+ return;+ }+ toast.success(`${ANALYSIS_LABELS[kind] || kind} complete`);+ if (kind === 'characters' && Array.isArray(snapshot.result?.mergedProfiles)) {+ setCharacters(snapshot.result.mergedProfiles);+ }+ if (kind === 'format' && snapshot.result?.formattedBody) {+ setBody(snapshot.result.formattedBody);+ toast('Format applied to draft buffer — save to persist', { icon: '💾' });+ }+ }, [runningKind, work.id]);++ const applyFormatText = (text) => {+ setBody(text);+ toast('Applied to editor — save to persist', { icon: '💾' });+ };+const activeDraft = useMemo(() => work.drafts?.find((d) => d.id === work.activeDraftVersionId),[work.drafts, work.activeDraftVersionId]);+ const activeHash = activeDraft?.contentHash || null;- // Drag-to-resize sidebar — width is per-user via localStorage so the choice- // sticks across reloads. The handle is desktop-only; the mobile stack ignores- // sidebarWidth (the aside renders as a row beneath the editor).+ // Click-to-jump from a storyboard card → scroll the prose textarea so the+ // scene's heading is visible. The Adapt LLM often paraphrases the user's+ // headings (e.g. user wrote `## Chapter 1`, LLM emits "Scene 1 — The Curry+ // Burns"), so we try a few candidates in order:+ // 1. Common markdown prefixes + the LLM heading+ // 2. Raw LLM heading+ // 3. First chunk of scene.summary or scene.action — these often quote+ // actual prose phrases+ // 4. Proportional scrollTop based on the scene's index in the storyboard+ // (sceneIndex / totalScenes) — guarantees we land somewhere reasonable+ // even when nothing matches.+ // setSelectionRange + focus uses the browser's caret-into-view scroll;+ // setting scrollTop afterward guarantees we land "near" the line in cases+ // where the browser doesn't re-scroll an already-visible caret.+ const jumpToScene = useCallback((scene, sceneIndex = -1, totalScenes = 0) => {+ const ta = textareaRef.current;+ if (!ta || !scene || !body) return;+ setActiveSceneId(scene.id || null);+ setMobileTab('writing');+ const heading = scene.heading || '';+ let idx = -1;+ for (const prefix of ['## ', '### ', '# ', '']) {+ if (!heading) break;+ idx = body.indexOf(prefix + heading);+ if (idx >= 0) break;+ }+ if (idx < 0) {+ // Try a chunk of the scene's summary or action — the LLM may have+ // pulled from real prose phrases.+ for (const candidate of [scene.summary, scene.action]) {+ if (!candidate) continue;+ const snippet = String(candidate).trim().slice(0, 40);+ if (!snippet) continue;+ idx = body.indexOf(snippet);+ if (idx >= 0) break;+ }+ }+ let target;+ if (idx >= 0) {+ ta.focus();+ ta.setSelectionRange(idx, idx);+ const fraction = idx / body.length;+ target = Math.max(0, fraction * (ta.scrollHeight - ta.clientHeight));+ } else if (totalScenes > 0 && sceneIndex >= 0) {+ // Last resort: position by scene index in the storyboard.+ const fraction = sceneIndex / totalScenes;+ target = Math.max(0, fraction * (ta.scrollHeight - ta.clientHeight));+ } else {+ return;+ }+ ta.scrollTop = target;+ }, [body]);++ // Per-scene Debug menu actions from SceneCard — for now everything except+ // "Jump to prose" (handled directly via onJumpToProse) opens the most+ // relevant drawer. Scoping AI tools to a single scene is a follow-up.+ const handleDebug = useCallback(({ kind, scene }) => {+ if (scene) setActiveSceneId(scene.id || null);+ if (kind === 'check-characters') setDrawer('characters');+ else if (kind === 'editorial') setDrawer('history');+ else if (kind === 'why-image') setDrawer('history');+ }, []);++ // Drag-to-resize sidebar (desktop only).const splitRef = useRef(null);const [sidebarWidth, setSidebarWidth] = useState(readSidebarWidth);- const [readingTheme, setReadingTheme] = useState(readReadingTheme);- const toggleReadingTheme = useCallback(() => {- setReadingTheme((prev) => {- const next = prev === 'dark' ? 'light' : 'dark';- try { window.localStorage.setItem(READING_THEME_KEY, next); } catch {}- return next;- });- }, []);- // Mirror sidebarWidth into a ref so the once-bound mousemove/mouseup effect- // reads the freshest value at release time without re-registering on every- // pixel of drag (200px drag = ~200 add/remove pairs otherwise).const sidebarWidthRef = useRef(sidebarWidth);useEffect(() => { sidebarWidthRef.current = sidebarWidth; }, [sidebarWidth]);const dragStartRef = useRef(null);@@ -219,7 +335,6 @@ export default function WorkEditor({ work, onChange }) {if (!dragStartRef.current) return;const { startX, startWidth, containerWidth } = dragStartRef.current;const max = Math.max(SIDEBAR_MIN + 1, containerWidth * SIDEBAR_MAX_FRACTION);- // Dragging left grows the right-hand sidebar; dragging right shrinks it.const next = Math.min(max, Math.max(SIDEBAR_MIN, startWidth - (e.clientX - startX)));setSidebarWidth(next);};@@ -235,8 +350,6 @@ export default function WorkEditor({ work, onChange }) {return () => {window.removeEventListener('mousemove', onMove);window.removeEventListener('mouseup', onUp);- // If the component unmounts mid-drag, restore body styles so the page- // doesn't keep the col-resize cursor / no-select state forever.if (dragStartRef.current) {document.body.style.cursor = '';document.body.style.userSelect = '';@@ -245,26 +358,36 @@ export default function WorkEditor({ work, onChange }) {};}, []);+ const toggleReadingTheme = useCallback(() => {+ setReadingTheme((prev) => {+ const next = prev === 'dark' ? 'light' : 'dark';+ try { window.localStorage.setItem(READING_THEME_KEY, next); } catch {}+ return next;+ });+ }, []);++ const closeOverflowAnd = (fn) => () => { setOverflowOpen(false); fn?.(); };+return (<div className="flex flex-col h-full">- <div className="flex flex-wrap items-center gap-2 px-4 py-3 border-b border-port-border bg-port-card">+ {/* Header — title + status on left, primary actions + overflow on right */}+ <div className="flex flex-wrap items-center gap-2 px-4 py-2 border-b border-port-border bg-port-card"><inputvalue={title}onChange={(e) => setTitle(e.target.value)}onBlur={commitTitle}onKeyDown={(e) => { if (e.key === 'Enter') e.target.blur(); }}- className="bg-transparent text-lg font-bold text-white border-none focus:outline-none focus:bg-port-bg/50 px-1 rounded flex-1 min-w-[200px]"+ className="bg-transparent text-base font-semibold text-white border-none focus:outline-none focus:bg-port-bg/50 px-1 rounded flex-1 min-w-[180px]"aria-label="Work title"/><selectvalue={status}onChange={(e) => commitStatus(e.target.value)}- className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-300"+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-gray-300"aria-label="Status">{Object.entries(STATUS_LABELS).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select>- <span className="text-xs text-gray-500 px-2 py-1 bg-port-bg/50 rounded">{KIND_LABELS[work.kind]}</span><buttononClick={handleSave}disabled={!dirty || saving}@@ -283,29 +406,63 @@ export default function WorkEditor({ work, onChange }) {><GitCommit size={12} /> Snapshot</button>- <button- onClick={toggleReadingTheme}- className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-port-bg border border-port-border text-gray-300 hover:text-white"- title={readingTheme === 'dark' ? 'Switch to light reading theme' : 'Switch to dark reading theme'}- aria-label="Toggle reading theme"- aria-pressed={readingTheme === 'light'}- >- {readingTheme === 'dark' ? <Sun size={12} /> : <Moon size={12} />}- </button>+ <div className="relative" ref={overflowRef}>+ <button+ onClick={() => setOverflowOpen((v) => !v)}+ className="flex items-center justify-center px-2 py-1 text-xs rounded bg-port-bg border border-port-border text-gray-300 hover:text-white"+ aria-label="Work menu"+ aria-expanded={overflowOpen}+ title="Work menu"+ >+ <MoreHorizontal size={14} />+ </button>+ {overflowOpen && (+ <div className="absolute right-0 top-full mt-1 z-30 w-60 rounded-md border border-port-border bg-port-card shadow-xl py-1 text-xs">+ <MenuSection label="AI">+ <MenuItem icon={Clapperboard} label="Run Adapt (rebuild storyboard)" running={runningKind === 'script'} onClick={closeOverflowAnd(() => runAnalysis('script'))} />+ <MenuItem icon={Users} label="Refresh characters" running={runningKind === 'characters'} onClick={closeOverflowAnd(() => runAnalysis('characters'))} />+ <MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === 'evaluate'} onClick={closeOverflowAnd(() => runAnalysis('evaluate'))} />+ <MenuItem icon={FileSignature} label="Format pass" running={runningKind === 'format'} onClick={closeOverflowAnd(() => runAnalysis('format'))} />+ </MenuSection>+ <MenuSection label="Open">+ <MenuItem icon={ListTree} label="Outline" onClick={closeOverflowAnd(() => setDrawer('outline'))} />+ <MenuItem icon={Clock} label="Versions" onClick={closeOverflowAnd(() => setDrawer('versions'))} />+ <MenuItem icon={Users} label="Characters" badge={characters.length || null} onClick={closeOverflowAnd(() => setDrawer('characters'))} />+ <MenuItem icon={History} label="Analysis history" onClick={closeOverflowAnd(() => setDrawer('history'))} />+ </MenuSection>+ <MenuSection label="View">+ <MenuItem+ icon={readingTheme === 'dark' ? Sun : Moon}+ label={readingTheme === 'dark' ? 'Light reading theme' : 'Dark reading theme'}+ onClick={closeOverflowAnd(toggleReadingTheme)}+ />+ {onToggleExercise && (+ <MenuItem+ icon={Timer}+ label={exerciseOpen ? 'Hide Write for 10' : 'Write for 10'}+ onClick={closeOverflowAnd(onToggleExercise)}+ active={exerciseOpen}+ />+ )}+ </MenuSection>+ </div>+ )}+ </div>+ </div>++ {/* Mobile-only Writing/Storyboard toggle — desktop renders both side-by-side. */}+ <div className="lg:hidden flex border-b border-port-border bg-port-bg/40 shrink-0">+ <MobileTab active={mobileTab === 'writing'} onClick={() => setMobileTab('writing')} icon={PenLine} label="Writing" />+ <MobileTab active={mobileTab === 'storyboard'} onClick={() => setMobileTab('storyboard')} icon={Clapperboard} label="Storyboard" /></div><div ref={splitRef} className="flex-1 flex flex-col lg:flex-row min-h-0">- <div className="relative min-h-0 flex-[2] lg:flex-1">+ <div className={`relative min-h-0 flex-1 ${mobileTab === 'storyboard' ? 'hidden lg:block' : 'block'}`}><textarearef={textareaRef}value={body}onChange={(e) => setBody(e.target.value)}placeholder="Start writing… Use # Chapter, ## Scene, ### Beat headings to outline."- // The theme system applies `background: var(--port-input-bg) !important`- // to every textarea, so a regular Tailwind `bg-...` class can't win.- // Override --port-input-bg inline (the !important rule then resolves- // to our value), and set the matching text color the same way for- // visual consistency across themes.style={readingTheme === 'light'? { '--port-input-bg': 'var(--wr-reading-paper)', color: '#1a1a1a' }: undefined}@@ -329,7 +486,7 @@ export default function WorkEditor({ work, onChange }) {persistSidebarWidth(SIDEBAR_DEFAULT);}}role="separator"- aria-label="Resize AI sidebar"+ aria-label="Resize storyboard sidebar"aria-orientation="vertical"title="Drag to resize · double-click to reset"className="hidden lg:block w-1 shrink-0 cursor-col-resize bg-port-border hover:bg-port-accent/60 active:bg-port-accent transition-colors"@@ -337,78 +494,145 @@ export default function WorkEditor({ work, onChange }) {<asidestyle={{ '--sidebar-w': `${sidebarWidth}px` }}- className="border-t lg:border-t-0 border-port-border bg-port-card/60 flex flex-col text-xs min-h-0 w-full flex-1 lg:flex-initial lg:w-[var(--sidebar-w)] lg:shrink-0">- <div className="flex border-b border-port-border bg-port-bg/40">- {SIDEBAR_TABS.map(({ id, label, Icon }) => (+ className={`border-t lg:border-t-0 border-port-border bg-port-card/60 flex flex-col text-xs min-h-0 w-full flex-1 lg:flex-initial lg:w-[var(--sidebar-w)] lg:shrink-0 ${+ mobileTab === 'writing' ? 'hidden lg:flex' : 'flex'+ }`}+ >+ <StoryboardPanel+ work={work}+ characters={characters}+ onJumpToScene={jumpToScene}+ onDebug={handleDebug}+ onRunAdapt={() => runAnalysis('script')}+ runningAdapt={runningKind === 'script'}+ readingTheme={readingTheme}+ activeSceneId={activeSceneId}+ />+ </aside>+ </div>++ {/* Slide-over drawers — only one open at a time */}+ <Drawer open={drawer === 'outline'} onClose={() => setDrawer(null)} title="Outline">+ <OutlineList activeDraft={activeDraft} onClose={() => setDrawer(null)} />+ </Drawer>+ <Drawer open={drawer === 'versions'} onClose={() => setDrawer(null)} title="Versions">+ <VersionsList work={work} dirty={dirty} onSwitch={(id) => { switchToDraft(id); setDrawer(null); }} />+ </Drawer>+ <Drawer open={drawer === 'characters'} onClose={() => setDrawer(null)} title="Characters">+ <CharactersBible+ workId={work.id}+ characters={characters}+ onCharactersChange={setCharacters}+ readingTheme={readingTheme}+ />+ </Drawer>+ <Drawer open={drawer === 'history'} onClose={() => setDrawer(null)} title="Analysis history">+ <AnalysisHistory work={work} activeHash={activeHash} onApplyFormat={applyFormatText} />+ </Drawer>+ </div>+ );+}++function MenuSection({ label, children }) {+ return (+ <div className="py-1 border-b border-port-border last:border-b-0">+ <div className="px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wider text-gray-500">{label}</div>+ {children}+ </div>+ );+}++function MenuItem({ icon: Icon, label, onClick, running = false, active = false, badge = null }) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={running}+ className={`w-full flex items-center gap-2 px-3 py-1.5 text-left text-[11px] hover:bg-port-bg disabled:opacity-50 ${+ active ? 'text-port-accent' : 'text-gray-300'+ }`}+ >+ {running+ ? <Loader2 size={11} className="animate-spin text-port-accent" />+ : <Icon size={11} className={active ? 'text-port-accent' : 'text-gray-500'} />+ }+ <span className="flex-1">{label}</span>+ {badge != null && <span className="text-[10px] text-gray-500">{badge}</span>}+ </button>+ );+}++function MobileTab({ active, onClick, icon: Icon, label }) {+ return (+ <button+ onClick={onClick}+ className={`flex-1 flex items-center justify-center gap-1.5 py-2 text-[12px] border-b-2 ${+ active ? 'border-port-accent text-white' : 'border-transparent text-gray-500 hover:text-gray-300'+ }`}+ >+ <Icon size={13} /> {label}+ </button>+ );+}++function OutlineList({ activeDraft, onClose }) {+ const segs = activeDraft?.segmentIndex || [];+ if (segs.length === 0) {+ return (+ <div className="text-xs text-gray-500 italic">+ No segments yet. Use # Chapter / ## Scene / ### Beat headings in the prose to populate the outline.+ </div>+ );+ }+ return (+ <ul className="space-y-1 text-xs">+ {segs.map((seg) => (+ <li key={seg.id} className="flex items-center gap-2 text-gray-400">+ <span className={`flex-1 truncate ${seg.kind === 'chapter' ? 'text-white font-semibold' : seg.kind === 'scene' ? 'text-gray-300' : 'pl-3 text-gray-500'}`}>+ {seg.heading}+ </span>+ <span className="text-[10px] text-gray-600">{seg.wordCount}w</span>+ </li>+ ))}+ </ul>+ );+}++function VersionsList({ work, dirty, onSwitch }) {+ const drafts = (work.drafts || []).slice().reverse();+ if (drafts.length === 0) {+ return <div className="text-xs text-gray-500 italic">No versions yet. Click Snapshot in the header to create one.</div>;+ }+ return (+ <>+ {dirty && (+ <div className="mb-2 px-2 py-1.5 text-[11px] border border-port-warning/40 bg-port-warning/5 text-port-warning rounded">+ Save or snapshot before switching versions — unsaved edits will be lost.+ </div>+ )}+ <ul className="space-y-1 text-xs">+ {drafts.map((draft) => {+ const isActive = draft.id === work.activeDraftVersionId;+ return (+ <li key={draft.id}><button- key={id}- onClick={() => setSidebarTab(id)}- className={`flex-1 flex items-center justify-center gap-1 px-2 py-2 text-[11px] border-b-2 ${- sidebarTab === id- ? 'border-port-accent text-white'- : 'border-transparent text-gray-500 hover:text-gray-300'+ onClick={() => onSwitch(draft.id)}+ disabled={isActive}+ className={`w-full flex items-center justify-between gap-2 px-2 py-1.5 rounded text-left ${+ isActive ? 'bg-port-accent/20 text-port-accent cursor-default' : 'text-gray-400 hover:bg-port-bg hover:text-white'}`}- aria-pressed={sidebarTab === id}>- <Icon size={11} /> {label}+ <span className="flex items-center gap-2 truncate">+ {isActive ? <Check size={11} /> : <Clock size={11} />}+ {draft.label}+ </span>+ <span className="text-[10px] text-gray-500">{draft.wordCount}w</span></button>- ))}- </div>- <div className="flex-1 overflow-y-auto px-3 py-3">- {sidebarTab === 'ai' && (- <AiPanel- work={work}- readingTheme={readingTheme}- onApplyFormat={(text) => {- // Don't autosave — keeps a bad format pass from overwriting- // the on-disk draft without an explicit Save.- setBody(text);- toast('Applied to editor — save to persist', { icon: '💾' });- }}- />- )}- {sidebarTab === 'outline' && (- <ul className="space-y-0.5">- {(activeDraft?.segmentIndex || []).map((seg) => (- <li key={seg.id} className="flex items-center gap-1 text-gray-400 truncate">- <FileText size={10} className="shrink-0" />- <span className={`truncate ${seg.kind === 'chapter' ? 'text-white' : seg.kind === 'scene' ? 'text-gray-300' : 'pl-3'}`}>- {seg.heading}- </span>- <span className="ml-auto text-[10px] text-gray-600">{seg.wordCount}</span>- </li>- ))}- {(!activeDraft?.segmentIndex || activeDraft.segmentIndex.length === 0) && (- <li className="text-gray-600 italic">No segments yet — use # Chapter / ## Scene headings to outline.</li>- )}- </ul>- )}- {sidebarTab === 'versions' && (- <ul className="space-y-1">- {(work.drafts || []).slice().reverse().map((draft) => {- const isActive = draft.id === work.activeDraftVersionId;- return (- <li key={draft.id}>- <button- onClick={() => switchToDraft(draft.id)}- className={`w-full flex items-center justify-between gap-2 px-2 py-1 rounded text-left ${- isActive ? 'bg-port-accent/20 text-port-accent' : 'text-gray-400 hover:bg-port-bg hover:text-white'- }`}- >- <span className="flex items-center gap-1 truncate">- <Clock size={10} />- {draft.label}- </span>- <span className="text-[10px] text-gray-500">{draft.wordCount}w</span>- </button>- </li>- );- })}- </ul>- )}- </div>- </aside>- </div>- </div>+ </li>+ );+ })}+ </ul>+ </>);}+diff --git a/client/src/components/writers-room/sceneCardHelpers.js b/client/src/components/writers-room/sceneCardHelpers.jsnew file mode 100644index 0000000000..0ed6a67388--- /dev/null+++ b/client/src/components/writers-room/sceneCardHelpers.js@@ -0,0 +1,78 @@+// Shared scene/character helpers used by both the storyboard sidebar and the+// (legacy) inline script result. Lives in its own module so SceneCard can be+// imported wherever scenes are rendered without dragging the whole AI panel.++// Defaults for the per-scene image gen pipe. Klein-4B is the fastest FLUX.2+// variant on Apple Silicon, and 768×512 is a 3:2 aspect that suits scene work.+export const WR_IMAGE_DEFAULTS = {+ modelId: 'flux2-klein-4b',+ mode: 'local',+ width: 768,+ height: 512,+};++export function readWrImageSettings(settings) {+ const stored = settings?.writersRoom?.imageGen || {};+ return {+ modelId: stored.modelId || WR_IMAGE_DEFAULTS.modelId,+ mode: stored.mode || WR_IMAGE_DEFAULTS.mode,+ width: Number.isFinite(stored.width) ? stored.width : WR_IMAGE_DEFAULTS.width,+ height: Number.isFinite(stored.height) ? stored.height : WR_IMAGE_DEFAULTS.height,+ };+}++// LLM scene lists use bare names ("ARIA"), profiles may use full names+// ("Aria Reyes") or "the bartender" — strip leading "the " and lowercase so+// either side resolves to the same key.+export const normCharKey = (s) => String(s || '').trim().toLowerCase().replace(/^the\s+/, '');++export function buildCharByKey(allCharacters) {+ const map = new Map();+ for (const profile of allCharacters || []) {+ map.set(normCharKey(profile.name), profile);+ for (const alias of profile.aliases || []) map.set(normCharKey(alias), profile);+ }+ return map;+}++export function matchSceneCharacters(sceneCharacterNames = [], charByKey) {+ if (!Array.isArray(sceneCharacterNames) || !sceneCharacterNames.length) return [];+ const matched = [];+ const seen = new Set();+ for (const name of sceneCharacterNames) {+ const profile = charByKey?.get(normCharKey(name));+ if (profile && !seen.has(profile.id)) {+ matched.push(profile);+ seen.add(profile.id);+ }+ }+ return matched;+}++const PROMPT_MAX = 1900;++// scene.visualPrompt is the load-bearing part of the image prompt — it must+// always survive truncation. Reserve room for title + visual prompt first,+// then fit the "Featuring" block into whatever is left, dropping characters+// one-by-one if needed.+export function buildScenePromptWithCharacters(workTitle, scene, matchedCharacters) {+ const titlePart = workTitle ? `${workTitle}. ` : '';+ const visual = scene.visualPrompt || '';+ const featuringFragments = (matchedCharacters || [])+ .filter((c) => c.physicalDescription && c.physicalDescription.trim())+ .map((c) => `${c.name}: ${c.physicalDescription.trim()}`);+ const PREFIX = 'Featuring — ';+ const reserveForVisual = titlePart.length + visual.length + 1;+ let budget = PROMPT_MAX - reserveForVisual - PREFIX.length;+ const fitFragments = [];+ for (const frag of featuringFragments) {+ const cost = (fitFragments.length === 0 ? 0 : 1) + frag.length;+ if (cost > budget) break;+ fitFragments.push(frag);+ budget -= cost;+ }+ const segs = [titlePart.trim()];+ if (fitFragments.length > 0) segs.push(`${PREFIX}${fitFragments.join(' ')}`);+ if (visual) segs.push(visual);+ return segs.filter(Boolean).join(' ').slice(0, PROMPT_MAX);+}diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsxindex 900c2988e5..004fb9304f 100644--- a/client/src/pages/WritersRoom.jsx+++ b/client/src/pages/WritersRoom.jsx@@ -1,6 +1,6 @@import { useEffect, useState, useCallback, useRef } from 'react';import { useParams, useNavigate } from 'react-router-dom';-import { NotebookPen, Timer, PanelLeftClose, PanelLeftOpen } from 'lucide-react';+import { NotebookPen, PanelLeftOpen } from 'lucide-react';import LibraryPane from '../components/writers-room/LibraryPane';import WorkEditor from '../components/writers-room/WorkEditor';import ExercisePanel from '../components/writers-room/ExercisePanel';@@ -121,18 +121,7 @@ export default function WritersRoom() {<div className="flex items-center gap-3 px-4 py-3 border-b border-port-border bg-port-card"><NotebookPen className="w-5 h-5 text-port-accent" /><h1 className="text-xl font-bold text-white">Writers Room</h1>- <span className="text-xs text-gray-500 hidden md:inline">Folders, works, drafts, and write-for-10 sprints</span>- <button- onClick={() => setShowExercise((s) => !s)}- className={`ml-auto flex items-center gap-1 px-3 py-1 text-xs rounded ${- showExercise ? 'bg-port-accent text-white' : 'bg-port-bg border border-port-border text-gray-300 hover:text-white'- }`}- aria-pressed={showExercise}- aria-label="Toggle write-for-10 exercise sidebar"- title="Toggle exercise sidebar"- >- <Timer size={12} /> Write for 10- </button>+ <span className="text-xs text-gray-500 hidden md:inline ml-auto">Folders, works, drafts, storyboard, and write-for-10 sprints</span></div><div@@ -175,7 +164,12 @@ export default function WritersRoom() {</div>)}{!loadingWork && activeWork && (- <WorkEditor work={activeWork} onChange={handleWorkChange} />+ <WorkEditor+ work={activeWork}+ onChange={handleWorkChange}+ onToggleExercise={() => setShowExercise((s) => !s)}+ exerciseOpen={showExercise}+ />)}</main>