Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: plan treatment prompts per field and keep revisions per project (#8980)
[._.]/ Adam Eivyb03242484d4c
diff --git a/client/src/components/musicVideo/TreatmentPanel.test.jsx b/client/src/components/musicVideo/TreatmentPanel.test.jsxindex d55ba9d760..75c95121e2 100644--- a/client/src/components/musicVideo/TreatmentPanel.test.jsx+++ b/client/src/components/musicVideo/TreatmentPanel.test.jsx@@ -7,7 +7,7 @@*/import { describe, it, expect, vi, beforeEach } from 'vitest';import { useState } from 'react';-import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';+import { render, renderHook, screen, fireEvent, waitFor, act } from '@testing-library/react';vi.mock('../../services/apiMusicVideo.js', () => ({getMusicVideoProject: vi.fn(),@@ -126,6 +126,30 @@ describe('TreatmentPanel apply review', () => {});});+describe('useMusicVideoTreatment across a project switch', () => {+ it('never hands a write still in flight for one project its revision to the next project', async () => {+ let resolveA;+ api.updateMusicVideoTreatment+ .mockImplementationOnce(() => new Promise((resolve) => { resolveA = resolve; }))+ .mockResolvedValueOnce({ treatment: { ...TREATMENT, revision: 8 } });+ const projectA = { ...PROJECT, id: 'mv-a', treatment: { ...TREATMENT, revision: 3 } };+ const projectB = { ...PROJECT, id: 'mv-b', treatment: { ...TREATMENT, revision: 7 } };+ const { result, rerender } = renderHook(({ project }) => useMusicVideoTreatment({ project, onProjectPatch: vi.fn(), replaceProject: vi.fn() }), {+ initialProps: { project: projectA },+ });+ let pendingA;+ act(() => { pendingA = result.current.save({ brief: { audience: 'a' } }); });+ await waitFor(() => expect(api.updateMusicVideoTreatment).toHaveBeenCalledTimes(1));+ rerender({ project: projectB });+ await act(async () => { resolveA({ treatment: { ...TREATMENT, revision: 9 } }); await pendingA; });+ await act(async () => { await result.current.save({ brief: { audience: 'b' } }); });+ expect(api.updateMusicVideoTreatment.mock.calls.map(([id, body]) => [id, body.baseRevision])).toEqual([+ ['mv-a', 3],+ ['mv-b', 7],+ ]);+ });+});+describe('TreatmentPanel edits and compile', () => {it('compiles only on an explicit click, and not before the song is analyzed', async () => {api.compileMusicVideoTreatment.mockResolvedValue({ treatment: { ...TREATMENT, revision: 4 }, aiUsed: false, aiSkippedReason: 'not-requested' });diff --git a/client/src/hooks/useMusicVideoTreatment.js b/client/src/hooks/useMusicVideoTreatment.jsindex 89ad4fb825..33dad4fa04 100644--- a/client/src/hooks/useMusicVideoTreatment.js+++ b/client/src/hooks/useMusicVideoTreatment.js@@ -33,7 +33,9 @@ const AI_SKIP_LABELS = {export default function useMusicVideoTreatment({ project, onProjectPatch, replaceProject } = {}) {const projectId = project?.id || null;const storedRevision = project?.treatment?.revision ?? 0;- const revisionRef = useRef(storedRevision);+ // Known treatment revision PER PROJECT, so a write still in flight for one+ // project can never hand its revision to the next project's writes.+ const revisionsRef = useRef(new Map());const chainRef = useRef(Promise.resolve());const [compiling, setCompiling] = useState(false);const [preview, setPreview] = useState(null);@@ -41,21 +43,19 @@ export default function useMusicVideoTreatment({ project, onProjectPatch, replacconst [applying, setApplying] = useState(false);const projectRef = useRef(projectId);+ projectRef.current = projectId;// A newer revision can arrive from outside this hook (a peer update, a- // reload); within one project never move the ref backwards past a write this- // hook already made. A project switch adopts that project's revision.+ // reload); never move a project's known revision backwards past a write this+ // hook already made.useEffect(() => {- if (projectRef.current !== projectId) {- projectRef.current = projectId;- revisionRef.current = storedRevision;- } else {- revisionRef.current = Math.max(revisionRef.current, storedRevision);- }+ if (!projectId) return;+ const known = revisionsRef.current.get(projectId) ?? 0;+ revisionsRef.current.set(projectId, Math.max(known, storedRevision));}, [projectId, storedRevision]);useEffect(() => { setPreview(null); }, [projectId]);const adopt = (id, treatment) => {- revisionRef.current = treatment?.revision ?? revisionRef.current;+ if (typeof treatment?.revision === 'number') revisionsRef.current.set(id, treatment.revision);onProjectPatch?.(id, { treatment });};@@ -63,7 +63,7 @@ export default function useMusicVideoTreatment({ project, onProjectPatch, replacif (err?.status === 409 && err?.code === 'TREATMENT_REVISION_CONFLICT') {toast.error('The treatment changed elsewhere — reloaded the latest version');return getMusicVideoProject(id, { silent: true }).then((fresh) => {- revisionRef.current = fresh?.treatment?.revision ?? 0;+ revisionsRef.current.set(id, fresh?.treatment?.revision ?? 0);replaceProject?.(fresh);}).catch(() => {});}@@ -74,14 +74,14 @@ export default function useMusicVideoTreatment({ project, onProjectPatch, replac// Serialize treatment writes; each reads the latest known revision when it runs.const enqueue = (work, fallback) => {const id = projectId;- const run = chainRef.current.then(() => work(id, revisionRef.current));+ const run = chainRef.current.then(() => work(id, revisionsRef.current.get(id) ?? 0));chainRef.current = run.catch((err) => handleConflict(id, err, fallback));return run.catch(() => null);};const save = (patch) => enqueue((id, baseRevision) => updateMusicVideoTreatment(id, { ...patch, baseRevision }, { silent: true })- .then(({ treatment }) => { adopt(id, treatment); setPreview(null); return treatment; }),+ .then(({ treatment }) => { adopt(id, treatment); if (id === projectRef.current) setPreview(null); return treatment; }),'Failed to save the treatment',);@@ -95,7 +95,7 @@ export default function useMusicVideoTreatment({ project, onProjectPatch, replac...(model ? { model } : {}),}, { silent: true }).then(({ treatment, aiUsed, aiSkippedReason }) => {adopt(id, treatment);- setPreview(null);+ if (id === projectRef.current) setPreview(null);const shots = treatment.shotDirections.length;if (useAi && !aiUsed) toast.error(`Drafted without AI — ${AI_SKIP_LABELS[aiSkippedReason] || aiSkippedReason}`);else toast.success(`Treatment compiled for ${shots} shot${shots === 1 ? '' : 's'}${aiUsed ? ' with AI' : ''}`);@@ -123,7 +123,7 @@ export default function useMusicVideoTreatment({ project, onProjectPatch, replac.then(() => applyMusicVideoTreatment(id, { revision, overwrite, addTextCues }, { silent: true })).then(({ project: next, result }) => {replaceProject?.(next);- setPreview(null);+ if (id === projectRef.current) setPreview(null);const kept = result.promptsKept.length + result.conflicted.length;toast.success(`Applied direction to ${result.directed} scene${result.directed === 1 ? '' : 's'}${kept ? ` — ${kept} hand-edited prompt${kept === 1 ? '' : 's'} kept` : ''}${result.textCuesAdded ? `, ${result.textCuesAdded} text cues added` : ''}`);return result;diff --git a/server/routes/musicVideoTreatment.test.js b/server/routes/musicVideoTreatment.test.jsindex 5e5ff6fa6d..2b4411b127 100644--- a/server/routes/musicVideoTreatment.test.js+++ b/server/routes/musicVideoTreatment.test.js@@ -51,7 +51,7 @@ const ANALYSIS = {const LYRICS = [{ text: 'Streetlights hum a borrowed tune', startSec: 8, endSec: 12 },{ text: 'We run until the morning', startSec: 12, endSec: 16 },- { text: 'Hold on, hold on to the light', startSec: 22, endSec: 26 },+ { text: 'Hold on, hold on to the light', startSec: 22, endSec: 27 }, // runs past its shot{ text: 'Never let the city sleep', startSec: 26, endSec: 30 },];@@ -230,6 +230,8 @@ describe('treatment apply', () => {seedImage('picked.png');await projects.updateScene(project.id, scenes[0].sceneId, { framePrompt: 'my own frame', prompt: 'my own motion' });await projects.appendSceneTakes(project.id, scenes[0].sceneId, [{ kind: 'image', assetId: 'picked.png', source: 'imported' }]);+ // Scene 2 has only its frame prompt written by hand; its motion prompt is empty.+ await projects.updateScene(project.id, scenes[2].sceneId, { framePrompt: 'hand frame' });runPromptThroughProvider.mockResolvedValueOnce({text: JSON.stringify({beats: [{ sectionIndex: 0, objective: 'Open on the train' }],@@ -249,10 +251,11 @@ describe('treatment apply', () => {const byScene = new Map(preview.body.scenes.map((s) => [s.sceneId, s]));expect(byScene.get(scenes[0].sceneId)).toMatchObject({ prompt: 'manual', keepsSelection: true, directionChanged: true });expect(byScene.get(scenes[1].sceneId).prompt).toBe('fill');+ expect(byScene.get(scenes[2].sceneId).fields).toEqual({ framePrompt: 'manual', prompt: 'fill' });const res = await request(app).post(`${base(project.id)}/treatment/apply`).send({ revision: preview.body.revision });expect(res.status).toBe(200);- expect(res.body.result.promptsKept).toEqual([scenes[0].sceneId]);+ expect(res.body.result.promptsKept).toEqual([scenes[0].sceneId, scenes[2].sceneId]);expect(res.body.result.directed).toBe(scenes.length);const after = await reload(project.id);@@ -260,6 +263,8 @@ describe('treatment apply', () => {expect(kept).toMatchObject({ framePrompt: 'my own frame', prompt: 'my own motion', referenceImageId: 'picked.png' });expect(kept.takes).toHaveLength(1);expect(filled).toMatchObject({ framePrompt: 'frame 1', prompt: 'motion 1' });+ // A hand edit to one prompt never blocks filling the other.+ expect(after.scenes[2]).toMatchObject({ framePrompt: 'hand frame', prompt: 'motion 2' });expect(filled.direction.frameClause).toContain('focal subject: subject 1');expect(filled.direction.frameClause).toContain('no text, letters, captions');const titled = after.scenes.find((s) => s.direction.typographyRole !== 'none');@@ -327,6 +332,12 @@ describe('treatment apply', () => {expect(composition.mode).toBe('concat');expect(composition.textCues.map((c) => c.text)).toEqual(LYRICS.map((c) => c.text));expect(composition.textCues.some((c) => c.emphasis === 'hero' && c.placement === 'upper')).toBe(true);+ // Each cue ends with the shot that directs it, never over the next shot.+ const { scenes } = await reload(project.id);+ for (const cue of composition.textCues) {+ const shot = scenes.find((sc) => cue.startSec >= sc.startSec && cue.startSec < sc.endSec);+ expect(cue.endSec).toBeLessThanOrEqual(shot.endSec);+ }});});diff --git a/server/services/musicVideo/treatment.js b/server/services/musicVideo/treatment.jsindex ec6c8973b5..50da531b40 100644--- a/server/services/musicVideo/treatment.js+++ b/server/services/musicVideo/treatment.js@@ -530,22 +530,28 @@ function sceneDirection(treatment, direction) {};}-// How Apply treats a scene's prompts: `fill` (empty), `replace` (still exactly-// what the treatment wrote last time), `unchanged` (already the suggestion),-// `manual` (edited by hand — kept unless explicitly overwritten), `none` (the-// direction carries no suggested prompts).-function promptPlan(scene, direction) {- const suggestion = { framePrompt: direction.suggestedFramePrompt, prompt: direction.suggestedPrompt };- if (!suggestion.framePrompt && !suggestion.prompt) return 'none';- const next = {- framePrompt: suggestion.framePrompt || scene.framePrompt || '',- prompt: suggestion.prompt || scene.prompt || '',- };- if (scenePromptFingerprint(next) === scenePromptFingerprint(scene)) return 'unchanged';- if (!isNonBlankStr(scene.framePrompt) && !isNonBlankStr(scene.prompt)) return 'fill';- if (scene.direction?.appliedPromptFingerprint === scenePromptFingerprint(scene)) return 'replace';- return 'manual';-}+const PROMPT_FIELDS = [['framePrompt', 'suggestedFramePrompt'], ['prompt', 'suggestedPrompt']];+const fieldFingerprint = (value) => fingerprint(value || '');++// How Apply treats each of a scene's two prompts, field by field (a hand edit+// to one never blocks filling the other): `fill` (empty), `replace` (still+// exactly what the treatment wrote there last time), `unchanged` (already the+// suggestion), `manual` (edited by hand — kept unless explicitly overwritten),+// `none` (no suggestion for that field).+function promptFieldPlans(scene, direction) {+ const owned = scene.direction?.appliedPrompts || {};+ return Object.fromEntries(PROMPT_FIELDS.map(([field, key]) => {+ const suggestion = direction[key];+ const current = scene[field] || '';+ if (!suggestion) return [field, 'none'];+ if (current === suggestion) return [field, 'unchanged'];+ if (!isNonBlankStr(current)) return [field, 'fill'];+ return [field, owned[field] === fieldFingerprint(current) ? 'replace' : 'manual'];+ }));+}+// The scene-level summary: the most consequential field plan.+const PLAN_PRIORITY = ['manual', 'fill', 'replace', 'unchanged', 'none'];+const summarizePlans = (plans) => PLAN_PRIORITY.find((p) => Object.values(plans).includes(p));function textCueCandidates(project, treatment) {const scenes = new Map((project.scenes || []).map((s) => [s.sceneId, s]));@@ -561,7 +567,9 @@ function textCueCandidates(project, treatment) {const cueText = cue.text.trim().slice(0, 500);if (existing.has(`${cueText}@${cue.startSec}`)) continue;existing.add(`${cueText}@${cue.startSec}`);- const endSec = isTime(cue.endSec) && cue.endSec > cue.startSec ? cue.endSec : scene.endSec;+ // Clamped to the directing shot: a line that runs on must not keep its+ // text over a later shot that reserved no (or another) region for it.+ const endSec = isTime(cue.endSec) && cue.endSec > cue.startSec ? Math.min(cue.endSec, scene.endSec) : scene.endSec;out.push({text: cueText,startSec: cue.startSec,@@ -596,12 +604,14 @@ export function buildApplyPreview(project) {if (!scene) { missingSceneIds.push(direction.sceneId); continue; }directed.add(scene.sceneId);const next = sceneDirection(treatment, direction);+ const fields = promptFieldPlans(scene, direction);scenes.push({sceneId: scene.sceneId,label: scene.label || scene.sectionLabel || '',directionChanged: directionKey(scene.direction) !== directionKey(next)|| scene.direction?.frameClause !== next.frameClause || scene.direction?.motionClause !== next.motionClause,- prompt: promptPlan(scene, direction),+ prompt: summarizePlans(fields),+ fields,promptFingerprint: scenePromptFingerprint(scene),current: { framePrompt: scene.framePrompt || '', prompt: scene.prompt || '' },suggested: { framePrompt: direction.suggestedFramePrompt, prompt: direction.suggestedPrompt },@@ -648,28 +658,30 @@ export function applyTreatmentToProject(project, { revision, overwrite = [], addif (!plan) return scene;const direction = directions.get(scene.sceneId);const next = { ...scene };- let write = plan.prompt === 'fill' || plan.prompt === 'replace';- if (plan.prompt === 'manual' && approved.has(scene.sceneId)) {- // The fingerprint pins the exact prompts the director reviewed: an edit- // made after that review is newer work and is kept.- if (approved.get(scene.sceneId) === plan.promptFingerprint) write = true;- else result.conflicted.push(scene.sceneId);- } else if (plan.prompt === 'manual') {- result.promptsKept.push(scene.sceneId);- }- if (write) {- if (direction.suggestedFramePrompt) next.framePrompt = direction.suggestedFramePrompt;- if (direction.suggestedPrompt) next.prompt = direction.suggestedPrompt;- result.promptsWritten.push(scene.sceneId);+ const hasManual = Object.values(plan.fields).includes('manual');+ // The fingerprint pins the exact prompts the director reviewed: an edit+ // made after that review is newer work and is kept.+ const approvedOverwrite = approved.has(scene.sceneId) && approved.get(scene.sceneId) === plan.promptFingerprint;+ if (hasManual && approved.has(scene.sceneId) && !approvedOverwrite) result.conflicted.push(scene.sceneId);+ else if (hasManual && !approvedOverwrite) result.promptsKept.push(scene.sceneId);+ // Only prompts the treatment wrote (or that already match it) are+ // treatment-owned; a kept hand edit keeps its previous ownership marker so+ // it still reads as manual next time.+ const appliedPrompts = { ...(scene.direction?.appliedPrompts || {}) };+ let wrote = false;+ for (const [field, key] of PROMPT_FIELDS) {+ const fieldPlan = plan.fields[field];+ if (fieldPlan === 'fill' || fieldPlan === 'replace' || (fieldPlan === 'manual' && approvedOverwrite)) {+ next[field] = direction[key];+ wrote = true;+ }+ if (fieldPlan !== 'none' && (fieldPlan !== 'manual' || approvedOverwrite)) appliedPrompts[field] = fieldFingerprint(next[field]);}- const owned = write || plan.prompt === 'unchanged';+ if (wrote) result.promptsWritten.push(scene.sceneId);next.direction = {...sceneDirection(treatment, direction),treatmentRevision: treatment.revision,- // Only prompts the treatment wrote (or that already match it) are- // treatment-owned; a kept hand edit keeps its previous ownership marker so- // it still reads as manual next time.- appliedPromptFingerprint: owned ? scenePromptFingerprint(next) : (scene.direction?.appliedPromptFingerprint ?? null),+ appliedPrompts,};result.directed += 1;return next;