Skip to content

Commit 1e89efa

Browse files
authored
fix: tear down session interactions and background processes on close (#711)
## Summary Follow up #710 with the session-close interaction and background-process cleanup changes from the protocol review. Applies to ACP v1 and v2; `session/delete` uses the same teardown path. - Give session-scoped permission requests and elicitations a shared cancellation owner, including idle/background interactions and registered child sessions. Preserve caller cancellation and leave request-scoped login interactions alone. - Cancel pending interactions before waiting for runtime teardown and reject new interactions while the owning session is closing. - Stop Codex background processes before unsubscribe and before responding to close, independently of AIR async-task display support. Codex's unsubscribe only detaches the subscriber; delayed unload is not a cleanup barrier. - Share background-terminal pagination with the existing task tracker. Read every page before terminating processes, and detect repeated cursors. - Clean up child processes only for ownership established by native events/readbacks. Do not wait on unrelated metadata reads during close or act on foreign ownership. - Preserve the local session and subscriptions when process cleanup fails, so close can be retried. A false termination result is checked against the current process list rather than assumed to mean success. - Make already-closed/unknown close requests succeed without unnecessary Codex calls, and publish terminal task state only after successful cleanup. ## Validation - `npm run typecheck` — passed, including examples. - `npm test` — 2,282 passed, 39 skipped. - `npm run test:integration` — all 19 tests passed across 8 files. - `npm run build` and `git diff --check` — passed. - A new real-Codex integration test starts a long-lived shell process, confirms it is alive, closes the session without AIR async-task support, and confirms the OS process has exited when close responds. - Real Codex smoke: `npm run codex-test -- -p "Reply with exactly OK. Do not use tools or modify any files." -o summary` — completed with `end_turn`. - Opt-in E2E suite was not run. ## Remaining follow-ups This is not a claim of complete v2 lifecycle conformance. The general post-close notification fence, resume snapshots/metadata, setup response ordering, and active-resume environment replacement remain separate changes. Active-resume replacement also needs the spec decision about in-flight operations using removed roots or MCP servers. No internal review Markdown file is included.
1 parent 6f96fbe commit 1e89efa

23 files changed

Lines changed: 567 additions & 55 deletions
Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,17 @@ type SessionUpdateParams = {sessionId: string; update: UpdateSessionEvent};
88
* Sends the notifications and requests of the adapter to the ACP client.
99
*
1010
* Every emission site of the adapter uses this connection.
11-
* So each tool call report goes through the same changed-fields filter,
12-
* whether it comes from a live event, a history replay, a permission flow or an async task.
11+
* Tool reports share a changed-fields filter, and session interactions share cancellation
12+
* on close, whether they belong to foreground work, background work or session startup.
1313
*/
14-
export class ToolCallReportingConnection {
14+
export class AcpClientDelivery {
1515
readonly reports = new ToolCallReports();
16+
private readonly sessionRequests = new Map<string, Set<AbortController>>();
1617

17-
constructor(private readonly client: AcpClientConnection) {}
18+
constructor(
19+
private readonly client: AcpClientConnection,
20+
private readonly sessionIsClosing: (sessionId: string) => boolean = () => false,
21+
) {}
1822

1923
/** Returns this connection with the signature of the SDK connection. */
2024
asClientConnection(): AcpClientConnection {
@@ -33,22 +37,57 @@ export class ToolCallReportingConnection {
3337

3438
async request(method: string, params?: unknown, options?: acp.SendRequestOptions): Promise<unknown> {
3539
if (method !== acp.methods.client.session.requestPermission || !isPermissionRequestParams(params)) {
36-
return await this.client.request(method, params, options);
40+
return await this.sendRequest(method, params, options);
3741
}
3842
// The client merges the request tool call into the stored tool call, like an update.
3943
// A cancelled or failed request may leave the client without these fields,
4044
// so the adapter then forgets the open record and sends every field again.
4145
this.reports.prepare(params.sessionId, {sessionUpdate: "tool_call_update", ...params.toolCall});
4246
let response: unknown;
4347
try {
44-
response = await this.client.request(method, params, options);
48+
response = await this.sendRequest(method, params, options);
4549
} catch (error) {
4650
this.reports.forgetOpen(params.sessionId, params.toolCall.toolCallId);
4751
throw error;
4852
}
4953
if (isCancelled(response)) this.reports.forgetOpen(params.sessionId, params.toolCall.toolCallId);
5054
return response;
5155
}
56+
57+
/** Withdraw pending UI without waiting for the client to answer the cancelled requests. */
58+
cancelSessionRequests(sessionId: string): void {
59+
for (const controller of this.sessionRequests.get(sessionId) ?? []) {
60+
controller.abort(acp.RequestError.requestCancelled(undefined, `Session ${sessionId} is closing`));
61+
}
62+
}
63+
64+
private async sendRequest(method: string, params: unknown, options?: acp.SendRequestOptions): Promise<unknown> {
65+
const sessionId = interactionSessionId(method, params);
66+
if (sessionId === null) return await this.client.request(method, params, options);
67+
if (this.sessionIsClosing(sessionId)) {
68+
throw acp.RequestError.requestCancelled(undefined, `Session ${sessionId} is closing`);
69+
}
70+
const controller = new AbortController();
71+
const requests = this.sessionRequests.get(sessionId) ?? new Set<AbortController>();
72+
this.sessionRequests.set(sessionId, requests);
73+
requests.add(controller);
74+
const cancellationSignal = options?.cancellationSignal
75+
? AbortSignal.any([options.cancellationSignal, controller.signal])
76+
: controller.signal;
77+
try {
78+
return await this.client.request(method, params, {...options, cancellationSignal});
79+
} finally {
80+
requests.delete(controller);
81+
if (requests.size === 0) this.sessionRequests.delete(sessionId);
82+
}
83+
}
84+
}
85+
86+
function interactionSessionId(method: string, params: unknown): string | null {
87+
if (method !== acp.methods.client.elicitation.create && method !== acp.methods.client.session.requestPermission) return null;
88+
if (params === null || typeof params !== "object") return null;
89+
const sessionId = (params as {sessionId?: unknown}).sessionId;
90+
return typeof sessionId === "string" ? sessionId : null;
5291
}
5392

5493
function isCancelled(response: unknown): boolean {

‎src/CodexAcpClient.ts‎

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ import {
7070
isMissingRolloutError,
7171
isThreadNotMaterializedError,
7272
isThreadActiveWriterError,
73+
isThreadNotFoundError,
74+
isThreadNotLoadedError,
7375
isUnknownThreadError,
7476
threadActiveWriterRequestError,
7577
} from "./CodexThreadErrors";
@@ -854,6 +856,8 @@ export class CodexAcpClient {
854856

855857
isSubagentThread(threadId: string): boolean { return this.subagents.isChildThread(threadId); }
856858

859+
readSubagentThread(threadId: string): Promise<Thread | null> { return this.subagents.readChildThread(threadId); }
860+
857861
async newSession(request: WithAcpMcpServers<acp.NewSessionRequest>): Promise<SessionMetadata> {
858862
const instructions = await this.resolveSessionInstructions(request, undefined, true);
859863
const additionalDirectories = readAdditionalDirectories(request.cwd, request.additionalDirectories, request._meta);
@@ -974,11 +978,35 @@ export class CodexAcpClient {
974978
}
975979

976980
async closeSession(sessionId: string): Promise<void> {
981+
const children = this.subagents.verifiedChildThreadIds(sessionId);
982+
// Unsubscribe only detaches. Codex can keep the runtime and its processes alive until a later unload.
983+
for (const threadId of [...children, sessionId]) {
984+
await this.stopBackgroundTerminals(threadId);
985+
}
986+
await this.codexClient.threadUnsubscribe({threadId: sessionId});
987+
this.codexClient.clearThreadHandlers(sessionId);
988+
this.subagents.clear(sessionId);
989+
}
990+
991+
private async stopBackgroundTerminals(threadId: string): Promise<void> {
977992
try {
978-
await this.codexClient.threadUnsubscribe({threadId: sessionId});
979-
} finally {
980-
this.codexClient.clearThreadHandlers(sessionId);
981-
this.subagents.clear(sessionId);
993+
// Read all pages before removing processes so cleanup cannot disturb pagination.
994+
const terminals = [];
995+
for await (const page of this.codexClient.backgroundTerminalPages(threadId)) terminals.push(...page);
996+
for (const terminal of terminals) {
997+
const result = await this.codexClient.threadBackgroundTerminalsTerminate({threadId, processId: terminal.processId});
998+
if (!result.terminated) {
999+
// False can mean either "already gone" or a failed stop. Verify which before closing.
1000+
for await (const page of this.codexClient.backgroundTerminalPages(threadId)) {
1001+
if (page.some(current => current.processId === terminal.processId)) {
1002+
throw new Error(`Codex could not stop background terminal ${terminal.processId}`);
1003+
}
1004+
}
1005+
}
1006+
}
1007+
} catch (error) {
1008+
// An already-unloaded runtime has no processes left to stop.
1009+
if (!isThreadNotFoundError(error) && !isThreadNotLoadedError(error)) throw error;
9821010
}
9831011
}
9841012

‎src/CodexAcpServer.ts‎

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ import type {QuotaMeta} from "./QuotaMeta";
109109
import {logger} from "./Logger";
110110
import {settledWithin} from "./StdUtils";
111111
import type {ToolCallReports} from "./ToolCallReports";
112-
import {ToolCallReportingConnection} from "./ToolCallReportingConnection";
112+
import {AcpClientDelivery} from "./AcpClientDelivery";
113113
import {type AcpMcpServer, getMcpServerName, type WithAcpMcpServers} from "./McpServerConfig";
114114
import {
115115
AUTH_STATUS_META_KEY,
@@ -488,7 +488,7 @@ export class CodexAcpServer {
488488
private codexAcpClient: CodexAcpClient;
489489
private readonly connection: AcpClientConnection;
490490
private readonly mcpServerSignIn: McpServerSignIn;
491-
private readonly reportingConnection: ToolCallReportingConnection;
491+
private readonly clientDelivery: AcpClientDelivery;
492492
/** ACP protocol version of the connection this agent serves, fixed by the protocol router. */
493493
readonly protocolVersion: 1 | 2;
494494
/** The v2 client handle; `null` on a v1 connection. */
@@ -594,19 +594,20 @@ export class CodexAcpServer {
594594
this.sessionGenerations = new Map();
595595
this.sessionOpenGenerations = new Map();
596596
this.permissionLifecycleContexts = new WeakMap();
597+
const sessionIsClosing = (id: string) => this.sessionIsClosing(this.subagentAssociations.get(id)?.rootSessionId ?? id);
597598
if (connection instanceof AcpV2Connection) {
598599
this.protocolVersion = 2;
599600
this.v2Connection = connection.client;
600-
this.reportingConnection = new ToolCallReportingConnection(connection.extensionOnlyV1View());
601-
this.connection = this.reportingConnection.asClientConnection();
601+
this.clientDelivery = new AcpClientDelivery(connection.extensionOnlyV1View(), sessionIsClosing);
602+
this.connection = this.clientDelivery.asClientConnection();
602603
connection.registerView(this.connection);
603604
// Foreground work includes adapter pauses between runtime turns, such as plan review.
604605
connection.setTurnRunningCheck((sessionId) => this.isSessionBusy(sessionId));
605606
} else {
606607
this.protocolVersion = 1;
607608
this.v2Connection = null;
608-
this.reportingConnection = new ToolCallReportingConnection(connection);
609-
this.connection = this.reportingConnection.asClientConnection();
609+
this.clientDelivery = new AcpClientDelivery(connection, sessionIsClosing);
610+
this.connection = this.clientDelivery.asClientConnection();
610611
}
611612
this.codexAcpClient = codexAcpClient;
612613
this.mcpServerSignIn = createMcpServerSignIn(
@@ -659,7 +660,7 @@ export class CodexAcpServer {
659660
const existing = this.sessions.get(sessionId)?.subagents;
660661
if (this.usesStandardSubagents() && existing instanceof StandardSubagentEventRouter && !existing.isRetired()) return existing;
661662
const session = new ACPSessionConnection(this.connection, sessionId);
662-
const release = (id: string) => this.reportingConnection.reports.releaseOpen(id);
663+
const release = (id: string) => this.clientDelivery.reports.releaseOpen(id);
663664
const models = () => {
664665
const state = this.sessions.get(sessionId);
665666
return state ? this.subagentModels(state) : null;
@@ -677,7 +678,7 @@ export class CodexAcpServer {
677678
}
678679

679680
private async readSubagentConfiguration(threadId: string, parentThreadId: string): Promise<ObservedSubagentConfiguration | null> {
680-
const {thread} = await this.codexAcpClient.appServerClient.threadRead({threadId});
681+
const thread = await this.codexAcpClient.readSubagentThread(threadId);
681682
if (!thread || thread.id !== threadId || thread.parentThreadId !== parentThreadId || thread.status.type === "notLoaded") return null;
682683
return {model: thread.model, effort: thread.reasoningEffort};
683684
}
@@ -781,7 +782,7 @@ export class CodexAcpServer {
781782
this.clientCapabilities = _params.clientCapabilities ?? null;
782783
this.initializeRequest = _params;
783784
this.capabilities = ClientCapabilities.from(_params.clientCapabilities);
784-
this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
785+
this.clientDelivery.reports.compareMeta = this.capabilities.airToolCallContract;
785786
this.booleanConfigOptionsSupported = clientSupportsBooleanConfigOptions(_params.clientCapabilities);
786787
this.sessionIndex.configure(_params.clientCapabilities);
787788
this.sessionIndex.observe(this.codexAcpClient);
@@ -843,7 +844,7 @@ export class CodexAcpServer {
843844
this.clientCapabilities = clientCapabilities;
844845
this.initializeRequest = {clientInfo: params.info};
845846
this.capabilities = ClientCapabilities.fromV2(clientCapabilities);
846-
this.reportingConnection.reports.compareMeta = this.capabilities.airToolCallContract;
847+
this.clientDelivery.reports.compareMeta = this.capabilities.airToolCallContract;
847848
// Boolean config options are baseline on v2, so there is nothing to probe.
848849
this.booleanConfigOptionsSupported = true;
849850
this.sessionIndex.configure(clientCapabilities);
@@ -1361,7 +1362,7 @@ export class CodexAcpServer {
13611362
subagents: this.createSubagentRouter(sessionId),
13621363
asyncTasks: this.createAsyncTasks(sessionId),
13631364
compactions: new CodexSessionCompactions(),
1364-
toolCallReports: this.reportingConnection.reports,
1365+
toolCallReports: this.clientDelivery.reports,
13651366
openToolCalls: new CodexSessionToolCalls(),
13661367
};
13671368
sessionState.titleGen = new TitleGenerator(
@@ -1995,17 +1996,20 @@ export class CodexAcpServer {
19951996

19961997
async closeSession(params: acp.CloseSessionRequest): Promise<acp.CloseSessionResponse> {
19971998
logger.log("Closing session...", {sessionId: params.sessionId});
1998-
const closeGeneration = this.bumpSessionGeneration(params.sessionId);
1999+
if (!this.hasLocalSession(params.sessionId)) return {};
2000+
let closeGeneration: number | null = null;
19992001
const sessionState = this.sessions.get(params.sessionId);
20002002
this.beginSessionCloseFence(params.sessionId);
20012003

20022004
try {
2005+
this.clientDelivery.cancelSessionRequests(params.sessionId);
2006+
for (const child of this.subagentAssociations.forRoot(params.sessionId)) {
2007+
this.clientDelivery.cancelSessionRequests(child.sessionId);
2008+
}
20032009
// Same as `session/cancel`: drop every v2 prompt still queued for this session first.
20042010
this.cancelQueuedV2Prompts(params.sessionId);
20052011
if (sessionState) {
20062012
await this.interruptSessionTurn(sessionState, "Close", true);
2007-
if (sessionState.subagents instanceof StandardSubagentEventRouter) await sessionState.subagents.finishOutstanding("disconnected");
2008-
sessionState.asyncTasks.clear();
20092013
sessionState.promptSuggestions?.invalidate();
20102014
} else {
20112015
logger.log("Close request received for unknown local session", {sessionId: params.sessionId});
@@ -2023,10 +2027,15 @@ export class CodexAcpServer {
20232027
// The thread is not loaded in a running app-server: nothing to close there, and no restart for it.
20242028
logger.log("Session closed without an app-server call: its app-server is gone", {sessionId: params.sessionId});
20252029
}
2030+
closeGeneration = this.bumpSessionGeneration(params.sessionId);
2031+
if (sessionState) {
2032+
if (sessionState.subagents instanceof StandardSubagentEventRouter) await sessionState.subagents.finishOutstanding("disconnected");
2033+
await sessionState.asyncTasks.finishAll("stopped");
2034+
}
20262035
await this.reportCodexTurnState(params.sessionId, {state: "idle", stopReason: "cancelled"});
20272036
logger.log("Session closed", {sessionId: params.sessionId});
20282037
} finally {
2029-
if (this.getSessionGeneration(params.sessionId) === closeGeneration) {
2038+
if (closeGeneration !== null && this.getSessionGeneration(params.sessionId) === closeGeneration) {
20302039
this.sessions.delete(params.sessionId);
20312040
this.asyncQuestions.get(params.sessionId)?.dispose();
20322041
this.asyncQuestions.delete(params.sessionId);
@@ -2041,6 +2050,7 @@ export class CodexAcpServer {
20412050
this.queuedV2PromptCancellers.delete(params.sessionId);
20422051
this.steeringQueues.delete(params.sessionId);
20432052
if (sessionState) {
2053+
sessionState.asyncTasks.clear();
20442054
this.availableCommands.cancelPendingSkillsPublish(sessionState);
20452055
}
20462056
}
@@ -3483,7 +3493,7 @@ export class CodexAcpServer {
34833493
subagents: this.createSubagentRouter(sessionId, true),
34843494
asyncTasks: this.createAsyncTasks(sessionId),
34853495
compactions: new CodexSessionCompactions(),
3486-
toolCallReports: this.reportingConnection.reports,
3496+
toolCallReports: this.clientDelivery.reports,
34873497
openToolCalls: new CodexSessionToolCalls(),
34883498
};
34893499
sessionState.titleGen = new TitleGenerator(
@@ -5480,7 +5490,7 @@ export class CodexAcpServer {
54805490

54815491
private async failUnfinishedToolCalls(sessionIds: Iterable<string>): Promise<void> {
54825492
for (const sessionId of sessionIds) {
5483-
for (const toolCallId of this.reportingConnection.reports.unfinished(sessionId)) {
5493+
for (const toolCallId of this.clientDelivery.reports.unfinished(sessionId)) {
54845494
await this.connection.notify(acp.methods.client.session.update, {
54855495
sessionId,
54865496
update: {sessionUpdate: "tool_call_update", toolCallId, status: "failed"},

‎src/CodexAppServerClient.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ import type {
102102
TurnError,
103103
} from "./app-server/v2";
104104
import type {
105+
ThreadBackgroundTerminal,
105106
ThreadBackgroundTerminalsRequest,
106107
ThreadBackgroundTerminalsTerminateParams,
107108
ThreadBackgroundTerminalsTerminateResponse,
@@ -838,6 +839,20 @@ export class CodexAppServerClient {
838839
return await this.sendRequest({method: "thread/backgroundTerminals/terminate", params});
839840
}
840841

842+
async *backgroundTerminalPages(threadId: string): AsyncGenerator<ThreadBackgroundTerminal[]> {
843+
const seen = new Set<string>();
844+
let cursor: string | null = null;
845+
do {
846+
const response = await this.threadBackgroundTerminalsList({threadId, cursor});
847+
yield response.data;
848+
cursor = response.nextCursor;
849+
if (cursor !== null) {
850+
if (seen.has(cursor)) throw new Error("Codex returned a repeated background terminal cursor");
851+
seen.add(cursor);
852+
}
853+
} while (cursor !== null);
854+
}
855+
841856
async threadGoalSet(params: ThreadGoalSetParams): Promise<ThreadGoalSetResponse> {
842857
return await this.sendRequest({ method: "thread/goal/set", params: params });
843858
}

0 commit comments

Comments
 (0)