diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 54c1137870e73..71a0a1db59131 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -2959,10 +2959,161 @@ describe("AcpAdapterV2", () => { (error as ProviderAdapter.ProviderAdapterTurnStartError).cause, ProviderAdapter.ProviderCompactionUnsupportedError, ); + assert.isTrue( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + ); } }).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; 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/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-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index c4b90adc0c3d1..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, @@ -10056,6 +10069,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. + ...(refusedWithSessionIntact(cause) ? { refusedBeforePrompt: true } : {}), }), ), ), 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 } }); +const watcher = watch(dirname(onlineFlag), (_event, name) => { + if (name !== basename(onlineFlag) || !existsSync(onlineFlag)) return; + watcher.close(); + update({ sessionUpdate: "config_option_update", configOptions: [modelOption(true)] }); +}); +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, browser }) => { + 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)); + // 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) => + 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; + }; + 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]; + + // 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 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(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)}`); + } + + 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); + } + }, +);