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): tabbed sidebar + Stop-all cancel for storyboard renders

Adam Eivyed7ccdce8055
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 06468257d3..68671cd9ba 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Writers Room — tabbed sidebar (Characters | World | Scenes | Boards | Config), top progress strip, and "Stop all" cancel for in-flight scene renders.** The right column was a single-purpose Storyboard pane with the bibles hidden behind drawer overlays from the work overflow menu — clicking "Refresh Characters" closed the menu and hid the only spinner, so users couldn't tell whether anything was happening. Replaced with a 5-tab sub-nav: **Characters** and **World** render their bibles inline with a top "Refresh from prose" button (with running spinner per-button); **Scenes** is the prose-derived outline (clickable rows jump to that segment in the textarea); **Boards** keeps the existing storyboard scene cards; **Config** consolidates the gear-icon's Adapt LLM picker, World style, and image-gen settings. A status strip ("Refreshing characters…") sits below the tab nav whenever any analysis runs — visible from any tab even after the overflow menu closes. Each tab's icon shows a spinner when its kind is the running one. Adapt auto-jumps to the Boards tab when it starts. Long queues of auto-generated scene images can now be aborted: when one or more scenes are rendering, a banner appears above the cards ("Rendering N scenes…") with a red **Stop all** button — clicking it POSTs `/api/image-gen/cancel { all: true }` (queued cancel before running so the slot doesn't refill mid-loop), then iterates each running scene's imperative ref and calls `cancel()` to roll local state back to idle (idempotent — handles the race where the cancellation `image-gen:failed` socket event arrives first and flips the card to `error`). Per-card unmount cleanup in `onRunningChange` prevents stale entries inflating the count if a scene disappears mid-render. Touched: `client/src/components/writers-room/{StoryboardPanel,WorkEditor,SceneCard,CharactersBible,SettingsBible}.jsx`, `client/src/services/apiImageVideo.js`, `server/routes/imageGen.{js,test.js}`.
+
- **Writers Room — 3-step storyboard setup (Characters → Settings → Adapt) replaces the lone "Run Adapt" CTA.** A fresh story used to greet the user with a single "Run Adapt" button, but Adapt's quality depends on the character + setting bibles being populated first (otherwise the LLM re-improvises descriptions every scene, breaking visual continuity). The empty-state CTA now shows a guided 3-step panel: each step has a status pill (numbered → spinner → green check), its own `Run characters` / `Run settings` / `Run Adapt` button, and a prominent `Run all in order →` master action that fires the sequential pipeline (`runFullPipeline`) so the user can one-click the whole flow. Once Adapt has run, a separate `BiblesMissingNotice` banner shows above the scenes if either bible is empty, with inline "Extract characters" / "Extract settings" buttons — so users who ran Adapt before populating bibles get a clear path to fix the visual drift without leaving the panel. `runAnalysis` now returns success/failure so the pipeline can bail on first error rather than silently chaining through a broken state. Touched: `client/src/components/writers-room/{StoryboardPanel,WorkEditor}.jsx`.
- **Writers Room — setting / world bible (`Refresh settings`) + bibles fed back into Adapt for cross-scene continuity.** New analysis kind `settings` extracts a per-location bible from prose: each entry keyed by screenplay slugline (`INT. CURRY OCITY — NIGHT`) with `description`, `palette`, `era`, `weather`, `recurringDetails`, plus prose evidence + missing-fields hints. Same merge semantics as the character bible — re-runs preserve user edits, only fill blanks, and add new locations. New stage `writers-room-settings` (md prompt + stage-config seed); new service `server/services/writersRoom/settings.js`; new routes `GET/POST /api/writers-room/works/:id/settings`, `PATCH/DELETE /api/writers-room/works/:id/settings/:settingId`; new `SettingsBible.jsx` drawer in WorkEditor with create/edit/delete; new `Refresh settings` menu item. Sluglines normalize identically on client + server (uppercase, em-dash → space, punctuation stripped) so `INT. KITCHEN — NIGHT` and `INT KITCHEN - NIGHT` resolve to the same entry. The script (Adapt) prompt now also receives both bibles as variables (`existingCharactersJson`, `existingSettingsJson`) and is instructed to (a) cite canonical character `physicalDescription` rather than re-improvising and (b) reuse the bible's slugline string verbatim so the storyboard pipeline auto-matches. SceneCard's image-prompt composition now layers the matched setting between world-style and characters: `{worldStyle} . {workTitle} . {setting.description} {setting.palette} {setting.recurring} . Featuring — {chars} . {scene.visualPrompt}` (priority order: visualPrompt always survives, then setting baseline, then characters drop one-by-one to fit the 1900-char budget). End-to-end verified — gemini-2.5-pro extracted 5 locations from a 4,800-word draft in 66s, merged with the user-edited entry, and now feeds image gen for visual continuity across scenes set in the same place. New files: `server/services/writersRoom/settings.js`, `client/src/components/writers-room/SettingsBible.jsx`, `data{,sample}/prompts/stages/writers-room-settings.md`. Touched: `server/lib/{validation,writersRoomPresets}.js`, `server/services/writersRoom/evaluator.js`, `server/routes/writersRoom.js`, `data{,sample}/prompts/{stages/writers-room-script.md,stage-config.json}`, `client/src/{services/apiWritersRoom.js,components/writers-room/{WorkEditor,StoryboardPanel,SceneCard,sceneCardHelpers}.jsx}`.
@@ -34,6 +36,8 @@
## Fixed
+- **Writers Room mobile editor squashed to ~150px (regression).** `WritersRoom`'s `<main>` element had `min-h-0 flex flex-col` with no `flex-1`, so on mobile (below `md:`, where the parent flips to `display: grid`) the main area sized to its natural content height — collapsing the textarea to whatever space was left after the library, header, and tab strip. Added `flex-1` so main grows to fill the remaining viewport on mobile; desktop is unaffected because `md:grid` takes over and the `flex-1` is dormant. Touched: `client/src/pages/WritersRoom.jsx`.
+
- **Collapsed sidebar footer overflow — theme toggle + bell wouldn't fit in the 64px rail.** The footer's two visible icons (ThemeModeToggle ~30px and NotificationDropdown bell ~36px plus a 2px focus-ring offset) summed to ~70–80px side-by-side, blowing out a `lg:w-16` collapsed sidebar that has only 32px of content width after `p-4`. Reduced collapsed-state footer padding to `p-2` (lg only) and stacked the buttons vertically (`lg:flex-col`) so each icon centers in the rail. Expanded layout is unchanged. Touched: `client/src/components/Layout.jsx`.
- **Writers Room mobile prose area squeezed by AI panel.** On mobile/tablet (below `lg`), the editor and AI sidebar stack vertically; the AI sidebar `<aside>` had no flex-grow, so it expanded to its (long) content height — leaving the prose textarea with whatever was left, often only ~150px. Gave the textarea wrapper `flex-[2]` and the AI aside `flex-1` on mobile (both reset at `lg:` where the desktop fixed-width split takes over) so the prose now gets ~2/3 of the available editor height and the AI panel scrolls internally within its 1/3. Touched: `client/src/components/writers-room/WorkEditor.jsx`.
diff --git a/client/src/components/writers-room/CharactersBible.jsx b/client/src/components/writers-room/CharactersBible.jsx
index 8e50fec91e..d83d1e55ec 100644
--- a/client/src/components/writers-room/CharactersBible.jsx
+++ b/client/src/components/writers-room/CharactersBible.jsx
@@ -81,7 +81,7 @@ export default function CharactersBible({ workId, characters: charactersProp, on
{!loading && characters.length === 0 && !creating && (
<div className="text-gray-500 italic px-1 mb-2">
- No profiles yet. Run "Refresh Characters" from the work menu, or add one manually.
+ No profiles yet. Click "Refresh from prose" above to extract them, or add one manually.
</div>
)}
diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsx
index 03078c61f0..1dfa562392 100644
--- a/client/src/components/writers-room/SceneCard.jsx
+++ b/client/src/components/writers-room/SceneCard.jsx
@@ -37,6 +37,7 @@ const SceneCard = forwardRef(function SceneCard({
isActive = false,
onJumpToProse = null,
onDebug = null,
+ onRunningChange = null,
}, ref) {
const light = readingTheme === 'light';
const matchedCharacters = useMemo(
@@ -80,6 +81,14 @@ const SceneCard = forwardRef(function SceneCard({
useClickOutside(debugMenuRef, showDebugMenu, () => setShowDebugMenu(false));
+ useEffect(() => {
+ onRunningChange?.(scene.id, genStatus === 'running');
+ // Unmount cleanup — without this a card that disappears while running
+ // (e.g. scene removed from a re-Adapt) leaves a stale entry in the
+ // parent's running-scene set, which inflates the "Rendering N…" count.
+ return () => onRunningChange?.(scene.id, false);
+ }, [scene.id, genStatus, onRunningChange]);
+
useEffect(() => {
const onStarted = (data) => {
if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;
@@ -174,15 +183,28 @@ const SceneCard = forwardRef(function SceneCard({
}
};
- // Expose generate() to the parent so the storyboard can batch-trigger
- // renders (e.g. auto-queue every missing image after Adapt completes).
+ // Drops jobIdRef so late socket events for the cancelled job are ignored,
+ // and rolls state back to idle (or to the prior image if there was one).
+ // Server-side cancellation is issued in bulk by the parent.
+ const cancelLocal = () => {
+ jobIdRef.current = null;
+ setProgress(null);
+ setError(null);
+ setGenerated(initialImage
+ ? { path: `/data/images/${initialImage.filename}`, jobId: initialImage.jobId, prompt: initialImage.prompt }
+ : null);
+ setGenStatus(initialImage ? 'done' : 'idle');
+ };
+
// canGenerate() returns false for cards that already have an image, are
- // mid-render, or lack a visualPrompt — the parent uses this to skip
- // ineligible scenes silently.
+ // mid-render, or lack a visualPrompt — the parent uses it to skip
+ // ineligible scenes silently when batch-queueing renders after Adapt.
useImperativeHandle(ref, () => ({
generate,
+ cancel: cancelLocal,
canGenerate: () => genStatus === 'idle' && !!scene.visualPrompt?.trim(),
- }), [genStatus, scene.visualPrompt]);
+ isRunning: () => genStatus === 'running',
+ }), [genStatus, scene.visualPrompt, initialImage?.filename]);
const progressPct = progress?.progress != null ? Math.round(progress.progress * 100) : null;
const view = progress?.currentImage ? 'live'
diff --git a/client/src/components/writers-room/SettingsBible.jsx b/client/src/components/writers-room/SettingsBible.jsx
index c4b5652cec..d291dde486 100644
--- a/client/src/components/writers-room/SettingsBible.jsx
+++ b/client/src/components/writers-room/SettingsBible.jsx
@@ -81,7 +81,7 @@ export default function SettingsBible({ workId, settings: settingsProp, onSettin
{!loading && settings.length === 0 && !creating && (
<div className="text-gray-500 italic px-1 mb-2">
- No locations yet. Run "Refresh Settings" from the work menu, or add one manually.
+ No locations yet. Click "Refresh from prose" above to extract them, or add one manually.
</div>
)}
diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsx
index 28d3b533bc..94cea92b95 100644
--- a/client/src/components/writers-room/StoryboardPanel.jsx
+++ b/client/src/components/writers-room/StoryboardPanel.jsx
@@ -1,5 +1,8 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { Clapperboard, Loader2, RefreshCcw, Settings as SettingsIcon, AlertTriangle, Palette, Check, Dice5, Cpu, Users, MapPin as MapPinIcon, ArrowRight } from 'lucide-react';
+import {
+ Clapperboard, Loader2, RefreshCcw, AlertTriangle, Palette, Check, Dice5, Cpu,
+ Users, MapPin as MapPinIcon, ArrowRight, ListTree, SlidersHorizontal, Square,
+} from 'lucide-react';
import { randomSeed } from '../../lib/genUtils';
import toast from '../ui/Toast';
import {
@@ -8,11 +11,13 @@ import {
listWritersRoomStylePresets,
} from '../../services/apiWritersRoom';
import { getSettings, updateSettings } from '../../services/apiSystem';
-import { listImageModels } from '../../services/apiImageVideo';
+import { listImageModels, cancelImageGen } from '../../services/apiImageVideo';
import { timeAgo } from '../../utils/formatters';
import useMounted from '../../hooks/useMounted';
import SceneCard from './SceneCard';
import StagePromptModelPicker from './StagePromptModelPicker';
+import CharactersBible from './CharactersBible';
+import SettingsBible from './SettingsBible';
import {
WR_IMAGE_DEFAULTS,
buildCharByKey,
@@ -24,6 +29,24 @@ import {
const SCRIPT_STAGE = 'writers-room-script';
+export const STORYBOARD_TAB = {
+ CHARACTERS: 'characters',
+ WORLD: 'world',
+ SCENES: 'scenes',
+ BOARDS: 'boards',
+ CONFIG: 'config',
+};
+const TAB = STORYBOARD_TAB;
+export const STORYBOARD_TAB_VALUES = Object.values(TAB);
+
+const RUN_LABEL = {
+ characters: 'Refreshing characters',
+ settings: 'Refreshing world',
+ script: 'Running Adapt',
+ evaluate: 'Editorial pass',
+ format: 'Format pass',
+};
+
export default function StoryboardPanel({
work,
characters = [],
@@ -39,17 +62,22 @@ export default function StoryboardPanel({
readingTheme = 'dark',
activeSceneId = null,
onStyleChange,
+ onCharactersChange,
+ onSettingsChange,
+ tab,
+ onTabChange,
}) {
+ const setTab = onTabChange;
const [latestScript, setLatestScript] = useState(null);
const [latestFailure, setLatestFailure] = useState(null);
const [loading, setLoading] = useState(false);
const [imageCfg, setImageCfg] = useState(WR_IMAGE_DEFAULTS);
const [models, setModels] = useState([]);
- const [showSettings, setShowSettings] = useState(false);
const [stylePresets, setStylePresets] = useState([]);
const mountedRef = useMounted();
const imageStyle = work.imageStyle || EMPTY_IMAGE_STYLE;
+ const activeDraft = (work.drafts || []).find((d) => d.id === work.activeDraftVersionId);
useEffect(() => {
let cancelled = false;
@@ -57,9 +85,9 @@ export default function StoryboardPanel({
getSettings().catch(() => ({})),
listImageModels().catch(() => []),
listWritersRoomStylePresets().catch(() => []),
- ]).then(([settings, modelList, presets]) => {
+ ]).then(([sysSettings, modelList, presets]) => {
if (cancelled) return;
- setImageCfg(readWrImageSettings(settings));
+ setImageCfg(readWrImageSettings(sysSettings));
setModels(Array.isArray(modelList) ? modelList : []);
setStylePresets(Array.isArray(presets) ? presets : []);
});
@@ -115,6 +143,47 @@ export default function StoryboardPanel({
// Map keyed by sceneId — replaced wholesale on each script load.
const sceneRefs = useRef({});
+ // Track which scenes are actively rendering so the Boards tab can show a
+ // "Cancel renders" CTA. SceneCard fires onRunningChange when its local
+ // genStatus toggles. Storing the Set as state (not ref) so the count
+ // re-renders the cancel button reactively.
+ const [runningSceneIds, setRunningSceneIds] = useState(() => new Set());
+ const handleSceneRunningChange = useCallback((sceneId, running) => {
+ setRunningSceneIds((prev) => {
+ const has = prev.has(sceneId);
+ if (running === has) return prev;
+ const next = new Set(prev);
+ if (running) next.add(sceneId);
+ else next.delete(sceneId);
+ return next;
+ });
+ }, []);
+ // Drop stale running-scene entries when the script reloads — old sceneIds
+ // may not exist in the new render.
+ useEffect(() => {
+ setRunningSceneIds(new Set());
+ }, [latestScript?.id]);
+
+ const cancelAllRenders = useCallback(async () => {
+ if (runningSceneIds.size === 0) return;
+ // Issue server cancel first so background work actually stops, then wipe
+ // local state on every running card so the UI returns to idle without
+ // waiting for the cancellation socket events to round-trip.
+ await cancelImageGen({ all: true }).catch((err) => {
+ toast.error(`Cancel failed: ${err.message}`);
+ });
+ // Reset every previously-running card unconditionally — if a
+ // cancellation 'failed' socket event raced ahead and flipped the card to
+ // 'error', isRunning() would return false, but we still want the card
+ // back at idle so the user can retry. cancel() is idempotent.
+ const total = runningSceneIds.size;
+ for (const sceneId of runningSceneIds) {
+ sceneRefs.current[sceneId]?.cancel?.();
+ }
+ setRunningSceneIds(new Set());
+ if (total > 0) toast(`Stopped ${total} render${total === 1 ? '' : 's'}`, { icon: '🛑' });
+ }, [runningSceneIds]);
+
// Auto-queue every missing image when latestScript updates *because* of a
// just-finished Adapt run. requestAnimationFrame defers until the cards
// have actually mounted with the new scenes — useImperativeHandle has to
@@ -125,9 +194,9 @@ export default function StoryboardPanel({
const handle = requestAnimationFrame(() => {
let queued = 0;
for (const sceneId in sceneRefs.current) {
- const handle = sceneRefs.current[sceneId];
- if (handle?.canGenerate?.()) {
- handle.generate();
+ const h = sceneRefs.current[sceneId];
+ if (h?.canGenerate?.()) {
+ h.generate();
queued += 1;
}
}
@@ -136,6 +205,16 @@ export default function StoryboardPanel({
return () => cancelAnimationFrame(handle);
}, [latestScript]);
+ // refresh-characters/settings stay on whichever tab the user is on (they
+ // have their own per-tab spinner); only Adapt yanks them to Boards so the
+ // newly-built storyboard is what they see when it finishes.
+ useEffect(() => {
+ if (runningKind === 'script') setTab(TAB.BOARDS);
+ // setTab intentionally omitted — caller may not memoize it, and the
+ // effect should only fire on runningKind transitions.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [runningKind]);
+
const persistCfg = useCallback(async (next) => {
setImageCfg(next);
const current = await getSettings().catch(() => ({}));
@@ -147,7 +226,10 @@ export default function StoryboardPanel({
const charByKey = useMemo(() => buildCharByKey(characters), [characters]);
const settingByKey = useMemo(() => buildSettingByKey(settings), [settings]);
- const activeDraft = (work.drafts || []).find((d) => d.id === work.activeDraftVersionId);
+ const scenesCount = useMemo(
+ () => (activeDraft?.segmentIndex || []).filter((s) => s.kind === 'scene').length,
+ [activeDraft?.segmentIndex]
+ );
const activeHash = activeDraft?.contentHash || null;
const isStale = !!latestScript?.sourceContentHash && !!activeHash && latestScript.sourceContentHash !== activeHash;
const scenes = latestScript?.result?.scenes || [];
@@ -155,125 +237,422 @@ export default function StoryboardPanel({
return (
<div className="flex flex-col h-full">
- <div className="flex items-center gap-2 px-3 py-2 border-b border-port-border bg-port-bg/40 shrink-0">
- <Clapperboard size={13} className="text-port-accent" />
- <span className="text-[11px] font-semibold text-gray-200 uppercase tracking-wider">Storyboard</span>
- {latestScript && (
- <span className="text-[10px] text-gray-500 truncate">
- {scenes.length} scene{scenes.length === 1 ? '' : 's'} · {timeAgo(latestScript.completedAt || latestScript.createdAt, 'never')}
- </span>
- )}
- {imageStyle.presetId !== STYLE_ID.NONE && (
- <button
- onClick={() => setShowSettings((v) => !v)}
- className="text-port-accent/80 hover:text-port-accent flex items-center gap-1 text-[10px]"
- title="World style applied — click to edit"
- >
- <Palette size={11} /> {styleChip(imageStyle, stylePresets)}
- </button>
- )}
- <button
- onClick={() => setShowSettings((v) => !v)}
- className="ml-auto text-gray-500 hover:text-white"
- title={`Image gen: ${imageCfg.modelId} · ${imageCfg.width}×${imageCfg.height}`}
- aria-label="Image gen settings"
- >
- <SettingsIcon size={12} />
- </button>
- </div>
+ <TabNav
+ tab={tab}
+ setTab={setTab}
+ runningKind={runningKind}
+ charactersCount={characters.length}
+ settingsCount={settings.length}
+ scenesCount={scenesCount}
+ boardsCount={scenes.length}
+ />
- {showSettings && (
- <div className="px-3 py-2 border-b border-port-border bg-port-card/30 shrink-0 space-y-3 max-h-[60vh] overflow-y-auto">
- <StagePromptModelPicker
- stageName={SCRIPT_STAGE}
- label="Adapt LLM"
- icon={<Cpu size={10} />}
- hint="Used when you click Run Adapt to break prose into scenes."
- />
- <WorldStyleRow
- value={imageStyle}
- presets={stylePresets}
- onChange={onStyleChange}
- />
- <ImageGenSettingsRow cfg={imageCfg} models={models} onChange={persistCfg} />
+ {runningKind && (
+ <div className="px-3 py-1.5 border-b border-port-border bg-port-accent/10 text-[11px] text-port-accent flex items-center gap-2 shrink-0">
+ <Loader2 size={11} className="animate-spin" />
+ <span>{RUN_LABEL[runningKind] || runningKind}…</span>
</div>
)}
- <div className="flex-1 overflow-y-auto px-3 py-3 space-y-2">
- {loading && (
- <div className="flex items-center justify-center text-[11px] text-gray-500 gap-2 py-6">
- <Loader2 size={14} className="animate-spin" /> Loading storyboard…
- </div>
+ <div className="flex-1 overflow-y-auto">
+ {tab === TAB.CHARACTERS && (
+ <BibleTab
+ kind="characters"
+ workId={work.id}
+ items={characters}
+ onItemsChange={onCharactersChange}
+ onRefresh={onRunCharacters}
+ running={runningKind === 'characters'}
+ anyRunning={!!runningKind}
+ readingTheme={readingTheme}
+ />
)}
-
- {!loading && latestFailure && (
- <FailedAdaptBanner
- failure={latestFailure}
- onRunAdapt={onRunAdapt}
- runningAdapt={runningAdapt}
- onOpenSettings={() => setShowSettings(true)}
- hasPriorScript={!!latestScript}
+ {tab === TAB.WORLD && (
+ <BibleTab
+ kind="world"
+ workId={work.id}
+ items={settings}
+ onItemsChange={onSettingsChange}
+ onRefresh={onRunSettings}
+ running={runningKind === 'settings'}
+ anyRunning={!!runningKind}
+ readingTheme={readingTheme}
/>
)}
-
- {!loading && !latestScript && !latestFailure && (
- <StoryboardSetup
+ {tab === TAB.SCENES && (
+ <ScenesTab activeDraft={activeDraft} onJumpToScene={onJumpToScene} />
+ )}
+ {tab === TAB.BOARDS && (
+ <BoardsTab
+ work={work}
+ scenes={scenes}
+ sceneImages={sceneImages}
+ latestScript={latestScript}
+ latestFailure={latestFailure}
+ loading={loading}
+ isStale={isStale}
+ imageCfg={imageCfg}
+ imageStyle={imageStyle}
+ stylePresets={stylePresets}
+ charByKey={charByKey}
+ settingByKey={settingByKey}
charactersCount={characters.length}
settingsCount={settings.length}
+ sceneRefs={sceneRefs}
+ onJumpToScene={onJumpToScene}
+ onDebug={onDebug}
+ onSceneRunningChange={handleSceneRunningChange}
+ onRunAdapt={onRunAdapt}
onRunCharacters={onRunCharacters}
onRunSettings={onRunSettings}
- onRunAdapt={onRunAdapt}
onRunFullPipeline={onRunFullPipeline}
+ runningAdapt={runningAdapt}
runningKind={runningKind}
+ readingTheme={readingTheme}
+ activeSceneId={activeSceneId}
+ onOpenConfig={() => setTab(TAB.CONFIG)}
+ runningRenderCount={runningSceneIds.size}
+ onCancelRenders={cancelAllRenders}
/>
)}
-
- {!loading && latestScript && isStale && !latestFailure && (
- <StaleBanner onRunAdapt={onRunAdapt} runningAdapt={runningAdapt} />
- )}
-
- {!loading && latestScript && !isStale && !latestFailure && (characters.length === 0 || settings.length === 0) && (
- <BiblesMissingNotice
- charactersMissing={characters.length === 0}
- settingsMissing={settings.length === 0}
- onRunCharacters={onRunCharacters}
- onRunSettings={onRunSettings}
- runningKind={runningKind}
+ {tab === TAB.CONFIG && (
+ <ConfigTab
+ imageCfg={imageCfg}
+ models={models}
+ onCfgChange={persistCfg}
+ stylePresets={stylePresets}
+ imageStyle={imageStyle}
+ onStyleChange={onStyleChange}
/>
)}
+ </div>
+ </div>
+ );
+}
- {!loading && latestScript && scenes.length === 0 && (
- <div className="text-[11px] text-gray-500 italic px-1">
- Adapt finished but produced no scenes. Try adding `## Scene` headings to your prose, then re-run.
- </div>
- )}
+function TabNav({
+ tab,
+ setTab,
+ runningKind,
+ charactersCount,
+ settingsCount,
+ scenesCount,
+ boardsCount,
+}) {
+ const tabs = [
+ { id: TAB.CHARACTERS, label: 'Characters', icon: Users, count: charactersCount, runningWhen: 'characters' },
+ { id: TAB.WORLD, label: 'World', icon: MapPinIcon, count: settingsCount, runningWhen: 'settings' },
+ { id: TAB.SCENES, label: 'Scenes', icon: ListTree, count: scenesCount, runningWhen: null },
+ { id: TAB.BOARDS, label: 'Boards', icon: Clapperboard, count: boardsCount, runningWhen: 'script' },
+ { id: TAB.CONFIG, label: 'Config', icon: SlidersHorizontal, count: null, runningWhen: null },
+ ];
+ return (
+ <div className="flex items-stretch border-b border-port-border bg-port-bg/40 shrink-0 overflow-x-auto">
+ {tabs.map((t) => {
+ const active = t.id === tab;
+ const running = runningKind && t.runningWhen === runningKind;
+ const Icon = t.icon;
+ return (
+ <button
+ key={t.id}
+ type="button"
+ onClick={() => setTab(t.id)}
+ className={`flex-1 min-w-0 flex items-center justify-center gap-1 px-2 py-2 text-[11px] border-b-2 transition-colors ${
+ active
+ ? 'border-port-accent text-white bg-port-card/40'
+ : 'border-transparent text-gray-500 hover:text-gray-200 hover:bg-port-card/20'
+ }`}
+ title={t.label}
+ aria-pressed={active}
+ >
+ {running
+ ? <Loader2 size={11} className="animate-spin text-port-accent shrink-0" />
+ : <Icon size={11} className="shrink-0" />
+ }
+ <span className="truncate">{t.label}</span>
+ {t.count != null && t.count > 0 && (
+ <span className={`text-[9px] px-1 rounded ${active ? 'text-gray-400' : 'text-gray-600'}`}>
+ {t.count}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
- {!loading && scenes.map((scene, i) => {
- const sceneId = scene.id || `scene-${i}`;
- return (
- <SceneCard
- key={sceneId}
- ref={(handle) => {
- if (handle) sceneRefs.current[sceneId] = handle;
- else delete sceneRefs.current[sceneId];
- }}
- scene={{ ...scene, id: sceneId }}
- workId={work.id}
- analysisId={latestScript.id}
- workTitle={work.title}
- imageCfg={imageCfg}
- imageStyle={imageStyle}
- initialImage={sceneImages[sceneId] || null}
- readingTheme={readingTheme}
- charByKey={charByKey}
- settingByKey={settingByKey}
- isActive={sceneId === activeSceneId}
- onJumpToProse={onJumpToScene ? () => onJumpToScene(scene, i, scenes.length) : null}
- onDebug={onDebug}
- />
- );
- })}
+const BIBLE_KINDS = {
+ characters: {
+ label: 'Character bible',
+ sub: 'Persisted across runs · feeds image-gen prompts',
+ refreshNoun: 'characters',
+ Component: CharactersBible,
+ propName: 'characters',
+ changeProp: 'onCharactersChange',
+ },
+ world: {
+ label: 'World / setting bible',
+ sub: 'Locations keyed by slugline · feeds image-gen prompts',
+ refreshNoun: 'world',
+ Component: SettingsBible,
+ propName: 'settings',
+ changeProp: 'onSettingsChange',
+ },
+};
+
+function BibleTab({ kind, workId, items, onItemsChange, onRefresh, running, anyRunning, readingTheme }) {
+ const meta = BIBLE_KINDS[kind];
+ const Bible = meta.Component;
+ const bibleProps = {
+ workId,
+ [meta.propName]: items,
+ [meta.changeProp]: onItemsChange,
+ readingTheme,
+ };
+ return (
+ <div className="px-3 py-3 space-y-3">
+ <RefreshHeader
+ noun={meta.refreshNoun}
+ label={meta.label}
+ sub={meta.sub}
+ running={running}
+ anyRunning={anyRunning}
+ onRefresh={onRefresh}
+ empty={items.length === 0}
+ />
+ <Bible {...bibleProps} />
+ </div>
+ );
+}
+
+function RefreshHeader({ noun, label, sub, running, anyRunning, onRefresh, empty }) {
+ return (
+ <div className="flex items-start justify-between gap-2 pb-2 border-b border-port-border">
+ <div className="min-w-0">
+ <div className="text-[12px] font-semibold text-gray-200">{label}</div>
+ <div className="text-[10px] text-gray-500">{sub}</div>
+ </div>
+ <button
+ type="button"
+ onClick={onRefresh}
+ disabled={anyRunning || !onRefresh}
+ className="shrink-0 flex items-center gap-1 px-2 py-1 text-[10px] rounded bg-port-bg border border-port-border text-gray-300 hover:bg-port-card hover:text-white disabled:opacity-50 disabled:cursor-not-allowed"
+ title={empty ? `Extract ${noun} from prose` : `Re-extract ${noun} from prose (merges into existing)`}
+ >
+ {running
+ ? <Loader2 size={10} className="animate-spin text-port-accent" />
+ : <RefreshCcw size={10} />
+ }
+ {running ? 'Refreshing…' : empty ? 'Extract from prose' : 'Refresh from prose'}
+ </button>
+ </div>
+ );
+}
+
+// ─── Scenes (outline from prose headings) ─────────────────────────────────
+function ScenesTab({ activeDraft, onJumpToScene }) {
+ const segs = activeDraft?.segmentIndex || [];
+ if (segs.length === 0) {
+ return (
+ <div className="px-3 py-3 text-[11px] text-gray-500 italic">
+ No segments yet. Use <code className="text-gray-300"># Chapter</code> /{' '}
+ <code className="text-gray-300">## Scene</code> /{' '}
+ <code className="text-gray-300">### Beat</code> headings in your prose to populate the outline.
</div>
+ );
+ }
+ return (
+ <ul className="px-3 py-3 space-y-1 text-[11px]">
+ {segs.map((seg) => {
+ const indent = seg.kind === 'beat' ? 'pl-4' : seg.kind === 'scene' ? 'pl-2' : '';
+ const tone = seg.kind === 'chapter' ? 'text-white font-semibold' : seg.kind === 'scene' ? 'text-gray-200' : 'text-gray-500';
+ return (
+ <li key={seg.id} className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={onJumpToScene ? () => onJumpToScene({ heading: seg.heading }) : undefined}
+ disabled={!onJumpToScene}
+ className={`flex-1 truncate text-left hover:text-port-accent disabled:hover:text-inherit ${indent} ${tone}`}
+ title={onJumpToScene ? 'Jump to this segment in the prose' : seg.heading}
+ >
+ {seg.heading}
+ </button>
+ <span className="text-[9px] text-gray-600 shrink-0">{seg.wordCount}w</span>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
+// ─── Boards (storyboard scene cards) ──────────────────────────────────────
+function BoardsTab({
+ work,
+ scenes,
+ sceneImages,
+ latestScript,
+ latestFailure,
+ loading,
+ isStale,
+ imageCfg,
+ imageStyle,
+ stylePresets,
+ charByKey,
+ settingByKey,
+ charactersCount,
+ settingsCount,
+ sceneRefs,
+ onJumpToScene,
+ onDebug,
+ onSceneRunningChange,
+ onRunAdapt,
+ onRunCharacters,
+ onRunSettings,
+ onRunFullPipeline,
+ runningAdapt,
+ runningKind,
+ readingTheme,
+ activeSceneId,
+ onOpenConfig,
+ runningRenderCount = 0,
+ onCancelRenders,
+}) {
+ return (
+ <div className="px-3 py-3 space-y-2">
+ {runningRenderCount > 0 && (
+ <div className="flex items-center justify-between gap-2 px-2.5 py-1.5 mb-1 border border-port-warning/40 bg-port-warning/5 rounded text-[11px]">
+ <div className="flex items-center gap-2 min-w-0">
+ <Loader2 size={11} className="animate-spin text-port-warning shrink-0" />
+ <span className="text-port-warning truncate">
+ Rendering {runningRenderCount} scene{runningRenderCount === 1 ? '' : 's'}…
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={onCancelRenders}
+ className="shrink-0 flex items-center gap-1 px-2 py-1 bg-port-error/15 border border-port-error/40 text-port-error rounded text-[10px] hover:bg-port-error/25"
+ title="Cancel every queued and in-flight scene render"
+ >
+ <Square size={10} /> Stop all
+ </button>
+ </div>
+ )}
+ {latestScript && (
+ <div className="flex items-center gap-2 pb-2 text-[10px] text-gray-500">
+ <span>{scenes.length} scene{scenes.length === 1 ? '' : 's'} · {timeAgo(latestScript.completedAt || latestScript.createdAt, 'never')}</span>
+ {imageStyle.presetId !== STYLE_ID.NONE && (
+ <button
+ type="button"
+ onClick={onOpenConfig}
+ className="text-port-accent/80 hover:text-port-accent flex items-center gap-1"
+ title="World style applied — click to edit in Config"
+ >
+ <Palette size={10} /> {styleChip(imageStyle, stylePresets)}
+ </button>
+ )}
+ </div>
+ )}
+
+ {loading && (
+ <div className="flex items-center justify-center text-[11px] text-gray-500 gap-2 py-6">
+ <Loader2 size={14} className="animate-spin" /> Loading storyboard…
+ </div>
+ )}
+
+ {!loading && latestFailure && (
+ <FailedAdaptBanner
+ failure={latestFailure}
+ onRunAdapt={onRunAdapt}
+ runningAdapt={runningAdapt}
+ onOpenConfig={onOpenConfig}
+ hasPriorScript={!!latestScript}
+ />
+ )}
+
+ {!loading && !latestScript && !latestFailure && (
+ <StoryboardSetup
+ charactersCount={charactersCount}
+ settingsCount={settingsCount}
+ onRunCharacters={onRunCharacters}
+ onRunSettings={onRunSettings}
+ onRunAdapt={onRunAdapt}
+ onRunFullPipeline={onRunFullPipeline}
+ runningKind={runningKind}
+ />
+ )}
+
+ {!loading && latestScript && isStale && !latestFailure && (
+ <StaleBanner onRunAdapt={onRunAdapt} runningAdapt={runningAdapt} />
+ )}
+
+ {!loading && latestScript && !isStale && !latestFailure && (charactersCount === 0 || settingsCount === 0) && (
+ <BiblesMissingNotice
+ charactersMissing={charactersCount === 0}
+ settingsMissing={settingsCount === 0}
+ onRunCharacters={onRunCharacters}
+ onRunSettings={onRunSettings}
+ runningKind={runningKind}
+ />
+ )}
+
+ {!loading && latestScript && scenes.length === 0 && (
+ <div className="text-[11px] text-gray-500 italic px-1">
+ Adapt finished but produced no scenes. Try adding `## Scene` headings to your prose, then re-run.
+ </div>
+ )}
+
+ {!loading && scenes.map((scene, i) => {
+ const sceneId = scene.id || `scene-${i}`;
+ return (
+ <SceneCard
+ key={sceneId}
+ ref={(handle) => {
+ if (handle) sceneRefs.current[sceneId] = handle;
+ else delete sceneRefs.current[sceneId];
+ }}
+ scene={{ ...scene, id: sceneId }}
+ workId={work.id}
+ analysisId={latestScript.id}
+ workTitle={work.title}
+ imageCfg={imageCfg}
+ imageStyle={imageStyle}
+ initialImage={sceneImages[sceneId] || null}
+ readingTheme={readingTheme}
+ charByKey={charByKey}
+ settingByKey={settingByKey}
+ isActive={sceneId === activeSceneId}
+ onJumpToProse={onJumpToScene ? () => onJumpToScene(scene, i, scenes.length) : null}
+ onDebug={onDebug}
+ onRunningChange={onSceneRunningChange}
+ />
+ );
+ })}
+ </div>
+ );
+}
+
+// ─── Config (image gen + style + Adapt LLM) ───────────────────────────────
+function ConfigTab({ imageCfg, models, onCfgChange, stylePresets, imageStyle, onStyleChange }) {
+ return (
+ <div className="px-3 py-3 space-y-4">
+ <section className="space-y-1.5">
+ <div className="text-[12px] font-semibold text-gray-200">Adapt LLM</div>
+ <StagePromptModelPicker
+ stageName={SCRIPT_STAGE}
+ label="Adapt LLM"
+ icon={<Cpu size={10} />}
+ hint="Used when you click Run Adapt to break prose into scenes."
+ />
+ </section>
+ <section className="space-y-1.5 pt-3 border-t border-port-border">
+ <div className="text-[12px] font-semibold text-gray-200">World style</div>
+ <WorldStyleRow value={imageStyle} presets={stylePresets} onChange={onStyleChange} />
+ </section>
+ <section className="space-y-1.5 pt-3 border-t border-port-border">
+ <div className="text-[12px] font-semibold text-gray-200">Image generation</div>
+ <ImageGenSettingsRow cfg={imageCfg} models={models} onChange={onCfgChange} />
+ </section>
</div>
);
}
@@ -340,7 +719,7 @@ function StoryboardSetup({
};
return (
- <div className="px-3 py-4 space-y-3">
+ <div className="px-1 py-1 space-y-3">
<div className="text-center space-y-1">
<Clapperboard size={24} className="mx-auto text-gray-600" />
<div className="text-[12px] text-gray-300 font-medium">No storyboard yet</div>
@@ -393,14 +772,14 @@ function StoryboardSetup({
{(charDone || setDone) && (
<div className="text-[10px] text-gray-500 text-center">
- Tip: edit either bible in the Work overflow menu before running Adapt.
+ Tip: edit either bible in its tab above before running Adapt.
</div>
)}
</div>
);
}
-function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenSettings, hasPriorScript }) {
+function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenConfig, hasPriorScript }) {
const error = failure?.error || 'Adapt failed for an unknown reason';
const isTimeout = /timed out/i.test(error);
return (
@@ -413,7 +792,7 @@ function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenSettings,
{isTimeout && (
<div className="text-gray-500 mt-1">
Long drafts are heavy for small/light models — try a faster model
- (e.g. an API provider) via the gear icon.
+ (e.g. an API provider) in the Config tab.
</div>
)}
{!hasPriorScript && (
@@ -425,10 +804,10 @@ function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenSettings,
</div>
<div className="flex gap-2 justify-end">
<button
- onClick={onOpenSettings}
+ onClick={onOpenConfig}
className="flex items-center gap-1 px-2 py-1 border border-port-border text-gray-300 rounded text-[10px] hover:bg-port-border/40"
>
- <SettingsIcon size={10} /> Adjust LLM
+ <SlidersHorizontal size={10} /> Adjust LLM
</button>
<button
onClick={onRunAdapt}
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index 30201b2aee..b12cff8f7d 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -10,7 +10,6 @@ import {
FileSignature,
Users,
MapPin,
- ListTree,
Clock,
History,
Timer,
@@ -33,13 +32,11 @@ import {
} from '../../services/apiWritersRoom';
import { STATUS_LABELS } from './labels';
import { countWords } from '../../utils/formatters';
-import StoryboardPanel from './StoryboardPanel';
-import CharactersBible from './CharactersBible';
-import SettingsBible from './SettingsBible';
+import StoryboardPanel, { STORYBOARD_TAB, STORYBOARD_TAB_VALUES } from './StoryboardPanel';
import AnalysisHistory from './AnalysisHistory';
const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', SETTINGS: 'settings', EVALUATE: 'evaluate', FORMAT: 'format' };
-const DRAWER = { OUTLINE: 'outline', VERSIONS: 'versions', CHARACTERS: 'characters', SETTINGS: 'settings', HISTORY: 'history' };
+const DRAWER = { VERSIONS: 'versions', HISTORY: 'history' };
const MOBILE_TAB = { WRITING: 'writing', STORYBOARD: 'storyboard' };
const ANALYSIS_LABELS = {
@@ -55,6 +52,7 @@ const SIDEBAR_DEFAULT = 480;
const SIDEBAR_MIN = 320;
const SIDEBAR_MAX_FRACTION = 0.6;
const READING_THEME_KEY = 'wr.readingTheme';
+const SIDEBAR_TAB_KEY = 'wr.sidebarTab';
function readReadingTheme() {
if (typeof window === 'undefined') return 'dark';
@@ -72,6 +70,12 @@ function persistSidebarWidth(width) {
try { window.localStorage.setItem(SIDEBAR_WIDTH_KEY, String(Math.round(width))); } catch {}
}
+function readSidebarTab() {
+ if (typeof window === 'undefined') return STORYBOARD_TAB.BOARDS;
+ const stored = window.localStorage.getItem(SIDEBAR_TAB_KEY);
+ return STORYBOARD_TAB_VALUES.includes(stored) ? stored : STORYBOARD_TAB.BOARDS;
+}
+
export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOpen }) {
const [body, setBody] = useState(work.activeDraftBody || '');
const [title, setTitle] = useState(work.title);
@@ -88,6 +92,11 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const [overflowOpen, setOverflowOpen] = useState(false);
const [mobileTab, setMobileTab] = useState(MOBILE_TAB.WRITING);
const [activeSceneId, setActiveSceneId] = useState(null);
+ const [sidebarTab, setSidebarTab] = useState(readSidebarTab);
+
+ useEffect(() => {
+ try { window.localStorage.setItem(SIDEBAR_TAB_KEY, sidebarTab); } catch { /* sandboxed storage */ }
+ }, [sidebarTab]);
const textareaRef = useRef(null);
const overflowRef = useRef(null);
@@ -323,10 +332,13 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
}, [body]);
// Per-scene Debug menu actions — until scoped tools land, route to the
- // most relevant drawer.
+ // most relevant tab/drawer.
const handleDebug = useCallback(({ kind, scene }) => {
if (scene) setActiveSceneId(scene.id || null);
- if (kind === 'check-characters') setDrawer(DRAWER.CHARACTERS);
+ if (kind === 'check-characters') {
+ setSidebarTab(STORYBOARD_TAB.CHARACTERS);
+ setMobileTab(MOBILE_TAB.STORYBOARD);
+ }
else if (kind === 'editorial') setDrawer(DRAWER.HISTORY);
else if (kind === 'why-image') setDrawer(DRAWER.HISTORY);
}, []);
@@ -442,10 +454,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} />
</MenuSection>
<MenuSection label="Open">
- <MenuItem icon={ListTree} label="Outline" onClick={closeOverflowAnd(() => setDrawer(DRAWER.OUTLINE))} />
<MenuItem icon={Clock} label="Versions" onClick={closeOverflowAnd(() => setDrawer(DRAWER.VERSIONS))} />
- <MenuItem icon={Users} label="Characters" badge={characters.length || null} onClick={closeOverflowAnd(() => setDrawer(DRAWER.CHARACTERS))} />
- <MenuItem icon={MapPin} label="Settings" badge={settings.length || null} onClick={closeOverflowAnd(() => setDrawer(DRAWER.SETTINGS))} />
<MenuItem icon={History} label="Analysis history" onClick={closeOverflowAnd(() => setDrawer(DRAWER.HISTORY))} />
</MenuSection>
<MenuSection label="View">
@@ -520,6 +529,8 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
work={work}
characters={characters}
settings={settings}
+ onCharactersChange={setCharacters}
+ onSettingsChange={setSettings}
onJumpToScene={jumpToScene}
onDebug={handleDebug}
onRunAdapt={() => runAnalysis(ANALYSIS_KIND.SCRIPT)}
@@ -531,32 +542,15 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
readingTheme={readingTheme}
activeSceneId={activeSceneId}
onStyleChange={commitImageStyle}
+ tab={sidebarTab}
+ onTabChange={setSidebarTab}
/>
</aside>
</div>
- <Drawer open={drawer === DRAWER.OUTLINE} onClose={() => setDrawer(null)} title="Outline">
- <OutlineList activeDraft={activeDraft} />
- </Drawer>
<Drawer open={drawer === DRAWER.VERSIONS} onClose={() => setDrawer(null)} title="Versions">
<VersionsList work={work} dirty={dirty} onSwitch={(id) => { switchToDraft(id); setDrawer(null); }} />
</Drawer>
- <Drawer open={drawer === DRAWER.CHARACTERS} onClose={() => setDrawer(null)} title="Characters">
- <CharactersBible
- workId={work.id}
- characters={characters}
- onCharactersChange={setCharacters}
- readingTheme={readingTheme}
- />
- </Drawer>
- <Drawer open={drawer === DRAWER.SETTINGS} onClose={() => setDrawer(null)} title="Settings (locations / world bible)">
- <SettingsBible
- workId={work.id}
- settings={settings}
- onSettingsChange={setSettings}
- readingTheme={readingTheme}
- />
- </Drawer>
<Drawer open={drawer === DRAWER.HISTORY} onClose={() => setDrawer(null)} title="Analysis history">
<AnalysisHistory work={work} activeHash={activeHash} onApplyFormat={applyFormatText} />
</Drawer>
@@ -606,29 +600,6 @@ function MobileTab({ active, onClick, icon: Icon, label }) {
);
}
-function OutlineList({ activeDraft }) {
- const segs = activeDraft?.segmentIndex || [];
- if (segs.length === 0) {
- return (
- <div className="text-xs text-gray-500 italic">
- No segments yet. Use # Chapter / ## Scene / ### Beat headings in the prose to populate the outline.
- </div>
- );
- }
- return (
- <ul className="space-y-1 text-xs">
- {segs.map((seg) => (
- <li key={seg.id} className="flex items-center gap-2 text-gray-400">
- <span className={`flex-1 truncate ${seg.kind === 'chapter' ? 'text-white font-semibold' : seg.kind === 'scene' ? 'text-gray-300' : 'pl-3 text-gray-500'}`}>
- {seg.heading}
- </span>
- <span className="text-[10px] text-gray-600">{seg.wordCount}w</span>
- </li>
- ))}
- </ul>
- );
-}
-
function VersionsList({ work, dirty, onSwitch }) {
const drafts = (work.drafts || []).slice().reverse();
if (drafts.length === 0) {
diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsx
index 004fb9304f..5743e5c627 100644
--- a/client/src/pages/WritersRoom.jsx
+++ b/client/src/pages/WritersRoom.jsx
@@ -152,7 +152,7 @@ export default function WritersRoom() {
</aside>
)}
- <main className="min-h-0 flex flex-col">
+ <main className="min-h-0 flex flex-col flex-1">
{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">
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 2167398b33..53ac35ea17 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -7,7 +7,13 @@ export const listImageModels = () => request('/image-gen/models');
export const listLoras = () => request('/image-gen/loras');
export const listImageGallery = () => request('/image-gen/gallery');
export const getActiveImageJob = () => request('/image-gen/active');
-export const cancelImageGen = () => request('/image-gen/cancel', { method: 'POST' });
+// cancelImageGen({ all: true }) cancels every queued/running image job.
+// cancelImageGen({ jobId }) cancels a specific job. Plain cancelImageGen()
+// cancels the most-recent queued/running job (legacy behavior).
+export const cancelImageGen = (opts = {}) => request('/image-gen/cancel', {
+ method: 'POST',
+ body: JSON.stringify(opts),
+});
export const deleteImage = (filename) => request(`/image-gen/${encodeURIComponent(filename)}`, { method: 'DELETE' });
export const setImageHidden = (filename, hidden) => request(`/image-gen/${encodeURIComponent(filename)}/visibility`, {
method: 'POST',
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 95c6fb94fe..5487804204 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -227,16 +227,33 @@ router.get('/:jobId/events', (req, res) => {
router.post('/cancel', asyncHandler(async (req, res) => {
// Cancel selection rules, in priority order:
- // 1. Explicit body.jobId — cancel that queued/running local image job.
+ // 1. body.all === true — cancel every queued/running image job. Used by
+ // the writers-room storyboard "Cancel renders" CTA, which can have
+ // 20+ scene renders in flight at once.
+ // 2. Explicit body.jobId — cancel that queued/running local image job.
// Required for users with multiple in-flight renders.
- // 2. No jobId — cancel the newest queued/running local image job (most
+ // 3. No jobId — cancel the newest queued/running local image job (most
// recent activity wins, matching the user's last "submit" gesture).
- // 3. No queue match — fall through to the codex-mode cancel.
+ // 4. No queue match — fall through to the codex-mode cancel.
const requestedJobId = typeof req.body?.jobId === 'string' && req.body.jobId.trim()
? req.body.jobId.trim()
: undefined;
const cancellable = listJobs({ kind: 'image' })
.filter((j) => j.status === 'queued' || j.status === 'running');
+ if (req.body?.all === true) {
+ // Cancel queued first so the running job's slot doesn't get refilled the
+ // moment we cancel it. Settle individually so one stale job doesn't
+ // block the rest. cancellable is already a fresh filter() result.
+ const ordered = cancellable.sort((a, b) => {
+ if (a.status === b.status) return 0;
+ return a.status === 'queued' ? -1 : 1;
+ });
+ const results = await Promise.all(ordered.map((j) => cancelJob(j.id).catch((err) => ({ ok: false, error: err.message }))));
+ // Belt-and-braces: also poke the legacy single-process cancel so any
+ // in-flight gen outside the queue (codex sync mode) gets stopped.
+ imageGen.cancel();
+ return res.json({ ok: true, canceled: results.filter((r) => r?.ok).length, attempted: results.length });
+ }
if (requestedJobId) {
const target = cancellable.find((j) => j.id === requestedJobId);
if (target) return res.json(await cancelJob(target.id));
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index fe5fa91e37..35ed40f012 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -257,5 +257,22 @@ describe('Image Gen Routes', () => {
expect(response.status).toBe(200);
expect(response.body.ok).toBe(true);
});
+
+ it('POST /cancel { all: true } cancels every queued/running image job', async () => {
+ mediaJobQueue.listJobs.mockReturnValueOnce([
+ { id: 'a', status: 'running' },
+ { id: 'b', status: 'queued' },
+ { id: 'c', status: 'queued' },
+ ]);
+ const response = await request(app).post('/api/image-gen/cancel').send({ all: true });
+ expect(response.status).toBe(200);
+ expect(response.body.ok).toBe(true);
+ expect(response.body.attempted).toBe(3);
+ expect(mediaJobQueue.cancelJob).toHaveBeenCalledTimes(3);
+ // Queued jobs cancelled before the running one — slot doesn't refill mid-loop.
+ expect(mediaJobQueue.cancelJob.mock.calls.map((c) => c[0])).toEqual(['b', 'c', 'a']);
+ // Belt-and-braces: legacy single-process cancel also poked.
+ expect(imageGen.cancel).toHaveBeenCalled();
+ });
});
});