Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(writers-room): AI passes (evaluate/format/script), per-scene image gen, drag-and-drop into folders, collapsible Library

Adam Eivyd6e03f622c2a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f7aaf68602..5f3695845e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Writers Room — manual AI passes (Evaluate / Format / Adapt to Screenplay).** Three new prompt stages in `data.sample/prompts/stages/writers-room-{evaluate,format,script}.md` (registered in `stage-config.json`, seeded into `data/prompts/` by `npm run setup:data`) drive a new evaluator service (`server/services/writersRoom/evaluator.js`). Triggered by user click from a new AI tab in the WorkEditor right sidebar — never auto-runs. **Evaluate** returns a structured editorial critique (logline, summary, themes, strengths, severity-tagged issues with verbatim excerpts, target-anchored suggestions). **Format** returns cleaned prose with paragraphing, dialogue formatting, whitespace, punctuation, and consistent chapter/scene markdown headings; an "Apply to draft" button replaces the editor buffer (no autosave — user still has to hit Save). **Adapt to Screenplay** returns a scene-by-scene breakdown with sluglines, action, dialogue, and a self-contained `visualPrompt` per scene that the per-scene "Generate image" button feeds into the existing `/api/image-gen/generate` queue — making Writers Room the first surface that hands prose-driven prompts straight into the FLUX.2 image pipeline. Snapshots are immutable and pinned to the source draft's `contentHash`; the analyses list shows a stale-warning badge when the draft has moved on since the analysis ran. Storage: `data/writers-room/works/<id>/analysis/<analysisId>.json`. Routes: `POST /api/writers-room/works/:id/analysis` (kind required), `GET /api/writers-room/works/:id/analysis`, `GET /api/writers-room/works/:id/analysis/:analysisId`. Boot recovery (`recoverStuckAnalyses` in `server/index.js`) marks any `running` snapshot as `failed` after a server restart so the UI never spins on a phantom row. Single source of truth for analysis kinds (`ANALYSIS_KINDS` in `writersRoomPresets.js`) shared by Zod and the evaluator. Reuses `stripCodeFences` from `server/lib/aiProvider.js` instead of carrying its own fence regex.
+- **Writers Room — drag-and-drop works between folders.** Each work row in the Library pane now has a grip handle (left edge) — drag from there to drop the work onto any folder header to file it, or onto the Unfiled zone to remove it from a folder. Built on `@dnd-kit/core` (already a dependency, same pattern as `KanbanBoard.jsx` / `goals/GoalsListView.jsx`). PointerSensor uses a 6px activation distance so a normal click still selects the work. Dropping into a closed folder auto-expands it so the moved work is immediately visible. While a drag is in flight the Unfiled zone always renders (even when empty) with a "Drop here to unfile" hint so a user can unfile the only work in a folder. A `<DragOverlay>` chip follows the cursor while the source row dims to 30% opacity. Toast confirms the move (`Moved "Bad Curry" to Dream Machine` / `Moved "Bad Curry" to Unfiled`). Backend was already wired — the existing `PATCH /api/writers-room/works/:id` accepts `{ folderId }`.
- **Writers Room (`/writers-room`) — Phase 1 authoring core.** New top-level `Create` sidebar group bundles **Media Gen** (default landing) with **Writers Room**, the new file-backed workspace for prose/short-story/screenplay/novel/essay drafts. Library pane manages folders + works; Markdown editor with live word count, segment-index outline (auto-derived from `#` chapters and `##`/`###` scenes), version snapshots, and Cmd/Ctrl+S save; "Write for 10" sprint timer with 5/10/15/25-min presets, prompt field, and per-session word-delta logging. Storage lives under `data/writers-room/` (`folders.json`, `exercises.json`, `works/<id>/manifest.json` + `drafts/*.md`) — driven by a single writer (`server/services/writersRoom/local.js`) following the Creative Director pattern. New routes under `/api/writers-room/*` cover folder/work CRUD, draft body I/O, version snapshot/switch, and exercise lifecycle. Backend tests cover word counting, content-hash determinism, segment-index splitting, folder/work CRUD with cross-validation (deleting a non-empty folder, missing-parent rejection), draft round-trip + version pointer-switching across multiple snapshots, exercise duration clamping + word-delta math + settled-state rejection, and the strict Zod schemas at the route boundary. Mobile/touch-friendly: library pane caps height on mobile, delete buttons stay reachable without hover. Phases 2-5 (manual AI analysis, Creative Director handoff, synced prose/script/media review, realtime CD feedback) tracked in `docs/features/writers-room.md`.
- **Queue additional renders while one is in flight.** Image Gen form fields stay editable during a render and the Generate button becomes a "Queue" button — submissions land in `mediaJobQueue` (server FIFO) without taking over the active SSE/preview, so the user can stack multiple prompts without waiting. A "+N queued" badge surfaces queue depth, and a 4 s `/api/media-jobs` poll syncs it against the server's truth and refreshes the gallery the moment a queued render completes (only on busy-count drop — no per-tick refresh churn). The poll's effect deps key on a `queueActive` boolean so the interval clock doesn't tear down on every count change. A separate "Cancel current" button lets the user kill the active render without losing the form's content. Mirrors the form-editable-during-render policy already in place for video gen.
- **STAGE pipeline for FLUX.2 model loading + downloads.** `flux2_macos.py` now emits `STAGE:download-tokenizer:<repo>` / `STAGE:download-pipeline:<repo>` / `STAGE:move-to-device` / `STAGE:inference` markers; `server/services/imageGen/local.js#handleLine` parses them and broadcasts a typed `{type:'stage', stage, detail}` SSE event. The Image Gen page maps each marker to a friendly label via a `STAGE_LABELS` lookup ("Downloading model weights (~8 GB on first run)…", "Moving model to GPU…", etc.) so the multi-minute first-run HF weight download no longer looks like a frozen "step 0/8". Inference progress events also carry the active phase so the step counter only ticks during real diffusion, not during download `tqdm` bars (which count safetensors files, not steps).
@@ -26,6 +28,7 @@
## Changed
+- **Writers Room — Library pane is collapsible.** A new chevron button in the header hides the 260px library to give the editor full width; a thin 32px rail stays visible with an expand button so the user can bring it back. State persists in `localStorage` under `wr.libraryCollapsed` and survives reloads. Right sidebar in the WorkEditor was also reorganized into three tabs — **AI** (default), **Outline**, **Versions** — replacing the previous always-visible Outline + Versions stack so the AI panel has room to render evaluation results, format diffs, and scene cards inline.
- **Edge-to-edge layout for Media Gen, Writers Room, and Settings.** Pages that own a tab strip now follow the canonical full-width shell (header → edge-to-edge tab bar → padded content area) used by Calendar/Brain/etc., so the tab strip pins to the page edges instead of floating inside a centered `max-w-7xl` box. `Layout.jsx` also drops the `max-w-7xl mx-auto` cap on the remaining boxed pages, so on wide monitors content fills the available width (outer `p-4 md:p-6` is preserved, so non-tabbed pages still have breathing room). `MediaGen.jsx` and `Settings.jsx` were rewritten to the canonical shell; `WritersRoom.jsx` swapped its `h-[calc(100vh-3rem)]` viewport hack for `h-full` so the desktop layout no longer leaves a 3rem dead gap at the bottom.
- **Sidebar reorg: AI group folded into Settings.** The top-level `AI` sidebar group is gone — its two children (`Prompts`, `Providers`) now live alphabetically under `Settings`. `server/lib/navManifest.js` re-keys `nav.prompts` → `nav.settings.prompts` and `nav.providers` → `nav.settings.providers` (with `section: 'Settings'`) so ⌘K and the voice agent's `ui_navigate` resolver group them with the rest of Settings. Routes (`/prompts`, `/ai`) are unchanged — only the navigational grouping moved, so existing bookmarks keep working.
- **Image Gen and Video Gen layouts tightened for above-the-fold density.** Form and preview now render side-by-side on `lg+` (`grid-cols-[3fr_2fr]`) instead of stacking; previews are capped (image `max-w-[360px]`, video `max-w-[420px]`) so they no longer dominate the viewport. Prompt + Negative Prompt sit in two columns on `md+`, parameter grids force three columns on `sm+`, the LTX mode switch and mode-specific image pickers are more compact, and section headers adopt a consistent `text-xs uppercase` style. Status text is hoisted into the Generate button row, video Download moved into the preview header for parity with image. Note: the codebase requires underscore (not comma) separators in Tailwind arbitrary grid template values (e.g. `lg:grid-cols-[3fr_2fr]`); the prior `[1fr,1.2fr]` was silently falling back to a single column.
@@ -33,6 +36,7 @@
## Fixed
+- **Writers Room — "Add folder" form no longer clips its Cancel button.** The new-folder inline form previously laid out as `[input flex-1] [Add] [Cancel]` inside the 260px library aside, which left no room for the Cancel button — it overflowed off the right edge and was clipped by the panel's overflow boundary. Restructured to stack: the input takes the full width, then `[Add (flex-1)] [Cancel]` sits on a second row inside a `bg-port-card` boxed group matching the new-work form's existing layout.
- **FLUX.2 stepwise previews now actually render.** The callback's `vae.decode(latents)` was silently failing every step with `IndexError: tuple index out of range` because `Flux2KleinPipeline` hands the callback latents in transformer-packed shape `(B, num_patches, C·P²)` (e.g. `(1, 2304, 128)` for 1024×576) but the VAE expects unpacked `(B, C, H, W)`. New `_unpack_flux2_latents()` does the patch unpack (2×2 patches × 8× VAE downsample) before the decode call. `make_stepwise_callback()` now takes `height`/`width` and short-circuits the unpack if a future pipeline version hands us an already-4-D tensor.
- **FLUX.2 install detection now checks functional health, not just file existence.** Previously `resolveFlux2Python()` returned the venv binary path as long as the file existed — but a venv whose install was killed mid-pip leaves the python binary behind with an empty site-packages, so the status endpoint reported `venvInstalled: true`, the install banner cleared, and rendering crashed with `Exit code 1` in 100ms when `flux2_macos.py` failed to `import diffusers`. New helper `isFlux2VenvHealthy()` (cached) probes `from diffusers import Flux2KleinPipeline` once. `/setup/flux2-status` and `/setup/flux2-install`'s early-return both use it, so a half-broken venv now reports as not-installed and the user can retry the install from the UI without manual cleanup.
- **PM2 watcher debounce reduced from 5 min → 1 min** and `ignore_watch` hardened with `data/`, `logs/`, `.cache/`, and `portos-stepwise-*` patterns. `watch: ['server']` already scopes the watcher correctly, but the long debounce meant a server-file edit + start-render-now sequence could cleanly kick off a render and then have PM2 restart 5 minutes in, killing the Python child with SIGINT halfway through. Tighter debounce + explicit defense-in-depth ignore patterns make the failure mode less catastrophic and easier to predict during dev.
diff --git a/client/src/components/writers-room/AiPanel.jsx b/client/src/components/writers-room/AiPanel.jsx
new file mode 100644
index 0000000000..90d3549955
--- /dev/null
+++ b/client/src/components/writers-room/AiPanel.jsx
@@ -0,0 +1,359 @@
+import { useEffect, useState, useCallback, useRef } from 'react';
+import { Sparkles, FileSignature, Clapperboard, Loader2, RotateCcw, AlertTriangle, Image as ImageIcon, Check } from 'lucide-react';
+import toast from '../ui/Toast';
+import {
+ listWritersRoomAnalyses,
+ runWritersRoomAnalysis,
+ getWritersRoomAnalysis,
+} from '../../services/apiWritersRoom';
+import { generateImage } from '../../services/apiSystem';
+import { timeAgo } from '../../utils/formatters';
+
+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' },
+};
+
+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 }) {
+ const [analyses, setAnalyses] = useState([]);
+ const [loadingList, setLoadingList] = useState(false);
+ const [running, setRunning] = useState(null);
+ const [expanded, setExpanded] = useState(null);
+ const [details, setDetails] = useState({});
+
+ const mountedRef = useRef(true);
+ useEffect(() => () => { 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 = await listWritersRoomAnalyses(work.id).catch((err) => {
+ if (mountedRef.current) toast.error(`Failed to list analyses: ${err.message}`);
+ return [];
+ });
+ if (!mountedRef.current) return;
+ setLoadingList(false);
+ setAnalyses(list);
+ }, [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({});
+ 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)]);
+ };
+
+ 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-3 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>
+
+ <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} />
+ )}
+ {full?.status === 'succeeded' && full.kind === 'format' && (
+ <FormatResult result={full.result} onApply={(text) => onApplyFormat?.(text)} />
+ )}
+ {full?.status === 'succeeded' && full.kind === 'script' && (
+ <ScriptResult result={full.result} workTitle={work.title} />
+ )}
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ </div>
+ );
+}
+
+function EvaluateResult({ result }) {
+ if (!result) return null;
+ return (
+ <div className="space-y-2 text-[11px] text-gray-300">
+ {result.logline && <div><span className="text-gray-500 uppercase text-[9px]">Logline</span><div className="italic">{result.logline}</div></div>}
+ {result.summary && <div><span className="text-gray-500 uppercase text-[9px]">Summary</span><div>{result.summary}</div></div>}
+ {result.themes?.length > 0 && (
+ <div>
+ <span className="text-gray-500 uppercase text-[9px]">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 bg-port-card border border-port-border rounded text-[10px]">{t}</span>)}
+ </div>
+ </div>
+ )}
+ {result.strengths?.length > 0 && (
+ <div>
+ <span className="text-gray-500 uppercase text-[9px]">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="text-gray-500 uppercase text-[9px]">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="text-gray-500 italic mt-0.5">"{iss.excerpt}"</div>}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ {result.suggestions?.length > 0 && (
+ <div>
+ <span className="text-gray-500 uppercase text-[9px]">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="text-gray-500 uppercase text-[9px]">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 text-gray-300 bg-port-bg border border-port-border rounded p-2 max-h-64 overflow-y-auto">{text}</pre>
+ </div>
+ );
+}
+
+function ScriptResult({ result, workTitle }) {
+ 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">
+ {result.logline && <div className="italic text-gray-400">"{result.logline}"</div>}
+ {result.scenes.map((scene, i) => (
+ <SceneCard key={scene.id || i} scene={scene} workTitle={workTitle} />
+ ))}
+ </div>
+ );
+}
+
+function SceneCard({ scene, workTitle }) {
+ const [genStatus, setGenStatus] = useState('idle');
+ const [generated, setGenerated] = useState(null);
+ const [error, setError] = useState(null);
+
+ const generate = async () => {
+ if (genStatus === 'running') return;
+ if (!scene.visualPrompt?.trim()) {
+ toast('No visual prompt for this scene', { icon: '⚠️' });
+ return;
+ }
+ setGenStatus('running');
+ setError(null);
+ // Truncate at 1900 chars to stay under the 2000-char API limit even when
+ // the model returns a chatty visualPrompt.
+ const prompt = `${workTitle ? `${workTitle}. ` : ''}${scene.visualPrompt}`.slice(0, 1900);
+ const res = await generateImage({ prompt }).catch((err) => {
+ setError(err.message);
+ setGenStatus('error');
+ return null;
+ });
+ if (!res) return;
+ setGenerated({ path: res.path, jobId: res.jobId, prompt });
+ setGenStatus('done');
+ };
+
+ return (
+ <div className="border border-port-border rounded p-2 space-y-1.5 bg-port-card/40">
+ <div className="flex items-start gap-2">
+ <div className="flex-1 min-w-0">
+ <div className="font-semibold text-white truncate">{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' ? 'Queuing…' : 'Image'}
+ </button>
+ </div>
+ {scene.summary && <div className="text-gray-400">{scene.summary}</div>}
+ {scene.characters?.length > 0 && (
+ <div className="flex flex-wrap gap-1">
+ {scene.characters.map((c, i) => <span key={i} className="px-1.5 py-0.5 bg-port-bg border border-port-border rounded text-[9px] uppercase tracking-wider">{c}</span>)}
+ </div>
+ )}
+ {scene.action && <div className="text-gray-300 whitespace-pre-wrap font-serif">{scene.action}</div>}
+ {scene.dialogue?.length > 0 && (
+ <div className="space-y-1 pl-3 border-l border-port-border">
+ {scene.dialogue.map((d, i) => (
+ <div key={i}>
+ <div className="text-[9px] uppercase tracking-wider text-gray-500">{d.character}</div>
+ <div className="text-gray-300 italic">"{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>
+ )}
+ {generated && (
+ <div className="mt-1 space-y-1">
+ <a href={generated.path} target="_blank" rel="noreferrer" className="block">
+ <img
+ src={generated.path}
+ alt={scene.heading}
+ loading="lazy"
+ className="w-full rounded border border-port-border"
+ onError={(e) => { e.currentTarget.style.display = 'none'; }}
+ />
+ </a>
+ <div className="text-[9px] text-gray-500 truncate">job {generated.jobId}</div>
+ </div>
+ )}
+ {error && <div className="text-[10px] text-port-error">{error}</div>}
+ </div>
+ );
+}
diff --git a/client/src/components/writers-room/LibraryPane.jsx b/client/src/components/writers-room/LibraryPane.jsx
index 1e0dd4b94b..f53ca473e6 100644
--- a/client/src/components/writers-room/LibraryPane.jsx
+++ b/client/src/components/writers-room/LibraryPane.jsx
@@ -1,14 +1,18 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
-import { Folder, FolderPlus, FilePlus, FileText, ChevronDown, ChevronRight, Trash2 } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Folder, FolderPlus, FilePlus, FileText, ChevronDown, ChevronRight, Trash2, GripVertical } from 'lucide-react';
+import { DndContext, DragOverlay, PointerSensor, useDraggable, useDroppable, useSensor, useSensors } from '@dnd-kit/core';
import toast from '../ui/Toast';
import {
createWritersRoomFolder,
deleteWritersRoomFolder,
createWritersRoomWork,
deleteWritersRoomWork,
+ updateWritersRoomWork,
} from '../../services/apiWritersRoom';
import { KIND_LABELS } from './labels';
+const UNFILED_DROP_ID = 'wr-unfiled';
+
export default function LibraryPane({ folders, works, activeWorkId, onSelectWork, onRefresh }) {
const [openFolders, setOpenFolders] = useState({});
const [creatingFolder, setCreatingFolder] = useState(false);
@@ -100,35 +104,44 @@ export default function LibraryPane({ folders, works, activeWorkId, onSelectWork
onRefresh?.();
};
- const renderWorkRow = (work) => {
- const isActive = work.id === activeWorkId;
- return (
- <li key={work.id} className="group relative">
- <button
- onClick={() => onSelectWork?.(work.id)}
- className={`w-full flex items-center gap-2 px-2 py-1.5 rounded text-left text-sm transition-colors ${
- isActive ? 'bg-port-accent/20 text-port-accent' : 'text-gray-300 hover:bg-port-card hover:text-white'
- }`}
- >
- <FileText size={14} aria-hidden="true" className="shrink-0" />
- <span className="truncate flex-1">{work.title}</span>
- <span className="text-[10px] text-gray-500 uppercase">{work.wordCount} w</span>
- </button>
- <button
- onClick={() => handleDeleteWork(work.id, work.title)}
- className={`absolute right-1 top-1.5 p-0.5 transition-opacity ${
- armedDelete === `work:${work.id}`
- ? 'opacity-100 text-port-error'
- : 'opacity-40 sm:opacity-0 group-hover:opacity-100 focus:opacity-100 text-gray-500 hover:text-port-error'
- }`}
- aria-label={`Delete ${work.title}`}
- title={armedDelete === `work:${work.id}` ? 'Click again to confirm' : 'Delete'}
- >
- <Trash2 size={12} />
- </button>
- </li>
- );
- };
+ // PointerSensor with a small activation distance so a quick click still
+ // selects the work — only an actual drag gesture starts a DnD operation.
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
+ const [draggingWork, setDraggingWork] = useState(null);
+
+ const handleDragStart = useCallback((event) => {
+ setDraggingWork(event.active.data.current?.work || null);
+ }, []);
+
+ const handleDragEnd = useCallback(async (event) => {
+ setDraggingWork(null);
+ const { active, over } = event;
+ if (!over || !active) return;
+ const work = active.data.current?.work;
+ if (!work) return;
+ const targetFolderId = over.data.current?.folderId ?? null;
+ if (work.folderId === targetFolderId) return;
+ const updated = await updateWritersRoomWork(work.id, { folderId: targetFolderId }).catch((err) => {
+ toast.error(`Move failed: ${err.message}`);
+ return null;
+ });
+ if (!updated) return;
+ const targetFolder = folders.find((f) => f.id === targetFolderId);
+ toast.success(`Moved "${work.title}" to ${targetFolder ? targetFolder.name : 'Unfiled'}`);
+ if (targetFolderId) setOpenFolders((s) => ({ ...s, [targetFolderId]: true }));
+ onRefresh?.();
+ }, [folders, onRefresh]);
+
+ const renderWorkRow = (work) => (
+ <WorkRow
+ key={work.id}
+ work={work}
+ isActive={work.id === activeWorkId}
+ armedDelete={armedDelete === `work:${work.id}`}
+ onSelect={() => onSelectWork?.(work.id)}
+ onDelete={() => handleDeleteWork(work.id, work.title)}
+ />
+ );
return (
<div className="space-y-4 text-sm">
@@ -155,17 +168,19 @@ export default function LibraryPane({ folders, works, activeWorkId, onSelectWork
</div>
{creatingFolder && (
- <form onSubmit={submitFolder} className="flex items-center gap-1">
+ <form onSubmit={submitFolder} className="space-y-1 bg-port-card border border-port-border rounded p-2">
<input
autoFocus
value={folderName}
onChange={(e) => setFolderName(e.target.value)}
placeholder="Folder name"
- className="flex-1 bg-port-card border border-port-border rounded px-2 py-1 text-xs"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs min-w-0"
/>
- <button type="submit" className="text-xs px-2 py-1 bg-port-accent text-white rounded">Add</button>
- <button type="button" onClick={() => { setCreatingFolder(false); setFolderName(''); }}
- className="text-xs px-2 py-1 text-gray-400">Cancel</button>
+ <div className="flex items-center gap-1">
+ <button type="submit" className="text-xs px-2 py-1 bg-port-accent text-white rounded flex-1">Add</button>
+ <button type="button" onClick={() => { setCreatingFolder(false); setFolderName(''); }}
+ className="text-xs px-2 py-1 text-gray-400">Cancel</button>
+ </div>
</form>
)}
@@ -192,69 +207,168 @@ export default function LibraryPane({ folders, works, activeWorkId, onSelectWork
</form>
)}
- <ul className="space-y-1">
- {folders.length === 0 && grouped.get(null).length === 0 && !creatingFolder && !creatingWork && (
- <li className="text-xs text-gray-500 px-2 py-3 text-center">
- No works yet. Click <FilePlus size={12} className="inline" /> to start.
- </li>
- )}
+ <DndContext sensors={sensors} onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
+ <ul className="space-y-1">
+ {folders.length === 0 && grouped.get(null).length === 0 && !creatingFolder && !creatingWork && (
+ <li className="text-xs text-gray-500 px-2 py-3 text-center">
+ No works yet. Click <FilePlus size={12} className="inline" /> to start.
+ </li>
+ )}
- {/* Unfiled works */}
- {grouped.get(null).length > 0 && (
- <li>
- <div className="text-[10px] uppercase text-gray-500 px-2 py-1">Unfiled</div>
- <ul className="space-y-0.5 pl-1 relative">{grouped.get(null).map(renderWorkRow)}</ul>
- </li>
- )}
+ <UnfiledZone
+ works={grouped.get(null)}
+ renderWorkRow={renderWorkRow}
+ showHeader={folders.length > 0 || grouped.get(null).length > 0}
+ isDragging={!!draggingWork}
+ />
- {folders.map((folder) => {
- const isOpen = openFolders[folder.id];
- const folderWorks = grouped.get(folder.id) || [];
- return (
- <li key={folder.id} className="group/folder">
- <div className="flex items-center gap-1">
- <button
- onClick={() => toggleFolder(folder.id)}
- className="flex-1 flex items-center gap-1 px-2 py-1 text-gray-300 hover:text-white text-sm"
- >
- {isOpen ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
- <Folder size={14} className="text-gray-400" />
- <span className="flex-1 text-left truncate">{folder.name}</span>
- <span className="text-[10px] text-gray-500">{folderWorks.length}</span>
- </button>
- <button
- onClick={() => { setCreatingWork(folder.id); setCreatingFolder(false); }}
- className="p-1 text-gray-500 hover:text-port-accent transition-opacity opacity-40 sm:opacity-0 group-hover/folder:opacity-100 focus:opacity-100"
- aria-label="Add work to folder"
- title="New work in folder"
- >
- <FilePlus size={12} />
- </button>
- <button
- onClick={() => handleDeleteFolder(folder.id, folder.name)}
- className={`p-1 transition-opacity ${
- armedDelete === `folder:${folder.id}`
- ? 'opacity-100 text-port-error'
- : 'opacity-40 sm:opacity-0 group-hover/folder:opacity-100 focus:opacity-100 text-gray-500 hover:text-port-error'
- }`}
- aria-label={`Delete folder ${folder.name}`}
- title={armedDelete === `folder:${folder.id}` ? 'Click again to confirm' : 'Delete folder'}
- >
- <Trash2 size={12} />
- </button>
- </div>
- {isOpen && (
- <ul className="space-y-0.5 pl-5 relative">
- {folderWorks.length === 0 && (
- <li className="text-xs text-gray-500 px-2 py-1">Empty</li>
- )}
- {folderWorks.map(renderWorkRow)}
- </ul>
- )}
- </li>
- );
- })}
- </ul>
+ {folders.map((folder) => (
+ <FolderRow
+ key={folder.id}
+ folder={folder}
+ works={grouped.get(folder.id) || []}
+ isOpen={!!openFolders[folder.id]}
+ isDragging={!!draggingWork}
+ armedDelete={armedDelete === `folder:${folder.id}`}
+ onToggle={() => toggleFolder(folder.id)}
+ onCreateWork={() => { setCreatingWork(folder.id); setCreatingFolder(false); }}
+ onDelete={() => handleDeleteFolder(folder.id, folder.name)}
+ renderWorkRow={renderWorkRow}
+ />
+ ))}
+ </ul>
+
+ <DragOverlay>
+ {draggingWork && (
+ <div className="flex items-center gap-2 px-2 py-1.5 rounded bg-port-card border border-port-accent text-sm text-port-accent shadow-lg">
+ <FileText size={14} aria-hidden="true" />
+ <span className="truncate max-w-[200px]">{draggingWork.title}</span>
+ </div>
+ )}
+ </DragOverlay>
+ </DndContext>
</div>
);
}
+
+// ---------- DnD-aware subcomponents ----------
+
+function WorkRow({ work, isActive, armedDelete, onSelect, onDelete }) {
+ const { attributes, listeners, setNodeRef, isDragging } = useDraggable({
+ id: `work:${work.id}`,
+ data: { work },
+ });
+ return (
+ <li className={`group relative ${isDragging ? 'opacity-30' : ''}`}>
+ <div className="flex items-stretch">
+ <button
+ ref={setNodeRef}
+ {...attributes}
+ {...listeners}
+ className="shrink-0 px-1 flex items-center cursor-grab active:cursor-grabbing touch-none text-gray-600 hover:text-gray-300"
+ title="Drag to move into a folder"
+ aria-label={`Drag ${work.title}`}
+ >
+ <GripVertical size={12} />
+ </button>
+ <button
+ onClick={onSelect}
+ className={`flex-1 flex items-center gap-2 px-2 py-1.5 rounded text-left text-sm transition-colors min-w-0 ${
+ isActive ? 'bg-port-accent/20 text-port-accent' : 'text-gray-300 hover:bg-port-card hover:text-white'
+ }`}
+ >
+ <FileText size={14} aria-hidden="true" className="shrink-0" />
+ <span className="truncate flex-1">{work.title}</span>
+ <span className="text-[10px] text-gray-500 uppercase">{work.wordCount} w</span>
+ </button>
+ </div>
+ <button
+ onClick={onDelete}
+ className={`absolute right-1 top-1.5 p-0.5 transition-opacity ${
+ armedDelete
+ ? 'opacity-100 text-port-error'
+ : 'opacity-40 sm:opacity-0 group-hover:opacity-100 focus:opacity-100 text-gray-500 hover:text-port-error'
+ }`}
+ aria-label={`Delete ${work.title}`}
+ title={armedDelete ? 'Click again to confirm' : 'Delete'}
+ >
+ <Trash2 size={12} />
+ </button>
+ </li>
+ );
+}
+
+function UnfiledZone({ works, renderWorkRow, showHeader, isDragging }) {
+ const { setNodeRef, isOver } = useDroppable({ id: UNFILED_DROP_ID, data: { folderId: null } });
+ const hasWorks = works.length > 0;
+ // Always render the drop target while a drag is in flight so a user can
+ // unfile a work even when the section is currently empty.
+ if (!hasWorks && !isDragging) return null;
+ return (
+ <li
+ ref={setNodeRef}
+ className={`rounded transition-colors ${isOver ? 'bg-port-accent/10 ring-1 ring-port-accent' : ''}`}
+ >
+ {(showHeader || isDragging) && (
+ <div className="text-[10px] uppercase text-gray-500 px-2 py-1">Unfiled</div>
+ )}
+ {hasWorks ? (
+ <ul className="space-y-0.5 pl-1 relative">{works.map(renderWorkRow)}</ul>
+ ) : (
+ <div className="text-xs text-gray-600 italic px-2 py-1">Drop here to unfile</div>
+ )}
+ </li>
+ );
+}
+
+function FolderRow({ folder, works, isOpen, isDragging, armedDelete, onToggle, onCreateWork, onDelete, renderWorkRow }) {
+ const { setNodeRef, isOver } = useDroppable({ id: `folder:${folder.id}`, data: { folderId: folder.id } });
+ return (
+ <li className="group/folder">
+ <div
+ ref={setNodeRef}
+ className={`flex items-center gap-1 rounded transition-colors ${
+ isOver && isDragging ? 'bg-port-accent/15 ring-1 ring-port-accent' : ''
+ }`}
+ >
+ <button
+ onClick={onToggle}
+ className="flex-1 flex items-center gap-1 px-2 py-1 text-gray-300 hover:text-white text-sm min-w-0"
+ >
+ {isOpen ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
+ <Folder size={14} className="text-gray-400" />
+ <span className="flex-1 text-left truncate">{folder.name}</span>
+ <span className="text-[10px] text-gray-500">{works.length}</span>
+ </button>
+ <button
+ onClick={onCreateWork}
+ className="p-1 text-gray-500 hover:text-port-accent transition-opacity opacity-40 sm:opacity-0 group-hover/folder:opacity-100 focus:opacity-100"
+ aria-label="Add work to folder"
+ title="New work in folder"
+ >
+ <FilePlus size={12} />
+ </button>
+ <button
+ onClick={onDelete}
+ className={`p-1 transition-opacity ${
+ armedDelete
+ ? 'opacity-100 text-port-error'
+ : 'opacity-40 sm:opacity-0 group-hover/folder:opacity-100 focus:opacity-100 text-gray-500 hover:text-port-error'
+ }`}
+ aria-label={`Delete folder ${folder.name}`}
+ title={armedDelete ? 'Click again to confirm' : 'Delete folder'}
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ {isOpen && (
+ <ul className="space-y-0.5 pl-5 relative">
+ {works.length === 0 && (
+ <li className="text-xs text-gray-500 px-2 py-1">Empty</li>
+ )}
+ {works.map(renderWorkRow)}
+ </ul>
+ )}
+ </li>
+ );
+}
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index 6472c1ad0f..5444018f5e 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
-import { Save, GitCommit, Clock, FileText } from 'lucide-react';
+import { Save, GitCommit, Clock, FileText, Sparkles, ListTree } from 'lucide-react';
import toast from '../ui/Toast';
import {
saveWritersRoomDraft,
@@ -9,10 +9,18 @@ import {
} from '../../services/apiWritersRoom';
import { KIND_LABELS, 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 },
+];
export default function WorkEditor({ work, onChange }) {
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
@@ -209,48 +217,74 @@ export default function WorkEditor({ work, onChange }) {
</div>
</div>
- <aside className="border-t lg:border-t-0 lg:border-l border-port-border bg-port-card/60 px-3 py-3 overflow-y-auto text-xs space-y-4">
- <div>
- <h3 className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Outline</h3>
- <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</li>
- )}
- </ul>
+ <aside className="border-t lg:border-t-0 lg:border-l border-port-border bg-port-card/60 flex flex-col text-xs min-h-0">
+ <div className="flex border-b border-port-border bg-port-bg/40">
+ {SIDEBAR_TABS.map(({ id, label, Icon }) => (
+ <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'
+ }`}
+ aria-pressed={sidebarTab === id}
+ >
+ <Icon size={11} /> {label}
+ </button>
+ ))}
</div>
-
- <div>
- <h3 className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Versions</h3>
- <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>
+ <div className="flex-1 overflow-y-auto px-3 py-3">
+ {sidebarTab === 'ai' && (
+ <AiPanel
+ work={work}
+ 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>
- );
- })}
- </ul>
+ ))}
+ {(!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>
diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsx
index 9783696caf..6f73970f3a 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 } from 'lucide-react';
+import { NotebookPen, Timer, PanelLeftClose, 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';
@@ -10,6 +10,8 @@ import {
getWritersRoomWork,
} from '../services/apiWritersRoom';
+const LIBRARY_COLLAPSED_KEY = 'wr.libraryCollapsed';
+
export default function WritersRoom() {
const { workId } = useParams();
const navigate = useNavigate();
@@ -18,6 +20,18 @@ export default function WritersRoom() {
const [activeWork, setActiveWork] = useState(null);
const [loadingWork, setLoadingWork] = useState(false);
const [showExercise, setShowExercise] = useState(false);
+ // Library collapsed state — desktop only; mobile keeps the library inline
+ // because there's no editor-vs-library tradeoff to make on a small screen.
+ const [libraryCollapsed, setLibraryCollapsed] = useState(() => {
+ try { return localStorage.getItem(LIBRARY_COLLAPSED_KEY) === '1'; } catch { return false; }
+ });
+ const toggleLibrary = useCallback(() => {
+ setLibraryCollapsed((prev) => {
+ const next = !prev;
+ try { localStorage.setItem(LIBRARY_COLLAPSED_KEY, next ? '1' : '0'); } catch { /* sandboxed storage */ }
+ return next;
+ });
+ }, []);
// Skip setState when an in-flight library or work fetch resolves after the
// page unmounts (rapid nav across pages).
@@ -92,9 +106,24 @@ export default function WritersRoom() {
});
};
+ // Inline gridTemplateColumns is a no-op while the container is `display: flex`
+ // (mobile) and takes effect once `md:grid` flips display at the breakpoint.
+ const libraryTrack = libraryCollapsed ? '32px' : '260px';
+ const exerciseSuffix = showExercise ? ' 320px' : '';
+ const desktopGridCols = `${libraryTrack} minmax(0, 1fr)${exerciseSuffix}`;
+
return (
<div className="flex flex-col h-full">
<div className="flex items-center gap-3 px-4 py-3 border-b border-port-border bg-port-card">
+ <button
+ onClick={toggleLibrary}
+ className="hidden md:inline-flex items-center justify-center w-6 h-6 text-gray-400 hover:text-white"
+ title={libraryCollapsed ? 'Show library' : 'Hide library'}
+ aria-label={libraryCollapsed ? 'Show library' : 'Hide library'}
+ aria-expanded={!libraryCollapsed}
+ >
+ {libraryCollapsed ? <PanelLeftOpen size={16} /> : <PanelLeftClose size={16} />}
+ </button>
<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>
@@ -111,16 +140,32 @@ export default function WritersRoom() {
</button>
</div>
- <div className="flex-1 grid grid-cols-1 md:grid-cols-[260px_1fr] lg:grid-cols-[260px_1fr_320px] min-h-0">
- <aside className="border-b md:border-b-0 md:border-r border-port-border bg-port-card/40 px-3 py-3 overflow-y-auto max-h-64 md:max-h-none">
- <LibraryPane
- folders={folders}
- works={works}
- activeWorkId={activeWork?.id}
- onSelectWork={selectWork}
- onRefresh={refreshLibrary}
- />
- </aside>
+ <div
+ className="flex-1 flex flex-col md:grid min-h-0"
+ style={{ gridTemplateColumns: desktopGridCols }}
+ >
+ {libraryCollapsed ? (
+ <aside className="hidden md:flex border-r border-port-border bg-port-card/40 items-start justify-center pt-3">
+ <button
+ onClick={toggleLibrary}
+ className="p-1.5 text-gray-500 hover:text-white"
+ title="Show library"
+ aria-label="Show library"
+ >
+ <PanelLeftOpen size={14} />
+ </button>
+ </aside>
+ ) : (
+ <aside className="border-b md:border-b-0 md:border-r border-port-border bg-port-card/40 px-3 py-3 overflow-y-auto max-h-64 md:max-h-none">
+ <LibraryPane
+ folders={folders}
+ works={works}
+ activeWorkId={activeWork?.id}
+ onSelectWork={selectWork}
+ onRefresh={refreshLibrary}
+ />
+ </aside>
+ )}
<main className="min-h-0 flex flex-col">
{loadingWork && <div className="p-6 text-sm text-gray-500">Loading work…</div>}
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index c39176c201..b83a71bddd 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -40,6 +40,17 @@ export const setWritersRoomActiveDraft = (id, draftId) => request(`/writers-room
method: 'PATCH',
});
+// Analysis (AI passes — evaluate / format / script)
+export const listWritersRoomAnalyses = (workId) =>
+ request(`/writers-room/works/${enc(workId)}/analysis`);
+export const runWritersRoomAnalysis = (workId, data) =>
+ request(`/writers-room/works/${enc(workId)}/analysis`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+ });
+export const getWritersRoomAnalysis = (workId, analysisId) =>
+ request(`/writers-room/works/${enc(workId)}/analysis/${enc(analysisId)}`);
+
// Exercises
export const listWritersRoomExercises = (workId) => {
const qs = workId ? `?workId=${enc(workId)}` : '';
diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.json
index dd36a7ac27..99bbdff26b 100644
--- a/data.sample/prompts/stage-config.json
+++ b/data.sample/prompts/stage-config.json
@@ -1,5 +1,26 @@
{
"stages": {
+ "writers-room-evaluate": {
+ "name": "Writers Room — Prose Evaluation",
+ "description": "Editorial pass on a Writers Room draft: logline, summary, themes, strengths, issues with excerpts, and concrete suggestions.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "writers-room-format": {
+ "name": "Writers Room — Auto-format Prose",
+ "description": "Copy-edit pass on a Writers Room draft: paragraphing, dialogue formatting, whitespace, punctuation, and consistent chapter/scene markdown headings. Returns cleaned prose only.",
+ "model": "default",
+ "returnsJson": false,
+ "variables": []
+ },
+ "writers-room-script": {
+ "name": "Writers Room — Adapt to Scene Script",
+ "description": "Adapt a Writers Room prose draft into a scene-by-scene screenplay-style breakdown with sluglines, action, dialogue, and per-scene visual prompts the image-gen pipeline can render.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"cd-treatment": {
"name": "Creative Director — Treatment",
"description": "Plan a long-form generated-video project: write the logline, synopsis, and scene-by-scene treatment.",
diff --git a/data.sample/prompts/stages/writers-room-evaluate.md b/data.sample/prompts/stages/writers-room-evaluate.md
new file mode 100644
index 0000000000..15a83751f3
--- /dev/null
+++ b/data.sample/prompts/stages/writers-room-evaluate.md
@@ -0,0 +1,54 @@
+# Writers Room — Prose Evaluation
+
+You are an editorial reader giving a single round of constructive feedback on a draft. Your job is to read the prose carefully and return a structured critique that helps the writer revise.
+
+## Work being reviewed
+
+- Title: {{work.title}}
+- Kind: {{work.kind}}
+- Status: {{work.status}}
+- Word count: {{work.wordCount}}
+
+## Prose
+
+```
+{{draftBody}}
+```
+
+## Task
+
+Read the entire draft. Then produce one editorial pass that covers:
+
+1. **Logline** — one sentence that captures what this story is about.
+2. **Summary** — two to four sentences that summarize the arc.
+3. **Themes** — the dominant themes the prose actually leans into (not aspirational).
+4. **Strengths** — concrete craft strengths visible in the text (voice, image, dialogue, pacing).
+5. **Issues** — concrete problems the writer should address. Each issue is an object with:
+ - `severity`: "minor" | "moderate" | "major"
+ - `category`: short tag like "pacing", "character", "clarity", "continuity", "voice", "stakes"
+ - `note`: 1–3 sentence description of the problem
+ - `excerpt`: a short verbatim quote from the draft that anchors the issue (≤ 200 characters)
+6. **Suggestions** — concrete next-step recommendations. Each suggestion is an object with:
+ - `target`: which scene / chapter / passage it applies to
+ - `recommendation`: 1–3 sentence actionable suggestion
+
+Be specific. Cite text. Do not summarize back generic writing advice.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "logline": "string",
+ "summary": "string",
+ "themes": ["string", ...],
+ "strengths": ["string", ...],
+ "issues": [
+ { "severity": "minor|moderate|major", "category": "string", "note": "string", "excerpt": "string" }
+ ],
+ "suggestions": [
+ { "target": "string", "recommendation": "string" }
+ ]
+}
+```
diff --git a/data.sample/prompts/stages/writers-room-format.md b/data.sample/prompts/stages/writers-room-format.md
new file mode 100644
index 0000000000..a6577b50bd
--- /dev/null
+++ b/data.sample/prompts/stages/writers-room-format.md
@@ -0,0 +1,36 @@
+# Writers Room — Auto-format Prose
+
+You are a copy editor cleaning up a draft. The author wants the prose tidied without changing the story or the voice.
+
+## Work being formatted
+
+- Title: {{work.title}}
+- Kind: {{work.kind}}
+- Word count: {{work.wordCount}}
+
+## Prose
+
+```
+{{draftBody}}
+```
+
+## Task
+
+Return the SAME story, same voice, same words wherever possible — but cleaned up. Apply these passes:
+
+1. **Paragraphing** — break run-on paragraphs at natural pauses; merge accidental fragments.
+2. **Dialogue formatting** — each speaker on a new line, proper quotation marks, attributions formatted consistently.
+3. **Whitespace** — collapse triple+ blank lines to a single blank; trim trailing spaces on lines.
+4. **Punctuation & spelling** — fix obvious typos, smart-quote consistency, em/en dash usage; do not change the author's intentional stylization.
+5. **Markdown headings** — if the draft uses chapter/scene markers, keep them as `# Chapter N — Title`, `## Scene Title`. Do not invent new headings.
+
+Do not:
+
+- Rewrite sentences for style or word choice.
+- Add or remove paragraphs of content.
+- Introduce summaries, headings, or commentary.
+- Wrap your output in code fences or commentary.
+
+## Output contract
+
+Return ONLY the cleaned prose as plain Markdown — no preamble, no closing remark, no code fence.
diff --git a/data.sample/prompts/stages/writers-room-script.md b/data.sample/prompts/stages/writers-room-script.md
new file mode 100644
index 0000000000..bfcf1a945d
--- /dev/null
+++ b/data.sample/prompts/stages/writers-room-script.md
@@ -0,0 +1,55 @@
+# Writers Room — Adapt Prose into Scene-by-Scene Script
+
+You are a screenwriter adapting a piece of prose into a scene-by-scene breakdown. The breakdown will drive both a downstream screenplay pass and a per-scene image/video reference pipeline, so each scene must carry both a screenplay-style description and a self-contained visual prompt.
+
+## Work being adapted
+
+- Title: {{work.title}}
+- Kind: {{work.kind}}
+- Word count: {{work.wordCount}}
+
+## Source prose
+
+```
+{{draftBody}}
+```
+
+## Task
+
+1. Identify the scenes in the prose. A scene = one continuous unit of action in one location with a stable point-of-view.
+2. For each scene, write:
+ - A heading like `Scene 1 — The Curry Burns`.
+ - A `slugline` in screenplay format: `INT./EXT. LOCATION — TIME OF DAY` (uppercase).
+ - A `summary` (1–3 sentences) of what happens.
+ - A `characters` list of named characters present.
+ - A short `action` block (≤ 5 sentences) in present tense, screenplay style.
+ - A `dialogue` array with significant lines: `[{ "character": "NAME", "line": "..." }]`. Skip filler like "He said hi." Only quote lines that carry the scene.
+ - A `visualPrompt`: a single self-contained image-generator prompt (~40–80 words) that describes the scene as a still frame: subjects, location, lighting, mood, camera framing, color palette, time of day. Bake in style cues from the prose (genre, era). Do NOT reference characters by name — describe them physically so an image model with no story context can render them.
+3. Don't pad. If the natural arc is 3 scenes, return 3.
+4. Keep `sourceSegmentIds` empty unless the prose uses explicit `# Chapter` / `## Scene` markdown headings — in that case, attribute each generated scene to the heading id like `seg-001`.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "title": "string (the work title or your suggested screenplay title)",
+ "logline": "string (one-sentence pitch)",
+ "scenes": [
+ {
+ "id": "scene-01",
+ "heading": "Scene 1 — Title",
+ "slugline": "INT. KITCHEN — NIGHT",
+ "summary": "string",
+ "characters": ["NAME", ...],
+ "action": "string",
+ "dialogue": [
+ { "character": "NAME", "line": "string" }
+ ],
+ "visualPrompt": "string",
+ "sourceSegmentIds": ["seg-001"]
+ }
+ ]
+}
+```
diff --git a/server/index.js b/server/index.js
index bbb42edba4..0320af744e 100644
--- a/server/index.js
+++ b/server/index.js
@@ -113,6 +113,7 @@ import { startUpdateScheduler, recordUpdateResult, clearStaleUpdateInProgress, g
import { restoreLoops } from './services/loops.js';
import { startBrainScheduler } from './services/brainScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
+import { recoverStuckAnalyses } from './services/writersRoom/evaluator.js';
import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';
import { initDrillCache } from './services/meatspacePostDrillCache.js';
import { createAIToolkit } from 'portos-ai-toolkit/server';
@@ -345,6 +346,7 @@ try {
// Recover any inbox entries stuck in 'classifying' from a previous crash/restart
recoverStuckClassifications().catch(err => console.error(`❌ Brain recovery failed: ${err.message}`));
+recoverStuckAnalyses().catch(err => console.error(`❌ Writers Room recovery failed: ${err.message}`));
// Initialize brain scheduler for daily digests and weekly reviews
startBrainScheduler();
// Initialize brain→memory bridge (mirrors brain data into CoS memory for semantic search)
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 33bc61ab3d..8f780a0cc2 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1,7 +1,7 @@
import { z } from 'zod';
import { ServerError } from './errorHandler.js';
import { ASPECT_RATIOS, QUALITIES, PROJECT_STATUSES, SCENE_STATUSES } from './creativeDirectorPresets.js';
-import { WORK_KINDS, WORK_STATUSES } from './writersRoomPresets.js';
+import { WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS } from './writersRoomPresets.js';
// =============================================================================
// AGENT PERSONALITY SCHEMAS
@@ -519,6 +519,10 @@ export const writersRoomExerciseFinishSchema = z.object({
appendedText: z.string().max(100000).nullable().optional()
}).strict();
+export const writersRoomAnalysisCreateSchema = z.object({
+ kind: z.enum(ANALYSIS_KINDS)
+}).strict();
+
// =============================================================================
// FEATURE AGENT SCHEMAS
// =============================================================================
diff --git a/server/lib/writersRoomPresets.js b/server/lib/writersRoomPresets.js
index a559d8fcb3..1145b70918 100644
--- a/server/lib/writersRoomPresets.js
+++ b/server/lib/writersRoomPresets.js
@@ -5,3 +5,4 @@
export const WORK_KINDS = ['novel', 'short-story', 'screenplay', 'essay', 'treatment', 'other'];
export const WORK_STATUSES = ['idea', 'drafting', 'revision', 'adaptation', 'rendering', 'complete', 'archived'];
export const EXERCISE_STATUSES = ['running', 'finished', 'discarded'];
+export const ANALYSIS_KINDS = ['evaluate', 'format', 'script'];
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index 999183a7bf..651a849ba4 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -14,6 +14,7 @@ import {
writersRoomSnapshotSchema,
writersRoomExerciseCreateSchema,
writersRoomExerciseFinishSchema,
+ writersRoomAnalysisCreateSchema,
} from '../lib/validation.js';
import {
listFolders, createFolder, deleteFolder,
@@ -21,6 +22,9 @@ import {
saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,
listExercises, createExercise, finishExercise, discardExercise,
} from '../services/writersRoom/local.js';
+import {
+ runAnalysis, listAnalyses, getAnalysis,
+} from '../services/writersRoom/evaluator.js';
const router = Router();
@@ -120,4 +124,20 @@ router.post('/exercises/:id/discard', asyncHandler(async (req, res) => {
res.json(await discardExercise(req.params.id));
}));
+// ---------- analysis ----------
+
+router.get('/works/:id/analysis', asyncHandler(async (req, res) => {
+ res.json(await listAnalyses(req.params.id));
+}));
+
+router.post('/works/:id/analysis', asyncHandler(async (req, res) => {
+ const data = validateRequest(writersRoomAnalysisCreateSchema, req.body || {});
+ const snapshot = await runAnalysis(req.params.id, data);
+ res.status(snapshot.status === 'succeeded' ? 201 : 200).json(snapshot);
+}));
+
+router.get('/works/:id/analysis/:analysisId', asyncHandler(async (req, res) => {
+ res.json(await getAnalysis(req.params.id, req.params.analysisId));
+}));
+
export default router;
diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.js
new file mode 100644
index 0000000000..c4f97bc2d6
--- /dev/null
+++ b/server/services/writersRoom/evaluator.js
@@ -0,0 +1,333 @@
+/**
+ * Writers Room — manual AI passes against a draft (evaluate / format / script).
+ * Snapshots persist immutably under data/writers-room/works/<id>/analysis/ and
+ * pin the source draft's contentHash so the UI can flag stale results.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { spawn } from 'child_process';
+import { readFile, readdir } from 'fs/promises';
+import { PATHS, atomicWrite, ensureDir, safeJSONParse } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { stripCodeFences } from '../../lib/aiProvider.js';
+import { getActiveProvider } from '../providers.js';
+import { buildPrompt } from '../promptService.js';
+import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';
+import { getWorkWithBody } from './local.js';
+
+export { ANALYSIS_KINDS };
+
+const KIND_META = {
+ evaluate: { stage: 'writers-room-evaluate', returnsJson: true },
+ format: { stage: 'writers-room-format', returnsJson: false },
+ script: { stage: 'writers-room-script', returnsJson: true },
+};
+
+const ANALYSIS_ID_RE = /^wr-analysis-[0-9a-f-]+$/i;
+
+const root = () => join(PATHS.data, 'writers-room');
+const analysisDir = (workId) => join(root(), 'works', workId, 'analysis');
+const analysisPath = (workId, id) => join(analysisDir(workId), `${id}.json`);
+
+function nowIso() { return new Date().toISOString(); }
+function badRequest(msg) { return new ServerError(msg, { status: 400, code: 'VALIDATION_ERROR' }); }
+function notFound(what) { return new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' }); }
+
+// ---------- LLM invocation ----------
+
+async function resolveProvider() {
+ const active = await getActiveProvider().catch(() => null);
+ if (active?.enabled) return active;
+ throw new ServerError('No AI provider available', { status: 503, code: 'NO_PROVIDER' });
+}
+
+async function callApiProvider(provider, model, prompt, temperature) {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ const response = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ model,
+ messages: [{ role: 'user', content: prompt }],
+ temperature,
+ }),
+ signal: AbortSignal.timeout(provider.timeout || 300000),
+ });
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ throw new Error(`AI API error: ${response.status} - ${text.slice(0, 500)}`);
+ }
+ const data = await response.json();
+ return data.choices?.[0]?.message?.content || '';
+}
+
+function callCliProvider(provider, model, prompt) {
+ return new Promise((resolve, reject) => {
+ const args = [...(provider.args || [])];
+ if (provider.headlessArgs?.length) args.push(...provider.headlessArgs);
+ const isGeminiCli = provider.id === 'gemini-cli';
+ if (isGeminiCli && !args.includes('--output-format') && !args.includes('-o')) {
+ args.push('--output-format', 'text');
+ }
+ if (model) args.push('--model', model);
+ // Send the prose via stdin for non-gemini CLIs — adapted-screenplay drafts
+ // can run tens of thousands of characters once headings and dialogue are
+ // inlined, well past argv ceilings on macOS/Linux.
+ const usingStdin = !isGeminiCli;
+ if (isGeminiCli) args.push('--prompt', prompt);
+ const child = spawn(provider.command, args, {
+ env: (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })(),
+ stdio: [usingStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
+ shell: false,
+ windowsHide: true,
+ });
+ let output = '';
+ child.stdout.on('data', (d) => { output += d.toString(); });
+ child.stderr.on('data', (d) => { output += d.toString(); });
+ const timeoutMs = provider.timeout || 300000;
+ const killer = setTimeout(() => {
+ child.kill('SIGKILL');
+ reject(new Error(`CLI AI call timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ child.on('close', (code) => {
+ clearTimeout(killer);
+ if (code === 0) resolve(output);
+ else reject(new Error(`CLI exited with code ${code}${output ? ': ' + output.slice(0, 500) : ''}`));
+ });
+ child.on('error', (err) => { clearTimeout(killer); reject(err); });
+ if (usingStdin) child.stdin.end(prompt);
+ });
+}
+
+async function callAI(stageName, variables, temperature) {
+ const provider = await resolveProvider();
+ const prompt = await buildPrompt(stageName, variables);
+ let model = provider.defaultModel;
+ if (provider.id === 'gemini-cli' && !model) {
+ model = provider.lightModel || 'gemini-2.5-flash-lite';
+ }
+ console.log(`📝 wr eval: ${provider.id} / ${model || '(default)'} / ${stageName}`);
+ if (provider.type === 'api') {
+ const content = await callApiProvider(provider, model, prompt, temperature);
+ return { content, model: model || null, providerId: provider.id };
+ }
+ if (provider.type === 'cli') {
+ const content = await callCliProvider(provider, model, prompt);
+ return { content, model: model || null, providerId: provider.id };
+ }
+ throw new Error(`Unsupported provider type: ${provider.type}`);
+}
+
+// ---------- response parsing ----------
+
+function extractJson(text) {
+ if (!text || typeof text !== 'string') throw new Error('Empty AI response');
+ let str = stripCodeFences(text);
+ // Some providers prepend explanation text; pull the first balanced object/array.
+ const objMatch = str.match(/[\{\[][\s\S]*[\}\]]/);
+ if (objMatch) str = objMatch[0];
+ return JSON.parse(str);
+}
+
+const SHAPERS = {
+ format: (raw) => {
+ let text = raw.trim();
+ const fence = text.match(/^```(?:markdown|md|text)?\s*([\s\S]*?)```$/);
+ if (fence) text = fence[1].trim();
+ return { formattedBody: text };
+ },
+ evaluate: (raw) => {
+ const parsed = extractJson(raw);
+ return {
+ logline: typeof parsed.logline === 'string' ? parsed.logline : null,
+ summary: typeof parsed.summary === 'string' ? parsed.summary : null,
+ themes: Array.isArray(parsed.themes) ? parsed.themes.filter((t) => typeof t === 'string') : [],
+ strengths: Array.isArray(parsed.strengths) ? parsed.strengths.filter((s) => typeof s === 'string') : [],
+ issues: Array.isArray(parsed.issues) ? parsed.issues.filter((i) => i && typeof i === 'object') : [],
+ suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions.filter((s) => s && typeof s === 'object') : [],
+ };
+ },
+ script: (raw) => {
+ const parsed = extractJson(raw);
+ const scenes = Array.isArray(parsed.scenes) ? parsed.scenes : [];
+ return {
+ title: typeof parsed.title === 'string' ? parsed.title : null,
+ logline: typeof parsed.logline === 'string' ? parsed.logline : null,
+ scenes: scenes.map((s, i) => ({
+ id: typeof s.id === 'string' ? s.id : `scene-${String(i + 1).padStart(2, '0')}`,
+ heading: typeof s.heading === 'string' ? s.heading : `Scene ${i + 1}`,
+ slugline: typeof s.slugline === 'string' ? s.slugline : null,
+ summary: typeof s.summary === 'string' ? s.summary : '',
+ characters: Array.isArray(s.characters) ? s.characters.filter((c) => typeof c === 'string') : [],
+ action: typeof s.action === 'string' ? s.action : '',
+ dialogue: Array.isArray(s.dialogue) ? s.dialogue.filter((d) => d && typeof d === 'object') : [],
+ visualPrompt: typeof s.visualPrompt === 'string' ? s.visualPrompt : '',
+ sourceSegmentIds: Array.isArray(s.sourceSegmentIds) ? s.sourceSegmentIds.filter((id) => typeof id === 'string') : [],
+ })),
+ };
+ },
+};
+
+// ---------- storage ----------
+
+async function listAnalysisIds(workId) {
+ const dir = analysisDir(workId);
+ await ensureDir(dir);
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
+ return entries
+ .filter((e) => e.isFile() && e.name.endsWith('.json'))
+ .map((e) => e.name.replace(/\.json$/, ''))
+ .filter((id) => ANALYSIS_ID_RE.test(id));
+}
+
+async function loadAnalysis(workId, id) {
+ const content = await readFile(analysisPath(workId, id), 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (content === null) return null;
+ return safeJSONParse(content, null, { allowArray: false, logError: true, context: analysisPath(workId, id) });
+}
+
+async function saveAnalysis(workId, snapshot) {
+ await ensureDir(analysisDir(workId));
+ await atomicWrite(analysisPath(workId, snapshot.id), snapshot);
+}
+
+function summarize(a) {
+ return {
+ id: a.id,
+ workId: a.workId,
+ kind: a.kind,
+ status: a.status,
+ draftVersionId: a.draftVersionId,
+ sourceContentHash: a.sourceContentHash,
+ providerId: a.providerId,
+ model: a.model,
+ error: a.error || null,
+ createdAt: a.createdAt,
+ completedAt: a.completedAt,
+ };
+}
+
+export async function listAnalyses(workId) {
+ const ids = await listAnalysisIds(workId);
+ const all = await Promise.all(ids.map((id) => loadAnalysis(workId, id)));
+ return all
+ .filter(Boolean)
+ .map(summarize)
+ .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
+}
+
+export async function getAnalysis(workId, id) {
+ if (!ANALYSIS_ID_RE.test(id)) throw badRequest('Invalid analysis id');
+ const a = await loadAnalysis(workId, id);
+ if (!a) throw notFound('Analysis');
+ return a;
+}
+
+// ---------- startup recovery ----------
+
+/**
+ * Mark any `running` snapshots as `failed`. A server restart kills in-flight
+ * LLM calls but the pre-call snapshot is already on disk, so without this the
+ * UI would spin forever on a phantom row. Idempotent; called fire-and-forget
+ * at boot.
+ */
+export async function recoverStuckAnalyses() {
+ const worksRoot = join(root(), 'works');
+ const workEntries = await readdir(worksRoot, { withFileTypes: true }).catch(() => []);
+ const counts = await Promise.all(
+ workEntries
+ .filter((e) => e.isDirectory())
+ .map(async (entry) => {
+ const ids = await listAnalysisIds(entry.name).catch(() => []);
+ const results = await Promise.all(ids.map(async (id) => {
+ const a = await loadAnalysis(entry.name, id);
+ if (a?.status !== 'running') return 0;
+ await saveAnalysis(entry.name, {
+ ...a,
+ status: 'failed',
+ error: 'Server restarted while this analysis was running',
+ completedAt: nowIso(),
+ });
+ return 1;
+ }));
+ return results.reduce((s, n) => s + n, 0);
+ })
+ );
+ const recovered = counts.reduce((s, n) => s + n, 0);
+ if (recovered > 0) console.log(`📝 wr: recovered ${recovered} stuck analysis snapshot(s) on boot`);
+}
+
+// ---------- run ----------
+
+export async function runAnalysis(workId, { kind } = {}) {
+ if (!ANALYSIS_KINDS.includes(kind)) {
+ throw badRequest(`Invalid analysis kind: ${kind}. Expected one of ${ANALYSIS_KINDS.join(', ')}`);
+ }
+ const { stage, returnsJson } = KIND_META[kind];
+ const { manifest, body } = await getWorkWithBody(workId);
+ if (!body || !body.trim()) {
+ throw badRequest('Cannot analyze an empty draft — write some prose first');
+ }
+ const draft = (manifest.drafts || []).find((d) => d.id === manifest.activeDraftVersionId);
+ const id = `wr-analysis-${randomUUID()}`;
+ const baseSnapshot = {
+ id,
+ workId,
+ kind,
+ status: 'running',
+ draftVersionId: manifest.activeDraftVersionId,
+ sourceContentHash: draft?.contentHash || null,
+ providerId: null,
+ model: null,
+ result: null,
+ error: null,
+ createdAt: nowIso(),
+ completedAt: null,
+ };
+ await saveAnalysis(workId, baseSnapshot);
+
+ // Awaited synchronously by the route — the client gets the finished record
+ // back in one round-trip. A failure mid-call is persisted as a `failed`
+ // snapshot so partial work never silently disappears.
+ try {
+ const variables = {
+ work: {
+ id: manifest.id,
+ title: manifest.title,
+ kind: manifest.kind,
+ status: manifest.status,
+ wordCount: draft?.wordCount || 0,
+ },
+ draftBody: body,
+ returnsJson,
+ };
+ const temperature = kind === 'format' ? 0.2 : 0.4;
+ const { content, model: usedModel, providerId: usedProvider } = await callAI(stage, variables, temperature);
+ const result = SHAPERS[kind](content);
+ const finished = {
+ ...baseSnapshot,
+ status: 'succeeded',
+ providerId: usedProvider,
+ model: usedModel,
+ result,
+ rawResponse: content,
+ completedAt: nowIso(),
+ };
+ await saveAnalysis(workId, finished);
+ return finished;
+ } catch (err) {
+ const failed = {
+ ...baseSnapshot,
+ status: 'failed',
+ error: err.message || String(err),
+ completedAt: nowIso(),
+ };
+ await saveAnalysis(workId, failed);
+ return failed;
+ }
+}