@devries-cameron20 / t3code-1 / commits / 7903b487ba
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(acp): Copilot runs end when its reply is done, not when its async shells exit (#36122)

Julius Marminge committed Nov 13, 2026 at 02:34 UTC 7903b487badeba1e53ba0cc5dc8be76a6c3ae0f4
4 files changed +228 -61
apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+89
@@ -1768,6 +1768,95 @@ describe("AcpRegistryAdapterV2", () => {
1768 }).pipe(Effect.provide(layerTest)),
1769 );
1770
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 +
1860 it.effect.each([
1861 { kind: "approval", stopReason: "end_turn", status: "completed" },
1862 { kind: "question", stopReason: "error", status: "failed" },
packages/provider-acp-registry/src/server/copilotAcp.ts
+11
@@ -22,6 +22,8 @@ export const copilotClientCapabilitiesMeta = {
22 "assistant.message_delta",
23 "assistant.reasoning_delta",
24 "session.compaction_complete",
25 + "assistant.turn_start",
26 + "assistant.idle",
27 ],
28 },
29 };
@@ -131,6 +133,15 @@ export function makeCopilotSubagentRouting() {
133 }
134 return context.markSessionCompacted(event.sessionId);
135 }
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 + }
145 default:
146 return Effect.void;
147 }
packages/provider-acp/src/server/AcpSessionRuntime.ts
+92 -60
@@ -1163,10 +1163,16 @@ export class AcpSessionRuntime extends Context.Service<
1163 providerId: string,
1164 ) => Effect.Effect<EffectAcpSchema.DisableProviderResponse, EffectAcpErrors.AcpError>;
1165 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 + */
1170 readonly prompt: (
1171 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 + },
1176 ) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
1177 readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
1178 readonly terminateProcessGroup?: Effect.Effect<void, AcpProcessGroupTerminationError>;
@@ -2376,6 +2382,17 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2382 yield* child.kill({ forceKillAfter: "1 second" }).pipe(Effect.ignore);
2383 });
2384
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 +
2396 const cancel = Effect.gen(function* () {
2397 const started = yield* getStartedState;
2398 const activePrompt = yield* Ref.get(activePromptRef);
@@ -2616,66 +2633,81 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* (
2633 Effect.andThen(runLoggedRequest("logout", {}, acp.agent.logout({}))),
2634 ),
2635 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),
2661 ),
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 + ),
2710 ),
2678 - ),
2711 cancel:
2712 options.cancelBehavior === "wait-for-prompt"
2713 ? promptDispatchSemaphore.withPermit(cancel)
packages/provider-acp/src/server/adapter.ts
+36 -1
@@ -251,6 +251,14 @@ export interface AcpAdapterV2ExtensionContext {
251 }) => Effect.Effect<void>;
252 /** For compactions reported outside ACP `compaction_update`. */
253 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>;
262 readonly requestUserInput: (
263 input: AcpAdapterV2UserInputRequest,
264 requestContext: EffectAcpProtocol.AcpRequestContext,
@@ -1482,6 +1490,8 @@ interface ActiveAcpTurn {
1490 readonly promptWireSettled: Deferred.Deferred<void, never>;
1491 /** Completed once `session/prompt` is the runtime's active prompt. */
1492 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>;
1495 /** Clock millis just before `session/prompt` was handed to the runtime. */
1496 promptSentAt: number | null;
1497 /** Completed when an update after dispatch matches `cancelAfterPromptStarts.isStart`. */
@@ -6967,6 +6977,27 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6977 handlerGeneration,
6978 markSessionCompacted(sessionId),
6979 ).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),
7001 applyBackgroundTaskMutation: (incoming) =>
7002 runRuntimeCallbackAtGeneration(
7003 handlerGeneration,
@@ -8418,6 +8449,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8449 workAccepted: false,
8450 promptWireSettled,
8451 promptDispatched,
8452 + foregroundIdle: yield* Deferred.make<void>(),
8453 promptSentAt: null,
8454 promptStarted,
8455 promptUsage: undefined,
@@ -8564,7 +8596,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8596 ? undefined
8597 : yield* flavor.watchPromptOutcome(requestedSessionId);
8598 const promptGeneration = yield* Ref.get(runtimeCallbackGeneration);
8567 - const promptOptions = { dispatched: context.promptDispatched };
8599 + const promptOptions = {
8600 + dispatched: context.promptDispatched,
8601 + released: context.foregroundIdle,
8602 + };
8603 context.promptSentAt = yield* Clock.currentTimeMillis;
8604 if (promptInactivityTimeoutMillis !== undefined) {
8605 context.inactivityWatchdog = yield* watchPromptInactivity(