diff --git a/apps/server/scripts/acp-replay-agent.ts b/apps/server/scripts/acp-replay-agent.ts index c68366828e91..ea4e85a730dc 100644 --- a/apps/server/scripts/acp-replay-agent.ts +++ b/apps/server/scripts/acp-replay-agent.ts @@ -73,7 +73,9 @@ function resumedCursor(): number { let cursor = resumedCursor(); let stopped = false; let nextAgentRequestId = 1; -const pendingClientRequestIds = new Map(); +// Several requests of one method can be open at once (a prompt steer is a second +// session/prompt while the first runs), so responses pair first-in-first-out per method. +const pendingClientRequestIds = new Map>(); const pendingAgentRequestMethods = new Map(); // The test reads status while this agent may still be running; rename makes each @@ -167,7 +169,10 @@ function send(message: JsonRpcMessage): void { } function pendingClientRequestId(method: string): string | number | undefined { - return pendingClientRequestIds.get(method); + const ids = pendingClientRequestIds.get(method); + const id = ids?.shift(); + if (ids !== undefined && ids.length === 0) pendingClientRequestIds.delete(method); + return id; } function logicalIncoming(message: JsonRpcMessage): LogicalFrame | undefined { @@ -228,7 +233,6 @@ function inboundMessage(recorded: LogicalFrame): JsonRpcMessage | undefined { stopWithFailure(`No pending client request for ${frame.method}`, frame); return undefined; } - pendingClientRequestIds.delete(frame.method); return { jsonrpc: "2.0", id, @@ -295,7 +299,9 @@ function handleMessage(message: JsonRpcMessage): void { return; } if (actual.kind === "request" && message.id !== undefined && message.id !== null) { - pendingClientRequestIds.set(actual.method, message.id); + const pending = pendingClientRequestIds.get(actual.method) ?? []; + pending.push(message.id); + pendingClientRequestIds.set(actual.method, pending); } else if (actual.kind === "response" && message.id !== undefined && message.id !== null) { pendingAgentRequestMethods.delete(String(message.id)); } diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index ef5eb91eef4b..52c8218366bc 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1649,6 +1649,194 @@ describe("AcpAdapterV2", () => { assert.deepEqual(promptTexts.slice(3), ["continue"], "a turn resumes only once"); }).pipe(Effect.provide(layerTest)), ); + + it.live("pairs responses to concurrent same-method requests in request order", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-acp-fifo-" }); + const statusPath = path.join(directory, "status.json"); + const instanceId = ProviderInstanceId.make("acp-test-concurrent-prompts"); + const threadId = ThreadId.make("thread-acp-concurrent-prompts"); + const sessionId = "concurrent-session"; + const update = (sessionUpdate: Record) => ({ + type: "emit_inbound", + frame: { + kind: "notification", + method: "session/update", + params: { sessionId, update: sessionUpdate }, + }, + }); + // A prompt steer is a second session/prompt while the first still runs, so two + // same-method client requests are open at once when the first response arrives. + const transcript = yield* decodeAcpReplayTranscript( + { + provider: ACP_TEST_DRIVER, + protocol: "acp.ndjson-jsonrpc", + version: "1", + scenario: "concurrent-prompts", + entries: [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { + protocolVersion: 1, + agentCapabilities: { sessionCapabilities: { close: {} } }, + authMethods: [], + }, + }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/new", params: "" }, + }, + { + type: "emit_inbound", + frame: { kind: "response", method: "session/new", result: { sessionId } }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + update({ sessionUpdate: "session_info_update", title: "before steer" }), + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + // In request order this cancelled response settles the original prompt, which + // the steer already superseded. Mis-paired onto the steer, it would end the + // turn as cancelled instead. + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { stopReason: "cancelled" }, + }, + }, + update({ + sessionUpdate: "agent_message_chunk", + messageId: "reply", + content: { type: "text", text: "after the steer" }, + }), + update({ sessionUpdate: "session_info_update", title: "steer output" }), + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { stopReason: "end_turn" }, + }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/close", params: "" }, + }, + { + type: "emit_inbound", + frame: { kind: "response", method: "session/close", result: {} }, + }, + ], + } as never, + ACP_TEST_DRIVER, + ); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + steersWithPrompt: () => true, + makeRuntime: makeAcpReplayRuntime({ + transcript, + statusPath, + scriptPath: yield* bundledReplayAgentPath, + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + fileSystem, + }), + assertComplete: makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: directory, + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-concurrent-prompts"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const until = (predicate: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) => + Effect.gen(function* () { + const seen: Array = []; + while (true) { + const event = yield* Queue.take(events); + seen.push(event); + if (predicate(event)) return seen; + } + }); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + }), + ); + const started = yield* until( + (event) => + event.type === "provider_thread.updated" && + event.providerThread.nativeMetadata?.title === "before steer", + ); + const running = started.findLast((event) => event.type === "provider_turn.updated"); + if (running?.type !== "provider_turn.updated") throw new Error("Missing active turn"); + yield* runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:1`), + providerThread, + providerTurnId: running.providerTurn.id, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("steer-concurrent-prompts"), + text: "steer message", + attachments: [], + }, + }); + const terminalEvents = yield* until((event) => event.type === "turn.terminal"); + const terminal = terminalEvents.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed"); + assert.isTrue( + terminalEvents.some( + (event) => + event.type === "message.updated" && event.message.text.includes("after the steer"), + ), + "the continued turn's output lands before the steer response settles it", + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.live("retains returned usage when Stop finalizes before the prompt callback", () => Effect.gen(function* () { const instanceId = ProviderInstanceId.make("acp-test-prompt-usage-stop");