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: stop caching a failed FLUX.2 venv health check forever, and extend the fix UI to non-flux diffusers models

Adam Eivybb49005ee8c4
diff --git a/client/src/lib/runnerFamilies.js b/client/src/lib/runnerFamilies.js
index 56becd2936..b656cba740 100644
--- a/client/src/lib/runnerFamilies.js
+++ b/client/src/lib/runnerFamilies.js
@@ -12,6 +12,15 @@ export const RUNNER_FAMILIES = Object.freeze({
QWEN: 'qwen',
});
+// Predicate: model runs through the generic diffusers runner script and so
+// shares the FLUX.2 venv's health check (isFlux2VenvHealthy in
+// server/lib/pythonSetup.js) — Z-Image, ERNIE, HiDream, and Qwen all dispatch
+// through that same shared torch venv rather than the mflux interpreter.
+// Mirror of server/lib/runners.js#usesDiffusersRunner.
+export const usesDiffusersRunner = (model) => [
+ RUNNER_FAMILIES.Z_IMAGE, RUNNER_FAMILIES.ERNIE, RUNNER_FAMILIES.HIDREAM, RUNNER_FAMILIES.QWEN,
+].includes(model?.runner);
+
// Video-LoRA families — kept separate from the image RUNNER_FAMILIES so the
// Civitai iteration (which only knows image baseModels) never sees them. Video
// LoRAs are imported from HuggingFace. Mirror of server/lib/runners.js.
diff --git a/client/src/lib/runnerFamilies.test.js b/client/src/lib/runnerFamilies.test.js
index 328ab2fb24..e9e4186674 100644
--- a/client/src/lib/runnerFamilies.test.js
+++ b/client/src/lib/runnerFamilies.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, flux2VariantFromModel, isVideoLoraFamily,
- loraCompatKey, composeCompatKey, loraFamilyOf, videoLoraFamily,
+ loraCompatKey, composeCompatKey, loraFamilyOf, videoLoraFamily, usesDiffusersRunner,
} from './runnerFamilies';
// This is the client mirror of server/lib/runners.js. The server suite greps
@@ -54,6 +54,16 @@ describe('runnerFamilies mirror', () => {
expect(loraFamilyOf(null)).toBe(null);
});
+ it('usesDiffusersRunner matches the shared-torch-venv families, not flux2/mflux', () => {
+ expect(usesDiffusersRunner({ runner: RUNNER_FAMILIES.Z_IMAGE })).toBe(true);
+ expect(usesDiffusersRunner({ runner: RUNNER_FAMILIES.ERNIE })).toBe(true);
+ expect(usesDiffusersRunner({ runner: RUNNER_FAMILIES.HIDREAM })).toBe(true);
+ expect(usesDiffusersRunner({ runner: RUNNER_FAMILIES.QWEN })).toBe(true);
+ expect(usesDiffusersRunner({ runner: RUNNER_FAMILIES.FLUX2 })).toBe(false);
+ expect(usesDiffusersRunner({ runner: RUNNER_FAMILIES.MFLUX })).toBe(false);
+ expect(usesDiffusersRunner(null)).toBe(false);
+ });
+
it('treats both video families as video, so an H3 LoRA deep-links to Video Gen', () => {
expect(isVideoLoraFamily(VIDEO_LORA_FAMILIES.MINIMAX_H3)).toBe(true);
expect(isVideoLoraFamily(VIDEO_LORA_FAMILIES.LTX_VIDEO)).toBe(true);
diff --git a/client/src/pages/ImageGen.flux2VenvShare.test.jsx b/client/src/pages/ImageGen.flux2VenvShare.test.jsx
new file mode 100644
index 0000000000..c966cbb762
--- /dev/null
+++ b/client/src/pages/ImageGen.flux2VenvShare.test.jsx
@@ -0,0 +1,97 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+// Z-Image dispatches through the same shared torch venv FLUX.2 does
+// (usesDiffusersRunner in runnerFamilies.js / runners.js), so a broken venv
+// must surface the same install banner FLUX.2 models get — with FLUX.2-only
+// wording (and the HF-gated-repo token banner) suppressed, since Z-Image
+// isn't a gated repo.
+const MODEL = { id: 'z-turbo', name: 'Z-Image Turbo', runner: 'z-image' };
+
+vi.mock('../services/api', () => ({
+ getInstances: vi.fn(async () => ({ peers: [] })),
+ getImageGenStatus: vi.fn(async () => ({ connected: true, mode: 'local', model: 'Z-Image Turbo' })),
+ generateImage: vi.fn(async () => ({ jobId: 'job-1' })),
+ generateImageMultipart: vi.fn(async () => ({})),
+ listImageModels: vi.fn(async () => [MODEL]),
+ listLorasFull: vi.fn(async () => []),
+ listImageGallery: vi.fn(async () => []),
+ cancelImageGen: vi.fn(async () => ({})),
+ deleteImage: vi.fn(async () => ({})),
+ setImageHidden: vi.fn(async () => ({})),
+ cleanGalleryImage: vi.fn(async () => ({})),
+ getActiveImageJob: vi.fn(async () => ({ activeJob: null })),
+ getSettings: vi.fn(async () => ({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3', modelId: 'z-turbo' } } })),
+ buildFormData: vi.fn(() => new FormData()),
+ listMediaJobs: vi.fn(async () => ({ jobs: [] })),
+ regenerateGalleryImage: vi.fn(async () => ({})),
+ getRegenAvailability: vi.fn(async () => ({ available: false })),
+ removeImageWatermark: vi.fn(async () => ({})),
+ getFlux2Status: vi.fn(async () => ({
+ venvInstalled: false, hfTokenPresent: false, licenseUrl: 'https://huggingface.co/example',
+ })),
+}));
+
+vi.mock('../hooks/useImageGenProgress', () => ({
+ useImageGenProgress: () => ({ progress: null, begin: vi.fn(), end: vi.fn(), resume: vi.fn() }),
+}));
+vi.mock('../hooks/useMediaJobSse', () => ({
+ useMediaJobSse: () => ({ attach: vi.fn(), eventSourceRef: { current: null } }),
+}));
+vi.mock('../hooks/useModelDownloadStatus', () => ({
+ useModelDownloadStatus: () => ({
+ getStatus: () => ({ cached: true }), start: vi.fn(), cancel: vi.fn(), repair: vi.fn(), refresh: vi.fn(),
+ downloading: false, repairing: false, progress: null, lastError: null, activeModelId: null, extra: {}, loading: false, statusError: null,
+ }),
+}));
+vi.mock('../hooks/useHfTokenStatus', () => ({ useHfTokenStatus: () => ({ present: true, refresh: vi.fn() }) }));
+vi.mock('../hooks/useAgyModels', () => ({ useAgyModels: () => ({ models: [], error: null }) }));
+vi.mock('../hooks/useMediaCompletionRefresh', () => ({ useMediaCompletionRefresh: vi.fn() }));
+vi.mock('../hooks/useMediaAnnotations', () => ({
+ useMediaAnnotations: () => ({ annotations: {}, updateAnnotation: vi.fn(), getCardProps: vi.fn(() => ({})) }),
+}));
+vi.mock('../hooks/useAutoRefetch', () => ({ useAutoRefetch: vi.fn() }));
+vi.mock('../hooks/usePreviewRoute', () => ({ default: () => [null, vi.fn()] }));
+vi.mock('../components/ui/Toast', () => ({
+ default: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), loading: vi.fn() }),
+}));
+vi.mock('../components/media/PromptEnhancer', () => ({ default: () => null }));
+vi.mock('../components/media/PromptFromMedia', () => ({ default: () => null }));
+vi.mock('../components/media/UniverseStylePicker', () => ({ default: () => null }));
+vi.mock('../components/media/StylePresetPicker', () => ({ default: () => null }));
+vi.mock('../components/media/MediaPreview', () => ({ default: () => null }));
+vi.mock('../components/media/MediaJobsQueue', () => ({ default: () => null }));
+vi.mock('../components/media/ResolutionField', () => ({ default: () => null }));
+vi.mock('../components/Drawer', () => ({ default: () => null }));
+vi.mock('../components/settings/ImageGenTab', () => ({ ImageGenTab: () => null }));
+vi.mock('../components/imageGen/Flux2InstallModal', () => ({ default: () => null }));
+vi.mock('../components/imageGen/GalleryImagePicker', () => ({ default: () => null }));
+vi.mock('../components/imageGen/InitImagePicker', () => ({ default: () => null }));
+vi.mock('../components/imageGen/ReferenceImagePicker', () => ({ default: () => null }));
+vi.mock('../components/imageGen/LoraPicker', () => ({ default: () => null }));
+
+const { default: ImageGen } = await import('./ImageGen.jsx');
+
+const mount = async () => {
+ await act(async () => {
+ render(
+ <MemoryRouter initialEntries={['/media/image']}>
+ <ImageGen />
+ </MemoryRouter>,
+ );
+ });
+};
+
+describe('ImageGen shared-venv install banner for non-flux2 diffusers models', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('shows the install banner (with model-specific wording, not an HF-token banner) when the shared venv is unhealthy', async () => {
+ await mount();
+
+ const banner = await screen.findByRole('button', { name: /Install FLUX.2/i });
+ expect(banner).toBeInTheDocument();
+ expect(screen.getByText(/Z-Image Turbo shares the FLUX.2 torch runtime/i)).toBeInTheDocument();
+ expect(screen.queryByText(/accept.*license/i)).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 4d00418253..cb369c9fd3 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -21,7 +21,7 @@ import PromptEnhancer from '../components/media/PromptEnhancer';
import PromptFromMedia from '../components/media/PromptFromMedia';
import BackendChipStrip from '../components/media/BackendChipStrip';
import { normalizeImage } from '../components/media/normalize';
-import { RUNNER_FAMILIES, loraCompatKey } from '../lib/runnerFamilies';
+import { RUNNER_FAMILIES, loraCompatKey, usesDiffusersRunner } from '../lib/runnerFamilies';
import { appendTriggerWords } from '../lib/loraTriggers';
import Flux2InstallModal from '../components/imageGen/Flux2InstallModal';
import HfTokenBanner from '../components/imageGen/HfTokenBanner';
@@ -674,6 +674,12 @@ export default function ImageGen() {
const currentModel = models.find((m) => m.id === modelId);
const isFlux2Model = currentModel?.runner === RUNNER_FAMILIES.FLUX2;
+ // Z-Image/ERNIE/HiDream/Qwen dispatch through the same shared torch venv
+ // FLUX.2 does (isFlux2VenvHealthy in pythonSetup.js gates all of them), so
+ // the install/repair flow below has to cover them too — otherwise a user on
+ // one of those models hits the "FLUX.2 runtime" gate with no UI path to fix
+ // it, since the fetch + Install button used to be flux2-only.
+ const sharesFlux2Venv = isFlux2Model || usesDiffusersRunner(currentModel);
// Edit-only models (Qwen-Image-Edit) require a source image — submitting
// text-only crashes the runner, so the server rejects it and we gate the
// submit button + show a hint rather than letting the user hit a failed job.
@@ -791,14 +797,14 @@ export default function ImageGen() {
}, [refreshFlux2Status]);
useEffect(() => {
- if (!isFlux2Model) { setFlux2Status(null); return; }
+ if (!sharesFlux2Venv) { setFlux2Status(null); return; }
// Abort the in-flight request when the user switches models before it
// resolves — otherwise a stale response could re-show the banner for
- // a non-flux2 selection.
+ // a selection that doesn't share the venv.
const controller = new AbortController();
refreshFlux2Status(controller.signal);
return () => controller.abort();
- }, [isFlux2Model, modelId, refreshFlux2Status]);
+ }, [sharesFlux2Venv, modelId, refreshFlux2Status]);
// Lazy-fetch HF token presence for legacy mflux gated models (FLUX.1-dev).
// FLUX.2 has its own combined status fetch above (which also covers the
@@ -836,8 +842,11 @@ export default function ImageGen() {
}, [generating, refreshGallery]);
useAutoRefetch(pollQueue, 4000, { enabled: queueActive, pollOnly: true });
- const flux2Issue = isFlux2Model && flux2Status
- ? (!flux2Status.venvInstalled ? 'venv' : !flux2Status.hfTokenPresent ? 'token' : null)
+ // The HF-gated-repo "token" issue only applies to actual FLUX.2 models —
+ // Z-Image/ERNIE/HiDream/Qwen share the venv but aren't gated repos, so a
+ // missing HF token must not block them.
+ const flux2Issue = sharesFlux2Venv && flux2Status
+ ? (!flux2Status.venvInstalled ? 'venv' : (isFlux2Model && !flux2Status.hfTokenPresent) ? 'token' : null)
: null;
const { visibleGallery, hiddenGallery } = useMemo(() => {
const visible = gallery.filter((img) => !img.hidden);
@@ -1361,8 +1370,10 @@ export default function ImageGen() {
{flux2Issue === 'venv' && (
<div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
<div>
- FLUX.2 runtime isn't installed yet. PortOS can set it up automatically
- — torch + diffusers download, ~3-10 min on first run.
+ {isFlux2Model
+ ? "FLUX.2 runtime isn't installed yet."
+ : `${currentModel?.name || 'This model'} shares the FLUX.2 torch runtime, which isn't installed yet.`}
+ {' '}PortOS can set it up automatically — torch + diffusers download, ~3-10 min on first run.
</div>
<button
type="button"
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index af64ad828d..287f2dc217 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -254,20 +254,36 @@ export function resolveFlux2Python() {
// killed-mid-install run leaves the binary but no packages, and we'd
// otherwise report that broken state as "ready" forever. Cached because the
// import probe spawns a process; bust via invalidateFlux2Health().
+//
+// A positive result is cached indefinitely — once the venv imports cleanly it
+// stays that way short of the user deleting it, which only happens through
+// this module's own install/invalidate path. A NEGATIVE result gets a short
+// TTL instead of the same indefinite cache: the shared diffusers venv also
+// gates Z-Image/ERNIE/HiDream/Qwen (usesDiffusersRunner in runners.js), and a
+// transient failure (venv mid-install, a package upgrade the user ran by hand
+// 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;
export async function isFlux2VenvHealthy() {
- if (cachedFlux2Healthy !== null) return cachedFlux2Healthy;
+ if (cachedFlux2Healthy === true) return true;
+ if (cachedFlux2Healthy === false && Date.now() - cachedFlux2HealthyAt < FLUX2_HEALTH_NEGATIVE_TTL_MS) {
+ return false;
+ }
const py = resolveFlux2Python();
- if (!py) { cachedFlux2Healthy = false; return false; }
+ if (!py) { cachedFlux2Healthy = false; cachedFlux2HealthyAt = Date.now(); return false; }
const ok = await execFileAsync(py, ['-c', 'from diffusers import Flux2KleinPipeline'], safeChildProcessOptions({ timeout: 30_000 }))
.then(() => true)
.catch(() => false);
cachedFlux2Healthy = ok;
+ cachedFlux2HealthyAt = Date.now();
return ok;
}
export function invalidateFlux2Health() {
cachedFlux2Python = null;
cachedFlux2Healthy = null;
+ cachedFlux2HealthyAt = 0;
}
// mflux's `mflux-train` LoRA trainer CLI is a console script installed beside
diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.js
index 780c629d03..6b956787ab 100644
--- a/server/lib/pythonSetup.test.js
+++ b/server/lib/pythonSetup.test.js
@@ -16,6 +16,10 @@ const mockState = {
pathPython: null,
// Directory names under uv python root, as readdirSync would return them.
uvPythonDirs: null,
+ // Controls the `from diffusers import Flux2KleinPipeline` probe independently
+ // of execShouldFail (which also drives the unrelated arch probe).
+ fluxImportShouldFail: false,
+ fluxImportCalls: 0,
};
vi.mock('node:os', async () => {
@@ -64,6 +68,10 @@ vi.mock('./childProcess.js', async () => {
if (probeArg.includes('platform.machine')) {
const a = mockState.archByPath.get(bin) ?? mockState.arch;
resolve({ stdout: `${a}\n`, stderr: '' });
+ } else if (probeArg.includes('Flux2KleinPipeline')) {
+ mockState.fluxImportCalls += 1;
+ if (mockState.fluxImportShouldFail) reject(new Error('ModuleNotFoundError'));
+ else resolve({ stdout: '', stderr: '' });
} else {
resolve({ stdout: '', stderr: '' });
}
@@ -95,6 +103,8 @@ const resetState = () => {
mockState.execShouldFail = false;
mockState.pathPython = null;
mockState.uvPythonDirs = null;
+ mockState.fluxImportShouldFail = false;
+ mockState.fluxImportCalls = 0;
};
describe('REQUIRED_PACKAGES', () => {
@@ -398,3 +408,42 @@ describe('detectVenvBasePythonSync', () => {
expect(detectVenvBasePythonSync()).toBeNull();
});
});
+
+describe('isFlux2VenvHealthy', () => {
+ beforeEach(resetState);
+ afterEach(() => vi.useRealTimers());
+
+ it('re-probes after a short TTL instead of caching a failure forever', async () => {
+ mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
+ mockState.fluxImportShouldFail = true;
+ vi.useFakeTimers();
+ const { isFlux2VenvHealthy } = await loadModule();
+
+ await expect(isFlux2VenvHealthy()).resolves.toBe(false);
+ expect(mockState.fluxImportCalls).toBe(1);
+
+ // The package now imports fine (e.g. the user finished installing it by
+ // hand), but the cached negative result must not re-probe immediately.
+ mockState.fluxImportShouldFail = false;
+ await expect(isFlux2VenvHealthy()).resolves.toBe(false);
+ expect(mockState.fluxImportCalls).toBe(1);
+
+ // Once the negative-result TTL elapses, the next call re-probes and picks
+ // up the fixed state without requiring a server restart.
+ await vi.advanceTimersByTimeAsync(60_001);
+ await expect(isFlux2VenvHealthy()).resolves.toBe(true);
+ expect(mockState.fluxImportCalls).toBe(2);
+ });
+
+ it('caches a healthy result indefinitely', async () => {
+ mockState.presentPaths.add('/Users/test/.portos/venv-flux2/bin/python3');
+ vi.useFakeTimers();
+ const { isFlux2VenvHealthy } = await loadModule();
+
+ await expect(isFlux2VenvHealthy()).resolves.toBe(true);
+ mockState.fluxImportShouldFail = true; // must not matter — already cached true
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ await expect(isFlux2VenvHealthy()).resolves.toBe(true);
+ expect(mockState.fluxImportCalls).toBe(1);
+ });
+});