fix: emit "cancelled" instead of "end_turn" when the session was interrupted. (#694)

### Summary

Fix session_state_changed: idle handler to check session.cancelled,
ensuring the prompt response returns stopReason:
  "cancelled" instead of "end_turn" when the session was interrupted.

### Problem

When a client sends session/cancel, the cancel() method sets
session.cancelled = true and calls query.interrupt(). The
SDK then transitions to idle state and emits a session_state_changed
event with state: "idle". However, the handler
for this event returns the prompt response immediately without checking
session.cancelled:

```
  case "session_state_changed": {
    if (message.state === "idle") {
      return { stopReason, usage: sessionUsage(session) };  // stopReason defaults to "end_turn"
    }
    break;
  }
```
Since stopReason is initialized as "end_turn" and may not have been
updated to "cancelled" by a preceding result
message (the result handler at line 601 does check session.cancelled),
the prompt response can incorrectly report
  stopReason: "end_turn" when the turn was actually cancelled.

This causes clients (e.g. JetBrains AI Assistant) to treat the turn as
completed normally rather than cancelled,
  leaving the frontend UI stuck in a "running" state.

### Fix

Check session.cancelled in the session_state_changed: idle handler,
mirroring the checks already present in the done
  handler (line 464) and the result handler (line 601):

```
  case "session_state_changed": {
    if (message.state === "idle") {
      if (session.cancelled) {
        stopReason = "cancelled";
      }
      return { stopReason, usage: sessionUsage(session) };
    }
    break;
  }
```

Per the ACP spec, upon receiving session/cancel the agent must respond
to the original session/prompt request with
StopReason::Cancelled. This fix ensures that obligation is met
regardless of which message type triggers the prompt
  response.

### Test plan

- Start a session, send a prompt, then immediately cancel — verify the
prompt response returns stopReason: "cancelled"
   and the client UI transitions out of "running" state
- Start a session, send a prompt, let it complete normally — verify
stopReason remains "end_turn" (no false
  cancellation)
  - Existing test suite passes (npm run test:run)
This commit is contained in:
Genhao Liu
2026-05-22 06:00:44 +08:00
committed by GitHub
parent cfce130707
commit 2414a6f98b

View File

@@ -864,6 +864,9 @@ export class ClaudeAcpAgent implements Agent {
}
case "session_state_changed": {
if (message.state === "idle") {
if (session.cancelled) {
stopReason = "cancelled";
}
return { stopReason, usage: sessionUsage(session) };
}
break;