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 (codex): clear stale beat analysis on track relink, close pending-kickoff race

[._.]/ Adam Eivyb1c82c426ee9
diff --git a/client/src/hooks/useYoutubeTrackImport.js b/client/src/hooks/useYoutubeTrackImport.js
index 008dd26aca..5498dbd3af 100644
--- a/client/src/hooks/useYoutubeTrackImport.js
+++ b/client/src/hooks/useYoutubeTrackImport.js
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
import toast from '../components/ui/Toast';
import { importTrackFromYoutube, cancelTrackImport, trackImportEventsUrl } from '../services/apiTracks.js';
import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
@@ -18,13 +18,16 @@ import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
*/
export default function useYoutubeTrackImport({ onComplete } = {}) {
const [job, setJob] = useState(null); // { jobId, context }
+ // `pending` covers the gap between clicking Import and the kickoff request
+ // resolving, when `job` is still null. Without it, `active` (below) would
+ // read false during that window, so a fast double-click could fire a
+ // second request (the second response's setJob would silently orphan the
+ // first job), AND a caller's "block navigation while active" guard
+ // (MusicVideo.jsx's selectProject/handleDelete) would let the user switch
+ // away/delete before the job even exists to be guarded against.
+ const [pending, setPending] = useState(false);
const sse = useSseProgress(job ? trackImportEventsUrl(job.jobId) : null);
const percent = Math.round(sse.latest?.percent ?? 0);
- // Synchronous re-entrancy guard for the gap between clicking Import and the
- // kickoff request resolving — `job` (state) doesn't flip true until then,
- // so a fast double-click would otherwise fire two requests and the second
- // response's setJob would silently orphan the first job.
- const startingRef = useRef(false);
useEffect(() => {
const frame = sse.latest;
@@ -53,12 +56,12 @@ export default function useYoutubeTrackImport({ onComplete } = {}) {
const start = (url, context) => {
const trimmed = url.trim();
- if (!trimmed || job || startingRef.current) return;
- startingRef.current = true;
+ if (!trimmed || job || pending) return;
+ setPending(true);
importTrackFromYoutube(trimmed, { silent: true })
.then(({ jobId }) => setJob({ jobId, context }))
.catch((err) => toast.error(err?.message || 'Failed to start YouTube import'))
- .finally(() => { startingRef.current = false; });
+ .finally(() => setPending(false));
};
const cancel = () => {
@@ -66,5 +69,5 @@ export default function useYoutubeTrackImport({ onComplete } = {}) {
cancelTrackImport(job.jobId, { silent: true }).catch(() => {});
};
- return { active: !!job, percent, start, cancel };
+ return { active: pending || !!job, percent, start, cancel };
}
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 012f0f7055..7d99b5a998 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -271,4 +271,29 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
resolveKickoff({ jobId: 'yt-job-1' });
await waitFor(() => expect(importTrackFromYoutube).toHaveBeenCalledTimes(1));
});
+
+ it('blocks switching projects during the pending kickoff window, before the job even exists', async () => {
+ const projectB = { ...PROJECT_NO_CLIP, id: 'mv-3', name: 'Other Project' };
+ listMusicVideoProjects.mockResolvedValue([PROJECT_NO_CLIP, projectB]);
+ let resolveKickoff;
+ importTrackFromYoutube.mockImplementation(() => new Promise((resolve) => { resolveKickoff = resolve; }));
+ render(<MusicVideo />);
+ const listBtnA = await screen.findByRole('button', { name: new RegExp(PROJECT_NO_CLIP.name) });
+ fireEvent.click(listBtnA);
+
+ const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)
+ .find((el) => el.id !== 'mv-yt-create');
+ fireEvent.change(editInput, { target: { value: 'https://youtu.be/pending' } });
+ fireEvent.click(within(editInput.closest('div')).getByRole('button', { name: /Import/i }));
+ // The kickoff POST has NOT resolved yet — no jobId, no SSE subscription —
+ // but switching away must already be blocked, or this project's import
+ // would attach with nobody listening once it lands.
+ expect(importTrackFromYoutube).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(screen.getByRole('button', { name: new RegExp(projectB.name) }));
+ expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/before switching projects/i));
+ expect(listBtnA).toHaveClass('border-port-accent');
+
+ resolveKickoff({ jobId: 'yt-job-pending' });
+ });
});
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index ecb1e80cc1..9530fcf642 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -85,7 +85,15 @@ export function applyProjectPatch(project, patch) {
if (patch.status && !MUSIC_VIDEO_STATUSES.includes(patch.status)) {
throw new ServerError(`Invalid status: ${patch.status}`, { status: 400, code: 'VALIDATION_ERROR' });
}
- return touch(project, patch);
+ // Changing the audio source invalidates the cached beat/tempo analysis —
+ // it was computed from the OLD track. AI Plan / Auto-arrange / BeatTimeline
+ // gate on `audioAnalysis` truthiness, and the render's beat-snap step reads
+ // its `beats` array; a stale analysis would silently apply the previous
+ // song's beat grid to the new audio (#1945 — both the manual "Change
+ // track" picker and the YouTube-import attach PATCH through here).
+ const trackChanged = ('trackId' in patch && patch.trackId !== project.trackId)
+ || ('uploadedAudioFilename' in patch && patch.uploadedAudioFilename !== project.uploadedAudioFilename);
+ return touch(project, trackChanged ? { ...patch, audioAnalysis: null } : patch);
}
/**
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index aa9c03b6f2..6459c156f2 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -49,6 +49,40 @@ describe('applyProjectPatch', () => {
it('accepts a valid status', () => {
expect(applyProjectPatch(baseProject(), { status: 'ready' }).status).toBe('ready');
});
+
+ it('clears cached audioAnalysis when trackId changes to a different track (#1945)', () => {
+ const analyzed = setAudioAnalysis({ ...baseProject(), trackId: 't1' }, {
+ bpm: 120, beats: [0, 0.5], downbeats: [0], sections: [{ label: 'Section 1', startSec: 0, endSec: 1 }], durationSec: 1,
+ });
+ expect(analyzed.audioAnalysis).not.toBeNull();
+ const next = applyProjectPatch(analyzed, { trackId: 't2' });
+ expect(next.trackId).toBe('t2');
+ expect(next.audioAnalysis).toBeNull();
+ });
+
+ it('leaves audioAnalysis intact when trackId is patched to the SAME value', () => {
+ const analyzed = setAudioAnalysis({ ...baseProject(), trackId: 't1' }, {
+ bpm: 120, beats: [0], downbeats: [0], sections: [{ label: 'S', startSec: 0, endSec: 1 }], durationSec: 1,
+ });
+ const next = applyProjectPatch(analyzed, { trackId: 't1', name: 'Renamed' });
+ expect(next.audioAnalysis).not.toBeNull();
+ });
+
+ it('leaves audioAnalysis intact for a patch that does not touch the track', () => {
+ const analyzed = setAudioAnalysis({ ...baseProject(), trackId: 't1' }, {
+ bpm: 120, beats: [0], downbeats: [0], sections: [{ label: 'S', startSec: 0, endSec: 1 }], durationSec: 1,
+ });
+ const next = applyProjectPatch(analyzed, { name: 'Renamed' });
+ expect(next.audioAnalysis).not.toBeNull();
+ });
+
+ it('clears audioAnalysis when uploadedAudioFilename changes to a different file', () => {
+ const analyzed = setAudioAnalysis({ ...baseProject(), uploadedAudioFilename: 'a.mp3' }, {
+ bpm: 100, beats: [0], downbeats: [0], sections: [{ label: 'S', startSec: 0, endSec: 1 }], durationSec: 1,
+ });
+ const next = applyProjectPatch(analyzed, { uploadedAudioFilename: 'b.mp3' });
+ expect(next.audioAnalysis).toBeNull();
+ });
});
describe('setAudioAnalysis', () => {