Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-841]): address review — duplicate-anchor scene match, sync-completion attach, reactive boards, route validation
[._.]/ Adam Eivy5d5ef9dc2a04
diff --git a/client/src/components/writers-room/LiveRenderPanel.jsx b/client/src/components/writers-room/LiveRenderPanel.jsxindex ad321625c8..8efd06caa8 100644--- a/client/src/components/writers-room/LiveRenderPanel.jsx+++ b/client/src/components/writers-room/LiveRenderPanel.jsx@@ -35,6 +35,7 @@ export default function LiveRenderPanel({body,renderContext,registerQueue,+ onSceneImageAttached,workTitle,}) {const [reserving, setReserving] = useState(false);@@ -54,12 +55,42 @@ export default function LiveRenderPanel({const sceneIdRef = useRef(null);const [genStatus, setGenStatus] = useState('idle');+ // Read the attach callback through a ref so the socket effect (and the+ // shared persist helper) stay identity-stable as the parent re-renders.+ const onAttachedRef = useRef(onSceneImageAttached);+ useEffect(() => { onAttachedRef.current = onSceneImageAttached; }, [onSceneImageAttached]);+// 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;+ // The async render can finish (socket completion / fast sync result) after the+ // user has moved the cursor and the context has changed, so read the analysis+ // id the job was reserved against through a ref rather than the live value.+ const analysisIdRef = useRef(analysisId);+ useEffect(() => { analysisIdRef.current = analysisId; }, [analysisId]);++ // Persist a finished render onto the script analysis (best-effort, mirroring+ // SceneCard) AND fold the returned sceneImages map up so the storyboard+ // updates reactively without a refetch. Shared by the socket-completion path+ // and the fast synchronous-completion path. { silent: true } because we own+ // the error UI here (a console.warn) — without it the helper would also toast.+ const persistAttach = useCallback((sceneId, jobId, prompt) => {+ const aid = analysisIdRef.current;+ if (!workId || !aid || !jobId || !sceneId) return;+ attachWritersRoomSceneImage(workId, aid, {+ sceneId,+ filename: `${jobId}.png`,+ jobId,+ prompt: prompt || null,+ }, { silent: true }).then((res) => {+ if (mountedRef.current && res?.analysis) onAttachedRef.current?.(res.analysis);+ }).catch((err) => {+ console.warn(`live render persist failed: ${err.message}`);+ });+ }, [workId, mountedRef]);// 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;@@ -76,19 +107,7 @@ export default function LiveRenderPanel({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}`);- });- }+ persistAttach(sceneId, completedJobId, data.prompt);};const onFailed = (data) => {if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;@@ -102,9 +121,9 @@ export default function LiveRenderPanel({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]);+ // sceneId comes from sceneIdRef (set when we kicked the job off); the+ // persist target inputs are read through refs inside persistAttach.+ }, [persistAttach, mountedRef]);const renderCursorScene = useCallback(async () => {if (reserving || genStatus === 'running') return;@@ -162,20 +181,32 @@ export default function LiveRenderPanel({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 {+ if (!jobId) {setGenStatus('idle');+ return;}- }, [reserving, genStatus, getCursorOffset, scenes, body, analysisId, workId, workTitle, imageCfg, ctx, registerQueue, mountedRef]);+ // A fast/synchronous backend (some external SD-API / Codex paths) can return+ // a finished result whose image-gen:completed socket event already fired+ // before we could set jobIdRef — so the socket handler ignored it and would+ // leave the button stuck on "Rendering…" with no attach. Detect the+ // already-done case from the HTTP result and finalize inline. Only register+ // into the render dock + wait on the socket for jobs that are still running.+ const alreadyDone = res.status && res.status !== 'queued' && res.status !== 'running';+ if (alreadyDone) {+ setGenStatus('idle');+ persistAttach(scene.id, jobId, prompt);+ return;+ }+ jobIdRef.current = jobId;+ sceneIdRef.current = scene.id;+ // 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: '🎬' });+ }, [reserving, genStatus, getCursorOffset, scenes, body, analysisId, workId, workTitle, imageCfg, ctx, registerQueue, persistAttach, mountedRef]);if (!liveMode?.enabled) return null;diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsxindex 8cdb5037b1..58ccd08ed7 100644--- a/client/src/components/writers-room/SceneCard.jsx+++ b/client/src/components/writers-room/SceneCard.jsx@@ -124,7 +124,7 @@ const SceneCard = forwardRef(function SceneCard({filename: `${completedJobId}.png`,jobId: completedJobId,prompt: data.prompt || null,- }).catch((err) => {+ }, { silent: true }).catch((err) => {console.warn(`scene-image persist failed: ${err.message}`);});}diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsxindex a27751b1d9..2adbf52017 100644--- a/client/src/components/writers-room/StoryboardPanel.jsx+++ b/client/src/components/writers-room/StoryboardPanel.jsx@@ -62,6 +62,7 @@ export default function StoryboardPanel({onPlacesChange,onScenesChange,onLiveRenderContextChange,+ registerSceneImageMerge,objects = [],onObjectsChange,onRunObjects,@@ -271,6 +272,24 @@ export default function StoryboardPanel({// eslint-disable-next-line react-hooks/exhaustive-deps}, [latestScript, charByKey, placeByKey, imageCfg, imageStyle]);+ // Expose an imperative "merge a freshly-attached sceneImages map" up to+ // WorkEditor so the live render preview's completion updates the boards+ // reactively (no refetch) — only when the attach targeted the analysis we're+ // currently showing (a stale attach against a since-replaced analysis is+ // dropped). The merged-in snapshot supersedes the prior sceneImages.+ useEffect(() => {+ if (!registerSceneImageMerge) return undefined;+ registerSceneImageMerge((analysis) => {+ if (!analysis?.id || !analysis.sceneImages) return;+ setLatestScript((prev) => (+ prev && prev.id === analysis.id+ ? { ...prev, sceneImages: { ...prev.sceneImages, ...analysis.sceneImages } }+ : prev+ ));+ });+ return () => registerSceneImageMerge(null);+ }, [registerSceneImageMerge]);+return (<div className="flex flex-col h-full"><TabPillsdiff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex fbdffcbe52..e7d395a5be 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -157,6 +157,13 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO// 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);+ // Imperative bridge: StoryboardPanel registers its sceneImages merge fn here+ // so a finished live render preview updates the boards reactively (no refetch).+ const sceneImageMergeRef = useRef(null);+ const registerSceneImageMerge = useCallback((fn) => { sceneImageMergeRef.current = fn; }, []);+ const handleSceneImageAttached = useCallback((analysis) => {+ sceneImageMergeRef.current?.(analysis);+ }, []);// View mode (Edit | Read | Review) is URL-driven so it deep-links and// survives reloads. ?view=read → ProseReader; ?view=review → SyncedReview@@ -981,6 +988,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseObody={body}renderContext={liveRenderContext}registerQueue={queueRegister}+ onSceneImageAttached={handleSceneImageAttached}workTitle={work.title}/><div className="shrink-0 max-h-[40%] min-h-0 border-b border-port-border overflow-hidden flex flex-col">@@ -1005,6 +1013,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOonRunObjects={() => runAnalysis(ANALYSIS_KIND.OBJECTS)}onScenesChange={setLatestScenes}onLiveRenderContextChange={setLiveRenderContext}+ registerSceneImageMerge={registerSceneImageMerge}onJumpToScene={jumpToScene}onDebug={handleDebug}onRunAdapt={() => runAnalysis(ANALYSIS_KIND.SCRIPT)}diff --git a/client/src/lib/wrSceneCursor.js b/client/src/lib/wrSceneCursor.jsindex 25878948e4..4350bd838d 100644--- a/client/src/lib/wrSceneCursor.js+++ b/client/src/lib/wrSceneCursor.js@@ -13,41 +13,47 @@// 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) {+// Searches from `fromIndex` so callers resolving scenes IN ORDER can advance+// past each match — otherwise scenes that share a heading/snippet (a recurring+// "INT. KITCHEN" slugline, repeated action text) would all collapse onto the+// first occurrence and a cursor in a later scene could resolve to an earlier+// one. Returns -1 when the scene can't be located at or after `fromIndex`.+export function sceneAnchorIndex(body, scene, fromIndex = 0) {if (!body || !scene) return -1;const heading = scene.heading || '';for (const prefix of ['## ', '### ', '# ', '']) {if (!heading) break;- const idx = body.indexOf(prefix + heading);+ const idx = body.indexOf(prefix + heading, fromIndex);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);+ const idx = body.indexOf(snippet, fromIndex);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.+// in, or null. Scenes are resolved IN ORDER with a moving search cursor so each+// scene maps to a strictly-increasing anchor position (duplicate headings don't+// collapse onto the same offset). The match is then the locatable scene with+// the greatest anchor index that is <= cursorOffset. 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. A scene that can't be+// located at/after the previous match is skipped without rewinding the cursor.export function sceneAtCursor(scenes, body, cursorOffset) {if (!Array.isArray(scenes) || !scenes.length || !body) return null;const caret = Number.isFinite(cursorOffset) ? cursorOffset : body.length;+ let searchFrom = 0;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 };- }+ const idx = sceneAnchorIndex(body, scene, searchFrom);+ if (idx < 0) return; // not locatable from here — skip, keep the cursor put+ searchFrom = idx + 1; // next scene must start strictly after this one+ if (idx <= caret) 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.jsindex c8b2bda44e..82941bfeb0 100644--- a/client/src/lib/wrSceneCursor.test.js+++ b/client/src/lib/wrSceneCursor.test.js@@ -33,6 +33,16 @@ describe('sceneAnchorIndex', () => {expect(sceneAnchorIndex('', SCENES[0])).toBe(-1);expect(sceneAnchorIndex(BODY, null)).toBe(-1);});++ it('honors fromIndex so repeated headings resolve to distinct occurrences', () => {+ const dup = '## INT. KITCHEN\nFirst time.\n## INT. KITCHEN\nSecond time.';+ const scene = { heading: 'INT. KITCHEN' };+ const first = sceneAnchorIndex(dup, scene);+ expect(first).toBe(0);+ const second = sceneAnchorIndex(dup, scene, first + 1);+ expect(second).toBe(dup.indexOf('## INT. KITCHEN', first + 1));+ expect(second).toBeGreaterThan(first);+ });});describe('sceneAtCursor', () => {@@ -66,4 +76,21 @@ describe('sceneAtCursor', () => {const hit = sceneAtCursor(SCENES, BODY, undefined);expect(hit?.scene.id).toBe('s2');});++ it('does not collapse two scenes that share a heading onto the first', () => {+ const dupBody = '## INT. KITCHEN\nFirst beat here.\n## INT. KITCHEN\nSecond beat here.';+ const dupScenes = [+ { id: 'a', heading: 'INT. KITCHEN' },+ { id: 'b', heading: 'INT. KITCHEN' },+ ];+ // Caret inside the SECOND kitchen scene must resolve to scene b, not a.+ const caret = dupBody.indexOf('Second beat') + 3;+ const hit = sceneAtCursor(dupScenes, dupBody, caret);+ expect(hit?.scene.id).toBe('b');+ expect(hit?.sceneNumber).toBe(2);++ // Caret inside the FIRST kitchen scene resolves to scene a.+ const firstCaret = dupBody.indexOf('First beat') + 3;+ expect(sceneAtCursor(dupScenes, dupBody, firstCaret)?.scene.id).toBe('a');+ });});diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.jsindex 522e893fc8..2c0d43d8d2 100644--- a/client/src/services/apiWritersRoom.js+++ b/client/src/services/apiWritersRoom.js@@ -72,10 +72,15 @@ export const suggestWritersRoomContinuation = (workId, context, options) =>body: JSON.stringify(context || {}),...(options || {}),});-export const attachWritersRoomSceneImage = (workId, analysisId, payload) =>+// Persist a scene→generated-image link on the analysis snapshot (and mirror it+// into the work's media collection). Returns { analysis, collectionId } — the+// analysis carries the merged sceneImages map so callers can update reactively.+// Pass { silent: true } when you own the error UI (e.g. a console.warn).+export const attachWritersRoomSceneImage = (workId, analysisId, payload, options) =>request(`/writers-room/works/${enc(workId)}/analysis/${enc(analysisId)}/scene-image`, {method: 'POST',body: JSON.stringify(payload),+ ...(options || {}),});// Reserve one live render preview (Phase 5) against the per-work render budget.diff --git a/server/lib/validation.js b/server/lib/validation.jsindex c71c2fe46b..b37475c145 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -878,6 +878,11 @@ export const writersRoomLiveSuggestSchema = z.object({selection: z.string().max(8_000).optional().default(''),}).strict();+// Live render-preview reservation takes no body — the work id is in the path+// and the budget is server-owned. A strict empty object rejects any crafted+// payload (e.g. an attempt to smuggle a usage counter) instead of ignoring it.+export const writersRoomLiveRenderPreviewSchema = z.object({}).strict();+export const writersRoomDraftSaveSchema = z.object({body: z.string().max(5_000_000), // 5 MB ceiling — well over a long novel in plain text// Catalog ingredient ids this draft version references. Optional: whendiff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.jsindex 906a49a5a0..20249c0da7 100644--- a/server/routes/writersRoom.js+++ b/server/routes/writersRoom.js@@ -17,6 +17,7 @@ import {writersRoomExerciseFinishSchema,writersRoomAnalysisCreateSchema,writersRoomLiveSuggestSchema,+ writersRoomLiveRenderPreviewSchema,writersRoomCharacterCreateSchema,writersRoomCharacterUpdateSchema,writersRoomPlaceCreateSchema,@@ -207,6 +208,7 @@ router.post('/works/:id/live-suggest', asyncHandler(async (req, res) => {// 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) => {+ validateRequest(writersRoomLiveRenderPreviewSchema, req.body || {});res.json(await reserveRenderPreview(req.params.id));}));diff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.jsindex 5d9fe3c2d8..f92e0ad5ec 100644--- a/server/routes/writersRoom.test.js+++ b/server/routes/writersRoom.test.js@@ -438,5 +438,13 @@ describe('writersRoom routes', () => {expect(r.body.renderBudget).toBe(20);expect(liveSvc.reserveRenderPreview).toHaveBeenCalledWith('wr-work-1');});++ it('POST /works/:id/live-render-preview rejects a non-empty body', async () => {+ const r = await request(app)+ .post('/api/writers-room/works/wr-work-1/live-render-preview')+ .send({ renderUsage: { count: 9999 } });+ expect(r.status).toBe(400);+ expect(liveSvc.reserveRenderPreview).not.toHaveBeenCalled();+ });});});