Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(mcp-oauth): settle the login when the token exchange fails after the callback

liuzixiang4ac79d7f98ea
diff --git a/apps/desktop/electron/main/mcp-oauth.ts b/apps/desktop/electron/main/mcp-oauth.ts
index 68c5158eb..440d9cf84 100644
--- a/apps/desktop/electron/main/mcp-oauth.ts
+++ b/apps/desktop/electron/main/mcp-oauth.ts
@@ -483,6 +483,14 @@ export class McpOAuthManager {
await new Promise<void>((resolve, reject) => {
let settled = false;
+ // A valid callback state has been consumed. Kept separate from
+ // `settled`: consuming the state starts the token exchange, whose
+ // awaits can still fail — latching `settled` here used to route those
+ // failures into the `if (!settled)` catch below, which swallowed them.
+ // The login then hung forever on the unresolved promise: no timeout,
+ // no cancel, no loopback shutdown, and every later `start()` for the
+ // same server deadlocked awaiting `finished`.
+ let stateConsumed = false;
const codeVerifier = randomBytes(32).toString("base64url");
const codeChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
const expectedState = randomBytes(16).toString("hex");
@@ -514,7 +522,7 @@ export class McpOAuthManager {
return;
}
- if (settled) {
+ if (stateConsumed) {
res.writeHead(409, { "content-type": "text/html; charset=utf-8" });
res.end(this.renderHtml(false, "Authorization already completed"));
return;
@@ -538,7 +546,7 @@ export class McpOAuthManager {
return;
}
- settled = true;
+ stateConsumed = true;
if (error) {
const displayErr = errorDescription ? `${error}: ${errorDescription}` : error;
@@ -636,14 +644,22 @@ export class McpOAuthManager {
),
);
- resolveToken(storedToken);
- resolve();
+ finish(undefined, storedToken);
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
- if (!settled) {
- settled = true;
- rejectToken(error);
- reject(error);
+ // A failure after the state was consumed (token endpoint down,
+ // non-JSON body, secret store unavailable) must still settle the
+ // login: `finish` no-ops only when the timeout or a cancel
+ // already decided the outcome. Without this, the awaited promise
+ // never settles and the loopback server leaks with the login
+ // stuck, deadlocking later logins for the same server.
+ finish(error);
+ try {
+ res.writeHead(500, { "content-type": "text/html; charset=utf-8" });
+ res.end(this.renderHtml(false, `Authorization failed: ${error.message}`));
+ } catch {
+ // The response socket may already be gone; the rejection above
+ // is what matters.
}
}
});
diff --git a/apps/desktop/test/mcp-oauth.test.mjs b/apps/desktop/test/mcp-oauth.test.mjs
index 9b07cc9fd..a7096fdb6 100644
--- a/apps/desktop/test/mcp-oauth.test.mjs
+++ b/apps/desktop/test/mcp-oauth.test.mjs
@@ -1027,3 +1027,61 @@ test("McpOAuthManager: a server without DCR fails loudly instead of opening a de
event.kind === "error" && event.errorCode === "MCP_OAUTH_DCR_UNAVAILABLE",
));
});
+
+test("McpOAuthManager: a failure after the callback still settles the login", async (t) => {
+ // The callback handler consumed the state and then awaited the token
+ // endpoint and the secret write. A throw there used to fall into a catch
+ // gated on the same settled flag the callback had already latched, so the
+ // login never settled: no error event, no timeout, no cancel, the loopback
+ // server stayed open, and every later start() for this server deadlocked
+ // awaiting `finished`. Here the secret store rejects.
+ const host = fakeHost();
+ const { mockFetch } = createMockFetch();
+ const { mockCreateServer, simulateCallback, isClosed } = createMockServerFactory();
+ const events = [];
+ let openedUrl = null;
+ let secretWrites = 0;
+ const manager = new McpOAuthManager({
+ call: async (method, params) => {
+ if (method === "secrets.set") {
+ secretWrites += 1;
+ throw new Error("secret store unavailable");
+ }
+ return host.call(method, params);
+ },
+ fetchImpl: mockFetch,
+ createServer: mockCreateServer,
+ emit: (event) => events.push(event),
+ openExternal: async (url) => {
+ openedUrl = url;
+ },
+ });
+ t.after(() => manager.disposeAll());
+
+ const startResult = await manager.start("exchange-throw", "https://notion.test/mcp");
+ assert.equal(startResult.ok, true);
+ for (let i = 0; i < 50; i++) {
+ if (openedUrl) break;
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ assert.ok(openedUrl, "the authorization URL should open");
+ const state = new URL(openedUrl).searchParams.get("state");
+ assert.ok(state);
+
+ const callbackRes = await simulateCallback(`/callback?code=valid-code&state=${encodeURIComponent(state)}`);
+ assert.equal(callbackRes.statusCode, 500, "the browser gets a failure page, not a hang");
+ assert.ok(callbackRes.body.includes("Authorization failed"));
+
+ // The rejection must reach the run loop: an error event, a closed loopback
+ // server, and a login that a later start() can move past.
+ await waitUntil(() => events.some((event) => event.kind === "error"));
+ const errorEvent = events.find((event) => event.kind === "error");
+ assert.match(errorEvent.message, /secret store unavailable/);
+ assert.equal(secretWrites, 1);
+ await waitUntil(() => isClosed());
+ assert.equal(isClosed(), true, "the loopback server is shut down");
+
+ const restart = await manager.start("exchange-throw", "https://notion.test/mcp");
+ assert.equal(restart.ok, true, "a retry after the failure must not deadlock");
+ assert.notEqual(restart.loginId, startResult.loginId);
+});