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: retain on-demand runs at project capacity

[._.]/ Adam Eivya6f21c16c0a3
diff --git a/server/services/cos.js b/server/services/cos.js
index c6752e4c5e..3c26d3aee2 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1051,6 +1051,8 @@ async function spawnDequeuePriority0OnDemand(ctx) {
const { schedule } = await drainOnDemandRequests({ state }, {
capacityExhausted: () => capacity.spawned >= capacity.availableSlots,
+ projectCapacityExhausted: (appId) =>
+ (capacity.spawnProjectCounts[appId || '_self'] || 0) >= capacity.perProjectLimit,
// Priority 0 is a COMMITTED tier — the request is cleared and the app-review
// marker bound before this runs, and nothing persists the task on a denial,
// so it opts out of the local-endpoint cap (#4834).
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 9fea19ef32..059e748cfa 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -945,10 +945,12 @@ export async function admitPendingUserTasks({ pendingUserTasks, instanceId }, ad
* autonomous action budget.
*/
async function spawnPriority0OnDemand(ctx) {
- const { state, availableSlots, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;
+ const { state, availableSlots, perProjectLimit, spawnProjectCounts, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;
const { schedule } = await drainOnDemandRequests({ state }, {
capacityExhausted: () => tasksToSpawn.length >= availableSlots,
+ projectCapacityExhausted: (appId) =>
+ (spawnProjectCounts[appId || '_self'] || 0) >= perProjectLimit,
canSpawn: (task) => canSpawnTask(task),
emitSpawn: (task) => {
tasksToSpawn.push(task);
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 3fe665196f..469984735a 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -288,14 +288,17 @@ describe('dry-run hook wiring matches the shared execute path', () => {
// re-inlines a loop into either engine is the regression, and no behavioral test
// of the shared module can see it.
describe('both on-demand engines delegate to the shared drain', () => {
- for (const [engine, src] of [
- ['cosTaskGenerator.spawnPriority0OnDemand', () => GEN_SRC],
- ['cos.spawnDequeuePriority0OnDemand', () => COS_SRC],
+ for (const [engine, src, projectCounts, projectLimit] of [
+ ['cosTaskGenerator.spawnPriority0OnDemand', () => GEN_SRC, 'spawnProjectCounts', 'perProjectLimit'],
+ ['cos.spawnDequeuePriority0OnDemand', () => COS_SRC, 'capacity.spawnProjectCounts', 'capacity.perProjectLimit'],
]) {
it(`${engine} calls drainOnDemandRequests and owns no request loop of its own`, () => {
const text = src();
expect(text).toMatch(/import \{ drainOnDemandRequests \} from '\.\/onDemandDrain\.js'/);
expect(text).toContain('drainOnDemandRequests({ state }, {');
+ expect(text, `${engine} must defer app-scoped requests when their project cap is full`).toContain(
+ `projectCapacityExhausted: (appId) =>\n (${projectCounts}[appId || '_self'] || 0) >= ${projectLimit},`
+ );
expect(
text,
`${engine} must not re-inline the on-demand loop — it belongs to onDemandDrain.js`
@@ -311,6 +314,8 @@ describe('both on-demand engines delegate to the shared drain', () => {
expect(DRAIN_SRC).toMatch(/const apps = onDemandRequests\.length > 0 \? await getActiveApps\(\)\.catch\(\(\) => null\) : \[\];/);
expect(DRAIN_SRC, 'a [] fallback is the #6618 defect — it clears the request as unknown-app')
.not.toMatch(/getActiveApps\(\)\.catch\(\(\) => \[\]\)/);
+ expect(DRAIN_SRC, 'a full project must leave its request queued before preparation')
+ .toMatch(/projectCapacityExhausted\(targetApp\?\.id \?\? request\.appId \?\? null\)[\s\S]*?continue;/);
const readIdx = DRAIN_SRC.indexOf('await getActiveApps()');
const loopIdx = DRAIN_SRC.indexOf('for (const request of onDemandRequests)');
expect(readIdx).toBeGreaterThan(-1);
diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.js
index 009a03b9c3..e412055ddc 100644
--- a/server/services/onDemandDrain.js
+++ b/server/services/onDemandDrain.js
@@ -12,12 +12,13 @@
* destroyed (issue #6618).
*
* The loop lives here now, so there is nothing left to mirror. Each engine
- * supplies an `adapter` for the only three things that genuinely differ:
+ * supplies an `adapter` for engine-specific capacity and dispatch behavior:
*
- * - `capacityExhausted()` / `canSpawn(task)` — the generator fills a
- * `tasksToSpawn` array against `availableSlots`; the dequeue engine runs the
- * `cosDequeue.js` capacity tracker and admits via `canSpawnCommitted`
- * (Priority 0 is a COMMITTED tier — see #4834).
+ * - `capacityExhausted()` / `projectCapacityExhausted(appId)` /
+ * `canSpawn(task)` — the generator fills a `tasksToSpawn` array against
+ * `availableSlots`; the dequeue engine runs the `cosDequeue.js` capacity
+ * tracker and admits via `canSpawnCommitted`. The per-project precheck keeps
+ * requests queued before preparation when their app is already full.
* - `emitSpawn(task)` — push-to-array + `trackSpawn` vs
* `cosEvents.emit('task:ready', …)` + `capacity.trackSpawn`.
* - `addTaskOptions` — the `{ ignoreTaskId }` only the dequeue engine forwards.
@@ -43,17 +44,24 @@ import { cardIdForRequest, finishPreflightCard, finishPreflightDispatch, reportP
* @param {{ state: object }} ctx Shared CoS state for this cycle.
* @param {{
* capacityExhausted: () => boolean,
+ * projectCapacityExhausted?: (appId: string|null) => boolean,
* canSpawn: (task: object) => boolean,
* emitSpawn: (task: object) => void,
* addTaskOptions?: object,
- * }} adapter The three per-engine differences.
+ * }} adapter Engine-specific capacity and dispatch behavior.
* @returns {Promise<{ schedule: object }>} The loaded schedule, so a caller that
* needs it downstream (dequeueNextTask's Priority 2 disabled-analysis-type
* gate) reuses this load instead of issuing a second one.
*/
export async function drainOnDemandRequests(ctx, adapter) {
const { state } = ctx;
- const { capacityExhausted, canSpawn, emitSpawn, addTaskOptions = {} } = adapter;
+ const {
+ capacityExhausted,
+ projectCapacityExhausted = () => false,
+ canSpawn,
+ emitSpawn,
+ addTaskOptions = {},
+ } = adapter;
// Deferred so the static import graph stays acyclic: cosTaskGenerator.js
// imports THIS module, and these six helpers are declared there. Deferring to
@@ -171,6 +179,19 @@ export async function drainOnDemandRequests(ctx, adapter) {
}
}
+ // A request that cannot fit under its app's concurrency cap must stay in
+ // the durable on-demand queue. Clearing it before preparation used to be
+ // safe only when the final `canSpawn` could not deny; per-project capacity
+ // can deny while global slots remain, which discarded the prepared task and
+ // closed the visible card without ever creating an agent task.
+ if (projectCapacityExhausted(targetApp?.id ?? request.appId ?? null)) {
+ emitLog('debug', `On-demand request deferred — per-project agent limit reached`, {
+ requestId: request.id,
+ taskType: request.taskType,
+ });
+ continue;
+ }
+
await taskScheduleMod.clearOnDemandRequest(request.id);
// Off the queue and into preparation. A task type with its own preflight
// (pr-reviewer) has no `prepare` step and reports its real first step
diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.js
index a2dc89e3bb..e132599c22 100644
--- a/server/services/onDemandDrain.test.js
+++ b/server/services/onDemandDrain.test.js
@@ -101,24 +101,26 @@ const STATE = { agents: {}, stats: {}, config: {} };
// The two real adapters, reproduced from the engines they belong to. Each test
// runs the shared loop through BOTH, so a behavior that only holds for one is a
// failure rather than an untested corner.
-function generatorAdapter({ availableSlots = 5 } = {}) {
+function generatorAdapter({ availableSlots = 5, projectCapacityExhausted = () => false } = {}) {
const tasksToSpawn = [];
return {
spawned: tasksToSpawn,
adapter: {
capacityExhausted: () => tasksToSpawn.length >= availableSlots,
+ projectCapacityExhausted,
canSpawn: () => true,
emitSpawn: (task) => tasksToSpawn.push(task),
},
};
}
-function dequeueAdapter({ availableSlots = 5, ignoreTaskId = 'completing-task' } = {}) {
+function dequeueAdapter({ availableSlots = 5, ignoreTaskId = 'completing-task', projectCapacityExhausted = () => false } = {}) {
const spawned = [];
return {
spawned,
adapter: {
capacityExhausted: () => spawned.length >= availableSlots,
+ projectCapacityExhausted,
canSpawn: () => true,
emitSpawn: (task) => spawned.push(task),
addTaskOptions: { ignoreTaskId },
@@ -265,6 +267,43 @@ describe.each(ENGINES)('%s — empty-result feedback', (_name, makeAdapter) => {
});
});
+describe.each(ENGINES)('%s — per-project capacity defers before preparation', (_name, makeAdapter) => {
+ it('keeps a full app request queued and its visible card open', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ const { spawned, adapter } = makeAdapter({ projectCapacityExhausted: appId => appId === 'acme' });
+
+ await drainOnDemandRequests({ state: STATE }, adapter);
+
+ expect(mocks.startPreflightCard).toHaveBeenCalledTimes(1);
+ expect(mocks.clearOnDemandRequest).not.toHaveBeenCalled();
+ expect(mocks.prepareManagedAppImprovementTask).not.toHaveBeenCalled();
+ expect(mocks.finishPreflightDispatch).not.toHaveBeenCalled();
+ expect(spawned).toEqual([]);
+ });
+
+ it('continues to other apps while retaining the full app request', async () => {
+ const otherApp = { id: 'other', name: 'Other App' };
+ mocks.getOnDemandRequests.mockResolvedValue([
+ appRequest({ id: 'req-full' }),
+ appRequest({ id: 'req-ready', appId: otherApp.id }),
+ ]);
+ mocks.getActiveApps.mockResolvedValue([APP, otherApp]);
+ mocks.prepareManagedAppImprovementTask.mockImplementation(async (_type, app) => ({
+ task: { id: `gen-${app.id}`, priority: 'HIGH', metadata: { app: app.id } },
+ pendingPerpetualDispatch: null,
+ }));
+ const { spawned, adapter } = makeAdapter({ projectCapacityExhausted: appId => appId === 'acme' });
+
+ await drainOnDemandRequests({ state: STATE }, adapter);
+
+ expect(mocks.clearOnDemandRequest).toHaveBeenCalledTimes(1);
+ expect(mocks.clearOnDemandRequest).toHaveBeenCalledWith('req-ready');
+ expect(mocks.prepareManagedAppImprovementTask).toHaveBeenCalledTimes(1);
+ expect(spawned).toHaveLength(1);
+ expect(spawned[0].id).toBe(`gen-${otherApp.id}`);
+ });
+});
+
describe.each(ENGINES)('%s — blocked-duplicate revive (#2614)', (_name, makeAdapter) => {
it('revives the blocked twin and emits it under the existing task id', async () => {
mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);