From cbc25af0d23c019afc5286938f44e23a5f65de97 Mon Sep 17 00:00:00 2001 From: srkrnmgda Date: Mon, 23 Nov 2026 14:48:53 -0500 Subject: [PATCH 1/7] test: failing tests for a refused ACP start leaving its history handoff pending An ACP agent refuses a turn before its prompt is sent, for example when it does not accept the model. The history handoff the refused start staged stays pending, and the next start treats that as an uncertain delivery and replaces the intact native session with a fresh one and a summary. The scenario drives the real app with a local ACP agent that stops offering the thread's model after its first reply, refuses two messages, then offers it again: the fourth message must reach the same native session. --- .../Adapters/AcpAdapterV2.test.ts | 3 + .../ProviderSwitch.integration.test.ts | 12 ++ .../src/server/ProviderAdapter.ts | 2 + ...-refused-model-keeps-native-session.e2e.ts | 164 ++++++++++++++++++ 4 files changed, 181 insertions(+) create mode 100644 scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 54c1137870e73..c9ecade07108b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -2959,6 +2959,9 @@ describe("AcpAdapterV2", () => { (error as ProviderAdapter.ProviderAdapterTurnStartError).cause, ProviderAdapter.ProviderCompactionUnsupportedError, ); + assert.isTrue( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + ); } }).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 811279357d917..5ebd017a8399b 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -19,6 +19,7 @@ import { ProviderSessionId, ProviderThreadId, ProviderTurnId, + RunId, ScheduledTaskId, ThreadId, TurnItemId, @@ -2794,6 +2795,17 @@ describe("orchestration v2 provider switching", () => { detail: "Claude provider query ended before the turn could start.", }), ], + // ACP rejects a model it cannot select before sending the prompt. + [ + "an ACP start that rejected the model", + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: GROK_DRIVER, + threadId, + providerThreadId: ProviderThreadId.make("provider-thread:acp-refused-start"), + runId: RunId.make("run:acp-refused-start"), + refusedBeforePrompt: true, + }), + ], // Injected history is text only, so a refusal after injection must not settle the image. [ "background work after native history injection", diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 015a68f48982b..5cefa6da97fab 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -406,6 +406,8 @@ export class ProviderAdapterTurnStartError extends Schema.TaggedError ({ + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: online ? "model-a" : "model-b", + options: online + ? [{ value: "model-a", name: "Model A" }, { value: "model-b", name: "Model B" }] + : [{ value: "model-b", name: "Model B" }], +}); +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +const respond = (id, result) => send({ id, result }); +const update = (update) => send({ method: "session/update", params: { sessionId, update } }); +setInterval(() => { + if (restored || prompts === 0 || !existsSync(onlineFlag)) return; + restored = true; + update({ sessionUpdate: "config_option_update", configOptions: [modelOption(true)] }); + writeFileSync(onlineFlag + ".ack", sessionId); +}, 100); +for await (const line of createInterface({ input: process.stdin })) { + const { id, method } = JSON.parse(line); + if (id === undefined) continue; + if (method === "initialize") { + respond(id, { protocolVersion: 1, agentInfo: { name: "refusing-agent", version: "1.0.0" }, agentCapabilities: {}, authMethods: [] }); + } else if (method === "session/new") { + respond(id, { sessionId, configOptions: [modelOption(true)] }); + } else if (method === "session/set_config_option") { + respond(id, { configOptions: [modelOption(true)] }); + } else if (method === "session/prompt") { + prompts += 1; + update({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: sessionId + " answered prompt " + prompts }, + }); + // The first reply ends with the agent no longer offering the thread's model. + if (prompts === 1) update({ sessionUpdate: "config_option_update", configOptions: [modelOption(false)] }); + respond(id, { stopReason: "end_turn" }); + } else { + send({ id, error: { code: -32601, message: "Method not found" } }); + } +} +`; + +test( + "An ACP agent that refuses the model keeps its native session for the next message", + WEB, + async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + const script = NodePath.join(project, "refusing-acp.mjs"); + const onlineFlag = NodePath.join(project, "online.flag"); + const settingsPath = NodePath.join(T3_HOME, "userdata/settings.json"); + const originalSettings = await NodeFSP.readFile(settingsPath, "utf8"); + const settings = JSON.parse(originalSettings); + await NodeFSP.writeFile(script, ACP); + settings.providerInstances["refusing-agent"] = { + driver: "acpRegistry", + displayName: "Refusing Agent", + enabled: true, + config: { source: "local", commandPath: process.execPath, commandArgs: [script, onlineFlag] }, + }; + try { + await NodeFSP.writeFile(settingsPath, JSON.stringify(settings)); + const { cli } = makeState(T3_HOME); + type Run = { threadId: string; status: string; reply: string | null; error: string | null }; + const refusedModel = (run: Run) => + run.status === "failed" && (run.error ?? "").includes('did not accept the model "model-a"'); + const send = async (threadId: string, text: string): Promise => { + const sent = await runPromise( + cli(["thread", "send", threadId, text, "--wait", "--json"], [0, 1]), + ); + return JSON.parse(sent.stdout) as Run; + }; + // The watcher reloads settings asynchronously. Retry only before a thread was created. + let first: Run | undefined; + for (let attempt = 0; attempt < 8 && first === undefined; attempt++) { + const started = await runPromise( + cli( + [ + "thread", + "start", + project, + "First request", + "--title", + "Refused model", + "--provider", + "refusing-agent", + "--model", + "model-a", + "--wait", + "--json", + ], + [0, 1], + ), + ); + if (!started.stdout.includes("threadId")) continue; + first = JSON.parse(started.stdout) as Run; + } + if (first?.status !== "completed" || first.reply === null) { + throw new Error(`The first turn did not complete: ${JSON.stringify(first)}`); + } + const session = first.reply.split(" ")[0]; + + // Two messages while the agent no longer offers the model: both are refused before a prompt. + for (const text of ["Second request", "Third request"]) { + const refused = await send(first.threadId, text); + if (!refusedModel(refused)) { + throw new Error(`The agent was expected to refuse the model: ${JSON.stringify(refused)}`); + } + } + + // The agent offers the model again, and the next message is sent. + await NodeFSP.writeFile(onlineFlag, "online"); + let restored = false; + for (let wait = 0; wait < 100 && !restored; wait++) { + restored = (await NodeFSP.readFile(`${onlineFlag}.ack`, "utf8").catch(() => "")) !== ""; + if (!restored) await new Promise((resolve) => setTimeout(resolve, 100)); + } + if (!restored) throw new Error("The agent did not offer the model again."); + // The app applies the agent's update on its own schedule, so a send can still meet the old + // model list. Retrying cannot hide the bug: without the fix the pending handoff replaces the + // session before the model is checked, and with it a refused send leaves the session in place. + let last = await send(first.threadId, "Fourth request"); + for (let attempt = 0; attempt < 5 && refusedModel(last); attempt++) { + await new Promise((resolve) => setTimeout(resolve, 500)); + last = await send(first.threadId, "Fourth request"); + } + if (last.status !== "completed") { + throw new Error(`The fourth request did not complete: ${JSON.stringify(last)}`); + } + + await t3.open({ threadId: first.threadId }); + const reply = screen.getByText(/answered prompt/).last(); + await reply.waitFor({ timeout: 60_000 }); + try { + // The refused messages never reached the agent, so the same session answers its second prompt. + await expect(reply).toHaveText(`${session} answered prompt 2`); + } finally { + await app.screenshot("reply-after-refused-model"); + } + } finally { + await NodeFSP.writeFile(settingsPath, originalSettings); + } + }, +); From 6c0437d473618735091c5ead7b151f1b5b4dba5f Mon Sep 17 00:00:00 2001 From: srkrnmgda Date: Mon, 23 Nov 2026 14:53:05 -0500 Subject: [PATCH 2/7] fix(acp): a refused model no longer abandons the native session The ACP adapter refuses a turn before its prompt is sent, yet the turn start service only recognised Claude's pre-prompt refusals. The history handoff the refused start staged stayed pending, and the start after it treated that as an uncertain delivery: it replaced the intact native session with a fresh one and a summary that kept a few items of the conversation. ACP turn start failures now say the agent received nothing, so the handoff is restored and the next start reuses the native session. --- apps/server/src/orchestration-v2/ProviderTurnStartService.ts | 2 ++ packages/provider-acp/src/server/adapter.ts | 3 +++ 2 files changed, 5 insertions(+) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 1cb77e387f950..8817a117634e2 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -140,6 +140,7 @@ export function abandonedProviderTurns( export const isProviderTurnStartError = Schema.is(ProviderTurnStartError); const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError); +const isProviderAdapterTurnStartError = Schema.is(ProviderAdapter.ProviderAdapterTurnStartError); const isProviderAdapterOpenSessionError = Schema.is( ProviderAdapter.ProviderAdapterOpenSessionError, ); @@ -160,6 +161,7 @@ const PROMPT_REFUSAL_TAGS = [ const refusedBeforePrompt = (error: unknown): boolean => PROMPT_REFUSAL_TAGS.some((tag) => Predicate.isTagged(error, tag)) || + (isProviderAdapterTurnStartError(error) && error.refusedBeforePrompt === true) || (isProviderAdapterProtocolError(error) && error.driver === CLAUDE_PROVIDER && error.detail === CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL) || diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index c4b90adc0c3d1..1200f0a0265a2 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -10056,6 +10056,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( providerThreadId: turnInput.providerThread.id, runId: turnInput.runId, cause, + // The prompt is sent from a forked fiber, and its failures settle the turn + // instead of reaching here, so no prompt was sent when this fails. + refusedBeforePrompt: true, }), ), ), From 82b7d03dc4ae05e455ce0c566052d04f172c6bae Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 20:43:23 +0000 Subject: [PATCH 3/7] test(scenarios): wait with expect.poll and Effect.sleep in the refused-model scenario The scenario's setTimeout waits failed the globalTimers typecheck rule. Co-Authored-By: Claude Opus 5.5 --- .../acp-refused-model-keeps-native-session.e2e.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts b/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts index daaeeb4f23be8..3f601cceb0577 100644 --- a/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts +++ b/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts @@ -3,6 +3,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import { expect } from "e2e"; +import * as Effect from "effect/Effect"; import { T3_HOME } from "../e2e.config.ts"; import { makeState, runPromise, test, WEB } from "./t3.ts"; @@ -130,18 +131,17 @@ test( // The agent offers the model again, and the next message is sent. await NodeFSP.writeFile(onlineFlag, "online"); - let restored = false; - for (let wait = 0; wait < 100 && !restored; wait++) { - restored = (await NodeFSP.readFile(`${onlineFlag}.ack`, "utf8").catch(() => "")) !== ""; - if (!restored) await new Promise((resolve) => setTimeout(resolve, 100)); - } - if (!restored) throw new Error("The agent did not offer the model again."); + await expect + .poll(() => NodeFSP.readFile(`${onlineFlag}.ack`, "utf8").catch(() => ""), { + timeout: 10_000, + }) + .not.toBe(""); // The app applies the agent's update on its own schedule, so a send can still meet the old // model list. Retrying cannot hide the bug: without the fix the pending handoff replaces the // session before the model is checked, and with it a refused send leaves the session in place. let last = await send(first.threadId, "Fourth request"); for (let attempt = 0; attempt < 5 && refusedModel(last); attempt++) { - await new Promise((resolve) => setTimeout(resolve, 500)); + await runPromise(Effect.sleep("500 millis")); last = await send(first.threadId, "Fourth request"); } if (last.status !== "completed") { From 07ce7b35efd797a221efc9e2190fb609e25badb7 Mon Sep 17 00:00:00 2001 From: srkrnmgda Date: Mon, 23 Nov 2026 15:42:08 -0500 Subject: [PATCH 4/7] test(acp): failing tests for unusable-session failures counted as refused before the prompt A turn start that cannot reopen its session, or whose session setup fails for a reason other than a refused model, may be on a session the agent lost. Flagging it as refused before the prompt restores its staged handoff, so the server never falls back to a fresh session and every later start retries the same session. --- .../Adapters/AcpAdapterV2.test.ts | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index c9ecade07108b..71a0a1db59131 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -2966,6 +2966,154 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + // A start that cannot reopen its session may be on a session the agent lost. It is not a refusal + // before the prompt, so the server's recovery for an unusable session still runs. + it.live("does not mark a start whose session failed to reopen as refused before its prompt", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make("acp-test-reopen-failure"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + environment: () => ({ T3_ACP_FAIL_LOAD_SESSION: "1" }), + }), + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-reopen-failure"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-reopen-failure"), + modelSelection, + runtimePolicy, + }); + const thread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); + const lostThread: OrchestrationV2ProviderThread = { + ...thread, + nativeThreadRef: { driver: ACP_TEST_DRIVER, nativeId: "lost-session", strength: "strong" }, + }; + const now = yield* DateTime.now; + const error = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread: lostThread, + instanceId, + runtimePolicy, + now, + ordinal: 1, + }), + ) + .pipe(Effect.flip); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError); + assert.notEqual( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + true, + ); + const methods = yield* pollProtocolMethods(protocolEvents); + assert.isTrue(methods.includes("session/load") || methods.includes("session/resume")); + assert.notInclude(methods, "session/prompt"); + }).pipe(Effect.provide(layerTest)), + ); + + // Only refusals that leave the session usable mark a start as refused before its prompt. A setup + // step other than the model can fail because the session is gone. + it.live("does not mark a start whose session setup failed as refused before its prompt", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make("acp-test-setup-failure"); + const threadId = ThreadId.make("thread-acp-setup-failure"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + environment: { T3_ACP_FAIL_SET_MODE_CONFIG_OPTION: "1" }, + }), + }, + selfInvocation: yield* resolveSelfInvocation(), + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const opened = { instanceId, model: "composer-2" } as const; + const withMode = { + instanceId, + model: "composer-2", + options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: "code" }], + } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-setup-failure"), + modelSelection: opened, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: opened, + runtimePolicy, + }); + const now = yield* DateTime.now; + const error = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal: 1, + modelSelection: withMode, + }), + ) + .pipe(Effect.flip); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError); + assert.notInstanceOf( + (error as ProviderAdapter.ProviderAdapterTurnStartError).cause, + ProviderAdapter.ProviderCompactionUnsupportedError, + ); + assert.notEqual( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + true, + ); + // The start reached the mode step the agent rejected, and sent no prompt. + const outgoing = Array.from(yield* Queue.takeAll(protocolEvents)).filter( + (event) => event.direction === "outgoing", + ); + assert.isTrue( + outgoing.some( + (event) => + rawProtocolMethod(event) === "session/set_config_option" && + rawProtocolRequestParam(event, "configId") === "mode", + ), + ); + assert.notInclude(outgoing.map(rawProtocolMethod), "session/prompt"); + }).pipe(Effect.provide(layerTest)), + ); + it.live("reapplies a selection after a switch away from it failed partway", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; From 21e7f937f7efe5c507bcbbad849442dce87fc778 Mon Sep 17 00:00:00 2001 From: srkrnmgda Date: Mon, 23 Nov 2026 15:57:14 -0500 Subject: [PATCH 5/7] fix(acp): flag only refusals that leave the session usable as refused before the prompt Every ACP turn start failure was marked refusedBeforePrompt, including a session that could not be reopened, a setup step that failed, and a failed runtime teardown. Those can mean the agent lost the session, and restoring the staged handoff for them removed the server's fallback to a fresh session, so every later start retried the same unusable session. Only a refused model and an unsupported compaction, which leave the session intact, carry the flag now. Every other start failure behaves as before. --- packages/provider-acp/src/server/adapter.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 1200f0a0265a2..b2289f454ad88 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -337,6 +337,19 @@ class AcpModelSelectionError extends Schema.TaggedError( } } +const isAcpModelSelectionError = Schema.is(AcpModelSelectionError); +const isProviderCompactionUnsupportedError = Schema.is( + ProviderAdapter.ProviderCompactionUnsupportedError, +); + +/** + * Turn-start refusals that leave the session usable. Other start failures, such as a session that + * cannot be reopened or a setup step that fails, can mean the agent lost the session, so the + * server keeps its recovery for them. + */ +const refusedWithSessionIntact = (cause: unknown) => + isAcpModelSelectionError(cause) || isProviderCompactionUnsupportedError(cause); + /** A prompt-steered turn spans several prompts, each reporting its own usage. */ function addAcpUsage( total: EffectAcpSchema.Usage | undefined, @@ -10058,7 +10071,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( cause, // The prompt is sent from a forked fiber, and its failures settle the turn // instead of reaching here, so no prompt was sent when this fails. - refusedBeforePrompt: true, + ...(refusedWithSessionIntact(cause) ? { refusedBeforePrompt: true } : {}), }), ), ), From 6b3da240bc69d4f5e6097f61a57404d223720a19 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 22:15:33 +0000 Subject: [PATCH 6/7] test(scenarios): send the recovery message once the app shows the restored model The scenario resent the fourth message on a sleep loop until the agent's restored model list reached the server, which the testing guide forbids. It now waits for the composer to name the model, which happens only after the server has the updated list, and sends once. The fake agent watches for its flag file instead of polling for it. Co-Authored-By: Claude Opus 5.5 --- ...-refused-model-keeps-native-session.e2e.ts | 37 +++++++------------ 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts b/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts index 3f601cceb0577..4e030e7994c8c 100644 --- a/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts +++ b/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts @@ -3,7 +3,6 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import { expect } from "e2e"; -import * as Effect from "effect/Effect"; import { T3_HOME } from "../e2e.config.ts"; import { makeState, runPromise, test, WEB } from "./t3.ts"; @@ -12,13 +11,13 @@ import { makeState, runPromise, test, WEB } from "./t3.ts"; // network can, and offers it again once the scenario creates the online flag. Each agent process // names its own session, so a reply says which native session answered it. const ACP = ` -import { existsSync, writeFileSync } from "node:fs"; +import { existsSync, watch } from "node:fs"; +import { basename, dirname } from "node:path"; import { createInterface } from "node:readline"; const onlineFlag = process.argv[2]; const sessionId = "session-" + process.pid; let prompts = 0; -let restored = false; const modelOption = (online) => ({ id: "model", name: "Model", @@ -32,12 +31,11 @@ const modelOption = (online) => ({ const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); const respond = (id, result) => send({ id, result }); const update = (update) => send({ method: "session/update", params: { sessionId, update } }); -setInterval(() => { - if (restored || prompts === 0 || !existsSync(onlineFlag)) return; - restored = true; +const watcher = watch(dirname(onlineFlag), (_event, name) => { + if (name !== basename(onlineFlag) || !existsSync(onlineFlag)) return; + watcher.close(); update({ sessionUpdate: "config_option_update", configOptions: [modelOption(true)] }); - writeFileSync(onlineFlag + ".ack", sessionId); -}, 100); +}); for await (const line of createInterface({ input: process.stdin })) { const { id, method } = JSON.parse(line); if (id === undefined) continue; @@ -65,7 +63,7 @@ for await (const line of createInterface({ input: process.stdin })) { test( "An ACP agent that refuses the model keeps its native session for the next message", WEB, - async ({ t3, app, screen }) => { + async ({ t3, app, screen, browser }) => { const project = await t3.project("demo"); const script = NodePath.join(project, "refusing-acp.mjs"); const onlineFlag = NodePath.join(project, "online.flag"); @@ -129,26 +127,17 @@ test( } } - // The agent offers the model again, and the next message is sent. + // The composer names the model only once the server has the agent's model list offering it, + // which the server publishes after updating the list the next turn start checks. + await t3.open({ threadId: first.threadId }); + const modelLabel = browser.locator("[data-chat-provider-model-picker-label]").first(); await NodeFSP.writeFile(onlineFlag, "online"); - await expect - .poll(() => NodeFSP.readFile(`${onlineFlag}.ack`, "utf8").catch(() => ""), { - timeout: 10_000, - }) - .not.toBe(""); - // The app applies the agent's update on its own schedule, so a send can still meet the old - // model list. Retrying cannot hide the bug: without the fix the pending handoff replaces the - // session before the model is checked, and with it a refused send leaves the session in place. - let last = await send(first.threadId, "Fourth request"); - for (let attempt = 0; attempt < 5 && refusedModel(last); attempt++) { - await runPromise(Effect.sleep("500 millis")); - last = await send(first.threadId, "Fourth request"); - } + await expect(modelLabel).toHaveText("Model A", { timeout: 30_000 }); + const last = await send(first.threadId, "Fourth request"); if (last.status !== "completed") { throw new Error(`The fourth request did not complete: ${JSON.stringify(last)}`); } - await t3.open({ threadId: first.threadId }); const reply = screen.getByText(/answered prompt/).last(); await reply.waitFor({ timeout: 60_000 }); try { From dd0b63a96a4131638b1b94a3e2476f414bf94b56 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:27:00 +0000 Subject: [PATCH 7/7] test(scenarios): start the refused-model thread once the server lists the agent The scenario retried thread start up to eight times while the settings watcher registered the agent, which the testing guide forbids. It now waits on the server config stream for the first provider list that includes the agent, then starts the thread once. Co-Authored-By: Claude Opus 5.5 --- ...-refused-model-keeps-native-session.e2e.ts | 68 +++++++++++-------- 1 file changed, 41 insertions(+), 27 deletions(-) diff --git a/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts b/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts index 4e030e7994c8c..37cfd80dbc8a4 100644 --- a/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts +++ b/scripts/scenarios/acp-refused-model-keeps-native-session.e2e.ts @@ -3,9 +3,11 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; import { T3_HOME } from "../e2e.config.ts"; -import { makeState, runPromise, test, WEB } from "./t3.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; // The agent drops "model-a" from its model list after its first reply, as an agent that lost its // network can, and offers it again once the scenario creates the online flag. Each agent process @@ -79,6 +81,23 @@ test( }; try { await NodeFSP.writeFile(settingsPath, JSON.stringify(settings)); + // The settings watcher registers the agent asynchronously; start once the server lists it. + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, app.baseUrl ?? ""); + yield* client.subscribeServerConfig({}).pipe( + Stream.filter((event) => + (event.type === "snapshot" + ? event.config.providers + : event.type === "providerStatuses" + ? event.payload.providers + : [] + ).some((provider) => provider.instanceId === "refusing-agent"), + ), + Stream.runHead, + ); + }).pipe(Effect.scoped), + ); const { cli } = makeState(T3_HOME); type Run = { threadId: string; status: string; reply: string | null; error: string | null }; const refusedModel = (run: Run) => @@ -89,32 +108,27 @@ test( ); return JSON.parse(sent.stdout) as Run; }; - // The watcher reloads settings asynchronously. Retry only before a thread was created. - let first: Run | undefined; - for (let attempt = 0; attempt < 8 && first === undefined; attempt++) { - const started = await runPromise( - cli( - [ - "thread", - "start", - project, - "First request", - "--title", - "Refused model", - "--provider", - "refusing-agent", - "--model", - "model-a", - "--wait", - "--json", - ], - [0, 1], - ), - ); - if (!started.stdout.includes("threadId")) continue; - first = JSON.parse(started.stdout) as Run; - } - if (first?.status !== "completed" || first.reply === null) { + const started = await runPromise( + cli( + [ + "thread", + "start", + project, + "First request", + "--title", + "Refused model", + "--provider", + "refusing-agent", + "--model", + "model-a", + "--wait", + "--json", + ], + [0, 1], + ), + ); + const first = JSON.parse(started.stdout) as Run; + if (first.status !== "completed" || first.reply === null) { throw new Error(`The first turn did not complete: ${JSON.stringify(first)}`); } const session = first.reply.split(" ")[0];