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

refactor: consolidate SSE job-slot hooks onto useMidiTranscription shape (#2368)

Adam Eivy2d039b906a74
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c8ad75087d..f7a4136317 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Changes
+- **The four SSE job-slot hooks now share one implementation.** `useReferenceAudioImport`, `useYoutubeTrackImport`, `useVideoDownload`, and `useMidiTranscription` each hand-rolled the same "kick off a job → stream SSE progress → settle on the terminal frame, with double-click and lost-connection recovery" machinery. That logic now lives in exactly one place — a new generic `useSseJobSlot` hook — and the four feature hooks are thin wrappers that pass their own kickoff/SSE/cancel calls plus per-feature toast copy (and, for MuScriptor, its runtime-install and gated-repo modals). Behavior-preserving refactor deferred from the MuScriptor /simplify pass (#2368); ~150 fewer lines.
+
- **Shell page quick-command buttons trimmed to the interactive tools.** Dropped the four shell one-liner shortcuts (`git status`, `git pull`, `npm test`, `npm run dev`) that duplicated things you'd just type, renamed the `antigravity` button to its actual command `agy`, and added a `grok` button alongside the other coding-agent launchers.
## Fixes
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 387a004b00..56e25b56c4 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -37,6 +37,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
+| `useSseJobSlot` | Generic single-slot SSE job: `pending`/`job` state, terminal-frame handling (`complete`/`error`/`canceled`), and `sse.closed`-without-terminal-frame recovery in one place. Returns `{ active, percent, stage, context, start, cancel }`; pass `startRequest`/`eventsUrl`/`cancelRequest` + per-feature toast copy. | Any "kick off a job → stream SSE → settle on terminal frame" hook. The reference-audio/YouTube/video-download/MIDI hooks all wrap this — don't re-roll the terminal-frame + lost-connection dance. |
| `useInstallStream` | BYO-runtime install-log EventSource lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes). Don't re-roll the EventSource teardown/onComplete-ref dance. |
| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. | Surfacing "Available" vs "Download" badge inline in the gen form. |
| `useImageGenProgress` | Live diffusion progress for an image-gen call. | Showing per-call image-gen progress. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 1bfc3bcd1d..eac65745a9 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -24,6 +24,7 @@ export { default as useImageGenQueue } from './useImageGenQueue.js';
export { default as useImageRenderSettings } from './useImageRenderSettings.js';
export { default as useSingleImageRender } from './useSingleImageRender.js';
export { default as useSlotInFlight } from './useSlotInFlight.js';
+export { default as useSseJobSlot } from './useSseJobSlot.js';
export { default as useSingToScore } from './useSingToScore.js';
export * from './useSingToScore.js';
export { default as useSongTraining } from './useSongTraining.js';
diff --git a/client/src/hooks/useMidiTranscription.js b/client/src/hooks/useMidiTranscription.js
index 14f9e1b969..a9c51c7be7 100644
--- a/client/src/hooks/useMidiTranscription.js
+++ b/client/src/hooks/useMidiTranscription.js
@@ -1,13 +1,13 @@
-import { useEffect, useRef, useState } from 'react';
-import toast from '../components/ui/Toast';
-import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
+import { useRef, useState } from 'react';
+import useSseJobSlot from './useSseJobSlot.js';
/**
* One audio → MIDI transcription job slot (MuScriptor) — generic over the
* Rounds and Music Video API surfaces, which share the same kickoff/SSE/cancel
- * job shape (mirroring useReferenceAudioImport). Call it once per UI surface
- * that can independently kick off a transcription so each owns its own job +
- * SSE subscription.
+ * job shape. A thin wrapper over the generic `useSseJobSlot` (#2368) that adds
+ * MuScriptor's two first-use modals (runtime install + gated-repo token). Call
+ * it once per UI surface that can independently kick off a transcription so each
+ * owns its own job + SSE subscription.
*
* `startRequest(context)` performs the feature's kickoff API call and resolves
* `{ jobId }`; `eventsUrl(jobId)` / `cancelRequest(jobId)` are that feature's
@@ -19,11 +19,6 @@ import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
* target even if the caller's own state changed while it was in flight.
*/
export default function useMidiTranscription({ startRequest, eventsUrl, cancelRequest, onComplete } = {}) {
- const [job, setJob] = useState(null); // { jobId, context }
- // Covers the gap between clicking Transcribe and the kickoff request
- // resolving, when `job` is still null — without it a fast double-click could
- // fire a second request whose response silently orphans the first job.
- const [pending, setPending] = useState(false);
// First-use runtime install (MuScriptor). When the kickoff returns a 503
// MIDI_RUNTIME_MISSING, we open an in-app installer modal instead of dead-
// ending on a "run this shell command" toast (mirrors the image/video model
@@ -42,86 +37,57 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe
// the captured transcription once a token is saved. Non-null = open for that
// target; `{ context, repo }`.
const [gatedContext, setGatedContext] = useState(null);
- const sse = useSseProgress(job ? eventsUrl(job.jobId) : null);
- const latest = sse.latest;
- const stage = latest?.stage ?? null;
- useEffect(() => {
- if (!job || !latest) return;
- if (latest.type === 'complete') {
- onComplete?.(latest, job.context);
- setJob(null);
- } else if (latest.type === 'error') {
- // Gated-repo download failure — open the license + token prompt instead
- // of toasting a raw HuggingFace traceback the user can't act on.
- if (latest.code === 'gated_repo') {
- setGatedContext({ context: job.context, repo: latest.repo || null });
- } else {
- toast.error(latest.error || 'MIDI transcription failed');
+ const slot = useSseJobSlot({
+ startRequest,
+ eventsUrl,
+ cancelRequest,
+ onComplete,
+ errorFallback: 'MIDI transcription failed',
+ canceledMessage: 'MIDI transcription cancelled',
+ lostConnectionMessage: 'Lost connection to the MIDI transcription',
+ startErrorFallback: 'Failed to start MIDI transcription',
+ // Runtime is present — reset the loop guard on a successful kickoff.
+ onKickoffSuccess: () => { installAttemptedRef.current = false; },
+ // The runtime isn't provisioned yet: install it in-app on first use, then
+ // re-run the transcription for the same target. Only auto-open once — a
+ // second miss after a "successful" install is a real fault, so let the
+ // default toast surface it instead of relooping the installer.
+ onKickoffError: (err, context) => {
+ if (err?.code === 'MIDI_RUNTIME_MISSING' && !installAttemptedRef.current) {
+ installAttemptedRef.current = true;
+ setInstallContext(context);
+ return true;
}
- setJob(null);
- } else if (latest.type === 'canceled' || latest.type === 'cancelled') {
- toast.info('MIDI transcription cancelled');
- setJob(null);
- }
- }, [latest]);
-
- // Stream closed without a terminal frame (server restart mid-transcription,
- // or the job was pruned before/after attach) — recover so the spinner can't hang.
- useEffect(() => {
- if (job && sse.closed && !isTerminalSseFrame(latest)) {
- setJob(null);
- toast.info('Lost connection to the MIDI transcription');
- }
- }, [sse.closed]);
-
- // The actual kickoff, shared by the user click (`start`) and the post-install
- // retry (`installGate.onComplete`). Kept free of the install-open gate so the
- // retry — fired synchronously right after clearing installContext, before the
- // re-render commits it — isn't swallowed by a stale closure value.
- const kickoff = (context) => {
- if (job || pending) return;
- setPending(true);
- startRequest(context)
- .then(({ jobId }) => {
- installAttemptedRef.current = false; // runtime is present — reset the loop guard
- setJob({ jobId, context });
- })
- .catch((err) => {
- // The runtime isn't provisioned yet: install it in-app on first use,
- // then re-run the transcription for the same target. Only auto-open
- // once — a second miss after a "successful" install is a real fault, so
- // surface the message instead of relooping the installer.
- if (err?.code === 'MIDI_RUNTIME_MISSING' && !installAttemptedRef.current) {
- installAttemptedRef.current = true;
- setInstallContext(context);
- return;
- }
- toast.error(err?.message || 'Failed to start MIDI transcription');
- })
- .finally(() => setPending(false));
- };
+ return false;
+ },
+ // Gated-repo download failure — open the license + token prompt instead of
+ // toasting a raw HuggingFace traceback the user can't act on.
+ onErrorFrame: (frame, context) => {
+ if (frame.code === 'gated_repo') {
+ setGatedContext({ context, repo: frame.repo || null });
+ return true;
+ }
+ return false;
+ },
+ });
const start = (context) => {
- if (job || pending || installContext !== null || gatedContext !== null) return;
- kickoff(context);
- };
-
- const cancel = () => {
- if (!job) return;
- cancelRequest(job.jobId, { silent: true }).catch(() => {});
+ if (installContext !== null || gatedContext !== null) return;
+ slot.start(context);
};
// Installer modal wiring — spread onto <MidiInstallModal>. Completing the
- // install re-fires the captured transcription; closing it (user cancel)
- // clears the pending target and resets the loop guard so a later click can
- // retry the install cleanly.
+ // install re-fires the captured transcription (via `slot.start` directly, so
+ // the retry isn't swallowed by this render's not-yet-cleared installContext);
+ // closing it (user cancel) clears the pending target and resets the loop
+ // guard so a later click can retry the install cleanly.
const installGate = {
open: installContext !== null,
onComplete: () => {
const ctx = installContext;
setInstallContext(null);
- if (ctx !== null) kickoff(ctx);
+ if (ctx !== null) slot.start(ctx);
},
onClose: () => {
setInstallContext(null);
@@ -139,7 +105,7 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe
onSaved: () => {
const ctx = gatedContext?.context ?? null;
setGatedContext(null);
- if (ctx !== null) kickoff(ctx);
+ if (ctx !== null) slot.start(ctx);
},
onClose: () => setGatedContext(null),
};
@@ -148,11 +114,11 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe
// gate per-target UI ("is the active job for THIS record?") without
// mirroring the value in its own state.
return {
- active: pending || !!job || installContext !== null || gatedContext !== null,
- stage,
- context: job?.context ?? null,
+ active: slot.active || installContext !== null || gatedContext !== null,
+ stage: slot.stage,
+ context: slot.context,
start,
- cancel,
+ cancel: slot.cancel,
installGate,
gatedGate,
};
diff --git a/client/src/hooks/useReferenceAudioImport.js b/client/src/hooks/useReferenceAudioImport.js
index 233875ad70..20483ceae2 100644
--- a/client/src/hooks/useReferenceAudioImport.js
+++ b/client/src/hooks/useReferenceAudioImport.js
@@ -1,11 +1,9 @@
-import { useEffect, useState } from 'react';
-import toast from '../components/ui/Toast';
import {
importReferenceAudio,
cancelReferenceAudioImport,
referenceAudioImportEventsUrl,
} from '../services/apiRounds.js';
-import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
+import useSseJobSlot from './useSseJobSlot.js';
/**
* One round reference-audio-import job slot (#2120) — download + extract a
@@ -13,9 +11,10 @@ import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
* progress. The deferred convenience path from the reference-audio analysis
* feature (#2106); upload/mic capture remain the primary attach paths.
*
- * Mirrors `useYoutubeTrackImport`: call it once per UI surface that can
- * independently kick off an import so each owns its own job + SSE subscription
- * (a shared slot would let a second kickoff orphan the first's in-flight job).
+ * A thin wrapper over the generic `useSseJobSlot` (#2368) — call it once per UI
+ * surface that can independently kick off an import so each owns its own job +
+ * SSE subscription (a shared slot would let a second kickoff orphan the first's
+ * in-flight job).
*
* `onComplete(filename, context)` fires once the download lands a file in the
* uploads dir — `context` is whatever was passed to `start(url, context)`,
@@ -23,54 +22,17 @@ import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
* target even if the caller's own state changed while it was in flight.
*/
export default function useReferenceAudioImport({ onComplete } = {}) {
- const [job, setJob] = useState(null); // { jobId, context }
- // `pending` covers the gap between clicking Download and the kickoff request
- // resolving, when `job` is still null — without it a fast double-click could
- // fire a second request whose response silently orphans the first job.
- const [pending, setPending] = useState(false);
- const sse = useSseProgress(job ? referenceAudioImportEventsUrl(job.jobId) : null);
- const latest = sse.latest;
- const percent = Math.round(latest?.percent ?? 0);
- const stage = latest?.stage ?? null;
-
- useEffect(() => {
- if (!job || !latest) return;
- if (latest.type === 'complete') {
- onComplete?.(latest.filename, job.context);
- toast.success('Reference audio downloaded — Save the song to keep it');
- setJob(null);
- } else if (latest.type === 'error') {
- toast.error(latest.error || 'Reference audio download failed');
- setJob(null);
- } else if (latest.type === 'canceled' || latest.type === 'cancelled') {
- toast.info('Reference audio download cancelled');
- setJob(null);
- }
- }, [latest]);
-
- // Stream closed without a terminal frame (server restart mid-download, or the
- // job was pruned before/after attach) — recover so the spinner can't hang.
- useEffect(() => {
- if (job && sse.closed && !isTerminalSseFrame(latest)) {
- setJob(null);
- toast.info('Lost connection to the reference-audio download');
- }
- }, [sse.closed]);
-
- const start = (url, context) => {
- const trimmed = (url || '').trim();
- if (!trimmed || job || pending) return;
- setPending(true);
- importReferenceAudio(trimmed, { silent: true })
- .then(({ jobId }) => setJob({ jobId, context }))
- .catch((err) => toast.error(err?.message || 'Failed to start reference-audio download'))
- .finally(() => setPending(false));
- };
-
- const cancel = () => {
- if (!job) return;
- cancelReferenceAudioImport(job.jobId, { silent: true }).catch(() => {});
- };
-
- return { active: pending || !!job, percent, stage, start, cancel };
+ const { active, percent, stage, start, cancel } = useSseJobSlot({
+ startRequest: (url) => importReferenceAudio(url, { silent: true }),
+ eventsUrl: referenceAudioImportEventsUrl,
+ cancelRequest: cancelReferenceAudioImport,
+ trimStartArg: true,
+ onComplete: (frame, context) => onComplete?.(frame.filename, context),
+ successToast: () => 'Reference audio downloaded — Save the song to keep it',
+ errorFallback: 'Reference audio download failed',
+ canceledMessage: 'Reference audio download cancelled',
+ lostConnectionMessage: 'Lost connection to the reference-audio download',
+ startErrorFallback: 'Failed to start reference-audio download',
+ });
+ return { active, percent, stage, start, cancel };
}
diff --git a/client/src/hooks/useSseJobSlot.js b/client/src/hooks/useSseJobSlot.js
new file mode 100644
index 0000000000..4e66f9781e
--- /dev/null
+++ b/client/src/hooks/useSseJobSlot.js
@@ -0,0 +1,120 @@
+import { useEffect, useState } from 'react';
+import toast from '../components/ui/Toast';
+import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
+
+/**
+ * One generic single-slot SSE job — the shared machinery every "kick off a job,
+ * stream progress over SSE, settle on the terminal frame" hook re-implements:
+ *
+ * - `pending` covers the gap between clicking Start and the kickoff request
+ * resolving, when `job` is still null — without it a fast double-click could
+ * fire a second request whose response silently orphans the first job.
+ * - the terminal-frame effect (`complete` / `error` / `canceled|cancelled`),
+ * - the `sse.closed`-without-a-terminal-frame recovery (server restart mid-job,
+ * or the job was pruned before/after attach) so the spinner can't hang.
+ *
+ * Call it once per UI surface that can independently kick off a job so each owns
+ * its own job + SSE subscription — a shared slot would let a second kickoff
+ * orphan the first's in-flight job (its SSE subscription would never re-attach).
+ *
+ * The three feature hooks (`useReferenceAudioImport`, `useYoutubeTrackImport`,
+ * `useVideoDownload`) and `useMidiTranscription` are thin wrappers over this;
+ * the recovery + terminal-frame logic lives here in exactly one place (#2368).
+ *
+ * Options:
+ * - `startRequest(startArg)` → resolves `{ jobId }` — the feature's kickoff call.
+ * - `eventsUrl(jobId)` / `cancelRequest(jobId, { silent })` — SSE URL + cancel call.
+ * - `onComplete(frame, context)` — fires on the terminal `complete` frame.
+ * - `context` (the second `start` arg, or the start arg itself when omitted) is
+ * captured at kickoff so a slow-finishing job still attaches to the right
+ * target even if the caller's own state changed while it was in flight.
+ * - `trimStartArg` — when true, `start(url, context)` trims `url` and no-ops on
+ * empty (the URL-import hooks); when false, `start(context)` passes through.
+ * - `successToast(frame)` — optional; toast.success its return when truthy.
+ * - `errorFallback` / `canceledMessage` / `lostConnectionMessage` /
+ * `startErrorFallback` — the per-feature toast copy.
+ * - `onErrorFrame(frame, context)` → return true to suppress the default error
+ * toast (the MIDI gated-repo prompt intercepts here).
+ * - `onKickoffError(err, startArg)` → return true to suppress the default kickoff
+ * error toast (the MIDI first-use install gate intercepts here).
+ * - `onKickoffSuccess(jobId, startArg)` — fires when the kickoff resolves.
+ */
+export default function useSseJobSlot({
+ startRequest,
+ eventsUrl,
+ cancelRequest,
+ onComplete,
+ trimStartArg = false,
+ successToast,
+ errorFallback = 'Job failed',
+ canceledMessage = 'Job cancelled',
+ lostConnectionMessage = 'Lost connection to the job',
+ startErrorFallback = 'Failed to start the job',
+ onErrorFrame,
+ onKickoffError,
+ onKickoffSuccess,
+} = {}) {
+ const [job, setJob] = useState(null); // { jobId, context }
+ const [pending, setPending] = useState(false);
+ const sse = useSseProgress(job ? eventsUrl(job.jobId) : null);
+ const latest = sse.latest;
+ const percent = Math.round(latest?.percent ?? 0);
+ const stage = latest?.stage ?? null;
+
+ useEffect(() => {
+ if (!job || !latest) return;
+ if (latest.type === 'complete') {
+ onComplete?.(latest, job.context);
+ const msg = successToast?.(latest);
+ if (msg) toast.success(msg);
+ setJob(null);
+ } else if (latest.type === 'error') {
+ if (!onErrorFrame?.(latest, job.context)) {
+ toast.error(latest.error || errorFallback);
+ }
+ setJob(null);
+ } else if (latest.type === 'canceled' || latest.type === 'cancelled') {
+ toast.info(canceledMessage);
+ setJob(null);
+ }
+ }, [latest]);
+
+ // Stream closed without a terminal frame — recover so the spinner can't hang.
+ useEffect(() => {
+ if (job && sse.closed && !isTerminalSseFrame(latest)) {
+ setJob(null);
+ toast.info(lostConnectionMessage);
+ }
+ }, [sse.closed]);
+
+ const start = (startArg, context) => {
+ const arg = trimStartArg ? (startArg ?? '').trim() : startArg;
+ if (trimStartArg && !arg) return;
+ if (job || pending) return;
+ setPending(true);
+ startRequest(arg)
+ .then(({ jobId }) => {
+ onKickoffSuccess?.(jobId, arg);
+ setJob({ jobId, context: context === undefined ? arg : context });
+ })
+ .catch((err) => {
+ if (onKickoffError?.(err, arg)) return;
+ toast.error(err?.message || startErrorFallback);
+ })
+ .finally(() => setPending(false));
+ };
+
+ const cancel = () => {
+ if (!job) return;
+ cancelRequest(job.jobId, { silent: true }).catch(() => {});
+ };
+
+ return {
+ active: pending || !!job,
+ percent,
+ stage,
+ context: job?.context ?? null,
+ start,
+ cancel,
+ };
+}
diff --git a/client/src/hooks/useVideoDownload.js b/client/src/hooks/useVideoDownload.js
index 160b8550df..dd51c82945 100644
--- a/client/src/hooks/useVideoDownload.js
+++ b/client/src/hooks/useVideoDownload.js
@@ -1,65 +1,26 @@
-import { useEffect, useState } from 'react';
-import toast from '../components/ui/Toast';
import { startVideoDownload, cancelVideoDownload, videoDownloadEventsUrl } from '../services/apiVideoDownload.js';
-import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
+import useSseJobSlot from './useSseJobSlot.js';
/**
* One full-video-download job slot (#1946) — start/cancel + SSE progress +
- * terminal-frame handling via `POST /api/devtools/video-download`. Mirrors
- * useYoutubeTrackImport (#1945): kick off returns a jobId, progress streams over
- * SSE, and terminal frames drive completion. `onComplete(video)` fires once the
- * download lands a video-history entry so the caller can prepend it to its list
- * without a full refetch.
+ * terminal-frame handling via `POST /api/devtools/video-download`. A thin
+ * wrapper over the generic `useSseJobSlot` (#2368): kick off returns a jobId,
+ * progress streams over SSE, and terminal frames drive completion.
+ * `onComplete(video)` fires once the download lands a video-history entry so the
+ * caller can prepend it to its list without a full refetch.
*/
export default function useVideoDownload({ onComplete } = {}) {
- const [job, setJob] = useState(null); // { jobId }
- // `pending` covers the gap between clicking Download and the kickoff request
- // resolving, when `job` is still null — without it a fast double-click could
- // fire a second request whose response silently orphans the first job.
- const [pending, setPending] = useState(false);
- const sse = useSseProgress(job ? videoDownloadEventsUrl(job.jobId) : null);
- const percent = Math.round(sse.latest?.percent ?? 0);
- const stage = sse.latest?.stage || null;
-
- useEffect(() => {
- const frame = sse.latest;
- if (!job || !frame) return;
- if (frame.type === 'complete') {
- onComplete?.(frame.video);
- toast.success(`Downloaded "${frame.video?.title || 'video'}"`);
- setJob(null);
- } else if (frame.type === 'error') {
- toast.error(frame.error || 'Video download failed');
- setJob(null);
- } else if (frame.type === 'canceled' || frame.type === 'cancelled') {
- toast.info('Video download cancelled');
- setJob(null);
- }
- }, [sse.latest]);
-
- // Stream closed without a terminal frame (server restart mid-download, or the
- // job was pruned before/after attach) — recover so the progress UI can't hang.
- useEffect(() => {
- if (job && sse.closed && !isTerminalSseFrame(sse.latest)) {
- setJob(null);
- toast.info('Lost connection to the download — check the list below');
- }
- }, [sse.closed]);
-
- const start = (url) => {
- const trimmed = (url || '').trim();
- if (!trimmed || job || pending) return;
- setPending(true);
- startVideoDownload(trimmed, { silent: true })
- .then(({ jobId }) => setJob({ jobId }))
- .catch((err) => toast.error(err?.message || 'Failed to start download'))
- .finally(() => setPending(false));
- };
-
- const cancel = () => {
- if (!job) return;
- cancelVideoDownload(job.jobId, { silent: true }).catch(() => {});
- };
-
- return { active: pending || !!job, percent, stage, start, cancel };
+ const { active, percent, stage, start, cancel } = useSseJobSlot({
+ startRequest: (url) => startVideoDownload(url, { silent: true }),
+ eventsUrl: videoDownloadEventsUrl,
+ cancelRequest: cancelVideoDownload,
+ trimStartArg: true,
+ onComplete: (frame) => onComplete?.(frame.video),
+ successToast: (frame) => `Downloaded "${frame.video?.title || 'video'}"`,
+ errorFallback: 'Video download failed',
+ canceledMessage: 'Video download cancelled',
+ lostConnectionMessage: 'Lost connection to the download — check the list below',
+ startErrorFallback: 'Failed to start download',
+ });
+ return { active, percent, stage, start, cancel };
}
diff --git a/client/src/hooks/useYoutubeTrackImport.js b/client/src/hooks/useYoutubeTrackImport.js
index 5498dbd3af..8539e3a56f 100644
--- a/client/src/hooks/useYoutubeTrackImport.js
+++ b/client/src/hooks/useYoutubeTrackImport.js
@@ -1,15 +1,14 @@
-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';
+import useSseJobSlot from './useSseJobSlot.js';
/**
* One YouTube-audio-import job slot (#1945) — start/cancel + SSE progress +
- * terminal-frame handling. Call it once per UI surface that can independently
- * kick off an import (e.g. the create form and an existing project's track
- * picker) so two surfaces each own their own job and SSE subscription; a
- * single shared slot would let a second surface's kickoff silently orphan the
- * first surface's in-flight job (its SSE subscription would never re-attach).
+ * terminal-frame handling. A thin wrapper over the generic `useSseJobSlot`
+ * (#2368); call it once per UI surface that can independently kick off an import
+ * (e.g. the create form and an existing project's track picker) so two surfaces
+ * each own their own job and SSE subscription — a single shared slot would let a
+ * second surface's kickoff silently orphan the first surface's in-flight job (its
+ * SSE subscription would never re-attach).
*
* `onComplete(track, context)` fires once the import lands a Track — `context`
* is whatever was passed to `start(url, context)`, captured at kickoff time so
@@ -17,57 +16,17 @@ import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';
* own state (e.g. which project is selected) changes while it's in flight.
*/
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);
-
- useEffect(() => {
- const frame = sse.latest;
- if (!job || !frame) return;
- if (frame.type === 'complete') {
- onComplete?.(frame.track, job.context);
- toast.success(`Imported "${frame.track.title}" from YouTube`);
- setJob(null);
- } else if (frame.type === 'error') {
- toast.error(frame.error || 'YouTube import failed');
- setJob(null);
- } else if (frame.type === 'canceled' || frame.type === 'cancelled') {
- toast.info('YouTube import cancelled');
- setJob(null);
- }
- }, [sse.latest]);
-
- // Stream closed without a terminal frame (server restart mid-import, or the
- // job was pruned before/after attach) — recover so the spinner can't hang.
- useEffect(() => {
- if (job && sse.closed && !isTerminalSseFrame(sse.latest)) {
- setJob(null);
- toast.info('Lost connection to the YouTube import — check the music library');
- }
- }, [sse.closed]);
-
- const start = (url, context) => {
- const trimmed = url.trim();
- 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(() => setPending(false));
- };
-
- const cancel = () => {
- if (!job) return;
- cancelTrackImport(job.jobId, { silent: true }).catch(() => {});
- };
-
- return { active: pending || !!job, percent, start, cancel };
+ const { active, percent, start, cancel } = useSseJobSlot({
+ startRequest: (url) => importTrackFromYoutube(url, { silent: true }),
+ eventsUrl: trackImportEventsUrl,
+ cancelRequest: cancelTrackImport,
+ trimStartArg: true,
+ onComplete: (frame, context) => onComplete?.(frame.track, context),
+ successToast: (frame) => `Imported "${frame.track.title}" from YouTube`,
+ errorFallback: 'YouTube import failed',
+ canceledMessage: 'YouTube import cancelled',
+ lostConnectionMessage: 'Lost connection to the YouTube import — check the music library',
+ startErrorFallback: 'Failed to start YouTube import',
+ });
+ return { active, percent, start, cancel };
}