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: require completed music installs before reporting success (#9933)
[._.]/ Adam Eivyaa51c481b43c
diff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsxindex 937c3f4786..430e0e7355 100644--- a/client/src/components/music/MusicGenPanel.jsx+++ b/client/src/components/music/MusicGenPanel.jsx@@ -365,7 +365,6 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artistif (!mountedRef.current) return;if (ev.type === 'progress') setSetupProgress({ message: `${ev.file || 'downloading'} — ${Math.round((ev.progress || 0) * 100)}%`, progress: ev.progress });else if (ev.type === 'stage') setSetupProgress({ message: ev.stage });- else if (ev.type === 'error') { failed = true; toast.error(ev.message || 'Download failed'); }}).catch((err) => { failed = true; if (mountedRef.current) toast.error(err.message || 'Install failed'); });if (!mountedRef.current) return;setInstalling(false);@@ -473,15 +472,13 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artistif (!repo || !engine) return;setInstalling(true);setInstallProgress({ message: `Starting ${repo}…` });- // Track failure across the stream: an `error` frame OR a thrown request- // (e.g. a 400 invalid-repo) means the install did NOT succeed, so we must- // not then clear the field / select the repo / report "Installed".+ // The terminal promise rejects errors and interrupted streams; keep retry+ // input and selection unchanged until completion is confirmed.let failed = false;await installAudioModel({ engine: engine.id, repo }, (ev) => {if (!mountedRef.current) return;if (ev.type === 'progress') setInstallProgress({ message: `${ev.file || 'downloading'} — ${Math.round((ev.progress || 0) * 100)}%`, progress: ev.progress });else if (ev.type === 'stage') setInstallProgress({ message: ev.stage });- else if (ev.type === 'error') { failed = true; toast.error(ev.message || 'Download failed'); }}).catch((err) => { failed = true; if (mountedRef.current) toast.error(err.message || 'Install failed'); });if (!mountedRef.current) return;setInstalling(false);diff --git a/client/src/components/music/MusicGenPanel.test.jsx b/client/src/components/music/MusicGenPanel.test.jsxindex 2bab21b5f8..95d1eb82a5 100644--- a/client/src/components/music/MusicGenPanel.test.jsx+++ b/client/src/components/music/MusicGenPanel.test.jsx@@ -1010,3 +1010,29 @@ describe('MusicGenPanel', () => {expect(screen.getByRole('status')).toHaveTextContent(/tens of minutes on a 24 GB GPU/i);});});++// These consumers use the real transport: a fulfilled mock cannot detect EOF success.+describe('Music installation terminal evidence', () => {+ afterEach(() => { vi.unstubAllGlobals(); });+ it.each(['', 'data: {"type":"progress","progress":0.5}\n\n', 'data: {"type":"error","message":"Download failed"}\n\n'])(+ 'keeps custom retry input and reports one failure for %j', async (body) => {+ vi.clearAllMocks();+ const { installAudioModel } = await import('../../services/apiMusic.js');+ api.installAudioModel.mockImplementation(installAudioModel);+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, body: new ReadableStream({ start(c) {+ c.enqueue(new TextEncoder().encode(body)); c.close();+ } }) }));+ api.listMusicEngines.mockResolvedValue({ defaultEngine: 'musicgen', engines: [engine()] });+ api.getActiveProcessing.mockResolvedValue({ jobs: [] });+ api.getInstances.mockResolvedValue({ peers: [] });+ render(<MusicGenPanel prompt="ambient" lyrics="" />);+ const field = await screen.findByPlaceholderText('org/model-repo');+ fireEvent.change(field, { target: { value: 'example/model' } });+ fireEvent.click(screen.getByRole('button', { name: /^Install$/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));+ expect(field).toHaveValue('example/model');+ expect(toast.success).not.toHaveBeenCalled();+ expect(api.listMusicEngines).toHaveBeenCalledTimes(1);+ },+ );+});diff --git a/client/src/components/music/SuperColliderStage.jsx b/client/src/components/music/SuperColliderStage.jsxindex a8a43dce05..3d41cd3e67 100644--- a/client/src/components/music/SuperColliderStage.jsx+++ b/client/src/components/music/SuperColliderStage.jsx@@ -77,7 +77,6 @@ export default function SuperColliderStage({await setupSuperCollider({ rebuild }, (frame) => {if (!mountedRef.current) return;if (frame.type === 'log') setSetupLog((log) => [...(log || []), frame.message].slice(-200));- else if (frame.type === 'error') failed = frame.message || 'SuperCollider setup failed';else if (frame.type === 'complete') setStatus(frame.status);}).catch((err) => { failed = err?.message || 'SuperCollider setup failed'; });if (!mountedRef.current) return;diff --git a/client/src/components/music/SuperColliderStage.test.jsx b/client/src/components/music/SuperColliderStage.test.jsxindex e114fd3af0..74d299669c 100644--- a/client/src/components/music/SuperColliderStage.test.jsx+++ b/client/src/components/music/SuperColliderStage.test.jsx@@ -2,6 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';import SuperColliderStage from './SuperColliderStage';import * as api from '../../services/api';+import toast from '../ui/Toast';+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));import { useSseProgress } from '../../hooks/useSseProgress';vi.mock('../../services/api', () => ({@@ -33,7 +35,7 @@ describe('<SuperColliderStage>', () => {api.renderSuperCollider.mockResolvedValue({ jobId: 'job-12345678', position: 1, seed: 7 });api.saveSuperColliderTake.mockResolvedValue({ track: { id: 'track-1' }, durationSec: 8 });});- afterEach(() => cleanup());+ afterEach(() => { cleanup(); vi.unstubAllGlobals(); });it('offers setup, without building, when the runtime is not ready', async () => {api.getSuperColliderStatus.mockResolvedValue({ state: 'image-missing', ready: false, message: 'image not built', action: 'Run setup' });@@ -88,3 +90,15 @@ describe('<SuperColliderStage>', () => {expect(api.saveSuperColliderTake).not.toHaveBeenCalled();});});++it('does not report readiness when the real setup stream ends without completion', async () => {+ const { setupSuperCollider } = await import('../../services/apiMusic.js');+ api.setupSuperCollider.mockImplementation(setupSuperCollider);+ api.getSuperColliderStatus.mockResolvedValue({ state: 'image-missing', ready: false, message: 'not built' });+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, body: new ReadableStream({ start(c) { c.close(); } }) }));+ mount();+ fireEvent.click(await screen.findByText('Set up SuperCollider'));+ await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));+ expect(toast.success).not.toHaveBeenCalled();+ vi.unstubAllGlobals();+});diff --git a/client/src/components/settings/LocalLlmLibraryView.jsx b/client/src/components/settings/LocalLlmLibraryView.jsxindex e4933c1c79..7d7952536a 100644--- a/client/src/components/settings/LocalLlmLibraryView.jsx+++ b/client/src/components/settings/LocalLlmLibraryView.jsx@@ -267,9 +267,8 @@ export default function LocalLlmLibraryView() {// shared audio-model registry (server/services/audioModels.js) via the Music// studio's streaming HF-download endpoint, so the Music studio picks them up.// The download streams SSE frames; surface progress in the same banner as the- // socket-driven install progress, and treat an `error` frame as failure.+ // socket-driven install progress; the promise owns terminal errors.const installAudio = (model) => {- let failed = false;return runAction(`install-${model.id}`,async () => {@@ -278,15 +277,11 @@ export default function LocalLlmLibraryView() {(ev) => {if (ev?.type === 'stage') setProgressMsg(ev.stage || '');else if (ev?.type === 'progress') setProgressMsg(`${ev.file || 'downloading'} — ${Math.round((ev.progress || 0) * 100)}%`);- else if (ev?.type === 'error') { failed = true; toast.error(ev.message || 'Download failed'); }},);- // installAudioModel resolves even after an error frame (it only throws on- // a non-OK response) — re-throw so runAction skips the success toast.- if (failed) throw Object.assign(new Error('audio install failed'), { handled: true });},`${model.name} installed — available in the Music studio`,- { onError: (err) => { if (!err?.handled) toast.error(err?.message || 'Install failed'); }, clearConfirm: false },+ { onError: (err) => toast.error(err?.message || 'Install failed'), clearConfirm: false },).finally(() => setProgressMsg(''));};const remove = (modelId) => runAction(`delete-${modelId}`, () => deleteLocalLlmModel(selected, modelId), `${modelId} deleted`)diff --git a/client/src/components/settings/LocalLlmLibraryView.test.jsx b/client/src/components/settings/LocalLlmLibraryView.test.jsxindex 1080ca8f50..f236dbf144 100644--- a/client/src/components/settings/LocalLlmLibraryView.test.jsx+++ b/client/src/components/settings/LocalLlmLibraryView.test.jsx@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { MemoryRouter, useLocation } from 'react-router';@@ -536,3 +536,28 @@ describe('LocalLlmLibraryView measured fit badge', () => {expect(await screen.findByText(/backend refused it \(measured\)/)).toBeInTheDocument();});});++describe('audio library installation terminal evidence', () => {+ afterEach(() => vi.unstubAllGlobals());+ it.each([+ ['data: {"type":"progress","progress":0.5}\n\n', false],+ ['data: {"type":"error","message":"Download failed"}\n\n', false],+ ['data: {"type":"complete"}\n\n', true],+ ])('reports installation result only from terminal evidence %j', async (body, succeeds) => {+ const api = await import('../../services/api');+ const { installAudioModel } = await import('../../services/apiMusic.js');+ const { default: toast } = await import('../ui/Toast');+ api.installAudioModel.mockImplementation(installAudioModel);+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, body: new ReadableStream({ start(c) {+ c.enqueue(new TextEncoder().encode(body)); c.close();+ } }) }));+ getLocalLlmCatalog.mockResolvedValue({ models: [{ id: 'example/audio', key: 'example-audio', name: 'Example audio',+ repository: 'example/audio', engine: 'musicgen', category: 'audio', size: '1 GB', params: '1B' }] });+ await renderLibrary();+ const card = (await screen.findByText('Example audio')).closest('.flex-col');+ fireEvent.click(within(card).getByRole('button', { name: /^Install$/ }));+ await waitFor(() => expect(api.installAudioModel).toHaveBeenCalled());+ await waitFor(() => expect(succeeds ? toast.success : toast.error).toHaveBeenCalledTimes(1));+ expect(succeeds ? toast.error : toast.success).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/apiMusic.js b/client/src/services/apiMusic.jsindex 8ae2b3d383..9127dfb4b1 100644--- a/client/src/services/apiMusic.js+++ b/client/src/services/apiMusic.js@@ -66,7 +66,8 @@ export const removeAudioModel = (engine, id, requestOptions = {}) =>// Install an additional audio model from HuggingFace into an engine. The server// streams the download as Server-Sent Events; this helper drives an EventSource// and invokes `onEvent({ type, progress, message, ... })` per frame, resolving-// when the stream ends. (POST-with-SSE: we use fetch + a manual reader since+// only after a complete frame. Error frames or interrupted streams reject.+// (POST-with-SSE: we use fetch + a manual reader since// EventSource is GET-only.) Returns a Promise<void>.export const installAudioModel = ({ engine, repo, name }, onEvent) => postForSseFrames('/api/music/models', { engine, repo, name }, onEvent);@@ -91,17 +92,31 @@ async function postForSseFrames(url, payload, onEvent) {const reader = res.body.getReader();const decoder = new TextDecoder();let buf = '';- for (;;) {- const { value, done } = await reader.read();- if (done) break;- buf += decoder.decode(value, { stream: true });- const frames = buf.split('\n\n');- buf = frames.pop() || '';- for (const frame of frames) {- const line = frame.split('\n').find((l) => l.startsWith('data:'));- if (!line) continue;- try { onEvent?.(JSON.parse(line.slice('data:'.length).trim())); } catch { /* ignore malformed frame */ }+ const handleFrame = (frame) => {+ const data = frame.split(/\r?\n/).filter((line) => line.startsWith('data:'))+ .map((line) => line.slice('data:'.length).trimStart()).join('\n');+ if (!data) return false;+ const event = JSON.parse(data);+ if (!event || typeof event !== 'object') return false;+ onEvent?.(event);+ if (event.type === 'error') throw new Error(event.message || event.error || 'Installation failed');+ return event.type === 'complete';+ };+ try {+ for (;;) {+ const { value, done } = await reader.read();+ buf += done ? decoder.decode() : decoder.decode(value, { stream: true });+ const frames = buf.split(/\r?\n\r?\n/);+ buf = frames.pop() || '';+ if (done && buf) frames.push(buf);+ for (const frame of frames) {+ if (handleFrame(frame)) return;+ }+ if (done) throw new Error('Installation connection ended before completion. Check installation status before retrying.');}+ } finally {+ await reader.cancel().catch(() => {});+ reader.releaseLock();}}diff --git a/client/src/services/apiMusic.test.js b/client/src/services/apiMusic.test.jsnew file mode 100644index 0000000000..ae60362d71--- /dev/null+++ b/client/src/services/apiMusic.test.js@@ -0,0 +1,48 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { installAudioModel, setupSuperCollider } from './apiMusic.js';+import { maybeRedirectToLogin } from './apiCore.js';++vi.mock('./apiCore.js', () => ({ request: vi.fn(), maybeRedirectToLogin: vi.fn() }));+afterEach(() => { vi.unstubAllGlobals(); vi.clearAllMocks(); });++const respond = (chunks) => vi.stubGlobal('fetch', vi.fn().mockResolvedValue({+ ok: true,+ body: new ReadableStream({ start(controller) {+ for (const chunk of chunks) controller.enqueue(new TextEncoder().encode(chunk));+ controller.close();+ } }),+}));++for (const [name, start] of [+ ['audio model', (onEvent) => installAudioModel({ engine: 'musicgen', repo: 'example/model' }, onEvent)],+ ['SuperCollider', (onEvent) => setupSuperCollider({}, onEvent)],+]) describe(`${name} installation transport`, () => {+ it.each(['', 'data: {"type":"log","message":"working"}\n\n', 'data: {"type":"progress","progress":0.5}\n\n'])(+ 'rejects an incomplete stream %j without retrying', async (body) => {+ respond([body]);+ await expect(start(vi.fn())).rejects.toThrow('before completion');+ expect(fetch).toHaveBeenCalledTimes(1);+ },+ );+ it('rejects the explicit terminal error even if completion follows', async () => {+ respond(['data: {"type":"error","message":"Download failed"}\n\ndata: {"type":"complete"}\n\n']);+ await expect(start(vi.fn())).rejects.toThrow('Download failed');+ });+ it('accepts fragmented CRLF framing and flushes the final buffered completion', async () => {+ respond(['data: {"type":"log","message":"working"}\r', '\n\r\ndata: {"type":', '"complete"}']);+ const events = vi.fn();+ await expect(start(events)).resolves.toBeUndefined();+ expect(events.mock.calls.map(([event]) => event.type)).toEqual(['log', 'complete']);+ });+ it('does not interpret malformed completion as success', async () => {+ respond(['data: {"type":"complete"\n\n']);+ await expect(start(vi.fn())).rejects.toThrow();+ });+});++it('preserves authentication redirect handling', async () => {+ const response = { ok: false, status: 401, text: async () => JSON.stringify({ code: 'AUTH_REQUIRED', error: 'Sign in' }) };+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));+ await expect(installAudioModel({ engine: 'musicgen', repo: 'example/model' })).rejects.toThrow('Sign in');+ expect(maybeRedirectToLogin).toHaveBeenCalledWith(response, { code: 'AUTH_REQUIRED', error: 'Sign in' });+});