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: move runtime installer streams to POST (#6936)
[._.]/ Adam Eivyadf3b112db40
diff --git a/client/src/components/imageGen/Flux2InstallModal.jsx b/client/src/components/imageGen/Flux2InstallModal.jsxindex 9d7c159fa5..60c675d4bf 100644--- a/client/src/components/imageGen/Flux2InstallModal.jsx+++ b/client/src/components/imageGen/Flux2InstallModal.jsx@@ -1,13 +1,13 @@/*** FLUX.2 venv installer modal. Streams progress from- * GET /api/image-gen/setup/flux2-install (SSE) and animates a 5-stage pipeline+ * POST /api/image-gen/setup/flux2-install (SSE) and animates a 5-stage pipeline* so the user sees something is happening during the multi-GB torch download.** Stages match the events emitted by installFlux2Venv() in pythonSetup.js:* detect → venv → upgrade-pip → install → verify → complete*- * Closing the modal mid-install (X button or backdrop click) terminates the- * EventSource, which the server interprets as a cancel and SIGTERMs pip.+ * Closing the modal mid-install (X button or backdrop click) aborts the fetch+ * stream, which the server interprets as a cancel and SIGTERMs pip.*/import { useEffect, useState } from 'react';@@ -28,14 +28,14 @@ const STAGE_INDEX = Object.fromEntries(STAGES.map((s, i) => [s.id, i]));export default function Flux2InstallModal({ open, onClose, onComplete }) {const [confirmingCancel, setConfirmingCancel] = useState(false);- // The shared install-stream hook owns the EventSource lifecycle, log+ // The shared install-stream hook owns the fetch-stream lifecycle, log// accumulation, stage tracking, connection-lost handling and auto-scroll.// onComplete is ref-stashed inside the hook so ImageGen's frequent state// churn (gallery, generating, localProgress) can't kill the install// mid-stream by re-running the effect.const { logs, currentStage, done, error, logsEndRef, close } = useInstallStream('/api/image-gen/setup/flux2-install',- { enabled: open, onComplete },+ { enabled: open, onComplete, method: 'POST' },);// Reset the cancel-confirm prompt whenever the modal closes, so a reopendiff --git a/client/src/components/imageGen/Flux2InstallModal.test.jsx b/client/src/components/imageGen/Flux2InstallModal.test.jsxindex 3272db33e4..75a4cc2951 100644--- a/client/src/components/imageGen/Flux2InstallModal.test.jsx+++ b/client/src/components/imageGen/Flux2InstallModal.test.jsx@@ -50,5 +50,9 @@ describe('Flux2InstallModal failure footer', () => {render(<Flux2InstallModal open onClose={vi.fn()} onComplete={vi.fn()} />);expect(screen.queryByRole('button', { name: /queue agent to investigate/i })).toBeNull();expect(screen.getByRole('button', { name: /^done$/i })).toBeTruthy();+ expect(useInstallStream).toHaveBeenCalledWith(+ '/api/image-gen/setup/flux2-install',+ expect.objectContaining({ method: 'POST' }),+ );});});diff --git a/client/src/components/install/MidiInstallModal.jsx b/client/src/components/install/MidiInstallModal.jsxindex 2a0ea94948..b629433b21 100644--- a/client/src/components/install/MidiInstallModal.jsx+++ b/client/src/components/install/MidiInstallModal.jsx@@ -16,6 +16,7 @@ export default function MidiInstallModal({ open, onClose, onComplete }) {runtime="muscriptor"label="MuScriptor (MIDI transcription)"installUrlBase="/api/midi-runtime/install"+ streamMethod="POST"description="Installing the MuScriptor runtime and Python packages (large download on first run)…"onClose={onClose}onComplete={onComplete}diff --git a/client/src/components/install/RuntimeInstallModal.jsx b/client/src/components/install/RuntimeInstallModal.jsxindex ae721749ec..3fe978043b 100644--- a/client/src/components/install/RuntimeInstallModal.jsx+++ b/client/src/components/install/RuntimeInstallModal.jsx@@ -32,9 +32,9 @@ export default function RuntimeInstallModal({// (e.g. TRELLIS.2's `repair=1`, which re-runs setup.sh over an existing install// to rebuild backends that failed to compile the first time — #2952).params,- // EventSource is GET-only. Installers that mutate host state use POST via the- // hook's fetch-stream mode so a dropped connection cannot auto-retry work.- streamMethod = 'GET',+ // Runtime actions mutate host state, so the shared default uses POST via the+ // hook's fetch-stream mode. GET installer URLs remain read-only status aliases.+ streamMethod = 'POST',// Chatty installers keep the rendered log stable by batching lines.flushMs = 100,// The footer line once the stream completes. Defaults to "is ready", which isdiff --git a/client/src/components/install/RuntimeInstallModal.test.jsx b/client/src/components/install/RuntimeInstallModal.test.jsxindex a888fa7606..9c4e301c15 100644--- a/client/src/components/install/RuntimeInstallModal.test.jsx+++ b/client/src/components/install/RuntimeInstallModal.test.jsx@@ -51,6 +51,10 @@ describe('RuntimeInstallModal failure footer', () => {useInstallStream.mockReturnValue(streamState());render(<RuntimeInstallModal open runtime="trellis2" label="TRELLIS.2" onClose={vi.fn()} />);expect(screen.queryByRole('button', { name: /queue agent to investigate/i })).toBeNull();+ expect(useInstallStream).toHaveBeenCalledWith(+ expect.stringContaining('/api/video-gen/setup/runtime-install'),+ expect.objectContaining({ method: 'POST' }),+ );});it('queues a CoS task carrying the failing stage, error and log tail, targeting PortOS itself', async () => {diff --git a/client/src/components/models/Image3dRuntimes.jsx b/client/src/components/models/Image3dRuntimes.jsxindex 43190c2d99..2304e4a50d 100644--- a/client/src/components/models/Image3dRuntimes.jsx+++ b/client/src/components/models/Image3dRuntimes.jsx@@ -204,6 +204,7 @@ export default function Image3dRuntimes() {runtime={installTarget?.id}label={installTarget?.label}installUrlBase={installTarget ? `/api/image-to-3d/targets/${installTarget.id}/install` : undefined}+ streamMethod="POST"// Repairing an already-installed target must re-run its setup rather than// short-circuit on "already installed" — that re-run is what rebuilds whatever// was missing (TRELLIS.2's Metal backends, Pixal3D's NATTEN kernels) now thatdiff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsxindex 43c8cce1aa..2171f9bd1b 100644--- a/client/src/components/music/MusicGenPanel.jsx+++ b/client/src/components/music/MusicGenPanel.jsx@@ -761,6 +761,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artistruntime={runtimeInstallEngine?.id}label={runtimeInstallEngine?.name}installUrlBase="/api/music/setup/runtime-install"+ streamMethod="POST"description="Installing the music runtime and python packages. Large downloads may take several minutes."onClose={handleRuntimeInstallClose}/>diff --git a/client/src/components/settings/LocalSetupPanel.jsx b/client/src/components/settings/LocalSetupPanel.jsxindex 619aed83fe..84603f4150 100644--- a/client/src/components/settings/LocalSetupPanel.jsx+++ b/client/src/components/settings/LocalSetupPanel.jsx@@ -79,7 +79,7 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPackreturn () => clearTimeout(t);}, [pythonPath, refreshCheck]);- // The shared install-stream hook owns the EventSource lifecycle, log+ // The shared install-stream hook owns the fetch-stream lifecycle, log// accumulation (capped at the same 200 lines as before), connection-lost// handling, unmount teardown, and auto-scroll.const {@@ -91,6 +91,7 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPacklogsEndRef,} = useInstallStream(installUrl, {maxLogLines: 200,+ method: 'POST',onComplete: () => {toast.success('Packages installed');refreshCheck(pythonPath);diff --git a/client/src/components/settings/LocalSetupPanel.test.jsx b/client/src/components/settings/LocalSetupPanel.test.jsxindex 322de5236c..ce6cc65df5 100644--- a/client/src/components/settings/LocalSetupPanel.test.jsx+++ b/client/src/components/settings/LocalSetupPanel.test.jsx@@ -65,5 +65,9 @@ describe('LocalSetupPanel install failure', () => {renderPanel();await waitFor(() => expect(screen.getByText(/install 1 missing package/i)).toBeTruthy());expect(screen.queryByRole('button', { name: /queue agent to investigate/i })).toBeNull();+ expect(useInstallStream).toHaveBeenCalledWith(+ null,+ expect.objectContaining({ method: 'POST' }),+ );});});diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex b29b661042..08d914c7ee 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -1215,6 +1215,27 @@ describe('Image Gen Routes', () => {});});+ describe('FLUX.2 installer contract', () => {+ it('GET /setup/flux2-install reports status without starting an install', async () => {+ const { installFlux2Venv, isFlux2VenvHealthy } = await import('../lib/pythonSetup.js');+ isFlux2VenvHealthy.mockResolvedValueOnce(false);+ const response = await request(app).get('/api/image-gen/setup/flux2-install');+ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({+ venvInstalled: false,+ expectedVenvPath: '/fake/flux2-venv',+ });+ expect(installFlux2Venv).not.toHaveBeenCalled();+ });++ it('POST /setup/flux2-install keeps the existing SSE completion contract', async () => {+ const response = await request(app).post('/api/image-gen/setup/flux2-install');+ expect(response.status).toBe(200);+ expect(response.text).toContain('"type":"complete"');+ expect(response.text).toContain('Already installed');+ });+ });+describe('GET /setup/check (cache behavior)', () => {// Each test uses a unique pythonPath so the module-scope cache from one// test doesn't bleed into the next (vi.clearAllMocks() resets call counts@@ -1282,14 +1303,23 @@ describe('Image Gen Routes', () => {expect(probePythonHealth).toHaveBeenCalledTimes(2);});- it('GET /setup/install completion invalidates the cache for that pythonPath', async () => {+ it('GET /setup/install reports setup status without starting pip', async () => {+ const { installPackages } = await import('../lib/pythonSetup.js');+ const p = '/usr/bin/python3-install-status-test';+ const status = await request(app).get(`/api/image-gen/setup/install?pythonPath=${encodeURIComponent(p)}&packages=mflux`);+ expect(status.status).toBe(200);+ expect(status.body).toMatchObject({ installed: ['mflux', 'mlx'], missing: [] });+ expect(installPackages).not.toHaveBeenCalled();+ });++ it('POST /setup/install completion invalidates the cache for that pythonPath', async () => {const p = '/usr/bin/python3-install-bust-test';// Warm cache.await request(app).get(`/api/image-gen/setup/check?pythonPath=${encodeURIComponent(p)}`);expect(probePythonHealth).toHaveBeenCalledTimes(1);// Run install (mocked installPackages resolves immediately).- const installRes = await request(app).get(`/api/image-gen/setup/install?pythonPath=${encodeURIComponent(p)}&packages=mflux`);+ const installRes = await request(app).post(`/api/image-gen/setup/install?pythonPath=${encodeURIComponent(p)}&packages=mflux`);expect(installRes.status).toBe(200);// The next /setup/check must re-probe — the install just changed the@@ -1299,6 +1329,39 @@ describe('Image Gen Routes', () => {expect(probePythonHealth).toHaveBeenCalledTimes(2);});+ it('POST /setup/install rejects invalid packages with the standard error envelope', async () => {+ const p = '/usr/bin/python3-install-validation-test';+ const response = await request(app).post(`/api/image-gen/setup/install?pythonPath=${encodeURIComponent(p)}&packages=not-allowed`);+ expect(response.status).toBe(400);+ expect(response.body).toMatchObject({+ code: 'INSTALL_PACKAGE_NOT_ALLOWED',+ error: expect.stringContaining('not-allowed'),+ });+ expect(response.body.timestamp).toEqual(expect.any(Number));+ });++ it('single-flights package installs per interpreter without treating a completed POST body as a disconnect', async () => {+ const { installPackages } = await import('../lib/pythonSetup.js');+ let finishInstall;+ const pending = new Promise((resolve) => { finishInstall = resolve; });+ const kill = vi.fn();+ installPackages.mockReturnValueOnce({ promise: pending, kill });+ const p = '/usr/bin/python3-install-single-flight-test';+ const url = `/api/image-gen/setup/install?pythonPath=${encodeURIComponent(p)}&packages=mflux`;++ const first = request(app).post(url).then((response) => response);+ await vi.waitFor(() => expect(installPackages).toHaveBeenCalledTimes(1));+ expect(kill).not.toHaveBeenCalled();++ const second = await request(app).post(url);+ expect(second.text).toContain('Another package install is already running');+ expect(installPackages).toHaveBeenCalledTimes(1);++ finishInstall({ ok: true, code: 0 });+ expect((await first).status).toBe(200);+ expect(kill).not.toHaveBeenCalled();+ });+it('write path sweeps expired entries so long-running processes do not accumulate', async () => {vi.useFakeTimers({ shouldAdvanceTime: true });try {diff --git a/server/routes/imageGenSetup.js b/server/routes/imageGenSetup.jsindex 03a27e7eb4..bc793eb5e8 100644--- a/server/routes/imageGenSetup.js+++ b/server/routes/imageGenSetup.js@@ -24,7 +24,7 @@ import {resolveFlux2Python, FLUX2_VENV_DEFAULT, installFlux2Venv, isFlux2VenvHealthy,} from '../lib/pythonSetup.js';import { PATHS } from '../lib/fileUtils.js';-import { openSseStream } from '../lib/sseDownload.js';+import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';import { getSetupCheck, invalidateSetupCheck, REQUIRED_PIP_NAMES } from '../services/imageGen/setup.js';const router = Router();@@ -36,7 +36,7 @@ router.get('/python', asyncHandler(async (_req, res) => {// SSE-driven FLUX.2 venv bootstrap. Replaces the "drop to a shell and run// INSTALL_FLUX2=1 bash scripts/setup-image-video.sh" friction with an in-app-// install: the client opens an EventSource, gets staged progress events+// install: the client opens a POST fetch stream, gets staged progress events// (detect → venv → upgrade-pip → install → verify), and either finishes or// surfaces a clear error. Runs the install logic in-process via// installFlux2Venv() so we get structured `stage` events the UI can animate@@ -47,7 +47,37 @@ router.get('/python', asyncHandler(async (_req, res) => {// gate the second click — the first install hasn't created the python yet.let flux2InstallInFlight = null;-router.get('/flux2-install', asyncHandler(async (req, res) => {+async function flux2Status(req) {+ const [token, healthy] = await Promise.all([getHfToken(), isFlux2VenvHealthy()]);+ const venvPython = resolveFlux2Python();+ // The 9B (bf16) and 4B variants ship as separately-gated repos with+ // distinct HF license URLs. Use the active model's `licenseUrl` when the+ // client supplies a `modelId`; fall back to the 4B URL for callers that+ // pre-date the multi-variant registry.+ const FLUX2_DEFAULT_LICENSE = 'https://huggingface.co/black-forest-labs/FLUX.2-klein-4B';+ let licenseUrl = FLUX2_DEFAULT_LICENSE;+ if (typeof req.query?.modelId === 'string' && req.query.modelId.length > 0) {+ const model = getImageModels().find((candidate) => candidate.id === req.query.modelId);+ if (isFlux2(model) && typeof model?.licenseUrl === 'string' && model.licenseUrl.length > 0) {+ licenseUrl = model.licenseUrl;+ }+ }+ return {+ hfTokenPresent: !!token,+ venvInstalled: healthy,+ venvPath: venvPython,+ expectedVenvPath: FLUX2_VENV_DEFAULT,+ licenseUrl,+ };+}++const sendFlux2Status = async (req, res) => res.json(await flux2Status(req));++// Backward-compatible read surface. GET reports the same readiness payload as+// /flux2-status and never starts the multi-GB installer.+router.get('/flux2-install', asyncHandler(sendFlux2Status));++router.post('/flux2-install', asyncHandler(async (req, res) => {const { send, safeEnd } = openSseStream(res);// Skip only when the venv binary AND the import work — a half-broken venv@@ -87,36 +117,14 @@ router.get('/flux2-install', asyncHandler(async (req, res) => {// Cancel the install if the client navigates away mid-bootstrap. A torch// install is a multi-GB download and would otherwise keep running invisibly.- req.on('close', () => { installLog.cancel(); kill(); safeEnd(); });+ onClientDisconnect(req, res, () => { installLog.cancel(); kill(); safeEnd(); });}));// Used by the FLUX.2 model picker: surface a banner when the gated repo's// license hasn't been accepted (HF_TOKEN missing) and the runner is set up.// `venvInstalled` reflects functional health (binary AND packages import) —// a half-broken venv would otherwise hide the install banner forever.-router.get('/flux2-status', asyncHandler(async (req, res) => {- const [token, healthy] = await Promise.all([getHfToken(), isFlux2VenvHealthy()]);- const venvPython = resolveFlux2Python();- // The 9B (bf16) and 4B variants ship as separately-gated repos with- // distinct HF license URLs. Use the active model's `licenseUrl` when the- // client supplies a `modelId`; fall back to the 4B URL for callers that- // pre-date the multi-variant registry.- const FLUX2_DEFAULT_LICENSE = 'https://huggingface.co/black-forest-labs/FLUX.2-klein-4B';- let licenseUrl = FLUX2_DEFAULT_LICENSE;- if (typeof req.query?.modelId === 'string' && req.query.modelId.length > 0) {- const model = getImageModels().find((m) => m.id === req.query.modelId);- if (isFlux2(model) && typeof model?.licenseUrl === 'string' && model.licenseUrl.length > 0) {- licenseUrl = model.licenseUrl;- }- }- res.json({- hfTokenPresent: !!token,- venvInstalled: healthy,- venvPath: venvPython,- expectedVenvPath: FLUX2_VENV_DEFAULT,- licenseUrl,- });-}));+router.get('/flux2-status', asyncHandler(sendFlux2Status));// Generic HF-token presence check for legacy mflux runners that don't need// the FLUX.2 venv. Any model entry with `requiresHfToken: true` in@@ -155,13 +163,18 @@ router.delete('/hf-token', asyncHandler(async (_req, res) => {const checkSchema = z.object({ pythonPath: z.string().min(1) });-router.get('/check', asyncHandler(async (req, res) => {+const sendSetupCheck = async (req, res) => {const { pythonPath } = validateRequest(checkSchema, req.query);if (!isAllowedPython(pythonPath)) {- throw new ServerError('pythonPath must be a python interpreter (basename python/python3/python3.NN)', { status: 400 });+ throw new ServerError('pythonPath must be a python interpreter (basename python/python3/python3.NN)', {+ status: 400,+ code: 'INVALID_PYTHON_PATH',+ });}res.json(await getSetupCheck(pythonPath));-}));+};++router.get('/check', asyncHandler(sendSetupCheck));const venvSchema = z.object({basePython: z.string().min(1).optional(),@@ -192,23 +205,28 @@ const installSchema = z.object({packages: z.array(z.string().min(1)).min(1).max(40),});-// EventSource consumers re-run /setup/check on `complete` to refresh status.-router.get('/install', (req, res) => {+// Backward-compatible read surface for stale installer URLs. It returns the+// same setup status as /check and never starts pip.+router.get('/install', asyncHandler(sendSetupCheck));++// Fetch-stream consumers re-run /setup/check on `complete` to refresh status.+const packageInstallsInFlight = new Map();+router.post('/install', asyncHandler(async (req, res) => {const pythonPath = req.query.pythonPath;const packages = String(req.query.packages || '').split(',').filter(Boolean);- const parsed = installSchema.safeParse({ pythonPath, packages });- if (!parsed.success) {- res.writeHead(400, { 'Content-Type': 'application/json' });- return res.end(JSON.stringify({ error: parsed.error.message }));- }- if (!isAllowedPython(parsed.data.pythonPath)) {- res.writeHead(400, { 'Content-Type': 'application/json' });- return res.end(JSON.stringify({ error: 'pythonPath must be a python interpreter' }));+ const input = validateRequest(installSchema, { pythonPath, packages });+ if (!isAllowedPython(input.pythonPath)) {+ throw new ServerError('pythonPath must be a python interpreter', {+ status: 400,+ code: 'INVALID_PYTHON_PATH',+ });}- const disallowed = parsed.data.packages.filter((p) => !REQUIRED_PIP_NAMES.has(p));+ const disallowed = input.packages.filter((p) => !REQUIRED_PIP_NAMES.has(p));if (disallowed.length) {- res.writeHead(400, { 'Content-Type': 'application/json' });- return res.end(JSON.stringify({ error: `Packages not in allowlist: ${disallowed.join(', ')}` }));+ throw new ServerError(`Packages not in allowlist: ${disallowed.join(', ')}`, {+ status: 400,+ code: 'INSTALL_PACKAGE_NOT_ALLOWED',+ });}// `send` and `safeEnd` from openSseStream no-op once the response has ended@@ -217,21 +235,29 @@ router.get('/install', (req, res) => {const { send, safeEnd } = openSseStream(res);// Server-console visibility for the (multi-GB) local pip install — the SSE// stream otherwise surfaces progress only in the browser.- const installLog = createInstallLogger({ installer: 'Image Gen packages', target: parsed.data.pythonPath });+ const installLog = createInstallLogger({ installer: 'Image Gen packages', target: input.pythonPath });const emit = (ev) => { installLog.onEvent(ev); send(ev); };+ if (packageInstallsInFlight.has(input.pythonPath)) {+ send({ type: 'error', message: `Another package install is already running for ${input.pythonPath}. Wait for it to finish or restart PortOS.` });+ return safeEnd();+ }installLog.start();- const { promise, kill } = installPackages(parsed.data.pythonPath, parsed.data.packages, emit);- promise.then(() => {- // Drop the now-stale setup-check snapshot before the client re-runs the- // probe on `complete` — without this it would read the pre-install- // missing-packages list back from cache.- invalidateSetupCheck(parsed.data.pythonPath);- safeEnd();- });+ const { promise, kill } = installPackages(input.pythonPath, input.packages, emit);+ packageInstallsInFlight.set(input.pythonPath, promise);+ promise+ .catch((err) => emit({ type: 'error', message: err?.message || 'Unknown installer failure' }))+ .finally(() => {+ packageInstallsInFlight.delete(input.pythonPath);+ // Drop the now-stale setup-check snapshot before the client re-runs the+ // probe on `complete` — without this it would read the pre-install+ // missing-packages list back from cache.+ invalidateSetupCheck(input.pythonPath);+ safeEnd();+ });// Client navigation away should kill pip — a torch upgrade can run for// 10+ minutes and would otherwise keep going invisibly.- req.on('close', () => { installLog.cancel(); kill(); safeEnd(); });-});+ onClientDisconnect(req, res, () => { installLog.cancel(); kill(); safeEnd(); });+}));export default router;diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex 159ff86b03..1b02ae7804 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -23,7 +23,7 @@ import {SUBJECT_SCALE_MIN_EXCLUSIVE, SUBJECT_SCALE_MAX,} from '../services/imageTo3d/renderOptions.js';import { createInstallLogger } from '../lib/installLogger.js';-import { openSseStream } from '../lib/sseDownload.js';+import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';const router = Router();@@ -75,45 +75,59 @@ const installsInFlight = new Set();* target's adapter (`services/imageTo3d/adapters.js`) — adding a target needs no* new branch here.*/+const annotateTargetStatus = async (target) => {+ const adapter = getTargetAdapter(target.id);+ const installed = adapter ? adapter.isInstalled() : null;+ // An installed target can still be silently degraded (e.g. TRELLIS.2's Metal+ // texture bake — #2952); a target's adapter opts into reporting that via+ // `describeInstallState()`. Only probed once installed — there is nothing to+ // report before then.+ const state = installed && adapter?.describeInstallState ? await adapter.describeInstallState() : null;+ return { ...target, installed, ...state?.fields };+};+router.get('/targets', asyncHandler(async (_req, res) => {const capabilities = await detectHostCapabilities();- const targets = await Promise.all(listTargets(capabilities).map(async (target) => {- const adapter = getTargetAdapter(target.id);- const installed = adapter ? adapter.isInstalled() : null;- // An installed target can still be silently degraded (e.g. TRELLIS.2's Metal- // texture bake — #2952); a target's adapter opts into reporting that via- // `describeInstallState()`. Only probed once installed — there is nothing to- // report before then.- const state = installed && adapter?.describeInstallState ? await adapter.describeInstallState() : null;- return { ...target, installed, ...state?.fields };- }));+ const targets = await Promise.all(listTargets(capabilities).map(annotateTargetStatus));res.json({ capabilities, targets });}));+const requireInstallableTarget = (targetId) => {+ const target = getTarget(targetId);+ const adapter = getTargetAdapter(targetId);+ if (!target || !adapter?.install) {+ throw new ServerError(`Unknown or non-installable image-to-3D target: ${targetId}`, {+ status: 400,+ code: 'IMAGE_TO_3D_TARGET_NOT_INSTALLABLE',+ });+ }+ return { target, adapter };+};++const sendTargetInstallStatus = async (targetId, res) => {+ requireInstallableTarget(targetId);+ const capabilities = await detectHostCapabilities();+ const target = listTargets(capabilities).find((candidate) => candidate.id === targetId) || getTarget(targetId);+ res.json({ capabilities, target: await annotateTargetStatus(target) });+};++const installQuerySchema = z.object({ repair: z.enum(['0', '1']).optional() });+/*** SSE-driven target install/repair, shared by every registered target. The- * client opens an EventSource and gets staged progress (`stage` → `log` →+ * client opens a POST fetch stream and gets staged progress (`stage` → `log` →* `complete` / `error`) while the target's adapter installs. Gated on hardware* support and single-flighted per target; killed if the client navigates away.* Only fires the real install on this explicit user request — never from boot* (AGENTS.md no-cold-bootstrap policy). Mirrors imageGenSetup.js's `/flux2-install`.*/-async function handleTargetInstall(targetId, req, res) {+async function handleTargetInstall(targetId, target, adapter, repair, req, res) {const { send, safeEnd } = openSseStream(res);- const target = getTarget(targetId);- const adapter = getTargetAdapter(targetId);- if (!target || !adapter?.install) {- send({ type: 'error', message: `Unknown or non-installable image-to-3D target: ${targetId}` });- return safeEnd();- }-// `repair=1` re-runs setup over an existing install. That is the documented fix// for a degraded install (e.g. TRELLIS.2's Metal texture bake — #2952): without// it, "Repair install" would hit the already-installed short-circuit below and// do nothing.- const repair = req.query.repair === '1';-if (adapter.isInstalled() && !repair) {send({ type: 'stage', stage: 'verify', message: `${target.label} already installed.` });// "Installed" is not the same as "installed well" — surface any adapter@@ -176,7 +190,7 @@ async function handleTargetInstall(targetId, req, res) {slotReleased = true;installsInFlight.delete(targetId);};- req.on('close', () => {+ onClientDisconnect(req, res, () => {aborted = true;installLog.cancel();// `close` also fires on normal completion; only a live handle means an@@ -249,11 +263,26 @@ async function handleTargetInstall(targetId, req, res) {});}-router.get('/targets/:targetId/install', asyncHandler((req, res) => handleTargetInstall(req.params.targetId, req, res)));+router.get('/targets/:targetId/install', asyncHandler(async (req, res) => {+ await sendTargetInstallStatus(req.params.targetId, res);+}));++router.post('/targets/:targetId/install', asyncHandler(async (req, res) => {+ const { target, adapter } = requireInstallableTarget(req.params.targetId);+ const { repair } = validateRequest(installQuerySchema, req.query);+ await handleTargetInstall(req.params.targetId, target, adapter, repair === '1', req, res);+}));// Compatibility alias for the pre-#3080 TRELLIS.2-specific install URL — existing// client bookmarks/links keep working.-router.get('/trellis2/install', asyncHandler((req, res) => handleTargetInstall('trellis2', req, res)));+router.get('/trellis2/install', asyncHandler(async (_req, res) => {+ await sendTargetInstallStatus('trellis2', res);+}));+router.post('/trellis2/install', asyncHandler(async (req, res) => {+ const { target, adapter } = requireInstallableTarget('trellis2');+ const { repair } = validateRequest(installQuerySchema, req.query);+ await handleTargetInstall('trellis2', target, adapter, repair === '1', req, res);+}));// ── Image-to-3D model records ─────────────────────────────────────────────// Namespaced under /models so `/:id` never shadows the `/targets` anddiff --git a/server/routes/imageTo3d.test.js b/server/routes/imageTo3d.test.jsindex bc277bd7d0..6e68f59634 100644--- a/server/routes/imageTo3d.test.js+++ b/server/routes/imageTo3d.test.js@@ -274,10 +274,27 @@ describe('image-to-3d routes', () => {});});-describe('GET /trellis2/install (SSE)', () => {+describe('POST /trellis2/install (SSE)', () => {+ it('keeps both GET install URLs read-only and returns target status', async () => {+ trellis2.installTrellis2.mockClear();+ trellis2.isTrellis2Installed.mockReturnValue(false);+ const canonical = await request(makeApp()).get('/api/image-to-3d/targets/trellis2/install');+ const legacy = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ expect(canonical.status).toBe(200);+ expect(canonical.body.target).toMatchObject({ id: 'trellis2', installed: false });+ expect(legacy.body.target).toMatchObject({ id: 'trellis2', installed: false });+ expect(trellis2.installTrellis2).not.toHaveBeenCalled();+ });++ it('streams the canonical POST target install route', async () => {+ trellis2.isTrellis2Installed.mockReturnValueOnce(false);+ const res = await request(makeApp()).post('/api/image-to-3d/targets/trellis2/install');+ expect(sseFrames(res.text).at(-1)).toMatchObject({ type: 'complete' });+ });+it('streams stage → complete on the happy path', async () => {trellis2.isTrellis2Installed.mockReturnValueOnce(false);- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');const frames = sseFrames(res.text);expect(frames).toContainEqual({ type: 'stage', stage: 'clone', message: 'git clone …' });expect(frames.at(-1)).toMatchObject({ type: 'complete' });@@ -292,7 +309,7 @@ describe('GET /trellis2/install (SSE)', () => {trellis2.probeMetalToolchain.mockResolvedValueOnce({available: false, installable: true, hint: 'it will be downloaded',});- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');expect(trellis2.installTrellis2).toHaveBeenCalledWith(expect.objectContaining({ installMetalToolchain: true }),);@@ -307,7 +324,7 @@ describe('GET /trellis2/install (SSE)', () => {trellis2.probeMetalToolchain.mockResolvedValueOnce({available: false, installable: false, blocker: 'requires-xcode', hint: 'install Xcode',});- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');expect(sseFrames(res.text).find((f) => f.stage === 'preflight')?.message).toContain('install Xcode');// A warning, not a refusal — geometry is unaffected — and no step that would fail.expect(trellis2.installTrellis2).toHaveBeenCalledWith(@@ -318,7 +335,7 @@ describe('GET /trellis2/install (SSE)', () => {it('adds no toolchain step or warning when it is already present', async () => {trellis2.installTrellis2.mockClear();trellis2.isTrellis2Installed.mockReturnValueOnce(false);- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');expect(sseFrames(res.text).find((f) => f.stage === 'preflight')).toBeUndefined();expect(trellis2.installTrellis2).toHaveBeenCalledWith(expect.objectContaining({ installMetalToolchain: false }),@@ -330,7 +347,7 @@ describe('GET /trellis2/install (SSE)', () => {// existing install once the Metal Toolchain is present (#2952).trellis2.installTrellis2.mockClear();trellis2.isTrellis2Installed.mockReturnValueOnce(true);- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install?repair=1');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install?repair=1');expect(trellis2.installTrellis2).toHaveBeenCalled();expect(sseFrames(res.text).at(-1)).toMatchObject({ type: 'complete' });});@@ -340,7 +357,7 @@ describe('GET /trellis2/install (SSE)', () => {trellis2.probeTrellis2TextureBake.mockResolvedValueOnce({quality: 'fallback', missing: ['mtldiffrast'], degradedQuality: [], modules: {}, help: 'repair me',});- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');const frames = sseFrames(res.text);const warning = frames.find((f) => f.stage === 'verify' && f.type === 'log')?.message;expect(warning).toContain('repair me');@@ -356,7 +373,7 @@ describe('GET /trellis2/install (SSE)', () => {// not just whatever the server process happened to be launched with.trellis2.installTrellis2.mockClear();trellis2.isTrellis2Installed.mockReturnValueOnce(false);- await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ await request(makeApp()).post('/api/image-to-3d/trellis2/install');expect(trellis2.installTrellis2).toHaveBeenCalledWith(expect.objectContaining({env: expect.objectContaining({ HF_TOKEN: 'hf_test', HUGGINGFACE_HUB_TOKEN: 'hf_test' }),}));@@ -368,7 +385,7 @@ describe('GET /trellis2/install (SSE)', () => {trellis2.installTrellis2.mockClear();trellis2.isTrellis2Installed.mockReturnValueOnce(false);hfChildEnv.mockRejectedValueOnce(new Error('settings.json is not valid JSON'));- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');const frames = sseFrames(res.text);expect(frames.at(-1)).toMatchObject({type: 'error',@@ -381,7 +398,7 @@ describe('GET /trellis2/install (SSE)', () => {it('short-circuits with complete when already installed (no install spawned)', async () => {trellis2.installTrellis2.mockClear();trellis2.isTrellis2Installed.mockReturnValueOnce(true);- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');const frames = sseFrames(res.text);expect(frames.at(-1)).toMatchObject({ type: 'complete', message: expect.stringMatching(/already/i) });expect(trellis2.installTrellis2).not.toHaveBeenCalled();@@ -396,7 +413,7 @@ describe('GET /trellis2/install (SSE)', () => {)),kill: vi.fn(),}));- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');const frames = sseFrames(res.text);expect(frames.at(-1)).toMatchObject({type: 'error',@@ -414,7 +431,7 @@ describe('GET /trellis2/install (SSE)', () => {)),kill: vi.fn(),}));- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');const frames = sseFrames(res.text);expect(frames.at(-1)).toMatchObject({ type: 'error', message: expect.stringMatching(/exited 1$/) });expect(frames.at(-1).message).not.toMatch(/network hiccup/i);@@ -424,7 +441,7 @@ describe('GET /trellis2/install (SSE)', () => {trellis2.installTrellis2.mockClear();trellis2.isTrellis2Installed.mockReturnValueOnce(false);targets.unavailableReason.mockReturnValueOnce('requires-apple-silicon');- const res = await request(makeApp()).get('/api/image-to-3d/trellis2/install');+ const res = await request(makeApp()).post('/api/image-to-3d/trellis2/install');const frames = sseFrames(res.text);// The human label, not the raw kebab-case reason code (#3579).expect(frames.at(-1)).toMatchObject({ type: 'error', message: expect.stringMatching(/Requires an Apple Silicon Mac/) });diff --git a/server/routes/midiRuntime.js b/server/routes/midiRuntime.jsindex c5c0c827ae..62435906d3 100644--- a/server/routes/midiRuntime.js+++ b/server/routes/midiRuntime.js@@ -1,7 +1,8 @@/*** MuScriptor (audio → MIDI transcription) runtime installer.*- * GET /api/midi-runtime/install → SSE stream of the venv install+ * GET /api/midi-runtime/install → JSON runtime status+ * POST /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-@@ -19,7 +20,7 @@ import { existsSync } from 'fs';import { asyncHandler } from '../lib/errorHandler.js';import { createLineReader } from '../lib/streamLines.js';import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';-import { openSseStream } from '../lib/sseDownload.js';+import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';import { createInstallLogger } from '../lib/installLogger.js';import {resolveMuscriptorPython,@@ -38,7 +39,18 @@ const MUSCRIPTOR_INSTALL_ENV = 'INSTALL_MUSCRIPTOR';// venv dir. The existsSync gate can't help before the venv is created.let installInFlight = null;-router.get('/install', asyncHandler(async (req, res) => {+router.get('/install', asyncHandler(async (_req, res) => {+ const installed = await isMuscriptorRuntimeReady();+ res.json({+ runtime: 'muscriptor',+ label: MUSCRIPTOR_LABEL,+ installed,+ pythonPath: installed ? resolveMuscriptorPython() : null,+ expectedVenvPath: MUSCRIPTOR_VENV_DEFAULT,+ });+}));++router.post('/install', asyncHandler(async (req, res) => {const { send, safeEnd } = openSseStream(res);// Server-console visibility for the multi-GB install (start / heartbeat /// outcome) — the SSE stream otherwise surfaces progress only in the browser.@@ -62,7 +74,7 @@ router.get('/install', asyncHandler(async (req, res) => {// then spawn a multi-GB installer nobody is listening to — uncancellable, and// holding the singleton until it finished on its own. `child` is a mutable// outer var so this handler kills the process group once it exists.- req.on('close', () => {+ onClientDisconnect(req, res, () => {clientGone = true;installLog.cancel();if (finished) return;diff --git a/server/routes/midiRuntime.test.js b/server/routes/midiRuntime.test.jsindex fa1e6b77d9..3dbe4866b8 100644--- a/server/routes/midiRuntime.test.js+++ b/server/routes/midiRuntime.test.js@@ -28,6 +28,9 @@ vi.mock('../lib/sseDownload.js', () => ({safeEnd: () => { if (!res.writableEnded) res.end(); },};},+ onClientDisconnect: (_req, res, handler) => {+ res.on('close', () => { if (!res.writableEnded) handler(); });+ },}));import { errorMiddleware } from '../lib/errorHandler.js';@@ -48,12 +51,20 @@ describe('midi-runtime routes', () => {py.installed = true;});- it('GET /install completes without spawning when the venv already exists', async () => {+ it('GET /install reports runtime status as JSON', async () => {const r = await request(app).get('/api/midi-runtime/install');expect(r.status).toBe(200);+ expect(r.body).toMatchObject({+ runtime: 'muscriptor',+ installed: true,+ pythonPath: '/home/x/.portos/venv-muscriptor/bin/python3',+ });+ });++ it('POST /install streams completion when the venv already exists', async () => {+ const r = await request(app).post('/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');});});diff --git a/server/routes/music.js b/server/routes/music.jsindex f7b5afaf29..002e06c96d 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -37,7 +37,7 @@ import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } fromimport { listMusicEngineCapabilities } from '../services/musicEngineCapabilities.js';import { describeMusic, writeLyrics } from '../services/musicDesigner.js';import { startHfDownloadStream } from '../services/hfDownloadStream.js';-import { openSseStream } from '../lib/sseDownload.js';+import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';import { createInstallLogger } from '../lib/installLogger.js';import { inspectModelCache } from '../lib/hfCache.js';import { getCudaCapability } from '../lib/cudaCapability.js';@@ -63,13 +63,12 @@ router.get('/engines', asyncHandler(async (_req, res) => {}));// --- Install music runtime venvs --------------------------------------------// Mirrors the image/video in-app setup flow: the client opens an EventSource+// Mirrors the image/video in-app setup flow: the client opens a POST fetch stream// and we shell out to the canonical setup script with the selected engine's// INSTALL_* env var set. Keeping the bash path as the single installer source// avoids a second Node implementation drifting from scripts/setup-image-video.sh.-router.get('/setup/runtime-status', asyncHandler(async (req, res) => {- const runtime = String(req.query?.runtime || '');+const requireMusicEngine = (runtime) => {const engine = ENGINES[runtime];if (!engine) {throw new ServerError(@@ -77,6 +76,12 @@ router.get('/setup/runtime-status', asyncHandler(async (req, res) => {{ status: 400, code: 'UNKNOWN_MUSIC_RUNTIME' },);}+ return engine;+};++const sendRuntimeStatus = async (req, res) => {+ const runtime = String(req.query?.runtime || '');+ const engine = requireMusicEngine(runtime);res.json({runtime: engine.id,label: engine.name,@@ -85,19 +90,23 @@ router.get('/setup/runtime-status', asyncHandler(async (req, res) => {expectedVenvPath: engine.venvDefault,installEnvVar: engine.installEnv,});-}));+};++router.get('/setup/runtime-status', asyncHandler(sendRuntimeStatus));++// Backward-compatible read surface for stale clients and status pollers. GET+// reports readiness only; installing is restricted to the POST route below.+router.get('/setup/runtime-install', asyncHandler(sendRuntimeStatus));const runtimeInstallInFlight = new Map();-router.get('/setup/runtime-install', asyncHandler(async (req, res) => {+router.post('/setup/runtime-install', asyncHandler(async (req, res) => {const runtime = String(req.query?.runtime || '');- const engine = ENGINES[runtime];+ // Validate before flushing SSE headers so callers receive the standard+ // { error, code, timestamp } response for a bad runtime.+ const engine = requireMusicEngine(runtime);const { send, safeEnd } = openSseStream(res);- if (!engine) {- send({ type: 'error', message: `Unknown music runtime: ${runtime}` });- return safeEnd();- }if (runtimeInstallInFlight.has(engine.id)) {send({ type: 'error', message: `Another ${engine.name} install is already running. Wait for it to finish or restart PortOS.` });return safeEnd();@@ -191,7 +200,7 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {}});- req.on('close', () => {+ onClientDisconnect(req, res, () => {if (finished) return;installLog.cancel();stopSetupScript(child);diff --git a/server/routes/music.test.js b/server/routes/music.test.jsindex 7efd2a1c68..c869727101 100644--- a/server/routes/music.test.js+++ b/server/routes/music.test.js@@ -138,6 +138,9 @@ const sse = vi.hoisted(() => ({}));vi.mock('../lib/sseDownload.js', () => ({openSseStream: (res) => sse.open(res),+ onClientDisconnect: (_req, res, handler) => {+ res.on('close', () => { if (!res.writableEnded) handler(); });+ },}));vi.mock('../services/hfDownloadStream.js', () => ({startHfDownloadStream: (args) => sse.run(args),@@ -349,7 +352,7 @@ describe('music routes', () => {});it('refuses MiniMax runtime installation while profile VRAM is unknown', async () => {- const r = await request(app).get('/api/music/setup/runtime-install?runtime=minimax-music3');+ const r = await request(app).post('/api/music/setup/runtime-install?runtime=minimax-music3');expect(r.status).toBe(200);expect(r.text).toContain('VRAM requirement has not been measured');expect(setup.spawn).not.toHaveBeenCalled();@@ -417,21 +420,29 @@ describe('music routes', () => {expect(ready.body.venvPath).toBe('/v/ace/bin/python3');});- it('GET /setup/runtime-install completes without spawning when already installed', async () => {+ it('GET /setup/runtime-install reports status without spawning', async () => {gen.ready = true;const r = await request(app).get('/api/music/setup/runtime-install?runtime=acestep');expect(r.status).toBe(200);- expect(r.text).toContain('"type":"complete"');- expect(r.text).toContain('Already installed');+ expect(r.body).toMatchObject({ runtime: 'acestep', installed: true });+ expect(setup.spawn).not.toHaveBeenCalled();});- it('GET /setup/runtime-install proceeds when the interpreter exists but the venv is broken', async () => {+ it('GET /setup/runtime-install rejects an unknown runtime before opening SSE', async () => {+ const r = await request(app).get('/api/music/setup/runtime-install?runtime=unknown');+ expect(r.status).toBe(400);+ expect(r.body).toMatchObject({ code: 'UNKNOWN_MUSIC_RUNTIME' });+ expect(r.body.timestamp).toEqual(expect.any(Number));+ expect(setup.spawn).not.toHaveBeenCalled();+ });++ it('POST /setup/runtime-install proceeds when the interpreter exists but the venv is broken', async () => {// Regression: a failed install leaves the venv's interpreter behind, so the// old interpreter-exists check short-circuited with "already installed" and// the engine could never be repaired from the UI.gen.ready = true; // resolvePython() finds the leftover interpretergen.healthy = false; // ...but the import probe fails- const r = await request(app).get('/api/music/setup/runtime-install?runtime=acestep');+ const r = await request(app).post('/api/music/setup/runtime-install?runtime=acestep');expect(r.status).toBe(200);expect(r.text).not.toContain('Already installed');expect(r.text).toContain('Starting ACE-Step install.');@@ -448,13 +459,13 @@ describe('music routes', () => {expect(acestep.ready).toBe(false);});- it('GET /setup/runtime-install refuses on a host that can never run the engine', async () => {+ it('POST /setup/runtime-install refuses on a host that can never run the engine', async () => {// Previously the route spawned the setup script, whose own platform guard// printed "Skipping." and exited 0 — surfaced to the user as "installer// exited 0 but the engine is still not available".gen.unsupportedPlatform = 'musicgen';gen.healthy = false;- const r = await request(app).get('/api/music/setup/runtime-install?runtime=musicgen');+ const r = await request(app).post('/api/music/setup/runtime-install?runtime=musicgen');expect(r.status).toBe(200);expect(r.text).toContain('cannot be installed on this host');expect(setup.spawn).not.toHaveBeenCalled();