Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(writers-room): Phase 1 + new Create sidebar group (#192)
[._.]/ Adam Eivycf7951633b15
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 81139e8736..1b5f4f3901 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **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).- **Friendly typed errors for HuggingFace failures.** Top-level exception handler in `flux2_macos.py` walks the exception cause chain (diffusers wraps HF errors in `OSError`) to detect `GatedRepoError` / `HfHubHTTPError(401)` / `RepositoryNotFoundError`, then emits a structured `USER_ERROR:<kind>:<repo>` line plus a friendly `❌ <prose>` line — including a `_repo_from_hf_error()` URL parser that reconstructs `owner/name` from the failing request URL because `huggingface_hub` doesn't always populate `error.repo_id`. `local.js` parses the `USER_ERROR:` line out of the stderr buffer (single `findIndex` pass — no nested `indexOf` O(n²)) and propagates `kind` + `repo` through both the per-job SSE error event and the `imageGenEvents.emit('failed', ...)` payload, so the queue's downstream broadcast inherits the friendly message instead of "Exit code 1". The Image Gen page renders a typed error card with an `ERROR_HEADINGS` lookup ("Model access required" / "HuggingFace token rejected" / "Model repo not found") and a one-click "Request access to <repo> ↗" button that deep-links to the HF page — replacing the previous behavior where a 9B gated-access failure surfaced as bare "Exit code 1" with a wall of Python tracebacks in `pm2 logs`.diff --git a/PLAN.md b/PLAN.mdindex 1c6ae90d30..737763dfde 100644--- a/PLAN.md+++ b/PLAN.md@@ -26,6 +26,7 @@ The PR landed with full pipeline mechanics + auto-recovery + smoke-test fixture,### Other backlog+- [ ] **Writers Room (Phase 2+)** — Phase 1 ships the authoring core (folders/works/drafts, "write for 10" exercise, version snapshots) under a new top-level `Create` sidebar group alongside Media Gen. Phases 2-5 cover manual AI analysis, Creative Director handoff, synced prose/script/media review, and realtime CD feedback. See [writers-room.md](./docs/features/writers-room.md).- [ ] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (Google Calendar via existing MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (needs API choice — OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js` scheduled actions).- [ ] **Voice agent vision fallback** — `ui_describe_visually` tool: screenshot the current tab (or a named canvas/chart) and send to a vision-capable model so "what's on this chart?" works on non-DOM content (CyberCity, graph views). Depends on a vision provider in `portos-ai-toolkit`.- [ ] **Voice agent — explicit long-term memory routing** — On "remember that …", auto-route to `brain_capture` and inject top-N relevant memories into the voice turn's system prompt via `brain_search`. Some of this is ambient today; make it explicit and self-improving.diff --git a/client/src/App.jsx b/client/src/App.jsxindex d641f21548..87d241cc1b 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -81,6 +81,7 @@ const Loops = lazyWithReload(() => import('./pages/Loops'));const CharacterSheet = lazyWithReload(() => import('./pages/CharacterSheet'));const Wiki = lazyWithReload(() => import('./pages/Wiki'));const RapidReaderPage = lazyWithReload(() => import('./pages/RapidReader'));+const WritersRoom = lazyWithReload(() => import('./pages/WritersRoom'));// Loading fallback for lazy-loaded pagesconst PageLoader = () => (@@ -209,6 +210,8 @@ export default function App() {<Route path="wiki" element={<Navigate to="/wiki/overview" replace />} /><Route path="wiki/:tab" element={<Wiki />} /><Route path="rapid-reader" element={<RapidReaderPage />} />+ <Route path="writers-room" element={<WritersRoom />} />+ <Route path="writers-room/works/:workId" element={<WritersRoom />} /><Route path="agents" element={<Agents />} /><Route path="agents/:agentId" element={<Agents />} /><Route path="agents/:agentId/:tab" element={<Agents />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex af408b1753..81783f845d 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -101,7 +101,6 @@ const navItems = [label: 'AI',icon: Bot,children: [- { to: '/media', label: 'Media Gen', icon: Layers },{ to: '/prompts', label: 'Prompts', icon: FileText },{ to: '/ai', label: 'Providers', icon: Bot }]@@ -172,6 +171,15 @@ const navItems = [{ to: '/messages/sync', label: 'Sync', icon: RefreshCw }]},+ {+ label: 'Create',+ icon: Sparkles,+ defaultTo: '/media',+ children: [+ { to: '/media', label: 'Media Gen', icon: Layers },+ { to: '/writers-room', label: 'Writers Room', icon: NotebookPen }+ ]+ },{label: 'Dev Tools',icon: Terminal,diff --git a/client/src/components/writers-room/ExercisePanel.jsx b/client/src/components/writers-room/ExercisePanel.jsxnew file mode 100644index 0000000000..640bfadbc8--- /dev/null+++ b/client/src/components/writers-room/ExercisePanel.jsx@@ -0,0 +1,223 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { Timer, Play, StopCircle, X } from 'lucide-react';+import toast from '../ui/Toast';+import {+ listWritersRoomExercises,+ createWritersRoomExercise,+ finishWritersRoomExercise,+ discardWritersRoomExercise,+} from '../../services/apiWritersRoom';+import { countWords, formatCountdown } from '../../utils/formatters';++const DURATION_PRESETS = [+ { label: '5 min', seconds: 300 },+ { label: '10 min', seconds: 600 },+ { label: '15 min', seconds: 900 },+ { label: '25 min', seconds: 1500 },+];++export default function ExercisePanel({ activeWork, onClose }) {+ const [history, setHistory] = useState([]);+ const [duration, setDuration] = useState(600);+ const [prompt, setPrompt] = useState('');+ const [active, setActive] = useState(null); // { id, startedAt, durationSeconds, startingWords }+ const [now, setNow] = useState(Date.now());+ const [text, setText] = useState('');+ const tickRef = useRef(null);++ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);++ const refresh = useCallback(async () => {+ // Capture the workId we asked for so a slow response from the previous+ // work can't overwrite the just-loaded history when the user switches+ // works rapidly.+ const requestedFor = activeWork?.id ?? null;+ const all = await listWritersRoomExercises(requestedFor).catch(() => []);+ if (!mountedRef.current) return;+ if (requestedFor !== (activeWork?.id ?? null)) return; // stale response+ setHistory(all);+ }, [activeWork?.id]);++ useEffect(() => { refresh(); }, [refresh]);++ // 1Hz tick while a session is running+ useEffect(() => {+ if (!active) return;+ tickRef.current = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(tickRef.current);+ }, [active]);++ const elapsed = active ? Math.floor((now - new Date(active.startedAt).getTime()) / 1000) : 0;+ const remaining = active ? active.durationSeconds - elapsed : duration;+ const wordsAdded = useMemo(() => countWords(text), [text]);+ const expired = active && remaining <= 0;++ const start = async () => {+ // Word count lives on the active draft metadata, not the work root, so+ // walk drafts → activeDraftVersionId before falling back to a top-level+ // wordCount (which only the listWorks summary exposes).+ const activeDraft = activeWork?.drafts?.find((d) => d.id === activeWork?.activeDraftVersionId);+ const startingWords = activeDraft?.wordCount ?? activeWork?.wordCount ?? 0;+ const session = await createWritersRoomExercise({+ workId: activeWork?.id ?? null,+ prompt: prompt.trim(),+ durationSeconds: duration,+ startingWords,+ }).catch((err) => {+ toast.error(`Failed to start: ${err.message}`);+ return null;+ });+ if (!session) return;+ setActive(session);+ setText('');+ setNow(Date.now());+ };++ const finishSession = async ({ keep } = { keep: true }) => {+ if (!active) return;+ // Only clear local state + toast success after the server confirms; on+ // failure we keep the session active so the user can retry instead of+ // staring at a "logged 0 words" UI that's drifted from the server.+ if (keep) {+ const startingWords = active.startingWords || 0;+ const result = await finishWritersRoomExercise(active.id, {+ endingWords: startingWords + wordsAdded,+ appendedText: text || null,+ }).catch((err) => {+ toast.error(`Finish failed: ${err.message}`);+ return null;+ });+ if (!result) return;+ toast.success(`Logged ${wordsAdded} words`);+ } else {+ const result = await discardWritersRoomExercise(active.id).catch((err) => {+ toast.error(`Discard failed: ${err.message}`);+ return null;+ });+ if (!result) return;+ }+ setActive(null);+ setText('');+ await refresh();+ };++ // Toast once when the timer crosses into expired. The ref guards against+ // multiple fires if `expired` stays true across re-renders.+ const expiredToastedRef = useRef(false);+ useEffect(() => {+ if (!expired) {+ expiredToastedRef.current = false;+ return;+ }+ if (expiredToastedRef.current) return;+ expiredToastedRef.current = true;+ toast('Timer up — finish or keep going', { icon: '⏰' });+ }, [expired]);++ return (+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden flex flex-col h-full">+ <div className="flex items-center gap-2 px-3 py-2 border-b border-port-border bg-port-bg/40">+ <Timer size={14} className="text-port-accent" />+ <h3 className="text-sm font-semibold text-white flex-1">Write for {Math.round(duration / 60)}</h3>+ <button onClick={onClose} className="text-gray-500 hover:text-white" aria-label="Close exercise">+ <X size={14} />+ </button>+ </div>++ {!active && (+ <div className="px-3 py-3 space-y-3">+ <div>+ <label className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">Duration</label>+ <div className="flex flex-wrap gap-1">+ {DURATION_PRESETS.map(({ label, seconds }) => (+ <button+ key={seconds}+ onClick={() => setDuration(seconds)}+ className={`px-2 py-1 text-xs rounded ${duration === seconds ? 'bg-port-accent text-white' : 'bg-port-bg border border-port-border text-gray-300'}`}+ >+ {label}+ </button>+ ))}+ </div>+ </div>++ <div>+ <label className="block text-[10px] uppercase tracking-wider text-gray-500 mb-1">+ Prompt {activeWork && <span className="text-gray-600">(or leave blank to free-write {activeWork.title})</span>}+ </label>+ <textarea+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ placeholder="What should this session focus on?"+ rows={2}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs"+ />+ </div>++ <button+ onClick={start}+ className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-port-accent text-white text-sm font-medium rounded hover:bg-port-accent/80"+ >+ <Play size={14} /> Start+ </button>+ </div>+ )}++ {active && (+ <div className="flex-1 flex flex-col min-h-0">+ <div className="px-3 py-2 border-b border-port-border bg-port-bg/40 flex items-center gap-3">+ <div className={`text-2xl font-mono ${expired ? 'text-port-error' : 'text-white'}`}>+ {formatCountdown(remaining)}+ </div>+ <div className="flex-1 text-xs text-gray-400">+ <div>{wordsAdded} words this session</div>+ {prompt && <div className="text-gray-500 italic truncate">{prompt}</div>}+ </div>+ <button onClick={() => finishSession({ keep: true })}+ className="flex items-center gap-1 px-2 py-1 bg-port-success/20 text-port-success text-xs rounded hover:bg-port-success/30"+ title="Save this session"+ >+ <StopCircle size={12} /> Finish+ </button>+ <button onClick={() => finishSession({ keep: false })}+ className="flex items-center gap-1 px-2 py-1 text-gray-500 text-xs rounded hover:text-port-error"+ title="Discard"+ >+ <X size={12} />+ </button>+ </div>+ <textarea+ autoFocus+ value={text}+ onChange={(e) => setText(e.target.value)}+ placeholder="Just write…"+ className="flex-1 resize-none bg-port-bg text-gray-100 px-3 py-2 text-sm focus:outline-none"+ spellCheck+ />+ </div>+ )}++ <div className="border-t border-port-border bg-port-bg/40 px-3 py-2 max-h-40 overflow-y-auto">+ <h4 className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Recent sessions</h4>+ {history.length === 0 && <p className="text-[11px] text-gray-600">No sessions yet</p>}+ <ul className="space-y-1">+ {history.slice(0, 8).map((ex) => (+ <li key={ex.id} className="text-[11px] flex items-center gap-2">+ <span className={`w-1.5 h-1.5 rounded-full ${+ ex.status === 'finished' ? 'bg-port-success' :+ ex.status === 'discarded' ? 'bg-gray-500' :+ 'bg-port-warning animate-pulse'+ }`} />+ <span className="text-gray-300">+ {ex.status === 'finished' ? `${ex.wordsAdded ?? 0} words` : ex.status}+ </span>+ <span className="text-gray-600 truncate flex-1">{ex.prompt || '(free-write)'}</span>+ <span className="text-gray-600">{Math.round((ex.durationSeconds || 0) / 60)}m</span>+ </li>+ ))}+ </ul>+ </div>+ </div>+ );+}diff --git a/client/src/components/writers-room/LibraryPane.jsx b/client/src/components/writers-room/LibraryPane.jsxnew file mode 100644index 0000000000..1e0dd4b94b--- /dev/null+++ b/client/src/components/writers-room/LibraryPane.jsx@@ -0,0 +1,260 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { Folder, FolderPlus, FilePlus, FileText, ChevronDown, ChevronRight, Trash2 } from 'lucide-react';+import toast from '../ui/Toast';+import {+ createWritersRoomFolder,+ deleteWritersRoomFolder,+ createWritersRoomWork,+ deleteWritersRoomWork,+} from '../../services/apiWritersRoom';+import { KIND_LABELS } from './labels';++export default function LibraryPane({ folders, works, activeWorkId, onSelectWork, onRefresh }) {+ const [openFolders, setOpenFolders] = useState({});+ const [creatingFolder, setCreatingFolder] = useState(false);+ const [folderName, setFolderName] = useState('');+ const [creatingWork, setCreatingWork] = useState(null); // folderId or 'unfiled'+ const [workTitle, setWorkTitle] = useState('');+ const [workKind, setWorkKind] = useState('short-story');+ // Two-click confirm: first click arms the button, second deletes.+ // Cleared automatically after 4s to avoid leaving a pending arm.+ const [armedDelete, setArmedDelete] = useState(null);+ const armTimerRef = useRef(null);+ useEffect(() => () => clearTimeout(armTimerRef.current), []);++ const grouped = useMemo(() => {+ const byFolder = new Map();+ byFolder.set(null, []);+ folders.forEach((f) => byFolder.set(f.id, []));+ works.forEach((w) => {+ const key = w.folderId && byFolder.has(w.folderId) ? w.folderId : null;+ byFolder.get(key).push(w);+ });+ for (const arr of byFolder.values()) {+ arr.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));+ }+ return byFolder;+ }, [folders, works]);++ const toggleFolder = (id) => setOpenFolders((s) => ({ ...s, [id]: !s[id] }));++ const submitFolder = async (e) => {+ e.preventDefault();+ if (!folderName.trim()) return;+ const folder = await createWritersRoomFolder({ name: folderName.trim() }).catch((err) => {+ toast.error(`Failed to create folder: ${err.message}`);+ return null;+ });+ if (!folder) return;+ setFolderName('');+ setCreatingFolder(false);+ setOpenFolders((s) => ({ ...s, [folder.id]: true }));+ onRefresh?.();+ };++ const submitWork = async (e) => {+ e.preventDefault();+ if (!workTitle.trim()) return;+ const folderId = creatingWork === 'unfiled' ? null : creatingWork;+ const work = await createWritersRoomWork({ title: workTitle.trim(), kind: workKind, folderId }).catch((err) => {+ toast.error(`Failed to create work: ${err.message}`);+ return null;+ });+ if (!work) return;+ setWorkTitle('');+ setWorkKind('short-story');+ setCreatingWork(null);+ onRefresh?.();+ onSelectWork?.(work.id);+ };++ const armDelete = (key) => {+ setArmedDelete(key);+ clearTimeout(armTimerRef.current);+ armTimerRef.current = setTimeout(+ () => setArmedDelete((current) => (current === key ? null : current)),+ 4000,+ );+ };++ const handleDeleteFolder = async (id, name) => {+ if (armedDelete !== `folder:${id}`) {+ armDelete(`folder:${id}`);+ toast(`Click again to delete folder "${name}"`);+ return;+ }+ setArmedDelete(null);+ await deleteWritersRoomFolder(id).catch((err) => toast.error(`Delete failed: ${err.message}`));+ onRefresh?.();+ };++ const handleDeleteWork = async (id, title) => {+ if (armedDelete !== `work:${id}`) {+ armDelete(`work:${id}`);+ toast(`Click again to delete "${title}"`);+ return;+ }+ setArmedDelete(null);+ await deleteWritersRoomWork(id).catch((err) => toast.error(`Delete failed: ${err.message}`));+ if (activeWorkId === id) onSelectWork?.(null);+ 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>+ );+ };++ return (+ <div className="space-y-4 text-sm">+ <div className="flex items-center justify-between">+ <h2 className="text-xs uppercase text-gray-400 tracking-wider">Library</h2>+ <div className="flex items-center gap-1">+ <button+ onClick={() => { setCreatingFolder(true); setCreatingWork(null); }}+ className="p-1 text-gray-400 hover:text-port-accent"+ title="New folder"+ aria-label="New folder"+ >+ <FolderPlus size={14} />+ </button>+ <button+ onClick={() => { setCreatingWork('unfiled'); setCreatingFolder(false); }}+ className="p-1 text-gray-400 hover:text-port-accent"+ title="New work"+ aria-label="New work"+ >+ <FilePlus size={14} />+ </button>+ </div>+ </div>++ {creatingFolder && (+ <form onSubmit={submitFolder} className="flex items-center gap-1">+ <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"+ />+ <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>+ </form>+ )}++ {creatingWork && (+ <form onSubmit={submitWork} className="space-y-1 bg-port-card border border-port-border rounded p-2">+ <input+ autoFocus+ value={workTitle}+ onChange={(e) => setWorkTitle(e.target.value)}+ placeholder="Title"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs"+ />+ <select+ value={workKind}+ onChange={(e) => setWorkKind(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs"+ >+ {Object.entries(KIND_LABELS).map(([k, l]) => <option key={k} value={k}>{l}</option>)}+ </select>+ <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">Create</button>+ <button type="button" onClick={() => setCreatingWork(null)} className="text-xs px-2 py-1 text-gray-400">Cancel</button>+ </div>+ </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>+ )}++ {/* 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>+ )}++ {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>+ </div>+ );+}diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxnew file mode 100644index 0000000000..17a57dfc0c--- /dev/null+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -0,0 +1,258 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { Save, GitCommit, Clock, FileText } from 'lucide-react';+import toast from '../ui/Toast';+import {+ saveWritersRoomDraft,+ snapshotWritersRoomDraft,+ setWritersRoomActiveDraft,+ updateWritersRoomWork,+} from '../../services/apiWritersRoom';+import { KIND_LABELS, STATUS_LABELS } from './labels';+import { countWords } from '../../utils/formatters';++export default function WorkEditor({ work, onChange }) {+ const [body, setBody] = useState(work.activeDraftBody || '');+ const [title, setTitle] = useState(work.title);+ // Optimistic mirror of work.status — the dropdown reads this so a status+ // change shows immediately, even before the PATCH round-trip resolves and+ // the parent re-renders with the new prop. Synced from the prop whenever+ // the prop changes (both work-id swap AND any time the parent updates).+ const [status, setStatus] = useState(work.status);+ const [savedBody, setSavedBody] = useState(work.activeDraftBody || '');+ const [saving, setSaving] = useState(false);+ const textareaRef = useRef(null);++ // Rehydrate body/title when the parent swaps the active work OR switches to+ // a different draft version of the same work. Both can change without the+ // work id changing (version-switch keeps work.id, swaps activeDraftVersionId).+ const prevKey = useRef({ id: work.id, draftId: work.activeDraftVersionId });+ useEffect(() => {+ const key = { id: work.id, draftId: work.activeDraftVersionId };+ if (prevKey.current.id === key.id && prevKey.current.draftId === key.draftId) return;+ prevKey.current = key;+ setBody(work.activeDraftBody || '');+ setSavedBody(work.activeDraftBody || '');+ setTitle(work.title);+ }, [work.id, work.activeDraftVersionId, work.activeDraftBody, work.title]);++ // Keep the optimistic status + title in sync with the source of truth —+ // separate from the rehydration effect so a PATCH that comes back via the+ // parent's onChange still updates the input even if no other field moved.+ // The "is the user actively editing" guard isn't needed for status (single+ // click) but title commits on blur, so the user can never be mid-edit when+ // a title prop change arrives.+ useEffect(() => { setStatus(work.status); }, [work.status]);+ useEffect(() => { setTitle(work.title); }, [work.title]);++ const dirty = body !== savedBody;+ const wordCount = useMemo(() => countWords(body), [body]);++ // Skip post-await setState if the editor unmounted (rapid work-switch or+ // page nav while a save / snapshot / status PATCH is in flight).+ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);++ // Refs let the once-bound keydown listener read the freshest body/saving+ // values without re-registering on every keystroke. The savingRef gate is+ // synchronous (unlike the `saving` state which only updates after React+ // re-renders), so rapid Cmd+S key-repeats can't slip past the guard and+ // queue overlapping save requests.+ const savingRef = useRef(false);+ const handleSaveRef = useRef(null);+ handleSaveRef.current = async () => {+ if (savingRef.current) return;+ savingRef.current = true;+ setSaving(true);+ const updated = await saveWritersRoomDraft(work.id, body).catch((err) => {+ if (mountedRef.current) toast.error(`Save failed: ${err.message}`);+ return null;+ });+ savingRef.current = false;+ if (!mountedRef.current) return;+ setSaving(false);+ if (!updated) return;+ setSavedBody(body);+ onChange?.(updated);+ toast.success('Saved');+ };+ const handleSave = () => handleSaveRef.current?.();++ useEffect(() => {+ const onKey = (e) => {+ const isSave = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's';+ if (!isSave) return;+ e.preventDefault();+ handleSaveRef.current?.();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, []);++ const handleSnapshot = async () => {+ if (dirty) {+ toast('Save before snapshotting', { icon: '⚠️' });+ return;+ }+ const updated = await snapshotWritersRoomDraft(work.id).catch((err) => {+ if (mountedRef.current) toast.error(`Snapshot failed: ${err.message}`);+ return null;+ });+ if (!updated || !mountedRef.current) return;+ onChange?.({ ...updated, activeDraftBody: body });+ toast.success(`Created ${updated.drafts[updated.drafts.length - 1].label}`);+ };++ const commitTitle = async () => {+ if (title === work.title) return;+ const updated = await updateWritersRoomWork(work.id, { title }).catch((err) => {+ if (mountedRef.current) toast.error(`Title save failed: ${err.message}`);+ return null;+ });+ if (!updated || !mountedRef.current) return;+ // Adopt the server-normalized title (e.g. trim() applied by the Zod+ // schema) — otherwise `title !== work.title` stays true on every blur+ // and the next focus-out re-PATCHes with the same un-normalized value.+ if (updated.title !== title) setTitle(updated.title);+ onChange?.({ ...updated, activeDraftBody: body });+ };++ const commitStatus = async (next) => {+ if (next === status) return;+ setStatus(next); // optimistic — survives a re-render before the PATCH resolves+ const updated = await updateWritersRoomWork(work.id, { status: next }).catch((err) => {+ if (mountedRef.current) {+ toast.error(`Status save failed: ${err.message}`);+ setStatus(work.status); // roll back on failure+ }+ return null;+ });+ if (updated && mountedRef.current) onChange?.({ ...updated, activeDraftBody: body });+ };++ const switchToDraft = async (draftId) => {+ if (draftId === work.activeDraftVersionId) return;+ if (dirty) {+ // Switching versions while the editor has unsaved edits would discard+ // them when the rehydration effect replaces `body` with the server+ // version. Block the switch and ask the user to settle the buffer.+ toast('Save or snapshot before switching versions', { icon: '⚠️' });+ return;+ }+ const updated = await setWritersRoomActiveDraft(work.id, draftId).catch((err) => {+ if (mountedRef.current) toast.error(`Switch failed: ${err.message}`);+ return null;+ });+ if (!updated || !mountedRef.current) return;+ // Reload via parent so body comes from the server's active version+ onChange?.(updated, { reload: true });+ };++ const activeDraft = useMemo(+ () => work.drafts?.find((d) => d.id === work.activeDraftVersionId),+ [work.drafts, work.activeDraftVersionId]+ );++ return (+ <div className="flex flex-col h-full">+ <div className="flex flex-wrap items-center gap-2 px-4 py-3 border-b border-port-border bg-port-card">+ <input+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ onBlur={commitTitle}+ onKeyDown={(e) => { if (e.key === 'Enter') e.target.blur(); }}+ className="bg-transparent text-lg font-bold text-white border-none focus:outline-none focus:bg-port-bg/50 px-1 rounded flex-1 min-w-[200px]"+ aria-label="Work title"+ />+ <select+ value={status}+ onChange={(e) => commitStatus(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-300"+ aria-label="Status"+ >+ {Object.entries(STATUS_LABELS).map(([k, l]) => <option key={k} value={k}>{l}</option>)}+ </select>+ <span className="text-xs text-gray-500 px-2 py-1 bg-port-bg/50 rounded">{KIND_LABELS[work.kind]}</span>+ <button+ onClick={handleSave}+ disabled={!dirty || saving}+ className={`flex items-center gap-1 px-3 py-1 text-xs rounded ${+ dirty && !saving ? 'bg-port-accent text-white hover:bg-port-accent/80' : 'bg-port-bg text-gray-500'+ }`}+ title={dirty ? 'Save (Ctrl/Cmd+S)' : 'Up to date'}+ >+ <Save size={12} /> {saving ? 'Saving…' : dirty ? 'Save' : 'Saved'}+ </button>+ <button+ onClick={handleSnapshot}+ disabled={dirty}+ className="flex items-center gap-1 px-3 py-1 text-xs rounded bg-port-bg border border-port-border text-gray-300 hover:text-white disabled:text-gray-600 disabled:cursor-not-allowed"+ title="Snapshot the active draft as a new version"+ >+ <GitCommit size={12} /> Snapshot+ </button>+ </div>++ <div className="flex-1 grid grid-cols-1 lg:grid-cols-[1fr_240px] min-h-0">+ <div className="relative min-h-0">+ <textarea+ ref={textareaRef}+ value={body}+ onChange={(e) => setBody(e.target.value)}+ placeholder="Start writing… Use # Chapter, ## Scene, ### Beat headings to outline."+ className="w-full h-full resize-none bg-port-bg text-gray-100 px-6 py-6 font-serif text-base leading-relaxed focus:outline-none"+ spellCheck+ />+ <div className="absolute bottom-2 right-3 flex items-center gap-3 text-[11px] text-gray-500 bg-port-bg/80 px-2 py-1 rounded">+ <span>{wordCount.toLocaleString()} words</span>+ {dirty && <span className="text-port-warning">● unsaved</span>}+ </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>+ </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>+ </li>+ );+ })}+ </ul>+ </div>+ </aside>+ </div>+ </div>+ );+}diff --git a/client/src/components/writers-room/labels.js b/client/src/components/writers-room/labels.jsnew file mode 100644index 0000000000..bf43a77b6c--- /dev/null+++ b/client/src/components/writers-room/labels.js@@ -0,0 +1,22 @@+// Display labels for Writers Room enums. Keys mirror the canonical enum+// values in server/lib/writersRoomPresets.js — keep in sync when adding kinds+// or statuses there.++export const KIND_LABELS = {+ novel: 'Novel',+ 'short-story': 'Short Story',+ screenplay: 'Screenplay',+ essay: 'Essay',+ treatment: 'Treatment',+ other: 'Other',+};++export const STATUS_LABELS = {+ idea: 'Idea',+ drafting: 'Drafting',+ revision: 'Revision',+ adaptation: 'Adaptation',+ rendering: 'Rendering',+ complete: 'Complete',+ archived: 'Archived',+};diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsxnew file mode 100644index 0000000000..55ed828100--- /dev/null+++ b/client/src/pages/WritersRoom.jsx@@ -0,0 +1,158 @@+import { useEffect, useState, useCallback, useRef } from 'react';+import { useParams, useNavigate } from 'react-router-dom';+import { NotebookPen, Timer } from 'lucide-react';+import LibraryPane from '../components/writers-room/LibraryPane';+import WorkEditor from '../components/writers-room/WorkEditor';+import ExercisePanel from '../components/writers-room/ExercisePanel';+import toast from '../components/ui/Toast';+import {+ listWritersRoomFolders,+ listWritersRoomWorks,+ getWritersRoomWork,+} from '../services/apiWritersRoom';++export default function WritersRoom() {+ const { workId } = useParams();+ const navigate = useNavigate();+ const [folders, setFolders] = useState([]);+ const [works, setWorks] = useState([]);+ const [activeWork, setActiveWork] = useState(null);+ const [loadingWork, setLoadingWork] = useState(false);+ const [showExercise, setShowExercise] = useState(false);++ // Skip setState when an in-flight library or work fetch resolves after the+ // page unmounts (rapid nav across pages).+ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);++ const refreshLibrary = useCallback(async () => {+ const [foldersList, worksList] = await Promise.all([+ listWritersRoomFolders().catch(() => []),+ listWritersRoomWorks().catch(() => []),+ ]);+ if (!mountedRef.current) return;+ setFolders(foldersList);+ setWorks(worksList);+ }, []);++ useEffect(() => { refreshLibrary(); }, [refreshLibrary]);++ // Load the active work when the URL changes+ useEffect(() => {+ if (!workId) {+ setActiveWork(null);+ return;+ }+ let cancelled = false;+ setLoadingWork(true);+ getWritersRoomWork(workId)+ .then((work) => { if (!cancelled) setActiveWork(work); })+ .catch(() => { if (!cancelled) setActiveWork(null); })+ .finally(() => { if (!cancelled) setLoadingWork(false); });+ return () => { cancelled = true; };+ }, [workId]);++ const selectWork = (id) => {+ if (!id) {+ navigate('/writers-room');+ return;+ }+ navigate(`/writers-room/works/${id}`);+ };++ const handleWorkChange = async (updated, opts = {}) => {+ let next = updated;+ if (opts.reload) {+ const fresh = await getWritersRoomWork(updated.id).catch(() => null);+ if (!mountedRef.current) return;+ if (!fresh) {+ // Reload failed — `updated` came from setWritersRoomActiveDraft and+ // lacks activeDraftBody, so setActiveWork(updated) would blank the+ // editor. Skip the swap; the previous activeWork (and its body) stay+ // visible and the user can retry the version-switch click.+ toast.error('Could not load that draft version');+ return;+ }+ next = fresh;+ }+ setActiveWork(next);+ // Splice the updated row into the library list (title / status / word+ // count) without refetching N manifests on every save.+ setWorks((prev) => {+ const activeDraft = (next.drafts || []).find((d) => d.id === next.activeDraftVersionId);+ const summary = {+ id: next.id,+ folderId: next.folderId,+ title: next.title,+ kind: next.kind,+ status: next.status,+ activeDraftVersionId: next.activeDraftVersionId,+ wordCount: activeDraft?.wordCount ?? 0,+ draftCount: (next.drafts || []).length,+ createdAt: next.createdAt,+ updatedAt: next.updatedAt,+ };+ const idx = prev.findIndex((w) => w.id === next.id);+ const merged = idx < 0 ? summary : { ...prev[idx], ...summary };+ const others = idx < 0 ? prev : [...prev.slice(0, idx), ...prev.slice(idx + 1)];+ // Library is sorted by updatedAt desc — re-sort after the merge so a+ // freshly-saved work surfaces at the top instead of staying mid-list.+ return [merged, ...others].sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));+ });+ };++ return (+ <div className="flex flex-col h-[calc(100vh-3rem)]">+ <div className="flex items-center gap-3 px-4 py-3 border-b border-port-border bg-port-card">+ <NotebookPen className="w-5 h-5 text-port-accent" />+ <h1 className="text-xl font-bold text-white">Writers Room</h1>+ <span className="text-xs text-gray-500 hidden md:inline">Folders, works, drafts, and write-for-10 sprints</span>+ <button+ onClick={() => setShowExercise((s) => !s)}+ className={`ml-auto flex items-center gap-1 px-3 py-1 text-xs rounded ${+ showExercise ? 'bg-port-accent text-white' : 'bg-port-bg border border-port-border text-gray-300 hover:text-white'+ }`}+ aria-pressed={showExercise}+ aria-label="Toggle write-for-10 exercise sidebar"+ title="Toggle exercise sidebar"+ >+ <Timer size={12} /> Write for 10+ </button>+ </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>++ <main className="min-h-0 flex flex-col">+ {loadingWork && <div className="p-6 text-sm text-gray-500">Loading work…</div>}+ {!loadingWork && !activeWork && (+ <div className="flex-1 flex items-center justify-center text-center p-8">+ <div className="max-w-md space-y-2 text-gray-400">+ <NotebookPen className="w-10 h-10 mx-auto text-gray-600" />+ <h2 className="text-lg text-white">No work selected</h2>+ <p className="text-sm">Pick a work from the library to start editing, or create a new one. Use the Write for 10 panel for timed sprints.</p>+ </div>+ </div>+ )}+ {!loadingWork && activeWork && (+ <WorkEditor work={activeWork} onChange={handleWorkChange} />+ )}+ </main>++ {showExercise && (+ <aside className="border-t lg:border-t-0 lg:border-l border-port-border bg-port-card/30 p-3 min-h-0 lg:overflow-y-auto">+ <ExercisePanel activeWork={activeWork} onClose={() => setShowExercise(false)} />+ </aside>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex f826973a9a..1e6d82cc03 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -37,6 +37,7 @@ export * from './apiDashboard.js';export * from './apiAsk.js';export * from './apiImageVideo.js';export * from './apiMediaJobs.js';+export * from './apiWritersRoom.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.jsnew file mode 100644index 0000000000..c39176c201--- /dev/null+++ b/client/src/services/apiWritersRoom.js@@ -0,0 +1,58 @@+import { request } from './apiCore.js';++const enc = encodeURIComponent;++// Folders+export const listWritersRoomFolders = () => request('/writers-room/folders');+export const createWritersRoomFolder = (data) => request('/writers-room/folders', {+ method: 'POST',+ body: JSON.stringify(data),+});+export const deleteWritersRoomFolder = (id) => request(`/writers-room/folders/${enc(id)}`, {+ method: 'DELETE',+});++// Works+export const listWritersRoomWorks = () => request('/writers-room/works');+export const createWritersRoomWork = (data) => request('/writers-room/works', {+ method: 'POST',+ body: JSON.stringify(data),+});+export const getWritersRoomWork = (id) => request(`/writers-room/works/${enc(id)}`);+export const updateWritersRoomWork = (id, patch) => request(`/writers-room/works/${enc(id)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+});+export const deleteWritersRoomWork = (id) => request(`/writers-room/works/${enc(id)}`, {+ method: 'DELETE',+});++// Drafts+export const saveWritersRoomDraft = (id, body) => request(`/writers-room/works/${enc(id)}/draft`, {+ method: 'PUT',+ body: JSON.stringify({ body }),+});+export const snapshotWritersRoomDraft = (id, label) => request(`/writers-room/works/${enc(id)}/versions`, {+ method: 'POST',+ body: JSON.stringify(label ? { label } : {}),+});+export const setWritersRoomActiveDraft = (id, draftId) => request(`/writers-room/works/${enc(id)}/versions/${enc(draftId)}`, {+ method: 'PATCH',+});++// Exercises+export const listWritersRoomExercises = (workId) => {+ const qs = workId ? `?workId=${enc(workId)}` : '';+ return request(`/writers-room/exercises${qs}`);+};+export const createWritersRoomExercise = (data) => request('/writers-room/exercises', {+ method: 'POST',+ body: JSON.stringify(data),+});+export const finishWritersRoomExercise = (id, data) => request(`/writers-room/exercises/${enc(id)}/finish`, {+ method: 'POST',+ body: JSON.stringify(data || {}),+});+export const discardWritersRoomExercise = (id) => request(`/writers-room/exercises/${enc(id)}/discard`, {+ method: 'POST',+});diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex 467738ee20..c8f68db657 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -109,6 +109,27 @@ export function formatBytes(bytes, decimals = 1) {return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;}+/**+ * Count whitespace-separated words in a string. Matches the server-side+ * countWords in writers-room storage so client + server agree.+ */+export function countWords(text) {+ if (!text) return 0;+ const m = String(text).trim().match(/\S+/g);+ return m ? m.length : 0;+}++/**+ * Format a number of seconds as MM:SS (e.g. 75 → "01:15"). Used for sprint+ * timers and other countdowns. Negative values clamp to 0.+ */+export function formatCountdown(seconds) {+ const safe = Math.max(0, Math.round(seconds));+ const m = Math.floor(safe / 60);+ const s = safe % 60;+ return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;+}+/*** Format a timestamp as a localized date+time string (e.g., "Apr 1, 2026, 1:30 PM")* @param {string|Date|null} value - ISO timestamp or Date objectdiff --git a/docs/features/writers-room.md b/docs/features/writers-room.mdnew file mode 100644index 0000000000..2b8f32b292--- /dev/null+++ b/docs/features/writers-room.md@@ -0,0 +1,604 @@+# Writers Room++## Intent++Writers Room is the PortOS workspace for creating, organizing, editing, analyzing,+and adapting literary works. It starts as a focused writing environment with+manual AI review actions, then grows into the story-to-media pipeline: prose to+script, script to character sheets and scene plans, scene plans to reference+images and video renders, and a synchronized review surface that keeps prose,+script, and media aligned.++The first version should support three jobs:++1. Manage writing projects: folders, works, drafts, versions, notes, and status.+2. Help the writer produce words: a "write for 10" exercise with timer, live+ word count, and progress tracking.+3. Run explicit AI passes over the current draft: summaries, character and scene+ extraction, expansion recommendations, prose-to-script adaptation, and media+ planning.++Realtime Creative Director feedback and background live analysis are intentionally+future work. In the first implementation, every AI evaluation and render action is+started by a user click.++## Baseline++`main` now contains both FLUX.2-klein image generation and the full Creative+Director / media-job-queue surface — `feat/creative-director` was squash-merged+as PR #191 (`9b36b900`). Phase 0 of this plan is therefore complete; Writers+Room implementation starts directly on `main`.++Reuse — do not rebuild — the existing image/video gen systems:++- `server/services/imageGen/` and `scripts/flux2_macos.py` for image renders.+- `server/services/videoGen/` for LTX/MLX video renders.+- `server/services/mediaJobQueue/` for serializing local image/video jobs.+- `server/services/creativeDirector/` for treatment/scene/run orchestration.+- `server/lib/mediaModels.js` as the source of truth for image/video models+ (including FLUX.2-klein image variants).++## Product Shape++### Navigation++Routes:++- `/writers-room` — Writers Room landing (library + editor)+- `/writers-room/works/:id` — Active work editor++Sidebar placement: a new top-level **Create** group that contains both+**Media Gen** (default landing for the group) and **Writers Room**. Creative+Director continues to live under `/media/creative-director` and is reachable from+Writers Room via the render-plan handoff. Configuration surfaces (Prompts,+Providers) stay under the existing **AI** group.++Add navigation entries in both places PortOS currently needs them:++- `client/src/components/Layout.jsx`+- `server/lib/navManifest.js`++### Primary Layout++The main Writers Room page should be a three-pane workspace:++- Left: library tree with folders, works, tags, status filters, recent drafts,+ and exercise sessions.+- Center: editor for the active draft, with title, metadata, save/version state,+ word count, and selected prose range.+- Right: action sidebar with manual AI tools grouped as Analyze, Adapt, Render,+ and Review.++The first editor can be a high-quality plain text or Markdown editor. Avoid a+rich-text dependency until formatting requirements justify it. The core needs are+stable text ranges, reliable word count, keyboard-friendly writing, and low risk+of corrupting large prose drafts.++### Writing Exercise++The "write for 10" section can live as a tab in Writers Room and as a quick action+from any work.++MVP behavior (ships in **Phase 1**):++- Configurable timer (5/10/15/25-min presets) with start, finish, and discard.+- Live word count of the sprint buffer, words added since session start.+- Session can start from a blank prompt or a selected work (free-write the+ current work's title appears as the implicit prompt).+- On finish, save the exercise session with starting/ending word counts and+ the appended sprint text.+- Track session history: date, duration, starting words, ending words, words+ added, linked work, and prompt.++Deferred to **Phase 2+** (NOT in Phase 1):++- Pause / resume mid-session (today's MVP is start/finish/discard only).+- Promote / append the sprint text into the active work's draft on finish+ (today the appendedText is logged with the session but not merged into the+ work). The session metadata already carries everything needed to wire this+ up later — surface a "Promote to draft" button on the recent-sessions list.+- Session can start from a selected prose segment (currently scopes to the+ whole work).++Do not blend this into POST yet. POST has creative writing drills, but Writers+Room needs an authoring-grade exercise log tied to works and drafts.++## Data Model++Use local, human-readable storage under `data/writers-room/`. Avoid one giant+JSON file for all prose. Store metadata as JSON and draft bodies as Markdown/text+files so long works remain manageable.++Recommended layout:++```text+data/writers-room/+ folders.json+ exercises.json+ works/+ <workId>/+ manifest.json+ drafts/+ <draftVersionId>.md+ analysis/+ <analysisId>.json+ render-plans/+ <renderPlanId>.json+```++### Folder++```json+{+ "id": "wr-folder-...",+ "parentId": null,+ "name": "Novel Drafts",+ "sortOrder": 0,+ "createdAt": "iso",+ "updatedAt": "iso"+}+```++### Work Manifest++The shape that ships in **Phase 1** (matches the on-disk file written by+`server/services/writersRoom/local.js`):++```json+{+ "id": "wr-work-...",+ "folderId": "wr-folder-..." or null,+ "title": "Working Title",+ "kind": "novel|short-story|screenplay|essay|treatment|other",+ "status": "idea|drafting|revision|adaptation|rendering|complete|archived",+ "activeDraftVersionId": "wr-draft-...",+ "drafts": [ /* see Draft Version */ ],+ "createdAt": "iso",+ "updatedAt": "iso"+}+```++**Phase 2+ planned (NOT yet persisted)** — added when the phase that uses+each field ships. Listed here so the data-model story stays continuous, but+the writer/validator drops them as YAGNI today:++```json+{+ "tags": [],+ "collectionId": "media-collection-id",+ "creativeDirectorProjectIds": [],+ "settings": {+ "defaultAnalysisProviderId": null,+ "defaultAnalysisModel": null,+ "defaultImageModelId": null,+ "defaultVideoModelId": null,+ "renderAspectRatio": "16:9",+ "renderQuality": "draft"+ }+}+```++### Draft Version++Draft metadata should be stored in `manifest.json`, with body text in+`drafts/<draftVersionId>.md`.++```json+{+ "id": "wr-draft-...",+ "label": "Draft 3",+ "contentFile": "drafts/wr-draft-....md",+ "contentHash": "sha256",+ "wordCount": 12842,+ "segmentIndex": [+ {+ "id": "seg-001",+ "kind": "chapter|scene|paragraph",+ "heading": "Chapter 1",+ "start": 0,+ "end": 1842,+ "wordCount": 312+ }+ ],+ "createdAt": "iso",+ "createdFromVersionId": null+}+```++The segment index is the foundation for stale-analysis detection and synced+prose/script/media review. AI outputs should attach to a draft version and to+specific segment IDs or character offsets.++### Analysis Snapshot++AI evaluations are immutable snapshots tied to a draft version. If the draft+changes later, show them as stale rather than mutating them silently.++```json+{+ "id": "wr-analysis-...",+ "workId": "wr-work-...",+ "draftVersionId": "wr-draft-...",+ "kind": "summary|characters|scenes|suggestions|expansion|script|media-plan",+ "sourceRange": { "start": 0, "end": 1842, "segmentIds": ["seg-001"] },+ "providerId": "openai",+ "model": "selected-model",+ "status": "queued|running|succeeded|failed",+ "result": {},+ "error": null,+ "createdAt": "iso",+ "completedAt": "iso"+}+```++Expected result schemas:++- Characters: `characters[]` with name, aliases, role, goals, traits,+ relationships, visual spec, first-seen segment, and evidence snippets.+- Scenes: `scenes[]` with summary, location, time, characters, plot beats,+ emotional turn, adaptation notes, and suggested visual prompt.+- Summary: logline, short summary, detailed synopsis, themes, open questions.+- Suggestions: issue/recommendation list with target segment, rationale,+ severity, and optional replacement/continuation text.+- Expansion: continuation options, missing-scene opportunities, character+ deepening notes, pacing recommendations.+- Script: screenplay-style script segments mapped back to prose segment IDs.+- Media plan: character reference prompts, scene reference prompts, shot list,+ video prompts, and Creative Director handoff metadata.++## Backend Plan++### Services++Add `server/services/writersRoom/local.js` for file-backed CRUD and draft I/O.+Keep it the only writer for `data/writers-room/`, matching the pattern used by+Creative Director and Video Timeline.++Responsibilities:++- create/update/delete folders+- create/update/archive works+- read/write draft body files+- create draft versions and compute word count/content hash+- build/update segment indexes+- save immutable analysis snapshots+- save exercise sessions+- create media collections for works when needed+- link works to Creative Director projects, media collections, and timeline+ projects++Add validation in `server/lib/validation.js` or a dedicated+`server/lib/writersRoomValidation.js` if the schemas get large. Keep Zod schemas+strict at the route boundary.++### Routes++Add `server/routes/writersRoom.js`.++Suggested endpoints:++| Method | Path | Purpose |+|--------|------|---------|+| GET | `/api/writers-room/folders` | List folders |+| POST | `/api/writers-room/folders` | Create folder |+| PATCH | `/api/writers-room/folders/:id` | Rename/move folder |+| DELETE | `/api/writers-room/folders/:id` | Delete empty folder |+| GET | `/api/writers-room/works` | List work summaries |+| POST | `/api/writers-room/works` | Create work |+| GET | `/api/writers-room/works/:id` | Get manifest, latest draft metadata, latest analysis summaries |+| PATCH | `/api/writers-room/works/:id` | Update work metadata/status/settings |+| DELETE | `/api/writers-room/works/:id` | Archive or delete work |+| GET | `/api/writers-room/works/:id/draft` | Get active draft body |+| PUT | `/api/writers-room/works/:id/draft` | Save active draft body and update segment index |+| POST | `/api/writers-room/works/:id/versions` | Snapshot current draft as a new version |+| GET | `/api/writers-room/works/:id/analysis` | List analysis snapshots |+| POST | `/api/writers-room/works/:id/analysis` | Manually run an AI evaluation |+| GET | `/api/writers-room/analysis/:analysisId` | Get full analysis result |+| POST | `/api/writers-room/exercises` | Start or save exercise session |+| PATCH | `/api/writers-room/exercises/:id` | Finish/discard/update session |+| POST | `/api/writers-room/works/:id/render-plans` | Create media plan from script/scenes |+| POST | `/api/writers-room/render-plans/:id/creative-director` | Create/link Creative Director project |++Analysis can be synchronous for small drafts in v1, but the API should already+carry `status` so it can move to queued/background execution without changing the+UI contract.++### AI Evaluation Service++Add `server/services/writersRoom/evaluator.js`.++Use existing provider and prompt infrastructure instead of hardcoding prompts in+the route. Recommended prompt stages under `data.sample/prompts/stages/`:++- `writers-room-summary.md`+- `writers-room-characters.md`+- `writers-room-scenes.md`+- `writers-room-suggestions.md`+- `writers-room-expansion.md`+- `writers-room-script.md`+- `writers-room-media-plan.md`++Prompt outputs should be JSON-first and schema-validated before persistence. If+validation fails, save the failed analysis snapshot with the raw error and do not+modify the work.++Manual trigger rule:++- No automatic eval on every keystroke.+- No background eval on draft save.+- Buttons in the sidebar trigger exactly one analysis kind for the selected+ range or the active draft.++## Creative Director And Media Integration++### What To Reuse++From `feat/creative-director`:++- `server/services/creativeDirector/local.js` for project state.+- `server/services/creativeDirector/orchestrator.js` for next-task decisions.+- `server/services/creativeDirector/agentBridge.js` and+ `completionHook.js` for CoS task chaining.+- `server/services/mediaJobQueue/index.js` for serializing local image/video+ jobs and avoiding GPU/Metal contention.+- `server/routes/creativeDirector.js` and `server/routes/mediaJobs.js`.+- Creative Director detail UI concepts: treatment, segments, runs.++From latest `main`:++- `server/lib/mediaModels.js` as the source of truth for image/video models,+ including FLUX.2-klein image models.+- `scripts/flux2_macos.py` and `scripts/flux2_quantized.py`.+- `/api/image-gen/models`, `/api/video-gen/models`, media collections, media+ history, and video timeline routes.++### Merge Requirements++When merging Creative Director onto latest main:++- Preserve FLUX.2 model registry fields: `runner`, `quantization`, `repo`,+ `tokenizerRepo`, `basePipelineRepo`, and `isFlux2`.+- Preserve the FLUX.2 setup/status route and HF token/license messaging.+- Keep mediaJobQueue's `providedJobId` behavior for image/video generators so+ queued job IDs match SSE event IDs.+- Re-run and update tests around `imageGen`, `videoGen`, `mediaModels`, and+ `mediaJobQueue`.++### Writers Room Bridge++Writers Room should not duplicate Creative Director. It should create inputs for+Creative Director and link back to its outputs.++Bridge behavior:++1. User runs `media-plan` or `script` analysis on a work or selected range.+2. Writers Room stores a render plan mapped to draft segment IDs.+3. User clicks "Create Creative Director project".+4. Server creates a Creative Director project with:+ - work title as project name+ - selected prose/script as `userStory`+ - work/render style as `styleSpec`+ - selected video model/aspect/quality+ - a media collection shared with the work+5. Creative Director plans and renders only after the user starts it.+6. Writers Room stores the returned `creativeDirectorProjectId` and displays+ Creative Director treatment/scenes/runs inline or through deep links.++For character and scene reference images, use image generation directly through+the existing image-gen route and media job queue. FLUX.2-klein is an image model,+so it is best suited for character sheets, scene references, and mood frames.+Scene videos still go through the configured video model pipeline.++## Synchronized Review Surface++Add this after core analysis and Creative Director handoff are stable.++Goal: let the user see how a story maps across forms.++View modes:++- Prose only+- Script only+- Media only+- Prose + script+- Script + media+- Prose + script + media++Mapping model:++```json+{+ "proseSegmentId": "seg-001",+ "scriptSegmentIds": ["script-001"],+ "mediaSegmentIds": ["media-001"],+ "creativeDirectorSceneIds": ["scene-1"],+ "mediaRefs": [+ { "kind": "image", "ref": "character-ref.png" },+ { "kind": "video", "ref": "video-history-id" }+ ]+}+```++Behavior:++- Selecting prose highlights the mapped script and media.+- Selecting script scrolls prose and media to the mapped segments.+- Media cards show provenance: source prose segment, script segment, prompt,+ model, render job, and Creative Director scene/run when applicable.+- If the draft content hash differs from the analysis/render plan version, show+ stale badges and require a deliberate refresh.++## Frontend Plan++Add:++- `client/src/pages/WritersRoom.jsx`+- `client/src/services/apiWritersRoom.js`+- `client/src/components/writers-room/LibraryPane.jsx`+- `client/src/components/writers-room/WorkEditor.jsx`+- `client/src/components/writers-room/ExercisePanel.jsx`+- `client/src/components/writers-room/AiSidebar.jsx`+- `client/src/components/writers-room/AnalysisPanel.jsx`+- `client/src/components/writers-room/RenderPlanPanel.jsx`+- `client/src/components/writers-room/SyncedReview.jsx`++MVP UI states:++- Empty library+- Create folder/work+- Save draft pending/saved/error+- Unsaved changes+- Exercise running/paused/complete+- Analysis idle/running/succeeded/failed/stale+- Render plan not created/ready/linked/rendering/complete+- Creative Director linked project status++Keep the UI dense and tool-like. This is an authoring workspace, not a marketing+page. Use icons for manual actions, tabs for work surfaces, and fixed panes so+the editor does not jump when analysis cards update.++## Phased Implementation++### Phase 0 - Merge Foundation [DONE]++Completed by squash-merge of `feat/creative-director` (PR #191, commit+`9b36b900`) and the FLUX.2 work that landed alongside it. Image/video routes,+mediaJobQueue, FLUX.2 model registry, Creative Director routes/UI, and SSE+progress all ship on `main` today.++### Phase 1 - Writers Room Core++Goal: works can be created, organized, edited, saved, versioned, and exercised.++- Add storage service, validation, routes, and API client.+- Add `/writers-room` route and nav entries.+- Build library pane and editor.+- Add autosave or explicit save with visible dirty/saved state. Prefer explicit+ save for the first version unless the editor proves stable.+- Add "write for 10" exercise session flow.+- Add word count, selected-range count, and draft version snapshots.++Exit criteria:++- User can create a folder, create a work, write prose, save it, snapshot a+ version, and complete a 10-minute exercise.++### Phase 2 - Manual AI Analysis++Goal: the writer can trigger useful, reviewable AI passes against a draft or+selected segment.++- Add prompt stages and evaluator service.+- Add analysis sidebar buttons for summary, characters, scenes, suggestions,+ expansion, and script.+- Store immutable analysis snapshots tied to draft version/content hash.+- Render structured analysis panels with evidence and stale badges.+- Add "accept into notes" or "copy into draft" only as explicit actions.++Exit criteria:++- No AI pass runs without a click.+- A changed draft marks old analysis as stale.+- Character/scene/script outputs retain source segment mappings.++### Phase 3 - Media Planning And Creative Director Handoff++Goal: a work can become a media plan, reference images, and a Creative Director+project.++- Add media-plan analysis kind.+- Add render plan storage and UI.+- Generate character reference prompts and scene reference prompts.+- Queue selected image previews using configured image model, including FLUX.2+ where available.+- Create/link Creative Director projects from render plans.+- Show Creative Director treatment/scenes/runs inside Writers Room as linked+ project state.++Exit criteria:++- User can select a scene or range, create a media plan, generate reference+ images, create a Creative Director project, and start rendering from a manual+ action.++### Phase 4 - Synchronized Prose, Script, Media Review++Goal: the user can inspect the adaptation chain and see what maps to what.++- Build `SyncedReview` with prose/script/media panes.+- Add segment mapping storage and stale-state detection.+- Support scroll/selection sync between panes.+- Link media items to collection, history, Creative Director scene, and source+ prose/script.++Exit criteria:++- User can open one work and review prose, script, and generated media with+ visible mappings and provenance.++### Phase 5 - Realtime Creative Director Feedback++Goal: evolve from manual passes to controlled live assistance.++- Optional live story continuation suggestions while writing.+- Optional render previews on selected scenes.+- Creative Director can propose next beats, alternate scenes, and visual+ treatments from the active cursor context.+- Add throttling, debouncing, budget controls, and explicit opt-in per work.++This phase should wait until manual analysis quality, mapping, and render costs+are proven.++## Test Plan++Backend:++- Writers Room storage CRUD and atomic writes.+- Draft save/version/content-hash behavior.+- Segment index generation for headings, blank-line scenes, and paragraphs.+- Analysis snapshot validation and stale detection.+- Exercise session lifecycle.+- Creative Director project linking.+- Media job queue integration with image and video job owners.+- Route validation and error shapes.++Frontend:++- Library create/select/delete flows.+- Editor dirty/saved/error state.+- Exercise timer and word-count deltas.+- Analysis sidebar loading, success, failure, stale states.+- Render plan and Creative Director linked-project states.+- Mobile layout for the three-pane workspace.++Regression:++- `/media/image`, `/media/video`, `/media/creative-director`, `/media/timeline`,+ and `/media/collections` still work.+- `server/lib/navManifest.test.js` still passes after adding Writers Room nav.+- FLUX.2 setup/status remains visible and its unsupported LoRA constraints are+ still enforced.++## Non-Goals For MVP++- Realtime background evaluation while typing.+- Multi-user collaboration.+- Rich screenplay pagination/export.+- Automatic rewrite of user prose.+- Fully autonomous story-to-movie generation without manual gates.+- Database migration for writing content.+- Public sharing or publishing workflows.++## Resolved Review Questions++1. **Sidebar placement** — A new top-level `Create` group containing Media Gen+ (default landing) and Writers Room. Prompts and Providers stay under `AI`.+2. **Editor** — Plain Markdown for v1. Revisit when screenplay formatting needs+ pagination.+3. **"Write for 10" sessions** — Can start standalone or attached to a work.+ Default the new-session form to "attach to active work" when one is open.+4. **First media milestone** — Character/scene reference images first, then+ video previews via Creative Director handoff.+5. **Creative Director auto-continue** — Inherit Creative Director's existing+ behavior; do not add a Writers-Room-specific gate. The user already controls+ per-scene start/cancel from the CD detail page.diff --git a/server/index.js b/server/index.jsindex cd8ed83201..bbb42edba4 100644--- a/server/index.js+++ b/server/index.js@@ -83,6 +83,7 @@ import videoGenRoutes from './routes/videoGen.js';import videoTimelineRoutes from './routes/videoTimeline.js';import mediaJobsRoutes from './routes/mediaJobs.js';import creativeDirectorRoutes from './routes/creativeDirector.js';+import writersRoomRoutes from './routes/writersRoom.js';import { initMediaJobQueue } from './services/mediaJobQueue/index.js';import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';import imageVideoModelsRoutes from './routes/imageVideoModels.js';@@ -320,6 +321,7 @@ app.use('/api/video-gen', videoGenRoutes);app.use('/api/video-timeline', videoTimelineRoutes);app.use('/api/media-jobs', mediaJobsRoutes);app.use('/api/creative-director', creativeDirectorRoutes);+app.use('/api/writers-room', writersRoomRoutes);app.use('/api/image-video/models', imageVideoModelsRoutes);// AUTOMATIC1111-compatible surface for tailnet clients — gated by// settings.imageGen.expose.a1111 so it returns 403 unless the user opted in.diff --git a/server/lib/creativeDirectorPrompts.test.js b/server/lib/creativeDirectorPrompts.test.jsindex 8336c71ce3..f8e9ca0d1f 100644--- a/server/lib/creativeDirectorPrompts.test.js+++ b/server/lib/creativeDirectorPrompts.test.js@@ -7,8 +7,21 @@ import { applyTemplate } from './promptTemplate.js';// Resolve the templates from disk so the tests exercise the real Prompts// Manager templates — if a future edit breaks an unwrapped {{var}} or a// mistyped section name, the test catches it.-const STAGES_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'data', 'prompts', 'stages');-const loadStage = async (stageName) => readFile(join(STAGES_DIR, `${stageName}.md`), 'utf-8');+//+// data/ is gitignored (populated on first boot via `npm run setup:data`),+// so on a fresh CI checkout only data.sample/ exists. Prefer the runtime+// copy (catches drift from local edits) and fall back to the committed+// seed so CI works without running setup first.+const __HERE = dirname(fileURLToPath(import.meta.url));+const RUNTIME_STAGES_DIR = join(__HERE, '..', '..', 'data', 'prompts', 'stages');+const SAMPLE_STAGES_DIR = join(__HERE, '..', '..', 'data.sample', 'prompts', 'stages');+const loadStage = async (stageName) => {+ const runtimePath = join(RUNTIME_STAGES_DIR, `${stageName}.md`);+ return readFile(runtimePath, 'utf-8').catch((err) => {+ if (err.code !== 'ENOENT') throw err;+ return readFile(join(SAMPLE_STAGES_DIR, `${stageName}.md`), 'utf-8');+ });+};// Mock the prompt-service buildPrompt to render the on-disk template through// the same engine production uses, without needing a live aiToolkit instance.diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 96c8af7b7f..9455cb0f6a 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -9,16 +9,17 @@ export const NAV_COMMANDS = [{ id: 'nav.cybercity', path: '/city', label: 'CyberCity', section: 'Main', aliases: ['city', 'cybercity'], keywords: ['3d', 'visualization'] },{ id: 'nav.apps', path: '/apps', label: 'Apps', section: 'Main', aliases: ['apps'] },- { id: 'nav.media', path: '/media/image', label: 'Media Gen', section: 'AI', aliases: ['media', 'media-gen', 'mediagen', 'generate'], keywords: ['image', 'video', 'render', 'art', 'movie'] },- { id: 'nav.media.image', path: '/media/image', label: 'Image', section: 'AI', aliases: ['image-gen', 'imagegen', 'generate-image', 'sd', 'stable-diffusion'], keywords: ['stable diffusion', 'render', 'art', 'picture', 'photo', 'draw', 'flux', 'mflux'] },- { id: 'nav.media.video', path: '/media/video', label: 'Video', section: 'AI', aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx'] },- { id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'AI', aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },- { id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'AI', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },- { id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'AI', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },- { id: 'nav.media.queue', path: '/media/queue', label: 'Render Queue', section: 'AI', aliases: ['render-queue', 'queue', 'media-queue', 'media-jobs'], keywords: ['render', 'queue', 'pending', 'jobs', 'pipeline'] },- { id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'AI', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },- { id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'AI', aliases: ['media-models', 'image-models', 'video-models', 'huggingface', 'loras'], keywords: ['hf cache', 'lora', 'model storage', 'disk'] },- { id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'AI', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },+ { id: 'nav.media', path: '/media/image', label: 'Media Gen', section: 'Create', aliases: ['media', 'media-gen', 'mediagen', 'generate'], keywords: ['image', 'video', 'render', 'art', 'movie'] },+ { id: 'nav.media.image', path: '/media/image', label: 'Image', section: 'Create', aliases: ['image-gen', 'imagegen', 'generate-image', 'sd', 'stable-diffusion'], keywords: ['stable diffusion', 'render', 'art', 'picture', 'photo', 'draw', 'flux', 'mflux'] },+ { id: 'nav.media.video', path: '/media/video', label: 'Video', section: 'Create', aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx'] },+ { id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'Create', aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },+ { id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },+ { id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },+ { id: 'nav.media.queue', path: '/media/queue', label: 'Render Queue', section: 'Create', aliases: ['render-queue', 'queue', 'media-queue', 'media-jobs'], keywords: ['render', 'queue', 'pending', 'jobs', 'pipeline'] },+ { id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },+ { id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface', 'loras'], keywords: ['hf cache', 'lora', 'model storage', 'disk'] },+ { id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },+ { id: 'nav.writers-room', path: '/writers-room', label: 'Writers Room', section: 'Create', aliases: ['writers-room', 'writersroom', 'writer', 'write', 'studio', 'novel'], keywords: ['prose', 'screenplay', 'story', 'draft', 'manuscript', 'literary', 'novel', 'short story'] },{ id: 'nav.prompts', path: '/prompts', label: 'Prompts', section: 'AI', aliases: ['prompts'] },{ id: 'nav.providers', path: '/ai', label: 'Providers', section: 'AI', aliases: ['providers', 'ai-providers'] },diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 03685746ba..33bc61ab3d 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1,6 +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';// =============================================================================// AGENT PERSONALITY SCHEMAS@@ -465,6 +466,59 @@ export const restoreRequestSchema = z.object({dryRun: z.boolean().optional().default(true)});+// =============================================================================+// WRITERS ROOM SCHEMAS+// =============================================================================++export const writersRoomWorkKindSchema = z.enum(WORK_KINDS);+export const writersRoomWorkStatusSchema = z.enum(WORK_STATUSES);++// IDs are either null (unfiled / unattached) or a non-empty trimmed string.+// Zod runs chain steps in declared order, so .trim() MUST come before .min(1)+// — otherwise a whitespace-only string passes min(1), then trim() collapses+// it to '' after the guard already accepted it. Same gotcha applies to all+// the .min(1).trim() pairs below.+const wrIdNullable = z.string().trim().min(1).max(100).nullable();++export const writersRoomFolderCreateSchema = z.object({+ name: z.string().trim().min(1).max(200),+ parentId: wrIdNullable.optional(),+ sortOrder: z.number().int().optional()+}).strict();++export const writersRoomWorkCreateSchema = z.object({+ title: z.string().trim().min(1).max(300),+ kind: writersRoomWorkKindSchema.optional().default('short-story'),+ folderId: wrIdNullable.optional()+}).strict();++export const writersRoomWorkUpdateSchema = z.object({+ title: z.string().trim().min(1).max(300).optional(),+ kind: writersRoomWorkKindSchema.optional(),+ status: writersRoomWorkStatusSchema.optional(),+ folderId: wrIdNullable.optional()+}).strict();++export const writersRoomDraftSaveSchema = z.object({+ body: z.string().max(5_000_000) // 5 MB ceiling — well over a long novel in plain text+}).strict();++export const writersRoomSnapshotSchema = z.object({+ label: z.string().trim().min(1).max(100).optional()+}).strict();++export const writersRoomExerciseCreateSchema = z.object({+ workId: wrIdNullable.optional(),+ prompt: z.string().max(2000).optional().default(''),+ durationSeconds: z.number().int().min(60).max(3600).default(600),+ startingWords: z.number().int().min(0).default(0)+}).strict();++export const writersRoomExerciseFinishSchema = z.object({+ endingWords: z.number().int().min(0).optional(),+ appendedText: z.string().max(100000).nullable().optional()+}).strict();+// =============================================================================// FEATURE AGENT SCHEMAS// =============================================================================diff --git a/server/lib/writersRoomPresets.js b/server/lib/writersRoomPresets.jsnew file mode 100644index 0000000000..a559d8fcb3--- /dev/null+++ b/server/lib/writersRoomPresets.js@@ -0,0 +1,7 @@+// Single source of truth for Writers Room enums. Imported by validation.js+// (Zod) and services/writersRoom/local.js (membership checks) so the schema+// and the storage layer can never drift.++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'];diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.jsnew file mode 100644index 0000000000..76c6100410--- /dev/null+++ b/server/routes/writersRoom.js@@ -0,0 +1,119 @@+/**+ * Writers Room routes — folder/work CRUD, draft body I/O, version snapshots,+ * exercise sessions. AI analysis + Creative Director handoff land in Phase 2/3.+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import {+ validateRequest,+ writersRoomFolderCreateSchema,+ writersRoomWorkCreateSchema,+ writersRoomWorkUpdateSchema,+ writersRoomDraftSaveSchema,+ writersRoomSnapshotSchema,+ writersRoomExerciseCreateSchema,+ writersRoomExerciseFinishSchema,+} from '../lib/validation.js';+import {+ listFolders, createFolder, deleteFolder,+ listWorks, getWorkWithBody, createWork, updateWork, deleteWork,+ saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,+ listExercises, createExercise, finishExercise, discardExercise,+} from '../services/writersRoom/local.js';++const router = Router();++// ---------- folders ----------++router.get('/folders', asyncHandler(async (_req, res) => {+ res.json(await listFolders());+}));++router.post('/folders', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomFolderCreateSchema, req.body);+ res.status(201).json(await createFolder(data));+}));++router.delete('/folders/:id', asyncHandler(async (req, res) => {+ res.json(await deleteFolder(req.params.id));+}));++// ---------- works ----------++router.get('/works', asyncHandler(async (_req, res) => {+ res.json(await listWorks());+}));++router.post('/works', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomWorkCreateSchema, req.body);+ res.status(201).json(await createWork(data));+}));++router.get('/works/:id', asyncHandler(async (req, res) => {+ const { manifest, body } = await getWorkWithBody(req.params.id);+ res.json({ ...manifest, activeDraftBody: body });+}));++router.patch('/works/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomWorkUpdateSchema, req.body);+ res.json(await updateWork(req.params.id, data));+}));++router.delete('/works/:id', asyncHandler(async (req, res) => {+ res.json(await deleteWork(req.params.id));+}));++// ---------- draft body / versions ----------++router.put('/works/:id/draft', asyncHandler(async (req, res) => {+ const { body } = validateRequest(writersRoomDraftSaveSchema, req.body);+ const { manifest, body: persisted } = await saveDraftBody(req.params.id, body);+ res.json({ ...manifest, activeDraftBody: persisted });+}));++router.post('/works/:id/versions', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomSnapshotSchema, req.body || {});+ res.status(201).json(await snapshotDraft(req.params.id, data));+}));++router.patch('/works/:id/versions/:draftId', asyncHandler(async (req, res) => {+ // Only one operation supported here today: set the active draft pointer.+ // Routes stays a PATCH so future label/contentHash updates can land cleanly.+ res.json(await setActiveDraft(req.params.id, req.params.draftId));+}));++router.get('/works/:id/versions/:draftId', asyncHandler(async (req, res) => {+ const body = await getDraftBody(req.params.id, req.params.draftId);+ res.json({ id: req.params.draftId, body });+}));++// ---------- exercises ----------++router.get('/exercises', asyncHandler(async (req, res) => {+ // Coerce ?workId to a single string. Express parses repeated keys as an+ // array; previously we dropped the filter entirely in that case, which+ // turned a filtered request into an unfiltered one (data leakage). Now we+ // pick the first non-empty string and ignore the rest, so a duplicated+ // param degrades to "filter by the first value" instead of "show all".+ const raw = req.query.workId;+ const candidate = Array.isArray(raw) ? raw.find((v) => typeof v === 'string' && v) : raw;+ const workId = typeof candidate === 'string' && candidate ? candidate : undefined;+ res.json(await listExercises({ workId }));+}));++router.post('/exercises', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomExerciseCreateSchema, req.body || {});+ res.status(201).json(await createExercise(data));+}));++router.post('/exercises/:id/finish', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomExerciseFinishSchema, req.body || {});+ res.json(await finishExercise(req.params.id, data));+}));++router.post('/exercises/:id/discard', asyncHandler(async (req, res) => {+ res.json(await discardExercise(req.params.id));+}));++export default router;diff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.jsnew file mode 100644index 0000000000..f81ed86a47--- /dev/null+++ b/server/routes/writersRoom.test.js@@ -0,0 +1,151 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/writersRoom/local.js', () => ({+ listFolders: vi.fn(async () => [{ id: 'wr-folder-1', name: 'Drafts' }]),+ createFolder: vi.fn(async (data) => ({ id: 'wr-folder-new', ...data })),+ deleteFolder: vi.fn(async () => ({ ok: true })),+ listWorks: vi.fn(async () => [{ id: 'wr-work-1', title: 'A' }]),+ createWork: vi.fn(async (data) => ({ id: 'wr-work-new', title: data.title, kind: data.kind || 'short-story' })),+ getWorkWithBody: vi.fn(),+ updateWork: vi.fn(async (id, patch) => ({ id, ...patch })),+ deleteWork: vi.fn(async () => ({ ok: true })),+ saveDraftBody: vi.fn(async (id, body) => ({ manifest: { id }, body })),+ snapshotDraft: vi.fn(async (id) => ({ id, drafts: [{}, {}] })),+ setActiveDraft: vi.fn(async (id, draftId) => ({ id, activeDraftVersionId: draftId })),+ getDraftBody: vi.fn(async () => 'draft body text'),+ listExercises: vi.fn(async () => []),+ createExercise: vi.fn(async (data) => ({ id: 'wr-ex-new', ...data })),+ finishExercise: vi.fn(async (id) => ({ id, status: 'finished' })),+ discardExercise: vi.fn(async (id) => ({ id, status: 'discarded' })),+}));++import * as svc from '../services/writersRoom/local.js';+import writersRoomRoutes from './writersRoom.js';++describe('writersRoom routes', () => {+ let app;++ beforeEach(() => {+ app = express();+ // Match the production parser limit so the schema's 5 MB ceiling, not the+ // express body parser, is what produces the 400 in the body-too-large test.+ app.use(express.json({ limit: '55mb' }));+ app.use('/api/writers-room', writersRoomRoutes);+ app.use(errorMiddleware);+ vi.clearAllMocks();+ });++ describe('folders', () => {+ it('GET /folders returns the list', async () => {+ const r = await request(app).get('/api/writers-room/folders');+ expect(r.status).toBe(200);+ expect(r.body[0].id).toBe('wr-folder-1');+ });++ it('POST /folders rejects empty name', async () => {+ const r = await request(app).post('/api/writers-room/folders').send({ name: '' });+ expect(r.status).toBe(400);+ });++ it('POST /folders accepts valid payload', async () => {+ const r = await request(app).post('/api/writers-room/folders').send({ name: 'Novels' });+ expect(r.status).toBe(201);+ expect(svc.createFolder).toHaveBeenCalledWith({ name: 'Novels' });+ });++ it('DELETE /folders/:id forwards to the service', async () => {+ const r = await request(app).delete('/api/writers-room/folders/wr-folder-1');+ expect(r.status).toBe(200);+ expect(svc.deleteFolder).toHaveBeenCalledWith('wr-folder-1');+ });+ });++ describe('works', () => {+ it('POST /works rejects unknown kind', async () => {+ const r = await request(app).post('/api/writers-room/works').send({ title: 'X', kind: 'manifesto' });+ expect(r.status).toBe(400);+ });++ it('POST /works defaults kind to short-story', async () => {+ const r = await request(app).post('/api/writers-room/works').send({ title: 'Untitled' });+ expect(r.status).toBe(201);+ expect(svc.createWork).toHaveBeenCalledWith({ title: 'Untitled', kind: 'short-story' });+ });++ it('GET /works/:id flattens manifest + activeDraftBody', async () => {+ svc.getWorkWithBody.mockResolvedValue({+ manifest: { id: 'wr-work-1', title: 'A' },+ body: 'prose',+ });+ const r = await request(app).get('/api/writers-room/works/wr-work-1');+ expect(r.status).toBe(200);+ expect(r.body.title).toBe('A');+ expect(r.body.activeDraftBody).toBe('prose');+ });++ it('PATCH /works/:id rejects unknown status', async () => {+ const r = await request(app).patch('/api/writers-room/works/wr-work-1').send({ status: 'wat' });+ expect(r.status).toBe(400);+ });++ it('PATCH /works/:id rejects extra fields (strict schema)', async () => {+ const r = await request(app).patch('/api/writers-room/works/wr-work-1').send({ tags: ['a'] });+ expect(r.status).toBe(400);+ });++ it('DELETE /works/:id forwards to the service', async () => {+ const r = await request(app).delete('/api/writers-room/works/wr-work-1');+ expect(r.status).toBe(200);+ expect(svc.deleteWork).toHaveBeenCalledWith('wr-work-1');+ });+ });++ describe('drafts', () => {+ it('PUT /works/:id/draft rejects body over 5MB', async () => {+ const big = 'x'.repeat(5_000_001);+ const r = await request(app).put('/api/writers-room/works/wr-work-1/draft').send({ body: big });+ expect(r.status).toBe(400);+ });++ it('PUT /works/:id/draft persists and echoes the body', async () => {+ const r = await request(app).put('/api/writers-room/works/wr-work-1/draft').send({ body: 'new prose' });+ expect(r.status).toBe(200);+ expect(svc.saveDraftBody).toHaveBeenCalledWith('wr-work-1', 'new prose');+ expect(r.body.activeDraftBody).toBe('new prose');+ });++ it('POST /works/:id/versions accepts an optional label', async () => {+ const r = await request(app).post('/api/writers-room/works/wr-work-1/versions').send({ label: 'Pre-revision' });+ expect(r.status).toBe(201);+ expect(svc.snapshotDraft).toHaveBeenCalledWith('wr-work-1', { label: 'Pre-revision' });+ });+ });++ describe('exercises', () => {+ it('POST /exercises clamps duration via schema (rejects 30 seconds)', async () => {+ const r = await request(app).post('/api/writers-room/exercises').send({ durationSeconds: 30 });+ expect(r.status).toBe(400);+ });++ it('POST /exercises accepts default duration', async () => {+ const r = await request(app).post('/api/writers-room/exercises').send({});+ expect(r.status).toBe(201);+ expect(svc.createExercise).toHaveBeenCalled();+ });++ it('POST /exercises/:id/finish forwards endingWords', async () => {+ const r = await request(app).post('/api/writers-room/exercises/wr-ex-1/finish').send({ endingWords: 100 });+ expect(r.status).toBe(200);+ expect(svc.finishExercise).toHaveBeenCalledWith('wr-ex-1', { endingWords: 100 });+ });++ it('POST /exercises/:id/discard hits the discard handler', async () => {+ const r = await request(app).post('/api/writers-room/exercises/wr-ex-1/discard');+ expect(r.status).toBe(200);+ expect(svc.discardExercise).toHaveBeenCalledWith('wr-ex-1');+ });+ });+});diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.jsnew file mode 100644index 0000000000..88cf442459--- /dev/null+++ b/server/services/writersRoom/local.js@@ -0,0 +1,479 @@+/**+ * Writers Room — file-backed storage for folders, works, drafts, and exercises.+ *+ * Layout under data/writers-room/:+ * folders.json+ * exercises.json+ * works/<workId>/manifest.json+ * works/<workId>/drafts/<draftVersionId>.md+ *+ * Manifest holds work metadata + the active draft's metadata + the version+ * history; draft bodies live as .md files so long prose stays out of the JSON.+ *+ * This module is the only writer for data/writers-room/. See+ * docs/features/writers-room.md for the full data model.+ */++import { join } from 'path';+import { randomUUID, createHash } from 'crypto';+import { readFile, rm, readdir } from 'fs/promises';+import { PATHS, atomicWrite, ensureDir, readJSONFile, safeJSONParse } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { WORK_KINDS, WORK_STATUSES } from '../../lib/writersRoomPresets.js';++// Paths are resolved lazily so tests can swap PATHS.data via vi.mock without+// the module-load snapshot freezing them at import time.+const root = () => join(PATHS.data, 'writers-room');+const foldersFile = () => join(root(), 'folders.json');+const exercisesFile = () => join(root(), 'exercises.json');+const worksDir = () => join(root(), 'works');++const WORK_ID_RE = /^wr-work-[0-9a-f-]+$/i;+const DRAFT_ID_RE = /^wr-draft-[0-9a-f-]+$/i;++function nowIso() {+ return new Date().toISOString();+}++function notFound(what) {+ return new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' });+}++function badRequest(message) {+ return new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });+}++function workDir(workId) {+ if (!WORK_ID_RE.test(workId)) throw badRequest('Invalid work id');+ return join(worksDir(), workId);+}++function draftPath(workId, draftId) {+ if (!DRAFT_ID_RE.test(draftId)) throw badRequest('Invalid draft id');+ return join(workDir(workId), 'drafts', `${draftId}.md`);+}++function manifestPath(workId) {+ return join(workDir(workId), 'manifest.json');+}++// ---------- text analysis ----------++export function countWords(text) {+ if (!text) return 0;+ const matches = String(text).trim().match(/\S+/g);+ return matches ? matches.length : 0;+}++export function contentHash(text) {+ return createHash('sha256').update(text || '').digest('hex');+}++/**+ * Build a segment index over Markdown-flavored prose.+ *+ * Splits on # / ## / ### headings (### collapses to scene; the outline panel+ * doesn't visually distinguish a separate "beat" tier in Phase 1). Anything+ * before the first heading becomes a "preamble" segment. No headings → one+ * "(untitled)" segment covers the whole body. Empty/missing text → empty+ * array (so a brand-new draft doesn't show a phantom segment in the outline).+ * The index powers the outline panel today and will anchor stale-analysis+ * detection in later phases.+ */+function segId(seq) {+ return `seg-${String(seq).padStart(3, '0')}`;+}++export function buildSegmentIndex(text) {+ if (!text) return [];+ const headingRe = /^(#{1,3})\s+(.+)$/gm;+ const matches = [];+ let m;+ while ((m = headingRe.exec(text)) !== null) {+ matches.push({ index: m.index, hashes: m[1], heading: m[2].trim() });+ }+ let seq = 0;+ if (matches.length === 0) {+ return [{ id: segId(++seq), kind: 'paragraph', heading: '(untitled)', start: 0, end: text.length, wordCount: countWords(text) }];+ }+ const segments = [];+ if (matches[0].index > 0 && text.slice(0, matches[0].index).trim().length > 0) {+ segments.push({+ id: segId(++seq), kind: 'paragraph', heading: '(preamble)',+ start: 0, end: matches[0].index, wordCount: countWords(text.slice(0, matches[0].index)),+ });+ }+ matches.forEach((match, i) => {+ const start = match.index;+ const end = i + 1 < matches.length ? matches[i + 1].index : text.length;+ segments.push({+ id: segId(++seq),+ kind: match.hashes.length === 1 ? 'chapter' : 'scene',+ heading: match.heading,+ start,+ end,+ wordCount: countWords(text.slice(start, end)),+ });+ });+ return segments;+}++// ---------- folder CRUD ----------++async function loadFolders() {+ await ensureDir(root());+ const raw = await readJSONFile(foldersFile(), []);+ return Array.isArray(raw) ? raw : [];+}++async function saveFolders(folders) {+ await ensureDir(root());+ await atomicWrite(foldersFile(), folders);+}++export async function listFolders() {+ return loadFolders();+}++export async function createFolder({ name, parentId = null, sortOrder = 0 }) {+ if (!name || !name.trim()) throw badRequest('Folder name required');+ const folders = await loadFolders();+ if (parentId && !folders.find((f) => f.id === parentId)) throw notFound('Parent folder');+ const folder = {+ id: `wr-folder-${randomUUID()}`,+ parentId,+ name: name.trim(),+ sortOrder,+ createdAt: nowIso(),+ updatedAt: nowIso(),+ };+ folders.push(folder);+ await saveFolders(folders);+ return folder;+}++export async function deleteFolder(id) {+ const folders = await loadFolders();+ if (!folders.find((f) => f.id === id)) throw notFound('Folder');+ const works = await listWorks();+ if (works.some((w) => w.folderId === id)) {+ throw badRequest('Folder is not empty — move or delete its works first');+ }+ if (folders.some((f) => f.parentId === id)) {+ throw badRequest('Folder has subfolders — delete or reparent them first');+ }+ await saveFolders(folders.filter((f) => f.id !== id));+ return { ok: true };+}++// ---------- work CRUD ----------++async function loadManifest(workId) {+ const path = manifestPath(workId);+ const content = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (content === null) return null;+ // Surface corrupted manifests as a deterministic 500 with a clear code so+ // listWorks can drop the work without masking the underlying issue, and+ // direct callers (getWork) get an actionable error instead of a raw+ // SyntaxError bubbling out of JSON.parse.+ const parsed = safeJSONParse(content, null, { allowArray: false, logError: true, context: path });+ if (parsed === null) {+ // Don't leak the on-disk path to the client; keep it in context for the+ // server logs (errorHandler emits context to logs but only message + code+ // to the response body).+ throw new ServerError(`Corrupted writers-room manifest for ${workId}`, {+ status: 500,+ code: 'CORRUPTED_MANIFEST',+ context: { workId, path },+ });+ }+ return parsed;+}++async function saveManifest(workId, manifest) {+ await ensureDir(join(workDir(workId), 'drafts'));+ await atomicWrite(manifestPath(workId), manifest);+}++async function listWorkIds() {+ await ensureDir(worksDir());+ const entries = await readdir(worksDir(), { withFileTypes: true });+ return entries.filter((e) => e.isDirectory() && WORK_ID_RE.test(e.name)).map((e) => e.name);+}++export async function listWorks() {+ const ids = await listWorkIds();+ // Tolerate KNOWN failure modes per work (corrupted JSON, missing file) so+ // one bad work doesn't 500 the whole library. Re-throw anything else+ // (permission errors, EIO, programming bugs) — silently swallowing those+ // would mask real outages. ENOENT bubbles as null from loadManifest itself,+ // not as a thrown error, so we only need to special-case CORRUPTED_MANIFEST.+ const manifests = await Promise.all(ids.map((id) => loadManifest(id).catch((err) => {+ if (err?.code === 'CORRUPTED_MANIFEST') {+ console.warn(`⚠️ wr: dropped work ${id} from listing — corrupted manifest`);+ return null;+ }+ throw err;+ })));+ return manifests+ .filter(Boolean)+ .map((manifest) => {+ const activeDraft = (manifest.drafts || []).find((d) => d.id === manifest.activeDraftVersionId);+ return {+ id: manifest.id,+ folderId: manifest.folderId,+ title: manifest.title,+ kind: manifest.kind,+ status: manifest.status,+ activeDraftVersionId: manifest.activeDraftVersionId,+ wordCount: activeDraft?.wordCount ?? 0,+ draftCount: (manifest.drafts || []).length,+ createdAt: manifest.createdAt,+ updatedAt: manifest.updatedAt,+ };+ })+ .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));+}++export async function getWork(id) {+ const manifest = await loadManifest(id);+ if (!manifest) throw notFound('Work');+ return manifest;+}++async function readDraftFile(workId, draftId) {+ return readFile(draftPath(workId, draftId), 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return '';+ throw err;+ });+}++export async function getWorkWithBody(id) {+ const manifest = await getWork(id);+ const activeId = manifest.activeDraftVersionId;+ if (!activeId) return { manifest, body: '' };+ return { manifest, body: await readDraftFile(id, activeId) };+}++export async function createWork({ folderId = null, title, kind = 'short-story' }) {+ if (!title || !title.trim()) throw badRequest('Work title required');+ if (!WORK_KINDS.includes(kind)) throw badRequest(`Invalid kind: ${kind}`);+ if (folderId) {+ const folders = await loadFolders();+ if (!folders.find((f) => f.id === folderId)) throw notFound('Folder');+ }+ const id = `wr-work-${randomUUID()}`;+ const draftId = `wr-draft-${randomUUID()}`;+ const now = nowIso();+ await ensureDir(join(workDir(id), 'drafts'));+ await atomicWrite(draftPath(id, draftId), '');+ const manifest = {+ id,+ folderId,+ title: title.trim(),+ kind,+ status: 'drafting',+ activeDraftVersionId: draftId,+ drafts: [+ {+ id: draftId,+ label: 'Draft 1',+ contentFile: `drafts/${draftId}.md`,+ contentHash: contentHash(''),+ wordCount: 0,+ segmentIndex: [],+ createdAt: now,+ createdFromVersionId: null,+ },+ ],+ createdAt: now,+ updatedAt: now,+ };+ await saveManifest(id, manifest);+ return manifest;+}++export async function updateWork(id, patch) {+ const manifest = await getWork(id);+ const allowed = ['title', 'folderId', 'kind', 'status'];+ const next = { ...manifest, updatedAt: nowIso() };+ for (const key of allowed) {+ if (patch[key] === undefined) continue;+ if (key === 'kind' && !WORK_KINDS.includes(patch.kind)) throw badRequest(`Invalid kind: ${patch.kind}`);+ if (key === 'status' && !WORK_STATUSES.includes(patch.status)) throw badRequest(`Invalid status: ${patch.status}`);+ next[key] = patch[key];+ }+ // Trim title and reject if it becomes empty after trim — keeps parity with+ // createWork's "title required" guard so a PATCH can't blank a title out.+ if (patch.title !== undefined) {+ const trimmed = String(patch.title ?? '').trim();+ if (!trimmed) throw badRequest('Work title required');+ next.title = trimmed;+ }+ // folderId can be set to a real folder id or to null (unfile the work).+ // Anything else would orphan it from the library tree.+ if (patch.folderId !== undefined && patch.folderId !== null) {+ const folders = await loadFolders();+ if (!folders.find((f) => f.id === patch.folderId)) throw notFound('Folder');+ }+ await saveManifest(id, next);+ return next;+}++export async function deleteWork(id) {+ // 404 the caller if the manifest is missing; rm() with force:true would+ // silently succeed on a non-existent dir and the user gets no signal.+ // Tolerate CORRUPTED_MANIFEST so a user can recover from on-disk corruption+ // by deleting the work via the API/UI instead of resorting to `rm -rf`.+ await getWork(id).catch((err) => {+ if (err?.code === 'CORRUPTED_MANIFEST') {+ console.warn(`⚠️ wr: deleting work ${id} despite corrupted manifest`);+ return;+ }+ throw err;+ });+ await rm(workDir(id), { recursive: true, force: true });+ return { ok: true };+}++// ---------- draft body / version snapshots ----------++function buildDraftMeta(text, base = {}) {+ return {+ ...base,+ contentHash: contentHash(text),+ wordCount: countWords(text),+ segmentIndex: buildSegmentIndex(text),+ };+}++export async function saveDraftBody(workId, body) {+ const manifest = await getWork(workId);+ const activeId = manifest.activeDraftVersionId;+ if (!activeId) throw badRequest('Work has no active draft');+ const text = String(body ?? '');+ await atomicWrite(draftPath(workId, activeId), text);+ const draftIdx = manifest.drafts.findIndex((d) => d.id === activeId);+ if (draftIdx < 0) throw notFound('Active draft');+ manifest.drafts[draftIdx] = buildDraftMeta(text, manifest.drafts[draftIdx]);+ manifest.updatedAt = nowIso();+ await saveManifest(workId, manifest);+ console.log(`📝 wr: saved draft ${activeId.slice(0, 14)}… (${manifest.drafts[draftIdx].wordCount} words)`);+ return { manifest, body: text };+}++export async function snapshotDraft(workId, { label } = {}) {+ const { manifest, body } = await getWorkWithBody(workId);+ const newDraftId = `wr-draft-${randomUUID()}`;+ const fromId = manifest.activeDraftVersionId;+ const draftLabel = label || `Draft ${manifest.drafts.length + 1}`;+ await atomicWrite(draftPath(workId, newDraftId), body);+ manifest.drafts.push(buildDraftMeta(body, {+ id: newDraftId,+ label: draftLabel,+ contentFile: `drafts/${newDraftId}.md`,+ createdAt: nowIso(),+ createdFromVersionId: fromId,+ }));+ manifest.activeDraftVersionId = newDraftId;+ manifest.updatedAt = nowIso();+ await saveManifest(workId, manifest);+ console.log(`📚 wr: snapshot ${draftLabel} for ${manifest.title}`);+ return manifest;+}++export async function setActiveDraft(workId, draftId) {+ const manifest = await getWork(workId);+ if (!manifest.drafts.find((d) => d.id === draftId)) throw notFound('Draft version');+ manifest.activeDraftVersionId = draftId;+ manifest.updatedAt = nowIso();+ await saveManifest(workId, manifest);+ return manifest;+}++export async function getDraftBody(workId, draftId) {+ const manifest = await getWork(workId);+ if (!manifest.drafts.find((d) => d.id === draftId)) throw notFound('Draft version');+ return readDraftFile(workId, draftId);+}++// ---------- exercise sessions ----------++async function loadExercises() {+ await ensureDir(root());+ const raw = await readJSONFile(exercisesFile(), []);+ return Array.isArray(raw) ? raw : [];+}++async function saveExercises(exercises) {+ await ensureDir(root());+ await atomicWrite(exercisesFile(), exercises);+}++export async function listExercises({ workId } = {}) {+ const all = await loadExercises();+ const filtered = workId ? all.filter((e) => e.workId === workId) : all;+ return filtered.sort((a, b) => (b.startedAt || '').localeCompare(a.startedAt || ''));+}++function settled(exercise) {+ return exercise.status === 'finished' || exercise.status === 'discarded';+}++export async function createExercise({ workId = null, prompt = '', durationSeconds = 600, startingWords = 0 }) {+ if (workId) await getWork(workId); // 404 if missing+ const exercise = {+ id: `wr-ex-${randomUUID()}`,+ workId,+ prompt: String(prompt || '').trim(),+ durationSeconds: Math.max(60, Math.min(durationSeconds, 60 * 60)),+ startingWords,+ endingWords: null,+ wordsAdded: null,+ appendedText: null,+ status: 'running',+ startedAt: nowIso(),+ finishedAt: null,+ };+ const all = await loadExercises();+ all.push(exercise);+ await saveExercises(all);+ return exercise;+}++export async function finishExercise(id, { endingWords, appendedText = null } = {}) {+ const all = await loadExercises();+ const idx = all.findIndex((e) => e.id === id);+ if (idx < 0) throw notFound('Exercise');+ if (settled(all[idx])) throw badRequest('Exercise is already settled');+ // Default missing endingWords to startingWords so wordsAdded never goes+ // negative when the caller forgets to send it; clamp the delta as a final+ // backstop for the case where the user backspaces past their starting count.+ const startingWords = all[idx].startingWords || 0;+ const resolvedEnding = endingWords ?? startingWords;+ const wordsAdded = Math.max(0, resolvedEnding - startingWords);+ const finished = {+ ...all[idx],+ endingWords: resolvedEnding,+ wordsAdded,+ appendedText: appendedText ?? null,+ status: 'finished',+ finishedAt: nowIso(),+ };+ all[idx] = finished;+ await saveExercises(all);+ return finished;+}++export async function discardExercise(id) {+ const all = await loadExercises();+ const idx = all.findIndex((e) => e.id === id);+ if (idx < 0) throw notFound('Exercise');+ if (settled(all[idx])) throw badRequest('Exercise is already settled');+ all[idx] = { ...all[idx], status: 'discarded', finishedAt: nowIso() };+ await saveExercises(all);+ return all[idx];+}diff --git a/server/services/writersRoom/local.test.js b/server/services/writersRoom/local.test.jsnew file mode 100644index 0000000000..103a26a0b9--- /dev/null+++ b/server/services/writersRoom/local.test.js@@ -0,0 +1,332 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++let tempRoot;++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return new Proxy(actual, {+ get(target, prop) {+ if (prop === 'PATHS') {+ return { ...actual.PATHS, data: tempRoot };+ }+ return target[prop];+ },+ });+});++const local = await import('./local.js');+const {+ countWords, contentHash, buildSegmentIndex,+ listFolders, createFolder, deleteFolder,+ listWorks, createWork, getWork, getWorkWithBody, updateWork, deleteWork,+ saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,+ listExercises, createExercise, finishExercise, discardExercise,+} = local;++beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-test-'));+});++afterEach(() => {+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });+ // Always restore real timers — without this, a thrown assertion inside a+ // useFakeTimers() block could leave subsequent tests running under fake+ // timers and silently flake (timeouts/Date.now stuck at the system time).+ vi.useRealTimers();+});++describe('text utilities', () => {+ it('countWords ignores leading/trailing whitespace and collapses runs', () => {+ expect(countWords('')).toBe(0);+ expect(countWords(' ')).toBe(0);+ expect(countWords('one')).toBe(1);+ expect(countWords('one two\nthree\tfour')).toBe(4);+ expect(countWords(' hello world ')).toBe(2);+ });++ it('contentHash is deterministic and changes when content changes', () => {+ const a = contentHash('hello');+ const b = contentHash('hello');+ const c = contentHash('hello!');+ expect(a).toBe(b);+ expect(a).not.toBe(c);+ expect(a).toMatch(/^[0-9a-f]{64}$/);+ });++ it('buildSegmentIndex returns single segment for body with no headings', () => {+ const idx = buildSegmentIndex('Some prose with no headings.');+ expect(idx).toHaveLength(1);+ expect(idx[0]).toMatchObject({ kind: 'paragraph', wordCount: 5 });+ });++ it('buildSegmentIndex splits on # / ## / ### (### collapses to scene)', () => {+ const text = '# Chapter 1\nProse here.\n## Scene A\nMore prose.\n### Beat 1\nA beat.';+ const idx = buildSegmentIndex(text);+ expect(idx.map((s) => s.kind)).toEqual(['chapter', 'scene', 'scene']);+ expect(idx.map((s) => s.heading)).toEqual(['Chapter 1', 'Scene A', 'Beat 1']);+ expect(idx.map((s) => s.id)).toEqual(['seg-001', 'seg-002', 'seg-003']);+ });++ it('buildSegmentIndex emits a preamble segment for content before the first heading', () => {+ const text = 'Preamble text.\n# Chapter 1\nBody.';+ const idx = buildSegmentIndex(text);+ expect(idx[0].heading).toBe('(preamble)');+ expect(idx[1].heading).toBe('Chapter 1');+ });+});++describe('folder CRUD', () => {+ it('creates and lists folders', async () => {+ const folder = await createFolder({ name: 'Novels' });+ expect(folder.id).toMatch(/^wr-folder-/);+ expect(folder.name).toBe('Novels');++ const all = await listFolders();+ expect(all).toHaveLength(1);+ expect(all[0].name).toBe('Novels');+ });++ it('rejects creating a folder with a missing parent', async () => {+ await expect(createFolder({ name: 'Child', parentId: 'wr-folder-missing' }))+ .rejects.toThrow(/not found/i);+ });++ it('refuses to delete a folder containing works', async () => {+ const folder = await createFolder({ name: 'Drafts' });+ await createWork({ folderId: folder.id, title: 'Story 1' });+ await expect(deleteFolder(folder.id)).rejects.toThrow(/not empty/i);+ });++ it('deletes an empty folder', async () => {+ const folder = await createFolder({ name: 'Empty' });+ const result = await deleteFolder(folder.id);+ expect(result.ok).toBe(true);+ expect(await listFolders()).toHaveLength(0);+ });+});++describe('work CRUD', () => {+ it('creates a work with an empty active draft', async () => {+ const work = await createWork({ title: 'My Novel', kind: 'novel' });+ expect(work.id).toMatch(/^wr-work-/);+ expect(work.activeDraftVersionId).toMatch(/^wr-draft-/);+ expect(work.drafts).toHaveLength(1);+ expect(work.drafts[0].wordCount).toBe(0);+ expect(work.kind).toBe('novel');+ expect(work.status).toBe('drafting');+ });++ it('rejects unknown kinds', async () => {+ await expect(createWork({ title: 'Bad', kind: 'manifesto' }))+ .rejects.toThrow(/Invalid kind/i);+ });++ it('lists works ordered by updatedAt descending', async () => {+ // Drive nowIso() deterministically — the previous version slept 5ms between+ // creates which can collapse to the same timestamp on slow/coarse-clock CI.+ // Vitest's setSystemTime advances `new Date()` (which nowIso uses).+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));++ const a = await createWork({ title: 'First' });+ vi.setSystemTime(new Date('2026-01-01T00:00:01.000Z'));+ const b = await createWork({ title: 'Second' });+ vi.setSystemTime(new Date('2026-01-01T00:00:02.000Z'));+ await updateWork(a.id, { title: 'First Updated' });++ const list = await listWorks();+ expect(list[0].id).toBe(a.id); // most recently touched+ expect(list[1].id).toBe(b.id);+ // Note: afterEach() also calls useRealTimers() as a safety net.+ });++ it('updateWork patches allowed fields and rejects invalid status', async () => {+ const work = await createWork({ title: 'Test' });+ const updated = await updateWork(work.id, { status: 'revision', title: 'Renamed' });+ expect(updated.status).toBe('revision');+ expect(updated.title).toBe('Renamed');+ await expect(updateWork(work.id, { status: 'invalid-status' }))+ .rejects.toThrow(/Invalid status/i);+ });++ it('updateWork rejects whitespace-only titles', async () => {+ const work = await createWork({ title: 'Keep' });+ await expect(updateWork(work.id, { title: ' ' })).rejects.toThrow(/title required/i);+ // Original title preserved on the persisted manifest+ const reloaded = await getWork(work.id);+ expect(reloaded.title).toBe('Keep');+ });++ it('updateWork rejects unknown folderId and accepts null', async () => {+ const work = await createWork({ title: 'Filed' });+ await expect(updateWork(work.id, { folderId: 'wr-folder-does-not-exist' }))+ .rejects.toThrow(/Folder not found/i);+ // null is valid — it unfiles the work from any folder+ const unfiled = await updateWork(work.id, { folderId: null });+ expect(unfiled.folderId).toBeNull();+ });++ it('deleteWork removes the work directory', async () => {+ const work = await createWork({ title: 'To Delete' });+ await deleteWork(work.id);+ await expect(getWork(work.id)).rejects.toThrow(/not found/i);+ expect(await listWorks()).toHaveLength(0);+ });+});++describe('draft body and versioning', () => {+ it('saveDraftBody persists text and updates word count + segment index', async () => {+ const work = await createWork({ title: 'Story' });+ const text = '# Chapter 1\nOnce upon a time, a cat learned to fly.';+ const { manifest, body } = await saveDraftBody(work.id, text);+ expect(body).toBe(text);+ const active = manifest.drafts.find((d) => d.id === manifest.activeDraftVersionId);+ expect(active.wordCount).toBe(countWords(text));+ expect(active.segmentIndex).toHaveLength(1);+ expect(active.segmentIndex[0].heading).toBe('Chapter 1');+ expect(active.contentHash).toBe(contentHash(text));+ });++ it('saveDraftBody round-trips through getWorkWithBody', async () => {+ const work = await createWork({ title: 'Round Trip' });+ await saveDraftBody(work.id, 'Body text v1.');+ const { body } = await getWorkWithBody(work.id);+ expect(body).toBe('Body text v1.');+ });++ it('snapshotDraft creates a new version that mirrors the current body', async () => {+ const work = await createWork({ title: 'Versioned' });+ await saveDraftBody(work.id, 'First pass.');+ const after = await snapshotDraft(work.id);+ expect(after.drafts).toHaveLength(2);+ expect(after.activeDraftVersionId).toBe(after.drafts[1].id);+ expect(after.drafts[1].wordCount).toBe(2);+ expect(after.drafts[1].createdFromVersionId).toBe(after.drafts[0].id);+ });++ it('setActiveDraft switches the pointer; subsequent saves write the new version', async () => {+ const work = await createWork({ title: 'Switch' });+ const firstId = work.activeDraftVersionId;+ await saveDraftBody(work.id, 'Version 1.');+ const snapped = await snapshotDraft(work.id);+ const secondId = snapped.activeDraftVersionId;+ await saveDraftBody(work.id, 'Version 2.');+ // Switching back should not erase v1+ const switched = await setActiveDraft(work.id, firstId);+ expect(switched.activeDraftVersionId).toBe(firstId);+ const v1 = await getDraftBody(work.id, firstId);+ const v2 = await getDraftBody(work.id, secondId);+ expect(v1).toBe('Version 1.');+ expect(v2).toBe('Version 2.');+ });++ it('writes the active draft body to disk on the expected path', async () => {+ const work = await createWork({ title: 'On Disk' });+ const draftFilePath = join(tempRoot, 'writers-room', 'works', work.id, 'drafts', `${work.activeDraftVersionId}.md`);+ expect(existsSync(draftFilePath)).toBe(true);+ expect(readFileSync(draftFilePath, 'utf-8')).toBe('');++ await saveDraftBody(work.id, 'persisted prose');+ expect(readFileSync(draftFilePath, 'utf-8')).toBe('persisted prose');+ });++ it('snapshotDraft uses the explicit label argument when provided', async () => {+ const work = await createWork({ title: 'Labeled' });+ await saveDraftBody(work.id, 'first.');+ const after = await snapshotDraft(work.id, { label: 'Pre-edit' });+ const newest = after.drafts[after.drafts.length - 1];+ expect(newest.label).toBe('Pre-edit');+ });++ it('snapshotDraft preserves prior versions on disk after multiple snapshots', async () => {+ const work = await createWork({ title: 'Round Trip' });+ await saveDraftBody(work.id, 'V1 text.');+ const afterV2 = await snapshotDraft(work.id);+ await saveDraftBody(work.id, 'V2 text.');+ const afterV3 = await snapshotDraft(work.id);+ await saveDraftBody(work.id, 'V3 text.');++ const v1Id = afterV2.drafts[0].id;+ const v2Id = afterV3.drafts[1].id;+ const v3Id = afterV3.activeDraftVersionId;+ expect(await getDraftBody(work.id, v1Id)).toBe('V1 text.');+ expect(await getDraftBody(work.id, v2Id)).toBe('V2 text.');+ expect(await getDraftBody(work.id, v3Id)).toBe('V3 text.');+ });+});++describe('exercise sessions', () => {+ it('creates a running exercise tied to a work', async () => {+ const work = await createWork({ title: 'Exercise Target' });+ const ex = await createExercise({ workId: work.id, prompt: 'free-write', startingWords: 100 });+ expect(ex.id).toMatch(/^wr-ex-/);+ expect(ex.status).toBe('running');+ expect(ex.workId).toBe(work.id);+ expect(ex.durationSeconds).toBe(600);+ });++ it('clamps duration to [60, 3600] seconds', async () => {+ const tooShort = await createExercise({ durationSeconds: 10 });+ expect(tooShort.durationSeconds).toBe(60);+ const tooLong = await createExercise({ durationSeconds: 99999 });+ expect(tooLong.durationSeconds).toBe(3600);+ });++ it('rejects creating an exercise tied to a missing work', async () => {+ await expect(createExercise({ workId: 'wr-work-deadbeef-1234-5678-aaaa-bbbbccccdddd' }))+ .rejects.toThrow(/not found/i);+ });++ it('finishExercise computes wordsAdded delta and seals the session', async () => {+ const start = Date.now();+ const ex = await createExercise({ startingWords: 50 });+ const finished = await finishExercise(ex.id, { endingWords: 175 });+ expect(finished.status).toBe('finished');+ expect(finished.wordsAdded).toBe(125);+ const finishedAtMs = Date.parse(finished.finishedAt);+ expect(finishedAtMs).toBeGreaterThanOrEqual(start);+ expect(finishedAtMs).toBeLessThanOrEqual(Date.now() + 1);++ // Finishing or discarding a settled session should be rejected.+ await expect(finishExercise(ex.id, { endingWords: 200 }))+ .rejects.toThrow(/already settled/i);+ await expect(discardExercise(ex.id))+ .rejects.toThrow(/already settled/i);+ });++ it('finishExercise clamps wordsAdded at 0 and defaults missing endingWords', async () => {+ // User backspaced past the starting word count → delta should not go negative.+ const ex1 = await createExercise({ startingWords: 200 });+ const finished1 = await finishExercise(ex1.id, { endingWords: 150 });+ expect(finished1.wordsAdded).toBe(0);+ expect(finished1.endingWords).toBe(150);++ // Caller forgot to send endingWords → fall back to startingWords (delta 0),+ // not 0 (which would have produced a -200 delta on the previous version).+ const ex2 = await createExercise({ startingWords: 200 });+ const finished2 = await finishExercise(ex2.id, {});+ expect(finished2.wordsAdded).toBe(0);+ expect(finished2.endingWords).toBe(200);+ });++ it('discardExercise marks the session as discarded', async () => {+ const ex = await createExercise({});+ const discarded = await discardExercise(ex.id);+ expect(discarded.status).toBe('discarded');+ });++ it('listExercises filters by workId', async () => {+ const w1 = await createWork({ title: 'W1' });+ const w2 = await createWork({ title: 'W2' });+ await createExercise({ workId: w1.id });+ await createExercise({ workId: w2.id });+ await createExercise({});++ expect(await listExercises({ workId: w1.id })).toHaveLength(1);+ expect(await listExercises({ workId: w2.id })).toHaveLength(1);+ expect(await listExercises()).toHaveLength(3);+ });+});