Skip to content

Commit ad993bb

Browse files
authored
fix: defer startup interactions until session setup is delivered (#714)
## Summary - Hold session-scoped permission requests and elicitations for a freshly created or forked session until its successful setup response has actually been written. Both the shared v1-shaped path and direct v2 requests use the same delivery barrier. - Make MCP startup reporting wait on that barrier before starting OAuth. The optional MCP startup wait still only waits for native startup status or its timeout, not for a client dialog, so setup cannot deadlock on sign-in. - Hold fresh standard-child announcements behind the parent creation response using the router's existing readiness mechanism. Creation only releases readiness; it does not run resume's child snapshot refresh. - Preserve caller cancellation and discard unsent interactions on close or disconnect. Track URL completions only after the interaction passes the startup barrier, and fence stale release callbacks from later session lifetimes. - Extend the existing response-write observer to distinguish success from error responses. Error responses and failed writes do not release startup UI. - Update the existing MCP startup documentation. No review/checklist Markdown file is added. The ACP v2 session-setup recommendation says Agents SHOULD NOT send session-scoped requests before the new-session response. Checked against ACP `d5e9949c`. SDK reference `e23cc640` processes incoming requests asynchronously, so handler completion alone is not a response-delivery boundary. The adapter now uses the existing `AcpResponseDelivery` observer for this policy on both protocol versions. ## Scope This does not globally pause interactions for already-active sessions on resume. Existing replay and current-state synchronization ordering remain intact. Active-resume environment replacement, complete configuration-change notifications, and remaining session/entity metadata reconstruction are separate follow-ups. ## Validation - `npm run typecheck` - `npm run build` - `npm test`: 2,310 passed, 39 skipped - `npm run test:integration`: all 19 passed on the final run - `npm run codex-test -- -p "Reply with exactly OK. Do not use tools or modify any files." -o summary`: completed with `end_turn` - `git diff --check` - Opt-in E2E tests were not run. New wire tests exercise both ACP versions with held response writes, MCP sign-in with and without the startup timeout, fresh child announcements, and fork interactions. Delivery tests cover unrelated sessions, cancellation/close/disconnect before sending, stale release callbacks, and unsent URL completions. Existing response-boundary tests cover failed writes and error responses. The first integration run failed the existing shell-approval assertion about output in the completed tool-call update. Two subsequent full integration runs passed without changing that test.
1 parent ef45a6d commit ad993bb

11 files changed

Lines changed: 343 additions & 32 deletions

‎docs/mcp-startup-await-timeout.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ startup state (`ready`, `failed`, or `cancelled`) before the request completes.
3131

3232
| Value | Behavior |
3333
|--------------------|---------------------------------------------------------------------------------------------------------------------------------------|
34-
| `<= 0` or ommitted | Do not wait. The request completes immediately once the session is created, before any requested MCP server reaches a terminal state. |
34+
| `<= 0` or omitted | Do not wait for the requested MCP servers to reach a terminal state. |
3535
| `> 0` | Wait up to that many milliseconds for a terminal state. If the timeout elapses first, the request completes without waiting further. |
3636

3737
There is no built-in default timeout: an omitted field means do not wait
@@ -54,6 +54,9 @@ A server that starts successfully gets no report. When a server fails because it
5454
supports URL elicitation, the adapter first starts the MCP OAuth sign-in. It reports the server only if the sign-in fails.
5555
The `session/new`, `session/resume`, and `session/load` sessions get these reports. The `session/fork` sessions do not.
5656

57+
On ACP connections, reports and OAuth sign-in for a newly created session wait until its `session/new` response
58+
has been written. The optional startup wait does not wait for the sign-in.
59+
5760
To see the live status of every MCP server, send the `/mcp` command. `/mcp reconnect` reloads the MCP configuration and
5861
restarts the servers that failed, stopped, or changed.
5962

‎src/ACPSessionConnection.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,12 @@ export class AcpV2Connection {
4040
if (sessionId !== null && this.sessionDelivery && !this.sessionDelivery.canRequestSession(sessionId)) {
4141
return Promise.reject(acp.RequestError.requestCancelled(undefined, `Session ${sessionId} is closing or closed`));
4242
}
43-
const send = () => client.request(method as `_${string}`, params, options);
44-
return this.sessionDelivery?.withElicitationRequest(method, params, send) ?? send();
43+
const send = () => {
44+
const request = () => client.request(method as `_${string}`, params, options);
45+
return this.sessionDelivery?.withElicitationRequest(method, params, request) ?? request();
46+
};
47+
const setup = sessionId === null ? null : this.sessionDelivery?.waitForSessionSetup(sessionId, options?.cancellationSignal);
48+
return setup ? setup.then(send) : send();
4549
},
4650
} as AcpV2ClientConnection;
4751
}

