mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-17 14:51:13 +00:00
fix: an autonomous result naming the original prompt must not end a steered turn early (#1451)
Thanks for merging #1392, and for #1233, which fixed the original hang
we reported in #1145.
**Problem.** Call the original prompt P and the steered instruction S.
While S is still running, a result from a cycle Claude Code started
itself (`origin: task-notification`), stamped with P's uuid, clears
`steeredAwaitingResult`. Its trailing idle then meets
`isSteeredSettleReady` and `session/prompt` returns while the steered
work is still streaming. The `steeredAwaitingResult` doc already states
the rule: *"while this is set the recorded outcome predates the steered
work and an idle must not settle on it"*. The code doesn't keep it for
this one shape.
The sequence (v0.97.0):
1. the interrupted cycle's result names P: `settleOrDefer`'s steering
branch records it;
2. S's echo: `steeredAwaitingResult = true`;
3. an autonomous result stamped `[P]`: `answersPendingPrompt` is true (P
is still in `turnQueue`), so it takes the user lane, reaches
`settleOrDefer`, and **clears `steeredAwaitingResult`**;
4. that cycle's idle: `isSteeredSettleReady` is true, so P settles
before S's own result.
#1185 doesn't cover this: it matches results that name the *steer*, and
this one names the original prompt.
**Change.**
- `settleOrDefer` takes one optional `{ steeredWork }` (default `true`,
so every existing caller is unchanged). In the steering branch it still
records `steeredSettle` (the last result and its usage still win), but
clears `steeredAwaitingResult` only for steered work.
- `answersSteer` moves up to the head of the result handling, so the two
settle calls can read it. Both the refusal settle and the end-of-result
settle pass `steeredWork: !startedByClaudeCode || answersSteer`.
- No new state. No change to `answersPendingPrompt`,
`isSteeredSettleReady`, the idle lane, owed-idle accounting or usage.
- The steered cycle's own result is not autonomous (in the existing
steer tests it carries no origin), so it still clears the flag. A result
that names the steer still leaves the steer lane at the result, as
before. If a CLI ever answered the steer with an autonomous result
naming only P, the turn would wait for the next result, `session/cancel`
or the next prompt, instead of ending early.
**Test.** Two cases (`end_turn` and `refusal` trailers) beside "does not
settle a steered turn on a lagged owed idle before the steered result",
which covers the unstamped variant of the same guard. They are the same
shape, with the autonomous result stamped with P and placed after the
steer's echo. Both fail on main and pass with the fix. The turn keeps
one stop reason across its cycles, so the refusal case expects
`refusal`. What it asserts is that the prompt ends last.
**Repro.** We have a ~180-line fake-CLI replay (no model, no network)
that drives the real adapter over stdio and times `session/prompt`
against the steered result: on 0.97.0 the prompt returns ~2.5 s early,
and with this change 1 ms after. It's the repro offered on #1145, and we
can attach it.
**Not covered:**
- An `is_error` autonomous result naming a pending prompt mid-steer
still fails that prompt (`failActiveWithSessionFailure`). That is a
different behaviour, an early failure rather than an early completion,
and is not addressed here.
- The steer-error arm (`is_error && isSteering && steeredEchoes.size >
0`) is unchanged. It runs only before the steer's echo, when there is no
wait to end yet.
Related: #1144, #1145, #1185, #1292 (the same family of protection for
autonomous cycles with an empty queue; if it lands first, this can be
re-expressed on top of it).
**Validation.** Both new cases fail on main and pass with the fix. `npm
run check` and `tsc --noEmit` are clean. Default suite with the fix:
3358 passed, 32 skipped, 2 failed: the `acp-scenarios` path
normalization, which also fails on main at `/usr/bin/node`, and one run
of a timing-sensitive hold test under heavy machine load (re-run quiet:
0/50 both ways, with and without the fix). Re-run on current `main`
(c7c80f7): 3378 passed, 32 skipped, 1 failed (the same `acp-scenarios`
case). No live-provider tests were run.
Co-authored-by: Ben Brandt <benjamin.j.brandt@gmail.com>
This commit is contained in:
@@ -28392,6 +28392,64 @@ describe("turn steering (_session/steering)", () => {
|
||||
expect(agent.sessions["test-session"].owedTrailingIdles).toBe(0);
|
||||
});
|
||||
|
||||
// The same guard when the autonomous cycle's result is stamped with the
|
||||
// original prompt: answersPendingPrompt then routes it to the user lane, and
|
||||
// its idle must still not settle the turn while the steered work runs.
|
||||
it.each(["end_turn", "refusal"] as const)(
|
||||
"does not settle a steered turn on an autonomous %s result naming the original prompt",
|
||||
async (stopReason) => {
|
||||
const timeline: string[] = [];
|
||||
const agent = new ClaudeAcpAgent(timelineClient(timeline), {
|
||||
log: () => {},
|
||||
error: () => {},
|
||||
});
|
||||
|
||||
injectGeneratorSession(agent, (input) => {
|
||||
async function* messageGenerator() {
|
||||
const iter = input[Symbol.asyncIterator]();
|
||||
const u1 = await iter.next();
|
||||
yield userEcho(u1.value);
|
||||
yield createAssistantText("working on it");
|
||||
const steered = await iter.next();
|
||||
yield { ...interruptedCycleResult(), user_message_uuid: u1.value.uuid };
|
||||
yield userEcho(steered.value);
|
||||
// A background cycle's result, stamped with the original prompt only.
|
||||
yield {
|
||||
...createResultMessage(),
|
||||
stop_reason: stopReason,
|
||||
origin: { kind: "task-notification" },
|
||||
user_message_uuid: u1.value.uuid,
|
||||
user_message_uuids: [u1.value.uuid],
|
||||
};
|
||||
yield idleMessage(); // that cycle's trailer
|
||||
yield createAssistantText("STEERED-OK");
|
||||
yield createResultMessage();
|
||||
yield idleMessage();
|
||||
}
|
||||
return messageGenerator();
|
||||
});
|
||||
|
||||
const turn = agent
|
||||
.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "start" }] })
|
||||
.then((response) => {
|
||||
timeline.push(`prompt:${response.stopReason}`);
|
||||
return response;
|
||||
});
|
||||
await waitFor(() => !!agent.sessions["test-session"]?.activeTurn);
|
||||
await agent.steer({
|
||||
sessionId: "test-session",
|
||||
prompt: [{ type: "text", text: "also handle X" }],
|
||||
});
|
||||
|
||||
await turn;
|
||||
await agent.sessions["test-session"]?.consumer;
|
||||
|
||||
// The turn keeps one stop reason across its cycles, so a refusal trailer's
|
||||
// reason is reported; what matters here is that the prompt ends last.
|
||||
expect(timeline).toEqual(["working on it", "STEERED-OK", `prompt:${stopReason}`]);
|
||||
},
|
||||
);
|
||||
|
||||
it("always injects at 'now' priority, ignoring any client-supplied priority", async () => {
|
||||
const agent = createMockAgent();
|
||||
const captured: any[] = [];
|
||||
|
||||
@@ -797,7 +797,8 @@ type Turn = {
|
||||
* `steeredSettle`. `steeredSettle` can already hold the interrupted cycle's
|
||||
* outcome (or a held turn's, moved over by `steer()`) when the echo lands, so
|
||||
* while this is set the recorded outcome predates the steered work and an
|
||||
* idle must not settle on it. */
|
||||
* idle must not settle on it. A result of an autonomous cycle that names
|
||||
* none of the turn's steers is not steered work, so it does not clear it. */
|
||||
steeredAwaitingResult?: boolean;
|
||||
/** What a steered turn settles with once its steered work has run: the outcome
|
||||
* of its latest result, so its usage covers every cycle the turn ran. */
|
||||
@@ -3907,14 +3908,19 @@ export class ClaudeAcpAgent {
|
||||
* calling settleActive directly bypasses the hold and re-opens the
|
||||
* out-of-turn permission deadlock (issue #866) through its lane. For a
|
||||
* client with `backgroundSubagents` this always settles now. */
|
||||
const settleOrDefer = async (outcome: TurnOutcome) => {
|
||||
const settleOrDefer = async (
|
||||
outcome: TurnOutcome,
|
||||
{ steeredWork = true }: { steeredWork?: boolean } = {},
|
||||
) => {
|
||||
// No result ends a steered turn: the steer aborted the cycle this result
|
||||
// may belong to, and the steered one is still to come. Record the outcome
|
||||
// for the idle lane (see Turn.steeredEchoes); later cycles overwrite it,
|
||||
// so the last result and its usage win.
|
||||
if (isSteering(session.activeTurn)) {
|
||||
session.activeTurn.steeredSettle = outcome;
|
||||
session.activeTurn.steeredAwaitingResult = false;
|
||||
// Only a result of the steered work ends the wait for it (see
|
||||
// Turn.steeredAwaitingResult).
|
||||
if (steeredWork) session.activeTurn.steeredAwaitingResult = false;
|
||||
return;
|
||||
}
|
||||
if (
|
||||
@@ -5612,6 +5618,10 @@ export class ClaudeAcpAgent {
|
||||
// commands whose shared or late result this is, even when the
|
||||
// result is the ACTIVE turn's (ensureActiveTurn never looks at
|
||||
// the map in that case).
|
||||
// Whether this result names one of the turn's steers. The settle
|
||||
// calls below read it too: a result of a cycle Claude Code started
|
||||
// that names none of them is not the steered work's result.
|
||||
let answersSteer = false;
|
||||
if (!isAutonomousResult) {
|
||||
recordResultForOrphanCommands();
|
||||
await ensureActiveTurn(message.user_message_uuid, message.user_message_uuids);
|
||||
@@ -5629,7 +5639,6 @@ export class ClaudeAcpAgent {
|
||||
const consumed =
|
||||
message.user_message_uuids ??
|
||||
(message.user_message_uuid !== undefined ? [message.user_message_uuid] : []);
|
||||
let answersSteer = false;
|
||||
for (const uuid of consumed) {
|
||||
steeredTurn.steeredEchoes.delete(uuid);
|
||||
if (steeredTurn.steeredUuids?.has(uuid)) answersSteer = true;
|
||||
@@ -6070,7 +6079,9 @@ export class ClaudeAcpAgent {
|
||||
// settling it out from under them would strand their output
|
||||
// and permission requests out-of-turn (issue #866's deadlock,
|
||||
// through the refusal lane).
|
||||
await settleOrDefer(turnOutcome(session, "refusal"));
|
||||
await settleOrDefer(turnOutcome(session, "refusal"), {
|
||||
steeredWork: !startedByClaudeCode || answersSteer,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -6258,7 +6269,9 @@ export class ClaudeAcpAgent {
|
||||
await compaction.reset();
|
||||
}
|
||||
if (!session.cancelled) {
|
||||
await settleOrDefer(turnOutcome(session, stopReason));
|
||||
await settleOrDefer(turnOutcome(session, stopReason), {
|
||||
steeredWork: !startedByClaudeCode || answersSteer,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
if (!isAutonomousResult) {
|
||||
|
||||
Reference in New Issue
Block a user