Skip to content

Commit 6bb0e0a

Browse files
fix(acp): follow a mode the agent left itself so picking it again applies
When an ACP agent leaves its selected native mode on its own (OMP leaves plan mode once its plan is approved), the thread kept showing the old mode. Picking it again changed nothing, so no mode change reached the agent. Forcing the old mode back on the next turn is wrong too: it reopens approval for a plan that already ran. At turn end the adapter now compares each mode option with the value configureSession left it at. When the agent changed it, the adapter adopts the agent's value as the configured selection and reports it through a new thread_model_selection.updated provider event. The ingestor writes it to the thread under the thread lock, so the Mode menu shows the agent's real mode, and picking the old mode again is a selection change that configures the session. A mode-only current_mode_update now also refreshes the mode option, so v1 agents that send no config_option_update are covered. AI-assisted; verified with the tests and tools listed above.
1 parent 866db49 commit 6bb0e0a

7 files changed

Lines changed: 322 additions & 4 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts‎

Lines changed: 173 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@ import {
88
} from "@t3tools/provider-acp-registry/testing";
99
import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings";
1010
import { AcpRegistryCatalog } from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
11-
import { decodeAcpReplayTranscript, makeAcpReplayRuntime } from "./AcpAdapterV2.testkit.ts";
11+
import {
12+
decodeAcpReplayTranscript,
13+
makeAcpReplayCompletenessAssertion,
14+
makeAcpReplayRuntime,
15+
} from "./AcpAdapterV2.testkit.ts";
1216
// @effect-diagnostics nodeBuiltinImport:off
1317
import * as NodeFS from "node:fs";
1418
import * as NodePath from "node:path";
@@ -2411,6 +2415,174 @@ describe("AcpAdapterV2", () => {
24112415
}).pipe(Effect.provide(layerTest), Effect.scoped),
24122416
);
24132417

