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(image-gen): report measured local readiness (#5071)

[._.]/ Adam Eivy2f7c46cc0e51
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index 50f11b6694..7421660ae0 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -23,7 +23,7 @@ import {
registerTool, updateTool, getToolsList,
saveHfToken, clearHfToken,
} from '../../services/api';
-import { deriveAvailableBackends, isCloudCliMode, IMAGE_GEN_MODE, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';
+import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';
import { resolveCleanersFromConfig } from '../../lib/imageCleaners';
import { useMediaJobSse } from '../../hooks/useMediaJobSse';
import { useAgyModels } from '../../hooks/useAgyModels';
@@ -339,6 +339,9 @@ export function ImageGenTab() {
.catch(() => setStatus({ connected: false, reason: 'Check failed', forTab: mediaTab }))
.finally(() => setChecking(false));
}, [probeMode, mediaTab]);
+ const statusReadiness = imageGenReadiness(status);
+ const statusReady = statusReadiness === 'ready';
+ const statusUnknown = statusReadiness === 'unknown';
// Backends the Test Render picker may offer — derived from the SAVED slice,
// not the live form, because a test render runs against what the server has
@@ -1363,10 +1366,10 @@ export function ImageGenTab() {
Test Connection
</button>
{status?.forTab === mediaTab && (
- <span className={`text-sm ${status.connected ? 'text-port-success' : 'text-port-error'}`}>
- {status.connected
- ? `${status.mode} — ${status.model || status.pythonPath}`
- : status.reason || 'Not connected'}
+ <span className={`text-sm ${statusReady ? 'text-port-success' : statusUnknown ? 'text-port-warning' : 'text-port-error'}`}>
+ {statusReady
+ ? `Ready — ${status.mode} — ${status.model || status.pythonPath}`
+ : `${statusUnknown ? 'Could not verify' : 'Unavailable'} — ${status.reason || 'Not connected'}`}
</span>
)}
</div>
diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsx
index 07b98b01c4..462d40b6fc 100644
--- a/client/src/components/settings/ImageGenTab.test.jsx
+++ b/client/src/components/settings/ImageGenTab.test.jsx
@@ -161,7 +161,7 @@ describe('ImageGenTab grouped tabs', () => {
getImageGenStatus.mockResolvedValue({ connected: true, mode: 'external', model: 'flux-v1' });
await renderTab();
fireEvent.click(screen.getByRole('button', { name: /Test Connection/i }));
- await waitFor(() => expect(screen.getByText(/external — flux-v1/)).toBeTruthy());
+ await waitFor(() => expect(screen.getByText(/Ready — external — flux-v1/)).toBeTruthy());
expect(getImageGenStatus).toHaveBeenCalledWith(undefined);
});
@@ -176,6 +176,20 @@ describe('ImageGenTab grouped tabs', () => {
expect(screen.queryByText(/grok — grok-cli 0\.0\.30/)).toBeNull();
});
+ it('keeps an inconclusive local probe distinct from an unavailable runtime', async () => {
+ getImageGenStatus.mockResolvedValue({
+ connected: false,
+ mode: 'local',
+ readiness: 'unknown',
+ reason: 'Could not verify the configured Python runtime',
+ });
+ await renderTab();
+ fireEvent.click(screen.getByRole('tab', { name: /^Local/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Test Connection/i }));
+
+ await waitFor(() => expect(screen.getByText(/Could not verify — Could not verify the configured Python runtime/)).toBeTruthy());
+ });
+
it('never shows an in-flight probe result under the tab the user switched to', async () => {
// Probe started on Grok, answered only after the user moved to Agy — the
// late response must not surface as if it described Agy.
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 4917409b91..bf0625f32e 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -65,7 +65,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `pipelineImageDefaults.js` | Pipeline comic-page image-gen defaults + settings reader. |
| `reverseOutlineGrid.js` | `buildPlotlineGrid` (reverse-outline scenes + plotlines → plotline-by-sequence grid rows/cells) + `sceneComponentCount`. Used by the Reverse Outline page. |
| `wrImageDefaults.js` | Writers Room per-scene image-gen defaults + style discriminators. |
-| `imageGenBackends.js` | Icon metadata + `deriveAvailableBackends` for the image-gen backends; re-exports everything from `imageGenModes.js` so consumers keep one import site. |
+| `imageGenBackends.js` | Icon metadata, `deriveAvailableBackends`, and `imageGenReadiness(status)` — a compatibility-safe `ready` / `unavailable` / `unknown` read of image-gen status responses; re-exports everything from `imageGenModes.js` so consumers keep one import site. |
| `imageGenModes.js` | Node-safe (dependency-free) image/video backend constants + pure helpers: `IMAGE_GEN_MODE`, render-target mirror (`RENDER_TARGET_OPTIONS`, `normalizeRenderPinValue`, `applyRecordRenderPin` — fold a record's `imageMode`/`imageModelId` pin over a settings-derived cfg), `VIDEO_RENDER_MODES`, `modeLabel`, cloud/model-override/i2i capability gating. Imported by the server-side parity suite — must stay importable without client packages. |
| `imageGenDefaults.js` | Shared `DEFAULT_NEGATIVE_PROMPT` used by the Image Gen form and quick-submit entry points. Mirrors server-side default. |
| `imageGenResolutions.js` | Shared resolution presets for image generation. |
diff --git a/client/src/lib/imageGenBackends.js b/client/src/lib/imageGenBackends.js
index 3fef17ee83..699c75cc8f 100644
--- a/client/src/lib/imageGenBackends.js
+++ b/client/src/lib/imageGenBackends.js
@@ -21,6 +21,14 @@ const MODE_ICONS = {
const metaFor = (mode) => ({ label: MODE_LABELS[mode], icon: MODE_ICONS[mode] });
+// Older peers and servers only return `connected`; newer local probes add a
+// three-way readiness result. Keep the compatibility read in one place so the
+// Image Gen page and Settings describe the same response identically.
+export const imageGenReadiness = (status) => {
+ if (['ready', 'unavailable', 'unknown'].includes(status?.readiness)) return status.readiness;
+ return status?.connected ? 'ready' : 'unavailable';
+};
+
export function deriveAvailableBackends(settings, { excludeExternal = false } = {}) {
const ig = settings?.imageGen || {};
const out = [];
diff --git a/client/src/lib/imageGenBackends.test.js b/client/src/lib/imageGenBackends.test.js
index 0f35308765..42dd10b1a7 100644
--- a/client/src/lib/imageGenBackends.test.js
+++ b/client/src/lib/imageGenBackends.test.js
@@ -9,11 +9,21 @@ import {
referenceSlotsFor,
supportsReferenceStrength,
deriveAvailableBackends,
+ imageGenReadiness,
applyRecordRenderPin,
renderPinLadder,
renderTargetPin,
} from './imageGenBackends';
+describe('imageGenReadiness', () => {
+ it('preserves the three-way local readiness contract and supports older responses', () => {
+ expect(imageGenReadiness({ readiness: 'ready', connected: true })).toBe('ready');
+ expect(imageGenReadiness({ readiness: 'unknown', connected: false })).toBe('unknown');
+ expect(imageGenReadiness({ connected: true })).toBe('ready');
+ expect(imageGenReadiness({ connected: false })).toBe('unavailable');
+ });
+});
+
describe('I2I_CAPABLE_MODES / isI2iCapableMode', () => {
it('treats every generation backend as i2i-capable, but not external', () => {
expect(I2I_CAPABLE_MODES).toEqual([
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 2b0c01cb35..e7bea39251 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -41,7 +41,7 @@ import {
AlertTriangle, X, Film,
} from 'lucide-react';
import { composeStyledPrompt } from '../lib/composeStyledPrompt';
-import { isCloudCliMode, deriveAvailableBackends, AGY_IMAGEGEN_DEFAULT_MODEL, IMAGE_GEN_MODE, cloudPromptRequired, isI2iCapableMode, pickI2iMode, modeLabel, referenceSlotsFor, supportsReferenceStrength } from '../lib/imageGenBackends';
+import { isCloudCliMode, deriveAvailableBackends, AGY_IMAGEGEN_DEFAULT_MODEL, IMAGE_GEN_MODE, cloudPromptRequired, imageGenReadiness, isI2iCapableMode, pickI2iMode, modeLabel, referenceSlotsFor, supportsReferenceStrength } from '../lib/imageGenBackends';
import { clampImageDimensions, clampImageEdge } from '../lib/imageGenResolutions';
import { peerModelRequiresInput } from '../lib/federatedMediaReadiness.js';
import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';
@@ -275,10 +275,10 @@ export default function ImageGen() {
// newer `local` probe that already returned green. Without this the badge
// gets stuck on "SD API unreachable" even though Local is selected.
const statusRequestToken = useRef(0);
- const refreshStatus = useCallback((mode) => {
+ const refreshStatus = useCallback((mode, localModelId) => {
const myToken = ++statusRequestToken.current;
setStatusLoading(true);
- getImageGenStatus(mode)
+ getImageGenStatus(mode, mode === IMAGE_GEN_MODE.LOCAL ? localModelId : undefined)
.then((s) => {
if (myToken !== statusRequestToken.current) return;
setStatus(s);
@@ -413,8 +413,8 @@ export default function ImageGen() {
// gating reflecting the previous backend.
useEffect(() => {
if (!effectiveMode) return;
- refreshStatus(effectiveMode);
- }, [effectiveMode, refreshStatus]);
+ refreshStatus(effectiveMode, modelId);
+ }, [effectiveMode, modelId, refreshStatus]);
// Deferred i2i mode nudge: once backends resolve, flip to an i2i-capable
// backend so the URL-supplied init image actually takes effect (the picker +
@@ -1193,6 +1193,9 @@ export default function ImageGen() {
}, [navigate]);
const notConnected = status && status.connected === false;
+ const statusReadiness = imageGenReadiness(status);
+ const statusReady = statusReadiness === 'ready';
+ const statusUnknown = statusReadiness === 'unknown';
return (
<div className="space-y-3">
@@ -1204,16 +1207,18 @@ export default function ImageGen() {
</span>
) : status ? (
<span className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-full border ${
- status.connected
+ statusReady
? 'border-port-success/40 bg-port-success/10 text-port-success'
- : 'border-port-error/40 bg-port-error/10 text-port-error'
+ : statusUnknown
+ ? 'border-port-warning/40 bg-port-warning/10 text-port-warning'
+ : 'border-port-error/40 bg-port-error/10 text-port-error'
}`}>
- {status.connected ? (
- <><span className="w-2 h-2 rounded-full bg-port-success" /> {status.model || CONNECTED_MODE_LABELS[status.mode] || 'external SD API'}</>
+ {statusReady ? (
+ <><span className="w-2 h-2 rounded-full bg-port-success" /> Ready — {status.model || CONNECTED_MODE_LABELS[status.mode] || 'external SD API'}</>
) : (
<>
<AlertTriangle className="w-3 h-3" />
- {status.reason || 'Not connected'} —
+ {statusUnknown ? 'Could not verify' : 'Unavailable'}: {status.reason || 'Not connected'} —
<button type="button" onClick={openSettings} className="underline">Settings</button>
</>
)}
@@ -1234,7 +1239,7 @@ export default function ImageGen() {
</div>
<div className="flex items-center gap-1">
<button
- onClick={() => refreshStatus(effectiveMode)}
+ onClick={() => refreshStatus(effectiveMode, modelId)}
disabled={statusLoading}
className="p-1.5 rounded text-gray-400 hover:text-white hover:bg-port-border/50 disabled:opacity-50"
title="Refresh status" aria-label="Refresh status"
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index d15e2800b0..65a380c719 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -308,7 +308,13 @@ export const getTailnetInfo = () => request('/instances/tailnet-suffix');
export const provisionTailnetCert = () => request('/instances/provision-cert', { method: 'POST' });
// Image Generation
-export const getImageGenStatus = (mode) => request(`/image-gen/status${mode ? `?mode=${encodeURIComponent(mode)}` : ''}`);
+export const getImageGenStatus = (mode, modelId) => {
+ const params = new URLSearchParams();
+ if (mode) params.set('mode', mode);
+ if (modelId) params.set('modelId', modelId);
+ const query = params.toString();
+ return request(`/image-gen/status${query ? `?${query}` : ''}`);
+};
export const generateImage = (data, options = {}) => request('/image-gen/generate', {
method: 'POST',
body: JSON.stringify(data),
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index ad9304ae81..653f1fa188 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -322,7 +322,9 @@ router.get('/status', asyncHandler(async (req, res) => {
// the dispatcher as `string | undefined`.
const rawMode = req.query.mode;
const mode = typeof rawMode === 'string' && IMAGE_GEN_MODES.includes(rawMode) ? rawMode : undefined;
- res.json(await imageGen.checkConnection({ mode }));
+ const rawModelId = req.query.modelId;
+ const modelId = typeof rawModelId === 'string' && rawModelId.length <= 64 ? rawModelId : undefined;
+ res.json(await imageGen.checkConnection({ mode, ...(modelId ? { modelId } : {}) }));
}));
router.get('/active', asyncHandler(async (_req, res) => {
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index c56066b6b4..754ae0734e 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -186,6 +186,13 @@ describe('Image Gen Routes', () => {
expect(imageGen.checkConnection).toHaveBeenCalledWith({ mode: 'codex' });
});
+ it('forwards a bounded local model selection into checkConnection', async () => {
+ imageGen.checkConnection.mockResolvedValue({ connected: true, mode: 'local', modelId: 'flux2-klein-4b' });
+ const response = await request(app).get('/api/image-gen/status?mode=local&modelId=flux2-klein-4b');
+ expect(response.status).toBe(200);
+ expect(imageGen.checkConnection).toHaveBeenCalledWith({ mode: 'local', modelId: 'flux2-klein-4b' });
+ });
+
it('ignores an invalid ?mode= query and uses the saved default', async () => {
imageGen.checkConnection.mockResolvedValue({ connected: true, mode: 'external' });
const response = await request(app).get('/api/image-gen/status?mode=bogus');
diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.js
index ebbbc3091a..ae67e66f34 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -21,13 +21,16 @@ import * as codex from './codex.js';
import * as grok from './grok.js';
import * as agy from './agy.js';
import {
- IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES, isEditCapableMode,
+ IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES, LOCAL_IMAGEGEN_DEFAULT_MODEL, isEditCapableMode,
} from './modes.js';
import { DEFAULT_NEGATIVE_PROMPT } from './defaults.js';
import { resolveCloudProviderConfig } from './cloudProviderConfig.js';
+import { getSetupCheck } from './setup.js';
import { rejectDegenerateFrame } from './frameGuard.js';
import { PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { isFlux2, usesDiffusersRunner } from '../../lib/runners.js';
+import { isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
// Cloud-CLI provider modules keyed by mode, so the shared gate in
// checkConnection/generateImage dispatches without a per-provider branch.
@@ -44,11 +47,112 @@ const CLOUD_PROVIDERS = {
// the provider modules above.
export { IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES };
const DEFAULT_MODE = IMAGE_GEN_MODE.EXTERNAL;
+const LOCAL_READINESS = Object.freeze({
+ READY: 'ready',
+ UNAVAILABLE: 'unavailable',
+ UNKNOWN: 'unknown',
+});
const cfg = (s) => s?.imageGen || {};
const sdapiUrl = (s) => cfg(s).external?.sdapiUrl || cfg(s).sdapiUrl || null;
const pythonPath = (s) => cfg(s).local?.pythonPath || null;
+const localStatus = ({ model, modelId, readiness, reason }) => ({
+ connected: readiness === LOCAL_READINESS.READY,
+ mode: IMAGE_GEN_MODE.LOCAL,
+ model: model?.name || modelId,
+ modelId,
+ runner: model?.runner || 'mflux',
+ readiness,
+ ...(reason ? { reason } : {}),
+});
+
+async function checkLocalConnection(settings, modelIdOverride) {
+ const modelId = modelIdOverride || cfg(settings).local?.modelId || LOCAL_IMAGEGEN_DEFAULT_MODEL;
+ const model = local.listImageModels().find((entry) => entry.id === modelId);
+ if (!model) {
+ return localStatus({
+ modelId,
+ readiness: LOCAL_READINESS.UNAVAILABLE,
+ reason: `Selected local model "${modelId}" is unavailable on this machine`,
+ });
+ }
+ if (model.hardwareCompatibility?.state === 'unavailable') {
+ return localStatus({
+ model,
+ modelId,
+ readiness: LOCAL_READINESS.UNAVAILABLE,
+ reason: model.hardwareCompatibility.reasons.join(' · ') || 'Selected model is incompatible with this machine',
+ });
+ }
+ if (model.hardwareCompatibility?.state === 'unknown') {
+ return localStatus({
+ model,
+ modelId,
+ readiness: LOCAL_READINESS.UNKNOWN,
+ reason: model.hardwareCompatibility.reasons.join(' · ') || 'Could not verify this machine supports the selected model',
+ });
+ }
+
+ // FLUX.2 and the Diffusers-family models use the dedicated torch venv, not
+ // the configurable mflux interpreter. Its health check is memoized by the
+ // setup flow, so ordinary status polls do not repeatedly import torch.
+ if (isFlux2(model) || usesDiffusersRunner(model)) {
+ const healthy = await isFlux2VenvHealthy().then((value) => value).catch(() => null);
+ if (healthy === true) return localStatus({ model, modelId, readiness: LOCAL_READINESS.READY });
+ if (healthy === false) {
+ return localStatus({
+ model,
+ modelId,
+ readiness: LOCAL_READINESS.UNAVAILABLE,
+ reason: 'The FLUX.2 image runtime is not installed or healthy',
+ });
+ }
+ return localStatus({
+ model,
+ modelId,
+ readiness: LOCAL_READINESS.UNKNOWN,
+ reason: 'Could not verify the FLUX.2 image runtime',
+ });
+ }
+
+ const py = pythonPath(settings);
+ if (!py) {
+ return localStatus({
+ model,
+ modelId,
+ readiness: LOCAL_READINESS.UNAVAILABLE,
+ reason: 'Python path not configured',
+ });
+ }
+ const setup = await getSetupCheck(py).then((result) => result).catch(() => null);
+ if (!setup) {
+ return localStatus({
+ model,
+ modelId,
+ readiness: LOCAL_READINESS.UNKNOWN,
+ reason: 'Could not verify the configured Python runtime',
+ });
+ }
+ if (setup.archMismatch) {
+ return localStatus({
+ model,
+ modelId,
+ readiness: LOCAL_READINESS.UNAVAILABLE,
+ reason: `Python architecture ${setup.interpreterArch || 'unknown'} is incompatible with this ${setup.hostArch || 'host'} runtime`,
+ });
+ }
+ if (setup.missing?.length) {
+ return localStatus({
+ model,
+ modelId,
+ readiness: LOCAL_READINESS.UNAVAILABLE,
+ reason: `Missing required packages: ${setup.missing.join(', ')}`,
+ });
+ }
+ return localStatus({ model, modelId, readiness: LOCAL_READINESS.READY });
+}
+
// Resolve the cleaner flags from body overrides + saved per-mode settings.
// Body fields win when explicit (per-render checkbox); otherwise inherit
// the saved per-mode defaults via `resolveCleanersFromConfig`. Shared by
@@ -67,13 +171,11 @@ export async function getMode() {
return cfg(s).mode || DEFAULT_MODE;
}
-export async function checkConnection({ mode: modeOverride } = {}) {
+export async function checkConnection({ mode: modeOverride, modelId: modelIdOverride } = {}) {
const s = await getSettings();
const mode = modeOverride || cfg(s).mode || DEFAULT_MODE;
if (mode === IMAGE_GEN_MODE.LOCAL) {
- const py = pythonPath(s);
- if (!py) return { connected: false, mode, reason: 'Python path not configured' };
- return { connected: true, mode, model: 'mflux/local', pythonPath: py };
+ return checkLocalConnection(s, modelIdOverride);
}
const cloudCheck = resolveCloudProviderConfig(s, mode);
if (cloudCheck) {
diff --git a/server/services/imageGen/index.test.js b/server/services/imageGen/index.test.js
new file mode 100644
index 0000000000..19209ff820
--- /dev/null
+++ b/server/services/imageGen/index.test.js
@@ -0,0 +1,127 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+
+const settings = vi.hoisted(() => ({ value: {} }));
+const models = vi.hoisted(() => ({ value: [] }));
+
+vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => settings.value) }));
+vi.mock('./local.js', () => ({
+ listImageModels: vi.fn(() => models.value),
+ getActiveJob: () => null,
+ attachSseClient: () => false,
+ cancel: () => false,
+}));
+vi.mock('./external.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null }));
+vi.mock('./codex.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null, cancelAll: () => false }));
+vi.mock('./grok.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null, cancelAll: () => false }));
+vi.mock('./agy.js', () => ({ checkConnection: vi.fn(), getActiveJob: () => null, cancelAll: () => false }));
+vi.mock('./setup.js', () => ({ getSetupCheck: vi.fn() }));
+vi.mock('../../lib/pythonSetup.js', () => ({ isFlux2VenvHealthy: vi.fn() }));
+
+import { checkConnection } from './index.js';
+import { getSetupCheck } from './setup.js';
+import { isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
+
+const mfluxModel = {
+ id: 'dev',
+ name: 'FLUX.1 Dev',
+ runner: 'mflux',
+ hardwareCompatibility: { state: 'available', reasons: [] },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ models.value = [mfluxModel];
+ settings.value = { imageGen: { mode: 'local', local: { pythonPath: '/test/python3' } } };
+});
+
+describe('local image connection readiness', () => {
+ it('reports ready only after the selected mflux model and interpreter health both pass', async () => {
+ getSetupCheck.mockResolvedValue({ missing: [], archMismatch: false });
+
+ await expect(checkConnection()).resolves.toMatchObject({
+ connected: true,
+ mode: 'local',
+ model: 'FLUX.1 Dev',
+ modelId: 'dev',
+ readiness: 'ready',
+ });
+ expect(getSetupCheck).toHaveBeenCalledWith('/test/python3');
+ });
+
+ it('reports missing interpreter packages as unavailable instead of configured', async () => {
+ getSetupCheck.mockResolvedValue({ missing: ['mflux', 'mlx'], archMismatch: false });
+
+ await expect(checkConnection()).resolves.toMatchObject({
+ connected: false,
+ readiness: 'unavailable',
+ reason: 'Missing required packages: mflux, mlx',
+ });
+ });
+
+ it('reports architecture incompatibility as unavailable', async () => {
+ getSetupCheck.mockResolvedValue({ missing: [], archMismatch: true, interpreterArch: 'x86_64', hostArch: 'arm64' });
+
+ await expect(checkConnection()).resolves.toMatchObject({
+ connected: false,
+ readiness: 'unavailable',
+ reason: expect.stringMatching(/architecture x86_64/i),
+ });
+ });
+
+ it('keeps failed interpreter probes distinct from missing packages', async () => {
+ getSetupCheck.mockRejectedValue(new Error('spawn failed'));
+
+ await expect(checkConnection()).resolves.toMatchObject({
+ connected: false,
+ readiness: 'unknown',
+ reason: 'Could not verify the configured Python runtime',
+ });
+ });
+
+ it('uses the selected model hardware requirements before probing Python', async () => {
+ models.value = [{ ...mfluxModel, hardwareCompatibility: { state: 'unavailable', reasons: ['Requires Apple Silicon'] } }];
+
+ await expect(checkConnection()).resolves.toMatchObject({
+ connected: false,
+ readiness: 'unavailable',
+ reason: 'Requires Apple Silicon',
+ });
+ expect(getSetupCheck).not.toHaveBeenCalled();
+ });
+
+ it('checks the dedicated runtime for FLUX.2-family models', async () => {
+ models.value = [{ ...mfluxModel, id: 'flux2-klein-4b', name: 'FLUX.2 Klein', runner: 'flux2' }];
+ settings.value = { imageGen: { mode: 'local', local: { modelId: 'flux2-klein-4b' } } };
+ isFlux2VenvHealthy.mockResolvedValue(true);
+
+ await expect(checkConnection()).resolves.toMatchObject({ connected: true, readiness: 'ready', runner: 'flux2' });
+ expect(getSetupCheck).not.toHaveBeenCalled();
+ });
+
+ it('uses a per-request local model selection when evaluating readiness', async () => {
+ models.value = [
+ mfluxModel,
+ { ...mfluxModel, id: 'flux2-klein-4b', name: 'FLUX.2 Klein', runner: 'flux2' },
+ ];
+ isFlux2VenvHealthy.mockResolvedValue(false);
+
+ await expect(checkConnection({ mode: 'local', modelId: 'flux2-klein-4b' })).resolves.toMatchObject({
+ connected: false,
+ modelId: 'flux2-klein-4b',
+ readiness: 'unavailable',
+ });
+ expect(getSetupCheck).not.toHaveBeenCalled();
+ });
+
+ it('reports an unhealthy dedicated runtime as unavailable', async () => {
+ models.value = [{ ...mfluxModel, id: 'z-image', runner: 'z-image' }];
+ settings.value = { imageGen: { mode: 'local', local: { modelId: 'z-image' } } };
+ isFlux2VenvHealthy.mockResolvedValue(false);
+
+ await expect(checkConnection()).resolves.toMatchObject({
+ connected: false,
+ readiness: 'unavailable',
+ reason: 'The FLUX.2 image runtime is not installed or healthy',
+ });
+ });
+});