Skip to content

Commit e059ab7

Browse files
authored
fix: scope authentication cancellation and initial status delivery (#720)
## Summary Continues the original SDK 2.2 audit (specification baseline `d5e9949c3e6a9cd072adebaa44e6f63289590c17`). Later specification changes remain out of scope. - Pass request cancellation from both ACP routers through login and its request-scoped URL interaction. Withdraw pending URL requests or complete accepted dialogs before the cancelled login response. - Serialize account authentication attempts. Keep ownership of a pending native start until its returned login ID can be cancelled, filter interactive completions by that ID, and drain cancelled API-key completions before another attempt starts (native API-key completions have no ID). - Return `-32000` when the user declines/abandons the login dialog. Reserve `-32800` for cancellation of the parent request. - Publish initial auth status at the successful initialize-response write boundary, including when the write is backpressured. Hold early native account updates until then. Direct in-process callers retain their asynchronous fallback. - Add dual-version wire coverage for held initialization, cancellation before native start returns, pending/accepted dialogs, disconnect, late completions, and API-key completion ownership. Make the wire harness close its transport as well as its client and dispatch registered native notification handlers. ## Validation - `npm run typecheck`: passed - `npm run build`: passed - `npm test`: 2,381 passed, 39 skipped - `npm run test:integration`: all 19 passed - `npm run codex-test -- -p "Reply with exactly OK. Do not use tools or modify any files." -o summary`: `end_turn` - `git diff --check`: passed Interactive login cancellation is tested over both real ACP wire paths with a mocked native app-server. Validation did not log out, replace credentials, or run an interactive real-account login. Opt-in E2E tests were not run. A cancelled API-key request cannot roll back native credential changes already made; its completion remains owned and drained before a subsequent login. ## Remaining scope This closes the auth cancellation and initial-auth ordering items only. The other original 2.2 follow-ups continue separately. No new review Markdown file is included.
1 parent 7d7e95a commit e059ab7

10 files changed

Lines changed: 418 additions & 122 deletions

‎src/AcpAgentRouter.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ function createRouter(
163163
};
164164
const attachAgent = (agent: CodexAcpServer, signal: AbortSignal) => {
165165
codexAcpServer = agent;
166+
agent.observeInitializeResponse();
166167
const stopSetupPublication = agent.observeSessionSetupResponses();
167168
signal.addEventListener("abort", () => {
168169
setups.clear();
@@ -174,9 +175,16 @@ function createRouter(
174175
});
175176
};
176177

178+
const initialize = async <T>(requestId: acp.JsonRpcId, operation: () => Promise<T>): Promise<T> => {
179+
const agent = getAgent();
180+
const result = await operation();
181+
responses.afterWrite(requestId, successful => { if (successful) agent.afterInitializeResponse(); });
182+
return result;
183+
};
184+
177185
const v1Agent = acp.agent({name: packageJson.name})
178186
.onConnect((connection) => attachAgent(createAgent(connection.client), connection.signal))
179-
.onRequest(acp.methods.agent.initialize, (ctx) => getAgent().initialize(ctx.params))
187+
.onRequest(acp.methods.agent.initialize, (ctx) => initialize(ctx.requestId, () => getAgent().initialize(ctx.params)))
180188
.onRequest(acp.methods.agent.session.new, (ctx) => createdSetup(ctx.requestId, () => getAgentForPaths(ctx.params).newSession(ctx.params)))
181189
.onRequest(acp.methods.agent.session.load, (ctx) => setup(ctx.params.sessionId, ctx.requestId, () => getAgentForPaths(ctx.params).loadSession(ctx.params), ctx.signal))
182190
.onRequest(acp.methods.agent.session.fork, (ctx) => createdSetup(ctx.requestId, () => getAgentForPaths(ctx.params).forkSession(ctx.params)))
@@ -186,7 +194,7 @@ function createRouter(
186194
.onRequest(acp.methods.agent.session.close, (ctx) => getAgent(ctx.params).closeSession(ctx.params))
187195
.onRequest(acp.methods.agent.session.setMode, (ctx) => getAgent(ctx.params).setSessionMode(ctx.params))
188196
.onRequest(acp.methods.agent.session.setConfigOption, (ctx) => getAgent(ctx.params).setSessionConfigOption(ctx.params))
189-
.onRequest(acp.methods.agent.authenticate, (ctx) => getAgent().authenticate(ctx.params, ctx.requestId))
197+
.onRequest(acp.methods.agent.authenticate, (ctx) => getAgent().authenticate(ctx.params, ctx.requestId, ctx.signal))
190198
.onRequest(acp.methods.agent.logout, (ctx) => getAgent().logout(ctx.params))
191199
.onRequest(acp.methods.agent.providers.list, (ctx) => getAgent().listProviders(ctx.params))
192200
.onRequest(acp.methods.agent.providers.set, (ctx) => getAgent().setProvider(ctx.params))
@@ -210,7 +218,7 @@ function createRouter(
210218

211219
const v2Agent = acpV2.agent({name: packageJson.name})
212220
.onConnect((connection) => attachAgent(createAgent(new AcpV2Connection(connection.client)), connection.signal))
213-
.onRequest(acpV2.methods.agent.initialize, (ctx) => getAgent().initializeV2(ctx.params))
221+
.onRequest(acpV2.methods.agent.initialize, (ctx) => initialize(ctx.requestId, () => getAgent().initializeV2(ctx.params)))
214222
// No `session/load`: v2 folds it into `session/resume` with `replayFrom`.
215223
.onRequest(acpV2.methods.agent.session.new, (ctx) => createdSetup(ctx.requestId, () => getAgentForPaths(ctx.params).newSessionV2(ctx.params)))
216224
.onRequest(acpV2.methods.agent.session.list, (ctx) => getAgentForPaths({cwd: ctx.params.cwd ?? null}).listSessions(ctx.params))
@@ -221,7 +229,7 @@ function createRouter(
221229
// No `session/set_mode`: v2 removed the modes API; modes are config options.
222230
.onRequest(acpV2.methods.agent.session.setConfigOption, (ctx) => getAgent(ctx.params).setSessionConfigOptionV2(ctx.params))
223231
// The v1-only `authentication/status|logout` extensions are not registered on v2.
224-
.onRequest(acpV2.methods.agent.auth.login, (ctx) => getAgent().authenticateV2(ctx.params, ctx.requestId))
232+
.onRequest(acpV2.methods.agent.auth.login, (ctx) => getAgent().authenticateV2(ctx.params, ctx.requestId, ctx.signal))
225233
.onRequest(acpV2.methods.agent.auth.logout, (ctx) => getAgent().logoutV2(ctx.params))
226234
.onRequest(acpV2.methods.agent.session.prompt, (ctx) => getAgent(ctx.params).promptV2(ctx.params, ctx.signal))
227235
.onNotification(acpV2.methods.agent.session.cancel, (ctx) => getAgent().cancel(ctx.params))

‎src/CodexAccountLogin.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import type {CodexAppServerClient} from "./CodexAppServerClient";
2+
import type {AccountLoginCompletedNotification, LoginAccountParams, LoginAccountResponse} from "./app-server/v2";
3+
import {throwIfRequestCancelled, withRequestCancellation} from "./RequestCancellation";
4+
import {logger} from "./Logger";
5+
6+
/** One native login owns its completion listener and any interactive login ID. */
7+
export async function runAccountLogin(
8+
client: CodexAppServerClient,
9+
params: LoginAccountParams,
10+
show: (response: LoginAccountResponse) => Promise<boolean>,
11+
signal?: AbortSignal,
12+
): Promise<boolean> {
13+
throwIfRequestCancelled(signal);
14+
let expectedId: string | null | undefined;
15+
const buffered: AccountLoginCompletedNotification[] = [];
16+
let complete!: (event: AccountLoginCompletedNotification) => void;
17+
let endWait!: (error: Error) => void;
18+
const notified = new Promise<AccountLoginCompletedNotification>((resolve, reject) => {
19+
complete = resolve;
20+
endWait = reject;
21+
});
22+
const accept = (event: AccountLoginCompletedNotification) => {
23+
if (expectedId === undefined) buffered.push(event);
24+
else if ((event.loginId ?? null) === expectedId) complete(event);
25+
};
26+
const listener = client.connection.onNotification("account/login/completed", accept);
27+
const completed = client.waitWhileConnected("account/login/completed", notified);
28+
void completed.catch(() => {});
29+
let response: LoginAccountResponse | null = null;
30+
let finished = false;
31+
try {
32+
// Keep ownership until a late start response can be cancelled by its own ID.
33+
response = await client.accountLogin(params);
34+
expectedId = "loginId" in response ? response.loginId : null;
35+
for (const event of buffered) accept(event);
36+
buffered.length = 0;
37+
throwIfRequestCancelled(signal);
38+
const first = await withRequestCancellation(Promise.race([
39+
completed.then(result => ({type: "completed" as const, result})),
40+
show(response).then(accepted => ({type: "shown" as const, accepted})),
41+
]), signal);
42+
if (first.type === "completed") {
43+
finished = true;
44+
return first.result.success;
45+
}
46+
if (!first.accepted) return false;
47+
const result = await withRequestCancellation(completed, signal);
48+
finished = true;
49+
return result.success;
50+
} finally {
51+
if (!finished && response && "loginId" in response) {
52+
await client.accountLoginCancel({loginId: response.loginId}).catch(error => {
53+
logger.error("Failed to cancel Codex account login", error);
54+
});
55+
} else if (signal?.aborted && response && expectedId === null) {
56+
// API-key completions have no ID. Drain this one before another login can start.
57+
await completed.catch(() => {});
58+
}
59+
endWait(new Error("Account login has ended"));
60+
listener.dispose();
61+
}
62+
}

‎src/CodexAcpClient.ts‎

Lines changed: 45 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
type ApiKeyAuthRequest,
33
CODEX_API_KEY_ENV_VAR,
4+
type CodexAuthRequest,
45
GatewayAuthMethod,
56
type GatewayAuthRequest,
67
isCodexAuthRequest,
@@ -32,7 +33,6 @@ import {isAccountReadAuthFailureError, isAccountReadUnavailableError} from "./Co
3233
import {listedSessionTitle, normalizeSessionTitle} from "./SessionTitle";
3334
import {type AcpMcpServer, type WithAcpMcpServers, normalizeMcpServers, toCodexMcpServerConfig} from "./McpServerConfig";
3435
import type {
35-
AccountLoginCompletedNotification,
3636
AccountUpdatedNotification,
3737
GetAccountRateLimitsResponse,
3838
GetAccountResponse,
@@ -66,6 +66,8 @@ import {arePathBasenamesEqual, arePathsEqual, isAbsolutePathLike, isAbsoluteProt
6666
import {CodexSubagentSubscriptions} from "./subagents/CodexSubagentSubscriptions";
6767
import {forkSession as runForkSession} from "./SessionFork";
6868
import type {SessionMetadata, SessionMetadataWithThread} from "./SessionMetadata";
69+
import {runAccountLogin} from "./CodexAccountLogin";
70+
import {throwIfRequestCancelled, withRequestCancellation} from "./RequestCancellation";
6971
import {
7072
isMissingRolloutError,
7173
isThreadNotMaterializedError,
@@ -162,7 +164,7 @@ export class CodexAcpClient {
162164
* routing). `authStatus` reports only the agent-owned one.
163165
*/
164166
private gatewayConfigSource: GatewayConfigSource | null;
165-
private pendingLoginCompleted: Promise<AccountLoginCompletedNotification> | null = null;
167+
private authenticationTail = Promise.resolve();
166168
private pendingAccountUpdated: Promise<AccountUpdatedNotification> | null = null;
167169
private readonly sessionNotificationQueues = new Map<string, Promise<void>>();
168170
private readonly subagents: CodexSubagentSubscriptions;
@@ -232,51 +234,55 @@ export class CodexAcpClient {
232234
return this.configPath;
233235
}
234236

235-
async authenticate(
237+
authenticate(
236238
authRequest: acp.AuthenticateRequest,
237239
urlElicitationRequester?: UrlElicitationRequester,
238-
): Promise<Boolean> {
240+
signal?: AbortSignal,
241+
): Promise<boolean> {
239242
if (!isCodexAuthRequest(authRequest)) {
240-
throw RequestError.invalidParams();
243+
return Promise.reject(RequestError.invalidParams());
241244
}
245+
const run = this.authenticationTail.then(() => this.authenticateOnce(authRequest, urlElicitationRequester, signal));
246+
this.authenticationTail = run.then(() => {}, () => {});
247+
return withRequestCancellation(run, signal);
248+
}
249+
250+
private async authenticateOnce(
251+
authRequest: CodexAuthRequest,
252+
urlElicitationRequester?: UrlElicitationRequester,
253+
signal?: AbortSignal,
254+
): Promise<boolean> {
255+
throwIfRequestCancelled(signal);
242256
this.gatewayConfig = null;
243257
this.gatewayConfigSource = null;
244258
switch (authRequest.methodId) {
245259
case "api-key":
246-
return await this.authenticateWithApiKey(authRequest);
260+
return await this.authenticateWithApiKey(authRequest, signal);
247261
case "chat-gpt":
248-
return await this.authenticateWithChatGpt();
262+
return await this.authenticateWithChatGpt(signal);
249263
case "chat-gpt-device-code":
250-
return await this.authenticateWithChatGptDeviceCode(urlElicitationRequester);
264+
return await this.authenticateWithChatGptDeviceCode(urlElicitationRequester, signal);
251265
case "gateway":
252266
return this.authenticateWithGateway(authRequest);
253267
}
254268
}
255269

256-
private async authenticateWithApiKey(authRequest: ApiKeyAuthRequest): Promise<Boolean> {
270+
private async authenticateWithApiKey(authRequest: ApiKeyAuthRequest, signal?: AbortSignal): Promise<boolean> {
257271
const apiKey = authRequest._meta?.["api-key"]?.apiKey ?? this.readApiKeyFromEnv();
258-
const loginCompletedPromise = this.awaitNextLoginCompleted();
259-
loginCompletedPromise.catch(() => {});
260-
await this.codexClient.accountLogin({
261-
type: "apiKey",
262-
apiKey,
263-
});
264-
const result = await loginCompletedPromise;
265-
return result.success;
272+
return runAccountLogin(this.codexClient, {type: "apiKey", apiKey}, async () => true, signal);
266273
}
267274

268-
private async authenticateWithChatGpt(): Promise<Boolean> {
275+
private async authenticateWithChatGpt(signal?: AbortSignal): Promise<boolean> {
269276
if (await this.hasWorkingChatGptLogin()) {
277+
throwIfRequestCancelled(signal);
270278
return true;
271279
}
272-
const loginCompletedPromise = this.awaitNextLoginCompleted();
273-
loginCompletedPromise.catch(() => {});
274-
const loginResponse = await this.codexClient.accountLogin({type: "chatgpt"});
275-
if (loginResponse.type == "chatgpt") {
276-
await open(loginResponse.authUrl);
277-
}
278-
const result = await loginCompletedPromise;
279-
return result.success;
280+
return runAccountLogin(this.codexClient, {type: "chatgpt"}, async response => {
281+
if (response.type !== "chatgpt") return false;
282+
throwIfRequestCancelled(signal);
283+
await open(response.authUrl);
284+
return true;
285+
}, signal);
280286
}
281287

282288
/**
@@ -304,58 +310,26 @@ export class CodexAcpClient {
304310
}
305311
}
306312

307-
private async authenticateWithChatGptDeviceCode(urlElicitationRequester?: UrlElicitationRequester): Promise<Boolean> {
313+
private async authenticateWithChatGptDeviceCode(urlElicitationRequester?: UrlElicitationRequester, signal?: AbortSignal): Promise<boolean> {
308314
if (await this.hasWorkingChatGptLogin()) {
315+
throwIfRequestCancelled(signal);
309316
return true;
310317
}
311318
if (!urlElicitationRequester) {
312319
throw RequestError.invalidRequest(undefined, "Device code authentication requires URL elicitation support");
313320
}
314-
const loginCompletedPromise = this.awaitNextLoginCompleted();
315-
loginCompletedPromise.catch(() => {});
316-
const loginResponse = await this.codexClient.accountLogin({type: "chatgptDeviceCode"});
317-
if (loginResponse.type !== "chatgptDeviceCode") {
318-
return false;
319-
}
320-
const elicitationResponsePromise = Promise.resolve(urlElicitationRequester.elicitUrl({
321-
url: loginResponse.verificationUrl,
322-
message: `Sign in to ChatGPT and enter this code: ${loginResponse.userCode}`,
323-
elicitationId: loginResponse.loginId,
324-
}));
325321
try {
326-
const first = await Promise.race([
327-
loginCompletedPromise.then(result => ({
328-
type: "loginCompleted" as const,
329-
result,
330-
})),
331-
elicitationResponsePromise.then(response => ({
332-
type: "elicitationResponse" as const,
333-
response,
334-
})),
335-
]);
336-
337-
if (first.type === "loginCompleted") {
338-
await urlElicitationRequester.completeElicitation();
339-
return first.result.success;
340-
}
341-
342-
if (!acp.CreateElicitationResponse.isAccept(first.response)) {
343-
await this.codexClient.accountLoginCancel({loginId: loginResponse.loginId});
344-
throw RequestError.requestCancelled(
345-
{methodId: "chat-gpt-device-code", action: first.response.action},
346-
"ChatGPT device code sign-in was cancelled",
347-
);
348-
}
349-
350-
const result = await loginCompletedPromise;
351-
await urlElicitationRequester.completeElicitation();
352-
return result.success;
353-
} catch (error) {
354-
// A lost app-server ends the login: the open URL elicitation must not stay open in the client.
355-
if (this.codexClient.connectionLoss.lost) {
356-
await Promise.resolve(urlElicitationRequester.completeElicitation()).catch(() => {});
357-
}
358-
throw error;
322+
return await runAccountLogin(this.codexClient, {type: "chatgptDeviceCode"}, async response => {
323+
if (response.type !== "chatgptDeviceCode") return false;
324+
const answer = await urlElicitationRequester.elicitUrl({
325+
url: response.verificationUrl,
326+
message: `Sign in to ChatGPT and enter this code: ${response.userCode}`,
327+
elicitationId: response.loginId,
328+
});
329+
return acp.CreateElicitationResponse.isAccept(answer);
330+
}, signal);
331+
} finally {
332+
await urlElicitationRequester.completeElicitation().catch(() => {});
359333
}
360334
}
361335

@@ -1413,21 +1387,6 @@ export class CodexAcpClient {
14131387
return withoutUnsupportedSkills(await this.codexClient.listSkills(params ?? {}));
14141388
}
14151389

1416-
private async awaitNextLoginCompleted(): Promise<AccountLoginCompletedNotification> {
1417-
if (this.pendingLoginCompleted !== null) {
1418-
return await this.pendingLoginCompleted;
1419-
}
1420-
this.pendingLoginCompleted = this.awaitSingleNotification(
1421-
"account/login/completed",
1422-
(event: AccountLoginCompletedNotification) => event,
1423-
);
1424-
try {
1425-
return await this.pendingLoginCompleted;
1426-
} finally {
1427-
this.pendingLoginCompleted = null;
1428-
}
1429-
}
1430-
14311390
private async awaitNextAccountUpdated(): Promise<AccountUpdatedNotification> {
14321391
if (this.pendingAccountUpdated !== null) {
14331392
return await this.pendingAccountUpdated;

0 commit comments

Comments
 (0)