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

feat(issue-2787): build a dedicated mflux venv when the system python is unsuitable

[._.]/ Adam Eivy67c842eff050
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index a177838484..f8a92bfbbd 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -103,22 +103,69 @@ if [[ "$INSTALL_MFLUX" == "1" ]]; then
MFLUX_PIN='mflux==0.17.5'
MLX_PIN='mlx==0.31.2'
MLX_METAL_PIN='mlx-metal==0.31.2'
- # 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)
- # WITHOUT re-downloading the heavy torch/mlx tree.
- "$PYTHON_BIN" -m pip install --upgrade --user --force-reinstall --no-deps "$MFLUX_PIN"
- # Step 2: let pip install mflux's DECLARED runtime deps — pip is the source
- # of truth, not a hand-kept list. mflux 0.17 imports packages the 0.12.x set
- # omitted (pillow, matplotlib, platformdirs, sentencepiece, piexif, …) and
- # constrains transformers>=5,<6 and mlx<0.32; a hand list silently drifts and
- # leaves `mflux-train` failing at import before it can reach the trainer.
- # No --no-deps (so missing deps ARE pulled) and no --upgrade (so an
- # already-satisfied heavyweight like torch isn't re-resolved/re-downloaded on
- # repeat runs); a dep that violates mflux's constraints is still corrected.
- # The explicit mlx/mlx-metal pins ride alongside mflux so pip resolves the
- # proven backend rather than the latest in-range build.
- "$PYTHON_BIN" -m pip install --user "$MFLUX_PIN" "$MLX_PIN" "$MLX_METAL_PIN"
+ # mflux/mlx need Python 3.10+. The historical layout installs mflux with
+ # `pip install --user` against $PYTHON_BIN, and PortOS finds `mflux-train`
+ # beside that interpreter. But when $PYTHON_BIN is too old (e.g. a system
+ # python3.8) or externally-managed (PEP 668) so the --user install fails or
+ # can't be imported, fall back to a dedicated venv at ~/.portos/venv-mflux —
+ # 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
+ # 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)
+ # WITHOUT re-downloading the heavy torch/mlx tree.
+ #
+ # Step 2: let pip install mflux's DECLARED runtime deps — pip is the source
+ # of truth, not a hand-kept list. mflux 0.17 imports packages the 0.12.x set
+ # omitted (pillow, matplotlib, platformdirs, sentencepiece, piexif, …) and
+ # constrains transformers>=5,<6 and mlx<0.32; a hand list silently drifts and
+ # leaves `mflux-train` failing at import before it can reach the trainer.
+ # No --no-deps (so missing deps ARE pulled) and no --upgrade (so an
+ # already-satisfied heavyweight like torch isn't re-resolved/re-downloaded on
+ # repeat runs); a dep that violates mflux's constraints is still corrected.
+ # The explicit mlx/mlx-metal pins ride alongside mflux so pip resolves the
+ # proven backend rather than the latest in-range build.
+ "$PYTHON_BIN" -m pip install --upgrade --user --force-reinstall --no-deps "$MFLUX_PIN" \
+ && "$PYTHON_BIN" -m pip install --user "$MFLUX_PIN" "$MLX_PIN" "$MLX_METAL_PIN" \
+ || MFLUX_USE_VENV=1
+ # A satisfied-looking pip run can still leave an unimportable stack on an odd
+ # system Python — verify mflux actually imports before trusting the --user path.
+ if [[ "$MFLUX_USE_VENV" == "0" ]] && ! "$PYTHON_BIN" -c 'import mflux' 2>/dev/null; then
+ echo "⚠️ mflux installed under $PYTHON_BIN but does not import — falling back to a dedicated venv."
+ MFLUX_USE_VENV=1
+ fi
+ else
+ MFLUX_PYVER="$("$PYTHON_BIN" -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || echo unknown)"
+ echo "⚠️ $PYTHON_BIN is Python ${MFLUX_PYVER} — mflux needs 3.10+; using a dedicated venv."
+ MFLUX_USE_VENV=1
+ fi
+
+ if [[ "$MFLUX_USE_VENV" == "1" ]]; then
+ # Dedicated mflux venv (Python 3.11) built with uv, mirroring the flux2/ltx/
+ # wan runtimes. uv provisions a managed 3.11 even when the system Python is
+ # unusable, which is exactly the case we're recovering from.
+ if ! have uv; then
+ echo "❌ Need 'uv' to build the mflux venv (system Python can't host mflux)." >&2
+ echo " Install uv (https://docs.astral.sh/uv/) or point PYTHON_BIN at a Python 3.10+, then re-run." >&2
+ exit 1
+ fi
+ MFLUX_VENV="${HOME}/.portos/venv-mflux"
+ MFLUX_VENV_PY="${MFLUX_VENV}/bin/python3"
+ if [[ ! -x "$MFLUX_VENV_PY" ]]; then
+ echo "📦 Creating mflux venv at ${MFLUX_VENV} (Python 3.11)..."
+ mkdir -p "${HOME}/.portos"
+ uv venv --python 3.11 "$MFLUX_VENV"
+ fi
+ echo "📦 Installing ${MFLUX_PIN} · ${MLX_PIN} · ${MLX_METAL_PIN} into ${MFLUX_VENV}..."
+ uv pip install --python "$MFLUX_VENV_PY" "$MFLUX_PIN" "$MLX_PIN" "$MLX_METAL_PIN"
+ if ! "$MFLUX_VENV_PY" -c 'import mflux' 2>/dev/null; then
+ echo "❌ mflux venv built but 'import mflux' failed." >&2
+ exit 1
+ fi
+ echo "✅ mflux venv ready: ${MFLUX_VENV_PY} (PortOS auto-discovers it — no Settings change needed)."
+ fi
fi
if [[ "$INSTALL_VIDEO" == "1" ]]; then
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 54b806923b..fa5e86dfbc 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -1,7 +1,7 @@
import { execFile, spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { arch, homedir, platform } from 'node:os';
-import { join } from 'node:path';
+import { dirname, join } from 'node:path';
import { promisify } from 'node:util';
import { PATHS } from './fileUtils.js';
import { safeChildProcessEnv, whichFirst } from './processEnv.js';
@@ -189,6 +189,50 @@ export function invalidateFlux2Health() {
cachedFlux2Healthy = null;
}
+// mflux's `mflux-train` LoRA trainer CLI is a console script installed beside
+// whichever Python pip-installed mflux. Historically that's the system /
+// image-gen Python (`pip install --user`), but on a box whose system Python
+// can't host mflux (too old, or PEP 668 externally-managed),
+// `scripts/setup-image-video.sh` instead builds a dedicated venv at
+// ~/.portos/venv-mflux — which we auto-discover here, mirroring
+// resolveFlux2Python. macOS/Linux only in practice (mflux is MLX/Apple-Silicon;
+// there's no Windows trainer), but the candidate list stays Windows-shaped for
+// symmetry with the other resolvers.
+const MFLUX_TRAIN_BIN = IS_WIN ? 'mflux-train.exe' : 'mflux-train';
+
+// True when `mflux-train` sits next to `pythonPath` (the same probe
+// loraTraining's isMfluxTrainAvailable uses; kept here so resolveMfluxPython is
+// self-contained). Null/empty path → false.
+export const hasMfluxTrain = (pythonPath) =>
+ !!pythonPath && existsSync(join(dirname(pythonPath), MFLUX_TRAIN_BIN));
+
+const MFLUX_VENV_CANDIDATES = IS_WIN
+ ? [
+ join(HOME, '.portos', 'venv-mflux', 'Scripts', 'python.exe'),
+ join(PATHS.data, 'python', 'venv-mflux', 'Scripts', 'python.exe'),
+ ]
+ : [
+ join(HOME, '.portos', 'venv-mflux', 'bin', 'python3'),
+ join(PATHS.data, 'python', 'venv-mflux', 'bin', 'python3'),
+ ];
+
+export const MFLUX_VENV_DEFAULT = MFLUX_VENV_CANDIDATES[0];
+
+// Resolve the Python whose `mflux-train` PortOS should spawn for MLX LoRA
+// training. Preference order: (1) an explicitly-configured image-gen Python
+// that actually ships mflux-train — the historical `pip --user` layout, so
+// existing installs behave exactly as before; (2) the first dedicated
+// ~/.portos/venv-mflux that ships it. When neither ships mflux-train, return
+// the configured path unchanged (or null) so the caller's isMfluxTrainAvailable
+// still reports the honest "not installed" state instead of a phantom venv path.
+export function resolveMfluxPython(configuredPath = null) {
+ if (hasMfluxTrain(configuredPath)) return configuredPath;
+ for (const p of MFLUX_VENV_CANDIDATES) {
+ if (hasMfluxTrain(p)) return p;
+ }
+ return configuredPath || null;
+}
+
// MusicGen (Pipeline Audio Phase 4c.2) runs in its own venv at
// ~/.portos/venv-musicgen — mlx + numpy + transformers, kept apart from the
// FLUX.2 torch pile. The MLX MusicGen implementation isn't a pip package, so
diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.js
index 0aba3e7538..6086c86c2f 100644
--- a/server/lib/pythonSetup.test.js
+++ b/server/lib/pythonSetup.test.js
@@ -200,3 +200,62 @@ describe('detectArm64Python', () => {
await expect(detectArm64Python()).resolves.toBe('/opt/homebrew/bin/python3');
});
});
+
+describe('hasMfluxTrain', () => {
+ beforeEach(resetState);
+
+ it('is false for a null/empty path', async () => {
+ const { hasMfluxTrain } = await loadModule();
+ expect(hasMfluxTrain(null)).toBe(false);
+ expect(hasMfluxTrain('')).toBe(false);
+ });
+
+ it('is true when mflux-train sits beside the python', async () => {
+ mockState.presentPaths.add('/opt/homebrew/bin/mflux-train');
+ const { hasMfluxTrain } = await loadModule();
+ expect(hasMfluxTrain('/opt/homebrew/bin/python3')).toBe(true);
+ });
+
+ it('is false when mflux-train is absent beside the python', async () => {
+ const { hasMfluxTrain } = await loadModule();
+ expect(hasMfluxTrain('/opt/homebrew/bin/python3')).toBe(false);
+ });
+});
+
+describe('resolveMfluxPython', () => {
+ beforeEach(resetState);
+ // darwin homedir is /Users/test → dedicated venv python is
+ // /Users/test/.portos/venv-mflux/bin/python3, mflux-train beside it.
+ const VENV_PY = '/Users/test/.portos/venv-mflux/bin/python3';
+ const VENV_TRAIN = '/Users/test/.portos/venv-mflux/bin/mflux-train';
+
+ it('prefers the configured python when it ships mflux-train (existing --user layout)', async () => {
+ mockState.presentPaths.add('/opt/homebrew/bin/mflux-train');
+ mockState.presentPaths.add(VENV_TRAIN); // even when the venv also exists, configured wins
+ const { resolveMfluxPython } = await loadModule();
+ expect(resolveMfluxPython('/opt/homebrew/bin/python3')).toBe('/opt/homebrew/bin/python3');
+ });
+
+ it('falls back to the dedicated venv when the configured python lacks mflux-train', async () => {
+ mockState.presentPaths.add(VENV_TRAIN);
+ const { resolveMfluxPython } = await loadModule();
+ expect(resolveMfluxPython('/opt/homebrew/bin/python3')).toBe(VENV_PY);
+ });
+
+ it('discovers the dedicated venv even when no python is configured', async () => {
+ mockState.presentPaths.add(VENV_TRAIN);
+ const { resolveMfluxPython } = await loadModule();
+ expect(resolveMfluxPython(null)).toBe(VENV_PY);
+ });
+
+ it('returns the configured path unchanged when neither ships mflux-train (honest "not installed")', async () => {
+ const { resolveMfluxPython } = await loadModule();
+ expect(resolveMfluxPython('/opt/homebrew/bin/python3')).toBe('/opt/homebrew/bin/python3');
+ });
+
+ it('returns null when nothing is configured and no venv exists', async () => {
+ const { resolveMfluxPython } = await loadModule();
+ expect(resolveMfluxPython(null)).toBeNull();
+ expect(resolveMfluxPython()).toBeNull();
+ });
+});
diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.js
index ed53e93e7d..e12718c8dc 100644
--- a/server/routes/loraTraining.js
+++ b/server/routes/loraTraining.js
@@ -13,7 +13,7 @@ import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { startTrainingRunSchema, validateRequest } from '../lib/validation.js';
import { assertSafeFilename } from '../lib/fileUtils.js';
-import { resolveFlux2Python, isFlux2VenvHealthy } from '../lib/pythonSetup.js';
+import { resolveFlux2Python, isFlux2VenvHealthy, resolveMfluxPython } from '../lib/pythonSetup.js';
import { getSettings } from '../services/settings.js';
import { attachSseClient, cancelJob } from '../services/mediaJobQueue/index.js';
import {
@@ -41,7 +41,10 @@ const router = Router();
// with the user's install, the torch venv is the fallback.
router.get('/status', asyncHandler(async (_req, res) => {
const settings = await getSettings();
- const mfluxPython = settings?.imageGen?.local?.pythonPath || null;
+ // Prefer the configured image-gen Python when it ships mflux-train, else the
+ // auto-discovered dedicated ~/.portos/venv-mflux — so the panel reports mflux
+ // ready even when the user never set pythonPath (fresh dedicated-venv install).
+ const mfluxPython = resolveMfluxPython(settings?.imageGen?.local?.pythonPath || null);
const flux2Python = resolveFlux2Python();
res.json({
runtimes: {
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index ef3e205f72..69e3d909c7 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -26,7 +26,7 @@ import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { spawnDetached, reapDetached, reattachDetached, isReattachable } from '../../lib/detachedSpawn.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { getImageModels } from '../../lib/mediaModels.js';
-import { resolveFlux2Python, isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
+import { resolveFlux2Python, isFlux2VenvHealthy, resolveMfluxPython } from '../../lib/pythonSetup.js';
import { getSettings } from '../settings.js';
import { enqueueJob, getJob, mediaJobEvents } from '../mediaJobQueue/index.js';
import { updateDataset } from '../loraDatasets.js';
@@ -147,7 +147,12 @@ export async function startTrainingRun({
datasetId, baseModelId, name = null, params = {}, acknowledgeCaptionLeak = false,
}) {
const settings = await getSettings();
- const pythonPath = settings?.imageGen?.local?.pythonPath || null;
+ // Resolve the mflux trainer's Python: the configured image-gen Python when it
+ // ships mflux-train (the `pip --user` layout), else an auto-discovered
+ // dedicated ~/.portos/venv-mflux (setup-image-video.sh's fallback for a system
+ // Python that can't host mflux). The resolved path threads into the job so
+ // runTraining spawns the right interpreter without re-resolving.
+ const pythonPath = resolveMfluxPython(settings?.imageGen?.local?.pythonPath || null);
// Engine pick: prefer mflux's MLX trainer when the user's mflux install
// ships it (Apple Silicon native, no second venv); fall back to the
// torch/diffusers trainer in venv-flux2.
diff --git a/server/services/loraTraining/mpsGuard.test.js b/server/services/loraTraining/mpsGuard.test.js
index 725ac4a762..34b5da4256 100644
--- a/server/services/loraTraining/mpsGuard.test.js
+++ b/server/services/loraTraining/mpsGuard.test.js
@@ -38,6 +38,9 @@ vi.mock('../mediaJobQueue/index.js', () => ({
vi.mock('../../lib/pythonSetup.js', () => ({
resolveFlux2Python: () => '/fake/venv-flux2/bin/python3',
isFlux2VenvHealthy: (...a) => isFlux2VenvHealthyMock(...a),
+ // No mflux-train anywhere → resolves to null, so routing falls through to the
+ // torch (flux2) runtime the guard protects. Mirrors resolveMfluxPython(null).
+ resolveMfluxPython: (p) => p || null,
}));
const { startTrainingRun } = await import('./index.js');