2418+
// regression: #27646 an agent that leaves its mode itself must not be forced back, but picking
2419+
// the old mode again must reach it, even when a v1 agent reports only the mode update.
2420+
it.live("reports a mode the agent left itself so picking it again is sent", () =>
2421+
Effect.gen(function* () {
2422+
const fileSystem = yield* FileSystem.FileSystem;
2423+
const path = yield* Path.Path;
2424+
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-mode-only-" });
2425+
const statusPath = path.join(directory, "status.json");
2426+
const sessionId = "mode-only-session";
2427+
const modeOption = (currentValue: string) => ({
2428+
id: "mode",
2429+
name: "Mode",
2430+
category: "mode",
2431+
type: "select",
2432+
currentValue,
2433+
options: [
2434+
{ value: "ask", name: "Ask" },
2435+
{ value: "architect", name: "Architect" },
2436+
],
2437+
});
2438+
const setArchitect = [
2439+
{
2440+
type: "expect_outbound" as const,
2441+
frame: {
2442+
kind: "request",
2443+
method: "session/set_config_option",
2444+
params: { sessionId, configId: "mode", value: "architect" },
2445+
},
2446+
},
2447+
{
2448+
type: "emit_inbound" as const,
2449+
frame: {
2450+
kind: "response",
2451+
method: "session/set_config_option",
2452+
result: { configOptions: [modeOption("architect")] },
2453+
},
2454+
},
2455+
];
2456+
const prompt = (updates: ReadonlyArray<unknown>) => [
2457+
{
2458+
type: "expect_outbound" as const,
2459+
frame: { kind: "request", method: "session/prompt", params: "<any>" },
2460+
},
2461+
...updates.map((update) => ({
2462+
type: "emit_inbound" as const,
2463+
frame: { kind: "notification", method: "session/update", params: { sessionId, update } },
2464+
})),
2465+
{
2466+
type: "emit_inbound" as const,
2467+
frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } },
2468+
},
2469+
];
2470+
const transcript = yield* decodeAcpReplayTranscript(
2471+
{
2472+
provider: ACP_TEST_DRIVER,
2473+
protocol: "acp.ndjson-jsonrpc",
2474+
version: "1",
2475+
scenario: "mode-only-update",
2476+
entries: [
2477+
{
2478+
type: "expect_outbound",
2479+
frame: { kind: "request", method: "initialize", params: "<any>" },
2480+
},
2481+
{
2482+
type: "emit_inbound",
2483+
frame: {
2484+
kind: "response",
2485+
method: "initialize",
2486+
result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] },
2487+
},
2488+
},
2489+
{
2490+
type: "expect_outbound",
2491+
frame: { kind: "request", method: "session/new", params: "<any>" },
2492+
},
2493+
{
2494+
type: "emit_inbound",
2495+
frame: {
2496+
kind: "response",
2497+
method: "session/new",
2498+
result: { sessionId, configOptions: [modeOption("ask")] },
2499+
},
2500+
},
2501+
...setArchitect,
2502+
...prompt([{ sessionUpdate: "current_mode_update", currentModeId: "ask" }]),
2503+
...prompt([]),
2504+
...setArchitect,
2505+
...prompt([]),
2506+
],
2507+
},
2508+
ACP_TEST_DRIVER,
2509+
);
2510+
const instanceId = ProviderInstanceId.make("acp-test-mode-only");
2511+
const threadId = ThreadId.make("thread-acp-mode-only");
2512+
const adapter = yield* makeAcpAdapterV2({
2513+
instanceId,
2514+
flavor: {
2515+
driver: ACP_TEST_DRIVER,
2516+
capabilities: AcpProviderCapabilitiesV2,
2517+
makeRuntime: makeAcpReplayRuntime({
2518+
transcript,
2519+
statusPath,
2520+
fileSystem,
2521+
scriptPath: yield* path.fromFileUrl(
2522+
new URL("../../../scripts/acp-replay-agent.ts", import.meta.url),
2523+
),
2524+
childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
2525+
}),
2526+
},
2527+
selfInvocation: yield* resolveSelfInvocation(),
2528+
});
2529+
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2530+
runtimeMode: "full-access",
2531+
interactionMode: "default",
2532+
cwd: directory,
2533+
});
2534+
const architect = {
2535+
instanceId,
2536+
model: "default",
2537+
options: [{ id: "mode", value: "architect" }],
2538+
} as const;
2539+
const ask = { ...architect, options: [{ id: "mode", value: "ask" }] };
2540+
const runtime = yield* adapter.openSession({
2541+
threadId,
2542+
providerSessionId: ProviderSessionId.make("provider-session-acp-mode-only"),
2543+
modelSelection: architect,
2544+
runtimePolicy,
2545+
});
2546+
const providerThread = yield* runtime.ensureThread({
2547+
threadId,
2548+
modelSelection: architect,
2549+
runtimePolicy,
2550+
});
2551+
const now = yield* DateTime.now;
2552+
const reported: Array<unknown> = [];
2553+
// The thread follows the agent to ask; only the user's renewed pick sets architect again.
2554+
for (const [ordinal, modelSelection] of [
2555+
[1, architect],
2556+
[2, ask],
2557+
[3, architect],
2558+
] as const) {
2559+
yield* runtime.startTurn(
2560+
makeTurnInput({
2561+
threadId,
2562+
providerThread,
2563+
instanceId,
2564+
runtimePolicy,
2565+
now,
2566+
ordinal,
2567+
modelSelection,
2568+
}),
2569+
);
2570+
yield* runtime.events.pipe(
2571+
Stream.takeUntil((event) => event.type === "turn.terminal"),
2572+
Stream.runForEach((event) =>
2573+
Effect.sync(() => {
2574+
if (event.type === "thread_model_selection.updated") {
2575+
reported.push({ threadId: event.threadId, modelSelection: event.modelSelection });
2576+
}
2577+
}),
2578+
),
2579+
);
2580+
}
2581+
assert.deepStrictEqual(reported, [{ threadId, modelSelection: ask }]);
2582+
yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript);
2583+
}).pipe(Effect.provide(layerTest), Effect.scoped),
2584+
);
2585+
24142586
// regression: #21499 turns blocked only on T3 thread waits must show as waiting
24152587
it.effect.each(["agent_message_chunk"] as const)(
24162588
"keeps named ACP %s open while deriving thread wait execution state",

‎apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2144,6 +2144,50 @@ layer("ProviderEventIngestorV2", (it) => {
21442144
}),
21452145
);
21462146

