Skip to content

Commit 7903b48

Browse files
fix(acp): Copilot runs end when its reply is done, not when its async shells exit (#36122)
1 parent fa9d85f commit 7903b48

4 files changed

Lines changed: 228 additions & 61 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1768,6 +1768,95 @@ describe("AcpRegistryAdapterV2", () => {
17681768
}).pipe(Effect.provide(layerTest)),
17691769
);
17701770

1771+
// Copilot holds session/prompt while an attached async shell runs (github/copilot-cli#5293);
1772+
// its documented foreground-done signal is the opt-in assistant.idle session event.
1773+
it.effect("settles Copilot's reply on assistant.idle while an async shell holds the prompt", () =>
1774+
Effect.gen(function* () {
1775+
const sessionId = "copilot-session";
1776+
const sessionEvent = (type: string) => ({
1777+
type: "emit_inbound",
1778+
frame: {
1779+
kind: "notification",
1780+
method: "github.com/copilot/sessionEvent",
1781+
params: { sessionId, type, data: {} },
1782+
},
1783+
});
1784+
const update = (sessionUpdate: Record<string, unknown>) =>
1785+
claudeFrames.update(sessionId, sessionUpdate);
1786+
const session = yield* openClaudeReplaySession(
1787+
[
1788+
{
1789+
type: "expect_outbound",
1790+
frame: { kind: "request", method: "initialize", params: "<any>" },
1791+
},
1792+
{
1793+
type: "emit_inbound",
1794+
frame: {
1795+
kind: "response",
1796+
method: "initialize",
1797+
result: {
1798+
protocolVersion: 1,
1799+
agentInfo: { name: "Copilot", version: "1.0.110" },
1800+
agentCapabilities: { loadSession: true },
1801+
authMethods: [],
1802+
},
1803+
},
1804+
},
1805+
{
1806+
type: "expect_outbound",
1807+
frame: { kind: "request", method: "session/new", params: "<any>" },
1808+
},
1809+
{
1810+
type: "emit_inbound",
1811+
frame: { kind: "response", method: "session/new", result: { sessionId } },
1812+
},
1813+
{
1814+
type: "expect_outbound",
1815+
frame: { kind: "request", method: "session/prompt", params: "<any>" },
1816+
},
1817+
// A previous prompt's idle can land before this prompt's turn starts.
1818+
sessionEvent("assistant.idle"),
1819+
update({ sessionUpdate: "session_info_update", title: "after stale idle" }),
1820+
sessionEvent("assistant.turn_start"),
1821+
update({
1822+
sessionUpdate: "tool_call",
1823+
toolCallId: "shell-1",
1824+
title: "sleep 120",
1825+
kind: "execute",
1826+
status: "completed",
1827+
rawInput: { command: "sleep 120", mode: "async", detach: false },
1828+
}),
1829+
update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "ok" } }),
1830+
sessionEvent("assistant.idle"),
1831+
update({ sessionUpdate: "session_info_update", title: "after foreground idle" }),
1832+
// The shell never exits, so the first session/prompt is never answered.
1833+
{
1834+
type: "expect_outbound",
1835+
frame: { kind: "request", method: "session/prompt", params: "<any>" },
1836+
},
1837+
sessionEvent("assistant.turn_start"),
1838+
update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "two" } }),
1839+
sessionEvent("assistant.idle"),
1840+
update({ sessionUpdate: "session_info_update", title: "after second idle" }),
1841+
],
1842+
undefined,
1843+
false,
1844+
"github-copilot-cli",
1845+
);
1846+
yield* session.runtime.startTurn(session.turnInput(1));
1847+
const stale = yield* session.throughMarker("after stale idle");
1848+
assert.isFalse(stale.some((event) => event.type === "turn.terminal"));
1849+
const foreground = yield* session.throughMarker("after foreground idle");
1850+
const terminal = foreground.find((event) => event.type === "turn.terminal");
1851+
assert.isDefined(terminal, "the run settles once Copilot's foreground work is idle");
1852+
assert.equal(terminal?.type === "turn.terminal" ? terminal.status : null, "completed");
1853+
yield* session.runtime.startTurn(session.turnInput(2));
1854+
const second = yield* session.throughMarker("after second idle");
1855+
const secondTerminal = second.find((event) => event.type === "turn.terminal");
1856+
assert.equal(secondTerminal?.type === "turn.terminal" ? secondTerminal.runOrdinal : null, 2);
1857+
}).pipe(Effect.provide(layerTest)),
1858+
);
1859+
17711860
it.effect.each([
17721861
{ kind: "approval", stopReason: "end_turn", status: "completed" },
17731862
{ kind: "question", stopReason: "error", status: "failed" },

‎packages/provider-acp-registry/src/server/copilotAcp.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ export const copilotClientCapabilitiesMeta = {
2222
"assistant.message_delta",
2323
"assistant.reasoning_delta",
2424
"session.compaction_complete",
25+
"assistant.turn_start",
26+
"assistant.idle",
2527
],
2628
},
2729
};
@@ -131,6 +133,15 @@ export function makeCopilotSubagentRouting() {
131133
}
132134
return context.markSessionCompacted(event.sessionId);
133135
}
136+
// Copilot holds session/prompt while an attached async shell runs (github/copilot-cli#5293).
137+
case "assistant.turn_start":
138+
case "assistant.idle": {
139+
if (event.agentId !== undefined || data.aborted === true) return Effect.void;
140+
return context.reportForegroundWork({
141+
sessionId: event.sessionId,
142+
state: event.type === "assistant.idle" ? "idle" : "running",
143+
});
144+
}
134145
default:
135146
return Effect.void;
136147
}

