mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-16 14:22:28 +00:00
Compare commits
5 Commits
v0.107.2-p
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc769c132c | ||
|
|
b437e4ee16 | ||
|
|
81650db3d3 | ||
|
|
c03b66cc9f | ||
|
|
7d9e1f6135 |
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.107.1"
|
||||
".": "0.107.2"
|
||||
}
|
||||
|
||||
13
CHANGELOG.md
13
CHANGELOG.md
@@ -1,5 +1,18 @@
|
||||
# Changelog
|
||||
|
||||
## [0.107.2](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.1...v0.107.2) (2026-11-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* end the turn task of a cycle that has no turn to claim its result ([#1622](https://github.com/agentclientprotocol/claude-agent-acp/issues/1622)) ([8de4981](https://github.com/agentclientprotocol/claude-agent-acp/commit/8de49818f1172c5187496a736f721dc6d2ba3fec))
|
||||
* keep Fast mode on when it is turned on after a model switch or mid-turn ([#1637](https://github.com/agentclientprotocol/claude-agent-acp/issues/1637)) ([81650db](https://github.com/agentclientprotocol/claude-agent-acp/commit/81650db3d3ca6f7b640fd5e1bbb5e1ff45f62fb7))
|
||||
* list a live Monitor whose task Claude Code reports as local_bash ([#1607](https://github.com/agentclientprotocol/claude-agent-acp/issues/1607)) ([41417f6](https://github.com/agentclientprotocol/claude-agent-acp/commit/41417f6eeeb5010c0eb439e256032cd7e9a44e37))
|
||||
* read the Claude Code stream after a query restart, not at the next prompt ([#1636](https://github.com/agentclientprotocol/claude-agent-acp/issues/1636)) ([c03b66c](https://github.com/agentclientprotocol/claude-agent-acp/commit/c03b66cc9f1aa6aa5e56668ac05e5a7f48418850))
|
||||
* read the Claude Code stream after every session setup, not at the first prompt ([#1623](https://github.com/agentclientprotocol/claude-agent-acp/issues/1623)) ([7d9e1f6](https://github.com/agentclientprotocol/claude-agent-acp/commit/7d9e1f6135b2c85cd8bdd0e76bc2bcf00795e6c9))
|
||||
* reject the SDK no-token sentinel in auth guards ([#1609](https://github.com/agentclientprotocol/claude-agent-acp/issues/1609)) ([c203b91](https://github.com/agentclientprotocol/claude-agent-acp/commit/c203b919ecca8a58e11bebb72274a5a203653d88))
|
||||
* update to @anthropic-ai/claude-agent-sdk 0.3.325 ([#1634](https://github.com/agentclientprotocol/claude-agent-acp/issues/1634)) ([db54135](https://github.com/agentclientprotocol/claude-agent-acp/commit/db5413513cbe58c045885e6bb015abfdb76be524))
|
||||
|
||||
## [0.107.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.0...v0.107.1) (2026-11-16)
|
||||
|
||||
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@agentclientprotocol/claude-agent-acp",
|
||||
"version": "0.107.1",
|
||||
"version": "0.107.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@agentclientprotocol/claude-agent-acp",
|
||||
"version": "0.107.1",
|
||||
"version": "0.107.2",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.7.0",
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"version": "0.107.1",
|
||||
"version": "0.107.2",
|
||||
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
|
||||
"main": "dist/lib.js",
|
||||
"types": "dist/lib.d.ts",
|
||||
|
||||
@@ -192,12 +192,20 @@ export function buildConfigOptions(
|
||||
* a fallback for resolutions that don't map back onto a selectable option
|
||||
* (e.g. a fuzzy hit on an out-of-picker verbatim entry). `value` is then the
|
||||
* canonical option value, the model id rather than the alias.
|
||||
*
|
||||
* With `passUnlisted`, a model value that resolves to none of the entries is
|
||||
* returned as it is, marked `unlisted`, for Claude Code to decide: the CLI's
|
||||
* picker leaves out models it runs, such as `claude-fable-5-2` before a CLI
|
||||
* lists it, or `claude-opus-4-6` once a newer Opus replaces it.
|
||||
* {@link setSelectedModel} refuses it with invalid params when Claude Code
|
||||
* does. Without it, such a value is refused here.
|
||||
*/
|
||||
export function configOptionValue(
|
||||
option: SessionConfigOption,
|
||||
params: SetSessionConfigOptionRequest,
|
||||
modelInfos: ModelInfo[],
|
||||
): { enabled: boolean } | { value: string } {
|
||||
passUnlisted = false,
|
||||
): { enabled: boolean } | { value: string; unlisted?: true } {
|
||||
const expectedType = option.type === "boolean" ? "boolean" : "string";
|
||||
if (typeof params.value !== expectedType) {
|
||||
throw RequestError.invalidParams(
|
||||
@@ -233,6 +241,9 @@ export function configOptionValue(
|
||||
}));
|
||||
validValue = toOptionValue(resolveModelPreference(optionInfos, requested));
|
||||
}
|
||||
if (!validValue && passUnlisted && requested.trim() !== "") {
|
||||
return { value: requested.trim(), unlisted: true };
|
||||
}
|
||||
}
|
||||
if (!validValue) {
|
||||
throw RequestError.invalidParams(
|
||||
@@ -242,3 +253,59 @@ export function configOptionValue(
|
||||
}
|
||||
return { value: validValue.value };
|
||||
}
|
||||
|
||||
/**
|
||||
* The codes with which Claude Code's `setModel` refuses a model id that the
|
||||
* session cannot use: an id it does not know (`not_found`,
|
||||
* `catalog_unknown`), one that settings restrict (`restricted_by_org`: an
|
||||
* `availableModels` allowlist, a managed `deniedModels` entry), one the
|
||||
* account or this CLI does not offer, and a `[1m]` form that is turned off or
|
||||
* that the model lacks.
|
||||
*
|
||||
* Claude Code sends the code as `error_code` of its answer and the SDK
|
||||
* (0.3.325) copies it to `errorCode` of the error that `setModel()` rejects
|
||||
* with. The SDK's types do not declare it.
|
||||
*/
|
||||
const UNUSABLE_MODEL_ERROR_CODES: ReadonlySet<string> = new Set([
|
||||
"not_found",
|
||||
"catalog_unknown",
|
||||
"restricted_by_org",
|
||||
"unavailable_for_account",
|
||||
"not_offered",
|
||||
"alias_1m_disabled",
|
||||
"alias_1m_unsupported",
|
||||
]);
|
||||
|
||||
/** Whether `setModel()` rejected with `error` because the session cannot use the model id. */
|
||||
function refusesModelId(error: unknown): error is Error {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const code = (error as { errorCode?: unknown }).errorCode;
|
||||
return typeof code === "string" && UNUSABLE_MODEL_ERROR_CODES.has(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches `query` to the model that {@link configOptionValue} selected.
|
||||
*
|
||||
* When Claude Code refuses an `unlisted` id as one the session cannot use
|
||||
* (see {@link UNUSABLE_MODEL_ERROR_CODES}), that is invalid params with Claude
|
||||
* Code's reason ("Model 'gpt-4' not found"), as for a value the option lacks.
|
||||
* Every other failure is thrown as it is and reaches the client as an
|
||||
* internal error: a failed switch to a listed value, and a failure that does
|
||||
* not judge the id, such as `auth_failed`, `rate_limit`, `check_unreachable`
|
||||
* (the API did not answer), `blocked_by_hook`, a closed query, or a refusal
|
||||
* without a code.
|
||||
*/
|
||||
export async function setSelectedModel(
|
||||
query: Pick<Query, "setModel">,
|
||||
selected: { value: string; unlisted?: true },
|
||||
): Promise<void> {
|
||||
try {
|
||||
await query.setModel(selected.value);
|
||||
} catch (error) {
|
||||
if (!selected.unlisted || !refusesModelId(error)) throw error;
|
||||
throw RequestError.invalidParams(
|
||||
undefined,
|
||||
`Invalid value for config option ${MODEL_CONFIG_ID}: ${selected.value}. ${error.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +130,27 @@ export function resolveFastModeEnabled(params: SetSessionConfigOptionRequest): b
|
||||
);
|
||||
}
|
||||
|
||||
/** Set the Fast mode flag on Claude Code, through `applyFlagSettings`.
|
||||
*
|
||||
* Turning it on sends `fastMode: false` first, a workaround for Claude Code
|
||||
* (CLI 2.1.325): it acts on `fastMode: true` only when its flag does not hold
|
||||
* `true` already, and ignores a repeat. Its flag stays `true` while it stops
|
||||
* serving Fast mode at a model switch (Fable 5.2 and Mythos 5.2 take only a
|
||||
* Fast mode that was turned on while they were selected) and reports
|
||||
* `fast_mode_state: "off"`. Without the reset, turning the toggle back on
|
||||
* changes nothing there, and the next `system`/init turns it off again.
|
||||
*
|
||||
* A refusal of the reset changes nothing. If Claude Code takes the reset and
|
||||
* refuses `true`, it is left off; the caller's option keeps its value, and the
|
||||
* next `system`/init turns off an option that reads on. */
|
||||
export async function applyFastModeFlag(
|
||||
applyFlagSettings: (settings: { fastMode: boolean }) => Promise<void>,
|
||||
enabled: boolean,
|
||||
): Promise<void> {
|
||||
if (enabled) await applyFlagSettings({ fastMode: false });
|
||||
await applyFlagSettings({ fastMode: enabled });
|
||||
}
|
||||
|
||||
/** Per-model Fast mode state threaded into `buildConfigOptions`. The
|
||||
* option is only surfaced when the current model `supported`s fast mode. */
|
||||
export type FastModeOptionState = {
|
||||
@@ -162,8 +183,10 @@ export type FastModeOptionState = {
|
||||
* `notice` is set when the user had Fast mode on and the SDK turned it off
|
||||
* with a retained reason: the description carries the same explanation, but a
|
||||
* toggle silently snapping back is worth saying out loud once. Off with no
|
||||
* reason, `sdk_opt_in_required` or `pending` stays quiet: a `result` can carry
|
||||
* the turn-start snapshot, so a notice there would falsely say "turned off". */
|
||||
* reason, `sdk_opt_in_required` or `pending` stays quiet: a report can carry
|
||||
* the flag as it was before a request of ours (see
|
||||
* {@link fastModeResultIsNews}), so a notice there would falsely say "turned
|
||||
* off". */
|
||||
export function fastModeStateChange(
|
||||
current: { enabled: boolean; disabledReason?: FastModeDisabledReason },
|
||||
state: FastModeState | undefined,
|
||||
@@ -195,6 +218,41 @@ export function fastModeStateChange(
|
||||
};
|
||||
}
|
||||
|
||||
/** A Fast mode report of Claude Code: the `fast_mode_state` and
|
||||
* `fast_mode_disabled_reason` of a `system`/init or of a result. */
|
||||
export type FastModeReport = {
|
||||
state: FastModeState | undefined;
|
||||
reason: FastModeDisabledReason | undefined;
|
||||
};
|
||||
|
||||
/** Whether a result's Fast mode report says something that `init`, the report
|
||||
* of its turn's `system`/init, did not.
|
||||
*
|
||||
* Claude Code (CLI 2.1.325) reads the `fastMode` flag once when a turn starts
|
||||
* and builds that turn's init and result from the one reading. A result that
|
||||
* repeats its init therefore predates a `session/set_config_option` that
|
||||
* arrived in between: mirroring it would turn the toggle back, until the next
|
||||
* turn's init. What a result adds is what Claude Code evaluates when it sends
|
||||
* it: a refusal by the account or the model, or the end of one.
|
||||
*
|
||||
* Reasons compare as retained ({@link normalizeFastModeDisabledReason}):
|
||||
* turning Fast mode on mid-turn drops `sdk_opt_in_required` from the result,
|
||||
* which is no news. True without an init, as for a result whose turn sent none.
|
||||
*
|
||||
* Not covered: a request that Claude Code applies after it read the flag and
|
||||
* before it sent the init. That init reports the earlier value too, and the
|
||||
* next turn's init corrects the toggle. */
|
||||
export function fastModeResultIsNews(
|
||||
init: FastModeReport | undefined,
|
||||
result: FastModeReport,
|
||||
): boolean {
|
||||
if (init === undefined) return true;
|
||||
return (
|
||||
result.state !== init.state ||
|
||||
normalizeFastModeDisabledReason(result.reason) !== normalizeFastModeDisabledReason(init.reason)
|
||||
);
|
||||
}
|
||||
|
||||
/** The notice of Fast mode that the SDK turned off, and its transcript line
|
||||
* for a client without `notice` updates. */
|
||||
export type FastModeOffNotice = {
|
||||
|
||||
@@ -62,6 +62,19 @@ export function startupFailure(reason: string, cliMessage: string): Error {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The error `setModel()` rejects with when Claude Code refuses the switch, as
|
||||
* SDK 0.3.325 builds it from the CLI's answer: `errorCode` is the answer's
|
||||
* `error_code`, such as `not_found` for "Model 'gpt-4' not found".
|
||||
*/
|
||||
export function setModelRefusal(message: string, errorCode: string): Error {
|
||||
return Object.assign(new Error(message), {
|
||||
telemetryMessage: "Claude Code control request failed (set_model)",
|
||||
errorClass: "control_request_failed",
|
||||
errorCode,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Declares the client capabilities through `initialize`, as a real client
|
||||
* does. The agent reads its capability choices only there.
|
||||
|
||||
@@ -15020,8 +15020,9 @@ describe("session/fork", () => {
|
||||
const modes = { currentModeId: "plan", availableModes: [] };
|
||||
|
||||
/** An agent whose sessions start without Claude Code: each one gets a
|
||||
* scripted query that runs `turn` for every prompt. */
|
||||
function forkingAgent(turn: (prompt: any) => any[] = () => []) {
|
||||
* scripted query that runs `turn` for every prompt, after it sent `backlog`
|
||||
* with no prompt open. */
|
||||
function forkingAgent(turn: (prompt: any) => any[] = () => [], backlog: any[] = []) {
|
||||
const updates: SessionNotification[] = [];
|
||||
const agent = new ClaudeAcpAgent(
|
||||
{ sessionUpdate: async (n: SessionNotification) => updates.push(n) } as unknown as AcpClient,
|
||||
@@ -15035,6 +15036,7 @@ describe("session/fork", () => {
|
||||
const sessionId = options.resume as string;
|
||||
const input = new Pushable<any>();
|
||||
async function* answer() {
|
||||
yield* backlog;
|
||||
for await (const prompt of input) yield* turn(prompt);
|
||||
}
|
||||
agent.sessions[sessionId] = mockSessionState(
|
||||
@@ -15115,6 +15117,57 @@ describe("session/fork", () => {
|
||||
expect(agent.sessions["fork-id"]).toBe(forked);
|
||||
});
|
||||
|
||||
// After a bridge restart, Claude Code runs a cron cycle and a background
|
||||
// task's follow-up before the first prompt. Nothing read the stream until
|
||||
// then, and the prompt took the cron cycle's result as its own.
|
||||
it.each(["resumeSession", "loadSession"] as const)(
|
||||
"reads what Claude Code sends before the first prompt after %s (#1621)",
|
||||
async (method) => {
|
||||
const state = (state: "running" | "idle") => ({
|
||||
type: "system",
|
||||
subtype: "session_state_changed",
|
||||
state,
|
||||
uuid: randomUUID(),
|
||||
session_id: "resumed-id",
|
||||
});
|
||||
const usage = (input: number, output: number) => ({
|
||||
input_tokens: input,
|
||||
output_tokens: output,
|
||||
cache_read_input_tokens: 0,
|
||||
cache_creation_input_tokens: 0,
|
||||
});
|
||||
const { agent } = forkingAgent(
|
||||
(prompt) => [
|
||||
userEcho(prompt),
|
||||
state("running"),
|
||||
successfulResultMessage({ usage: usage(7, 3) }),
|
||||
state("idle"),
|
||||
],
|
||||
[
|
||||
// A cron prompt: its result has no origin.
|
||||
state("running"),
|
||||
successfulResultMessage({ usage: usage(111, 11) }),
|
||||
state("idle"),
|
||||
state("running"),
|
||||
successfulResultMessage({ origin: { kind: "task-notification" }, usage: usage(222, 22) }),
|
||||
state("idle"),
|
||||
],
|
||||
);
|
||||
// Only a load replays the transcript.
|
||||
if (method === "loadSession") vi.mocked(getSessionMessages).mockResolvedValueOnce([]);
|
||||
await agent[method]({ sessionId: "resumed-id", cwd: "/workspace", mcpServers: [] });
|
||||
// The reader starts after the response.
|
||||
await vi.waitFor(() => expect(agent.sessions["resumed-id"].lastSessionState).toBe("idle"));
|
||||
|
||||
const response = await agent.prompt({
|
||||
sessionId: "resumed-id",
|
||||
prompt: [{ type: "text", text: "go on" }],
|
||||
});
|
||||
|
||||
expect(response.usage).toMatchObject({ inputTokens: 7, outputTokens: 3 });
|
||||
},
|
||||
);
|
||||
|
||||
it("fails when the forked session cannot start", async () => {
|
||||
const { agent, createSession } = forkingAgent();
|
||||
createSession.mockRejectedValueOnce(new Error("Claude Code did not start"));
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { AcpClient } from "../../acp-client.js";
|
||||
import type { AcpSessionNotification } from "../../acp-subagents.js";
|
||||
import { ALLOW_BYPASS } from "../../permissions/modes.js";
|
||||
import { NativeSubagentRuntime } from "../../native-subagents.js";
|
||||
import { startupFailure } from "../helpers.js";
|
||||
import { setModelRefusal, startupFailure } from "../helpers.js";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
@@ -46,9 +46,19 @@ vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
|
||||
...actual,
|
||||
query: (args: { prompt: unknown; options: Options }) => {
|
||||
capturedOptions = args.options;
|
||||
// Like Claude Code's, the stream stays open until the query is closed.
|
||||
let streamClosed = () => {};
|
||||
const closed = new Promise<void>((resolve) => (streamClosed = resolve));
|
||||
return makeMockQuery({
|
||||
interrupt: () => (interruptImpl ? interruptImpl() : Promise.resolve(undefined)),
|
||||
close: () => closeSpy(),
|
||||
close: () => {
|
||||
closeSpy();
|
||||
streamClosed();
|
||||
},
|
||||
next: async () => {
|
||||
await closed;
|
||||
return { done: true as const, value: undefined };
|
||||
},
|
||||
initializationResult: async () => {
|
||||
await initGate;
|
||||
if (initError) throw initError;
|
||||
@@ -1494,9 +1504,13 @@ describe("createSession options merging", () => {
|
||||
it.each([
|
||||
["an unknown configId", { configId: "nope", value: "x" }],
|
||||
["a boolean for a select", { configId: "model", type: "boolean" as const, value: true }],
|
||||
["a value the option does not offer", { configId: "model", value: "gpt-4" }],
|
||||
["a model Claude Code does not know", { configId: "model", value: "gpt-4" }],
|
||||
])("skips an entry with %s and sets the entries after it", async (_name, entry) => {
|
||||
const plain = await agent.newSession({ cwd, mcpServers: [] });
|
||||
// An id the option does not list goes to Claude Code, which refuses an unknown one.
|
||||
setModelImpl = async (model) => {
|
||||
throw setModelRefusal(`Model '${model}' not found`, "not_found");
|
||||
};
|
||||
|
||||
const response = await agent.newSession({
|
||||
cwd,
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import type { ClientCapabilities, SessionNotification } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { FastModeDisabledReason, ModelInfo } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type {
|
||||
FastModeDisabledReason,
|
||||
FastModeState,
|
||||
ModelInfo,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
|
||||
import {
|
||||
buildConfigOptions,
|
||||
@@ -8,6 +12,7 @@ import {
|
||||
} from "../../session-config-options.js";
|
||||
import {
|
||||
createFastModeConfigOption,
|
||||
fastModeResultIsNews,
|
||||
fastModeStateEnabled,
|
||||
normalizeFastModeDisabledReason,
|
||||
resolveFastModeEnabled,
|
||||
@@ -197,6 +202,30 @@ describe("normalizeFastModeDisabledReason", () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe("fastModeResultIsNews", () => {
|
||||
type Report = [FastModeState | undefined, FastModeDisabledReason | undefined];
|
||||
|
||||
it.each([
|
||||
["has no init to repeat", undefined, ["off", undefined], true],
|
||||
["repeats its init", ["off", undefined], ["off", undefined], false],
|
||||
// Turning Fast mode on mid-turn drops `sdk_opt_in_required` from the result.
|
||||
[
|
||||
"differs only by an unexplained reason",
|
||||
["off", "sdk_opt_in_required"],
|
||||
["off", undefined],
|
||||
false,
|
||||
],
|
||||
["adds a refusal", ["off", undefined], ["off", "extra_usage_disabled"], true],
|
||||
["reports another state", ["off", "network_error"], ["on", undefined], true],
|
||||
] as [string, Report | undefined, Report, boolean][])(
|
||||
"tells whether a result that %s is news",
|
||||
(_case, init, result, news) => {
|
||||
const report = ([state, reason]: Report) => ({ state, reason });
|
||||
expect(fastModeResultIsNews(init && report(init), report(result))).toBe(news);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("buildConfigOptions Fast mode", () => {
|
||||
it("omits the Fast mode option when the model does not support it", () => {
|
||||
const options = buildConfigOptions(MODES, MODELS, MODEL_INFOS, undefined, [], "default", {
|
||||
@@ -271,7 +300,8 @@ describe("setSessionConfigOption Fast mode toggle", () => {
|
||||
type: "boolean",
|
||||
value: true,
|
||||
});
|
||||
expect(applyFlagSettings).toHaveBeenCalledWith({ fastMode: true });
|
||||
// Off first: Claude Code ignores a `true` while its flag holds `true`.
|
||||
expect(applyFlagSettings.mock.calls).toEqual([[{ fastMode: false }], [{ fastMode: true }]]);
|
||||
expect(onResponse.configOptions).toContainEqual(createFastModeConfigOption(true, true));
|
||||
expect(
|
||||
(agent as unknown as { sessions: Record<string, { fastModeEnabled: boolean }> }).sessions[
|
||||
@@ -285,7 +315,7 @@ describe("setSessionConfigOption Fast mode toggle", () => {
|
||||
type: "boolean",
|
||||
value: false,
|
||||
});
|
||||
expect(applyFlagSettings).toHaveBeenLastCalledWith({ fastMode: false });
|
||||
expect(applyFlagSettings.mock.calls.slice(2)).toEqual([[{ fastMode: false }]]);
|
||||
expect(offResponse.configOptions).toContainEqual(createFastModeConfigOption(false, true));
|
||||
});
|
||||
|
||||
@@ -569,12 +599,18 @@ describe("syncFastModeState (SDK-driven state changes)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Fast mode that Claude Code refuses during a turn", () => {
|
||||
describe("Fast mode that Claude Code reports during a turn", () => {
|
||||
const SESSION_ID = "test-session";
|
||||
|
||||
/** A session whose Claude Code answers the first prompt with a `system`/init
|
||||
* that reports Fast mode off with `reason`, as it does on every turn. */
|
||||
async function setupTurn(reason: FastModeDisabledReason) {
|
||||
* that reports Fast mode off with `reason`, as it does on every turn, and
|
||||
* then with a result that carries the `result` fields. `duringTurn` runs
|
||||
* between the two, once the adapter has handled the init. */
|
||||
async function setupTurn(
|
||||
reason: FastModeDisabledReason,
|
||||
result: Record<string, unknown> = {},
|
||||
duringTurn: (agent: ClaudeAcpAgent) => Promise<unknown> = async () => {},
|
||||
) {
|
||||
const updates: SessionNotification[] = [];
|
||||
const client = {
|
||||
sessionUpdate: async (n: SessionNotification) => {
|
||||
@@ -595,7 +631,8 @@ describe("Fast mode that Claude Code refuses during a turn", () => {
|
||||
fast_mode_disabled_reason: reason,
|
||||
session_id: SESSION_ID,
|
||||
};
|
||||
yield successfulResultMessage();
|
||||
await duringTurn(agent);
|
||||
yield successfulResultMessage(result);
|
||||
yield { type: "system", subtype: "session_state_changed", state: "idle" };
|
||||
}
|
||||
const query = Object.assign(wrapQuery(messages()), { applyFlagSettings: async () => {} });
|
||||
@@ -653,4 +690,41 @@ describe("Fast mode that Claude Code refuses during a turn", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
/**
|
||||
* Scenario:
|
||||
* 1. A turn's init reports Fast mode off (`sdk_opt_in_required`: no opt-in yet).
|
||||
* 2. The client turns Fast mode on while the turn runs.
|
||||
* 3. The turn's result reports Fast mode off: Claude Code read the flag when
|
||||
* the turn started. It carries no reason, or the account's refusal.
|
||||
* Expected:
|
||||
* - Without a reason the result repeats the init: `fast` stays on, with no update.
|
||||
* - With `extra_usage_disabled`, `fast` reads off again.
|
||||
*/
|
||||
it.each([
|
||||
["keeps", "repeats the init", {}, true],
|
||||
["turns off", "adds a refusal", { fast_mode_disabled_reason: "extra_usage_disabled" }, false],
|
||||
])(
|
||||
"%s a Fast mode that the client turned on during the turn when the result %s",
|
||||
async (_outcome, _result, reported, enabled) => {
|
||||
const { agent, updates } = await setupTurn(
|
||||
"sdk_opt_in_required",
|
||||
{ fast_mode_state: "off", ...reported },
|
||||
(agent) =>
|
||||
agent.setSessionConfigOption({
|
||||
sessionId: SESSION_ID,
|
||||
configId: "fast",
|
||||
type: "boolean",
|
||||
value: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await agent.prompt({ sessionId: SESSION_ID, prompt: [{ type: "text", text: "hi" }] });
|
||||
|
||||
expect(agent.sessions[SESSION_ID].fastModeEnabled).toBe(enabled);
|
||||
expect(updates.filter((n) => n.update.sessionUpdate === "config_option_update")).toHaveLength(
|
||||
enabled ? 0 : 1,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -64,6 +65,8 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
|
||||
let rejectConfigUpdate: boolean;
|
||||
let models: typeof MODELS;
|
||||
let mcpServers: Array<{ name: string; status: string }>;
|
||||
/** What a query that resumes a session sends before it reads a prompt. */
|
||||
let backlog: any[];
|
||||
|
||||
function createQuery(request: { options: Options; prompt: AsyncIterable<any> }) {
|
||||
const state = {
|
||||
@@ -108,6 +111,7 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
|
||||
}),
|
||||
close: vi.fn(),
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
if (request.options.resume) yield* backlog;
|
||||
for await (const message of request.prompt) {
|
||||
calls.push({ prompt: message.message.content, state: { ...state } });
|
||||
yield userEcho(message);
|
||||
@@ -137,6 +141,7 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
|
||||
rejectConfigUpdate = false;
|
||||
models = MODELS;
|
||||
mcpServers = [];
|
||||
backlog = [];
|
||||
sdk.query.mockImplementation((request) => {
|
||||
const query = createQuery(request);
|
||||
queries.push(query);
|
||||
@@ -340,6 +345,18 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
|
||||
expect(updates.at(-1).update.configOptions).toEqual(agent.sessions[sessionId].configOptions);
|
||||
});
|
||||
|
||||
// The gateway of `providers/set` listed the models, so only those can run
|
||||
// there, though Claude Code would take the id.
|
||||
it("refuses a model id the option does not list without asking Claude Code", async () => {
|
||||
const { sessionId } = await newSession();
|
||||
|
||||
await expect(select(sessionId, "model", "claude-fable-5-2")).rejects.toMatchObject({
|
||||
code: -32602,
|
||||
message: expect.stringMatching(/Invalid value for config option model: claude-fable-5-2$/),
|
||||
});
|
||||
expect(lastQuery().setModel).not.toHaveBeenCalledWith("claude-fable-5-2");
|
||||
});
|
||||
|
||||
it("restores Auto once the restored model supports it", async () => {
|
||||
models = MODELS.map((model) =>
|
||||
model.value === "sonnet" ? { ...model, supportsAutoMode: false } : model,
|
||||
@@ -639,6 +656,33 @@ describe("provider updates preserve session configuration", { timeout: 10_000 },
|
||||
]);
|
||||
});
|
||||
|
||||
// Claude Code can run a cycle of its own on the new query before the next
|
||||
// prompt, for example a cron prompt. The reader of the old query ended with
|
||||
// that query.
|
||||
it("reads what the new query sends before the next prompt", async () => {
|
||||
const { sessionId } = await newSession();
|
||||
// The reader of the first query starts in a timer after the setup response.
|
||||
// Without this wait the timer would run after the restart and start the
|
||||
// reader of the new query.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const state = (state: "running" | "idle") => ({
|
||||
type: "system",
|
||||
subtype: "session_state_changed",
|
||||
state,
|
||||
uuid: randomUUID(),
|
||||
session_id: sessionId,
|
||||
});
|
||||
const usage = { ...successfulResultMessage().usage, input_tokens: 111 };
|
||||
// A cron prompt: its result has no origin.
|
||||
backlog = [state("running"), successfulResultMessage({ usage }), state("idle")];
|
||||
await refresh();
|
||||
await vi.waitFor(() => expect(agent.sessions[sessionId].lastSessionState).toBe("idle"));
|
||||
|
||||
const response = await prompt(sessionId);
|
||||
|
||||
expect(response.usage).toMatchObject({ inputTokens: 0 });
|
||||
});
|
||||
|
||||
it("reports a failed client MCP server once across a provider refresh", async () => {
|
||||
mcpServers = [{ name: "client-fs", status: "failed" }];
|
||||
const { sessionId } = await agent.newSession({
|
||||
|
||||
@@ -4,20 +4,28 @@ import { AcpClient } from "../../acp-client.js";
|
||||
import { loggableBaseUrl } from "../../providers.js";
|
||||
|
||||
const mockQuery = vi.hoisted(() =>
|
||||
vi.fn(() => ({
|
||||
initializationResult: vi.fn().mockResolvedValue({
|
||||
models: [
|
||||
{ value: "id", displayName: "name", description: "description", supportsAutoMode: true },
|
||||
],
|
||||
}),
|
||||
setModel: vi.fn(),
|
||||
setPermissionMode: vi.fn(),
|
||||
supportedCommands: vi.fn().mockResolvedValue([]),
|
||||
close: vi.fn(),
|
||||
interrupt: vi.fn().mockResolvedValue(undefined),
|
||||
getContextUsage: vi.fn().mockResolvedValue({ totalTokens: 0, rawMaxTokens: 200000 }),
|
||||
[Symbol.asyncIterator]: async function* () {},
|
||||
})),
|
||||
vi.fn(() => {
|
||||
// Like Claude Code's, the stream stays open until the query is closed.
|
||||
const closed = Promise.withResolvers<void>();
|
||||
return {
|
||||
initializationResult: vi.fn().mockResolvedValue({
|
||||
models: [
|
||||
{ value: "id", displayName: "name", description: "description", supportsAutoMode: true },
|
||||
],
|
||||
}),
|
||||
setModel: vi.fn(),
|
||||
setPermissionMode: vi.fn(),
|
||||
supportedCommands: vi.fn().mockResolvedValue([]),
|
||||
close: vi.fn(() => closed.resolve()),
|
||||
interrupt: vi.fn().mockResolvedValue(undefined),
|
||||
getContextUsage: vi.fn().mockResolvedValue({ totalTokens: 0, rawMaxTokens: 200000 }),
|
||||
next: async () => {
|
||||
await closed.promise;
|
||||
return { done: true as const, value: undefined };
|
||||
},
|
||||
[Symbol.asyncIterator]: async function* () {},
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("@anthropic-ai/claude-agent-sdk", async () => ({
|
||||
|
||||
@@ -3,7 +3,7 @@ import { SessionNotification } from "@agentclientprotocol/sdk/unstable";
|
||||
import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { ClaudeAcpAgent as ClaudeAcpAgentType } from "../../v1/acp-agent.js";
|
||||
import type { AcpClient } from "../../acp-client.js";
|
||||
import { makeMockQuery } from "../helpers.js";
|
||||
import { makeMockQuery, setModelRefusal } from "../helpers.js";
|
||||
|
||||
const { registerHookCallbackSpy } = vi.hoisted(() => ({
|
||||
registerHookCallbackSpy: vi.fn(),
|
||||
@@ -331,18 +331,22 @@ describe("session config options", () => {
|
||||
expect(modelOption?.currentValue).toBe("claude-sonnet-4-6");
|
||||
});
|
||||
|
||||
// "a" is a substring of "Claude", "son" of "sonnet": only whole words match.
|
||||
// "a" is a substring of "Claude", "son" of "sonnet": only whole words match,
|
||||
// so each goes to Claude Code as it is, which refuses an id it does not know.
|
||||
it.each(["gpt-4", "not-a-model", "son", "foo-sonnet"])(
|
||||
"rejects the model %s and leaves the model as it was",
|
||||
"rejects the model %s that Claude Code refuses and leaves the model as it was",
|
||||
async (value) => {
|
||||
setModelSpy.mockRejectedValue(setModelRefusal(`Model '${value}' not found`, "not_found"));
|
||||
await expect(
|
||||
agent.setSessionConfigOption({ sessionId: SESSION_ID, configId: "model", value }),
|
||||
).rejects.toMatchObject({
|
||||
code: -32602,
|
||||
message: expect.stringContaining(`Invalid value for config option model: ${value}`),
|
||||
message: expect.stringContaining(
|
||||
`Invalid value for config option model: ${value}. Model '${value}' not found`,
|
||||
),
|
||||
});
|
||||
|
||||
expect(setModelSpy).not.toHaveBeenCalled();
|
||||
expect(setModelSpy).toHaveBeenCalledWith(value);
|
||||
const session = (
|
||||
agent as unknown as {
|
||||
sessions: Record<string, { configOptions: typeof MOCK_CONFIG_OPTIONS }>;
|
||||
@@ -354,6 +358,28 @@ describe("session config options", () => {
|
||||
},
|
||||
);
|
||||
|
||||
// These failures do not judge the id, which Claude Code may well run.
|
||||
it.each([
|
||||
setModelRefusal("Authentication failed. Please check your API credentials.", "auth_failed"),
|
||||
setModelRefusal("Network error. Please check your internet connection.", "check_unreachable"),
|
||||
setModelRefusal("Model switch blocked by a PreModelSwitch hook: not now", "blocked_by_hook"),
|
||||
// A query that closed: the SDK's own error, with no code.
|
||||
new Error("Query closed before response received"),
|
||||
])(
|
||||
"keeps a failed switch to an unlisted model as the error it is: $message",
|
||||
async (failure) => {
|
||||
setModelSpy.mockRejectedValue(failure);
|
||||
|
||||
await expect(
|
||||
agent.setSessionConfigOption({
|
||||
sessionId: SESSION_ID,
|
||||
configId: "model",
|
||||
value: "claude-fable-5-2",
|
||||
}),
|
||||
).rejects.toBe(failure);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects a non-string value for a select option with invalid params", async () => {
|
||||
await expect(
|
||||
agent.setSessionConfigOption({
|
||||
@@ -1169,13 +1195,21 @@ describe("session config options", () => {
|
||||
value: "claude-sonnet-4-6",
|
||||
});
|
||||
expect(modelValues(switched.configOptions)).toEqual(["claude-opus-4-5", "claude-sonnet-4-6"]);
|
||||
await expect(
|
||||
agent.setSessionConfigOption({
|
||||
sessionId: SESSION_ID,
|
||||
configId: "model",
|
||||
value: "claude-offlist-9",
|
||||
}),
|
||||
).rejects.toThrow("Invalid value");
|
||||
});
|
||||
|
||||
it("passes a model id the option does not list to Claude Code, and lists it once Claude Code takes it", async () => {
|
||||
const response = await agent.setSessionConfigOption({
|
||||
sessionId: SESSION_ID,
|
||||
configId: "model",
|
||||
value: "claude-fable-5-2",
|
||||
});
|
||||
|
||||
expect(setModelSpy).toHaveBeenCalledWith("claude-fable-5-2");
|
||||
const model = response.configOptions?.find((o) => o.id === "model");
|
||||
expect(model?.currentValue).toBe("claude-fable-5-2");
|
||||
expect(
|
||||
(model as { options: { value: string }[] } | undefined)?.options.map((o) => o.value),
|
||||
).toEqual(["claude-opus-4-5", "claude-sonnet-4-6", "claude-fable-5-2"]);
|
||||
});
|
||||
|
||||
it("setSessionMode also syncs configOptions", async () => {
|
||||
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
v2ConfigOptions,
|
||||
} from "../../v2/session-requests.js";
|
||||
import { encodeProjectPath } from "../../session-index/project-dirs.js";
|
||||
import { startupFailure } from "../helpers.js";
|
||||
import { setModelRefusal, startupFailure } from "../helpers.js";
|
||||
import packageJson from "../../../package.json" with { type: "json" };
|
||||
|
||||
const execFileSpy = vi.hoisted(() => vi.fn());
|
||||
@@ -1221,9 +1221,11 @@ describe("ACP v2 sessions", () => {
|
||||
{ value: "reviewer", name: "reviewer", description: "Reviews changes" },
|
||||
],
|
||||
});
|
||||
// Each value goes to Claude Code before the option shows it.
|
||||
// Each value goes to Claude Code before the option shows it. Fast mode
|
||||
// goes off first: Claude Code ignores a `true` while its flag holds `true`.
|
||||
expect(sdk.flagSettings).toEqual([
|
||||
{ effortLevel: "high" },
|
||||
{ fastMode: false },
|
||||
{ fastMode: true },
|
||||
{ ultracode: true },
|
||||
{ agent: "reviewer" },
|
||||
@@ -1255,9 +1257,9 @@ describe("ACP v2 sessions", () => {
|
||||
],
|
||||
// "a" is a substring of "claude": a substring match would pick Opus.
|
||||
[
|
||||
"a model the session does not offer",
|
||||
"a model Claude Code does not know",
|
||||
{ configId: "model", type: "id", value: "not-a-model" },
|
||||
"Invalid value for config option model: not-a-model",
|
||||
"Invalid value for config option model: not-a-model. Model 'not-a-model' not found",
|
||||
],
|
||||
[
|
||||
"a mode the session does not offer",
|
||||
@@ -1274,6 +1276,10 @@ describe("ACP v2 sessions", () => {
|
||||
async (_case, request, message) => {
|
||||
const models: Array<string | undefined> = [];
|
||||
sdk.setModel = async (model) => {
|
||||
// Claude Code refuses an id it does not know.
|
||||
if (model === "not-a-model") {
|
||||
throw setModelRefusal(`Model '${model}' not found`, "not_found");
|
||||
}
|
||||
models.push(model);
|
||||
};
|
||||
const client = v2Client();
|
||||
@@ -1300,6 +1306,140 @@ describe("ACP v2 sessions", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("passes a model id the option does not list to Claude Code, and lists it once Claude Code takes it", async () => {
|
||||
const models: Array<string | undefined> = [];
|
||||
sdk.setModel = async (model) => {
|
||||
models.push(model);
|
||||
};
|
||||
const client = v2Client();
|
||||
const response = await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
|
||||
const response = await agent.request(v2.methods.agent.session.setConfigOption, {
|
||||
sessionId,
|
||||
configId: "model",
|
||||
type: "id",
|
||||
value: "claude-fable-5-2",
|
||||
});
|
||||
await client.authUpdate(1);
|
||||
return response;
|
||||
});
|
||||
|
||||
expect(models).toEqual(["claude-fable-5-2"]);
|
||||
const model = response.configOptions.find((option) => option.configId === "model");
|
||||
expect(model?.currentValue).toBe("claude-fable-5-2");
|
||||
expect(
|
||||
(model as { options: { value: string }[] } | undefined)?.options.map(
|
||||
(entry) => entry.value,
|
||||
),
|
||||
).toContain("claude-fable-5-2");
|
||||
});
|
||||
|
||||
it("refuses a model id the option does not list when a gateway listed the models", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => new Response(JSON.stringify({ data: [{ id: OPUS.value }] }))),
|
||||
);
|
||||
const models: Array<string | undefined> = [];
|
||||
sdk.setModel = async (model) => {
|
||||
models.push(model);
|
||||
};
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
await agent.request(v2.methods.agent.providers.set, {
|
||||
providerId: "main",
|
||||
apiType: "anthropic",
|
||||
baseUrl: "https://gateway.example.com",
|
||||
});
|
||||
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
|
||||
await expect(
|
||||
agent.request(v2.methods.agent.session.setConfigOption, {
|
||||
sessionId,
|
||||
configId: "model",
|
||||
type: "id",
|
||||
value: "claude-fable-5-2",
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
code: -32602,
|
||||
message: expect.stringMatching(
|
||||
/Invalid value for config option model: claude-fable-5-2$/,
|
||||
),
|
||||
});
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
|
||||
expect(models).not.toContain("claude-fable-5-2");
|
||||
});
|
||||
|
||||
// The failure does not judge the id, which Claude Code may well run.
|
||||
it("answers a failed switch to an unlisted model with an internal error when Claude Code did not refuse the id", async () => {
|
||||
sdk.setModel = async () => {
|
||||
throw setModelRefusal(
|
||||
"Authentication failed. Please check your API credentials.",
|
||||
"auth_failed",
|
||||
);
|
||||
};
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
|
||||
await expect(
|
||||
agent.request(v2.methods.agent.session.setConfigOption, {
|
||||
sessionId,
|
||||
configId: "model",
|
||||
type: "id",
|
||||
value: "claude-fable-5-2",
|
||||
}),
|
||||
).rejects.toMatchObject({ code: -32603 });
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
});
|
||||
|
||||
// The query of a restart may run on a provider that cannot serve the model
|
||||
// of the query it replaces, though Claude Code would take the id.
|
||||
it("does not pass the model of a replaced query to Claude Code when the new query does not list it", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(
|
||||
async () =>
|
||||
new Response(JSON.stringify({ data: [{ id: OPUS.value }, { id: HAIKU.value }] })),
|
||||
),
|
||||
);
|
||||
const models: Array<string | undefined> = [];
|
||||
sdk.setModel = async (model) => {
|
||||
models.push(model);
|
||||
};
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
await agent.request(v2.methods.agent.providers.set, {
|
||||
providerId: "main",
|
||||
apiType: "anthropic",
|
||||
baseUrl: "https://gateway.example.com",
|
||||
});
|
||||
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
|
||||
await agent.request(v2.methods.agent.session.setConfigOption, {
|
||||
sessionId,
|
||||
configId: "model",
|
||||
type: "id",
|
||||
value: HAIKU.value,
|
||||
});
|
||||
// Without the gateway, the session's new query lists Opus only.
|
||||
sdk.initializationResult = async () => ({ models: [OPUS] });
|
||||
await agent.request(v2.methods.agent.providers.disable, { providerId: "main" });
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
|
||||
expect(models).toEqual([HAIKU.value]);
|
||||
expect(
|
||||
client
|
||||
.updates("config_option_update")
|
||||
.at(-1)
|
||||
?.configOptions.find((option) => option.configId === "model"),
|
||||
).toMatchObject({ currentValue: OPUS.value });
|
||||
});
|
||||
|
||||
it("rebuilds the options for a model switch, and clears an effort the new model lacks", async () => {
|
||||
const client = v2Client();
|
||||
const response = await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
@@ -1399,6 +1539,7 @@ describe("ACP v2 sessions", () => {
|
||||
expect(sdk.queryOptions[1].effort).toBeUndefined();
|
||||
expect(sdk.flagSettings).toEqual([
|
||||
{ ultracode: true },
|
||||
{ fastMode: false },
|
||||
{ fastMode: true },
|
||||
{ effortLevel: "low", ultracode: true },
|
||||
{ agent: "reviewer" },
|
||||
@@ -1490,6 +1631,48 @@ describe("ACP v2 sessions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Scenario:
|
||||
* 1. A turn's `system`/init reports Fast mode off (`sdk_opt_in_required`: no opt-in yet).
|
||||
* 2. The client turns Fast mode on while the turn runs.
|
||||
* 3. The turn's result reports Fast mode off without a reason: Claude Code
|
||||
* read the flag when the turn started.
|
||||
* Expected:
|
||||
* - The `fast` option stays on: the only update is the one that turned it on.
|
||||
*/
|
||||
it("keeps a Fast mode that the client turned on during the turn", async () => {
|
||||
const initHandled = Promise.withResolvers<void>();
|
||||
const turnedOn = Promise.withResolvers<void>();
|
||||
scriptTurns(async function* (options) {
|
||||
yield fastModeInit(options, "off", "sdk_opt_in_required");
|
||||
initHandled.resolve();
|
||||
await turnedOn.promise;
|
||||
yield assistantText(options, "Done.");
|
||||
yield result(options, { fast_mode_state: "off" });
|
||||
yield idleState(options);
|
||||
});
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
|
||||
await agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: text("hi") });
|
||||
await initHandled.promise;
|
||||
await agent.request(v2.methods.agent.session.setConfigOption, {
|
||||
sessionId,
|
||||
configId: "fast",
|
||||
type: "boolean",
|
||||
value: true,
|
||||
});
|
||||
turnedOn.resolve();
|
||||
await vi.waitFor(() => expect(turnTrace(client.sessionUpdates)).toContain("idle end_turn"));
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
|
||||
const updates = client.updates("config_option_update");
|
||||
expect(updates).toHaveLength(1);
|
||||
expect(fastOption(updates[0])).toMatchObject({ currentValue: true });
|
||||
});
|
||||
|
||||
it("reports a refusal fallback with a notice and follows the model it swapped to", async () => {
|
||||
sdk.initializationResult = async () => ({ models: [OPUS, HAIKU] });
|
||||
scriptTurns(async function* (options) {
|
||||
@@ -4573,6 +4756,69 @@ describe("ACP v2 model cycles that Claude Code starts on its own", () => {
|
||||
expect(turnTrace(client.sessionUpdates).at(-1)).toBe("idle end_turn");
|
||||
});
|
||||
|
||||
// A resumed session can run cycles before its first prompt, for example a
|
||||
// cron prompt. v2 reads the query from the start of the session, so that
|
||||
// output is reported as it comes and does not answer the prompt.
|
||||
it("reports a cycle that a resumed session runs before the first prompt, apart from the prompt's turn", async () => {
|
||||
sdk.run = async function* (prompts, options) {
|
||||
const input = prompts[Symbol.asyncIterator]();
|
||||
if (!options.resume) {
|
||||
while (!(await input.next()).done);
|
||||
return;
|
||||
}
|
||||
// A cron prompt: its result has no origin.
|
||||
yield assistantText(options, "Checked the build.", "msg_cron");
|
||||
yield result(options, { usage: { ...result(options).usage, input_tokens: 111 } });
|
||||
yield idleState(options);
|
||||
const { value } = await input.next();
|
||||
yield {
|
||||
type: "user",
|
||||
message: value!.message,
|
||||
parent_tool_use_id: null,
|
||||
uuid: value!.uuid,
|
||||
session_id: options.sessionId,
|
||||
isReplay: true,
|
||||
};
|
||||
yield assistantText(options, "Here is the answer.");
|
||||
yield result(options, { usage: { ...result(options).usage, input_tokens: 7 } });
|
||||
yield idleState(options);
|
||||
while (!(await input.next()).done);
|
||||
};
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
|
||||
await agent.request(v2.methods.agent.session.close, { sessionId });
|
||||
await agent.request(v2.methods.agent.session.resume, { sessionId, cwd });
|
||||
await vi.waitFor(() =>
|
||||
expect(turnTrace(client.sessionUpdates)).toContain("agent_message_chunk"),
|
||||
);
|
||||
await agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: text("hi") });
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
turnTrace(client.sessionUpdates).filter((state) => state.startsWith("idle end")),
|
||||
).toHaveLength(2),
|
||||
);
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
// Without the `idle` that the resume reports.
|
||||
expect(turnTrace(client.sessionUpdates).filter((state) => state !== "idle")).toEqual([
|
||||
"running",
|
||||
"agent_message_chunk",
|
||||
"idle end_turn",
|
||||
"user_message",
|
||||
"running",
|
||||
"agent_message_chunk",
|
||||
"idle end_turn",
|
||||
]);
|
||||
expect(
|
||||
client
|
||||
.updates("state_update")
|
||||
.filter((update: any) => update.stopReason)
|
||||
.map((update: any) => update.usage.inputTokens),
|
||||
).toEqual([111, 7]);
|
||||
});
|
||||
|
||||
it("ends the tool call that a cancelled cycle runs with Claude Code's result, before idle cancelled", async () => {
|
||||
const interrupted = Promise.withResolvers<void>();
|
||||
sdk.interrupt = async () => interrupted.resolve();
|
||||
@@ -9991,6 +10237,36 @@ describe("ACP v2 providers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// The new query of a restart can run a cycle before the next prompt, for
|
||||
// example a cron prompt. v2 reads every query from its start, so the cycle
|
||||
// is reported as it comes.
|
||||
it("reports a cycle that the new query of a restart runs before the next prompt", async () => {
|
||||
sdk.run = async function* (prompts, options) {
|
||||
if (options.resume) {
|
||||
// A cron prompt: its result has no origin.
|
||||
yield assistantText(options, "Checked the build.", "msg_cron");
|
||||
yield result(options);
|
||||
yield idleState(options);
|
||||
}
|
||||
const input = prompts[Symbol.asyncIterator]();
|
||||
while (!(await input.next()).done);
|
||||
};
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
await agent.request(v2.methods.agent.session.new, { cwd });
|
||||
await setGateway(agent);
|
||||
await vi.waitFor(() =>
|
||||
expect(turnTrace(client.sessionUpdates)).toEqual([
|
||||
"running",
|
||||
"agent_message_chunk",
|
||||
"idle end_turn",
|
||||
]),
|
||||
);
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("routes only the sessions started after a gateway login", async () => {
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
|
||||
@@ -405,15 +405,19 @@ import {
|
||||
clientSupportsBooleanConfigOptions,
|
||||
clientSupportsRecommendedConfigValue,
|
||||
configOptionValue,
|
||||
setSelectedModel,
|
||||
discoverCustomAgents,
|
||||
} from "../session-config-options.js";
|
||||
import {
|
||||
applyFastModeFlag,
|
||||
createFastModeConfigOption,
|
||||
FAST_MODE_CONFIG_ID,
|
||||
fastModeResultIsNews,
|
||||
fastModeStateChange,
|
||||
fastModeStateEnabled,
|
||||
normalizeFastModeDisabledReason,
|
||||
type FastModeOptionState,
|
||||
type FastModeReport,
|
||||
} from "../session-fast-mode.js";
|
||||
import {
|
||||
cacheResultContextWindow,
|
||||
@@ -1070,11 +1074,15 @@ export type Session = {
|
||||
/** Why the SDK currently can't serve Fast mode: the last
|
||||
* `fast_mode_disabled_reason` that `explainFastModeDisabledReason` explains.
|
||||
* {@link normalizeFastModeDisabledReason} drops the two it doesn't,
|
||||
* `sdk_opt_in_required` and `pending`, to `undefined`. Refreshed from every
|
||||
* `fast_mode_disabled_reason` the SDK reports on `system`/init and user-turn
|
||||
* `result`s; surfaced in the Fast mode option's description so a toggle that
|
||||
* snaps back off explains itself. */
|
||||
* `sdk_opt_in_required` and `pending`, to `undefined`. Refreshed from the
|
||||
* `fast_mode_disabled_reason` the SDK reports on every `system`/init, and on
|
||||
* a user-turn `result` that does not repeat its init; surfaced in the Fast
|
||||
* mode option's description so a toggle that snaps back off explains itself. */
|
||||
fastModeDisabledReason?: FastModeDisabledReason;
|
||||
/** The Fast mode report of the last `system`/init, until a result of a
|
||||
* prompt takes it: a result that repeats it is not mirrored (see
|
||||
* {@link fastModeResultIsNews}). */
|
||||
fastModeInitReport?: FastModeReport;
|
||||
abortController: AbortController;
|
||||
/** Signal the consumer races `query.next()` against. Aborted by cancel()
|
||||
* (after a grace period) to force the active turn to settle "cancelled" when
|
||||
@@ -1122,6 +1130,10 @@ export type Session = {
|
||||
* the process-wide provider config can change while a session is being
|
||||
* created, while the query stays baked to the env it was created with. */
|
||||
providerCacheKey: string;
|
||||
/** A `providers/set` gateway listed the models, so only those can run: a
|
||||
* model id the option does not list is refused rather than passed to
|
||||
* Claude Code (`configOptionValue`). */
|
||||
modelsNarrowedByGateway?: boolean;
|
||||
/** Accumulated task list for the session, keyed by task ID. Task IDs are
|
||||
* per-session, so this state must not be shared across sessions. */
|
||||
taskState: TaskState;
|
||||
@@ -2475,8 +2487,10 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
// Once Remote Control is on, other clients can start turns or send
|
||||
// messages on their own. Something has to read the query stream for
|
||||
// those to reach this client, and a command that answers without a turn
|
||||
// would otherwise leave the stream unread until the next prompt.
|
||||
// those to reach this client. The reader starts after the session's
|
||||
// setup response and after a query restart; a command that comes before
|
||||
// the setup's timer ran (see `afterSetupResponse`) answers without a
|
||||
// turn and would leave the stream unread until that timer.
|
||||
this.ensureConsumer(session, params.sessionId);
|
||||
// Answered by the adapter without a model turn.
|
||||
events.inserted(randomUUID());
|
||||
@@ -3071,7 +3085,9 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
|
||||
/** Lazily start the per-session consumer that drains the SDK query stream for
|
||||
* the session's whole life. Idempotent: only the first `prompt()` starts it. */
|
||||
* the session's whole life. Idempotent: the first caller starts it, a
|
||||
* session setup (see `afterSetupResponse`), a query restart (see
|
||||
* `replaceSessionQuery`) or a `prompt()`. */
|
||||
private ensureConsumer(session: Session, sessionId: string): void {
|
||||
if (session.consumer) {
|
||||
return;
|
||||
@@ -4696,6 +4712,10 @@ export class ClaudeAcpAgent {
|
||||
// A fresh `system`/init (e.g. after reinitialize) can carry an
|
||||
// updated Fast mode state; reconcile it with what we seeded at
|
||||
// session creation.
|
||||
session.fastModeInitReport = {
|
||||
state: message.fast_mode_state,
|
||||
reason: message.fast_mode_disabled_reason,
|
||||
};
|
||||
await this.syncFastModeState(
|
||||
params.sessionId,
|
||||
session,
|
||||
@@ -5563,17 +5583,27 @@ export class ClaudeAcpAgent {
|
||||
const pendingExitPlanModeInterruption = session.pendingExitPlanModeInterruption;
|
||||
const pendingExitPlanContextReset = session.pendingExitPlanContextReset;
|
||||
try {
|
||||
// Reconcile the Fast mode toggle with the SDK's reported state.
|
||||
// Reconcile the Fast mode toggle with the SDK's reported state,
|
||||
// unless the result repeats its turn's init (see
|
||||
// `fastModeResultIsNews`).
|
||||
// Gated to user-driven turns like every other side effect below;
|
||||
// an autonomous cycle's state lands on the next user turn's
|
||||
// result. Runs even when the turn errors or was cancelled.
|
||||
if (!isAutonomousResult) {
|
||||
await this.syncFastModeState(
|
||||
params.sessionId,
|
||||
session,
|
||||
message.fast_mode_state,
|
||||
message.fast_mode_disabled_reason,
|
||||
);
|
||||
const fastModeInitReport = session.fastModeInitReport;
|
||||
session.fastModeInitReport = undefined;
|
||||
const fastModeReport = {
|
||||
state: message.fast_mode_state,
|
||||
reason: message.fast_mode_disabled_reason,
|
||||
};
|
||||
if (fastModeResultIsNews(fastModeInitReport, fastModeReport)) {
|
||||
await this.syncFastModeState(
|
||||
params.sessionId,
|
||||
session,
|
||||
message.fast_mode_state,
|
||||
message.fast_mode_disabled_reason,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// A user-turn result needs an active turn so its stop reason is
|
||||
@@ -7777,11 +7807,14 @@ export class ClaudeAcpAgent {
|
||||
/**
|
||||
* `duringSetup`: the value is one of a setup request's `configOptions`. No
|
||||
* mode update goes out, and the warning of an Auto mode fallback waits for
|
||||
* the next prompt.
|
||||
* the next prompt. `restoring`: the value is the replaced query's
|
||||
* (`restoreSessionChoices`), so a model id the option does not list is
|
||||
* refused rather than passed to Claude Code.
|
||||
*/
|
||||
private async selectSessionConfigOption(
|
||||
params: SetSessionConfigOptionRequest,
|
||||
duringSetup = false,
|
||||
restoring = false,
|
||||
): Promise<SetSessionConfigOptionResponse> {
|
||||
const session = this.sessions[params.sessionId];
|
||||
if (!session) {
|
||||
@@ -7799,7 +7832,12 @@ export class ClaudeAcpAgent {
|
||||
if (!option) {
|
||||
throw RequestError.invalidParams(undefined, `Unknown config option: ${params.configId}`);
|
||||
}
|
||||
const selected = configOptionValue(option, params, session.modelInfos);
|
||||
const selected = configOptionValue(
|
||||
option,
|
||||
params,
|
||||
session.modelInfos,
|
||||
!restoring && !session.modelsNarrowedByGateway,
|
||||
);
|
||||
if ("enabled" in selected) {
|
||||
if (params.configId === FAST_MODE_CONFIG_ID) {
|
||||
await this.applyFastMode(session, selected.enabled);
|
||||
@@ -7819,7 +7857,7 @@ export class ClaudeAcpAgent {
|
||||
);
|
||||
if (!duringSetup) await this.sessionModes.publishCurrent(params.sessionId, effectiveValue);
|
||||
} else if (params.configId === MODEL_CONFIG_ID) {
|
||||
await this.sessions[params.sessionId].query.setModel(resolvedValue);
|
||||
await setSelectedModel(this.sessions[params.sessionId].query, selected);
|
||||
}
|
||||
// Effort SDK sync is handled inside applyConfigOptionValue so that direct
|
||||
// effort changes and effort changes induced by a model switch go through
|
||||
@@ -9231,9 +9269,9 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
|
||||
/**
|
||||
* The work that follows a session setup response: the session's commands,
|
||||
* the current states of the subagents a load replayed, and MCP server
|
||||
* authentication.
|
||||
* The work that follows a session setup response: reading the session's
|
||||
* query, the session's commands, the current states of the subagents a load
|
||||
* replayed, and MCP server authentication.
|
||||
*
|
||||
* Call it in the same synchronous step as the handler's `return`: an
|
||||
* `await` between them would let the timer run before the response. The ACP
|
||||
@@ -9248,6 +9286,14 @@ export class ClaudeAcpAgent {
|
||||
*/
|
||||
private afterSetupResponse(sessionId: string, mcpServers: McpServer[]): void {
|
||||
setTimeout(() => {
|
||||
// Claude Code can run cycles of its own before the first prompt, for
|
||||
// example a cron prompt or a finished background task of a session that a
|
||||
// bridge restart resumed. Output that nothing reads waits in the stream,
|
||||
// and the first prompt would take the first result in it as its answer.
|
||||
// After the load's replay, so live output does not interleave with the
|
||||
// replayed history.
|
||||
const session = this.sessions[sessionId];
|
||||
if (session && !session.queryClosed) this.ensureConsumer(session, sessionId);
|
||||
this.sendAvailableCommandsUpdate(sessionId);
|
||||
void this.publishCurrentSubagentStates(sessionId);
|
||||
startMcpAuthentication(this, sessionId, mcpServers);
|
||||
@@ -9569,8 +9615,9 @@ export class ClaudeAcpAgent {
|
||||
* option is guaranteed to be present in `configOptions`. */
|
||||
private async applyFastMode(session: Session, enabled: boolean): Promise<void> {
|
||||
// Apply the SDK flag first so a rejected control request leaves both the
|
||||
// session state and the config option untouched (no UI/SDK desync).
|
||||
await session.query.applyFlagSettings({ fastMode: enabled });
|
||||
// session state and the config option untouched (see `applyFastModeFlag`
|
||||
// for a refusal after its reset).
|
||||
await applyFastModeFlag((settings) => session.query.applyFlagSettings(settings), enabled);
|
||||
session.fastModeEnabled = enabled;
|
||||
this.refreshFastModeOption(session, enabled);
|
||||
}
|
||||
@@ -10470,6 +10517,7 @@ export class ClaudeAcpAgent {
|
||||
contextWindowSize: seededWindow.size,
|
||||
contextWindowAuthoritative: seededWindow.authoritative,
|
||||
providerCacheKey,
|
||||
modelsNarrowedByGateway: resolvedProvider?.listedModels !== undefined,
|
||||
taskState,
|
||||
subagentChecklists: creationOpts.replayState?.subagentChecklists ?? new Set(),
|
||||
toolUseCache: {},
|
||||
@@ -10605,7 +10653,7 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
}
|
||||
|
||||
/** Recreates the session's query and restores its choices and reported MCP servers, unless it was closed meanwhile. */
|
||||
/** Recreates the session's query, restores its choices and reported MCP servers, and starts reading it, unless it was closed meanwhile. */
|
||||
private async replaceSessionQuery(
|
||||
sessionId: string,
|
||||
session: Session,
|
||||
@@ -10638,6 +10686,12 @@ export class ClaudeAcpAgent {
|
||||
error,
|
||||
);
|
||||
});
|
||||
// The reader of the old query ended with that query. Claude Code can run
|
||||
// cycles of its own on the new one before the next prompt, for example a
|
||||
// cron prompt or the follow-up to a finished background task, and that
|
||||
// prompt would take the first unread result as its answer. After the
|
||||
// choices are restored, so the reader reports against the restored state.
|
||||
if (!recreated.queryClosed) this.ensureConsumer(recreated, sessionId);
|
||||
}
|
||||
|
||||
/** Re-applies the choices of `previous` to the session that replaced it; a choice the new query rejects is logged. */
|
||||
@@ -10658,7 +10712,8 @@ export class ClaudeAcpAgent {
|
||||
};
|
||||
const select = (configId: string, value: string) =>
|
||||
restore(`${configId} "${value}"`, () =>
|
||||
this.selectSessionConfigOption({ sessionId, configId, value }),
|
||||
// A model the new query does not list falls back: it may be one the new provider cannot serve.
|
||||
this.selectSessionConfigOption({ sessionId, configId, value }, false, true),
|
||||
);
|
||||
|
||||
// First: the model decides which modes, effort levels, Fast mode and ultracode exist.
|
||||
|
||||
@@ -1186,6 +1186,7 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
client,
|
||||
effortSettings: () => mergeEffortSettings(settings.getSettings(), configured),
|
||||
recommendedValue: this.air.recommendedValue,
|
||||
narrowsModels: routing.narrowsModels,
|
||||
},
|
||||
(notification) => session.output.emitV1([notification]),
|
||||
this.logger,
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
AGENT_CONFIG_ID,
|
||||
buildConfigOptions,
|
||||
configOptionValue,
|
||||
setSelectedModel,
|
||||
discoverCustomAgents,
|
||||
} from "../session-config-options.js";
|
||||
import {
|
||||
@@ -62,11 +63,14 @@ import {
|
||||
type EffortState,
|
||||
} from "../session-effort.js";
|
||||
import {
|
||||
applyFastModeFlag,
|
||||
createFastModeConfigOption,
|
||||
FAST_MODE_CONFIG_ID,
|
||||
fastModeResultIsNews,
|
||||
fastModeStateChange,
|
||||
fastModeStateEnabled,
|
||||
normalizeFastModeDisabledReason,
|
||||
type FastModeReport,
|
||||
} from "../session-fast-mode.js";
|
||||
import {
|
||||
MODEL_CONFIG_ID,
|
||||
@@ -116,6 +120,8 @@ export interface ConfigSetup {
|
||||
effortSettings(): Settings;
|
||||
/** The client declared AIR's `recommendedValue` (see the module doc). */
|
||||
recommendedValue: boolean;
|
||||
/** A `providers/set` gateway listed the models, so only those can run. */
|
||||
narrowsModels: boolean;
|
||||
}
|
||||
|
||||
export class SessionConfig {
|
||||
@@ -128,10 +134,14 @@ export class SessionConfig {
|
||||
private effort: EffortState;
|
||||
private fastModeEnabled: boolean;
|
||||
private fastModeDisabledReason: FastModeDisabledReason | undefined;
|
||||
/** The Fast mode report of the last `system`/init, until a result of a prompt takes it. */
|
||||
private fastModeInitReport: FastModeReport | undefined;
|
||||
private ultracodeEnabled: boolean;
|
||||
private readonly ultracodeWorkflowsEnabled: boolean | undefined;
|
||||
/** The end of the last change (see the module doc). */
|
||||
private changes: Promise<void> = Promise.resolve();
|
||||
/** A model id the option does not list goes to Claude Code (`configOptionValue`), unless a gateway listed the models. */
|
||||
private readonly passUnlistedModels: boolean;
|
||||
|
||||
private constructor(
|
||||
private readonly sessionId: string,
|
||||
@@ -157,7 +167,9 @@ export class SessionConfig {
|
||||
private readonly notify: (notification: SessionNotification) => void,
|
||||
private readonly logger: Logger,
|
||||
autoModeFallbackWarningPending: boolean,
|
||||
narrowsModels: boolean,
|
||||
) {
|
||||
this.passUnlistedModels = !narrowsModels;
|
||||
this.session = {
|
||||
query,
|
||||
modes,
|
||||
@@ -294,6 +306,7 @@ export class SessionConfig {
|
||||
notify,
|
||||
logger,
|
||||
autoModeFallbackWarningPending,
|
||||
setup.narrowsModels,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -379,7 +392,8 @@ export class SessionConfig {
|
||||
};
|
||||
const select = (configId: string, value: string) =>
|
||||
restore(`${configId} "${value}"`, () =>
|
||||
this.apply({ sessionId: this.sessionId, configId, type: "id", value }),
|
||||
// A model the new query does not list falls back: it may be one the new provider cannot serve.
|
||||
this.apply({ sessionId: this.sessionId, configId, type: "id", value }, false, true),
|
||||
);
|
||||
const model = previous.session.models.currentModelId;
|
||||
if (this.session.models.currentModelId !== model) await select(MODEL_CONFIG_ID, model);
|
||||
@@ -425,10 +439,15 @@ export class SessionConfig {
|
||||
return result;
|
||||
}
|
||||
|
||||
/** `duringSetup`: see {@link setInitial}. */
|
||||
/**
|
||||
* `duringSetup`: see {@link setInitial}. `restoring`: the value is the
|
||||
* previous query's ({@link restoreFrom}), so a model id the option does not
|
||||
* list is refused rather than passed to Claude Code.
|
||||
*/
|
||||
private async apply(
|
||||
params: v2.SetSessionConfigOptionRequest,
|
||||
duringSetup = false,
|
||||
restoring = false,
|
||||
): Promise<void> {
|
||||
const request = v1SetSessionConfigOptionRequest(params);
|
||||
const option = this.session.configOptions.find((entry) => entry.id === request.configId);
|
||||
@@ -438,7 +457,12 @@ export class SessionConfig {
|
||||
`Unknown config option: ${request.configId}`,
|
||||
);
|
||||
}
|
||||
const selected = configOptionValue(option, request, this.modelInfos);
|
||||
const selected = configOptionValue(
|
||||
option,
|
||||
request,
|
||||
this.modelInfos,
|
||||
this.passUnlistedModels && !restoring,
|
||||
);
|
||||
if ("enabled" in selected) {
|
||||
if (request.configId === FAST_MODE_CONFIG_ID) await this.setFastMode(selected.enabled);
|
||||
else await this.setUltracode(selected.enabled);
|
||||
@@ -450,7 +474,7 @@ export class SessionConfig {
|
||||
await this.applyMode(value as PermissionMode, duringSetup);
|
||||
return;
|
||||
case MODEL_CONFIG_ID:
|
||||
await this.session.query.setModel(value);
|
||||
await setSelectedModel(this.session.query, selected);
|
||||
await this.recordModel(value, duringSetup);
|
||||
return;
|
||||
case EFFORT_CONFIG_ID:
|
||||
@@ -527,22 +551,28 @@ export class SessionConfig {
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude Code reported a Fast mode state (`system`/init, a result). Returns
|
||||
* whether the option changed. Without a Fast mode option the model does not
|
||||
* support it, and the state says nothing of the user's intent, which stays
|
||||
* for a model that does (see `fastModeStateChange`).
|
||||
* Claude Code reported a Fast mode state, on a `system`/init or on a result
|
||||
* (`from`). Returns whether the option changed. A result that repeats the
|
||||
* init of its turn changes nothing (see `fastModeResultIsNews`). Without a
|
||||
* Fast mode option the model does not support it, and the state says nothing
|
||||
* of the user's intent, which stays for a model that does (see
|
||||
* `fastModeStateChange`).
|
||||
*/
|
||||
fastModeReported(
|
||||
state: FastModeState | undefined,
|
||||
reason: FastModeDisabledReason | undefined,
|
||||
): boolean {
|
||||
fastModeReported(report: FastModeReport, from: "init" | "result"): boolean {
|
||||
if (from === "init") {
|
||||
this.fastModeInitReport = report;
|
||||
} else {
|
||||
const init = this.fastModeInitReport;
|
||||
this.fastModeInitReport = undefined;
|
||||
if (!fastModeResultIsNews(init, report)) return false;
|
||||
}
|
||||
if (!this.session.configOptions.some((option) => option.id === FAST_MODE_CONFIG_ID)) {
|
||||
return false;
|
||||
}
|
||||
const change = fastModeStateChange(
|
||||
{ enabled: this.fastModeEnabled, disabledReason: this.fastModeDisabledReason },
|
||||
state,
|
||||
reason,
|
||||
report.state,
|
||||
report.reason,
|
||||
);
|
||||
if (!change) return false;
|
||||
this.fastModeEnabled = change.enabled;
|
||||
@@ -581,9 +611,12 @@ export class SessionConfig {
|
||||
this.setCurrentValue(AGENT_CONFIG_ID, value);
|
||||
}
|
||||
|
||||
/** Applied first, so a rejected control request leaves the option as it was. */
|
||||
/**
|
||||
* Applied first, so a rejected control request leaves the option as it was
|
||||
* (see `applyFastModeFlag` for a refusal after its reset).
|
||||
*/
|
||||
private async setFastMode(enabled: boolean): Promise<void> {
|
||||
await this.session.query.applyFlagSettings({ fastMode: enabled });
|
||||
await applyFastModeFlag((settings) => this.session.query.applyFlagSettings(settings), enabled);
|
||||
this.fastModeEnabled = enabled;
|
||||
this.refreshFastModeOption();
|
||||
}
|
||||
|
||||
@@ -839,12 +839,16 @@ export class V2Session implements RequestTarget {
|
||||
this.reports.modelChanged(id, info);
|
||||
}
|
||||
|
||||
/** Claude Code reported a Fast mode state, on `system`/init or a result. */
|
||||
private fastModeReported(message: {
|
||||
fast_mode_state?: FastModeState;
|
||||
fast_mode_disabled_reason?: FastModeDisabledReason;
|
||||
}): void {
|
||||
if (this.config.fastModeReported(message.fast_mode_state, message.fast_mode_disabled_reason)) {
|
||||
/** Claude Code reported a Fast mode state, on a `system`/init or on a result (`from`). */
|
||||
private fastModeReported(
|
||||
message: {
|
||||
fast_mode_state?: FastModeState;
|
||||
fast_mode_disabled_reason?: FastModeDisabledReason;
|
||||
},
|
||||
from: "init" | "result",
|
||||
): void {
|
||||
const report = { state: message.fast_mode_state, reason: message.fast_mode_disabled_reason };
|
||||
if (this.config.fastModeReported(report, from)) {
|
||||
this.send({ sessionUpdate: "config_option_update", configOptions: this.config.options() });
|
||||
}
|
||||
}
|
||||
@@ -990,7 +994,7 @@ export class V2Session implements RequestTarget {
|
||||
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.
|
||||
this.fastModeReported(message);
|
||||
this.fastModeReported(message, "init");
|
||||
this.reports.handle(message);
|
||||
// Its terminal-bound commands leave the list.
|
||||
if (this.commands.init(message)) this.resendCommands();
|
||||
@@ -1172,7 +1176,7 @@ export class V2Session implements RequestTarget {
|
||||
// A cycle that Claude Code started on its own leaves its Fast mode state
|
||||
// to the next result of a prompt.
|
||||
if (!(message.origin && AUTONOMOUS_RESULT_ORIGINS.has(message.origin.kind))) {
|
||||
this.fastModeReported(message);
|
||||
this.fastModeReported(message, "result");
|
||||
}
|
||||
this.reports.result(message);
|
||||
// Before the result's text below, which can repeat the failed request's.
|
||||
|
||||
Reference in New Issue
Block a user