The best way to control Claude Code, Codex and more from any computer or phone
fix(acp): a late session/load response no longer leaves the session without model controls (#23586)
Julius Marminge committed
Nov 19, 2026 at 11:14 UTC
5f8ab374af87a1324ca52ccbe7786a308dbc8311
5 files changed
+815
-22
apps/server/scripts/acp-mock-agent.ts
+39
@@ -71,6 +71,11 @@ const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
71
const failLoadSessionAfterConfigReplay =
72
process.env.T3_ACP_FAIL_LOAD_SESSION_AFTER_CONFIG_REPLAY === "1";
73
const emitLoadReplay = process.env.T3_ACP_EMIT_LOAD_REPLAY === "1";
74
+const delayLoadSessionAfterReplay = process.env.T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY === "1";
75
+const loadSessionDelayMs = Number(process.env.T3_ACP_LOAD_SESSION_DELAY_MS ?? "5000");
76
+const modeNotifiedBeforeDelayedLoadReply = process.env.T3_ACP_NOTIFY_MODE_BEFORE_LOAD_REPLY;
77
+const holdSetConfigOptionUntilLoadReply =
78
+ process.env.T3_ACP_HOLD_SET_CONFIG_OPTION_UNTIL_LOAD_REPLY === "1";
79
const loadReplyDelayMs = Number(process.env.T3_ACP_LOAD_REPLY_DELAY_MS ?? "0");
80
const loadNeverReplies = process.env.T3_ACP_LOAD_NEVER_REPLIES === "1";
81
const rejectPromptUntilLoaded = process.env.T3_ACP_REJECT_PROMPT_UNTIL_LOADED === "1";
@@ -504,6 +509,7 @@ const program = Effect.gen(function* () {
509
const agent = yield* EffectAcpAgent.AcpAgent;
510
const nativeCancelRequested = yield* Deferred.make<void>();
511
const nativeCancelRelease = yield* Deferred.make<void>();
512
+ const delayedLoadReplied = yield* Deferred.make<void>();
513
const publishAntigravityCommands = (targetSessionId: string) =>
514
agent.client.sessionUpdate({
515
sessionId: targetSessionId,
@@ -734,6 +740,33 @@ const program = Effect.gen(function* () {
740
"Mock load session failure after config replay",
741
);
742
}
743
+ if (delayLoadSessionAfterReplay) {
744
+ emitLoadReplayNotifications(requestedSessionId);
745
+ yield* agent.client.sessionUpdate({
746
+ sessionId: requestedSessionId,
747
+ update: {
748
+ sessionUpdate: "user_message_chunk",
749
+ messageId: "mock-user-message",
750
+ content: { type: "text", text: "replay-tail" },
751
+ },
752
+ });
753
+ // Answer with the configuration as of the load, like an agent whose
754
+ // response was built before later selections landed.
755
+ const loadedConfigOptions = configOptions();
756
+ if (modeNotifiedBeforeDelayedLoadReply !== undefined) {
757
+ yield* Effect.sleep(loadSessionDelayMs / 2);
758
+ currentModeId = modeNotifiedBeforeDelayedLoadReply;
759
+ yield* agent.client.sessionUpdate({
760
+ sessionId: requestedSessionId,
761
+ update: { sessionUpdate: "current_mode_update", currentModeId },
762
+ });
763
+ }
764
+ yield* Effect.sleep(loadSessionDelayMs);
765
+ yield* Deferred.succeed(delayedLoadReplied, undefined);
766
+ return {
767
+ configOptions: loadedConfigOptions,
768
+ };
769
+ }
770
if (emitLoadReplay) {
771
emitLoadReplayNotifications(requestedSessionId);
772
}
@@ -838,6 +871,12 @@ const program = Effect.gen(function* () {
871
872
yield* agent.handleSetSessionConfigOption((request) =>
873
Effect.gen(function* () {
874
+ if (holdSetConfigOptionUntilLoadReply) {
875
+ // Like an agent that serves requests in order: the delayed load reply
876
+ // goes out first, then this one.
877
+ yield* Deferred.await(delayedLoadReplied);
878
+ yield* Effect.sleep(100);
879
+ }
880
if (failSetModeConfigOption && request.configId === "mode") {
881
return yield* AcpError.AcpRequestError.invalidParams(
882
"Mock invalid params for session/set_config_option",
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+314
@@ -476,6 +476,8 @@ function makeMockRuntime(input: {
476
| ((runtimeOrdinal: number) => Readonly<Record<string, string>>);
477
readonly protocolEvents?: Queue.Queue<EffectAcpProtocol.AcpProtocolLogEvent>;
478
readonly cancelBehavior?: AcpSessionRuntime.AcpSessionRuntimeOptions["cancelBehavior"];
479
+ // Also opts into replay-idle readiness, which runtimes leave off by default.
480
+ readonly sessionLoadReplayIdleGap?: Duration.Input;
481
readonly ownDescendantProcessGroups?: boolean;
482
readonly ownDetachedProcessGroup?: boolean;
483
readonly processGroupPlatform?: NodeJS.Platform;
@@ -516,6 +518,12 @@ function makeMockRuntime(input: {
518
AcpSessionRuntime.layer({
519
...runtimeInput,
520
...(input.cancelBehavior === undefined ? {} : { cancelBehavior: input.cancelBehavior }),
521
+ ...(input.sessionLoadReplayIdleGap === undefined
522
+ ? {}
523
+ : {
524
+ sessionLoadReplayIdleGap: input.sessionLoadReplayIdleGap,
525
+ sessionLoadReplayIdleReadiness: true,
526
+ }),
527
...(input.ownDetachedProcessGroup === undefined
528
? {}
529
: { ownDetachedProcessGroup: input.ownDetachedProcessGroup }),
@@ -4894,6 +4902,312 @@ describe("AcpAdapterV2", () => {
4902
}).pipe(Effect.provide(layerTest)),
4903
);
4904
4905
+ it.live("enables model switching when session/load answers with a model after replay idle", () =>
4906
+ Effect.gen(function* () {
4907
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
4908
+ const path = yield* Path.Path;
4909
+ const selfInvocation = yield* resolveSelfInvocation();
4910
+ const mockAgentPath = yield* path.fromFileUrl(
4911
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
4912
+ );
4913
+ const lateConfigOptions = yield* Deferred.make<void>();
4914
+ let acpRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"] | undefined;
4915
+ const publishedConfigurations: Array<ReadonlyArray<EffectAcpSchema.SessionConfigOption>> = [];
4916
+ const instanceId = ProviderInstanceId.make("acp-test-late-session-load");
4917
+ const adapter = yield* makeAcpAdapterV2({
4918
+ instanceId,
4919
+ flavor: {
4920
+ driver: ACP_TEST_DRIVER,
4921
+ capabilities: AcpProviderCapabilitiesV2,
4922
+ onSessionConfigurationUpdate: (configOptions) =>
4923
+ Effect.sync(() => publishedConfigurations.push(configOptions)),
4924
+ makeRuntime: makeMockRuntime({
4925
+ childProcessSpawner,
4926
+ mockAgentPath,
4927
+ environment: {
4928
+ T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY: "1",
4929
+ T3_ACP_LOAD_SESSION_DELAY_MS: "500",
4930
+ },
4931
+ sessionLoadReplayIdleGap: "100 millis",
4932
+ wrapRuntime: (runtime) => {
4933
+ acpRuntime = runtime;
4934
+ return {
4935
+ ...runtime,
4936
+ getEvents: () =>
4937
+ runtime
4938
+ .getEvents()
4939
+ .pipe(
4940
+ Stream.tap((event) =>
4941
+ event._tag === "ConfigOptionsUpdated"
4942
+ ? Deferred.succeed(lateConfigOptions, undefined)
4943
+ : Effect.void,
4944
+ ),
4945
+ ),
4946
+ };
4947
+ },
4948
+ }),
4949
+ },
4950
+ selfInvocation,
4951
+ });
4952
+ const runtime = yield* adapter.openSession({
4953
+ threadId: ThreadId.make("thread-acp-late-session-load"),
4954
+ providerSessionId: ProviderSessionId.make("provider-session-acp-late-session-load"),
4955
+ modelSelection: { instanceId, model: "default" },
4956
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4957
+ runtimeMode: "full-access",
4958
+ interactionMode: "default",
4959
+ cwd: process.cwd(),
4960
+ }),
4961
+ initialNativeThreadId: "mock-session-1",
4962
+ });
4963
+
4964
+ yield* Deferred.await(lateConfigOptions).pipe(Effect.timeoutOption("5 seconds"));
4965
+ yield* acpRuntime!.drainEvents;
4966
+
4967
+ assert.isTrue(
4968
+ runtime.providerSession.capabilities.sessions.supportsModelSwitchInSession,
4969
+ "model switching stays disabled after the late session/load response offered a model",
4970
+ );
4971
+ // Registry agents fill their model picker from this callback.
4972
+ assert.equal(
4973
+ publishedConfigurations.filter((options) =>
4974
+ options.some((option) => option.category === "model"),
4975
+ ).length,
4976
+ 1,
4977
+ "the late session/load configuration must reach the catalog exactly once",
4978
+ );
4979
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
4980
+ );
4981
+
4982
+ it.live("applies the thread's model after a late session/load that lands during open", () =>
4983
+ Effect.gen(function* () {
4984
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
4985
+ const path = yield* Path.Path;
4986
+ const selfInvocation = yield* resolveSelfInvocation();
4987
+ const mockAgentPath = yield* path.fromFileUrl(
4988
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
4989
+ );
4990
+ const protocolEvents = yield* Queue.unbounded<EffectAcpProtocol.AcpProtocolLogEvent>();
4991
+ const adoptionHandled = yield* Deferred.make<void>();
4992
+ const adopted = yield* Deferred.make<void>();
4993
+ const publishedConfigurations: Array<ReadonlyArray<EffectAcpSchema.SessionConfigOption>> = [];
4994
+ let publications = 0;
4995
+ let acpRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"] | undefined;
4996
+ const instanceId = ProviderInstanceId.make("acp-test-late-session-load-selection");
4997
+ const threadId = ThreadId.make("thread-acp-late-session-load-selection");
4998
+ const adapter = yield* makeAcpAdapterV2({
4999
+ instanceId,
5000
+ flavor: {
5001
+ driver: ACP_TEST_DRIVER,
5002
+ capabilities: AcpProviderCapabilitiesV2,
5003
+ onSessionEvent: (event) =>
5004
+ event._tag === "SessionSetupAdopted"
5005
+ ? Deferred.succeed(adoptionHandled, undefined).pipe(Effect.asVoid)
5006
+ : Effect.void,
5007
+ // Holds openSession's own publication until the adapter has seen the
5008
+ // late response, so adoption overlaps session configuration.
5009
+ onSessionConfigurationUpdate: (configOptions) =>
5010
+ (publications++ === 0 ? Deferred.await(adoptionHandled) : Effect.void).pipe(
5011
+ Effect.andThen(Effect.sync(() => publishedConfigurations.push(configOptions))),
5012
+ Effect.andThen(
5013
+ configOptions.some((option) => option.category === "model")
5014
+ ? Deferred.succeed(adopted, undefined)
5015
+ : Effect.void,
5016
+ ),
5017
+ ),
5018
+ makeRuntime: makeMockRuntime({
5019
+ childProcessSpawner,
5020
+ mockAgentPath,
5021
+ protocolEvents,
5022
+ environment: {
5023
+ T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY: "1",
5024
+ T3_ACP_LOAD_SESSION_DELAY_MS: "500",
5025
+ },
5026
+ sessionLoadReplayIdleGap: "100 millis",
5027
+ wrapRuntime: (runtime) => {
5028
+ acpRuntime = runtime;
5029
+ return runtime;
5030
+ },
5031
+ }),
5032
+ },
5033
+ selfInvocation,
5034
+ });
5035
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
5036
+ runtimeMode: "full-access",
5037
+ interactionMode: "default",
5038
+ cwd: process.cwd(),
5039
+ });
5040
+ const modelSelection = { instanceId, model: "composer-2" } as const;
5041
+ const runtime = yield* adapter.openSession({
5042
+ threadId,
5043
+ providerSessionId: ProviderSessionId.make("provider-session-acp-late-load-selection"),
5044
+ modelSelection,
5045
+ runtimePolicy,
5046
+ initialNativeThreadId: "mock-session-1",
5047
+ });
5048
+ yield* Deferred.await(adopted).pipe(Effect.timeoutOption("5 seconds"));
5049
+ yield* acpRuntime!.drainEvents;
5050
+ const providerThread = yield* runtime.ensureThread({
5051
+ threadId,
5052
+ modelSelection,
5053
+ runtimePolicy,
5054
+ });
5055
+ yield* Queue.clear(protocolEvents);
5056
+
5057
+ yield* runtime.startTurn(
5058
+ makeTurnInput({
5059
+ threadId,
5060
+ providerThread,
5061
+ instanceId,
5062
+ runtimePolicy,
5063
+ modelSelection,
5064
+ now: yield* DateTime.now,
5065
+ }),
5066
+ );
5067
+ const methods: Array<string> = [];
5068
+ while (!methods.includes("session/prompt")) {
5069
+ const event = yield* Queue.take(protocolEvents);
5070
+ if (event.direction !== "outgoing") continue;
5071
+ const method = rawProtocolMethod(event);
5072
+ if (method !== undefined) methods.push(method);
5073
+ }
5074
+
5075
+ assert.include(
5076
+ methods,
5077
+ "session/set_config_option",
5078
+ "the selected model was only applied to the provisional setup, which offered no model",
5079
+ );
5080
+ assert.isTrue(
5081
+ publishedConfigurations.at(-1)?.some((option) => option.category === "model"),
5082
+ "the provisional catalog was published over the late session/load one",
5083
+ );
5084
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
5085
+ );
5086
+
5087
+ // Adoption either reaches the adapter after openSession configured the
5088
+ // provisional setup, or before it, so openSession configures the adopted one.
5089
+ it.live.each([false, true])(
5090
+ "restores the native build mode after a Plan turn that followed a late session/load (adopted before configuration: %s)",
5091
+ (adoptedBeforeConfiguration) =>
5092
+ Effect.gen(function* () {
5093
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
5094
+ const path = yield* Path.Path;
5095
+ const selfInvocation = yield* resolveSelfInvocation();
5096
+ const mockAgentPath = yield* path.fromFileUrl(
5097
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
5098
+ );
5099
+ const protocolEvents = yield* Queue.unbounded<EffectAcpProtocol.AcpProtocolLogEvent>();
5100
+ const adopted = yield* Deferred.make<void>();
5101
+ const adoptionHandled = yield* Deferred.make<void>();
5102
+ let holdFirstModeRead = adoptedBeforeConfiguration;
5103
+ let acpRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"] | undefined;
5104
+ const instanceId = ProviderInstanceId.make("acp-test-late-session-load-plan");
5105
+ const threadId = ThreadId.make("thread-acp-late-session-load-plan");
5106
+ const adapter = yield* makeAcpAdapterV2({
5107
+ instanceId,
5108
+ flavor: {
5109
+ driver: ACP_TEST_DRIVER,
5110
+ capabilities: AcpProviderCapabilitiesV2,
5111
+ onSessionEvent: (event) =>
5112
+ event._tag === "SessionSetupAdopted"
5113
+ ? Deferred.succeed(adoptionHandled, undefined).pipe(Effect.asVoid)
5114
+ : Effect.void,
5115
+ makeRuntime: makeMockRuntime({
5116
+ childProcessSpawner,
5117
+ mockAgentPath,
5118
+ protocolEvents,
5119
+ environment: {
5120
+ T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY: "1",
5121
+ T3_ACP_LOAD_SESSION_DELAY_MS: "500",
5122
+ },
5123
+ sessionLoadReplayIdleGap: "100 millis",
5124
+ wrapRuntime: (runtime) => {
5125
+ acpRuntime = runtime;
5126
+ return {
5127
+ ...runtime,
5128
+ getModeState: Effect.suspend(() => {
5129
+ if (!holdFirstModeRead) return runtime.getModeState;
5130
+ holdFirstModeRead = false;
5131
+ return Deferred.await(adoptionHandled).pipe(
5132
+ Effect.andThen(runtime.getModeState),
5133
+ );
5134
+ }),
5135
+ getEvents: () =>
5136
+ runtime
5137
+ .getEvents()
5138
+ .pipe(
5139
+ Stream.tap((event) =>
5140
+ event._tag === "SessionSetupAdopted"
5141
+ ? Deferred.succeed(adopted, undefined)
5142
+ : Effect.void,
5143
+ ),
5144
+ ),
5145
+ };
5146
+ },
5147
+ }),
5148
+ },
5149
+ selfInvocation,
5150
+ });
5151
+ const policy = (interactionMode: "default" | "plan") =>
5152
+ ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
5153
+ runtimeMode: "full-access",
5154
+ interactionMode,
5155
+ cwd: process.cwd(),
5156
+ });
5157
+ const planPolicy = policy("plan");
5158
+ const modelSelection = { instanceId, model: "default" } as const;
5159
+ const runtime = yield* adapter.openSession({
5160
+ threadId,
5161
+ providerSessionId: ProviderSessionId.make("provider-session-acp-late-load-plan"),
5162
+ modelSelection,
5163
+ runtimePolicy: planPolicy,
5164
+ initialNativeThreadId: "mock-session-1",
5165
+ });
5166
+ yield* Deferred.await(adopted).pipe(Effect.timeoutOption("5 seconds"));
5167
+ yield* acpRuntime!.drainEvents;
5168
+ const providerThread = yield* runtime.ensureThread({
5169
+ threadId,
5170
+ modelSelection,
5171
+ runtimePolicy: planPolicy,
5172
+ });
5173
+ yield* Queue.clear(protocolEvents);
5174
+ const now = yield* DateTime.now;
5175
+ const runTurn = Effect.fnUntraced(function* (
5176
+ ordinal: number,
5177
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
5178
+ ) {
5179
+ yield* runtime.startTurn(
5180
+ makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal }),
5181
+ );
5182
+ yield* runtime.events.pipe(
5183
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
5184
+ Stream.runDrain,
5185
+ );
5186
+ const modeValues: Array<unknown> = [];
5187
+ while (true) {
5188
+ const event = yield* Queue.take(protocolEvents);
5189
+ if (event.direction !== "outgoing") continue;
5190
+ const request = rawProtocolRequest(event);
5191
+ if (request?.method === "session/prompt") return modeValues;
5192
+ if (request?.method === "session/set_config_option") {
5193
+ modeValues.push((request.params as { readonly value?: unknown }).value);
5194
+ }
5195
+ }
5196
+ });
5197
+
5198
+ // Configured against the adopted setup, openSession already switched to Plan.
5199
+ assert.deepEqual(
5200
+ yield* runTurn(0, planPolicy),
5201
+ adoptedBeforeConfiguration ? [] : ["architect"],
5202
+ );
5203
+ assert.deepEqual(
5204
+ yield* runTurn(1, policy("default")),
5205
+ ["ask"],
5206
+ "Build must restore the mode the late session/load reported, not the provisional setup's",
5207
+ );
5208
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
5209
+ );
5210
+
5211
it.live("creates a fresh ACP identity when recovering an exhausted target", () =>
5212
Effect.gen(function* () {
5213
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
+156
@@ -24,6 +24,7 @@ import { describe, expect } from "vite-plus/test";
24
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
25
import { AgentScope } from "@t3tools/shared/AgentScope";
26
import * as EffectAcpErrors from "effect-acp/errors";
27
+import type * as EffectAcpSchema from "effect-acp/compat";
28
import type * as EffectAcpProtocol from "effect-acp/protocol";
29
30
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
@@ -1218,6 +1219,161 @@ describe("AcpSessionRuntime", () => {
1219
),
1220
);
1221
1222
+ // Live clock: the replay-idle gap must elapse in real time against the mock agent process.
1223
+ it.live("adopts config options from a session/load response that arrives after replay idle", () =>
1224
+ Effect.gen(function* () {
1225
+ const runtime = yield* AcpSessionRuntime.make({
1226
+ ...mockRuntimeOptions,
1227
+ spawn: {
1228
+ ...mockRuntimeOptions.spawn,
1229
+ env: {
1230
+ T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY: "1",
1231
+ T3_ACP_LOAD_SESSION_DELAY_MS: "500",
1232
+ },
1233
+ },
1234
+ resumeSessionId: "mock-session-1",
1235
+ sessionLoadReplayIdleGap: "100 millis",
1236
+ sessionLoadReplayIdleReadiness: true,
1237
+ });
1238
+ const started = yield* runtime.start();
1239
+ expect(started.sessionSetupResult._meta).toMatchObject({ t3SessionLoadReady: "replay_idle" });
1240
+
1241
+ yield* runtime.getEvents().pipe(
1242
+ Stream.filter((event) => event._tag === "ConfigOptionsUpdated"),
1243
+ Stream.take(1),
1244
+ Stream.runDrain,
1245
+ Effect.timeoutOption("5 seconds"),
1246
+ );
1247
+
1248
+ expect((yield* runtime.getConfigOptions).map((option) => option.id)).toEqual([
1249
+ "mode",
1250
+ "model",
1251
+ ]);
1252
+ }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1253
+ );
1254
+
1255
+ it.live("drops a late session/load response when a selection was sent before it", () =>
1256
+ Effect.gen(function* () {
1257
+ const lateLoadLogged = yield* Deferred.make<void>();
1258
+ const runtime = yield* AcpSessionRuntime.make({
1259
+ ...mockRuntimeOptions,
1260
+ spawn: {
1261
+ ...mockRuntimeOptions.spawn,
1262
+ env: {
1263
+ T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY: "1",
1264
+ T3_ACP_LOAD_SESSION_DELAY_MS: "500",
1265
+ T3_ACP_HOLD_SET_CONFIG_OPTION_UNTIL_LOAD_REPLY: "1",
1266
+ },
1267
+ },
1268
+ resumeSessionId: "mock-session-1",
1269
+ sessionLoadReplayIdleGap: "100 millis",
1270
+ sessionLoadReplayIdleReadiness: true,
1271
+ requestLogger: (event) =>
1272
+ event.method === "session/load" &&
1273
+ event.status === "succeeded" &&
1274
+ (event.result as { readonly configOptions?: unknown } | undefined)?.configOptions !==
1275
+ undefined
1276
+ ? Deferred.succeed(lateLoadLogged, undefined).pipe(Effect.asVoid)
1277
+ : Effect.void,
1278
+ });
1279
+ const started = yield* runtime.start();
1280
+ // The agent answers the load before this request, so no config change
1281
+ // is visible when the late response arrives.
1282
+ yield* runtime.setConfigOption("model", "gpt-5.4");
1283
+ yield* Deferred.await(lateLoadLogged).pipe(Effect.timeout("5 seconds"));
1284
+
1285
+ expect((yield* runtime.start()).sessionSetupResult).toBe(started.sessionSetupResult);
1286
+ const model = (yield* runtime.getConfigOptions).find((option) => option.id === "model");
1287
+ expect(model?.currentValue).toBe("gpt-5.4");
1288
+ }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1289
+ );
1290
+
1291
+ it.live("drops a late session/load response when the agent changed mode before it", () =>
1292
+ Effect.gen(function* () {
1293
+ const lateLoadLogged = yield* Deferred.make<void>();
1294
+ const runtime = yield* AcpSessionRuntime.make({
1295
+ ...mockRuntimeOptions,
1296
+ spawn: {
1297
+ ...mockRuntimeOptions.spawn,
1298
+ env: {
1299
+ T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY: "1",
1300
+ T3_ACP_LOAD_SESSION_DELAY_MS: "500",
1301
+ T3_ACP_NOTIFY_MODE_BEFORE_LOAD_REPLY: "code",
1302
+ },
1303
+ },
1304
+ resumeSessionId: "mock-session-1",
1305
+ sessionLoadReplayIdleGap: "100 millis",
1306
+ sessionLoadReplayIdleReadiness: true,
1307
+ // The mock speaks ACP v2, which has no current_mode_update; decode it as a v1 agent's.
1308
+ transformSessionUpdate: (notification) =>
1309
+ notification.update.sessionUpdate === "_t3_unknown" &&
1310
+ notification.update.originalSessionUpdate === "current_mode_update"
1311
+ ? {
1312
+ ...notification,
1313
+ update: notification.update.raw as EffectAcpSchema.SessionNotification["update"],
1314
+ }
1315
+ : notification,
1316
+ requestLogger: (event) =>
1317
+ event.method === "session/load" &&
1318
+ event.status === "succeeded" &&
1319
+ (event.result as { readonly configOptions?: unknown } | undefined)?.configOptions !==
1320
+ undefined
1321
+ ? Deferred.succeed(lateLoadLogged, undefined).pipe(Effect.asVoid)
1322
+ : Effect.void,
1323
+ });
1324
+ const started = yield* runtime.start();
1325
+ // No mode metadata yet, so the notification leaves the mode state as is.
1326
+ expect(yield* runtime.getModeState).toBeUndefined();
1327
+ yield* Deferred.await(lateLoadLogged).pipe(Effect.timeout("5 seconds"));
1328
+
1329
+ expect((yield* runtime.start()).sessionSetupResult).toBe(started.sessionSetupResult);
1330
+ expect(yield* runtime.getModeState).toBeUndefined();
1331
+ }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1332
+ );
1333
+
1334
+ it.live("drops a late session/load response that startup metadata superseded", () =>
1335
+ Effect.gen(function* () {
1336
+ const provisionalLogged = yield* Deferred.make<void>();
1337
+ const allowStartup = yield* Deferred.make<void>();
1338
+ const lateLoadLogged = yield* Deferred.make<void>();
1339
+ const runtime = yield* AcpSessionRuntime.make({
1340
+ ...mockRuntimeOptions,
1341
+ spawn: {
1342
+ ...mockRuntimeOptions.spawn,
1343
+ env: {
1344
+ T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY: "1",
1345
+ T3_ACP_LOAD_SESSION_DELAY_MS: "500",
1346
+ },
1347
+ },
1348
+ resumeSessionId: "mock-session-1",
1349
+ sessionLoadReplayIdleGap: "100 millis",
1350
+ sessionLoadReplayIdleReadiness: true,
1351
+ requestLogger: (event) => {
1352
+ if (event.method !== "session/load" || event.status !== "succeeded") {
1353
+ return Effect.void;
1354
+ }
1355
+ return (event.result as { readonly configOptions?: unknown } | undefined)
1356
+ ?.configOptions === undefined
1357
+ ? Deferred.succeed(provisionalLogged, undefined).pipe(
1358
+ Effect.andThen(Deferred.await(allowStartup)),
1359
+ )
1360
+ : Deferred.succeed(lateLoadLogged, undefined).pipe(Effect.asVoid);
1361
+ },
1362
+ });
1363
+ const startup = yield* runtime.start().pipe(Effect.forkChild);
1364
+ yield* Deferred.await(provisionalLogged);
1365
+ yield* runtime.request("_test/startup-metadata", {});
1366
+ yield* Deferred.succeed(allowStartup, undefined);
1367
+ yield* Fiber.join(startup);
1368
+ yield* Deferred.await(lateLoadLogged).pipe(Effect.timeout("5 seconds"));
1369
+
1370
+ expect(yield* runtime.getModeState).toMatchObject({ currentModeId: "code" });
1371
+ expect(
1372
+ (yield* runtime.getConfigOptions).find((option) => option.category === "model"),
1373
+ ).toMatchObject({ currentValue: "gpt-5.4" });
1374
+ }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1375
+ );
1376
+
1377
it.effect("keeps active configuration after a candidate session load fails", () =>
1378
Effect.gen(function* () {
1379
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
packages/provider-acp/src/server/AcpSessionRuntime.ts
+191
-14
@@ -76,6 +76,12 @@ export type AcpSessionRuntimeEvent =
76
| {
77
readonly _tag: "ConnectionTerminated";
78
readonly error: EffectAcpErrors.AcpError;
79
+ }
80
+ | {
81
+ // A session/load response that arrived after replay idle replaced the
82
+ // provisional setup; its config/mode events were emitted just before.
83
+ readonly _tag: "SessionSetupAdopted";
84
+ readonly result: AcpSessionRuntimeStartResult;
85
};
86
87
const defaultSessionLoadTimeout = Duration.seconds(90);
@@ -1303,6 +1309,23 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
1309
const activePromptRef = yield* Ref.make<Option.Option<AcpActivePrompt>>(Option.none());
1310
const assistantUpdatesOpenRef = yield* Ref.make(true);
1311
const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());
1312
+ // When replay idle makes a loaded session usable first, the agent's real
1313
+ // session/load response is still pending; it is adopted once it arrives.
1314
+ const lateSessionLoadRef = yield* Ref.make<
1315
+ Option.Option<{
1316
+ readonly payload: EffectAcpSchema.LoadSessionRequest;
1317
+ readonly provisional: EffectAcpSchema.LoadSessionResponse;
1318
+ readonly response: Fiber.Fiber<
1319
+ Option.Option<EffectAcpSchema.LoadSessionResponse>,
1320
+ EffectAcpErrors.AcpError
1321
+ >;
1322
+ }>
1323
+ >(Option.none());
1324
+ // Counts mode, config, and model writes sent to the agent and the mode and
1325
+ // config notifications it sent back. A late session/load response predates
1326
+ // all of them, even a write still pending or a notification that left the
1327
+ // mode state unchanged.
1328
+ const sessionChangeCountRef = yield* Ref.make(0);
1329
1330
const ensureConnected = Effect.gen(function* () {
1331
const error = yield* Ref.get(terminationErrorRef);
@@ -1365,6 +1388,15 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
1388
const logRequest = (event: AcpSessionRequestLogEvent) =>
1389
options.requestLogger ? options.requestLogger(event) : Effect.void;
1390
1391
+ const runLoggedSessionWrite = <A>(
1392
+ method: string,
1393
+ payload: unknown,
1394
+ effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
1395
+ ): Effect.Effect<A, EffectAcpErrors.AcpError> =>
1396
+ Ref.update(sessionChangeCountRef, (count) => count + 1).pipe(
1397
+ Effect.andThen(runLoggedRequest(method, payload, effect)),
1398
+ );
1399
+
1400
const runLoggedRequest = <A>(
1401
method: string,
1402
payload: unknown,
@@ -1715,8 +1747,12 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
1747
const configOptionUpdates = yield* Ref.make(0);
1748
const processSessionUpdate = (notification: EffectAcpSchema.SessionNotification) =>
1749
(notification.update.sessionUpdate === "config_option_update"
1718
- ? Ref.update(configOptionUpdates, (count) => count + 1)
1719
- : Effect.void
1750
+ ? Ref.update(configOptionUpdates, (count) => count + 1).pipe(
1751
+ Effect.andThen(Ref.update(sessionChangeCountRef, (count) => count + 1)),
1752
+ )
1753
+ : notification.update.sessionUpdate === "current_mode_update"
1754
+ ? Ref.update(sessionChangeCountRef, (count) => count + 1)
1755
+ : Effect.void
1756
).pipe(
1757
Effect.andThen(
1758
handleSessionUpdate({
@@ -1972,6 +2008,110 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2008
return nextState;
2009
});
2010
2011
+ const cancelLateSessionLoad = Ref.getAndSet(lateSessionLoadRef, Option.none()).pipe(
2012
+ Effect.flatMap(
2013
+ Option.match({
2014
+ onNone: () => Effect.void,
2015
+ onSome: (late) => Fiber.interrupt(late.response),
2016
+ }),
2017
+ ),
2018
+ Effect.asVoid,
2019
+ );
2020
+
2021
+ // Adopts the agent's real session/load response after a replay-idle start.
2022
+ // Anything that changed the session or its configuration in between is newer
2023
+ // than this response, so the response is dropped instead of applied.
2024
+ const followLateSessionLoad = Effect.fn("AcpSessionRuntime.followLateSessionLoad")(function* (
2025
+ started: AcpStartedState,
2026
+ // Notifications counted after this baseline are newer than the response.
2027
+ provisionalChangeCount?: number,
2028
+ ) {
2029
+ const late = yield* Ref.get(lateSessionLoadRef);
2030
+ if (Option.isNone(late) || late.value.provisional !== started.sessionSetupResult) {
2031
+ return;
2032
+ }
2033
+ const { payload, response: lateFiber } = late.value;
2034
+ const provisionalConfigOptions = yield* SubscriptionRef.get(configOptionsRef);
2035
+ const provisionalModeState = yield* Ref.get(modeStateRef);
2036
+ const baselineChangeCount = provisionalChangeCount ?? (yield* Ref.get(sessionChangeCountRef));
2037
+ const adoptLateResponse = Effect.fn("AcpSessionRuntime.adoptLateSessionLoad")(function* (
2038
+ response: EffectAcpSchema.LoadSessionResponse,
2039
+ ) {
2040
+ const current = yield* Ref.get(lateSessionLoadRef);
2041
+ const startState = yield* Ref.get(startStateRef);
2042
+ if (
2043
+ Option.isNone(current) ||
2044
+ current.value.response !== lateFiber ||
2045
+ startState._tag !== "Started" ||
2046
+ startState.result !== started ||
2047
+ (yield* Ref.get(stoppingRef)) ||
2048
+ (yield* SubscriptionRef.get(configOptionsRef)) !== provisionalConfigOptions ||
2049
+ (yield* Ref.get(modeStateRef)) !== provisionalModeState ||
2050
+ (yield* Ref.get(sessionChangeCountRef)) !== baselineChangeCount
2051
+ ) {
2052
+ return;
2053
+ }
2054
+ yield* Ref.set(lateSessionLoadRef, Option.none());
2055
+ const result = {
2056
+ ...started,
2057
+ sessionSetupResult: response,
2058
+ modelConfigId: extractModelConfigId(response) ?? started.modelConfigId,
2059
+ };
2060
+ yield* Ref.set(startStateRef, { _tag: "Started", result });
2061
+ const modeState = parseSessionModeState(response);
2062
+ if (modeState !== undefined) {
2063
+ yield* Ref.set(modeStateRef, modeState);
2064
+ }
2065
+ if (response.configOptions != null) {
2066
+ yield* processSessionUpdate({
2067
+ sessionId: started.sessionId,
2068
+ update: { sessionUpdate: "config_option_update", configOptions: response.configOptions },
2069
+ });
2070
+ } else if (modeState !== undefined) {
2071
+ yield* processSessionUpdate({
2072
+ sessionId: started.sessionId,
2073
+ update: { sessionUpdate: "current_mode_update", currentModeId: modeState.currentModeId },
2074
+ });
2075
+ }
2076
+ yield* Queue.offer(eventQueue, { _tag: "SessionSetupAdopted", result });
2077
+ });
2078
+ yield* Fiber.join(lateFiber).pipe(
2079
+ Effect.flatMap(
2080
+ Option.match({
2081
+ onNone: () =>
2082
+ Effect.fail(
2083
+ new EffectAcpErrors.AcpTransportError({
2084
+ operation: "call-rpc",
2085
+ method: "session/load",
2086
+ detail: "session/load timed out after replay idle",
2087
+ cause: undefined,
2088
+ }),
2089
+ ),
2090
+ onSome: (response) =>
2091
+ notificationSemaphore.withPermit(adoptLateResponse(response)).pipe(
2092
+ Effect.andThen(
2093
+ logRequest({
2094
+ method: "session/load",
2095
+ payload,
2096
+ status: "succeeded",
2097
+ result: response,
2098
+ }),
2099
+ ),
2100
+ ),
2101
+ }),
2102
+ ),
2103
+ // Supersession and shutdown interrupt the request; only a real failure
2104
+ // or timeout is worth a failed log.
2105
+ Effect.onError((cause) =>
2106
+ Cause.hasInterruptsOnly(cause)
2107
+ ? Effect.void
2108
+ : logRequest({ method: "session/load", payload, status: "failed", cause }),
2109
+ ),
2110
+ Effect.ignore,
2111
+ Effect.forkIn(runtimeScope),
2112
+ );
2113
+ });
2114
+
2115
const runLoadSessionWithReplayIdle = (
2116
loadPayload: EffectAcpSchema.LoadSessionRequest,
2117
initializeResult: EffectAcpSchema.InitializeResponse,
@@ -1996,6 +2136,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2136
}),
2137
);
2138
2139
+ yield* cancelLateSessionLoad;
2140
return yield* Effect.gen(function* () {
2141
yield* logRequest({
2142
method: "session/load",
@@ -2003,6 +2144,14 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2144
status: "started",
2145
});
2146
2147
+ // Forked so a replay-idle win leaves the request running; the timeout
2148
+ // still bounds it and the runtime scope cancels it on shutdown.
2149
+ const responseFiber = yield* acp.agent
2150
+ .loadSession(loadPayload)
2151
+ .pipe(Effect.timeoutOption(sessionLoadTimeout), Effect.forkIn(runtimeScope));
2152
+ const awaitResponse = Fiber.join(responseFiber).pipe(
2153
+ Effect.map(Option.map((response) => ({ response, provisional: false }))),
2154
+ );
2155
const loadOrReplayIdle =
2156
options.sessionLoadReplayIdleReadiness === true
2157
? Effect.gen(function* () {
@@ -2010,16 +2159,18 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2159
gateRef: sessionLoadGateRef,
2160
}).pipe(Effect.forkIn(runtimeScope));
2161
return yield* Effect.raceFirst(
2013
- acp.agent.loadSession(loadPayload),
2014
- Fiber.join(idleFiber),
2162
+ awaitResponse,
2163
+ Fiber.join(idleFiber).pipe(
2164
+ Effect.map((response) => Option.some({ response, provisional: true })),
2165
+ ),
2166
).pipe(Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)));
2167
})
2017
- : acp.agent.loadSession(loadPayload);
2168
+ : awaitResponse;
2169
const loaded = yield* loadOrReplayIdle.pipe(
2170
Effect.timeoutOption(sessionLoadTimeout),
2171
Effect.flatMap((result) =>
2172
Effect.fromOption(
2022
- result,
2173
+ Option.flatten(result),
2174
() =>
2175
new EffectAcpErrors.AcpTransportError({
2176
operation: "call-rpc",
@@ -2029,12 +2180,17 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2180
}),
2181
),
2182
),
2032
- Effect.tap((result) =>
2183
+ Effect.onExit((exit) =>
2184
+ Exit.isSuccess(exit) && exit.value.provisional
2185
+ ? Effect.void
2186
+ : Fiber.interrupt(responseFiber).pipe(Effect.ignore),
2187
+ ),
2188
+ Effect.tap(({ response }) =>
2189
logRequest({
2190
method: "session/load",
2191
payload: loadPayload,
2192
status: "succeeded",
2037
- result,
2193
+ result: response,
2194
}),
2195
),
2196
Effect.onError((cause) =>
@@ -2051,9 +2207,17 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2207
const candidateConfigOptions = Option.isSome(gate)
2208
? gate.value.candidateConfigOptions
2209
: undefined;
2054
- return loaded.configOptions == null && candidateConfigOptions !== undefined
2055
- ? { ...loaded, configOptions: candidateConfigOptions }
2056
- : loaded;
2210
+ const response =
2211
+ loaded.response.configOptions == null && candidateConfigOptions !== undefined
2212
+ ? { ...loaded.response, configOptions: candidateConfigOptions }
2213
+ : loaded.response;
2214
+ if (loaded.provisional) {
2215
+ yield* Ref.set(
2216
+ lateSessionLoadRef,
2217
+ Option.some({ payload: loadPayload, provisional: response, response: responseFiber }),
2218
+ );
2219
+ }
2220
+ return response;
2221
}).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));
2222
}),
2223
);
@@ -2100,7 +2264,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2264
// handled before this fiber resumes. The result then stays out.
2265
return Ref.get(configOptionUpdates).pipe(
2266
Effect.flatMap((updatesBefore) =>
2103
- runLoggedRequest(
2267
+ runLoggedSessionWrite(
2268
"session/set_config_option",
2269
requestPayload,
2270
acp.agent.setSessionConfigOption(requestPayload),
@@ -2353,12 +2517,14 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2517
return yield* error.value;
2518
}
2519
yield* Ref.set(startStateRef, { _tag: "Started", result });
2520
+ const changeCountBeforeMetadata = yield* Ref.get(sessionChangeCountRef);
2521
const metadata = yield* Ref.getAndSet(startupMetadataRef, []);
2522
for (const notification of metadata) {
2523
if (notification.sessionId === result.sessionId) {
2524
yield* processSessionUpdate(notification);
2525
}
2526
}
2527
+ yield* followLateSessionLoad(result, changeCountBeforeMetadata);
2528
yield* Deferred.succeed(deferred, result);
2529
}),
2530
),
@@ -2513,9 +2679,11 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2679
return runLoadSessionWithReplayIdle(requestPayload, started.initializeResult);
2680
}),
2681
Effect.flatMap((response) => adoptSession(sessionId, response)),
2682
+ Effect.tap((started) => followLateSessionLoad(started)),
2683
),
2684
resumeSession: (sessionId, activationOptions) =>
2685
start.pipe(
2686
+ Effect.tap(() => cancelLateSessionLoad),
2687
Effect.flatMap((started) => {
2688
const requestPayload = {
2689
sessionId,
@@ -2533,6 +2701,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2701
),
2702
forkSession: (sessionId, activationOptions, meta) =>
2703
start.pipe(
2704
+ Effect.tap(() => cancelLateSessionLoad),
2705
Effect.flatMap((started) => {
2706
const requestPayload = {
2707
sessionId,
@@ -2763,7 +2932,11 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2932
if (modeConfigOption === undefined && modeState !== undefined) {
2933
const started = yield* getStartedState;
2934
const payload = { sessionId: started.sessionId, modeId };
2766
- yield* runLoggedRequest("session/set_mode", payload, acp.agent.setSessionMode(payload));
2935
+ yield* runLoggedSessionWrite(
2936
+ "session/set_mode",
2937
+ payload,
2938
+ acp.agent.setSessionMode(payload),
2939
+ );
2940
yield* updateCurrentModeId(modeId);
2941
return {} satisfies EffectAcpSchema.SetSessionModeResponse;
2942
}
@@ -2784,7 +2957,11 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2957
modelId,
2958
...(meta === undefined ? {} : { _meta: meta }),
2959
};
2787
- return runLoggedRequest("session/set_model", payload, acp.agent.setSessionModel(payload));
2960
+ return runLoggedSessionWrite(
2961
+ "session/set_model",
2962
+ payload,
2963
+ acp.agent.setSessionModel(payload),
2964
+ );
2965
}),
2966
),
2967
setConfigOption,
packages/provider-acp/src/server/adapter.ts
+115
-8
@@ -891,6 +891,13 @@ export const AcpProviderCapabilitiesV2 = {
891
},
892
} satisfies OrchestrationV2ProviderCapabilities;
893
894
+function canSwitchModelInSession(
895
+ configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
896
+ models: EffectAcpSchema.SessionModelState | null | undefined,
897
+): boolean {
898
+ return findModelConfigOption(configOptions) !== undefined || models != null;
899
+}
900
+
901
const STEER_DELIVERY_BOUND = "2 seconds";
902
903
/**
@@ -945,9 +952,7 @@ function negotiatedCapabilities(
952
const session = agent.sessionCapabilities;
953
const setup = started.sessionSetupResult;
954
const canSwitchModel =
948
- modelOptionArrivesLate ||
949
- findModelConfigOption(setup.configOptions) !== undefined ||
950
- setup.models != null;
955
+ modelOptionArrivesLate || canSwitchModelInSession(setup.configOptions, setup.models);
956
const canLoad = agent.loadSession === true;
957
const canFork = session?.fork != null;
958
return {
@@ -2642,6 +2647,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2647
Queue.offer(events, event).pipe(Effect.asVoid);
2648
let scheduleDeferredFinalize: (context: ActiveAcpTurn) => Effect.Effect<void> = () =>
2649
Effect.void;
2650
+ let refreshModelSwitchCapability: Effect.Effect<void> = Effect.void;
2651
+ // openSession configures the session itself; a late setup that lands
2652
+ // first waits here and is adopted once that configuration is in place.
2653
+ const lateSessionSetup: {
2654
+ openSessionConfigured: boolean;
2655
+ pending: Effect.Effect<void> | null;
2656
+ } = { openSessionConfigured: false, pending: null };
2657
2658
const nativeLogging = options.nativeLogging?.(input.threadId);
2659
const promptInactivityTimeoutMillis =
@@ -7094,6 +7106,41 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7106
);
7107
});
7108
7109
+ // The adopted response never passes through the raw session-update
7110
+ // handler, so this is its one catalog publication.
7111
+ const adoptLateSessionSetup = Effect.fnUntraced(function* (
7112
+ targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"],
7113
+ result: AcpSessionRuntime.AcpSessionRuntimeStartResult,
7114
+ provisionalBuildSnapshot: AcpNativeBuildConfiguration | undefined,
7115
+ ) {
7116
+ const current = yield* Ref.get(activeSessionSetup);
7117
+ if (current === null || current.sessionId !== result.sessionId) {
7118
+ return;
7119
+ }
7120
+ yield* Ref.set(activeSessionSetup, result);
7121
+ // The selection was configured against the provisional setup's
7122
+ // options, so the next turn re-applies it against the real ones.
7123
+ yield* Ref.set(activeSelection, null);
7124
+ yield* Ref.set(activeInteractionMode, null);
7125
+ // A build snapshot saved before the adoption was seen holds the
7126
+ // provisional state; one saved by a deferred openSession
7127
+ // configuration already read the adopted options and stays.
7128
+ if (
7129
+ provisionalBuildSnapshot !== undefined &&
7130
+ nativeBuildConfigurationBySessionId.get(result.sessionId) === provisionalBuildSnapshot
7131
+ ) {
7132
+ nativeBuildConfigurationBySessionId.delete(result.sessionId);
7133
+ }
7134
+ yield* refreshModelSwitchCapability;
7135
+ yield* (
7136
+ flavor.onSessionConfigurationUpdate?.(
7137
+ yield* targetRuntime.getConfigOptions,
7138
+ yield* targetRuntime.getModeState,
7139
+ result.sessionSetupResult.models,
7140
+ ) ?? Effect.void
7141
+ );
7142
+ });
7143
+
7144
const wireAcpRuntimeHandlers = Effect.fnUntraced(function* (
7145
targetRuntime: AcpSessionRuntime.AcpSessionRuntime["Service"],
7146
handlerGeneration: number,
@@ -7111,8 +7158,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7158
}
7159
return runRuntimeCallbackAtGeneration(
7160
handlerGeneration,
7114
- flavor.onSessionEvent?.(event, input.runtimePolicy.cwd ?? process.cwd()) ??
7115
- Effect.void,
7161
+ Effect.andThen(
7162
+ event._tag === "ConfigOptionsUpdated"
7163
+ ? refreshModelSwitchCapability
7164
+ : event._tag === "SessionSetupAdopted"
7165
+ ? Effect.suspend(() => {
7166
+ const adopt = adoptLateSessionSetup(
7167
+ targetRuntime,
7168
+ event.result,
7169
+ nativeBuildConfigurationBySessionId.get(event.result.sessionId),
7170
+ );
7171
+ if (lateSessionSetup.openSessionConfigured) return adopt;
7172
+ lateSessionSetup.pending = adopt;
7173
+ return Effect.void;
7174
+ })
7175
+ : Effect.void,
7176
+ flavor.onSessionEvent?.(event, input.runtimePolicy.cwd ?? process.cwd()) ??
7177
+ Effect.void,
7178
+ ),
7179
).pipe(Effect.asVoid);
7180
}),
7181
Effect.forkIn(handlerOptions.scope ?? runtimeScope ?? sessionScope),
@@ -8220,18 +8283,60 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8283
yield* Ref.set(activeSelection, input.modelSelection);
8284
yield* Ref.set(activeInteractionMode, input.runtimePolicy.interactionMode);
8285
const createdAt = yield* DateTime.now;
8223
- const providerSession: OrchestrationV2ProviderSession = {
8286
+ let providerSession: OrchestrationV2ProviderSession = {
8287
id: input.providerSessionId,
8288
driver,
8289
providerInstanceId: options.instanceId,
8290
status: "ready",
8291
cwd: input.runtimePolicy.cwd ?? process.cwd(),
8292
model: input.modelSelection.model,
8230
- capabilities,
8293
+ capabilities: {
8294
+ ...capabilities,
8295
+ sessions: {
8296
+ ...capabilities.sessions,
8297
+ supportsModelSwitchInSession:
8298
+ capabilities.sessions.supportsModelSwitchInSession ||
8299
+ canSwitchModelInSession(
8300
+ yield* runtime.getConfigOptions,
8301
+ (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models,
8302
+ ),
8303
+ },
8304
+ },
8305
createdAt,
8306
updatedAt: createdAt,
8307
lastError: null,
8308
};
8309
+ // Config options can first offer a model after setup, e.g. when a
8310
+ // session/load response arrives after replay idle. Upgrade-only: a
8311
+ // later partial config update must not revoke the switch mid-session.
8312
+ refreshModelSwitchCapability = Effect.gen(function* () {
8313
+ const { capabilities } = providerSession;
8314
+ if (capabilities.sessions.supportsModelSwitchInSession) {
8315
+ return;
8316
+ }
8317
+ const supportsModelSwitchInSession = canSwitchModelInSession(
8318
+ yield* runtime.getConfigOptions,
8319
+ (yield* Ref.get(activeSessionSetup))?.sessionSetupResult.models,
8320
+ );
8321
+ if (!supportsModelSwitchInSession) {
8322
+ return;
8323
+ }
8324
+ providerSession = {
8325
+ ...providerSession,
8326
+ capabilities: {
8327
+ ...capabilities,
8328
+ sessions: { ...capabilities.sessions, supportsModelSwitchInSession },
8329
+ },
8330
+ updatedAt: yield* DateTime.now,
8331
+ };
8332
+ yield* emitProviderEvent({ type: "provider_session.updated", driver, providerSession });
8333
+ });
8334
+ lateSessionSetup.openSessionConfigured = true;
8335
+ const pendingLateSessionSetup = lateSessionSetup.pending;
8336
+ lateSessionSetup.pending = null;
8337
+ if (pendingLateSessionSetup !== null) {
8338
+ yield* pendingLateSessionSetup;
8339
+ }
8340
8341
const providerTurnPayload = (
8342
context: ActiveAcpTurn,
@@ -9582,7 +9687,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9687
instanceId: options.instanceId,
9688
driver,
9689
providerSessionId: input.providerSessionId,
9585
- providerSession,
9690
+ get providerSession() {
9691
+ return providerSession;
9692
+ },
9693
canResumeAfterRestart: canLoadSession || canResumeSession,
9694
events: Stream.fromEffectRepeat(Queue.take(events)),
9695
...(flavor.getModelContextWindow === undefined