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: detect and repair missing Qwen image pipelines

[._.]/ Adam Eivyb7e5e617980f
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index a6a1e7257b..5774a00f28 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -1109,6 +1109,10 @@ if [[ "$INSTALL_FLUX2" == "1" ]]; then
"peft>=0.17" \
"optimum-quanto>=0.2.7" \
pillow
+ # Same-version dev snapshots are not replaced by --upgrade. Refresh the
+ # pipeline code without reinstalling torch or its platform-specific wheel.
+ "$FLUX2_PY" -m pip install --force-reinstall --no-deps \
+ "diffusers @ git+https://github.com/huggingface/diffusers"
probe_or_fail \
"flux2 venv built but 'from diffusers import Flux2KleinPipeline, QwenImage21Pipeline' failed." \
"Try: $FLUX2_PY -m pip install --upgrade --force-reinstall 'diffusers @ git+https://github.com/huggingface/diffusers'" \
diff --git a/scripts/z_image_turbo.py b/scripts/z_image_turbo.py
index afe20bd6ef..d7c565282a 100644
--- a/scripts/z_image_turbo.py
+++ b/scripts/z_image_turbo.py
@@ -157,6 +157,7 @@ def load_pipeline(
if pipeline_class:
cls = getattr(diffusers, pipeline_class, None)
if cls is None:
+ print("USER_ERROR:torch_runtime_broken", file=sys.stderr, flush=True)
print(
f"❌ Unknown diffusers pipeline class: {pipeline_class}. "
"Upgrade the image runtime: INSTALL_FLUX2=1 FLUX2_FORCE_REINSTALL=1 "
diff --git a/scripts/z_image_turbo_test.py b/scripts/z_image_turbo_test.py
index 783e9dcadd..05c46d194c 100644
--- a/scripts/z_image_turbo_test.py
+++ b/scripts/z_image_turbo_test.py
@@ -1,6 +1,7 @@
"""Runner contract tests without model weights or a torch installation."""
import contextlib
import importlib
+import io
import sys
import tempfile
import unittest
@@ -23,6 +24,20 @@ class Qwen21Pipeline:
class RunnerContract(unittest.TestCase):
+ def test_missing_pipeline_reports_runtime_remedy_before_exit_two(self):
+ with patch.dict(sys.modules, {'torch': SimpleNamespace()}):
+ runner = importlib.import_module('z_image_turbo')
+ stderr = io.StringIO()
+ with patch.dict(sys.modules, {'diffusers': SimpleNamespace()}), patch.multiple(
+ runner, suppress_cosmetic_clip_truncation=lambda: None,
+ heartbeat=lambda _: contextlib.nullcontext(),
+ ), contextlib.redirect_stderr(stderr), self.assertRaises(SystemExit) as stopped:
+ runner.load_pipeline('Qwen/Qwen-Image-2.1', 'cpu', 'bf16', 'QwenImage21Pipeline')
+ self.assertEqual(stopped.exception.code, 2)
+ self.assertIn('USER_ERROR:torch_runtime_broken', stderr.getvalue())
+ self.assertIn('QwenImage21Pipeline', stderr.getvalue())
+ self.assertIn('FLUX2_FORCE_REINSTALL=1', stderr.getvalue())
+
def test_qwen21_generation_and_edit_preserve_alpha(self):
torch = SimpleNamespace(
bfloat16='bf16', float32='fp32', inference_mode=contextlib.nullcontext,
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 56b6a004bd..fae0354eda 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -365,41 +365,37 @@ export function resolveFlux2Python() {
// outside PortOS) would otherwise report "unavailable" for the rest of the
// server's lifetime with no way for the user to recover short of a restart.
const FLUX2_HEALTH_NEGATIVE_TTL_MS = 60_000;
-let cachedFlux2Healthy = null;
-let cachedFlux2HealthyAt = 0;
-// In-flight dedupe. The cache is only written AFTER the probe resolves, so N
-// callers arriving on a cold or just-invalidated cache each spawned their own
-// full torch+diffusers import — seconds of CPU and hundreds of MB apiece. That
-// is not hypothetical: opening Settings › Image Gen › Local fires the status
-// probe and the runtime card together, and finishing an install invalidates the
-// cache and then re-probes from both the card and its host. Collapsing them onto
-// one promise costs nothing when the cache is warm, since that path returns
-// before this is read.
-let flux2HealthInFlight = null;
-export async function isFlux2VenvHealthy() {
- if (cachedFlux2Healthy === true) return true;
- if (cachedFlux2Healthy === false && Date.now() - cachedFlux2HealthyAt < FLUX2_HEALTH_NEGATIVE_TTL_MS) {
- return false;
- }
- if (flux2HealthInFlight) return flux2HealthInFlight;
- flux2HealthInFlight = probeFlux2Venv().finally(() => { flux2HealthInFlight = null; });
- return flux2HealthInFlight;
+// Each selected pipeline has its own verdict: FLUX.2 importing successfully
+// says nothing about a newer Qwen class being present in the same installation.
+const flux2Health = new Map();
+export async function isFlux2VenvHealthy(pipelineClass = '') {
+ const key = pipelineClass || '';
+ const cached = flux2Health.get(key);
+ if (cached?.healthy === true) return true;
+ if (cached?.healthy === false && Date.now() - cached.at < FLUX2_HEALTH_NEGATIVE_TTL_MS) return false;
+ if (cached?.pending) return cached.pending;
+ const entry = {};
+ flux2Health.set(key, entry);
+ entry.pending = probeFlux2Venv(key).then((healthy) => {
+ entry.healthy = healthy;
+ entry.at = Date.now();
+ return healthy;
+ }).finally(() => { entry.pending = null; });
+ return entry.pending;
}
-async function probeFlux2Venv() {
+async function probeFlux2Venv(pipelineClass) {
const py = resolveFlux2Python();
- const ok = py
- ? await execFileAsync(py, ['-c', 'from diffusers import Flux2KleinPipeline'], safeChildProcessOptions({ timeout: 30_000 }))
+ // Pass registry content as argv, never interpolate it into Python code.
+ const probe = 'from diffusers import Flux2KleinPipeline; import diffusers, sys; getattr(diffusers, sys.argv[1]) if sys.argv[1] else None';
+ return py
+ ? await execFileAsync(py, ['-c', probe, pipelineClass], safeChildProcessOptions({ timeout: 30_000 }))
.then(() => true)
.catch(() => false)
: false;
- cachedFlux2Healthy = ok;
- cachedFlux2HealthyAt = Date.now();
- return ok;
}
export function invalidateFlux2Health() {
cachedFlux2Python = null;
- cachedFlux2Healthy = null;
- cachedFlux2HealthyAt = 0;
+ flux2Health.clear();
}
// mflux's `mflux-train` LoRA trainer CLI is a console script installed beside
@@ -1067,6 +1063,14 @@ export function installFlux2Venv(onLog) {
}
if (killed) return { ok: false, stage: 'install', cancelled: true };
+ // Git snapshots can share a dev version; --upgrade alone then keeps the
+ // older installed code. Refresh only diffusers, preserving the torch wheel.
+ if (!await runPython([venvPython, '-m', 'pip', 'install', '--force-reinstall', '--no-deps',
+ FLUX2_PIP_SPECS.find((spec) => spec.startsWith('diffusers @ '))])) {
+ return fail('install', 'Refreshing the diffusers pipeline code failed.');
+ }
+ if (killed) return { ok: false, stage: 'install', cancelled: true };
+
stage('verify', 'Verifying FLUX.2 and Qwen 2.1 pipeline imports…');
if (!await runPython([venvPython, '-c', 'from diffusers import Flux2KleinPipeline, QwenImage21Pipeline; print("ok")'])) {
onLog({ type: 'error', message: 'Verification failed: FLUX.2 or Qwen 2.1 pipeline did not import. Try INSTALL_FLUX2=1 FLUX2_FORCE_REINSTALL=1 bash scripts/setup-image-video.sh' });
diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.js
index c5392449e5..d209a0a4c2 100644
--- a/server/lib/pythonSetup.test.js
+++ b/server/lib/pythonSetup.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { posixPath } from './testHelper.js';
// Mutable state read by the hoisted vi.mock factories below. Each test mutates
@@ -20,6 +20,7 @@ const mockState = {
// of execShouldFail (which also drives the unrelated arch probe).
fluxImportShouldFail: false,
fluxImportCalls: 0,
+ missingPipeline: null,
// `sys.version_info` answers per interpreter path, for the MIN_VENV_PYTHON
// gate. Unlisted paths answer with `defaultVersion`.
versionByPath: new Map(),
@@ -103,7 +104,7 @@ vi.mock('./childProcess.js', async () => {
resolve({ stdout: `${a}\n`, stderr: '' });
} else if (probeArg.includes('Flux2KleinPipeline')) {
mockState.fluxImportCalls += 1;
- if (mockState.fluxImportShouldFail) reject(new Error('ModuleNotFoundError'));
+ if (mockState.fluxImportShouldFail || (mockState.missingPipeline && args[2] === mockState.missingPipeline)) reject(new Error('ModuleNotFoundError'));
else resolve({ stdout: '', stderr: '' });
} else {
resolve({ stdout: '', stderr: '' });
@@ -151,6 +152,7 @@ const resetState = () => {
mockState.uvPythonDirs = null;
mockState.fluxImportShouldFail = false;
mockState.fluxImportCalls = 0;
+ mockState.missingPipeline = null;
mockState.versionByPath = new Map();
mockState.defaultVersion = '3.12.4';
mockState.spawnExitByArgs = new Map();
@@ -534,6 +536,18 @@ describe('isFlux2VenvHealthy', () => {
expect(mockState.fluxImportCalls).toBe(2);
});
+ it('keeps selected-pipeline readiness separate and refreshes it after runtime repair', async () => {
+ mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
+ mockState.missingPipeline = 'QwenImage21Pipeline';
+ const { isFlux2VenvHealthy, invalidateFlux2Health } = await loadModule();
+ await expect(isFlux2VenvHealthy()).resolves.toBe(true);
+ await expect(isFlux2VenvHealthy('QwenImage21Pipeline')).resolves.toBe(false);
+ await expect(isFlux2VenvHealthy()).resolves.toBe(true);
+ mockState.missingPipeline = null;
+ invalidateFlux2Health();
+ await expect(isFlux2VenvHealthy('QwenImage21Pipeline')).resolves.toBe(true);
+ });
+
it('caches a healthy result indefinitely', async () => {
mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
vi.useFakeTimers();
@@ -675,6 +689,12 @@ describe('installFlux2Venv failure reporting', () => {
expect(error.message).toContain('exit code 1');
});
+ it('fails the install when refreshing same-version diffusers code fails', async () => {
+ const { result, events } = await failingStage('--force-reinstall --no-deps');
+ expect(result).toEqual({ ok: false, stage: 'install' });
+ expect(events.find((ev) => ev.type === 'error').message).toContain('Refreshing the diffusers pipeline code failed');
+ });
+
it('emits a terminal error frame when the pip bootstrap exits non-zero', async () => {
const { result, events } = await failingStage('--upgrade pip wheel setuptools');
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index af5581b010..047cdb0526 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -590,7 +590,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// Decks page rendered that as an unexplained "Failed" badge. Refuse up front
// with the same reason and one-button remedy the status probe reports.
if (usesTorchVenv(model)) {
- const healthy = await isFlux2VenvHealthy().then((v) => v).catch(() => null);
+ const healthy = await isFlux2VenvHealthy(model.pipelineClass).then((v) => v).catch(() => null);
if (healthy === false) {
throw new ServerError(
`The shared torch image runtime is not installed or healthy (expected at ${FLUX2_VENV_DEFAULT}). Install it from Settings › Image Gen › Local, then retry. FLUX.2, Z-Image, ERNIE, HiDream and Qwen all render through it.`,
@@ -978,6 +978,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// the runtime still failed to import. Bust the health cache so the next
// status poll reports the truth instead of the cached pass, and name the
// same one-button remedy rather than leaving the caller with "Exit code 1".
+ if (userKind === 'torch_runtime_broken') invalidateFlux2Health();
if (!userMessage && usesTorchVenv(model)) {
const importBroken = lines.some((l) => /^(ModuleNotFoundError|ImportError)\b/.test(l) || /cannot import name /.test(l));
if (importBroken) {
@@ -1013,13 +1014,13 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
? `${userMessage}\n\n(diagnostic) ${reason}`
: `Generation failed: ${reason}\n${tail}`;
console.error(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${userMessage || reason}`);
- job.error = userMessage || reason;
+ job.error = userMessage || errorText;
job.errorKind = userKind;
job.errorRepo = userRepo;
broadcastSse(job, { type: 'error', error: errorText, kind: userKind, repo: userRepo });
// Propagate the friendly message (not the raw "Exit code 1") to the
// job queue so its `failed` log line and future SSE replays carry it.
- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: userMessage || reason });
+ imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: job.error });
} else {
job.status = 'complete';
// Large-source regen (issue #912): the render ran at a clamped FLUX-sane
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 76f9380318..4097b83260 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -2,6 +2,14 @@ import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vites
import { mkdtempSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
+import { EventEmitter } from 'node:events';
+
+const mockSpawn = vi.fn();
+vi.mock('../../lib/childProcess.js', async (original) => ({ ...await original(), spawn: (...args) => mockSpawn(...args) }));
+vi.mock('../../lib/heavyJobClaim.js', () => ({ claimHeavyLocalJob: async () => ({ ok: true, release: async () => {} }) }));
+vi.mock('../localMemory.js', () => ({ gpuBlockersMessage: vi.fn(), prepareLocalMemory: async () => ({ blockers: [], unloaded: [] }) }));
+vi.mock('../hfToken.js', () => ({ hfChildEnv: async () => ({}) }));
+vi.mock('../../lib/fileUtils.js', async (original) => ({ ...await original(), ensureDir: vi.fn() }));
// FLUX.2 venv resolution mock — flip between "installed" and "missing" with
// the .returnValue setter on each test.
@@ -11,7 +19,7 @@ const mockResolveFlux2Python = vi.fn();
const mockIsFlux2VenvHealthy = vi.fn(async () => true);
vi.mock('../../lib/pythonSetup.js', () => ({
resolveFlux2Python: () => mockResolveFlux2Python(),
- isFlux2VenvHealthy: () => mockIsFlux2VenvHealthy(),
+ isFlux2VenvHealthy: (...args) => mockIsFlux2VenvHealthy(...args),
invalidateFlux2Health: vi.fn(),
FLUX2_VENV_DEFAULT: '/fake/home/.portos/venv-flux2/bin/python3',
}));
@@ -995,11 +1003,39 @@ describe('imageGen local.generateImage runtime pre-flight', () => {
mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
mockIsFlux2VenvHealthy.mockResolvedValue(false);
- await expect(generateImage({ modelId: 'flux2-klein-4b', prompt: 'a fox' })).rejects.toMatchObject({
+ await expect(generateImage({ modelId: 'qwen-image-2.1', prompt: 'a fox' })).rejects.toMatchObject({
// Same code buildArgs throws when the venv's python is missing outright.
code: 'IMAGE_GEN_FLUX2_NOT_INSTALLED',
status: 400,
message: expect.stringContaining('not installed or healthy'),
});
+ expect(mockIsFlux2VenvHealthy).toHaveBeenCalledWith('QwenImage21Pipeline');
+ });
+});
+
+// Regression: SSE had the Python diagnosis, but the queue and status snapshot
+// replaced it with only an exit code. Exercise the actual child close boundary.
+describe('local render failure delivery', () => {
+ it.each([
+ ['USER_ERROR:torch_runtime_broken\n❌ Unknown diffusers pipeline class: QwenImage21Pipeline. Reinstall the runtime.\n', 'Reinstall the runtime.'],
+ ['runner.py: error: invalid value for --steps\n', 'invalid value for --steps'],
+ ])('preserves the runner diagnosis in failed events and SSE replays', async (stderr, expected) => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ mockIsFlux2VenvHealthy.mockResolvedValue(true);
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ mockSpawn.mockReturnValue(child);
+ const { imageGenEvents } = await import('../imageGenEvents.js');
+ const { attachSseClient } = await import('./local.js');
+ const failed = new Promise((resolve) => imageGenEvents.once('failed', resolve));
+ const { jobId } = await generateImage({ modelId: 'qwen-image-2.1', prompt: 'a fox' });
+ child.stderr.emit('data', Buffer.from(stderr));
+ child.emit('close', 2);
+ expect((await failed).error).toContain(expected);
+ const response = { writeHead: vi.fn(), write: vi.fn(), end: vi.fn(), req: new EventEmitter() };
+ expect(attachSseClient(jobId, response)).toBe(true);
+ expect(response.write.mock.calls[0][0]).toContain(expected);
+ response.req.emit('close');
});
});
diff --git a/server/services/imageGen/localRuntime.js b/server/services/imageGen/localRuntime.js
index fb3d5e1242..3ae74880f4 100644
--- a/server/services/imageGen/localRuntime.js
+++ b/server/services/imageGen/localRuntime.js
@@ -85,7 +85,7 @@ export async function diagnoseLocalRuntime({ modelId: requestedModelId, settings
// binary, and treating that as ready is how a deck render ended up reporting
// a bare `Exit code 1`. Memoized in pythonSetup so ordinary status polls do
// not repeatedly import torch.
- const healthy = await isFlux2VenvHealthy().then((value) => value).catch(() => null);
+ const healthy = await isFlux2VenvHealthy(model.pipelineClass).then((value) => value).catch(() => null);
if (healthy === true) return verdict({ readiness: READY });
if (healthy === false) {
return verdict({
diff --git a/server/services/imageGen/localRuntime.test.js b/server/services/imageGen/localRuntime.test.js
index 784aace387..e111ae7929 100644
--- a/server/services/imageGen/localRuntime.test.js
+++ b/server/services/imageGen/localRuntime.test.js
@@ -29,8 +29,8 @@ beforeEach(() => {
// reported "All required packages installed" for an unrenderable machine.
describe('diagnoseLocalRuntime remedies', () => {
it('offers the runtime install for a model whose shared torch venv is unhealthy', async () => {
- models.value = [{ ...mflux, id: 'z-image', runner: 'z-image' }];
- settings.value = { imageGen: { local: { modelId: 'z-image' } } };
+ models.value = [{ ...mflux, id: 'qwen-image-2.1', runner: 'qwen', pipelineClass: 'QwenImage21Pipeline' }];
+ settings.value = { imageGen: { local: { modelId: 'qwen-image-2.1' } } };
isFlux2VenvHealthy.mockResolvedValue(false);
await expect(diagnoseLocalRuntime()).resolves.toMatchObject({
@@ -38,6 +38,7 @@ describe('diagnoseLocalRuntime remedies', () => {
runtime: 'torch-venv',
remedy: { kind: 'install-torch-venv', venvPath: '/test/venv-flux2/bin/python3' },
});
+ expect(isFlux2VenvHealthy).toHaveBeenCalledWith('QwenImage21Pipeline');
});
it('offers the pip install, with the pip-spec names, for a missing mflux package', async () => {