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: filter model choices by host capabilities

[._.]/ Adam Eivyef9fd3c51e7b
diff --git a/client/src/components/ProviderModelSelector.jsx b/client/src/components/ProviderModelSelector.jsx
index 33c32b6d4b..09a581fea7 100644
--- a/client/src/components/ProviderModelSelector.jsx
+++ b/client/src/components/ProviderModelSelector.jsx
@@ -52,7 +52,16 @@
* their family.
*/
import { useId } from 'react';
-import { effectiveModelFor, effortLevelsForProvider, effortSurvivingModel, localToolUseHint, withToolUseOptionLabel } from '../utils/providers.js';
+import {
+ effectiveModelFor,
+ effortLevelsForProvider,
+ effortSurvivingModel,
+ filterHardwareCompatibleProviderModels,
+ isProviderHardwareCompatible,
+ isProviderModelHardwareCompatible,
+ localToolUseHint,
+ withToolUseOptionLabel,
+} from '../utils/providers.js';
import useToolUseModelIds from '../hooks/useToolUseModelIds.js';
import EffortSelect from './cos/EffortSelect.jsx';
import ToolUseWarning from './ui/ToolUseWarning.jsx';
@@ -125,9 +134,19 @@ export default function ProviderModelSelector({
// silently blanking the select. This is the single DRY gate for every
// provider→model picker; callers may also pre-filter, which is idempotent.
const visibleProviders = providers.filter(
- (p) => p.enabled !== false || p.id === selectedProviderId
+ (p) => (p.enabled !== false || p.id === selectedProviderId)
+ && (isProviderHardwareCompatible(p) || p.id === selectedProviderId)
);
- const showModel = alwaysShowModel || availableModels.length > 0;
+ const compatibleModels = filterHardwareCompatibleProviderModels(availableModels, selectedProvider);
+ const selectedModelIsUnavailable = Boolean(
+ selectedModel
+ && !isProviderModelHardwareCompatible(selectedProvider, selectedModel)
+ );
+ const modelOptions = selectedModelIsUnavailable
+ && !compatibleModels.some((model) => modelOption(model)?.value === selectedModel)
+ ? [selectedModel, ...compatibleModels]
+ : compatibleModels;
+ const showModel = alwaysShowModel || modelOptions.length > 0;
// The effort select is opt-in (`onEffortChange`) AND self-hiding: EffortSelect
// renders null for a provider with no effort control, so gate the label+wrapper
// on the same predicate or a non-effort provider gets an orphaned label.
@@ -160,9 +179,14 @@ export default function ProviderModelSelector({
className={SELECT_CLASS}
>
{emptyProviderOption != null && <option value="">{emptyProviderOption}</option>}
- {visibleProviders.map(p => (
- <option key={p.id} value={p.id}>{p.name}</option>
- ))}
+ {visibleProviders.map((p) => {
+ const unavailable = !isProviderHardwareCompatible(p);
+ return (
+ <option key={p.id} value={p.id} disabled={unavailable}>
+ {p.name}{unavailable ? ' (unavailable on this machine)' : ''}
+ </option>
+ );
+ })}
</select>
</div>
{showModel && (
@@ -178,13 +202,18 @@ export default function ProviderModelSelector({
className={SELECT_CLASS}
>
{emptyModelOption != null && <option value="">{emptyModelOption}</option>}
- {availableModels.map(m => {
+ {modelOptions.map(m => {
const opt = modelOption(m);
if (!opt) return null;
+ const unavailable = !isProviderModelHardwareCompatible(selectedProvider, opt.value);
const label = annotateToolUse
? withToolUseOptionLabel(opt.value, opt.label, selectedProvider, toolUseIdsByProvider)
: opt.label;
- return <option key={opt.value} value={opt.value}>{label}</option>;
+ return (
+ <option key={opt.value} value={opt.value} disabled={unavailable}>
+ {unavailable ? `${label} (unavailable on this machine)` : label}
+ </option>
+ );
})}
</select>
{/* No remediation link: this selector renders in hosts that aren't
diff --git a/client/src/components/ProviderModelSelector.test.jsx b/client/src/components/ProviderModelSelector.test.jsx
index 0f7d1a6f8e..f559f58423 100644
--- a/client/src/components/ProviderModelSelector.test.jsx
+++ b/client/src/components/ProviderModelSelector.test.jsx
@@ -119,6 +119,22 @@ describe('ProviderModelSelector', () => {
expect(labels).toEqual(['Provider One', 'Provider Two']);
});
+ it('hides incompatible providers and models while preserving selected pins', () => {
+ renderSelector({
+ providers: [
+ { id: 'p1', name: 'Provider One', modelHardwareCompatibility: { 'too-large': { state: 'unavailable' } } },
+ { id: 'p2', name: 'Provider Two', hardwareCompatibility: { state: 'unavailable' } },
+ { id: 'p3', name: 'Provider Three' },
+ ],
+ selectedModel: 'too-large',
+ availableModels: ['too-large', 'small'],
+ });
+ const [providerSelect, modelSelect] = screen.getAllByRole('combobox');
+ expect([...providerSelect.querySelectorAll('option')].map((option) => option.value)).toEqual(['p1', 'p3']);
+ expect([...modelSelect.querySelectorAll('option')].map((option) => option.value)).toEqual(['too-large', 'small']);
+ expect(modelSelect.querySelector('option[value="too-large"]').disabled).toBe(true);
+ });
+
it('stacks the selects vertically when layout="stacked"', () => {
const { container } = renderSelector({ layout: 'stacked' });
expect(container.firstChild.className).toContain('flex-col');
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsx
index 26e86ad5a1..0bd693104a 100644
--- a/client/src/components/providers/ProviderCard.jsx
+++ b/client/src/components/providers/ProviderCard.jsx
@@ -16,12 +16,14 @@ import { Terminal } from 'lucide-react';
import {
CONTEXT_WINDOW_SOURCE,
PROVIDER_CARD_STATE,
+ filterHardwareCompatibleProviderModels,
isApiProvider,
isGrokBuildCli,
gatewayForProvider,
isPrivateNetworkEndpoint,
isProcessProvider,
isRunnerAllowedCommand,
+ isProviderHardwareCompatible,
isTuiProvider,
isLaunchableTuiProvider,
providerTypeClass,
@@ -97,6 +99,7 @@ export default function ProviderCard({
servingModel = false,
}) {
const style = CARD_STATE_STYLES[cardState.state];
+ const compatibleModels = filterHardwareCompatibleProviderModels(provider.models, provider);
return (
<div
className={`@container bg-port-card border border-l-4 rounded-xl p-4 ${style.border} ${style.dim || ''} ${
@@ -177,6 +180,14 @@ export default function ProviderCard({
NO AGENT RUNNER
</span>
)}
+ {!isProviderHardwareCompatible(provider) && (
+ <span
+ className="text-xs px-2 py-0.5 rounded bg-port-warning/20 text-port-warning"
+ title={provider.hardwareCompatibility?.reasons?.join(' · ')}
+ >
+ HARDWARE MISMATCH
+ </span>
+ )}
</div>
<div className="flex flex-wrap items-center gap-2 @2xl:justify-end">
@@ -298,6 +309,12 @@ export default function ProviderCard({
</div>
)}
+ {!isProviderHardwareCompatible(provider) && (
+ <div className="max-w-3xl text-xs rounded border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-port-warning">
+ Hidden from provider/model pickers on this machine: {provider.hardwareCompatibility?.reasons?.join(' · ') || 'hardware requirements are not met'}.
+ </div>
+ )}
+
<div className="text-sm text-gray-400 space-y-1">
{provider.llamaBacked && (
<p className="text-xs text-purple-300/90">
@@ -337,8 +354,8 @@ export default function ProviderCard({
<p className="text-xs">API key: <span className="text-port-warning">not set — Edit this provider to paste one</span></p>
)
)}
- {provider.models?.length > 0 && (
- <p>Models: {provider.models.slice(0, 3).join(', ')}{provider.models.length > 3 ? ` +${provider.models.length - 3}` : ''}</p>
+ {compatibleModels.length > 0 && (
+ <p>Models: {compatibleModels.slice(0, 3).join(', ')}{compatibleModels.length > 3 ? ` +${compatibleModels.length - 3}` : ''}</p>
)}
{provider.defaultModel && (
<p className="break-words">Default: <code className="text-gray-300 break-all">{provider.defaultModel}</code></p>
diff --git a/client/src/hooks/useLocalModels.js b/client/src/hooks/useLocalModels.js
index d43f20b1cf..dfe94d3043 100644
--- a/client/src/hooks/useLocalModels.js
+++ b/client/src/hooks/useLocalModels.js
@@ -23,7 +23,11 @@ import { getLocalLlmStatus } from '../services/apiLocalLlm';
* can tell "not fetched" from a confirmed `false` and never offers an install
* for an app it simply hasn't heard about yet.
*
- * @returns {{ ollama: string[], lmstudio: string[], installed: { ollama: boolean|null, lmstudio: boolean|null }, recommendations: { ollama: object|null, lmstudio: object|null }, ctxById: Record<string, number>, loading: boolean }}
+ * `hardwareCompatibilityByBackend` carries the server's definitive model
+ * compatibility verdicts into provider editors without changing the existing
+ * string-id API used by other consumers of this hook.
+ *
+ * @returns {{ ollama: string[], lmstudio: string[], installed: { ollama: boolean|null, lmstudio: boolean|null }, recommendations: { ollama: object|null, lmstudio: object|null }, ctxById: Record<string, number>, hardwareCompatibilityByBackend: { ollama: Record<string, object>, lmstudio: Record<string, object> }, loading: boolean }}
*/
export default function useLocalModels() {
const [state, setState] = useState({
@@ -32,6 +36,7 @@ export default function useLocalModels() {
installed: { ollama: null, lmstudio: null },
recommendations: { ollama: null, lmstudio: null },
ctxById: {},
+ hardwareCompatibilityByBackend: { ollama: {}, lmstudio: {} },
loading: true,
});
@@ -43,9 +48,15 @@ export default function useLocalModels() {
if (canceled) return;
const ids = (list) => (list || []).map((m) => m.id || m.name).filter(Boolean);
const ctxById = {};
- for (const m of [...(status?.ollama?.models || []), ...(status?.lmstudio?.models || [])]) {
- const id = m.id || m.name;
- if (id && Number(m.contextLength) > 0) ctxById[id] = m.contextLength;
+ const hardwareCompatibilityByBackend = { ollama: {}, lmstudio: {} };
+ for (const backend of ['ollama', 'lmstudio']) {
+ for (const m of status?.[backend]?.models || []) {
+ const id = m.id || m.name;
+ if (id && m.hardwareCompatibility && typeof m.hardwareCompatibility === 'object') {
+ hardwareCompatibilityByBackend[backend][id] = m.hardwareCompatibility;
+ }
+ if (id && Number(m.contextLength) > 0) ctxById[id] = m.contextLength;
+ }
}
const installedFlag = (backend) => (
typeof status?.[backend]?.installed === 'boolean' ? status[backend].installed : null
@@ -59,6 +70,7 @@ export default function useLocalModels() {
lmstudio: status?.lmstudio?.recommendations?.editorial || null,
},
ctxById,
+ hardwareCompatibilityByBackend,
loading: false,
});
})
diff --git a/client/src/hooks/useProviderModels.js b/client/src/hooks/useProviderModels.js
index 36638b3c70..8d506884d0 100644
--- a/client/src/hooks/useProviderModels.js
+++ b/client/src/hooks/useProviderModels.js
@@ -1,6 +1,13 @@
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import * as api from '../services/api';
-import { filterSelectableModels, selectableModelsForProvider, withStaleAntigravityPin } from '../utils/providers';
+import {
+ filterHardwareCompatibleProviderModels,
+ filterSelectableModels,
+ isProviderHardwareCompatible,
+ isProviderModelHardwareCompatible,
+ selectableModelsForProvider,
+ withStaleAntigravityPin,
+} from '../utils/providers';
// The provider's selectable model source: its `models` list, or — when that
// list is empty (a cloud/manual provider configured with only a defaultModel,
@@ -71,10 +78,22 @@ export default function useProviderModels({ filter, allowDefault = false, silent
// picker on a local backend whose default is a text model), so pick the first
// model that passes the filter instead.
const pickInitialModel = useCallback((provider) => {
- if (!modelFilter) return provider?.defaultModel || '';
- const models = filterSelectableModels(sourceModels(provider, withEffort))
- .filter((m) => modelFilter(m, provider));
- return models[0] || '';
+ const models = filterHardwareCompatibleProviderModels(
+ filterSelectableModels(sourceModels(provider, withEffort)),
+ provider,
+ );
+ if (!modelFilter) {
+ // Configured-default sentinels are intentionally removed from the option
+ // list, but remain a valid selected value when the provider/model gate
+ // says they can run. A model-specific hardware mismatch should instead
+ // fall through to the first compatible real model.
+ if (provider?.defaultModel && isProviderModelHardwareCompatible(provider, provider.defaultModel)) {
+ return provider.defaultModel;
+ }
+ return models[0] || '';
+ }
+ const filtered = models.filter((m) => modelFilter(m, provider));
+ return filtered[0] || '';
}, [modelFilter, withEffort]);
// `load` must NOT depend on `pickInitialModel` (and so on `modelFilter`): a
@@ -96,7 +115,9 @@ export default function useProviderModels({ filter, allowDefault = false, silent
return { providers: [] };
});
const filterFn = filter || (p => p.enabled);
- const filtered = (data.providers || []).filter(filterFn);
+ const filtered = (data.providers || [])
+ .filter(isProviderHardwareCompatible)
+ .filter(filterFn);
setProviders(filtered);
if (!allowDefault && filtered.length > 0 && !hasSetInitialRef.current) {
hasSetInitialRef.current = true;
@@ -123,7 +144,10 @@ export default function useProviderModels({ filter, allowDefault = false, silent
// sourceModels falls back to [defaultModel] when `models` is empty (an
// `[]` is truthy, so a bare `||` would leave the dropdown empty for a
// cloud/manual provider configured with only a defaultModel).
- const models = filterSelectableModels(sourceModels(currentProvider, withEffort));
+ const models = filterHardwareCompatibleProviderModels(
+ filterSelectableModels(sourceModels(currentProvider, withEffort)),
+ currentProvider,
+ );
const filtered = modelFilter ? models.filter((m) => modelFilter(m, currentProvider)) : models;
// Legacy-pin escape hatch (see `withStaleAntigravityPin`): only relevant
// once the list has been collapsed to base models, so it rides `withEffort`.
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 9c16860363..c1c2cb69fe 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -4,7 +4,7 @@ import { AlertTriangle, Gauge } from 'lucide-react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
-import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isGrokBuildCli, isLocalEndpoint, isLocalInstanceProvider, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';
+import { filterHardwareCompatibleProviderModels, filterSelectableModels, filterGenerationModels, isEmbeddingModel, isProviderHardwareCompatible, isProviderModelHardwareCompatible, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isGrokBuildCli, isLocalEndpoint, isLocalInstanceProvider, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, gatewayForProvider, isClaudeCommandProvider, generationControlsFor, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';
import useLocalModels from '../hooks/useLocalModels';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import BrailleSpinner from '../components/BrailleSpinner';
@@ -390,12 +390,13 @@ export default function AIProviders() {
};
const handleAddAllSamples = async () => {
- if (sampleProviders.length === 0) return;
+ const compatibleSamples = sampleProviders.filter(isProviderHardwareCompatible);
+ if (compatibleSamples.length === 0) return;
const succeededIds = [];
const failedIds = [];
- for (const provider of sampleProviders) {
+ for (const provider of compatibleSamples) {
try {
await api.createProvider(provider);
succeededIds.push(provider.id);
@@ -571,12 +572,12 @@ export default function AIProviders() {
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold text-white">Sample Providers</h2>
<div className="flex gap-2">
- {sampleProviders.length > 1 && (
+ {sampleProviders.filter(isProviderHardwareCompatible).length > 1 && (
<button
onClick={handleAddAllSamples}
className="px-3 py-1.5 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded transition-colors"
>
- Add All ({sampleProviders.length})
+ Add All ({sampleProviders.filter(isProviderHardwareCompatible).length})
</button>
)}
<button
@@ -646,6 +647,11 @@ export default function AIProviders() {
{filterSelectableModels(provider.models).length > 0 && (
<p>Models: {filterSelectableModels(provider.models).slice(0, 3).join(', ')}{filterSelectableModels(provider.models).length > 3 ? ` +${filterSelectableModels(provider.models).length - 3}` : ''}</p>
)}
+ {!isProviderHardwareCompatible(provider) && (
+ <p className="text-port-warning">
+ Unavailable on this machine: {provider.hardwareCompatibility?.reasons?.join(' · ') || 'hardware requirements are not met'}
+ </p>
+ )}
{provider.envVars && Object.keys(provider.envVars).length > 0 && (
<div className="mt-0.5">
<span>Env:</span>
@@ -662,10 +668,10 @@ export default function AIProviders() {
</div>
<button
onClick={() => handleAddSample(provider)}
- disabled={addingSample[provider.id]}
+ disabled={addingSample[provider.id] || !isProviderHardwareCompatible(provider)}
className="px-4 py-1.5 text-sm bg-port-success/20 text-port-success hover:bg-port-success/30 rounded transition-colors disabled:opacity-50 shrink-0"
>
- {addingSample[provider.id] ? 'Adding...' : 'Add'}
+ {addingSample[provider.id] ? 'Adding...' : isProviderHardwareCompatible(provider) ? 'Add' : 'Unavailable'}
</button>
</div>
))}
@@ -684,7 +690,7 @@ export default function AIProviders() {
className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white w-full sm:w-auto"
>
<option value="">Select Provider</option>
- {providers.filter(p => p.enabled).map(p => (
+ {providers.filter(p => p.enabled && isProviderHardwareCompatible(p)).map(p => (
<option key={p.id} value={p.id}>{p.name}{isTuiProvider(p) ? ' (CoS TUI)' : ''}</option>
))}
</select>
@@ -883,7 +889,7 @@ export default function AIProviders() {
);
}
-function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders = [], localModels = { ollama: [], lmstudio: [], ctxById: {} }, runnerAllowedCommands = null }) {
+function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders = [], localModels = { ollama: [], lmstudio: [], ctxById: {}, hardwareCompatibilityByBackend: {} }, runnerAllowedCommands = null }) {
const [formData, setFormData] = useState({
name: provider?.name || '',
type: provider?.type || 'cli',
@@ -893,6 +899,8 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
apiKey: '',
allowCustomEndpoint: provider?.allowCustomEndpoint === true,
models: provider?.models || [],
+ hardwareRequirements: provider?.hardwareRequirements,
+ modelHardwareRequirements: provider?.modelHardwareRequirements,
defaultModel: provider?.defaultModel || '',
effort: provider?.effort || '',
lightModel: provider?.lightModel || '',
@@ -931,11 +939,41 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
return backend ? localModels[backend] : [];
};
+ const liveHardwareFor = (p) => {
+ const backend = localBackendForProvider(p);
+ return backend ? localModels.hardwareCompatibilityByBackend?.[backend] || {} : {};
+ };
+
// Generation pickers (default + light/medium/heavy tiers) — drop embedding-only
// models (and internal sentinels) so an embedding can't be chosen as a model
// that runs prompts, consistent with the fallback picker below.
const mergedModels = mergeModelLists(formData.models, liveModelsFor(formData));
- const availableModels = filterGenerationModels(mergedModels);
+ // The server publishes compatibility for both the provider runtime and any
+ // explicitly annotated model. Unknown probe results stay in the list; only a
+ // definitive mismatch is hidden.
+ const capabilityProvider = {
+ ...provider,
+ ...formData,
+ id: provider?.id,
+ models: mergedModels,
+ modelHardwareCompatibility: {
+ ...provider?.modelHardwareCompatibility,
+ ...liveHardwareFor(formData),
+ },
+ };
+ const availableModels = filterHardwareCompatibleProviderModels(
+ filterGenerationModels(mergedModels),
+ capabilityProvider,
+ );
+ const configuredModels = [
+ formData.defaultModel,
+ formData.lightModel,
+ formData.mediumModel,
+ formData.heavyModel,
+ ].filter((model) => model
+ && !isEmbeddingModel(model)
+ && !availableModels.includes(model)
+ && !isProviderModelHardwareCompatible(capabilityProvider, model));
// A provider can pin its tiers to the "use the CLI's own default" sentinel
// while still publishing a real model catalog (Antigravity: `agy models`
// lists real ids, but PortOS leaves the tiers on agy's own default). The
@@ -949,7 +987,6 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
// providers, whose ladder is keyed on `ollamaBacked`. Merge the live edits
// over the stored record instead, so edits to command/endpoint/envVars count
// immediately while the markers survive.
- const capabilityProvider = { ...provider, ...formData, id: provider?.id, models: mergedModels };
// Shared option list for the Default Model + Light/Medium/Heavy tier selects,
// so the sentinel option can't be added to some and missed on others.
const modelSelectOptions = (
@@ -958,23 +995,45 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
{configuredDefault && (
<option value={configuredDefault}>Use the CLI&apos;s configured default</option>
)}
- {availableModels.map(model => (
- <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById, capabilityProvider)}</option>
+ {[...new Set([...configuredModels, ...availableModels])].map(model => (
+ <option key={model} value={model} disabled={!availableModels.includes(model)}>
+ {modelOptionLabel(model, localModels.ctxById, capabilityProvider)}
+ {!availableModels.includes(model) ? ' (unavailable on this machine)' : ''}
+ </option>
))}
</>
);
// Filter out current provider from fallback options (treat undefined enabled as enabled)
- const fallbackOptions = allProviders.filter(p => p.id !== provider?.id && p.enabled !== false);
+ const fallbackOptions = allProviders.filter(p => p.id !== provider?.id
+ && p.enabled !== false
+ && (isProviderHardwareCompatible(p) || p.id === formData.fallbackProvider));
// The fallback model is a model OF the selected fallback provider, so its
// option list comes from that provider's `models` — merged with the live
// installed list for local backends, and embedding-only models dropped (a
// fallback runs prompts, so `nomic-embed-text` must never be selectable here).
const selectedFallbackProvider = allProviders.find(p => p.id === formData.fallbackProvider);
+ const fallbackCapabilityProvider = selectedFallbackProvider && {
+ ...selectedFallbackProvider,
+ modelHardwareCompatibility: {
+ ...selectedFallbackProvider.modelHardwareCompatibility,
+ ...liveHardwareFor(selectedFallbackProvider),
+ },
+ };
const fallbackModelOptions = filterGenerationModels(
mergeModelLists(selectedFallbackProvider?.models, liveModelsFor(selectedFallbackProvider)),
);
+ const compatibleFallbackModelOptions = filterHardwareCompatibleProviderModels(
+ fallbackModelOptions,
+ fallbackCapabilityProvider,
+ );
+ const fallbackModelIsUnavailable = Boolean(
+ formData.fallbackModel
+ && !isEmbeddingModel(formData.fallbackModel)
+ && !compatibleFallbackModelOptions.includes(formData.fallbackModel)
+ && !isProviderModelHardwareCompatible(fallbackCapabilityProvider, formData.fallbackModel)
+ );
// `capabilityProvider`, not `formData`: the per-model windows model refresh
// recorded (`modelContextWindows`) live on the RECORD and are not form fields,
// so reading formData alone reported the assumed 128K for a model whose real
@@ -1165,6 +1224,14 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
mutable state (formData and the new-env-var row) therefore lives in
this component, above the Drawer — never inside the panels below. */}
<form onSubmit={handleSubmit} className="space-y-4">
+ {provider?.hardwareCompatibility?.state === 'unavailable' && (
+ <Banner tone="warning" icon={AlertTriangle}>
+ <p>
+ This provider is unavailable on this machine: {provider.hardwareCompatibility.reasons?.join(' · ') || 'hardware requirements are not met'}.
+ Its models are hidden from selection until the host matches those requirements.
+ </p>
+ </Banner>
+ )}
{activeTab === 'connection' && (
<div className="space-y-4">
<FormField label="Name *">
@@ -1527,7 +1594,9 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
>
<option value="">None (use system default)</option>
{fallbackOptions.map(p => (
- <option key={p.id} value={p.id}>{p.name}</option>
+ <option key={p.id} value={p.id} disabled={!isProviderHardwareCompatible(p)}>
+ {p.name}{!isProviderHardwareCompatible(p) ? ' (unavailable on this machine)' : ''}
+ </option>
))}
</select>
<p className="text-xs text-gray-500 mt-1">
@@ -1537,14 +1606,19 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
{formData.fallbackProvider && (
<FormField label="Fallback Model" className="mt-3">
- {fallbackModelOptions.length > 0 ? (
+ {compatibleFallbackModelOptions.length > 0 ? (
<select
value={formData.fallbackModel}
onChange={(e) => setFormData(prev => ({ ...prev, fallbackModel: e.target.value }))}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
>
<option value="">Use fallback provider's default</option>
- {fallbackModelOptions.map(model => (
+ {fallbackModelIsUnavailable && (
+ <option value={formData.fallbackModel} disabled>
+ {modelOptionLabel(formData.fallbackModel, localModels.ctxById, selectedFallbackProvider)} (unavailable on this machine)
+ </option>
+ )}
+ {compatibleFallbackModelOptions.map(model => (
<option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById, selectedFallbackProvider)}</option>
))}
</select>
diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsx
index a2d83d3c3d..a2717d7a59 100644
--- a/client/src/pages/LocalLlmPlayground.jsx
+++ b/client/src/pages/LocalLlmPlayground.jsx
@@ -9,6 +9,7 @@ import toast from '../components/ui/Toast';
import { copyToClipboard } from '../lib/clipboard';
import { localLlmTargetKey } from '../lib/localLlmTargetKey';
import { formatBytes, recommendedRamGb, timeUntil } from '../utils/formatters';
+import { filterHardwareCompatibleModels } from '../utils/systemCapabilities';
import { compareLocalLlmModels, getLoadedLlmModels, getLocalLlmCatalog, getLocalLlmStatus, streamLocalLlmTest } from '../services/api';
const BACKEND_LABEL = { ollama: 'Ollama', lmstudio: 'LM Studio' };
@@ -316,7 +317,7 @@ export default function LocalLlmPlayground() {
const models = [];
for (const backend of ['ollama', 'lmstudio']) {
const catalogById = new Map((catalogByBackend[backend] || []).map((entry) => [normalizeCatalogId(backend, entry.id), entry]));
- for (const model of status?.[backend]?.models || []) {
+ for (const model of filterHardwareCompatibleModels(status?.[backend]?.models)) {
models.push({
backend,
modelId: model.id,
@@ -345,6 +346,15 @@ export default function LocalLlmPlayground() {
return map;
}, [loadedModels]);
+ useEffect(() => {
+ if (loadingStatus || status == null) return;
+ const installedKeys = new Set(installedTargets.map(localLlmTargetKey));
+ setSelectedTargets((previous) => {
+ const next = previous.filter((target) => installedKeys.has(localLlmTargetKey(target)));
+ return next.length === previous.length ? previous : next;
+ });
+ }, [installedTargets, loadingStatus, status]);
+
useEffect(() => {
if (selectedTargets.length > 0 || installedTargets.length === 0) return;
setSelectedTargets([{ backend: installedTargets[0].backend, modelId: installedTargets[0].modelId }]);
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 42fabc8b4e..bac40d645f 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -62,7 +62,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiScaffold.js` | App scaffolding templates. |
| `apiSchedules.js` | Automation schedules. |
| `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. |
-| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison). |
+| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison). |
| `apiAuth.js` | Optional login password — status, login/logout, set/clear password. |
| `apiLoops.js` | Scheduled loops. |
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 5c4829fdf3..875f7f8e8b 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -1,9 +1,12 @@
import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';
+import { filterHardwareCompatibleModels } from '../utils/systemCapabilities.js';
// Image gen — local backend extras (gallery, models, LoRAs, cancel, delete).
// generateImage / getImageGenStatus / generateAvatar live in apiSystem.js for
// backward compatibility with existing call sites.
-export const listImageModels = (options) => request('/image-gen/models', options);
+export const listImageModels = ({ includeUnavailable = false, ...options } = {}) =>
+ request('/image-gen/models', options)
+ .then((models) => filterHardwareCompatibleModels(models, { includeUnavailable }));
export const listAgyImageModels = (options) => request('/image-gen/agy/models', options);
// Per-model download status: `[{ id, repo, cached, sizeBytes }]`. Drives the
// inline Available/Download badge on the image gen form.
@@ -155,8 +158,14 @@ export async function createImageGenVenv() {
}
// Video gen
-export const getVideoGenStatus = (options = {}) => request('/video-gen/status', options);
-export const listVideoModels = (options) => request('/video-gen/models', options);
+export const getVideoGenStatus = (options = {}) => request('/video-gen/status', options)
+ .then((status) => ({
+ ...status,
+ models: filterHardwareCompatibleModels(status?.models),
+ }));
+export const listVideoModels = ({ includeUnavailable = false, ...options } = {}) =>
+ request('/video-gen/models', options)
+ .then((models) => filterHardwareCompatibleModels(models, { includeUnavailable }));
// Install-wide acknowledgement of a restricted model's reviewed license, keyed
// by the exact `termsGate.id`. Persisted server-side so accepting once (on any
// render surface) authorizes every other one, including background producers.
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index d2f513bc72..6358b24b60 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -24,6 +24,7 @@ export const getCharacter = ({ skills = true, metrics = true, ...options } = {})
// Health
export const checkHealth = (options) => request('/system/health', options);
export const getSystemHealth = (options) => request('/system/health/details', options);
+export const getSystemCapabilities = (options) => request('/system/capabilities', options);
// Its own route, not a field on health/details — peers scrape that payload and
// persist it verbatim, and the build stamp must stay machine-local (#4694).
export const getSystemBuild = (options) => request('/system/build', options);
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 6ab371f4c5..a681ccf0c5 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -42,6 +42,7 @@ grep -i "what you want to do" client/src/utils/README.md
| `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. |
| `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. Also `migrateLegacyNavPath(path, commands)` — maps a stored path onto the CURRENT path of the page that used to answer to it, driven by each command's own `previousPaths` (declared in `server/lib/navManifest.js` beside the page that moved, shipped whole in the palette manifest). A pin is a stored route path, so without it a moved page's pin stops matching the manifest and the sidebar row silently vanishes on update. |
| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isAntigravityProvider`, `isLaunchableTuiProvider` — a TUI provider carrying the server-resolved `tuiCommandLine`, i.e. one a human can start at a shell prompt; shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree — `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` (an OpenCode wrapper front-ending a hosted OpenAI-compatible gateway — `orcarouter`, `openrouter` — which inherits its API key at spawn time from the sibling API provider whose id equals the gateway id; reads the generic `gatewayBacked` marker and, forever, the legacy per-gateway boolean. MIRROR of `server/lib/providerGateways.js`, which the browser cannot import; keep the three copies in lockstep), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — `resolveSeriesRunLlm` (mirror of server `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. `isLocalInstanceProvider(provider)` — the narrower question, mirroring server `localProviderRuntime.js#isLocalInstanceEndpoint`: does this provider talk to a daemon on THIS machine (loopback, or no endpoint at all)? Gate anything that explains a provider by inspecting the host PortOS runs on — install state, "start it from Settings → Local LLM" — since `localBackendForProvider` matches by NAME and would otherwise claim a peer's LM Studio. And `credentialSource(provider)` plus `providerCardState(provider, { runtime, status, keySetFor, envVarSet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential environment variable), or simply switched off? Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, and the same computation `getFallbackProvider` routes on) and adds the local-app runtime shape plus tri-state checks for stored, inherited, and process environment credentials. Unknown lookup values mean "not probed", never "missing". Drives the AI Providers page card colors and grouping — distinct from `ProviderReadiness`/`GET /api/providers/readiness`, which probes the local daemon behind a provider. `resolvesOutsidePortosPath(provider)` — does this provider resolve its binary somewhere the runtime probe never looked (an explicit path in `command`, or its own `PATH` in `envVars`)? Mirror of the same two guards in the server's `providerRuntimeKey`, and what keeps the card's badge from accusing a working provider the router happily routes. And `providerRuntimeKey(provider)` — the key a provider's runtime is published under by `GET /api/providers/runtimes`, so a card can show its CLI install status (bare binary name for a cli/tui provider, provider id for an API provider fronted by a local app); the runtime table itself stays server-side. |
+| `systemCapabilities` | Server-annotated hardware compatibility helpers: preserve model/provider choices when compatibility is unknown, and hide only entries whose `hardwareCompatibility.state` is definitively `unavailable`. |
| `layeredIntelligenceReasons` | Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (`formatLiReason`, `liReasonTone`, `LI_NEUTRAL_REASONS`). |
## Module loading / resilience
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index 77296e59f2..1770331059 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -27,6 +27,7 @@ export * from './urlNormalize.js';
export * from './platform.js';
export * from './navWorkingSet.js';
export * from './providers.js';
+export * from './systemCapabilities.js';
export * from './layeredIntelligenceReasons.js';
// === Module loading / resilience ===
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 616c2a9a62..98670239a6 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -1,4 +1,5 @@
import { formatContextLength } from './formatters.js';
+import { isHardwareCompatible } from './systemCapabilities.js';
/**
* Sentinel value used by the Codex provider to indicate the model is configured
@@ -183,6 +184,24 @@ export const PROVIDER_TYPES = Object.freeze({
export const filterSelectableModels = (models) =>
(models || []).filter(m => !isConfiguredDefaultModel(m));
+/**
+ * Server-side hardware metadata is advisory for unknown probe results and
+ * definitive only when `state` is `unavailable`. Keep this helper fail-open so
+ * older servers and custom providers remain selectable.
+ */
+export const isProviderHardwareCompatible = (provider) =>
+ isHardwareCompatible(provider?.hardwareCompatibility);
+
+export const isProviderModelHardwareCompatible = (provider, model) =>
+ isProviderHardwareCompatible(provider)
+ && isHardwareCompatible(provider?.modelHardwareCompatibility?.[model]);
+
+export const filterHardwareCompatibleProviderModels = (models, provider) =>
+ (models || []).filter((model) => {
+ const modelId = typeof model === 'string' ? model : model?.id;
+ return isProviderModelHardwareCompatible(provider, modelId);
+ });
+
/**
* Reasoning-effort levels per effort-capable CLI — MIRROR of
* `CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` /
diff --git a/client/src/utils/systemCapabilities.js b/client/src/utils/systemCapabilities.js
new file mode 100644
index 0000000000..7c7ed6f81a
--- /dev/null
+++ b/client/src/utils/systemCapabilities.js
@@ -0,0 +1,14 @@
+/**
+ * Browser-side helpers for the server's hardware compatibility annotations.
+ * The browser does not re-probe the host: the server owns detection, and an
+ * absent annotation stays compatible for older servers and custom records.
+ */
+
+export const isHardwareCompatible = (compatibility) => compatibility?.state !== 'unavailable';
+
+export const isHardwareAvailable = (item) => isHardwareCompatible(item?.hardwareCompatibility);
+
+export const filterHardwareCompatibleModels = (models, { includeUnavailable = false } = {}) => {
+ const list = Array.isArray(models) ? models : [];
+ return includeUnavailable ? list : list.filter(isHardwareAvailable);
+};
diff --git a/client/src/utils/systemCapabilities.test.js b/client/src/utils/systemCapabilities.test.js
new file mode 100644
index 0000000000..873df84c6c
--- /dev/null
+++ b/client/src/utils/systemCapabilities.test.js
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+import {
+ filterHardwareCompatibleModels,
+ isHardwareAvailable,
+ isHardwareCompatible,
+} from './systemCapabilities.js';
+import {
+ filterHardwareCompatibleProviderModels,
+ isProviderHardwareCompatible,
+ isProviderModelHardwareCompatible,
+} from './providers.js';
+
+describe('system capability selection helpers', () => {
+ it('fails open for old servers and unknown probes', () => {
+ expect(isHardwareCompatible()).toBe(true);
+ expect(isHardwareCompatible({ state: 'unknown' })).toBe(true);
+ expect(isHardwareAvailable({})).toBe(true);
+ expect(filterHardwareCompatibleModels([
+ { id: 'old-server-model' },
+ { id: 'probe-unknown', hardwareCompatibility: { state: 'unknown' } },
+ { id: 'too-large', hardwareCompatibility: { state: 'unavailable' } },
+ ])).toEqual([
+ { id: 'old-server-model' },
+ { id: 'probe-unknown', hardwareCompatibility: { state: 'unknown' } },
+ ]);
+ });
+
+ it('can include unavailable entries when an editor needs to explain them', () => {
+ const unavailable = { id: 'too-large', hardwareCompatibility: { state: 'unavailable' } };
+ expect(filterHardwareCompatibleModels([unavailable], { includeUnavailable: true })).toEqual([unavailable]);
+ });
+
+ it('filters provider models only when the provider or model is definitively unavailable', () => {
+ const provider = {
+ hardwareCompatibility: { state: 'available' },
+ modelHardwareCompatibility: {
+ small: { state: 'available' },
+ large: { state: 'unavailable' },
+ uncertain: { state: 'unknown' },
+ },
+ };
+ expect(isProviderHardwareCompatible(provider)).toBe(true);
+ expect(isProviderModelHardwareCompatible(provider, 'large')).toBe(false);
+ expect(filterHardwareCompatibleProviderModels(['small', 'large', 'uncertain'], provider)).toEqual(['small', 'uncertain']);
+ expect(isProviderHardwareCompatible({ hardwareCompatibility: { state: 'unavailable' } })).toBe(false);
+ });
+});
diff --git a/docs/API.md b/docs/API.md
index 2efee8a61c..35488423c4 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -31,6 +31,12 @@ PortOS is designed for personal/developer use on trusted networks. It implements
## REST Endpoints
+### System
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/system/capabilities` | Host-local platform, architecture, Apple Silicon, memory, CPU, and cached CUDA capability snapshot used to filter model/provider selections. Probe failures remain `unknown`; this payload is intentionally not included in federation health records. |
+
### Federated peer-probe contract
PortOS peers running independently upgraded installs use the following existing
@@ -528,6 +534,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/alerts` | System alerts |
| `/api/avatar` | Avatar rendering/config |
| `/api/system` | System health metrics |
+| `/api/system/capabilities` | Local hardware capabilities for model/provider selection |
| `/api/capabilities` | Feature capability flags |
| `/api/agent-context` | Opt-in, loopback-only read-only MCP context and runtime manifest |
| `/api/workspace-contexts` | Workspace context management |
diff --git a/server/index.js b/server/index.js
index b9bb779ade..5d662ad366 100644
--- a/server/index.js
+++ b/server/index.js
@@ -15,6 +15,7 @@ import alertsRoutes from './routes/alerts.js';
import appleHealthRoutes from './routes/appleHealth.js';
import avatarRoutes from './routes/avatar.js';
import systemHealthRoutes from './routes/systemHealth.js';
+import systemCapabilitiesRoutes from './routes/systemCapabilities.js';
import systemResourcesRoutes from './routes/systemResources.js';
import capabilitiesRoutes from './routes/capabilities.js';
import agentContextMcpRoutes from './routes/agentContextMcp.js';
@@ -239,6 +240,7 @@ app.use('/api/auth', authRoutes);
app.use('/api/alerts', alertsRoutes);
app.use('/api/avatar', avatarRoutes);
app.use('/api/system', systemHealthRoutes);
+app.use('/api/system/capabilities', systemCapabilitiesRoutes);
app.use('/api/system-resources', systemResourcesRoutes);
app.use('/api/capabilities', capabilitiesRoutes);
app.use('/api/agent-context', agentContextMcpRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index bad0aaea34..2b83ab89c5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -375,7 +375,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |
| `condaEnv.js` | Resolves a NAMED conda environment's interpreter: `condaEnvPythonCandidates(envName)` builds the ordered candidate list (`CONDA_PREFIX` — walking up two levels when it points at an `envs/<name>` rather than a root — then `CONDA_ROOT`, `~/miniconda3`, `~/anaconda3`, `~/miniforge3`, `~/mambaforge`, `/opt/conda`), and `resolveCondaEnvPython(envName, { exists })` returns the first that exists or `null`. Separate from `pythonSetup.js` (which probes *venv* layouts and computes candidates from `PATHS` at module load) so a conda lookup pulls in no eager path work. Used by the image-to-3D CUDA lanes, which each own a distinct env (`trellis2`, `pixal3d`) so one lane's pinned deps can't disturb the other's. |
-| `cudaCapability.js` | NVIDIA CUDA host probe — the one place that shells to `nvidia-smi`. `detectCudaGpus()` / cached `getCudaCapability()` return `{ available, status, gpus, maxVramGb }` where `status` is three-way: `'available'`, `'absent'` (no driver, or driver present with zero GPUs), or `'unknown'` (nvidia-smi exists but wouldn't answer — `available` is `null`, never `false`, so callers can say "couldn't detect" instead of lying about the hardware). `unknown` is not memoized so a transient driver hiccup retries. `parseNvidiaSmiGpus(stdout)` is the pure CSV parser (a `[N/A]` VRAM column yields `vramGb: null`, not a dropped GPU). Gates the image-to-3D `local-cuda` lane and the Windows FLUX.2 CUDA-torch wheel choice (`pythonSetup.js#hasNvidiaGpu`). `detectCudaComputeCapability()` is a SEPARATE `nvidia-smi` query (`--query-gpu=name,compute_cap,memory.total`, parsed by `parseNvidiaSmiComputeCaps`) returning `primaryComputeCap` — the arch of the LARGEST card, since a render uses one GPU — for build flags like NATTEN's `NATTEN_CUDA_ARCH`; kept separate because an older driver rejects `compute_cap` and would fail the whole VRAM query with it. `detectCudaUtilization()` / `getCudaUtilization()` add live per-GPU utilization on a short TTL. |
+| `cudaCapability.js` | NVIDIA CUDA host probe — the one place that shells to `nvidia-smi`. `detectCudaGpus()` / cached `getCudaCapability()` return `{ available, status, gpus, maxVramGb }` where `status` is three-way: `'available'`, `'absent'` (no driver, or driver present with zero GPUs), or `'unknown'` (nvidia-smi exists but wouldn't answer — `available` is `null`, never `false`, so callers can say "couldn't detect" instead of lying about the hardware). `unknown` is not memoized so a transient driver hiccup retries. `parseNvidiaSmiGpus(stdout)` is the pure CSV parser (a `[N/A]` VRAM column yields `vramGb: null`, not a dropped GPU). Gates the image-to-3D `local-cuda` lane and the Windows FLUX.2 CUDA-torch wheel choice (`pythonSetup.js#hasNvidiaGpu`). `detectCudaComputeCapability()` / cached `getCudaComputeCapability()` are a SEPARATE `nvidia-smi` query (`--query-gpu=name,compute_cap,memory.total`, parsed by `parseNvidiaSmiComputeCaps`) returning `primaryComputeCap` — the arch of the LARGEST card, since a render uses one GPU — for build flags like NATTEN's `NATTEN_CUDA_ARCH` and SGLang provider filtering; kept separate because an older driver rejects `compute_cap` and would fail the whole VRAM query with it. `detectCudaUtilization()` / `getCudaUtilization()` add live per-GPU utilization on a short TTL. |
+| `systemCapabilities.js` | Machine-local capability snapshot plus the shared three-state hardware requirement evaluator. Captures coarse platform, architecture, Apple Silicon, memory, CPU, and cached CUDA facts; derives requirements for media models, local-LLM catalog entries, and provider runtimes; hides only known-incompatible choices while preserving `unknown` probe results. |
| `db.js` | PostgreSQL connection pool. |
| `pgTimestamp.js` | `mirrorTimestamp(value, fallback)` — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against `Date.parse` rollover + out-of-range years. |
| `pgTools.js` | `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. |
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index db65694636..3ebc753045 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -592,6 +592,10 @@ export function createProviderService(config = {}) {
endpoint: providerData.endpoint || null,
apiKey: providerData.apiKey || '',
models: providerData.models || [],
+ ...(providerData.hardwareRequirements ? { hardwareRequirements: providerData.hardwareRequirements } : {}),
+ ...(providerData.modelHardwareRequirements
+ ? { modelHardwareRequirements: providerData.modelHardwareRequirements }
+ : {}),
defaultModel: providerData.defaultModel || null,
effort: providerData.effort || null,
lightModel: providerData.lightModel || null,
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index f16bce5c96..16f632811c 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -136,6 +136,8 @@ describe('Provider Service', () => {
endpoint: 'https://api.example.com/v1',
apiKey: 'sk-test-secret',
models: ['model-a', 'model-b', 'model-c'],
+ hardwareRequirements: { platforms: ['darwin'], minMemoryGb: 32 },
+ modelHardwareRequirements: { 'model-c': { minMemoryGb: 64 } },
defaultModel: 'model-a',
effort: 'xhigh',
lightModel: 'model-b',
diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.js
index f58eed6792..04b6bb9b87 100644
--- a/server/lib/aiToolkit/validation.js
+++ b/server/lib/aiToolkit/validation.js
@@ -18,6 +18,18 @@ const providerEffort = z.preprocess(
z.enum(PROVIDER_EFFORT_LEVELS).nullable().optional()
);
+// Hardware metadata is declarative and machine-local. Keep the shape bounded
+// so a provider record cannot turn into an unbounded arbitrary JSON payload.
+const providerHardwareRequirementsSchema = z.object({
+ platforms: z.array(z.string().trim().min(1).max(32)).min(1).max(8).optional(),
+ architectures: z.array(z.string().trim().min(1).max(32)).min(1).max(8).optional(),
+ requiresAppleSilicon: z.boolean().optional(),
+ requiresNvidiaGpu: z.boolean().optional(),
+ minMemoryGb: z.number().positive().max(4096).optional(),
+ minVramGb: z.number().positive().max(4096).optional(),
+ minCudaComputeCapability: z.number().positive().max(20).optional(),
+}).strict();
+
/**
* Sanitize the untrusted `screenshots[]` array from POST /api/runs into safe,
* screenshots-dir-relative basenames. `screenshots[]` is unauthenticated user
@@ -73,6 +85,11 @@ export const providerSchema = z.object({
),
apiKey: z.string().optional(),
models: z.array(z.string()).optional(),
+ // Optional hardware gates for local providers. The PortOS host decorates
+ // responses with inferred runtime requirements as well, so old records do
+ // not need a migration to participate in filtering.
+ hardwareRequirements: providerHardwareRequirementsSchema.optional(),
+ modelHardwareRequirements: z.record(providerHardwareRequirementsSchema).optional(),
defaultModel: z.string().nullable().optional(),
// Empty string is the UI's "use the provider/CLI default" sentinel.
effort: providerEffort,
diff --git a/server/lib/cudaCapability.js b/server/lib/cudaCapability.js
index 35fa250a8a..e76c919aac 100644
--- a/server/lib/cudaCapability.js
+++ b/server/lib/cudaCapability.js
@@ -310,6 +310,28 @@ export function resetCudaCapabilityCache() {
cacheExpiresAt = Infinity;
}
+// Compute capability is a separate nvidia-smi query because older drivers can
+// answer the VRAM query while rejecting the `compute_cap` column. Cache it with
+// the same three-state retry policy so provider responses do not spawn a second
+// process on every request.
+let cachedComputeProbe = null;
+let computeCacheExpiresAt = Infinity;
+
+export async function getCudaComputeCapability({ refresh = false, now = Date.now, ...probeOpts } = {}) {
+ if (!refresh && cachedComputeProbe && now() < computeCacheExpiresAt) return cachedComputeProbe;
+ const pending = detectCudaComputeCapability(probeOpts);
+ cachedComputeProbe = pending;
+ computeCacheExpiresAt = Infinity;
+ const result = await pending;
+ if (result.status === 'unknown') computeCacheExpiresAt = now() + CUDA_UNKNOWN_RETRY_MS;
+ return result;
+}
+
+export function resetCudaComputeCapabilityCache() {
+ cachedComputeProbe = null;
+ computeCacheExpiresAt = Infinity;
+}
+
let cachedUtilization = null;
let utilizationExpiresAt = 0;
export const CUDA_UTILIZATION_TTL_MS = 4000;
diff --git a/server/lib/cudaCapability.test.js b/server/lib/cudaCapability.test.js
index fa8369908f..7351915983 100644
--- a/server/lib/cudaCapability.test.js
+++ b/server/lib/cudaCapability.test.js
@@ -4,7 +4,9 @@ import {
parseNvidiaSmiGpus,
detectCudaGpus,
getCudaCapability,
+ getCudaComputeCapability,
resetCudaCapabilityCache,
+ resetCudaComputeCapabilityCache,
CUDA_UNKNOWN_RETRY_MS,
parseNvidiaSmiComputeCaps,
detectCudaComputeCapability,
@@ -19,7 +21,10 @@ const RTX_3090 = 'NVIDIA GeForce RTX 3090, 24576\n';
/** An execFile stub that invokes the callback with `(err, stdout)`. */
const execStub = (err, stdout = '') => vi.fn((_cmd, _args, _opts, cb) => cb(err, stdout));
-beforeEach(() => resetCudaCapabilityCache());
+beforeEach(() => {
+ resetCudaCapabilityCache();
+ resetCudaComputeCapabilityCache();
+});
describe('parseNvidiaSmiGpus', () => {
it('parses a real single-GPU reading and rounds VRAM to whole GB', () => {
@@ -251,6 +256,15 @@ describe('detectCudaComputeCapability', () => {
});
});
+describe('getCudaComputeCapability caching', () => {
+ it('probes once and serves the cached compute capability afterwards', async () => {
+ const execFileImpl = execStub(null, 'NVIDIA RTX 5090, 12.0, 32768\n');
+ await getCudaComputeCapability({ execFileImpl });
+ await getCudaComputeCapability({ execFileImpl });
+ expect(execFileImpl).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('detectCudaUtilization', () => {
it('parses utilization rows', async () => {
const res = await detectCudaUtilization({
diff --git a/server/lib/index.js b/server/lib/index.js
index ef8d4558af..cb34969275 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -362,6 +362,7 @@ export * from './db.js';
export * from './pgTimestamp.js';
export * from './pgTools.js';
export * from './platform.js';
+export * from './systemCapabilities.js';
export * from './ports.js';
export * from './signalCrypto.js';
export * from './timezone.js';
diff --git a/server/lib/localLlmCatalog.js b/server/lib/localLlmCatalog.js
index 0441ed7e1e..24d04c49f3 100644
--- a/server/lib/localLlmCatalog.js
+++ b/server/lib/localLlmCatalog.js
@@ -14,6 +14,8 @@
// imported anywhere. The installed-state overlay is applied by the caller
// (server/services/localLlm.js) which knows what's actually on disk.
+import { hardwareRequirementsForLocalLlm } from './systemCapabilities.js';
+
export const BACKENDS = ['ollama', 'lmstudio'];
export const isBackend = (b) => BACKENDS.includes(b);
@@ -769,7 +771,7 @@ export function getOllamaImportSpec(modelId) {
* @param {string} backend - 'ollama' | 'lmstudio'
* @param {string[]} [installedIds] - ids currently installed on that backend
* @param {{ appleSilicon?: boolean }} [options] - host capabilities used for platform-gated entries
- * @returns {Array<{ id, key, name, category, recommendedFor, featured, params, size, family, description, note, repository, gated, capabilities, format, contextLength, installed }>}
+ * @returns {Array<{ id, key, name, category, recommendedFor, featured, params, size, family, description, note, repository, gated, capabilities, format, hardwareRequirements, contextLength, installed }>}
*/
export function getCatalog(backend, installedIds = [], { appleSilicon } = {}) {
if (!isBackend(backend)) return [];
@@ -796,6 +798,7 @@ export function getCatalog(backend, installedIds = [], { appleSilicon } = {}) {
gated: entry.gated === true,
capabilities: entry.capabilities,
format: entry.format || null,
+ hardwareRequirements: hardwareRequirementsForLocalLlm(entry),
// Native context window (tokens), when it's a documented spec; null otherwise.
contextLength: Number.isFinite(entry.context) ? entry.context : null,
installed: entryIdsForBackend(entry, backend)
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index 70e4e41911..b74ba9085a 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -8,7 +8,7 @@
* cached at boot — there's no hot-reload).
*
* Schema (see seed defaults below for the full picture):
- * - video.mlx[], video.cuda[]: { id, name, repo?, steps, guidance, broken?, disclosure? }
+ * - video.mlx[], video.cuda[]: { id, name, repo?, steps, guidance, broken?, disclosure?, hardwareRequirements? }
* The two buckets split on RUNTIME FAMILY, not operating system: `mlx`
* holds the Apple-MLX runtimes, `cuda` the plain torch+CUDA ones (which
* run on Windows AND Linux). They were keyed `macos` / `windows` before
@@ -48,7 +48,7 @@
* as "supports everything". A declared list always wins.
* - video.defaultMlx / video.defaultCuda: id of the default model
* (legacy `defaultMacos` / `defaultWindows` still read)
- * - image[]: { id, name, steps, guidance, broken? }
+ * - image[]: { id, name, steps, guidance, broken?, hardwareRequirements? }
* - textEncoders[]: { id, label, repo, localPath? }
* - selectedTextEncoder: id of the active text encoder
*/
@@ -73,6 +73,12 @@ import { applyVideoDisclosures } from './videoDisclosure.js';
import { applyVideoFinishProfiles, sanitizeFinishProfiles } from './videoFinishProfiles.js';
import { applyVideoSpeedProfiles, sanitizeSpeedProfiles } from './videoSpeedProfiles.js';
import { applyVideoSupportedModes } from './videoModeProfiles.js';
+import {
+ captureSystemCapabilities,
+ hardwareRequirementsForMediaModel,
+ isHardwareCompatible,
+ withHardwareCompatibility,
+} from './systemCapabilities.js';
// fileUtils.ensureDir is async/Promise-returning; this module needs a
// synchronous version because `loadMediaModels()` is called at import-time
// from videoGen/imageGen modules, which can't await before exporting.
@@ -1428,11 +1434,19 @@ export const requiredModelCacheGroups = (model) => {
export const getVideoModels = () => {
const reg = loadMediaModels();
- const list = readVideoBucket(reg.video, activeVideoBucket()) || [];
- return applyVideoSupportedModes(list.filter((m) => !platformBroken(m.broken)));
+ const bucket = activeVideoBucket();
+ const capabilities = captureSystemCapabilities();
+ const list = readVideoBucket(reg.video, bucket) || [];
+ return applyVideoSupportedModes(list.filter((m) => !platformBroken(m.broken))).map((model) => (
+ withHardwareCompatibility(
+ model,
+ capabilities,
+ hardwareRequirementsForMediaModel(model, { kind: 'video', bucket }),
+ )
+ ));
};
-export const getDefaultVideoModelId = () => {
+export const getDefaultVideoModelId = (capabilities = captureSystemCapabilities()) => {
const reg = loadMediaModels();
// Note: defaultMlx / defaultCuda may legitimately point at a model
// flagged `deprecated: true` — the dgrauet (non-deprecated) runtime
@@ -1445,20 +1459,32 @@ export const getDefaultVideoModelId = () => {
// Validate against the bucket's available (non-broken) list — a typo or
// a model marked broken on this bucket would otherwise surface as
// "Unknown video model" the first time the UI tries to use the default.
- const available = getVideoModels();
- if (available.some((m) => m.id === configuredId)) return configuredId;
- const fallback = available[0]?.id;
+ const available = getVideoModels().map((model) => withHardwareCompatibility(
+ model,
+ capabilities,
+ model.hardwareRequirements,
+ ));
+ const compatible = available.filter((model) => isHardwareCompatible(model.hardwareCompatibility));
+ if (compatible.some((m) => m.id === configuredId)) return configuredId;
+ const fallback = compatible[0]?.id;
if (fallback) {
- console.log(`⚠️ Unknown default video model "${configuredId}" for ${bucket}; falling back to "${fallback}"`);
+ console.log(`⚠️ Default video model "${configuredId}" is unavailable or unknown for ${bucket}; falling back to "${fallback}"`);
return fallback;
}
- console.log(`⚠️ Unknown default video model "${configuredId}" for ${bucket}; no available models to fall back to`);
+ console.log(`⚠️ Default video model "${configuredId}" is unavailable or unknown for ${bucket}; no available models to fall back to`);
return configuredId;
};
export const getImageModels = () => {
const reg = loadMediaModels();
- return (reg.image || []).filter((m) => !platformBroken(m.broken));
+ const capabilities = captureSystemCapabilities();
+ return (reg.image || [])
+ .filter((m) => !platformBroken(m.broken))
+ .map((model) => withHardwareCompatibility(
+ model,
+ capabilities,
+ hardwareRequirementsForMediaModel(model, { kind: 'image' }),
+ ));
};
// Map a registry entry to the HuggingFace repo id whose weights need to be
diff --git a/server/lib/platform.js b/server/lib/platform.js
index acb547bab0..793be285d5 100644
--- a/server/lib/platform.js
+++ b/server/lib/platform.js
@@ -1,7 +1,10 @@
import { exec, execSync } from './childProcess.js';
import { promisify } from 'util';
-const execAsync = promisify(exec);
+// Keep promisification lazy so pure platform consumers can be imported from
+// tests that intentionally mock only the child-process methods they exercise.
+// The call path still uses the same shared `exec` wrapper when a port probe runs.
+const execAsync = (...args) => promisify(exec)(...args);
const platform = process.platform;
diff --git a/server/lib/systemCapabilities.js b/server/lib/systemCapabilities.js
new file mode 100644
index 0000000000..61d5a1f123
--- /dev/null
+++ b/server/lib/systemCapabilities.js
@@ -0,0 +1,410 @@
+/**
+ * Host capabilities and the shared hardware-requirement evaluator.
+ *
+ * This module deliberately reports coarse, machine-local facts only. It never
+ * includes a hostname, path, account, or network identity. Consumers use the
+ * evaluator's three-state result to hide only a known mismatch; a failed probe
+ * stays `unknown` so a transient driver problem cannot make a valid option
+ * disappear.
+ */
+
+import os from 'os';
+import { isAppleSilicon } from './platform.js';
+import { getCudaCapability, getCudaComputeCapability } from './cudaCapability.js';
+
+export const SYSTEM_CAPABILITIES_VERSION = 1;
+
+const KNOWN_CUDA_STATUSES = new Set(['available', 'absent', 'unknown']);
+
+const MEDIA_HARDWARE_REQUIREMENTS = Object.freeze({
+ // The legacy entries default to mflux, which is an Apple-MLX runner.
+ dev: Object.freeze({ platforms: ['darwin'], requiresAppleSilicon: true }),
+ schnell: Object.freeze({ platforms: ['darwin'], requiresAppleSilicon: true }),
+ // These are the explicit floors in the shipped model descriptions. Keep
+ // them here as derived metadata so older media-models.json files get the
+ // same protection without an on-disk migration.
+ 'flux2-klein-4b': Object.freeze({ minMemoryGb: 16 }),
+ 'flux2-klein-9b': Object.freeze({ minMemoryGb: 32 }),
+ 'flux2-klein-4b-int8': Object.freeze({ minMemoryGb: 32 }),
+ 'flux2-klein-9b-bf16': Object.freeze({ minMemoryGb: 64 }),
+ 'hidream-i1-full': Object.freeze({ minMemoryGb: 48 }),
+ 'hidream-i1-fast': Object.freeze({ minMemoryGb: 48 }),
+ 'qwen-image': Object.freeze({ minMemoryGb: 64 }),
+ 'qwen-image-edit': Object.freeze({ minMemoryGb: 64 }),
+ 'z-image-turbo-bf16': Object.freeze({ minMemoryGb: 16 }),
+ 'ernie-image': Object.freeze({ minMemoryGb: 32 }),
+ 'ernie-image-turbo': Object.freeze({ minMemoryGb: 32 }),
+});
+
+const LOCAL_LLM_HARDWARE_REQUIREMENTS = Object.freeze({
+ // These entries are the 15–24 GB builds in the catalog's 32–128 GB tier.
+ // The extra headroom accounts for the runtime and context cache, rather
+ // than treating the quantized file size as the whole machine requirement.
+ 'qwen3.8-27b-mlx-4bit': Object.freeze({
+ platforms: ['darwin'],
+ requiresAppleSilicon: true,
+ minMemoryGb: 32,
+ }),
+ 'qwen3.8-27b-uncensored-mlx': Object.freeze({
+ platforms: ['darwin'],
+ requiresAppleSilicon: true,
+ minMemoryGb: 32,
+ }),
+ 'qwen3.8-27b': Object.freeze({ minMemoryGb: 32 }),
+ 'gemma4-26b-a4b': Object.freeze({ minMemoryGb: 32 }),
+ 'muse-glimmer-30b': Object.freeze({ minMemoryGb: 32 }),
+ 'glm-4.7-flash': Object.freeze({ minMemoryGb: 32 }),
+ 'olmo-3.1-32b': Object.freeze({ minMemoryGb: 32 }),
+ 'gemma4-31b': Object.freeze({ minMemoryGb: 64 }),
+ 'nemotron-3-nano-30b-a3b': Object.freeze({ minMemoryGb: 32 }),
+ 'qwen3.5-122b-a10b': Object.freeze({ minMemoryGb: 96 }),
+ 'qwen3-coder-30b': Object.freeze({ minMemoryGb: 32 }),
+ 'devstral-small-2-24b': Object.freeze({ minMemoryGb: 32 }),
+ 'north-mini-code-1.0': Object.freeze({ minMemoryGb: 32 }),
+ 'ornith-35b': Object.freeze({ minMemoryGb: 32 }),
+ 'nex-n2-mini': Object.freeze({ minMemoryGb: 32 }),
+ 'qwen3.6-35b-a3b': Object.freeze({ minMemoryGb: 32 }),
+ 'qwen3.6-fable-fusion': Object.freeze({ minMemoryGb: 64 }),
+ 'qwen3-vl-30b-a3b': Object.freeze({ minMemoryGb: 32 }),
+});
+
+// Installed local runtimes expose model IDs with quant/runtime suffixes rather
+// than the catalog's stable keys. These aliases keep the automatic gate useful
+// for stored provider pins too, including the MLX-only variants.
+const LOCAL_MODEL_HARDWARE_REQUIREMENTS = Object.freeze({
+ ...LOCAL_LLM_HARDWARE_REQUIREMENTS,
+ 'qwen3.8-27b-mlx': Object.freeze({
+ platforms: ['darwin'],
+ requiresAppleSilicon: true,
+ minMemoryGb: 32,
+ }),
+ 'gemma4-26b-mlx': Object.freeze({ minMemoryGb: 32, platforms: ['darwin'], requiresAppleSilicon: true }),
+ 'gemma4-31b-mlx': Object.freeze({ minMemoryGb: 64, platforms: ['darwin'], requiresAppleSilicon: true }),
+});
+const LOCAL_MODEL_REQUIREMENT_KEYS = Object.freeze(
+ Object.keys(LOCAL_MODEL_HARDWARE_REQUIREMENTS).sort((a, b) => b.length - a.length),
+);
+
+const providerRuntimeRequirements = Object.freeze({
+ mtplx: Object.freeze({
+ platforms: ['darwin'],
+ requiresAppleSilicon: true,
+ }),
+ vllm: Object.freeze({
+ platforms: ['linux', 'win32'],
+ requiresNvidiaGpu: true,
+ minVramGb: 24,
+ }),
+ sglang: Object.freeze({
+ platforms: ['linux', 'win32'],
+ requiresNvidiaGpu: true,
+ minVramGb: 32,
+ minCudaComputeCapability: 9,
+ }),
+});
+
+const localProvider = (provider) => provider?.ollamaBacked
+ || provider?.llamaBacked
+ || provider?.mtplxBacked
+ || provider?.vllmBacked
+ || provider?.sglangBacked
+ || provider?.id === 'mtplx';
+
+const localModelHardwareRequirements = (model) => {
+ if (typeof model !== 'string' || !model.trim()) return {};
+ const normalized = model.trim().toLowerCase().replace(/[:_/]/g, '-');
+ const key = LOCAL_MODEL_REQUIREMENT_KEYS
+ .find((candidate) => normalized === candidate || normalized.startsWith(`${candidate}-`));
+ return key ? LOCAL_MODEL_HARDWARE_REQUIREMENTS[key] : {};
+};
+
+const positiveNumber = (value) => {
+ const number = Number(value);
+ return Number.isFinite(number) && number > 0 ? number : null;
+};
+
+const uniqueStrings = (value) => [...new Set(
+ (Array.isArray(value) ? value : [])
+ .filter((item) => typeof item === 'string' && item.trim())
+ .map((item) => item.trim()),
+)];
+
+/**
+ * Normalize the user-editable requirement shape. Unknown values are omitted,
+ * not treated as a failing requirement, so old/custom records remain safe to
+ * read while the compatibility state stays honest.
+ */
+export function normalizeHardwareRequirements(requirements) {
+ if (!requirements || typeof requirements !== 'object' || Array.isArray(requirements)) return {};
+ const normalized = {};
+ const platforms = uniqueStrings(requirements.platforms);
+ const architectures = uniqueStrings(requirements.architectures);
+ if (platforms.length) normalized.platforms = platforms;
+ if (architectures.length) normalized.architectures = architectures;
+ for (const key of ['requiresAppleSilicon', 'requiresNvidiaGpu']) {
+ if (typeof requirements[key] === 'boolean') normalized[key] = requirements[key];
+ }
+ for (const key of ['minMemoryGb', 'minVramGb', 'minCudaComputeCapability']) {
+ const value = positiveNumber(requirements[key]);
+ if (value !== null) normalized[key] = value;
+ }
+ return normalized;
+}
+
+/** Merge requirement layers, with later explicit values taking precedence. */
+export function mergeHardwareRequirements(...layers) {
+ return normalizeHardwareRequirements(Object.assign({}, ...layers));
+}
+
+const memoryGbFromBytes = (bytes) => {
+ const number = Number(bytes);
+ return Number.isFinite(number) && number > 0
+ ? Math.round(number / 1024 ** 3)
+ : null;
+};
+
+/**
+ * Capture the synchronous host facts needed by the selection surfaces.
+ * `isAppleSilicon` is the canonical probe and handles Rosetta-launched Node.
+ */
+export function captureSystemCapabilities({
+ platform = process.platform,
+ arch = process.arch,
+ appleSilicon,
+ totalMemoryBytes = os.totalmem(),
+ cpuCount = os.cpus().length,
+} = {}) {
+ const resolvedAppleSilicon = platform === 'darwin'
+ ? (typeof appleSilicon === 'boolean' ? appleSilicon : isAppleSilicon({ platform, arch }))
+ : false;
+ return {
+ version: SYSTEM_CAPABILITIES_VERSION,
+ platform,
+ arch,
+ appleSilicon: resolvedAppleSilicon,
+ cpuCount: Number.isInteger(cpuCount) && cpuCount > 0 ? cpuCount : null,
+ totalMemoryGb: memoryGbFromBytes(totalMemoryBytes),
+ };
+}
+
+const normalizeCudaCapabilities = (cuda) => {
+ const status = KNOWN_CUDA_STATUSES.has(cuda?.status) ? cuda.status : 'unknown';
+ const gpus = Array.isArray(cuda?.gpus)
+ ? cuda.gpus
+ .filter((gpu) => gpu && typeof gpu === 'object')
+ .map((gpu) => ({
+ name: typeof gpu.name === 'string' ? gpu.name : null,
+ vramGb: positiveNumber(gpu.vramGb),
+ computeCap: typeof gpu.computeCap === 'string' ? gpu.computeCap : null,
+ }))
+ : [];
+ return {
+ status,
+ gpus,
+ maxVramGb: positiveNumber(cuda?.maxVramGb),
+ primaryComputeCap: typeof cuda?.primaryComputeCap === 'string' ? cuda.primaryComputeCap : null,
+ error: typeof cuda?.error === 'string' ? cuda.error : null,
+ };
+};
+
+/**
+ * Full capability snapshot for the dedicated system endpoint and provider
+ * cards. The CUDA probe has its own cache and three-state result.
+ */
+export async function detectSystemCapabilities(options = {}) {
+ const {
+ cudaProbe = getCudaCapability,
+ cudaComputeProbe,
+ ...captureOptions
+ } = options;
+ const base = captureSystemCapabilities(captureOptions);
+ const cuda = await cudaProbe();
+ // Keep injected probes hermetic in tests; production's cached VRAM probe is
+ // the only path that automatically adds the cached compute-capability probe.
+ const compute = cudaComputeProbe
+ ? await cudaComputeProbe()
+ : cudaProbe === getCudaCapability && cuda?.status === 'available' && !cuda.primaryComputeCap
+ ? await getCudaComputeCapability()
+ : null;
+ const computeByName = new Map((compute?.gpus || []).map((gpu) => [gpu.name, gpu]));
+ const enrichedCuda = compute
+ ? {
+ ...cuda,
+ primaryComputeCap: cuda?.primaryComputeCap || compute.primaryComputeCap,
+ gpus: (cuda?.gpus || []).map((gpu) => ({
+ ...gpu,
+ computeCap: gpu.computeCap || computeByName.get(gpu.name)?.computeCap || null,
+ })),
+ }
+ : cuda;
+ return { ...base, cuda: normalizeCudaCapabilities(enrichedCuda) };
+}
+
+const reasonFor = (key, value) => {
+ if (key === 'platforms') return `Requires ${value.join(' or ')}`;
+ if (key === 'architectures') return `Requires ${value.join(' or ')} architecture`;
+ if (key === 'requiresAppleSilicon') return 'Requires Apple Silicon';
+ if (key === 'requiresNvidiaGpu') return 'Requires an NVIDIA GPU';
+ if (key === 'minMemoryGb') return `Requires at least ${value} GB of system memory`;
+ if (key === 'minVramGb') return `Requires an NVIDIA GPU with at least ${value} GB VRAM`;
+ if (key === 'minCudaComputeCapability') return `Requires CUDA compute capability ${value}+`;
+ return 'Hardware requirement not met';
+};
+
+const compareCudaCapability = (value) => {
+ const number = Number(value);
+ return Number.isFinite(number) ? number : null;
+};
+
+/**
+ * Evaluate a requirement against a capability snapshot.
+ *
+ * `state: 'unknown'` is intentionally compatible for filtering purposes. A
+ * menu hides only `unavailable`, while a caller that needs a hard execution
+ * gate can distinguish unknown and ask the runtime to verify again.
+ */
+export function evaluateHardwareRequirements(requirements, capabilities = captureSystemCapabilities()) {
+ const normalized = normalizeHardwareRequirements(requirements);
+ const unavailable = [];
+ const unknown = [];
+ const capability = capabilities || {};
+
+ if (normalized.platforms) {
+ if (typeof capability.platform !== 'string') unknown.push(reasonFor('platforms', normalized.platforms));
+ else if (!normalized.platforms.includes(capability.platform)) unavailable.push(reasonFor('platforms', normalized.platforms));
+ }
+ if (normalized.architectures) {
+ if (typeof capability.arch !== 'string') unknown.push(reasonFor('architectures', normalized.architectures));
+ else if (!normalized.architectures.includes(capability.arch)) unavailable.push(reasonFor('architectures', normalized.architectures));
+ }
+ if (normalized.requiresAppleSilicon) {
+ if (typeof capability.appleSilicon !== 'boolean') unknown.push(reasonFor('requiresAppleSilicon'));
+ else if (!capability.appleSilicon) unavailable.push(reasonFor('requiresAppleSilicon'));
+ }
+ if (normalized.minMemoryGb != null) {
+ const memory = positiveNumber(capability.totalMemoryGb);
+ if (memory === null) unknown.push(reasonFor('minMemoryGb', normalized.minMemoryGb));
+ else if (memory < normalized.minMemoryGb) unavailable.push(reasonFor('minMemoryGb', normalized.minMemoryGb));
+ }
+
+ const needsCuda = normalized.requiresNvidiaGpu || normalized.minVramGb != null || normalized.minCudaComputeCapability != null;
+ if (needsCuda) {
+ const cuda = capability.cuda;
+ if (!cuda || !KNOWN_CUDA_STATUSES.has(cuda.status) || cuda.status === 'unknown') {
+ unknown.push(reasonFor('requiresNvidiaGpu'));
+ } else if (cuda.status === 'absent') {
+ unavailable.push(reasonFor('requiresNvidiaGpu'));
+ } else {
+ if (normalized.minVramGb != null) {
+ const vram = positiveNumber(cuda.maxVramGb);
+ if (vram === null) unknown.push(reasonFor('minVramGb', normalized.minVramGb));
+ else if (vram < normalized.minVramGb) unavailable.push(reasonFor('minVramGb', normalized.minVramGb));
+ }
+ if (normalized.minCudaComputeCapability != null) {
+ const computeCap = compareCudaCapability(cuda.primaryComputeCap);
+ if (computeCap === null) unknown.push(reasonFor('minCudaComputeCapability', normalized.minCudaComputeCapability));
+ else if (computeCap < normalized.minCudaComputeCapability) {
+ unavailable.push(reasonFor('minCudaComputeCapability', normalized.minCudaComputeCapability));
+ }
+ }
+ }
+ }
+
+ const reasons = [...new Set([...unavailable, ...unknown])];
+ return {
+ state: unavailable.length ? 'unavailable' : unknown.length ? 'unknown' : 'available',
+ reasons,
+ requirements: normalized,
+ };
+}
+
+export const isHardwareCompatible = (compatibility) => compatibility?.state !== 'unavailable';
+
+/** Resolve the derived requirements for an image or video registry entry. */
+export function hardwareRequirementsForMediaModel(model, { kind = 'image', bucket } = {}) {
+ const runtimeRequirements = {};
+ if (kind === 'video') {
+ if (bucket === 'mlx') {
+ runtimeRequirements.platforms = ['darwin'];
+ runtimeRequirements.requiresAppleSilicon = true;
+ } else if (bucket === 'cuda') {
+ runtimeRequirements.platforms = ['linux', 'win32'];
+ runtimeRequirements.requiresNvidiaGpu = true;
+ }
+ } else if (model?.runner === 'mflux' || (!model?.runner && ['dev', 'schnell'].includes(model?.id))) {
+ runtimeRequirements.platforms = ['darwin'];
+ runtimeRequirements.requiresAppleSilicon = true;
+ }
+ // Custom image entries may carry the same coarse memory estimate as video
+ // entries. Apply it across both registries before the static shipped map and
+ // an explicit user override take their usual precedence.
+ if (positiveNumber(model?.memoryGb) !== null) runtimeRequirements.minMemoryGb = Number(model.memoryGb);
+ return mergeHardwareRequirements(runtimeRequirements, MEDIA_HARDWARE_REQUIREMENTS[model?.id], model?.hardwareRequirements);
+}
+
+/** Resolve a catalog entry's explicit platform/memory gates. */
+export function hardwareRequirementsForLocalLlm(entry) {
+ const platformRequirements = entry?.appleSiliconOnly
+ ? { platforms: ['darwin'], requiresAppleSilicon: true }
+ : {};
+ return mergeHardwareRequirements(platformRequirements, LOCAL_LLM_HARDWARE_REQUIREMENTS[entry?.key], entry?.hardwareRequirements);
+}
+
+/** Resolve inferred and user-configured provider requirements. */
+export function hardwareRequirementsForProvider(provider) {
+ const runtime = provider?.mtplxBacked || provider?.id === 'mtplx'
+ ? 'mtplx'
+ : provider?.vllmBacked
+ ? 'vllm'
+ : provider?.sglangBacked
+ ? 'sglang'
+ : null;
+ return mergeHardwareRequirements(providerRuntimeRequirements[runtime], provider?.hardwareRequirements);
+}
+
+export function hardwareRequirementsForProviderModel(provider, model) {
+ return mergeHardwareRequirements(
+ hardwareRequirementsForProvider(provider),
+ localProvider(provider) ? localModelHardwareRequirements(model) : null,
+ provider?.modelHardwareRequirements?.[model],
+ );
+}
+
+/** Add the compatibility facts consumed by model and provider selection UIs. */
+export function withHardwareCompatibility(item, capabilities, requirements) {
+ const hardwareRequirements = normalizeHardwareRequirements(requirements ?? item?.hardwareRequirements);
+ if (Object.keys(hardwareRequirements).length === 0
+ && !item?.hardwareRequirements
+ && !item?.hardwareCompatibility) return item;
+ return {
+ ...item,
+ hardwareRequirements,
+ hardwareCompatibility: evaluateHardwareRequirements(hardwareRequirements, capabilities),
+ };
+}
+
+export function withProviderHardwareCompatibility(provider, capabilities) {
+ const hardwareRequirements = hardwareRequirementsForProvider(provider);
+ const modelRequirementLayers = provider?.modelHardwareRequirements || {};
+ const modelIds = [...new Set([
+ ...(Array.isArray(provider?.models) ? provider.models : []),
+ ...Object.keys(modelRequirementLayers),
+ provider?.defaultModel,
+ provider?.lightModel,
+ provider?.mediumModel,
+ provider?.heavyModel,
+ provider?.fallbackModel,
+ ].filter((model) => typeof model === 'string' && model))];
+ const modelHardwareCompatibility = Object.fromEntries(modelIds.map((model) => {
+ const requirements = hardwareRequirementsForProviderModel(provider, model);
+ return [model, evaluateHardwareRequirements(requirements, capabilities)];
+ }));
+ if (Object.keys(hardwareRequirements).length === 0
+ && Object.keys(modelRequirementLayers).length === 0) return provider;
+ return {
+ ...provider,
+ hardwareRequirements,
+ hardwareCompatibility: evaluateHardwareRequirements(hardwareRequirements, capabilities),
+ modelHardwareCompatibility,
+ };
+}
diff --git a/server/lib/systemCapabilities.test.js b/server/lib/systemCapabilities.test.js
new file mode 100644
index 0000000000..de2c2d65ab
--- /dev/null
+++ b/server/lib/systemCapabilities.test.js
@@ -0,0 +1,181 @@
+import { describe, expect, it } from 'vitest';
+import {
+ captureSystemCapabilities,
+ detectSystemCapabilities,
+ evaluateHardwareRequirements,
+ hardwareRequirementsForLocalLlm,
+ hardwareRequirementsForMediaModel,
+ hardwareRequirementsForProvider,
+ hardwareRequirementsForProviderModel,
+ normalizeHardwareRequirements,
+ withProviderHardwareCompatibility,
+} from './systemCapabilities.js';
+
+const bytesForGb = (gb) => gb * 1024 ** 3;
+
+const APPLE_32GB = {
+ platform: 'darwin',
+ arch: 'arm64',
+ appleSilicon: true,
+ totalMemoryGb: 32,
+ cuda: { status: 'absent', gpus: [], maxVramGb: null, primaryComputeCap: null },
+};
+
+describe('systemCapabilities', () => {
+ it('captures normalized local facts without leaking machine identity', () => {
+ expect(captureSystemCapabilities({
+ platform: 'darwin',
+ arch: 'x64',
+ appleSilicon: true,
+ totalMemoryBytes: bytesForGb(64),
+ cpuCount: 12,
+ })).toEqual({
+ version: 1,
+ platform: 'darwin',
+ arch: 'x64',
+ appleSilicon: true,
+ cpuCount: 12,
+ totalMemoryGb: 64,
+ });
+
+ expect(captureSystemCapabilities({
+ platform: 'win32',
+ arch: 'x64',
+ appleSilicon: true,
+ totalMemoryBytes: bytesForGb(16),
+ cpuCount: 8,
+ }).appleSilicon).toBe(false);
+ });
+
+ it('normalizes custom requirement layers and ignores malformed values', () => {
+ expect(normalizeHardwareRequirements({
+ platforms: [' darwin ', 'darwin', 3],
+ architectures: ['arm64'],
+ requiresAppleSilicon: true,
+ minMemoryGb: 64,
+ minVramGb: 0,
+ minCudaComputeCapability: 'not-a-number',
+ hostname: 'should-not-cross-the-boundary',
+ })).toEqual({
+ platforms: ['darwin'],
+ architectures: ['arm64'],
+ requiresAppleSilicon: true,
+ minMemoryGb: 64,
+ });
+ });
+
+ it('distinguishes confirmed mismatches from an unreadable capability', () => {
+ expect(evaluateHardwareRequirements({ platforms: ['win32'] }, APPLE_32GB).state).toBe('unavailable');
+ expect(evaluateHardwareRequirements({ minMemoryGb: 64 }, APPLE_32GB).state).toBe('unavailable');
+ expect(evaluateHardwareRequirements({ minMemoryGb: 64 }, { ...APPLE_32GB, totalMemoryGb: null }).state).toBe('unknown');
+ expect(evaluateHardwareRequirements({ requiresNvidiaGpu: true }, APPLE_32GB).state).toBe('unavailable');
+ expect(evaluateHardwareRequirements({ requiresNvidiaGpu: true }, {
+ ...APPLE_32GB,
+ cuda: { status: 'unknown' },
+ }).state).toBe('unknown');
+ expect(evaluateHardwareRequirements({ minCudaComputeCapability: 9 }, {
+ ...APPLE_32GB,
+ cuda: { status: 'available', maxVramGb: 32, primaryComputeCap: '8.6' },
+ }).state).toBe('unavailable');
+ });
+
+ it('uses the injected CUDA probe for deterministic full snapshots', async () => {
+ await expect(detectSystemCapabilities({
+ platform: 'linux',
+ arch: 'x64',
+ totalMemoryBytes: bytesForGb(128),
+ cpuCount: 32,
+ cudaProbe: async () => ({
+ status: 'available',
+ gpus: [{ name: 'Example GPU', vramGb: 24, computeCap: '8.6' }],
+ maxVramGb: 24,
+ primaryComputeCap: '8.6',
+ }),
+ })).resolves.toMatchObject({
+ platform: 'linux',
+ totalMemoryGb: 128,
+ cuda: {
+ status: 'available',
+ maxVramGb: 24,
+ primaryComputeCap: '8.6',
+ },
+ });
+ });
+
+ it('merges the cached compute-capability probe into a full snapshot', async () => {
+ await expect(detectSystemCapabilities({
+ platform: 'linux',
+ cudaProbe: async () => ({
+ status: 'available',
+ gpus: [{ name: 'Example GPU', vramGb: 24 }],
+ maxVramGb: 24,
+ }),
+ cudaComputeProbe: async () => ({
+ status: 'available',
+ primaryComputeCap: '9.0',
+ gpus: [{ name: 'Example GPU', computeCap: '9.0', vramGb: 24 }],
+ }),
+ })).resolves.toMatchObject({
+ cuda: {
+ primaryComputeCap: '9.0',
+ gpus: [{ name: 'Example GPU', computeCap: '9.0' }],
+ },
+ });
+ });
+
+ it('derives requirements for shipped media, local LLM, and provider runtimes', () => {
+ expect(hardwareRequirementsForMediaModel({ id: 'flux2-klein-9b-bf16', runner: 'flux2' })).toMatchObject({ minMemoryGb: 64 });
+ expect(hardwareRequirementsForMediaModel({ id: 'qwen-image', runner: 'qwen' })).toMatchObject({ minMemoryGb: 64 });
+ expect(hardwareRequirementsForMediaModel({ id: 'hidream-i1-full', runner: 'hidream' })).toMatchObject({ minMemoryGb: 48 });
+ expect(hardwareRequirementsForMediaModel({ id: 'custom-image', memoryGb: 64 })).toMatchObject({ minMemoryGb: 64 });
+ expect(hardwareRequirementsForMediaModel({ id: 'mlx-model', runner: 'mlx_video' }, { kind: 'video', bucket: 'mlx' })).toMatchObject({
+ platforms: ['darwin'],
+ requiresAppleSilicon: true,
+ });
+ expect(hardwareRequirementsForMediaModel({ id: 'cuda-model', memoryGb: 48 }, { kind: 'video', bucket: 'cuda' })).toMatchObject({
+ platforms: ['linux', 'win32'],
+ requiresNvidiaGpu: true,
+ minMemoryGb: 48,
+ });
+ expect(hardwareRequirementsForLocalLlm({ key: 'qwen3.8-27b' })).toMatchObject({ minMemoryGb: 32 });
+ expect(hardwareRequirementsForLocalLlm({ key: 'qwen3.5-122b-a10b' })).toMatchObject({ minMemoryGb: 96 });
+ expect(hardwareRequirementsForProvider({ id: 'provider', vllmBacked: true })).toMatchObject({
+ platforms: ['linux', 'win32'],
+ requiresNvidiaGpu: true,
+ minVramGb: 24,
+ });
+ expect(hardwareRequirementsForProvider({ id: 'provider', sglangBacked: true })).toMatchObject({
+ minVramGb: 32,
+ minCudaComputeCapability: 9,
+ });
+ expect(hardwareRequirementsForProviderModel({
+ id: 'provider',
+ hardwareRequirements: { minMemoryGb: 16 },
+ modelHardwareRequirements: { 'large-model': { minMemoryGb: 64 } },
+ }, 'large-model')).toMatchObject({ minMemoryGb: 64 });
+ expect(hardwareRequirementsForProviderModel({ ollamaBacked: true }, 'qwen3.8:27b-mlx')).toMatchObject({
+ platforms: ['darwin'],
+ requiresAppleSilicon: true,
+ minMemoryGb: 32,
+ });
+ expect(hardwareRequirementsForProviderModel({ endpoint: 'https://api.example.com/v1' }, 'gemma4-31b')).toEqual({});
+ });
+
+ it('decorates provider and model compatibility in one response projection', () => {
+ const provider = withProviderHardwareCompatibility({
+ id: 'vllm',
+ vllmBacked: true,
+ models: ['small', 'large'],
+ modelHardwareRequirements: { large: { minMemoryGb: 256 } },
+ }, {
+ platform: 'linux',
+ arch: 'x64',
+ totalMemoryGb: 128,
+ cuda: { status: 'available', maxVramGb: 24, primaryComputeCap: '8.6' },
+ });
+
+ expect(provider.hardwareCompatibility.state).toBe('available');
+ expect(provider.modelHardwareCompatibility.small.state).toBe('available');
+ expect(provider.modelHardwareCompatibility.large.state).toBe('unavailable');
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index f47f9a961b..db62c814ff 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -470,6 +470,16 @@ export const gameFeedbackSchema = z.object({
}).strict();
// Provider schema
+const providerHardwareRequirementsSchema = z.object({
+ platforms: z.array(z.string().trim().min(1).max(32)).min(1).max(8).optional(),
+ architectures: z.array(z.string().trim().min(1).max(32)).min(1).max(8).optional(),
+ requiresAppleSilicon: z.boolean().optional(),
+ requiresNvidiaGpu: z.boolean().optional(),
+ minMemoryGb: z.number().positive().max(4096).optional(),
+ minVramGb: z.number().positive().max(4096).optional(),
+ minCudaComputeCapability: z.number().positive().max(20).optional(),
+}).strict();
+
export const providerSchema = z.object({
name: z.string().min(1).max(100),
type: z.enum(['cli', 'api', 'tui']),
@@ -478,6 +488,8 @@ export const providerSchema = z.object({
endpoint: z.string().url().optional(),
apiKey: z.string().optional(),
models: z.array(z.string()).optional(),
+ hardwareRequirements: providerHardwareRequirementsSchema.optional(),
+ modelHardwareRequirements: z.record(providerHardwareRequirementsSchema).optional(),
defaultModel: z.string().nullable().optional(),
timeout: z.number().int().min(AI_RUN_TIMEOUT_MIN_MS).max(AI_RUN_TIMEOUT_MAX_MS).optional(),
enabled: z.boolean().optional(),
diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.js
index 375d3315ea..fadab87aaf 100644
--- a/server/routes/imageVideoModels.js
+++ b/server/routes/imageVideoModels.js
@@ -28,6 +28,7 @@ import { emptyToUndefined, validateRequest } from '../lib/validation.js';
import { ADDABLE_IMAGE_RUNNERS, ADDABLE_VIDEO_RUNTIMES, searchHuggingfaceModels } from '../lib/huggingfaceModel.js';
import { addModelFromHuggingface } from '../services/mediaModelInstall.js';
import { getMediaModelStorage } from '../services/mediaModelStorage.js';
+import { detectSystemCapabilities, withHardwareCompatibility } from '../lib/systemCapabilities.js';
const router = Router();
@@ -60,6 +61,8 @@ router.get('/registry', asyncHandler(async (_req, res) => {
runner: m.runner || null,
steps: m.steps ?? null,
guidance: m.guidance ?? null,
+ hardwareRequirements: m.hardwareRequirements || {},
+ hardwareCompatibility: m.hardwareCompatibility || null,
deprecated: !!m.deprecated,
broken: m.broken ?? false,
builtIn: !isUserModelEntry(m),
@@ -69,7 +72,12 @@ router.get('/registry', asyncHandler(async (_req, res) => {
// One encoder can be offered by more than one model. Keep one management row
// per encoder while retaining the model ids it is compatible with, rather
// than rendering duplicate rows (or arbitrarily hiding one relationship).
- const videoModels = getVideoModels();
+ const capabilities = await detectSystemCapabilities();
+ const videoModels = getVideoModels().map((model) => withHardwareCompatibility(
+ model,
+ capabilities,
+ model.hardwareRequirements,
+ ));
const textEncoderMap = new Map();
for (const model of videoModels) {
for (const option of videoTextEncoderOptions(model)) {
@@ -91,7 +99,11 @@ router.get('/registry', asyncHandler(async (_req, res) => {
// are single-list.
res.json({
video: flatten(videoModels, 'video'),
- image: flatten(getImageModels(), 'image'),
+ image: flatten(getImageModels().map((model) => withHardwareCompatibility(
+ model,
+ capabilities,
+ model.hardwareRequirements,
+ )), 'image'),
textEncoders: [...textEncoderMap.values()],
});
}));
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 6744715554..a740402993 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -48,6 +48,11 @@ import { SPEC_TYPE_SUGGESTIONS } from '../lib/specDecodePresets.js'
import { resetProviderReadinessCache } from '../services/providerReadiness.js'
import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
import { isAppleSilicon } from '../lib/platform.js'
+import {
+ captureSystemCapabilities,
+ isHardwareCompatible,
+ withHardwareCompatibility,
+} from '../lib/systemCapabilities.js'
import { searchHuggingFaceModels, enrichCatalogWithVariants, applyMeasuredFit } from '../services/huggingFaceCatalog.js'
import { getMeasuredFits } from '../services/localModelAssessmentStore.js'
import {
@@ -125,16 +130,27 @@ router.get('/catalog', asyncHandler(async (req, res) => {
const installedForVariants = installedModels.map((m) => (
backend === 'lmstudio' && m.quantization ? `${m.id}@${m.quantization}` : m.id
))
+ // Total system memory drives both the hardware gate and the RAM-aware
+ // recommended quant. Unified memory on Apple Silicon also backs the GPU, so a
+ // big box can default to higher fidelity.
+ const systemMemoryBytes = os.totalmem()
+ const capabilities = captureSystemCapabilities({
+ appleSilicon: isAppleSilicon(),
+ totalMemoryBytes: systemMemoryBytes,
+ })
// Native MLX entries are meaningful only on Apple Silicon. Keep this gate at
// the route boundary so the pure catalog remains useful to tests and other
// callers while the user-facing picker never offers an un-runnable format.
- const catalogOptions = { appleSilicon: isAppleSilicon() }
- const models = q
+ const catalogOptions = { appleSilicon: capabilities.appleSilicon }
+ const catalog = q
? searchCatalog(backend, q, installedRaw, catalogOptions)
: getCatalog(backend, installedRaw, catalogOptions)
- // Total system memory drives the RAM-aware recommended quant (unified memory on
- // Apple Silicon also backs the GPU, so a big box can default to higher fidelity).
- const systemMemoryBytes = os.totalmem()
+ // Keep the full compatibility fact on each visible row for callers that want
+ // to explain a recommendation, but hide only definitive mismatches. Unknown
+ // memory/probe states remain visible and fail open.
+ const models = catalog
+ .map((model) => withHardwareCompatibility(model, capabilities, model.hardwareRequirements))
+ .filter((model) => isHardwareCompatible(model.hardwareCompatibility))
// Quant-variant enrichment probes Hugging Face per HF-backed entry, so it's
// opt-in (`?variants=1`): the recommended-models picker requests it, but callers
// that only need catalog metadata (e.g. the playground decorating installed
diff --git a/server/routes/providers.js b/server/routes/providers.js
index d54951a04b..ea5a3ff345 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -27,6 +27,11 @@ import { getProviderPrerequisiteMap } from '../services/providerPrerequisites.js
import { runLocalRuntimeSetup, SETUP_ACTIONS } from '../services/localRuntimeSetup.js';
import { localEndpointPort, localRuntimeForProvider } from '../lib/localProviderRuntime.js';
import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';
+import {
+ captureSystemCapabilities,
+ detectSystemCapabilities,
+ withProviderHardwareCompatibility,
+} from '../lib/systemCapabilities.js';
/**
* The CoS Agent Runner's exec allowlist, published read-only so the AI
@@ -121,7 +126,9 @@ const withTuiLaunchCommand = (provider) => {
* the toolkit keeps its copy so it stays correct standalone. Both decorate on
* the way out only — the field is never persisted.
*/
-const presentProvider = (provider) => sanitizeProvider(withTuiLaunchCommand(withRefreshCapability(provider)));
+const presentProvider = (provider, capabilities = captureSystemCapabilities()) => sanitizeProvider(
+ withProviderHardwareCompatibility(withTuiLaunchCommand(withRefreshCapability(provider)), capabilities),
+);
/**
* Create PortOS-specific provider routes
@@ -144,19 +151,19 @@ export function createPortOSProviderRoutes(aiToolkit) {
* Computed on the RAW providers, before sanitization: the API-key check reads
* `apiKey`, which `sanitizeProvider` replaces with a boolean.
*
- * Synchronous by design — this endpoint is fetched by half the app, so it
- * reads the runtime probe's cache and lets a cold one refresh in the
- * background rather than putting a `--version` sweep of every CLI on that
- * critical path. An unprobed runtime simply publishes no finding, and the
- * page's own `/runtimes` fetch fills that gap on the card.
+ * The capability probe is cached and performed once per response, so every
+ * provider shares one host snapshot instead of triggering its own hardware
+ * checks. An unreadable probe remains `unknown`, which keeps the provider
+ * visible until the runtime can make a confirmed decision.
*/
router.get('/', asyncHandler(async (req, res) => {
const data = await providerService.getAllProviders();
const prerequisites = getProviderPrerequisiteMap(data.providers);
+ const capabilities = await detectSystemCapabilities();
res.json({
activeProvider: data.activeProvider,
providers: data.providers.map((provider) => ({
- ...presentProvider(provider),
+ ...presentProvider(provider, capabilities),
prerequisitesMet: prerequisites[provider.id]?.met ?? true,
missingPrerequisites: prerequisites[provider.id]?.missing ?? [],
})),
@@ -166,7 +173,7 @@ export function createPortOSProviderRoutes(aiToolkit) {
router.get('/active', asyncHandler(async (req, res) => {
const provider = await providerService.getActiveProvider();
- res.json(presentProvider(provider));
+ res.json(presentProvider(provider, await detectSystemCapabilities()));
}));
// PUT /active must be defined before PUT /:id to avoid the wildcard
@@ -181,12 +188,13 @@ export function createPortOSProviderRoutes(aiToolkit) {
if (!provider) {
throw new ServerError('Provider not found', { status: 404 });
}
- res.json(presentProvider(provider));
+ res.json(presentProvider(provider, await detectSystemCapabilities()));
}));
router.get('/samples', asyncHandler(async (req, res) => {
const providers = await providerService.getSampleProviders();
- res.json({ providers: providers.map(presentProvider) });
+ const capabilities = await detectSystemCapabilities();
+ res.json({ providers: providers.map((provider) => presentProvider(provider, capabilities)) });
}));
// A CLI/TUI provider is only usable if its runtime binary is on PortOS's
@@ -616,7 +624,7 @@ export function createPortOSProviderRoutes(aiToolkit) {
router.get('/:id', asyncHandler(async (req, res) => {
const provider = await providerService.getProviderById(req.params.id);
if (!provider) throw new ServerError('Provider not found', { status: 404 });
- res.json(presentProvider(provider));
+ res.json(presentProvider(provider, await detectSystemCapabilities()));
}));
// PUT /:id — intercept to (a) validate the body via a partial provider
@@ -651,7 +659,7 @@ export function createPortOSProviderRoutes(aiToolkit) {
}
const provider = await providerService.updateProvider(req.params.id, updates);
- res.json(presentProvider(provider));
+ res.json(presentProvider(provider, await detectSystemCapabilities()));
}));
// POST / — intercept to (a) validate the body against providerSchema so
@@ -665,7 +673,7 @@ export function createPortOSProviderRoutes(aiToolkit) {
throw new ServerError('Invalid provider data', { status: 400, code: 'VALIDATION_ERROR', context: { details: validation.errors } });
}
const provider = await providerService.createProvider(validation.data);
- res.status(201).json(presentProvider(provider));
+ res.status(201).json(presentProvider(provider, await detectSystemCapabilities()));
}));
// Mount base toolkit routes last (GET/PUT /:id and POST / are now shadowed
diff --git a/server/routes/systemCapabilities.js b/server/routes/systemCapabilities.js
new file mode 100644
index 0000000000..9993a273e3
--- /dev/null
+++ b/server/routes/systemCapabilities.js
@@ -0,0 +1,14 @@
+import { Router } from 'express';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { detectSystemCapabilities } from '../lib/systemCapabilities.js';
+
+const router = Router();
+
+// This is deliberately separate from /health/details. Health details are
+// scraped and persisted by federation peers; hardware capabilities are local
+// selection context and must not silently join a sync payload.
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await detectSystemCapabilities());
+}));
+
+export default router;
diff --git a/server/routes/systemCapabilities.test.js b/server/routes/systemCapabilities.test.js
new file mode 100644
index 0000000000..34f98e8ac8
--- /dev/null
+++ b/server/routes/systemCapabilities.test.js
@@ -0,0 +1,39 @@
+import { describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const mock = vi.hoisted(() => ({ detectSystemCapabilities: vi.fn() }));
+vi.mock('../lib/systemCapabilities.js', () => mock);
+
+const { default: routes } = await import('./systemCapabilities.js');
+
+const app = express();
+app.use('/api/system/capabilities', routes);
+app.use(errorMiddleware);
+
+describe('system capability routes', () => {
+ it('returns the local capability snapshot without federation fields', async () => {
+ mock.detectSystemCapabilities.mockResolvedValueOnce({
+ version: 1,
+ platform: 'darwin',
+ arch: 'arm64',
+ appleSilicon: true,
+ cpuCount: 12,
+ totalMemoryGb: 64,
+ cuda: { status: 'absent', gpus: [], maxVramGb: null },
+ });
+
+ const response = await request(app).get('/api/system/capabilities');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({
+ platform: 'darwin',
+ appleSilicon: true,
+ totalMemoryGb: 64,
+ cuda: { status: 'absent' },
+ });
+ expect(response.body).not.toHaveProperty('hostname');
+ expect(response.body).not.toHaveProperty('network');
+ });
+});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index dd1f119b62..9dc49a2255 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -70,9 +70,22 @@ import {
getVideoRuntimeStatus,
streamVideoRuntimeInstall,
} from '../services/videoGen/runtimeInstaller.js';
+import { detectSystemCapabilities, withHardwareCompatibility } from '../lib/systemCapabilities.js';
const router = Router();
+const hardwareAwareVideoModels = async () => {
+ const capabilities = await detectSystemCapabilities();
+ return {
+ capabilities,
+ models: listVideoModels().map((model) => withHardwareCompatibility(
+ model,
+ capabilities,
+ model.hardwareRequirements,
+ )),
+ };
+};
+
// M4A files are stored in an MP4 container. Browsers and OS file pickers
// label them inconsistently: Safari uses `video/mp4`, Chrome/Firefox use
// `audio/mp4`, and some platforms emit `audio/x-m4a` or `audio/aac`.
@@ -357,6 +370,7 @@ router.get('/status', asyncHandler(async (_req, res) => {
const s = await getSettings();
const py = s.imageGen?.local?.pythonPath || null;
const { connected, reason, missing, pythonVersion } = await resolveLocalPythonHealth(py);
+ const { capabilities, models } = await hardwareAwareVideoModels();
res.json({
connected,
pythonPath: py,
@@ -366,8 +380,8 @@ router.get('/status', asyncHandler(async (_req, res) => {
// Each entry carries its optional `disclosure` block (provenance, weights/
// runtime licenses, pinned-snapshot download size) straight off the
// registry — absent for custom models, which the UI renders as Unknown.
- models: listVideoModels(),
- defaultModel: defaultVideoModelId(),
+ models,
+ defaultModel: defaultVideoModelId(capabilities),
// Server-owned execution + policy scope per render backend (#3674). The
// client renders these strings verbatim so the wording can't drift between
// the two surfaces.
@@ -474,9 +488,10 @@ async function resolveLocalPythonHealth(py) {
}
}
-router.get('/models', (_req, res) => {
- res.json(listVideoModels());
-});
+router.get('/models', asyncHandler(async (_req, res) => {
+ const { models } = await hardwareAwareVideoModels();
+ res.json(models);
+}));
// Resolve the repo set an integrity scan should cover. A specific `modelId`
// scopes to that model's repo; no modelId scans every model repo plus the
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 5b0cc8d809..9b5a6db27f 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -40,6 +40,7 @@ import { parseByteProgress, formatDownloadMessage } from '../videoGen/generateVi
const IS_WIN = process.platform === 'win32';
import { getImageModels, isFlux2, isErnie, isHiDream, isQwen } from '../../lib/mediaModels.js';
+import { isHardwareCompatible } from '../../lib/systemCapabilities.js';
import { usesDiffusersRunner, flux2Bf16BaseRepo } from '../../lib/runners.js';
import { weaveLoraTriggers } from '../../lib/loraTriggers.js';
import { readTriggerWordsByFilename } from '../loras.js';
@@ -503,6 +504,12 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// 'windows' on a macOS box).
const model = getImageModels().find((m) => m.id === modelId);
if (!model) throw new ServerError(`Unknown or unsupported model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
+ if (!isHardwareCompatible(model.hardwareCompatibility)) {
+ throw new ServerError(
+ `Image model "${modelId}" is unavailable on this machine: ${model.hardwareCompatibility.reasons.join(' · ')}`,
+ { status: 400, code: 'MODEL_HARDWARE_UNAVAILABLE' },
+ );
+ }
// 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.
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index 5659baa179..78ebdc295c 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -37,6 +37,7 @@ import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';
import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';
import { getUniverseRenderPin } from '../universeBuilder/crud.js';
import { getImageModels, isFlux2, isEditOnly } from '../../lib/mediaModels.js';
+import { isHardwareCompatible } from '../../lib/systemCapabilities.js';
import { usesDiffusersRunner } from '../../lib/runners.js';
// The job tags that name the record owning a render, each mapped to the record
@@ -303,8 +304,8 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
* called from the route right before it enqueues a local job.
*
* Resolves the effective model via the same fallback chain the local worker
- * uses (`params.modelId` → `'dev'` → the first registered model) and
- * validates it can actually run: an edit-only model (e.g. Qwen-Image-Edit)
+ * uses (`params.modelId` → compatible `'dev'` → the first compatible model)
+ * and validates it can actually run: an edit-only model (e.g. Qwen-Image-Edit)
* requires a source image, and any model that isn't FLUX.2 or diffusers-run
* needs a configured pythonPath. Throws the identical `ServerError`s (same
* status/code/message, same order) the route used to throw inline — these
@@ -329,9 +330,21 @@ export function resolveLocalImageModel(settings, params) {
{ status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' },
);
}
- const selectedModel = allModels.find((m) => m.id === params.modelId)
- ?? allModels.find((m) => m.id === 'dev')
- ?? allModels[0];
+ const requestedModel = allModels.find((m) => m.id === params.modelId);
+ // An explicit pin must fail clearly when the host cannot run it. For an
+ // omitted pin, prefer the historical `dev` default only when it is actually
+ // compatible, then choose the first known-compatible model. This keeps a
+ // Windows/Linux install from silently queueing the Apple-only default.
+ const selectedModel = requestedModel || [
+ allModels.find((m) => m.id === 'dev'),
+ ...allModels,
+ ].filter(Boolean).find((model) => isHardwareCompatible(model.hardwareCompatibility)) || allModels[0];
+ if (selectedModel && !isHardwareCompatible(selectedModel.hardwareCompatibility)) {
+ throw new ServerError(
+ `Image model "${selectedModel.id}" is unavailable on this machine: ${selectedModel.hardwareCompatibility.reasons.join(' · ')}`,
+ { status: 400, code: 'MODEL_HARDWARE_UNAVAILABLE' },
+ );
+ }
// Edit-only models (Qwen-Image-Edit) load a pipeline that REQUIRES a
// source image. Reject a text-only submission up-front rather than
// enqueueing a job that crashes deep inside diffusers. `params.initImagePath`
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index b098091450..060f667290 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -34,9 +34,10 @@ import { pipeline } from 'stream/promises'
import { Readable } from 'stream'
import { PATHS, atomicWrite, ensureDir, pathExists, sleep } from '../lib/fileUtils.js'
import { compareSemver } from '../lib/versionUtils.js'
-import { isBackend, mapModelToBackend, getOllamaImportSpec } from '../lib/localLlmCatalog.js'
+import { getCatalog, isBackend, mapModelToBackend, getOllamaImportSpec } from '../lib/localLlmCatalog.js'
import { sanitizeOllamaName } from '../lib/localLlmDisk.js'
import { recommendEditorialModel, isVisionModel, isVisionCapableCliProvider, isToolUseModel } from '../lib/localModelHeuristics.js'
+import { captureSystemCapabilities, withHardwareCompatibility } from '../lib/systemCapabilities.js'
// Disk-only read of the measured assessments (`localModelAssessmentStore.js` has no
// path to a provider, so this cannot turn a status poll into an LLM call), and
// no import cycle: the store deliberately does not import this module.
@@ -606,31 +607,44 @@ function lmStudioBadgeCapabilities(m) {
return caps
}
+/**
+ * Add catalog-derived hardware metadata to a live model when PortOS knows its
+ * identity. Unknown/custom models stay fail-open with an empty requirement set.
+ */
+function annotateInstalledModel(backend, rawModel, normalizedModel, capabilities) {
+ const catalogEntry = getCatalog(backend, [rawModel.id]).find((entry) => entry.installed)
+ return withHardwareCompatibility(
+ normalizedModel,
+ capabilities,
+ catalogEntry?.hardwareRequirements || rawModel.hardwareRequirements,
+ )
+}
+
/** Normalize each backend's installed-model shape into one card shape. */
-function normalizeModels(backend, models) {
+function normalizeModels(backend, models, capabilities = captureSystemCapabilities()) {
if (backend === 'ollama') {
- return models.map((m) => ({
- id: m.id, name: m.name, size: m.size ?? null,
- params: m.params || null, quantization: m.quantization || null, family: m.family || null,
- contextLength: m.contextLength ?? null,
- // Ollama's /api/tags doesn't tag vision capability, but /api/show does —
- // when the model has been enriched with a `capabilities` array (status
- // path, or the listVisionModels enrichment below) prefer it; otherwise
- // fall back to the id heuristic. Passing the object lets a vision-capable
- // MoE like `qwen3.6:35b` (no `vl`/`vision` token in its id) resolve true.
- vision: isVisionModel(Array.isArray(m.capabilities) ? { id: m.id, capabilities: m.capabilities } : m.id),
- capabilities: ollamaBadgeCapabilities(m.capabilities)
- }))
+ return models.map((m) => annotateInstalledModel(backend, m, {
+ id: m.id, name: m.name, size: m.size ?? null,
+ params: m.params || null, quantization: m.quantization || null, family: m.family || null,
+ contextLength: m.contextLength ?? null,
+ // Ollama's /api/tags doesn't tag vision capability, but /api/show does —
+ // when the model has been enriched with a `capabilities` array (status
+ // path, or the listVisionModels enrichment below) prefer it; otherwise
+ // fall back to the id heuristic. Passing the object lets a vision-capable
+ // MoE like `qwen3.6:35b` (no `vl`/`vision` token in its id) resolve true.
+ vision: isVisionModel(Array.isArray(m.capabilities) ? { id: m.id, capabilities: m.capabilities } : m.id),
+ capabilities: ollamaBadgeCapabilities(m.capabilities)
+ }, capabilities))
}
- return models.map((m) => ({
- id: m.id, name: m.id, size: null,
- params: null, quantization: m.quantization || null, family: m.arch || null,
- contextLength: m.maxContextLength ?? null,
- // LM Studio's native model list tags vision models `type: 'vlm'` — prefer
- // that over the id regex.
- vision: isVisionModel(m),
- capabilities: lmStudioBadgeCapabilities(m)
- }))
+ return models.map((m) => annotateInstalledModel(backend, m, {
+ id: m.id, name: m.id, size: null,
+ params: null, quantization: m.quantization || null, family: m.arch || null,
+ contextLength: m.maxContextLength ?? null,
+ // LM Studio's native model list tags vision models `type: 'vlm'` — prefer
+ // that over the id regex.
+ vision: isVisionModel(m),
+ capabilities: lmStudioBadgeCapabilities(m)
+ }, capabilities))
}
/**
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index bc1300f811..8701fc8436 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -627,6 +627,7 @@ describe('localLlm', () => {
mocks.ollama.getInstalledModels.mockResolvedValueOnce([
{ id: 'qwen3.6:35b', name: 'qwen3.6:35b', capabilities: ['completion', 'tools', 'vision', 'thinking'] },
{ id: 'nomic-embed-text', name: 'nomic-embed-text', capabilities: ['embedding'] },
+ { id: 'gemma4:31b', name: 'gemma4:31b' },
{ id: 'legacy-model', name: 'legacy-model' },
]);
const models = await svc.listModels('ollama');
@@ -639,6 +640,10 @@ describe('localLlm', () => {
// untrue claim: it renders an empty badge row and makes every capability
// test look inapplicable. Still no guessing (unlike the vision id heuristic).
expect(models.find((m) => m.id === 'legacy-model').capabilities).toBeNull();
+ expect(models.find((m) => m.id === 'gemma4:31b')).toMatchObject({
+ hardwareRequirements: { minMemoryGb: 64 },
+ hardwareCompatibility: { state: expect.any(String) },
+ });
});
it('derives LM Studio badges from the native `type` field plus the shared tool-use id heuristic', async () => {
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index b005fb5797..c4789d1874 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -24,6 +24,12 @@ import {
import { videoGenEvents } from './events.js';
import { broadcastSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';
+import {
+ captureSystemCapabilities,
+ detectSystemCapabilities,
+ isHardwareCompatible,
+ withHardwareCompatibility,
+} from '../../lib/systemCapabilities.js';
import { findFfmpeg } from '../../lib/ffmpeg.js';
import { inspectModelCache, findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
@@ -119,9 +125,9 @@ export const resolveVideoModel = (modelId) =>
export const listVideoModels = () => getVideoModels().map(decorateVideoModel);
-export const defaultVideoModelId = () => getDefaultVideoModelId();
+export const defaultVideoModelId = (capabilities) => getDefaultVideoModelId(capabilities);
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, speedProfileId = null, hidden = false, jobId: providedJobId = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId, width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, speedProfileId = null, hidden = false, jobId: providedJobId = null }) {
uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is now enforced by the mediaJobQueue worker upstream — only
@@ -129,8 +135,34 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// callers (legacy / tests) bypass the queue and would clobber the shared active process
// on concurrent calls; that's an explicit "don't do that" contract.
- const model = resolveVideoModel(modelId);
+ const needsCuda = (requirements) => requirements?.requiresNvidiaGpu
+ || requirements?.minVramGb != null
+ || requirements?.minCudaComputeCapability != null;
+ let capabilities = captureSystemCapabilities();
+ // `undefined`/empty means the caller omitted the field and may use the
+ // configured default. Explicit null is a routed-job sentinel and must remain
+ // an unknown model so an older dispatcher cannot render a remote job locally.
+ const modelWasOmitted = modelId === undefined || modelId === '';
+ let selectedModelId = modelWasOmitted ? defaultVideoModelId(capabilities) : modelId;
+ let resolvedModel = resolveVideoModel(selectedModelId);
+ if (needsCuda(resolvedModel?.hardwareRequirements)) {
+ capabilities = await detectSystemCapabilities();
+ if (modelWasOmitted) selectedModelId = defaultVideoModelId(capabilities);
+ resolvedModel = resolveVideoModel(selectedModelId);
+ }
+ modelId = selectedModelId;
+ const model = resolvedModel && withHardwareCompatibility(
+ resolvedModel,
+ capabilities,
+ resolvedModel.hardwareRequirements,
+ );
if (!model) throw new ServerError(`Unknown video model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
+ if (!isHardwareCompatible(model.hardwareCompatibility)) {
+ throw new ServerError(
+ `Video model "${modelId}" is unavailable on this machine: ${model.hardwareCompatibility.reasons.join(' · ')}`,
+ { status: 400, code: 'MODEL_HARDWARE_UNAVAILABLE' },
+ );
+ }
// Validate the mode contract before cache lookups, image resize, or staging
// work. Internal producers and persisted/retried jobs bypass route
// preparation, so silently dropping one of these inputs here would render a
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index 0c9bdbfb70..a5a97362b0 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -55,6 +55,12 @@ import {
loadHistory,
DEFAULT_NUM_FRAMES,
} from './local.js';
+import {
+ captureSystemCapabilities,
+ detectSystemCapabilities,
+ isHardwareCompatible,
+ withHardwareCompatibility,
+} from '../../lib/systemCapabilities.js';
// Straight from the leaf, not through local.js: the suites that exercise this
// module mock local.js wholesale, and a mocked rule table would assert nothing.
import { videoModeContractError, videoChainUnsupportedError, videoReferenceModeError } from './modeContract.js';
@@ -64,11 +70,29 @@ import { resolveByovRuntimeLoraCapable, videoLoraUnsupportedError } from './runt
// multipart preparation path. Keep the model/mode gates here so a model edit
// cannot delete the original history row before the replacement is renderable.
export async function validateVideoRetryParams(params = {}) {
- const modelId = params.modelId || defaultVideoModelId();
- const model = listVideoModels().find((entry) => entry.id === modelId);
+ const needsCuda = (requirements) => requirements?.requiresNvidiaGpu
+ || requirements?.minVramGb != null
+ || requirements?.minCudaComputeCapability != null;
+ let capabilities = captureSystemCapabilities();
+ const modelWasOmitted = params.modelId === undefined || params.modelId === '';
+ let modelId = modelWasOmitted ? defaultVideoModelId(capabilities) : params.modelId;
+ const knownModels = listVideoModels();
+ let model = knownModels.find((entry) => entry.id === modelId);
+ if (needsCuda(model?.hardwareRequirements)) {
+ capabilities = await detectSystemCapabilities();
+ if (modelWasOmitted) modelId = defaultVideoModelId(capabilities);
+ model = knownModels.find((entry) => entry.id === modelId);
+ }
+ model = model && withHardwareCompatibility(model, capabilities, model.hardwareRequirements);
if (!model) {
throw new ServerError(`Unknown modelId: ${modelId}`, { status: 400, code: 'VIDEO_GEN_UNKNOWN_MODEL' });
}
+ if (!isHardwareCompatible(model.hardwareCompatibility)) {
+ throw new ServerError(
+ `Video model "${modelId}" is unavailable on this machine: ${model.hardwareCompatibility.reasons.join(' · ')}`,
+ { status: 400, code: 'MODEL_HARDWARE_UNAVAILABLE' },
+ );
+ }
if (!isStockTextEncoder(params.textEncoderId)
&& !supportsVideoTextEncoder(model, params.textEncoderId)) {
throw videoTextEncoderUnsupportedError(model, params.textEncoderId);
@@ -252,18 +276,46 @@ export async function prepareVideoGenParams({ body, uploads, localOnlyParamKeys
// and listVideoModels() is the kind of thing test mocks easily get out
// of sync if called twice.
const knownModels = listVideoModels();
- const effectiveModelId = body.modelId || defaultVideoModelId();
- const effectiveModel = knownModels.find((m) => m.id === effectiveModelId);
- // Validate modelId synchronously (when supplied). Without this the queue
+ const needsCuda = (requirements) => requirements?.requiresNvidiaGpu
+ || requirements?.minVramGb != null
+ || requirements?.minCudaComputeCapability != null;
+ let capabilities = captureSystemCapabilities();
+ // `undefined`/empty means the request omitted a model and may use the
+ // configured default. Explicit null is the routed-job sentinel and must
+ // remain unknown so a legacy local dispatcher cannot render a remote job
+ // locally.
+ const modelWasOmitted = body.modelId === undefined || body.modelId === '';
+ let effectiveModelId = modelWasOmitted ? defaultVideoModelId(capabilities) : body.modelId;
+ let effectiveModel = knownModels.find((m) => m.id === effectiveModelId);
+ if (needsCuda(effectiveModel?.hardwareRequirements)) {
+ capabilities = await detectSystemCapabilities();
+ if (modelWasOmitted) {
+ effectiveModelId = defaultVideoModelId(capabilities);
+ effectiveModel = knownModels.find((m) => m.id === effectiveModelId);
+ }
+ }
+ effectiveModel = effectiveModel && withHardwareCompatibility(
+ effectiveModel,
+ capabilities,
+ effectiveModel.hardwareRequirements,
+ );
+ // Validate modelId before staging (when supplied). Without this the queue
// would happily accept a typo'd modelId and fail asynchronously inside
// the worker — leaving a persisted, doomed queue entry.
- if (body.modelId && !effectiveModel) {
+ if (body.modelId !== undefined && !effectiveModel) {
await cleanupMultipartTemp(uploads);
throw new ServerError(
`Unknown modelId: ${body.modelId}`,
{ status: 400, code: 'VIDEO_GEN_UNKNOWN_MODEL' },
);
}
+ if (effectiveModel && !isHardwareCompatible(effectiveModel.hardwareCompatibility)) {
+ await cleanupMultipartTemp(uploads);
+ throw new ServerError(
+ `Video model "${effectiveModelId}" is unavailable on this machine: ${effectiveModel.hardwareCompatibility.reasons.join(' · ')}`,
+ { status: 400, code: 'MODEL_HARDWARE_UNAVAILABLE' },
+ );
+ }
// Substituted prompt conditioner (#4081). A pure registry lookup with no
// dependency on anything staged, so it belongs with the other pre-staging
// model gates: the request that named the bad conditioner is the only place
diff --git a/server/services/videoGen/prepareParams.test.js b/server/services/videoGen/prepareParams.test.js
index e4147de8e2..d5ca28832b 100644
--- a/server/services/videoGen/prepareParams.test.js
+++ b/server/services/videoGen/prepareParams.test.js
@@ -53,7 +53,12 @@ import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';
import { getTrack } from '../tracks/index.js';
import { getSettings } from '../settings.js';
import { listVideoModels, defaultVideoModelId, loadHistory } from './local.js';
-import { prepareVideoGenParams, withStagedRollback, cleanupMultipartTemp } from './prepareParams.js';
+import {
+ prepareVideoGenParams,
+ validateVideoRetryParams,
+ withStagedRollback,
+ cleanupMultipartTemp,
+} from './prepareParams.js';
// Field names the route owns Zod schemas for; the service only needs the keys
// to decide grok eligibility. Mirrors LOCAL_ONLY_VIDEO_PARAMS in the route.
@@ -401,6 +406,15 @@ describe('prepareVideoGenParams', () => {
});
});
+describe('validateVideoRetryParams', () => {
+ it('keeps an explicit null model sentinel unknown instead of selecting the default', async () => {
+ await expect(validateVideoRetryParams({ modelId: null })).rejects.toMatchObject({
+ status: 400,
+ code: 'VIDEO_GEN_UNKNOWN_MODEL',
+ });
+ });
+});
+
describe('prepareVideoGenParams — MiniMax H3 contract', () => {
// H3 is license-gated, and the only authorization is the acknowledgement
// recorded in settings — so every test below that is about H3's *mode*