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
auto-install MuScriptor MIDI runtime on first transcribe click
[._.]/ Adam Eivy5f342f43d13a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 613b9424eb..194e3f2395 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,4 +6,6 @@## Features+- **Audio → MIDI transcription now installs its runtime automatically on first use.** Clicking *Transcribe MIDI* (Rounds reference audio) or *MIDI* (Music Video source track) used to dead-end on a toast telling you to run `INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh` in a terminal. Now, when the MuScriptor venv isn't provisioned yet, PortOS opens an in-app installer that streams the setup line-by-line — the same experience as the image and video model runtimes — and, on completion, automatically runs the transcription you originally asked for. A new `GET /api/midi-runtime/install` endpoint reuses the shared `RuntimeInstallModal`/SSE-install path (in-flight singleton, detached process group so a cancel kills pip/git children, post-install venv re-probe); `useMidiTranscription` catches the `503 MIDI_RUNTIME_MISSING` kickoff, gates the modal, and retries once installed (with a loop guard so a genuinely-failed install surfaces its error instead of relooping).+- **PortOS now installs a service worker for offline app-shell loading and low-bandwidth caching** — the modern replacement for the long-deprecated AppCache manifest. After the first online visit, the built app shell (`index.html`) and the content-hashed JS/CSS chunks are cached, so the UI loads instantly on repeat visits, keeps rendering when the server is briefly unreachable (flaky Tailnet links), and stops re-pulling megabytes of vendor JS on every navigation over a slow connection. Google Fonts and static public assets (icons, textures, manifest) are cached too. Real-time and large/dynamic routes — `/api/*`, `/socket.io/*`, and `/data/*` media — are **never** cached, so live data and streamed assets always hit the network (HTTP Range preserved for `/data`). Navigations stay network-first so a fresh build is always picked up when online, and the existing build-id / stale-chunk-reload machinery still handles "the server rebuilt while a tab was open." The worker registers only in a production **secure context** (HTTPS, or `localhost`) — it is a progressive enhancement that silently no-ops over a plain-HTTP Tailnet hostname and in the Vite dev server (where it also tears down any stale worker). Implemented as a hand-rolled worker (`client/public/sw.js`) with no new dependency; registration lives in `client/src/lib/registerServiceWorker.js`. The PWA manifest gained explicit `id`/`scope` for a deterministic installed-app identity.diff --git a/client/src/components/install/MidiInstallModal.jsx b/client/src/components/install/MidiInstallModal.jsxnew file mode 100644index 0000000000..2a0ea94948--- /dev/null+++ b/client/src/components/install/MidiInstallModal.jsx@@ -0,0 +1,24 @@+/**+ * First-use installer for the MuScriptor (audio → MIDI) runtime. A thin preset+ * over RuntimeInstallModal pointed at /api/midi-runtime/install — opened by+ * useMidiTranscription when the transcribe kickoff returns 503+ * MIDI_RUNTIME_MISSING, so clicking Transcribe on a fresh install bootstraps the+ * venv in-app (like the image/video model runtimes) and then auto-continues the+ * transcription on completion.+ */++import RuntimeInstallModal from './RuntimeInstallModal';++export default function MidiInstallModal({ open, onClose, onComplete }) {+ return (+ <RuntimeInstallModal+ open={open}+ runtime="muscriptor"+ label="MuScriptor (MIDI transcription)"+ installUrlBase="/api/midi-runtime/install"+ description="Installing the MuScriptor runtime and Python packages (large download on first run)…"+ onClose={onClose}+ onComplete={onComplete}+ />+ );+}diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsxindex 70507b3450..41fa541780 100644--- a/client/src/components/songs/ReferenceAnalysis.jsx+++ b/client/src/components/songs/ReferenceAnalysis.jsx@@ -36,6 +36,7 @@ import {} from '../../services/apiRounds.js';import useReferenceAudioImport from '../../hooks/useReferenceAudioImport.js';import useMidiTranscription from '../../hooks/useMidiTranscription.js';+import MidiInstallModal from '../install/MidiInstallModal.jsx';import { startMemoRecording, arrayBufferToBase64 } from '../../lib/audioRecorder';import { proposeSegmentScore, proposeStackedSegmentScore, diffScoreBars, PITCH_CLASS_NAMES } from '../../lib/referenceAnalysis';import { scoreHasMusic, parseScore } from '../../lib/scoreNotation';@@ -179,6 +180,7 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {if (reference.audioFilename) {return (<div className="flex flex-wrap items-center gap-2">+ <MidiInstallModal {...midiJob.installGate} /><span className="flex items-center gap-1.5 text-xs text-port-success"><AudioLines size={14} /> Audio attached</span>@@ -213,7 +215,7 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {<buttontype="button"onClick={() => midiJob.start(reference.audioFilename)}- title="Transcribe this audio to MIDI with MuScriptor (local, needs INSTALL_MUSCRIPTOR=1)"+ title="Transcribe this audio to MIDI with MuScriptor (local — installs automatically on first use)"className="flex items-center gap-1 px-2 py-1 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50"><Music size={13} /> Transcribe MIDIdiff --git a/client/src/hooks/useMidiTranscription.js b/client/src/hooks/useMidiTranscription.jsindex ae2d60d7dd..4ae6130219 100644--- a/client/src/hooks/useMidiTranscription.js+++ b/client/src/hooks/useMidiTranscription.js@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import toast from '../components/ui/Toast';import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';@@ -24,6 +24,17 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe// 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+ // runtime installers), then re-run the transcription once the install+ // completes. `installContext` doubles as the open flag AND the captured+ // target: non-null means the installer is open for that target, null closed.+ const [installContext, setInstallContext] = useState(null);+ // Guard against a reopen loop: if a transcription 503s again right after an+ // install reported success, fall back to the hint toast instead of looping+ // the modal open.+ const installAttemptedRef = useRef(false);const sse = useSseProgress(job ? eventsUrl(job.jobId) : null);const latest = sse.latest;const stage = latest?.stage ?? null;@@ -51,22 +62,62 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe}}, [sse.closed]);- const start = (context) => {+ // 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 }) => setJob({ jobId, context }))- .catch((err) => toast.error(err?.message || 'Failed to start MIDI transcription'))+ .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));};+ const start = (context) => {+ if (job || pending || installContext !== null) return;+ kickoff(context);+ };+const cancel = () => {if (!job) return;cancelRequest(job.jobId, { silent: true }).catch(() => {});};+ // 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.+ const installGate = {+ open: installContext !== null,+ onComplete: () => {+ const ctx = installContext;+ setInstallContext(null);+ if (ctx !== null) kickoff(ctx);+ },+ onClose: () => {+ setInstallContext(null);+ installAttemptedRef.current = false;+ },+ };+// `context` exposes the in-flight job's captured target so a caller can// gate per-target UI ("is the active job for THIS record?") without// mirroring the value in its own state.- return { active: pending || !!job, stage, context: job?.context ?? null, start, cancel };+ return { active: pending || !!job || installContext !== null, stage, context: job?.context ?? null, start, cancel, installGate };}diff --git a/client/src/hooks/useMidiTranscription.test.jsx b/client/src/hooks/useMidiTranscription.test.jsxnew file mode 100644index 0000000000..ee93a94b0f--- /dev/null+++ b/client/src/hooks/useMidiTranscription.test.jsx@@ -0,0 +1,88 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';++// Toast + the SSE subscription are the only seams; stub both so the hook runs+// in jsdom and we can assert which toast (if any) fired.+const toast = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }));+vi.mock('../components/ui/Toast', () => ({ default: toast }));+vi.mock('./useSseProgress.js', () => ({+ useSseProgress: () => ({ latest: null, closed: false }),+ isTerminalSseFrame: () => false,+}));++import useMidiTranscription from './useMidiTranscription.js';++const runtimeMissing = () => Object.assign(new Error('MuScriptor runtime not found.'), { code: 'MIDI_RUNTIME_MISSING', status: 503 });++describe('useMidiTranscription — first-use install gate', () => {+ let startRequest;+ const makeHook = () => renderHook(() => useMidiTranscription({+ startRequest,+ eventsUrl: (id) => `/e/${id}`,+ cancelRequest: vi.fn().mockResolvedValue({}),+ onComplete: vi.fn(),+ }));++ beforeEach(() => {+ toast.error.mockClear();+ toast.info.mockClear();+ startRequest = vi.fn();+ });++ it('opens the installer (no error toast) when the kickoff reports the runtime is missing', async () => {+ startRequest.mockRejectedValueOnce(runtimeMissing());+ const { result } = makeHook();+ await act(async () => { result.current.start('song.wav'); });+ expect(result.current.installGate.open).toBe(true);+ expect(toast.error).not.toHaveBeenCalled();+ expect(startRequest).toHaveBeenCalledTimes(1);+ });++ it('re-runs the captured transcription after the install completes', async () => {+ startRequest.mockRejectedValueOnce(runtimeMissing());+ startRequest.mockResolvedValueOnce({ jobId: 'job-1' });+ const { result } = makeHook();+ await act(async () => { result.current.start('song.wav'); });+ expect(result.current.installGate.open).toBe(true);++ await act(async () => { result.current.installGate.onComplete(); });+ expect(result.current.installGate.open).toBe(false);+ // Retried with the SAME target captured at first click, and now active.+ expect(startRequest).toHaveBeenNthCalledWith(2, 'song.wav');+ expect(result.current.active).toBe(true);+ });++ it('closing the installer clears the pending target and resets the loop guard', async () => {+ startRequest.mockRejectedValue(runtimeMissing());+ const { result } = makeHook();+ await act(async () => { result.current.start('song.wav'); });+ expect(result.current.installGate.open).toBe(true);++ await act(async () => { result.current.installGate.onClose(); });+ expect(result.current.installGate.open).toBe(false);++ // A fresh click re-opens the installer (guard was reset on close).+ await act(async () => { result.current.start('song.wav'); });+ expect(result.current.installGate.open).toBe(true);+ });++ it('a real error (not a missing runtime) toasts instead of opening the installer', async () => {+ startRequest.mockRejectedValueOnce(Object.assign(new Error('boom'), { status: 500 }));+ const { result } = makeHook();+ await act(async () => { result.current.start('song.wav'); });+ expect(result.current.installGate.open).toBe(false);+ expect(toast.error).toHaveBeenCalledWith('boom');+ });++ it('does not loop the installer if the runtime is still missing right after a "successful" install', async () => {+ startRequest.mockRejectedValue(runtimeMissing()); // every kickoff 503s+ const { result } = makeHook();+ await act(async () => { result.current.start('song.wav'); });+ expect(result.current.installGate.open).toBe(true);++ // Install "completes" but the retry 503s again — surface it, don't reopen.+ await act(async () => { result.current.installGate.onComplete(); });+ expect(result.current.installGate.open).toBe(false);+ expect(toast.error).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 50b9b92961..e14424fdaa 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -22,6 +22,7 @@ import {cancelMusicVideoMidiTranscription,} from '../services/apiMusicVideo.js';import useMidiTranscription from '../hooks/useMidiTranscription.js';+import MidiInstallModal from '../components/install/MidiInstallModal.jsx';import { generateImage } from '../services/apiSystem.js';import { generateVideo } from '../services/apiImageVideo.js';import { listTracks, trackAudioUrl } from '../services/apiTracks.js';@@ -561,6 +562,7 @@ export default function MusicVideo() {return (<div className="space-y-4">+ <MidiInstallModal {...midiJob.installGate} /><PageHeader icon={Film} title="Music Video" subtitle="Director-controlled, beat-aware music videos" /><div className="grid grid-cols-1 md:grid-cols-3 gap-4">@@ -648,7 +650,7 @@ export default function MusicVideo() {disabled={midiJob.active || (!selected.trackId && !selected.uploadedAudioFilename)}title={!selected.trackId && !selected.uploadedAudioFilename? 'Link a track first'- : 'Transcribe the track to MIDI with MuScriptor (local, needs INSTALL_MUSCRIPTOR=1)'}+ : 'Transcribe the track to MIDI with MuScriptor (local — installs automatically on first use)'}className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50"><Music size={15} /> MIDI</button>diff --git a/server/index.js b/server/index.jsindex 811bedcdd4..fc78689aeb 100644--- a/server/index.js+++ b/server/index.js@@ -152,6 +152,7 @@ import sdapiRoutes from './routes/sdapi.js';import openclawRoutes from './routes/openclaw.js';import sharingRoutes from './routes/sharing.js';import roundsRoutes from './routes/rounds.js';+import midiRuntimeRoutes from './routes/midiRuntime.js';import peerSyncRoutes from './routes/peerSync.js';import { initSharing } from './services/sharing/index.js';import askRoutes from './routes/ask.js';@@ -566,6 +567,7 @@ app.use('/sdapi/v1', sdapiRoutes);app.use('/api/openclaw', openclawRoutes);app.use('/api/sharing', sharingRoutes);app.use('/api/rounds', roundsRoutes);+app.use('/api/midi-runtime', midiRuntimeRoutes);app.use('/api/peer-sync', peerSyncRoutes);app.use('/api/ask', askRoutes);diff --git a/server/routes/midiRuntime.js b/server/routes/midiRuntime.jsnew file mode 100644index 0000000000..d1447d2d32--- /dev/null+++ b/server/routes/midiRuntime.js@@ -0,0 +1,128 @@+/**+ * MuScriptor (audio → MIDI transcription) runtime installer.+ *+ * GET /api/midi-runtime/install → SSE stream of the venv install+ *+ * The MIDI transcription feature (Rounds reference audio + Music Video source+ * track) runs in an opt-in venv at ~/.portos/venv-muscriptor. Rather than dead-+ * ending on a "run this shell command" hint the first time a user clicks+ * Transcribe, this endpoint bootstraps that venv in-app — the same+ * `INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh` path the README+ * documents, streamed line-by-line — so first use auto-installs like the image+ * and video model runtimes do (see server/routes/music.js and videoGen.js for+ * the sibling installers this mirrors). The client opens RuntimeInstallModal on+ * a 503 MIDI_RUNTIME_MISSING and retries the transcription once this completes.+ */++import { Router } from 'express';+import { existsSync } from 'fs';+import { spawn } from 'child_process';+import { join } from 'path';+import { asyncHandler } from '../lib/errorHandler.js';+import { PATHS } from '../lib/fileUtils.js';+import { safeChildProcessEnv } from '../lib/processEnv.js';+import { openSseStream } from '../lib/sseDownload.js';+import {+ resolveMuscriptorPython,+ invalidateMuscriptorPython,+ MUSCRIPTOR_VENV_DEFAULT,+} from '../lib/pythonSetup.js';++const router = Router();++const MUSCRIPTOR_LABEL = 'MuScriptor (MIDI transcription)';+const MUSCRIPTOR_INSTALL_ENV = 'INSTALL_MUSCRIPTOR';++// In-flight singleton — a rapid double-open of the install modal would+// otherwise race two `bash setup-image-video.sh` children against the same+// venv dir. The existsSync gate can't help before the venv is created.+let installInFlight = null;++router.get('/install', asyncHandler(async (req, res) => {+ const { send, safeEnd } = openSseStream(res);++ if (installInFlight) {+ send({ type: 'error', message: 'A MuScriptor install is already running. Wait for it to finish or restart PortOS.' });+ return safeEnd();+ }+ installInFlight = true;++ // The venv may already exist (another surface installed it) — short-circuit+ // rather than re-running the multi-GB setup. Drop the cached resolve first so+ // this reflects on-disk truth, not a stale null from before a prior install.+ invalidateMuscriptorPython();+ const existing = resolveMuscriptorPython();+ if (existing) {+ installInFlight = null;+ send({ type: 'log', message: `MuScriptor already installed at ${existing}` });+ send({ type: 'complete', message: 'Already installed — nothing to do.' });+ return safeEnd();+ }++ const scriptPath = join(PATHS.root, 'scripts', 'setup-image-video.sh');+ if (!existsSync(scriptPath)) {+ installInFlight = null;+ send({ type: 'error', message: `Installer script not found at ${scriptPath}` });+ return safeEnd();+ }++ send({ type: 'log', message: `Starting MuScriptor install via ${MUSCRIPTOR_INSTALL_ENV}=1 bash scripts/setup-image-video.sh` });+ // `detached: true` puts bash in its own process group so a cancel (client+ // closing the SSE stream) can SIGTERM uv / pip / git children too — otherwise+ // a multi-GB download keeps burning bandwidth after the modal closes.+ const child = spawn('bash', [scriptPath], {+ env: safeChildProcessEnv({ [MUSCRIPTOR_INSTALL_ENV]: '1' }),+ stdio: ['ignore', 'pipe', 'pipe'],+ detached: true,+ });+ installInFlight = child;+ let finished = false;++ const onChunk = (chunk) => {+ for (const line of chunk.toString().split(/[\r\n]+/)) {+ const t = line.trimEnd();+ if (t) send({ type: 'log', message: t });+ }+ };+ child.stdout.on('data', onChunk);+ child.stderr.on('data', onChunk);+ child.on('error', (err) => {+ finished = true;+ installInFlight = null;+ send({ type: 'error', message: `Installer failed to spawn: ${err.message}` });+ safeEnd();+ });+ child.on('close', (code) => {+ finished = true;+ installInFlight = null;+ // Drop the cached resolve so this probe (and the next transcription) sees+ // the freshly-created venv, then re-probe rather than trusting the exit+ // code alone — the setup script import-verifies MuScriptor and exits+ // non-zero on failure, but a partial venv shouldn't be reported "ready".+ invalidateMuscriptorPython();+ const py = resolveMuscriptorPython();+ if (code === 0 && py) {+ send({ type: 'complete', message: `MuScriptor ready: ${py}` });+ } else if (code === 0) {+ send({ type: 'error', message: `Installer exited 0 but ${MUSCRIPTOR_VENV_DEFAULT} is still missing. Re-run from a terminal to see what happened.` });+ } else {+ send({ type: 'error', message: `Installer exited with code ${code}.` });+ }+ safeEnd();+ });++ req.on('close', () => {+ if (finished) return;+ if (!child.killed && child.pid) {+ // Negative pid signals the whole process group — setup-image-video.sh+ // shells out to uv / pip / git, and a plain SIGTERM on bash leaves those+ // running. Guard against ESRCH on an already-dead group.+ try { process.kill(-child.pid, 'SIGTERM'); }+ catch { child.kill('SIGTERM'); }+ }+ installInFlight = null;+ safeEnd();+ });+}));++export default router;diff --git a/server/routes/midiRuntime.test.js b/server/routes/midiRuntime.test.jsnew file mode 100644index 0000000000..f333d93e0f--- /dev/null+++ b/server/routes/midiRuntime.test.js@@ -0,0 +1,53 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++// Drive the venv-resolve per case. `installed` toggles whether+// resolveMuscriptorPython() finds a venv — the only branch we exercise without+// spawning bash (the not-installed path shells out to setup-image-video.sh,+// which a unit test must never run, same posture as music.test.js).+const py = vi.hoisted(() => ({ installed: true }));+vi.mock('../lib/pythonSetup.js', () => ({+ resolveMuscriptorPython: () => (py.installed ? '/home/x/.portos/venv-muscriptor/bin/python3' : null),+ invalidateMuscriptorPython: vi.fn(),+ MUSCRIPTOR_VENV_DEFAULT: '/home/x/.portos/venv-muscriptor/bin/python3',+}));++// Real SSE frames so supertest can read them off the response body.+vi.mock('../lib/sseDownload.js', () => ({+ openSseStream: (res) => {+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });+ return {+ send: (event) => res.write(`data: ${JSON.stringify(event)}\n\n`),+ safeEnd: () => { if (!res.writableEnded) res.end(); },+ };+ },+}));++import { errorMiddleware } from '../lib/errorHandler.js';+import midiRuntimeRoutes from './midiRuntime.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/midi-runtime', midiRuntimeRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('midi-runtime routes', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ py.installed = true;+ });++ it('GET /install completes without spawning when the venv already exists', async () => {+ const r = await request(app).get('/api/midi-runtime/install');+ expect(r.status).toBe(200);+ expect(r.text).toContain('"type":"complete"');+ expect(r.text).toContain('Already installed');+ // The success frame names the resolved interpreter so the modal can show it.+ expect(r.text).toContain('venv-muscriptor');+ });+});