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

fix: do not gate on an unavailable local provider, and refuse Run-now up front (#4834)

[._.]/ Adam Eivy29d5ba40fd49
diff --git a/server/services/cos.js b/server/services/cos.js
index 21a52b7342..3d7882dbc1 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -147,7 +147,7 @@ import {
// guards instead of a local replica. The async tiers stay here as
// `spawnDequeuePriorityN(ctx)` helpers.
import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';
-import { buildLocalEndpointSlotContext } from './cosLocalEndpointSlots.js';
+import { buildLocalEndpointSlotContext, localEndpointCapacityError } from './cosLocalEndpointSlots.js';
/**
* Get current CoS status
@@ -591,6 +591,16 @@ export async function forceSpawnTask(taskId) {
return { error: resolution.error };
}
+ // Same reason as the resolution pre-check above: the local-endpoint cap
+ // (#4834) is enforced later, inside the `task:ready` listener, so without this
+ // "Run now" would toast "Spawning" for a task the chokepoint immediately holds
+ // as pending. Checked against the RESOLVED provider (post-fallback), so it
+ // never refuses a run that would have swapped to a cloud provider anyway.
+ const localCapacityError = await localEndpointCapacityError(resolution.provider, state.agents);
+ if (localCapacityError) {
+ return { error: localCapacityError };
+ }
+
cosEvents.emit('task:ready', { ...task, taskType: task.taskType || 'internal' });
return { success: true, taskId };
}
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index e7c01904ce..14fac6246e 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -714,6 +714,63 @@ describe('localEndpointOfProvider (#4834)', () => {
});
+describe('resolveLocalEndpoint — unavailable providers are not gated (#4834)', () => {
+ // A saturated LOCAL provider that is currently unavailable (rate-limited,
+ // cooling down, down) is not where the task lands: resolveAgentProviderAndModel
+ // swaps it for a fallback, often a cloud one. Gating on it anyway would hold
+ // the task behind a GPU it never touches — and nothing about that busy GPU
+ // would ever clear the hold, so the task starves.
+ const withAvailability = (available) => createLocalEndpointSlotContext({
+ providers: ALL_PROVIDERS,
+ activeProvider: CLOUD_PROVIDER,
+ isAvailable: (id) => available.includes(id),
+ });
+
+ it('resolves to null when the pinned local provider is unavailable', () => {
+ const slots = withAvailability(['anthropic']);
+ expect(slots.resolveLocalEndpoint(taskOnProvider('t', 'lmstudio-tui'))).toBeNull();
+ });
+
+ it('still gates the same provider once it is available again', () => {
+ const slots = withAvailability(['lmstudio-tui', 'anthropic']);
+ expect(slots.resolveLocalEndpoint(taskOnProvider('t', 'lmstudio-tui'))).toBe(LOCAL_ENDPOINT);
+ });
+
+ it('resolves to null when the ACTIVE local provider is unavailable', () => {
+ const slots = createLocalEndpointSlotContext({
+ providers: ALL_PROVIDERS,
+ activeProvider: LOCAL_TUI_PROVIDER,
+ isAvailable: () => false,
+ });
+ expect(slots.resolveLocalEndpoint(taskOnProvider('t'))).toBeNull();
+ });
+
+ it('does not starve a queued task behind an unavailable local endpoint', () => {
+ // End-to-end through the real tracker: one agent is running on the local
+ // endpoint, but the provider has since gone unavailable, so the queued task
+ // must dispatch (onto its fallback) instead of waiting forever.
+ const state = makeState({
+ maxConcurrentAgents: 5,
+ runningAgents: [makeRunningAgentOnProvider('lmstudio-tui')],
+ });
+ const slots = withAvailability(['anthropic']);
+ const capacity = createDequeueCapacity(state, {
+ localEndpointCounts: countRunningAgentsByLocalEndpoint(state.agents, slots.endpointForAgent),
+ localEndpointLimit: slots.limit,
+ resolveLocalEndpoint: slots.resolveLocalEndpoint,
+ });
+
+ const spawned = priorityDequeue(userBuckets([taskOnProvider('task-local-1', 'lmstudio-tui')]), capacity);
+ expect(spawned.map(t => t.id)).toEqual(['task-local-1']);
+ });
+
+ it('leaves a task with no resolvable provider ungated', () => {
+ const slots = createLocalEndpointSlotContext({ providers: [], activeProvider: null });
+ expect(slots.resolveLocalEndpoint(taskOnProvider('t'))).toBeNull();
+ expect(slots.resolveLocalEndpoint(taskOnProvider('t', 'ghost'))).toBeNull();
+ });
+});
+
describe('local-endpoint spawn reservations (#4834)', () => {
beforeEach(() => __resetLocalEndpointSpawnReservations());
@@ -1144,6 +1201,31 @@ describe('cos.js source — priority + capacity invariants', () => {
expect(LIFECYCLE_SRC).toMatch(/providerEndpoint:\s*provider\.endpoint\s*\|\|\s*null/);
});
+ it('forceSpawnTask refuses synchronously when the local endpoint is full (#4834)', () => {
+ // "Run now" returns before the spawn happens, so without its own check it
+ // would answer { success: true } and toast "Spawning" for a task the
+ // chokepoint immediately holds — the same lie the provider-resolution
+ // pre-check directly above it exists to prevent. It must run AFTER
+ // resolution so it reads the post-fallback provider.
+ const forceFn = extractFnBody(COS_SRC, COS_SRC.indexOf('export async function forceSpawnTask'));
+ expect(forceFn).toMatch(/localEndpointCapacityError\(resolution\.provider/);
+ expect(forceFn.indexOf('resolveAgentProviderAndModel'))
+ .toBeLessThan(forceFn.indexOf('localEndpointCapacityError'));
+ expect(forceFn.indexOf('localEndpointCapacityError'))
+ .toBeLessThan(forceFn.indexOf("cosEvents.emit('task:ready'"));
+ });
+
+ it('the gate ignores an UNAVAILABLE provider so a held task cannot starve (#4834)', () => {
+ // A saturated local provider that is down is not where the task lands —
+ // spawn swaps it for a fallback. Holding on it would wait on a GPU the task
+ // never touches, with nothing to clear the hold.
+ const SLOTS_SRC = readFileSync(join(__dirname, 'cosLocalEndpointSlots.js'), 'utf-8');
+ const ctxFn = extractFnBody(SLOTS_SRC, SLOTS_SRC.indexOf('export function createLocalEndpointSlotContext'));
+ expect(ctxFn).toMatch(/if \(!isAvailable\(provider\.id\)\) return null;/);
+ expect(SLOTS_SRC, 'the live context must use the real provider-status predicate')
+ .toMatch(/isAvailable:\s*isProviderAvailable/);
+ });
+
it('idle generator is fenced by spawned===0 / tasksToSpawn.length===0', () => {
// Pin the strict-idle gate. If a refactor drops either fence, idle could
// spawn alongside autoSystem/mission and double-load the agent pool.
diff --git a/server/services/cosLocalEndpointSlots.js b/server/services/cosLocalEndpointSlots.js
index 70cb743fdf..21450852f7 100644
--- a/server/services/cosLocalEndpointSlots.js
+++ b/server/services/cosLocalEndpointSlots.js
@@ -24,6 +24,7 @@
import { isLocalEndpoint, LOCAL_LLM_MAX_CONCURRENCY } from '../lib/promptRunner.js';
import { listProviders, getActiveProvider } from './providers.js';
+import { isProviderAvailable } from './providerStatus.js';
import { countRunningAgentsByLocalEndpoint } from './cosDequeue.js';
// One knob governs both paths — no new config key. A local box beefy enough to
@@ -55,13 +56,23 @@ export function localEndpointOfProvider(provider) {
* - `endpointForAgent(agent)` — the endpoint a RUNNING agent is occupying,
* from the `providerId` agentLifecycle stamps onto its metadata.
* - `resolveLocalEndpoint(task)` — the endpoint a QUEUED task would land on.
- * Mirrors `resolveAgentProviderAndModel`: a `metadata.provider` pin wins,
- * and an unknown pin falls back to the active provider exactly as spawn
- * does. A runtime fallback swap can still move a run to another provider —
- * this is avoidance, not a guarantee, and promptRunner's gate plus the OOM
- * nudge/fail-over remain the recovery half.
+ * Mirrors `resolveAgentProviderAndModel`: a `metadata.provider` pin wins, an
+ * unknown pin falls back to the active provider, and an UNAVAILABLE provider
+ * resolves to null because spawn will swap it for a fallback (often cloud) —
+ * gating on it would hold the task behind a GPU it is never going to touch,
+ * with nothing to clear the hold. A runtime fallback swap after that point
+ * can still move a run: this is avoidance, not a guarantee, and
+ * promptRunner's gate plus the OOM nudge/fail-over remain the recovery half.
+ *
+ * `isAvailable` is injected (rather than imported) so this stays pure and a
+ * test can drive the real resolver without provider-status module state.
*/
-export function createLocalEndpointSlotContext({ providers = [], activeProvider = null, limit = LOCAL_ENDPOINT_AGENT_LIMIT } = {}) {
+export function createLocalEndpointSlotContext({
+ providers = [],
+ activeProvider = null,
+ limit = LOCAL_ENDPOINT_AGENT_LIMIT,
+ isAvailable = () => true,
+} = {}) {
const byId = new Map();
for (const provider of providers) {
if (provider?.id) byId.set(provider.id, provider);
@@ -69,7 +80,14 @@ export function createLocalEndpointSlotContext({ providers = [], activeProvider
if (activeProvider?.id && !byId.has(activeProvider.id)) byId.set(activeProvider.id, activeProvider);
const endpointById = (id) => localEndpointOfProvider(byId.get(id));
- const activeEndpoint = localEndpointOfProvider(activeProvider);
+
+ // The provider a queued task would be resolved onto, before the availability
+ // check below. An unknown pin falls through to the active provider, exactly
+ // as `resolveAgentProviderAndModel` does.
+ const providerForTask = (task) => {
+ const pinnedId = task?.metadata?.provider;
+ return (pinnedId && byId.get(pinnedId)) || activeProvider;
+ };
return {
limit,
@@ -84,9 +102,14 @@ export function createLocalEndpointSlotContext({ providers = [], activeProvider
return providerId ? endpointById(providerId) : null;
},
resolveLocalEndpoint: (task) => {
- const pinnedId = task?.metadata?.provider;
- if (pinnedId) return byId.has(pinnedId) ? endpointById(pinnedId) : activeEndpoint;
- return activeEndpoint;
+ const provider = providerForTask(task);
+ if (!provider?.id) return null;
+ // An unavailable provider is NOT where this task lands — spawn swaps it
+ // for a fallback. Holding the task at this endpoint anyway would starve
+ // it: the fallback it actually wants may be cloud, and nothing about the
+ // busy GPU would ever clear the hold.
+ if (!isAvailable(provider.id)) return null;
+ return localEndpointOfProvider(provider);
},
};
}
@@ -101,7 +124,7 @@ export function createLocalEndpointSlotContext({ providers = [], activeProvider
export async function buildLocalEndpointSlotContext() {
const providers = await listProviders();
const activeProvider = await getActiveProvider().catch(() => null);
- return createLocalEndpointSlotContext({ providers, activeProvider });
+ return createLocalEndpointSlotContext({ providers, activeProvider, isAvailable: isProviderAvailable });
}
// ── In-flight spawn reservations ───────────────────────────────────────────
@@ -170,10 +193,36 @@ export async function acquireLocalEndpointSpawnSlot(task, agents) {
const endpoint = slots.resolveLocalEndpoint(task);
if (!endpoint) return { ok: true, release: NOOP_RELEASE };
- const running = countRunningAgentsByLocalEndpoint(agents, slots.endpointForAgent)[endpoint] || 0;
- const inFlight = running + pendingLocalEndpointSpawns(endpoint);
- if (inFlight >= slots.limit) {
- return { ok: false, reason: `local endpoint ${endpoint} is at capacity (${inFlight}/${slots.limit})` };
+ const { atCapacity, inFlight, limit } = readEndpointCapacity(endpoint, agents, slots);
+ if (atCapacity) {
+ return { ok: false, reason: `local endpoint ${endpoint} is at capacity (${inFlight}/${limit})` };
}
return { ok: true, release: reserveLocalEndpointSpawn(endpoint) };
}
+
+/** Running agents plus in-flight reservations on `endpoint`, against the cap. */
+function readEndpointCapacity(endpoint, agents, slots) {
+ const running = countRunningAgentsByLocalEndpoint(agents, slots.endpointForAgent)[endpoint] || 0;
+ const inFlight = running + pendingLocalEndpointSpawns(endpoint);
+ return { inFlight, limit: slots.limit, atCapacity: inFlight >= slots.limit };
+}
+
+/**
+ * Why a spawn on the ALREADY-RESOLVED `provider` must wait, or null when it may
+ * proceed.
+ *
+ * `forceSpawnTask` (the user's explicit "Run now") returns synchronously while
+ * the spawn happens later in a `task:ready` listener, so without this it would
+ * answer `{ success: true }` and toast "Spawning" for a dispatch the chokepoint
+ * immediately holds — the same lie the provider-resolution pre-check upstream of
+ * it exists to prevent. Takes the post-fallback provider, so it is strictly more
+ * accurate than the queued-task prediction in `resolveLocalEndpoint`.
+ */
+export async function localEndpointCapacityError(provider, agents) {
+ const endpoint = localEndpointOfProvider(provider);
+ if (!endpoint) return null;
+ const slots = await buildLocalEndpointSlotContext();
+ const { atCapacity, inFlight, limit } = readEndpointCapacity(endpoint, agents, slots);
+ if (!atCapacity) return null;
+ return `Local inference endpoint ${endpoint} is at capacity (${inFlight}/${limit}) — wait for a running agent to finish`;
+}
diff --git a/server/services/subAgentSpawner.dispatchHolds.test.js b/server/services/subAgentSpawner.dispatchHolds.test.js
index b6692efa16..fd2d6ce738 100644
--- a/server/services/subAgentSpawner.dispatchHolds.test.js
+++ b/server/services/subAgentSpawner.dispatchHolds.test.js
@@ -1,8 +1,8 @@
/**
- * The two dispatch HOLDS at the `task:ready` chokepoint, and what releases them.
+ * The three dispatch HOLDS at the `task:ready` chokepoint, and what releases them.
*
- * Both leave the task queued for a condition that clears on its own, rather than
- * failing it:
+ * Each leaves the task queued for a condition that clears on its own, rather
+ * than failing it:
*
* - Runner down. `portos-cos` is a separate PM2 app the user can stop from the
* Apps page, and in runner mode it owns every agent process. Dispatching into
@@ -14,6 +14,10 @@
* pull / submodule update / npm install before `pm2 delete`. An agent spawned
* in that window is severed by the restart.
*
+ * - Local inference endpoint at capacity (issue #4834). A CoS agent runs a
+ * vendor CLI that talks to the local model server directly, so promptRunner's
+ * in-flight gate never sees it; two agents at one GPU takes an accelerator
+ * OOM. The slot is reserved across the spawn window and released after.
* The holds live in that listener, not inside `runAgentSpawn`, because a hold
* below the spawn body's entry returns past `releaseAppReviewMarker` and strands
* the synthetic "in review" marker for the whole outage (issue #989). The side
@@ -51,6 +55,14 @@ vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn() }));
vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./updateChecker.js', () => ({ isUpdateInProgress: vi.fn().mockReturnValue(false) }));
vi.mock('./missions.js', () => ({ releaseMissionSubTask: vi.fn().mockResolvedValue(null) }));
+vi.mock('./cosState.js', () => ({ loadState: vi.fn().mockResolvedValue({ agents: {} }) }));
+// The real slot module is covered end-to-end in cos.test.js (resolvers, running
+// tally, reservations). Mocked here so this suite stays about the LISTENER's
+// wiring — hold vs spawn vs release — and doesn't drag promptRunner's provider
+// graph into a file that mocks providerStatus.
+vi.mock('./cosLocalEndpointSlots.js', () => ({
+ acquireLocalEndpointSpawnSlot: vi.fn().mockResolvedValue({ ok: true, release: vi.fn() }),
+}));
vi.mock('./agentOrchestrator.js', () => ({
completeAgent: vi.fn(),
spawnAgentForTask: vi.fn().mockResolvedValue('agent-1'),
@@ -68,6 +80,7 @@ import { releaseAppReviewMarker } from './appActivity.js';
import { isUpdateInProgress } from './updateChecker.js';
import { releaseMissionSubTask } from './missions.js';
import { setUseRunner } from './agentState.js';
+import { acquireLocalEndpointSpawnSlot } from './cosLocalEndpointSlots.js';
const dispatch = (task) => taskHandlers.get('task:ready')(task);
@@ -281,6 +294,81 @@ describe('subAgentSpawner — mission sub-task release (#4858)', () => {
});
});
+describe('subAgentSpawner — local-endpoint capacity hold (#4834)', () => {
+ // A CoS agent runs a vendor CLI that opens its own connection to the local
+ // model server, so promptRunner's in-flight gate never sees it. The hold lives
+ // at this listener rather than in `dequeueNextTask` because six other emitters
+ // (evaluateTasks, forceSpawnTask, the job scheduler, the Creative Director
+ // bridge, …) reach the spawner without passing through the scheduler at all.
+ let release;
+
+ beforeEach(async () => {
+ await initSpawner();
+ vi.clearAllMocks();
+ vi.useRealTimers();
+ setUseRunner(true);
+ isRunnerReachable.mockResolvedValue(true);
+ isUpdateInProgress.mockReturnValue(false);
+ release = vi.fn();
+ acquireLocalEndpointSpawnSlot.mockResolvedValue({ ok: true, release });
+ });
+
+ it('spawns and releases the reserved slot when one is available', async () => {
+ await dispatch({ id: 'cos-l1', metadata: {} });
+
+ expect(spawnAgentForTask).toHaveBeenCalledTimes(1);
+ expect(release).toHaveBeenCalledTimes(1);
+ });
+
+ it('holds the task instead of dispatching a second agent at a saturated GPU', async () => {
+ acquireLocalEndpointSpawnSlot.mockResolvedValue({ ok: false, reason: 'local endpoint http://localhost:1234/v1 is at capacity (1/1)' });
+
+ await dispatch({ id: 'cos-l2', metadata: {} });
+
+ // Held, not failed: the task record stays `pending`, so the next dequeue
+ // tick re-picks it once the running agent frees the endpoint.
+ expect(spawnAgentForTask).not.toHaveBeenCalled();
+ });
+
+ it('releases the app-review marker and the job reservation, same as the other holds', async () => {
+ acquireLocalEndpointSpawnSlot.mockResolvedValue({ ok: false, reason: 'at capacity' });
+
+ await dispatch({ id: 'cos-l3', metadata: { app: 'some-app', jobId: 'job-11' } });
+
+ expect(releaseAppReviewMarker).toHaveBeenCalledWith('some-app');
+ expect(cosEvents.emit).toHaveBeenCalledWith('job:spawn-failed', { jobId: 'job-11' });
+ });
+
+ it('releases the slot even when the spawn throws', async () => {
+ // Without the `finally`, a failed spawn would leak the reservation and wedge
+ // the endpoint until the process restarts.
+ spawnAgentForTask.mockRejectedValueOnce(new Error('boom'));
+
+ await dispatch({ id: 'cos-l4', metadata: {} });
+
+ expect(release).toHaveBeenCalledTimes(1);
+ });
+
+ it('checks capacity AFTER the update and runner holds, which are cheaper', async () => {
+ isUpdateInProgress.mockReturnValue(true);
+
+ await dispatch({ id: 'cos-l5', metadata: {} });
+
+ expect(acquireLocalEndpointSpawnSlot).not.toHaveBeenCalled();
+ });
+
+ it('resumes spawning once the endpoint frees up — the hold is not sticky', async () => {
+ acquireLocalEndpointSpawnSlot.mockResolvedValue({ ok: false, reason: 'at capacity' });
+ await dispatch({ id: 'cos-l6', metadata: {} });
+ expect(spawnAgentForTask).not.toHaveBeenCalled();
+
+ acquireLocalEndpointSpawnSlot.mockResolvedValue({ ok: true, release });
+ await dispatch({ id: 'cos-l6', metadata: {} });
+
+ expect(spawnAgentForTask).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('subAgentSpawner — runner connection events', () => {
beforeEach(async () => {
await initSpawner();