Skip to content

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

feat([issue-841]): live render previews on the scene at the cursor in Writers Room

[._.]/ Adam Eivyb6c3344316ad
diff --git a/client/src/components/writers-room/LiveRenderPanel.jsx b/client/src/components/writers-room/LiveRenderPanel.jsx
new file mode 100644
index 0000000000..ad321625c8
--- /dev/null
+++ b/client/src/components/writers-room/LiveRenderPanel.jsx
@@ -0,0 +1,219 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { ImagePlus, Loader2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import { generateImage } from '../../services/apiSystem';
+import {
+ attachWritersRoomSceneImage,
+ reserveWritersRoomRenderPreview,
+} from '../../services/apiWritersRoom';
+import socket from '../../services/socket';
+import useMounted from '../../hooks/useMounted';
+import { WR_IMAGE_DEFAULTS, buildSceneRenderPayload } from '../../lib/wrImageDefaults';
+import { sceneAtCursor } from '../../lib/wrSceneCursor';
+import {
+ buildScenePrompt,
+ matchSceneCharacters,
+ matchScenePlace,
+} from '../../lib/scenePrompt';
+
+// Phase 5 live render preview. While the work has live mode opted in, the
+// writer can trigger a quick reference render for the scene their cursor sits
+// in — reusing the existing image-gen route (`generateImage`) and the shared
+// image-gen socket queue (registered via `registerQueue` so the render dock
+// labels + tracks it exactly like a storyboard render). A DISTINCT per-work
+// daily render budget (separate from the text-suggest budget) is enforced
+// server-side: we reserve a slot first, and only kick the render off if the
+// reservation succeeds. On completion the image is persisted onto the script
+// analysis via the same `scene-image` attach path the storyboard uses.
+//
+// Like LiveContinuationPanel this is a presentation + fetch shell: WorkEditor
+// owns the textarea/cursor and the scene/analysis context, and feeds them in.
+export default function LiveRenderPanel({
+ workId,
+ liveMode,
+ getCursorOffset,
+ body,
+ renderContext,
+ registerQueue,
+ workTitle,
+}) {
+ const [reserving, setReserving] = useState(false);
+ const [notice, setNotice] = useState(null);
+ // Local render-usage so a fresh reservation updates the "N left today"
+ // readout immediately; re-synced from the prop on a parent-driven change
+ // (budget edit, work swap) so it isn't shadowed.
+ const [renderUsage, setRenderUsage] = useState(liveMode?.renderUsage || null);
+ useEffect(() => { setRenderUsage(liveMode?.renderUsage || null); }, [liveMode?.renderUsage]);
+ const mountedRef = useMounted();
+
+ // Track the live job so late socket events for a superseded/cancelled render
+ // are ignored, mirroring SceneCard. `sceneIdRef` remembers which scene the
+ // in-flight job renders so onCompleted can attach without re-resolving the
+ // (possibly moved) cursor.
+ const jobIdRef = useRef(null);
+ const sceneIdRef = useRef(null);
+ const [genStatus, setGenStatus] = useState('idle');
+
+ // Stabilize the derived context so it doesn't re-create the render callback's
+ // deps on every parent render (renderContext is a fresh object each time).
+ const ctx = useMemo(() => renderContext || {}, [renderContext]);
+ const analysisId = ctx.analysisId || null;
+ const scenes = useMemo(() => (Array.isArray(ctx.scenes) ? ctx.scenes : []), [ctx.scenes]);
+ const imageCfg = ctx.imageCfg || WR_IMAGE_DEFAULTS;
+
+ // Resolve the scene under the caret so the button can name its target (and
+ // disable when there's nothing to render). Recomputed cheaply on each render;
+ // the caret read happens lazily inside the click handler so this is just for
+ // the label/enabled state on the latest known offset.
+ const [cursorOffset, setCursorOffset] = useState(null);
+ const target = sceneAtCursor(scenes, body, cursorOffset);
+
+ useEffect(() => {
+ const onCompleted = (data) => {
+ if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;
+ const completedJobId = jobIdRef.current;
+ const sceneId = sceneIdRef.current;
+ jobIdRef.current = null;
+ sceneIdRef.current = null;
+ if (mountedRef.current) setGenStatus('idle');
+ // Persist onto the analysis snapshot + the work's auto media-collection,
+ // exactly like SceneCard. Best-effort — a failed persist still leaves the
+ // render in the queue/dock and the collection.
+ if (workId && analysisId && completedJobId && sceneId) {
+ attachWritersRoomSceneImage(workId, analysisId, {
+ sceneId,
+ filename: `${completedJobId}.png`,
+ jobId: completedJobId,
+ prompt: data.prompt || null,
+ }).catch((err) => {
+ console.warn(`live render persist failed: ${err.message}`);
+ });
+ }
+ };
+ const onFailed = (data) => {
+ if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;
+ jobIdRef.current = null;
+ sceneIdRef.current = null;
+ if (mountedRef.current) setGenStatus('idle');
+ };
+ socket.on('image-gen:completed', onCompleted);
+ socket.on('image-gen:failed', onFailed);
+ return () => {
+ socket.off('image-gen:completed', onCompleted);
+ socket.off('image-gen:failed', onFailed);
+ };
+ // sceneId comes from sceneIdRef (set when we kicked the job off), so this
+ // effect only needs the persist target inputs.
+ }, [workId, analysisId, mountedRef]);
+
+ const renderCursorScene = useCallback(async () => {
+ if (reserving || genStatus === 'running') return;
+ const offset = getCursorOffset?.();
+ setCursorOffset(offset ?? null);
+ const hit = sceneAtCursor(scenes, body, offset);
+ if (!hit) {
+ setNotice('Place your cursor inside a script scene, then try again. (Run Adapt to script if you have no scenes yet.)');
+ return;
+ }
+ const { scene } = hit;
+ if (!scene.visualPrompt?.trim()) {
+ setNotice('That scene has no visual prompt yet — re-run Adapt to script to refresh it.');
+ return;
+ }
+ if (!analysisId) {
+ setNotice('No script analysis to attach the render to yet — run Adapt to script first.');
+ return;
+ }
+
+ setNotice(null);
+ setReserving(true);
+ // Reserve a render slot against the per-work daily render budget BEFORE
+ // spending the GPU/provider. 409 → live mode off, 429 → budget spent; both
+ // are expected control-flow shown inline, not red toasts.
+ const reservation = await reserveWritersRoomRenderPreview(workId, { silent: true }).catch((err) => {
+ if (mountedRef.current) {
+ if (err?.status === 429) setNotice('Daily render budget reached — resets at UTC midnight.');
+ else if (err?.status === 409) setNotice('Live mode is off for this work.');
+ else toast.error(`Render reservation failed: ${err.message}`);
+ }
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setReserving(false);
+ if (!reservation) return;
+ if (reservation.renderUsage) setRenderUsage(reservation.renderUsage);
+
+ const matchedCharacters = matchSceneCharacters(scene.characters, ctx.charByKey);
+ const matchedPlace = matchScenePlace(scene.slugline, ctx.placeByKey);
+ const prompt = buildScenePrompt(workTitle, scene, matchedCharacters, ctx.imageStyle?.prompt || '', matchedPlace);
+
+ setGenStatus('running');
+ const res = await generateImage(buildSceneRenderPayload({
+ prompt,
+ negativePrompt: ctx.imageStyle?.negativePrompt || '',
+ imageCfg,
+ }), { silent: true }).catch((err) => {
+ if (mountedRef.current) {
+ toast.error(`Render failed: ${err.message}`);
+ setGenStatus('idle');
+ }
+ return null;
+ });
+ if (!mountedRef.current) return;
+ if (!res) return;
+ const jobId = res.jobId || res.generationId || null;
+ jobIdRef.current = jobId;
+ sceneIdRef.current = jobId ? scene.id : null;
+ if (jobId) {
+ // Register into the shared render dock so the job shows alongside
+ // storyboard renders.
+ const num = hit.sceneNumber;
+ const numLabel = Number.isFinite(num) ? `S${String(num).padStart(2, '0')}` : '';
+ const sceneLabel = `${numLabel} ${scene.heading || ''}`.trim() || scene.heading || 'Scene';
+ registerQueue?.({ jobId, sceneId: scene.id, sceneLabel: `Preview · ${sceneLabel}` });
+ toast('Live preview rendering — see the render dock', { icon: '🎬' });
+ } else {
+ setGenStatus('idle');
+ }
+ }, [reserving, genStatus, getCursorOffset, scenes, body, analysisId, workId, workTitle, imageCfg, ctx, registerQueue, mountedRef]);
+
+ if (!liveMode?.enabled) return null;
+
+ const budget = liveMode?.dailyRenderBudget ?? 0;
+ const spent = renderUsage?.count ?? 0;
+ const remainingLabel = budget > 0 ? `${Math.max(0, budget - spent)} / ${budget} left today` : 'unlimited';
+ const busy = reserving || genStatus === 'running';
+ const targetLabel = target
+ ? `S${String(target.sceneNumber).padStart(2, '0')} ${target.scene.heading || ''}`.trim()
+ : null;
+
+ return (
+ <div className="px-3 py-2 border-b border-port-border">
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-1.5 text-[11px] font-semibold text-port-success">
+ <ImagePlus size={12} /> Live Render
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="text-[10px] text-gray-500" title="Daily render-preview budget">{remainingLabel}</span>
+ <button
+ type="button"
+ onClick={renderCursorScene}
+ disabled={busy}
+ className="flex items-center gap-1 px-2 py-0.5 text-[10px] rounded bg-port-bg border border-port-border text-gray-300 hover:text-white disabled:opacity-50"
+ title="Render a quick reference image for the scene at your cursor"
+ >
+ {busy ? <Loader2 size={10} className="animate-spin" /> : <ImagePlus size={10} />}
+ {genStatus === 'running' ? 'Rendering…' : 'Render scene'}
+ </button>
+ </div>
+ </div>
+ {notice ? (
+ <div className="mt-1.5 text-[10px] text-gray-400">{notice}</div>
+ ) : (
+ <div className="mt-1 text-[10px] text-gray-500 truncate" title={targetLabel || undefined}>
+ {targetLabel ? `Cursor scene: ${targetLabel}` : 'Place your cursor in a scene to render it.'}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsx
index cc3cffb6d9..8cdb5037b1 100644
--- a/client/src/components/writers-room/SceneCard.jsx
+++ b/client/src/components/writers-room/SceneCard.jsx
@@ -15,7 +15,7 @@ import {
} from '../../services/apiWritersRoom';
import socket from '../../services/socket';
import useClickOutside from '../../hooks/useClickOutside';
-import { WR_IMAGE_DEFAULTS } from '../../lib/wrImageDefaults';
+import { WR_IMAGE_DEFAULTS, buildSceneRenderPayload } from '../../lib/wrImageDefaults';
import {
buildScenePrompt,
matchSceneCharacters,
@@ -159,18 +159,11 @@ const SceneCard = forwardRef(function SceneCard({
setProgress(null);
setGenerated(null);
const prompt = buildScenePrompt(workTitle, scene, matchedCharacters, imageStyle?.prompt || '', matchedPlace);
- const stepsNum = imageCfg.steps ? Number(imageCfg.steps) : undefined;
- const seedNum = imageCfg.seed && Number(imageCfg.seed) >= 0 ? Number(imageCfg.seed) : undefined;
- const res = await generateImage({
+ const res = await generateImage(buildSceneRenderPayload({
prompt,
negativePrompt: imageStyle?.negativePrompt || '',
- modelId: imageCfg.modelId,
- mode: imageCfg.mode,
- width: imageCfg.width,
- height: imageCfg.height,
- ...(Number.isFinite(stepsNum) ? { steps: stepsNum } : {}),
- ...(Number.isFinite(seedNum) ? { seed: seedNum } : {}),
- }).catch((err) => {
+ imageCfg,
+ })).catch((err) => {
setError(err.message);
setGenStatus('error');
return null;
diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsx
index 1b69769ed9..a27751b1d9 100644
--- a/client/src/components/writers-room/StoryboardPanel.jsx
+++ b/client/src/components/writers-room/StoryboardPanel.jsx
@@ -61,6 +61,7 @@ export default function StoryboardPanel({
onCharactersChange,
onPlacesChange,
onScenesChange,
+ onLiveRenderContextChange,
objects = [],
onObjectsChange,
onRunObjects,
@@ -252,6 +253,24 @@ export default function StoryboardPanel({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [latestScript]);
+ // Surface everything the Phase 5 live render preview needs to render the
+ // scene under the cursor: the scenes + their owning analysis id (for the
+ // scene-image attach), the bible lookup maps, and the active image config /
+ // world style. The panel reuses SceneCard's exact prompt + render path, so it
+ // needs the same inputs. Keyed on the analysis snapshot identity (scenes /
+ // charByKey / placeByKey are all derived from it or from the bible props).
+ useEffect(() => {
+ onLiveRenderContextChange?.({
+ analysisId: latestScript?.id || null,
+ scenes,
+ charByKey,
+ placeByKey,
+ imageCfg,
+ imageStyle,
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [latestScript, charByKey, placeByKey, imageCfg, imageStyle]);
+
return (
<div className="flex flex-col h-full">
<TabPills
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index 85d5632389..fbdffcbe52 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -45,6 +45,7 @@ import { STATUS_LABELS } from './labels';
import { countWords } from '../../utils/formatters';
import StoryboardPanel, { STORYBOARD_TAB, STORYBOARD_TAB_VALUES } from './StoryboardPanel';
import LiveContinuationPanel from './LiveContinuationPanel';
+import LiveRenderPanel from './LiveRenderPanel';
import AnalysisHistory from './AnalysisHistory';
import ProseReader from './ProseReader';
import SyncedReview from './SyncedReview';
@@ -152,6 +153,10 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const liveTriggerRef = useRef(null);
const liveTimerRef = useRef(null);
const registerLiveTrigger = useCallback((fn) => { liveTriggerRef.current = fn; }, []);
+ // Phase 5 live render preview — the scene/analysis/image context the storyboard
+ // surfaces, fed into LiveRenderPanel so it can render the scene at the cursor
+ // using the existing image-gen route + the shared render queue (queueRegister).
+ const [liveRenderContext, setLiveRenderContext] = useState(null);
// View mode (Edit | Read | Review) is URL-driven so it deep-links and
// survives reloads. ?view=read → ProseReader; ?view=review → SyncedReview
@@ -473,6 +478,13 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
};
}, [body]);
+ // Caret offset into the body for the live render preview's scene resolution.
+ // Falls back to end-of-body when the textarea isn't mounted (e.g. Read view).
+ const getCursorOffset = useCallback(() => {
+ const ta = textareaRef.current;
+ return ta?.selectionStart ?? body.length;
+ }, [body]);
+
// Insert a suggested snippet at the caret (replacing any selection), then
// restore focus + caret after the inserted text so the writer keeps flowing.
const insertAtCursor = useCallback((opt) => {
@@ -961,15 +973,26 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
}`}
>
{liveEnabled && viewMode === 'edit' && (
- <div className="shrink-0 max-h-[40%] min-h-0 border-b border-port-border overflow-hidden flex flex-col">
- <LiveContinuationPanel
+ <>
+ <LiveRenderPanel
workId={work.id}
liveMode={liveMode}
- getCursorContext={getCursorContext}
- onInsert={insertAtCursor}
- registerTrigger={registerLiveTrigger}
+ getCursorOffset={getCursorOffset}
+ body={body}
+ renderContext={liveRenderContext}
+ registerQueue={queueRegister}
+ workTitle={work.title}
/>
- </div>
+ <div className="shrink-0 max-h-[40%] min-h-0 border-b border-port-border overflow-hidden flex flex-col">
+ <LiveContinuationPanel
+ workId={work.id}
+ liveMode={liveMode}
+ getCursorContext={getCursorContext}
+ onInsert={insertAtCursor}
+ registerTrigger={registerLiveTrigger}
+ />
+ </div>
+ </>
)}
<StoryboardPanel
work={work}
@@ -981,6 +1004,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
onObjectsChange={setObjects}
onRunObjects={() => runAnalysis(ANALYSIS_KIND.OBJECTS)}
onScenesChange={setLatestScenes}
+ onLiveRenderContextChange={setLiveRenderContext}
onJumpToScene={jumpToScene}
onDebug={handleDebug}
onRunAdapt={() => runAnalysis(ANALYSIS_KIND.SCRIPT)}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index a6d96a5415..e6663faca6 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -81,4 +81,5 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
+| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
| `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index a1d1e3c743..8720d9921d 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -49,4 +49,5 @@ export * from './voiceLabel.js';
// === Page-scoped pure helpers ===
export * from './universeBuilderExpand.js';
+export * from './wrSceneCursor.js';
export * from './writingGuide.js';
diff --git a/client/src/lib/wrImageDefaults.js b/client/src/lib/wrImageDefaults.js
index 7634401bdd..1f1d71785f 100644
--- a/client/src/lib/wrImageDefaults.js
+++ b/client/src/lib/wrImageDefaults.js
@@ -24,6 +24,27 @@ export const WR_IMAGE_DEFAULTS = Object.freeze({
seed: '',
});
+// Build the /image-gen/generate request body for a Writers Room scene render.
+// Folds the prompt + the per-scene imageCfg (parsing the string steps/seed
+// inputs to numbers, dropping empties so the model uses its own defaults) into
+// the payload shape both SceneCard and the live render preview send. Keeping
+// the steps/seed parsing in one place means the two render entry points can't
+// drift on what "use the model default" means.
+export function buildSceneRenderPayload({ prompt, negativePrompt = '', imageCfg = WR_IMAGE_DEFAULTS }) {
+ const stepsNum = imageCfg.steps ? Number(imageCfg.steps) : undefined;
+ const seedNum = imageCfg.seed && Number(imageCfg.seed) >= 0 ? Number(imageCfg.seed) : undefined;
+ return {
+ prompt,
+ negativePrompt,
+ modelId: imageCfg.modelId,
+ mode: imageCfg.mode,
+ width: imageCfg.width,
+ height: imageCfg.height,
+ ...(Number.isFinite(stepsNum) ? { steps: stepsNum } : {}),
+ ...(Number.isFinite(seedNum) ? { seed: seedNum } : {}),
+ };
+}
+
// Resolve the per-scene render config. When the user hasn't pinned a Writers
// Room mode, prefer Codex if enabled — cloud models render storyboard scenes
// more reliably than local diffusion when both are available. If the stored
diff --git a/client/src/lib/wrSceneCursor.js b/client/src/lib/wrSceneCursor.js
new file mode 100644
index 0000000000..25878948e4
--- /dev/null
+++ b/client/src/lib/wrSceneCursor.js
@@ -0,0 +1,54 @@
+// Resolve which script scene the writer's caret currently sits in.
+//
+// Writers Room script analyses don't store prose offsets — scenes are matched
+// to the manuscript by text (this mirrors WorkEditor's jumpToScene, which
+// locates a scene by searching for its heading, then a summary/action snippet).
+// For the live render preview we need the inverse: given a caret offset, find
+// the scene whose anchor text starts at the greatest index that is still at or
+// before the caret. That's the scene the caret is reading "inside of".
+//
+// Pure + client-only (it operates on the editor body string + a numeric
+// offset), so it has no server mirror. Returns the matched scene object plus
+// the 1-based scene number, or null when nothing matches.
+
+// Find the prose offset where a scene begins, trying the LLM heading (with the
+// markdown prefixes the editor uses) first, then a summary/action snippet.
+// Returns -1 when the scene can't be located in the body.
+export function sceneAnchorIndex(body, scene) {
+ if (!body || !scene) return -1;
+ const heading = scene.heading || '';
+ for (const prefix of ['## ', '### ', '# ', '']) {
+ if (!heading) break;
+ const idx = body.indexOf(prefix + heading);
+ if (idx >= 0) return idx;
+ }
+ for (const candidate of [scene.summary, scene.action]) {
+ if (!candidate) continue;
+ const snippet = String(candidate).trim().slice(0, 40);
+ if (!snippet) continue;
+ const idx = body.indexOf(snippet);
+ if (idx >= 0) return idx;
+ }
+ return -1;
+}
+
+// Return { scene, sceneNumber } for the scene the caret at `cursorOffset` sits
+// in, or null. The match is the locatable scene with the greatest anchor index
+// that is <= cursorOffset; ties (multiple scenes resolving to the same index)
+// keep the later one in list order. sceneNumber is the 1-based index in the
+// original scenes array (so it lines up with the storyboard numbering), not the
+// position among locatable scenes.
+export function sceneAtCursor(scenes, body, cursorOffset) {
+ if (!Array.isArray(scenes) || !scenes.length || !body) return null;
+ const caret = Number.isFinite(cursorOffset) ? cursorOffset : body.length;
+ let best = null;
+ scenes.forEach((scene, i) => {
+ const idx = sceneAnchorIndex(body, scene);
+ if (idx < 0 || idx > caret) return;
+ if (!best || idx >= best.index) {
+ best = { scene, sceneNumber: i + 1, index: idx };
+ }
+ });
+ if (best) return { scene: best.scene, sceneNumber: best.sceneNumber };
+ return null;
+}
diff --git a/client/src/lib/wrSceneCursor.test.js b/client/src/lib/wrSceneCursor.test.js
new file mode 100644
index 0000000000..c8b2bda44e
--- /dev/null
+++ b/client/src/lib/wrSceneCursor.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect } from 'vitest';
+import { sceneAnchorIndex, sceneAtCursor } from './wrSceneCursor.js';
+
+const BODY = [
+ '# Chapter One',
+ '',
+ '## The arrival',
+ 'She stepped off the train into the rain.',
+ '',
+ '## The market',
+ 'Stalls lined the square, loud and bright.',
+].join('\n');
+
+const SCENES = [
+ { id: 's1', heading: 'The arrival', summary: 'She stepped off the train', visualPrompt: 'a' },
+ { id: 's2', heading: 'The market', summary: 'Stalls lined the square', visualPrompt: 'b' },
+];
+
+describe('sceneAnchorIndex', () => {
+ it('locates a scene by its markdown heading', () => {
+ const idx = sceneAnchorIndex(BODY, SCENES[1]);
+ expect(idx).toBe(BODY.indexOf('## The market'));
+ });
+
+ it('falls back to a summary snippet when the heading is absent', () => {
+ const scene = { heading: 'Nowhere in the body', summary: 'Stalls lined the square' };
+ const idx = sceneAnchorIndex(BODY, scene);
+ expect(idx).toBe(BODY.indexOf('Stalls lined the square'));
+ });
+
+ it('returns -1 when nothing matches', () => {
+ expect(sceneAnchorIndex(BODY, { heading: 'Ghost', summary: 'no such text' })).toBe(-1);
+ expect(sceneAnchorIndex('', SCENES[0])).toBe(-1);
+ expect(sceneAnchorIndex(BODY, null)).toBe(-1);
+ });
+});
+
+describe('sceneAtCursor', () => {
+ it('returns the scene whose anchor is the greatest index <= the caret', () => {
+ // Caret inside the second scene's prose.
+ const caret = BODY.indexOf('Stalls lined') + 5;
+ const hit = sceneAtCursor(SCENES, BODY, caret);
+ expect(hit?.scene.id).toBe('s2');
+ expect(hit?.sceneNumber).toBe(2); // 1-based index in the scenes array
+ });
+
+ it('returns the first scene when the caret sits in its prose', () => {
+ const caret = BODY.indexOf('She stepped') + 3;
+ const hit = sceneAtCursor(SCENES, BODY, caret);
+ expect(hit?.scene.id).toBe('s1');
+ expect(hit?.sceneNumber).toBe(1);
+ });
+
+ it('returns null when the caret is before the first locatable scene', () => {
+ const hit = sceneAtCursor(SCENES, BODY, 2); // inside "# Chapter One"
+ expect(hit).toBeNull();
+ });
+
+ it('returns null for empty inputs', () => {
+ expect(sceneAtCursor([], BODY, 10)).toBeNull();
+ expect(sceneAtCursor(SCENES, '', 10)).toBeNull();
+ expect(sceneAtCursor(null, BODY, 10)).toBeNull();
+ });
+
+ it('defaults a non-finite offset to end-of-body (last scene wins)', () => {
+ const hit = sceneAtCursor(SCENES, BODY, undefined);
+ expect(hit?.scene.id).toBe('s2');
+ });
+});
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index 09a62d707d..522e893fc8 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -78,6 +78,17 @@ export const attachWritersRoomSceneImage = (workId, analysisId, payload) =>
body: JSON.stringify(payload),
});
+// Reserve one live render preview (Phase 5) against the per-work render budget.
+// Call this BEFORE kicking off the render via the existing image-gen route —
+// the server gates on the live-mode toggle (409) and the distinct daily render
+// budget (429). Returns { renderUsage, renderBudget }. Callers own their own
+// error UI, so pass { silent: true } to avoid a double toast.
+export const reserveWritersRoomRenderPreview = (workId, options) =>
+ request(`/writers-room/works/${enc(workId)}/live-render-preview`, {
+ method: 'POST',
+ ...(options || {}),
+ });
+
// Synced review (Phase 4): a read-model that maps prose segments ↔ script
// scenes ↔ generated media with provenance + stale detection. Derived on the
// server from the active draft's segment index and the `script` analysis
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 11513a692f..c71c2fe46b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -845,14 +845,18 @@ export const writersRoomImageStyleSchema = z.object({
// Phase 5 live-mode opt-in (per work). `enabled` gates the editor's
// background continuation suggestions; `debounceMs` is the client's
// idle-after-typing throttle before it asks; `dailyCallBudget` caps how many
-// suggest calls the server will run per UTC day (0 = unlimited). The
-// server-tracked `usage` counter is NOT user-editable — it's bumped by the
-// suggest path and reset on a new day — so it lives outside this update schema
-// (mirrors how `pipelineSeriesId` is set by linkToPipeline, not updateWork).
+// suggest calls the server will run per UTC day (0 = unlimited);
+// `dailyRenderBudget` is the distinct cap on live render previews (renders cost
+// materially more than text, so they get their own knob). The server-tracked
+// `usage` / `renderUsage` counters are NOT user-editable — they're bumped by
+// the suggest / render-reserve paths and reset on a new day — so they live
+// outside this update schema (mirrors how `pipelineSeriesId` is set by
+// linkToPipeline, not updateWork).
export const writersRoomLiveModeSchema = z.object({
enabled: z.boolean().default(false),
debounceMs: z.number().int().min(800).max(30_000).default(2500),
dailyCallBudget: z.number().int().min(0).max(10_000).default(100),
+ dailyRenderBudget: z.number().int().min(0).max(10_000).default(20),
}).strict();
export const writersRoomWorkUpdateSchema = z.object({
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index a153bd394f..906a49a5a0 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -35,7 +35,7 @@ import {
runAnalysis, listAnalyses, getAnalysis, attachSceneImage,
} from '../services/writersRoom/evaluator.js';
import { getSyncedReview } from '../services/writersRoom/syncedReview.js';
-import { suggestContinuation } from '../services/writersRoom/liveDirector.js';
+import { suggestContinuation, reserveRenderPreview } from '../services/writersRoom/liveDirector.js';
import {
listCharacters, createCharacter, updateCharacter, deleteCharacter,
} from '../services/writersRoom/characters.js';
@@ -202,6 +202,14 @@ router.post('/works/:id/live-suggest', asyncHandler(async (req, res) => {
res.json(await suggestContinuation(req.params.id, data));
}));
+// Reserve one live render preview against the per-work render budget. The
+// client kicks off the actual render via the existing /image-gen route + media
+// queue AFTER this succeeds — the service enforces opt-in (409 if off) and the
+// daily render budget (429 if spent), distinct from the text-suggest budget.
+router.post('/works/:id/live-render-preview', asyncHandler(async (req, res) => {
+ res.json(await reserveRenderPreview(req.params.id));
+}));
+
// ---------- synced review (Phase 4: prose ↔ script ↔ media) ----------
// Read-model assembled on demand from the active draft's segment index and the
diff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.js
index a485e2aee5..5d9fe3c2d8 100644
--- a/server/routes/writersRoom.test.js
+++ b/server/routes/writersRoom.test.js
@@ -67,6 +67,10 @@ vi.mock('../services/writersRoom/liveDirector.js', () => ({
usage: { date: '2026-06-03', count: 1 },
budget: 100,
})),
+ reserveRenderPreview: vi.fn(async () => ({
+ renderUsage: { date: '2026-06-03', count: 1 },
+ renderBudget: 20,
+ })),
}));
import * as svc from '../services/writersRoom/local.js';
@@ -416,5 +420,23 @@ describe('writersRoom routes', () => {
expect(r.status).toBe(400);
expect(liveSvc.suggestContinuation).not.toHaveBeenCalled();
});
+
+ it('PATCH /works/:id accepts a dailyRenderBudget knob', async () => {
+ const r = await request(app)
+ .patch('/api/writers-room/works/wr-work-1')
+ .send({ liveMode: { dailyRenderBudget: 5 } });
+ expect(r.status).toBe(200);
+ expect(svc.updateWork).toHaveBeenCalledWith('wr-work-1', { liveMode: { dailyRenderBudget: 5 } });
+ });
+
+ it('POST /works/:id/live-render-preview reserves a render slot', async () => {
+ const r = await request(app)
+ .post('/api/writers-room/works/wr-work-1/live-render-preview')
+ .send({});
+ expect(r.status).toBe(200);
+ expect(r.body.renderUsage.count).toBe(1);
+ expect(r.body.renderBudget).toBe(20);
+ expect(liveSvc.reserveRenderPreview).toHaveBeenCalledWith('wr-work-1');
+ });
});
});
diff --git a/server/services/writersRoom/liveDirector.js b/server/services/writersRoom/liveDirector.js
index ea7d713bc7..4b22841f7f 100644
--- a/server/services/writersRoom/liveDirector.js
+++ b/server/services/writersRoom/liveDirector.js
@@ -15,7 +15,9 @@
import { ServerError } from '../../lib/errorHandler.js';
import { runStagedLLM } from '../../lib/stageRunner.js';
-import { getWork, resolveLiveMode, recordLiveModeUsage, utcDayKey } from './local.js';
+import {
+ getWork, resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, utcDayKey,
+} from './local.js';
import { badRequest } from './_shared.js';
const STAGE = 'writers-room-continue';
@@ -26,6 +28,27 @@ const MAX_OPTIONS = 4;
export const ERR_LIVE_MODE_OFF = 'LIVE_MODE_OFF';
export const ERR_BUDGET_EXCEEDED = 'LIVE_BUDGET_EXCEEDED';
+// Shared opt-in + daily-budget gate for the live paths. Throws the coded
+// 409 (live mode off) / 429 (budget spent) ServerErrors the route maps to a
+// status. `usage` is the relevant per-day counter, `budget` its cap (0 =
+// unlimited), `label` names the budget in the 429 message. A counter whose
+// stored date isn't today counts as 0 spent-today (it rolls over on write), so
+// yesterday's count can't block today. utcDayKey() is the same boundary the
+// recordLiveMode*Usage writers roll over on, so the check can't drift.
+function assertLiveBudget(live, { usage, budget, label }) {
+ if (!live.enabled) {
+ throw new ServerError('Live mode is off for this work', { status: 409, code: ERR_LIVE_MODE_OFF });
+ }
+ const today = utcDayKey();
+ const spentToday = usage.date === today ? usage.count : 0;
+ if (budget > 0 && spentToday >= budget) {
+ throw new ServerError(
+ `Live ${label} budget reached (${budget}/day) — resets at UTC midnight`,
+ { status: 429, code: ERR_BUDGET_EXCEEDED },
+ );
+ }
+}
+
function shapeOptions(parsed) {
const raw = Array.isArray(parsed?.options) ? parsed.options : [];
return raw
@@ -49,25 +72,7 @@ function shapeOptions(parsed) {
export async function suggestContinuation(workId, { before = '', after = '', selection = '' } = {}) {
const manifest = await getWork(workId); // 404s if the work is missing
const live = resolveLiveMode(manifest);
-
- if (!live.enabled) {
- throw new ServerError('Live mode is off for this work', { status: 409, code: ERR_LIVE_MODE_OFF });
- }
-
- // Daily budget gate. 0 means unlimited. The counter rolls over per UTC day
- // inside recordLiveModeUsage; here we just compare today's count against the
- // cap before spending an LLM call. Reading the resolved usage (which is not
- // date-normalized) would let yesterday's count block today, so treat a
- // stale-date counter as 0 spent-today. Same utcDayKey as the writer so the
- // boundaries can't drift.
- const today = utcDayKey();
- const spentToday = live.usage.date === today ? live.usage.count : 0;
- if (live.dailyCallBudget > 0 && spentToday >= live.dailyCallBudget) {
- throw new ServerError(
- `Live suggestion budget reached (${live.dailyCallBudget}/day) — resets at UTC midnight`,
- { status: 429, code: ERR_BUDGET_EXCEEDED },
- );
- }
+ assertLiveBudget(live, { usage: live.usage, budget: live.dailyCallBudget, label: 'suggestion' });
if (!before.trim() && !after.trim() && !selection.trim()) {
throw badRequest('Need some prose around the cursor to suggest a continuation');
@@ -98,3 +103,25 @@ export async function suggestContinuation(workId, { before = '', after = '', sel
budget: live.dailyCallBudget,
};
}
+
+/**
+ * Reserve one live render preview against the per-work render budget. The
+ * actual image render reuses the existing image-gen route + media job queue on
+ * the client — this is purely the server-side opt-in + budget gate so a client
+ * that ignores the toggle still can't run unbounded renders. Throws the same
+ * coded errors as suggestContinuation (live-mode off → 409, budget spent → 429)
+ * and bumps the distinct daily render counter on success. Returns
+ * `{ renderUsage, renderBudget }` so the client can render remaining budget.
+ *
+ * Budget is charged at reservation time (before the render kicks off) rather
+ * than on completion: the GPU/provider cost is incurred the moment the job is
+ * enqueued, and a client that fires-and-forgets must still hit the cap.
+ */
+export async function reserveRenderPreview(workId) {
+ const manifest = await getWork(workId); // 404s if the work is missing
+ const live = resolveLiveMode(manifest);
+ assertLiveBudget(live, { usage: live.renderUsage, budget: live.dailyRenderBudget, label: 'render' });
+
+ const renderUsage = (await recordLiveModeRenderUsage(workId)).renderUsage;
+ return { renderUsage, renderBudget: live.dailyRenderBudget };
+}
diff --git a/server/services/writersRoom/liveDirector.test.js b/server/services/writersRoom/liveDirector.test.js
index a1094627a1..b576b3ea00 100644
--- a/server/services/writersRoom/liveDirector.test.js
+++ b/server/services/writersRoom/liveDirector.test.js
@@ -17,7 +17,9 @@ vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLL
const local = await import('./local.js');
const { createWork, updateWork, getWork } = local;
-const { suggestContinuation, ERR_LIVE_MODE_OFF, ERR_BUDGET_EXCEEDED } = await import('./liveDirector.js');
+const {
+ suggestContinuation, reserveRenderPreview, ERR_LIVE_MODE_OFF, ERR_BUDGET_EXCEEDED,
+} = await import('./liveDirector.js');
beforeEach(() => {
tempRoot = mkdtempSync(join(tmpdir(), 'wr-live-test-'));
@@ -117,3 +119,64 @@ describe('suggestContinuation', () => {
expect(res.usage).toMatchObject({ date: '2026-06-04', count: 1 });
});
});
+
+describe('reserveRenderPreview', () => {
+ it('throws LIVE_MODE_OFF when the work has not opted in', async () => {
+ const work = await createWork({ title: 'Off' });
+ await expect(reserveRenderPreview(work.id))
+ .rejects.toMatchObject({ code: ERR_LIVE_MODE_OFF, status: 409 });
+ });
+
+ it('reserves a slot and bumps the distinct render counter on success', async () => {
+ const work = await createWork({ title: 'On' });
+ await updateWork(work.id, { liveMode: { enabled: true } });
+
+ const res = await reserveRenderPreview(work.id);
+ expect(res.renderUsage.count).toBe(1);
+ expect(res.renderBudget).toBe(20); // DEFAULT_LIVE_MODE.dailyRenderBudget
+
+ // The render counter is independent of the text-suggest counter.
+ const reloaded = await getWork(work.id);
+ expect(reloaded.liveMode.usage).toMatchObject({ count: 0 });
+ expect(reloaded.liveMode.renderUsage).toMatchObject({ count: 1 });
+ });
+
+ it('enforces the daily render budget separately from the suggest budget', async () => {
+ runStagedLLM.mockResolvedValue(OPTIONS_RESPONSE);
+ const work = await createWork({ title: 'Capped' });
+ await updateWork(work.id, { liveMode: { enabled: true, dailyRenderBudget: 1, dailyCallBudget: 5 } });
+
+ await reserveRenderPreview(work.id); // render count -> 1
+ await expect(reserveRenderPreview(work.id))
+ .rejects.toMatchObject({ code: ERR_BUDGET_EXCEEDED, status: 429 });
+
+ // The suggest budget is untouched by render reservations.
+ const res = await suggestContinuation(work.id, { before: 'still allowed' });
+ expect(res.usage.count).toBe(1);
+ });
+
+ it('treats dailyRenderBudget 0 as unlimited', async () => {
+ const work = await createWork({ title: 'Unlimited' });
+ await updateWork(work.id, { liveMode: { enabled: true, dailyRenderBudget: 0 } });
+
+ await reserveRenderPreview(work.id);
+ await reserveRenderPreview(work.id);
+ const res = await reserveRenderPreview(work.id);
+ expect(res.renderUsage.count).toBe(3);
+ });
+
+ it('rolls the render budget over on a new UTC day', async () => {
+ const work = await createWork({ title: 'Rollover' });
+ await updateWork(work.id, { liveMode: { enabled: true, dailyRenderBudget: 1 } });
+
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-06-03T12:00:00Z'));
+ await reserveRenderPreview(work.id);
+ await expect(reserveRenderPreview(work.id))
+ .rejects.toMatchObject({ code: ERR_BUDGET_EXCEEDED });
+
+ vi.setSystemTime(new Date('2026-06-04T00:01:00Z'));
+ const res = await reserveRenderPreview(work.id);
+ expect(res.renderUsage).toMatchObject({ date: '2026-06-04', count: 1 });
+ });
+});
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 8480a7a264..bb21538f7b 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -314,25 +314,36 @@ export async function createWork({ folderId = null, title, kind = 'short-story'
// Default Phase 5 live-mode config. Stored on the manifest only once the user
// opts in; readers (the suggest path) fall back to this when the field is
-// absent. `usage` is the server-tracked daily budget counter — never accepted
-// from the client (updateWork strips it; only recordLiveModeUsage writes it).
+// absent. `usage` is the server-tracked daily budget counter for text
+// suggestions; `renderUsage` is the distinct counter for live render previews
+// (renders cost materially more than text, so they get their own budget knob
+// `dailyRenderBudget`). Neither counter is accepted from the client (updateWork
+// strips both; only recordLiveModeUsage / recordLiveModeRenderUsage write them).
export const DEFAULT_LIVE_MODE = Object.freeze({
enabled: false,
debounceMs: 2500,
dailyCallBudget: 100,
+ dailyRenderBudget: 20,
usage: Object.freeze({ date: null, count: 0 }),
+ renderUsage: Object.freeze({ date: null, count: 0 }),
});
+function resolveUsageCounter(stored) {
+ return {
+ date: typeof stored?.date === 'string' ? stored.date : null,
+ count: Number.isInteger(stored?.count) ? stored.count : 0,
+ };
+}
+
export function resolveLiveMode(manifest) {
const stored = manifest?.liveMode || {};
return {
enabled: stored.enabled === true,
debounceMs: Number.isInteger(stored.debounceMs) ? stored.debounceMs : DEFAULT_LIVE_MODE.debounceMs,
dailyCallBudget: Number.isInteger(stored.dailyCallBudget) ? stored.dailyCallBudget : DEFAULT_LIVE_MODE.dailyCallBudget,
- usage: {
- date: typeof stored.usage?.date === 'string' ? stored.usage.date : null,
- count: Number.isInteger(stored.usage?.count) ? stored.usage.count : 0,
- },
+ dailyRenderBudget: Number.isInteger(stored.dailyRenderBudget) ? stored.dailyRenderBudget : DEFAULT_LIVE_MODE.dailyRenderBudget,
+ usage: resolveUsageCounter(stored.usage),
+ renderUsage: resolveUsageCounter(stored.renderUsage),
};
}
@@ -347,9 +358,9 @@ export async function updateWork(id, patch) {
next[key] = patch[key];
}
// liveMode is a partial merge (the UI PATCHes one knob at a time) onto the
- // resolved current config — and the client-supplied `usage` is dropped so a
- // crafted PATCH can't reset the server-side daily budget counter. Only the
- // three user-editable knobs flow through.
+ // resolved current config — and the client-supplied usage counters are
+ // dropped so a crafted PATCH can't reset the server-side daily budgets. Only
+ // the user-editable knobs flow through; both server-owned counters carry over.
if (patch.liveMode !== undefined && patch.liveMode !== null) {
const current = resolveLiveMode(manifest);
const p = patch.liveMode;
@@ -357,7 +368,9 @@ export async function updateWork(id, patch) {
enabled: typeof p.enabled === 'boolean' ? p.enabled : current.enabled,
debounceMs: Number.isInteger(p.debounceMs) ? p.debounceMs : current.debounceMs,
dailyCallBudget: Number.isInteger(p.dailyCallBudget) ? p.dailyCallBudget : current.dailyCallBudget,
+ dailyRenderBudget: Number.isInteger(p.dailyRenderBudget) ? p.dailyRenderBudget : current.dailyRenderBudget,
usage: current.usage,
+ renderUsage: current.renderUsage,
};
}
// Trim title and reject if it becomes empty after trim — keeps parity with
@@ -420,6 +433,24 @@ export async function recordLiveModeUsage(id) {
return nextLive;
}
+/**
+ * Bump the live-mode daily RENDER usage counter for a work, rolling over to a
+ * fresh count on a new UTC day. Distinct from `recordLiveModeUsage` because
+ * render previews carry a different cost profile and their own budget knob
+ * (`dailyRenderBudget`). Set once per reserved render-preview by the
+ * live-director path. Returns the resolved live config with the new
+ * `renderUsage` so the caller can echo remaining render budget.
+ */
+export async function recordLiveModeRenderUsage(id) {
+ const manifest = await getWork(id);
+ const live = resolveLiveMode(manifest);
+ const today = utcDayKey();
+ const count = live.renderUsage.date === today ? live.renderUsage.count + 1 : 1;
+ const nextLive = { ...live, renderUsage: { date: today, count } };
+ await saveManifest(id, { ...manifest, liveMode: nextLive, updatedAt: nowIso() });
+ return nextLive;
+}
+
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.
diff --git a/server/services/writersRoom/local.test.js b/server/services/writersRoom/local.test.js
index 068f960ebe..3dbf85014f 100644
--- a/server/services/writersRoom/local.test.js
+++ b/server/services/writersRoom/local.test.js
@@ -18,7 +18,7 @@ const {
listWorks, createWork, getWork, getWorkWithBody, updateWork, deleteWork,
saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,
listExercises, createExercise, finishExercise, discardExercise,
- resolveLiveMode, recordLiveModeUsage, DEFAULT_LIVE_MODE,
+ resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, DEFAULT_LIVE_MODE,
} = local;
beforeEach(() => {
@@ -365,7 +365,9 @@ describe('live mode (Phase 5)', () => {
expect(live.enabled).toBe(false);
expect(live.debounceMs).toBe(DEFAULT_LIVE_MODE.debounceMs);
expect(live.dailyCallBudget).toBe(DEFAULT_LIVE_MODE.dailyCallBudget);
+ expect(live.dailyRenderBudget).toBe(DEFAULT_LIVE_MODE.dailyRenderBudget);
expect(live.usage).toEqual({ date: null, count: 0 });
+ expect(live.renderUsage).toEqual({ date: null, count: 0 });
});
it('updateWork partial-merges liveMode knobs without clobbering siblings', async () => {
@@ -377,17 +379,30 @@ describe('live mode (Phase 5)', () => {
const b = await updateWork(work.id, { liveMode: { debounceMs: 5000 } });
expect(b.liveMode.enabled).toBe(true); // preserved
expect(b.liveMode.debounceMs).toBe(5000);
+
+ // The distinct render budget merges independently of the suggest budget.
+ const c = await updateWork(work.id, { liveMode: { dailyRenderBudget: 7 } });
+ expect(c.liveMode.dailyRenderBudget).toBe(7);
+ expect(c.liveMode.dailyCallBudget).toBe(DEFAULT_LIVE_MODE.dailyCallBudget); // preserved
+ expect(c.liveMode.enabled).toBe(true); // preserved
});
- it('updateWork strips a client-supplied usage counter (server-owned)', async () => {
+ it('updateWork strips client-supplied usage counters (both server-owned)', async () => {
const work = await createWork({ title: 'Guard' });
- await recordLiveModeUsage(work.id); // count -> 1 today
+ await recordLiveModeUsage(work.id); // suggest count -> 1 today
+ await recordLiveModeRenderUsage(work.id); // render count -> 1 today
const tampered = await updateWork(work.id, {
- liveMode: { enabled: true, usage: { date: '1999-01-01', count: 9999 } },
+ liveMode: {
+ enabled: true,
+ usage: { date: '1999-01-01', count: 9999 },
+ renderUsage: { date: '1999-01-01', count: 9999 },
+ },
});
- // The crafted usage is dropped — the real counter is preserved.
+ // Both crafted counters are dropped — the real counters are preserved.
expect(tampered.liveMode.usage.count).toBe(1);
expect(tampered.liveMode.usage.date).not.toBe('1999-01-01');
+ expect(tampered.liveMode.renderUsage.count).toBe(1);
+ expect(tampered.liveMode.renderUsage.date).not.toBe('1999-01-01');
});
it('recordLiveModeUsage increments within a day and rolls over on a new UTC day', async () => {
@@ -404,4 +419,22 @@ describe('live mode (Phase 5)', () => {
const u3 = await recordLiveModeUsage(work.id);
expect(u3.usage).toEqual({ date: '2026-06-04', count: 1 });
});
+
+ it('recordLiveModeRenderUsage bumps a counter independent of the suggest counter', async () => {
+ const work = await createWork({ title: 'RenderBudget' });
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-06-03T10:00:00Z'));
+ await recordLiveModeUsage(work.id); // suggest -> 1
+
+ const r1 = await recordLiveModeRenderUsage(work.id);
+ expect(r1.renderUsage).toEqual({ date: '2026-06-03', count: 1 });
+ expect(r1.usage).toEqual({ date: '2026-06-03', count: 1 }); // suggest untouched
+ const r2 = await recordLiveModeRenderUsage(work.id);
+ expect(r2.renderUsage).toEqual({ date: '2026-06-03', count: 2 });
+
+ // New UTC day resets the render counter to 1.
+ vi.setSystemTime(new Date('2026-06-04T00:05:00Z'));
+ const r3 = await recordLiveModeRenderUsage(work.id);
+ expect(r3.renderUsage).toEqual({ date: '2026-06-04', count: 1 });
+ });
});