2147+
it.effect(
2148+
"moves a thread to the selection its agent reported, once and only for its instance",
2149+
() =>
2150+
Effect.gen(function* () {
2151+
const now = yield* DateTime.now;
2152+
const eventSink = yield* EventSink.EventSinkV2;
2153+
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
2154+
const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
2155+
const idAllocator = yield* IdAllocator.IdAllocatorV2;
2156+
const rootEvent = yield* threadCreatedEvent(now);
2157+
yield* eventSink.write({ events: [rootEvent] });
2158+
const providerSessionId = yield* idAllocator.allocate.providerSession({
2159+
providerInstanceId: modelSelection.instanceId,
2160+
threadId: rootEvent.threadId,
2161+
});
2162+
const ingest = (reported: ModelSelection) =>
2163+
ingestor.ingestNormalized({
2164+
providerSessionId,
2165+
providerInstanceId: modelSelection.instanceId,
2166+
threadId: rootEvent.threadId,
2167+
event: {
2168+
type: "thread_model_selection.updated",
2169+
driver: CODEX_DRIVER,
2170+
threadId: rootEvent.threadId,
2171+
modelSelection: reported,
2172+
},
2173+
});
2174+
const reported = { ...modelSelection, options: [{ id: "mode", value: "default" }] };
2175+
assert.deepEqual(
2176+
(yield* ingest(reported)).map((stored) => stored.event.type),
2177+
["thread.model-selection-updated"],
2178+
);
2179+
assert.deepEqual(
2180+
(yield* projectionStore.getThread(rootEvent.threadId)).modelSelection,
2181+
reported,
2182+
);
2183+
assert.deepEqual(yield* ingest(reported), []);
2184+
assert.deepEqual(
2185+
yield* ingest({ ...reported, instanceId: ProviderInstanceId.make("other-instance") }),
2186+
[],
2187+
);
2188+
}),
2189+
);
2190+
21472191
it.effect(
21482192
"recovers a missing Claude child once and preserves saved metadata on later recovery",
21492193
() =>

‎apps/server/src/orchestration-v2/ProviderEventIngestor.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,29 @@ export const layer: Layer.Layer<
493493
}),
494494
];
495495
}
496+
case "thread_model_selection.updated": {
497+
const { modelSelection } = input.event;
498+
const thread = yield* projections.getThread(input.event.threadId).pipe(
499+
Effect.catchTags({
500+
ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
501+
}),
502+
);
503+
if (
504+
thread === null ||
505+
thread.modelSelection.instanceId !== modelSelection.instanceId ||
506+
modelSelectionsEqual(thread.modelSelection, modelSelection)
507+
)
508+
return [];
509+
const now = yield* DateTime.now;
510+
return [
511+
yield* makeDomainEvent(input, {
512+
type: "thread.model-selection-updated",
513+
threadId: thread.id,
514+
payload: { ...thread, modelSelection, updatedAt: now },
515+
occurredAt: now,
516+
}),
517+
];
518+
}
496519
case "provider_session.updated":
497520
return [
498521
yield* makeDomainEvent(input, {
@@ -849,7 +872,9 @@ export const layer: Layer.Layer<
849872
(effect) =>
850873
input.event.type === "app_thread.created"
851874
? threadCommands.withLock(input.event.appThread.id, effect)
852-
: effect,
875+
: input.event.type === "thread_model_selection.updated"
876+
? threadCommands.withLock(input.event.threadId, effect)
877+
: effect,
853878
),
854879
),
855880
});

