Fix Claude permission waits and MCP responses

This commit is contained in:
Mohamed Boudra
2025-12-24 23:23:16 +07:00
parent e41ad30d26
commit 9d3b45475a
6 changed files with 704 additions and 565 deletions
@@ -615,6 +615,8 @@ export class AgentManager {
const initialStatus = snapshot.lifecycle;
const initialBusy = isAgentBusy(initialStatus);
const waitForActive = options?.waitForActive ?? false;
const hasPendingRun =
"pendingRun" in snapshot && Boolean(snapshot.pendingRun);
if (!waitForActive && !initialBusy) {
return {
status: initialStatus,
@@ -622,6 +624,13 @@ export class AgentManager {
lastMessage: this.getLastAssistantMessage(agentId)
};
}
if (waitForActive && !initialBusy && !hasPendingRun) {
return {
status: initialStatus,
permission: null,
lastMessage: this.getLastAssistantMessage(agentId)
};
}
if (options?.signal?.aborted) {
throw createAbortError(options.signal, "wait_for_agent aborted");
@@ -637,7 +646,7 @@ export class AgentManager {
}
let currentStatus: AgentLifecycleStatus = initialStatus;
let hasStarted = initialBusy;
let hasStarted = initialBusy || hasPendingRun;
// Bug #3 Fix: Declare unsubscribe and abortHandler upfront so cleanup can reference them
let unsubscribe: (() => void) | null = null;
@@ -688,7 +697,6 @@ export class AgentManager {
// This prevents race condition if callback fires synchronously with replayState: true
unsubscribe = this.subscribe(
(event) => {
// Bug #2 Fix: Only handle agent_state events, remove redundant agent_stream handling
if (event.type === "agent_state") {
currentStatus = event.agent.lifecycle;
const pending = this.peekPendingPermission(event.agent);
@@ -703,6 +711,25 @@ export class AgentManager {
if (!waitForActive || hasStarted) {
finish(null);
}
return;
}
if (event.type === "agent_stream") {
if (event.event.type === "permission_requested") {
finish(event.event.request);
return;
}
if (event.event.type === "turn_failed") {
currentStatus = "error";
hasStarted = true;
finish(null);
return;
}
if (event.event.type === "turn_completed") {
currentStatus = "idle";
hasStarted = true;
finish(null);
}
}
},
{ agentId, replayState: true }