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: surface FableLoom media generation lifecycle
Adam Eivyb9893531c7b6
diff --git a/client/src/components/fableloom/LoomCanvas.jsx b/client/src/components/fableloom/LoomCanvas.jsxindex c75d9c7e63..015ed8f9a9 100644--- a/client/src/components/fableloom/LoomCanvas.jsx+++ b/client/src/components/fableloom/LoomCanvas.jsx@@ -21,6 +21,7 @@ import useContainerWidth from '../../hooks/useContainerWidth';import {layoutLoomGraph, LOOM_EDGE_LABEL_MAX, LOOM_ORIENTATION,} from '../../lib/loomLayout';+import LoomSceneMedia from './LoomSceneMedia';const DRAG_THRESHOLD_PX = 4;@@ -37,6 +38,8 @@ const startOfPath = (d) => {export default function LoomCanvas({episode, selectedNodeId, onSelectNode, onMoveNode,viewportWidth: viewportWidthProp, orientation: orientationProp,+ mediaJobs = {}, onGenerateImage, onGenerateVideo,+ generationDisabled = false, generationDisabledReason = '',}) {// An in-flight drag lives entirely outside React state: the dragged <g>'s// transform is mutated directly per pointermove, and the position commits@@ -246,24 +249,25 @@ export default function LoomCanvas({selected ? 'stroke-port-accent' : 'stroke-port-border'}`}/>- {node.image && (- <image- href={`/data/images/${node.image}`}- x={8} y={26} width={54} height={nodeH - 34}- preserveAspectRatio="xMidYMid slice"- />- )}<text x={10} y={17} className="fill-port-text text-[11px] font-semibold pointer-events-none">{truncate(node.title || 'Untitled scene', titleMax)}</text><foreignObject- x={node.image ? 68 : 10}+ x={8}y={24}- width={nodeW - (node.image ? 78 : 20)}+ width={nodeW - 16}height={nodeH - 48}>- <div className="text-[10px] leading-snug text-port-text-muted overflow-hidden h-full pointer-events-none">- {truncate(node.prose, stacked ? 80 : 110)}+ <div className="h-full" xmlns="http://www.w3.org/1999/xhtml">+ <LoomSceneMedia+ node={node}+ jobs={mediaJobs[node.id]}+ onGenerateImage={onGenerateImage}+ onGenerateVideo={onGenerateVideo}+ compact+ generationDisabled={generationDisabled}+ generationDisabledReason={generationDisabledReason}+ /></div></foreignObject><g transform={`translate(10, ${nodeH - 16})`} className="pointer-events-none">diff --git a/client/src/components/fableloom/LoomCanvas.test.jsx b/client/src/components/fableloom/LoomCanvas.test.jsxindex 3c1b5dfcc8..9860f5279c 100644--- a/client/src/components/fableloom/LoomCanvas.test.jsx+++ b/client/src/components/fableloom/LoomCanvas.test.jsx@@ -34,6 +34,60 @@ describe('LoomCanvas', () => {expect(screen.getByText('enter the gate')).toBeInTheDocument();});+ it('keeps media controls in each visual node and gives a finished video preview precedence', () => {+ const onGenerateImage = vi.fn();+ const onGenerateVideo = vi.fn();+ const withMedia = episode();+ withMedia.nodes[0] = {+ ...withMedia.nodes[0], image: 'scene.png', videoHistoryId: 'video-1',+ };+ render(+ <LoomCanvas+ episode={withMedia}+ selectedNodeId={null}+ onSelectNode={() => {}}+ onGenerateImage={onGenerateImage}+ onGenerateVideo={onGenerateVideo}+ />,+ );++ expect(screen.getByLabelText('The Gate video preview')).toBeInTheDocument();+ expect(screen.queryByAltText('The Gate image preview')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Regenerate image' }));+ fireEvent.click(screen.getByRole('button', { name: 'Regenerate video' }));+ expect(onGenerateImage).toHaveBeenCalledWith(withMedia.nodes[0]);+ expect(onGenerateVideo).toHaveBeenCalledWith(withMedia.nodes[0]);+ });++ it('shows live image progress and retains an actionable failed indicator', () => {+ const { rerender } = render(+ <LoomCanvas+ episode={episode()}+ selectedNodeId={null}+ onSelectNode={() => {}}+ onGenerateImage={() => {}}+ onGenerateVideo={() => {}}+ mediaJobs={{ n1: { image: { jobId: 'image-1', status: 'running', progress: 0.42, currentImage: 'AAAA' } } }}+ />,+ );+ expect(screen.getByAltText('The Gate image generation preview')).toBeInTheDocument();+ expect(screen.getByText('Generating image 42%')).toBeInTheDocument();++ rerender(+ <LoomCanvas+ episode={episode()}+ selectedNodeId={null}+ onSelectNode={() => {}}+ onGenerateImage={() => {}}+ onGenerateVideo={() => {}}+ mediaJobs={{ n1: { image: { jobId: 'image-1', status: 'failed', error: 'Synthetic failure' } } }}+ />,+ );+ expect(screen.getByRole('alert')).toHaveTextContent('Image failed');+ expect(screen.getByRole('alert')).toHaveAttribute('title', 'Synthetic failure');+ expect(screen.getAllByRole('button', { name: 'Generate image' })[0]).toBeEnabled();+ });+it('selects a node on keyboard activation', () => {const onSelectNode = vi.fn();render(<LoomCanvas episode={episode()} selectedNodeId={null} onSelectNode={onSelectNode} />);diff --git a/client/src/components/fableloom/LoomMediaJobWatchers.jsx b/client/src/components/fableloom/LoomMediaJobWatchers.jsxnew file mode 100644index 0000000000..bbd3dd9956--- /dev/null+++ b/client/src/components/fableloom/LoomMediaJobWatchers.jsx@@ -0,0 +1,49 @@+/**+ * One subscription per active FableLoom scene-media job.+ *+ * The page owns the job map so the canvas card and editor rail consume the+ * same lifecycle instead of mounting duplicate socket subscriptions. Watchers+ * forward snapshots and report each terminal result once; the page then owns+ * notifications and the optimistic final-media swap.+ */++import { useEffect, useRef } from 'react';+import useMediaJobProgress from '../../hooks/useMediaJobProgress';++function LoomMediaJobWatcher({ nodeId, kind, job, onUpdate, onTerminal }) {+ const progress = useMediaJobProgress(job.jobId, { kind });+ const reportedTerminalRef = useRef(null);++ useEffect(() => {+ if (!job.jobId || progress.status === 'unknown') return;+ onUpdate(nodeId, kind, job.jobId, progress);++ const terminal = progress.status === 'failed'+ || progress.status === 'canceled'+ || (progress.status === 'completed' && (kind === 'video' || progress.filename));+ const terminalKey = terminal ? `${job.jobId}:${progress.status}` : null;+ if (!terminalKey || reportedTerminalRef.current === terminalKey) return;+ reportedTerminalRef.current = terminalKey;+ onTerminal(nodeId, kind, job.jobId, progress);+ }, [job.jobId, kind, nodeId, onTerminal, onUpdate, progress]);++ return null;+}++export default function LoomMediaJobWatchers({ jobs, onUpdate, onTerminal }) {+ return Object.entries(jobs).flatMap(([nodeId, nodeJobs]) => (+ ['image', 'video'].map((kind) => {+ const job = nodeJobs?.[kind];+ return job?.jobId ? (+ <LoomMediaJobWatcher+ key={`${nodeId}:${kind}:${job.jobId}`}+ nodeId={nodeId}+ kind={kind}+ job={job}+ onUpdate={onUpdate}+ onTerminal={onTerminal}+ />+ ) : null;+ })+ ));+}diff --git a/client/src/components/fableloom/LoomMediaJobWatchers.test.jsx b/client/src/components/fableloom/LoomMediaJobWatchers.test.jsxnew file mode 100644index 0000000000..c0ead25bd2--- /dev/null+++ b/client/src/components/fableloom/LoomMediaJobWatchers.test.jsx@@ -0,0 +1,35 @@+import { describe, expect, it, vi } from 'vitest';+import { render, waitFor } from '@testing-library/react';++const hookState = vi.hoisted(() => ({+ value: { status: 'queued', progress: 0, filename: null, error: null },+}));+vi.mock('../../hooks/useMediaJobProgress', () => ({ default: () => hookState.value }));++import LoomMediaJobWatchers from './LoomMediaJobWatchers';++describe('LoomMediaJobWatchers', () => {+ it('forwards a failed terminal media job exactly once', async () => {+ const onUpdate = vi.fn();+ const onTerminal = vi.fn();+ const props = {+ jobs: { node1: { image: { jobId: 'image-1', status: 'queued' } } },+ onUpdate,+ onTerminal,+ };+ const { rerender } = render(<LoomMediaJobWatchers {...props} />);+ await waitFor(() => expect(onUpdate).toHaveBeenCalledWith(+ 'node1', 'image', 'image-1', expect.objectContaining({ status: 'queued' }),+ ));++ hookState.value = { status: 'failed', progress: 0, filename: null, error: 'Synthetic failure' };+ rerender(<LoomMediaJobWatchers {...props} />);+ await waitFor(() => expect(onTerminal).toHaveBeenCalledTimes(1));+ expect(onTerminal).toHaveBeenCalledWith(+ 'node1', 'image', 'image-1', expect.objectContaining({ status: 'failed', error: 'Synthetic failure' }),+ );++ rerender(<LoomMediaJobWatchers {...props} />);+ expect(onTerminal).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsxindex d682a3f683..735185c55f 100644--- a/client/src/components/fableloom/LoomNodeEditor.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.jsx@@ -13,19 +13,19 @@*/import { useEffect, useMemo, useState } from 'react';-import { GitBranch, ImagePlus, Loader2, Trash2, Video } from 'lucide-react';+import { GitBranch, Loader2, Trash2 } from 'lucide-react';import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import { FormField } from '../ui/FormField.jsx';-import MediaImage from '../MediaImage';import { useAsyncAction } from '../../hooks/useAsyncAction';import { useConfirmDelete } from '../../hooks/useConfirmDelete';import {addLoomTransition, branchLoomNode, deleteLoomNode, deleteLoomTransition,- generateImage, generateVideo, updateLoomNode, updateLoomTransition,+ updateLoomNode, updateLoomTransition,} from '../../services/api';import { fieldClass, labelClass, sceneFieldClass } from './fieldStyles';import { isTeleplayFormat } from './loomFormats';+import LoomSceneMedia from './LoomSceneMedia';import { FABLELOOM_CAMERA_MOVEMENTS } from '../../../../server/lib/fableLoomCameraMovements.js';import { FABLELOOM_PLAYBACK_MODES } from '../../../../server/lib/fableLoomPlayback.js';@@ -37,7 +37,11 @@ const rowToPatch = ({ targetNodeId, intent, triggersText, description }) => ({description: description || '',});-export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onClearSelection, onMakeStart }) {+export default function LoomNodeEditor({+ loom, episode, node, onLoomUpdate, onClearSelection, onMakeStart,+ mediaJobs = {}, onGenerateImage, onGenerateVideo,+ generationDisabled = false, generationDisabledReason = '',+}) {const [form, setForm] = useState(null);// In-flight blur-saves; the AI buttons (which read server-side state) stay// disabled until every pending save settles.@@ -162,7 +166,7 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCltoast.success('New branches woven');}, { errorMessage: 'Branching failed' });- const [runGenerateImage, rendering] = useAsyncAction(async () => {+ const runGenerateImage = async () => {const prompt = form.imagePrompt.trim();if (!prompt) {toast.error('Write an image prompt first');@@ -173,36 +177,23 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCl// files the finished image onto this node even if the page unmounts// mid-render.await saveField('imagePrompt', prompt);- await generateImage({- prompt: loom.styleNotes ? `${prompt}\n\nStyle: ${loom.styleNotes}` : prompt,- fableLoom: { loomId: loom.id, episodeId: episode.id, nodeId: node.id },- }, { silent: true });- toast.success('Scene render queued — it will attach when it completes');- }, { errorMessage: 'Could not queue the render' });+ await onGenerateImage?.({ ...node, imagePrompt: prompt });+ };- const [runGenerateVideo, videoRendering] = useAsyncAction(async () => {+ const runGenerateVideo = async () => {const authoredPrompt = form.videoPrompt.trim() || form.prose.trim();if (!authoredPrompt) {toast.error('Write the scene first');return;}- // Prefer the explicit single-cut direction; legacy nodes fall back to the- // authored scene until they are updated.- // An existing rendered still seeds image-to-video when one is available.await saveField('videoPrompt', form.videoPrompt);- const movement = FABLELOOM_CAMERA_MOVEMENTS.find((move) => move.value === form.cameraMovement);- const direction = movement?.prompt || form.cameraMovement.trim();- const prompt = direction ? `${authoredPrompt}\n\nCamera direction: ${direction}` : authoredPrompt;- await generateVideo({- prompt: loom.styleNotes ? `${prompt}\n\nStyle: ${loom.styleNotes}` : prompt,- backend: 'local',- mode: node.image ? 'image' : 'text',- ...(node.image ? { sourceImageFile: node.image } : {}),- disableAudio: true,- fableLoom: JSON.stringify({ loomId: loom.id, episodeId: episode.id, nodeId: node.id }),+ await onGenerateVideo?.({+ ...node,+ prose: form.prose,+ videoPrompt: form.videoPrompt,+ cameraMovement: form.cameraMovement,});- toast.success('Scene video queued — it will attach when it completes');- }, { errorMessage: 'Could not queue the video render' });+ };const handleDelete = async () => {const updated = await deleteLoomNode(loom.id, episode.id, node.id).catch(() => null);@@ -308,18 +299,19 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCl)}<div>- <div className="flex items-center justify-between mb-1">- <span className="text-xs font-medium text-port-text-muted">Scene image</span>- <button- type="button"- onClick={runGenerateImage}- disabled={rendering || aiBlocked}- className="flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-50"- >- {rendering ? <Loader2 size={12} className="animate-spin" /> : <ImagePlus size={12} />}- Generate- </button>- </div>+ <span className="mb-1 block text-xs font-medium text-port-text-muted">Scene media</span>+ <LoomSceneMedia+ node={node}+ jobs={mediaJobs}+ onGenerateImage={runGenerateImage}+ onGenerateVideo={runGenerateVideo}+ generationDisabled={aiBlocked || generationDisabled}+ generationDisabledReason={aiBlocked ? 'Wait for scene changes to save' : generationDisabledReason}+ />+ </div>++ <div>+ <span className="mb-1 block text-xs font-medium text-port-text-muted">Scene image prompt</span><textarearows={2}className={fieldClass}@@ -329,28 +321,10 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onClonChange={(e) => setForm((p) => ({ ...p, imagePrompt: e.target.value }))}onBlur={() => saveField('imagePrompt', form.imagePrompt)}/>- {node.image && (- <MediaImage- src={`/data/images/${node.image}`}- alt={form.title || 'Scene render'}- className="mt-2 rounded max-w-full max-h-48 object-cover"- />- )}</div><div>- <div className="flex items-center justify-between mb-1">- <span className="text-xs font-medium text-port-text-muted">Scene video</span>- <button- type="button"- onClick={runGenerateVideo}- disabled={videoRendering || aiBlocked}- className="flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-50"- >- {videoRendering ? <Loader2 size={12} className="animate-spin" /> : <Video size={12} />}- Generate video- </button>- </div>+ <span className="mb-1 block text-xs font-medium text-port-text-muted">Scene video prompt</span><div className="space-y-2"><label htmlFor="loom-node-camera-movement" className={labelClass}>Camera movement</label><select@@ -381,16 +355,6 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCl/><p className="text-xs text-port-text-muted">Falls back to the scene text when no dedicated video prompt is set.</p></div>- {node.videoHistoryId && (- <video- controls- playsInline- preload="metadata"- src={`/data/videos/${encodeURIComponent(node.videoHistoryId)}.mp4`}- aria-label={form.title || 'Scene video'}- className="mt-2 rounded max-w-full max-h-56 bg-black"- />- )}</div><div>diff --git a/client/src/components/fableloom/LoomNodeEditor.test.jsx b/client/src/components/fableloom/LoomNodeEditor.test.jsxindex 984b6b7f5f..e0767a3fec 100644--- a/client/src/components/fableloom/LoomNodeEditor.test.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.test.jsx@@ -7,15 +7,12 @@ vi.mock('../../services/api', () => ({branchLoomNode: vi.fn(),deleteLoomNode: vi.fn(),deleteLoomTransition: vi.fn(),- generateImage: vi.fn(),- generateVideo: vi.fn(),updateLoomNode: vi.fn(),updateLoomTransition: vi.fn(),}));-vi.mock('../MediaImage', () => ({ default: () => null }));import {- addLoomTransition, branchLoomNode, deleteLoomTransition, generateVideo, updateLoomNode, updateLoomTransition,+ addLoomTransition, branchLoomNode, deleteLoomTransition, updateLoomNode, updateLoomTransition,} from '../../services/api';import LoomNodeEditor from './LoomNodeEditor';@@ -39,6 +36,8 @@ const renderEditor = (transitions = [existingPath]) => {const nodes = makeNodes(transitions);const episode = { id: 'ep-1', startNodeId: 'n1', nodes };const onLoomUpdate = vi.fn();+ const onGenerateImage = vi.fn().mockResolvedValue({ jobId: 'image-1' });+ const onGenerateVideo = vi.fn().mockResolvedValue({ jobId: 'video-1' });render(<LoomNodeEditorloom={loom}@@ -46,9 +45,11 @@ const renderEditor = (transitions = [existingPath]) => {node={nodes[0]}onLoomUpdate={onLoomUpdate}onClearSelection={() => {}}+ onGenerateImage={onGenerateImage}+ onGenerateVideo={onGenerateVideo}/>,);- return { onLoomUpdate };+ return { onLoomUpdate, onGenerateImage, onGenerateVideo };};beforeEach(() => vi.clearAllMocks());@@ -116,27 +117,22 @@ describe('LoomNodeEditor paths', () => {describe('LoomNodeEditor scene media', () => {it('queues a local video from the teleplay scene and rendered still', async () => {const user = userEvent.setup();- generateVideo.mockResolvedValue({ jobId: 'video-1', status: 'queued' });- renderEditor();+ const { onGenerateVideo } = renderEditor();expect(screen.getByLabelText('Video prompt')).toHaveValue('The gate opens in one continuous shot.');expect(screen.getByLabelText('Camera movement')).toHaveValue('slow-dolly-in');await user.click(screen.getByRole('button', { name: 'Generate video' }));- await waitFor(() => expect(generateVideo).toHaveBeenCalledTimes(1));- expect(generateVideo).toHaveBeenCalledWith({- prompt: 'The gate opens in one continuous shot.\n\nCamera direction: Camera slowly moves forward toward the subject.',- backend: 'local',- mode: 'image',- sourceImageFile: 'scene.png',- disableAudio: true,- fableLoom: JSON.stringify({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'n1' }),- });+ await waitFor(() => expect(onGenerateVideo).toHaveBeenCalledTimes(1));+ expect(onGenerateVideo).toHaveBeenCalledWith(expect.objectContaining({+ id: 'n1', prose: scene, image: 'scene.png',+ videoPrompt: 'The gate opens in one continuous shot.', cameraMovement: 'slow-dolly-in',+ }));});it('uses the scene for text-to-video when no rendered still exists', async () => {const user = userEvent.setup();- generateVideo.mockResolvedValue({ jobId: 'video-2', status: 'queued' });+ const onGenerateVideo = vi.fn().mockResolvedValue({ jobId: 'video-2' });const nodes = makeNodes([]).map((node) => node.id === 'n1'? { ...node, image: null, videoPrompt: '', cameraMovement: '' }: node);@@ -147,16 +143,17 @@ describe('LoomNodeEditor scene media', () => {node={nodes[0]}onLoomUpdate={vi.fn()}onClearSelection={() => {}}+ onGenerateImage={vi.fn()}+ onGenerateVideo={onGenerateVideo}/>,);await user.click(screen.getByRole('button', { name: 'Generate video' }));- await waitFor(() => expect(generateVideo).toHaveBeenCalledTimes(1));- expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({- prompt: scene, backend: 'local', mode: 'text', fableLoom: expect.any(String),+ await waitFor(() => expect(onGenerateVideo).toHaveBeenCalledTimes(1));+ expect(onGenerateVideo).toHaveBeenCalledWith(expect.objectContaining({+ prose: scene, videoPrompt: '', image: null,}));- expect(generateVideo.mock.calls[0][0]).not.toHaveProperty('sourceImageFile');});it('persists a selected camera movement from the shared vocabulary', async () => {diff --git a/client/src/components/fableloom/LoomSceneMedia.jsx b/client/src/components/fableloom/LoomSceneMedia.jsxnew file mode 100644index 0000000000..877324ea3c--- /dev/null+++ b/client/src/components/fableloom/LoomSceneMedia.jsx@@ -0,0 +1,175 @@+/**+ * FableLoom's shared scene-media surface.+ *+ * Used in both the graph node and selected-scene editor. A completed video is+ * always the final preview; otherwise the still image (or the current latent+ * frame while rendering) remains visible. Generation controls never disappear,+ * and queued/running/failed/canceled states stay visible after the POST returns.+ */++import { AlertCircle, ImagePlus, Loader2, Video } from 'lucide-react';+import MediaImage from '../MediaImage';++const ACTIVE_STATUSES = new Set(['submitting', 'queued', 'running', 'unknown']);++const isActive = (job) => Boolean(job && ACTIVE_STATUSES.has(job.status));++const progressPercent = (job) => {+ if (!job) return null;+ if (Number.isFinite(job.totalSteps) && job.totalSteps > 0 && Number.isFinite(job.step)) {+ return Math.round((job.step / job.totalSteps) * 100);+ }+ return Number.isFinite(job.progress) ? Math.round(job.progress * 100) : null;+};++const jobStateLabel = (kind, job) => {+ const noun = kind === 'video' ? 'video' : 'image';+ if (!job) return null;+ if (job.status === 'failed') return `${noun[0].toUpperCase()}${noun.slice(1)} failed`;+ if (job.status === 'canceled') return `${noun[0].toUpperCase()}${noun.slice(1)} canceled`;+ if (!isActive(job)) return null;+ const pct = progressPercent(job);+ return job.status === 'submitting'+ ? `Starting ${noun}…`+ : `Generating ${noun}${pct !== null ? ` ${pct}%` : '…'}`;+};++export default function LoomSceneMedia({+ node,+ jobs = {},+ onGenerateImage,+ onGenerateVideo,+ compact = false,+ generationDisabled = false,+ generationDisabledReason = '',+}) {+ const imageJob = jobs.image || null;+ const videoJob = jobs.video || null;+ const imageActive = isActive(imageJob);+ const videoActive = isActive(videoJob);+ const activeJob = videoActive ? videoJob : imageActive ? imageJob : null;+ const activeKind = videoActive ? 'video' : imageActive ? 'image' : null;+ const failedJob = videoJob?.status === 'failed'+ ? { kind: 'video', ...videoJob }+ : imageJob?.status === 'failed'+ ? { kind: 'image', ...imageJob }+ : null;+ const canceledJob = !failedJob && (videoJob?.status === 'canceled'+ ? { kind: 'video', ...videoJob }+ : imageJob?.status === 'canceled'+ ? { kind: 'image', ...imageJob }+ : null);+ const noticeJob = failedJob || canceledJob;+ const noticeLabel = noticeJob && jobStateLabel(noticeJob.kind, noticeJob);+ const activeLabel = activeKind && jobStateLabel(activeKind, activeJob);+ const title = node.title || 'Scene';++ // The final video wins. During a new video render its live frame wins; when+ // no live frame exists, retain the still rather than replacing useful visual+ // context with an empty spinner.+ const showFinalVideo = Boolean(node.videoHistoryId) && !videoActive;+ const liveFrame = activeJob?.currentImage || null;+ const showStill = !showFinalVideo && !liveFrame && Boolean(node.image);+ const showSpinner = !showFinalVideo && !liveFrame && !showStill && Boolean(activeJob);++ const stopNodeActivation = (event) => event.stopPropagation();+ const buttonClass = compact+ ? 'inline-flex min-w-0 items-center justify-center gap-1 rounded border border-port-border bg-port-bg/80 px-1.5 py-1 text-[9px] text-port-text hover:border-port-accent hover:text-port-accent disabled:opacity-45'+ : 'inline-flex items-center justify-center gap-1.5 rounded border border-port-border px-2.5 py-1.5 text-xs text-port-text hover:border-port-accent hover:text-port-accent disabled:opacity-45';++ return (+ <div className={compact ? 'flex h-full min-h-0 flex-col gap-1' : 'space-y-2'}>+ <div className={`relative min-h-0 overflow-hidden rounded border border-port-border bg-port-bg ${compact ? 'flex-1' : 'aspect-video max-h-56'}`}>+ {showFinalVideo ? (+ <video+ src={`/data/videos/${encodeURIComponent(node.videoHistoryId)}.mp4`}+ aria-label={`${title} video preview`}+ className="h-full w-full object-cover"+ controls={!compact}+ autoPlay={compact}+ muted={compact}+ loop={compact}+ playsInline+ preload={compact ? 'metadata' : 'none'}+ onPointerDown={stopNodeActivation}+ onClick={stopNodeActivation}+ />+ ) : liveFrame ? (+ <img+ src={`data:image/png;base64,${liveFrame}`}+ alt={`${title} ${activeKind} generation preview`}+ className="h-full w-full object-cover"+ />+ ) : showStill ? (+ <MediaImage+ src={`/data/images/${node.image}`}+ alt={`${title} image preview`}+ className="h-full w-full object-cover"+ />+ ) : showSpinner ? (+ <div className="grid h-full min-h-16 place-items-center text-port-accent">+ <Loader2 size={compact ? 16 : 22} className="animate-spin" aria-hidden="true" />+ </div>+ ) : (+ <div className="flex h-full min-h-16 flex-col items-center justify-center gap-1 text-port-text-muted">+ <ImagePlus size={compact ? 15 : 22} aria-hidden="true" />+ <span className={compact ? 'text-[9px]' : 'text-xs'}>No scene media yet</span>+ </div>+ )}++ {activeLabel && (+ <div className="port-media-overlay absolute inset-x-0 bottom-0 px-2 py-1 text-center text-[9px] font-medium" role="status">+ {activeLabel}+ </div>+ )}+ {noticeLabel && (+ <div+ className="port-media-overlay-strong absolute inset-x-0 bottom-0 flex items-center justify-center gap-1 px-2 py-1 text-[9px] font-medium text-port-error"+ role={compact ? 'alert' : undefined}+ title={noticeJob.error || noticeLabel}+ >+ <AlertCircle size={10} aria-hidden="true" /> {noticeLabel}+ </div>+ )}+ </div>++ <div+ className="grid shrink-0 grid-cols-2 gap-1"+ onPointerDown={stopNodeActivation}+ onClick={stopNodeActivation}+ onKeyDown={stopNodeActivation}+ >+ <button+ type="button"+ onClick={() => onGenerateImage?.(node)}+ disabled={imageActive || generationDisabled || !onGenerateImage}+ title={generationDisabledReason || (node.image ? 'Regenerate scene image' : 'Generate scene image')}+ className={buttonClass}+ >+ {imageActive ? <Loader2 size={compact ? 10 : 12} className="animate-spin" /> : <ImagePlus size={compact ? 10 : 12} />}+ <span className="truncate">{imageActive ? 'Generating image' : node.image ? 'Regenerate image' : 'Generate image'}</span>+ </button>+ <button+ type="button"+ onClick={() => onGenerateVideo?.(node)}+ disabled={videoActive || generationDisabled || !onGenerateVideo}+ title={generationDisabledReason || (node.videoHistoryId ? 'Regenerate scene video' : 'Generate scene video')}+ className={buttonClass}+ >+ {videoActive ? <Loader2 size={compact ? 10 : 12} className="animate-spin" /> : <Video size={compact ? 10 : 12} />}+ <span className="truncate">{videoActive ? 'Generating video' : node.videoHistoryId ? 'Regenerate video' : 'Generate video'}</span>+ </button>+ </div>++ {noticeLabel && !compact && (+ <p className="flex items-start gap-1 text-xs text-port-error" role="alert">+ <AlertCircle size={13} className="mt-0.5 shrink-0" aria-hidden="true" />+ <span>{noticeLabel}{noticeJob.error ? `: ${noticeJob.error}` : ''}</span>+ </p>+ )}+ {generationDisabledReason && !noticeLabel && !compact && (+ <p className="text-xs text-port-text-muted" role="status">{generationDisabledReason}</p>+ )}+ </div>+ );+}diff --git a/client/src/components/fableloom/sceneMediaRequests.js b/client/src/components/fableloom/sceneMediaRequests.jsnew file mode 100644index 0000000000..39279438ee--- /dev/null+++ b/client/src/components/fableloom/sceneMediaRequests.js@@ -0,0 +1,45 @@+/**+ * Shared FableLoom scene-media request builders.+ *+ * Both the graph-card buttons and the selected-scene editor queue through the+ * page owner. Keeping request composition here makes their image/video prompts+ * identical: the canonical universe/series style preset leads, the scene owns+ * the subject/action, and loom-local direction remains an explicit suffix.+ */++import { composeStyledPrompt } from '../../lib/composeStyledPrompt';+import { FABLELOOM_CAMERA_MOVEMENTS } from '../../../../server/lib/fableLoomCameraMovements.js';++const withLoomStyle = (prompt, styleNotes) => {+ const notes = typeof styleNotes === 'string' ? styleNotes.trim() : '';+ return notes ? `${prompt}\n\nStyle: ${notes}` : prompt;+};++export function buildFableLoomImageRequest({ loom, episodeId, node, stylePreset = null }) {+ const authoredPrompt = withLoomStyle((node?.imagePrompt || '').trim(), loom?.styleNotes);+ const styled = composeStyledPrompt(authoredPrompt, '', stylePreset);+ return {+ prompt: styled.prompt,+ ...(styled.negativePrompt ? { negativePrompt: styled.negativePrompt } : {}),+ fableLoom: { loomId: loom.id, episodeId, nodeId: node.id },+ };+}++export function buildFableLoomVideoRequest({ loom, episodeId, node, stylePreset = null }) {+ const authoredPrompt = (node?.videoPrompt || '').trim() || (node?.prose || '').trim();+ const movement = FABLELOOM_CAMERA_MOVEMENTS.find((move) => move.value === node?.cameraMovement);+ const direction = movement?.prompt || (node?.cameraMovement || '').trim();+ const directedPrompt = direction+ ? `${authoredPrompt}\n\nCamera direction: ${direction}`+ : authoredPrompt;+ const styled = composeStyledPrompt(withLoomStyle(directedPrompt, loom?.styleNotes), '', stylePreset);+ return {+ prompt: styled.prompt,+ ...(styled.negativePrompt ? { negativePrompt: styled.negativePrompt } : {}),+ backend: 'local',+ mode: node?.image ? 'image' : 'text',+ ...(node?.image ? { sourceImageFile: node.image } : {}),+ disableAudio: true,+ fableLoom: JSON.stringify({ loomId: loom.id, episodeId, nodeId: node.id }),+ };+}diff --git a/client/src/components/fableloom/sceneMediaRequests.test.js b/client/src/components/fableloom/sceneMediaRequests.test.jsnew file mode 100644index 0000000000..8a3c1ed85d--- /dev/null+++ b/client/src/components/fableloom/sceneMediaRequests.test.js@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';+import { buildFableLoomImageRequest, buildFableLoomVideoRequest } from './sceneMediaRequests';++const loom = { id: 'loom-1', styleNotes: 'cool rim light' };++describe('FableLoom scene media request composition', () => {+ it('prefixes the canonical universe style and carries its avoid list into image generation', () => {+ expect(buildFableLoomImageRequest({+ loom,+ episodeId: 'ep-1',+ node: { id: 'node-1', imagePrompt: 'a scout wakes in alien grass' },+ stylePreset: { prompt: 'painted graphic novel', negativePrompt: 'photorealism' },+ })).toEqual({+ prompt: 'painted graphic novel. a scout wakes in alien grass\n\nStyle: cool rim light',+ negativePrompt: 'photorealism',+ fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' },+ });+ });++ it('builds image-to-video direction from the shared camera vocabulary', () => {+ expect(buildFableLoomVideoRequest({+ loom,+ episodeId: 'ep-1',+ node: {+ id: 'node-1',+ prose: 'The gate opens.',+ videoPrompt: 'One continuous reveal.',+ cameraMovement: 'slow-dolly-in',+ image: 'scene.png',+ },+ stylePreset: { prompt: 'painted graphic novel', negativePrompt: 'photorealism' },+ })).toEqual({+ prompt: 'painted graphic novel. One continuous reveal.\n\nCamera direction: Camera slowly moves forward toward the subject.\n\nStyle: cool rim light',+ negativePrompt: 'photorealism',+ backend: 'local',+ mode: 'image',+ sourceImageFile: 'scene.png',+ disableAudio: true,+ fableLoom: JSON.stringify({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' }),+ });+ });+});diff --git a/client/src/lib/loomLayout.js b/client/src/lib/loomLayout.jsindex 7958b6a628..1daa6c0bc9 100644--- a/client/src/lib/loomLayout.js+++ b/client/src/lib/loomLayout.js@@ -24,7 +24,10 @@*/export const LOOM_NODE_W = 200;-export const LOOM_NODE_H = 112;+// Tall enough for the scene's visual preview + always-visible image/video+// controls. The graph is a visual editor, so media is the card's primary body+// rather than a thumbnail squeezed beside prose.+export const LOOM_NODE_H = 184;/** Longest intent text drawn on an edge before it is ellipsized. */export const LOOM_EDGE_LABEL_MAX = 24;export const LOOM_ORIENTATION = Object.freeze({ LR: 'lr', TB: 'tb' });diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsxindex 9a83820441..0b76703d49 100644--- a/client/src/pages/FableLoomStory.jsx+++ b/client/src/pages/FableLoomStory.jsx@@ -12,7 +12,7 @@* thing you scroll.*/-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';import { Link, Navigate, useNavigate, useParams, useSearchParams } from 'react-router';import { ArrowLeft, BookOpenText, ListTree, Loader2, Plus, Settings, Sparkles, Trash2, Waypoints, Workflow as WorkflowIcon } from 'lucide-react';import toast from '../components/ui/Toast';@@ -27,16 +27,22 @@ import useContainerWidth from '../hooks/useContainerWidth';import LoomCanvas from '../components/fableloom/LoomCanvas';import LoomEpisodeOutline from '../components/fableloom/LoomEpisodeOutline';import LoomEpisodeFeedback from '../components/fableloom/LoomEpisodeFeedback';+import LoomMediaJobWatchers from '../components/fableloom/LoomMediaJobWatchers';import LoomNodeEditor from '../components/fableloom/LoomNodeEditor';import LoomPlayPanel from '../components/fableloom/LoomPlayPanel';import LoomSettingsDrawer from '../components/fableloom/LoomSettingsDrawer';import LoomSeriesPlan from '../components/fableloom/LoomSeriesPlan';import LoomValidationPanel from '../components/fableloom/LoomValidationPanel';import { fieldClass, labelClass } from '../components/fableloom/fieldStyles';+import {+ buildFableLoomImageRequest, buildFableLoomVideoRequest,+} from '../components/fableloom/sceneMediaRequests';+import { universeStylePreset } from '../lib/universeStylePreset';import { LOOM_ORIENTATION, LOOM_STACK_WIDTH } from '../lib/loomLayout';import {- addLoomEpisode, addLoomNode, deleteLoomEpisode, getLoom, getPipelineSeries,- updateLoomEpisode, updateLoomNode, weaveLoomEpisode,+ addLoomEpisode, addLoomNode, deleteLoomEpisode, generateImage, generateVideo,+ getLoom, getPipelineSeries, getUniverse, updateLoomEpisode, updateLoomNode,+ weaveLoomEpisode,} from '../services/api';export default function FableLoomStory({ view = 'graph' }) {@@ -48,6 +54,13 @@ export default function FableLoomStory({ view = 'graph' }) {// `seriesId` is a soft ref: deleting the series is allowed and leaves the id// dangling, so an unresolvable id renders NO chip rather than a dead link.const [linkedSeries, setLinkedSeries] = useState(null);+ const [linkedSeriesStatus, setLinkedSeriesStatus] = useState('idle');+ const [linkedUniverse, setLinkedUniverse] = useState(null);+ const [linkedUniverseStatus, setLinkedUniverseStatus] = useState('idle');+ // nodeId -> { image?: job snapshot, video?: job snapshot }. The page owns+ // this so the graph card and editor rail display one shared lifecycle and the+ // socket hook mounts exactly once per job.+ const [mediaJobs, setMediaJobs] = useState({});const [notFound, setNotFound] = useState(false);const [setupOpen, setSetupOpen] = useState(false);const [settingsOpen, setSettingsOpen] = useState(false);@@ -64,6 +77,7 @@ export default function FableLoomStory({ view = 'graph' }) {useEffect(() => {setNotFound(false);+ setMediaJobs({});getLoom(loomId).then(setLoom).catch(() => setNotFound(true));}, [loomId]);@@ -71,18 +85,218 @@ export default function FableLoomStory({ view = 'graph' }) {useEffect(() => {if (!linkedSeriesId) {setLinkedSeries(null);+ setLinkedSeriesStatus('idle');return undefined;}let canceled = false;+ setLinkedSeries(null);+ setLinkedSeriesStatus('loading');getPipelineSeries(linkedSeriesId, { silent: true })- .then((series) => { if (!canceled) setLinkedSeries(series || null); })- .catch(() => { if (!canceled) setLinkedSeries(null); });+ .then((series) => {+ if (canceled) return;+ setLinkedSeries(series || null);+ setLinkedSeriesStatus(series ? 'ready' : 'unavailable');+ })+ .catch(() => {+ if (canceled) return;+ setLinkedSeries(null);+ setLinkedSeriesStatus('unavailable');+ });return () => { canceled = true; };}, [linkedSeriesId]);+ // A loom normally carries universeId directly. The series fallback covers+ // older/hand-linked records whose visual context exists only on the series.+ const linkedUniverseId = loom?.universeId || linkedSeries?.universeId || null;+ useEffect(() => {+ if (!linkedUniverseId) {+ setLinkedUniverse(null);+ setLinkedUniverseStatus('idle');+ return undefined;+ }+ let canceled = false;+ setLinkedUniverse(null);+ setLinkedUniverseStatus('loading');+ getUniverse(linkedUniverseId, { silent: true })+ .then((universe) => {+ if (canceled) return;+ setLinkedUniverse(universe || null);+ setLinkedUniverseStatus(universe ? 'ready' : 'unavailable');+ })+ .catch(() => {+ if (canceled) return;+ setLinkedUniverse(null);+ setLinkedUniverseStatus('unavailable');+ });+ return () => { canceled = true; };+ }, [linkedUniverseId]);++ const seriesStylePending = Boolean(linkedSeriesId)+ && linkedSeriesStatus !== 'ready'+ && linkedSeriesStatus !== 'unavailable';+ const universeStylePending = Boolean(linkedUniverseId)+ && linkedUniverseStatus !== 'ready'+ && linkedUniverseStatus !== 'unavailable';+ const styleContextLoading = seriesStylePending || universeStylePending;+ const styleContextUnavailable = Boolean(linkedUniverseId) && linkedUniverseStatus === 'unavailable';+ const generationDisabledReason = styleContextLoading+ ? 'Loading linked universe style…'+ : styleContextUnavailable+ ? 'Linked universe style is unavailable'+ : '';+ const sceneStylePreset = useMemo(+ () => universeStylePreset(linkedUniverse, linkedSeries),+ [linkedSeries, linkedUniverse],+ );+const episode = seriesPlanOpen ? null : loom?.episodes.find((e) => e.id === episodeId) || null;const node = episode?.nodes.find((n) => n.id === nodeId) || null;+ const setSceneMediaJob = useCallback((targetNodeId, kind, nextJob) => {+ setMediaJobs((prev) => {+ const currentNodeJobs = prev[targetNodeId] || {};+ if (nextJob) {+ return { ...prev, [targetNodeId]: { ...currentNodeJobs, [kind]: nextJob } };+ }+ const nextNodeJobs = { ...currentNodeJobs };+ delete nextNodeJobs[kind];+ if (Object.keys(nextNodeJobs).length > 0) return { ...prev, [targetNodeId]: nextNodeJobs };+ const next = { ...prev };+ delete next[targetNodeId];+ return next;+ });+ }, []);++ const handleMediaJobUpdate = useCallback((targetNodeId, kind, jobId, progress) => {+ setMediaJobs((prev) => {+ const current = prev[targetNodeId]?.[kind];+ if (!current || current.jobId !== jobId) return prev;+ return {+ ...prev,+ [targetNodeId]: {+ ...prev[targetNodeId],+ [kind]: { ...current, ...progress, jobId },+ },+ };+ });+ }, []);++ const applySceneMedia = useCallback((targetNodeId, patch) => {+ setLoom((prev) => (prev ? {+ ...prev,+ episodes: prev.episodes.map((item) => ({+ ...item,+ nodes: item.nodes.map((scene) => (scene.id === targetNodeId ? { ...scene, ...patch } : scene)),+ })),+ } : prev));+ }, []);++ const handleMediaJobTerminal = useCallback((targetNodeId, kind, jobId, progress) => {+ const label = kind === 'video' ? 'video' : 'image';+ if (progress.status === 'failed') {+ toast.error(`Scene ${label} generation failed${progress.error ? `: ${progress.error}` : ''}`);+ return;+ }+ if (progress.status === 'canceled') return;+ if (progress.status !== 'completed') return;++ if (kind === 'image') {+ applySceneMedia(targetNodeId, { image: progress.filename, imageJobId: jobId });+ } else {+ applySceneMedia(targetNodeId, { videoHistoryId: jobId });+ }+ setSceneMediaJob(targetNodeId, kind, null);+ toast.success(`Scene ${label} ready`);+ }, [applySceneMedia, setSceneMediaJob]);++ const queueSceneImage = useCallback(async (targetNode) => {+ const prompt = (targetNode?.imagePrompt || '').trim();+ if (!prompt) {+ toast.error('Write an image prompt first');+ return null;+ }+ if (styleContextLoading || styleContextUnavailable) {+ toast.error(generationDisabledReason || 'Scene style is not ready');+ return null;+ }++ setSceneMediaJob(targetNode.id, 'image', { jobId: null, status: 'submitting', progress: 0 });+ const queued = await generateImage(buildFableLoomImageRequest({+ loom, episodeId, node: targetNode, stylePreset: sceneStylePreset,+ }), { silent: true }).catch((err) => {+ setSceneMediaJob(targetNode.id, 'image', {+ jobId: null, status: 'failed', progress: 0, error: err.message || 'Could not start the render',+ });+ toast.error(`Could not start scene image: ${err.message || 'Render request failed'}`);+ return null;+ });+ if (!queued) return null;+ // External SD-API renders synchronously: its generationId identifies the+ // completed request, not a media-job record. The server has already filed+ // the image onto the scene, so swap the preview immediately and do not+ // mount a watcher that would poll a nonexistent queue job.+ if (!queued.jobId && queued.filename) {+ applySceneMedia(targetNode.id, {+ image: queued.filename,+ imageJobId: queued.generationId || null,+ });+ setSceneMediaJob(targetNode.id, 'image', null);+ toast.success('Scene image ready');+ return queued;+ }+ // `generationId` was the queue id on older route responses, but external+ // synchronous results carry no status. Keep that compatibility without+ // confusing their transient generation id for a pollable job.+ const jobId = queued.jobId || (queued.status ? queued.generationId : null);+ if (!jobId) {+ const error = 'Image generator returned no job id';+ setSceneMediaJob(targetNode.id, 'image', { jobId: null, status: 'failed', progress: 0, error });+ toast.error(error);+ return null;+ }+ setSceneMediaJob(targetNode.id, 'image', {+ jobId, status: queued.status || 'queued', progress: 0,+ });+ toast.success('Scene image queued');+ return queued;+ }, [applySceneMedia, episodeId, generationDisabledReason, loom, sceneStylePreset, setSceneMediaJob, styleContextLoading, styleContextUnavailable]);++ const queueSceneVideo = useCallback(async (targetNode) => {+ const prompt = (targetNode?.videoPrompt || '').trim() || (targetNode?.prose || '').trim();+ if (!prompt) {+ toast.error('Write the scene first');+ return null;+ }+ if (styleContextLoading || styleContextUnavailable) {+ toast.error(generationDisabledReason || 'Scene style is not ready');+ return null;+ }++ setSceneMediaJob(targetNode.id, 'video', { jobId: null, status: 'submitting', progress: 0 });+ const queued = await generateVideo(buildFableLoomVideoRequest({+ loom, episodeId, node: targetNode, stylePreset: sceneStylePreset,+ })).catch((err) => {+ setSceneMediaJob(targetNode.id, 'video', {+ jobId: null, status: 'failed', progress: 0, error: err.message || 'Could not start the render',+ });+ toast.error(`Could not start scene video: ${err.message || 'Render request failed'}`);+ return null;+ });+ if (!queued) return null;+ const jobId = queued.jobId || queued.generationId;+ if (!jobId) {+ const error = 'Video generator returned no job id';+ setSceneMediaJob(targetNode.id, 'video', { jobId: null, status: 'failed', progress: 0, error });+ toast.error(error);+ return null;+ }+ setSceneMediaJob(targetNode.id, 'video', {+ jobId, status: queued.status || 'queued', progress: 0,+ });+ toast.success('Scene video queued');+ return queued;+ }, [episodeId, generationDisabledReason, loom, sceneStylePreset, setSceneMediaJob, styleContextLoading, styleContextUnavailable]);+const basePath = `/fableloom/${loomId}`;const episodePath = useCallback((epId, nId) => `${basePath}/${epId}${nId ? `/${nId}` : ''}`,@@ -176,6 +390,11 @@ export default function FableLoomStory({ view = 'graph' }) {return (<div ref={pageRef} className="h-full flex flex-col">+ <LoomMediaJobWatchers+ jobs={mediaJobs}+ onUpdate={handleMediaJobUpdate}+ onTerminal={handleMediaJobTerminal}+ /><header className="border-b border-port-border px-4 py-2.5 space-y-2"><div className="flex items-center gap-3 flex-wrap"><Link to="/fableloom" className="text-port-text-muted hover:text-port-text" aria-label="Back to FableLoom">@@ -301,6 +520,11 @@ export default function FableLoomStory({ view = 'graph' }) {onSelectNode={selectNode}onMoveNode={handleMoveNode}orientation={graphOrientation}+ mediaJobs={mediaJobs}+ onGenerateImage={queueSceneImage}+ onGenerateVideo={queueSceneVideo}+ generationDisabled={styleContextLoading || styleContextUnavailable}+ generationDisabledReason={generationDisabledReason}/>) : (<div className="h-full grid place-items-center p-8 text-center">@@ -340,6 +564,11 @@ export default function FableLoomStory({ view = 'graph' }) {node={node}onLoomUpdate={setLoom}onClearSelection={() => navigate(episodePath(episode.id))}+ mediaJobs={mediaJobs[node.id]}+ onGenerateImage={queueSceneImage}+ onGenerateVideo={queueSceneVideo}+ generationDisabled={styleContextLoading || styleContextUnavailable}+ generationDisabledReason={generationDisabledReason}onMakeStart={node.id !== episode.startNodeId ? async () => {const updated = await updateLoomEpisode(loomId, episode.id, { startNodeId: node.id }).catch(() => null);diff --git a/client/src/pages/FableLoomStory.test.jsx b/client/src/pages/FableLoomStory.test.jsxindex 8dfdda4df5..70c038318e 100644--- a/client/src/pages/FableLoomStory.test.jsx+++ b/client/src/pages/FableLoomStory.test.jsx@@ -1,22 +1,61 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, waitFor } from '@testing-library/react';import { MemoryRouter, Route, Routes } from 'react-router';+import userEvent from '@testing-library/user-event';++const toastMocks = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));+vi.mock('../components/ui/Toast', () => ({ default: toastMocks }));vi.mock('../services/api', () => ({addLoomEpisode: vi.fn(),addLoomNode: vi.fn(),deleteLoomEpisode: vi.fn(),+ generateImage: vi.fn(),+ generateVideo: vi.fn(),getLoom: vi.fn(),getPipelineSeries: vi.fn(),+ getUniverse: vi.fn(),updateLoomEpisode: vi.fn(),updateLoom: vi.fn(),updateLoomNode: vi.fn(),weaveLoomEpisode: vi.fn(),}));-// The graph canvas and the rails are irrelevant to the header — stub them so-// the suite exercises the loom → series backlink and nothing else.-vi.mock('../components/fableloom/LoomCanvas', () => ({ default: () => <div /> }));+// Keep the graph lightweight while exposing its page-owned scene-media action+// and state. The canvas component itself covers preview/button rendering.+vi.mock('../components/fableloom/LoomCanvas', () => ({+ default: ({ episode, mediaJobs, onGenerateImage, generationDisabled }) => (+ <div>+ <button+ type="button"+ disabled={generationDisabled}+ onClick={() => onGenerateImage(episode.nodes[0])}+ >+ Canvas generate image+ </button>+ <span data-testid="canvas-image-status">{mediaJobs[episode.nodes[0].id]?.image?.status || 'idle'}</span>+ <span data-testid="canvas-image-filename">{episode.nodes[0].image || 'none'}</span>+ </div>+ ),+}));+vi.mock('../components/fableloom/LoomMediaJobWatchers', () => ({+ default: ({ jobs, onUpdate, onTerminal }) => {+ const image = jobs['node-1']?.image;+ if (!image?.jobId) return null;+ return (+ <button+ type="button"+ onClick={() => {+ const failed = { ...image, status: 'failed', error: 'Synthetic provider failure' };+ onUpdate('node-1', 'image', image.jobId, failed);+ onTerminal('node-1', 'image', image.jobId, failed);+ }}+ >+ Simulate image failure+ </button>+ );+ },+}));vi.mock('../components/fableloom/LoomEpisodeOutline', () => ({ default: ({ episode }) => <div data-testid="episode-outline">{episode.title}</div> }));vi.mock('../components/fableloom/LoomNodeEditor', () => ({ default: () => <div /> }));vi.mock('../components/fableloom/LoomPlayPanel', () => ({ default: () => <div /> }));@@ -61,6 +100,7 @@ const renderEditor = () => render(beforeEach(() => {vi.clearAllMocks();api.getLoom.mockResolvedValue(loom());+ api.getUniverse.mockResolvedValue(null);});describe('FableLoomStory navigation and series backlink', () => {@@ -144,3 +184,74 @@ describe('FableLoomStory episode outline route', () => {expect(screen.getByRole('tab', { name: 'Outline' })).toHaveAttribute('aria-selected', 'true');});});++describe('FableLoomStory scene media lifecycle', () => {+ it('queues with canonical universe style and notifies when the render later fails', async () => {+ const user = userEvent.setup();+ api.getLoom.mockResolvedValue(loom({+ universeId: 'universe-1',+ styleNotes: 'blue dusk lighting',+ episodes: [episode({+ nodes: [{+ id: 'node-1',+ title: 'Threshold',+ prose: 'You stand before the first door.',+ imagePrompt: 'an ancient gate in alien grass',+ transitions: [],+ }],+ })],+ }));+ api.getUniverse.mockResolvedValue({+ id: 'universe-1',+ influences: { embrace: ['painted ink'], avoid: ['photorealism'] },+ });+ api.generateImage.mockResolvedValue({ jobId: 'image-job-1', status: 'queued' });+ renderEditor();++ const generate = await screen.findByRole('button', { name: 'Canvas generate image' });+ await waitFor(() => expect(generate).toBeEnabled());+ await user.click(generate);++ await waitFor(() => expect(api.generateImage).toHaveBeenCalledTimes(1));+ expect(api.generateImage).toHaveBeenCalledWith({+ prompt: 'painted ink. an ancient gate in alien grass\n\nStyle: blue dusk lighting',+ negativePrompt: 'photorealism',+ fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' },+ }, { silent: true });+ expect(screen.getByTestId('canvas-image-status')).toHaveTextContent('queued');++ await user.click(screen.getByRole('button', { name: 'Simulate image failure' }));+ await waitFor(() => expect(screen.getByTestId('canvas-image-status')).toHaveTextContent('failed'));+ expect(toastMocks.error).toHaveBeenCalledWith(+ 'Scene image generation failed: Synthetic provider failure',+ );+ });++ it('shows a synchronously generated scene image without watching a nonexistent job', async () => {+ const user = userEvent.setup();+ api.getLoom.mockResolvedValue(loom({+ episodes: [episode({+ nodes: [{+ id: 'node-1',+ title: 'Threshold',+ prose: 'You stand before the first door.',+ imagePrompt: 'an example threshold',+ transitions: [],+ }],+ })],+ }));+ api.generateImage.mockResolvedValue({+ generationId: 'sync-generation-1',+ filename: 'finished-scene.png',+ path: '/data/images/finished-scene.png',+ });+ renderEditor();++ await user.click(await screen.findByRole('button', { name: 'Canvas generate image' }));++ await waitFor(() => expect(screen.getByTestId('canvas-image-filename'))+ .toHaveTextContent('finished-scene.png'));+ expect(screen.getByTestId('canvas-image-status')).toHaveTextContent('idle');+ expect(toastMocks.success).toHaveBeenCalledWith('Scene image ready');+ });+});diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 653f1fa188..a946f9c6cb 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -45,6 +45,7 @@ import { getSettings } from '../services/settings.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';import { collectRemoteInputAssets } from '../services/federatedMedia/inputAssets.js';import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';+import { attachNodeImage } from '../services/fableLoom/records.js';const router = Router();@@ -162,8 +163,8 @@ const generateSchema = z.object({// (`fableLoomSceneImageHook`) files the finished render onto that loom// episode's scene node — durably, even if the editor unmounted mid-render.// Only the async local/Codex lanes ride the queue; the synchronous external- // SD-API lane returns the filename inline and the client PATCHes the node.- // Rides into job.params untouched via `...params`. JSON-only.+ // SD-API lane is attached directly by this route after generation. Rides+ // into job.params untouched via `...params`. JSON-only.fableLoom: z.object({loomId: z.string().min(1).max(200),episodeId: z.string().min(1).max(200),@@ -541,7 +542,16 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {model: selectedModel?.id || params.modelId || 'dev',}));}- res.json(await imageGen.generateImage(params));+ const result = await imageGen.generateImage(params);+ if (params.fableLoom && result?.filename) {+ await attachNodeImage(+ params.fableLoom.loomId,+ params.fableLoom.episodeId,+ params.fableLoom.nodeId,+ { filename: result.filename, jobId: result.generationId },+ );+ }+ res.json(result);}));router.post('/avatar', asyncHandler(async (req, res) => {diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 754ae0734e..243faf8aa2 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -10,6 +10,9 @@ import { writeFile, rm } from 'fs/promises';import { tmpdir } from 'os';import { join as pathJoin } from 'path';+const attachNodeImage = vi.hoisted(() => vi.fn(async () => ({})));+vi.mock('../services/fableLoom/records.js', () => ({ attachNodeImage }));+vi.mock('../services/imageGen/index.js', () => ({checkConnection: vi.fn(),generateImage: vi.fn(),@@ -229,6 +232,29 @@ describe('Image Gen Routes', () => {expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ prompt: 'a fantasy landscape' }));});+ it('durably attaches a synchronous FableLoom scene render', async () => {+ imageGen.generateImage.mockResolvedValue({+ generationId: 'gen-scene-001',+ filename: 'scene.png',+ path: '/data/images/scene.png',+ });++ const response = await request(app)+ .post('/api/image-gen/generate')+ .send({+ prompt: 'an example scene',+ fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' },+ });++ expect(response.status).toBe(200);+ expect(attachNodeImage).toHaveBeenCalledWith(+ 'loom-1',+ 'ep-1',+ 'node-1',+ { filename: 'scene.png', jobId: 'gen-scene-001' },+ );+ });+it('accepts a missing/empty prompt (i2i / edit / unconditional), defaulting it to empty', async () => {imageGen.generateImage.mockResolvedValue({generationId: 'gen-empty',diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 71baa4c14c..3f9962e6b7 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -9,10 +9,10 @@* Wire format: `codex exec --skip-git-repo-check --sandbox workspace-write* '$imagegen <prompt>'`. Codex prints a `session id: <uuid>` banner on stderr* and usually writes the final PNG to- * `~/.codex/generated_images/<session-id>/ig_*.png`. Newer Codex builds can- * keep the image bytes only in the session JSONL's `image_generation_end`- * event, so we parse the banner and harvest both locations after the child- * exits.+ * `~/.codex/generated_images/<session-id>/*.png` (`ig_*.png` historically;+ * newer builds use `exec-*.png`). Other Codex builds can keep the image bytes+ * only in the session JSONL's `image_generation_end` event, so we parse the+ * banner and harvest both locations after the child exits.** The user must explicitly enable this provider in Settings → Image Gen* because not every Codex account has access to the `image_gen` tool. When@@ -460,14 +460,15 @@ const finalizeError = (job, jobId, proc, reason) => {closeJobAfterDelay(jobs, jobId);};-// Returns the absolute path to the newest ig_*.png in the session dir, or-// null if none appears within `timeoutMs`. Polls every 250ms — the file-// usually lands in <1s but the rare slow case is fine.+// Returns the absolute path to the newest PNG in the session dir. Codex has+// used both `ig_*.png` and `exec-*.png`; the per-session directory is already+// the ownership boundary, so a filename-prefix allowlist only turns valid tool+// output into a false failure when the CLI changes its internal naming again.async function latestGeneratedImageFile(sessionId) {const dir = codexImagesDir(sessionId);if (!existsSync(dir)) return null;const names = await readdir(dir).catch(() => []);- const pngs = names.filter((f) => f.startsWith('ig_') && f.endsWith('.png'));+ const pngs = names.filter((name) => name.toLowerCase().endsWith('.png'));if (pngs.length) {const stats = await Promise.all(pngs.map(async (n) => {const s = await stat(join(dir, n)).catch(() => null);@@ -543,8 +544,8 @@ async function harvestGeneratedImage(sessionId, timeoutMs) {if (path) return { path };// Newer Codex builds may persist image bytes only in the session JSONL as- // image_generation_end.result (base64), without materializing- // ~/.codex/generated_images/<session-id>/ig_*.png. Decode that fallback so+ // image_generation_end.result (base64), without materializing a PNG in+ // ~/.codex/generated_images/<session-id>/. Decode that fallback so// a real generation does not get reported as "success but no file".const sessionImage = await harvestSessionLogImage(sessionId);if (sessionImage) return { buffer: sessionImage.buffer, sessionLogPath: sessionImage.path };diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex 6ef3f68ca9..7e6d4f4db8 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -331,7 +331,7 @@ describe('codex provider — generateImage', () => {});describe('codex provider — image harvest', () => {- it('copies the latest ig_*.png from ~/.codex/generated_images/<session-id>/ into PATHS.images', async () => {+ it('copies the latest PNG from ~/.codex/generated_images/<session-id>/ into PATHS.images', async () => {const sessionId = '019dd59e-a8da-7bd2-a7d8-4ac6f46e7b07';const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);await mkdir(codexDir, { recursive: true });@@ -367,6 +367,27 @@ describe('codex provider — image harvest', () => {expect(existsSync(sidecar)).toBe(true);});+ it('harvests the exec-named PNG emitted by newer Codex image tools', async () => {+ const sessionId = '33333333-3333-4333-8333-333333333333';+ const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);+ await mkdir(codexDir, { recursive: true });+ const fakePngBytes = Buffer.from('new-codex-png');+ await writeFile(join(codexDir, 'exec-example-output.png'), fakePngBytes);++ const completedListener = vi.fn();+ imageGenEvents.on('completed', completedListener);++ const job = await codex.generateImage({ prompt: 'an example landscape' });+ const child = spawnCalls[0].child;+ child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));+ child.stdout.emit('data', Buffer.from('[Generated image](sandbox:/example/generated_images/session/exec-example-output.png)'));+ child.exitCode = 0;+ child.emit('close', 0, null);++ await vi.waitFor(() => expect(completedListener).toHaveBeenCalledTimes(1));+ expect(await readFile(join(FAKE_IMAGES_DIR, job.filename))).toEqual(fakePngBytes);+ });+it('decodes image bytes from the Codex session JSONL when no generated_images file exists', async () => {const sessionId = '22222222-2222-4222-8222-222222222222';const sessionsDir = join(TEST_HOME, '.codex', 'sessions', '2026', '06', '22');