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(fableloom): bind scenes to Universe canon and compile capability-budgeted render requests (#5379)

[._.]/ Adam Eivy8c7a6f256b7e
diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsx
index 37fdd2d293..9cc406a58a 100644
--- a/client/src/components/fableloom/LoomNodeEditor.jsx
+++ b/client/src/components/fableloom/LoomNodeEditor.jsx
@@ -44,7 +44,7 @@ const rowToPatch = ({ targetNodeId, intent, triggersText, description }) => ({
});
export default function LoomNodeEditor({
- loom, episode, node, onLoomUpdate, onClearSelection, onMakeStart,
+ loom, episode, node, universe, onLoomUpdate, onClearSelection, onMakeStart,
mediaJobs = {}, onGenerateImage, onGenerateVideo,
generationDisabled = false, generationDisabledReason = '',
}) {
@@ -70,6 +70,11 @@ export default function LoomNodeEditor({
imagePrompt: node.imagePrompt || '',
videoPrompt: node.videoPrompt || '',
cameraMovement: node.cameraMovement || '',
+ visualCanon: node.visualCanon ? {
+ ...node.visualCanon,
+ characterAppearances: [...(node.visualCanon.characterAppearances || [])],
+ objectIds: [...(node.visualCanon.objectIds || [])],
+ } : null,
playbackMode: node.playbackMode || 'decision',
audienceConnection: node.audienceConnection || 'disconnected',
playbackAssets: node.playbackAssets || null,
@@ -107,6 +112,13 @@ export default function LoomNodeEditor({
return updated;
};
+ const saveVisualCanon = (next) => {
+ setForm((current) => ({ ...current, visualCanon: next }));
+ patchNode({ visualCanon: next });
+ };
+
+ const updateVisualCanon = (patch) => saveVisualCanon({ ...form.visualCanon, ...patch });
+
// Blur-save helper: skip the round-trip when the value matches the record
// (tabbing through the panel shouldn't rewrite the loom).
const saveField = (key, value) => {
@@ -474,6 +486,187 @@ export default function LoomNodeEditor({
/>
</div>
+ <div className="rounded border border-port-border p-3 space-y-3">
+ <label className="flex items-center gap-2 text-sm" htmlFor="loom-node-visual-canon">
+ <input
+ id="loom-node-visual-canon"
+ aria-label="Bind this shot to Universe canon"
+ type="checkbox"
+ checked={Boolean(form.visualCanon)}
+ onChange={(event) => saveVisualCanon(event.target.checked ? {
+ mode: 'locked', characterAppearances: [], placeId: null, objectIds: [],
+ continuitySourceNodeId: null, shotNotes: '', storyboardImageApproved: false,
+ } : null)}
+ />
+ Bind this shot to Universe canon
+ </label>
+ {form.visualCanon && (
+ <div className="space-y-3">
+ <label className="flex items-center gap-2 text-xs" htmlFor="loom-node-canon-draft">
+ <input
+ id="loom-node-canon-draft"
+ aria-label="Allow degraded canon draft"
+ type="checkbox"
+ checked={form.visualCanon.mode === 'draft'}
+ onChange={(event) => updateVisualCanon({ mode: event.target.checked ? 'draft' : 'locked' })}
+ />
+ Allow an explicitly degraded draft when this backend cannot preserve canon
+ </label>
+
+ <fieldset className="space-y-2">
+ <legend className={labelClass}>Characters</legend>
+ {(universe?.characters || []).map((character) => {
+ const appearance = form.visualCanon.characterAppearances
+ .find((item) => item.characterId === character.id);
+ return (
+ <div key={character.id} className="rounded bg-port-bg-subtle p-2 space-y-2">
+ <label className="flex items-center gap-2 text-xs" htmlFor={`loom-canon-character-${character.id}`}>
+ <input
+ id={`loom-canon-character-${character.id}`}
+ aria-label={character.name}
+ type="checkbox"
+ checked={Boolean(appearance)}
+ onChange={(event) => updateVisualCanon({
+ characterAppearances: event.target.checked
+ ? [...form.visualCanon.characterAppearances, { characterId: character.id, wardrobeId: null, expression: '', continuityNotes: '' }]
+ : form.visualCanon.characterAppearances.filter((item) => item.characterId !== character.id),
+ })}
+ />
+ {character.name}
+ </label>
+ {appearance && (character.wardrobes || []).length > 0 && (
+ <select
+ className={fieldClass}
+ aria-label={`${character.name} wardrobe`}
+ value={appearance.wardrobeId || ''}
+ onChange={(event) => updateVisualCanon({
+ characterAppearances: form.visualCanon.characterAppearances.map((item) => (
+ item.characterId === character.id ? { ...item, wardrobeId: event.target.value || null } : item
+ )),
+ })}
+ >
+ <option value="">Default wardrobe</option>
+ {character.wardrobes.map((wardrobe) => (
+ <option key={wardrobe.id} value={wardrobe.id}>{wardrobe.name || wardrobe.label || 'Wardrobe'}</option>
+ ))}
+ </select>
+ )}
+ {appearance && (
+ <div className="grid gap-2 sm:grid-cols-2">
+ <input
+ className={fieldClass}
+ aria-label={`${character.name} expression`}
+ placeholder="Expression"
+ value={appearance.expression || ''}
+ onChange={(event) => setForm((current) => ({
+ ...current,
+ visualCanon: {
+ ...current.visualCanon,
+ characterAppearances: current.visualCanon.characterAppearances.map((item) => (
+ item.characterId === character.id ? { ...item, expression: event.target.value } : item
+ )),
+ },
+ }))}
+ onBlur={() => patchNode({ visualCanon: form.visualCanon })}
+ />
+ <input
+ className={fieldClass}
+ aria-label={`${character.name} continuity notes`}
+ placeholder="Continuity notes"
+ value={appearance.continuityNotes || ''}
+ onChange={(event) => setForm((current) => ({
+ ...current,
+ visualCanon: {
+ ...current.visualCanon,
+ characterAppearances: current.visualCanon.characterAppearances.map((item) => (
+ item.characterId === character.id ? { ...item, continuityNotes: event.target.value } : item
+ )),
+ },
+ }))}
+ onBlur={() => patchNode({ visualCanon: form.visualCanon })}
+ />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </fieldset>
+
+ <FormField label="Location" labelClassName={labelClass}>
+ <select
+ className={fieldClass}
+ value={form.visualCanon.placeId || ''}
+ onChange={(event) => updateVisualCanon({ placeId: event.target.value || null })}
+ >
+ <option value="">No bound location</option>
+ {(universe?.places || []).map((place) => (
+ <option key={place.id} value={place.id}>{place.name || place.slugline}</option>
+ ))}
+ </select>
+ </FormField>
+
+ {(universe?.objects || []).length > 0 && (
+ <fieldset className="space-y-1">
+ <legend className={labelClass}>Props and objects</legend>
+ {universe.objects.map((object) => (
+ <label key={object.id} className="flex items-center gap-2 text-xs" htmlFor={`loom-canon-object-${object.id}`}>
+ <input
+ id={`loom-canon-object-${object.id}`}
+ aria-label={object.name}
+ type="checkbox"
+ checked={form.visualCanon.objectIds.includes(object.id)}
+ onChange={(event) => updateVisualCanon({
+ objectIds: event.target.checked
+ ? [...form.visualCanon.objectIds, object.id]
+ : form.visualCanon.objectIds.filter((id) => id !== object.id),
+ })}
+ />
+ {object.name}
+ </label>
+ ))}
+ </fieldset>
+ )}
+
+ <FormField label="Continuity source" labelClassName={labelClass}>
+ <select
+ className={fieldClass}
+ value={form.visualCanon.continuitySourceNodeId || ''}
+ onChange={(event) => updateVisualCanon({ continuitySourceNodeId: event.target.value || null })}
+ >
+ <option value="">Automatic (only for one incoming scene)</option>
+ {otherNodes.filter((candidate) => candidate.transitions?.some((transition) => transition.targetNodeId === node.id))
+ .map((candidate) => <option key={candidate.id} value={candidate.id}>{candidate.title || 'Untitled scene'}</option>)}
+ </select>
+ </FormField>
+
+ <FormField label="Shot continuity notes" labelClassName={labelClass}>
+ <textarea
+ rows={2}
+ className={fieldClass}
+ value={form.visualCanon.shotNotes || ''}
+ onChange={(event) => setForm((current) => ({
+ ...current, visualCanon: { ...current.visualCanon, shotNotes: event.target.value },
+ }))}
+ onBlur={() => patchNode({ visualCanon: form.visualCanon })}
+ />
+ </FormField>
+
+ {node.image && (
+ <label className="flex items-center gap-2 text-xs" htmlFor="loom-node-storyboard-approved">
+ <input
+ id="loom-node-storyboard-approved"
+ aria-label="Approve storyboard image for video"
+ type="checkbox"
+ checked={form.visualCanon.storyboardImageApproved === true}
+ onChange={(event) => updateVisualCanon({ storyboardImageApproved: event.target.checked })}
+ />
+ Approve the current storyboard image as this shot's video first frame
+ </label>
+ )}
+ </div>
+ )}
+ </div>
+
<div>
<span className="mb-1 block text-xs font-medium text-port-text-muted">Scene image prompt</span>
<textarea
diff --git a/client/src/components/fableloom/LoomNodeEditor.test.jsx b/client/src/components/fableloom/LoomNodeEditor.test.jsx
index edd015351d..c68311fd67 100644
--- a/client/src/components/fableloom/LoomNodeEditor.test.jsx
+++ b/client/src/components/fableloom/LoomNodeEditor.test.jsx
@@ -43,6 +43,11 @@ const renderEditor = (transitions = [existingPath]) => {
loom={loom}
episode={episode}
node={nodes[0]}
+ universe={{
+ characters: [{ id: 'char-1', name: 'Aria', wardrobes: [{ id: 'coat', name: 'Travel coat' }] }],
+ places: [{ id: 'place-1', name: 'Atrium' }],
+ objects: [{ id: 'object-1', name: 'Compass' }],
+ }}
onLoomUpdate={onLoomUpdate}
onClearSelection={() => {}}
onGenerateImage={onGenerateImage}
@@ -134,6 +139,29 @@ describe('LoomNodeEditor paths', () => {
});
describe('LoomNodeEditor scene media', () => {
+ it('persists structured canon bindings and explicit storyboard approval', async () => {
+ const user = userEvent.setup();
+ updateLoomNode.mockResolvedValue({ id: 'loom-1' });
+ renderEditor();
+
+ await user.click(screen.getByLabelText('Bind this shot to Universe canon'));
+ await user.click(screen.getByLabelText('Aria'));
+ await user.selectOptions(screen.getByLabelText('Aria wardrobe'), 'coat');
+ await user.selectOptions(screen.getByLabelText('Location'), 'place-1');
+ await user.click(screen.getByLabelText('Compass'));
+ await user.click(screen.getByLabelText("Approve the current storyboard image as this shot's video first frame"));
+
+ await waitFor(() => expect(updateLoomNode).toHaveBeenLastCalledWith(
+ 'loom-1', 'ep-1', 'n1',
+ { visualCanon: expect.objectContaining({
+ mode: 'locked',
+ characterAppearances: [expect.objectContaining({ characterId: 'char-1', wardrobeId: 'coat' })],
+ placeId: 'place-1', objectIds: ['object-1'], storyboardImageApproved: true,
+ }) },
+ { silent: true },
+ ));
+ });
+
it('queues a local video from the teleplay scene and rendered still', async () => {
const user = userEvent.setup();
const { onGenerateVideo } = renderEditor();
diff --git a/client/src/components/fableloom/sceneMediaRequests.js b/client/src/components/fableloom/sceneMediaRequests.js
index ae51d48cd1..5a8f151177 100644
--- a/client/src/components/fableloom/sceneMediaRequests.js
+++ b/client/src/components/fableloom/sceneMediaRequests.js
@@ -5,8 +5,9 @@
* 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.
- * Image generation also conditions on a rendered direct predecessor when one
- * exists, preserving visual continuity across adjacent graph shots.
+ * The server-side visual-canon compiler owns reference allocation and graph
+ * continuity. These builders send authored intent plus the destination tag;
+ * they never pre-flatten canon into an untyped browser reference list.
*/
import { composeStyledPrompt } from '../../lib/composeStyledPrompt';
@@ -17,40 +18,12 @@ const withLoomStyle = (prompt, styleNotes) => {
return notes ? `${prompt}\n\nStyle: ${notes}` : prompt;
};
-// Keep enough reference influence to carry likeness and environment forward
-// without asking the model to preserve the prior shot's composition.
-export const FABLELOOM_CONTINUITY_STRENGTH = 0.4;
-
-/**
- * Resolve the still from a direct incoming graph neighbor. Storage order is
- * the deterministic tie-break at a convergence because a shared target node
- * has no active reader path while it is being authored. Self-loops never seed
- * themselves, and unrelated adjacent array entries are not "prior" shots.
- */
-export function findFableLoomPriorImage(episode, nodeId) {
- const nodes = Array.isArray(episode?.nodes) ? episode.nodes : [];
- if (!nodeId || episode?.startNodeId === nodeId) return null;
- const predecessor = nodes.find((candidate) => (
- candidate?.id !== nodeId
- && typeof candidate?.image === 'string'
- && candidate.image.trim()
- && Array.isArray(candidate.transitions)
- && candidate.transitions.some((transition) => transition?.targetNodeId === nodeId)
- ));
- return predecessor?.image.trim() || null;
-}
-
-export function buildFableLoomImageRequest({ loom, episode, episodeId, node, stylePreset = null }) {
+export function buildFableLoomImageRequest({ loom, episodeId, node, stylePreset = null }) {
const authoredPrompt = withLoomStyle((node?.imagePrompt || '').trim(), loom?.styleNotes);
const styled = composeStyledPrompt(authoredPrompt, '', stylePreset);
- const priorImage = findFableLoomPriorImage(episode, node?.id);
return {
prompt: styled.prompt,
...(styled.negativePrompt ? { negativePrompt: styled.negativePrompt } : {}),
- ...(priorImage ? {
- referenceImageFiles: [priorImage],
- referenceStrengths: [FABLELOOM_CONTINUITY_STRENGTH],
- } : {}),
fableLoom: { loomId: loom.id, episodeId, nodeId: node.id },
};
}
diff --git a/client/src/components/fableloom/sceneMediaRequests.test.js b/client/src/components/fableloom/sceneMediaRequests.test.js
index 79afd3ca7e..9d149c1e80 100644
--- a/client/src/components/fableloom/sceneMediaRequests.test.js
+++ b/client/src/components/fableloom/sceneMediaRequests.test.js
@@ -17,7 +17,7 @@ describe('FableLoom scene media request composition', () => {
});
});
- it('conditions an image on its rendered direct predecessor, not an unrelated adjacent scene', () => {
+ it('leaves typed continuity allocation to the server-side compiler', () => {
const target = { id: 'node-3', imagePrompt: 'the scout enters a crystal observatory' };
const episode = {
nodes: [
@@ -31,11 +31,9 @@ describe('FableLoom scene media request composition', () => {
],
};
- expect(buildFableLoomImageRequest({ loom, episode, episodeId: 'ep-1', node: target }))
- .toMatchObject({
- referenceImageFiles: ['prior-shot.png'],
- referenceStrengths: [0.4],
- });
+ const request = buildFableLoomImageRequest({ loom, episode, episodeId: 'ep-1', node: target });
+ expect(request).not.toHaveProperty('referenceImageFiles');
+ expect(request.fableLoom).toEqual({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-3' });
});
it('keeps an opening scene text-to-image when a loop points back to it', () => {
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index 04569ccee2..138c2ab7af 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -45,12 +45,6 @@ import {
weaveLoomEpisode,
} from '../services/api';
-const CONTINUITY_FALLBACK_CODES = new Set([
- 'IMAGE_EDIT_UNSUPPORTED_MODE',
- 'REFERENCE_IMAGE_NOT_FOUND',
- 'REFERENCE_IMAGES_FLUX2_ONLY',
-]);
-
export default function FableLoomStory({ view = 'graph' }) {
const { loomId, episodeId, nodeId } = useParams();
const navigate = useNavigate();
@@ -192,7 +186,13 @@ export default function FableLoomStory({ view = 'graph' }) {
...prev,
episodes: prev.episodes.map((item) => ({
...item,
- nodes: item.nodes.map((scene) => (scene.id === targetNodeId ? { ...scene, ...patch } : scene)),
+ nodes: item.nodes.map((scene) => (scene.id === targetNodeId ? {
+ ...scene,
+ ...patch,
+ ...(patch.image && scene.visualCanon ? {
+ visualCanon: { ...scene.visualCanon, storyboardImageApproved: false },
+ } : {}),
+ } : scene)),
})),
} : prev));
}, []);
@@ -227,20 +227,13 @@ export default function FableLoomStory({ view = 'graph' }) {
}
setSceneMediaJob(targetNode.id, 'image', { jobId: null, status: 'submitting', progress: 0 });
- const imageRequest = (includeContinuity) => buildFableLoomImageRequest({
+ const imageRequest = buildFableLoomImageRequest({
loom,
- episode: includeContinuity ? episode : null,
episodeId,
node: targetNode,
stylePreset: sceneStylePreset,
});
- let continuityFallbackCode = null;
- const queued = await generateImage(imageRequest(true), { silent: true })
- .catch((err) => {
- if (!CONTINUITY_FALLBACK_CODES.has(err.code)) throw err;
- continuityFallbackCode = err.code;
- return generateImage(imageRequest(false), { silent: true });
- })
+ const queued = await generateImage(imageRequest, { silent: true })
.catch((err) => {
setSceneMediaJob(targetNode.id, 'image', {
jobId: null, status: 'failed', progress: 0, error: err.message || 'Could not start the render',
@@ -249,11 +242,6 @@ export default function FableLoomStory({ view = 'graph' }) {
return null;
});
if (!queued) return null;
- if (continuityFallbackCode) {
- toast.warning(continuityFallbackCode === 'REFERENCE_IMAGE_NOT_FOUND'
- ? 'The prior shot image is missing — rendering this scene without continuity conditioning'
- : 'The current image backend cannot use the prior shot — rendering this scene without continuity conditioning');
- }
// 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
@@ -585,6 +573,7 @@ export default function FableLoomStory({ view = 'graph' }) {
loom={loom}
episode={episode}
node={node}
+ universe={linkedUniverse}
onLoomUpdate={setLoom}
onClearSelection={() => navigate(episodePath(episode.id))}
mediaJobs={mediaJobs[node.id]}
diff --git a/client/src/pages/FableLoomStory.test.jsx b/client/src/pages/FableLoomStory.test.jsx
index 4a49bb8809..2e71d0a46c 100644
--- a/client/src/pages/FableLoomStory.test.jsx
+++ b/client/src/pages/FableLoomStory.test.jsx
@@ -264,7 +264,7 @@ describe('FableLoomStory scene media lifecycle', () => {
expect(toastMocks.success).toHaveBeenCalledWith('Scene image ready');
});
- it('passes the rendered incoming shot into the next scene image request', async () => {
+ it('sends only the scene tag so the server resolves typed graph continuity', async () => {
const user = userEvent.setup();
api.getLoom.mockResolvedValue(loom({
episodes: [episode({
@@ -292,13 +292,11 @@ describe('FableLoomStory scene media lifecycle', () => {
await waitFor(() => expect(api.generateImage).toHaveBeenCalledWith({
prompt: 'the same scout crosses into the observatory',
- referenceImageFiles: ['threshold.png'],
- referenceStrengths: [0.4],
fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-2' },
}, { silent: true }));
});
- it('retries without continuity when the configured backend cannot accept the prior shot', async () => {
+ it('does not silently retry a rejected canon request without its conditioning', async () => {
const user = userEvent.setup();
api.getLoom.mockResolvedValue(loom({
episodes: [episode({
@@ -316,23 +314,20 @@ describe('FableLoomStory scene media lifecycle', () => {
],
})],
}));
- api.generateImage
- .mockRejectedValueOnce(Object.assign(new Error('Text-to-image only'), {
- code: 'IMAGE_EDIT_UNSUPPORTED_MODE',
- }))
- .mockResolvedValueOnce({ jobId: 'image-job-fallback', status: 'queued' });
+ api.generateImage.mockRejectedValueOnce(Object.assign(new Error('Canon conditioning unavailable'), {
+ code: 'FABLELOOM_CANON_CONDITIONING_UNAVAILABLE',
+ }));
renderEditor();
await user.click(await screen.findByRole('button', { name: 'Canvas generate second image' }));
- await waitFor(() => expect(api.generateImage).toHaveBeenCalledTimes(2));
- expect(api.generateImage.mock.calls[0][0]).toMatchObject({ referenceImageFiles: ['threshold.png'] });
- expect(api.generateImage.mock.calls[1]).toEqual([{
+ await waitFor(() => expect(api.generateImage).toHaveBeenCalledTimes(1));
+ expect(api.generateImage.mock.calls[0]).toEqual([{
prompt: 'the scout enters the observatory',
fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-2' },
}, { silent: true }]);
- expect(toastMocks.warning).toHaveBeenCalledWith(
- 'The current image backend cannot use the prior shot — rendering this scene without continuity conditioning',
+ expect(toastMocks.error).toHaveBeenCalledWith(
+ 'Could not start scene image: Canon conditioning unavailable',
);
});
});
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
index 7e50f0d991..05117f2752 100644
--- a/docs/features/fableloom.md
+++ b/docs/features/fableloom.md
@@ -183,35 +183,39 @@ nodeId }` destination tag. The completion hook
(`server/services/fableLoomSceneImageHook.js`) files the finished render onto
the node durably — even if the editor unmounted mid-render — with
newest-render-wins per node. The loom's `styleNotes` are appended to the
-prompt for a consistent look. When a direct incoming scene already has a
-rendered still, its gallery filename is also sent as the next scene's init
-image at `0.4` strength. Graph edges, not node-array adjacency, define which
-shot is prior; at a convergence the first rendered incoming scene in stable
-episode order is the deterministic authoring-time source because there is no
-active reader path yet. Opening scenes and scenes without a rendered incoming
-neighbor remain text-to-image.
-
-Continuity conditioning is best-effort for the current stopgap: if the active
-backend is text-to-image-only, or the predecessor's gallery file has since been
-removed, the editor warns and retries the scene without the init image rather
-than blocking production. Canon-locked generation will replace that fallback
-with an explicit capability gate in the planned typed-reference workflow.
+prompt for a consistent look. The browser sends no untyped continuity images:
+`visualConditioning.js` resolves the current node, linked Universe, stable
+character/wardrobe/location/object ids, approved identity assets, compatible
+local character LoRAs, and graph predecessor on the server after the effective
+backend/model is known. A locked convergence uses an explicitly selected
+incoming node; without one it reports the ambiguity instead of guessing.
+Openings never inherit a loop-back shot.
+
+The scene editor's **Universe canon** section chooses locked or explicitly
+degraded-draft behavior. Locked image renders fail before enqueue if an
+identity package is incomplete, a required reference is unavailable or over
+budget, or the backend does not declare multi-character preservation. Draft
+renders remain usable but record every omitted input and warning. Each render
+stores a versioned `visualConditioning` manifest with bindings, backend
+capabilities, selected asset basenames, adapter SHA-256/scales, compiler
+version, temporal source, and omissions; machine-local paths never enter the
+loom or Universe record.
**Generate video** prefers the node's dedicated single-clip `videoPrompt`, adds
the selected movement's production direction from the shared camera registry,
and falls back to scene text for legacy nodes. The registry includes dolly,
truck, pan/tilt, crane, orbit, tracking, handheld, drone, focus, roll, parallax,
body-mounted, bullet-time, hyperlapse, and locked-off setups. If the node has a
-rendered image, it becomes the video's first-frame conditioning image;
-otherwise the render is text-to-video. The completion hook
+rendered image, a locked scene also requires the author to approve that exact
+storyboard as the first-frame contract; replacing the still clears approval.
+Text-to-video and stale/unapproved first frames can render only as explicit
+draft/degraded work. The completion hook
(`server/services/fableLoomSceneVideoHook.js`) files the finished
`videoHistoryId` onto the node durably, with newest-render-wins per node.
Decision videos are authored as seamless loops; automatic-cut videos land on
a final beat that hands cleanly to the next node.
-The broader character/environment canon-reference design, including structured
-scene bindings, provider input budgets, prompt compilation, provenance, and
-branch convergence, is specified in
+The character/environment canon-reference design and rationale is specified in
[`docs/plans/2026-08-29-fableloom-visual-continuity.md`](../plans/2026-08-29-fableloom-visual-continuity.md).
The character voice, production provenance, playback-asset, QR join, and
two-device hosted-mode contracts are specified in
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 633b721162..3d928f3c3f 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -10099,7 +10099,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 750
+ "line": 788
}
]
},
@@ -10110,7 +10110,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 774
+ "line": 812
}
]
},
@@ -10121,7 +10121,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 769
+ "line": 807
}
]
},
@@ -10132,7 +10132,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 803
+ "line": 841
}
]
},
@@ -10143,7 +10143,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 788
+ "line": 826
}
]
},
@@ -10154,7 +10154,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 765
+ "line": 803
}
]
},
@@ -10165,7 +10165,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 693
+ "line": 731
}
]
},
@@ -10176,7 +10176,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 335
+ "line": 339
}
]
},
@@ -10187,7 +10187,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 339
+ "line": 343
}
]
},
@@ -10198,7 +10198,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 561
+ "line": 599
}
]
},
@@ -10209,7 +10209,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 699
+ "line": 737
}
]
},
@@ -10220,7 +10220,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 684
+ "line": 722
}
]
},
@@ -10231,7 +10231,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 385
+ "line": 389
}
]
},
@@ -10242,7 +10242,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 680
+ "line": 718
}
]
},
@@ -10253,7 +10253,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 583
+ "line": 621
}
]
},
@@ -10264,7 +10264,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 661
+ "line": 699
}
]
},
@@ -10275,7 +10275,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 642
+ "line": 680
}
]
},
@@ -10286,7 +10286,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 594
+ "line": 632
}
]
},
@@ -10297,7 +10297,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 622
+ "line": 660
}
]
},
@@ -10308,7 +10308,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 352
+ "line": 356
}
]
},
@@ -10418,7 +10418,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 321
+ "line": 325
}
]
},
@@ -10429,7 +10429,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 62
+ "line": 66
}
]
},
@@ -10440,7 +10440,7 @@
"sources": [
{
"source": "server/routes/imageGen.js",
- "line": 577
+ "line": 615
}
]
},
@@ -21853,7 +21853,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 906
+ "line": 909
}
]
},
@@ -21864,7 +21864,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1256
+ "line": 1285
}
]
},
@@ -21875,7 +21875,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1232
+ "line": 1261
}
]
},
@@ -21886,7 +21886,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1261
+ "line": 1290
}
]
},
@@ -21897,7 +21897,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1290
+ "line": 1319
}
]
},
@@ -21908,7 +21908,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1338
+ "line": 1367
}
]
},
@@ -21919,7 +21919,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1310
+ "line": 1339
}
]
},
@@ -21930,7 +21930,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1346
+ "line": 1375
}
]
},
@@ -21941,7 +21941,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1342
+ "line": 1371
}
]
},
@@ -21952,7 +21952,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 785
+ "line": 788
}
]
},
@@ -21963,7 +21963,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 804
+ "line": 807
}
]
},
@@ -21974,7 +21974,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1363
+ "line": 1392
}
]
},
@@ -21985,7 +21985,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 438
+ "line": 441
}
]
},
@@ -21996,7 +21996,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 442
+ "line": 445
}
]
},
@@ -22007,7 +22007,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 510
+ "line": 513
}
]
},
@@ -22018,7 +22018,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 751
+ "line": 754
}
]
},
@@ -22029,7 +22029,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 736
+ "line": 739
}
]
},
@@ -22040,7 +22040,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 639
+ "line": 642
}
]
},
@@ -22051,7 +22051,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 719
+ "line": 722
}
]
},
@@ -22062,7 +22062,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 480
+ "line": 483
}
]
},
@@ -22073,7 +22073,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 482
+ "line": 485
}
]
},
@@ -22084,7 +22084,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 476
+ "line": 479
}
]
},
@@ -22095,7 +22095,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 388
+ "line": 391
}
]
},
@@ -22106,7 +22106,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1380
+ "line": 1409
}
]
},
@@ -22117,7 +22117,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 893
+ "line": 896
}
]
},
@@ -22128,7 +22128,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 879
+ "line": 882
}
]
},
@@ -22139,7 +22139,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 849
+ "line": 852
}
]
},
@@ -22150,7 +22150,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 859
+ "line": 862
}
]
},
@@ -22161,7 +22161,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1331
+ "line": 1360
}
]
},
@@ -22172,7 +22172,7 @@
"sources": [
{
"source": "server/routes/videoGen.js",
- "line": 1369
+ "line": 1398
}
]
},
@@ -23411,8 +23411,8 @@
],
"stats": {
"mounts": 145,
- "operations": 2108,
- "declarations": 2111,
+ "operations": 2112,
+ "declarations": 2115,
"sourceFiles": 225
}
}
diff --git a/server/lib/fableLoomLimits.js b/server/lib/fableLoomLimits.js
index ba3c59e791..25f93a41c1 100644
--- a/server/lib/fableLoomLimits.js
+++ b/server/lib/fableLoomLimits.js
@@ -26,6 +26,10 @@ export const LOOM_LIMITS = Object.freeze({
IMAGE_PROMPT_MAX: 2000,
VIDEO_PROMPT_MAX: 4000,
CAMERA_MOVEMENT_MAX: 80,
+ VISUAL_BINDINGS_MAX: 12,
+ VISUAL_NOTE_MAX: 500,
+ VISUAL_PROVENANCE_ASSETS_MAX: 24,
+ VISUAL_PROVENANCE_MESSAGES_MAX: 24,
ENDING_LABEL_MAX: 200,
TRANSITIONS_MAX: 12,
INTENT_MAX: 120,
diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.js
index e959b55bee..644cee87fb 100644
--- a/server/lib/fableLoomValidation.js
+++ b/server/lib/fableLoomValidation.js
@@ -121,6 +121,21 @@ const transitionSchema = z.object({
...transitionFields,
});
+const visualCanonSchema = z.object({
+ mode: z.enum(['locked', 'draft']).optional(),
+ characterAppearances: z.array(z.object({
+ characterId: refId.unwrap(),
+ wardrobeId: refId.unwrap().nullable().optional(),
+ expression: z.string().max(LOOM_LIMITS.VISUAL_NOTE_MAX).optional(),
+ continuityNotes: z.string().max(LOOM_LIMITS.VISUAL_NOTE_MAX).optional(),
+ })).max(LOOM_LIMITS.VISUAL_BINDINGS_MAX).optional(),
+ placeId: refId.optional(),
+ objectIds: z.array(refId.unwrap()).max(LOOM_LIMITS.VISUAL_BINDINGS_MAX).optional(),
+ continuitySourceNodeId: nodeIdStr.nullable().optional(),
+ shotNotes: z.string().max(LOOM_LIMITS.VISUAL_NOTE_MAX).optional(),
+ storyboardImageApproved: z.boolean().optional(),
+}).nullable();
+
// Sub-resource POST: no `id` — the server mints it.
export const transitionCreateSchema = z.object(transitionFields);
@@ -174,6 +189,7 @@ const nodeFields = {
imagePrompt: z.string().max(LOOM_LIMITS.IMAGE_PROMPT_MAX).optional(),
videoPrompt: z.string().max(LOOM_LIMITS.VIDEO_PROMPT_MAX).optional(),
cameraMovement: z.string().max(LOOM_LIMITS.CAMERA_MOVEMENT_MAX).optional(),
+ visualCanon: visualCanonSchema.optional(),
playbackMode: z.enum(FABLELOOM_PLAYBACK_MODES).optional(),
audienceConnection: z.enum(FABLELOOM_AUDIENCE_CONNECTION_STATES).optional(),
videoHistoryId: z.string().max(200).nullable().optional(),
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 6bf855326f..ca792a641f 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -354,7 +354,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// (record kind/category `fableLoom`). A pre-feature receiver has no merge
// path for the whole-record story graph, so only this category pauses until
// both peers upgrade; unrelated categories continue syncing.
- fableLoom: 1,
+ // v2 = scene nodes gained portable `visualCanon` bindings plus the latest
+ // render's path-free `visualConditioning` provenance. A v1 peer would strip
+ // both during whole-record LWW, so newer sends must pause until it upgrades.
+ fableLoom: 2,
// v1 = Creative Director projects (PostgreSQL `creative_director_projects`)
// federated via the per-record peer-sync push pipeline (record kind
// `creativeDirectorProject`, sync category `creativeDirectorProjects`, #1564).
diff --git a/server/lib/socketEventCatalog.generated.json b/server/lib/socketEventCatalog.generated.json
index 9ea0776ee5..4ffe1f1073 100644
--- a/server/lib/socketEventCatalog.generated.json
+++ b/server/lib/socketEventCatalog.generated.json
@@ -2220,7 +2220,7 @@
{
"direction": "client-to-server",
"source": "client/src/pages/FableLoomHostedJoin.jsx",
- "line": 171
+ "line": 155
},
{
"direction": "client-to-server",
@@ -2238,7 +2238,7 @@
{
"direction": "client-to-server",
"source": "client/src/pages/FableLoomHostedJoin.jsx",
- "line": 161
+ "line": 145
},
{
"direction": "client-to-server",
@@ -2373,7 +2373,7 @@
{
"direction": "client-to-server",
"source": "client/src/pages/FableLoomHostedJoin.jsx",
- "line": 189
+ "line": 172
},
{
"direction": "client-to-server",
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 80a7ecf5d6..77432e4f33 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -26,7 +26,7 @@ import { getImageModels, requiredReposForModel } from '../lib/mediaModels.js';
import { inspectModelCache, verifyModelCache, repairModelCache, aggregateVerifies } from '../lib/hfCache.js';
import { startHfDownloadStream } from '../services/hfDownloadStream.js';
import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
-import { prepareGenerateParams, resolveLocalImageModel } from '../services/imageGen/prepareParams.js';
+import { prepareGenerateParams, resolveLocalImageModel, selectLocalImageModel } from '../services/imageGen/prepareParams.js';
import { applyImageClean, applyWatermarkRemoval, applyLightRegenVariant } from '../services/imageGen/variants.js';
import { join, basename } from 'node:path';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
@@ -46,6 +46,10 @@ import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmissi
import { collectRemoteInputAssets } from '../services/federatedMedia/inputAssets.js';
import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';
import { attachNodeImage } from '../services/fableLoom/records.js';
+import {
+ compileFableLoomVisualRequest, fableLoomImageCapabilities,
+} from '../services/fableLoom/visualConditioning.js';
+import { loraCompatKey } from '../lib/runners.js';
const router = Router();
@@ -390,6 +394,36 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
referenceImageFields: REFERENCE_IMAGE_FIELDS,
});
+ // FableLoom is compiled server-side after the backend pin resolves. The
+ // browser's prompt/reference fields are hints only: stable scene bindings,
+ // approved assets and deterministic graph continuity own the final request.
+ if (params.fableLoom) {
+ const selected = mode === IMAGE_GEN_MODE.LOCAL ? selectLocalImageModel(params.modelId) : null;
+ const model = selected ? { ...selected, loraCompatKey: loraCompatKey(selected) } : null;
+ const providerMode = params.mediaProviderPeerId ? 'federated' : mode;
+ const compiled = await compileFableLoomVisualRequest({
+ tag: params.fableLoom,
+ kind: 'image',
+ capability: fableLoomImageCapabilities({
+ mode: providerMode,
+ model,
+ inputBudget: mode === IMAGE_GEN_MODE.AGY ? 3 : MAX_REFERENCE_IMAGES,
+ }),
+ authoredPrompt: params.prompt,
+ authoredNegativePrompt: params.negativePrompt,
+ });
+ if (compiled) {
+ params.prompt = compiled.prompt;
+ params.negativePrompt = compiled.negativePrompt;
+ params.referenceImagePaths = compiled.referenceImagePaths;
+ params.referenceImageStrengths = compiled.referenceImageStrengths;
+ params.loraFilenames = compiled.loraFilenames;
+ params.loraPaths = [];
+ params.loraScales = compiled.loraScales;
+ params.visualConditioning = compiled.visualConditioning;
+ }
+ }
+
// Resolve an optional universe-collection target into a job tag the
// completion hook understands. Done server-side so a base-style probe lands
// in the same "Universe: <name>" bucket as batch renders without the
@@ -552,7 +586,11 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
params.fableLoom.loomId,
params.fableLoom.episodeId,
params.fableLoom.nodeId,
- { filename: result.filename, jobId: result.generationId },
+ {
+ filename: result.filename,
+ jobId: result.generationId,
+ visualConditioning: params.visualConditioning,
+ },
);
}
res.json(result);
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 243faf8aa2..316c9865d3 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -13,6 +13,23 @@ import { join as pathJoin } from 'path';
const attachNodeImage = vi.hoisted(() => vi.fn(async () => ({})));
vi.mock('../services/fableLoom/records.js', () => ({ attachNodeImage }));
+const compiledVisual = vi.hoisted(() => ({
+ version: 1, compilerVersion: '1.0.0', status: 'locked', assets: [], adapters: [], omitted: [], warnings: [],
+}));
+const compileFableLoomVisualRequest = vi.hoisted(() => vi.fn(async ({ authoredPrompt, authoredNegativePrompt }) => ({
+ prompt: authoredPrompt,
+ negativePrompt: authoredNegativePrompt || '',
+ referenceImagePaths: [],
+ referenceImageStrengths: [],
+ loraFilenames: [],
+ loraScales: [],
+ visualConditioning: compiledVisual,
+})));
+vi.mock('../services/fableLoom/visualConditioning.js', () => ({
+ compileFableLoomVisualRequest,
+ fableLoomImageCapabilities: vi.fn(() => ({ version: 1, kind: 'image' })),
+}));
+
vi.mock('../services/imageGen/index.js', () => ({
checkConnection: vi.fn(),
generateImage: vi.fn(),
@@ -251,8 +268,11 @@ describe('Image Gen Routes', () => {
'loom-1',
'ep-1',
'node-1',
- { filename: 'scene.png', jobId: 'gen-scene-001' },
+ { filename: 'scene.png', jobId: 'gen-scene-001', visualConditioning: compiledVisual },
);
+ expect(compileFableLoomVisualRequest).toHaveBeenCalledWith(expect.objectContaining({
+ tag: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' }, kind: 'image',
+ }));
});
it('accepts a missing/empty prompt (i2i / edit / unconditional), defaulting it to empty', async () => {
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 37ca00589d..bb1c458188 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -72,6 +72,9 @@ import {
streamVideoRuntimeInstall,
} from '../services/videoGen/runtimeInstaller.js';
import { detectSystemCapabilities, withHardwareCompatibility } from '../lib/systemCapabilities.js';
+import {
+ compileFableLoomVisualRequest, fableLoomVideoCapabilities,
+} from '../services/fableLoom/visualConditioning.js';
const router = Router();
@@ -1029,6 +1032,31 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
});
const { backend, cleanupStaged } = prepared;
+ if (body.fableLoom) {
+ const compiled = await compileFableLoomVisualRequest({
+ tag: body.fableLoom,
+ kind: 'video',
+ capability: fableLoomVideoCapabilities({ backend, model: prepared.effectiveModel }),
+ authoredPrompt: body.prompt,
+ authoredNegativePrompt: body.negativePrompt,
+ sourceImagePath: prepared.sourceImagePath,
+ }).catch(async (error) => {
+ await cleanupStaged();
+ throw error;
+ });
+ if (compiled) {
+ body.prompt = compiled.prompt;
+ body.negativePrompt = compiled.negativePrompt;
+ if (prepared.sourceImagePath && !compiled.sourceImagePath) {
+ await prepared.discardSourceImage();
+ prepared.uploadedTempPath = null;
+ prepared.mode = 'text';
+ }
+ prepared.sourceImagePath = compiled.sourceImagePath;
+ body.visualConditioning = compiled.visualConditioning;
+ }
+ }
+
// #3326 — `enqueueJob` is the last place a throw can strand the durable
// copies the service staged (the job never exists, so the worker's cleanup
// never runs). Release them, then rethrow untouched for the error middleware.
@@ -1130,6 +1158,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
// FableLoom scene attach tag. Rides into persisted job.params so the
// completion hook can file the clip even if the editor unmounted.
...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),
+ ...(body.visualConditioning ? { visualConditioning: body.visualConditioning } : {}),
});
// Match the legacy response shape (jobId, generationId, filename, model,
// mode) so existing client code keeps working; add status+position for
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 98ed347989..7d1d0607c9 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -5,6 +5,25 @@ import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { DEFAULT_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';
+const compiledVisual = vi.hoisted(() => ({
+ version: 1, compilerVersion: '1.0.0', status: 'locked', assets: [], adapters: [], omitted: [], warnings: [],
+}));
+const compileFableLoomVisualRequest = vi.hoisted(() => vi.fn(async ({ authoredPrompt, authoredNegativePrompt, sourceImagePath }) => ({
+ prompt: authoredPrompt,
+ negativePrompt: authoredNegativePrompt || '',
+ referenceImagePaths: [],
+ referenceImageStrengths: [],
+ loraFilenames: [],
+ loraScales: [],
+ sourceImagePath,
+ visualConditioning: compiledVisual,
+})));
+const fableLoomVideoCapabilities = vi.hoisted(() => vi.fn(() => ({ version: 1, kind: 'video' })));
+vi.mock('../services/fableLoom/visualConditioning.js', () => ({
+ compileFableLoomVisualRequest,
+ fableLoomVideoCapabilities,
+}));
+
const installProcess = vi.hoisted(() => {
const spawn = vi.fn();
const makeChild = () => {
@@ -76,7 +95,9 @@ vi.mock('../services/videoGen/local.js', () => ({
// include it so the a2v happy-path tests don't trip the A2V_REQUIRES_LTX2
// guard. Tests that need to exercise the legacy runtime override the mock
// per-test via mockReturnValueOnce.
- listVideoModels: vi.fn(() => [{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' }]),
+ listVideoModels: vi.fn(() => [{
+ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2', supportedModes: ['text', 'image', 'fflf'],
+ }]),
defaultVideoModelId: vi.fn(() => 'ltx2_unified'),
loadHistory: vi.fn(async () => []),
getHistoryItem: vi.fn(async () => null),
@@ -493,7 +514,9 @@ describe('videoGen routes', () => {
it('returns the static catalog', async () => {
const r = await request(app).get('/api/video-gen/models');
expect(r.status).toBe(200);
- expect(r.body).toEqual([{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' }]);
+ expect(r.body).toEqual([{
+ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2', supportedModes: ['text', 'image', 'fflf'],
+ }]);
});
});
@@ -1010,8 +1033,33 @@ describe('videoGen routes', () => {
params: expect.objectContaining({
sourceImagePath: '/mock/images/scene-image.png',
fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' },
+ visualConditioning: compiledVisual,
}),
}));
+ expect(compileFableLoomVisualRequest).toHaveBeenCalledWith(expect.objectContaining({
+ tag: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' }, kind: 'video',
+ }));
+ expect(fableLoomVideoCapabilities).toHaveBeenCalledWith(expect.objectContaining({
+ backend: 'local',
+ model: expect.objectContaining({ supportedModes: expect.any(Array) }),
+ }));
+ });
+
+ it('converts an explicitly degraded FableLoom render to text mode when its frame is omitted', async () => {
+ compileFableLoomVisualRequest.mockResolvedValueOnce({
+ prompt: 'the gate slowly opens', negativePrompt: '', sourceImagePath: null,
+ visualConditioning: { ...compiledVisual, status: 'degraded' },
+ });
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'the gate slowly opens',
+ mode: 'image',
+ sourceImageFile: 'scene-image.png',
+ fableLoom: JSON.stringify({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' }),
+ });
+ expect(r.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ params: expect.objectContaining({ mode: 'text', sourceImagePath: null }),
+ }));
});
it('rejects a musicVideo i2v render when the reference frame cannot be resolved (no silent t2v)', async () => {
diff --git a/server/services/characterLoraResolver.js b/server/services/characterLoraResolver.js
index a721db11db..1d5dd4d1f1 100644
--- a/server/services/characterLoraResolver.js
+++ b/server/services/characterLoraResolver.js
@@ -44,7 +44,7 @@ const isCompat = (lora, compatKey) => {
* user's style LoRAs. Returns
* `[{ filename, scale, triggerWord, character }]`.
*/
-export async function resolveCharacterLoras(matchedCharacters, { compatKey = null, max = 3 } = {}) {
+export async function resolveCharacterLoras(matchedCharacters, { compatKey = null, max = 3, allPerCharacter = false } = {}) {
const characters = (matchedCharacters || []).filter(Boolean);
if (!characters.length) return [];
const loras = await listLoras();
@@ -53,18 +53,21 @@ export async function resolveCharacterLoras(matchedCharacters, { compatKey = nul
const usedFilenames = new Set();
for (const character of characters) {
if (out.length >= max) break;
- const match = trained.find((l) =>
+ const matches = trained.filter((l) =>
!usedFilenames.has(l.filename)
&& matchesCharacter(l.character, { entryId: character.id, ingredientId: character.ingredientId })
&& isCompat(l, compatKey));
- if (!match) continue;
- usedFilenames.add(match.filename);
- out.push({
- filename: match.filename,
- scale: Number.isFinite(match.recommendedScale) ? match.recommendedScale : 1.0,
- triggerWord: match.triggerWords?.[0] || null,
- character: match.character,
- });
+ for (const match of matches) {
+ if (out.length >= max) break;
+ usedFilenames.add(match.filename);
+ out.push({
+ filename: match.filename,
+ scale: Number.isFinite(match.recommendedScale) ? match.recommendedScale : 1.0,
+ triggerWord: match.triggerWords?.[0] || null,
+ character: match.character,
+ });
+ if (!allPerCharacter) break;
+ }
}
return out;
}
diff --git a/server/services/characterLoraResolver.test.js b/server/services/characterLoraResolver.test.js
index a859b7cff8..7b74035430 100644
--- a/server/services/characterLoraResolver.test.js
+++ b/server/services/characterLoraResolver.test.js
@@ -68,6 +68,19 @@ describe('resolveCharacterLoras', () => {
expect(out).toHaveLength(3);
});
+ it('returns every compatible local adapter per bound character when requested', async () => {
+ listLoras.mockResolvedValue([
+ trainedLora({ filename: 'a.safetensors', loraCompatKey: 'flux2-4b' }),
+ trainedLora({ filename: 'b.safetensors', loraCompatKey: 'flux2-4b' }),
+ trainedLora({ filename: 'wrong.safetensors', loraCompatKey: 'mflux' }),
+ ]);
+ const out = await resolveCharacterLoras(
+ [{ id: 'char-1' }],
+ { compatKey: 'flux2-4b', allPerCharacter: true, max: 8 },
+ );
+ expect(out.map((item) => item.filename)).toEqual(['a.safetensors', 'b.safetensors']);
+ });
+
it('returns [] for empty matches without touching the lora list', async () => {
expect(await resolveCharacterLoras([])).toEqual([]);
expect(listLoras).not.toHaveBeenCalled();
diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.md
index 02e8abb20f..c7f3f9f26c 100644
--- a/server/services/fableLoom/README.md
+++ b/server/services/fableLoom/README.md
@@ -8,6 +8,7 @@ intent to a transition and moves them through the graph until an ending.
| Module | Purpose |
|---|---|
| `records.js` | Sanitizer + CRUD + peer LWW/tombstone merge for looms/episodes/nodes; transitions are addressable one at a time (`addNodeTransition` / `updateNodeTransition` / `deleteNodeTransition`) as well as replaceable as a whole array via the node patch; `attachNodeImage`, `attachNodeVideo`, and `attachNodePlaybackAsset` for media-job hooks. |
+| `visualConditioning.js` | Compiles stable scene canon bindings into capability-budgeted prompts, typed reference assets, local character adapters, and durable render provenance. |
| `weave.js` | AI ops via `runStagedLLM`: `generateSeriesPlan` (full arc / plot-point / side-quest scaffold), `weaveEpisode` (single-camera-cut graph with automatic cuts and looping decisions), `branchNode` (grow paths), `feedbackEpisode` (apply a conversational sparse patch to one episode), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition; tapped/automatic paths resolve with NO LLM call), `reformatEpisodeScenes` (rewrite ONE episode's scenes into another format; the loom's format pin lands only once every episode is converted). |
| `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. |
| `hostedSession.js` | Scoped QR-hosted play session lifecycle, HTTPS readiness preflight, token hashing, live voice gate revalidation, and half-duplex turn taking (#5383). |
diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.js
index a317545ef8..f26c71e127 100644
--- a/server/services/fableLoom/index.js
+++ b/server/services/fableLoom/index.js
@@ -52,6 +52,12 @@ export {
asLoomFormat,
isLoomFormat,
} from './formats.js';
+export {
+ FABLELOOM_VISUAL_COMPILER_VERSION,
+ compileFableLoomVisualRequest,
+ fableLoomImageCapabilities,
+ fableLoomVideoCapabilities,
+} from './visualConditioning.js';
export {
DEFAULT_SESSION_TTL_MINUTES,
MAX_SESSION_TTL_MINUTES,
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index 701beb7b18..e365294cde 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -67,6 +67,101 @@ const sanitizePos = (raw) => (raw && typeof raw === 'object'
? { x: Math.round(raw.x), y: Math.round(raw.y) }
: null);
+const sanitizeVisualConditioning = (raw) => {
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) return null;
+ const list = (value, max) => (Array.isArray(value) ? value.slice(0, max) : []);
+ const capability = raw.capability && typeof raw.capability === 'object' ? raw.capability : {};
+ const bindings = raw.bindings && typeof raw.bindings === 'object' ? raw.bindings : {};
+ return {
+ version: 1,
+ compilerVersion: trimTo(raw.compilerVersion, 40),
+ status: ['locked', 'draft', 'degraded'].includes(raw.status) ? raw.status : 'degraded',
+ universeId: nullableRef(raw.universeId),
+ capability: {
+ version: Number.isInteger(capability.version) ? capability.version : 1,
+ kind: capability.kind === 'video' ? 'video' : 'image',
+ backend: trimTo(capability.backend, 40),
+ modelId: nullableRef(capability.modelId),
+ referenceRoles: list(capability.referenceRoles, 24)
+ .map((item) => trimTo(item, 64)).filter(Boolean),
+ referenceBudget: Number.isInteger(capability.referenceBudget)
+ ? Math.max(0, Math.min(24, capability.referenceBudget)) : 0,
+ supportsLora: capability.supportsLora === true,
+ loraCompatKey: nullableRef(capability.loraCompatKey),
+ loraBudget: Number.isInteger(capability.loraBudget)
+ ? Math.max(0, Math.min(8, capability.loraBudget)) : 0,
+ multiCharacterPreservation: capability.multiCharacterPreservation === true,
+ ...(capability.kind === 'video' ? {
+ firstFrame: capability.firstFrame === true,
+ lastFrame: capability.lastFrame === true,
+ extension: capability.extension === true,
+ } : {}),
+ },
+ bindings: {
+ inferred: bindings.inferred === true,
+ characterAppearances: list(bindings.characterAppearances, LOOM_LIMITS.VISUAL_BINDINGS_MAX)
+ .filter((item) => item && typeof item === 'object' && nullableRef(item.characterId))
+ .map((item) => ({
+ characterId: nullableRef(item.characterId),
+ wardrobeId: nullableRef(item.wardrobeId),
+ expression: trimTo(item.expression, LOOM_LIMITS.VISUAL_NOTE_MAX),
+ continuityNotes: trimTo(item.continuityNotes, LOOM_LIMITS.VISUAL_NOTE_MAX),
+ })),
+ placeId: nullableRef(bindings.placeId),
+ objectIds: list(bindings.objectIds, LOOM_LIMITS.VISUAL_BINDINGS_MAX)
+ .map(nullableRef).filter(Boolean),
+ },
+ assets: list(raw.assets, LOOM_LIMITS.VISUAL_PROVENANCE_ASSETS_MAX)
+ .filter((item) => item && typeof item === 'object')
+ .map((item) => ({
+ role: trimTo(item.role, 64), bindingId: nullableRef(item.bindingId),
+ required: item.required === true, filename: trimTo(item.filename, 256),
+ })),
+ adapters: list(raw.adapters, 8)
+ .filter((item) => item && typeof item === 'object')
+ .map((item) => ({
+ characterId: nullableRef(item.characterId), filename: trimTo(item.filename, 256),
+ scale: Number.isFinite(item.scale) ? Math.max(0, Math.min(2, item.scale)) : 1,
+ sha256: typeof item.sha256 === 'string' && /^[a-f0-9]{64}$/i.test(item.sha256) ? item.sha256 : null,
+ })),
+ omitted: list(raw.omitted, LOOM_LIMITS.VISUAL_PROVENANCE_MESSAGES_MAX)
+ .filter((item) => item && typeof item === 'object')
+ .map((item) => ({
+ role: trimTo(item.role, 64), bindingId: nullableRef(item.bindingId),
+ reason: trimTo(item.reason, 80),
+ ...(item.filename ? { filename: trimTo(item.filename, 256) } : {}),
+ })),
+ warnings: (Array.isArray(raw.warnings) ? raw.warnings : [])
+ .map((item) => trimTo(item, LOOM_LIMITS.VISUAL_NOTE_MAX)).filter(Boolean)
+ .slice(0, LOOM_LIMITS.VISUAL_PROVENANCE_MESSAGES_MAX),
+ temporalSourceNodeId: nullableRef(raw.temporalSourceNodeId),
+ compiledAt: isStr(raw.compiledAt) ? raw.compiledAt : null,
+ };
+};
+
+const sanitizeVisualCanon = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const appearances = (Array.isArray(raw.characterAppearances) ? raw.characterAppearances : [])
+ .filter((item) => item && typeof item === 'object' && nullableRef(item.characterId))
+ .slice(0, LOOM_LIMITS.VISUAL_BINDINGS_MAX)
+ .map((item) => ({
+ characterId: nullableRef(item.characterId),
+ wardrobeId: nullableRef(item.wardrobeId),
+ expression: trimTo(item.expression, LOOM_LIMITS.VISUAL_NOTE_MAX),
+ continuityNotes: trimTo(item.continuityNotes, LOOM_LIMITS.VISUAL_NOTE_MAX),
+ }));
+ return {
+ mode: raw.mode === 'draft' ? 'draft' : 'locked',
+ characterAppearances: appearances,
+ placeId: nullableRef(raw.placeId),
+ objectIds: (Array.isArray(raw.objectIds) ? raw.objectIds : [])
+ .map(nullableRef).filter(Boolean).slice(0, LOOM_LIMITS.VISUAL_BINDINGS_MAX),
+ continuitySourceNodeId: nullableRef(raw.continuitySourceNodeId),
+ shotNotes: trimTo(raw.shotNotes, LOOM_LIMITS.VISUAL_NOTE_MAX),
+ storyboardImageApproved: raw.storyboardImageApproved === true,
+ };
+};
+
function sanitizeTransition(raw) {
if (!raw || typeof raw !== 'object') return null;
const intent = trimTo(raw.intent, LOOM_LIMITS.INTENT_MAX);
@@ -95,6 +190,8 @@ function sanitizeNode(raw) {
imageJobId: isStr(raw.imageJobId) && raw.imageJobId ? raw.imageJobId.slice(0, 200) : null,
videoPrompt: trimTo(raw.videoPrompt, LOOM_LIMITS.VIDEO_PROMPT_MAX),
cameraMovement: trimTo(normalizeFableLoomCameraMovement(raw.cameraMovement), LOOM_LIMITS.CAMERA_MOVEMENT_MAX),
+ visualCanon: sanitizeVisualCanon(raw.visualCanon),
+ visualConditioning: sanitizeVisualConditioning(raw.visualConditioning),
playbackMode: asFableLoomPlaybackMode(raw.playbackMode),
audienceConnection: asFableLoomAudienceConnection(raw.audienceConnection),
videoHistoryId: isSafeVideoHistoryId(raw.videoHistoryId) ? raw.videoHistoryId : null,
@@ -194,7 +291,7 @@ export function sanitizeLoom(raw) {
.sort((a, b) => a.number - b.number || a.createdAt.localeCompare(b.createdAt));
return {
id: raw.id,
- schemaVersion: 1,
+ schemaVersion: 2,
name,
logline: trimTo(raw.logline, LOOM_LIMITS.LOGLINE_MAX),
premise: trimTo(raw.premise, LOOM_LIMITS.PREMISE_MAX),
@@ -405,6 +502,32 @@ export async function deleteLoom(id) {
emitRecordDeleted('fableLoom', id);
}
+// A v1 peer cannot represent the v2 scene production fields. When that older
+// peer wins whole-record LWW after an unrelated edit, retain the local fields
+// on nodes that still exist instead of letting its unaware sanitizer clear
+// them. A v2 sender's present null remains an intentional clear.
+const preserveLegacyVisualProduction = (remote, local, senderVersion) => {
+ if (!local || senderVersion >= 2) return remote;
+ const localEpisodes = new Map(local.episodes.map((episode) => [episode.id, episode]));
+ return {
+ ...remote,
+ episodes: remote.episodes.map((episode) => {
+ const localNodes = new Map((localEpisodes.get(episode.id)?.nodes || []).map((node) => [node.id, node]));
+ return {
+ ...episode,
+ nodes: episode.nodes.map((node) => {
+ const localNode = localNodes.get(node.id);
+ return localNode ? {
+ ...node,
+ visualCanon: localNode.visualCanon,
+ visualConditioning: localNode.visualConditioning,
+ } : node;
+ }),
+ };
+ }),
+ };
+};
+
/**
* Merge FableLoom records received from a federated peer. Records are
* sanitized before persistence, unioned by id, and resolved by whole-record
@@ -412,7 +535,10 @@ export async function deleteLoom(id) {
*/
export async function mergeLoomsFromSync(
remoteLooms,
- { source = { via: 'sync', peerId: null } } = {},
+ {
+ source = { via: 'sync', peerId: null },
+ senderSchemaVersions = { fableLoom: 2 },
+ } = {},
) {
if (!Array.isArray(remoteLooms)) return { applied: false, count: 0 };
const byId = new Map();
@@ -426,18 +552,23 @@ export async function mergeLoomsFromSync(
const applied = await queueLoomWrite(remote.id, async () => {
const local = sanitizeLoom(await readRaw(remote.id));
if (local && !compareNewerWins(remote.updatedAt, local.updatedAt)) return false;
+ const merged = preserveLegacyVisualProduction(
+ remote,
+ local,
+ Number(senderSchemaVersions?.fableLoom) || 0,
+ );
if (local) {
await maybeJournalBeforeOverwrite({
- kind: 'fableLoom', id: remote.id, local, remote, source,
+ kind: 'fableLoom', id: remote.id, local, remote: merged, source,
});
} else {
await setSyncBaseHash(
'fableLoom',
- remote.id,
- contentHashForRecord('fableLoom', remote),
+ merged.id,
+ contentHashForRecord('fableLoom', merged),
);
}
- await writeRaw(remote.id, remote);
+ await writeRaw(merged.id, merged);
return true;
});
if (applied) changed += 1;
@@ -534,7 +665,7 @@ export function deleteEpisode(loomId, episodeId) {
const NODE_PATCH_FIELDS = [
'title', 'prose', 'imagePrompt', 'videoPrompt', 'cameraMovement', 'playbackMode',
- 'audienceConnection', 'videoHistoryId', 'playbackAssets', 'interactionWindow',
+ 'audienceConnection', 'visualCanon', 'videoHistoryId', 'playbackAssets', 'interactionWindow',
'isEnding', 'endingLabel', 'pos', 'transitions',
];
@@ -660,7 +791,7 @@ export function deleteNodeTransition(loomId, episodeId, nodeId, transitionId) {
* updated node (or null when the loom/episode/node has since been deleted —
* the hook logs and moves on rather than erroring).
*/
-export async function attachNodeImage(loomId, episodeId, nodeId, { filename, jobId }) {
+export async function attachNodeImage(loomId, episodeId, nodeId, { filename, jobId, visualConditioning = null }) {
if (!isValidLoomId(loomId) || !isSafeImageFilename(filename)) return null;
const updated = await mutateLoom(loomId, (loom) => {
const episode = loom.episodes.find((e) => e.id === episodeId);
@@ -668,6 +799,8 @@ export async function attachNodeImage(loomId, episodeId, nodeId, { filename, job
if (!node) return null;
node.image = filename;
node.imageJobId = isStr(jobId) ? jobId : null;
+ node.visualConditioning = visualConditioning;
+ if (node.visualCanon) node.visualCanon.storyboardImageApproved = false;
episode.updatedAt = new Date().toISOString();
return loom;
}).catch(() => null);
@@ -679,13 +812,14 @@ export async function attachNodeImage(loomId, episodeId, nodeId, { filename, job
* are also the generated filenames under data/videos, but are kept as ids so
* the node can use the same history/media conventions as other video surfaces.
*/
-export async function attachNodeVideo(loomId, episodeId, nodeId, { videoHistoryId }) {
+export async function attachNodeVideo(loomId, episodeId, nodeId, { videoHistoryId, visualConditioning = null }) {
if (!isValidLoomId(loomId) || !isSafeVideoHistoryId(videoHistoryId)) return null;
const updated = await mutateLoom(loomId, (loom) => {
const episode = loom.episodes.find((e) => e.id === episodeId);
const node = episode?.nodes.find((n) => n.id === nodeId);
if (!node) return null;
node.videoHistoryId = videoHistoryId;
+ node.visualConditioning = visualConditioning;
episode.updatedAt = new Date().toISOString();
return loom;
}).catch(() => null);
diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.js
index 0a5e576edb..b3e587c150 100644
--- a/server/services/fableLoom/records.test.js
+++ b/server/services/fableLoom/records.test.js
@@ -233,6 +233,38 @@ describe('loom CRUD', () => {
expect(await getLoom(local.id)).toBeNull();
});
+ it('preserves v2 visual production fields when a v1 peer wins an unrelated LWW edit', async () => {
+ let loom = await makeLoom({ name: 'Local production' });
+ loom = await addEpisode(loom.id, { title: 'Pilot' });
+ loom = await addNode(loom.id, loom.episodes[0].id, {
+ title: 'Bound shot',
+ visualCanon: { mode: 'locked', characterAppearances: [{ characterId: 'char-a' }] },
+ });
+ const node = loom.episodes[0].nodes[0];
+ await attachNodeImage(loom.id, loom.episodes[0].id, node.id, {
+ filename: 'bound-shot.png',
+ jobId: 'job-visual',
+ visualConditioning: {
+ version: 1, compilerVersion: '1.0.0', status: 'locked', universeId: 'uni-1',
+ },
+ });
+ loom = await getLoom(loom.id);
+ const remoteV1 = {
+ ...loom,
+ name: 'Renamed by v1 peer',
+ updatedAt: '2099-01-01T00:00:00.000Z',
+ episodes: loom.episodes.map((episode) => ({
+ ...episode,
+ nodes: episode.nodes.map(({ visualCanon: _canon, visualConditioning: _conditioning, ...rest }) => rest),
+ })),
+ };
+
+ await mergeLoomsFromSync([remoteV1], { senderSchemaVersions: { fableLoom: 1 } });
+ const mergedNode = (await getLoom(loom.id)).episodes[0].nodes[0];
+ expect(mergedNode.visualCanon).toMatchObject({ mode: 'locked', characterAppearances: [{ characterId: 'char-a' }] });
+ expect(mergedNode.visualConditioning).toMatchObject({ version: 1, compilerVersion: '1.0.0' });
+ });
+
it('journals divergent story edits and can restore the authored snapshot', async () => {
const local = await makeLoom({ name: 'Local story', premise: 'Local premise' });
const base = { ...local, name: 'Shared story', premise: 'Shared premise' };
@@ -560,6 +592,31 @@ describe('attachNodeImage', () => {
expect((await getLoom(loom.id)).episodes[0].nodes[0].image).toBe('job-1.png');
});
+ it('stores render provenance and clears storyboard approval when a new image lands', async () => {
+ const loom = await makeLoom();
+ let updated = await addEpisode(loom.id, {});
+ const episodeId = updated.episodes[0].id;
+ updated = await addNode(loom.id, episodeId, {
+ title: 'A', visualCanon: { mode: 'locked', storyboardImageApproved: true },
+ });
+ const node = updated.episodes[0].nodes[0];
+ const visualConditioning = {
+ version: 1, compilerVersion: '1.0.0', status: 'locked',
+ capability: { kind: 'image', backend: 'local', referenceRoles: ['character-neutral'], injected: 'x'.repeat(1000) },
+ bindings: { inferred: false, characterAppearances: [{ characterId: 'char-a' }], injected: 'x'.repeat(1000) },
+ assets: [{ role: 'character-neutral', bindingId: 'char-a', filename: 'identity.png', path: '/private/identity.png' }],
+ adapters: [], omitted: [], warnings: [],
+ };
+ const attached = await attachNodeImage(loom.id, episodeId, node.id, {
+ filename: 'job-2.png', jobId: 'job-2', visualConditioning,
+ });
+ expect(attached.visualCanon.storyboardImageApproved).toBe(false);
+ expect(attached.visualConditioning).toMatchObject({ version: 1, status: 'locked' });
+ expect(JSON.stringify(attached.visualConditioning)).not.toContain('/private/');
+ expect(attached.visualConditioning.capability.injected).toBeUndefined();
+ expect(attached.visualConditioning.bindings.injected).toBeUndefined();
+ });
+
it('returns null (no throw) when the target is gone or the filename is unsafe', async () => {
const loom = await makeLoom();
const updated = await addEpisode(loom.id, {});
diff --git a/server/services/fableLoom/visualConditioning.js b/server/services/fableLoom/visualConditioning.js
new file mode 100644
index 0000000000..60ee01489b
--- /dev/null
+++ b/server/services/fableLoom/visualConditioning.js
@@ -0,0 +1,369 @@
+/**
+ * FableLoom visual-canon compiler.
+ *
+ * Turns stable scene bindings into the exact prompt, typed input images and
+ * local character adapters a render can actually consume. The returned v1
+ * manifest is durable provenance: unsupported/over-budget inputs are named,
+ * never silently discarded, and a locked scene fails before enqueue.
+ */
+
+import { basename, join } from 'node:path';
+import { stat } from 'node:fs/promises';
+import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS, resolveImageInputPath, sha256File } from '../../lib/fileUtils.js';
+import { characterIdentityPackReadiness } from '../../lib/storyBible.js';
+import {
+ matchCharactersInText, matchObjectsInText, matchPlacesInText,
+} from '../../lib/scenePrompt.js';
+import { getUniverse } from '../universeBuilder.js';
+import { resolveCharacterLoras } from '../characterLoraResolver.js';
+import { getSeries } from '../pipeline/series.js';
+import { getLoom } from './records.js';
+
+export const FABLELOOM_VISUAL_COMPILER_VERSION = '1.0.0';
+
+const byId = (list) => new Map((Array.isArray(list) ? list : []).filter((item) => item?.id).map((item) => [item.id, item]));
+const text = (value) => (typeof value === 'string' ? value.trim() : '');
+const compact = (values) => values.map(text).filter(Boolean);
+const unique = (values) => [...new Set(values.filter(Boolean))];
+const publicAsset = (path, role, bindingId, required = false) => ({
+ role, bindingId, required, filename: basename(path), path,
+});
+const adapterDigestCache = new Map();
+
+const adapterDigest = async (path, hashFile) => {
+ if (hashFile !== sha256File) return hashFile(path);
+ const info = await stat(path);
+ const key = `${info.size}:${info.mtimeMs}`;
+ const cached = adapterDigestCache.get(path);
+ if (cached?.key === key) return cached.sha256;
+ const sha256 = await hashFile(path);
+ adapterDigestCache.set(path, { key, sha256 });
+ if (adapterDigestCache.size > 64) adapterDigestCache.delete(adapterDigestCache.keys().next().value);
+ return sha256;
+};
+
+const visualPromptForCharacter = (character, appearance, triggerWords) => {
+ const wardrobe = character.wardrobes?.find((item) => item.id === appearance?.wardrobeId);
+ return compact([
+ `Character: ${character.name}`,
+ character.physicalDescription || character.visualIdentity || character.visualNotes,
+ wardrobe && `Wardrobe: ${wardrobe.name || wardrobe.label || ''} ${wardrobe.description || wardrobe.prompt || ''}`,
+ appearance?.expression && `Expression: ${appearance.expression}`,
+ appearance?.continuityNotes && `Continuity: ${appearance.continuityNotes}`,
+ triggerWords.length && `Identity adapter triggers: ${triggerWords.join(', ')}`,
+ ]).join('. ');
+};
+
+const resolveTemporalNode = (episode, node, explicitId) => {
+ if (episode.startNodeId === node.id) return { node: null, reason: 'opening-scene' };
+ const incoming = episode.nodes.filter((candidate) => candidate.id !== node.id
+ && candidate.transitions?.some((transition) => transition.targetNodeId === node.id));
+ if (explicitId) {
+ const explicit = incoming.find((candidate) => candidate.id === explicitId);
+ return explicit ? { node: explicit, reason: 'explicit' } : { node: null, reason: 'invalid-explicit-source' };
+ }
+ if (incoming.length === 1) return { node: incoming[0], reason: 'single-predecessor' };
+ return { node: null, reason: incoming.length > 1 ? 'ambiguous-convergence' : 'no-predecessor' };
+};
+
+const bindScene = ({ node, episode, universe }) => {
+ const declared = node.visualCanon;
+ const characters = Array.isArray(universe.characters) ? universe.characters : [];
+ const places = Array.isArray(universe.places) ? universe.places : [];
+ const objects = Array.isArray(universe.objects) ? universe.objects : [];
+ const sourceText = compact([node.title, node.prose, node.imagePrompt, node.videoPrompt]).join('\n');
+ const characterMap = byId(characters);
+ const placeMap = byId(places);
+ const objectMap = byId(objects);
+ const appearances = declared
+ ? declared.characterAppearances || []
+ : matchCharactersInText(sourceText, characters).map((character) => ({ characterId: character.id }));
+ const boundCharacters = appearances.map((appearance) => ({ appearance, character: characterMap.get(appearance.characterId) }))
+ .filter((item) => item.character);
+ const boundPlace = declared
+ ? placeMap.get(declared.placeId) || null
+ : matchPlacesInText(sourceText, places)[0] || null;
+ const boundObjects = declared
+ ? (declared.objectIds || []).map((id) => objectMap.get(id)).filter(Boolean)
+ : matchObjectsInText(sourceText, objects);
+ const missing = declared ? [
+ ...appearances.filter((item) => !characterMap.has(item.characterId)).map((item) => ({ role: 'character', bindingId: item.characterId, reason: 'binding-not-found' })),
+ ...appearances.filter((item) => {
+ const character = characterMap.get(item.characterId);
+ return item.wardrobeId && character && !character.wardrobes?.some((wardrobe) => wardrobe.id === item.wardrobeId);
+ }).map((item) => ({ role: 'wardrobe', bindingId: item.wardrobeId, reason: 'binding-not-found' })),
+ ...(declared.placeId && !boundPlace ? [{ role: 'environment', bindingId: declared.placeId, reason: 'binding-not-found' }] : []),
+ ...(declared.objectIds || []).filter((id) => !objectMap.has(id)).map((id) => ({ role: 'object', bindingId: id, reason: 'binding-not-found' })),
+ ] : [];
+ return { declared: Boolean(declared), appearances, boundCharacters, boundPlace, boundObjects, missing };
+};
+
+const imageAssetsForCharacter = (character, locked, resolveAsset) => {
+ const readiness = characterIdentityPackReadiness(character);
+ const roleRank = new Map(['neutral', 'profile', 'full-body', 'expression-gesture', 'wardrobe', 'prop-scale', 'negative-identity']
+ .map((role, index) => [role, index]));
+ const unavailable = [];
+ const approved = [...readiness.assets].sort((left, right) => (
+ (roleRank.get(left.role) ?? 99) - (roleRank.get(right.role) ?? 99)
+ )).map((asset) => {
+ const path = resolveAsset(asset.imageRef);
+ if (!path) unavailable.push({
+ role: `character-${asset.role}`, bindingId: character.id, reason: 'asset-unavailable',
+ });
+ return path ? publicAsset(path, `character-${asset.role}`, character.id) : null;
+ }).filter(Boolean);
+ if (approved.length) return {
+ primary: [{ ...approved[0], required: true }], supplemental: approved.slice(1), readiness, unavailable,
+ };
+ if (locked) return { primary: [], supplemental: [], readiness, unavailable };
+ const fallback = resolveAsset(character.primaryImageRef || character.referenceSheetImageRef);
+ return {
+ primary: fallback ? [publicAsset(fallback, 'character-draft-reference', character.id)] : [],
+ supplemental: [], readiness, unavailable,
+ };
+};
+
+const allocateAssets = (candidates, capability) => {
+ const supported = new Set(capability.referenceRoles || []);
+ const accepted = [];
+ const omitted = [];
+ for (const candidate of candidates) {
+ if (!supported.has(candidate.role) && !supported.has(candidate.role.split('-').slice(0, 2).join('-'))) {
+ omitted.push({ role: candidate.role, bindingId: candidate.bindingId, reason: 'capability-unsupported' });
+ } else if (accepted.length >= capability.referenceBudget) {
+ omitted.push({ role: candidate.role, bindingId: candidate.bindingId, reason: 'reference-budget' });
+ } else {
+ accepted.push(candidate);
+ }
+ }
+ return { accepted, omitted };
+};
+
+const blockedError = (messages, manifest) => new ServerError(
+ `Canon-locked render cannot preserve the declared scene: ${messages.join('; ')}`,
+ {
+ status: 409,
+ code: 'FABLELOOM_CANON_CONDITIONING_UNAVAILABLE',
+ context: { details: { visualConditioning: manifest } },
+ },
+);
+
+/**
+ * Compile one tagged render. Dependencies are injectable so tests exercise
+ * the real public compiler contract without touching the live universe store.
+ */
+export async function compileFableLoomVisualRequest({
+ tag, kind, capability, authoredPrompt = '', authoredNegativePrompt = '', sourceImagePath = null,
+ loadLoom = getLoom, loadUniverse = getUniverse, loadSeries = getSeries,
+ resolveLoras = resolveCharacterLoras,
+ hashFile = sha256File, resolveAsset = resolveImageInputPath,
+ now = () => new Date().toISOString(),
+}) {
+ if (!tag?.loomId || !tag.episodeId || !tag.nodeId) return null;
+ const loom = await loadLoom(tag.loomId);
+ const episode = loom?.episodes?.find((item) => item.id === tag.episodeId);
+ const node = episode?.nodes?.find((item) => item.id === tag.nodeId);
+ if (!loom || !episode || !node) throw new ServerError('FableLoom scene not found', { status: 404, code: 'NOT_FOUND' });
+ const series = !loom.universeId && loom.seriesId ? await loadSeries(loom.seriesId).catch(() => null) : null;
+ const universeId = loom.universeId || series?.universeId || null;
+ const universe = universeId ? await loadUniverse(universeId) : null;
+ // Legacy/unlinked scenes keep their pre-compiler prompt-only behavior. A
+ // scene carrying explicit canon bindings must resolve the canon it names.
+ if (!universe && !node.visualCanon) return null;
+ if (!universe) throw new ServerError('FableLoom linked universe not found', { status: 409, code: 'FABLELOOM_UNIVERSE_UNAVAILABLE' });
+
+ const bindings = bindScene({ node, episode, universe });
+ const locked = bindings.declared && node.visualCanon.mode !== 'draft';
+ const warnings = bindings.declared ? [] : ['Bindings inferred from scene text; render is draft-only'];
+ const failures = [];
+ const omitted = [...bindings.missing];
+ if (locked && bindings.missing.length) failures.push('one or more stable bindings no longer resolve');
+ if (locked && bindings.boundCharacters.length > 1 && !capability.multiCharacterPreservation) {
+ failures.push(`backend does not declare multi-character preservation for ${bindings.boundCharacters.length} characters`);
+ }
+
+ const loraMatches = capability.supportsLora
+ ? await resolveLoras(bindings.boundCharacters.map(({ character }) => character), {
+ compatKey: capability.loraCompatKey || null, max: Number.MAX_SAFE_INTEGER, allPerCharacter: true,
+ })
+ : [];
+ const acceptedLoras = loraMatches.slice(0, capability.loraBudget || 0);
+ const omittedLoras = loraMatches.slice(acceptedLoras.length);
+ omitted.push(...omittedLoras.map((lora) => ({
+ role: 'character-adapter',
+ bindingId: lora.character?.entryId || lora.character?.ingredientId || null,
+ filename: basename(lora.filename),
+ reason: 'adapter-budget',
+ })));
+ if (locked && omittedLoras.length) failures.push('compatible character adapters exceed the backend adapter budget');
+ const adapterTriggerWords = new Map();
+ const adapters = [];
+ for (const lora of acceptedLoras) {
+ const path = join(PATHS.loras, basename(lora.filename));
+ const sha256 = await adapterDigest(path, hashFile).catch(() => null);
+ adapters.push({
+ characterId: lora.character?.entryId || null,
+ filename: basename(lora.filename), scale: lora.scale, sha256,
+ });
+ if (locked && !sha256) failures.push(`adapter ${basename(lora.filename)} could not be fingerprinted`);
+ if (lora.triggerWord) {
+ const id = lora.character?.entryId;
+ adapterTriggerWords.set(id, [...(adapterTriggerWords.get(id) || []), lora.triggerWord]);
+ }
+ }
+ if (!capability.supportsLora && bindings.boundCharacters.length) {
+ omitted.push(...bindings.boundCharacters.map(({ character }) => ({ role: 'character-adapter', bindingId: character.id, reason: 'capability-unsupported' })));
+ }
+
+ const temporal = resolveTemporalNode(episode, node, node.visualCanon?.continuitySourceNodeId);
+ const candidates = [];
+ if (kind === 'video') {
+ const approvedStoryboardPath = resolveAsset(node.image);
+ const requestedCurrentStoryboard = approvedStoryboardPath && sourceImagePath
+ && basename(approvedStoryboardPath) === basename(sourceImagePath);
+ if (requestedCurrentStoryboard && node.visualCanon?.storyboardImageApproved) {
+ candidates.push(publicAsset(approvedStoryboardPath, 'storyboard-first-frame', node.id, locked));
+ } else {
+ omitted.push({ role: 'storyboard-first-frame', bindingId: node.id, reason: 'missing-stale-or-unapproved' });
+ if (locked) failures.push('storyboard first frame is missing, stale, or not author-approved');
+ }
+ } else {
+ if (temporal.node) {
+ const path = temporal.node.image ? resolveAsset(temporal.node.image) : null;
+ if (path) candidates.push(publicAsset(path, 'temporal-predecessor', temporal.node.id, locked));
+ else {
+ omitted.push({ role: 'temporal-predecessor', bindingId: temporal.node.id, reason: 'asset-unavailable' });
+ if (locked) failures.push('temporal predecessor image is unavailable');
+ }
+ } else if (temporal.reason === 'invalid-explicit-source' || temporal.reason === 'ambiguous-convergence') {
+ omitted.push({ role: 'temporal-predecessor', bindingId: null, reason: temporal.reason });
+ if (locked) failures.push(temporal.reason === 'invalid-explicit-source'
+ ? 'explicit temporal source is not an incoming graph predecessor'
+ : 'convergent scene needs an explicit incoming temporal source');
+ }
+ const characterAssets = [];
+ for (const { character } of bindings.boundCharacters) {
+ const resolved = imageAssetsForCharacter(character, locked, resolveAsset);
+ if (locked && resolved.readiness.status !== 'ready') failures.push(`${character.name} identity package is ${resolved.readiness.status}`);
+ if (locked && resolved.primary.length === 0) failures.push(`${character.name} approved identity assets are unavailable`);
+ omitted.push(...resolved.unavailable);
+ characterAssets.push(resolved);
+ }
+ // Guarantee each cast member's primary approved identity anchor is
+ // considered before supplemental profile/body sheets consume the budget.
+ candidates.push(...characterAssets.flatMap((item) => item.primary));
+ candidates.push(...characterAssets.flatMap((item) => item.supplemental));
+ if (bindings.boundPlace?.primaryImageRef) {
+ const path = resolveAsset(bindings.boundPlace.primaryImageRef);
+ if (path) candidates.push(publicAsset(path, 'environment', bindings.boundPlace.id));
+ else omitted.push({ role: 'environment', bindingId: bindings.boundPlace.id, reason: 'asset-unavailable' });
+ } else if (bindings.boundPlace) {
+ omitted.push({ role: 'environment', bindingId: bindings.boundPlace.id, reason: 'reference-not-configured' });
+ }
+ for (const object of bindings.boundObjects) {
+ const path = resolveAsset(object.primaryImageRef);
+ if (path) candidates.push(publicAsset(path, 'object', object.id));
+ else omitted.push({
+ role: 'object', bindingId: object.id,
+ reason: object.primaryImageRef ? 'asset-unavailable' : 'reference-not-configured',
+ });
+ }
+ }
+
+ const allocation = allocateAssets(candidates, capability);
+ omitted.push(...allocation.omitted);
+ if (locked && allocation.omitted.some((item) => candidates.find((asset) => asset.role === item.role && asset.bindingId === item.bindingId)?.required)) {
+ failures.push('required canon assets exceed or are unsupported by the backend capability manifest');
+ }
+
+ const characterPrompts = bindings.boundCharacters.map(({ character, appearance }) => visualPromptForCharacter(
+ character, appearance, adapterTriggerWords.get(character.id) || [],
+ ));
+ const placePrompt = bindings.boundPlace && compact([
+ `Environment: ${bindings.boundPlace.name || bindings.boundPlace.slugline}`,
+ bindings.boundPlace.description, bindings.boundPlace.recurringDetails,
+ ]).join('. ');
+ const objectPrompts = bindings.boundObjects.map((object) => compact([
+ `Object: ${object.name}`, object.description, object.significance,
+ ]).join('. '));
+ const universeStyle = compact([
+ universe.influences?.embrace?.length && universe.influences.embrace.join(', '),
+ universe.styleNotes,
+ ]);
+ const positive = compact([
+ universeStyle.length && `Universe style: ${universeStyle.join('. ')}`,
+ placePrompt, ...characterPrompts, ...objectPrompts,
+ authoredPrompt || (kind === 'video' ? node.videoPrompt || node.prose : node.imagePrompt),
+ node.visualCanon?.shotNotes && `Shot continuity: ${node.visualCanon.shotNotes}`,
+ ]).join('\n\n').slice(0, 8000);
+ const identityAvoid = bindings.boundCharacters.flatMap(({ character }) => character.identityPack?.avoid || []);
+ const negativePrompt = unique(compact([
+ authoredNegativePrompt, ...(universe.influences?.avoid || []), ...identityAvoid,
+ ])).join(', ').slice(0, 8000);
+ const manifest = {
+ version: 1,
+ compilerVersion: FABLELOOM_VISUAL_COMPILER_VERSION,
+ status: locked ? 'locked' : (omitted.length || warnings.length ? 'degraded' : 'draft'),
+ universeId: universe.id,
+ capability,
+ bindings: {
+ inferred: !bindings.declared,
+ characterAppearances: bindings.boundCharacters.map(({ character, appearance }) => ({
+ characterId: character.id, wardrobeId: appearance.wardrobeId || null,
+ expression: appearance.expression || '', continuityNotes: appearance.continuityNotes || '',
+ })),
+ placeId: bindings.boundPlace?.id || null,
+ objectIds: bindings.boundObjects.map((object) => object.id),
+ },
+ assets: allocation.accepted.map(({ path: _path, ...asset }) => asset),
+ adapters,
+ omitted,
+ warnings,
+ temporalSourceNodeId: temporal.node?.id || null,
+ compiledAt: now(),
+ };
+ if (locked && failures.length) throw blockedError(unique(failures), { ...manifest, status: 'degraded', warnings: unique([...warnings, ...failures]) });
+ return {
+ prompt: positive,
+ negativePrompt,
+ referenceImagePaths: allocation.accepted.map((asset) => asset.path),
+ referenceImageStrengths: allocation.accepted.map((asset) => asset.role === 'temporal-predecessor' ? 0.4 : 1),
+ loraFilenames: adapters.map((adapter) => adapter.filename),
+ loraScales: adapters.map((adapter) => adapter.scale),
+ sourceImagePath: kind === 'video' ? allocation.accepted[0]?.path || null : null,
+ visualConditioning: manifest,
+ };
+}
+
+export function fableLoomImageCapabilities({ mode, model = null, inputBudget = 4 }) {
+ const localFlux2 = mode === 'local' && model?.runner === 'flux2';
+ const cloudEdit = ['codex', 'grok', 'agy'].includes(mode);
+ return Object.freeze({
+ version: 1, kind: 'image', backend: mode, modelId: model?.id || null,
+ referenceRoles: localFlux2 || cloudEdit
+ ? ['temporal-predecessor', 'character-neutral', 'character-profile', 'character-full-body', 'character-expression-gesture', 'character-wardrobe', 'character-prop-scale', 'character-negative-identity', 'character-draft-reference', 'environment', 'object']
+ : [],
+ referenceBudget: localFlux2 || cloudEdit ? inputBudget : 0,
+ supportsLora: localFlux2 || (mode === 'local' && model?.runner === 'mflux'),
+ loraCompatKey: model?.loraCompatKey || null,
+ loraBudget: 8,
+ multiCharacterPreservation: localFlux2,
+ });
+}
+
+export function fableLoomVideoCapabilities({ backend, model = null }) {
+ const supportedModes = Array.isArray(model?.supportedModes) ? model.supportedModes : [];
+ return Object.freeze({
+ version: 1, kind: 'video', backend, modelId: model?.id || null,
+ referenceRoles: supportedModes.includes('image') ? ['storyboard-first-frame'] : [],
+ referenceBudget: supportedModes.includes('image') ? 1 : 0,
+ supportsLora: false,
+ loraCompatKey: null,
+ loraBudget: 0,
+ multiCharacterPreservation: model?.fableLoomMultiCharacterPreservation === true,
+ firstFrame: supportedModes.includes('image'),
+ lastFrame: supportedModes.includes('fflf'),
+ extension: supportedModes.includes('extend'),
+ });
+}
diff --git a/server/services/fableLoom/visualConditioning.test.js b/server/services/fableLoom/visualConditioning.test.js
new file mode 100644
index 0000000000..8f7ad2a1e5
--- /dev/null
+++ b/server/services/fableLoom/visualConditioning.test.js
@@ -0,0 +1,210 @@
+import { describe, expect, it, vi } from 'vitest';
+import { ServerError } from '../../lib/errorHandler.js';
+import {
+ compileFableLoomVisualRequest,
+ fableLoomImageCapabilities,
+ fableLoomVideoCapabilities,
+} from './visualConditioning.js';
+
+const identityPack = (prefix) => ({
+ assets: [
+ { role: 'neutral', imageRef: `${prefix}-neutral.png`, approved: true },
+ { role: 'profile', imageRef: `${prefix}-profile.png`, approved: true },
+ { role: 'full-body', imageRef: `${prefix}-body.png`, approved: true },
+ ],
+ avoid: [`wrong ${prefix} face`],
+});
+
+const universe = {
+ id: 'universe-1',
+ styleNotes: 'painted cinematic realism',
+ characters: [{
+ id: 'char-a', name: 'Aria', physicalDescription: 'silver braid',
+ imageRefs: ['aria-neutral.png', 'aria-profile.png', 'aria-body.png'],
+ identityPack: identityPack('aria'),
+ wardrobes: [{ id: 'wardrobe-red', name: 'Red coat', description: 'weathered wool' }],
+ }, {
+ id: 'char-b', name: 'Bex', physicalDescription: 'round glasses',
+ imageRefs: ['bex-neutral.png', 'bex-profile.png', 'bex-body.png'],
+ identityPack: identityPack('bex'),
+ }],
+ places: [{ id: 'place-1', name: 'Atrium', description: 'glass roof', primaryImageRef: 'atrium.png' }],
+ objects: [{ id: 'object-1', name: 'Compass', description: 'brass', primaryImageRef: 'compass.png' }],
+};
+
+const loomWith = (visualCanon, { convergence = false } = {}) => ({
+ id: 'loom-1', universeId: universe.id,
+ episodes: [{
+ id: 'episode-1', startNodeId: 'opening',
+ nodes: [
+ { id: 'opening', image: 'opening.png', transitions: [{ targetNodeId: 'shot' }] },
+ ...(convergence ? [{ id: 'alternate', image: 'alternate.png', transitions: [{ targetNodeId: 'shot' }] }] : []),
+ {
+ id: 'shot', title: 'Aria enters the Atrium with the Compass', imagePrompt: 'A cautious arrival',
+ visualCanon, transitions: [], image: 'storyboard.png',
+ },
+ ],
+ }],
+});
+
+const deps = (loom) => ({
+ loadLoom: vi.fn(async () => loom),
+ loadUniverse: vi.fn(async () => universe),
+ resolveAsset: (filename) => filename ? `/approved/${filename}` : null,
+ resolveLoras: vi.fn(async () => [{
+ filename: 'aria-v2.safetensors', scale: 0.75, triggerWord: 'ARIA_V2',
+ character: { entryId: 'char-a' },
+ }]),
+ hashFile: vi.fn(async () => 'a'.repeat(64)),
+ now: () => '2026-08-29T00:00:00.000Z',
+});
+
+const lockedBinding = {
+ mode: 'locked',
+ characterAppearances: [{
+ characterId: 'char-a', wardrobeId: 'wardrobe-red', expression: 'alert', continuityNotes: 'coat stays wet',
+ }],
+ placeId: 'place-1', objectIds: ['object-1'], storyboardImageApproved: true,
+};
+
+describe('FableLoom visual conditioning compiler', () => {
+ it('compiles stable bindings, approved identity assets, adapters, graph continuity and provenance', async () => {
+ const loom = loomWith(lockedBinding);
+ const result = await compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' },
+ kind: 'image',
+ capability: fableLoomImageCapabilities({
+ mode: 'local', model: { id: 'flux2-klein', runner: 'flux2', loraCompatKey: 'flux2-4b' }, inputBudget: 6,
+ }),
+ authoredPrompt: 'A cautious arrival',
+ ...deps(loom),
+ });
+
+ expect(result.prompt).toContain('Character: Aria');
+ expect(result.prompt).toContain('Wardrobe: Red coat');
+ expect(result.prompt).toContain('ARIA_V2');
+ expect(result.negativePrompt).toContain('wrong aria face');
+ expect(result.visualConditioning).toMatchObject({
+ status: 'locked', compilerVersion: '1.0.0', universeId: universe.id,
+ temporalSourceNodeId: 'opening',
+ bindings: { inferred: false, placeId: 'place-1', objectIds: ['object-1'] },
+ adapters: [{ filename: 'aria-v2.safetensors', scale: 0.75, sha256: 'a'.repeat(64) }],
+ });
+ expect(result.visualConditioning.assets[0]).toMatchObject({ role: 'temporal-predecessor', filename: 'opening.png' });
+ expect(result.referenceImagePaths.every((path) => path.startsWith('/approved/'))).toBe(true);
+ expect(JSON.stringify(result.visualConditioning)).not.toContain('/approved/');
+ });
+
+ it('fails a locked render when a backend cannot preserve the bound cast', async () => {
+ const loom = loomWith({
+ ...lockedBinding,
+ characterAppearances: [{ characterId: 'char-a' }, { characterId: 'char-b' }],
+ });
+ const run = compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' },
+ kind: 'image',
+ capability: fableLoomImageCapabilities({ mode: 'codex', inputBudget: 4 }),
+ ...deps(loom),
+ });
+ await expect(run).rejects.toMatchObject({ code: 'FABLELOOM_CANON_CONDITIONING_UNAVAILABLE' });
+ });
+
+ it('requires an approved storyboard first frame for locked video and records capability degradation', async () => {
+ const loom = loomWith({ ...lockedBinding, storyboardImageApproved: false });
+ const capability = fableLoomVideoCapabilities({
+ backend: 'local', model: { id: 'ltx-example', supportedModes: ['text', 'image', 'fflf'] },
+ });
+ await expect(compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' },
+ kind: 'video', capability, sourceImagePath: '/approved/storyboard.png', ...deps(loom),
+ })).rejects.toBeInstanceOf(ServerError);
+
+ loom.episodes[0].nodes.at(-1).visualCanon.mode = 'draft';
+ const draft = await compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' },
+ kind: 'video', capability, sourceImagePath: '/approved/storyboard.png', ...deps(loom),
+ });
+ expect(draft.visualConditioning.status).toBe('degraded');
+ expect(draft.referenceImagePaths).toEqual([]);
+ });
+
+ it('uses an explicit incoming source at convergence and rejects a non-incoming override', async () => {
+ const loom = loomWith({ ...lockedBinding, continuitySourceNodeId: 'alternate' }, { convergence: true });
+ const capability = fableLoomImageCapabilities({
+ mode: 'local', model: { id: 'flux2-klein', runner: 'flux2' }, inputBudget: 8,
+ });
+ const valid = await compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image', capability, ...deps(loom),
+ });
+ expect(valid.visualConditioning.temporalSourceNodeId).toBe('alternate');
+
+ loom.episodes[0].nodes.at(-1).visualCanon.continuitySourceNodeId = 'missing';
+ await expect(compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image', capability, ...deps(loom),
+ })).rejects.toMatchObject({ code: 'FABLELOOM_CANON_CONDITIONING_UNAVAILABLE' });
+
+ delete loom.episodes[0].nodes.at(-1).visualCanon.continuitySourceNodeId;
+ await expect(compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image', capability, ...deps(loom),
+ })).rejects.toMatchObject({ code: 'FABLELOOM_CANON_CONDITIONING_UNAVAILABLE' });
+ });
+
+ it('records every compatible adapter that exceeds the backend budget and blocks locked output', async () => {
+ const loom = loomWith(lockedBinding);
+ const injected = deps(loom);
+ injected.resolveLoras.mockResolvedValue([
+ { filename: 'aria-a.safetensors', scale: 0.7, character: { entryId: 'char-a' } },
+ { filename: 'aria-b.safetensors', scale: 0.8, character: { entryId: 'char-a' } },
+ ]);
+ const capability = {
+ ...fableLoomImageCapabilities({
+ mode: 'local', model: { id: 'flux2-klein', runner: 'flux2' }, inputBudget: 8,
+ }),
+ loraBudget: 1,
+ };
+
+ const run = compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image', capability, ...injected,
+ });
+ await expect(run).rejects.toMatchObject({
+ code: 'FABLELOOM_CANON_CONDITIONING_UNAVAILABLE',
+ context: { details: { visualConditioning: { omitted: [expect.objectContaining({
+ role: 'character-adapter', filename: 'aria-b.safetensors', reason: 'adapter-budget',
+ })] } } },
+ });
+ });
+
+ it('keeps legacy inferred bindings explicitly draft/degraded', async () => {
+ const loom = loomWith(null);
+ const result = await compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image',
+ capability: fableLoomImageCapabilities({ mode: 'external' }), ...deps(loom),
+ });
+ expect(result.visualConditioning).toMatchObject({ status: 'degraded', bindings: { inferred: true } });
+ expect(result.visualConditioning.omitted.length).toBeGreaterThan(0);
+ });
+
+ it('resolves an older loom through its linked series and leaves unlinked legacy scenes unchanged', async () => {
+ const loom = loomWith(lockedBinding);
+ loom.universeId = null;
+ loom.seriesId = 'series-1';
+ const injected = deps(loom);
+ const result = await compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image',
+ capability: fableLoomImageCapabilities({
+ mode: 'local', model: { id: 'flux2-klein', runner: 'flux2' }, inputBudget: 8,
+ }),
+ loadSeries: vi.fn(async () => ({ id: 'series-1', universeId: universe.id })),
+ ...injected,
+ });
+ expect(result.visualConditioning.universeId).toBe(universe.id);
+
+ loom.seriesId = null;
+ loom.episodes[0].nodes.at(-1).visualCanon = null;
+ await expect(compileFableLoomVisualRequest({
+ tag: { loomId: loom.id, episodeId: 'episode-1', nodeId: 'shot' }, kind: 'image',
+ capability: fableLoomImageCapabilities({ mode: 'external' }),
+ ...injected,
+ })).resolves.toBeNull();
+ });
+});
diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.js
index 1ffb9b2c90..6ae592571c 100644
--- a/server/services/fableLoom/weave.js
+++ b/server/services/fableLoom/weave.js
@@ -165,6 +165,7 @@ const generatedNodeFields = (raw) => ({
imagePrompt: raw.imagePrompt,
videoPrompt: raw.videoPrompt,
cameraMovement: raw.cameraMovement,
+ visualCanon: raw.visualCanon,
playbackMode: raw.playbackMode,
audienceConnection: raw.audienceConnection,
isEnding: raw.isEnding === true,
diff --git a/server/services/fableLoomSceneImageHook.js b/server/services/fableLoomSceneImageHook.js
index 84528bb57c..186ac4e3bc 100644
--- a/server/services/fableLoomSceneImageHook.js
+++ b/server/services/fableLoomSceneImageHook.js
@@ -35,7 +35,11 @@ const hook = createMediaJobImageHook({
sceneKey: ({ loomId, episodeId, nodeId }) => `${loomId}:${episodeId}:${nodeId}`,
describe: ({ loomId, nodeId }) => `${loomId.slice(0, 13)}/${nodeId.slice(0, 13)}`,
attach: ({ loomId, episodeId, nodeId, filename, job }) =>
- attachNodeImage(loomId, episodeId, nodeId, { filename, jobId: deriveRenderJobId(job, filename) }),
+ attachNodeImage(loomId, episodeId, nodeId, {
+ filename,
+ jobId: deriveRenderJobId(job, filename),
+ ...(job.params?.visualConditioning ? { visualConditioning: job.params.visualConditioning } : {}),
+ }),
onAttached: ({ loomId, nodeId, filename }, result) => {
if (!result) return;
console.log(`🧶 fableloom scene image ${loomId.slice(0, 13)}/${nodeId.slice(0, 13)} ← ${filename}`);
diff --git a/server/services/fableLoomSceneVideoHook.js b/server/services/fableLoomSceneVideoHook.js
index c52fc2261b..e388bb14cd 100644
--- a/server/services/fableLoomSceneVideoHook.js
+++ b/server/services/fableLoomSceneVideoHook.js
@@ -25,8 +25,11 @@ const hook = createMediaJobImageHook({
serializeKey: ({ loomId }) => loomId,
sceneKey: ({ loomId, episodeId, nodeId }) => `${loomId}:${episodeId}:${nodeId}`,
describe: ({ loomId, nodeId }) => `${loomId.slice(0, 13)}/${nodeId.slice(0, 13)}`,
- attach: ({ loomId, episodeId, nodeId, videoHistoryId }) =>
- attachNodeVideo(loomId, episodeId, nodeId, { videoHistoryId }),
+ attach: ({ loomId, episodeId, nodeId, videoHistoryId, job }) =>
+ attachNodeVideo(loomId, episodeId, nodeId, {
+ videoHistoryId,
+ ...(job.params?.visualConditioning ? { visualConditioning: job.params.visualConditioning } : {}),
+ }),
onAttached: ({ loomId, nodeId, videoHistoryId }, result) => {
if (!result) return;
console.log(`🎬 fableloom scene video ${loomId.slice(0, 13)}/${nodeId.slice(0, 13)} ← ${videoHistoryId}`);
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.js
index dd153ccac6..fa02adfcf6 100644
--- a/server/services/imageGen/agy.js
+++ b/server/services/imageGen/agy.js
@@ -213,6 +213,7 @@ export async function generateImage({
initImagePath,
initImageStrength,
referenceImagePaths = [],
+ visualConditioning = null,
jobId: providedJobId = null,
cleanC2PA = false,
denoise = false,
@@ -259,6 +260,7 @@ export async function generateImage({
// renders on Antigravity's fixed server-side backend — record it so
// provenance names the model that actually produced the pixels (#3231).
imageModel: AGY_IMAGEGEN_IMAGE_MODEL,
+ ...(visualConditioning ? { visualConditioning } : {}),
createdAt: new Date().toISOString(),
};
const job = { ...meta, clients: [], status: 'running' };
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 3f9962e6b7..1d4c5c31c8 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -172,6 +172,7 @@ export function buildCodexAttachmentPrefix({ initPath, referenceCount, initImage
export async function generateImage({
codexPath, model, effort, prompt = '', width, height, negativePrompt,
initImagePath, initImageStrength, referenceImagePaths = [],
+ visualConditioning = null,
jobId: providedJobId = null,
cleanC2PA = false,
denoise = false,
@@ -259,6 +260,7 @@ export async function generateImage({
id: jobId, prompt: prompt.trim(), negativePrompt: negativePrompt || '',
width: width ? Number(width) : null, height: height ? Number(height) : null,
filename, mode: IMAGE_GEN_MODE.CODEX, model: effectiveModel,
+ ...(visualConditioning ? { visualConditioning } : {}),
createdAt: new Date().toISOString(),
};
const job = { ...meta, clients: [], status: 'running' };
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
index 816060a0ab..6c001b9eb2 100644
--- a/server/services/imageGen/grok.js
+++ b/server/services/imageGen/grok.js
@@ -211,6 +211,7 @@ export function buildGrokPrompt({
export async function generateImage({
grokPath, aspectRatio, prompt = '', width, height, negativePrompt,
initImagePath, initImageStrength, referenceImagePaths = [],
+ visualConditioning = null,
jobId: providedJobId = null,
cleanC2PA = false,
denoise = false,
@@ -268,6 +269,7 @@ export async function generateImage({
id: jobId, prompt: prompt.trim(), negativePrompt: negativePrompt || '',
width: width ? Number(width) : null, height: height ? Number(height) : null,
filename, mode: IMAGE_GEN_MODE.GROK,
+ ...(visualConditioning ? { visualConditioning } : {}),
...(effectiveRatio ? { aspectRatio: effectiveRatio } : {}),
createdAt: new Date().toISOString(),
};
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index b2c6cbde05..88d7ff5bda 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -333,6 +333,7 @@ export function buildSidecarMeta({
initImageStrength = null,
referenceImagePaths = [],
referenceImageStrengths = [],
+ visualConditioning = null,
// SynthID-defeat regen lineage. When `regenOf` is set, this render is a
// post-hoc round-trip of an existing gallery image through local FLUX
// img2img (issue #912) — stamp the source filename as `cleanedFrom` (so the
@@ -413,7 +414,7 @@ export function buildSidecarMeta({
// a Flux2KVLayerCache.store + _flux2_kv_causal_attention patch that scales
// each reference's V slice by the corresponding strength (1.0 = upstream
// baseline, 0.0 = ignored). Mirrors the Python sidecar's `referenceStrengths`.
- const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, initImageFilename: validInitImagePath ? basename(validInitImagePath) : null, initImageStrength: validInitImageStrength, referenceImageFilenames: validReferenceImagePaths.map((p) => basename(p)), referenceImageStrengths: validReferenceImageStrengths, createdAt: now() };
+ const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: Number(width), height: Number(height), steps: actualSteps, guidance: actualGuidance, quantize, filename, loraFilenames: validLoraFilenames, loraPaths: validLoras, loraScales, initImageFilename: validInitImagePath ? basename(validInitImagePath) : null, initImageStrength: validInitImageStrength, referenceImageFilenames: validReferenceImagePaths.map((p) => basename(p)), referenceImageStrengths: validReferenceImageStrengths, ...(visualConditioning ? { visualConditioning } : {}), createdAt: now() };
// Regen lineage (issue #912). `regenOf` is the source gallery filename this
// render was generated from. We reuse the existing `cleanedFrom` field so the
// lightbox's `computeImageVariantGroup` groups the regen under its source with
@@ -530,7 +531,7 @@ export function parseImageExecutionMarker(line) {
};
}
-export async function generateImage({ pythonPath, prompt = '', negativePrompt = '', modelId = LOCAL_IMAGEGEN_DEFAULT_MODEL, width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null, cleanC2PA = false, denoise = false, regenOf = null, upscaleTo = null, outputTarget = null }) {
+export async function generateImage({ pythonPath, prompt = '', negativePrompt = '', modelId = LOCAL_IMAGEGEN_DEFAULT_MODEL, width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], visualConditioning = null, jobId: providedJobId = null, cleanC2PA = false, denoise = false, regenOf = null, upscaleTo = null, outputTarget = null }) {
// Empty prompt is allowed: img2img / edit / unconditional renders are driven
// by the init image (or run unconditionally), so text isn't required. The
// mflux/diffusers runners accept an empty `--prompt` — the regen pass (#912)
@@ -618,6 +619,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
initImageStrength,
referenceImagePaths,
referenceImageStrengths,
+ visualConditioning,
regenOf,
loraTriggerWords,
resolveInputPath: resolveImageInputPath,
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 4944ac2207..f83ab0509b 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -645,6 +645,14 @@ describe('imageGen local.buildSidecarMeta', () => {
expect(meta.referenceImageStrengths).toEqual([0.85, 0.5]);
});
+ it('persists FableLoom visual-conditioning provenance without rewriting it', () => {
+ const visualConditioning = {
+ version: 1, compilerVersion: '1.0.0', status: 'locked', assets: [{ role: 'character-neutral', filename: 'aria.png' }],
+ };
+ const { meta } = buildSidecarMeta({ ...baseMetaInput, visualConditioning });
+ expect(meta.visualConditioning).toBe(visualConditioning);
+ });
+
it('stamps regen lineage (cleanedFrom + regen* fields) when regenOf is set', () => {
const { meta } = buildSidecarMeta({
...baseMetaInput,
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index aae3f72f7e..eba9c2012b 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -2882,7 +2882,7 @@ describe('peerSync', () => {
});
expect(mergeLoomsFromSync).toHaveBeenCalledWith(
[expect.objectContaining({ id: 'loom-1' })],
- { source: { via: 'peer-push', peerId: 'peer-a' } },
+ { source: { via: 'peer-push', peerId: 'peer-a' }, senderSchemaVersions: {} },
);
});
diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.js
index 3537e8be3b..95cbc0737c 100644
--- a/server/services/sharing/peerSyncReceive.js
+++ b/server/services/sharing/peerSyncReceive.js
@@ -340,7 +340,7 @@ export async function applyIncomingPush(payload) {
} else if (kind === 'moodBoard') {
await mergeBoardsFromSync([record], { source });
} else if (kind === 'fableLoom') {
- await mergeLoomsFromSync([record], { source });
+ await mergeLoomsFromSync([record], { source, senderSchemaVersions });
} else if (kind === 'writersRoomWork') {
const mergeResult = await mergeWorksFromSync([record], { source });
// Did the receiver accept the remote work (insert / remote-won LWW)? This
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index 25e7a98e2c..c033f39ed9 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -128,7 +128,7 @@ export const listVideoModels = () => getVideoModels().map(decorateVideoModel);
export const defaultVideoModelId = (capabilities) => getDefaultVideoModelId(capabilities);
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId, width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, speedProfileId = null, hidden = false, jobId: providedJobId = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId, width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, speedProfileId = null, visualConditioning = null, hidden = false, jobId: providedJobId = null }) {
uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is now enforced by the mediaJobQueue worker upstream — only
@@ -681,6 +681,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
audioFilePath,
icReferencePaths: resolvedIcReferencePaths,
}),
+ ...(visualConditioning ? { visualConditioning } : {}),
// Stamp the experimental fast-path so A/B analysis can tell a two-stage
// render apart from a user who happened to pick 8 steps — comparing it
// against the default Standard render is the whole point of the knob.
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index 7ec1a3dfa2..b3a2f03362 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -218,7 +218,8 @@ export const withStagedRollback = async (cleanupStaged, fn) => {
* from the route (which owns their Zod schemas) so this module never has to
* import back into `routes/`.
* @returns {Promise<object>} On the grok lane:
- * `{ backend, grok, sourceImagePath, uploadedTempPath, cleanupStaged }`.
+ * `{ backend, grok, effectiveModel, sourceImagePath, uploadedTempPath,
+ * discardSourceImage, cleanupStaged }`.
* On the local lane, additionally `{ pythonPath, effectiveModelId, mode,
* lastImagePath, audioFilePath, icReferencePaths, resolvedKeyframes,
* extendFromVideoPath, uploadedTempPaths, loras, effectiveChunks,
@@ -708,6 +709,14 @@ async function resolvePreparedParams({
{ status: 400, code: 'MUSIC_VIDEO_SOURCE_REQUIRED' },
);
}
+ const discardSourceImage = async () => {
+ if (uploadedTempPath) {
+ await unlink(uploadedTempPath).catch(() => {});
+ const index = stagedDurablePaths.indexOf(uploadedTempPath);
+ if (index >= 0) stagedDurablePaths.splice(index, 1);
+ }
+ if (uploads.sourceImage?.path) await unlink(uploads.sourceImage.path).catch(() => {});
+ };
// Grok backend short-circuit (#2859 phase 2): everything past this point —
// last-frame/keyframe staging, extend resolution, LoRA gating — is
// local-runtime machinery grok doesn't use. sourceImagePath (upload or
@@ -724,7 +733,15 @@ async function resolvePreparedParams({
{ status: 400, code: 'GROK_IMAGEGEN_DISABLED' },
);
}
- return { backend, grok, sourceImagePath, uploadedTempPath, cleanupStaged };
+ return {
+ backend,
+ grok,
+ effectiveModel: { id: 'grok', supportedModes: ['text', 'image'] },
+ sourceImagePath,
+ uploadedTempPath,
+ discardSourceImage,
+ cleanupStaged,
+ };
}
if (uploads.lastImage) {
@@ -1013,6 +1030,7 @@ async function resolvePreparedParams({
return {
backend,
pythonPath,
+ effectiveModel,
effectiveModelId,
mode: body.mode,
sourceImagePath,
@@ -1027,6 +1045,7 @@ async function resolvePreparedParams({
effectiveChunks,
effectiveChunkPrompts,
effectiveContextFrames,
+ discardSourceImage,
cleanupStaged,
};
}
diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.js
index e2bc5b5bcf..11053439ce 100644
--- a/server/services/videoGen/prepareParams.test.js
+++ b/server/services/videoGen/prepareParams.test.js
@@ -134,7 +134,9 @@ describe('cleanupMultipartTemp', () => {
describe('prepareVideoGenParams', () => {
beforeEach(() => {
vi.clearAllMocks();
- listVideoModels.mockReturnValue([{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2' }]);
+ listVideoModels.mockReturnValue([{
+ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2', supportedModes: ['text', 'image', 'fflf'],
+ }]);
loadHistory.mockResolvedValue([]);
});
@@ -143,6 +145,7 @@ describe('prepareVideoGenParams', () => {
const prepared = await prepare({ mode: 'image', chunks: 2 }, { sourceImage: upload('sourceImage') });
expect(prepared.backend).toBe('local');
expect(prepared.effectiveModelId).toBe('ltx2_unified');
+ expect(prepared.effectiveModel.supportedModes).toEqual(['text', 'image', 'fflf']);
expect(prepared.effectiveChunks).toBe(2);
expect(posix(prepared.sourceImagePath)).toMatch(/^\/mock\/uploads\/video-source-.*\.png$/);
// The start-frame upload rides the legacy single field so already-persisted
@@ -150,6 +153,10 @@ describe('prepareVideoGenParams', () => {
expect(prepared.uploadedTempPath).toBe(prepared.sourceImagePath);
expect(prepared.uploadedTempPaths).toEqual([]);
expect(unlinkedDurablePaths()).toEqual([]);
+
+ await prepared.discardSourceImage();
+ expect(unlinkedDurablePaths()).toEqual([posix(prepared.uploadedTempPath)]);
+ expect(unlink).toHaveBeenCalledWith('/tmp/multipart-sourceImage-frame.png');
});
it('short-circuits for grok without staging local-only inputs', async () => {
@@ -157,6 +164,7 @@ describe('prepareVideoGenParams', () => {
expect(prepared.backend).toBe('grok');
expect(prepared.grok.grokPath).toBe('/usr/bin/grok');
expect(prepared.sourceImagePath).toBe('/mock/images/still.png');
+ expect(prepared.effectiveModel).toMatchObject({ id: 'grok', supportedModes: ['text', 'image'] });
// The local-only fields are absent entirely — the route must not read them.
expect(prepared.effectiveChunks).toBeUndefined();
expect(prepared.loras).toBeUndefined();