Skip to content

Commit 1840a4e

Browse files
fix(server): keep the host awake for background agents
hasWorkingRuns only looked at run status, so a Claude background subagent that outlived its parent run dropped the wake lock. Count holding background tasks too, and reconcile on provider-thread updates. Co-authored-by: Cursor <[email protected]>
1 parent d136c08 commit 1840a4e

4 files changed

Lines changed: 107 additions & 5 deletions

File tree

‎apps/server/src/background/HostWakeLock.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import * as ServerSettings from "../serverSettings.ts";
1515
import * as HostWakeLock from "./HostWakeLock.ts";
1616

1717
const runUpdated = { type: "run.updated" } as OrchestrationV2DomainEvent;
18+
const providerThreadUpdated = { type: "provider-thread.updated" } as OrchestrationV2DomainEvent;
1819
const turnItemUpdated = { type: "turn-item.updated" } as OrchestrationV2DomainEvent;
1920

2021
const setup = Effect.fn("HostWakeLockTest.setup")(function* (input: {
@@ -150,6 +151,23 @@ describe("HostWakeLock", () => {
150151
),
151152
);
152153

154+
it.effect("reconciles when a provider thread's background roster changes", () =>
155+
Effect.scoped(
156+
Effect.gen(function* () {
157+
const host = yield* setup({ mode: "whileWorking" });
158+
159+
yield* Ref.set(host.working, true);
160+
yield* Queue.offer(host.events, providerThreadUpdated);
161+
yield* Queue.take(host.spawned);
162+
163+
yield* Ref.set(host.working, false);
164+
yield* Queue.offer(host.events, providerThreadUpdated);
165+
yield* Queue.take(host.released);
166+
expect(yield* Ref.get(host.spawns)).toBe(1);
167+
}),
168+
),
169+
);
170+
153171
it.effect("takes the lock again after the helper exits by itself", () =>
154172
Effect.scoped(
155173
Effect.gen(function* () {

‎apps/server/src/background/HostWakeLock.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,13 @@ export const make = Effect.gen(function* () {
109109
),
110110
Stream.merge(
111111
orchestrator.streamDomainEvents.pipe(
112-
Stream.filter((event) => event.type === "run.created" || event.type === "run.updated"),
112+
Stream.filter(
113+
(event) =>
114+
event.type === "run.created" ||
115+
event.type === "run.updated" ||
116+
// Background agents can outlive their parent run; their roster lives here.
117+
event.type === "provider-thread.updated",
118+
),
113119
),
114120
),
115121
Stream.runForEach(() => reconcile),

‎apps/server/src/orchestration-v2/ProjectionStore.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -829,6 +829,68 @@ it.effect("working runs exclude queued and finished runs", () =>
829829
});
830830
assert.equal(yield* store.hasWorkingRuns(), working, status);
831831
}
832+
833+
// A Claude background subagent can keep working after its parent run completes.
834+
const providerThreadId = ProviderThreadId.make("provider-thread:working-runs");
835+
const providerThread = {
836+
id: providerThreadId,
837+
driver,
838+
providerInstanceId,
839+
providerSessionId: null,
840+
appThreadId: threadId,
841+
ownerNodeId: null,
842+
nativeThreadRef: null,
843+
nativeConversationHeadRef: null,
844+
status: "idle" as const,
845+
firstRunOrdinal: 1,
846+
lastRunOrdinal: 1,
847+
handoffIds: [],
848+
forkedFrom: null,
849+
pendingBackgroundTasks: [{ taskId: "review", kind: "subagent" as const }],
850+
createdAt: now,
851+
updatedAt: now,
852+
};
853+
yield* store.apply({
854+
id: EventId.make("working-runs:background-subagent"),
855+
type: "provider-thread.updated",
856+
threadId,
857+
occurredAt: now,
858+
payload: providerThread,
859+
});
860+
assert.isTrue(yield* store.hasWorkingRuns());
861+
862+
yield* store.apply({
863+
id: EventId.make("working-runs:idle-command"),
864+
type: "provider-thread.updated",
865+
threadId,
866+
occurredAt: now,
867+
payload: {
868+
...providerThread,
869+
pendingBackgroundTasks: [{ taskId: "dev-server", kind: "command" }],
870+
},
871+
});
872+
assert.isFalse(yield* store.hasWorkingRuns());
873+
874+
yield* store.apply({
875+
id: EventId.make("working-runs:awaited-command"),
876+
type: "provider-thread.updated",
877+
threadId,
878+
occurredAt: now,
879+
payload: {
880+
...providerThread,
881+
pendingBackgroundTasks: [{ taskId: "tests", kind: "command", awaited: true as const }],
882+
},
883+
});
884+
assert.isTrue(yield* store.hasWorkingRuns());
885+
886+
yield* store.apply({
887+
id: EventId.make("working-runs:background-cleared"),
888+
type: "provider-thread.updated",
889+
threadId,
890+
occurredAt: now,
891+
payload: { ...providerThread, pendingBackgroundTasks: [] },
892+
});
893+
assert.isFalse(yield* store.hasWorkingRuns());
832894
}).pipe(Effect.provide(layerTest)),
833895
);
834896

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -517,7 +517,12 @@ export interface ProjectionStoreV2Shape {
517517
>;
518518
/** Threads that are not deleted, archived ones included. */
519519
readonly countThreads: () => Effect.Effect<number, ProjectionStoreV2Error>;
520-
/** Excludes queued runs, which can sit idle until a usage limit resets. */
520+
/**
521+
* True while a run is preparing/starting/running/waiting, or while a provider
522+
* thread still holds completion on background work (subagent, background_task,
523+
* or an awaited command/monitor) after its parent run ends. Excludes queued
524+
* runs, which can sit idle until a usage limit resets.
525+
*/
521526
readonly hasWorkingRuns: () => Effect.Effect<boolean, ProjectionStoreV2Error>;
522527
/** Every active thread, in shell order. */
523528
readonly listActiveShellIndex: () => Effect.Effect<
@@ -7227,10 +7232,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
72277232
}, Effect.mapError(shellSnapshotReadError));
72287233

72297234
const hasWorkingRuns = Effect.fn("ProjectionStore.hasWorkingRuns")(function* () {
7235+
// Same hold rules as backgroundWorkHoldsCompletion: subagent/background_task
7236+
// always hold; command/monitor only when awaited.
72307237
const rows = yield* sql<{ readonly working: number }>`
7231-
SELECT EXISTS (
7232-
SELECT 1 FROM orchestration_v2_projection_runs
7233-
WHERE status IN ('preparing', 'starting', 'running', 'waiting')
7238+
SELECT (
7239+
EXISTS (
7240+
SELECT 1 FROM orchestration_v2_projection_runs
7241+
WHERE status IN ('preparing', 'starting', 'running', 'waiting')
7242+
)
7243+
OR EXISTS (
7244+
SELECT 1
7245+
FROM orchestration_v2_projection_provider_threads AS provider_thread
7246+
JOIN json_each(provider_thread.payload_json, '$.pendingBackgroundTasks') AS task
7247+
WHERE json_extract(task.value, '$.awaited') = 1
7248+
OR json_extract(task.value, '$.kind') IN ('subagent', 'background_task')
7249+
)
72347250
) AS working
72357251
`;
72367252
return rows[0]?.working === 1;

0 commit comments

Comments
 (0)