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([issue-704]): Writers Room synced prose/script/media review (Phase 4)

[._.]/ Adam Eivyb2c87e0677ef
diff --git a/client/src/components/writers-room/SyncedReview.jsx b/client/src/components/writers-room/SyncedReview.jsx
new file mode 100644
index 0000000000..c8c2fc51f6
--- /dev/null
+++ b/client/src/components/writers-room/SyncedReview.jsx
@@ -0,0 +1,398 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ AlertTriangle, Clapperboard, FileText, Image as ImageIcon, Link2, Loader2, RefreshCw, X,
+} from 'lucide-react';
+import { getWritersRoomSyncedReview } from '../../services/apiWritersRoom';
+import { timeAgo } from '../../utils/formatters';
+import useMounted from '../../hooks/useMounted';
+
+// Phase 4 synchronized review: prose ↔ script ↔ media in three sync'd panes.
+// Selecting any item highlights — and scrolls to — what it maps to in the
+// other panes. The mapping + provenance is assembled server-side
+// (GET /synced-review); see services/writersRoom/syncedReview.js.
+
+const PANES = [
+ { key: 'prose', label: 'Prose', icon: FileText },
+ { key: 'script', label: 'Script', icon: Clapperboard },
+ { key: 'media', label: 'Media', icon: ImageIcon },
+];
+
+const imgUrl = (ref) => `/data/images/${ref}`;
+
+// Scroll a pane's scroll container so the element tagged with `data-sync-id`
+// lands near the top, WITHOUT scrolling the whole window (manual scrollTop
+// rather than scrollIntoView, which walks every scrollable ancestor).
+function scrollPaneTo(container, syncId) {
+ if (!container || !syncId || typeof container.scrollTo !== 'function') return;
+ const el = container.querySelector(`[data-sync-id="${CSS.escape(syncId)}"]`);
+ if (!el) return;
+ const top = el.offsetTop - container.offsetTop - 12;
+ container.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
+}
+
+// Derive the highlight sets for a selection. Each pane reads its own set; the
+// selected item itself always highlights. Empty sets when nothing is selected.
+function computeHighlights(data, selection) {
+ const proseIds = new Set();
+ const sceneIds = new Set();
+ const mediaSceneIds = new Set(); // media items are keyed by their source sceneId
+ if (!data || !selection) return { proseIds, sceneIds, mediaSceneIds };
+ if (selection.type === 'prose') {
+ proseIds.add(selection.id);
+ const seg = data.prose.segments.find((s) => s.id === selection.id);
+ (seg?.scriptSceneIds || []).forEach((id) => sceneIds.add(id));
+ (seg?.media || []).forEach((m) => mediaSceneIds.add(m.sceneId));
+ } else if (selection.type === 'script') {
+ sceneIds.add(selection.id);
+ const sc = data.script.scenes.find((s) => s.id === selection.id);
+ (sc?.proseSegmentIds || []).forEach((id) => proseIds.add(id));
+ if (sc?.media) mediaSceneIds.add(selection.id);
+ } else if (selection.type === 'media') {
+ mediaSceneIds.add(selection.id);
+ const item = data.media.items.find((m) => m.sceneId === selection.id);
+ (item?.proseSegmentIds || []).forEach((id) => proseIds.add(id));
+ if (item && !item.orphan) sceneIds.add(selection.id);
+ }
+ return { proseIds, sceneIds, mediaSceneIds };
+}
+
+// Visual state for a card given the active selection: 'selected' | 'linked' |
+// 'dim' | 'none'. Drives the ring/opacity so a selection reads at a glance.
+function cardState(isSelected, isLinked, hasSelection) {
+ if (isSelected) return 'selected';
+ if (isLinked) return 'linked';
+ return hasSelection ? 'dim' : 'none';
+}
+
+const CARD_CLASS = {
+ selected: 'border-port-accent ring-1 ring-port-accent bg-port-accent/[0.06]',
+ linked: 'border-port-accent/50 bg-port-accent/[0.03]',
+ dim: 'border-port-border opacity-40',
+ none: 'border-port-border',
+};
+
+export default function SyncedReview({ work }) {
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(null);
+ const [selection, setSelection] = useState(null);
+ const [visible, setVisible] = useState(() => new Set(['prose', 'script', 'media']));
+ const mountedRef = useMounted();
+
+ const proseRef = useRef(null);
+ const scriptRef = useRef(null);
+ const mediaRef = useRef(null);
+
+ const refresh = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ const result = await getWritersRoomSyncedReview(work.id, { silent: true }).catch((err) => {
+ if (mountedRef.current) setError(err.message || 'Failed to load review');
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setLoading(false);
+ if (result) setData(result);
+ }, [work.id, mountedRef]);
+
+ useEffect(() => {
+ setData(null);
+ setSelection(null);
+ refresh();
+ }, [refresh]);
+
+ const { proseIds, sceneIds, mediaSceneIds } = useMemo(
+ () => computeHighlights(data, selection),
+ [data, selection],
+ );
+
+ // Resolve prose segment ids → headings for provenance labels.
+ const segHeading = useMemo(() => {
+ const map = new Map();
+ (data?.prose.segments || []).forEach((s) => map.set(s.id, s.heading || s.id));
+ return map;
+ }, [data]);
+
+ // On selection, scroll the OTHER panes to the first mapped item.
+ useEffect(() => {
+ if (!selection || !data) return;
+ if (selection.type !== 'prose' && proseIds.size) scrollPaneTo(proseRef.current, [...proseIds][0]);
+ if (selection.type !== 'script' && sceneIds.size) scrollPaneTo(scriptRef.current, [...sceneIds][0]);
+ if (selection.type !== 'media' && mediaSceneIds.size) scrollPaneTo(mediaRef.current, [...mediaSceneIds][0]);
+ }, [selection, data, proseIds, sceneIds, mediaSceneIds]);
+
+ const select = useCallback((type, id) => {
+ setSelection((prev) => (prev && prev.type === type && prev.id === id ? null : { type, id }));
+ }, []);
+
+ const togglePane = useCallback((key) => {
+ setVisible((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) {
+ if (next.size === 1) return prev; // keep at least one pane visible
+ next.delete(key);
+ } else {
+ next.add(key);
+ }
+ return next;
+ });
+ }, []);
+
+ const hasSelection = !!selection;
+ const visibleCount = [...visible].length;
+ const colClass = visibleCount === 1 ? 'lg:grid-cols-1' : visibleCount === 2 ? 'lg:grid-cols-2' : 'lg:grid-cols-3';
+
+ if (loading && !data) {
+ return (
+ <div className="w-full h-full flex items-center justify-center text-gray-500 text-sm gap-2">
+ <Loader2 size={16} className="animate-spin" /> Loading synced review…
+ </div>
+ );
+ }
+
+ if (error && !data) {
+ return (
+ <div className="w-full h-full flex flex-col items-center justify-center text-sm gap-3 px-6 text-center">
+ <AlertTriangle size={20} className="text-port-error" />
+ <div className="text-gray-400">{error}</div>
+ <button onClick={refresh} className="flex items-center gap-1 px-3 py-1 rounded bg-port-bg border border-port-border text-gray-300 hover:text-white">
+ <RefreshCw size={12} /> Retry
+ </button>
+ </div>
+ );
+ }
+
+ if (!data) return null;
+
+ const noProse = data.prose.segments.length === 0;
+
+ return (
+ <div className="w-full h-full flex flex-col bg-port-bg min-h-0">
+ {/* Toolbar */}
+ <div className="flex items-center gap-2 px-4 py-2 border-b border-port-border bg-port-bg/60 shrink-0 flex-wrap">
+ <div className="flex items-center bg-port-card border border-port-border rounded p-0.5" role="group" aria-label="Visible panes">
+ {PANES.map(({ key, label, icon: Icon }) => (
+ <button
+ key={key}
+ type="button"
+ aria-pressed={visible.has(key)}
+ onClick={() => togglePane(key)}
+ className={`flex items-center gap-1 px-2 py-0.5 text-[11px] rounded ${
+ visible.has(key) ? 'bg-port-accent text-white' : 'text-gray-400 hover:text-gray-200'
+ }`}
+ title={`Toggle ${label} pane`}
+ >
+ <Icon size={11} /> {label}
+ </button>
+ ))}
+ </div>
+
+ {data.script.stale && (
+ <span className="flex items-center gap-1 text-[10px] text-port-warning border border-port-warning/40 rounded px-1.5 py-0.5" title="The draft changed after this script was generated — re-run Adapt to refresh the mapping.">
+ <AlertTriangle size={10} /> Script is stale
+ </span>
+ )}
+
+ {hasSelection && (
+ <button
+ onClick={() => setSelection(null)}
+ className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-white px-2 py-0.5 rounded border border-port-border"
+ title="Clear selection"
+ >
+ <X size={11} /> Clear link
+ </button>
+ )}
+
+ <div className="ml-auto flex items-center gap-2">
+ {data.script.completedAt && (
+ <span className="text-[10px] text-gray-500" title={`Provider: ${data.script.providerId || '—'} · Model: ${data.script.model || '—'}`}>
+ script {timeAgo(data.script.completedAt, '')}
+ </span>
+ )}
+ <button
+ onClick={refresh}
+ disabled={loading}
+ className="flex items-center gap-1 text-[11px] text-gray-300 hover:text-white px-2 py-0.5 rounded bg-port-card border border-port-border disabled:opacity-50"
+ title="Reload mappings"
+ >
+ <RefreshCw size={11} className={loading ? 'animate-spin' : ''} /> Refresh
+ </button>
+ </div>
+ </div>
+
+ {noProse ? (
+ <div className="flex-1 flex items-center justify-center text-gray-500 text-sm px-6 text-center">
+ Nothing to review yet — switch to Edit, write some prose, and save. Run “Adapt” to generate the script mapping.
+ </div>
+ ) : (
+ <div className={`flex-1 min-h-0 grid grid-cols-1 ${colClass} gap-px bg-port-border overflow-hidden`}>
+ {visible.has('prose') && (
+ <ProsePane
+ containerRef={proseRef}
+ segments={data.prose.segments}
+ proseIds={proseIds}
+ hasSelection={hasSelection}
+ onSelect={(id) => select('prose', id)}
+ />
+ )}
+ {visible.has('script') && (
+ <ScriptPane
+ containerRef={scriptRef}
+ script={data.script}
+ sceneIds={sceneIds}
+ hasSelection={hasSelection}
+ segHeading={segHeading}
+ onSelect={(id) => select('script', id)}
+ />
+ )}
+ {visible.has('media') && (
+ <MediaPane
+ containerRef={mediaRef}
+ items={data.media.items}
+ mediaSceneIds={mediaSceneIds}
+ hasSelection={hasSelection}
+ segHeading={segHeading}
+ onSelect={(sceneId) => select('media', sceneId)}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+// Shared pane chrome: the scroll container + sticky header. Each pane passes
+// its own item list (or empty state) as children.
+function ScrollPane({ containerRef, icon: Icon, label, count, children }) {
+ return (
+ <div ref={containerRef} className="bg-port-bg overflow-y-auto min-h-0">
+ <div className="flex items-center gap-1.5 px-3 py-1.5 text-[11px] uppercase tracking-wider text-gray-400 border-b border-port-border bg-port-card/60 sticky top-0 z-10">
+ <Icon size={12} /> {label}
+ <span className="text-gray-600">· {count}</span>
+ </div>
+ {children}
+ </div>
+ );
+}
+
+// ---- Prose pane ----
+function ProsePane({ containerRef, segments, proseIds, hasSelection, onSelect }) {
+ return (
+ <ScrollPane containerRef={containerRef} icon={FileText} label="Prose" count={segments.length}>
+ <div className="p-3 space-y-2">
+ {segments.map((seg) => {
+ const state = cardState(false, proseIds.has(seg.id), hasSelection);
+ return (
+ <button
+ key={seg.id}
+ data-sync-id={seg.id}
+ onClick={() => onSelect(seg.id)}
+ className={`w-full text-left rounded border px-3 py-2 transition-all ${CARD_CLASS[state]}`}
+ >
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <span className="text-[11px] font-medium text-gray-300 truncate">{seg.heading}</span>
+ <span className="flex items-center gap-2 shrink-0 text-[10px] text-gray-500">
+ {seg.scriptSceneIds.length > 0 && (
+ <span className="flex items-center gap-0.5"><Clapperboard size={10} />{seg.scriptSceneIds.length}</span>
+ )}
+ {seg.media.length > 0 && (
+ <span className="flex items-center gap-0.5"><ImageIcon size={10} />{seg.media.length}</span>
+ )}
+ </span>
+ </div>
+ <p className="text-[11px] text-gray-400 leading-snug line-clamp-3 whitespace-pre-wrap font-serif">{seg.text}</p>
+ </button>
+ );
+ })}
+ </div>
+ </ScrollPane>
+ );
+}
+
+// ---- Script pane ----
+function ScriptPane({ containerRef, script, sceneIds, hasSelection, segHeading, onSelect }) {
+ return (
+ <ScrollPane containerRef={containerRef} icon={Clapperboard} label="Script" count={script.scenes.length}>
+ {!script.available ? (
+ <div className="p-4 text-[11px] text-gray-500 text-center">
+ {script.status === 'failed'
+ ? `Adapt failed: ${script.error}`
+ : 'No script yet — run “Adapt” to extract scenes from the prose.'}
+ </div>
+ ) : (
+ <div className="p-3 space-y-2">
+ {script.scenes.map((sc) => {
+ const state = cardState(false, sceneIds.has(sc.id), hasSelection);
+ return (
+ <button
+ key={sc.id}
+ data-sync-id={sc.id}
+ onClick={() => onSelect(sc.id)}
+ className={`w-full text-left rounded border px-3 py-2 transition-all ${CARD_CLASS[state]}`}
+ >
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <span className="text-[11px] font-medium text-gray-200 truncate">{sc.heading || sc.id}</span>
+ {sc.media && <ImageIcon size={11} className="text-port-accent shrink-0" />}
+ </div>
+ {sc.slugline && <div className="text-[10px] uppercase tracking-wide text-gray-500 mb-1">{sc.slugline}</div>}
+ {sc.summary && <p className="text-[11px] text-gray-400 leading-snug line-clamp-2">{sc.summary}</p>}
+ <div className="flex items-center gap-1.5 mt-1.5 flex-wrap">
+ {sc.proseSegmentIds.length > 0 ? (
+ sc.proseSegmentIds.map((pid) => (
+ <span key={pid} className="flex items-center gap-0.5 text-[9px] text-gray-400 bg-port-card border border-port-border rounded px-1 py-0.5">
+ <Link2 size={8} /> {segHeading.get(pid) || pid}
+ </span>
+ ))
+ ) : (
+ <span className="text-[9px] text-gray-600 italic">no mapped prose</span>
+ )}
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </ScrollPane>
+ );
+}
+
+// ---- Media pane ----
+function MediaPane({ containerRef, items, mediaSceneIds, hasSelection, segHeading, onSelect }) {
+ return (
+ <ScrollPane containerRef={containerRef} icon={ImageIcon} label="Media" count={items.length}>
+ {items.length === 0 ? (
+ <div className="p-4 text-[11px] text-gray-500 text-center">
+ No rendered media yet — generate scene images from the Storyboard panel.
+ </div>
+ ) : (
+ <div className="p-3 grid grid-cols-2 gap-2">
+ {items.map((m) => {
+ const state = cardState(false, mediaSceneIds.has(m.sceneId), hasSelection);
+ return (
+ <button
+ key={`${m.sceneId}-${m.ref}`}
+ data-sync-id={m.sceneId}
+ onClick={() => onSelect(m.sceneId)}
+ className={`text-left rounded border overflow-hidden transition-all ${CARD_CLASS[state]}`}
+ >
+ <img src={imgUrl(m.ref)} alt={m.sceneHeading || 'scene render'} loading="lazy" className="w-full aspect-video object-cover bg-port-card" />
+ <div className="px-2 py-1.5 space-y-0.5">
+ <div className="text-[10px] font-medium text-gray-300 truncate">
+ {m.orphan ? <span className="text-port-warning">source scene removed</span> : (m.sceneHeading || m.sceneId)}
+ </div>
+ {!m.orphan && m.proseSegmentIds.length > 0 && (
+ <div className="text-[9px] text-gray-500 truncate" title={m.proseSegmentIds.map((p) => segHeading.get(p) || p).join(', ')}>
+ from {m.proseSegmentIds.map((p) => segHeading.get(p) || p).join(', ')}
+ </div>
+ )}
+ {m.prompt && <div className="text-[9px] text-gray-600 line-clamp-2" title={m.prompt}>{m.prompt}</div>}
+ {m.generatedAt && <div className="text-[9px] text-gray-600">{timeAgo(m.generatedAt, '')}</div>}
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </ScrollPane>
+ );
+}
diff --git a/client/src/components/writers-room/SyncedReview.test.jsx b/client/src/components/writers-room/SyncedReview.test.jsx
new file mode 100644
index 0000000000..fb27c147b2
--- /dev/null
+++ b/client/src/components/writers-room/SyncedReview.test.jsx
@@ -0,0 +1,103 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+
+// Mock the API so the component renders a deterministic synced-review payload.
+const getWritersRoomSyncedReview = vi.fn();
+vi.mock('../../services/apiWritersRoom', () => ({
+ getWritersRoomSyncedReview: (...args) => getWritersRoomSyncedReview(...args),
+}));
+
+import SyncedReview from './SyncedReview';
+
+function payload(overrides = {}) {
+ return {
+ workId: 'wr-work-1',
+ title: 'Test',
+ draftVersionId: 'wr-draft-1',
+ activeContentHash: 'h',
+ prose: {
+ segments: [
+ { id: 'seg-001', kind: 'chapter', heading: 'Opening', start: 0, end: 10, wordCount: 5, text: 'The hero wakes.', scriptSceneIds: ['scene-01'], media: [] },
+ { id: 'seg-002', kind: 'chapter', heading: 'Battle', start: 10, end: 20, wordCount: 5, text: 'Swords clash.', scriptSceneIds: [], media: [] },
+ ],
+ },
+ script: {
+ available: true, status: 'succeeded', stale: false, analysisId: 'script',
+ providerId: 'openai', model: 'gpt-x', completedAt: '2026-01-01T00:00:00Z', error: null,
+ title: 'T', logline: 'L',
+ scenes: [
+ { id: 'scene-01', heading: 'Opening Scene', slugline: 'INT. ROOM', summary: 'wakes', characters: [], sourceSegmentIds: ['seg-001'], proseSegmentIds: ['seg-001'], media: null },
+ ],
+ },
+ media: { items: [] },
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ getWritersRoomSyncedReview.mockReset();
+});
+
+const work = { id: 'wr-work-1', title: 'Test' };
+
+describe('SyncedReview', () => {
+ it('renders the three panes from the assembled payload', async () => {
+ getWritersRoomSyncedReview.mockResolvedValue(payload());
+ render(<SyncedReview work={work} />);
+ // unique body text identifies each prose segment card
+ expect(await screen.findByText('The hero wakes.')).toBeTruthy();
+ expect(screen.getByText('Swords clash.')).toBeTruthy();
+ expect(screen.getByText('Opening Scene')).toBeTruthy();
+ // pane toggles in the toolbar
+ expect(screen.getByTitle('Toggle Prose pane')).toBeTruthy();
+ expect(screen.getByTitle('Toggle Script pane')).toBeTruthy();
+ expect(screen.getByTitle('Toggle Media pane')).toBeTruthy();
+ });
+
+ it('selecting a prose segment activates the cross-link (Clear link appears)', async () => {
+ getWritersRoomSyncedReview.mockResolvedValue(payload());
+ render(<SyncedReview work={work} />);
+ fireEvent.click(await screen.findByText('The hero wakes.'));
+ expect(await screen.findByText(/Clear link/)).toBeTruthy();
+ // clicking again clears the selection
+ fireEvent.click(screen.getByText('The hero wakes.'));
+ await waitFor(() => expect(screen.queryByText(/Clear link/)).toBeNull());
+ });
+
+ it('toggling the Script pane off hides it but keeps at least one pane', async () => {
+ getWritersRoomSyncedReview.mockResolvedValue(payload());
+ render(<SyncedReview work={work} />);
+ await screen.findByText('Opening Scene');
+ // toggle Script pane off via the toolbar button
+ const scriptToggle = screen.getByTitle('Toggle Script pane');
+ fireEvent.click(scriptToggle);
+ await waitFor(() => expect(screen.queryByText('Opening Scene')).toBeNull());
+ // prose pane still present
+ expect(screen.getByText('The hero wakes.')).toBeTruthy();
+ });
+
+ it('shows the stale badge when the script is stale', async () => {
+ getWritersRoomSyncedReview.mockResolvedValue(payload({
+ script: { ...payload().script, stale: true },
+ }));
+ render(<SyncedReview work={work} />);
+ expect(await screen.findByText(/Script is stale/)).toBeTruthy();
+ });
+
+ it('renders an empty state when the draft has no prose segments', async () => {
+ getWritersRoomSyncedReview.mockResolvedValue(payload({
+ prose: { segments: [] },
+ script: { ...payload().script, available: false, scenes: [] },
+ }));
+ render(<SyncedReview work={work} />);
+ expect(await screen.findByText(/Nothing to review yet/)).toBeTruthy();
+ });
+
+ it('prompts to run Adapt when no script is available', async () => {
+ getWritersRoomSyncedReview.mockResolvedValue(payload({
+ script: { available: false, status: null, stale: false, scenes: [], error: null },
+ }));
+ render(<SyncedReview work={work} />);
+ expect(await screen.findByText(/run .*Adapt/i)).toBeTruthy();
+ });
+});
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index ecf40414a4..2e2d98dc5a 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -19,6 +19,7 @@ import {
Loader2,
BookOpen,
Pencil,
+ Columns3,
Film,
ExternalLink,
} from 'lucide-react';
@@ -44,6 +45,7 @@ import { countWords } from '../../utils/formatters';
import StoryboardPanel, { STORYBOARD_TAB, STORYBOARD_TAB_VALUES } from './StoryboardPanel';
import AnalysisHistory from './AnalysisHistory';
import ProseReader from './ProseReader';
+import SyncedReview from './SyncedReview';
import ProseTokenPopover from './ProseTokenPopover';
import WritersRoomDock from './WritersRoomDock';
import useImageGenQueue from '../../hooks/useImageGenQueue';
@@ -139,14 +141,16 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
stopOne: queueStopOne,
} = useImageGenQueue();
- // View mode (Edit | Read) is URL-driven so it deep-links and survives reloads.
- // ?view=read switches to ProseReader; default is the existing textarea.
+ // View mode (Edit | Read | Review) is URL-driven so it deep-links and
+ // survives reloads. ?view=read → ProseReader; ?view=review → SyncedReview
+ // (Phase 4 prose/script/media surface); default is the existing textarea.
const [searchParams, setSearchParams] = useSearchParams();
- const viewMode = searchParams.get('view') === 'read' ? 'read' : 'edit';
+ const rawView = searchParams.get('view');
+ const viewMode = rawView === 'read' ? 'read' : rawView === 'review' ? 'review' : 'edit';
const setViewMode = useCallback((mode) => {
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
- if (mode === 'read') next.set('view', 'read'); else next.delete('view');
+ if (mode === 'read' || mode === 'review') next.set('view', mode); else next.delete('view');
return next;
}, { replace: true });
}, [setSearchParams]);
@@ -690,6 +694,17 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
>
<BookOpen size={11} /> Read
</button>
+ <button
+ type="button"
+ aria-pressed={viewMode === 'review'}
+ onClick={() => setViewMode('review')}
+ className={`flex items-center gap-1 px-2 py-0.5 text-[11px] rounded ${
+ viewMode === 'review' ? 'bg-port-card text-white' : 'text-gray-400 hover:text-gray-200'
+ }`}
+ title="Synced prose · script · media review"
+ >
+ <Columns3 size={11} /> Review
+ </button>
</div>
<button
onClick={handleSave}
@@ -765,11 +780,15 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
/>
)}
- {/* 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 === MOBILE_TAB.WRITING} onClick={() => setMobileTab(MOBILE_TAB.WRITING)} icon={PenLine} label="Writing" />
- <MobileTab active={mobileTab === MOBILE_TAB.STORYBOARD} onClick={() => setMobileTab(MOBILE_TAB.STORYBOARD)} icon={Clapperboard} label="Storyboard" />
- </div>
+ {/* Mobile-only Writing/Storyboard toggle — desktop renders both side-by-side.
+ Review mode is a full-width surface with no storyboard sidebar, so the
+ toggle is irrelevant there. */}
+ {viewMode !== 'review' && (
+ <div className="lg:hidden flex border-b border-port-border bg-port-bg/40 shrink-0">
+ <MobileTab active={mobileTab === MOBILE_TAB.WRITING} onClick={() => setMobileTab(MOBILE_TAB.WRITING)} icon={PenLine} label="Writing" />
+ <MobileTab active={mobileTab === MOBILE_TAB.STORYBOARD} onClick={() => setMobileTab(MOBILE_TAB.STORYBOARD)} icon={Clapperboard} label="Storyboard" />
+ </div>
+ )}
{/*
When the render dock is visible (queue non-empty) it's `position: fixed`
@@ -783,8 +802,10 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
className="flex-1 flex flex-col lg:flex-row min-h-0"
style={renderQueue.length ? { paddingBottom: 56 } : undefined}
>
- <div className={`relative min-h-0 flex-1 ${mobileTab === MOBILE_TAB.STORYBOARD ? 'hidden lg:block' : 'block'}`}>
- {viewMode === 'read' ? (
+ <div className={`relative min-h-0 flex-1 ${viewMode !== 'review' && mobileTab === MOBILE_TAB.STORYBOARD ? 'hidden lg:block' : 'block'}`}>
+ {viewMode === 'review' ? (
+ <SyncedReview work={work} />
+ ) : viewMode === 'read' ? (
<div ref={readerRef} className="w-full h-full">
<ProseReader
body={body}
@@ -812,16 +833,20 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
className="w-full h-full resize-none px-6 py-6 text-base focus:outline-none"
/>
)}
- <div
- className={`absolute bottom-2 right-3 flex items-center gap-3 text-[11px] px-2 py-1 rounded pointer-events-none ${
- readingTheme === 'light' ? 'text-gray-700 bg-[var(--wr-reading-paper)]/85' : 'text-gray-500 bg-port-bg/80'
- }`}
- >
- <span>{wordCount.toLocaleString()} words</span>
- {dirty && <span className="text-port-warning">● unsaved</span>}
- </div>
+ {viewMode !== 'review' && (
+ <div
+ className={`absolute bottom-2 right-3 flex items-center gap-3 text-[11px] px-2 py-1 rounded pointer-events-none ${
+ readingTheme === 'light' ? 'text-gray-700 bg-[var(--wr-reading-paper)]/85' : 'text-gray-500 bg-port-bg/80'
+ }`}
+ >
+ <span>{wordCount.toLocaleString()} words</span>
+ {dirty && <span className="text-port-warning">● unsaved</span>}
+ </div>
+ )}
</div>
+ {/* Review mode is a full-width synced surface — no storyboard sidebar. */}
+ {viewMode !== 'review' && (
<div
onMouseDown={onSplitMouseDown}
onDoubleClick={() => {
@@ -834,7 +859,9 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
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"
/>
+ )}
+ {viewMode !== 'review' && (
<aside
style={{ '--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 ${
@@ -869,6 +896,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
onTabChange={setSidebarTab}
/>
</aside>
+ )}
</div>
<ProseTokenPopover
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index 561614d044..4039dd12e4 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -66,6 +66,13 @@ export const attachWritersRoomSceneImage = (workId, analysisId, payload) =>
body: JSON.stringify(payload),
});
+// Synced review (Phase 4): a read-model that maps prose segments ↔ script
+// scenes ↔ generated media with provenance + stale detection. Derived on the
+// server from the active draft's segment index and the `script` analysis
+// snapshot — no separate persistence.
+export const getWritersRoomSyncedReview = (workId, options) =>
+ request(`/writers-room/works/${enc(workId)}/synced-review`, options);
+
// Characters (editable bible — separate from immutable analysis snapshots)
export const listWritersRoomCharacters = (workId) =>
request(`/writers-room/works/${enc(workId)}/characters`);
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index e609035305..954e1db4ca 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -33,6 +33,7 @@ import {
import {
runAnalysis, listAnalyses, getAnalysis, attachSceneImage,
} from '../services/writersRoom/evaluator.js';
+import { getSyncedReview } from '../services/writersRoom/syncedReview.js';
import {
listCharacters, createCharacter, updateCharacter, deleteCharacter,
} from '../services/writersRoom/characters.js';
@@ -188,6 +189,15 @@ router.get('/works/:id/analysis/:analysisId', asyncHandler(async (req, res) => {
res.json(await getAnalysis(req.params.id, req.params.analysisId));
}));
+// ---------- synced review (Phase 4: prose ↔ script ↔ media) ----------
+
+// Read-model assembled on demand from the active draft's segment index and the
+// `script` analysis snapshot (scenes + scene images). No new persistence — see
+// services/writersRoom/syncedReview.js for why this derives rather than stores.
+router.get('/works/:id/synced-review', asyncHandler(async (req, res) => {
+ res.json(await getSyncedReview(req.params.id));
+}));
+
// ---------- characters ----------
router.get('/works/:id/characters', asyncHandler(async (req, res) => {
diff --git a/server/services/writersRoom/syncedReview.js b/server/services/writersRoom/syncedReview.js
new file mode 100644
index 0000000000..41cd6253cd
--- /dev/null
+++ b/server/services/writersRoom/syncedReview.js
@@ -0,0 +1,178 @@
+/**
+ * Writers Room — Phase 4 synchronized prose/script/media review surface.
+ *
+ * This is a *read-model*: it derives the prose↔script↔media mapping from data
+ * that already exists immutably elsewhere rather than persisting a fourth copy.
+ * - prose segments ← the active draft's `segmentIndex` (built on every save)
+ * - script scenes ← the `script` analysis snapshot's `result.scenes[]`,
+ * each carrying `sourceSegmentIds` back to prose
+ * - media refs ← the same snapshot's `sceneImages` map (scene → image)
+ *
+ * Deriving on read (instead of a persisted render-plan store) means there is no
+ * second source of truth to keep in sync, and staleness falls straight out of
+ * the analysis snapshot's pinned `sourceContentHash` vs. the live draft hash —
+ * the same contentHash machinery the rest of Writers Room already uses.
+ *
+ * The mapping model from docs/features/writers-room.md ("Synchronized Review
+ * Surface") is expressed *relationally* across the three pane arrays — every
+ * prose segment lists the script scenes mapped to it; every scene lists the
+ * prose segments it adapts and the media rendered from it; every media item
+ * carries its full provenance back to scene + prose. There is intentionally no
+ * separate `mappings[]` array — that would be a redundant denormalization of
+ * exactly these cross-references.
+ */
+
+import { getWorkWithBody } from './local.js';
+import { getAnalysis } from './evaluator.js';
+import { assertValidWorkId } from './_shared.js';
+
+const SCRIPT_ANALYSIS_ID = 'script';
+
+// Pull the active draft's metadata (contentHash, segmentIndex) out of the
+// manifest. Returns a stable empty shape when there's no active draft yet so
+// callers never have to null-check the index.
+function activeDraftMeta(manifest) {
+ const activeId = manifest?.activeDraftVersionId || null;
+ const draft = (manifest?.drafts || []).find((d) => d.id === activeId) || null;
+ return {
+ draftVersionId: activeId,
+ contentHash: draft?.contentHash || null,
+ segmentIndex: Array.isArray(draft?.segmentIndex) ? draft.segmentIndex : [],
+ };
+}
+
+// One media item per rendered scene image. Provenance points back to the scene
+// it was rendered from and (transitively) the prose segments that scene adapts.
+// An image whose `sceneId` no longer matches any scene (the script was
+// re-extracted with different ids after the render) is surfaced as an orphan —
+// honest "source scene no longer in script" rather than silently dropped.
+function buildMediaItem(sceneId, img, sceneById) {
+ const scene = sceneById.get(sceneId) || null;
+ return {
+ sceneId,
+ sceneHeading: scene?.heading || null,
+ orphan: !scene,
+ kind: 'image',
+ ref: img.filename,
+ jobId: img.jobId || null,
+ prompt: img.prompt || null,
+ generatedAt: img.generatedAt || null,
+ proseSegmentIds: scene ? scene.proseSegmentIds : [],
+ };
+}
+
+/**
+ * Pure assembler — no I/O. Given the work manifest, the active draft body, and
+ * the (possibly absent / failed) `script` analysis snapshot, produce the full
+ * synced-review payload. Kept pure so the mapping logic is unit-testable
+ * without touching the filesystem.
+ */
+export function buildSyncedReview({ manifest, body = '', scriptAnalysis = null }) {
+ const { draftVersionId, contentHash, segmentIndex } = activeDraftMeta(manifest);
+ const text = String(body || '');
+
+ // Prose segments with their sliced text. Offsets come from the segment index
+ // computed at save time, so they line up with the persisted body.
+ const proseSegments = segmentIndex.map((seg) => ({
+ id: seg.id,
+ kind: seg.kind,
+ heading: seg.heading,
+ start: seg.start,
+ end: seg.end,
+ wordCount: seg.wordCount,
+ text: text.slice(seg.start, seg.end).trim(),
+ // filled in below once we know which scenes map back to each segment
+ scriptSceneIds: [],
+ media: [],
+ }));
+ const proseSegmentIds = new Set(proseSegments.map((s) => s.id));
+ const proseById = new Map(proseSegments.map((s) => [s.id, s]));
+
+ const rawScenes = Array.isArray(scriptAnalysis?.result?.scenes)
+ ? scriptAnalysis.result.scenes
+ : [];
+ const sceneImages = scriptAnalysis?.sceneImages && typeof scriptAnalysis.sceneImages === 'object'
+ ? scriptAnalysis.sceneImages
+ : {};
+
+ // Script scenes. `sourceSegmentIds` from the LLM is validated against the
+ // live prose index — hallucinated or stale segment refs are dropped so a
+ // mapping never points at a segment that isn't on screen.
+ const scenes = rawScenes.map((s) => {
+ const validProseIds = (Array.isArray(s.sourceSegmentIds) ? s.sourceSegmentIds : [])
+ .filter((id) => proseSegmentIds.has(id));
+ const img = sceneImages[s.id];
+ return {
+ id: s.id,
+ heading: s.heading || null,
+ slugline: s.slugline || null,
+ summary: s.summary || null,
+ characters: Array.isArray(s.characters) ? s.characters : [],
+ proseSegmentIds: validProseIds,
+ media: img?.filename
+ ? { kind: 'image', ref: img.filename, jobId: img.jobId || null, prompt: img.prompt || null, generatedAt: img.generatedAt || null }
+ : null,
+ };
+ });
+ const sceneById = new Map(scenes.map((s) => [s.id, s]));
+
+ // Back-fill prose → scene and prose → media from the validated scene mappings.
+ for (const scene of scenes) {
+ for (const segId of scene.proseSegmentIds) {
+ const seg = proseById.get(segId);
+ if (!seg) continue;
+ seg.scriptSceneIds.push(scene.id);
+ if (scene.media) seg.media.push({ ...scene.media, sceneId: scene.id });
+ }
+ }
+
+ // Media pane — every rendered scene image, including orphans.
+ const mediaItems = Object.entries(sceneImages)
+ .filter(([, img]) => img && img.filename)
+ .map(([sceneId, img]) => buildMediaItem(sceneId, img, sceneById))
+ .sort((a, b) => (b.generatedAt || '').localeCompare(a.generatedAt || ''));
+
+ const sceneCount = scenes.length;
+ const available = sceneCount > 0;
+ const stale = available
+ && !!scriptAnalysis?.sourceContentHash
+ && !!contentHash
+ && scriptAnalysis.sourceContentHash !== contentHash;
+
+ return {
+ workId: manifest?.id || null,
+ title: manifest?.title || null,
+ draftVersionId,
+ activeContentHash: contentHash,
+ prose: { segments: proseSegments },
+ script: {
+ available,
+ status: scriptAnalysis?.status || null,
+ stale,
+ analysisId: scriptAnalysis ? SCRIPT_ANALYSIS_ID : null,
+ providerId: scriptAnalysis?.providerId || null,
+ model: scriptAnalysis?.model || null,
+ completedAt: scriptAnalysis?.completedAt || null,
+ error: scriptAnalysis?.status === 'failed' ? (scriptAnalysis.error || 'Script analysis failed') : null,
+ title: scriptAnalysis?.result?.title || null,
+ logline: scriptAnalysis?.result?.logline || null,
+ scenes,
+ },
+ media: { items: mediaItems },
+ };
+}
+
+/**
+ * Orchestrator — load the work + active body + script analysis and assemble the
+ * synced-review read-model. A missing script analysis (never run, or a fresh
+ * work) is a normal empty state, not an error.
+ */
+export async function getSyncedReview(workId) {
+ assertValidWorkId(workId);
+ const { manifest, body } = await getWorkWithBody(workId);
+ const scriptAnalysis = await getAnalysis(workId, SCRIPT_ANALYSIS_ID).catch((err) => {
+ if (err?.code === 'NOT_FOUND') return null;
+ throw err;
+ });
+ return buildSyncedReview({ manifest, body, scriptAnalysis });
+}
diff --git a/server/services/writersRoom/syncedReview.test.js b/server/services/writersRoom/syncedReview.test.js
new file mode 100644
index 0000000000..4021b3a5f1
--- /dev/null
+++ b/server/services/writersRoom/syncedReview.test.js
@@ -0,0 +1,152 @@
+import { describe, it, expect } from 'vitest';
+import { buildSyncedReview } from './syncedReview.js';
+import { buildSegmentIndex } from './local.js';
+
+// Realistic body so segment offsets line up with the sliced text the UI shows.
+const BODY = '# Opening\nThe hero wakes at dawn.\n\n# Battle\nSwords clash loudly.';
+const SEGMENTS = buildSegmentIndex(BODY); // → seg-001 (Opening), seg-002 (Battle)
+
+function makeManifest({ contentHash = 'hash-current' } = {}) {
+ return {
+ id: 'wr-work-abc',
+ title: 'Test Work',
+ activeDraftVersionId: 'wr-draft-1',
+ drafts: [{ id: 'wr-draft-1', contentHash, segmentIndex: SEGMENTS }],
+ };
+}
+
+function makeScriptAnalysis(overrides = {}) {
+ return {
+ id: 'script',
+ status: 'succeeded',
+ draftVersionId: 'wr-draft-1',
+ sourceContentHash: 'hash-current',
+ providerId: 'openai',
+ model: 'gpt-x',
+ completedAt: '2026-01-01T00:00:00Z',
+ result: {
+ title: 'The Tale',
+ logline: 'A hero rises.',
+ scenes: [
+ { id: 'scene-01', heading: 'Opening', summary: 'wakes', sourceSegmentIds: ['seg-001'], characters: ['Hero'] },
+ // seg-999 is a hallucinated/stale ref that must be dropped
+ { id: 'scene-02', heading: 'Battle', summary: 'fight', sourceSegmentIds: ['seg-002', 'seg-999'], characters: [] },
+ ],
+ },
+ sceneImages: {
+ 'scene-01': { filename: 'scene-01.png', jobId: 'job-1', prompt: 'a hero at dawn', generatedAt: '2026-01-02T00:00:00Z' },
+ // image whose scene id no longer matches any scene → orphan
+ 'scene-orphan': { filename: 'orphan.png', jobId: 'job-2', prompt: 'ghost', generatedAt: '2026-01-03T00:00:00Z' },
+ },
+ ...overrides,
+ };
+}
+
+describe('buildSyncedReview — prose pane', () => {
+ it('derives prose segments with sliced body text', () => {
+ const out = buildSyncedReview({ manifest: makeManifest(), body: BODY, scriptAnalysis: null });
+ expect(out.prose.segments).toHaveLength(2);
+ const [opening, battle] = out.prose.segments;
+ expect(opening.id).toBe('seg-001');
+ expect(opening.heading).toBe('Opening');
+ expect(opening.text).toContain('hero wakes at dawn');
+ expect(battle.text).toContain('Swords clash loudly');
+ });
+
+ it('returns empty prose when there is no active draft', () => {
+ const manifest = { id: 'wr-work-x', title: 'Empty', activeDraftVersionId: null, drafts: [] };
+ const out = buildSyncedReview({ manifest, body: '', scriptAnalysis: null });
+ expect(out.prose.segments).toEqual([]);
+ expect(out.draftVersionId).toBeNull();
+ expect(out.script.available).toBe(false);
+ });
+});
+
+describe('buildSyncedReview — script pane & mappings', () => {
+ it('maps scenes to prose and back-fills prose → scene', () => {
+ const out = buildSyncedReview({ manifest: makeManifest(), body: BODY, scriptAnalysis: makeScriptAnalysis() });
+ expect(out.script.available).toBe(true);
+ expect(out.script.title).toBe('The Tale');
+ const [opening, battle] = out.prose.segments;
+ expect(opening.scriptSceneIds).toEqual(['scene-01']);
+ expect(battle.scriptSceneIds).toEqual(['scene-02']);
+ // and the scene → prose direction
+ expect(out.script.scenes[0].proseSegmentIds).toEqual(['seg-001']);
+ });
+
+ it('drops hallucinated/stale sourceSegmentIds that no longer exist in prose', () => {
+ const out = buildSyncedReview({ manifest: makeManifest(), body: BODY, scriptAnalysis: makeScriptAnalysis() });
+ const battleScene = out.script.scenes.find((s) => s.id === 'scene-02');
+ // the LLM referenced seg-002 (valid) + seg-999 (gone); only the valid one
+ // survives into the mapping the UI renders
+ expect(battleScene.proseSegmentIds).toEqual(['seg-002']);
+ });
+
+ it('flags stale when the analysis hash no longer matches the active draft', () => {
+ const fresh = buildSyncedReview({ manifest: makeManifest(), body: BODY, scriptAnalysis: makeScriptAnalysis() });
+ expect(fresh.script.stale).toBe(false);
+ const drifted = buildSyncedReview({
+ manifest: makeManifest({ contentHash: 'hash-new' }),
+ body: BODY,
+ scriptAnalysis: makeScriptAnalysis(),
+ });
+ expect(drifted.script.stale).toBe(true);
+ });
+
+ it('treats a missing script analysis as a normal empty state', () => {
+ const out = buildSyncedReview({ manifest: makeManifest(), body: BODY, scriptAnalysis: null });
+ expect(out.script.available).toBe(false);
+ expect(out.script.scenes).toEqual([]);
+ expect(out.media.items).toEqual([]);
+ expect(out.prose.segments[0].scriptSceneIds).toEqual([]);
+ });
+
+ it('surfaces a failed analysis error and reports no scenes', () => {
+ const out = buildSyncedReview({
+ manifest: makeManifest(),
+ body: BODY,
+ scriptAnalysis: { id: 'script', status: 'failed', error: 'boom', result: null },
+ });
+ expect(out.script.available).toBe(false);
+ expect(out.script.status).toBe('failed');
+ expect(out.script.error).toBe('boom');
+ });
+});
+
+describe('buildSyncedReview — media pane & provenance', () => {
+ it('attaches scene images to scene + prose and builds the media pane newest-first', () => {
+ const out = buildSyncedReview({ manifest: makeManifest(), body: BODY, scriptAnalysis: makeScriptAnalysis() });
+ // scene → media
+ const openingScene = out.script.scenes.find((s) => s.id === 'scene-01');
+ expect(openingScene.media).toMatchObject({ kind: 'image', ref: 'scene-01.png', jobId: 'job-1' });
+ // prose → media (back-filled with the source scene id)
+ expect(out.prose.segments[0].media).toEqual([
+ { kind: 'image', ref: 'scene-01.png', jobId: 'job-1', prompt: 'a hero at dawn', generatedAt: '2026-01-02T00:00:00Z', sceneId: 'scene-01' },
+ ]);
+ // media pane: two items, newest (orphan, Jan 3) first
+ expect(out.media.items).toHaveLength(2);
+ expect(out.media.items[0].ref).toBe('orphan.png');
+ expect(out.media.items[1].ref).toBe('scene-01.png');
+ });
+
+ it('marks an image whose scene no longer exists as an orphan with no prose mapping', () => {
+ const out = buildSyncedReview({ manifest: makeManifest(), body: BODY, scriptAnalysis: makeScriptAnalysis() });
+ const orphan = out.media.items.find((m) => m.ref === 'orphan.png');
+ expect(orphan.orphan).toBe(true);
+ expect(orphan.sceneHeading).toBeNull();
+ expect(orphan.proseSegmentIds).toEqual([]);
+ const mapped = out.media.items.find((m) => m.ref === 'scene-01.png');
+ expect(mapped.orphan).toBe(false);
+ expect(mapped.sceneHeading).toBe('Opening');
+ expect(mapped.proseSegmentIds).toEqual(['seg-001']);
+ });
+
+ it('ignores scene-image entries with no filename', () => {
+ const analysis = makeScriptAnalysis({
+ sceneImages: { 'scene-01': { filename: '', jobId: 'job-x' } },
+ });
+ const out = buildSyncedReview({ manifest: makeManifest(), body: BODY, scriptAnalysis: analysis });
+ expect(out.media.items).toEqual([]);
+ expect(out.script.scenes[0].media).toBeNull();
+ });
+});