fix: follow the permission mode that Claude Code reports (#1740)

Stacked on #1737: both change `SessionModeManager` and the mode tests.
Merge #1737 first. GitHub then points this PR at `main`.

The adapter decides a session's permission mode itself and passes it to
Claude Code at launch. Claude Code can then end up in another mode, and
the adapter never heard of it: neither core read the mode that Claude
Code reports.

## What went wrong

With a client's `settings` that disable Auto mode (`disableAutoMode:
"disable"`), on a machine whose default mode is `auto`:

- the adapter starts the session with `--permission-mode auto` and shows
Auto;
- Claude Code starts in `auto` and moves to `default` a moment later;
- the session's mode option keeps showing Auto while every tool call
asks for permission.

Seen on v1 and v2 with Claude Code 2.1.333.

## Change

Claude Code reports the session's mode in two frames, both declared in
the SDK types:

- `system`/`status` with `permissionMode`, after a change. It sends one
after a change that the adapter asked for too.
- `system`/`init` with `permissionMode`, at the start of each turn.

Both cores now record that mode and tell the client:

- `SessionModeManager.modeReported` (`src/session-mode.ts`) owns the
rule for v1: nothing for the mode already recorded, a log line for a
mode that the session does not offer, and nothing for a frame of a query
that the session no longer runs on. The v1 loop calls it for both
frames, and the `EnterPlanMode` hook goes through it as well, so the
first of the hook and the frame is recorded.
- v2 calls its existing `modeChanged` for both frames. It already had
the same two checks for `EnterPlanMode`.

The `init` frame is needed beside the `status` frame: in three live runs
of the case above on v1, the `status` frame reached the loop once. In
the other two, the first report of `default` was the `init` frame of the
first turn. On v2 the `status` frame arrived in all three runs.

`current_permission_mode` in the answer to the initialize request is not
used. The SDK types do not declare it, and in two of three runs it still
said `auto`.

## Limits

- The `session/new` response can still say `auto`. On v1 the correction
arrives when the first turn starts: the adapter reads Claude Code's
frames from the first prompt on. On v2 it arrived within 1.5 seconds of
`session/new`, before any prompt, in three of three runs.
- The mode list still offers Auto in that session. Choosing it fails
with Claude Code's own message, "Cannot set permission mode to auto:
auto mode disabled by settings".
- Nothing ties a frame to the request that caused it. After two quick
mode changes by the client, the first one's frame can arrive when the
second mode is already recorded, and the session shows the first mode
until the second frame arrives.

## Checked against Claude Code 2.1.333

- The case above, three runs each on v1 and v2: the client is told
`default` once in every run.
- A plan approved from plan mode, on v1 and v2: the same updates as
before the change, in the same order.
- A subagent with its own `permissionMode` does not report it as the
session's mode.

## Testing

- `src/tests/session-mode.test.ts`: a reported mode is recorded and
announced; nothing for the recorded mode, for a mode that the session
does not offer (logged), and for a frame of a former query.
- `src/tests/v1/acp-agent.test.ts`, `src/tests/v2/v2.test.ts`: both
frames change the session's mode in each core.
- `npm run build`, `npm run check` and `npm run test:run` (4,959 tests
pass), and the whole suite against Claude Code 2.1.333 with
`RUN_INTEGRATION_TESTS=true` (5,010 tests pass), on this branch together
with #1737, #1738, #1739 and #1741. In that run the 10 s `tsc` setup
hook of "ACP subprocess integration" timed out on a loaded machine; that
suite passes by itself.
This commit is contained in:
Ben Brandt
2026-12-01 18:12:16 +01:00
committed by GitHub
parent 4dd607cec1
commit 5ff3411cfa
6 changed files with 167 additions and 2 deletions

View File

@@ -392,6 +392,37 @@ export class SessionModeManager<S extends SessionMode> {
});
}
/**
* Records the mode that Claude Code reports for `session`, and tells the
* client. Claude Code reports the mode in the `init` frame at the start of
* each turn, and in a `status` frame after a change. That covers a change
* of its own: a session that starts in `auto` while settings disable Auto
* mode is in `default` a moment later, with a `status` frame or, when the
* change came before the answer to the initialize request, without one.
*
* Changes nothing for the mode already recorded, which is what a frame
* names after a change that the adapter asked for, and for a mode that the
* session does not offer, which is logged (see {@link setQueryMode}).
*
* Nothing ties a frame to the request that caused it. After two quick
* changes by the client, the first one's frame can arrive when the second
* mode is already recorded: the session then shows the first mode until
* the second frame arrives.
*/
async modeReported(sessionId: string, session: S, mode: PermissionMode): Promise<void> {
// A frame of a query that the session no longer runs on is not its mode.
if (this.options.getSession(sessionId) !== session) return;
if (session.modes.currentModeId === mode) return;
if (!this.isAvailable(session.modes.availableModes, mode)) {
this.options.logError(
`Claude Code reports permission mode "${mode}", which the session does not offer; keeping "${session.modes.currentModeId}".`,
);
return;
}
await this.publishCurrent(sessionId, mode);
await this.options.updateConfigOption(sessionId, MODE_CONFIG_ID, mode);
}
async publishFallbackWarning(sessionId: string, session: SessionMode): Promise<void> {
session.autoModeFallbackWarningPending = false;
if (session.autoModeFallbackWarningShown) return;

View File

@@ -188,6 +188,44 @@ describe("session mode", () => {
);
});
it.each([
{
name: "records a mode that Claude Code reports, and tells the client",
reported: "plan",
recorded: "plan",
},
{ name: "changes nothing for a report of the recorded mode", reported: "default" },
{
name: "logs a reported mode that the session does not offer, and keeps the recorded one",
reported: "dontAsk",
logged: true,
},
{
name: "changes nothing for a report from a query that the session no longer runs on",
reported: "plan",
fromFormerQuery: true,
},
] as const)("$name", async ({ reported, recorded, logged = false, fromFormerQuery = false }) => {
const session = createSession();
const updates: SessionNotification[] = [];
const { manager, notifications, updateConfigOption } = createManager(session, updates);
await manager.modeReported(SESSION_ID, fromFormerQuery ? createSession() : session, reported);
expect(updates).toEqual(
recorded
? [
{
sessionId: SESSION_ID,
update: { sessionUpdate: "current_mode_update", currentModeId: recorded },
},
]
: [],
);
expect(updateConfigOption.mock.calls).toEqual(recorded ? [[SESSION_ID, "mode", recorded]] : []);
expect(notifications.logError).toHaveBeenCalledTimes(logged ? 1 : 0);
});
it("rejects missing and closed sessions", async () => {
await expect(
createManager(undefined).manager.setSessionMode({ sessionId: SESSION_ID, modeId: "plan" }),

View File

@@ -17923,6 +17923,59 @@ describe("usage_update computation", () => {
});
});
describe("permission mode that Claude Code reports", () => {
it.each([
[
// What Claude Code 2.1.333 sends once it left `auto` because settings disable Auto mode.
"a status frame",
{ type: "system", subtype: "status", status: null, permissionMode: "default" },
],
[
// The start of a turn. Claude Code does not always send the status frame of that change.
"the init frame of a turn",
{ type: "system", subtype: "init", permissionMode: "default" },
],
])("records the mode of %s, and tells the client", async (_, frame) => {
const updates: SessionNotification[] = [];
const agent = new ClaudeAcpAgent(
{
sessionUpdate: async (notification: SessionNotification) => {
updates.push(notification);
},
} as unknown as AcpClient,
{ log: vi.fn(), error: vi.fn() },
);
await initializeClient(agent, {});
const input = new Pushable<any>();
async function* messages() {
const { value } = await input[Symbol.asyncIterator]().next();
yield { ...frame, uuid: randomUUID(), session_id: "test-session" };
yield userEcho(value);
yield successfulResultMessage();
yield { type: "system", subtype: "session_state_changed", state: "idle" };
}
agent.sessions["test-session"] = mockSessionState({
query: wrapQuery(messages()),
input,
modes: {
currentModeId: "auto",
availableModes: [
{ id: "default", name: "Manual" },
{ id: "auto", name: "Auto" },
],
},
});
await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "hi" }] });
expect(agent.sessions["test-session"]!.modes.currentModeId).toBe("default");
expect(updates.map((notification) => notification.update)).toContainEqual({
sessionUpdate: "current_mode_update",
currentModeId: "default",
});
});
});
describe("foreground fork tool results", () => {
it.each([
["plain", {}, null],

View File

@@ -1735,6 +1735,27 @@ describe("ACP v2 core", () => {
});
});
it.each([
// What Claude Code 2.1.333 sends after a mode change, also one of its own.
["a status frame", { type: "system", subtype: "status", status: null, permissionMode: "plan" }],
// The start of a turn. Claude Code does not always send the status frame of a change.
["the init frame of a turn", { type: "system", subtype: "init", permissionMode: "plan" }],
])("records the mode that Claude Code reports in %s", async (_name, frame) => {
const client = v2Client();
await client.connect(async (agent) => {
const { claude } = await openSession(agent);
claude.send({ ...frame, uuid: randomUUID(), mcp_servers: [] });
await vi.waitFor(() =>
expect(client.sessionUpdates).toContainEqual({
sessionUpdate: "config_option_update",
configOptions: expect.arrayContaining([
expect.objectContaining({ configId: "mode", currentValue: "plan" }),
]),
}),
);
});
});
it("stays idle at the echo of a model change's local command output", async () => {
const client = v2Client();
await client.connect(async (agent) => {

View File

@@ -5156,6 +5156,14 @@ export class ClaudeAcpAgent {
case "system":
switch (message.subtype) {
case "init":
// The mode at the start of the turn (see `modeReported`).
if (message.permissionMode) {
await this.sessionModes.modeReported(
params.sessionId,
session,
message.permissionMode,
);
}
// Latch the lifecycle capability so cancel() routes orphan
// accounting through `orphanCommands` (per-uuid, exact)
// instead of the coalescing-blind count. Never unlatch: init
@@ -5229,6 +5237,14 @@ export class ClaudeAcpAgent {
);
break;
case "status": {
// The mode after a change (see `modeReported`).
if (message.permissionMode) {
await this.sessionModes.modeReported(
params.sessionId,
session,
message.permissionMode,
);
}
// A model request that serves none of the prompts a cancel
// stopped is new work, such as Claude Code's follow-up after a
// background command finished. It comes after the stopped
@@ -10887,9 +10903,11 @@ export class ClaudeAcpAgent {
hooks: [
...(subagentConfigHook ? [subagentConfigHook] : []),
createPostToolUseHook({
// Claude Code reports the mode in a `status` frame too: the
// first of the two is recorded.
onEnterPlanMode: async () => {
await this.sessionModes.publishCurrent(sessionId, "plan");
await this.updateConfigOption(sessionId, MODE_CONFIG_ID, "plan");
const entered = this.sessions[sessionId];
if (entered) await this.sessionModes.modeReported(sessionId, entered, "plan");
},
}),
],

View File

@@ -1209,6 +1209,8 @@ export class V2Session implements RequestTarget {
case "system":
switch (message.subtype) {
case "init":
// Claude Code's report of the mode at the start of the turn.
if (message.permissionMode) this.modeChanged(message.permissionMode);
if (message.capabilities?.includes("msg_lifecycle_v1")) this.lifecycleFrames = true;
this.elicitations.init(message.capabilities);
// A fresh init (such as after a reinitialize) can carry another Fast mode state.
@@ -1218,6 +1220,8 @@ export class V2Session implements RequestTarget {
if (this.commands.init(message)) this.resendCommands();
return;
case "status":
// Claude Code's report of the mode after a change, also one of its own.
if (message.permissionMode) this.modeChanged(message.permissionMode);
// Each model request starts with one, which lists the prompts it serves.
if (message.status === "requesting") {
const prompts = (message as { user_message_uuids?: unknown }).user_message_uuids;