‎packages/provider-acp/src/server/AcpSessionRuntime.ts‎

Lines changed: 92 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,10 +1163,16 @@ export class AcpSessionRuntime extends Context.Service<
11631163
providerId: string,
11641164
) => Effect.Effect<EffectAcpSchema.DisableProviderResponse, EffectAcpErrors.AcpError>;
11651165
readonly logout: Effect.Effect<EffectAcpSchema.LogoutResponse, EffectAcpErrors.AcpError>;
1166-
/** options.dispatched settles when cancel can target this prompt. */
1166+
/**
1167+
* options.dispatched settles when cancel can target this prompt. options.released lets the
1168+
* next prompt go out while this one's response is still held; it still resolves this call.
1169+
*/
11671170
readonly prompt: (
11681171
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
1169-
options?: { readonly dispatched?: Deferred.Deferred<void> },
1172+
options?: {
1173+
readonly dispatched?: Deferred.Deferred<void>;
1174+
readonly released?: Deferred.Deferred<void>;
1175+
},
11701176
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
11711177
readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
11721178
readonly terminateProcessGroup?: Effect.Effect<void, AcpProcessGroupTerminationError>;
@@ -2376,6 +2382,17 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
23762382
yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
23772383
});
23782384

2385+
const joinPrompt = (
2386+
fiber: Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>,
2387+
) =>
2388+
Fiber.join(fiber).pipe(
2389+
Effect.catchCauseIf(
2390+
(cause) => options.cancelBehavior !== "wait-for-prompt" && Cause.hasInterruptsOnly(cause),
2391+
(_cause) =>
2392+
Effect.succeed({ stopReason: "cancelled" } satisfies EffectAcpSchema.PromptResponse),
2393+
),
2394+
);
2395+
23792396
const cancel = Effect.gen(function* () {
23802397
const started = yield* getStartedState;
23812398
const activePrompt = yield* Ref.get(activePromptRef);
@@ -2616,66 +2633,81 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
26162633
Effect.andThen(runLoggedRequest("logout", {}, acp.agent.logout({}))),
26172634
),
26182635
prompt: (payload, promptOptions?) =>
2619-
promptSerializationSemaphore.withPermit(
2620-
Effect.acquireUseRelease(
2621-
promptDispatchSemaphore.withPermit(
2622-
Effect.gen(function* () {
2623-
const started = yield* getStartedState;
2624-
yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
2625-
yield* Ref.set(assistantUpdatesOpenRef, true);
2626-
const requestPayload = {
2627-
sessionId: started.sessionId,
2628-
...payload,
2629-
} satisfies EffectAcpSchema.PromptRequest;
2630-
const completed = yield* Deferred.make<void>();
2631-
const fiber = yield* runLoggedRequest(
2632-
"session/prompt",
2633-
requestPayload,
2634-
acp.agent.prompt(requestPayload),
2635-
).pipe(Effect.forkIn(runtimeScope));
2636-
const active = { fiber, completed } satisfies AcpActivePrompt;
2637-
yield* Ref.set(activePromptRef, Option.some(active));
2638-
if (promptOptions?.dispatched) {
2639-
yield* Deferred.succeed(promptOptions.dispatched, undefined);
2640-
}
2641-
return active;
2642-
}).pipe(notificationSemaphore.withPermit),
2643-
),
2644-
(activePrompt) =>
2645-
Fiber.join(activePrompt.fiber).pipe(
2646-
Effect.catchCauseIf(
2647-
(cause) =>
2648-
options.cancelBehavior !== "wait-for-prompt" && Cause.hasInterruptsOnly(cause),
2649-
(_cause) =>
2650-
Effect.succeed({
2651-
stopReason: "cancelled",
2652-
} satisfies EffectAcpSchema.PromptResponse),
2653-
),
2654-
Effect.tap(() =>
2655-
closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }),
2656-
),
2636+
promptSerializationSemaphore
2637+
.withPermit(
2638+
Effect.acquireUseRelease(
2639+
promptDispatchSemaphore.withPermit(
2640+
Effect.gen(function* () {
2641+
const started = yield* getStartedState;
2642+
yield* closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef });
2643+
yield* Ref.set(assistantUpdatesOpenRef, true);
2644+
const requestPayload = {
2645+
sessionId: started.sessionId,
2646+
...payload,
2647+
} satisfies EffectAcpSchema.PromptRequest;
2648+
const completed = yield* Deferred.make<void>();
2649+
const fiber = yield* runLoggedRequest(
2650+
"session/prompt",
2651+
requestPayload,
2652+
acp.agent.prompt(requestPayload),
2653+
).pipe(Effect.forkIn(runtimeScope));
2654+
const active = { fiber, completed } satisfies AcpActivePrompt;
2655+
yield* Ref.set(activePromptRef, Option.some(active));
2656+
if (promptOptions?.dispatched) {
2657+
yield* Deferred.succeed(promptOptions.dispatched, undefined);
2658+
}
2659+
return active;
2660+
}).pipe(notificationSemaphore.withPermit),
26572661
),
2658-
(activePrompt, result) =>
2659-
Effect.gen(function* () {
2660-
if (
2661-
options.cancelBehavior === "wait-for-prompt" &&
2662-
Exit.isFailure(result) &&
2663-
Cause.hasInterrupts(result.cause)
2664-
) {
2665-
yield* retireRuntime(
2666-
new EffectAcpErrors.AcpTransportError({
2667-
method: "session/prompt",
2668-
detail: "The ACP prompt stopped before the agent confirmed completion.",
2669-
cause: undefined,
2670-
}),
2671-
);
2672-
}
2673-
yield* Fiber.interrupt(activePrompt.fiber).pipe(Effect.ignore);
2674-
yield* Ref.set(activePromptRef, Option.none());
2675-
yield* Deferred.succeed(activePrompt.completed, undefined);
2676-
}),
2662+
(activePrompt) => {
2663+
const settled = joinPrompt(activePrompt.fiber).pipe(
2664+
Effect.tap(() =>
2665+
closeActiveAssistantSegment({ queue: eventQueue, assistantSegmentRef }),
2666+
),
2667+
Effect.map((response) => ({ _tag: "Settled" as const, response })),
2668+
);
2669+
return promptOptions?.released === undefined
2670+
? settled
2671+
: Effect.raceFirst(
2672+
settled,
2673+
Deferred.await(promptOptions.released).pipe(
2674+
Effect.as({ _tag: "Released" as const, fiber: activePrompt.fiber }),
2675+
),
2676+
);
2677+
},
2678+
(activePrompt, result) =>
2679+
Effect.gen(function* () {
2680+
if (Exit.isSuccess(result) && result.value._tag === "Released") {
2681+
yield* Ref.set(activePromptRef, Option.none());
2682+
yield* Deferred.succeed(activePrompt.completed, undefined);
2683+
return;
2684+
}
2685+
if (
2686+
options.cancelBehavior === "wait-for-prompt" &&
2687+
Exit.isFailure(result) &&
2688+
Cause.hasInterrupts(result.cause)
2689+
) {
2690+
yield* retireRuntime(
2691+
new EffectAcpErrors.AcpTransportError({
2692+
method: "session/prompt",
2693+
detail: "The ACP prompt stopped before the agent confirmed completion.",
2694+
cause: undefined,
2695+
}),
2696+
);
2697+
}
2698+
yield* Fiber.interrupt(activePrompt.fiber).pipe(Effect.ignore);
2699+
yield* Ref.set(activePromptRef, Option.none());
2700+
yield* Deferred.succeed(activePrompt.completed, undefined);
2701+
}),
2702+
),
2703+
)
2704+
.pipe(
2705+
Effect.flatMap((outcome) =>
2706+
outcome._tag === "Settled"
2707+
? Effect.succeed(outcome.response)
2708+
: joinPrompt(outcome.fiber),
2709+
),
26772710
),
2678-
),
26792711
cancel:
26802712
options.cancelBehavior === "wait-for-prompt"
26812713
? promptDispatchSemaphore.withPermit(cancel)

