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

report the local image runtime the same way on every surface, with a one-button fix

[._.]/ Adam Eivy0681bc375e51
diff --git a/client/src/components/decks/DeckCardGrid.jsx b/client/src/components/decks/DeckCardGrid.jsx
index 2884e4f805..28a96520be 100644
--- a/client/src/components/decks/DeckCardGrid.jsx
+++ b/client/src/components/decks/DeckCardGrid.jsx
@@ -72,7 +72,7 @@ export default function DeckCardGrid({ deck, onOpenCard, onRenderCard, onPreview
onRender={() => (needsPrompt ? onOpenCard(card) : onRenderCard(card))}
onPreview={() => onPreview(card)}
onComplete={(filename) => onRenderComplete(card.id, filename)}
- onTerminalStatus={(s) => onRenderTerminal(card.id, s)}
+ onTerminalStatus={(s, error) => onRenderTerminal(card.id, s, error)}
emptyIcon={needsPrompt ? PencilLine : undefined}
emptyHint={needsPrompt ? `Write a prompt for ${card.name}` : `Render ${card.name}`}
alt={card.name}
@@ -91,6 +91,16 @@ export default function DeckCardGrid({ deck, onOpenCard, onRenderCard, onPreview
) : null}
</button>
<Pill tone={meta.tone} size="xs" icon={meta.icon} className="mt-auto">{meta.label}</Pill>
+ {/* Why it failed. The slot clears itself on a terminal
+ failure (so the card stays re-renderable), taking the
+ shared thumbnail's own message with it — this is the only
+ place a deck can show it. The fix button for a broken
+ runtime lives in the render bar above. */}
+ {status === CARD_STATUS.FAILED && card.render?.error ? (
+ <p className="w-full text-center text-[10px] leading-snug text-port-error line-clamp-3" title={card.render.error}>
+ {card.render.error}
+ </p>
+ ) : null}
</li>
);
})}
diff --git a/client/src/components/decks/DeckRenderControls.jsx b/client/src/components/decks/DeckRenderControls.jsx
index b59bcbd13c..3a34ebf481 100644
--- a/client/src/components/decks/DeckRenderControls.jsx
+++ b/client/src/components/decks/DeckRenderControls.jsx
@@ -1,15 +1,17 @@
import { useId } from 'react';
import { Loader2, Play, RefreshCw, Sliders, Sparkles, WandSparkles } from 'lucide-react';
+import LocalRuntimeStatus from '../imageGen/LocalRuntimeStatus';
import RecordRenderPinRow from '../imageGen/RecordRenderPinRow';
import CollapsibleSection from '../ui/CollapsibleSection';
import FormField from '../ui/FormField';
import DeckLlmPinPicker from './DeckLlmPinPicker';
import useFieldDraft from '../../hooks/useFieldDraft';
import useImageRenderSettings from '../../hooks/useImageRenderSettings';
+import useLocalImageRuntime from '../../hooks/useLocalImageRuntime';
import {
DECK_CARD_SIZE, DECK_CARD_SIZE_BY_KIND, DECK_CARD_SIZE_MAX, DECK_CARD_SIZE_MIN,
} from '../../lib/decks';
-import { RENDER_TARGET, modeLabel } from '../../lib/imageGenBackends';
+import { IMAGE_GEN_MODE, IMAGE_RUNTIME_READINESS, RENDER_TARGET, modeLabel } from '../../lib/imageGenBackends';
import { clampImageEdge } from '../../lib/imageGenResolutions';
import { pluralize } from '../../lib/textUtils';
@@ -50,6 +52,17 @@ export default function DeckRenderControls({
const renderFacts = backends.length
? [modeLabel(imageCfg.mode), model, `${size.width}×${size.height}`].filter(Boolean)
: [];
+ // `backends` is empty until the settings fetch lands, and until then imageCfg
+ // is the UNRESOLVED placeholder (local + the install default) — probing on
+ // that asks about the wrong model, and about a local runtime a cloud-pinned
+ // deck never touches. Wait for the real answer.
+ const rendersLocally = backends.length > 0 && imageCfg.mode === IMAGE_GEN_MODE.LOCAL;
+ const localRuntime = useLocalImageRuntime(rendersLocally ? (imageCfg.modelId || null) : null);
+ // Queueing 79 cards against a runtime the server will refuse is the reported
+ // complaint one step earlier than the error message, so the buttons stand down
+ // while it is unavailable. An unknown verdict does NOT block — a probe that
+ // could not answer must not be able to lock the deck out of rendering.
+ const runtimeBlocked = localRuntime.runtime?.readiness === IMAGE_RUNTIME_READINESS.UNAVAILABLE;
return (
<div className="bg-port-card border border-port-border rounded-md p-3 space-y-3">
@@ -92,6 +105,17 @@ export default function DeckRenderControls({
/>
</div>
+ {/* A deck that renders locally is blocked by the same runtime state the
+ Image Gen page and Settings report — and a card whose render died on a
+ broken venv previously showed only a "Failed" badge. Show the verdict
+ and its one-button fix at the point of action, and stay silent while
+ the runtime is healthy. */}
+ <LocalRuntimeStatus
+ runtime={localRuntime.runtime}
+ onRefresh={localRuntime.refresh}
+ hideWhenReady
+ />
+
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<Step step="1" title="Prompts" note={promptNote({ generating, unprompted, total })}>
{(noteId) => (<>
@@ -119,12 +143,12 @@ export default function DeckRenderControls({
</>)}
</Step>
- <Step step="2" title="Render" note={renderNote({ prompted, rendering, missing, inFlight })}>
+ <Step step="2" title="Render" note={renderNote({ prompted, rendering, missing, inFlight, runtimeBlocked })}>
{(noteId) => (<>
<button
type="button"
onClick={onRenderMissing}
- disabled={busy || missing === 0 || !prompted}
+ disabled={busy || missing === 0 || !prompted || runtimeBlocked}
aria-describedby={noteId}
className={promptsAreTheNextStep ? SECONDARY_BTN : PRIMARY_BTN}
>
@@ -134,7 +158,7 @@ export default function DeckRenderControls({
<button
type="button"
onClick={onRenderAll}
- disabled={busy || !prompted}
+ disabled={busy || !prompted || runtimeBlocked}
aria-describedby={noteId}
title="Queues a fresh render for every card that has a prompt"
className={SECONDARY_BTN}
@@ -205,7 +229,8 @@ const promptNote = ({ generating, unprompted, total }) => {
// The same for step 2. The two counts compose into one sentence rather than
// each owning a phrasing, so "some missing, some in flight" reads like the two
// states it is instead of a third variant.
-const renderNote = ({ prompted, rendering, missing, inFlight }) => {
+const renderNote = ({ prompted, rendering, missing, inFlight, runtimeBlocked }) => {
+ if (runtimeBlocked) return 'The local image runtime is unavailable — fix it above, then render.';
if (!prompted) return 'A card renders from its prompt. Write prompts first.';
if (rendering) return 'Queueing renders…';
const parts = [];
diff --git a/client/src/components/decks/DeckRenderControls.test.jsx b/client/src/components/decks/DeckRenderControls.test.jsx
index e86e2a3a73..a009e00f8a 100644
--- a/client/src/components/decks/DeckRenderControls.test.jsx
+++ b/client/src/components/decks/DeckRenderControls.test.jsx
@@ -15,13 +15,18 @@ vi.mock('../../hooks/useImageRenderSettings', () => ({
vi.mock('./DeckLlmPinPicker', () => ({ default: () => <div /> }));
// The pin row probes the local catalog + the install's model pin itself, so the
// deck page threads neither through.
+const localRuntime = vi.hoisted(() => ({ value: { readiness: 'ready', modelId: 'flux2-klein-9b', model: 'FLUX.2 Klein 9B', runtimeLabel: 'Shared torch runtime', reason: null, remedy: null } }));
vi.mock('../../services/api', () => ({
listImageModels: vi.fn().mockResolvedValue([
{ id: 'flux2-klein-9b', name: 'FLUX.2 Klein 9B' },
{ id: 'qwen-image', name: 'Qwen-Image' },
]),
getSettings: vi.fn().mockResolvedValue({ imageGen: { local: { modelId: 'flux2-klein-9b' } } }),
+ getImageGenStatus: vi.fn(async () => localRuntime.value),
}));
+// The install modal opens its own SSE stream; this suite is about whether the
+// render bar surfaces the runtime verdict and its fix, not about installing.
+vi.mock('../imageGen/Flux2InstallModal', () => ({ default: () => null }));
const deck = {
id: 'd1', kind: 'playing', imageMode: 'local', imageModelId: null, promptLlm: null,
@@ -131,3 +136,50 @@ describe('DeckRenderControls', () => {
expect(btn(/^Render missing \(79\)$/).className).toContain('bg-port-accent');
});
});
+
+// A deck renders on the same local runtime the Image Gen page and Settings
+// report. Before the shared verdict reached here, a deck whose runtime was
+// broken offered "Render all" as though it would work, and the cards came back
+// as unexplained "Failed" badges.
+describe('DeckRenderControls local runtime', () => {
+ const broken = {
+ readiness: 'unavailable', modelId: 'flux2-klein-9b', model: 'FLUX.2 Klein 9B',
+ runtimeLabel: 'Shared torch runtime',
+ reason: 'The shared torch image runtime is not installed or healthy (expected at /home/u/.portos/venv-flux2/bin/python3)',
+ remedy: { kind: 'install-torch-venv', label: 'Install runtime', venvPath: '/home/u/.portos/venv-flux2/bin/python3' },
+ };
+
+ it('stays silent about a healthy runtime, and leaves the render buttons alone', async () => {
+ localRuntime.value = {
+ readiness: 'ready', modelId: 'flux2-klein-9b', model: 'FLUX.2 Klein 9B',
+ runtimeLabel: 'Shared torch runtime', reason: null, remedy: null,
+ };
+ await renderControls({ completion: completion({ prompted: 79 }) });
+ expect(screen.queryByRole('button', { name: /install runtime/i })).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /^Render all/ })).toBeEnabled();
+ });
+
+ it('names the broken runtime and offers its one-button fix before any render is queued', async () => {
+ localRuntime.value = broken;
+ await renderControls();
+ expect(screen.getByText(/not installed or healthy/i)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /install runtime/i })).toBeInTheDocument();
+ });
+
+ // The reported complaint one step earlier than the error message: queueing a
+ // whole deck against a runtime the server is going to refuse.
+ it('stands the render buttons down while the runtime is unavailable, and says why', async () => {
+ localRuntime.value = broken;
+ await renderControls({ completion: completion({ prompted: 79 }) });
+ expect(screen.getByRole('button', { name: /^Render all/ })).toBeDisabled();
+ expect(screen.getByRole('button', { name: /^Render missing/ })).toBeDisabled();
+ expect(screen.getByText(/local image runtime is unavailable/i)).toBeInTheDocument();
+ });
+
+ // An unanswerable probe must not be able to lock a working deck out.
+ it('does not block rendering on an unknown verdict', async () => {
+ localRuntime.value = { readiness: 'unknown', modelId: 'flux2-klein-9b', model: 'FLUX.2 Klein 9B', reason: 'Could not verify', remedy: null };
+ await renderControls({ completion: completion({ prompted: 79 }) });
+ expect(screen.getByRole('button', { name: /^Render all/ })).toBeEnabled();
+ });
+});
diff --git a/client/src/components/imageGen/LocalRuntimeStatus.jsx b/client/src/components/imageGen/LocalRuntimeStatus.jsx
new file mode 100644
index 0000000000..ba7412efd6
--- /dev/null
+++ b/client/src/components/imageGen/LocalRuntimeStatus.jsx
@@ -0,0 +1,131 @@
+import { useCallback, useState } from 'react';
+import { AlertTriangle, CheckCircle2, Download, HelpCircle, RefreshCw, Settings as SettingsIcon, Wand2 } from 'lucide-react';
+import Banner from '../ui/Banner';
+import Flux2InstallModal from './Flux2InstallModal';
+import { IMAGE_RUNTIME_READINESS, IMAGE_RUNTIME_REMEDY } from '../../lib/imageGenBackends';
+
+/**
+ * The local image runtime, described the ONE way the server describes it, with
+ * the single action that fixes it attached.
+ *
+ * The Image Gen page used to say "Unavailable: the FLUX.2 image runtime is not
+ * installed or healthy" while Settings › Image Gen › Local — two clicks away,
+ * probing a different interpreter — said "All required packages installed", and
+ * a deck card that hit the same wall said only "Failed".
+ *
+ * Presentation only: `useLocalImageRuntime` owns the probe, so a host can gate
+ * its own Render button on the same verdict this renders.
+ */
+
+// Where the remedies this component cannot perform itself are performed. Owned
+// here rather than passed in, so a settings-route move is one edit and a new
+// host cannot retype it wrong.
+export const IMAGE_SETTINGS_HREF = '/media/image?settings=1&mediaTab=local';
+
+const TONE = {
+ [IMAGE_RUNTIME_READINESS.READY]: { tone: 'success', Icon: CheckCircle2 },
+ [IMAGE_RUNTIME_READINESS.UNKNOWN]: { tone: 'warning', Icon: HelpCircle },
+ [IMAGE_RUNTIME_READINESS.UNAVAILABLE]: { tone: 'error', Icon: AlertTriangle },
+};
+
+const REMEDY_ICON = {
+ [IMAGE_RUNTIME_REMEDY.SET_PYTHON_PATH]: Wand2,
+ [IMAGE_RUNTIME_REMEDY.SWITCH_PYTHON]: Wand2,
+};
+
+export default function LocalRuntimeStatus({
+ runtime,
+ loading = false,
+ onRefresh = null,
+ // Called after the runtime install finishes, so a host holding state that
+ // depends on the verdict can re-read it.
+ onRuntimeChanged = null,
+ // The settings form itself passes false — a link back to the page you are
+ // already on is worse than no affordance at all.
+ settingsLink = true,
+ // Render nothing while the runtime is ready. Surfaces whose subject IS the
+ // runtime (the settings panel) want the green state; surfaces that merely
+ // depend on it (a deck's render bar) want silence until there is something to
+ // act on.
+ hideWhenReady = false,
+ className = '',
+}) {
+ const [installOpen, setInstallOpen] = useState(false);
+ const closeInstall = useCallback(() => setInstallOpen(false), []);
+ const handleInstallComplete = useCallback(() => {
+ onRefresh?.();
+ onRuntimeChanged?.();
+ }, [onRefresh, onRuntimeChanged]);
+
+ if (!runtime) {
+ return loading
+ ? <p className={`text-xs text-gray-500 ${className}`}>Checking the local image runtime…</p>
+ : null;
+ }
+ const ready = runtime.readiness === IMAGE_RUNTIME_READINESS.READY;
+ if (hideWhenReady && ready) return null;
+
+ const { tone, Icon } = TONE[runtime.readiness] || TONE[IMAGE_RUNTIME_READINESS.UNKNOWN];
+ const remedy = runtime.remedy;
+ // A remedy this component can perform itself, vs. one whose form lives in
+ // Settings. Anything else renders as a reason with no button.
+ const selfServe = remedy?.kind === IMAGE_RUNTIME_REMEDY.INSTALL_TORCH_VENV;
+ const RemedyIcon = REMEDY_ICON[remedy?.kind] || SettingsIcon;
+
+ return (
+ <>
+ <Banner
+ tone={tone}
+ icon={Icon}
+ size="sm"
+ className={className}
+ actions={onRefresh ? (
+ <button
+ type="button"
+ onClick={onRefresh}
+ disabled={loading}
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded p-1.5 text-gray-400 hover:bg-port-border/50 hover:text-white disabled:opacity-50"
+ title="Re-check the local image runtime" aria-label="Re-check the local image runtime"
+ >
+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
+ </button>
+ ) : null}
+ >
+ <span className="font-medium">
+ {ready
+ ? `Ready — ${runtime.model || runtime.modelId}`
+ : `${runtime.readiness === IMAGE_RUNTIME_READINESS.UNKNOWN ? 'Could not verify' : 'Unavailable'} — ${runtime.reason}`}
+ </span>
+ {runtime.runtimeLabel && <span className="mt-0.5 block text-[11px] text-gray-400">{runtime.runtimeLabel}</span>}
+
+ {(selfServe || (remedy && settingsLink)) && (
+ <span className="mt-2 flex flex-wrap items-center gap-2">
+ {selfServe ? (
+ <button
+ type="button"
+ onClick={() => setInstallOpen(true)}
+ className="inline-flex min-h-[40px] items-center gap-2 rounded-lg bg-port-accent px-3 py-2 text-sm text-white hover:bg-port-accent/80"
+ >
+ <Download size={14} aria-hidden="true" /> {remedy.label}
+ </button>
+ ) : (
+ // A plain anchor, not a router Link: hosts render this outside a
+ // Router in their own suites, and the target is a different page
+ // either way (same idiom as the Models → Media links in Settings).
+ <a
+ href={IMAGE_SETTINGS_HREF}
+ className="inline-flex min-h-[40px] items-center gap-2 rounded-lg border border-port-border px-3 py-2 text-sm text-gray-300 hover:bg-port-border/50 hover:text-white"
+ >
+ <RemedyIcon size={14} aria-hidden="true" /> {remedy.label}
+ </a>
+ )}
+ {selfServe && remedy.venvPath && (
+ <span className="text-[11px] text-gray-500">Installs to <code>{remedy.venvPath}</code></span>
+ )}
+ </span>
+ )}
+ </Banner>
+ <Flux2InstallModal open={installOpen} onClose={closeInstall} onComplete={handleInstallComplete} />
+ </>
+ );
+}
diff --git a/client/src/components/pipeline/MediaJobThumb.jsx b/client/src/components/pipeline/MediaJobThumb.jsx
index a5539e7017..c1f5935505 100644
--- a/client/src/components/pipeline/MediaJobThumb.jsx
+++ b/client/src/components/pipeline/MediaJobThumb.jsx
@@ -45,8 +45,11 @@ export default function MediaJobThumb({
// Forward subscription state to the parent so callers (e.g. PageRow's
// disable-while-rendering logic, lightbox nav builders) don't need a
- // duplicate useMediaJobProgress subscription on the same jobId.
- useEffect(() => { if (onStatus) onStatus(effectiveStatus); }, [effectiveStatus, onStatus]);
+ // duplicate useMediaJobProgress subscription on the same jobId. The failure
+ // reason rides the second argument so a caller that records a failed render
+ // can show WHY live, instead of only after a reload re-reads the persisted
+ // record; callers that only care about the status ignore it.
+ useEffect(() => { if (onStatus) onStatus(effectiveStatus, error); }, [effectiveStatus, error, onStatus]);
useEffect(() => { if (onFilename && effectiveFilename) onFilename(effectiveFilename); }, [effectiveFilename, onFilename]);
if (!jobId) return null;
@@ -149,10 +152,13 @@ export default function MediaJobThumb({
return (
<div
title={error || 'Render failed'}
- className={`${stateDims} bg-port-bg rounded border border-port-error/40 flex flex-col items-center justify-center gap-1 text-[10px] text-port-error`}
+ className={`${stateDims} bg-port-bg rounded border border-port-error/40 flex flex-col items-center justify-center gap-1 px-1 text-center text-[10px] text-port-error`}
>
- <AlertCircle size={14} />
- <span>failed</span>
+ <AlertCircle size={14} aria-hidden="true" />
+ {/* The reason as page text, not only as a `title`: a tooltip on a
+ thumbnail reaches nobody on touch, which is how a render blocked by
+ an unhealthy local runtime read as an unexplained "failed". */}
+ <span className="line-clamp-3 leading-snug">{error || 'failed'}</span>
</div>
);
}
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index e305fc5125..b032f3d5c4 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -16,6 +16,8 @@ import FormField from '../ui/FormField';
import TabPills from '../ui/TabPills';
import BrailleSpinner from '../BrailleSpinner';
import LocalSetupPanel from './LocalSetupPanel';
+import LocalRuntimeStatus from '../imageGen/LocalRuntimeStatus';
+import useLocalImageRuntime from '../../hooks/useLocalImageRuntime';
import useDrawerTab from '../../hooks/useDrawerTab';
import { isLoopbackHost } from '../../lib/loopbackHost.js';
import { PORTS } from '../../lib/ports.js';
@@ -24,7 +26,7 @@ import {
registerTool, updateTool, getToolsList,
saveHfToken, clearHfToken,
} from '../../services/api';
-import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, CODEX_IMAGEGEN_DEFAULT_MODEL, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, localModelSelectOptions, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';
+import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, LOCAL_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, CODEX_IMAGEGEN_DEFAULT_MODEL, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, localModelSelectOptions, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';
import { resolveCleanersFromConfig } from '../../lib/imageCleaners';
import { withUnlistedOption } from '../../lib/withUnlistedOption';
import { useMediaJobSse } from '../../hooks/useMediaJobSse';
@@ -398,6 +400,15 @@ export function ImageGenTab() {
const statusReadiness = imageGenReadiness(status);
const statusReady = statusReadiness === 'ready';
const statusUnknown = statusReadiness === 'unknown';
+ // The Local tab's own verdict, for the model IT has pinned — independent of
+ // `status`, which follows whichever backend tab is active.
+ const localRuntime = useLocalImageRuntime(localModelId || LOCAL_IMAGEGEN_DEFAULT_MODEL);
+ // A pip install into the mflux interpreter flips the verdict for an mflux
+ // model, and neither probe can observe that on its own.
+ const onLocalPackagesChanged = useCallback(() => {
+ localRuntime.refresh();
+ checkStatus();
+ }, [localRuntime, checkStatus]);
// 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
@@ -978,7 +989,20 @@ export function ImageGenTab() {
missing packages directly. HF model weights stream into the standard <code>~/.cache/huggingface</code>
and are surfaced in <a href="/models/media" className="text-port-accent hover:underline">Models → Media</a>.
</p>
- <LocalSetupPanel pythonPath={pythonPath} onPythonPathChange={setPythonPath} />
+ {/* The verdict first, then the interpreter detail below it. The
+ packages panel only ever probes the mflux interpreter, so on its
+ own it reported "All required packages installed" for a machine
+ whose pinned model renders through the SHARED torch venv and could
+ not run at all. This is the same diagnosis the Image Gen status
+ pill and the renderer's pre-flight refusal use — settingsLink is
+ off because this IS the settings form. */}
+ <LocalRuntimeStatus
+ runtime={localRuntime.runtime}
+ loading={localRuntime.loading}
+ onRefresh={localRuntime.refresh}
+ settingsLink={false}
+ />
+ <LocalSetupPanel pythonPath={pythonPath} onPythonPathChange={setPythonPath} onPackagesChanged={onLocalPackagesChanged} />
<FormField
label="Default model"
labelClassName="block text-xs font-medium text-gray-400 mb-1"
diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsx
index 43e1550382..418b97c857 100644
--- a/client/src/components/settings/ImageGenTab.test.jsx
+++ b/client/src/components/settings/ImageGenTab.test.jsx
@@ -28,6 +28,8 @@ vi.mock('../ui/Toast', () => ({
vi.mock('./LocalSetupPanel', () => ({
default: ({ pythonPath }) => <div data-testid="local-setup-panel">{pythonPath}</div>,
}));
+// The runtime card's install modal opens its own SSE stream.
+vi.mock('../imageGen/Flux2InstallModal', () => ({ default: () => null }));
vi.mock('../../hooks/useMediaJobSse', () => ({
useMediaJobSse: () => ({ attach: vi.fn(), close: vi.fn() }),
}));
@@ -61,6 +63,7 @@ beforeEach(() => {
},
});
getToolsList.mockResolvedValue([]);
+ getImageGenStatus.mockResolvedValue({ connected: true, mode: 'local', readiness: 'ready', model: 'FLUX.1 Dev', modelId: 'dev' });
useHfTokenStatus.mockReturnValue({ present: false, source: 'none', refresh: vi.fn() });
updateSettings.mockResolvedValue({});
listAgyImageModels.mockResolvedValue({ models: ['gemini-image', 'custom/image-v2'], error: null });
@@ -548,3 +551,34 @@ describe('ImageGenTab — Grok CLI section (#2859)', () => {
expect(patch.imageGen.mode).toBe('local');
});
});
+
+// The packages panel above the card only ever probes the mflux interpreter, so
+// on its own it told a machine whose selected default renders through the
+// shared torch venv that everything was installed — while the Image Gen page
+// two clicks away called the same machine unavailable.
+describe('ImageGenTab local runtime card', () => {
+ const brokenTorchRuntime = {
+ readiness: 'unavailable', modelId: 'flux2-klein-4b', model: 'FLUX.2 Klein',
+ runtimeLabel: 'Shared torch runtime (FLUX.2 · Z-Image · ERNIE · HiDream · Qwen)',
+ reason: 'The shared torch image runtime is not installed or healthy (expected at /home/u/.portos/venv-flux2/bin/python3)',
+ remedy: { kind: 'install-torch-venv', label: 'Install runtime', venvPath: '/home/u/.portos/venv-flux2/bin/python3' },
+ };
+
+ it('reports the shared torch runtime the pinned model actually needs', async () => {
+ getImageGenStatus.mockResolvedValue(brokenTorchRuntime);
+ await renderTab();
+ fireEvent.click(screen.getByRole('tab', { name: /^Local/i }));
+
+ expect(await screen.findByText(/not installed or healthy/i)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /install runtime/i })).toBeInTheDocument();
+ });
+
+ it('probes the runtime for the model the tab has pinned, not the install default', async () => {
+ await renderTab();
+ fireEvent.click(screen.getByRole('tab', { name: /^Local/i }));
+ await waitFor(() => expect(getImageGenStatus).toHaveBeenCalledWith('local', 'dev', expect.anything()));
+
+ fireEvent.change(screen.getByLabelText('Default model'), { target: { value: 'flux2-klein-4b' } });
+ await waitFor(() => expect(getImageGenStatus).toHaveBeenCalledWith('local', 'flux2-klein-4b', expect.anything()));
+ });
+});
diff --git a/client/src/components/universe/EntryThumbSlot.jsx b/client/src/components/universe/EntryThumbSlot.jsx
index f2465d8044..afc7b767f1 100644
--- a/client/src/components/universe/EntryThumbSlot.jsx
+++ b/client/src/components/universe/EntryThumbSlot.jsx
@@ -49,9 +49,10 @@ export default function EntryThumbSlot({
// expects a key re-keys its job map so the in-flight job is never cleared and
// the slot spins forever. Terminal status goes to `onTerminalStatus` instead.
onComplete = null,
- // `('failed' | 'canceled')` when the job terminates without a filename, for
- // callers that report a failed render. Separate from `onComplete` per the
- // arity note above; fires after it, so the clear happens first either way.
+ // `(status, error)` — `'failed' | 'canceled'` plus the failure reason when
+ // the job terminates without a filename, for callers that report a failed
+ // render. Separate from `onComplete` per the arity note above; fires after
+ // it, so the clear happens first either way.
onTerminalStatus = null,
canRender = true,
// The empty slot's affordance. Glyph and label travel together because a host
@@ -79,10 +80,10 @@ export default function EntryThumbSlot({
// render instead of once when the job settles. (`onComplete` goes to
// `onFilename` unwrapped, so its identity — and arity — stay the caller's.)
const onStatus = useCallback(
- (s) => {
+ (s, error) => {
if (s !== 'failed' && s !== 'canceled') return;
onComplete?.(null);
- onTerminalStatus?.(s);
+ onTerminalStatus?.(s, error || null);
},
[onComplete, onTerminalStatus],
);
diff --git a/client/src/components/universe/EntryThumbSlot.test.jsx b/client/src/components/universe/EntryThumbSlot.test.jsx
index 72066eaa67..2febff8f67 100644
--- a/client/src/components/universe/EntryThumbSlot.test.jsx
+++ b/client/src/components/universe/EntryThumbSlot.test.jsx
@@ -79,8 +79,10 @@ describe('EntryThumbSlot — three-state thumbnail', () => {
// read as a job key: it would look up `renderingJobs['failed']`, find nothing,
// never clear the real job, and leave the slot spinning after every render.
// Terminal status therefore goes to its own prop, and `onComplete` stays
- // strictly one-argument.
- it('calls onComplete with exactly one argument, reporting status separately', () => {
+ // strictly one-argument. That prop takes the failure REASON in its second
+ // slot, which is how a caller that records a failed render can explain it
+ // without waiting for a reload to re-read the persisted record.
+ it('calls onComplete with exactly one argument, reporting status and reason separately', () => {
jobStatus = 'failed';
const onComplete = vi.fn();
const onTerminalStatus = vi.fn();
@@ -93,14 +95,14 @@ describe('EntryThumbSlot — three-state thumbnail', () => {
/>,
);
expect(onComplete.mock.calls[0]).toHaveLength(1);
- expect(onTerminalStatus).toHaveBeenCalledWith('failed');
+ expect(onTerminalStatus).toHaveBeenCalledWith('failed', 'boom');
});
it('reports a cancel distinctly so callers can stay silent on one', () => {
jobStatus = 'canceled';
const onTerminalStatus = vi.fn();
render(<EntryThumbSlot inFlightJobId="job-v" onTerminalStatus={onTerminalStatus} canRender={false} />);
- expect(onTerminalStatus).toHaveBeenCalledWith('canceled');
+ expect(onTerminalStatus).toHaveBeenCalledWith('canceled', null);
});
it('does NOT clear the in-flight job for non-terminal statuses', () => {
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index a0606d2077..2e6c26a34e 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -71,6 +71,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useClonedGltf` | Clones a drei-cached GLTF scene with skeleton bindings intact and wires its animations; the colocated `GltfPrimitive` prevents R3F from disposing shared cache resources. Accepts an optional animation transform for derived clip sets. | Any skinned GLTF rendered from `useGLTF`; render its scene through `GltfPrimitive` so remounts cannot inherit disposed geometry or materials. |
| `usePreviewRoute` | URL-driven `[preview, setPreview]` via `?preview=<filename>`. | Any page hosting `<MediaPreview>` — gives the preview a deep-link. |
| `useImageGenQueue` | Work-scoped live queue of in-flight image renders. | Pages that show per-work image-gen queue state. |
+| `useLocalImageRuntime` | The local image runtime's verdict for one model — `{ runtime, loading, refresh }` — from `GET /api/image-gen/status?mode=local&modelId=…`, the same `diagnoseLocalRuntime` the renderer refuses against. `runtime` carries `readiness`, `reason` and a one-button `remedy`. Pass `null` while the host is still resolving which model it renders on. | Any surface whose renders can be blocked by an unhealthy local runtime: pair it with `LocalRuntimeStatus` to show the verdict and its fix, and read `readiness` to stand the surface's own Render button down. |
| `useImageRenderSettings` | Load the pipeline image-gen config once (`getSettings → readPipelineImageSettings`), failing open to `PIPELINE_IMAGE_DEFAULTS`; takes `{ record, target }` to fold that record's `imageMode`/`imageModelId` pin, then the target's `renderDefaults` pin, over the install default; returns `{ imageCfg }`. | A single-image render slot that needs the render config and doesn't already load the full settings blob. Pass `record` + `target` whenever the render belongs to a pinnable record (universe, series, sprite). |
| `useUserTimezone` | Resolve the user's configured IANA timezone (`settings.timezone`) once, falling back to the browser zone then UTC; returns the tz string. | A date-scoped surface that must derive "today" the same way the server does (POST launcher/history day keys, #2681). |
| `useSingleImageRender` | Queue-one-render / wait-for-completion jobId lifecycle: builds opts from `imageCfg`, calls `buildPrompt`, POSTs `generateImage`, tracks the `jobId` head, and runs a once-per-`(key, filename)` completion guard before `onComplete`. | Single-image render slots driven by `EntryThumbSlot`/`MediaJobThumb` (style probe, characters step). Completion SSE stays in the thumb. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 698eaef3bd..9a460f5523 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -30,6 +30,7 @@ export { default as useNoteSave } from './useNoteSave.js';
export { default as useHoverTooltip } from './useHoverTooltip.js';
export { default as useImageGenQueue } from './useImageGenQueue.js';
export { default as useImageRenderSettings } from './useImageRenderSettings.js';
+export { default as useLocalImageRuntime } from './useLocalImageRuntime.js';
export { default as useUserTimezone } from './useUserTimezone.js';
export { default as useSingleImageRender } from './useSingleImageRender.js';
export { default as useSlotInFlight } from './useSlotInFlight.js';
diff --git a/client/src/hooks/useLocalImageRuntime.js b/client/src/hooks/useLocalImageRuntime.js
new file mode 100644
index 0000000000..9384b40487
--- /dev/null
+++ b/client/src/hooks/useLocalImageRuntime.js
@@ -0,0 +1,38 @@
+import { useCallback, useEffect, useState } from 'react';
+import { getImageGenStatus } from '../services/api';
+
+/**
+ * The local image runtime's verdict for one model — `readiness`, the `reason`,
+ * and the one-button `remedy` that fixes it — from the SAME server diagnosis the
+ * renderer refuses against (`server/services/imageGen/localRuntime.js`).
+ *
+ * A hook rather than state fused into the status card, because a host usually
+ * needs the VALUE as well as the display: a deck has to disable "Render all"
+ * when the runtime is dead, which is the reported complaint one step earlier
+ * than the error message.
+ *
+ * `modelId` may be null while the host is still resolving which model it renders
+ * on; the probe waits rather than asking about the install default and then
+ * re-asking. Silent — the card owns its own failure display.
+ */
+export default function useLocalImageRuntime(modelId) {
+ const [runtime, setRuntime] = useState(null);
+ const [loading, setLoading] = useState(!!modelId);
+ // Manual refreshes (the card's button, an install completing) must re-run
+ // without changing `modelId`, and must abort with it.
+ const [attempt, setAttempt] = useState(0);
+ const refresh = useCallback(() => setAttempt((n) => n + 1), []);
+
+ useEffect(() => {
+ if (!modelId) { setRuntime(null); setLoading(false); return undefined; }
+ const controller = new AbortController();
+ setLoading(true);
+ getImageGenStatus('local', modelId, { silent: true, signal: controller.signal })
+ .then((s) => { if (!controller.signal.aborted && s) setRuntime(s); })
+ .catch(() => {})
+ .finally(() => { if (!controller.signal.aborted) setLoading(false); });
+ return () => controller.abort();
+ }, [modelId, attempt]);
+
+ return { runtime, loading, refresh };
+}
diff --git a/client/src/lib/imageGenBackends.js b/client/src/lib/imageGenBackends.js
index 699c75cc8f..e1072d7570 100644
--- a/client/src/lib/imageGenBackends.js
+++ b/client/src/lib/imageGenBackends.js
@@ -7,7 +7,7 @@
*/
import { Cpu, Terminal, Cloud, Sparkles } from 'lucide-react';
-import { IMAGE_GEN_MODE, MODE_LABELS } from './imageGenModes.js';
+import { IMAGE_GEN_MODE, IMAGE_RUNTIME_READINESS, MODE_LABELS } from './imageGenModes.js';
export * from './imageGenModes.js';
@@ -25,7 +25,7 @@ const metaFor = (mode) => ({ label: MODE_LABELS[mode], icon: MODE_ICONS[mode] })
// 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;
+ if (Object.values(IMAGE_RUNTIME_READINESS).includes(status?.readiness)) return status.readiness;
return status?.connected ? 'ready' : 'unavailable';
};
diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.js
index dd6e623ad1..3264a802ec 100644
--- a/client/src/lib/imageGenModes.js
+++ b/client/src/lib/imageGenModes.js
@@ -56,6 +56,10 @@ import {
maxInputImages,
supportsCloudModelOverride,
} from '../../../server/lib/imageGenCapabilities.js';
+import {
+ IMAGE_RUNTIME_READINESS,
+ IMAGE_RUNTIME_REMEDY,
+} from '../../../server/lib/imageRuntimeRemedies.js';
export {
// Shipped per-backend defaults, so a UI that displays "the model/effort a job
@@ -76,6 +80,12 @@ export {
// pickers filter through and what `pickI2iMode` walks.
I2I_CAPABLE_MODES,
IMAGE_GEN_MODE,
+ // The local image-runtime vocabulary the status probe, the renderer's
+ // pre-flight refusal and every blocked surface share. A component branches on
+ // `IMAGE_RUNTIME_REMEDY.X`, never on the literal string — a hand-copied
+ // remedy kind is a button that silently stops matching the server.
+ IMAGE_RUNTIME_READINESS,
+ IMAGE_RUNTIME_REMEDY,
// The local model a blank `imageGen.local.modelId` resolves to, so the
// Settings Local tab can name the install default instead of showing a blank
// select whose meaning the user has to guess.
diff --git a/client/src/pages/DeckDetail.jsx b/client/src/pages/DeckDetail.jsx
index 2762d5fb03..348cb49ad6 100644
--- a/client/src/pages/DeckDetail.jsx
+++ b/client/src/pages/DeckDetail.jsx
@@ -179,8 +179,10 @@ function DeckEditor({ id }) {
}));
}, [patchLocalCard]);
- const onRenderTerminal = useCallback((cardId, status) => {
- patchLocalCard(cardId, (c) => ({ render: { ...(c.render || {}), status } }));
+ // Mirror what the server's own completion hook writes (`markCardRenderTerminal`)
+ // so the grid can explain a failure immediately instead of only after a reload.
+ const onRenderTerminal = useCallback((cardId, status, error = null) => {
+ patchLocalCard(cardId, (c) => ({ render: { ...(c.render || {}), status, error: error || null } }));
}, [patchLocalCard]);
const handleDelete = async () => {
diff --git a/client/src/pages/ImageGen.flux2VenvShare.test.jsx b/client/src/pages/ImageGen.flux2VenvShare.test.jsx
index f397b314c6..6f0494dcdc 100644
--- a/client/src/pages/ImageGen.flux2VenvShare.test.jsx
+++ b/client/src/pages/ImageGen.flux2VenvShare.test.jsx
@@ -1,8 +1,12 @@
// 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.
+// must offer the same one-button install FLUX.2 models get — and NOT the
+// HF-gated-repo token banner, since Z-Image isn't a gated repo.
+//
+// The offer now rides the readiness pill's own `remedy`, which comes from the
+// shared server diagnosis (`services/imageGen/localRuntime.js`) rather than
+// from a second probe: a page-specific banner beside the pill meant the page
+// could render an install button from one producer and a verdict from another.
import { beforeEach, describe, expect, it } from 'vitest';
import { screen } from '@testing-library/react';
@@ -16,20 +20,29 @@ import {
await loadImageGenPage();
-describe('ImageGen shared-venv install banner for non-flux2 diffusers models', () => {
+describe('ImageGen shared-venv install offer for non-flux2 diffusers models', () => {
beforeEach(() => {
resetImageGenMockState();
state.models = [imageGenModel('z-turbo', { name: 'Z-Image Turbo', runner: 'z-image' })];
state.settings = { imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3', modelId: 'z-turbo' } } };
state.flux2Status = { venvInstalled: false, hfTokenPresent: false, licenseUrl: 'https://huggingface.co/example' };
+ state.getImageGenStatus.mockResolvedValue({
+ connected: false,
+ mode: 'local',
+ model: 'Z-Image Turbo',
+ modelId: 'z-turbo',
+ readiness: 'unavailable',
+ runtime: 'torch-venv',
+ reason: 'The shared torch image runtime is not installed or healthy (expected at /home/u/.portos/venv-flux2/bin/python3)',
+ remedy: { kind: 'install-torch-venv', label: 'Install runtime', venvPath: '/home/u/.portos/venv-flux2/bin/python3' },
+ });
});
- it('shows the install banner (with model-specific wording, not an HF-token banner) when the shared venv is unhealthy', async () => {
+ it('offers the runtime install from the readiness pill, with no HF-token banner', async () => {
await renderImageGenPage();
- 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(await screen.findByRole('button', { name: /Install runtime/i })).toBeInTheDocument();
+ expect(screen.getByText(/not installed or healthy/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 947fbd90cd..8653f56f42 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -45,7 +45,7 @@ import {
} from 'lucide-react';
import { composeStyledPrompt } from '../lib/composeStyledPrompt';
import { universeStylePreset } from '../lib/universeStylePreset';
-import { isCloudCliMode, deriveAvailableBackends, AGY_IMAGEGEN_DEFAULT_MODEL, IMAGE_GEN_MODE, cloudPromptRequired, imageGenReadiness, isI2iCapableMode, pickI2iMode, modeLabel, referenceSlotsFor, supportsReferenceStrength } from '../lib/imageGenBackends';
+import { IMAGE_RUNTIME_REMEDY, 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';
@@ -859,8 +859,12 @@ export default function ImageGen() {
const handleFlux2ModalClose = useCallback(() => setFlux2InstallOpen(false), []);
const handleFlux2InstallComplete = useCallback(() => {
refreshFlux2Status();
+ // The status pill reads the same runtime health, so re-probe it too — the
+ // pill now offers the install button itself and would otherwise keep
+ // claiming "Unavailable" for a runtime that just finished installing.
+ refreshStatus(effectiveMode, modelId);
toast.success('FLUX.2 runtime installed');
- }, [refreshFlux2Status]);
+ }, [refreshFlux2Status, refreshStatus, effectiveMode, modelId]);
useEffect(() => {
if (!sharesFlux2Venv) { setFlux2Status(null); return; }
@@ -908,12 +912,12 @@ export default function ImageGen() {
}, [generating, refreshRecent]);
useAutoRefetch(pollQueue, 4000, { enabled: queueActive, pollOnly: true });
- // The HF-gated-repo "token" issue only applies to actual FLUX.2 models —
+ // The HF-gated-repo token gate applies to actual FLUX.2 models only —
// 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;
+ // missing HF token must not block them. The venv's own health is NOT read
+ // here: it reaches the page through `status.remedy` on the shared diagnosis,
+ // which is what the readiness pill renders its install button from.
+ const needsFlux2Token = isFlux2Model && !!flux2Status && flux2Status.venvInstalled && !flux2Status.hfTokenPresent;
// Favorites are filtered before LIMIT on the server, so old favorites remain
// reachable even when none of the newest five images is starred.
const visibleGallery = useMemo(() => gallery.filter(img => !img.hidden), [gallery]);
@@ -1356,7 +1360,18 @@ export default function ImageGen() {
<>
<AlertTriangle className="w-3 h-3" />
{statusUnknown ? 'Could not verify' : 'Unavailable'}: {status.reason || 'Not connected'} —
- <button type="button" onClick={openSettings} className="underline">Settings</button>
+ {/* The probe names the ONE action that fixes this state
+ (server/services/imageGen/localRuntime.js). Offer it here:
+ sending the user to Settings for a broken shared torch venv
+ landed them on a panel that probes a DIFFERENT interpreter
+ and reports "All required packages installed". */}
+ {status.remedy?.kind === IMAGE_RUNTIME_REMEDY.INSTALL_TORCH_VENV ? (
+ <button type="button" onClick={() => setFlux2InstallOpen(true)} className="underline">
+ {status.remedy.label}
+ </button>
+ ) : (
+ <button type="button" onClick={openSettings} className="underline">Settings</button>
+ )}
</>
)}
</span>
@@ -1510,25 +1525,7 @@ export default function ImageGen() {
setNegativePrompt={setNegativePrompt}
/>
- {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>
- {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"
- onClick={() => setFlux2InstallOpen(true)}
- className="self-start sm:self-auto whitespace-nowrap inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent text-white text-xs font-medium hover:bg-port-accent/80 disabled:opacity-50"
- >
- <Sparkles size={14} />
- Install FLUX.2
- </button>
- </div>
- )}
- {flux2Issue === 'token' && (
+ {needsFlux2Token && (
<HfTokenBanner
modelLabel={currentModel?.name || 'FLUX.2-klein'}
licenseUrl={flux2Status.licenseUrl}
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 2b64a83792..0f03bcaa5f 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -372,12 +372,16 @@ export const getTailnetInfo = () => request('/instances/tailnet-suffix');
export const provisionTailnetCert = () => request('/instances/provision-cert', { method: 'POST' });
// Image Generation
-export const getImageGenStatus = (mode, modelId) => {
+// `mode` is an explicit override, not the saved one, so a surface that is not
+// in local mode can still ask "what would a local render of X do?" — which is
+// what the runtime status card asks. `options` lets a background probe pass
+// `{ silent, signal }`; a foreground check omits them and keeps the toast.
+export const getImageGenStatus = (mode, modelId, options = {}) => {
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}` : ''}`);
+ return request(`/image-gen/status${query ? `?${query}` : ''}`, options);
};
export const generateImage = (data, options = {}) => request('/image-gen/generate', {
method: 'POST',
diff --git a/server/lib/README.md b/server/lib/README.md
index 87ae3da960..85e6feb2c9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -35,6 +35,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). Also the backup-exclude anchoring rule (#7241): `anchorUserExclude` / `anchorUserExcludes` prepend the rsync root anchor (`/`) to any user pattern that is not already anchored and is not deliberately `*`/`**`-led, and `isSafeExcludePattern` (defined as `anchorUserExclude(x) !== null`, so the two can never disagree) rejects a `..` segment, a NUL, or a pattern longer than `EXCLUDE_PATTERN_MAX_LENGTH` once anchored — one rule shared by `backupConfigSchema` and `services/backup.js#computeEffectiveExcludes`, since an unanchored `cache/` is an rsync filter that matches at EVERY depth. Mirrored to `client/src/lib/backupExcludes.js`. |
| `generationModes.js` | Shared immutable image/video render-backend alphabets (`IMAGE_GEN_MODE[S]`, `QUEUEABLE_IMAGE_MODES`, `VIDEO_GEN_MODE[S]`, and cloud subsets) plus `mediaJobExecutionLane({ kind, mode, remote })` / `MEDIA_JOB_EXECUTION_LANES` — THE media-queue lane rule the scheduler and the public job projection share, kept below both validation and generation services so schemas never import orchestration modules. |
| `imageGenCapabilities.js` | Per-backend image-gen capability literals, a dependency-free leaf beside `generationModes.js`: `EDIT_INCAPABLE_IMAGE_MODES`/`isEditCapableMode` and the derived `I2I_CAPABLE_MODES`, the shipped defaults (`CODEX_IMAGEGEN_DEFAULT_MODEL`/`_EFFORT`, `AGY_IMAGEGEN_DEFAULT_MODEL`, `AGY_IMAGEGEN_IMAGE_MODEL`), the `AGY_`/`GROK_ASPECT_RATIOS` alphabets, and `IMAGE_GEN_PROVIDER_CAPABILITIES` (`supportsModelOverride`, `maxInputImages`, `promptRequiredWithInputImage`) with its `supportsCloudModelOverride`/`maxInputImages`/`cloudPromptRequired` readers. The `services/imageGen/*` modules re-export these, and `client/src/lib/imageGenModes.js` imports them instead of copying them (#6590). |
+| `imageRuntimeRemedies.js` | Local image-runtime vocabulary, a dependency-free leaf beside `imageGenCapabilities.js`: `IMAGE_RUNTIME_READINESS` (ready/unavailable/unknown), `IMAGE_RUNTIME` + `IMAGE_RUNTIME_LABELS` (the shared torch venv vs. the configurable mflux interpreter), `IMAGE_RUNTIME_REMEDY` (the one action that fixes each unavailable state), and `IMAGE_RUNTIME_UNAVAILABLE_CODE`. `services/imageGen/localRuntime.js` builds the diagnosis from these, `services/imageGen/local.js` tags its pre-flight render refusal with the same remedy, and `client/src/lib/imageGenModes.js` re-exports them so no component hand-copies a remedy kind. |
| `renderModeLadder.js` | Image-gen mode resolution ladder (#6815), a dependency-free leaf beside `generationModes.js`/`renderTargets.js` so the client imports it directly instead of hand-copying it: `isModeUsable(settings, mode)` (queueable + enabled gate, no per-provider spec lookup), `pickUsableMode(settings, candidates)` (first usable candidate, falling through disabled pins to the cloud-then-local tail), `renderTargetDefaults(settings, target)` (the normalized `settings.renderDefaults[target]` pin), and `imageModeCandidates(settings, target, record)` (the shared `[recordPin, targetPin, installDefault]` candidate order, declared once so a UI's own "what will Auto resolve to" display can't drift from the resolver). `services/imageGen/cloudProviderConfig.js` re-exports the first three for its existing callers. |
| `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. |
| `fableLoomCameraMovements.js` | Shared FableLoom camera-movement registry for generated cut direction and the manual scene editor selector. |
diff --git a/server/lib/imageRuntimeRemedies.js b/server/lib/imageRuntimeRemedies.js
new file mode 100644
index 0000000000..2e7cbed536
--- /dev/null
+++ b/server/lib/imageRuntimeRemedies.js
@@ -0,0 +1,57 @@
+/**
+ * Local image-runtime vocabulary — readiness verdicts, runtime ids, and the
+ * remedy kinds that name the ONE action that fixes each unavailable state.
+ *
+ * Lives in `lib/` rather than beside the image-gen service because several
+ * layers have to agree and none can afford the others' import closure: the
+ * diagnosis (`services/imageGen/localRuntime.js`), the renderer
+ * (`services/imageGen/local.js`), `services/imageGen/regen.js`, and the client,
+ * which re-exports this through `client/src/lib/imageGenModes.js` so a remedy
+ * kind is never hand-copied into a component. Naming is `IMAGE_RUNTIME_*`, not
+ * `LOCAL_RUNTIME_*`, so nothing here reads as a sibling of
+ * `localProviderRuntime.js`'s `LOCAL_RUNTIMES` — that is the local-LLM provider
+ * roster, an unrelated domain.
+ */
+
+import { isFlux2, usesDiffusersRunner } from './runners.js';
+
+export const IMAGE_RUNTIME_READINESS = Object.freeze({
+ READY: 'ready',
+ UNAVAILABLE: 'unavailable',
+ UNKNOWN: 'unknown',
+});
+
+// Which runtime backs a selected local model. FLUX.2, Z-Image, ERNIE, HiDream
+// and Qwen all share ONE torch+diffusers venv (isFlux2/usesDiffusersRunner in
+// runners.js gate the same `isFlux2VenvHealthy` probe), so they share one
+// runtime id and one install remedy. mflux models run on the configurable
+// interpreter from settings.imageGen.local.pythonPath.
+export const IMAGE_RUNTIME = Object.freeze({
+ TORCH_VENV: 'torch-venv',
+ MFLUX_PYTHON: 'mflux-python',
+});
+
+export const IMAGE_RUNTIME_LABELS = Object.freeze({
+ [IMAGE_RUNTIME.TORCH_VENV]: 'Shared torch runtime (FLUX.2 · Z-Image · ERNIE · HiDream · Qwen)',
+ [IMAGE_RUNTIME.MFLUX_PYTHON]: 'mflux Python interpreter',
+});
+
+// Which runtime a model needs. Shipping the vocabulary without the CLASSIFIER
+// left `isFlux2(m) || usesDiffusersRunner(m)` hand-copied at five call sites, so
+// adding a sixth diffusers family meant finding all of them — exactly the drift
+// the enum exists to end. `services/imageGen/regen.js` re-exports this as
+// `modelUsesFluxVenv` for its existing callers.
+export const imageRuntimeFor = (model) =>
+ (isFlux2(model) || usesDiffusersRunner(model)) ? IMAGE_RUNTIME.TORCH_VENV : IMAGE_RUNTIME.MFLUX_PYTHON;
+
+export const usesTorchVenv = (model) => imageRuntimeFor(model) === IMAGE_RUNTIME.TORCH_VENV;
+
+// The single action that resolves each unavailable state. The client maps these
+// onto one button apiece — see client/src/components/imageGen/LocalRuntimeStatus.jsx.
+export const IMAGE_RUNTIME_REMEDY = Object.freeze({
+ INSTALL_TORCH_VENV: 'install-torch-venv',
+ INSTALL_PACKAGES: 'install-packages',
+ SET_PYTHON_PATH: 'set-python-path',
+ SWITCH_PYTHON: 'switch-python',
+ CHOOSE_MODEL: 'choose-model',
+});
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 86e4f4ce15..20de01a245 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -559,7 +559,22 @@ describe('deferred imports stay deferred (#6156)', () => {
// mode -> provider map stays in modelPinAudit.js rather than moving to a shared
// leaf, which would have cost ~54 (one more file in the static closure of every
// suite reaching routes/providers.js).
-const MAX_STATIC_INSTANTIATIONS = 104487;
+// Making the local image runtime describe itself the same way everywhere
+// measures +65, and every one of those is the module-catalog rule rather than a
+// heavy edge. The vocabulary the layers share — the status probe, the renderer's
+// pre-flight refusal, regen.js, and the client, which re-exports it through
+// imageGenModes.js so no component hand-copies a remedy kind — has to be a
+// leaf under lib/ (it imports only runners.js), and registering a new lib/ file
+// in index.js is mandatory (lib/index.test.js fails without it), which puts
+// imageRuntimeRemedies.js into the closure of the ~57 suites that reach the
+// barrel; the rest reach it through services/imageGen/local.js and regen.js,
+// which classify a model's runtime with the same helper, plus the new suite's
+// own closure. The diagnosis module itself (localRuntime.js, which pulls the
+// model registry and the setup-check cache) measured a further +111 from the
+// image-gen dispatcher and is NOT in this number: checkConnection reaches it
+// through a memoized call-site await import(), so the ~110 suites that never
+// probe a local runtime do not pay for it.
+const MAX_STATIC_INSTANTIATIONS = 104552;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/lib/index.js b/server/lib/index.js
index ad7f35fc24..a8048157c3 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -491,6 +491,7 @@ export * from './renderTargets.js';
export * from './renderTiming.js';
export * from './generationModes.js';
export * from './imageGenCapabilities.js';
+export * from './imageRuntimeRemedies.js';
export * from './renderModeLadder.js';
export * from './spriteVocabulary.js';
export * from './spriteChromaKey.js';
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 631d652662..2cc658d5ed 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -367,16 +367,31 @@ export function resolveFlux2Python() {
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;
+}
+async function probeFlux2Venv() {
const py = resolveFlux2Python();
- 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);
+ const ok = py
+ ? await execFileAsync(py, ['-c', 'from diffusers import Flux2KleinPipeline'], safeChildProcessOptions({ timeout: 30_000 }))
+ .then(() => true)
+ .catch(() => false)
+ : false;
cachedFlux2Healthy = ok;
cachedFlux2HealthyAt = Date.now();
return ok;
diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.js
index ae67e66f34..085a78bb6b 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -21,16 +21,14 @@ 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, LOCAL_IMAGEGEN_DEFAULT_MODEL, isEditCapableMode,
+ IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES, 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';
+import { IMAGE_RUNTIME_READINESS } from '../../lib/imageRuntimeRemedies.js';
// Cloud-CLI provider modules keyed by mode, so the shared gate in
// checkConnection/generateImage dispatches without a per-provider branch.
@@ -47,110 +45,46 @@ 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 } : {}),
-});
+// One shared load of the diagnosis module, deferred because this dispatcher is
+// reached by ~110 server suites that never probe a local runtime, while
+// `localRuntime.js` pulls the model registry and the setup-check cache
+// (server/AGENTS.md, "Import scoping"). Memoized so two concurrent status polls
+// cannot race two imports of one mocked specifier — under the test runner, one
+// of them escapes the mock. A rejected load is forgotten so a transient failure
+// does not poison every later probe.
+let localRuntimeModule = null;
+const localRuntime = () => (localRuntimeModule ||= import('./localRuntime.js').catch((err) => {
+ localRuntimeModule = null;
+ throw err;
+}));
+/**
+ * Wire shape for a local-mode status probe. The verdict itself comes from the
+ * shared diagnosis in `localRuntime.js` — this only projects it onto the
+ * `{ connected, mode, model, … }` envelope every backend answers with, and
+ * carries `remedy`/`runtime` through so the client can render the same
+ * one-button fix the Settings panel and the renderer describe.
+ */
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 });
+ const { diagnoseLocalRuntime } = await localRuntime();
+ const d = await diagnoseLocalRuntime({ modelId: modelIdOverride, settings });
+ return {
+ connected: d.readiness === IMAGE_RUNTIME_READINESS.READY,
+ mode: IMAGE_GEN_MODE.LOCAL,
+ model: d.model?.name || d.modelId,
+ modelId: d.modelId,
+ runner: d.runner,
+ runtime: d.runtime,
+ runtimeLabel: d.runtimeLabel,
+ readiness: d.readiness,
+ reason: d.reason,
+ remedy: d.remedy,
+ };
}
// Resolve the cleaner flags from body overrides + saved per-mode settings.
diff --git a/server/services/imageGen/index.test.js b/server/services/imageGen/index.test.js
index 19209ff820..46a365e0da 100644
--- a/server/services/imageGen/index.test.js
+++ b/server/services/imageGen/index.test.js
@@ -5,17 +5,19 @@ 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,
}));
+// The model registry moved behind the shared diagnosis in localRuntime.js, which
+// reads it from the lib leaf rather than through the renderer.
+vi.mock('../../lib/mediaModels.js', () => ({ getImageModels: vi.fn(() => models.value) }));
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() }));
+vi.mock('../../lib/pythonSetup.js', () => ({ isFlux2VenvHealthy: vi.fn(), FLUX2_VENV_DEFAULT: '/test/venv-flux2/bin/python3' }));
import { checkConnection } from './index.js';
import { getSetupCheck } from './setup.js';
@@ -121,7 +123,8 @@ describe('local image connection readiness', () => {
await expect(checkConnection()).resolves.toMatchObject({
connected: false,
readiness: 'unavailable',
- reason: 'The FLUX.2 image runtime is not installed or healthy',
+ reason: expect.stringContaining('shared torch image runtime is not installed or healthy'),
+ remedy: { kind: 'install-torch-venv', label: 'Install runtime', venvPath: '/test/venv-flux2/bin/python3' },
});
});
});
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index cb4e2933ad..af5581b010 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -25,7 +25,8 @@ import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { rejectDegenerateFrame } from './frameGuard.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
-import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';
+import { resolveFlux2Python, FLUX2_VENV_DEFAULT, isFlux2VenvHealthy, invalidateFlux2Health } from '../../lib/pythonSetup.js';
+import { usesTorchVenv } from '../../lib/imageRuntimeRemedies.js';
import { hfChildEnv } from '../hfToken.js';
import { extractGatedRepo, isGatedRepoError } from '../../lib/hfErrors.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
@@ -579,9 +580,27 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// Both flux2 and z-image runners resolve their own Python via the FLUX.2
// venv — only the legacy mflux/imagine_win path needs the user-configured
// Settings > Image Gen pythonPath.
- if (!isFlux2(model) && !usesDiffusersRunner(model) && !pythonPath) {
+ if (!usesTorchVenv(model) && !pythonPath) {
throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' });
}
+ // Health, not mere presence. buildArgs below only checks that the shared
+ // torch venv's python BINARY exists, so a venv left half-installed (killed
+ // mid-download, a hand-run pip upgrade that broke diffusers) spawned anyway
+ // and died with an ImportError the caller saw as a bare "Exit code 1" — the
+ // 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);
+ 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.`,
+ // Same code buildArgs throws when the venv's python is missing outright:
+ // "the shared torch runtime is not usable" is one state to a caller,
+ // whether it is absent or broken.
+ { status: 400, code: 'IMAGE_GEN_FLUX2_NOT_INSTALLED' },
+ );
+ }
+ }
// FLUX.2 and Z-Image runners now load LoRAs via diffusers'
// pipe.load_lora_weights — but only LoRAs trained against the matching
// base model will produce sensible output. The LoRA picker UI uses the
@@ -955,6 +974,18 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
userMessage = 'Your mflux install is corrupted (entry-point shim and package layout out of sync). Repair with: `pip uninstall -y mflux && pip install --user --force-reinstall --no-cache-dir --no-deps mflux`. If you use conda, run the same in your conda env\'s pip.';
}
}
+ // The precheck passed (or its memoized "healthy" answer is now stale) and
+ // 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 (!userMessage && usesTorchVenv(model)) {
+ const importBroken = lines.some((l) => /^(ModuleNotFoundError|ImportError)\b/.test(l) || /cannot import name /.test(l));
+ if (importBroken) {
+ invalidateFlux2Health();
+ userKind = 'torch_runtime_broken';
+ userMessage = `The shared torch image runtime at ${FLUX2_VENV_DEFAULT} could not import its packages. Reinstall it from Settings › Image Gen › Local, then retry this render.`;
+ }
+ }
// Legacy mflux-generate is a pre-built binary, so it doesn't emit the
// structured USER_ERROR markers the flux2/z-image Python runners use.
// Match the raw huggingface_hub stack instead — `GatedRepoError` or the
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 9b05a05e9e..76f9380318 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -6,8 +6,13 @@ import { tmpdir } from 'os';
// FLUX.2 venv resolution mock — flip between "installed" and "missing" with
// the .returnValue setter on each test.
const mockResolveFlux2Python = vi.fn();
+// Health is a SEPARATE probe from resolution: a half-installed venv still has
+// its python binary, which is exactly the state generateImage now refuses.
+const mockIsFlux2VenvHealthy = vi.fn(async () => true);
vi.mock('../../lib/pythonSetup.js', () => ({
resolveFlux2Python: () => mockResolveFlux2Python(),
+ isFlux2VenvHealthy: () => mockIsFlux2VenvHealthy(),
+ invalidateFlux2Health: vi.fn(),
FLUX2_VENV_DEFAULT: '/fake/home/.portos/venv-flux2/bin/python3',
}));
@@ -21,6 +26,7 @@ vi.mock('../../lib/pythonSetup.js', () => ({
let tmpRegistryDir;
let priorRegistryEnv;
let buildArgs;
+let generateImage;
let buildSidecarMeta;
let resolveOutputPlacement;
let parseImageExecutionMarker;
@@ -31,7 +37,7 @@ beforeAll(async () => {
priorRegistryEnv = process.env.PORTOS_MEDIA_MODELS_FILE;
process.env.PORTOS_MEDIA_MODELS_FILE = join(tmpRegistryDir, 'media-models.json');
vi.resetModules();
- ({ buildArgs, buildSidecarMeta, resolveOutputPlacement, parseImageExecutionMarker } = await import('./local.js'));
+ ({ buildArgs, buildSidecarMeta, resolveOutputPlacement, parseImageExecutionMarker, generateImage } = await import('./local.js'));
({ PATHS } = await import('../../lib/fileUtils.js'));
});
@@ -974,3 +980,26 @@ describe('imageGen local.resolveOutputPlacement (issue #2264 non-gallery render
expect(resolveOutputPlacement({ dir: 123 }).outputDir).toBe(PATHS.images);
});
});
+
+describe('imageGen local.generateImage runtime pre-flight', () => {
+ beforeEach(() => {
+ mockResolveFlux2Python.mockReset();
+ mockIsFlux2VenvHealthy.mockReset();
+ });
+
+ // The binary exists, so buildArgs would happily spawn it — and did, until the
+ // render died inside python with an ImportError the Decks page rendered as an
+ // unexplained "Failed". Refuse before spawning, with the reason and the
+ // one-button remedy the status probe reports for the same machine.
+ it('refuses a shared-torch-runtime render when the venv is present but unhealthy', async () => {
+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');
+ mockIsFlux2VenvHealthy.mockResolvedValue(false);
+
+ await expect(generateImage({ modelId: 'flux2-klein-4b', 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'),
+ });
+ });
+});
diff --git a/server/services/imageGen/localRuntime.js b/server/services/imageGen/localRuntime.js
new file mode 100644
index 0000000000..fb3d5e1242
--- /dev/null
+++ b/server/services/imageGen/localRuntime.js
@@ -0,0 +1,134 @@
+/**
+ * Local image-gen runtime diagnosis — the ONE place that answers "can this
+ * machine render with the selected local model, and if not, what single action
+ * fixes it?".
+ *
+ * The answer used to be computed in three places that disagreed: the status
+ * probe behind the Image Gen banner (which probed the shared torch venv), the
+ * Settings › Image Gen › Local panel (which probed only the mflux interpreter's
+ * pip packages, and so reported "All required packages installed" while the
+ * selected FLUX.2 default was unrenderable), and the renderer (which checked
+ * only that the venv's python BINARY existed, letting a broken venv fail as a
+ * bare `Exit code 1` on the Decks page).
+ *
+ * Every unavailable verdict names a `remedy` the UI renders as a single button.
+ */
+
+import { getSettings } from '../settings.js';
+import { getImageModels } from '../../lib/mediaModels.js';
+import { getSetupCheck } from './setup.js';
+import { isFlux2VenvHealthy, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';
+import { LOCAL_IMAGEGEN_DEFAULT_MODEL } from './modes.js';
+import {
+ IMAGE_RUNTIME_LABELS, IMAGE_RUNTIME_READINESS, IMAGE_RUNTIME_REMEDY, imageRuntimeFor, usesTorchVenv,
+} from '../../lib/imageRuntimeRemedies.js';
+
+const { READY, UNAVAILABLE, UNKNOWN } = IMAGE_RUNTIME_READINESS;
+
+/**
+ * Diagnose the local runtime for one model.
+ *
+ * `settings` is optional — pass the already-loaded object from a caller that
+ * has one (the dispatcher does) so a status poll doesn't re-read settings.
+ */
+export async function diagnoseLocalRuntime({ modelId: requestedModelId, settings } = {}) {
+ const s = settings || await getSettings();
+ const local = s?.imageGen?.local || {};
+ const modelId = requestedModelId || local.modelId || LOCAL_IMAGEGEN_DEFAULT_MODEL;
+ const model = getImageModels().find((entry) => entry.id === modelId);
+
+ if (!model) {
+ return {
+ modelId,
+ model: null,
+ runner: null,
+ runtime: null,
+ runtimeLabel: null,
+ readiness: UNAVAILABLE,
+ reason: `Selected local model "${modelId}" is unavailable on this machine`,
+ remedy: { kind: IMAGE_RUNTIME_REMEDY.CHOOSE_MODEL, label: 'Choose a different model' },
+ };
+ }
+
+ // Every branch below answers for one model, so the identity fields are bound
+ // once here rather than re-passed at each of the nine return sites — where one
+ // of them would eventually be forgotten.
+ const runtime = imageRuntimeFor(model);
+ const verdict = ({ readiness, reason = null, remedy = null }) => ({
+ modelId,
+ model: { id: model.id, name: model.name || model.id, runner: model.runner || 'mflux' },
+ runner: model.runner || 'mflux',
+ runtime,
+ runtimeLabel: IMAGE_RUNTIME_LABELS[runtime],
+ readiness,
+ reason,
+ remedy,
+ });
+
+ const compat = model.hardwareCompatibility;
+ if (compat?.state === 'unavailable') {
+ return verdict({
+ readiness: UNAVAILABLE,
+ reason: compat.reasons?.join(' · ') || 'Selected model is incompatible with this machine',
+ remedy: { kind: IMAGE_RUNTIME_REMEDY.CHOOSE_MODEL, label: 'Choose a compatible model' },
+ });
+ }
+ if (compat?.state === 'unknown') {
+ return verdict({
+ readiness: UNKNOWN,
+ reason: compat.reasons?.join(' · ') || 'Could not verify this machine supports the selected model',
+ });
+ }
+
+ if (usesTorchVenv(model)) {
+ // Health, not mere presence: a killed-mid-install venv still has its python
+ // 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);
+ if (healthy === true) return verdict({ readiness: READY });
+ if (healthy === false) {
+ return verdict({
+ readiness: UNAVAILABLE,
+ reason: `The shared torch image runtime is not installed or healthy (expected at ${FLUX2_VENV_DEFAULT})`,
+ remedy: { kind: IMAGE_RUNTIME_REMEDY.INSTALL_TORCH_VENV, label: 'Install runtime', venvPath: FLUX2_VENV_DEFAULT },
+ });
+ }
+ return verdict({ readiness: UNKNOWN, reason: 'Could not verify the shared torch image runtime' });
+ }
+
+ const pythonPath = local.pythonPath || null;
+ if (!pythonPath) {
+ return verdict({
+ readiness: UNAVAILABLE,
+ reason: 'Python path not configured',
+ remedy: { kind: IMAGE_RUNTIME_REMEDY.SET_PYTHON_PATH, label: 'Detect Python' },
+ });
+ }
+ const setup = await getSetupCheck(pythonPath).then((result) => result).catch(() => null);
+ if (!setup) return verdict({ readiness: UNKNOWN, reason: 'Could not verify the configured Python runtime' });
+ if (setup.archMismatch) {
+ return verdict({
+ readiness: UNAVAILABLE,
+ reason: `Python architecture ${setup.interpreterArch || 'unknown'} is incompatible with this ${setup.hostArch || 'host'} runtime`,
+ remedy: {
+ kind: IMAGE_RUNTIME_REMEDY.SWITCH_PYTHON,
+ label: setup.suggestedArm64Python ? `Switch to ${setup.suggestedArm64Python}` : 'Choose a matching Python',
+ pythonPath: setup.suggestedArm64Python || null,
+ },
+ });
+ }
+ if (setup.missing?.length) {
+ return verdict({
+ readiness: UNAVAILABLE,
+ reason: `Missing required packages: ${setup.missing.join(', ')}`,
+ remedy: {
+ kind: IMAGE_RUNTIME_REMEDY.INSTALL_PACKAGES,
+ label: `Install ${setup.missing.length} missing package${setup.missing.length === 1 ? '' : 's'}`,
+ pythonPath,
+ packages: setup.missingPip || [],
+ },
+ });
+ }
+ return verdict({ readiness: READY });
+}
diff --git a/server/services/imageGen/localRuntime.test.js b/server/services/imageGen/localRuntime.test.js
new file mode 100644
index 0000000000..784aace387
--- /dev/null
+++ b/server/services/imageGen/localRuntime.test.js
@@ -0,0 +1,70 @@
+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('../../lib/mediaModels.js', () => ({ getImageModels: vi.fn(() => models.value) }));
+vi.mock('./setup.js', () => ({ getSetupCheck: vi.fn() }));
+vi.mock('../../lib/pythonSetup.js', () => ({
+ isFlux2VenvHealthy: vi.fn(),
+ FLUX2_VENV_DEFAULT: '/test/venv-flux2/bin/python3',
+}));
+
+import { diagnoseLocalRuntime } from './localRuntime.js';
+import { getSetupCheck } from './setup.js';
+import { isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
+
+const mflux = { id: 'dev', name: 'FLUX.1 Dev', runner: 'mflux', hardwareCompatibility: { state: 'available', reasons: [] } };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ models.value = [mflux];
+ settings.value = { imageGen: { local: { pythonPath: '/test/python3' } } };
+});
+
+// Every unavailable verdict has to name the ONE action that fixes it, or the UI
+// falls back to "go look in Settings" — which is precisely the loop this module
+// exists to close, because the Settings panel probes a different interpreter and
+// 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' } } };
+ isFlux2VenvHealthy.mockResolvedValue(false);
+
+ await expect(diagnoseLocalRuntime()).resolves.toMatchObject({
+ readiness: 'unavailable',
+ runtime: 'torch-venv',
+ remedy: { kind: 'install-torch-venv', venvPath: '/test/venv-flux2/bin/python3' },
+ });
+ });
+
+ it('offers the pip install, with the pip-spec names, for a missing mflux package', async () => {
+ getSetupCheck.mockResolvedValue({ missing: ['cv2'], missingPip: ['opencv-python'], archMismatch: false });
+
+ await expect(diagnoseLocalRuntime()).resolves.toMatchObject({
+ readiness: 'unavailable',
+ runtime: 'mflux-python',
+ remedy: { kind: 'install-packages', pythonPath: '/test/python3', packages: ['opencv-python'] },
+ });
+ });
+
+ it('offers the suggested interpreter when the configured one is the wrong architecture', async () => {
+ getSetupCheck.mockResolvedValue({
+ missing: [], archMismatch: true, interpreterArch: 'x86_64', hostArch: 'arm64',
+ suggestedArm64Python: '/opt/homebrew/bin/python3',
+ });
+
+ await expect(diagnoseLocalRuntime()).resolves.toMatchObject({
+ readiness: 'unavailable',
+ remedy: { kind: 'switch-python', pythonPath: '/opt/homebrew/bin/python3' },
+ });
+ });
+
+ it('leaves an unverifiable runtime without a remedy rather than guessing one', async () => {
+ getSetupCheck.mockRejectedValue(new Error('spawn failed'));
+
+ await expect(diagnoseLocalRuntime()).resolves.toMatchObject({ readiness: 'unknown', remedy: null });
+ });
+});
diff --git a/server/services/imageGen/regen.js b/server/services/imageGen/regen.js
index f6f54e64cb..8b2c8d42f2 100644
--- a/server/services/imageGen/regen.js
+++ b/server/services/imageGen/regen.js
@@ -29,6 +29,7 @@ import sharp from 'sharp';
import { getSettings } from '../settings.js';
import { getImageModels, isFlux2 } from '../../lib/mediaModels.js';
import { usesDiffusersRunner } from '../../lib/runners.js';
+import { usesTorchVenv } from '../../lib/imageRuntimeRemedies.js';
import { isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
import { IMAGE_GEN_MODE } from './modes.js';
@@ -151,7 +152,7 @@ export function clampRegenDimensions(srcWidth, srcHeight, maxMegapixels = DEFAUL
// FLUX.2 + the diffusers-family runners (Z-Image / ERNIE / HiDream / Qwen) all
// share the FLUX.2 venv and implement img2img via `--image-path`.
-export const modelUsesFluxVenv = (model) => isFlux2(model) || usesDiffusersRunner(model);
+export { usesTorchVenv as modelUsesFluxVenv };
// Whether a model RELIABLY does the img2img round-trip regen needs — i.e. it
// honors the init image rather than silently degrading to txt2img (which would
@@ -209,7 +210,7 @@ export async function resolveRegenBackend({ sourceModelId } = {}) {
const mfluxReady = mfluxBinaryPresent(pythonPath);
const candidates = orderRegenCandidates(models, sourceModelId).filter(modelSupportsRegen);
for (const model of candidates) {
- if (modelUsesFluxVenv(model)) {
+ if (usesTorchVenv(model)) {
if (fluxVenvHealthy) return { available: true, model, pythonPath };
} else if (mfluxReady) {
return { available: true, model, pythonPath };
diff --git a/server/services/imageGen/regen.test.js b/server/services/imageGen/regen.test.js
index f5f40d1b54..7f585f4396 100644
--- a/server/services/imageGen/regen.test.js
+++ b/server/services/imageGen/regen.test.js
@@ -6,8 +6,11 @@ vi.mock('../../lib/mediaModels.js', () => ({
getImageModels: vi.fn(() => []),
isFlux2: (m) => m?.runner === 'flux2',
}));
+// imageRuntimeRemedies.js classifies a model from BOTH predicates, so the mock
+// has to supply both or the shared classifier can't resolve.
vi.mock('../../lib/runners.js', () => ({
usesDiffusersRunner: (m) => m?.runner === 'z-image',
+ isFlux2: (m) => m?.runner === 'flux2',
}));
vi.mock('../settings.js', () => ({
getSettings: vi.fn(async () => ({})),
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 9efabb1612..9a9ed9f7ab 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -33,6 +33,7 @@ import { unlink } from 'fs/promises';
import { join, resolve as pathResolve, sep as PATH_SEP } from 'path';
import { PATHS, readJSONFileStrict, atomicWrite, ensureDir, sleep } from '../../lib/fileUtils.js';
import { SSE_HEADERS } from '../../lib/sseHeaders.js';
+import { ServerError } from '../../lib/errorHandler.js';
import { reapAndCleanDetachedDirs } from '../../lib/detachedSpawn.js';
import {
broadcastSse,
@@ -669,7 +670,14 @@ function startLaneJob(job, { lane }) {
if (job.status === 'running') {
job.status = job.cancelRequested ? 'canceled' : 'failed';
videoHolds.captureFailure(job, err);
- job.error = job.cancelRequested ? 'Canceled' : `runJob threw: ${err.message}`;
+ // A ServerError carries a message the gen module wrote FOR the user, so
+ // surface it verbatim — every media surface renders `job.error`, and the
+ // "runJob threw:" prefix turned an actionable refusal into developer
+ // noise. Anything else is an unexpected crash and keeps the prefix so
+ // the origin stays obvious.
+ job.error = job.cancelRequested
+ ? 'Canceled'
+ : err instanceof ServerError ? err.message : `runJob threw: ${err.message}`;
job.completedAt = new Date().toISOString();
broadcastSse(ensureSseEntry(job.id), job.cancelRequested
? { type: 'canceled', reason: job.error } : { type: 'error', error: job.error });