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

address self-review: report the lane a federated job runs in, not a sum of lanes

[._.]/ Adam Eivyf674f6300761
diff --git a/client/src/components/instances/PeerMediaProviderPanel.jsx b/client/src/components/instances/PeerMediaProviderPanel.jsx
index 570b117b58..e29ef1f4a7 100644
--- a/client/src/components/instances/PeerMediaProviderPanel.jsx
+++ b/client/src/components/instances/PeerMediaProviderPanel.jsx
@@ -48,7 +48,7 @@ export default function PeerMediaProviderPanel({ peer, onRefresh }) {
// eslint-disable-next-line react-hooks/exhaustive-deps
[config.raw, capabilities],
);
- const queueSummary = useMemo(() => summarizePeerMediaQueue(readiness.queue), [readiness.queue]);
+ const queueSegments = summarizePeerMediaQueue(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
@@ -120,12 +120,10 @@ export default function PeerMediaProviderPanel({ peer, onRefresh }) {
{config.enabled && (
<>
- {queueSummary.slots && (
+ {queueSegments.length > 0 && (
<div className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[10px] text-gray-500">
<Gauge size={11} className="shrink-0" />
- <span>{queueSummary.slots} active</span>
- {queueSummary.drain && <span>· runs {queueSummary.drain}</span>}
- {queueSummary.kinds.length > 0 && <span>· {queueSummary.kinds.join(' · ')}</span>}
+ <span>{queueSegments.join(' · ')}</span>
</div>
)}
diff --git a/client/src/components/instances/PeerMediaProviderPanel.test.jsx b/client/src/components/instances/PeerMediaProviderPanel.test.jsx
index f7b65630da..263065783b 100644
--- a/client/src/components/instances/PeerMediaProviderPanel.test.jsx
+++ b/client/src/components/instances/PeerMediaProviderPanel.test.jsx
@@ -75,14 +75,13 @@ describe('PeerMediaProviderPanel', () => {
mediaProvider: { enabled: true, audioModels: [] },
mediaProviderStatus: withQueue({
concurrency: 2,
- byKind: { audio: { running: 1, queued: 2 }, image: { running: 0, queued: 0 }, video: { running: 0, queued: 0 } },
+ byKind: { audio: { running: 1, queued: 2 } },
}),
};
render(<PeerMediaProviderPanel peer={peer} onRefresh={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: /Remote media provider/i }));
- expect(screen.getByText(/runs 2 at a time/i)).toBeInTheDocument();
- expect(screen.getByText(/audio 1 running, 2 queued/i)).toBeInTheDocument();
+ expect(screen.getByText(/runs 2 at a time · audio 1 running, 2 queued/i)).toBeInTheDocument();
// An idle kind is omitted, not rendered as a zero.
expect(screen.queryByText(/(image|video) \d/i)).not.toBeInTheDocument();
});
diff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsx
index 0a72c2d69a..b8e43fc77d 100644
--- a/client/src/components/music/MusicGenPanel.jsx
+++ b/client/src/components/music/MusicGenPanel.jsx
@@ -33,6 +33,10 @@ import {
listMusicEngines, getInstances, generateMusic, installAudioModel, removeAudioModel, getActiveProcessing, getMediaJob, getTrack, cancelMediaJob,
} from '../../services/api';
import { formatDownloadGb } from '../../utils/formatters';
+import {
+ resolvePeerMediaReadiness,
+ summarizePeerMediaQueue,
+} from '../../lib/federatedMediaReadiness.js';
import RuntimeInstallModal from '../install/RuntimeInstallModal';
/**
@@ -479,7 +483,12 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
const selectedUserModel = engine?.models?.find((m) => m.id === modelId && m.userAdded);
const showRuntimeInstallHint = !isRemote && !!engine && (!engine.ready || !selectedModelReady) && (!!prompt?.trim() || userSelectedEngine);
- const remoteStatus = selectedRemotePeer?.mediaProviderStatus;
+ // The same resolver the Instances card and System Health use, rather than
+ // reading `state` off the stored probe: a snapshot recorded as `ready` keeps
+ // saying so after its freshness window closes, and this is the surface where
+ // the user actually commits a render to that peer.
+ const remoteReadiness = selectedRemotePeer ? resolvePeerMediaReadiness(selectedRemotePeer) : null;
+ const remoteQueueSegments = remoteReadiness ? summarizePeerMediaQueue(remoteReadiness.queue) : [];
return (
<div className="space-y-2 border border-port-border rounded-lg p-3 bg-port-bg/40">
@@ -522,11 +531,10 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
</select>
</label>
<p className="text-[11px] text-gray-400">
- {remoteStatus?.state === 'ready' && remoteStatus.snapshot?.queue
- ? `${remoteStatus.snapshot.queue.running} running · ${remoteStatus.snapshot.queue.queued} queued`
- : remoteStatus?.state === 'stale'
- ? 'Capacity is stale; remote generation is blocked until the peer reports fresh status.'
- : 'Remote generation requires a ready, authenticated peer with fresh capacity.'}
+ {remoteReadiness?.state === 'ready' && remoteQueueSegments.length > 0
+ ? remoteQueueSegments.join(' · ')
+ : remoteReadiness?.help
+ || 'Remote generation requires a ready, authenticated peer with fresh capacity.'}
</p>
<div className="grid grid-cols-2 gap-2">
{(['style', 'mood', 'tempo', 'energy']).map((field) => (
diff --git a/client/src/components/system-resources/MediaCapacityPanel.jsx b/client/src/components/system-resources/MediaCapacityPanel.jsx
index 3ebfefba6e..d8820eec34 100644
--- a/client/src/components/system-resources/MediaCapacityPanel.jsx
+++ b/client/src/components/system-resources/MediaCapacityPanel.jsx
@@ -45,7 +45,7 @@ function LaneRow({ label, help, lane }) {
function PeerRow({ peer }) {
const readiness = resolvePeerMediaReadiness(peer);
- const queue = summarizePeerMediaQueue(readiness.queue);
+ const queueSegments = summarizePeerMediaQueue(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">
@@ -58,9 +58,7 @@ function PeerRow({ peer }) {
{readiness.kinds.length > 0
? <span>{readiness.kinds.join(' · ')}</span>
: <span>no models allowlisted</span>}
- {queue.slots && <span>{queue.slots}</span>}
- {queue.drain && <span>{queue.drain}</span>}
- {queue.kinds.length > 0 && <span>{queue.kinds.join(' · ')}</span>}
+ {queueSegments.length > 0 && <span>{queueSegments.join(' · ')}</span>}
{readiness.checkedAt && <span>checked {timeAgo(readiness.checkedAt)}</span>}
</div>
{readiness.help && (
diff --git a/client/src/components/system-resources/MediaCapacityPanel.test.jsx b/client/src/components/system-resources/MediaCapacityPanel.test.jsx
index 039547621e..30359046a8 100644
--- a/client/src/components/system-resources/MediaCapacityPanel.test.jsx
+++ b/client/src/components/system-resources/MediaCapacityPanel.test.jsx
@@ -91,7 +91,7 @@ describe('MediaCapacityPanel', () => {
renderPanel();
expect(await screen.findByText('render-box')).toBeInTheDocument();
expect(screen.getByText('ready')).toBeInTheDocument();
- expect(screen.getByText('1 running · 0 queued · 1/4 slots')).toBeInTheDocument();
+ expect(screen.getByText('1 running · 0 queued · 1/4 slots active')).toBeInTheDocument();
});
// The local lanes above already show running/limit; a peer row that could only
@@ -106,15 +106,14 @@ describe('MediaCapacityPanel', () => {
queue: {
running: 1, queued: 0, totalActive: 1, maxQueuedJobs: 4, accepting: true,
concurrency: 4,
- byKind: { audio: { running: 1, queued: 0 }, image: { running: 0, queued: 0 }, video: { running: 0, queued: 0 } },
+ byKind: { audio: { running: 1, queued: 0 } },
},
capabilities: [],
},
},
})] });
renderPanel();
- expect(await screen.findByText('4 at a time')).toBeInTheDocument();
- expect(screen.getByText('audio 1 running')).toBeInTheDocument();
+ expect(await screen.findByText(/runs 4 at a time · audio 1 running/)).toBeInTheDocument();
});
// An older provider sends neither field. The row drops the segments rather
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 8f0d14d5bd..daf09ce155 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -44,7 +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`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block — slot occupancy, how many jobs drain in parallel, and which kinds are busy — dropping any segment an older provider did not send rather than showing it as a zero. Display only — the server re-probes and fail-closes before any job leaves. |
+| `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`. `summarizePeerMediaQueue(queue)` renders the peer’s queue block into finished display segments — slot occupancy, how many jobs drain in parallel, and which kinds are busy — so every surface shows the same words, dropping any segment an older provider did not send rather than showing it as a zero. 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
index 08dc7783b8..56be71deb7 100644
--- a/client/src/lib/federatedMediaReadiness.js
+++ b/client/src/lib/federatedMediaReadiness.js
@@ -72,6 +72,9 @@ const PEER_OFFLINE = Object.freeze({ label: 'peer offline', tone: 'warning' });
// 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([]);
+// A peer with no snapshot yet is the common case on a fresh instance, and its
+// row re-renders on every 15s poll — no reason to allocate a fresh empty array.
+const NO_QUEUE_SEGMENTS = Object.freeze([]);
const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);
// NUL separator, matching the server's own model key: a printable separator
@@ -130,54 +133,45 @@ function verifiedState(status, now) {
return state;
}
-// Same rationale as NO_CAPABILITIES, for the queue summary's kind list.
-const NO_KIND_SUMMARY = Object.freeze([]);
const isCount = (value) => Number.isInteger(value) && value >= 0;
/**
- * The peer's queue block as a display summary, shared by both surfaces.
+ * The peer's queue block as finished display segments.
*
- * `concurrency` and `byKind` reached the wire after v1 shipped (#4348), so an
- * older provider omits them and every segment here is independently optional —
- * a missing field is dropped rather than rendered as a zero, which would claim
- * an idle lane the peer never reported. `slots` stays first because it is the
- * one segment every provider has always sent.
+ * Returns the rendered phrases rather than the numbers behind them, so every
+ * surface shows the same words — a lib that stopped at "3/4 slots" and left
+ * each caller to append its own connective would reintroduce, one layer down,
+ * exactly the disagreement this module exists to prevent.
+ *
+ * `concurrency` and `byKind` reached the wire after v1 shipped (#4348): an
+ * older provider omits them, so their segments are dropped rather than shown as
+ * a zero that would claim an idle lane the peer never reported on.
*
* @param {object|null} queue - `snapshot.queue` from a probed peer
- * @returns {{slots: string|null, drain: string|null, kinds: string[]}}
+ * @returns {string[]} segments to render in order, possibly empty
*/
export function summarizePeerMediaQueue(queue) {
- if (!isRecord(queue)) return { slots: null, drain: null, kinds: NO_KIND_SUMMARY };
- const slots = isCount(queue.running) && isCount(queue.queued)
- && isCount(queue.totalActive) && isCount(queue.maxQueuedJobs)
- ? `${queue.running} running · ${queue.queued} queued · ${queue.totalActive}/${queue.maxQueuedJobs} slots`
- : null;
- // "How fast does that backlog drain?", which queue depth alone cannot answer:
- // two jobs ahead on a 1-wide lane is a very different wait from two on a
- // 10-wide one.
- const drain = Number.isInteger(queue.concurrency) && queue.concurrency > 0
- ? `${queue.concurrency} at a time`
- : null;
- // Only kinds actually occupying a lane. Listing three zeroes crowds out the
- // one number that matters, and the `slots` segment above already reports
- // whether anything is running at all.
- const byKind = isRecord(queue.byKind) ? queue.byKind : null;
- const kinds = byKind
- ? FEDERATED_MEDIA_KINDS
- .map(({ kind, label }) => {
- const entry = byKind[kind];
- if (!isRecord(entry)) return null;
- const running = isCount(entry.running) ? entry.running : 0;
- const queued = isCount(entry.queued) ? entry.queued : 0;
- if (running + queued === 0) return null;
- const parts = [];
- if (running > 0) parts.push(`${running} running`);
- if (queued > 0) parts.push(`${queued} queued`);
- return `${label} ${parts.join(', ')}`;
- })
- .filter(Boolean)
- : NO_KIND_SUMMARY;
- return { slots, drain, kinds: kinds.length > 0 ? kinds : NO_KIND_SUMMARY };
+ if (!isRecord(queue)) return NO_QUEUE_SEGMENTS;
+ const segments = [];
+ if (isCount(queue.running) && isCount(queue.queued)
+ && isCount(queue.totalActive) && isCount(queue.maxQueuedJobs)) {
+ segments.push(`${queue.running} running · ${queue.queued} queued · ${queue.totalActive}/${queue.maxQueuedJobs} slots active`);
+ }
+ if (isCount(queue.concurrency) && queue.concurrency > 0) {
+ segments.push(`runs ${queue.concurrency} at a time`);
+ }
+ // The provider reports only the kinds holding a lane, so every entry here has
+ // work in it; a kind that is idle is simply absent.
+ const byKind = isRecord(queue.byKind) ? queue.byKind : {};
+ for (const { kind, label } of FEDERATED_MEDIA_KINDS) {
+ const entry = byKind[kind];
+ if (!isRecord(entry) || !isCount(entry.running) || !isCount(entry.queued)) continue;
+ const parts = [];
+ if (entry.running > 0) parts.push(`${entry.running} running`);
+ if (entry.queued > 0) parts.push(`${entry.queued} queued`);
+ if (parts.length > 0) segments.push(`${label} ${parts.join(', ')}`);
+ }
+ return segments;
}
/**
diff --git a/client/src/lib/federatedMediaReadiness.test.js b/client/src/lib/federatedMediaReadiness.test.js
index 9cef0aae24..4d9be95429 100644
--- a/client/src/lib/federatedMediaReadiness.test.js
+++ b/client/src/lib/federatedMediaReadiness.test.js
@@ -193,45 +193,37 @@ describe('summarizePeerMediaQueue', () => {
totalActive: 2, providerActive: 1, queued: 1, running: 1, maxQueuedJobs: 4, accepting: true, ...overrides,
});
- it('renders slots, drain rate, and only the kinds actually occupying a lane', () => {
- const summary = summarizePeerMediaQueue(queue({
+ it('renders slots, drain rate, and every kind holding a lane', () => {
+ expect(summarizePeerMediaQueue(queue({
concurrency: 2,
- byKind: {
- audio: { running: 1, queued: 1 },
- image: { running: 0, queued: 1 },
- video: { running: 0, queued: 0 },
- },
- }));
- expect(summary.slots).toBe('1 running · 1 queued · 2/4 slots');
- expect(summary.drain).toBe('2 at a time');
- expect(summary.kinds).toEqual(['audio 1 running, 1 queued', 'image 1 queued']);
+ byKind: { audio: { running: 1, queued: 1 }, image: { running: 0, queued: 1 } },
+ }))).toEqual([
+ '1 running · 1 queued · 2/4 slots active',
+ 'runs 2 at a time',
+ 'audio 1 running, 1 queued',
+ 'image 1 queued',
+ ]);
});
// An older provider sends neither field. Rendering the absence as a zero
// would claim idle lanes the peer never reported on.
it('drops the segments an older provider never sent instead of showing zeroes', () => {
- const summary = summarizePeerMediaQueue(queue());
- expect(summary.slots).toBe('1 running · 1 queued · 2/4 slots');
- expect(summary.drain).toBeNull();
- expect(summary.kinds).toEqual([]);
+ expect(summarizePeerMediaQueue(queue())).toEqual(['1 running · 1 queued · 2/4 slots active']);
});
- it('drops a concurrency that is absent, zero, or not a whole count', () => {
- expect(summarizePeerMediaQueue(queue({ concurrency: 0 })).drain).toBeNull();
- expect(summarizePeerMediaQueue(queue({ concurrency: 1.5 })).drain).toBeNull();
- expect(summarizePeerMediaQueue(queue({ concurrency: '4' })).drain).toBeNull();
+ it('drops a concurrency that claims no capacity', () => {
+ expect(summarizePeerMediaQueue(queue({ concurrency: 0 }))).toHaveLength(1);
});
- it('omits a kind reporting no work rather than listing it as idle', () => {
- const summary = summarizePeerMediaQueue(queue({
+ // The provider omits an idle kind, but a build that sent one must not add a
+ // segment saying nothing.
+ it('omits a kind reporting no work', () => {
+ expect(summarizePeerMediaQueue(queue({
byKind: { audio: { running: 0, queued: 0 }, image: { running: 2, queued: 0 } },
- }));
- expect(summary.kinds).toEqual(['image 2 running']);
+ }))).toEqual(['1 running · 1 queued · 2/4 slots active', 'image 2 running']);
});
- it('reports no slot line at all when the queue block is missing or malformed', () => {
- for (const bad of [null, undefined, 'busy', queue({ maxQueuedJobs: null })]) {
- expect(summarizePeerMediaQueue(bad).slots).toBeNull();
- }
+ it('reports nothing at all when the queue block is missing', () => {
+ for (const bad of [null, undefined, 'busy']) expect(summarizePeerMediaQueue(bad)).toEqual([]);
});
});
diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.md
index 2404b692bc..47d91956ae 100644
--- a/docs/FEDERATED_MEDIA_PROVIDERS.md
+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md
@@ -315,6 +315,8 @@ CUDA has three states: `available`, `absent`, and `unknown`. A CUDA model is rea
The configured `maxQueuedJobs` is conservative: all queued/running work that consumes this machine's media resources counts against it. Outgoing proxy jobs are excluded because they consume another peer's capacity; counting them could make two idle peers report busy while waiting on each other.
+### Drain rate and per-kind occupancy
+
The queue block also reports how fast that backlog drains, because a depth alone
cannot say:
@@ -323,18 +325,25 @@ cannot say:
| `totalActive` | every queued/running local media job, including kinds this contract does not federate |
| `providerActive` / `queued` / `running` | the subset owned by federated callers |
| `maxQueuedJobs` | the admission bound `accepting` is computed against |
-| `concurrency` | how many of those active jobs actually run at once here |
-| `byKind` | per-kind `{running, queued}` for `audio`/`image`/`video` |
+| `concurrency` | how many jobs run at once on the lane a federated submission lands on |
+| `byKind` | `{running, queued}` for each negotiated kind currently holding a lane |
Two jobs ahead of a submission mean two renders' wait on a serialized lane and
-roughly none on a parallel one; `concurrency` is what tells those apart.
-`byKind` covers the federated kinds only, so it need not sum to `totalActive` —
-local work of an unfederated kind (LoRA training) occupies the same lanes.
-
-`concurrency` and `byKind` were added after wire v1 shipped, so both are
-optional: a provider on an older build omits them and a consumer must read the
-absence as **unknown**, never as zero. The UI drops the segment rather than
-rendering a lane as idle that the peer never reported on.
+roughly none on a parallel one; `concurrency` is what tells those apart. It is
+the width of the one lane a federated job runs in, **not** a sum across lanes —
+the lanes are alternatives, so a machine with a wide parallel cloud-CLI lane
+must not claim that width for GPU work that serializes. Every job this contract
+carries is a local-engine render, so today that is the serialized GPU lane.
+
+`byKind` lists only the negotiated kinds currently holding a lane; with the
+block present, an absent kind is idle. It need not sum to `totalActive`, which
+also counts local work of kinds this contract does not federate (LoRA training)
+occupying the same lanes.
+
+Both fields were added after wire v1 shipped, so both are optional: a provider
+on an older build omits them and a consumer must read that absence as
+**unknown**, never as zero. The UI drops the segment rather than rendering a
+lane as idle that the peer never reported on.
Status never includes prompts, lyrics, credentials, local paths, commission records, or private creative metadata.
diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.js
index df65c292cf..6a9026dc85 100644
--- a/server/lib/federatedMediaWire.js
+++ b/server/lib/federatedMediaWire.js
@@ -194,24 +194,18 @@ const federatedMediaQueueStatusSchema = z.object({
running: z.number().int().nonnegative(),
maxQueuedJobs: z.number().int().positive(),
accepting: z.boolean(),
- // Added after wire v1 shipped, so both are optional AND nullable: a provider
- // on an older build omits them, and reading an absent value as a number
- // would invent capacity that was never reported. `null`/absent means
- // "unknown", never "zero" — the sentinel rule in CLAUDE.md.
+ // Both added after wire v1 shipped, so both are optional: an older provider
+ // omits them, and absent must read as UNKNOWN rather than zero. See "Drain
+ // rate and per-kind occupancy" in docs/FEDERATED_MEDIA_PROVIDERS.md for what
+ // they mean and why queue depth alone could not answer it.
//
- // `concurrency` is how many of the reported active jobs actually run at
- // once here, which is what turns a queue depth into an expected wait: two
- // jobs ahead of you on a serialized lane is a very different answer from two
- // on a parallel one, and `maxQueuedJobs` alone cannot tell them apart.
+ // Bounded well above any lane width this build configures, so a provider with
+ // more or wider lanes than ours still validates.
concurrency: z.number().int().positive().max(64).nullable().optional(),
- // `byKind` covers the federated kinds only. `totalActive` legitimately
- // exceeds their sum: it also counts local media work of kinds this contract
- // does not federate (e.g. LoRA training), which occupies the same lanes.
- //
- // `partialRecord`, not `record`: a Zod 4 record over an enum key is
- // exhaustive, so the day a fourth kind joins KNOWN_MEDIA_KINDS every older
- // provider's three-kind payload would fail validation on a newer consumer.
- // The provider only ever reports the kinds the consumer negotiated anyway.
+ // Only the kinds actually holding a lane: with the block present, an absent
+ // kind is idle. `partialRecord`, not `record` — a Zod 4 record over an enum
+ // key is exhaustive, so the day a fourth kind joins KNOWN_MEDIA_KINDS every
+ // older provider's payload would fail validation on a newer consumer.
byKind: z.partialRecord(mediaKindSchema, federatedMediaKindOccupancySchema).optional(),
});
diff --git a/server/lib/federatedMediaWire.test.js b/server/lib/federatedMediaWire.test.js
index 91110adb78..1cce438ffb 100644
--- a/server/lib/federatedMediaWire.test.js
+++ b/server/lib/federatedMediaWire.test.js
@@ -186,7 +186,6 @@ describe('federated media status kind projection', () => {
byKind: {
audio: { running: 1, queued: 0 },
image: { running: 0, queued: 1 },
- video: { running: 0, queued: 0 },
},
},
}));
@@ -200,10 +199,10 @@ describe('federated media status kind projection', () => {
expect(parsed.queue.byKind).toBeUndefined();
});
- // The kind list is negotiated, so a provider legitimately reports fewer kinds
- // than the consumer knows about. A record that demanded every key would make
- // an audio-only projection unparseable the moment a fourth kind is added.
- it('accepts a byKind covering only the negotiated kinds', () => {
+ // The provider reports only the kinds holding a lane, and the kind list is
+ // negotiated besides. A record that demanded every key would make an
+ // audio-only projection unparseable the moment a fourth kind is added.
+ it('accepts a byKind covering only some kinds', () => {
expect(federatedMediaProviderStatusSchema.safeParse(status({
queue: { ...status().queue, byKind: { audio: { running: 1, queued: 0 } } },
})).success).toBe(true);
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index bda2b799af..2c6e7725ac 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -28,8 +28,8 @@ import {
cancelJob,
enqueueJob,
getJob,
- getQueueCapacity,
isRemoteMediaJob,
+ laneConcurrencyFor,
listJobs,
} from './mediaJobQueue/index.js';
import { listMusicEngineCapabilities } from './musicEngineCapabilities.js';
@@ -348,54 +348,54 @@ async function capabilitiesForKind(kind, config, { pythonPath = null } = {}) {
return [];
}
+// Every job this provider accepts is a local-engine render — buildQueueParams
+// deliberately omits `mode`, and the cloud-CLI backends are not federatable —
+// so the lane a submission lands on is decided by its kind alone. The queue
+// answers how wide that lane is; the minimum across the negotiated kinds is the
+// fail-closed reading if two kinds ever route differently.
+const federatedLaneConcurrency = (kinds) => Math.min(
+ ...kinds.map((kind) => laneConcurrencyFor({ kind, params: {} })),
+);
+
/**
- * How many of the locally-counted active jobs actually run at once here.
+ * Jobs occupying this machine's own generation lanes, and whether another fits.
*
- * `maxQueuedJobs` is an admission bound, not a rate: it says how much work this
- * provider will hold, not how fast that work drains. Two jobs ahead of a
- * submission mean two renders' wait on the serialized GPU lane and roughly none
- * on the parallel cloud-CLI lane, and a consumer reading only the queue depth
- * cannot tell those apart. Summing exactly the lanes `activeQueueSnapshot`
- * counts — the local generation lanes, never the outgoing proxy lane — keeps
- * the two numbers describing the same population.
+ * Outgoing proxy jobs consume a remote peer's capacity, not this provider's, so
+ * they are excluded — counting them can deadlock two otherwise-idle peers into
+ * both reporting busy while each waits on the other.
*/
-function localGenerationConcurrency() {
- const { lanes } = getQueueCapacity();
- return lanes.gpu.limit + lanes.cloud.limit;
-}
-
-function activeQueueSnapshot(config) {
- // Outgoing proxy jobs consume a remote peer's capacity, not this provider's
- // local generation resources. Counting them here can create a federation
- // deadlock where two otherwise-idle peers both report busy while waiting on
- // each other.
+function activeQueueSnapshot(config, kinds) {
const active = listJobs().filter((job) =>
ACTIVE_STATUSES.has(job.status) && !isRemoteMediaJob(job),
);
- const providerActive = active.filter((job) => job.owner?.startsWith(OWNER_PREFIX));
- // Seed every federated kind so an idle lane reports 0 rather than being
- // absent — an absent key and a zero read identically in a UI, and only one of
- // them is true. Derived from the same filtered list as the slot count, not
- // from getQueueCapacity().byKind, which also counts the outgoing proxy jobs
- // this snapshot deliberately excludes.
- const byKind = Object.fromEntries(
- KNOWN_MEDIA_KINDS.map((kind) => [kind, { running: 0, queued: 0 }]),
- );
+ let providerActive = 0;
+ let queued = 0;
+ let running = 0;
+ // Only the kinds the caller negotiated, and only those actually holding a
+ // lane: with the block present, an absent kind is idle. Derived from the same
+ // filtered list as the slot count rather than from getQueueCapacity().byKind,
+ // which also counts the outgoing proxy jobs excluded above.
+ const byKind = {};
for (const job of active) {
- // A local job of a kind this contract does not federate (LoRA training)
- // still occupies a lane, so it counts toward `totalActive` — it just has
- // no bucket of its own, which is why the two need not sum.
- const bucket = byKind[job.kind];
- if (bucket) bucket[job.status === 'running' ? 'running' : 'queued'] += 1;
+ if (job.owner?.startsWith(OWNER_PREFIX)) {
+ providerActive += 1;
+ if (job.status === 'running') running += 1; else queued += 1;
+ }
+ // Local work of a kind this contract does not federate (LoRA training) still
+ // holds a lane, so it counts toward `totalActive` while having no bucket —
+ // which is why the two need not sum.
+ if (!kinds.includes(job.kind)) continue;
+ const bucket = byKind[job.kind] ?? (byKind[job.kind] = { running: 0, queued: 0 });
+ bucket[job.status === 'running' ? 'running' : 'queued'] += 1;
}
return {
totalActive: active.length,
- providerActive: providerActive.length,
- queued: providerActive.filter((job) => job.status === 'queued').length,
- running: providerActive.filter((job) => job.status === 'running').length,
+ providerActive,
+ queued,
+ running,
maxQueuedJobs: config.maxQueuedJobs,
accepting: active.length < config.maxQueuedJobs,
- concurrency: localGenerationConcurrency(),
+ concurrency: federatedLaneConcurrency(kinds),
byKind,
};
}
@@ -416,7 +416,7 @@ export async function getFederatedMediaProviderStatus(config, { kinds = ['audio'
const capabilities = (await Promise.all(
requestedKinds.map((kind) => capabilitiesForKind(kind, config, { pythonPath })),
)).flat();
- const queue = activeQueueSnapshot(config);
+ const queue = activeQueueSnapshot(config, requestedKinds);
const anyReady = capabilities.some((capability) => capability.ready);
return {
wireVersion: FEDERATED_MEDIA_WIRE_VERSION,
@@ -594,7 +594,7 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
return { replayed: true, job: await describeFederatedMediaJob(callerId, existing) };
}
- const queue = activeQueueSnapshot(config);
+ const queue = activeQueueSnapshot(config, [input.kind]);
if (!queue.accepting) {
unavailable('Provider queue is at capacity', 'MEDIA_PROVIDER_BUSY', 429, {
retryable: true,
diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.js
index 17a25739f7..c68100ea77 100644
--- a/server/services/federatedMediaProvider.test.js
+++ b/server/services/federatedMediaProvider.test.js
@@ -13,7 +13,7 @@ const state = vi.hoisted(() => ({
imageModels: [],
videoModels: [],
cachedRepos: new Set(),
- queueCapacity: null,
+ cloudLaneLimit: 3,
}));
vi.mock('./settings.js', () => ({
@@ -54,7 +54,9 @@ vi.mock('./musicEngineCapabilities.js', () => ({
vi.mock('./mediaJobQueue/index.js', () => ({
listJobs: vi.fn(() => state.jobs),
- getQueueCapacity: vi.fn(() => state.queueCapacity),
+ // Mirrors the real lane routing: a federated job never sets a cloud `mode`,
+ // so every kind this contract carries lands on the serialized GPU lane.
+ laneConcurrencyFor: vi.fn((job) => (job?.params?.mode ? state.cloudLaneLimit : 1)),
isRemoteMediaJob: (job) => job?.kind === 'audio' && job.params?.remoteMedia !== undefined,
getJob: vi.fn((id) => state.jobs.find((job) => job.id === id) || null),
enqueueJob: vi.fn(({ kind, owner, params }) => {
@@ -153,11 +155,7 @@ beforeEach(() => {
state.imageModels = [];
state.videoModels = [];
state.cachedRepos = new Set();
- // Mirrors getQueueCapacity()'s real shape: a serialized GPU lane, a parallel
- // cloud-CLI lane, and the outgoing proxy lane the provider must ignore.
- state.queueCapacity = {
- lanes: { gpu: { running: 0, queued: 0, limit: 1 }, cloud: { running: 0, queued: 0, limit: 3 }, remote: { running: 0, queued: 0, limit: 20 } },
- };
+ state.cloudLaneLimit = 3;
__resetFederatedMediaProviderForTests();
});
@@ -215,11 +213,13 @@ describe('federated media provider capacity and idempotency', () => {
});
});
- it('reports the local generation concurrency behind the queue depth', async () => {
+ // The bug this replaced: summing every local lane told an audio-only provider
+ // it "runs 4 at a time" because the parallel cloud-CLI lane is wide, when its
+ // music renders serialize one at a time.
+ it('reports the lane a federated job actually lands on, not a whole-machine sum', async () => {
+ state.cloudLaneLimit = 10;
const status = await getFederatedMediaProviderStatus(config());
- // GPU (1) + cloud CLI (3). The 20-wide outgoing proxy lane is excluded for
- // the same reason its jobs are: it renders on someone else's hardware.
- expect(status.queue.concurrency).toBe(4);
+ expect(status.queue.concurrency).toBe(1);
});
it('breaks the shared queue down by federated kind, excluding outgoing proxy jobs', async () => {
@@ -237,18 +237,20 @@ describe('federated media provider capacity and idempotency', () => {
expect(status.queue.byKind).toEqual({
audio: { running: 1, queued: 1 },
image: { running: 0, queued: 1 },
- video: { running: 0, queued: 0 },
});
+ // The training job holds a lane but has no bucket, which is why byKind
+ // need not sum to totalActive.
expect(status.queue.totalActive).toBe(4);
});
- it('seeds an idle kind with zeroes rather than omitting it', async () => {
+ // Reporting image/video occupancy to a consumer that negotiated audio only
+ // would leave byKind as the one part of the payload the kind projection does
+ // not govern.
+ it('scopes the per-kind breakdown to the negotiated kinds', async () => {
+ state.jobs = [{ id: 'a', kind: 'image', status: 'running', owner: null }];
const status = await getFederatedMediaProviderStatus(config());
- expect(status.queue.byKind).toEqual({
- audio: { running: 0, queued: 0 },
- image: { running: 0, queued: 0 },
- video: { running: 0, queued: 0 },
- });
+ expect(status.queue.byKind).toEqual({});
+ expect(status.queue.totalActive).toBe(1);
});
it('queues allowlisted audio without exposing the prompt in its response', async () => {
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index a4e245ffb5..9d9956c065 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -318,11 +318,37 @@ export function getRunningJob() {
* totals: {running: number, queued: number},
* runningKind: string|null}}
*/
+// One definition of each lane's slot count, shared by getQueueCapacity and
+// laneConcurrencyFor so a caller can never read a limit this module has moved.
+const laneLimits = () => ({
+ gpu: 1,
+ cloud: codexParallelLimit,
+ remote: REMOTE_MEDIA_PARALLEL_LIMIT,
+});
+
+/**
+ * How many jobs like `job` run at once here — the slot count of the lane
+ * `jobLane` would route it to.
+ *
+ * Exported for the same reason `getQueueCapacity` is: the lane split is private
+ * to this module, so a caller asking "how fast would this drain?" must not
+ * answer it by naming lanes. Summing limits by hand also gives the wrong
+ * number — the lanes are alternatives, not a pool, so a machine whose parallel
+ * cloud-CLI lane is wide would claim that width for GPU work that serializes.
+ *
+ * @param {{kind: string, params?: object}} job - a real or prospective job
+ * @returns {number} the lane's configured concurrency
+ */
+export function laneConcurrencyFor(job) {
+ return laneLimits()[jobLane(job)];
+}
+
export function getQueueCapacity() {
+ const limits = laneLimits();
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 },
+ gpu: { running: running ? 1 : 0, queued: 0, limit: limits.gpu },
+ cloud: { running: cloudRunning.length, queued: 0, limit: limits.cloud },
+ remote: { running: remoteRunning.length, queued: 0, limit: limits.remote },
};
// 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
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 3ddcebdc1e..b4596f2e42 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
// The queue persists to data/media-jobs.json. Steer it at a temp dir so each
// test gets a clean slate without scribbling over the real data dir.
@@ -241,6 +242,29 @@ describe('mediaJobQueue', () => {
});
});
+ describe('laneConcurrencyFor', () => {
+ // The lanes are alternatives, not a pool: a caller that summed their limits
+ // would claim the wide cloud-CLI width for GPU work that serializes.
+ it('answers with the lane the job would run in, never a total', () => {
+ const { lanes } = mediaJobQueue.getQueueCapacity();
+ expect(mediaJobQueue.laneConcurrencyFor({ kind: 'audio', params: {} })).toBe(lanes.gpu.limit);
+ expect(mediaJobQueue.laneConcurrencyFor({ kind: 'image', params: {} })).toBe(lanes.gpu.limit);
+ expect(mediaJobQueue.laneConcurrencyFor({
+ kind: 'image', params: { mode: IMAGE_GEN_MODE.CODEX },
+ })).toBe(lanes.cloud.limit);
+ expect(mediaJobQueue.laneConcurrencyFor({
+ kind: 'audio', params: { remoteMedia: remoteMediaParams() },
+ })).toBe(mediaJobQueue.REMOTE_MEDIA_PARALLEL_LIMIT);
+ });
+
+ it('tracks the cloud lane limit as configured rather than a snapshot of it', () => {
+ mediaJobQueue.setCodexParallelLimit(5);
+ expect(mediaJobQueue.laneConcurrencyFor({
+ kind: 'image', params: { mode: IMAGE_GEN_MODE.CODEX },
+ })).toBe(5);
+ });
+ });
+
it('rejects unknown kinds', () => {
expect(() => mediaJobQueue.enqueueJob({ kind: 'bogus', params: {} })).toThrow(/invalid kind/);
});