From bf3f8e50052b6cbfda2f648401236af1fdca8e9f Mon Sep 17 00:00:00 2001 From: justsisyphus Date: Mon, 19 Jan 2026 14:34:15 +0900 Subject: [PATCH] fix(background-agent): prevent premature task completion when agent still running - Add session.status re-check in stability detection before completing - Reset stablePolls if session is not idle (agent still working) - Fix statusText to show CANCELLED instead of COMPLETED for non-completed tasks --- src/features/background-agent/manager.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/features/background-agent/manager.ts b/src/features/background-agent/manager.ts index e6233a0d6..0b2a51aa8 100644 --- a/src/features/background-agent/manager.ts +++ b/src/features/background-agent/manager.ts @@ -924,8 +924,7 @@ export class BackgroundManager { const allComplete = !pendingSet || pendingSet.size === 0 const remainingCount = pendingSet?.size ?? 0 - // Build notification message - const statusText = task.status === "error" ? "FAILED" : "COMPLETED" + const statusText = task.status === "completed" ? "COMPLETED" : "CANCELLED" const errorInfo = task.error ? `\n**Error:** ${task.error}` : "" let notification: string @@ -1228,6 +1227,20 @@ Use \`background_output(task_id="${task.id}")\` to retrieve this result when rea if (task.lastMsgCount === currentMsgCount) { task.stablePolls = (task.stablePolls ?? 0) + 1 if (task.stablePolls >= 3) { + // Re-fetch session status to confirm agent is truly idle + const recheckStatus = await this.client.session.status() + const recheckData = (recheckStatus.data ?? {}) as Record + const currentStatus = recheckData[sessionID] + + if (currentStatus?.type !== "idle") { + log("[background-agent] Stability reached but session not idle, resetting:", { + taskId: task.id, + sessionStatus: currentStatus?.type ?? "not_in_status" + }) + task.stablePolls = 0 + continue + } + // Edge guard: Validate session has actual output before completing const hasValidOutput = await this.validateSessionHasOutput(sessionID) if (!hasValidOutput) {