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

fix: merge storyboard scene writes against fresh state so sibling renders don't clobber job ids (#3400)

[._.]/ Adam Eivy82cdc5cf823f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2fd9d15458..21dfec85cf 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -7,6 +7,7 @@
## Fixed
+- **[issue-3400] Rendering two storyboard scenes at once no longer loses one of the jobs.** `enqueueStoryboardSceneVideo`, `enqueueStoryboardShotStartFrame`, and `refineStoryboardScenePrompt` each read `stages.storyboards.scenes` up front, then wrote the whole pre-read array back through `updateStage`. That write *is* serialized, but the array it shallow-merges was built outside the lock — so two enqueues for different scenes that both read before either wrote would revert each other's freshly-stamped `sceneVideoJobId` / `startFrameJobId`, and the losing render would run to completion with nothing left pointing at it. All three now patch a single scene through `updateStageWithLatest`, so the read-modify-write of `scenes` happens inside the write region and only the targeted index is replaced. A scene that disappeared between the caller's read and the write now 404s instead of resurrecting itself.
- **[issue-3407] Stacker News sync works again.** Stacker News renamed its territory listing route from `/recent` to `/new`, so every browser-transport sync was refused with "landed on a different page than the one requested" — the redirect guard correctly caught the rename. Syncs now request the new route directly; the guard stays strict.
- **A completed TUI agent could be recorded as failed by a duplicate finalize.** `cleanupOrphanedAgents` runs every 15 minutes and calls `syncRunnerAgents`, which only checked `runnerAgents` for "already tracked" — but a runner-backed TUI agent is owned by the live `spawnTuiAgent` closure, which registers in `activeAgents` and never in `runnerAgents`. Any TUI run outliving one health-check tick was therefore hoisted into `runnerAgents` mid-flight, so the `agent:completed` event the runner emits when the TUI spawner's own `finish()` kills the session slipped past the `if (!agent) return` guard and ran a *second* `finalizeAgent`. That overwrote a sentinel-signalled success with `success: false, exitCode: 143` plus a bogus `startup-failure` analysis (computed from an output buffer that path can't read — a TUI writes `output.txt` under the dated run dir, not `AGENTS_DIR/<id>`), which in turn flipped the agent card to Failed and requeued the already-finished task as `pending`. Observed on a 55-minute release-check run that had already published v2.37.0 and merged all three of its PRs.
- **`completeAgent` is now idempotent, so the caller-level guard is no longer the only line of defense.** Six call sites funnel every terminal agent write through `completeAgent`, and each carried the same latent "I might be second" assumption. A duplicate call re-recorded `result` (success verdict, exit code, error analysis) and re-ran the completed-agent directory move; the guards that caught the TUI double-finalize above read the record *outside* the state lock, so they narrowed the race rather than closing it. `completeAgent` now returns an already-`completed` record unmutated from inside the lock it already holds — and skips the budget-ledger charge and the second `agent:completed` emit that would otherwise re-run the scheduler hand-off. `paused` records are still completable, so a resumed agent can't wedge. The one thing a duplicate *does* still do is finish a half-written archive: `archiveCompletedAgent` is now idempotent (the directory move is skipped once the date bucket exists, the index write always re-runs because `saveAgentIndex` swallows its own errors), and the cross-filesystem copy fallback rolls back a partially-copied target instead of leaving a directory that every later attempt mistakes for a finished archive.
diff --git a/server/services/pipeline/storyboards.js b/server/services/pipeline/storyboards.js
index 1d69d4836a..a41bd3df03 100644
--- a/server/services/pipeline/storyboards.js
+++ b/server/services/pipeline/storyboards.js
@@ -7,7 +7,7 @@
*/
import { enqueueJob } from '../mediaJobQueue/index.js';
-import { updateStage, assertStageUnlocked } from './issues.js';
+import { updateStageWithLatest, assertStageUnlocked } from './issues.js';
import { buildStoryboardsShotOwner } from './owners.js';
import { ServerError } from '../../lib/errorHandler.js';
import { matchCharactersInText } from '../../lib/scenePrompt.js';
@@ -19,6 +19,36 @@ import {
seriesBibleCtx, issueCtx, neighborText, loadRefineContext,
} from './visualStageHelpers.js';
+/**
+ * Splice ONE storyboard scene through `updateStageWithLatest` (the serialized
+ * issue write tail) so the write merges against the freshest persisted
+ * `scenes` array (#3400).
+ *
+ * `updateStage` serializes, but it shallow-merges whatever `scenes` value the
+ * caller computed *outside* the lock. Two enqueues for different scenes that
+ * both read the stage before either wrote would therefore clobber each other's
+ * freshly-stamped job id, leaving the losing job running untracked. Passing a
+ * mutator instead keeps the read-modify-write of `scenes` inside the lock, so
+ * only the targeted index is replaced.
+ *
+ * `mutate(scene) → nextScene` runs against the freshest scene at `index`.
+ * Returns `{ issue, stage }` from the write tail.
+ */
+function patchStoryboardScene(issueId, index, mutate) {
+ return updateStageWithLatest(issueId, 'storyboards', (currentStage) => {
+ const currentScenes = Array.isArray(currentStage?.scenes) ? currentStage.scenes : [];
+ const current = currentScenes[index];
+ if (!current) {
+ throw new ServerError(`sceneIndex ${index} out of range (have ${currentScenes.length})`, {
+ status: 404, code: 'PIPELINE_SCENE_NOT_FOUND',
+ });
+ }
+ const nextScenes = [...currentScenes];
+ nextScenes[index] = mutate(current);
+ return { status: 'edited', scenes: nextScenes };
+ });
+}
+
/**
* Enqueue a single-scene video render for a storyboard scene. Builds the
* same prompt the episode-video CD treatment would build for this scene
@@ -107,11 +137,9 @@ export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options =
owner: `pipeline:${issueId}:storyboards:scene${idx}`,
});
- scenes[idx] = { ...scene, sceneVideoJobId: jobId };
- const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {
- status: 'edited',
- scenes,
- });
+ const { issue: updatedIssue, stage } = await patchStoryboardScene(
+ issueId, idx, (current) => ({ ...current, sceneVideoJobId: jobId }),
+ );
console.log(`🎥 Pipeline scene video — issue=${issueId.slice(0, 8)} scene=${idx + 1} jobId=${jobId.slice(0, 8)}`);
return { jobId, prompt, sceneIndex: idx, issue: updatedIssue, stage };
}
@@ -181,11 +209,15 @@ export async function enqueueStoryboardShotStartFrame(issueId, sceneIndex, shotI
logLine: `🎞️ Pipeline shot start-frame — issue=${issueId.slice(0, 8)} scene=${sIdx + 1} shot=${tIdx + 1}`,
});
- shots[tIdx] = { ...shot, startFrameJobId: jobId };
- scenes[sIdx] = { ...scene, shots };
- const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {
- status: 'edited',
- scenes,
+ const { issue: updatedIssue, stage } = await patchStoryboardScene(issueId, sIdx, (current) => {
+ const currentShots = Array.isArray(current.shots) ? [...current.shots] : [];
+ if (!currentShots[tIdx]) {
+ throw new ServerError(`shotIndex ${tIdx} out of range (have ${currentShots.length})`, {
+ status: 404, code: 'PIPELINE_SHOT_NOT_FOUND',
+ });
+ }
+ currentShots[tIdx] = { ...currentShots[tIdx], startFrameJobId: jobId };
+ return { ...current, shots: currentShots };
});
return { jobId, mode, prompt, sceneIndex: sIdx, shotIndex: tIdx, issue: updatedIssue, stage };
}
@@ -240,7 +272,7 @@ async function loadStoryboardScenePromptContext(issueId, sceneIndex) {
* description on the scene. Returns { scene, issue, stage, runId, changes, providerId }.
*/
export async function refineStoryboardScenePrompt(issueId, sceneIndex, options = {}) {
- const { idx, scenes, scene, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);
+ const { idx, variables } = await loadStoryboardScenePromptContext(issueId, sceneIndex);
const { refined, changes, runId, providerId } = await runPromptRefine({
templateName: 'pipeline-storyboard-image-prompt',
@@ -250,12 +282,13 @@ export async function refineStoryboardScenePrompt(issueId, sceneIndex, options =
logTag: `Pipeline scene refine — issue=${issueId.slice(0, 8)} scene=${idx + 1}`,
});
- scenes[idx] = { ...scene, description: refined };
- const { issue: updatedIssue, stage } = await updateStage(issueId, 'storyboards', {
- status: 'edited',
- scenes,
- });
- return { scene: scenes[idx], issue: updatedIssue, stage, runId, changes, providerId };
+ // Same freshest-scenes merge as the enqueue paths — the LLM round-trip above
+ // is the widest read→write window in this file, so a sibling scene's render
+ // enqueue landing mid-refine must not be reverted by this write.
+ const { issue: updatedIssue, stage } = await patchStoryboardScene(
+ issueId, idx, (current) => ({ ...current, description: refined }),
+ );
+ return { scene: stage.scenes[idx], issue: updatedIssue, stage, runId, changes, providerId };
}
/**
diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.js
index 2406e34175..44e6894804 100644
--- a/server/services/pipeline/visualStages.test.js
+++ b/server/services/pipeline/visualStages.test.js
@@ -26,7 +26,14 @@ const mockIssue = {
},
};
-const getIssueMock = vi.fn(async () => structuredClone(mockIssue));
+// The stage state the serialized write tail sees. Kept separate from
+// `mockIssue` so a test can point the outer `getIssue` read AND the write-tail
+// mock at the same overridden stage (see `useStoryboardScenes`) — a mutator
+// that patches the freshest persisted array must see what the caller read.
+let persistedStages = structuredClone(mockIssue.stages);
+
+const DEFAULT_GET_ISSUE = async () => structuredClone(mockIssue);
+const getIssueMock = vi.fn(DEFAULT_GET_ISSUE);
const updateStageMock = vi.fn(async (issueId, stageId, patch) => ({
issue: { ...mockIssue, stages: { ...mockIssue.stages, [stageId]: { ...mockIssue.stages[stageId], ...patch } } },
stage: { ...mockIssue.stages[stageId], ...patch },
@@ -35,12 +42,13 @@ const assertStageUnlockedMock = vi.fn(() => undefined);
// updateStageWithLatest runs the caller's computeFn against the latest comicPages
// stage (mirrors the real serialized-write behavior) so the render+persist tests
// can assert the exact slot the route/tool would write.
-const updateStageWithLatestMock = vi.fn(async (issueId, stageId, computeFn) => {
- const current = structuredClone(mockIssue.stages[stageId] || {});
+const DEFAULT_UPDATE_STAGE_WITH_LATEST = async (issueId, stageId, computeFn) => {
+ const current = structuredClone(persistedStages[stageId] || {});
const patch = computeFn(current);
const stage = { ...current, ...patch };
return { issue: { ...mockIssue, stages: { ...mockIssue.stages, [stageId]: stage } }, stage };
-});
+};
+const updateStageWithLatestMock = vi.fn(DEFAULT_UPDATE_STAGE_WITH_LATEST);
vi.mock('./issues.js', () => ({
getIssue: (...a) => getIssueMock(...a),
updateStage: (...a) => updateStageMock(...a),
@@ -130,13 +138,31 @@ const {
// tests can feed enqueueVisualImage a canon (pickCanon reads universe.characters).
const { getUniverse } = await import('../universeBuilder.js');
+// Point BOTH the outer `getIssue` read and the serialized write tail at the
+// same storyboards scenes, so a mutator computed inside the write region sees
+// the array the caller validated against.
+const useStoryboardScenes = (scenes) => {
+ persistedStages.storyboards = { scenes: structuredClone(scenes) };
+ getIssueMock.mockResolvedValueOnce({
+ ...structuredClone(mockIssue),
+ stages: { ...structuredClone(mockIssue.stages), storyboards: { scenes: structuredClone(scenes) } },
+ });
+};
+
beforeEach(() => {
- getIssueMock.mockClear();
+ persistedStages = structuredClone(mockIssue.stages);
+ // Restore implementations, not just call logs — tests that install a
+ // stateful write tail (#3400) or a describe-level getIssue would otherwise
+ // leak into every later test in this 1500-line file.
+ getIssueMock.mockReset();
+ getIssueMock.mockImplementation(DEFAULT_GET_ISSUE);
updateStageMock.mockClear();
- updateStageWithLatestMock.mockClear();
+ updateStageWithLatestMock.mockReset();
+ updateStageWithLatestMock.mockImplementation(DEFAULT_UPDATE_STAGE_WITH_LATEST);
+ enqueueJobMock.mockReset();
+ enqueueJobMock.mockImplementation(() => ({ jobId: 'job-fake-1234' }));
updateSeasonOnSeriesMock.mockClear();
assertStageUnlockedMock.mockClear();
- enqueueJobMock.mockClear();
// Restore the default implementation — several #904 tests install a
// per-test mockImplementation/mockRejectedValue that would otherwise leak
// into the next test (mockClear resets calls, not the implementation).
@@ -568,12 +594,9 @@ describe('enqueueStoryboardSceneVideo', () => {
kind: 'video',
params: expect.objectContaining({ mode: 't2v', disableAudio: true, width: 432, height: 768 }),
}));
- expect(updateStageMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.objectContaining({
- status: 'edited',
- scenes: expect.arrayContaining([
- expect.objectContaining({ sceneVideoJobId: 'job-fake-1234' }),
- ]),
- }));
+ expect(updateStageWithLatestMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.any(Function));
+ expect(result.stage.scenes[0].sceneVideoJobId).toBe('job-fake-1234');
+ expect(result.stage.status).toBe('edited');
});
});
@@ -604,10 +627,7 @@ describe('enqueueStoryboardShotStartFrame', () => {
});
it('happy path: enqueues image job, stamps startFrameJobId on the shot', async () => {
- getIssueMock.mockResolvedValueOnce({
- ...structuredClone(mockIssue),
- stages: { ...mockIssue.stages, storyboards: { scenes: [{ description: 'wide', shots: [{ id: 's1', description: 'close on the lock' }] }] } },
- });
+ useStoryboardScenes([{ description: 'wide', shots: [{ id: 's1', description: 'close on the lock' }] }]);
const result = await enqueueStoryboardShotStartFrame('iss-test', 0, 0);
expect(result.jobId).toBe('job-fake-1234');
expect(result.sceneIndex).toBe(0);
@@ -616,25 +636,114 @@ describe('enqueueStoryboardShotStartFrame', () => {
kind: 'image',
owner: 'pipeline:iss-test:storyboards:scene0:shot0',
}));
- expect(updateStageMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.objectContaining({
- status: 'edited',
- scenes: expect.arrayContaining([
- expect.objectContaining({
- shots: expect.arrayContaining([
- expect.objectContaining({ startFrameJobId: 'job-fake-1234' }),
- ]),
- }),
- ]),
- }));
+ expect(updateStageWithLatestMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.any(Function));
+ expect(result.stage.scenes[0].shots[0].startFrameJobId).toBe('job-fake-1234');
+ expect(result.stage.status).toBe('edited');
});
it('falls back to the parent scene description when the shot description is empty', async () => {
+ useStoryboardScenes([{ description: 'wide shot of the bridge at dawn', shots: [{ id: 's1', description: '' }] }]);
+ const result = await enqueueStoryboardShotStartFrame('iss-test', 0, 0);
+ expect(result.prompt).toMatch(/bridge at dawn/i);
+ });
+});
+
+// #3400 — two enqueues for DIFFERENT scenes on the same issue used to clobber
+// each other: both read `scenes` up front, then each wrote the whole pre-read
+// array back through `updateStage`, so the second write reverted the first
+// scene's freshly-stamped job id and left that job running untracked.
+// `updateStage` serializing the writes never helped — the array being written
+// was computed outside the lock. These tests drive both enqueues concurrently
+// against a genuinely stateful store and assert BOTH job ids survive.
+describe('concurrent storyboard scene enqueues (#3400)', () => {
+ // A real serialized write tail: one shared persisted stage, one mutex, and
+ // the caller's computeFn evaluated INSIDE the lock against fresh state.
+ const installSerializedWriteTail = (initialScenes) => {
+ const persisted = { storyboards: { scenes: structuredClone(initialScenes) } };
+ let tail = Promise.resolve();
+ getIssueMock.mockImplementation(async () => ({
+ ...structuredClone(mockIssue),
+ stages: { ...structuredClone(mockIssue.stages), storyboards: structuredClone(persisted.storyboards) },
+ }));
+ updateStageWithLatestMock.mockImplementation((issueId, stageId, computeFn) => {
+ tail = tail.then(async () => {
+ // yield once inside the lock so an unserialized implementation would
+ // definitely interleave here
+ await Promise.resolve();
+ const current = structuredClone(persisted[stageId] || {});
+ const patch = computeFn(current);
+ persisted[stageId] = { ...current, ...patch };
+ return { issue: { ...mockIssue, stages: structuredClone(persisted) }, stage: structuredClone(persisted[stageId]) };
+ });
+ return tail;
+ });
+ return persisted;
+ };
+
+ it('keeps both sceneVideoJobIds when two scene-video enqueues interleave', async () => {
+ const persisted = installSerializedWriteTail([
+ { slugline: 'A', description: 'Scene 1.' },
+ { slugline: 'B', description: 'Scene 2.' },
+ ]);
+ enqueueJobMock
+ .mockReturnValueOnce({ jobId: 'job-scene-0' })
+ .mockReturnValueOnce({ jobId: 'job-scene-1' });
+
+ await Promise.all([
+ enqueueStoryboardSceneVideo('iss-test', 0, {}),
+ enqueueStoryboardSceneVideo('iss-test', 1, {}),
+ ]);
+
+ expect(persisted.storyboards.scenes[0].sceneVideoJobId).toBe('job-scene-0');
+ expect(persisted.storyboards.scenes[1].sceneVideoJobId).toBe('job-scene-1');
+ });
+
+ it('keeps both startFrameJobIds when two shot enqueues on different scenes interleave', async () => {
+ const persisted = installSerializedWriteTail([
+ { description: 'Scene 1.', shots: [{ id: 's1', description: 'shot one' }] },
+ { description: 'Scene 2.', shots: [{ id: 's2', description: 'shot two' }] },
+ ]);
+ enqueueJobMock
+ .mockReturnValueOnce({ jobId: 'job-shot-0' })
+ .mockReturnValueOnce({ jobId: 'job-shot-1' });
+
+ await Promise.all([
+ enqueueStoryboardShotStartFrame('iss-test', 0, 0),
+ enqueueStoryboardShotStartFrame('iss-test', 1, 0),
+ ]);
+
+ expect(persisted.storyboards.scenes[0].shots[0].startFrameJobId).toBe('job-shot-0');
+ expect(persisted.storyboards.scenes[1].shots[0].startFrameJobId).toBe('job-shot-1');
+ });
+
+ it('a scene-video enqueue does not revert a concurrent sibling-scene prompt refine', async () => {
+ const persisted = installSerializedWriteTail([
+ { description: 'Scene 1.' },
+ { description: 'Scene 2.' },
+ ]);
+ enqueueJobMock.mockReturnValueOnce({ jobId: 'job-scene-0' });
+
+ await Promise.all([
+ enqueueStoryboardSceneVideo('iss-test', 0, {}),
+ refineStoryboardScenePrompt('iss-test', 1),
+ ]);
+
+ expect(persisted.storyboards.scenes[0].sceneVideoJobId).toBe('job-scene-0');
+ expect(persisted.storyboards.scenes[1].description).toBe('refined prompt body');
+ });
+
+ it('404s when the target scene disappeared before the write landed', async () => {
+ installSerializedWriteTail([{ description: 'Scene 1.' }, { description: 'Scene 2.' }]);
getIssueMock.mockResolvedValueOnce({
...structuredClone(mockIssue),
- stages: { ...mockIssue.stages, storyboards: { scenes: [{ description: 'wide shot of the bridge at dawn', shots: [{ id: 's1', description: '' }] }] } },
+ stages: {
+ ...structuredClone(mockIssue.stages),
+ // the caller reads 3 scenes, but only 2 are persisted by write time
+ storyboards: { scenes: [{ description: 'a' }, { description: 'b' }, { description: 'c' }] },
+ },
});
- const result = await enqueueStoryboardShotStartFrame('iss-test', 0, 0);
- expect(result.prompt).toMatch(/bridge at dawn/i);
+ await expect(enqueueStoryboardSceneVideo('iss-test', 2, {}))
+ .rejects.toThrow(/out of range/);
});
});
@@ -1314,12 +1423,11 @@ describe('refineStoryboardScenePrompt', () => {
}),
expect.objectContaining({ returnsJson: true }),
);
- expect(updateStageMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.objectContaining({
- status: 'edited',
- scenes: expect.arrayContaining([
- expect.objectContaining({ description: 'refined prompt body' }),
- ]),
- }));
+ expect(updateStageWithLatestMock).toHaveBeenCalledWith('iss-test', 'storyboards', expect.any(Function));
+ expect(result.stage.scenes[1].description).toBe('refined prompt body');
+ // the sibling scene this call never touched is preserved verbatim
+ expect(result.stage.scenes[0].description).toBe('Scene 1 baseline.');
+ expect(result.scene.description).toBe('refined prompt body');
});
});