diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts index 0e96eeb6e60..06073b16a97 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, jest, spyOn } from "bun:test"; import { spawn } from "node:child_process"; import type { ChatSelections } from "@superset/chat/core"; -import type { Item } from "@superset/chat/protocol"; +import type { Decision, Item } from "@superset/chat/protocol"; import { AGENT_DEFAULT_MODE, wrapHiddenText } from "@superset/chat/protocol"; import type { AdapterEvent, ResolveAttachment } from "../types"; import { @@ -5970,6 +5970,155 @@ describe("AcpAdapter config options", () => { await adapter.dispose(); }); + + const PLAN_OPTIONS = [ + { + optionId: "exit-plan-clear-auto", + name: "Yes, clear context (12% used) and use auto mode", + kind: "allow_always", + }, + { + optionId: "exit-plan-auto", + name: "Yes, and use auto mode", + kind: "allow_always", + }, + { optionId: "plan", name: "No, keep planning", kind: "reject_once" }, + ]; + + const PLAN_MODEL_OPTION = { + ...MODEL_OPTION, + options: [ + { value: "default", name: "Default (recommended)" }, + ...MODEL_OPTION.options, + ], + }; + + const approvePlan = async ( + decision: Decision, + picked: ChatSelections = { modelId: "sonnet", effortId: "low" }, + ) => { + const agent = new FakeAcpAgent(); + agent.protocolVersion = 1; + agent.newSessionConfigOptions = [PLAN_MODEL_OPTION, EFFORT_OPTION]; + agent.holdPrompts = true; + const { adapter, events } = startAdapter(agent, undefined, picked); + await flush(); + adapter.prompt([{ type: "text", text: "plan it" }]); + await flush(); + agent.requestPermissionWith( + { + toolCall: { toolCallId: "tc-plan", title: "Ready to code?" }, + options: PLAN_OPTIONS, + }, + 9401, + ); + await flush(); + const approval = itemsOf(events).find( + (item) => item.kind === "approval_request", + ); + const before = agent.sent.length; + adapter.respondToApproval(approval?.id ?? "", decision); + const report = async (model: string, effort: string) => { + agent.notify("sess-1", { + sessionUpdate: "config_option_update", + configOptions: [ + { ...PLAN_MODEL_OPTION, currentValue: model }, + { ...EFFORT_OPTION, currentValue: effort }, + ], + }); + await flush(); + }; + const configured = () => + agent.sent + .slice(before) + .filter((f) => f.method === "session/set_config_option") + .map((f) => f.params); + return { adapter, agent, configured, report }; + }; + + it.each([ + ["Default", "default"], + ["the settings model", "opus"], + ])("puts the model and effort back when the cleared context reports %s", async (_, reported) => { + const { adapter, configured, report } = await approvePlan({ + type: "option", + optionId: "exit-plan-clear-auto", + }); + await report(reported, "high"); + expect(configured()).toEqual([ + { sessionId: "sess-1", configId: "model", value: "sonnet" }, + { sessionId: "sess-1", configId: "effort", value: "low" }, + ]); + await adapter.dispose(); + }); + + it("treats a plain accept of a plan as the clear-context option it selects", async () => { + const { adapter, configured, report } = await approvePlan({ + type: "accept", + }); + await report("default", "high"); + expect(configured()).toEqual([ + { sessionId: "sess-1", configId: "model", value: "sonnet" }, + { sessionId: "sess-1", configId: "effort", value: "low" }, + ]); + await adapter.dispose(); + }); + + it("leaves the model alone when a plan approval keeps the context", async () => { + const { adapter, configured, report } = await approvePlan({ + type: "option", + optionId: "exit-plan-auto", + }); + await report("default", "high"); + expect(configured()).toEqual([]); + await adapter.dispose(); + }); + + it("puts back the model the user picks while the context resets", async () => { + const { adapter, configured, report } = await approvePlan({ + type: "option", + optionId: "exit-plan-clear-auto", + }); + adapter.setConfigOption("model", "opus"); + await flush(); + await report("default", "low"); + expect(configured()).toEqual([ + { sessionId: "sess-1", configId: "model", value: "opus" }, + { sessionId: "sess-1", configId: "model", value: "opus" }, + ]); + await adapter.dispose(); + }); + + it.each([ + ["Default", "default"], + ["a model the reset reports truly", "sonnet"], + ])("does not undo a later model fallback after a reset that kept %s", async (_, modelId) => { + const { adapter, configured, report } = await approvePlan( + { type: "option", optionId: "exit-plan-clear-auto" }, + { modelId, effortId: "low" }, + ); + await report(modelId, "low"); + await report("opus", "low"); + expect(configured()).toEqual([]); + await adapter.dispose(); + }); + + it.each([ + ["finishes", (agent: FakeAcpAgent) => agent.releasePrompts("end_turn")], + ["fails", (agent: FakeAcpAgent) => agent.failHeldPrompts(-32603, "boom")], + ])("does not carry the saved picks past a turn that %s", async (_, end) => { + const { adapter, agent, configured, report } = await approvePlan({ + type: "option", + optionId: "exit-plan-clear-auto", + }); + end(agent); + await flush(); + adapter.prompt([{ type: "text", text: "next" }]); + await flush(); + await report("default", "high"); + expect(configured()).toEqual([]); + await adapter.dispose(); + }); }); describe("AcpAdapter attachments", () => { diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.ts index a4336275641..eb959e53f23 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.ts @@ -203,6 +203,8 @@ export type AcpImageStoreContext = { const STARTUP_TIMEOUT_MS = 120_000; const START_OPTIONS_GRACE_MS = 1_000; +// claude-agent-acp reports the default or settings model for the fresh context these plan approvals start, whatever it runs. +const CONTEXT_RESET_OPTION = /^exit-plan-clear-/; const REQUEST_TIMEOUT_MS = 30_000; const STDERR_TAIL_CHARS = 4000; const ASK_MODE_ID = "default"; @@ -467,6 +469,7 @@ export class AcpAdapter implements HarnessAdapter { }, ); private configOptions: SessionConfigOption[] = []; + private picksBeforeContextReset: ChatSelections | null = null; private replaying = false; private agentName: string | null = null; private quietReplay = false; @@ -624,10 +627,11 @@ export class AcpAdapter implements HarnessAdapter { return; } this.pendingApprovals.delete(approvalId); - this.client.respond( - pending.requestId, - this.approvalOutcome(pending, decision), - ); + const outcome = this.approvalOutcome(pending, decision); + if (CONTEXT_RESET_OPTION.test(selectedOptionId(outcome) ?? "")) { + this.picksBeforeContextReset = this.modelAndEffort(); + } + this.client.respond(pending.requestId, outcome); if (this.currentTurn?.status !== "running") this.sendCustomAnswer(); this.emitItem( { @@ -708,6 +712,12 @@ export class AcpAdapter implements HarnessAdapter { const sessionId = this.sessionId; if (!client || !sessionId) return Promise.resolve(false); const previous = this.configOptions; + const changed = previous.find((option) => option.id === configId); + const category = changed && selectionCategoryOf(changed); + if (this.picksBeforeContextReset && category === "model") + this.picksBeforeContextReset.modelId = value; + if (this.picksBeforeContextReset && category === "thought_level") + this.picksBeforeContextReset.effortId = value; const previousModeId = configId === this.modeConfigId ? this.modeId : undefined; this.configOptions = previous.map((option) => @@ -1218,6 +1228,7 @@ export class AcpAdapter implements HarnessAdapter { usage?: AcpPromptUsage, ): void { this.endCompactions(); + this.picksBeforeContextReset = null; this.main.flush(); this.emitTurn({ id: turnId, @@ -1246,6 +1257,7 @@ export class AcpAdapter implements HarnessAdapter { private failTurn(turnId: string, error: TurnError): void { this.endCompactions(); this.customAnswer = null; + this.picksBeforeContextReset = null; this.main.flush(); this.cancelPendingApprovals(turnId); this.emitTurn({ @@ -1397,6 +1409,7 @@ export class AcpAdapter implements HarnessAdapter { return; case "config_option_update": this.handleConfigOptions(outer.data.update); + this.restorePicksAfterContextReset(); return; case "state_update": this.handleStateUpdate(outer.data.update); @@ -1991,6 +2004,28 @@ export class AcpAdapter implements HarnessAdapter { } } + private modelAndEffort(): ChatSelections { + const current = (category: SelectionCategory) => + this.configOptions.find( + (option) => selectionCategoryOf(option) === category, + )?.currentValue; + const modelId = current("model"); + const effortId = current("thought_level"); + return { + ...(modelId ? { modelId } : {}), + ...(effortId ? { effortId } : {}), + }; + } + + private restorePicksAfterContextReset(): void { + const picks = this.picksBeforeContextReset; + if (!picks) return; + this.picksBeforeContextReset = null; + const now = this.modelAndEffort(); + if (now.modelId !== picks.modelId || now.effortId !== picks.effortId) + void this.applyConfigSelections(picks); + } + private startModeId( startOptions: HarnessStartOptions, resumed: boolean, @@ -2837,6 +2872,12 @@ function listedSessions(response: unknown): DiscoverSessionsResult { }; } +function selectedOptionId(outcome: unknown): string | undefined { + const optionId = (outcome as { outcome?: { optionId?: unknown } }).outcome + ?.optionId; + return typeof optionId === "string" ? optionId : undefined; +} + function flattenSelectOptions( entries: AcpConfigSelectOption[], labelOf: (name: string) => string,