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: make video runtime installs POST-only (#4895)

Adam Eivyc425ebb63674
diff --git a/client/src/pages/VideoGen.composeWhileBusy.test.jsx b/client/src/pages/VideoGen.composeWhileBusy.test.jsx
index cce9ff7334..3176b1b780 100644
--- a/client/src/pages/VideoGen.composeWhileBusy.test.jsx
+++ b/client/src/pages/VideoGen.composeWhileBusy.test.jsx
@@ -125,7 +125,9 @@ vi.mock('../components/media/PromptFromMedia', () => ({
vi.mock('../components/Drawer', () => ({ default: () => null }));
vi.mock('../components/settings/ImageGenTab', () => ({ ImageGenTab: () => null }));
vi.mock('../components/settings/LocalSetupPanel', () => ({ default: () => null }));
-vi.mock('../components/install/RuntimeInstallModal', () => ({ default: () => null }));
+vi.mock('../components/install/RuntimeInstallModal', () => ({
+ default: ({ streamMethod }) => <div data-testid="runtime-install-modal" data-stream-method={streamMethod} />,
+}));
vi.mock('../components/videoGen/FramePanel', () => ({ default: () => null }));
vi.mock('../components/videoGen/KeyframePanel', () => ({ default: () => null }));
vi.mock('../components/videoGen/AudioPanel', () => ({ default: () => null }));
@@ -151,6 +153,18 @@ describe('VideoGen compose-while-busy', () => {
state.eventSourceRef.current = null;
});
+ it('starts runtime installation through the non-idempotent POST stream', async () => {
+ await act(async () => {
+ render(
+ <MemoryRouter initialEntries={['/media/video']}>
+ <VideoGen />
+ </MemoryRouter>,
+ );
+ });
+
+ expect(screen.getByTestId('runtime-install-modal')).toHaveAttribute('data-stream-method', 'POST');
+ });
+
it('leaves Enhance with AI and Prompt from media usable so the next clip can be queued', async () => {
await act(async () => {
render(
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index c0a887e442..a2c7677983 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -1483,6 +1483,7 @@ export default function VideoGen() {
open={installModalOpen}
runtime={byovRuntime}
label={byovStatus?.label}
+ streamMethod="POST"
onClose={() => setInstallModalOpen(false)}
onComplete={() => refreshByovStatus()}
/>
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index c7ee0e1758..948e880db6 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -7,7 +7,6 @@
*/
import { Router } from 'express';
-import { existsSync } from 'fs';
import { basename } from 'path';
import os from 'os';
import { z } from 'zod';
@@ -26,18 +25,11 @@ import {
import { IMAGE_GEN_MODE } from '../services/imageGen/modes.js';
import { getSettings, updateSettingsWith } from '../services/settings.js';
import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';
-import { createLineReader } from '../lib/streamLines.js';
-import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';
import {
listVideoModels,
defaultVideoModelId,
BYOV_RUNTIME_INFO,
- isByovRuntimeInstalled,
isByovRuntimeReady,
- isByovRuntimeCurrent,
- invalidateByovReadyCache,
- invalidateByovLoraCapabilityCache,
- invalidateRuntimeFingerprintCache,
resolveRuntimeFingerprint,
loadHistory,
getHistoryItem,
@@ -68,12 +60,15 @@ import {
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import { saveUploadedGalleryVideo } from '../services/videoUpload.js';
import { JSON_BODY_LIMIT_BYTES } from '../lib/uploadLimits.js';
-import { createInstallLogger } from '../lib/installLogger.js';
import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';
import { collectRemoteInputAssets } from '../services/federatedMedia/inputAssets.js';
import { effectiveJobPrompt } from '../lib/federatedMediaWire.js';
import { isRemoteMediaJob } from '../services/mediaJobQueue/remoteMediaJob.js';
import { buildFederatedMediaRequest } from '../lib/federatedMediaRequest.js';
+import {
+ getVideoRuntimeStatus,
+ streamVideoRuntimeInstall,
+} from '../services/videoGen/runtimeInstaller.js';
const router = Router();
@@ -432,172 +427,26 @@ router.post('/model-terms', asyncHandler(async (req, res) => {
// alone is too permissive: a partial install (clone done, `uv pip install`
// aborted) leaves a venv directory present but no torch, which would
// hide the banner and make every render fail with a deep ImportError.
-router.get('/setup/runtime-status', asyncHandler(async (req, res) => {
+const sendRuntimeStatus = async (req, res) => {
const runtime = String(req.query?.runtime || '');
- const info = BYOV_RUNTIME_INFO[runtime];
- if (!info) {
- // `failValidation` only accepts a Zod safeParse result — calling it with
- // (res, string) would TypeError on `parsed.error.issues.map(...)` and
- // bubble as a 500 instead of the intended 400.
- throw new ServerError(
- `Unknown runtime: ${runtime}. Expected one of: ${Object.keys(BYOV_RUNTIME_INFO).join(', ')}`,
- { status: 400, code: 'UNKNOWN_BYOV_RUNTIME' },
- );
- }
- const binaryPresent = isByovRuntimeInstalled(info.id);
- // Check the immutable source pin before the import probe. Source-only
- // runtimes execute checkout code while importing, so an outdated or dirty
- // checkout must surface Upgrade / Repair without being loaded first.
- const current = binaryPresent ? await isByovRuntimeCurrent(info.id) : false;
- const packagesReady = current ? await isByovRuntimeReady(info.id) : false;
- res.json({
- runtime: info.id,
- label: info.label,
- installed: binaryPresent && packagesReady && current,
- binaryPresent,
- packagesReady,
- current,
- upgradeAvailable: binaryPresent && !current,
- venvPath: info.venvPython,
- repoDir: info.repoDir,
- repoUrl: info.repoUrl,
- installSourceLabel: info.installSourceLabel,
- installEnvVar: info.installEnvVar,
- });
-}));
-
-// In-flight singleton per runtime. A rapid double-click of the install
-// button would otherwise race two `bash setup-image-video.sh` processes
-// against the same target dir, both trying to git-clone or pip-install at
-// once. Existing existsSync gate doesn't help — the install hasn't created
-// the venv yet on the second click.
-const runtimeInstallInFlight = new Map();
-
-// Shells out to scripts/setup-image-video.sh with the runtime's INSTALL_X
-// env pre-set, so the in-app installer and the README's terminal recipe
-// invoke the exact same install path — no parallel Node-side implementation
-// per runtime to keep in sync.
-router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
- const runtime = String(req.query?.runtime || '');
- const info = BYOV_RUNTIME_INFO[runtime];
- const { send, safeEnd } = openSseStream(res);
- let child = null;
- let aborted = false;
-
- // Register disconnect handling before any readiness/revision await. Those
- // probes can take tens of seconds on a damaged venv; closing the modal during
- // that window must prevent the large installer from starting unattended.
- res.on('close', () => {
- if (res.writableEnded) return;
- aborted = true;
- if (info && runtimeInstallInFlight.get(info.id) === null) {
- runtimeInstallInFlight.delete(info.id);
- }
- stopSetupScript(child);
- });
+ res.json(await getVideoRuntimeStatus(runtime));
+};
- if (!info) {
- send({ type: 'error', message: `Unknown runtime: ${runtime}` });
- return safeEnd();
- }
- // Claim the in-flight slot SYNCHRONOUSLY, before any await. Two near-
- // simultaneous SSE requests would otherwise both reach the readiness await
- // on line below, both observe `!ready`, and both spawn `setup-image-video.sh`
- // against the same target dir — racing two git clones / pip installs.
- // Placeholder (`null`) gets replaced with the real child handle once spawned;
- // every early-return path below releases the slot.
- if (runtimeInstallInFlight.has(info.id)) {
- send({ type: 'error', message: `Another ${info.label} install is already running. Wait for it to finish or restart PortOS.` });
- return safeEnd();
- }
- runtimeInstallInFlight.set(info.id, null);
- // Skip ONLY when the binary, import probe, AND immutable revision all pass.
- // A partial install needs Repair, while a healthy checkout on an older pin
- // needs Upgrade; treating either as "already installed" strands the user
- // behind a button that can never perform the action it advertises.
- const alreadyInstalled = isByovRuntimeInstalled(info.id);
- const alreadyCurrent = alreadyInstalled && await isByovRuntimeCurrent(info.id);
- if (aborted) return safeEnd();
- const alreadyReady = alreadyCurrent && await isByovRuntimeReady(info.id);
- if (aborted) return safeEnd();
- if (alreadyInstalled && alreadyReady && alreadyCurrent) {
- runtimeInstallInFlight.delete(info.id);
- send({ type: 'log', message: `${info.label} already installed at ${info.venvPython}` });
- send({ type: 'complete', message: 'Already installed — nothing to do.' });
- return safeEnd();
- }
- // The install may add/remove packages; drop any cached "ready" so the
- // post-install /runtime-status response reflects the new state instead of
- // a stale "true" from before a deliberate cleanup. Same for the cached
- // runtime fingerprint — a reinstall can bump ltx/mlx/torch versions.
- invalidateByovReadyCache(info.id);
- invalidateByovLoraCapabilityCache(info.id);
- invalidateRuntimeFingerprintCache(info.id);
+router.get('/setup/runtime-status', asyncHandler(sendRuntimeStatus));
- if (!existsSync(SETUP_IMAGE_VIDEO_SCRIPT)) {
- runtimeInstallInFlight.delete(info.id);
- send({ type: 'error', message: `Installer script not found at ${SETUP_IMAGE_VIDEO_SCRIPT}` });
- return safeEnd();
- }
+// Backward-compatible read surface for stale clients or status pollers. GET
+// never installs; host mutation is restricted to the POST route below.
+router.get('/setup/runtime-install', asyncHandler(sendRuntimeStatus));
- send({ type: 'log', message: `▸ Starting ${info.label} install via ${info.installEnvVar}=1 bash scripts/setup-image-video.sh` });
- // Server-console visibility for the multi-GB install (start / heartbeat /
- // outcome) — the SSE stream otherwise surfaces progress only in the browser.
- const installLog = createInstallLogger({ installer: info.label, target: info.venvPython });
- const emit = (ev) => { installLog.onEvent(ev); send(ev); };
- installLog.start();
- const installEnv = {
- [info.installEnvVar]: '1',
- ...(info.pinEnvVar && info.expectedRevision ? { [info.pinEnvVar]: info.expectedRevision } : {}),
- };
- // spawnSetupScript owns the interpreter / path / process-group details that a
- // cancel and a Windows box each depend on — see lib/setupScriptRunner.js.
- child = spawnSetupScript(installEnv);
- runtimeInstallInFlight.set(info.id, child);
-
- // `splitRe: /[\r\n]+/` so a bash/pip/tqdm progress bar that redraws with a
- // bare `\r` surfaces each redraw as its own log line; the carry buffer
- // stitches a line split across chunk boundaries (flushed on close).
- const onLine = (line) => {
- const t = line.trimEnd();
- if (t) emit({ type: 'log', message: t });
- };
- const stdoutReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
- const stderrReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
- child.stdout.on('data', stdoutReader.push);
- child.stderr.on('data', stderrReader.push);
- child.on('error', (err) => {
- runtimeInstallInFlight.delete(info.id);
- emit({ type: 'error', message: `Installer failed to spawn: ${err.message}` });
- safeEnd();
- });
- child.on('close', async (code) => {
- stdoutReader.flush();
- stderrReader.flush();
- runtimeInstallInFlight.delete(info.id);
- // Re-probe rather than trusting exit code alone — partial installs
- // (network drop mid-clone, missing requirements file, ctrl-c via
- // SIGTERM) can exit 0 but leave the venv unable to import its core
- // packages. Probe both the binary AND the import surface so the
- // success message can't lie. The banner gate uses the same probe.
- const binaryPresent = isByovRuntimeInstalled(info.id);
- const current = binaryPresent && await isByovRuntimeCurrent(info.id);
- const packagesReady = current && await isByovRuntimeReady(info.id);
- if (code === 0 && binaryPresent && packagesReady && current) {
- emit({ type: 'complete', message: `${info.label} ready: ${info.venvPython}` });
- } else if (code === 0 && !binaryPresent) {
- emit({ type: 'error', message: `Installer exited 0 but the runtime is still missing. Review the log above, then use Repair in this panel.` });
- } else if (code === 0) {
- emit({ type: 'error', message: packagesReady
- ? 'Installer exited 0 but the runtime is still on an outdated revision. Review the source-update log above, then use Repair in this panel.'
- : `Installer exited 0 but the runtime can't import its core packages. Review the package errors above, then use Repair in this panel.` });
- } else {
- emit({ type: 'error', message: `Installer exited with code ${code}.` });
- }
- safeEnd();
+router.post('/setup/runtime-install', asyncHandler(async (req, res) => {
+ const { send, safeEnd } = openSseStream(res);
+ await streamVideoRuntimeInstall({
+ runtime: String(req.query?.runtime || ''),
+ send,
+ safeEnd,
+ onDisconnect: (handler) => res.on('close', handler),
+ isResponseEnded: () => res.writableEnded,
});
-
- res.on('close', () => { if (!res.writableEnded) installLog.cancel(); });
}));
async function resolveLocalPythonHealth(py) {
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index b8bb1a182b..a80c319a04 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -36,8 +36,17 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => ({
// child as a clean exit, i.e. "capable". Pin the verdict explicitly so each
// test states the capability it is exercising.
const loraCapability = vi.hoisted(() => ({ capable: false }));
+const runtimeProbes = vi.hoisted(() => ({
+ isByovRuntimeInstalled: vi.fn(() => false),
+ isByovRuntimeReady: vi.fn(async () => false),
+ isByovRuntimeCurrent: vi.fn(async () => false),
+ invalidateByovReadyCache: vi.fn(),
+ invalidateByovLoraCapabilityCache: vi.fn(),
+ invalidateRuntimeFingerprintCache: vi.fn(),
+}));
vi.mock('../services/videoGen/runtimes.js', async (importOriginal) => ({
...(await importOriginal()),
+ ...runtimeProbes,
resolveByovRuntimeLoraCapable: vi.fn(async (runtime) => runtime === 'minimax_h3' && loraCapability.capable),
}));
@@ -116,12 +125,7 @@ vi.mock('../services/videoGen/local.js', () => ({
},
hunyuan: { id: 'hunyuan', label: 'HunyuanVideo MLX', venvPython: '/tmp/hunyuan.py', installEnvVar: 'INSTALL_HUNYUAN', repoUrl: 'x', repoDir: '/tmp' },
},
- isByovRuntimeInstalled: vi.fn(() => false),
- isByovRuntimeReady: vi.fn(async () => false),
- isByovRuntimeCurrent: vi.fn(async () => false),
- invalidateByovReadyCache: vi.fn(),
- invalidateByovLoraCapabilityCache: vi.fn(),
- invalidateRuntimeFingerprintCache: vi.fn(),
+ ...runtimeProbes,
// /status now surfaces a runtime block (host chip/os + per-runtime versions).
// Mock returns a fixed shape so the status test can assert it's wired through.
resolveRuntimeFingerprint: vi.fn(async () => ({
@@ -301,6 +305,9 @@ describe('videoGen routes', () => {
// bailed before the route consumed it can't leak into the next test.
pendingUpload.current = null;
installProcess.spawn.mockReset().mockImplementation(() => installProcess.makeChild());
+ runtimeProbes.isByovRuntimeInstalled.mockReturnValue(false);
+ runtimeProbes.isByovRuntimeReady.mockResolvedValue(false);
+ runtimeProbes.isByovRuntimeCurrent.mockResolvedValue(false);
});
describe('GET /status', () => {
@@ -429,12 +436,22 @@ describe('videoGen routes', () => {
});
});
- describe('GET /setup/runtime-install', () => {
+ describe('/setup/runtime-install', () => {
+ it('keeps GET read-only and returns the current runtime status', async () => {
+ const r = await request(app).get('/api/video-gen/setup/runtime-install?runtime=wan22');
+ expect(r.status).toBe(200);
+ expect(r.body).toMatchObject({
+ runtime: 'wan22', installed: false, binaryPresent: false,
+ packagesReady: false, current: false,
+ });
+ expect(installProcess.spawn).not.toHaveBeenCalled();
+ });
+
it('short-circuits only when the runtime packages and pinned revision are current', async () => {
videoGenService.isByovRuntimeInstalled.mockReturnValueOnce(true);
videoGenService.isByovRuntimeReady.mockResolvedValueOnce(true);
videoGenService.isByovRuntimeCurrent.mockResolvedValueOnce(true);
- const r = await request(app).get('/api/video-gen/setup/runtime-install?runtime=wan22');
+ const r = await request(app).post('/api/video-gen/setup/runtime-install?runtime=wan22');
expect(r.status).toBe(200);
expect(r.text).toContain('"type":"complete"');
expect(r.text).toContain('Already installed');
@@ -451,7 +468,7 @@ describe('videoGen routes', () => {
videoGenService.isByovRuntimeCurrent
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true);
- const r = await request(app).get('/api/video-gen/setup/runtime-install?runtime=wan22');
+ const r = await request(app).post('/api/video-gen/setup/runtime-install?runtime=wan22');
expect(r.status).toBe(200);
expect(r.text).toContain('"type":"complete"');
expect(r.text).toContain('Wan 2.2 MLX ready');
diff --git a/server/services/videoGen/runtimeInstaller.js b/server/services/videoGen/runtimeInstaller.js
new file mode 100644
index 0000000000..17d77ab3fe
--- /dev/null
+++ b/server/services/videoGen/runtimeInstaller.js
@@ -0,0 +1,201 @@
+/**
+ * Video Gen — BYOV runtime status and streamed installation.
+ *
+ * Routes supply the SSE transport callbacks; this service owns runtime
+ * validation, single-flight installation, process lifecycle, and post-install
+ * readiness checks.
+ */
+
+import { existsSync } from 'fs';
+import { createInstallLogger } from '../../lib/installLogger.js';
+import { createLineReader } from '../../lib/streamLines.js';
+import {
+ SETUP_IMAGE_VIDEO_SCRIPT,
+ spawnSetupScript,
+ stopSetupScript,
+} from '../../lib/setupScriptRunner.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import {
+ BYOV_RUNTIME_INFO,
+ invalidateByovLoraCapabilityCache,
+ invalidateByovReadyCache,
+ invalidateRuntimeFingerprintCache,
+ isByovRuntimeCurrent,
+ isByovRuntimeInstalled,
+ isByovRuntimeReady,
+} from './runtimes.js';
+
+// In-flight singleton per runtime. A rapid double-click of the install button
+// must not race two setup scripts against the same checkout and venv.
+const runtimeInstallInFlight = new Map();
+
+export async function getVideoRuntimeStatus(runtime) {
+ const info = BYOV_RUNTIME_INFO[runtime];
+ if (!info) {
+ throw new ServerError(
+ `Unknown runtime: ${runtime}. Expected one of: ${Object.keys(BYOV_RUNTIME_INFO).join(', ')}`,
+ { status: 400, code: 'UNKNOWN_BYOV_RUNTIME' },
+ );
+ }
+
+ const binaryPresent = isByovRuntimeInstalled(info.id);
+ // Source-only runtimes execute checkout code during the import probe, so an
+ // outdated or dirty checkout must be rejected before anything imports it.
+ const current = binaryPresent ? await isByovRuntimeCurrent(info.id) : false;
+ const packagesReady = current ? await isByovRuntimeReady(info.id) : false;
+ return {
+ runtime: info.id,
+ label: info.label,
+ installed: binaryPresent && packagesReady && current,
+ binaryPresent,
+ packagesReady,
+ current,
+ upgradeAvailable: binaryPresent && !current,
+ venvPath: info.venvPython,
+ repoDir: info.repoDir,
+ repoUrl: info.repoUrl,
+ installSourceLabel: info.installSourceLabel,
+ installEnvVar: info.installEnvVar,
+ };
+}
+
+/**
+ * Stream one runtime installation through caller-owned transport callbacks.
+ *
+ * @param {object} options
+ * @param {string} options.runtime
+ * @param {(event: object) => void} options.send
+ * @param {() => void} options.safeEnd
+ * @param {(handler: () => void) => void} options.onDisconnect
+ * @param {() => boolean} options.isResponseEnded
+ */
+export async function streamVideoRuntimeInstall({
+ runtime,
+ send,
+ safeEnd,
+ onDisconnect,
+ isResponseEnded,
+}) {
+ const info = BYOV_RUNTIME_INFO[runtime];
+ let child = null;
+ let installLog = null;
+ let aborted = false;
+ let finished = false;
+
+ // Register before any readiness/revision await. Those probes can take tens
+ // of seconds on a damaged venv; closing the modal during one must prevent a
+ // multi-gigabyte installer from starting unattended.
+ onDisconnect(() => {
+ if (isResponseEnded()) return;
+ aborted = true;
+ installLog?.cancel();
+ if (info && runtimeInstallInFlight.get(info.id) === null) {
+ runtimeInstallInFlight.delete(info.id);
+ }
+ stopSetupScript(child);
+ });
+
+ if (!info) {
+ send({ type: 'error', message: `Unknown runtime: ${runtime}` });
+ return safeEnd();
+ }
+
+ // Reserve synchronously before any await. The null placeholder is replaced
+ // by the child once spawned and released by every early-return path.
+ if (runtimeInstallInFlight.has(info.id)) {
+ send({ type: 'error', message: `Another ${info.label} install is already running. Wait for it to finish or restart PortOS.` });
+ return safeEnd();
+ }
+ runtimeInstallInFlight.set(info.id, null);
+
+ const alreadyInstalled = isByovRuntimeInstalled(info.id);
+ const alreadyCurrent = alreadyInstalled && await isByovRuntimeCurrent(info.id);
+ if (aborted) return safeEnd();
+ const alreadyReady = alreadyCurrent && await isByovRuntimeReady(info.id);
+ if (aborted) return safeEnd();
+ if (alreadyInstalled && alreadyReady && alreadyCurrent) {
+ runtimeInstallInFlight.delete(info.id);
+ send({ type: 'log', message: `${info.label} already installed at ${info.venvPython}` });
+ send({ type: 'complete', message: 'Already installed — nothing to do.' });
+ return safeEnd();
+ }
+
+ // An install can add/remove packages or update a checkout. Invalidate every
+ // runtime-derived cache before spawning so later status reads re-probe it.
+ invalidateByovReadyCache(info.id);
+ invalidateByovLoraCapabilityCache(info.id);
+ invalidateRuntimeFingerprintCache(info.id);
+
+ if (!existsSync(SETUP_IMAGE_VIDEO_SCRIPT)) {
+ runtimeInstallInFlight.delete(info.id);
+ send({ type: 'error', message: `Installer script not found at ${SETUP_IMAGE_VIDEO_SCRIPT}` });
+ return safeEnd();
+ }
+
+ send({ type: 'log', message: `▸ Starting ${info.label} install via ${info.installEnvVar}=1 bash scripts/setup-image-video.sh` });
+ installLog = createInstallLogger({ installer: info.label, target: info.venvPython });
+ const emit = (event) => { installLog.onEvent(event); send(event); };
+ installLog.start();
+ const installEnv = {
+ [info.installEnvVar]: '1',
+ ...(info.pinEnvVar && info.expectedRevision ? { [info.pinEnvVar]: info.expectedRevision } : {}),
+ };
+
+ try {
+ child = spawnSetupScript(installEnv);
+ } catch (err) {
+ finished = true;
+ runtimeInstallInFlight.delete(info.id);
+ emit({ type: 'error', message: `Installer failed to spawn: ${err.message}` });
+ return safeEnd();
+ }
+ runtimeInstallInFlight.set(info.id, child);
+
+ // Bare carriage returns are progress redraws. Surface each as a log line,
+ // while createLineReader still stitches chunks split mid-line.
+ const onLine = (line) => {
+ const text = line.trimEnd();
+ if (text) emit({ type: 'log', message: text });
+ };
+ const stdoutReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ const stderrReader = createLineReader(onLine, { splitRe: /[\r\n]+/ });
+ child.stdout.on('data', stdoutReader.push);
+ child.stderr.on('data', stderrReader.push);
+ child.on('error', (err) => {
+ if (finished) return;
+ finished = true;
+ runtimeInstallInFlight.delete(info.id);
+ emit({ type: 'error', message: `Installer failed to spawn: ${err.message}` });
+ safeEnd();
+ });
+ child.on('close', async (code) => {
+ if (finished) return;
+ try {
+ stdoutReader.flush();
+ stderrReader.flush();
+ finished = true;
+ runtimeInstallInFlight.delete(info.id);
+ // Exit 0 is not proof of a usable install: network failures and partial
+ // package writes can still leave a binary with a broken import surface.
+ const binaryPresent = isByovRuntimeInstalled(info.id);
+ const current = binaryPresent && await isByovRuntimeCurrent(info.id);
+ const packagesReady = current && await isByovRuntimeReady(info.id);
+ if (code === 0 && binaryPresent && packagesReady && current) {
+ emit({ type: 'complete', message: `${info.label} ready: ${info.venvPython}` });
+ } else if (code === 0 && !binaryPresent) {
+ emit({ type: 'error', message: 'Installer exited 0 but the runtime is still missing. Review the log above, then use Repair in this panel.' });
+ } else if (code === 0) {
+ emit({ type: 'error', message: packagesReady
+ ? 'Installer exited 0 but the runtime is still on an outdated revision. Review the source-update log above, then use Repair in this panel.'
+ : `Installer exited 0 but the runtime can't import its core packages. Review the package errors above, then use Repair in this panel.` });
+ } else {
+ emit({ type: 'error', message: `Installer exited with code ${code}.` });
+ }
+ safeEnd();
+ } catch (err) {
+ console.error(`❌ ${info.label} install completion check failed: ${err.message}`);
+ emit({ type: 'error', message: `${info.label} install completion check failed: ${err.message}` });
+ safeEnd();
+ }
+ });
+}