‎apps/server/src/orchestration-v2/RunExecutionService.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,8 @@ export function routeProviderEvent(
408408
},
409409
];
410410
}
411+
case "thread_model_selection.updated":
412+
return [event.threadId === input.threadId, state];
411413
case "provider_thread.updated": {
412414
const belongs =
413415
state.ownedProviderThreadIds.has(event.providerThread.id) ||

‎packages/provider-acp/src/server/AcpSessionRuntime.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2798,10 +2798,25 @@ const handleSessionUpdate =
27982798
);
27992799
}
28002800
const parsed = parseSessionUpdateEvent(params);
2801-
if (parsed.modeId) {
2801+
const modeId = parsed.modeId;
2802+
if (modeId) {
28022803
yield* Ref.update(modeStateRef, (current) =>
2803-
current === undefined ? current : updateModeState(current, parsed.modeId!),
2804+
current === undefined ? current : updateModeState(current, modeId),
28042805
);
2806+
// A mode-only update would otherwise leave the mode option showing the old mode.
2807+
const configOptions = yield* SubscriptionRef.get(configOptionsRef);
2808+
const isStaleMode = (option: (typeof configOptions)[number]) =>
2809+
option.category === "mode" && option.type === "select" && option.currentValue !== modeId;
2810+
if (configOptions.some(isStaleMode)) {
2811+
yield* SubscriptionRef.set(
2812+
configOptionsRef,
2813+
configOptions.map((option) =>
2814+
option.category === "mode" && option.type === "select"
2815+
? { ...option, currentValue: modeId }
2816+
: option,
2817+
),
2818+
);
2819+
}
28052820
}
28062821
for (const event of parsed.events) {
28072822
if (event._tag === "ToolCallUpdated") {

‎packages/provider-acp/src/server/adapter.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,6 +1932,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
19321932
});
19331933
const activeSelection = yield* Ref.make<ModelSelection | null>(null);
19341934
const activeInteractionMode = yield* Ref.make<ProviderInteractionMode | null>(null);
1935+
// Mode values configureSession left the agent in; a later difference is the agent's own change.
1936+
const configuredModes = yield* Ref.make<ReadonlyMap<string, string>>(new Map());
1937+
const readModes = Effect.gen(function* () {
1938+
const modes = new Map<string, string>();
1939+
for (const option of yield* runtime.getConfigOptions) {
1940+
if (
1941+
option.type === "select" &&
1942+
(option.category === "mode" || option.category === "collaboration_mode")
1943+
) {
1944+
modes.set(option.id, option.currentValue);
1945+
}
1946+
}
1947+
const modeId = (yield* runtime.getModeState)?.currentModeId;
1948+
if (modeId !== undefined && !modes.has(ACP_SESSION_MODE_OPTION_ID)) {
1949+
modes.set(ACP_SESSION_MODE_OPTION_ID, modeId);
1950+
}
1951+
return modes;
1952+
});
19351953
const promptInstructionStates = yield* Ref.make(new Map<string, T3AcpInstructionState>());
19361954
// Unique markers keep delayed prompt completions from clearing later compactions.
19371955
const compactionMarkers = yield* Ref.make(new Map<string, symbol>());
@@ -7466,6 +7484,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
74667484
}
74677485
}
74687486
yield* validateModelSelection(modelSelection);
7487+
yield* Ref.set(configuredModes, yield* readModes);
74697488
yield* (
74707489
flavor.onSessionConfigurationUpdate?.(
74717490
yield* runtime.getConfigOptions,
@@ -7603,6 +7622,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
76037622
);
76047623
});
76057624

7625+
// Re-applying the thread's mode would undo a deliberate exit, such as leaving plan mode once
7626+
// the plan was approved. Report it instead, so picking the old mode again is a real change.
7627+
const reportAgentModeChanges = Effect.fnUntraced(function* (threadId: ThreadId) {
7628+
const selection = yield* Ref.get(activeSelection);
7629+
if (selection === null || selection.options === undefined) return;
7630+
const configured = yield* Ref.get(configuredModes);
7631+
const live = yield* readModes;
7632+
let changed = false;
7633+
const options = selection.options.map((option) => {
7634+
const value = live.get(option.id);
7635+
if (
7636+
value === undefined ||
7637+
typeof option.value !== "string" ||
7638+
value === configured.get(option.id) ||
7639+
value === option.value
7640+
) {
7641+
return option;
7642+
}
7643+
changed = true;
7644+
return { ...option, value };
7645+
});
7646+
if (!changed) return;
7647+
const reported = { ...selection, options };
7648+
yield* Ref.set(activeSelection, reported);
7649+
yield* Ref.set(configuredModes, live);
7650+
yield* emitProviderEvent({
7651+
type: "thread_model_selection.updated",
7652+
driver,
7653+
threadId,
7654+
modelSelection: reported,
7655+
});
7656+
});
7657+
76067658
const finalizeTurn = Effect.fnUntraced(function* (
76077659
context: ActiveAcpTurn,
76087660
status: "completed" | "interrupted" | "failed" | "cancelled",
@@ -7679,6 +7731,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
76797731
},
76807732
});
76817733
}
7734+
yield* reportAgentModeChanges(context.input.threadId);
76827735
const turn = providerTurnPayload(context, settledStatus, now);
76837736
yield* Ref.update(providerTurns, (current) => {
76847737
const updated = new Map(current);

0 commit comments

Comments
 (0)