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

address review (claude): make a capped reformat actually resumable

[._.]/ Adam Eivyb308d4fef8aa
diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsx
index c561666b51..06ae3bde8b 100644
--- a/client/src/components/fableloom/LoomSettingsDrawer.jsx
+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx
@@ -14,6 +14,7 @@
* all, so this only governs typed input.
*/
+import { useRef } from 'react';
import { Loader2, Sparkles } from 'lucide-react';
import Drawer from '../Drawer';
import ProviderModelSelector from '../ProviderModelSelector';
@@ -42,17 +43,32 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,
{ errorMessage: 'Save failed' },
);
+ // The merge base is a ref, not the render-time props, because the picker can
+ // emit TWO changes in one tick: choosing a model whose provider tier has no
+ // effort ladder also clears the effort. Both callbacks would otherwise build
+ // their payload from the same pre-change props, and since a PATCH replaces
+ // `playSettings` wholesale the second would put the just-picked model back to
+ // what it was. Props re-seed the ref whenever the server echo lands.
+ const pendingPlay = useRef(null);
+ if (!pendingPlay.current || !saving) pendingPlay.current = { providerId: play.providerId ?? null, model: play.model ?? null, effort: play.effort ?? null };
+
// Clearing the provider clears the model and effort with it — neither is
// meaningful (or necessarily valid) without the provider that offered them.
- const savePlay = (changes) => patch({
- playSettings: { providerId: play.providerId ?? null, model: play.model ?? null, effort: play.effort ?? null, ...changes },
- });
+ const savePlay = (changes) => {
+ pendingPlay.current = { ...pendingPlay.current, ...changes };
+ return patch({ playSettings: { ...pendingPlay.current } });
+ };
// `onRewritten` fires on BOTH paths on purpose. A rewrite persists each
// chunk as it lands, so even a run that throws part-way has already changed
// scene text on the server — any editor still holding the pre-rewrite text
// would write it back on its next blur-save.
const [runReformat, reformatting] = useAsyncAction(async () => {
+ // Clear the scene selection UP FRONT. A multi-chunk run takes minutes, and
+ // the page underneath stays interactive — an editor still holding the
+ // pre-rewrite text would write it back on any blur during that window, not
+ // just after the run settles.
+ onRewritten?.({ refetch: false });
const result = await reformatLoom(loom.id, { format }, { silent: true })
.finally(() => onRewritten?.());
onLoomUpdate(result.loom);
@@ -62,7 +78,15 @@ export default function LoomSettingsDrawer({ open, onClose, loom, onLoomUpdate,
}, { errorMessage: 'The rewrite failed' });
return (
- <Drawer open={open} onClose={onClose} title="Story settings" subtitle={loom.name} size="sm">
+ <Drawer
+ open={open}
+ onClose={onClose}
+ title="Story settings"
+ subtitle={loom.name}
+ size="sm"
+ closeOnEsc={!reformatting}
+ closeOnBackdrop={!reformatting}
+ >
<div className="space-y-5">
<section className="space-y-2">
<FormField label="Scene format" labelClassName={labelClass}>
diff --git a/client/src/components/fableloom/loomFormats.test.js b/client/src/components/fableloom/loomFormats.test.js
new file mode 100644
index 0000000000..ed88e80a3a
--- /dev/null
+++ b/client/src/components/fableloom/loomFormats.test.js
@@ -0,0 +1,50 @@
+import { describe, it, expect } from 'vitest';
+import { existsSync, readFileSync } from 'fs';
+import { dirname, join, resolve } from 'path';
+import { LOOM_FORMATS, isTeleplayFormat, loomFormatHint, loomFormatLabel } from './loomFormats.js';
+
+const SERVER_FORMATS = join('server', 'services', 'fableLoom', 'formats.js');
+
+// Walk up from the working directory rather than assuming it — the client
+// suite runs from `client/`, but a root-level runner would start elsewhere.
+function findServerFormats() {
+ let dir = process.cwd();
+ for (let depth = 0; depth < 6; depth += 1) {
+ const candidate = join(dir, SERVER_FORMATS);
+ if (existsSync(candidate)) return candidate;
+ const parent = dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return null;
+}
+
+// This module is a hand-mirror of server/services/fableLoom/formats.js. The
+// server rejects an unknown format at the door, so a client-only id ships a
+// select option that 400s on save with the whole suite still green — the
+// mirror needs a guard, not just a comment saying to keep it in step.
+describe('loomFormats', () => {
+ it('offers exactly the ids the server accepts', () => {
+ const path = findServerFormats();
+ // A null path means the mirror source moved; failing here is the point —
+ // silently skipping would retire the guard without anyone noticing.
+ expect(path, `could not find ${SERVER_FORMATS} from ${resolve(process.cwd())}`).not.toBeNull();
+ const source = readFileSync(path, 'utf8');
+ const declared = source.match(/LOOM_FORMATS = Object\.freeze\(\[([\s\S]*?)\]\)/);
+ expect(declared, 'server LOOM_FORMATS declaration not recognized').not.toBeNull();
+ const serverIds = [...declared[1].matchAll(/'([^']+)'/g)].map((m) => m[1]);
+ expect(serverIds.length).toBeGreaterThan(0);
+ expect(LOOM_FORMATS.map((f) => f.id)).toEqual(serverIds);
+ });
+
+ it('labels and hints every id, and never falls through to a blank', () => {
+ for (const { id } of LOOM_FORMATS) {
+ expect(loomFormatLabel(id)).toBeTruthy();
+ expect(loomFormatHint(id)).toBeTruthy();
+ }
+ // An unknown id degrades to the default rather than rendering empty chrome.
+ expect(loomFormatLabel('haiku')).toBe(LOOM_FORMATS[0].label);
+ expect(isTeleplayFormat('haiku')).toBe(false);
+ expect(isTeleplayFormat('teleplay')).toBe(true);
+ });
+});
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index 02143d9035..d8795e4310 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -82,10 +82,11 @@ export default function FableLoomStory() {
// moved some). Re-read the record and drop the scene selection: an open
// scene editor still holds the pre-rewrite text and would write it back on
// its next blur-save.
- const handleRewritten = async () => {
+ const handleRewritten = async ({ refetch = true } = {}) => {
+ if (nodeId) navigate(episodePath(episodeId, null) + (playOpen ? '?play=1' : ''));
+ if (!refetch) return;
const fresh = await getLoom(loomId).catch(() => null);
if (fresh) setLoom(fresh);
- if (nodeId) navigate(episodePath(episodeId, null) + (playOpen ? '?play=1' : ''));
};
const handleAddNode = async () => {
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index 80b260edbf..52a9fd7681 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -24,7 +24,7 @@ import {
writeRaw,
} from './store.js';
import { LOOM_LIMITS } from './limits.js';
-import { asLoomFormat } from './formats.js';
+import { asLoomFormat, isLoomFormat } from './formats.js';
export { LOOM_LIMITS };
@@ -83,6 +83,12 @@ function sanitizeNode(raw) {
image: isSafeImageFilename(raw.image) ? raw.image : null,
imageJobId: isStr(raw.imageJobId) && raw.imageJobId ? raw.imageJobId.slice(0, 200) : null,
isEnding: raw.isEnding === true,
+ // The format this scene's text is actually WRITTEN in — server-set, not
+ // patchable. `null` means unknown (authored before the field existed, or
+ // by hand), which a reformat treats as "needs converting". Without it a
+ // rewrite that stopped at the per-request ceiling would re-send the scenes
+ // it already converted and never reach the ones it didn't.
+ format: isLoomFormat(raw.format) ? raw.format : null,
endingLabel: trimTo(raw.endingLabel, LOOM_LIMITS.ENDING_LABEL_MAX),
transitions: (Array.isArray(raw.transitions) ? raw.transitions : [])
.map(sanitizeTransition)
diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.js
index 64ff1b3804..4bf55f23ba 100644
--- a/server/services/fableLoom/weave.js
+++ b/server/services/fableLoom/weave.js
@@ -153,7 +153,9 @@ export async function weaveEpisode(loomId, episodeId, {
const { nodes, startNodeId } = mapGeneratedGraph(content);
const updated = await mutateLoom(loomId, (current) => {
const ep = findEpisode(current, episodeId);
- ep.nodes = nodes;
+ // Stamped with the format they were generated in, so a later reformat can
+ // tell them apart from scenes already in the target format.
+ ep.nodes = nodes.map((n) => ({ ...n, format: asLoomFormat(loom.format) }));
ep.startNodeId = startNodeId;
ep.updatedAt = new Date().toISOString();
return current;
@@ -193,7 +195,7 @@ export async function branchNode(loomId, episodeId, nodeId, {
const source = findNode(ep, nodeId);
for (const branch of branches) {
if (ep.nodes.length >= LOOM_LIMITS.NODES_MAX) break;
- const newNode = { id: `node-${randomUUID()}`, ...generatedNodeFields(branch.node), transitions: [], pos: null };
+ const newNode = { id: `node-${randomUUID()}`, ...generatedNodeFields(branch.node), format: asLoomFormat(loom.format), transitions: [], pos: null };
ep.nodes.push(newNode);
source.transitions = [...(source.transitions || []), {
targetNodeId: newNode.id,
@@ -336,8 +338,10 @@ const REFORMAT_CHUNK = 5;
// Hard ceiling on provider calls per request. The record caps allow 100
// episodes x 200 scenes, which at 5 per call is 4,000 sequential calls behind
// one HTTP request — a spend and timeout hazard nobody asked for. A run that
-// hits the ceiling reports what is left; re-running finishes the job, because
-// scenes already rewritten are skipped as no-ops by the next pass.
+// hits the ceiling reports what is left, and re-running genuinely finishes the
+// job: each scene is stamped with the format it was written in as it lands, so
+// the next pass skips what is already converted instead of re-sending it and
+// stopping in the same place forever.
const REFORMAT_CHUNKS_MAX = 40;
/**
@@ -347,10 +351,10 @@ const REFORMAT_CHUNKS_MAX = 40;
*
* Each chunk is persisted as it lands: a provider failure halfway through
* leaves the already-rewritten scenes rewritten, and re-running finishes the
- * job rather than starting over. The format pin is written LAST — a run that
- * rewrote nothing must not leave the loom claiming a format its scenes aren't
- * in, or every later weave/branch/play generates against a contract the story
- * doesn't follow.
+ * job rather than starting over. The loom's format pin is written LAST and only
+ * once EVERY scene is converted — a loom still holding unconverted scenes must
+ * not claim a format its story isn't in, or every later weave/branch/play
+ * generates against a contract that story doesn't follow.
*/
export async function reformatLoom(loomId, { format, providerId, model, effort } = {}) {
const target = asLoomFormat(format);
@@ -362,7 +366,7 @@ export async function reformatLoom(loomId, { format, providerId, model, effort }
// scene, so the model invents one and it lands on the node as if authored.
const pending = loom.episodes.map((episode) => ({
episode,
- nodes: episode.nodes.filter((n) => isStr(n.prose) && n.prose.trim()),
+ nodes: episode.nodes.filter((n) => isStr(n.prose) && n.prose.trim() && n.format !== target),
})).filter((e) => e.nodes.length);
const sceneCount = pending.reduce((total, e) => total + e.nodes.length, 0);
let rewritten = 0;
@@ -378,7 +382,11 @@ export async function reformatLoom(loomId, { format, providerId, model, effort }
}
chunks += 1;
const { content, runId } = await runStagedLLM('fableloom-reformat-scenes', {
- storyContext: storyContext(loom, episode),
+ // The TARGET format, not the loom's current one: the pin is written
+ // last, so passing `loom` would assert the source format as fact in
+ // the same prompt that asks for the target — and would render
+ // differently on a resumed run than on the first one.
+ storyContext: storyContext({ ...loom, format: target }, episode),
canonDigest: canonDigest || '(none)',
formatLabel: loomFormatLabel(target),
sceneFormatContract: sceneFormatContract(target),
@@ -402,6 +410,7 @@ export async function reformatLoom(loomId, { format, providerId, model, effort }
const rewrite = byId.get(sceneNode.id);
if (!rewrite) continue;
sceneNode.prose = rewrite.prose;
+ sceneNode.format = target;
if (isStr(rewrite.title) && rewrite.title.trim()) sceneNode.title = rewrite.title;
}
ep.updatedAt = new Date().toISOString();
@@ -414,6 +423,10 @@ export async function reformatLoom(loomId, { format, providerId, model, effort }
// A loom with nothing to rewrite is a no-op, not a failure — the pin is still
// the point. Only a loom that HAD scenes and got none back is a bad response.
if (sceneCount && !rewritten) throw aiShapeError('The model returned no rewritten scenes');
- const updated = await mutateLoom(loomId, (current) => ({ ...current, format: target }));
+ // Only a fully-converted loom gets the pin; a run that stopped at the ceiling
+ // leaves it alone so the record never claims a format half its scenes lack.
+ const updated = remaining
+ ? await getLoom(loomId)
+ : await mutateLoom(loomId, (current) => ({ ...current, format: target }));
return { loom: updated, format: target, rewritten, remaining, runIds };
}
diff --git a/server/services/fableLoom/weave.test.js b/server/services/fableLoom/weave.test.js
index 46a61a241b..677b03062d 100644
--- a/server/services/fableLoom/weave.test.js
+++ b/server/services/fableLoom/weave.test.js
@@ -22,7 +22,7 @@ vi.mock('../universeBuilder.js', () => ({ getUniverse: getUniverseMock }));
const getSeriesMock = vi.hoisted(() => vi.fn(async () => null));
vi.mock('../pipeline/series.js', () => ({ getSeries: getSeriesMock }));
-const { createLoom, addEpisode, addNode, updateLoom, updateNode, getLoom } = await import('./records.js');
+const { createLoom, addEpisode, addNode, mutateLoom, updateLoom, updateNode, getLoom } = await import('./records.js');
const { _resetFableLoomBackend } = await import('./store.js');
const {
branchNode, buildCanonDigest, mapGeneratedGraph, playTurn, reformatLoom, reviewEpisode, weaveEpisode,
@@ -379,6 +379,56 @@ describe('reformatLoom', () => {
expect(result.loom.episodes[0].nodes.find((n) => n.title.startsWith('Placeholder')).prose).toBe('');
});
+ it('stops at the per-request ceiling and genuinely finishes on the next run', async () => {
+ const { loomId, episodeId } = await setup();
+ // The ceiling is 40 chunks x 5 scenes = 200, and NODES_MAX caps ONE episode
+ // at 200 — so only a multi-episode loom can reach it. Two episodes of 105
+ // scenes = 42 chunks: the first run stops 2 chunks short.
+ const withEp2 = await addEpisode(loomId, { title: 'Two' });
+ const episode2Id = withEp2.episodes[1].id;
+ await mutateLoom(loomId, (current) => {
+ for (const [index, epId] of [episodeId, episode2Id].entries()) {
+ const ep = current.episodes.find((e) => e.id === epId);
+ ep.nodes = Array.from({ length: 105 }, (_, i) => ({
+ id: `node-ceiling-${index}-${i}`, title: `Scene ${i}`, prose: `Prose ${index}-${i}.`, transitions: [],
+ }));
+ }
+ return current;
+ });
+ runStagedLLM.mockImplementation(async (stage, variables) => ({
+ content: { scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: `INT. ${sc.prose}` })) },
+ }));
+
+ const first = await reformatLoom(loomId, { format: 'teleplay' });
+ expect(first).toMatchObject({ rewritten: 200, remaining: 10 });
+ // The loom is NOT pinned yet — 5 scenes are still prose.
+ expect(first.loom.format).toBe('prose');
+
+ const callsAfterFirst = runStagedLLM.mock.calls.length;
+ const second = await reformatLoom(loomId, { format: 'teleplay' });
+ // Only the 2 leftover chunks are re-sent; the 200 already converted are skipped.
+ expect(runStagedLLM.mock.calls.length - callsAfterFirst).toBe(2);
+ expect(second).toMatchObject({ rewritten: 10, remaining: 0 });
+ expect(second.loom.format).toBe('teleplay');
+ const allNodes = second.loom.episodes.flatMap((e) => e.nodes);
+ expect(allNodes).toHaveLength(210);
+ expect(allNodes.every((n) => n.prose.startsWith('INT. '))).toBe(true);
+ expect(allNodes.every((n) => n.format === 'teleplay')).toBe(true);
+ });
+
+ it('asks the model for the TARGET format, not the one the loom still holds', async () => {
+ const { loomId } = await proseSetup();
+ runStagedLLM.mockImplementation(async (stage, variables) => ({
+ content: { scenes: JSON.parse(variables.scenesJson).map((sc) => ({ id: sc.id, prose: 'INT. GATE' })) },
+ }));
+ await reformatLoom(loomId, { format: 'teleplay' });
+ const [, variables] = runStagedLLM.mock.calls[0];
+ // Asserting the source format here as fact would contradict the template's
+ // own "Target format" heading in the same prompt.
+ expect(variables.storyContext).toContain('teleplay');
+ expect(variables.storyContext).not.toContain('narrated prose');
+ });
+
it('ignores scenes the model dropped or blanked, and fails when it returns none', async () => {
const { loomId, gateId, insideId } = await proseSetup();
runStagedLLM.mockResolvedValue({ content: { scenes: [{ id: gateId, prose: 'INT. GATE' }, { id: insideId, prose: ' ' }] } });