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([issue-4348]): report media-lane and peer-provider capacity on System Health

[._.]/ Adam Eivya5fe1ab54413
diff --git a/client/src/components/instances/PeerMediaProviderPanel.jsx b/client/src/components/instances/PeerMediaProviderPanel.jsx
index a38735fd9d..d427c66e05 100644
--- a/client/src/components/instances/PeerMediaProviderPanel.jsx
+++ b/client/src/components/instances/PeerMediaProviderPanel.jsx
@@ -1,62 +1,21 @@
import { useMemo, useState } from 'react';
-import { Check, ChevronDown, ChevronRight, Film, Gauge, Image, Music2 } from 'lucide-react';
+import { Check, ChevronDown, ChevronRight, Gauge } from 'lucide-react';
import { probePeer, updatePeer } from '../../services/api';
+import {
+ FEDERATED_MEDIA_KINDS,
+ federatedMediaModelKey as keyOf,
+ peerMediaProviderConfig,
+ resolvePeerMediaReadiness,
+} from '../../lib/federatedMediaReadiness.js';
import Pill from '../ui/Pill';
-// Wire v1 shipped audio-only, then grew image and video (#4348). The panel is
-// driven off this table rather than one hardcoded lane so a peer that shares a
-// GPU for renders is configurable at all — before this, image/video models were
-// accepted by the server but had no surface to allowlist them from, which left
-// federated renders unreachable from the UI.
-const KINDS = Object.freeze([
- { kind: 'audio', label: 'audio', field: 'audioModels', Icon: Music2 },
- { kind: 'image', label: 'image', field: 'imageModels', Icon: Image },
- { kind: 'video', label: 'video', field: 'videoModels', Icon: Film },
-]);
-
-const STATE_META = {
- ready: { label: 'ready', tone: 'success' },
- busy: { label: 'busy', tone: 'warning' },
- stale: { label: 'stale', tone: 'warning' },
- unauthorized: { label: 'auth required', tone: 'warning' },
- unsupported: { label: 'older peer', tone: 'note' },
- disabled: { label: 'provider off', tone: 'note' },
- unavailable: { label: 'unavailable', tone: 'warning' },
- unreachable: { label: 'unreachable', tone: 'warning' },
- invalid: { label: 'invalid status', tone: 'warning' },
-};
-
-const STATE_HELP = {
- busy: 'The peer is reachable, but its shared media lane is currently at capacity.',
- stale: 'The last capacity snapshot expired. New remote work is blocked until a fresh probe succeeds.',
- unauthorized: 'Store this peer’s instance-password credential above and make sure this instance is registered there.',
- unsupported: 'This peer does not expose the federated-media wire-v1 status endpoint yet.',
- disabled: 'Enable federated media sharing on the peer under Settings → Sharing.',
- unavailable: 'The peer has no currently ready allowlisted media runtime/model.',
- unreachable: 'The media status request failed. New remote work remains blocked.',
- invalid: 'The peer returned a response that did not match the versioned media-provider contract.',
-};
-
-const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);
-// NUL separator, matching the server's own model key: a printable separator
-// would let an engine name containing it collide with a different pair.
-const keyOf = ({ engine, modelId }) => `${engine}\u0000${modelId}`;
-const listOf = (raw, field) => (Array.isArray(raw?.[field]) ? raw[field] : []);
-
-function configOf(peer) {
- const raw = isRecord(peer?.mediaProvider) ? peer.mediaProvider : {};
- const models = {};
- for (const { kind, field } of KINDS) models[kind] = listOf(raw, field);
- return { raw, enabled: raw.enabled === true, models };
-}
-
// A peer only advertises the kinds this instance asked for, and it only asks
// for kinds that already have an allowlisted model — so an already-selected
// model the peer has stopped advertising still has to appear, or the user could
// never uncheck it. Those rows render as `not-advertised`.
-function modelRows(selected, status, kind) {
+function modelRows(selected, capabilities, kind) {
const rows = new Map();
- for (const capability of status?.snapshot?.capabilities || []) {
+ for (const capability of capabilities) {
if (capability?.kind !== kind || !capability.engine || !capability.modelId) continue;
rows.set(keyOf(capability), capability);
}
@@ -80,19 +39,15 @@ function modelRows(selected, status, kind) {
export default function PeerMediaProviderPanel({ peer, onRefresh }) {
const [expanded, setExpanded] = useState(false);
const [saving, setSaving] = useState(false);
- const config = configOf(peer);
- const status = peer.mediaProviderStatus || null;
+ const config = peerMediaProviderConfig(peer);
+ const readiness = resolvePeerMediaReadiness(peer);
+ const capabilities = readiness.capabilities;
const rowsByKind = useMemo(
- () => Object.fromEntries(KINDS.map(({ kind }) => [kind, modelRows(config.models[kind], status, kind)])),
+ () => Object.fromEntries(FEDERATED_MEDIA_KINDS.map(({ kind }) => [kind, modelRows(config.models[kind], capabilities, kind)])),
// eslint-disable-next-line react-hooks/exhaustive-deps
- [config.raw, status],
+ [config.raw, capabilities],
);
- const stateMeta = !config.enabled
- ? { label: 'off', tone: 'note' }
- : peer.status !== 'online'
- ? { label: 'peer offline', tone: 'warning' }
- : STATE_META[status?.state] || { label: 'checking', tone: 'muted' };
- const queue = status?.snapshot?.queue;
+ const queue = readiness.queue;
// Carry every kind's list forward on each write. The server merges the
// mediaProvider object, but a patch that omitted a list this panel never
@@ -102,7 +57,7 @@ export default function PeerMediaProviderPanel({ peer, onRefresh }) {
const next = {
...config.raw,
enabled: config.enabled,
- ...Object.fromEntries(KINDS.map(({ kind, field }) => [field, config.models[kind]])),
+ ...Object.fromEntries(FEDERATED_MEDIA_KINDS.map(({ kind, field }) => [field, config.models[kind]])),
...patch,
};
const updated = await updatePeer(peer.id, { mediaProvider: next }).catch(() => null);
@@ -138,8 +93,8 @@ export default function PeerMediaProviderPanel({ peer, onRefresh }) {
<span className="text-[10px] text-gray-500 uppercase tracking-wider font-medium group-hover:text-gray-400 transition-colors">
Remote media provider
</span>
- <Pill tone={stateMeta.tone} size="xs" bordered={false} className="ml-auto">
- {stateMeta.label}
+ <Pill tone={readiness.tone} size="xs" bordered={false} className="ml-auto">
+ {readiness.label}
</Pill>
</button>
@@ -173,11 +128,11 @@ export default function PeerMediaProviderPanel({ peer, onRefresh }) {
</div>
)}
- {status?.state && status.state !== 'ready' && STATE_HELP[status.state] && (
- <p className="text-[10px] text-port-warning leading-snug">{STATE_HELP[status.state]}</p>
+ {readiness.help && (
+ <p className="text-[10px] text-port-warning leading-snug">{readiness.help}</p>
)}
- {KINDS.map(({ kind, label, field, Icon }) => {
+ {FEDERATED_MEDIA_KINDS.map(({ kind, label, field, Icon }) => {
const rows = rowsByKind[kind];
const selectedKeys = new Set(config.models[kind]
.filter((model) => model?.engine && model.modelId)
diff --git a/client/src/components/system-resources/MediaCapacityPanel.jsx b/client/src/components/system-resources/MediaCapacityPanel.jsx
new file mode 100644
index 0000000000..ca2c6cbb54
--- /dev/null
+++ b/client/src/components/system-resources/MediaCapacityPanel.jsx
@@ -0,0 +1,162 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Gauge } from 'lucide-react';
+import { Link } from 'react-router';
+import * as api from '../../services/api.js';
+import Pill from '../ui/Pill';
+import { timeAgo } from '../../utils/formatters';
+import {
+ FEDERATED_MEDIA_KINDS,
+ resolvePeerMediaReadiness,
+} from '../../lib/federatedMediaReadiness.js';
+
+// Three-state, never a boolean. `unknown` means the nvidia-smi probe itself
+// failed; reporting that as "no GPU" would tell the user a machine has no
+// accelerator when the truth is that we could not find out (#4348).
+const CUDA_META = {
+ available: { label: 'CUDA available', tone: 'success' },
+ absent: { label: 'no CUDA device', tone: 'note' },
+ unknown: { label: 'CUDA unknown', tone: 'warning' },
+};
+
+const LANES = [
+ { id: 'gpu', label: 'Local GPU', help: 'Serialized — one render at a time.' },
+ { id: 'cloud', label: 'Cloud CLI', help: 'Parallel — external quota, no local GPU.' },
+ { id: 'remote', label: 'Federated', help: 'Parallel — rendered on a peer.' },
+];
+
+function LaneRow({ label, help, lane }) {
+ const saturated = lane.running >= lane.limit;
+ return (
+ <div className="rounded-lg border border-port-border bg-port-bg px-3 py-2">
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-medium text-gray-300">{label}</span>
+ <span className={`ml-auto text-xs font-mono ${saturated ? 'text-port-warning' : 'text-gray-400'}`}>
+ {lane.running}/{lane.limit}
+ </span>
+ </div>
+ <div className="mt-0.5 text-[10px] text-gray-600">
+ {lane.queued > 0 ? `${lane.queued} queued · ` : ''}{help}
+ </div>
+ </div>
+ );
+}
+
+function PeerRow({ peer }) {
+ const readiness = resolvePeerMediaReadiness(peer);
+ const queue = readiness.queue;
+ return (
+ <div className="rounded-lg border border-port-border bg-port-bg px-3 py-2">
+ <div className="flex items-center gap-2">
+ <span className="truncate text-xs font-medium text-gray-300">{peer.name || peer.id}</span>
+ <Pill tone={readiness.tone} size="xs" bordered={false} className="ml-auto shrink-0">
+ {readiness.label}
+ </Pill>
+ </div>
+ <div className="mt-0.5 flex flex-wrap items-center gap-x-2 text-[10px] text-gray-600">
+ {readiness.kinds.length > 0
+ ? <span>{readiness.kinds.join(' · ')}</span>
+ : <span>no models allowlisted</span>}
+ {queue && (
+ <span>
+ {queue.running} running · {queue.queued} queued · {queue.totalActive}/{queue.maxQueuedJobs} slots
+ </span>
+ )}
+ {readiness.checkedAt && <span>checked {timeAgo(readiness.checkedAt)}</span>}
+ </div>
+ {readiness.help && (
+ <p className="mt-1 text-[10px] leading-snug text-port-warning">{readiness.help}</p>
+ )}
+ </div>
+ );
+}
+
+/**
+ * Local media-lane capacity plus every opted-in peer provider's readiness
+ * (#4348) — the System Health answer to "can this install render right now,
+ * here or on a peer, and if not, why not?".
+ *
+ * The peer half is assembled in the browser from `GET /api/instances`, which is
+ * a LOCAL read. It is deliberately not folded into `/api/system/health/details`
+ * alongside the local half: registered peers fetch that endpoint on every
+ * probe, so our peer list and routing policy would ride federation with it —
+ * exactly what `redactPeerForWire` keeps machine-local.
+ */
+export default function MediaCapacityPanel({ media }) {
+ const [peers, setPeers] = useState(null);
+ const [peersFailed, setPeersFailed] = useState(false);
+
+ const loadPeers = useCallback(async () => {
+ const data = await api.getInstances({ silent: true }).catch(() => null);
+ // `null` = the read failed, distinct from `[]` = read fine, no peers. A
+ // failed read must not render as "you have no providers configured".
+ if (!data) {
+ setPeersFailed(true);
+ return;
+ }
+ setPeersFailed(false);
+ setPeers(Array.isArray(data.peers) ? data.peers : []);
+ }, []);
+
+ useEffect(() => { loadPeers(); }, [loadPeers]);
+
+ const providers = (peers || []).filter((peer) => peer?.mediaProvider?.enabled === true);
+ const cuda = CUDA_META[media?.gpu?.cudaStatus] || CUDA_META.unknown;
+
+ return (
+ <div className="rounded-xl border border-port-border bg-port-card p-4">
+ <div className="flex items-center gap-2">
+ <Gauge size={16} className="text-port-accent" />
+ <h3 className="font-semibold text-white">Media capacity</h3>
+ <Pill tone={cuda.tone} size="xs" bordered={false} className="ml-auto">{cuda.label}</Pill>
+ </div>
+
+ {!media ? (
+ <p className="mt-3 text-sm text-gray-400">
+ Media-lane capacity is unavailable. Local render slots and queue depth are unknown.
+ </p>
+ ) : (
+ <>
+ <div className="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-3">
+ {LANES.map(({ id, label, help }) => (
+ <LaneRow key={id} label={label} help={help} lane={media.lanes[id]} />
+ ))}
+ </div>
+
+ <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-gray-500">
+ <span>{media.totals.running} running · {media.totals.queued} queued</span>
+ {FEDERATED_MEDIA_KINDS.map(({ kind, label }) => {
+ const counts = media.byKind?.[kind];
+ if (!counts || (!counts.running && !counts.queued)) return null;
+ return <span key={kind}>{label}: {counts.running}/{counts.queued}</span>;
+ })}
+ </div>
+ </>
+ )}
+
+ <div className="mt-4 border-t border-port-border/60 pt-3">
+ <div className="flex items-center gap-2">
+ <h4 className="text-xs font-semibold uppercase tracking-wider text-gray-500">Peer providers</h4>
+ <Link to="/instances" className="ml-auto text-[11px] text-port-accent hover:underline">
+ Instances
+ </Link>
+ </div>
+
+ {peersFailed ? (
+ <p className="mt-2 text-xs text-port-warning">
+ Peer list unavailable — provider readiness is unknown.
+ </p>
+ ) : peers === null ? (
+ <p className="mt-2 text-xs text-gray-500">Loading peer providers…</p>
+ ) : providers.length === 0 ? (
+ <p className="mt-2 text-xs text-gray-500">
+ No peer is enabled as a media provider. Enable one from Instances to render on another machine.
+ </p>
+ ) : (
+ <div className="mt-2 space-y-1.5">
+ {providers.map((peer) => <PeerRow key={peer.id} peer={peer} />)}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/system-resources/MediaCapacityPanel.test.jsx b/client/src/components/system-resources/MediaCapacityPanel.test.jsx
new file mode 100644
index 0000000000..f64cedbadc
--- /dev/null
+++ b/client/src/components/system-resources/MediaCapacityPanel.test.jsx
@@ -0,0 +1,130 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+const api = vi.hoisted(() => ({ getInstances: vi.fn() }));
+vi.mock('../../services/api.js', () => api);
+
+const MediaCapacityPanel = (await import('./MediaCapacityPanel.jsx')).default;
+
+const media = (overrides = {}) => ({
+ gpu: { cudaStatus: 'available', laneBusy: true, laneKind: 'video' },
+ lanes: {
+ gpu: { running: 1, queued: 2, limit: 1 },
+ cloud: { running: 0, queued: 0, limit: 1 },
+ remote: { running: 3, queued: 0, limit: 20 },
+ },
+ byKind: {
+ video: { running: 1, queued: 2 },
+ image: { running: 0, queued: 0 },
+ audio: { running: 3, queued: 0 },
+ training: { running: 0, queued: 0 },
+ },
+ totals: { running: 4, queued: 2 },
+ ...overrides,
+});
+
+const providerPeer = (overrides = {}) => ({
+ id: 'peer-1',
+ name: 'render-box',
+ status: 'online',
+ mediaProvider: { enabled: true, audioModels: [{ engine: 'minimax', modelId: 'music-3' }] },
+ mediaProviderStatus: {
+ checkedAt: new Date().toISOString(),
+ state: 'ready',
+ freshUntil: new Date(Date.now() + 60_000).toISOString(),
+ snapshot: {
+ queue: { running: 1, queued: 0, totalActive: 1, maxQueuedJobs: 4, accepting: true },
+ capabilities: [],
+ },
+ },
+ ...overrides,
+});
+
+const renderPanel = (props = {}) => render(
+ <MemoryRouter>
+ <MediaCapacityPanel media={media()} {...props} />
+ </MemoryRouter>,
+);
+
+describe('MediaCapacityPanel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getInstances.mockResolvedValue({ peers: [] });
+ });
+
+ it('shows each lane’s occupancy against its configured limit', async () => {
+ renderPanel();
+ expect(await screen.findByText('Local GPU')).toBeInTheDocument();
+ expect(screen.getByText('1/1')).toBeInTheDocument();
+ expect(screen.getByText('3/20')).toBeInTheDocument();
+ expect(screen.getByText('4 running · 2 queued')).toBeInTheDocument();
+ });
+
+ it('reports queue depth per kind, skipping idle kinds', async () => {
+ renderPanel();
+ expect(await screen.findByText('video: 1/2')).toBeInTheDocument();
+ expect(screen.getByText('audio: 3/0')).toBeInTheDocument();
+ expect(screen.queryByText(/^image:/)).not.toBeInTheDocument();
+ });
+
+ // available / absent / unknown are three distinct claims — a failed probe must
+ // never be rendered as "this machine has no GPU".
+ it.each([
+ ['available', 'CUDA available'],
+ ['absent', 'no CUDA device'],
+ ['unknown', 'CUDA unknown'],
+ ])('renders the %s CUDA state as its own label', async (cudaStatus, label) => {
+ renderPanel({ media: media({ gpu: { cudaStatus, laneBusy: false, laneKind: null } }) });
+ expect(await screen.findByText(label)).toBeInTheDocument();
+ });
+
+ it('renders an unknown state rather than an idle one when the report is missing', async () => {
+ renderPanel({ media: null });
+ expect(await screen.findByText(/Media-lane capacity is unavailable/)).toBeInTheDocument();
+ expect(screen.getByText('CUDA unknown')).toBeInTheDocument();
+ expect(screen.queryByText('Local GPU')).not.toBeInTheDocument();
+ });
+
+ it('lists an opted-in peer provider with its readiness and queue', async () => {
+ api.getInstances.mockResolvedValue({ peers: [providerPeer()] });
+ renderPanel();
+ expect(await screen.findByText('render-box')).toBeInTheDocument();
+ expect(screen.getByText('ready')).toBeInTheDocument();
+ expect(screen.getByText('1 running · 0 queued · 1/4 slots')).toBeInTheDocument();
+ });
+
+ it('shows an expired snapshot as stale with its remedy, not as ready', async () => {
+ api.getInstances.mockResolvedValue({
+ peers: [providerPeer({
+ mediaProviderStatus: {
+ checkedAt: new Date(Date.now() - 600_000).toISOString(),
+ state: 'ready',
+ freshUntil: new Date(Date.now() - 300_000).toISOString(),
+ snapshot: { queue: { running: 0, queued: 0, totalActive: 0, maxQueuedJobs: 4, accepting: true }, capabilities: [] },
+ },
+ })],
+ });
+ renderPanel();
+ expect(await screen.findByText('stale')).toBeInTheDocument();
+ expect(screen.queryByText('ready')).not.toBeInTheDocument();
+ expect(screen.getByText(/last capacity snapshot expired/i)).toBeInTheDocument();
+ });
+
+ it('omits a peer that is not enabled as a media provider', async () => {
+ api.getInstances.mockResolvedValue({
+ peers: [providerPeer({ id: 'p2', name: 'laptop', mediaProvider: { enabled: false } })],
+ });
+ renderPanel();
+ expect(await screen.findByText(/No peer is enabled as a media provider/)).toBeInTheDocument();
+ expect(screen.queryByText('laptop')).not.toBeInTheDocument();
+ });
+
+ // A failed read and a genuinely peerless install must not render identically.
+ it('distinguishes a failed peer read from having no providers', async () => {
+ api.getInstances.mockRejectedValue(new Error('offline'));
+ renderPanel();
+ expect(await screen.findByText(/provider readiness is unknown/i)).toBeInTheDocument();
+ expect(screen.queryByText(/No peer is enabled as a media provider/)).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 4cf19243f0..f79e9c6cc9 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -44,6 +44,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. |
| `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |
| `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. |
+| `federatedMediaReadiness.js` | One reading of a peer’s federated media-provider readiness (#4348), shared by the Instances peer card and the System Health capacity panel so the two cannot disagree. `resolvePeerMediaReadiness(peer, { now })` maps the stored probe onto a display state/label/tone plus its remedy text, queue snapshot, capabilities, and per-kind allowlists; it re-derives `stale` when the snapshot’s `freshUntil` has passed, so a snapshot probed as `ready` cannot keep reading `ready` after the server would refuse to submit against it. Also exports `FEDERATED_MEDIA_KINDS` (audio/image/video + their config fields and icons), the state/help tables, and `peerMediaProviderConfig`. Display only — the server re-probes and fail-closes before any job leaves. |
| `glbFailure.js` | Turns a 3D asset failure into an actionable sentence. `glbFailureHint(error)` matches the message against a shared table (an HTML body reaching the glTF parser, a WebGL context failure, a 404) and returns `null` when nothing recognizes it — so a caller can tell "we know the cause" from "we don't" and fall back to the raw text. `glbErrorText(error)` reads a message off whatever shape was thrown. Shared because the CoS avatars load remote GLBs too: every caught error there used to be reported as "this display has no WebGL", sending the user to change an unrelated setting (#4688). Consumed by `media/GlbViewer.jsx` and `cos/CoSCanvasGuard.jsx`. |
| `grokVideoClip.js` | Mirror of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. |
| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |
diff --git a/client/src/lib/federatedMediaReadiness.js b/client/src/lib/federatedMediaReadiness.js
new file mode 100644
index 0000000000..6748e1904d
--- /dev/null
+++ b/client/src/lib/federatedMediaReadiness.js
@@ -0,0 +1,131 @@
+/**
+ * One reading of "is this peer usable as a media provider right now?" (#4348).
+ *
+ * Two surfaces answer that question — the Instances peer card (which also
+ * edits the per-kind allowlist) and the System Health capacity panel — and they
+ * must not disagree: a card reading `ready` beside a panel reading `stale` is
+ * worse than either alone. The state machine, its labels, and the remedy text
+ * therefore live here rather than inside one component.
+ *
+ * The server stays authoritative. `assertFederatedMediaProviderSelection`
+ * (server/services/federatedMediaConsumer.js) re-probes and fail-closes before
+ * any job leaves this instance, so nothing here gates work — it only decides
+ * what the user is shown.
+ */
+
+import { Film, Image, Music2 } from 'lucide-react';
+
+// Wire v1 shipped audio-only, then grew image and video (#4348). Every surface
+// iterates this table so a newly federated kind cannot appear on one screen and
+// be missing from another.
+export const FEDERATED_MEDIA_KINDS = Object.freeze([
+ { kind: 'audio', label: 'audio', field: 'audioModels', Icon: Music2 },
+ { kind: 'image', label: 'image', field: 'imageModels', Icon: Image },
+ { kind: 'video', label: 'video', field: 'videoModels', Icon: Film },
+]);
+
+export const FEDERATED_MEDIA_STATE_META = Object.freeze({
+ ready: { label: 'ready', tone: 'success' },
+ busy: { label: 'busy', tone: 'warning' },
+ stale: { label: 'stale', tone: 'warning' },
+ unauthorized: { label: 'auth required', tone: 'warning' },
+ unsupported: { label: 'older peer', tone: 'note' },
+ disabled: { label: 'provider off', tone: 'note' },
+ unavailable: { label: 'unavailable', tone: 'warning' },
+ unreachable: { label: 'unreachable', tone: 'warning' },
+ invalid: { label: 'invalid status', tone: 'warning' },
+});
+
+export const FEDERATED_MEDIA_STATE_HELP = Object.freeze({
+ busy: 'The peer is reachable, but its shared media lane is currently at capacity.',
+ stale: 'The last capacity snapshot expired. New remote work is blocked until a fresh probe succeeds.',
+ unauthorized: 'Store this peer’s instance-password credential above and make sure this instance is registered there.',
+ unsupported: 'This peer does not expose the federated-media wire-v1 status endpoint yet.',
+ disabled: 'Enable federated media sharing on the peer under Settings → Sharing.',
+ unavailable: 'The peer has no currently ready allowlisted media runtime/model.',
+ unreachable: 'The media status request failed. New remote work remains blocked.',
+ invalid: 'The peer returned a response that did not match the versioned media-provider contract.',
+});
+
+// Not a real provider state — the peer is opted in but no probe has landed yet.
+// Kept distinct from `unavailable` so a first-run instance doesn't accuse a
+// perfectly healthy peer of having nothing to offer.
+const CHECKING = Object.freeze({ label: 'checking', tone: 'muted' });
+const OFF = Object.freeze({ label: 'off', tone: 'note' });
+const PEER_OFFLINE = Object.freeze({ label: 'peer offline', tone: 'warning' });
+// One shared empty array rather than a fresh literal per call: callers memoize
+// on `capabilities`, and a new identity every render would defeat that memo for
+// exactly the peers that have nothing to recompute.
+const NO_CAPABILITIES = Object.freeze([]);
+
+const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);
+// NUL separator, matching the server's own model key: a printable separator
+// would let an engine name containing it collide with a different pair.
+export const federatedMediaModelKey = ({ engine, modelId }) => `${engine}\u0000${modelId}`;
+const listOf = (raw, field) => (Array.isArray(raw?.[field]) ? raw[field] : []);
+
+/**
+ * The peer's locally-stored provider config, with every kind's list present.
+ * @returns {{raw: object, enabled: boolean, models: Record<string, object[]>}}
+ */
+export function peerMediaProviderConfig(peer) {
+ const raw = isRecord(peer?.mediaProvider) ? peer.mediaProvider : {};
+ const models = {};
+ for (const { kind, field } of FEDERATED_MEDIA_KINDS) models[kind] = listOf(raw, field);
+ return { raw, enabled: raw.enabled === true, models };
+}
+
+/**
+ * Has the stored snapshot outlived the freshness window it was probed under?
+ *
+ * The probe records `freshUntil` from the provider's own `generatedAt +
+ * staleAfterMs`, then the record sits on disk until the next peer poll. A
+ * snapshot probed as `ready` therefore keeps reading `ready` long after the
+ * server would refuse to submit against it, which is precisely the
+ * "stale must not look available" rule the capacity contract is built on.
+ * Re-deriving expiry at render time closes that gap without a second probe.
+ */
+function snapshotExpired(status, now) {
+ const freshUntil = Date.parse(status?.freshUntil);
+ return Number.isFinite(freshUntil) && freshUntil < now;
+}
+
+/**
+ * Resolve one peer's media-provider readiness for display.
+ *
+ * @param {object} peer - a sanitized peer record from `GET /api/instances`
+ * @param {{now?: number}} [options]
+ * @returns {{configured: boolean, state: string|null, label: string, tone: string,
+ * help: string|null, queue: object|null, capabilities: object[], checkedAt: string|null,
+ * models: Record<string, object[]>, modelCount: number, kinds: string[]}}
+ */
+export function resolvePeerMediaReadiness(peer, { now = Date.now() } = {}) {
+ const config = peerMediaProviderConfig(peer);
+ const status = isRecord(peer?.mediaProviderStatus) ? peer.mediaProviderStatus : null;
+ const snapshot = isRecord(status?.snapshot) ? status.snapshot : null;
+ // An expired snapshot is stale whatever the probe concluded — including the
+ // `ready` it concluded at probe time.
+ const state = !status
+ ? null
+ : (snapshotExpired(status, now) ? 'stale' : status.state);
+ const meta = !config.enabled
+ ? OFF
+ : peer?.status !== 'online'
+ ? PEER_OFFLINE
+ : (FEDERATED_MEDIA_STATE_META[state] || CHECKING);
+ return {
+ configured: config.enabled,
+ state,
+ label: meta.label,
+ tone: meta.tone,
+ // Remedy text belongs to the provider state, not to the peer being offline
+ // — an offline peer's own row already says so.
+ help: (config.enabled && state && state !== 'ready' && FEDERATED_MEDIA_STATE_HELP[state]) || null,
+ queue: isRecord(snapshot?.queue) ? snapshot.queue : null,
+ capabilities: Array.isArray(snapshot?.capabilities) ? snapshot.capabilities : NO_CAPABILITIES,
+ checkedAt: typeof status?.checkedAt === 'string' ? status.checkedAt : null,
+ models: config.models,
+ modelCount: FEDERATED_MEDIA_KINDS.reduce((sum, { kind }) => sum + config.models[kind].length, 0),
+ kinds: FEDERATED_MEDIA_KINDS.filter(({ kind }) => config.models[kind].length > 0).map(({ kind }) => kind),
+ };
+}
diff --git a/client/src/lib/federatedMediaReadiness.test.js b/client/src/lib/federatedMediaReadiness.test.js
new file mode 100644
index 0000000000..50f55a43e5
--- /dev/null
+++ b/client/src/lib/federatedMediaReadiness.test.js
@@ -0,0 +1,133 @@
+import { describe, it, expect } from 'vitest';
+import {
+ FEDERATED_MEDIA_KINDS,
+ FEDERATED_MEDIA_STATE_HELP,
+ federatedMediaModelKey,
+ peerMediaProviderConfig,
+ resolvePeerMediaReadiness,
+} from './federatedMediaReadiness.js';
+
+const NOW = Date.parse('2026-08-20T12:00:00.000Z');
+const iso = (offsetMs) => new Date(NOW + offsetMs).toISOString();
+
+const peer = (overrides = {}) => ({
+ id: 'peer-1',
+ name: 'render-box',
+ status: 'online',
+ mediaProvider: { enabled: true, audioModels: [{ engine: 'minimax', modelId: 'music-3' }] },
+ mediaProviderStatus: {
+ checkedAt: iso(-1000),
+ state: 'ready',
+ reason: null,
+ freshUntil: iso(60_000),
+ snapshot: {
+ queue: { running: 1, queued: 0, totalActive: 1, maxQueuedJobs: 4, accepting: true },
+ capabilities: [{ kind: 'audio', engine: 'minimax', modelId: 'music-3', ready: true }],
+ },
+ },
+ ...overrides,
+});
+
+describe('resolvePeerMediaReadiness', () => {
+ it('reports a fresh ready provider with its queue and capabilities', () => {
+ const readiness = resolvePeerMediaReadiness(peer(), { now: NOW });
+ expect(readiness).toMatchObject({ configured: true, state: 'ready', label: 'ready', tone: 'success', help: null });
+ expect(readiness.queue.maxQueuedJobs).toBe(4);
+ expect(readiness.capabilities).toHaveLength(1);
+ expect(readiness.kinds).toEqual(['audio']);
+ expect(readiness.modelCount).toBe(1);
+ });
+
+ // The load-bearing case: the probe concluded `ready`, then the snapshot
+ // expired while the record sat on disk. The server would refuse to submit
+ // against it, so the UI must not keep advertising it as available.
+ it('downgrades an expired ready snapshot to stale', () => {
+ const readiness = resolvePeerMediaReadiness(peer(), { now: NOW + 61_000 });
+ expect(readiness.state).toBe('stale');
+ expect(readiness.label).toBe('stale');
+ expect(readiness.tone).toBe('warning');
+ expect(readiness.help).toBe(FEDERATED_MEDIA_STATE_HELP.stale);
+ });
+
+ it('keeps a snapshot fresh right up to its expiry instant', () => {
+ expect(resolvePeerMediaReadiness(peer(), { now: NOW + 60_000 }).state).toBe('ready');
+ });
+
+ it('leaves a state with no freshness window alone', () => {
+ const unreachable = peer({
+ mediaProviderStatus: { checkedAt: iso(-1000), state: 'unreachable', reason: 'timeout', freshUntil: null, snapshot: null },
+ });
+ const readiness = resolvePeerMediaReadiness(unreachable, { now: NOW + 10_000_000 });
+ expect(readiness.state).toBe('unreachable');
+ expect(readiness.help).toBe(FEDERATED_MEDIA_STATE_HELP.unreachable);
+ expect(readiness.queue).toBeNull();
+ expect(readiness.capabilities).toEqual([]);
+ });
+
+ it('reads a peer with no provider config as off, not as broken', () => {
+ const readiness = resolvePeerMediaReadiness({ id: 'p', status: 'online' }, { now: NOW });
+ expect(readiness).toMatchObject({ configured: false, state: null, label: 'off', tone: 'note', help: null });
+ expect(readiness.modelCount).toBe(0);
+ });
+
+ // An opted-in peer that has not been probed yet is not the same claim as a
+ // peer with nothing to offer.
+ it('reads an unprobed opted-in peer as checking', () => {
+ const readiness = resolvePeerMediaReadiness(peer({ mediaProviderStatus: undefined }), { now: NOW });
+ expect(readiness.label).toBe('checking');
+ expect(readiness.state).toBeNull();
+ });
+
+ it('reports an offline peer as offline rather than as a provider fault', () => {
+ const readiness = resolvePeerMediaReadiness(peer({ status: 'offline' }), { now: NOW });
+ expect(readiness.label).toBe('peer offline');
+ expect(readiness.tone).toBe('warning');
+ });
+
+ it('surfaces the remedy for a disabled provider', () => {
+ const disabled = peer({
+ mediaProviderStatus: { checkedAt: iso(-1), state: 'disabled', reason: 'MEDIA_PROVIDER_DISABLED', freshUntil: null, snapshot: null },
+ });
+ expect(resolvePeerMediaReadiness(disabled, { now: NOW }).help).toBe(FEDERATED_MEDIA_STATE_HELP.disabled);
+ });
+
+ it('lists only the kinds that actually have an allowlisted model', () => {
+ const multi = peer({
+ mediaProvider: {
+ enabled: true,
+ audioModels: [{ engine: 'minimax', modelId: 'music-3' }],
+ imageModels: [],
+ videoModels: [{ engine: 'local', modelId: 'ltx2' }],
+ },
+ });
+ const readiness = resolvePeerMediaReadiness(multi, { now: NOW });
+ expect(readiness.kinds).toEqual(['audio', 'video']);
+ expect(readiness.modelCount).toBe(2);
+ });
+
+ it('tolerates a malformed stored config without throwing', () => {
+ const junk = resolvePeerMediaReadiness(
+ { id: 'p', status: 'online', mediaProvider: 'nope', mediaProviderStatus: [] },
+ { now: NOW },
+ );
+ expect(junk.configured).toBe(false);
+ expect(junk.capabilities).toEqual([]);
+ });
+});
+
+describe('peerMediaProviderConfig', () => {
+ it('always returns a list for every known kind', () => {
+ const config = peerMediaProviderConfig({ mediaProvider: { enabled: true } });
+ for (const { kind } of FEDERATED_MEDIA_KINDS) expect(config.models[kind]).toEqual([]);
+ });
+});
+
+describe('federatedMediaModelKey', () => {
+ // Matches the server's own NUL-separated key. A printable separator would let
+ // an engine name containing it collide with a different engine/model pair.
+ it('separates engine from model with NUL', () => {
+ expect(federatedMediaModelKey({ engine: 'local', modelId: 'ltx2' })).toBe('local\u0000ltx2');
+ expect(federatedMediaModelKey({ engine: 'a', modelId: 'b-c' }))
+ .not.toBe(federatedMediaModelKey({ engine: 'a-b', modelId: 'c' }));
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 8c4989fe24..9199824148 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -26,6 +26,7 @@ export * from './catalogTypes.js';
export * from './creativeDirectorPlan.js';
export * from './creativeDirectorPreview.js';
export * from './editorialRoadmap.js';
+export * from './federatedMediaReadiness.js';
export * from './glbFailure.js';
export * from './grokVideoClip.js';
export * from './imageCleaners.js';
diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsx
index 66031e8f9f..ea49d5ce27 100644
--- a/client/src/pages/SystemHealthPage.jsx
+++ b/client/src/pages/SystemHealthPage.jsx
@@ -10,6 +10,7 @@ import { useConfirmDelete } from '../hooks/useConfirmDelete.js';
import StoragePanel from '../components/system-resources/StoragePanel.jsx';
import ModelsPanel from '../components/system-resources/ModelsPanel.jsx';
import QueuesPanel from '../components/system-resources/QueuesPanel.jsx';
+import MediaCapacityPanel from '../components/system-resources/MediaCapacityPanel.jsx';
const HEALTH_STYLE = {
healthy: { color: 'text-port-success', bg: 'bg-port-success/10', icon: CheckCircle, label: 'Healthy' },
@@ -348,6 +349,8 @@ function SystemHealthOverview() {
)}
</section>
+ <MediaCapacityPanel media={health.media} />
+
<section className="bg-port-card border border-port-border rounded-xl p-4">
<h3 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
<Activity size={16} />
diff --git a/client/src/pages/SystemHealthPage.test.jsx b/client/src/pages/SystemHealthPage.test.jsx
index 48698ac8eb..949aa05710 100644
--- a/client/src/pages/SystemHealthPage.test.jsx
+++ b/client/src/pages/SystemHealthPage.test.jsx
@@ -27,6 +27,10 @@ vi.mock('../services/api', () => ({
deleteCachedModel: vi.fn(),
deleteLora: vi.fn(),
deleteLocalLlmModel: vi.fn(),
+ // The overview's media-capacity panel reads the peer list to report federated
+ // provider readiness (#4348). No peers keeps this page's assertions about
+ // local metrics unaffected.
+ getInstances: vi.fn(() => Promise.resolve({ peers: [] })),
}));
vi.mock('../hooks/useProviderModels', () => ({
diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.md
index ab90588006..dfe5be34fe 100644
--- a/docs/FEDERATED_MEDIA_PROVIDERS.md
+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md
@@ -2,7 +2,7 @@
PortOS can opt in to serving local media-generation capacity to another registered PortOS peer. The wire contract, `/api/federation/media/v1`, carries queued **audio, image, and video** generation through the existing durable `mediaJobQueue` and this machine's local engines.
-Provider-side queueing, consumer-side capacity discovery, and durable remote execution are available for all three kinds. Provider selection is exposed through the generation APIs; the picker UI, multi-provider scheduling, input-asset transfer, and higher-level commission routing remain later slices of issue #4348.
+Provider-side queueing, consumer-side capacity discovery, durable remote execution, and unattended (Creative Director / Commission) routing are available for all three kinds. Interactive provider selection is exposed through the generation APIs and the Music Studio panel; Image Gen / Video Gen pickers, multi-provider scheduling, and input-asset transfer remain later slices of issue #4348.
## Enable a provider
@@ -225,6 +225,47 @@ machine. A provider rejection inside a batch is contained rather than fatal —
one refused portrait or scene frame is recorded in that run's `skipped` list and
the rest of the batch still queues.
+## Capacity at a glance (System Health)
+
+**System Health → Overview → Media capacity** answers "can this install render
+right now, here or on a peer, and if not, why not?" in one card.
+
+The **local** half comes from `GET /api/system/health/details` under a `media`
+key: this machine's CUDA state and, per lane, how many renders are running
+against that lane's configured concurrency plus how deep its queue is.
+
+| Lane | Concurrency | What runs there |
+|------|-------------|-----------------|
+| Local GPU | 1 (serialized) | local image/video/audio/training renders |
+| Cloud CLI | `imageGen.codex.parallelLimit` | codex/grok/agy renders — external quota, no local GPU |
+| Federated | 20 | outgoing proxy jobs rendering on a peer |
+
+CUDA is reported with the same three states the wire uses — `available`,
+`absent`, and `unknown` — and the card labels them distinctly. A probe that
+could not run is not the claim "this machine has no GPU", and collapsing the two
+is what would make an operator go hunting for a card that is sitting there fine.
+An unreadable capacity report renders as unknown rather than as an idle machine.
+
+The **peer** half lists every peer enabled as a media provider with its
+readiness state, allowlisted kinds, the peer's own shared queue depth against its
+`maxQueuedJobs`, and how long ago it was probed — the same state vocabulary and
+remedy text the Instances peer card uses, from one shared resolver
+(`client/src/lib/federatedMediaReadiness.js`), so the two screens cannot
+disagree.
+
+Both surfaces re-derive **stale** at render time from the stored snapshot's
+`freshUntil`. A snapshot probed as `ready` sits on the peer record until the
+next poll, so without that check it would keep reading `ready` well after the
+server would refuse to submit against it — the inverse of the fail-closed rule
+the capacity contract is built on. Nothing here gates work either way: the
+server re-probes and fail-closes before any job leaves.
+
+The peer half is assembled in the browser from `GET /api/instances`, a local
+read. It is deliberately **not** folded into `/api/system/health/details`
+alongside the local half: registered peers fetch that endpoint on every probe,
+so our peer list and routing policy would ride federation with it — exactly what
+`redactPeerForWire` keeps machine-local.
+
## Authentication and identity
Every request requires both:
@@ -308,4 +349,4 @@ A remote job's conditioning prompt is persisted **only inside its versioned `rem
## Current boundary
-Wire v1 carries instrumental audio, text-to-image, and text-to-video. Interactive remote selection is exposed through the Music Studio panel and the generation APIs rather than a peer picker on the Image Gen / Video Gen pages; unattended work routes through **Instances → Unattended render routing**. Still remaining from #4348: those Image Gen / Video Gen pickers, a privacy-preserving design for remote lyrical conditioning (which is also what keeps unattended audio local), input-asset transfer (init/reference images, LoRAs, chained renders), multi-provider fairness/failover, and aggregate provider health on System Health.
+Wire v1 carries instrumental audio, text-to-image, and text-to-video. Interactive remote selection is exposed through the Music Studio panel and the generation APIs rather than a peer picker on the Image Gen / Video Gen pages; unattended work routes through **Instances → Unattended render routing**. Still remaining from #4348: those Image Gen / Video Gen pickers, a privacy-preserving design for remote lyrical conditioning (which is also what keeps unattended audio local), input-asset transfer (init/reference images, LoRAs, chained renders), and multi-provider fairness/failover.
diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.js
index ceaaed70b1..6c71a25a1a 100644
--- a/server/routes/systemHealth.js
+++ b/server/routes/systemHealth.js
@@ -15,6 +15,7 @@ import { checkGhHealth } from '../services/github.js';
import { isAuthEnabled } from '../services/auth.js';
import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';
import { getActiveProcessing } from '../services/activeProcessing.js';
+import { getMediaCapacity } from '../services/mediaCapacity.js';
// Defaults are tuned for a real dev machine: memory routinely sits in the
// 75-85% band on a host with a couple of LLMs loaded, and big SSDs commonly
@@ -82,7 +83,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {
const startTime = Date.now();
// Gather data in parallel
- const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds, forgeHealth] = await Promise.all([
+ const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds, forgeHealth, mediaCapacity] = await Promise.all([
listProcesses().catch(() => []),
apps.getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),
cos.getStatus().catch(() => null),
@@ -92,7 +93,10 @@ router.get('/health/details', asyncHandler(async (req, res) => {
statfs('/').catch(() => null),
getMemoryStats(),
loadThresholds(),
- checkGhHealth().catch(() => ({ status: 'error', ok: false, detail: 'Health check failed', remedy: null, checkedAt: null }))
+ checkGhHealth().catch(() => ({ status: 'error', ok: false, detail: 'Health check failed', remedy: null, checkedAt: null })),
+ // Media-lane capacity never fails the health report: an unreadable GPU probe
+ // degrades to `null`, which the UI renders as unknown rather than as idle.
+ getMediaCapacity().catch(() => null)
]);
const memUsagePercent = Math.round((memStats.used / memStats.total) * 100);
@@ -286,6 +290,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {
processes: processStats,
apps: appStats,
cos: cosInfo,
+ media: mediaCapacity,
database: dbHealth,
forge: forgeHealth,
thresholds,
diff --git a/server/services/mediaCapacity.js b/server/services/mediaCapacity.js
new file mode 100644
index 0000000000..0759350455
--- /dev/null
+++ b/server/services/mediaCapacity.js
@@ -0,0 +1,44 @@
+/**
+ * Local media-lane capacity — "what is this machine rendering, and can it take
+ * another job?" (#4348).
+ *
+ * Split out of `activeProcessing.js` rather than folded into it: that service
+ * answers a live-activity question for the dashboard (it lists every in-flight
+ * job, probes GPU *utilization* on a 4s TTL, and reads CoS/Ollama state), while
+ * System Health needs only the cheap capacity shape and is polled on a much
+ * slower cadence. Sharing the heavier projection would drag nvidia-smi
+ * utilization probes and a CoS task read onto every health poll.
+ *
+ * FEDERATION NOTE: this shape is returned by `GET /api/system/health/details`,
+ * which registered peers fetch on every probe. It therefore describes ONLY this
+ * machine's own runtime — never our peer list, our routing policy, or the
+ * models we have allowlisted on someone else's instance. Consumer-side
+ * capacity stays local (see `redactPeerForWire` in services/instances.js), and
+ * the provider-side allowlist has its own authenticated endpoint.
+ */
+
+import { getCudaCapability } from '../lib/cudaCapability.js';
+import { getQueueCapacity } from './mediaJobQueue/index.js';
+
+/**
+ * @returns {Promise<{gpu: {cudaStatus: 'available'|'absent'|'unknown', laneBusy: boolean, laneKind: string|null},
+ * lanes: object, byKind: object, totals: {running: number, queued: number}}>}
+ */
+export async function getMediaCapacity() {
+ // Three-state, never a boolean: `unknown` (the probe itself failed) must stay
+ // distinct from `absent` (no CUDA device here). A caller that collapses them
+ // reports a failed probe as "this machine has no GPU", which is the exact
+ // conflation the issue's capacity contract forbids.
+ const capability = await getCudaCapability().catch(() => ({ status: 'unknown' }));
+ const capacity = getQueueCapacity();
+ return {
+ gpu: {
+ cudaStatus: capability.status,
+ laneBusy: capacity.lanes.gpu.running > 0,
+ laneKind: capacity.runningKind,
+ },
+ lanes: capacity.lanes,
+ byKind: capacity.byKind,
+ totals: capacity.totals,
+ };
+}
diff --git a/server/services/mediaCapacity.test.js b/server/services/mediaCapacity.test.js
new file mode 100644
index 0000000000..0850863731
--- /dev/null
+++ b/server/services/mediaCapacity.test.js
@@ -0,0 +1,87 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const getCudaCapability = vi.fn();
+const getQueueCapacity = vi.fn();
+
+vi.mock('../lib/cudaCapability.js', () => ({ getCudaCapability: (...args) => getCudaCapability(...args) }));
+vi.mock('./mediaJobQueue/index.js', () => ({ getQueueCapacity: (...args) => getQueueCapacity(...args) }));
+
+const { getMediaCapacity } = await import('./mediaCapacity.js');
+
+const capacity = (overrides = {}) => ({
+ lanes: {
+ gpu: { running: 0, queued: 0, limit: 1 },
+ cloud: { running: 0, queued: 0, limit: 1 },
+ remote: { running: 0, queued: 0, limit: 20 },
+ },
+ byKind: {
+ video: { running: 0, queued: 0 },
+ image: { running: 0, queued: 0 },
+ training: { running: 0, queued: 0 },
+ audio: { running: 0, queued: 0 },
+ },
+ totals: { running: 0, queued: 0 },
+ runningKind: null,
+ ...overrides,
+});
+
+describe('getMediaCapacity', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getCudaCapability.mockResolvedValue({ status: 'available' });
+ getQueueCapacity.mockReturnValue(capacity());
+ });
+
+ it('reports the GPU lane busy with the kind it is rendering', async () => {
+ getQueueCapacity.mockReturnValue(capacity({
+ lanes: {
+ gpu: { running: 1, queued: 2, limit: 1 },
+ cloud: { running: 0, queued: 0, limit: 1 },
+ remote: { running: 0, queued: 0, limit: 20 },
+ },
+ totals: { running: 1, queued: 2 },
+ runningKind: 'video',
+ }));
+ const result = await getMediaCapacity();
+ expect(result.gpu.laneBusy).toBe(true);
+ expect(result.gpu.laneKind).toBe('video');
+ expect(result.lanes.gpu).toEqual({ running: 1, queued: 2, limit: 1 });
+ expect(result.totals).toEqual({ running: 1, queued: 2 });
+ });
+
+ it('reports an idle GPU lane as not busy with no kind', async () => {
+ const result = await getMediaCapacity();
+ expect(result.gpu.laneBusy).toBe(false);
+ expect(result.gpu.laneKind).toBeNull();
+ });
+
+ // The whole point of the three-state contract: a probe that could not run is
+ // not the same claim as "this machine has no CUDA device".
+ it.each(['available', 'absent', 'unknown'])('passes through the %s CUDA state verbatim', async (status) => {
+ getCudaCapability.mockResolvedValue({ status });
+ expect((await getMediaCapacity()).gpu.cudaStatus).toBe(status);
+ });
+
+ it('degrades a failed CUDA probe to unknown rather than absent', async () => {
+ getCudaCapability.mockRejectedValue(new Error('nvidia-smi exploded'));
+ const result = await getMediaCapacity();
+ expect(result.gpu.cudaStatus).toBe('unknown');
+ // The rest of the report still has to arrive — a GPU probe failure must not
+ // blank out queue depth the queue itself knows perfectly well.
+ expect(result.lanes.remote.limit).toBe(20);
+ });
+
+ it('carries per-kind queue depth through', async () => {
+ getQueueCapacity.mockReturnValue(capacity({
+ byKind: {
+ video: { running: 0, queued: 0 },
+ image: { running: 1, queued: 3 },
+ training: { running: 0, queued: 0 },
+ audio: { running: 0, queued: 1 },
+ },
+ }));
+ const result = await getMediaCapacity();
+ expect(result.byKind.image).toEqual({ running: 1, queued: 3 });
+ expect(result.byKind.audio).toEqual({ running: 0, queued: 1 });
+ });
+});
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index ac7e88c16d..ff837764d8 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -300,6 +300,55 @@ export function getRunningJob() {
return running;
}
+/**
+ * Lane occupancy and queue depth, reported by the queue itself.
+ *
+ * The lane split (serialized GPU vs. parallel cloud-CLI vs. parallel remote)
+ * and each lane's slot count are private to this module, so a caller that
+ * counted `listJobs()` by hand would have to re-derive `jobLane` and would
+ * drift from it the first time a new cloud mode is added. Capacity questions
+ * are answered here for the same reason `isRemoteMediaJob` has one definition.
+ *
+ * `limit` is the lane's configured concurrency, NOT a queue bound: work over
+ * the limit waits rather than being rejected. The federated-provider admission
+ * bound is a separate setting (see federatedMediaProvider.js).
+ *
+ * @returns {{lanes: Record<'gpu'|'cloud'|'remote', {running: number, queued: number, limit: number}>,
+ * byKind: Record<string, {running: number, queued: number}>,
+ * totals: {running: number, queued: number},
+ * runningKind: string|null}}
+ */
+export function getQueueCapacity() {
+ const lanes = {
+ gpu: { running: running ? 1 : 0, queued: 0, limit: 1 },
+ cloud: { running: cloudRunning.length, queued: 0, limit: codexParallelLimit },
+ remote: { running: remoteRunning.length, queued: 0, limit: REMOTE_MEDIA_PARALLEL_LIMIT },
+ };
+ // Seed every known kind so a lane with no work reports 0 rather than being
+ // absent — an absent key and a zero read identically in a UI, and only one
+ // of them is true.
+ const byKind = Object.fromEntries(JOB_KINDS.map((kind) => [kind, { running: 0, queued: 0 }]));
+ // Lane `running` counts come straight off the lane arrays above; only the
+ // shared `queue` has to be classified, because it holds every lane's waiting
+ // work in one submission-ordered list.
+ for (const job of queue) {
+ lanes[jobLane(job)].queued += 1;
+ if (byKind[job.kind]) byKind[job.kind].queued += 1;
+ }
+ for (const job of [...(running ? [running] : []), ...cloudRunning, ...remoteRunning]) {
+ if (byKind[job.kind]) byKind[job.kind].running += 1;
+ }
+ return {
+ lanes,
+ byKind,
+ totals: {
+ running: lanes.gpu.running + lanes.cloud.running + lanes.remote.running,
+ queued: queue.length,
+ },
+ runningKind: running?.kind ?? null,
+ };
+}
+
export function listJobs({ status, kind, owner } = {}) {
const all = [
...(running ? [running] : []),
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index f4c02ae236..a1323eca58 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -182,6 +182,65 @@ describe('mediaJobQueue', () => {
expect(r2.position).toBe(2);
});
+ describe('getQueueCapacity', () => {
+ it('separates the serialized GPU lane from the parallel remote lane', async () => {
+ // Both lanes run concurrently, so a remote job must NOT be reported as
+ // waiting behind the local GPU render — that conflation is what made two
+ // idle peers each read as busy while waiting on the other.
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ stubs.generateAudioRemote.mockImplementation(() => new Promise(() => {}));
+ mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local' } });
+ mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'waiting' } });
+ mediaJobQueue.enqueueJob({
+ kind: 'audio',
+ params: {
+ prompt: '',
+ engine: 'remote-audio',
+ modelId: 'example/model',
+ remoteMedia: remoteMediaParams(),
+ },
+ });
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1
+ && stubs.generateAudioRemote.mock.calls.length === 1);
+
+ const capacity = mediaJobQueue.getQueueCapacity();
+ // The remote render runs concurrently with the local one and the second
+ // video still waits — the remote job neither occupies the GPU lane nor
+ // queues behind it.
+ expect(capacity.lanes.gpu).toMatchObject({ running: 1, queued: 1, limit: 1 });
+ expect(capacity.lanes.remote).toMatchObject({ running: 1, queued: 0 });
+ expect(capacity.runningKind).toBe('video');
+ expect(capacity.totals).toEqual({ running: 2, queued: 1 });
+ });
+
+ it('counts queue depth per kind', async () => {
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ mediaJobQueue.enqueueJob({ kind: 'image', params: {} });
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
+
+ const { byKind } = mediaJobQueue.getQueueCapacity();
+ expect(byKind.video).toEqual({ running: 1, queued: 1 });
+ expect(byKind.image).toEqual({ running: 0, queued: 1 });
+ });
+
+ // An absent key and a zero read identically in a UI, and only one of them
+ // is true — every known kind must be present even with no work.
+ it('reports every known kind on an empty queue', () => {
+ const { byKind, totals, runningKind } = mediaJobQueue.getQueueCapacity();
+ expect(Object.keys(byKind).sort()).toEqual([...mediaJobQueue.JOB_KINDS].sort());
+ expect(Object.values(byKind).every((c) => c.running === 0 && c.queued === 0)).toBe(true);
+ expect(totals).toEqual({ running: 0, queued: 0 });
+ expect(runningKind).toBeNull();
+ });
+
+ it('reports the remote lane bound', () => {
+ expect(mediaJobQueue.getQueueCapacity().lanes.remote.limit)
+ .toBe(mediaJobQueue.REMOTE_MEDIA_PARALLEL_LIMIT);
+ });
+ });
+
it('rejects unknown kinds', () => {
expect(() => mediaJobQueue.enqueueJob({ kind: 'bogus', params: {} })).toThrow(/invalid kind/);
});