Skip to content

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

feat(writers-room): persist per-scene images + auto-collection + reading theme

Adam Eivyf080a0d329e1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c086fb1436..6d55c55f77 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -28,6 +28,8 @@
## Changed
+- **Writers Room — per-scene generated images persist across navigation + auto-collect.** Scene images used to vanish from the UI the moment you navigated away, even though the rendered PNG was sitting on disk. Now: when `image-gen:completed` fires for a scene, the client POSTs `/api/writers-room/works/:id/analysis/:analysisId/scene-image` which (a) writes the scene→image link to the analysis snapshot under `sceneImages[sceneId]`, and (b) appends the image to a per-work auto-created MediaGen Collection (`Writers Room: <title>`, lazily created on first render and cached on the work manifest under `mediaCollectionId`). Re-opening the Adapt result re-seeds each `SceneCard` with its persisted image, so it shows the final render immediately instead of an empty button. Stale collection ids (e.g. user deleted the collection out-of-band) fall through to a fresh create.
+- **Writers Room — per-work reading theme switcher.** The WorkEditor header now has a Sun/Moon toggle (next to Save/Snapshot) that flips the prose textarea + AI sidebar's Adapt scene cards between dark mode (default — matches the rest of PortOS) and a sepia/light reading mode (`#f5f1e8` background, dark text) for users who don't want to read white-on-black for hours. Persists per-user via `localStorage` (`wr.readingTheme`); page chrome and library stay app-themed so the contrast cue stays consistent. Scene-card body text, character chips, dialogue, and the "X words / unsaved" status pill all flip with the toggle.
- **Writers Room — per-scene image gen has its own model + resolution settings.** The Adapt result now exposes a small inline settings row (gear button under the logline) where you can pick the model (`flux2-klein-4b` is the default — fastest FLUX.2 variant on Apple Silicon — with `flux2-klein-9b`, `flux2-klein-4b-int8`, and the existing `dev`/`schnell` mflux models also selectable) and a resolution preset (default 768×512 / 3:2; presets cover 1:1, 2:3, 16:9, and 1:1 1024). Choices persist to `settings.json` under `writersRoom.imageGen` so they survive reloads and apply across all works in the Writers Room. The per-scene preview area now uses the configured aspect ratio instead of always being square, so 3:2 / 16:9 renders aren't letterboxed inside an `aspect-square` slot.
- **Writers Room — AI sidebar is wider and drag-to-resize.** The right-hand AI/Outline/Versions panel default jumps from 240px → 480px so the Adapt scene cards, Evaluate critique, and Format diff render as real page content instead of being squeezed into a margin. A new vertical splitter between the editor and the sidebar lets the user drag to resize (range 280px → 70% of the work area); the chosen width persists per-user via `localStorage` (`wr.sidebarWidth`) so it sticks across reloads. Double-clicking the splitter resets to 480px. Mobile/tablet (< `lg`) still stacks editor + sidebar vertically and ignores the saved width.
- **Writers Room — per-scene image gen now shows a real preview area.** Clicking the per-scene "Image" button used to silently fire a render with no in-card UI feedback — for FLUX.2 jobs that take 30-90s, this looked like nothing happened until the final PNG appeared. Each `SceneCard` now subscribes to `image-gen:started` / `progress` / `completed` / `failed` socket events filtered by its own job id and renders an `aspect-square` preview slot (matching the Image Gen page) that shows: a spinner with "Step N/M" + ETA while queued, the live base64 diffusion frame as the model decodes intermediate latents, a thin progress bar overlaid at the bottom, and the final PNG once `image-gen:completed` fires. The button label flips between "Image" / "Rendering…" / "Re-render" so the state is unambiguous from the row header alone. Two scenes generating concurrently can't fight over progress because each card filters by its own jobId rather than sharing a single hook.
diff --git a/client/src/components/writers-room/AiPanel.jsx b/client/src/components/writers-room/AiPanel.jsx
index 4b100a4a95..54fec9876b 100644
--- a/client/src/components/writers-room/AiPanel.jsx
+++ b/client/src/components/writers-room/AiPanel.jsx
@@ -5,6 +5,7 @@ import {
listWritersRoomAnalyses,
runWritersRoomAnalysis,
getWritersRoomAnalysis,
+ attachWritersRoomSceneImage,
} from '../../services/apiWritersRoom';
import { generateImage, getSettings, updateSettings } from '../../services/apiSystem';
import { listImageModels } from '../../services/apiImageVideo';
@@ -43,7 +44,7 @@ const SEVERITY_COLOR = {
minor: 'text-gray-400 border-port-border',
};
-export default function AiPanel({ work, onApplyFormat }) {
+export default function AiPanel({ work, onApplyFormat, readingTheme = 'dark' }) {
const [analyses, setAnalyses] = useState([]);
const [loadingList, setLoadingList] = useState(false);
const [running, setRunning] = useState(null);
@@ -197,7 +198,14 @@ export default function AiPanel({ work, onApplyFormat }) {
<FormatResult result={full.result} onApply={(text) => onApplyFormat?.(text)} />
)}
{full?.status === 'succeeded' && full.kind === 'script' && (
- <ScriptResult result={full.result} workTitle={work.title} />
+ <ScriptResult
+ result={full.result}
+ workId={work.id}
+ analysisId={full.id}
+ sceneImages={full.sceneImages || {}}
+ workTitle={work.title}
+ readingTheme={readingTheme}
+ />
)}
</div>
)}
@@ -283,7 +291,7 @@ function FormatResult({ result, onApply }) {
);
}
-function ScriptResult({ result, workTitle }) {
+function ScriptResult({ result, workId, analysisId, sceneImages = {}, workTitle, readingTheme = 'dark' }) {
// Image-gen settings are scoped to the Writers Room (not the global Image Gen
// page) so a writer can pick a fast/small model + 3:2 aspect without
// disrupting the dedicated Image Gen workflow.
@@ -329,9 +337,21 @@ function ScriptResult({ result, workTitle }) {
{showSettings && (
<ImageGenSettingsRow cfg={imageCfg} models={models} onChange={persistCfg} />
)}
- {result.scenes.map((scene, i) => (
- <SceneCard key={scene.id || i} scene={scene} workTitle={workTitle} imageCfg={imageCfg} />
- ))}
+ {result.scenes.map((scene, i) => {
+ const sceneId = scene.id || `scene-${i}`;
+ return (
+ <SceneCard
+ key={sceneId}
+ scene={{ ...scene, id: sceneId }}
+ workId={workId}
+ analysisId={analysisId}
+ workTitle={workTitle}
+ imageCfg={imageCfg}
+ initialImage={sceneImages[sceneId] || null}
+ readingTheme={readingTheme}
+ />
+ );
+ })}
</div>
);
}
@@ -385,14 +405,19 @@ function ImageGenSettingsRow({ cfg, models, onChange }) {
);
}
-function SceneCard({ scene, workTitle, imageCfg = WR_IMAGE_DEFAULTS }) {
+function SceneCard({ scene, workId, analysisId, workTitle, imageCfg = WR_IMAGE_DEFAULTS, initialImage = null, readingTheme = 'dark' }) {
+ const light = readingTheme === 'light';
// genStatus drives the button + preview overlay:
// idle → no preview area shown
// running → preview area shows spinner / live diffusion frame from socket
// done → preview area shows the final rendered image
// error → preview area shows the error
- const [genStatus, setGenStatus] = useState('idle');
- const [generated, setGenerated] = useState(null);
+ // Seed from initialImage so a previously-rendered scene shows its image
+ // immediately on remount (e.g. after navigating back to the work).
+ const [genStatus, setGenStatus] = useState(initialImage ? 'done' : 'idle');
+ const [generated, setGenerated] = useState(initialImage
+ ? { path: `/data/images/${initialImage.filename}`, jobId: initialImage.jobId, prompt: initialImage.prompt }
+ : null);
const [error, setError] = useState(null);
// Live diffusion progress for THIS scene's job, filtered by the jobId we
// got back from generateImage. Each SceneCard tracks its own job, so two
@@ -424,10 +449,24 @@ function SceneCard({ scene, workTitle, imageCfg = WR_IMAGE_DEFAULTS }) {
};
const onCompleted = (data) => {
if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;
+ const completedJobId = jobIdRef.current;
setGenerated((prev) => prev ? { ...prev, path: data.path || prev.path } : prev);
setGenStatus('done');
setProgress(null);
jobIdRef.current = null;
+ // Persist the scene→image link so the user sees the same image when
+ // they navigate back. The image filename is `<jobId>.png` per the local
+ // image-gen route's response shape.
+ if (workId && analysisId && scene.id) {
+ attachWritersRoomSceneImage(workId, analysisId, {
+ sceneId: scene.id,
+ filename: `${completedJobId}.png`,
+ jobId: completedJobId,
+ prompt: data.prompt || null,
+ }).catch((err) => {
+ console.warn(`scene-image persist failed: ${err.message}`);
+ });
+ }
};
const onFailed = (data) => {
if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;
@@ -446,7 +485,7 @@ function SceneCard({ scene, workTitle, imageCfg = WR_IMAGE_DEFAULTS }) {
socket.off('image-gen:completed', onCompleted);
socket.off('image-gen:failed', onFailed);
};
- }, []);
+ }, [workId, analysisId, scene.id]);
const generate = async () => {
if (genStatus === 'running') return;
@@ -495,10 +534,12 @@ function SceneCard({ scene, workTitle, imageCfg = WR_IMAGE_DEFAULTS }) {
const showPreviewArea = view !== null;
return (
- <div className="border border-port-border rounded p-2 space-y-1.5 bg-port-card/40">
+ <div className={`border rounded p-2 space-y-1.5 ${
+ light ? 'border-gray-300 bg-[#f5f1e8] text-gray-900' : 'border-port-border bg-port-card/40'
+ }`}>
<div className="flex items-start gap-2">
<div className="flex-1 min-w-0">
- <div className="font-semibold text-white truncate">{scene.heading}</div>
+ <div className={`font-semibold truncate ${light ? 'text-gray-900' : 'text-white'}`}>{scene.heading}</div>
{scene.slugline && <div className="text-[10px] text-port-accent uppercase tracking-wide">{scene.slugline}</div>}
</div>
<button
@@ -565,19 +606,25 @@ function SceneCard({ scene, workTitle, imageCfg = WR_IMAGE_DEFAULTS }) {
<div className="text-[9px] text-gray-500 truncate">job {generated.jobId}</div>
)}
- {scene.summary && <div className="text-gray-400">{scene.summary}</div>}
+ {scene.summary && <div className={light ? 'text-gray-700' : 'text-gray-400'}>{scene.summary}</div>}
{scene.characters?.length > 0 && (
<div className="flex flex-wrap gap-1">
- {scene.characters.map((c, i) => <span key={i} className="px-1.5 py-0.5 bg-port-bg border border-port-border rounded text-[9px] uppercase tracking-wider">{c}</span>)}
+ {scene.characters.map((c, i) => (
+ <span key={i} className={`px-1.5 py-0.5 border rounded text-[9px] uppercase tracking-wider ${
+ light ? 'bg-white border-gray-300 text-gray-700' : 'bg-port-bg border-port-border'
+ }`}>{c}</span>
+ ))}
</div>
)}
- {scene.action && <div className="text-gray-300 whitespace-pre-wrap font-serif">{scene.action}</div>}
+ {scene.action && (
+ <div className={`whitespace-pre-wrap font-serif ${light ? 'text-gray-900' : 'text-gray-300'}`}>{scene.action}</div>
+ )}
{scene.dialogue?.length > 0 && (
- <div className="space-y-1 pl-3 border-l border-port-border">
+ <div className={`space-y-1 pl-3 border-l ${light ? 'border-gray-400' : 'border-port-border'}`}>
{scene.dialogue.map((d, i) => (
<div key={i}>
- <div className="text-[9px] uppercase tracking-wider text-gray-500">{d.character}</div>
- <div className="text-gray-300 italic">"{d.line}"</div>
+ <div className={`text-[9px] uppercase tracking-wider ${light ? 'text-gray-600' : 'text-gray-500'}`}>{d.character}</div>
+ <div className={`italic ${light ? 'text-gray-900' : 'text-gray-300'}`}>"{d.line}"</div>
</div>
))}
</div>
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index 66d1415838..e3c4bbb61e 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { Save, GitCommit, Clock, FileText, Sparkles, ListTree } from 'lucide-react';
+import { Save, GitCommit, Clock, FileText, Sparkles, ListTree, Sun, Moon } from 'lucide-react';
import toast from '../ui/Toast';
import {
saveWritersRoomDraft,
@@ -21,6 +21,12 @@ const SIDEBAR_WIDTH_KEY = 'wr.sidebarWidth';
const SIDEBAR_DEFAULT = 480;
const SIDEBAR_MIN = 280;
const SIDEBAR_MAX_FRACTION = 0.7; // never let the sidebar eat more than 70% of the work area
+const READING_THEME_KEY = 'wr.readingTheme';
+function readReadingTheme() {
+ if (typeof window === 'undefined') return 'dark';
+ const v = window.localStorage.getItem(READING_THEME_KEY);
+ return v === 'light' ? 'light' : 'dark';
+}
function readSidebarWidth() {
if (typeof window === 'undefined') return SIDEBAR_DEFAULT;
@@ -182,6 +188,14 @@ export default function WorkEditor({ work, onChange }) {
// sidebarWidth (the aside renders as a row beneath the editor).
const splitRef = useRef(null);
const [sidebarWidth, setSidebarWidth] = useState(readSidebarWidth);
+ const [readingTheme, setReadingTheme] = useState(readReadingTheme);
+ const toggleReadingTheme = useCallback(() => {
+ setReadingTheme((prev) => {
+ const next = prev === 'dark' ? 'light' : 'dark';
+ try { window.localStorage.setItem(READING_THEME_KEY, next); } catch {}
+ return next;
+ });
+ }, []);
// Mirror sidebarWidth into a ref so the once-bound mousemove/mouseup effect
// reads the freshest value at release time without re-registering on every
// pixel of drag (200px drag = ~200 add/remove pairs otherwise).
@@ -266,6 +280,15 @@ export default function WorkEditor({ work, onChange }) {
>
<GitCommit size={12} /> Snapshot
</button>
+ <button
+ onClick={toggleReadingTheme}
+ className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-port-bg border border-port-border text-gray-300 hover:text-white"
+ title={readingTheme === 'dark' ? 'Switch to light reading theme' : 'Switch to dark reading theme'}
+ aria-label="Toggle reading theme"
+ aria-pressed={readingTheme === 'light'}
+ >
+ {readingTheme === 'dark' ? <Sun size={12} /> : <Moon size={12} />}
+ </button>
</div>
<div ref={splitRef} className="flex-1 flex flex-col lg:flex-row min-h-0">
@@ -275,10 +298,14 @@ export default function WorkEditor({ work, onChange }) {
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"
+ className={`w-full h-full resize-none px-6 py-6 font-serif text-base leading-relaxed focus:outline-none ${
+ readingTheme === 'light' ? 'bg-[#f5f1e8] text-gray-900' : 'bg-port-bg text-gray-100'
+ }`}
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">
+ <div className={`absolute bottom-2 right-3 flex items-center gap-3 text-[11px] px-2 py-1 rounded ${
+ readingTheme === 'light' ? 'text-gray-600 bg-[#f5f1e8]/80' : 'text-gray-500 bg-port-bg/80'
+ }`}>
<span>{wordCount.toLocaleString()} words</span>
{dirty && <span className="text-port-warning">● unsaved</span>}
</div>
@@ -320,6 +347,7 @@ export default function WorkEditor({ work, onChange }) {
{sidebarTab === 'ai' && (
<AiPanel
work={work}
+ readingTheme={readingTheme}
onApplyFormat={(text) => {
// Don't autosave — keeps a bad format pass from overwriting
// the on-disk draft without an explicit Save.
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index b83a71bddd..d47ac9d05b 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -50,6 +50,11 @@ export const runWritersRoomAnalysis = (workId, data) =>
});
export const getWritersRoomAnalysis = (workId, analysisId) =>
request(`/writers-room/works/${enc(workId)}/analysis/${enc(analysisId)}`);
+export const attachWritersRoomSceneImage = (workId, analysisId, payload) =>
+ request(`/writers-room/works/${enc(workId)}/analysis/${enc(analysisId)}/scene-image`, {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ });
// Exercises
export const listWritersRoomExercises = (workId) => {
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index 651a849ba4..7cf8832a93 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -21,10 +21,12 @@ import {
listWorks, getWorkWithBody, createWork, updateWork, deleteWork,
saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,
listExercises, createExercise, finishExercise, discardExercise,
+ ensureWorkMediaCollection,
} from '../services/writersRoom/local.js';
import {
- runAnalysis, listAnalyses, getAnalysis,
+ runAnalysis, listAnalyses, getAnalysis, attachSceneImage,
} from '../services/writersRoom/evaluator.js';
+import { addItem as addCollectionItem, ERR_DUPLICATE } from '../services/mediaCollections.js';
const router = Router();
@@ -140,4 +142,19 @@ router.get('/works/:id/analysis/:analysisId', asyncHandler(async (req, res) => {
res.json(await getAnalysis(req.params.id, req.params.analysisId));
}));
+// Persist a scene→generated-image link on the analysis snapshot, AND mirror
+// the image into the work's auto-collection so it appears in MediaGen's
+// Collections view. Called by SceneCard when image-gen:completed fires.
+router.post('/works/:id/analysis/:analysisId/scene-image', asyncHandler(async (req, res) => {
+ const { sceneId, filename, jobId, prompt } = req.body || {};
+ const updated = await attachSceneImage(req.params.id, req.params.analysisId, { sceneId, filename, jobId, prompt });
+ // Add to the per-work collection. Best-effort — a duplicate (same render
+ // already in the collection) is a no-op, not an error.
+ const collection = await ensureWorkMediaCollection(req.params.id);
+ await addCollectionItem(collection.id, { kind: 'image', ref: filename }).catch((err) => {
+ if (err?.code !== ERR_DUPLICATE) throw err;
+ });
+ res.json({ analysis: updated, collectionId: collection.id });
+}));
+
export default router;
diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.js
index c4f97bc2d6..7479fdf268 100644
--- a/server/services/writersRoom/evaluator.js
+++ b/server/services/writersRoom/evaluator.js
@@ -228,6 +228,33 @@ export async function getAnalysis(workId, id) {
return a;
}
+// Persist the per-scene generated-image reference on the analysis snapshot so
+// the UI can re-show the image after navigation/reload. Scenes are keyed by
+// their `result.scenes[i].id`; we don't validate the id against the scene
+// list because the LLM occasionally drifts (regenerated analyses can have
+// different scene ids) and overwriting an old key is harmless.
+export async function attachSceneImage(workId, id, { sceneId, filename, jobId, prompt }) {
+ if (!ANALYSIS_ID_RE.test(id)) throw badRequest('Invalid analysis id');
+ if (typeof sceneId !== 'string' || !sceneId.trim()) throw badRequest('sceneId required');
+ if (typeof filename !== 'string' || !filename.trim()) throw badRequest('filename required');
+ const a = await loadAnalysis(workId, id);
+ if (!a) throw notFound('Analysis');
+ const next = {
+ ...a,
+ sceneImages: {
+ ...(a.sceneImages || {}),
+ [sceneId]: {
+ filename: filename.trim(),
+ jobId: typeof jobId === 'string' ? jobId : null,
+ prompt: typeof prompt === 'string' ? prompt : null,
+ generatedAt: nowIso(),
+ },
+ },
+ };
+ await saveAnalysis(workId, next);
+ return next;
+}
+
// ---------- startup recovery ----------
/**
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 2aae1b1bbd..97662d2e58 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -202,6 +202,28 @@ async function saveManifest(workId, manifest) {
await atomicWrite(manifestPath(workId), manifest);
}
+// Lazy-import to break a circular dep (mediaCollections doesn't import us, but
+// importing it at module-top would still be fine; the function-level import
+// just keeps this helper self-contained next to its caller).
+export async function ensureWorkMediaCollection(workId) {
+ const manifest = await getWork(workId);
+ const { getCollection, createCollection, ERR_NOT_FOUND } = await import('../mediaCollections.js');
+ if (manifest.mediaCollectionId) {
+ const existing = await getCollection(manifest.mediaCollectionId).catch((err) => {
+ // The collection was deleted out-of-band — drop the stale id and recreate.
+ if (err?.code === ERR_NOT_FOUND) return null;
+ throw err;
+ });
+ if (existing) return existing;
+ }
+ const collection = await createCollection({
+ name: `Writers Room: ${manifest.title}`.slice(0, 80),
+ description: `Auto-generated images for "${manifest.title}"`,
+ });
+ await saveManifest(workId, { ...manifest, mediaCollectionId: collection.id, updatedAt: nowIso() });
+ return collection;
+}
+
async function listWorkIds() {
await ensureDir(worksDir());
const entries = await readdir(worksDir(), { withFileTypes: true });