‎src/AcpAgentRouter.ts‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,13 @@ function createRouter(
105105
const setups = new Map<string, SetupState>();
106106
const setup = <T>(sessionId: string, requestId: acpV2.JsonRpcId, operation: () => Promise<T>, signal: AbortSignal): Promise<T> => {
107107
const agent = getAgent({sessionId});
108-
if (!agent.usesStandardSubagents()) return operation();
108+
if (!agent.usesStandardSubagents()) {
109+
return operation().then(result => {
110+
const publish = agent.captureSessionSetupPublication(sessionId);
111+
responses.afterWrite(requestId, successful => { if (successful) void publish(); });
112+
return result;
113+
});
114+
}
109115
const assertCurrent = agent.captureSessionSetup(sessionId);
110116
const state = setups.get(sessionId) ?? {tail: Promise.resolve(), publication: Promise.resolve(), epoch: 0, pending: 0};
111117
setups.set(sessionId, state);
@@ -120,7 +126,7 @@ function createRouter(
120126
const response = new Promise<T>((done, failed) => { resolve = done; reject = failed; });
121127
state.tail = state.tail.catch(() => {}).then(async () => {
122128
let registered = false;
123-
let succeeded = false;
129+
let publish: (() => Promise<void>) | null = null;
124130
try {
125131
for (;;) {
126132
const publication = state.publication;
@@ -129,14 +135,14 @@ function createRouter(
129135
}
130136
if (signal.aborted) throw new acp.RequestError(-32800, "Session setup was cancelled");
131137
assertCurrent();
132-
responses.afterWrite(requestId, () => {
133-
if (epoch === state.epoch && succeeded) state.publication = agent.afterSessionSetupResponse(sessionId);
138+
responses.afterWrite(requestId, successful => {
139+
if (successful && epoch === state.epoch && publish) state.publication = publish();
134140
void state.publication.then(finish, finish);
135141
});
136142
registered = true;
137143
const result = await operation();
138144
if (signal.aborted) throw new acp.RequestError(-32800, "Session setup was cancelled");
139-
succeeded = true;
145+
publish = agent.captureSessionSetupPublication(sessionId);
140146
resolve(result);
141147
} catch (error) {
142148
reject(error);
@@ -146,10 +152,21 @@ function createRouter(
146152
// The next setup waits for delivery, not the request handler that produces the response.
147153
return response;
148154
};
155+
const createdSetup = async <T extends {sessionId: string}>(
156+
requestId: acpV2.JsonRpcId, operation: () => Promise<T>,
157+
): Promise<T> => {
158+
const agent = getAgent();
159+
const result = await operation();
160+
const publish = agent.captureSessionCreationPublication(result.sessionId);
161+
responses.afterWrite(requestId, successful => { if (successful) publish(); });
162+
return result;
163+
};
149164
const attachAgent = (agent: CodexAcpServer, signal: AbortSignal) => {
150165
codexAcpServer = agent;
166+
const stopSetupPublication = agent.observeSessionSetupResponses();
151167
signal.addEventListener("abort", () => {
152168
setups.clear();
169+
stopSetupPublication();
153170
agent.sessionIndex.dispose();
154171
if (codexAcpServer === agent) {
155172
codexAcpServer = null;
@@ -160,9 +177,9 @@ function createRouter(
160177
const v1Agent = acp.agent({name: packageJson.name})
161178
.onConnect((connection) => attachAgent(createAgent(connection.client), connection.signal))
162179
.onRequest(acp.methods.agent.initialize, (ctx) => getAgent().initialize(ctx.params))
163-
.onRequest(acp.methods.agent.session.new, (ctx) => getAgentForPaths(ctx.params).newSession(ctx.params))
180+
.onRequest(acp.methods.agent.session.new, (ctx) => createdSetup(ctx.requestId, () => getAgentForPaths(ctx.params).newSession(ctx.params)))
164181
.onRequest(acp.methods.agent.session.load, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).loadSession(ctx.params), ctx.signal))
165-
.onRequest(acp.methods.agent.session.fork, (ctx) => getAgentForPaths(ctx.params).forkSession(ctx.params))
182+
.onRequest(acp.methods.agent.session.fork, (ctx) => createdSetup(ctx.requestId, () => getAgentForPaths(ctx.params).forkSession(ctx.params)))
166183
.onRequest(acp.methods.agent.session.list, (ctx) => getAgentForPaths({cwd: ctx.params.cwd ?? null}).listSessions(ctx.params))
167184
.onRequest(acp.methods.agent.session.delete, (ctx) => getAgent(ctx.params).deleteSession(ctx.params))
168185
.onRequest(acp.methods.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).resumeSession(ctx.params), ctx.signal))
@@ -195,11 +212,11 @@ function createRouter(
195212
.onConnect((connection) => attachAgent(createAgent(new AcpV2Connection(connection.client)), connection.signal))
196213
.onRequest(acpV2.methods.agent.initialize, (ctx) => getAgent().initializeV2(ctx.params))
197214
// No `session/load`: v2 folds it into `session/resume` with `replayFrom`.
198-
.onRequest(acpV2.methods.agent.session.new, (ctx) => getAgentForPaths(ctx.params).newSessionV2(ctx.params))
215+
.onRequest(acpV2.methods.agent.session.new, (ctx) => createdSetup(ctx.requestId, () => getAgentForPaths(ctx.params).newSessionV2(ctx.params)))
199216
.onRequest(acpV2.methods.agent.session.list, (ctx) => getAgentForPaths({cwd: ctx.params.cwd ?? null}).listSessions(ctx.params))
200217
.onRequest(acpV2.methods.agent.session.delete, (ctx) => getAgent(ctx.params).deleteSession(ctx.params))
201218
.onRequest(acpV2.methods.agent.session.resume, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).resumeSessionV2(ctx.params), ctx.signal))
202-
.onRequest(acpV2.methods.agent.session.fork, (ctx) => getAgentForPaths(ctx.params).forkSessionV2(ctx.params))
219+
.onRequest(acpV2.methods.agent.session.fork, (ctx) => createdSetup(ctx.requestId, () => getAgentForPaths(ctx.params).forkSessionV2(ctx.params)))
203220
.onRequest(acpV2.methods.agent.session.close, (ctx) => getAgent(ctx.params).closeSession(ctx.params))
204221
// No `session/set_mode`: v2 removed the modes API; modes are config options.
205222
.onRequest(acpV2.methods.agent.session.setConfigOption, (ctx) => getAgent(ctx.params).setSessionConfigOptionV2(ctx.params))

‎src/AcpClientDelivery.ts‎

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export class AcpClientDelivery {
1515
private readonly sessionRequests = new Map<string, Set<AbortController>>();
1616
private readonly closedSessions = new Set<string>();
1717
private readonly urlElicitations = new Map<string, {sessionId: string | null}>();
18+
private readonly sessionSetups = new Map<string, {ready: Promise<void>; release: () => void}>();
1819
private sendElicitationCompletion: (params: unknown) => Promise<void>;
1920

2021
constructor(
@@ -38,9 +39,57 @@ export class AcpClientDelivery {
3839
this.closedSessions.delete(sessionId);
3940
}
4041

42+
/** A new session cannot open client UI until its setup response has been written. */
43+
beginSessionSetup(sessionId: string): void {
44+
if (this.sessionSetups.has(sessionId)) return;
45+
let release!: () => void;
46+
const ready = new Promise<void>(resolve => { release = resolve; });
47+
this.sessionSetups.set(sessionId, {ready, release});
48+
}
49+
50+
sessionSetupReady(sessionId: string): Promise<void> | null {
51+
return this.sessionSetups.get(sessionId)?.ready ?? null;
52+
}
53+
54+
captureSessionSetupRelease(sessionId: string): () => void {
55+
const setup = this.sessionSetups.get(sessionId);
56+
return () => {
57+
if (setup && this.sessionSetups.get(sessionId) === setup) this.finishSessionSetup(sessionId);
58+
};
59+
}
60+
61+
private finishSessionSetup(sessionId: string): void {
62+
const setup = this.sessionSetups.get(sessionId);
63+
this.sessionSetups.delete(sessionId);
64+
setup?.release();
65+
}
66+
67+
waitForSessionSetup(sessionId: string, signal?: AbortSignal): Promise<void> | null {
68+
const ready = this.sessionSetupReady(sessionId);
69+
if (!ready) return null;
70+
return new Promise<void>((resolve, reject) => {
71+
const cancelled = () => reject(acp.RequestError.requestCancelled(undefined, `Session ${sessionId} setup was cancelled`));
72+
if (signal?.aborted) { cancelled(); return; }
73+
signal?.addEventListener("abort", cancelled, {once: true});
74+
void ready.then(() => {
75+
signal?.removeEventListener("abort", cancelled);
76+
if (signal?.aborted || !this.canRequestSession(sessionId)) cancelled();
77+
else resolve();
78+
});
79+
});
80+
}
81+
82+
disposeSessionSetups(): void {
83+
for (const sessionId of this.sessionSetups.keys()) {
84+
this.closedSessions.add(sessionId);
85+
this.cancelSessionRequests(sessionId);
86+
}
87+
}
88+
4189
/** Final teardown updates have been sent. Nothing else may publish for this session lifetime. */
4290
closeSession(sessionId: string): void {
4391
this.closedSessions.add(sessionId);
92+
this.finishSessionSetup(sessionId);
4493
for (const [id, scope] of this.urlElicitations) {
4594
if (scope.sessionId === sessionId) this.urlElicitations.delete(id);
4695
}
@@ -103,13 +152,14 @@ export class AcpClientDelivery {
103152
for (const controller of this.sessionRequests.get(sessionId) ?? []) {
104153
controller.abort(acp.RequestError.requestCancelled(undefined, `Session ${sessionId} is closing`));
105154
}
155+
this.finishSessionSetup(sessionId);
106156
}
107157

108158
private sendRequest(method: string, params: unknown, options?: acp.SendRequestOptions): Promise<unknown> {
109159
const sessionId = clientRequestSessionId(method, params);
110-
return this.withElicitationRequest(method, params, () => sessionId === null
111-
? this.client.request(method, params, options)
112-
: this.sendSessionRequest(sessionId, method, params, options));
160+
return sessionId === null
161+
? this.withElicitationRequest(method, params, () => this.client.request(method, params, options))
162+
: this.sendSessionRequest(sessionId, method, params, options);
113163
}
114164

115165
/** Direct v2 requests and the shared v1-shaped path keep the same URL scope. */
@@ -145,7 +195,10 @@ export class AcpClientDelivery {
145195
? AbortSignal.any([options.cancellationSignal, controller.signal])
146196
: controller.signal;
147197
try {
148-
return await this.client.request(method, params, {...options, cancellationSignal});
198+
const setup = this.waitForSessionSetup(sessionId, cancellationSignal);
199+
if (setup) await setup;
200+
return await this.withElicitationRequest(method, params,
201+
() => this.client.request(method, params, {...options, cancellationSignal}));
149202
} finally {
150203
requests.delete(controller);
151204
if (requests.size === 0) this.sessionRequests.delete(sessionId);

‎src/AcpResponseDelivery.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ import type {AnyMessage, JsonRpcId, Stream} from "@agentclientprotocol/sdk/exper
22

33
/** Observe completed response writes without changing SDK framing. */
44
export class AcpResponseDelivery {
5-
private readonly callbacks = new Map<JsonRpcId, () => void>();
5+
private readonly callbacks = new Map<JsonRpcId, (successful: boolean) => void>();
66
private disposed = false;
77

8-
afterWrite(requestId: JsonRpcId, callback: () => void): void {
8+
afterWrite(requestId: JsonRpcId, callback: (successful: boolean) => void): void {
99
if (!this.disposed) this.callbacks.set(requestId, callback);
1010
}
1111

@@ -20,7 +20,7 @@ export class AcpResponseDelivery {
2020
if ("method" in message || message.id === null) return;
2121
const callback = this.callbacks.get(message.id);
2222
this.callbacks.delete(message.id);
23-
callback?.();
23+
callback?.("result" in message);
2424
},
2525
close: async () => {
2626
const writer = stream.writable.getWriter();

‎src/CodexAcpServer.ts‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,7 @@ export class CodexAcpServer {
489489
private readonly connection: AcpClientConnection;
490490
private readonly mcpServerSignIn: McpServerSignIn;
491491
private readonly clientDelivery: AcpClientDelivery;
492+
private setupResponseOrdering = false;
492493
/** ACP protocol version of the connection this agent serves, fixed by the protocol router. */
493494
readonly protocolVersion: 1 | 2;
494495
/** The v2 client handle; `null` on a v1 connection. */
@@ -623,6 +624,7 @@ export class CodexAcpServer {
623624
this.mcpServerSignIn,
624625
() => this.capabilities,
625626
(sessionId) => this.sessions.has(sessionId) && !this.sessionIsClosing(sessionId),
627+
(sessionId, signal) => this.clientDelivery.waitForSessionSetup(sessionId, signal),
626628
);
627629
this.defaultAuthRequest = defaultAuthRequest ?? null;
628630
this.codexProcessState = codexProcessState ?? null;
@@ -666,9 +668,12 @@ export class CodexAcpServer {
666668
const state = this.sessions.get(sessionId);
667669
return state ? this.subagentModels(state) : null;
668670
};
671+
const setupReady = this.clientDelivery.sessionSetupReady(sessionId);
672+
const transition = this.sessions.get(sessionId)?.subagentTransition;
673+
const ready = setupReady ? Promise.all([setupReady, transition]).then(() => {}) : transition;
669674
const router = this.usesStandardSubagents()
670675
? new StandardSubagentEventRouter(sessionId, session, this.subagentAssociations, release, this.capabilities, replay,
671-
this.sessions.get(sessionId)?.subagentTransition,
676+
ready,
672677
id => this.codexAcpClient.appServerClient.runningTurnId(id), models, {
673678
read: (id, parent) => this.readSubagentConfiguration(id, parent),
674679
enqueuePublication: publish => this.codexAcpClient.enqueueSessionTransition(sessionId, publish),
@@ -743,13 +748,32 @@ export class CodexAcpServer {
743748
return check;
744749
}
745750

746-
afterSessionSetupResponse(sessionId: string): Promise<void> {
747-
const router = this.sessions.get(sessionId)?.subagents;
748-
if (!(router instanceof StandardSubagentEventRouter) || this.sessionIsClosing(sessionId)) return Promise.resolve();
749-
this.codexAcpClient.redispatchSessionNotifications(sessionId, router.releaseReplay(), () => router.publishReplaySnapshots());
750-
return this.codexAcpClient.waitForSessionNotifications(sessionId).catch(error => {
751-
logger.error("Failed to release child traffic after session setup", error);
752-
});
751+
/** Direct method callers have no transport response-write boundary. */
752+
observeSessionSetupResponses(): () => void {
753+
this.setupResponseOrdering = true;
754+
return () => {
755+
this.mcpSessionStartup.dispose();
756+
this.clientDelivery.disposeSessionSetups();
757+
};
758+
}
759+
760+
captureSessionCreationPublication(sessionId: string): () => void {
761+
return this.clientDelivery.captureSessionSetupRelease(sessionId);
762+
}
763+
764+
captureSessionSetupPublication(sessionId: string): () => Promise<void> {
765+
const session = this.sessions.get(sessionId);
766+
const release = this.clientDelivery.captureSessionSetupRelease(sessionId);
767+
return async () => {
768+
release();
769+
if (!session || this.sessions.get(sessionId) !== session || this.sessionIsClosing(sessionId)) return;
770+
const router = session.subagents;
771+
if (!(router instanceof StandardSubagentEventRouter)) return;
772+
this.codexAcpClient.redispatchSessionNotifications(sessionId, router.releaseReplay(), () => router.publishReplaySnapshots());
773+
await this.codexAcpClient.waitForSessionNotifications(sessionId).catch(error => {
774+
logger.error("Failed to release child traffic after session setup", error);
775+
});
776+
};
753777
}
754778

755779
private async interruptStandardChildren(session: SessionState): Promise<void> {
@@ -1338,6 +1362,7 @@ export class CodexAcpServer {
13381362
const sessionMcpServers = this.resolveSessionMcpServers(requestedMcpServers, operation === "resume");
13391363
const currentModel = this.findCurrentModel(models, currentModelId);
13401364
const currentModelSupportsFast = modelSupportsFast(currentModel);
1365+
if (this.setupResponseOrdering && operation !== "resume") this.clientDelivery.beginSessionSetup(sessionId);
13411366
const sessionState: SessionState = {
13421367
sessionId: sessionId,
13431368
currentModelId: currentModelId,

0 commit comments

Comments
 (0)