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

fix: guard installer disconnect probes (#6936)

[._.]/ Adam Eivy7ee4fd50f736
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 08d914c7ee..cc86a01737 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import express from 'express';
-import { pinPlatform, request } from '../lib/testHelper.js';
+import { request as httpRequest } from 'node:http';
+import { pinPlatform, request, startLoopbackServer, closeLoopbackServer } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
@@ -20,6 +21,18 @@ vi.mock('../lib/paths.js', async (importOriginal) =>
makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-imagegen-') }));
afterAll(cleanupTempDataRoots);
+const disconnectLifecycle = vi.hoisted(() => ({ onDisconnect: vi.fn() }));
+vi.mock('../lib/sseDownload.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ onClientDisconnect: (req, res, handler) => actual.onClientDisconnect(req, res, () => {
+ disconnectLifecycle.onDisconnect();
+ handler();
+ }),
+ };
+});
+
import imageGenRoutes from './imageGen.js';
import * as fileUtils from '../lib/fileUtils.js';
import * as regen from '../services/imageGen/regen.js';
@@ -1234,6 +1247,38 @@ describe('Image Gen Routes', () => {
expect(response.text).toContain('"type":"complete"');
expect(response.text).toContain('Already installed');
});
+
+ it('does not start an install after the client disconnects during the health probe', async () => {
+ const { installFlux2Venv, isFlux2VenvHealthy } = await import('../lib/pythonSetup.js');
+ let finishProbe;
+ isFlux2VenvHealthy.mockReturnValueOnce(new Promise((resolve) => { finishProbe = resolve; }));
+ const server = await startLoopbackServer(app);
+ const { port } = server.address();
+ const clientRequest = httpRequest({
+ host: '127.0.0.1',
+ port,
+ path: '/api/image-gen/setup/flux2-install',
+ method: 'POST',
+ });
+ clientRequest.on('error', () => {});
+ clientRequest.end();
+
+ let serverClosed = false;
+ try {
+ await vi.waitFor(() => expect(isFlux2VenvHealthy).toHaveBeenCalled());
+ const closed = new Promise((resolve) => clientRequest.once('close', resolve));
+ clientRequest.destroy();
+ await closed;
+ await vi.waitFor(() => expect(disconnectLifecycle.onDisconnect).toHaveBeenCalled());
+ finishProbe(false);
+ await closeLoopbackServer(server);
+ serverClosed = true;
+ expect(installFlux2Venv).not.toHaveBeenCalled();
+ } finally {
+ finishProbe?.(false);
+ if (!serverClosed) await closeLoopbackServer(server);
+ }
+ });
});
describe('GET /setup/check (cache behavior)', () => {
diff --git a/server/routes/imageGenSetup.js b/server/routes/imageGenSetup.js
index bc793eb5e8..57de6f80e5 100644
--- a/server/routes/imageGenSetup.js
+++ b/server/routes/imageGenSetup.js
@@ -79,6 +79,18 @@ router.get('/flux2-install', asyncHandler(sendFlux2Status));
router.post('/flux2-install', asyncHandler(async (req, res) => {
const { send, safeEnd } = openSseStream(res);
+ let clientGone = false;
+ let installLog = null;
+ let killInstall = null;
+
+ // Register before the health probe: it can take long enough for a client to
+ // leave, and starting the multi-GB install after that would orphan the work.
+ onClientDisconnect(req, res, () => {
+ clientGone = true;
+ installLog?.cancel();
+ killInstall?.();
+ safeEnd();
+ });
// Skip only when the venv binary AND the import work — a half-broken venv
// (binary present, packages missing from a killed mid-install) needs to
@@ -88,6 +100,7 @@ router.post('/flux2-install', asyncHandler(async (req, res) => {
send({ type: 'complete', message: 'Already installed — nothing to do.' });
return safeEnd();
}
+ if (clientGone) return safeEnd();
if (flux2InstallInFlight) {
send({ type: 'error', message: 'Another FLUX.2 install is already running. Wait for it to finish or restart PortOS.' });
return safeEnd();
@@ -95,11 +108,12 @@ router.post('/flux2-install', asyncHandler(async (req, res) => {
// Server-console visibility for the multi-GB torch install (start / stage
// milestones / outcome) — installFlux2Venv streams progress only to `send`.
- const installLog = createInstallLogger({ installer: 'FLUX.2 venv', target: FLUX2_VENV_DEFAULT });
+ installLog = createInstallLogger({ installer: 'FLUX.2 venv', target: FLUX2_VENV_DEFAULT });
const emit = (ev) => { installLog.onEvent(ev); send(ev); };
installLog.start();
const { promise, kill } = installFlux2Venv(emit);
+ killInstall = kill;
flux2InstallInFlight = promise;
promise
// installFlux2Venv resolves { ok:false } on some pip failures without
@@ -114,10 +128,6 @@ router.post('/flux2-install', asyncHandler(async (req, res) => {
flux2InstallInFlight = null;
safeEnd();
});
-
- // Cancel the install if the client navigates away mid-bootstrap. A torch
- // install is a multi-GB download and would otherwise keep running invisibly.
- onClientDisconnect(req, res, () => { installLog.cancel(); kill(); safeEnd(); });
}));
// Used by the FLUX.2 model picker: surface a banner when the gated repo's
diff --git a/server/routes/midiRuntime.test.js b/server/routes/midiRuntime.test.js
index 3dbe4866b8..3f7a6ad046 100644
--- a/server/routes/midiRuntime.test.js
+++ b/server/routes/midiRuntime.test.js
@@ -20,7 +20,8 @@ vi.mock('../lib/pythonSetup.js', () => ({
}));
// Real SSE frames so supertest can read them off the response body.
-vi.mock('../lib/sseDownload.js', () => ({
+vi.mock('../lib/sseDownload.js', async () => ({
+ ...(await vi.importActual('../lib/sseDownload.js')),
openSseStream: (res) => {
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
return {
@@ -28,9 +29,6 @@ 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';
@@ -66,5 +64,6 @@ describe('midi-runtime routes', () => {
expect(r.status).toBe(200);
expect(r.text).toContain('"type":"complete"');
expect(r.text).toContain('Already installed');
+ expect(r.text).toContain('venv-muscriptor');
});
});
diff --git a/server/routes/music.test.js b/server/routes/music.test.js
index c869727101..b82668c2d1 100644
--- a/server/routes/music.test.js
+++ b/server/routes/music.test.js
@@ -136,11 +136,9 @@ const sse = vi.hoisted(() => ({
};
}),
}));
-vi.mock('../lib/sseDownload.js', () => ({
+vi.mock('../lib/sseDownload.js', async () => ({
+ ...(await vi.importActual('../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),
@@ -428,6 +426,16 @@ describe('music routes', () => {
expect(setup.spawn).not.toHaveBeenCalled();
});
+ it('POST /setup/runtime-install completes without spawning when already installed', async () => {
+ gen.ready = true;
+ gen.healthy = true;
+ const r = await request(app).post('/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(setup.spawn).not.toHaveBeenCalled();
+ });
+
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);