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

require Python 3.10+ for the FLUX.2 venv and stop hiding pip failures as "connection lost"

[._.]/ Adam Eivy90db541408fe
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index 4fa9267028..d9e3e43ae2 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -77,6 +77,28 @@ venv_python() {
# shared with venv_python so the two probes can't drift apart.
venv_exists() { [[ -x "$1/bin/python3" || -x "$1/Scripts/python.exe" ]]; }
+# True when $1 is a Python 3.10+ interpreter. Mirrors MIN_VENV_PYTHON in
+# server/lib/pythonSetup.js, and for the same reason: below 3.10 pip resolves an
+# old setuptools (<77) inside its build isolation, which rejects the PEP 639
+# *string* form of `project.license`. A git-sourced dependency that uses it
+# (sdnq declares `license = "GPL-3.0-only"`) then dies in "Getting requirements
+# to build wheel" — after the multi-GB torch download, with a schema error that
+# reads like a pip bug. mflux/mlx need the same floor.
+python_at_least_310() {
+ [[ -n "${1:-}" ]] && "$1" -c 'import sys; sys.exit(0 if sys.version_info[:2] >= (3, 10) else 1)' 2>/dev/null
+}
+
+# Echo the first Python 3.10+ on PATH, preferring $PYTHON_BIN. Empty when the
+# machine has none.
+newest_supported_python() {
+ local candidate
+ if python_at_least_310 "$PYTHON_BIN"; then command -v "$PYTHON_BIN"; return 0; fi
+ for candidate in python3.14 python3.13 python3.12 python3.11 python3.10; do
+ if have "$candidate" && python_at_least_310 "$candidate"; then command -v "$candidate"; return 0; fi
+ done
+ return 1
+}
+
# mere.run is a signed native binary and is the one setup path that does not
# need Python. Keep the bare-script default and every mixed install strict: only
# an explicit INSTALL_MERERUN=1 request with no other runtime selected may run
@@ -177,7 +199,7 @@ if [[ "$INSTALL_MFLUX" == "1" ]]; then
# the same pattern the flux2/ltx/wan runtimes use. PortOS's resolveMfluxPython()
# auto-discovers that venv, so no Settings change is needed either way.
MFLUX_USE_VENV=0
- if "$PYTHON_BIN" -c 'import sys; sys.exit(0 if sys.version_info[:2] >= (3, 10) else 1)' 2>/dev/null; then
+ if python_at_least_310 "$PYTHON_BIN"; then
# Step 1: force-reinstall mflux's OWN files with --no-deps to flush a stale
# file layout left by a partial reinstall (we hit this on 0.12.1, where
# `mflux/models/flux/cli/` went missing, breaking the entry-point shim)
@@ -1020,10 +1042,21 @@ if [[ "$INSTALL_FLUX2" == "1" ]]; then
# fragile, so we use a sibling venv. server/lib/pythonSetup.js looks for
# this venv's interpreter when the active model has runner=='flux2'.
FLUX2_VENV="${HOME}/.portos/venv-flux2"
- if ! venv_exists "$FLUX2_VENV"; then
- echo "📦 Creating FLUX.2 venv at ${FLUX2_VENV}..."
- mkdir -p "${HOME}/.portos"
- "$PYTHON_BIN" -m venv "$FLUX2_VENV"
+ if ! FLUX2_BASE_PY="$(newest_supported_python)"; then
+ echo "❌ FLUX.2 needs Python 3.10+ to build its venv; \`$PYTHON_BIN\` is older and no newer python3.NN is on PATH." >&2
+ echo " Install one (e.g. 'brew install [email protected]' or 'uv python install 3.12'), then re-run with PYTHON_BIN pointing at it." >&2
+ exit 1
+ fi
+ mkdir -p "${HOME}/.portos"
+ # A venv left behind by an earlier run against a too-old base can never
+ # install these packages, and `python -m venv` reuses it silently — so every
+ # retry would fail the same way. Rebuild it instead of pip-ing into it.
+ if venv_exists "$FLUX2_VENV" && ! python_at_least_310 "$(venv_python "$FLUX2_VENV")"; then
+ echo "♻️ FLUX.2 venv at ${FLUX2_VENV} predates Python 3.10 — recreating it..."
+ "$FLUX2_BASE_PY" -m venv --clear "$FLUX2_VENV"
+ elif ! venv_exists "$FLUX2_VENV"; then
+ echo "📦 Creating FLUX.2 venv at ${FLUX2_VENV} from ${FLUX2_BASE_PY}..."
+ "$FLUX2_BASE_PY" -m venv "$FLUX2_VENV"
fi
FLUX2_PY="$(venv_python "$FLUX2_VENV")"
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 1ad3af1dd2..d78ef0cbed 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -228,6 +228,72 @@ export function detectVenvBasePythonSync() {
return venvBaseCandidatesSync()[0] || detectPythonSync();
}
+// Minimum CPython for a venv PortOS builds the torch/diffusers stack into.
+//
+// Below 3.10, pip resolves an old setuptools (<77) inside its own build
+// isolation, and that setuptools rejects the PEP 639 *string* form of
+// `project.license`. A git-sourced dependency that uses it — `sdnq` declares
+// `license = "GPL-3.0-only"` — then dies in "Getting requirements to build
+// wheel" with `project.license must be valid exactly by one definition`, which
+// reads like a pip bug and lands only AFTER the multi-GB torch download. The
+// same floor is what mflux/mlx need (scripts/setup-image-video.sh checks it
+// before the `pip install --user` path) and what the model-abuse guard's own
+// `isBasePythonSupported` enforces, so gate the BASE interpreter up front
+// rather than diagnosing the build failure downstream.
+//
+// Nothing here caps the upper end: a base newer than the torch wheels support
+// fails with pip's own "No matching distribution" message, which is already
+// actionable, and hard-coding a ceiling would reject each new CPython release
+// until someone remembered to raise it.
+export const MIN_VENV_PYTHON = Object.freeze([3, 10]);
+export const MIN_VENV_PYTHON_LABEL = MIN_VENV_PYTHON.join('.');
+
+// `{ version, major, minor }` for an interpreter, or null when it can't be run
+// (missing, not an interpreter, a Store alias, a venv whose base was pruned).
+// Deliberately null rather than throwing: every caller treats "can't tell" the
+// same as "too old", because building a torch venv from it is a coin flip.
+export async function probePythonVersion(pythonPath, { env, timeout = 10_000 } = {}) {
+ if (!pythonPath) return null;
+ const { stdout } = await execFileAsync(
+ pythonPath,
+ ['-c', 'import sys; print("%d.%d.%d" % sys.version_info[:3])'],
+ // Room for a chatty interpreter's banner/deprecation noise before the
+ // version line: a maxBuffer overflow rejects the interpreter outright, and
+ // "rejected" here means refusing to install at all.
+ safeChildProcessOptions({ ...(env ? { env } : {}), timeout, maxBuffer: 64 * 1024 }),
+ ).catch(() => ({ stdout: '' }));
+ const line = String(stdout).trim().split(/\r?\n/).pop() || '';
+ const parts = /^(\d+)\.(\d+)\.(\d+)$/.exec(line);
+ if (!parts) return null;
+ return { version: line, major: Number(parts[1]), minor: Number(parts[2]) };
+}
+
+export const meetsMinVenvPython = (probed) =>
+ !!probed && (probed.major > MIN_VENV_PYTHON[0]
+ || (probed.major === MIN_VENV_PYTHON[0] && probed.minor >= MIN_VENV_PYTHON[1]));
+
+export async function isSupportedVenvBase(pythonPath, options) {
+ return meetsMinVenvPython(await probePythonVersion(pythonPath, options));
+}
+
+// venvBaseCandidatesSync() split by MIN_VENV_PYTHON, preserving its ordering
+// (the tier ranking in that function is about torch loading correctly, and
+// still decides which SUPPORTED base wins). `rejected` carries the version we
+// found so the installer can say *why* a Python it can see is unusable instead
+// of claiming none exists. Probes run in parallel: the list is short and
+// already existsSync-filtered.
+export async function classifyVenvBases() {
+ const candidates = venvBaseCandidatesSync();
+ const probed = await Promise.all(candidates.map((p) => probePythonVersion(p)));
+ const supported = [];
+ const rejected = [];
+ candidates.forEach((path, i) => {
+ if (meetsMinVenvPython(probed[i])) supported.push(path);
+ else rejected.push({ path, version: probed[i]?.version || 'unknown' });
+ });
+ return { supported, rejected };
+}
+
export async function detectPython() {
// mlx ships arm64-only wheels; prefer an arm64 interpreter on Apple Silicon
// so /opt/anaconda3 (often x86_64) doesn't beat /opt/homebrew/bin/python3.
@@ -860,28 +926,77 @@ export function installFlux2Venv(onLog) {
const log = (message) => onLog({ type: 'log', message });
const trackProc = (p) => { currentProc = p; };
- const runPython = async (args) =>
- (await streamSpawn(args[0], args.slice(1), onLog, trackProc)) === 0;
+ // Last non-zero exit, so `fail` can name it. streamSpawn already forwards the
+ // child's own output as `log` frames, so the error frame only has to say
+ // which step died and point at those lines.
+ let lastExitCode = null;
+ const runPython = async (args) => {
+ const code = await streamSpawn(args[0], args.slice(1), onLog, trackProc);
+ if (code !== 0) lastExitCode = code;
+ return code === 0;
+ };
+
+ // Every non-cancelled failure MUST emit a terminal `error` frame. The SSE
+ // route ends the stream when this promise settles, and useInstallStream reads
+ // a close with no terminal frame as "Connection to installer lost. Restart
+ // PortOS or try again." — so a plain pip failure used to surface as a
+ // phantom transport error with the real cause buried in the log.
+ const fail = (stageName, message) => {
+ const exit = lastExitCode == null ? '' : ` (exit code ${lastExitCode})`;
+ onLog({ type: 'error', message: `${message}${exit} See the install log above for the failing step.` });
+ return { ok: false, stage: stageName };
+ };
const promise = (async () => {
- stage('detect', 'Looking for system Python…');
+ stage('detect', `Looking for Python ${MIN_VENV_PYTHON_LABEL}+…`);
// The base to CREATE the FLUX.2 venv from — deliberately not detectPython(),
// which ranks PortOS's own already-provisioned image-gen venv first and is
// answering a different question ("which interpreter can we pip into").
// Building a venv from an already-provisioned venv is fragile — its
// pyvenv.cfg can pin an interpreter path a later system upgrade removes.
- const baseCandidates = venvBaseCandidatesSync();
- const basePython = detectVenvBasePythonSync();
+ //
+ // Version-filtered, not just "first one that exists": the candidate list is
+ // ranked for torch loading correctly, and its lower tiers routinely hold a
+ // long-EOL interpreter (a stock /opt/anaconda3 ships 3.8) that installs the
+ // whole multi-GB torch tree and only then fails building sdnq's wheel. See
+ // MIN_VENV_PYTHON.
+ const { supported: baseCandidates, rejected } = await classifyVenvBases();
+ if (!baseCandidates.length) {
+ // Same last resort detectVenvBasePythonSync() carries: with nothing in the
+ // ranked pool, an app-managed venv or a PATH python (the WindowsApps alias
+ // is already filtered out there) beats refusing to install — as long as it
+ // clears the floor.
+ const lastResort = detectPythonSync();
+ const probed = await probePythonVersion(lastResort);
+ if (meetsMinVenvPython(probed)) baseCandidates.push(lastResort);
+ else if (lastResort && !rejected.some((r) => r.path === lastResort)) {
+ rejected.push({ path: lastResort, version: probed?.version || 'unknown' });
+ }
+ }
+ const basePython = baseCandidates[0];
if (!basePython) {
- onLog({ type: 'error', message: 'No system Python 3 found. Install Python 3.10+ and try again.' });
+ const seen = rejected.map(({ path, version }) => `${path} (${version})`).join(', ');
+ onLog({
+ type: 'error',
+ message: seen
+ ? `No Python ${MIN_VENV_PYTHON_LABEL}+ found — FLUX.2 needs one to build its venv. Found only: ${seen}. Install a newer Python (e.g. \`brew install [email protected]\` or \`uv python install 3.12\`) and try again.`
+ : `No system Python 3 found. Install Python ${MIN_VENV_PYTHON_LABEL}+ and try again.`,
+ });
return { ok: false, stage: 'detect' };
}
log(`Using base Python: ${basePython}`);
+ if (killed) return { ok: false, stage: 'detect', cancelled: true };
stage('venv', `Creating FLUX.2 venv at ${FLUX2_VENV_DEFAULT}…`);
const targetDir = FLUX2_VENV_DEFAULT.replace(IS_WIN ? /\\Scripts\\python\.exe$/ : /\/bin\/python3$/, '');
+ // createVenv reuses an existing interpreter as-is, so a venv left behind by
+ // an earlier run against a too-old base would survive every retry — and
+ // keep failing the same way. Rebuild it rather than pip into it.
+ const staleVenv = existsSync(FLUX2_VENV_DEFAULT) && !await isSupportedVenvBase(FLUX2_VENV_DEFAULT);
+ if (staleVenv) log(`Existing venv is older than Python ${MIN_VENV_PYTHON_LABEL} — rebuilding it.`);
+ if (killed) return { ok: false, stage: 'venv', cancelled: true };
const venvFallback = baseCandidates.find((p) => p !== basePython);
- let venvPython = await createVenv(basePython, targetDir).catch((err) => {
+ let venvPython = await createVenv(basePython, targetDir, { clear: staleVenv }).catch((err) => {
log(`venv creation failed against ${basePython}: ${err.message}`);
return null;
});
@@ -904,7 +1019,7 @@ export function installFlux2Venv(onLog) {
stage('upgrade-pip', 'Upgrading pip + wheel + setuptools…');
if (!await runPython([venvPython, '-m', 'pip', 'install', '--upgrade', 'pip', 'wheel', 'setuptools'])) {
- return { ok: false, stage: 'upgrade-pip' };
+ return fail('upgrade-pip', 'Could not upgrade pip/wheel/setuptools in the new venv.');
}
if (killed) return { ok: false, stage: 'upgrade-pip', cancelled: true };
@@ -921,15 +1036,15 @@ export function installFlux2Venv(onLog) {
const torchArgs = ['install', '--upgrade', '--progress-bar', 'on', ...FLUX2_TORCH_SPECS];
if (useCuda) torchArgs.push('--index-url', cudaIndex);
if (!await runPython([venvPython, '-m', 'pip', ...torchArgs])) {
- return { ok: false, stage: 'install' };
+ return fail('install', 'Installing torch + torchvision failed.');
}
if (killed) return { ok: false, stage: 'install', cancelled: true };
const otherSpecs = FLUX2_PIP_SPECS.filter((s) => !FLUX2_TORCH_SPECS.includes(s));
if (!await runPython([venvPython, '-m', 'pip', 'install', '--upgrade', '--progress-bar', 'on', ...otherSpecs])) {
- return { ok: false, stage: 'install' };
+ return fail('install', 'Installing the FLUX.2 packages failed.');
}
} else if (!await runPython([venvPython, '-m', 'pip', 'install', '--upgrade', '--progress-bar', 'on', ...FLUX2_PIP_SPECS])) {
- return { ok: false, stage: 'install' };
+ return fail('install', 'Installing the FLUX.2 packages failed.');
}
if (killed) return { ok: false, stage: 'install', cancelled: true };
diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.js
index 590e27fb90..5f88452b98 100644
--- a/server/lib/pythonSetup.test.js
+++ b/server/lib/pythonSetup.test.js
@@ -20,6 +20,18 @@ const mockState = {
// of execShouldFail (which also drives the unrelated arch probe).
fluxImportShouldFail: false,
fluxImportCalls: 0,
+ // `sys.version_info` answers per interpreter path, for the MIN_VENV_PYTHON
+ // gate. Unlisted paths answer with `defaultVersion`.
+ versionByPath: new Map(),
+ defaultVersion: '3.12.4',
+ // Exit codes for the pip/venv children installFlux2Venv spawns, keyed by a
+ // substring of the joined argv ('pip install --upgrade pip' etc). Anything
+ // unmatched exits 0.
+ spawnExitByArgs: new Map(),
+ // Every [bin, ...args] installFlux2Venv spawned, in order.
+ spawnCalls: [],
+ // Every [bin, '-m', 'venv', …] createVenv ran, in order.
+ venvCalls: [],
};
vi.mock('node:os', async () => {
@@ -65,7 +77,19 @@ vi.mock('./childProcess.js', async () => {
return;
}
const probeArg = args?.[1] || '';
- if (probeArg.includes('platform.machine')) {
+ if (args?.[0] === '-m' && probeArg === 'venv') {
+ // Mimic `python -m venv`: record the invocation and make the resulting
+ // interpreter exist, so createVenv's post-condition check passes.
+ mockState.venvCalls.push([bin, ...args]);
+ mockState.presentPaths.add(`${args[args.length - 1]}/bin/python3`);
+ resolve({ stdout: '', stderr: '' });
+ } else if (probeArg.includes('sys.version_info')) {
+ const version = mockState.versionByPath.has(bin)
+ ? mockState.versionByPath.get(bin)
+ : mockState.defaultVersion;
+ if (!version) reject(new Error('not an interpreter'));
+ else resolve({ stdout: `${version}\n`, stderr: '' });
+ } else if (probeArg.includes('platform.machine')) {
const a = mockState.archByPath.get(bin) ?? mockState.arch;
resolve({ stdout: `${a}\n`, stderr: '' });
} else if (probeArg.includes('Flux2KleinPipeline')) {
@@ -76,7 +100,20 @@ vi.mock('./childProcess.js', async () => {
resolve({ stdout: '', stderr: '' });
}
});
- return { ...actual, execFile: fakeExecFile };
+ const { EventEmitter } = await vi.importActual('node:events');
+ // streamSpawn only needs stdout/stderr emitters plus a 'close' event.
+ const fakeSpawn = (bin, args) => {
+ mockState.spawnCalls.push([bin, ...args]);
+ const proc = new EventEmitter();
+ proc.stdout = new EventEmitter();
+ proc.stderr = new EventEmitter();
+ proc.kill = () => { proc.killed = true; };
+ const joined = args.join(' ');
+ const hit = [...mockState.spawnExitByArgs.entries()].find(([needle]) => joined.includes(needle));
+ setImmediate(() => proc.emit('close', hit ? hit[1] : 0));
+ return proc;
+ };
+ return { ...actual, execFile: fakeExecFile, spawn: fakeSpawn };
});
// The PATH fallbacks shell out for real; stub them so a test box's own Python
@@ -105,6 +142,11 @@ const resetState = () => {
mockState.uvPythonDirs = null;
mockState.fluxImportShouldFail = false;
mockState.fluxImportCalls = 0;
+ mockState.versionByPath = new Map();
+ mockState.defaultVersion = '3.12.4';
+ mockState.spawnExitByArgs = new Map();
+ mockState.spawnCalls = [];
+ mockState.venvCalls = [];
};
describe('REQUIRED_PACKAGES', () => {
@@ -495,3 +537,140 @@ describe('isFlux2VenvHealthy', () => {
expect(mockState.fluxImportCalls).toBe(1);
});
});
+
+describe('classifyVenvBases', () => {
+ beforeEach(resetState);
+
+ it('splits candidates on the MIN_VENV_PYTHON floor, keeping the ranked order', async () => {
+ mockState.presentPaths.add('/opt/anaconda3/bin/python3');
+ mockState.presentPaths.add('/opt/homebrew/bin/python3');
+ mockState.presentPaths.add('/usr/bin/python3');
+ mockState.versionByPath.set('/opt/anaconda3/bin/python3', '3.8.5');
+ mockState.versionByPath.set('/opt/homebrew/bin/python3', '3.12.7');
+ mockState.versionByPath.set('/usr/bin/python3', '3.9.6');
+
+ const { classifyVenvBases } = await loadModule();
+ const { supported, rejected } = await classifyVenvBases();
+
+ expect(supported.map(posixPath)).toEqual(['/opt/homebrew/bin/python3']);
+ expect(rejected.map(({ path, version }) => `${posixPath(path)} ${version}`))
+ .toEqual(['/opt/anaconda3/bin/python3 3.8.5', '/usr/bin/python3 3.9.6']);
+ });
+
+ it('rejects an interpreter whose version probe fails — "can\'t tell" is not "new enough"', async () => {
+ mockState.presentPaths.add('/opt/homebrew/bin/python3');
+ mockState.versionByPath.set('/opt/homebrew/bin/python3', null);
+
+ const { classifyVenvBases } = await loadModule();
+ const { supported, rejected } = await classifyVenvBases();
+
+ expect(supported).toEqual([]);
+ expect(rejected).toEqual([{ path: '/opt/homebrew/bin/python3', version: 'unknown' }]);
+ });
+});
+
+// A stock /opt/anaconda3 ships Python 3.8, and it outranks Homebrew in the
+// candidate list (conda is not PEP 668 externally-managed). Building the FLUX.2
+// venv from it downloads the whole multi-GB torch tree and only THEN dies
+// building sdnq's wheel, because pip's build isolation resolves a setuptools
+// too old to parse PEP 639's string `project.license`. The gate has to happen
+// at detect time, on the base interpreter.
+describe('installFlux2Venv base-interpreter floor', () => {
+ beforeEach(resetState);
+
+ const runInstall = async (mod) => {
+ const events = [];
+ const { promise } = mod.installFlux2Venv((ev) => events.push(ev));
+ return { result: await promise, events };
+ };
+
+ it('skips a too-old base that outranks a supported one', async () => {
+ mockState.presentPaths.add('/opt/anaconda3/bin/python3');
+ mockState.presentPaths.add('/opt/homebrew/bin/python3');
+ mockState.versionByPath.set('/opt/anaconda3/bin/python3', '3.8.5');
+ mockState.versionByPath.set('/opt/homebrew/bin/python3', '3.12.7');
+
+ const mod = await loadModule();
+ const { result } = await runInstall(mod);
+
+ expect(result.ok).toBe(true);
+ expect(mockState.venvCalls.map(([bin]) => posixPath(bin))).toEqual(['/opt/homebrew/bin/python3']);
+ });
+
+ it('fails at detect naming the versions it found, instead of downloading torch first', async () => {
+ mockState.presentPaths.add('/opt/anaconda3/bin/python3');
+ mockState.versionByPath.set('/opt/anaconda3/bin/python3', '3.8.5');
+
+ const mod = await loadModule();
+ const { result, events } = await runInstall(mod);
+
+ expect(result).toEqual({ ok: false, stage: 'detect' });
+ expect(mockState.venvCalls).toEqual([]);
+ expect(mockState.spawnCalls).toEqual([]);
+ const error = events.find((ev) => ev.type === 'error');
+ expect(error.message).toContain('/opt/anaconda3/bin/python3 (3.8.5)');
+ expect(error.message).toContain('3.10+');
+ });
+
+ it('rebuilds a venv left behind by an earlier run against a too-old base', async () => {
+ mockState.presentPaths.add('/opt/homebrew/bin/python3');
+ mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
+ mockState.versionByPath.set('/opt/homebrew/bin/python3', '3.12.7');
+ mockState.versionByPath.set('/Users/test/.portos/venv-flux2/bin/python3', '3.8.5');
+
+ const mod = await loadModule();
+ const { result } = await runInstall(mod);
+
+ expect(result.ok).toBe(true);
+ // Without --clear, `python -m venv` reuses the 3.8 interpreter in place and
+ // every retry fails identically.
+ expect(mockState.venvCalls[0]).toContain('--clear');
+ });
+
+ it('reuses a venv that already clears the floor', async () => {
+ mockState.presentPaths.add('/opt/homebrew/bin/python3');
+ mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
+ mockState.versionByPath.set('/opt/homebrew/bin/python3', '3.12.7');
+ mockState.versionByPath.set('/Users/test/.portos/venv-flux2/bin/python3', '3.12.7');
+
+ const mod = await loadModule();
+ const { result } = await runInstall(mod);
+
+ expect(result.ok).toBe(true);
+ expect(mockState.venvCalls).toEqual([]);
+ });
+});
+
+// The SSE client reads a stream that closes without a terminal frame as
+// "Connection to installer lost. Restart PortOS or try again." — so a pip step
+// that exits non-zero used to surface as a phantom transport error with the
+// real cause buried in the scrollback.
+describe('installFlux2Venv failure reporting', () => {
+ beforeEach(resetState);
+
+ const failingStage = async (needle) => {
+ mockState.presentPaths.add('/opt/homebrew/bin/python3');
+ mockState.spawnExitByArgs.set(needle, 1);
+ const mod = await loadModule();
+ const events = [];
+ const { promise } = mod.installFlux2Venv((ev) => events.push(ev));
+ return { result: await promise, events };
+ };
+
+ it('emits a terminal error frame when the pip install exits non-zero', async () => {
+ const { result, events } = await failingStage('--progress-bar');
+
+ expect(result).toEqual({ ok: false, stage: 'install' });
+ const error = events.find((ev) => ev.type === 'error');
+ expect(error.message).toContain('Installing the FLUX.2 packages failed');
+ expect(error.message).toContain('exit code 1');
+ });
+
+ it('emits a terminal error frame when the pip bootstrap exits non-zero', async () => {
+ const { result, events } = await failingStage('--upgrade pip wheel setuptools');
+
+ expect(result).toEqual({ ok: false, stage: 'upgrade-pip' });
+ expect(events.find((ev) => ev.type === 'error').message)
+ .toContain('Could not upgrade pip/wheel/setuptools');
+ });
+});
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 849051100a..38e91c7038 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -1285,6 +1285,38 @@ describe('Image Gen Routes', () => {
expect(response.text).toContain('Already installed');
});
+ // The client renders a stream that closes with no terminal frame as
+ // "Connection to installer lost. Restart PortOS or try again." — a phantom
+ // transport error that hides the real failure. installFlux2Venv emits its
+ // own error frame; this is the route's backstop for a path that doesn't.
+ it('POST /setup/flux2-install reports a silent installer failure instead of closing the stream bare', async () => {
+ const { installFlux2Venv, isFlux2VenvHealthy } = await import('../lib/pythonSetup.js');
+ isFlux2VenvHealthy.mockResolvedValueOnce(false);
+ installFlux2Venv.mockReturnValueOnce({
+ promise: Promise.resolve({ ok: false, stage: 'install' }),
+ kill: vi.fn(),
+ });
+
+ const response = await request(app).post('/api/image-gen/setup/flux2-install');
+
+ expect(response.status).toBe(200);
+ expect(response.text).toContain('"type":"error"');
+ expect(response.text).toContain('failed at the install stage');
+ });
+
+ it('POST /setup/flux2-install stays silent when the client cancelled the install', async () => {
+ const { installFlux2Venv, isFlux2VenvHealthy } = await import('../lib/pythonSetup.js');
+ isFlux2VenvHealthy.mockResolvedValueOnce(false);
+ installFlux2Venv.mockReturnValueOnce({
+ promise: Promise.resolve({ ok: false, stage: 'install', cancelled: true }),
+ kill: vi.fn(),
+ });
+
+ const response = await request(app).post('/api/image-gen/setup/flux2-install');
+
+ expect(response.text).not.toContain('"type":"error"');
+ });
+
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;
diff --git a/server/routes/imageGenSetup.js b/server/routes/imageGenSetup.js
index 57de6f80e5..a55a48e485 100644
--- a/server/routes/imageGenSetup.js
+++ b/server/routes/imageGenSetup.js
@@ -109,19 +109,31 @@ 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`.
installLog = createInstallLogger({ installer: 'FLUX.2 venv', target: FLUX2_VENV_DEFAULT });
- const emit = (ev) => { installLog.onEvent(ev); send(ev); };
+ // The client reads a stream that closes with no terminal frame as
+ // "Connection to installer lost" — a phantom transport error that hides the
+ // real cause. installFlux2Venv emits one on every non-cancelled failure;
+ // this tracks whether it did so the reconcile below can backstop a path that
+ // ever forgets, rather than letting the modal lie about why it stopped.
+ let terminalSent = false;
+ const emit = (ev) => {
+ if (ev?.type === 'error' || ev?.type === 'complete') terminalSent = true;
+ 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
- // emitting a terminal SSE event, so reconcile the outcome from the result
- // (a no-op if `onEvent` already logged a complete/error frame).
+ // Reconcile the outcome from the result — a no-op for the console logger if
+ // `onEvent` already saw a complete/error frame.
.then((result) => {
if (result?.ok) installLog.success(result?.pythonPath ? `ready: ${result.pythonPath}` : undefined);
else installLog.failure(`failed at stage ${result?.stage || 'unknown'}`);
+ if (!result?.ok && !result?.cancelled && !terminalSent) {
+ emit({ type: 'error', message: `FLUX.2 install failed at the ${result?.stage || 'unknown'} stage. See the install log above.` });
+ }
})
.catch((err) => emit({ type: 'error', message: err?.message || 'Unknown installer failure' }))
.finally(() => {