mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-16 14:22:28 +00:00
fix: end the turn task of a cycle that has no turn to claim its result (#1622)
When Claude Code's scheduler fires a `ScheduleWakeup` or a cron prompt with no prompt open, the bridge opens an AIR async task for the cycle, but nothing ends it. The cycle's result has no `origin`, so it is not in `AUTONOMOUS_RESULT_ORIGINS` and takes the user lane. With no active or queued turn it settles nothing, and it records an owed trailing idle. The `idle` handler ends an open autonomous task only at `owedTrailingIdles === 0`, and it absorbs the owed idle first. The task stays open until the stream ends or a later cycle sweeps the debt. This change ends the open autonomous task at any result that no turn can own: the session is not cancelled and has no active turn and no unsettled queued turn. That is the condition that already opens the task, so both ends now call one helper (`noTurnOwnsCycle`, next to `firstUnsettledQueuedTurn`). The new end uses the same placeholder rule as the autonomous lane (`num_turns > 0 || is_error`). It adds a scripted SDK-stream regression: a prompt's turn, a `command_lifecycle` `started` with `wakeup_source: "loop_wakeup"` before the prompt's idle, a cycle with a result that has no origin, then one idle for both. It checks that the task completes. It fails before the fix (the task is only closed as `failed` when the stream ends) and passes after. ## Why this rule I considered two designs: 1. End the task for any result with no turn to claim it (this PR). 2. Treat a scheduler-fired cycle as autonomous, so its result takes the autonomous lane. I chose 1: - The result carries no origin, so 2 needs state that remembers "this cycle started with a `wakeup_source`" from the `command_lifecycle` frame, and a way to match that state to a later result. It would miss cycles with no fire frame (Claude Code before 2.1.307 sends no `wakeup_source`), and any other origin-less cycle that Claude Code starts on its own, including origins it adds later. - The comment on `AUTONOMOUS_RESULT_ORIGINS` explains why the lane default is fail-open: moving a user result into the autonomous lane hangs the prompt where the #825 detector cannot see it. This change moves no result between lanes. It only ends a task when no turn exists that a user-lane result could settle, so there is nothing to hang. - Starting and ending the task now share one predicate, so they cannot disagree about which cycles belong to no turn. The state of the task lives in `AsyncTaskRuntime` (`autonomousTurnEnded`, unchanged). The predicate reads the session's turn queue, which `async-tasks.ts` does not own, so the check stays in the v1 consumer next to `firstUnsettledQueuedTurn` and only calls the runtime. ## What stays as it was - #825 (the abandoned-turn detector) fails an unsettled active turn at an idle that no result owes. The new end needs no active and no queued turn, so the detector never has a turn to fail here. A result with an active or queued turn is claimed as before (`ensureActiveTurn` still ends the task when it promotes the head). - The result keeps its owed trailing idle (`owedTrailingIdles++`), its usage and its other user-lane handling. Its idle is absorbed as owed, so it cannot be read as a later prompt being abandoned. The `running` transition still sweeps unpaid debt. - A cancelled session is excluded, so the orphan results of cancelled prompts keep their existing handling. ## v2 Not affected. v2 reports a cycle as a turn and ends it at the cycle's result, whatever its origin: `Session.result` opens a turn if none is open, then ends it. v2 has no async task that a result must close separately. A test in `src/tests/v2/acp-v2.test.ts` runs the same stream (a prompt, a scheduler fire, one idle for both results) and checks that the cycle reports `running` and `idle end_turn`. It passes with and without this change. Fixes #1620. ## Validation Rebased on `main` at7e857d5. - `npm run check` and `npm run build` pass. - `npm run test:run`: 4,134 passed, 36 skipped, 1 failed. The failure is `tools.test.ts` "picks up a rewrite that restored the modification time of the file", which also fails on `main` at7e857d5without this change. - The new v1 test fails on `main` (`['async_task_spawned', 'failed']` instead of `['async_task_spawned', 'completed']`) and passes with the fix. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -26220,6 +26220,38 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
|
||||
]);
|
||||
});
|
||||
|
||||
// A scheduler fire is not an autonomous origin: its result has no
|
||||
// `origin`, so it takes the user lane with no turn to claim it.
|
||||
it("ends the task at the result of the cycle that a fire started (#1620)", async () => {
|
||||
const { agent, asyncTaskUpdates } = await airAgent();
|
||||
injectGeneratorSession(agent, (input) => {
|
||||
async function* messageGenerator() {
|
||||
const iter = input[Symbol.asyncIterator]();
|
||||
yield userEcho((await iter.next()).value);
|
||||
yield running();
|
||||
yield assistantText("working");
|
||||
yield resultMessage();
|
||||
// The overdue ScheduleWakeup fires at once, before the prompt's idle.
|
||||
yield lifecycleStarted({ wakeup_source: "loop_wakeup" });
|
||||
yield assistantText("That wakeup was stale");
|
||||
yield resultMessage();
|
||||
// One idle covers both results.
|
||||
yield idle();
|
||||
}
|
||||
return messageGenerator();
|
||||
});
|
||||
|
||||
await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "go" }] });
|
||||
await agent.sessions["test-session"]?.consumer;
|
||||
|
||||
// The stream ending closes an open task as failed, so a task that only the
|
||||
// end of the stream ended would not be completed.
|
||||
expect(asyncTaskUpdates().map((update) => update.state ?? update.sessionUpdate)).toEqual([
|
||||
"async_task_spawned",
|
||||
"completed",
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves the task as before for a started frame without a known wakeup source", async () => {
|
||||
const updates = await autonomousTurn((afterRunning) =>
|
||||
afterRunning
|
||||
|
||||
@@ -4504,6 +4504,37 @@ describe("ACP v2 model cycles that Claude Code starts on its own", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// The result of a cycle that a scheduler fire started has no `origin`. v2
|
||||
// ends every cycle at its result, so unlike v1 it has no task left open.
|
||||
it("ends a cycle that a scheduler fire started at its result, which has no origin", async () => {
|
||||
scriptTurns(async function* (options) {
|
||||
yield assistantText(options, "Started the build in the background.");
|
||||
yield result(options);
|
||||
// The overdue ScheduleWakeup fires before the prompt's idle.
|
||||
yield {
|
||||
type: "command_lifecycle",
|
||||
command_uuid: "scheduler-fire",
|
||||
state: "started",
|
||||
wakeup_source: "loop_wakeup",
|
||||
scheduled_for: 1_790_000_000_000,
|
||||
uuid: randomUUID(),
|
||||
session_id: options.sessionId,
|
||||
};
|
||||
yield assistantText(options, "That wakeup was stale.", "msg_wakeup");
|
||||
yield result(options);
|
||||
// One idle covers both results.
|
||||
yield idleState(options);
|
||||
});
|
||||
const client = await promptAndWait(2);
|
||||
|
||||
expect(turnTrace(client.sessionUpdates)).toEqual([
|
||||
...endedTurn,
|
||||
"running",
|
||||
"agent_message_chunk",
|
||||
"idle end_turn",
|
||||
]);
|
||||
});
|
||||
|
||||
it("closes a tool call that Claude dropped before it ran in a cycle as cancelled, before the cycle's idle", async () => {
|
||||
scriptTurns(async function* (options) {
|
||||
yield assistantText(options, "Started the build in the background.");
|
||||
|
||||
@@ -3772,6 +3772,13 @@ export class ClaudeAcpAgent {
|
||||
* the autonomous stretch-close guard. */
|
||||
const firstUnsettledQueuedTurn = () => (session.turnQueue ?? []).find((t) => !t.settled);
|
||||
|
||||
/** Whether no turn can own what the stream carries now: nothing is
|
||||
* cancelled, active or queued. Output then belongs to a cycle that Claude
|
||||
* Code started on its own, such as a scheduler fire, and so does its
|
||||
* result, whatever its origin says. */
|
||||
const noTurnOwnsCycle = () =>
|
||||
!session.cancelled && !session.activeTurn && !firstUnsettledQueuedTurn();
|
||||
|
||||
/** Claim the structured replacement for the turn currently producing a
|
||||
* local-command output. Undefined means this is not a structured
|
||||
* local-command turn (or its request failed), null means another SDK
|
||||
@@ -4550,13 +4557,7 @@ export class ClaudeAcpAgent {
|
||||
// open, it starts an autonomous turn: name the fire as its cause,
|
||||
// whether `session_state_changed` already opened the task or not.
|
||||
const cause = scheduledFireCause(frame);
|
||||
if (
|
||||
cause &&
|
||||
asyncTasks.enabled &&
|
||||
!session.cancelled &&
|
||||
!session.activeTurn &&
|
||||
!firstUnsettledQueuedTurn()
|
||||
) {
|
||||
if (cause && asyncTasks.enabled && noTurnOwnsCycle()) {
|
||||
await asyncTasks.autonomousTurnStarted(cause);
|
||||
}
|
||||
// Remember dispatch on the live turn so a cancel() that orphans
|
||||
@@ -4670,9 +4671,7 @@ export class ClaudeAcpAgent {
|
||||
!asyncTasks.autonomousTurnOpen &&
|
||||
(message.type === "assistant" || message.type === "stream_event") &&
|
||||
message.parent_tool_use_id === null &&
|
||||
!session.cancelled &&
|
||||
!session.activeTurn &&
|
||||
!firstUnsettledQueuedTurn()
|
||||
noTurnOwnsCycle()
|
||||
) {
|
||||
await asyncTasks.autonomousTurnStarted();
|
||||
}
|
||||
@@ -5542,10 +5541,20 @@ export class ClaudeAcpAgent {
|
||||
const startedByClaudeCode =
|
||||
message.origin != null && AUTONOMOUS_RESULT_ORIGINS.has(message.origin.kind);
|
||||
const isAutonomousResult = startedByClaudeCode && !answersPendingPrompt(message);
|
||||
// A result with no turn to claim it also ends the cycle that
|
||||
// Claude Code started on its own, whatever its origin says. A
|
||||
// scheduler fire (a ScheduleWakeup or cron prompt) is one: its
|
||||
// result has no origin, so it takes the user lane, where it owes a
|
||||
// trailing idle. That idle is absorbed before the idle check for an
|
||||
// autonomous cycle sees a zero debt, so only this result can end
|
||||
// the task. The user lane is otherwise unchanged: the owed idle
|
||||
// and the #825 detector, which needs an unsettled turn, work as
|
||||
// before.
|
||||
const endsOwnCycle = isAutonomousResult || noTurnOwnsCycle();
|
||||
// A placeholder result (`num_turns: 0`, see below) comes before
|
||||
// the followup that answers it, so the autonomous turn goes on.
|
||||
if (
|
||||
isAutonomousResult &&
|
||||
endsOwnCycle &&
|
||||
asyncTasks.autonomousTurnOpen &&
|
||||
(message.num_turns > 0 || message.is_error)
|
||||
) {
|
||||
|
||||
Reference in New Issue
Block a user