diff --git a/packages/cli/src/acp/agent.ts b/packages/cli/src/acp/agent.ts index 454b6705cfa..911b49bddab 100644 --- a/packages/cli/src/acp/agent.ts +++ b/packages/cli/src/acp/agent.ts @@ -6,6 +6,7 @@ import { type AgentNotificationMethod, type AgentRequestHandlersByMethod, type AgentRequestMethod, + type JsonRpcId, type Stream, } from "@agentclientprotocol/sdk" import type { OpenCodeClient } from "@opencode/client/promise" @@ -40,7 +41,12 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre Effect.tapCauseIf(Cause.hasDies, (cause) => Effect.logError("ACP request failed", cause)), Effect.catchDefect((defect) => Effect.fail(ACPError.toRequestError(ACPError.fromUnknown(defect)))), ) - return (ctx: AgentHandlerContext) => run(handler(ctx)) + return (ctx: AgentHandlerContext & { readonly requestId?: JsonRpcId }) => { + if (ctx.requestId === undefined) return run(handler(ctx)) + return run( + handler(ctx).pipe(Effect.provideService(ACPConnection.Responded, acp.connection.responded(ctx.requestId))), + ) + } } const app = agent({ name: "opencode" }) const request = ( @@ -106,13 +112,13 @@ export const connect = Effect.fnUntraced(function* (client: OpenCodeClient, stre "session/cancel", handle((service, ctx) => service.cancel(ctx.params)), ) - const agentConnection = app.connect(stream) - const connection = ACPConnection.make(agentConnection) + const acp = ACPConnection.make(app, stream) + const connection = acp.connection const sessions = yield* ACPSessions.make({ client, connection, catalog }) const capabilities = yield* Ref.make({ childSessionUpdates: false }) const turn = yield* ACPTurn.make({ client, connection, sessions, catalog, capabilities }) yield* Deferred.succeed(ready, ACPService.make({ client, connection, catalog, sessions, capabilities, turn })) - return agentConnection + return acp.agent }) const spanName = (method: string) => `cli.acp.${method.replaceAll("/", ".")}` diff --git a/packages/cli/src/acp/connection.ts b/packages/cli/src/acp/connection.ts index 5cb181695e4..f53e54b5469 100644 --- a/packages/cli/src/acp/connection.ts +++ b/packages/cli/src/acp/connection.ts @@ -1,15 +1,26 @@ import { methods, - type AgentConnection, + type AgentApp, + type AnyMessage, + type JsonRpcId, type RequestError, type RequestPermissionRequest, type RequestPermissionResponse, type SessionNotification, + type Stream, } from "@agentclientprotocol/sdk" -import { Context, type Effect } from "effect" +import { Context, Deferred, Effect } from "effect" import type { ACPError } from "./error" import { ACPPromise } from "./promise" +/** + * Completes once the response to the request being handled is written, so messages sent afterwards follow it. + * Interrupts when the request fails. Outside a request it completes immediately. + */ +export const Responded = Context.Reference>("@opencode/cli/acp/Connection/Responded", { + defaultValue: () => Effect.void, +}) + export interface Interface { readonly sessionUpdate: (params: SessionNotification) => Effect.Effect /** Interruption cancels the client's request. */ @@ -20,20 +31,47 @@ export interface Interface { method: string, params: Record, ) => Effect.Effect + /** Tracks an incoming request from now on and returns its `Responded`. */ + readonly responded: (requestId: JsonRpcId) => Effect.Effect } export class Service extends Context.Service()("@opencode/cli/acp/Connection") {} -export function make(connection: AgentConnection) { - return Service.of({ - sessionUpdate: (params) => - ACPPromise.promise(() => connection.client.notify(methods.client.session.update, params)), - requestPermission: (params) => - ACPPromise.promise((signal) => - connection.client.request(methods.client.session.requestPermission, params, { cancellationSignal: signal }), - ), - extNotification: (method, params) => ACPPromise.promise(() => connection.client.notify(method, params)), +export function make(app: AgentApp, stream: Stream) { + // Settled as each response is written to the stream, which serializes every outgoing message. + const responses = new Map>() + const writer = stream.writable.getWriter() + const agent = app.connect({ + readable: stream.readable, + writable: new WritableStream({ + write: async (message) => { + await writer.write(message) + if ("method" in message) return + const responded = responses.get(message.id) + if (!responded) return + responses.delete(message.id) + Deferred.doneUnsafe(responded, "result" in message ? Effect.void : Effect.interrupt) + }, + close: () => writer.close(), + abort: (reason) => writer.abort(reason), + }), }) + return { + agent, + connection: Service.of({ + sessionUpdate: (params) => ACPPromise.promise(() => agent.client.notify(methods.client.session.update, params)), + requestPermission: (params) => + ACPPromise.promise((signal) => + agent.client.request(methods.client.session.requestPermission, params, { cancellationSignal: signal }), + ), + extNotification: (method, params) => ACPPromise.promise(() => agent.client.notify(method, params)), + responded: (requestId) => { + const responded = Deferred.makeUnsafe() + responses.set(requestId, responded) + return Deferred.await(responded) + }, + }), + } } export * as ACPConnection from "./connection" diff --git a/packages/cli/src/acp/service.ts b/packages/cli/src/acp/service.ts index 9e5ee50e9fb..b985b2092a3 100644 --- a/packages/cli/src/acp/service.ts +++ b/packages/cli/src/acp/service.ts @@ -191,8 +191,11 @@ export function make(input: { loadSession: Effect.fnUntraced(function* (params) { const session = yield* getSession(params.sessionId, params.cwd) const attached = yield* input.sessions.attach(session, session.location.directory, params.mcpServers) - yield* replay(attached) - return { configOptions: yield* currentOptions(attached) } + return yield* replay(attached).pipe( + Effect.andThen(currentOptions(attached)), + Effect.map((configOptions) => ({ configOptions })), + Effect.onError(() => input.sessions.detach(attached.id)), + ) }), listSessions: Effect.fnUntraced(function* (params) { const page = yield* ACPPromise.promise(() => @@ -237,8 +240,10 @@ export function make(input: { forkSession: Effect.fnUntraced(function* (params) { const forked = yield* ACPPromise.promise(() => input.client.session.fork({ sessionID: params.sessionId })) const attached = yield* input.sessions.attach(forked, forked.location.directory, params.mcpServers ?? []) - yield* replay(attached) - return { sessionId: attached.id, configOptions: yield* currentOptions(attached) } + return yield* currentOptions(attached).pipe( + Effect.map((configOptions) => ({ sessionId: attached.id, configOptions })), + Effect.onError(() => input.sessions.detach(attached.id)), + ) }), setSessionConfigOption: Effect.fnUntraced(function* (params) { const attached = yield* input.sessions.require(params.sessionId) diff --git a/packages/cli/src/acp/sessions.ts b/packages/cli/src/acp/sessions.ts index fdc1455c8c5..521975e66e9 100644 --- a/packages/cli/src/acp/sessions.ts +++ b/packages/cli/src/acp/sessions.ts @@ -4,7 +4,7 @@ import type { OpenCodeClient, OpenCodeEvent, SessionInfo } from "@opencode/clien import { Context, Deferred, Effect, Exit, Queue, Ref, Scope, Stream } from "effect" import type { ACPCatalog, Catalog } from "./catalog" import { availableCommands, configOptions, type Selection } from "./config-option" -import type { ACPConnection } from "./connection" +import { ACPConnection } from "./connection" import { ACPError } from "./error" import { ACPPromise } from "./promise" @@ -16,9 +16,9 @@ export type Attached = { export interface Interface { /** - * Attaches a session in its own scope, closing any previous attachment of the same ID. The scope follows the - * cwd's catalog and pushes config option and command updates while it is open. A failed attach leaves the - * session detached. + * Attaches a session in its own scope, closing any previous attachment of the same ID. Once the attaching request + * has responded, the scope follows the cwd's catalog and pushes config option and command updates while it is + * open. A failed attach leaves the session detached. */ readonly attach: ( session: SessionInfo, @@ -141,26 +141,27 @@ export const make = Effect.fnUntraced(function* (input: { const replaced = sessions.get(session.id) sessions.set(session.id, entry) if (replaced) yield* Scope.close(replaced.scope, Exit.void) - yield* registerMcp(entry.attached, mcpServers).pipe( - Effect.andThen(sendCommands(session.id, current)), - Effect.onError(() => remove(session.id, entry)), - ) - // `changes` emits the latest catalog first, so a reload since `current` is still pushed. One fold applies - // catalog and selection changes so pushes leave the client on the latest pair. - yield* Stream.merge( - input.catalog.changes(cwd).pipe(Stream.map((catalog) => ({ catalog, patch: {} }))), - Stream.fromQueue(entry.selected).pipe(Stream.map((patch) => ({ catalog: undefined, patch }))), - ).pipe( - Stream.runFoldEffect( - () => current, - (previous, step) => { - const next = step.catalog ?? previous - return changed(entry.attached, previous, next, step.patch).pipe(Effect.ignore, Effect.as(next)) - }, - ), - Effect.ignore, - Effect.forkIn(entry.scope), - ) + yield* registerMcp(entry.attached, mcpServers).pipe(Effect.onError(() => remove(session.id, entry))) + const responded = yield* ACPConnection.Responded + // Updates wait for the response that hands the client this session. `changes` emits the latest catalog + // first, so a reload since `current` is still pushed. One fold applies catalog and selection changes so + // pushes leave the client on the latest pair. + yield* Effect.gen(function* () { + yield* responded + yield* sendCommands(session.id, current) + yield* Stream.merge( + input.catalog.changes(cwd).pipe(Stream.map((catalog) => ({ catalog, patch: {} }))), + Stream.fromQueue(entry.selected).pipe(Stream.map((patch) => ({ catalog: undefined, patch }))), + ).pipe( + Stream.runFoldEffect( + () => current, + (previous, step) => { + const next = step.catalog ?? previous + return changed(entry.attached, previous, next, step.patch).pipe(Effect.ignore, Effect.as(next)) + }, + ), + ) + }).pipe(Effect.ignore, Effect.forkIn(entry.scope)) return entry.attached }), detach: Effect.fn("cli.acp.sessions.detach")(function* (sessionID) { diff --git a/packages/cli/test/acp/catalog.test.ts b/packages/cli/test/acp/catalog.test.ts index 8d2530bd8dd..fcb202b0226 100644 --- a/packages/cli/test/acp/catalog.test.ts +++ b/packages/cli/test/acp/catalog.test.ts @@ -145,6 +145,7 @@ describe("acp catalog and config options over the wire", () => { const closed = await acp.newSession() const open = await acp.newSession() await acp.request("session/close", { sessionId: closed.sessionId }) + await initialCommands(acp, open.sessionId, 1) return open.sessionId }, ], @@ -157,6 +158,7 @@ describe("acp catalog and config options over the wire", () => { const params = { cwd: "/workspace", sessionId: session.sessionId, mcpServers: [] } await acp.request(method, params) await acp.request(method, params) + await initialCommands(acp, session.sessionId, 3) return session.sessionId }, ] as const, @@ -301,6 +303,14 @@ async function change(acp: Wire, sessionId: string, kind: string, trigger: () => ) } +// Each attach sends its commands after the response, so later counts start once every attach has sent them. +function initialCommands(acp: Wire, sessionId: string, attaches: number) { + return acp.until( + () => acp.updates.filter((item) => item.sessionId === sessionId && commandNames(item)).length === attaches, + "initial commands", + ) +} + function updateKinds(acp: Wire, since: number) { return acp.updates.slice(since).map((item) => [item.sessionId, item.update.sessionUpdate]) } diff --git a/packages/cli/test/acp/session.test.ts b/packages/cli/test/acp/session.test.ts index 81a0b1506e7..3f3aa30ed4f 100644 --- a/packages/cli/test/acp/session.test.ts +++ b/packages/cli/test/acp/session.test.ts @@ -1,7 +1,17 @@ import { describe, expect, test } from "bun:test" -import type { McpServer } from "@agentclientprotocol/sdk" +import type { McpServer, SessionNotification } from "@agentclientprotocol/sdk" +import { Schema } from "effect" import { currentValue } from "./select-options" -import { ephemeralEvent, makeSession, rpcError, secondModel, startSession, startWire, testModel } from "./wire-fixture" +import { + ephemeralEvent, + makeSession, + rpcError, + secondModel, + startSession, + startWire, + testModel, + type Wire, +} from "./wire-fixture" describe("acp session lifecycle over the wire", () => { test("initialize advertises capabilities and terminal auth only when the client asks", async () => { @@ -76,7 +86,7 @@ describe("acp session lifecycle over the wire", () => { expect(acp.server.selections).toEqual([]) }) - test("loads and forks with paginated replay while resume does not replay", async () => { + test("loads with paginated replay while resume and fork do not replay", async () => { await using acp = await startWire() const history = Array.from({ length: 201 }, (_, index) => ({ id: `msg_${index}`, @@ -122,7 +132,7 @@ describe("acp session lifecycle over the wire", () => { : [], ) expect(replayed("ses_loaded")).toEqual(history.map((message) => message.id)) - expect(replayed(forked.sessionId)).toEqual(history.map((message) => message.id)) + expect(replayed(forked.sessionId)).toEqual([]) expect(replayed("ses_resume")).toEqual([]) expect( acp.updates.find((item) => item.sessionId === "ses_loaded" && item.update.sessionUpdate === "user_message_chunk") @@ -134,6 +144,67 @@ describe("acp session lifecycle over the wire", () => { }) }) + test("publishes a session's commands after the response that attaches it", async () => { + await using acp = await startWire() + acp.server.sessions.set("ses_loaded", makeSession("ses_loaded")) + acp.server.messages.set("ses_loaded", [{ id: "msg_0", type: "user", text: "hello", time: { created: 0 } }]) + await acp.initialize() + const params = { cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] } + + expect(await untilCommands(acp, () => acp.newSession())).toEqual(["response", "available_commands_update"]) + expect(await untilCommands(acp, () => acp.request("session/load", params))).toEqual([ + "user_message_chunk", + "response", + "available_commands_update", + ]) + expect(await untilCommands(acp, () => acp.request("session/resume", params))).toEqual([ + "response", + "available_commands_update", + ]) + expect(await untilCommands(acp, () => acp.request("session/fork", params))).toEqual([ + "response", + "available_commands_update", + ]) + }) + + test("does not publish commands for a session closed before its load responds", async () => { + const held = Promise.withResolvers() + await using acp = await startWire({ + fetch: (request) => (request.path === "/api/session/ses_loaded/message" ? held.promise : undefined), + }) + acp.server.sessions.set("ses_loaded", makeSession("ses_loaded")) + await acp.initialize() + + const loaded = acp.request("session/load", { cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] }) + await acp.until(() => acp.server.requests.some((item) => item.path === "/api/session/ses_loaded/message")) + await acp.request("session/close", { sessionId: "ses_loaded" }) + held.resolve(undefined) + await loaded + // A later session's commands follow the load response, giving a stray update time to arrive. + const created = await acp.newSession() + await acp.until(() => acp.updates.some(isCommands), "commands for the later session") + + expect(acp.updates.filter(isCommands).map((item) => item.sessionId)).toEqual([created.sessionId]) + }) + + test("detaches a session whose load fails after attaching", async () => { + await using acp = await startWire({ + fetch: (request) => + request.path === "/api/session/ses_loaded/message" ? new Response(null, { status: 500 }) : undefined, + }) + acp.server.sessions.set("ses_loaded", makeSession("ses_loaded")) + await acp.initialize() + + expect( + await rpcError(acp.request("session/load", { cwd: "/workspace", sessionId: "ses_loaded", mcpServers: [] })), + ).toMatchObject({ code: -32603 }) + expect( + await rpcError( + acp.request("session/set_config_option", { sessionId: "ses_loaded", configId: "mode", value: "plan" }), + ), + ).toMatchObject({ code: -32602, data: { sessionId: "ses_loaded" } }) + }) + test("lists server-backed pages for the requested cwd", async () => { await using acp = await startWire() Array.from({ length: 101 }, (_, index) => @@ -271,6 +342,7 @@ describe("acp session lifecycle over the wire", () => { await acp.initialize() const failed = await acp.newSession() const other = await acp.newSession() + await acp.until(() => acp.updates.filter(isCommands).length === 2, "initial commands") expect( await rpcError( @@ -290,3 +362,27 @@ describe("acp session lifecycle over the wire", () => { ).toMatchObject({ code: -32602, data: { sessionId: failed.sessionId } }) }) }) + +const isSessionUpdate = Schema.is( + Schema.Struct({ + method: Schema.Literal("session/update"), + params: Schema.Struct({ update: Schema.Struct({ sessionUpdate: Schema.String }) }), + }), +) + +function isCommands(item: SessionNotification) { + return item.update.sessionUpdate === "available_commands_update" +} + +// Labels what the agent sends from the request until the commands that follow it, in wire order. +async function untilCommands(acp: Wire, send: () => Promise) { + const start = acp.received.length + await send() + return acp.until(() => { + const labels = acp.received.slice(start).map((message) => { + if (isSessionUpdate(message)) return message.params.update.sessionUpdate + return "method" in message ? message.method : "response" + }) + return labels.includes("available_commands_update") && labels + }, "available commands") +}