Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions apps/server/scripts/acp-replay-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ function resumedCursor(): number {
let cursor = resumedCursor();
let stopped = false;
let nextAgentRequestId = 1;
const pendingClientRequestIds = new Map<string, string | number>();
// 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<string, Array<string | number>>();
const pendingAgentRequestMethods = new Map<string, string>();

// The test reads status while this agent may still be running; rename makes each
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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));
}
Expand Down
188 changes: 188 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => ({
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: "<any>" },
},
{
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: "<any>" },
},
{
type: "emit_inbound",
frame: { kind: "response", method: "session/new", result: { sessionId } },
},
{
type: "expect_outbound",
frame: { kind: "request", method: "session/prompt", params: "<any>" },
},
update({ sessionUpdate: "session_info_update", title: "before steer" }),
{
type: "expect_outbound",
frame: { kind: "request", method: "session/prompt", params: "<any>" },
},
// 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: "<any>" },
},
{
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<ProviderAdapter.ProviderAdapterV2Event>();
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<ProviderAdapter.ProviderAdapterV2Event> = [];
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");
Expand Down
Loading