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): addProjectScenes returns the freshly-persisted project

[._.]/ Adam Eivyfa30cb439453
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
index b79ce3811b..eb536e0408 100644
--- a/server/services/musicVideo/planner.js
+++ b/server/services/musicVideo/planner.js
@@ -39,15 +39,25 @@ const SCENE_TEXT_MAX = 2000;
// cap, just without the optional first-pass prompt text.
const MAX_SECTIONS_FOR_PROMPTS = 80;
+// Mirrors musicVideoSceneCreateSchema's startSec/endSec bounds (musicVideoValidation.js)
+// so a section just outside the downstream scene schema's range is dropped
+// here rather than failing addScenes' atomic batch validation and aborting
+// the whole plan request over one bad section.
+const MAX_SECTION_SEC = 36000;
+
/**
- * Keep only sections with a valid forward-time span. Defensive against a
- * malformed/legacy cached analysis — `musicVideoAudioAnalysisSchema` doesn't
- * enforce `endSec > startSec` per section. Shared by the scene-input builder
- * and the LLM prompt builder so their array indices always agree.
+ * Keep only sections with a valid forward-time span within the bounds the
+ * downstream scene schema accepts. Defensive against a malformed/legacy
+ * cached analysis — `musicVideoAudioAnalysisSchema` doesn't enforce these
+ * per-section invariants the way `musicVideoSceneCreateSchema` does. Shared
+ * by the scene-input builder and the LLM prompt builder so their array
+ * indices always agree.
*/
export function validSections(sections) {
return (Array.isArray(sections) ? sections : [])
- .filter((s) => s && typeof s.startSec === 'number' && typeof s.endSec === 'number' && s.endSec > s.startSec);
+ .filter((s) => s
+ && typeof s.startSec === 'number' && s.startSec >= 0
+ && typeof s.endSec === 'number' && s.endSec > s.startSec && s.endSec <= MAX_SECTION_SEC);
}
/**
@@ -192,14 +202,14 @@ export async function planProject(id, { seedPrompts = true, providerId, model }
}
}
- const scenes = await addProjectScenes(id, sceneInputs);
- // Assemble the response in-memory from the pre-mutation `project` + the
- // scenes `addProjectScenes` just returned, rather than a second
- // getProject round trip — addScenes' `touch()` only changes `scenes` +
- // `updatedAt`, so this mirrors exactly what a re-fetch would return
- // without a second DB transaction / whole-file re-read (the client's
- // single-scene `addMusicVideoScene` path already composes state this way).
- const updated = { ...project, scenes: [...(project.scenes || []), ...scenes], updatedAt: new Date().toISOString() };
+ // `addProjectScenes` returns the project it just persisted (read fresh
+ // under the same lock/transaction that wrote it, not a re-derived
+ // snapshot) — using it directly avoids both a stale-snapshot response
+ // (a concurrent edit made while the prompt-seeding LLM call was in
+ // flight would otherwise be silently dropped from this response and
+ // visually reverted by the client's replaceProject) and a redundant
+ // second getProject round trip.
+ const { project: updated, scenes } = await addProjectScenes(id, sceneInputs);
console.log(`🪄 Music Video plan: seeded ${scenes.length} scene${scenes.length === 1 ? '' : 's'} for ${id} (prompts ${promptsSeeded ? 'seeded' : `skipped: ${promptsSkippedReason || 'n/a'}`})`);
return { project: updated, scenesAdded: scenes.length, promptsSeeded, promptsSkippedReason };
}
diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.js
index 165200bbaf..d859e647f3 100644
--- a/server/services/musicVideo/planner.test.js
+++ b/server/services/musicVideo/planner.test.js
@@ -41,12 +41,14 @@ beforeEach(() => {
});
describe('validSections', () => {
- it('keeps only sections with a positive forward span', () => {
+ it('keeps only sections with a positive forward span within the scene-schema bounds', () => {
const result = validSections([
{ label: 'A', startSec: 0, endSec: 5 },
{ label: 'bad-order', startSec: 5, endSec: 5 },
{ label: 'bad-reverse', startSec: 8, endSec: 3 },
{ label: 'missing-times' },
+ { label: 'negative-start', startSec: -1, endSec: 5 },
+ { label: 'over-max', startSec: 0, endSec: 36001 },
null,
]);
expect(result).toEqual([{ label: 'A', startSec: 0, endSec: 5 }]);
@@ -113,28 +115,40 @@ describe('planProject', () => {
await expect(planProject('mv-1')).rejects.toMatchObject({ status: 422, code: 'NOT_ANALYZED' });
});
- it('seeds one scene per section and skips prompts gracefully when no provider is configured', async () => {
+ // addProjectScenes returns the project it just persisted (read fresh under
+ // its own lock/transaction), NOT a value the caller derives from the
+ // pre-mutation `getProject` snapshot — so the mock's returned project here
+ // deliberately differs from `makeProject()` (an extra `renderHistoryId`) to
+ // prove `planProject` uses what addProjectScenes hands back, not a stale
+ // composition of its own.
+ const FRESH_SCENES = [{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }];
+ function freshProjectResult(overrides = {}) {
+ return { project: { ...makeProject(), renderHistoryId: 'rh-fresh', scenes: FRESH_SCENES, ...overrides }, scenes: FRESH_SCENES };
+ }
+
+ it('seeds one scene per section, calls getProject exactly once, and returns the freshly-persisted project from addProjectScenes', async () => {
const project = makeProject();
- getProject.mockResolvedValueOnce(project).mockResolvedValueOnce({ ...project, scenes: [{ sceneId: 's1' }] });
- addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ getProject.mockResolvedValue(project);
+ addProjectScenes.mockResolvedValue(freshProjectResult());
resolveProviderAndModel.mockResolvedValue({ provider: null, selectedModel: null });
const result = await planProject('mv-1');
+ expect(getProject).toHaveBeenCalledTimes(1);
expect(addProjectScenes).toHaveBeenCalledWith('mv-1', expect.arrayContaining([
expect.objectContaining({ label: 'Intro', startSec: 0, endSec: 10 }),
]));
expect(addProjectScenes.mock.calls[0][1]).toHaveLength(3);
expect(runPromptThroughProvider).not.toHaveBeenCalled();
+ expect(result.project.renderHistoryId).toBe('rh-fresh');
expect(result.scenesAdded).toBe(3);
expect(result.promptsSeeded).toBe(false);
expect(result.promptsSkippedReason).toBe('no-provider');
});
it('skips the LLM call entirely when seedPrompts is false', async () => {
- const project = makeProject();
- getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
- addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ getProject.mockResolvedValue(makeProject());
+ addProjectScenes.mockResolvedValue(freshProjectResult());
const result = await planProject('mv-1', { seedPrompts: false });
@@ -144,9 +158,8 @@ describe('planProject', () => {
});
it('merges first-pass framePrompt/prompt into the matching scenes when the LLM call succeeds', async () => {
- const project = makeProject();
- getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
- addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ getProject.mockResolvedValue(makeProject());
+ addProjectScenes.mockResolvedValue(freshProjectResult());
resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });
runPromptThroughProvider.mockResolvedValue({
text: JSON.stringify([
@@ -167,9 +180,8 @@ describe('planProject', () => {
});
it('degrades to plain scenes when the LLM call throws', async () => {
- const project = makeProject();
- getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
- addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ getProject.mockResolvedValue(makeProject());
+ addProjectScenes.mockResolvedValue(freshProjectResult());
resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });
runPromptThroughProvider.mockRejectedValue(new Error('boom'));
@@ -182,9 +194,8 @@ describe('planProject', () => {
});
it('degrades to plain scenes when the LLM response is unparsable', async () => {
- const project = makeProject();
- getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
- addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ getProject.mockResolvedValue(makeProject());
+ addProjectScenes.mockResolvedValue(freshProjectResult());
resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', type: 'api' }, selectedModel: 'gpt' });
runPromptThroughProvider.mockResolvedValue({ text: 'not json at all' });
@@ -195,9 +206,8 @@ describe('planProject', () => {
});
it('skips prompt-seeding when the resolved provider is disabled', async () => {
- const project = makeProject();
- getProject.mockResolvedValueOnce(project).mockResolvedValueOnce(project);
- addProjectScenes.mockResolvedValue([{ sceneId: 's1' }, { sceneId: 's2' }, { sceneId: 's3' }]);
+ getProject.mockResolvedValue(makeProject());
+ addProjectScenes.mockResolvedValue(freshProjectResult());
resolveProviderAndModel.mockResolvedValue({ provider: { id: 'p1', enabled: false }, selectedModel: 'gpt' });
const result = await planProject('mv-1');
@@ -205,4 +215,17 @@ describe('planProject', () => {
expect(runPromptThroughProvider).not.toHaveBeenCalled();
expect(result.promptsSkippedReason).toBe('provider-disabled');
});
+
+ it('logs and falls through to no-provider when resolveProviderAndModel itself throws', async () => {
+ getProject.mockResolvedValue(makeProject());
+ addProjectScenes.mockResolvedValue(freshProjectResult());
+ resolveProviderAndModel.mockRejectedValue(new Error('toolkit not initialized'));
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const result = await planProject('mv-1');
+
+ expect(result.promptsSkippedReason).toBe('no-provider');
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('toolkit not initialized'));
+ warnSpy.mockRestore();
+ });
});
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
index dee78b1763..d9a0682996 100644
--- a/server/services/musicVideo/projects.js
+++ b/server/services/musicVideo/projects.js
@@ -111,11 +111,16 @@ export async function addProjectScene(id, sceneInput) {
return scene;
}
-/** Bulk-append scenes (the autonomous planner, #1855) — emits one update, not N. */
+/**
+ * Bulk-append scenes (the autonomous planner, #1855) — emits one update, not
+ * N. Returns `{ project, scenes }` — the freshly-persisted project, so a
+ * caller composing a response never has to re-fetch or risk overwriting a
+ * concurrent edit with stale state.
+ */
export async function addProjectScenes(id, sceneInputs) {
- const scenes = await (await selectBackend()).addProjectScenes(id, sceneInputs);
+ const { project, scenes } = await (await selectBackend()).addProjectScenes(id, sceneInputs);
emitRecordUpdated('musicVideoProject', id);
- return scenes;
+ return { project, scenes };
}
export async function updateScene(id, sceneId, patch) {
diff --git a/server/services/musicVideo/projects.test.js b/server/services/musicVideo/projects.test.js
index b6122afefc..86ec488fb6 100644
--- a/server/services/musicVideo/projects.test.js
+++ b/server/services/musicVideo/projects.test.js
@@ -63,14 +63,15 @@ describe('musicVideo dispatcher — record-event emit (#1770)', () => {
expect(emitRecordDeleted).not.toHaveBeenCalled();
});
- it('addProjectScenes bulk-appends and emits exactly one updated (not one per scene)', async () => {
+ it('addProjectScenes bulk-appends, emits exactly one updated (not one per scene), and returns the freshly-persisted project', async () => {
const p = await projects.createProject({ name: 'A' });
emitRecordUpdated.mockClear();
- const scenes = await projects.addProjectScenes(p.id, [{ prompt: 'one' }, { prompt: 'two' }, { prompt: 'three' }]);
+ const { project, scenes } = await projects.addProjectScenes(p.id, [{ prompt: 'one' }, { prompt: 'two' }, { prompt: 'three' }]);
expect(scenes).toHaveLength(3);
expect(scenes.map((s) => s.order)).toEqual([0, 1, 2]);
+ expect(project.scenes).toHaveLength(3);
expect(emitRecordUpdated).toHaveBeenCalledTimes(1);
expect(emitRecordUpdated).toHaveBeenCalledWith('musicVideoProject', p.id);
diff --git a/server/services/musicVideo/projectsDB.js b/server/services/musicVideo/projectsDB.js
index 6bc8876d4c..fc3e488710 100644
--- a/server/services/musicVideo/projectsDB.js
+++ b/server/services/musicVideo/projectsDB.js
@@ -195,13 +195,19 @@ export async function addProjectScene(id, sceneInput) {
return result;
}
-/** Bulk-append scenes (the autonomous planner, #1855) — one locked read/write. */
+/**
+ * Bulk-append scenes (the autonomous planner, #1855) — one locked read/write.
+ * Returns `{ project, scenes }` (the freshly-persisted project, read under
+ * the same `SELECT ... FOR UPDATE` that wrote it — not a pre-mutation
+ * snapshot) so a caller composing a response never has to re-fetch or risk
+ * overwriting a concurrent edit with stale state.
+ */
export async function addProjectScenes(id, sceneInputs) {
- const { result } = await withLockedProject(id, (p) => {
+ const { project, result: scenes } = await withLockedProject(id, (p) => {
const { project, scenes } = addScenes(p, sceneInputs);
return { project, result: scenes };
});
- return result;
+ return { project, scenes };
}
export async function updateScene(id, sceneId, patch) {
diff --git a/server/services/musicVideo/projectsFile.js b/server/services/musicVideo/projectsFile.js
index b08b38446a..8d9b8c5297 100644
--- a/server/services/musicVideo/projectsFile.js
+++ b/server/services/musicVideo/projectsFile.js
@@ -158,13 +158,18 @@ export async function addProjectScene(id, sceneInput) {
return scene;
}
-/** Bulk-append scenes (the autonomous planner, #1855) — one load/save round trip. */
+/**
+ * Bulk-append scenes (the autonomous planner, #1855) — one load/save round
+ * trip. Returns `{ project, scenes }` (the freshly-persisted project, not a
+ * pre-mutation snapshot) so a caller composing a response never has to
+ * re-fetch or risk overwriting a concurrent edit with stale state.
+ */
export async function addProjectScenes(id, sceneInputs) {
const { all, idx } = await loadAllAndIndex(id);
const { project, scenes } = addScenes(all[idx], sceneInputs);
all[idx] = project;
await saveAll(all);
- return scenes;
+ return { project, scenes };
}
export async function updateScene(id, sceneId, patch) {