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

surface MuScriptor first-use model download as a distinct stage with a toast

[._.]/ Adam Eivy7ccdc7fa95c8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0662cf4707..b84a0eb987 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Changes
+- **The MIDI transcription button now shows a distinct "Downloading model…" phase with a toast, instead of an opaque multi-minute spinner.** MuScriptor auto-downloads its (gated, multi-hundred-MB) weights from HuggingFace on first use, but the sidecar reported that first-run download as the same generic `load-model` stage as a fast cached load — so the Transcribe MIDI / MIDI buttons just sat in an animation state with no explanation for minutes. `transcribe_muscriptor.py` now peeks at the HF hub cache and emits a separate `download-model` STAGE only when a download is actually about to happen; the shared `useMidiTranscription` hook maps it to a "Downloading model…" label (now exposed as a ready-to-render `stageLabel` both the Rounds and Music Video surfaces use — the Music Video button previously showed only a static "MIDI · Cancel" with no progress) and fires a one-time toast ("Downloading the MuScriptor model — first use only, this can take a few minutes.") when the download begins. Cache detection is best-effort — a wrong guess only mislabels the stage, never fails the transcription.
+
- **The offline service worker's cold-first-visit route gap is now a documented, accepted trade-off rather than an open question (#2424).** A route visited *only* during the very first page load (before the SW registers at `window.load`) has an uncached chunk, so an offline reload of exactly that route boots the shell but can't render until the route is visited online once more. Fully closing this would require a build-time precache manifest (workbox / vite-plugin-pwa or an emitted asset-manifest) that precaches *every* build chunk upfront — which spends first-visit bandwidth on routes the user may never open, directly against this SW's low-bandwidth goal. For a single-user app the mitigation is a one-time online load per route, so the limitation is deliberately left in place; the reasoning is now recorded inline in `client/public/sw.js` so it doesn't dangle-point at a closed issue. No behavior change.
- **CoS task-learning success rates now decay via a recency window, so a since-resolved failure burst stops signaling Layered Intelligence that work is needed (#2460).** The `byTaskType` counters in `data/cos/learning.json` are lifetime-cumulative and never age out — a provider misconfig or PTY-capture artifacts recorded as failures on a now-retired task type permanently depressed the success rate the LI reasoner reads via its `cosMetrics` source (default-on for PortOS), long after the root cause was fixed. Each task-type bucket now also carries a bounded `recentOutcomes` ring (`{ t, s }`, cap 50, mirroring the `failureSignatures.recent` precedent) that `recordTaskCompletion` appends to; a new pure `computeWindowedStats` derives a `recentSuccessRate` windowed by BOTH count and age (defaults: last 30 runs / 30 days, configurable), exposed via `getWindowedStats(taskType, { maxCount, maxAgeMs })`. The LI `cosMetrics` source now surfaces lifetime and windowed rates labeled distinctly, so a resolved failure burst self-heals without a manual `resetTaskTypeLearning`, while the lifetime counters stay intact for the dashboard/telemetry views. `recentSuccessRate` uses a `null` sentinel (never a fabricated `0%`) when the window has no samples, so the reasoner falls back to the lifetime rate. Store version bumped 1→2 with an idempotent migration (188) that initializes an EMPTY ring per task type — deliberately not backfilled from failure-only history, which would fabricate an all-failure window.
diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsx
index 8c15426253..8ce29bbe43 100644
--- a/client/src/components/songs/ReferenceAnalysis.jsx
+++ b/client/src/components/songs/ReferenceAnalysis.jsx
@@ -52,16 +52,6 @@ const MAX_AUDIO_BYTES = 35 * 1024 * 1024;
// disable adding more client-side; the server enforces the real bounds.
const REF_SEGMENTS_MAX = 24;
-// Human labels for the MuScriptor sidecar's STAGE names (SSE progress frames).
-const MIDI_STAGE_LABELS = {
- starting: 'Starting…',
- 'import-runtime': 'Loading runtime…',
- 'load-model': 'Loading model…',
- transcribe: 'Transcribing…',
- 'write-midi': 'Writing MIDI…',
- importing: 'Saving…',
-};
-
const msToSec = (ms) => (Math.max(0, ms) / 1000).toFixed(1);
const secToMs = (raw) => {
const n = Number(raw);
@@ -213,7 +203,7 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {
</>
) : midiJob.active ? (
<span className="flex items-center gap-1.5 px-2 py-1 text-xs rounded-lg border border-port-border text-gray-300">
- <Loader2 size={13} className="animate-spin" /> {MIDI_STAGE_LABELS[midiJob.stage] || 'Transcribing…'}
+ <Loader2 size={13} className="animate-spin" /> {midiJob.stageLabel}
<button type="button" onClick={midiJob.cancel} title="Cancel MIDI transcription" className="ml-1 text-gray-400 hover:text-port-error">
<X size={13} />
</button>
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 2995b83be7..2af124d5d4 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -157,4 +157,4 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useYoutubeTrackImport` | One YouTube-audio-import job slot (#1945): start/cancel + SSE progress + terminal-frame handling via `POST /api/tracks/import/youtube`. Returns `{ active, percent, start(url, context), cancel }`; `onComplete(track, context)` fires with the finished Track. Call once per UI surface that can independently kick off an import — a shared slot would let one surface's kickoff orphan another's in-flight job. | Any picker that lets a user paste a YouTube URL to create a Track (Music Video's create form and track-change row). |
| `useVideoDownload` | One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via `POST /api/devtools/video-download`. Returns `{ active, percent, stage, start(url), cancel }`; `onComplete(video)` fires with the finished video-history entry. | The Dev Tools Video Downloader page. |
| `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. |
-| `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, context, start(context), cancel }` (`context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. |
+| `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. |
diff --git a/client/src/hooks/useMidiTranscription.js b/client/src/hooks/useMidiTranscription.js
index a9c51c7be7..4e8d356ca8 100644
--- a/client/src/hooks/useMidiTranscription.js
+++ b/client/src/hooks/useMidiTranscription.js
@@ -1,6 +1,25 @@
-import { useRef, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
+import toast from '../components/ui/Toast';
import useSseJobSlot from './useSseJobSlot.js';
+// Human labels for the MuScriptor sidecar's STAGE names (SSE progress frames).
+// Shared by every surface that shows a transcription's progress (Rounds +
+// Music Video) so the phrasing stays in one place. `download-model` is the
+// first-use weight download the sidecar reports distinctly from a cached
+// `load-model` load — the difference between a multi-minute wait and a quick
+// one, so it gets its own label + a one-time toast (below).
+export const MIDI_STAGE_LABELS = Object.freeze({
+ starting: 'Starting…',
+ 'import-runtime': 'Loading runtime…',
+ 'download-model': 'Downloading model…',
+ 'load-model': 'Loading model…',
+ transcribe: 'Transcribing…',
+ 'write-midi': 'Writing MIDI…',
+ importing: 'Saving…',
+});
+
+export const midiStageLabel = (stage) => MIDI_STAGE_LABELS[stage] || 'Transcribing…';
+
/**
* One audio → MIDI transcription job slot (MuScriptor) — generic over the
* Rounds and Music Video API surfaces, which share the same kickoff/SSE/cancel
@@ -72,6 +91,20 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe
},
});
+ // First-use weight download is the slow part — the sidecar reports it as a
+ // distinct `download-model` stage. Fire a one-time toast when it begins so
+ // the user is told "we're downloading the model" instead of watching an
+ // unexplained multi-minute spinner (the button label alone is easy to miss).
+ // Re-arm once the job settles so a later cold-cache size re-toasts.
+ const downloadToastedRef = useRef(false);
+ useEffect(() => {
+ if (!slot.active) { downloadToastedRef.current = false; return; }
+ if (slot.stage === 'download-model' && !downloadToastedRef.current) {
+ downloadToastedRef.current = true;
+ toast.info('Downloading the MuScriptor model — first use only, this can take a few minutes.');
+ }
+ }, [slot.active, slot.stage]);
+
const start = (context) => {
if (installContext !== null || gatedContext !== null) return;
slot.start(context);
@@ -116,6 +149,9 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe
return {
active: slot.active || installContext !== null || gatedContext !== null,
stage: slot.stage,
+ // Ready-to-render human label for the current stage (defaults to
+ // "Transcribing…") so surfaces don't each re-map the STAGE names.
+ stageLabel: midiStageLabel(slot.stage),
context: slot.context,
start,
cancel: slot.cancel,
diff --git a/client/src/hooks/useMidiTranscription.test.jsx b/client/src/hooks/useMidiTranscription.test.jsx
index 1377bf5d35..0495127581 100644
--- a/client/src/hooks/useMidiTranscription.test.jsx
+++ b/client/src/hooks/useMidiTranscription.test.jsx
@@ -162,3 +162,56 @@ describe('useMidiTranscription — gated-repo gate', () => {
expect(toast.error).toHaveBeenCalledWith('boom');
});
});
+
+describe('useMidiTranscription — progress stage labels + download toast', () => {
+ const makeHook = () => renderHook(() => useMidiTranscription({
+ startRequest: vi.fn().mockResolvedValue({ jobId: 'job-1' }),
+ eventsUrl: (id) => `/e/${id}`,
+ cancelRequest: vi.fn().mockResolvedValue({}),
+ onComplete: vi.fn(),
+ }));
+
+ beforeEach(() => {
+ toast.info.mockClear();
+ sseState.latest = null;
+ sseState.closed = false;
+ });
+
+ it('exposes a human stageLabel for the current STAGE, defaulting to Transcribing…', async () => {
+ const { result, rerender } = makeHook();
+ await act(async () => { result.current.start('song.wav'); });
+
+ sseState.latest = { type: 'progress', stage: 'download-model' };
+ await act(async () => { rerender(); });
+ expect(result.current.stageLabel).toBe('Downloading model…');
+
+ sseState.latest = { type: 'progress', stage: 'write-midi' };
+ await act(async () => { rerender(); });
+ expect(result.current.stageLabel).toBe('Writing MIDI…');
+
+ sseState.latest = { type: 'progress', stage: 'some-future-stage' };
+ await act(async () => { rerender(); });
+ expect(result.current.stageLabel).toBe('Transcribing…');
+ });
+
+ it('fires a one-time toast when the first-use model download begins', async () => {
+ const { result, rerender } = makeHook();
+ await act(async () => { result.current.start('song.wav'); });
+
+ sseState.latest = { type: 'progress', stage: 'download-model' };
+ await act(async () => { rerender(); });
+ // Re-render still on the download stage must not re-toast.
+ await act(async () => { rerender(); });
+ expect(toast.info).toHaveBeenCalledTimes(1);
+ expect(toast.info.mock.calls[0][0]).toMatch(/downloading the muscriptor model/i);
+ });
+
+ it('does not toast when the model loads from cache (load-model, no download)', async () => {
+ const { result, rerender } = makeHook();
+ await act(async () => { result.current.start('song.wav'); });
+
+ sseState.latest = { type: 'progress', stage: 'load-model' };
+ await act(async () => { rerender(); });
+ expect(toast.info).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index bd700ace31..0c61dfbc51 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -650,7 +650,7 @@ export default function MusicVideo() {
{midiTargetsSelected ? (
<button onClick={midiJob.cancel} title="Cancel MIDI transcription"
className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0">
- <Activity size={15} className="animate-spin" /> MIDI · Cancel
+ <Activity size={15} className="animate-spin" /> {midiJob.stageLabel} · Cancel
</button>
) : (
<>
diff --git a/scripts/transcribe_muscriptor.py b/scripts/transcribe_muscriptor.py
index 6f8f32c3d6..2e7ab50974 100644
--- a/scripts/transcribe_muscriptor.py
+++ b/scripts/transcribe_muscriptor.py
@@ -82,6 +82,44 @@ def _load_model(TranscriptionModel, size):
return TranscriptionModel.load_model()
+def _weights_cached(size):
+ """True when this size's weights are already in the HuggingFace hub cache.
+
+ `TranscriptionModel.load_model()` auto-downloads the weights from the gated
+ `MuScriptor/muscriptor-<size>` repo on first use, then loads a cached copy on
+ every run after — but from the caller's side both look like the same opaque
+ `load-model` stage that can sit for minutes on the first (download) call. We
+ peek at the hub cache first so the JS side can show a distinct, honest
+ "Downloading model weights…" phase (with a toast) only when a download is
+ actually about to happen, instead of an unexplained multi-minute spinner.
+
+ A repo counts as cached only when its `snapshots/` tree holds at least one
+ non-empty file — HF materializes snapshot symlinks only after a blob finishes
+ downloading, so a half-finished download (blob still `.incomplete`) correctly
+ reads as not-cached. Heuristic and best-effort: the worst case of a wrong
+ guess is a mislabeled stage, never a failed transcription. If the muscriptor
+ repo id ever diverges from the assumed `MuScriptor/muscriptor-<size>`, this
+ quietly returns False and we fall back to the generic load-model label.
+ """
+ hub_cache = (
+ os.environ.get("HF_HUB_CACHE")
+ or (os.path.join(os.environ["HF_HOME"], "hub") if os.environ.get("HF_HOME") else None)
+ or os.path.expanduser("~/.cache/huggingface/hub")
+ )
+ snapshots = os.path.join(hub_cache, f"models--MuScriptor--muscriptor-{size}", "snapshots")
+ if not os.path.isdir(snapshots):
+ return False
+ for root, _dirs, files in os.walk(snapshots):
+ for name in files:
+ try:
+ # getsize follows the snapshot symlink to the real blob.
+ if os.path.getsize(os.path.join(root, name)) > 0:
+ return True
+ except OSError:
+ continue
+ return False
+
+
@install_hf_error_handler
def main():
parser = argparse.ArgumentParser(description="PortOS MuScriptor runner (audio → MIDI)")
@@ -101,7 +139,11 @@ def main():
log_stage("import-runtime")
TranscriptionModel = _import_model_class(args.runtime_dir)
- log_stage("load-model", args.model)
+ # First use downloads the weights (minutes); every run after loads the
+ # cached copy (seconds). Emit a distinct `download-model` stage for the
+ # former so the UI can say "Downloading…" + toast, rather than an opaque
+ # multi-minute "Loading model…".
+ log_stage("download-model" if not _weights_cached(args.model) else "load-model", args.model)
model = _load_model(TranscriptionModel, args.model)
log_stage("transcribe", os.path.basename(args.audio))
diff --git a/server/services/audioMidiTranscription.js b/server/services/audioMidiTranscription.js
index 2578e77b3e..c103de3b7a 100644
--- a/server/services/audioMidiTranscription.js
+++ b/server/services/audioMidiTranscription.js
@@ -8,8 +8,10 @@
* (`INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh`) through the
* sidecar `scripts/transcribe_muscriptor.py`, which mirrors the generate_*
* audio sidecars' STAGE:/RESULT: wire protocol. Model weights auto-download
- * from HuggingFace on first use, so the first transcription can sit in
- * `load-model` for a while — the STAGE lines keep that visible.
+ * from HuggingFace on first use; the sidecar emits a distinct `download-model`
+ * stage (vs `load-model` for a cached load) so the client can show an honest
+ * "Downloading model weights…" phase + toast instead of an opaque multi-minute
+ * spinner — the STAGE lines keep the whole run visible.
*
* Job shape mirrors roundReferenceAudioImport.js (the lightweight SSE-job
* pattern): kickoff returns `{ jobId }` immediately, the transcription runs