‎packages/provider-acp/src/server/adapter.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,14 @@ export interface AcpAdapterV2ExtensionContext {
251251
}) => Effect.Effect<void>;
252252
/** For compactions reported outside ACP `compaction_update`. */
253253
readonly markSessionCompacted: (sessionId: string) => Effect.Effect<void>;
254+
/**
255+
* For agents that hold `session/prompt` past their foreground work on ACP v1. An idle settles
256+
* the run only after a `running` report during it, so an earlier prompt's idle cannot.
257+
*/
258+
readonly reportForegroundWork: (notice: {
259+
readonly sessionId: string;
260+
readonly state: "running" | "idle";
261+
}) => Effect.Effect<void>;
254262
readonly requestUserInput: (
255263
input: AcpAdapterV2UserInputRequest,
256264
requestContext: EffectAcpProtocol.AcpRequestContext,
@@ -1482,6 +1490,8 @@ interface ActiveAcpTurn {
14821490
readonly promptWireSettled: Deferred.Deferred<void, never>;
14831491
/** Completed once `session/prompt` is the runtime's active prompt. */
14841492
readonly promptDispatched: Deferred.Deferred<void, never>;
1493+
/** Frees the runtime for the next prompt while the agent still holds this one's response. */
1494+
readonly foregroundIdle: Deferred.Deferred<void>;
14851495
/** Clock millis just before `session/prompt` was handed to the runtime. */
14861496
promptSentAt: number | null;
14871497
/** Completed when an update after dispatch matches `cancelAfterPromptStarts.isStart`. */
@@ -6967,6 +6977,27 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
69676977
handlerGeneration,
69686978
markSessionCompacted(sessionId),
69696979
).pipe(Effect.asVoid),
6980+
reportForegroundWork: (notice) =>
6981+
runRuntimeCallbackAtGeneration(
6982+
handlerGeneration,
6983+
Effect.gen(function* () {
6984+
if (yield* Ref.get(stoppedRunQuarantine)) return;
6985+
const context = yield* Ref.get(activeTurn);
6986+
if (
6987+
context === null ||
6988+
context.finalized ||
6989+
context.interrupted ||
6990+
context.nativeThreadId !== notice.sessionId
6991+
)
6992+
return;
6993+
if (notice.state === "running") {
6994+
context.workAccepted = true;
6995+
} else if (context.workAccepted) {
6996+
yield* Deferred.succeed(context.foregroundIdle, undefined);
6997+
yield* finalizeTurn(context, "completed");
6998+
}
6999+
}),
7000+
).pipe(Effect.asVoid),
69707001
applyBackgroundTaskMutation: (incoming) =>
69717002
runRuntimeCallbackAtGeneration(
69727003
handlerGeneration,
@@ -8418,6 +8449,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
84188449
workAccepted: false,
84198450
promptWireSettled,
84208451
promptDispatched,
8452+
foregroundIdle: yield* Deferred.make<void>(),
84218453
promptSentAt: null,
84228454
promptStarted,
84238455
promptUsage: undefined,
@@ -8564,7 +8596,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
85648596
? undefined
85658597
: yield* flavor.watchPromptOutcome(requestedSessionId);
85668598
const promptGeneration = yield* Ref.get(runtimeCallbackGeneration);
8567-
const promptOptions = { dispatched: context.promptDispatched };
8599+
const promptOptions = {
8600+
dispatched: context.promptDispatched,
8601+
released: context.foregroundIdle,
8602+
};
85688603
context.promptSentAt = yield* Clock.currentTimeMillis;
85698604
if (promptInactivityTimeoutMillis !== undefined) {
85708605
context.inactivityWatchdog = yield* watchPromptInactivity(

0 commit comments

Comments
 (0)