mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 04:36:26 +00:00
fix(claude): keep idle agents ready after a clean exit (#11273)
The daemon reported every exit between turns as lost work. Keep the agent idle when the process exited cleanly and had no work to lose. Preserve the order of failure and background cleanup when work was lost. Co-authored-by: lucamzanon <luca.m.zanon@gmail.com>
This commit is contained in:
co-authored by
lucamzanon
parent
0d215ecf29
commit
d7404733f6
@@ -54,6 +54,27 @@ function createQueryMock(events: unknown[], options: QueryMockOptions = {}): Que
|
||||
} as Query;
|
||||
}
|
||||
|
||||
function createAcknowledgingQuery(prompt: ClaudeQueryInput["prompt"], events: unknown[]): Query {
|
||||
if (typeof prompt === "string") throw new Error("Expected a streaming prompt");
|
||||
const submitted = prompt[Symbol.asyncIterator]().next();
|
||||
const query = createQueryMock([
|
||||
{ ...(events[0] as object), claude_code_version: "2.1.310" },
|
||||
...events.slice(1),
|
||||
]);
|
||||
const nextEvent = query.next.bind(query);
|
||||
let acknowledged = false;
|
||||
query.next = async () => {
|
||||
if (acknowledged) return nextEvent();
|
||||
acknowledged = true;
|
||||
const { value } = await submitted;
|
||||
return {
|
||||
done: false,
|
||||
value: { type: "command_lifecycle", command_uuid: value.uuid, state: "started" },
|
||||
} as Awaited<ReturnType<Query["next"]>>;
|
||||
};
|
||||
return query;
|
||||
}
|
||||
|
||||
function createChildProcessStub(): ChildProcess & { killSignals: (NodeJS.Signals | number)[] } {
|
||||
const child = new EventEmitter() as ChildProcess & {
|
||||
killSignals: (NodeJS.Signals | number)[];
|
||||
@@ -186,11 +207,42 @@ describe("Claude runtime exit", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("fails a running workflow when its idle Claude runtime exits", async () => {
|
||||
test("stays quiet when the idle process exits cleanly with nothing running", async () => {
|
||||
let capturedOptions: Options | undefined;
|
||||
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
|
||||
const queryFactory = vi.fn(({ options, prompt }: ClaudeQueryInput) => {
|
||||
capturedOptions = options;
|
||||
return createQueryMock(RUNNING_WORKFLOW_TURN_EVENTS);
|
||||
return createAcknowledgingQuery(prompt, COMPLETED_TURN_EVENTS);
|
||||
});
|
||||
const child = createChildProcessStub();
|
||||
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
queryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
|
||||
|
||||
try {
|
||||
await session.run("first turn");
|
||||
await expect.poll(() => session.canStopRuntime?.()).toBe(true);
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
child.emit("exit", 0, null);
|
||||
|
||||
expect(events.some((event) => event.type === "turn_failed")).toBe(false);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([0, 1])("fails a running workflow on idle exit with code %i", async (code) => {
|
||||
let capturedOptions: Options | undefined;
|
||||
const queryFactory = vi.fn(({ options, prompt }: ClaudeQueryInput) => {
|
||||
capturedOptions = options;
|
||||
return createAcknowledgingQuery(prompt, RUNNING_WORKFLOW_TURN_EVENTS);
|
||||
});
|
||||
const child = createChildProcessStub();
|
||||
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
|
||||
@@ -205,9 +257,11 @@ describe("Claude runtime exit", () => {
|
||||
|
||||
try {
|
||||
await session.run("run a workflow in the background");
|
||||
await expect.poll(() => session.canStopRuntime?.()).toBe(true);
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
child.emit("exit", 1, null);
|
||||
child.emit("exit", code, null);
|
||||
|
||||
expect(events.some((event) => event.type === "turn_failed")).toBe(true);
|
||||
const workflowUpserts = events
|
||||
.filter((event) => event.type === "provider_subagent")
|
||||
.map((event) => event.event)
|
||||
@@ -348,11 +402,11 @@ describe("Claude runtime exit", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("reports the failure before it empties background work when the idle process dies", async () => {
|
||||
test.each([0, 1])("reports idle exit code %i before clearing background work", async (code) => {
|
||||
let capturedOptions: Options | undefined;
|
||||
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
|
||||
const queryFactory = vi.fn(({ options, prompt }: ClaudeQueryInput) => {
|
||||
capturedOptions = options;
|
||||
return createQueryMock(BACKGROUND_SHELL_TURN_EVENTS);
|
||||
return createAcknowledgingQuery(prompt, BACKGROUND_SHELL_TURN_EVENTS);
|
||||
});
|
||||
const child = createChildProcessStub();
|
||||
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
|
||||
@@ -364,12 +418,17 @@ describe("Claude runtime exit", () => {
|
||||
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
|
||||
|
||||
try {
|
||||
await session.run("start a background shell");
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
await session.run("start a background shell");
|
||||
await expect
|
||||
.poll(() => events)
|
||||
.toContainEqual(expect.objectContaining({ type: "turn_completed" }));
|
||||
expect(await session.canStopRuntime?.()).toBe(false);
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
events.length = 0;
|
||||
|
||||
child.emit("exit", 1, null);
|
||||
child.emit("exit", code, null);
|
||||
|
||||
// A watcher that sees the work end first takes the idle child for settled.
|
||||
expect(
|
||||
|
||||
@@ -3470,6 +3470,10 @@ class ClaudeAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async canStopRuntime(): Promise<boolean> {
|
||||
return this.isRuntimeSafeToStop();
|
||||
}
|
||||
|
||||
private isRuntimeSafeToStop(): boolean {
|
||||
return (
|
||||
!this.activeForegroundTurnId &&
|
||||
!this.autonomousTurn &&
|
||||
@@ -4660,6 +4664,22 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return;
|
||||
}
|
||||
this.childProcess = null;
|
||||
if (
|
||||
code === 0 &&
|
||||
signal === null &&
|
||||
this.isRuntimeSafeToStop() &&
|
||||
!this.notificationTurnId &&
|
||||
!this.taskProtocolSource.hasRunningTasks()
|
||||
) {
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
this.failRunningRuntimeTasks();
|
||||
this.logger.info(
|
||||
{ agentId: this.agentId, pid: child.pid },
|
||||
"Claude runtime exited cleanly while idle",
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.logger.warn(
|
||||
{ agentId: this.agentId, pid: child.pid, code, signal },
|
||||
"Claude runtime exited unexpectedly",
|
||||
|
||||
@@ -319,6 +319,13 @@ export class ClaudeTaskProtocolSource {
|
||||
return observations;
|
||||
}
|
||||
|
||||
hasRunningTasks(): boolean {
|
||||
for (const id of this.declaredIds) {
|
||||
if (this.lastStatusById.get(id) === "running") return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A lost Claude process terminates every task it owned, including backgrounded workflows. */
|
||||
failRunningTasks(): SubagentObservation[] {
|
||||
const observations: SubagentObservation[] = [];
|
||||
|
||||
Reference in New Issue
Block a user