Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(settings): make OpenRouter sign-in cancellable and stop "signed in" on Deny

M3gA-Mindfee16c28e720
diff --git a/app/src/components/settings/panels/__tests__/AIPanel.test.tsx b/app/src/components/settings/panels/__tests__/AIPanel.test.tsx
index c4e3f42bb4..cf56629bc1 100644
--- a/app/src/components/settings/panels/__tests__/AIPanel.test.tsx
+++ b/app/src/components/settings/panels/__tests__/AIPanel.test.tsx
@@ -1443,6 +1443,38 @@ describe('AIPanel', () => {
);
});
+ // Regression: the dialog disabled Cancel (and blocked Esc / click-outside)
+ // for the whole browser round-trip, so an abandoned sign-in left the user
+ // stuck on "Connecting…" with no way out.
+ it('keeps Cancel usable while OpenRouter sign-in is pending and aborts the flow', async () => {
+ vi.mocked(loadAISettings).mockResolvedValue({ ...baseSettings, cloudProviders: [] });
+ let signal: AbortSignal | undefined;
+ vi.mocked(connectOpenRouterViaOAuth).mockImplementation(deps => {
+ signal = deps?.signal;
+ return new Promise((_, reject) =>
+ signal?.addEventListener('abort', () =>
+ reject(new Error('OpenRouter OAuth was cancelled.'))
+ )
+ );
+ });
+
+ renderWithProviders(<AIPanel />);
+ await openProviderConnectDialog('openrouter');
+ const dialog = await screen.findByRole('dialog', { name: /Connect OpenRouter/i });
+ fireEvent.click(within(dialog).getByRole('button', { name: /Sign in with OpenRouter/i }));
+ await waitFor(() => expect(connectOpenRouterViaOAuth).toHaveBeenCalledTimes(1));
+
+ const cancel = within(dialog).getByRole('button', { name: /^Cancel$/i });
+ expect(cancel).toBeEnabled();
+ fireEvent.click(cancel);
+
+ expect(signal?.aborted).toBe(true);
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: /Connect OpenRouter/i })).not.toBeInTheDocument()
+ );
+ expect(setCloudProviderKey).not.toHaveBeenCalled();
+ });
+
// Regression: picking a provider in the add-provider modal has to hand off to
// that provider's own connect dialog. Two Radix dialogs are involved (the
// picker unmounts as the key dialog mounts), so this asserts the handoff
diff --git a/app/src/components/settings/panels/ai/ProviderConnectControls.tsx b/app/src/components/settings/panels/ai/ProviderConnectControls.tsx
index a69d32ef75..1950d83b3f 100644
--- a/app/src/components/settings/panels/ai/ProviderConnectControls.tsx
+++ b/app/src/components/settings/panels/ai/ProviderConnectControls.tsx
@@ -74,6 +74,9 @@ export const ProviderKeyDialog = ({
const [phase, setPhase] = useState<'idle' | 'saving' | 'oauth'>('idle');
const [error, setError] = useState<string | null>(null);
const busy = phase !== 'idle';
+ // A pending OAuth sign-in waits on the browser for up to minutes, so it must
+ // stay dismissable (onCancel aborts it); only an in-flight save locks the dialog.
+ const saving = phase === 'saving';
const placeholder = isLocalRuntime
? defaultEndpointFor(slug) || t('settings.ai.defaultLocalEndpoint')
@@ -170,18 +173,18 @@ export const ProviderKeyDialog = ({
<DialogRoot
open
onOpenChange={next => {
- if (!next && !busy) onCancel();
+ if (!next && !saving) onCancel();
}}>
<DialogContent
aria-labelledby={titleId}
onEscapeKeyDown={event => {
- if (busy) event.preventDefault();
+ if (saving) event.preventDefault();
}}
onPointerDownOutside={event => {
- if (busy) event.preventDefault();
+ if (saving) event.preventDefault();
}}
onInteractOutside={event => {
- if (busy) event.preventDefault();
+ if (saving) event.preventDefault();
}}
className="border border-line p-6 shadow-soft">
{platformLinkUrl ? (
@@ -299,7 +302,7 @@ export const ProviderKeyDialog = ({
</div>
) : null}
<div className="mt-6 flex justify-end gap-2">
- <Button type="button" variant="secondary" size="sm" onClick={onCancel} disabled={busy}>
+ <Button type="button" variant="secondary" size="sm" onClick={onCancel} disabled={saving}>
{t('common.cancel')}
</Button>
<Button
diff --git a/app/src/utils/__tests__/loopbackOauthListener.test.ts b/app/src/utils/__tests__/loopbackOauthListener.test.ts
index b38a9ad55f..b7d7dc4b3e 100644
--- a/app/src/utils/__tests__/loopbackOauthListener.test.ts
+++ b/app/src/utils/__tests__/loopbackOauthListener.test.ts
@@ -173,6 +173,28 @@ describe('startLoopbackOauthListener', () => {
}
});
+ test('cancel clears the pending timeout so it cannot stop a later listener', async () => {
+ vi.useFakeTimers();
+ try {
+ mockInvoke.mockResolvedValue({ redirectUri: 'http://127.0.0.1:53824/auth', state: 's' });
+ mockListen.mockResolvedValue(vi.fn());
+
+ const handle = await startLoopbackOauthListener({ timeoutSecs: 1 });
+ void handle!.awaitCallback().catch(() => {});
+ await Promise.resolve();
+ await handle!.cancel();
+ mockInvoke.mockClear();
+
+ // The cancelled attempt's timer must not fire stop() against whatever
+ // listener (e.g. a retry) is active by then.
+ vi.advanceTimersByTime(1000);
+ await Promise.resolve();
+ expect(mockInvoke).not.toHaveBeenCalledWith('stop_loopback_oauth_listener');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
test('ignores callback events that arrive after timeout', async () => {
vi.useFakeTimers();
try {
diff --git a/app/src/utils/__tests__/openrouterOAuth.test.ts b/app/src/utils/__tests__/openrouterOAuth.test.ts
index 7624b18fb5..38516ad57f 100644
--- a/app/src/utils/__tests__/openrouterOAuth.test.ts
+++ b/app/src/utils/__tests__/openrouterOAuth.test.ts
@@ -105,6 +105,56 @@ describe('connectOpenRouterViaOAuth', () => {
expect(cancel).toHaveBeenCalledTimes(1);
});
+ it('rejects a Deny callback that carries only the state, without exchanging', async () => {
+ // OpenRouter's Deny redirects to callback_url with nothing but the echoed
+ // state (observed 2026-09-15).
+ const fetchImpl = vi.fn();
+
+ await expect(
+ connectOpenRouterViaOAuth({
+ startLoopbackListener: vi
+ .fn()
+ .mockResolvedValue({
+ redirectUri: 'http://127.0.0.1:3000/auth?state=expected-state',
+ state: 'expected-state',
+ awaitCallback: vi
+ .fn()
+ .mockResolvedValue('http://127.0.0.1:3000/auth?state=expected-state'),
+ cancel: vi.fn().mockResolvedValue(undefined),
+ }),
+ openExternalUrl: vi.fn().mockResolvedValue(undefined),
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ })
+ ).rejects.toThrow('OpenRouter OAuth did not return an authorization code.');
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it('passes the abort signal to the key exchange so a cancel stops it', async () => {
+ const controller = new AbortController();
+ const fetchImpl = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ key: 'k' }) });
+
+ await connectOpenRouterViaOAuth({
+ signal: controller.signal,
+ startLoopbackListener: vi
+ .fn()
+ .mockResolvedValue({
+ redirectUri: 'http://127.0.0.1:3000/auth?state=expected-state',
+ state: 'expected-state',
+ awaitCallback: vi
+ .fn()
+ .mockResolvedValue('http://127.0.0.1:3000/auth?state=expected-state&code=abc123'),
+ cancel: vi.fn().mockResolvedValue(undefined),
+ }),
+ openExternalUrl: vi.fn().mockResolvedValue(undefined),
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ });
+
+ expect(fetchImpl).toHaveBeenCalledWith(
+ 'https://openrouter.ai/api/v1/auth/keys',
+ expect.objectContaining({ signal: controller.signal })
+ );
+ });
+
it('cancels the loopback listener when the OAuth flow is aborted', async () => {
const cancel = vi.fn().mockResolvedValue(undefined);
const controller = new AbortController();
diff --git a/app/src/utils/loopbackOauthListener.ts b/app/src/utils/loopbackOauthListener.ts
index 68c07f1326..0e49de1ad2 100644
--- a/app/src/utils/loopbackOauthListener.ts
+++ b/app/src/utils/loopbackOauthListener.ts
@@ -103,39 +103,37 @@ export const startLoopbackOauthListener = async (
}
};
+ // `done` closes the race where the timeout (or a cancel) lands *before* the
+ // async `listen()` registration resolves: the just-registered unlisten handle
+ // is torn down instead of being stored in module-global `activeUnlisten`.
+ let done = false;
+ let timer: number | undefined;
+ let unlisten: UnlistenFn | null = null;
+ const teardown = () => {
+ done = true;
+ window.clearTimeout(timer);
+ if (unlisten) {
+ unlisten();
+ if (activeUnlisten === unlisten) activeUnlisten = null;
+ unlisten = null;
+ }
+ };
+
const awaitCallback = (): Promise<string> =>
new Promise<string>((resolve, reject) => {
- // `timedOut` closes the race where `setTimeout` fires *before* the async
- // `listen()` registration resolves: previously the just-registered
- // unlisten handle was stored in module-global `activeUnlisten` after the
- // promise had already rejected, leaving the listener armed until the
- // next `startLoopbackOauthListener` call cleaned it up.
- let timedOut = false;
- let unlisten: UnlistenFn | null = null;
- const timer = window.setTimeout(() => {
- timedOut = true;
- if (unlisten) {
- unlisten();
- if (activeUnlisten === unlisten) activeUnlisten = null;
- }
+ timer = window.setTimeout(() => {
+ teardown();
void stop();
reject(new Error('Loopback OAuth listener timed out'));
}, timeoutSecs * 1000);
listen<CallbackPayload>(CALLBACK_EVENT, event => {
- if (timedOut) return;
- window.clearTimeout(timer);
- if (unlisten) {
- unlisten();
- if (activeUnlisten === unlisten) activeUnlisten = null;
- }
+ if (done) return;
+ teardown();
resolve(event.payload.url);
})
.then(fn => {
- if (timedOut) {
- // Timer already rejected the promise — tear down the
- // just-registered handle so it does not leak into
- // `activeUnlisten` and stay armed past the timeout.
+ if (done) {
fn();
return;
}
@@ -143,13 +141,20 @@ export const startLoopbackOauthListener = async (
activeUnlisten = fn;
})
.catch(err => {
- if (timedOut) return;
+ if (done) return;
window.clearTimeout(timer);
reject(err);
});
});
- return { redirectUri: redirectUriWithState, state: result.state, awaitCallback, cancel: stop };
+ // Cancel must also clear the timeout: a cancelled attempt's timer otherwise
+ // fires later and stops whichever listener is active by then (a retry's).
+ const cancel = async () => {
+ teardown();
+ await stop();
+ };
+
+ return { redirectUri: redirectUriWithState, state: result.state, awaitCallback, cancel };
};
const appendState = (uri: string, state: string): string => {
diff --git a/app/src/utils/openrouterOAuth.ts b/app/src/utils/openrouterOAuth.ts
index 0506d42975..68ea0cdf6b 100644
--- a/app/src/utils/openrouterOAuth.ts
+++ b/app/src/utils/openrouterOAuth.ts
@@ -65,10 +65,14 @@ function extractOAuthCode(callbackUrl: string, expectedState: string): string {
async function exchangeCodeForKey(
code: string,
verifier: string,
- fetchImpl: typeof fetch
+ fetchImpl: typeof fetch,
+ signal?: AbortSignal
): Promise<string> {
+ // `signal` aborts an exchange still in flight when the user cancels, so a
+ // late callback cannot import a key after the dialog was dismissed.
const response = await fetchImpl(OPENROUTER_TOKEN_URL, {
method: 'POST',
+ signal,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, code_verifier: verifier, code_challenge_method: PKCE_METHOD }),
});
@@ -152,7 +156,7 @@ export async function connectOpenRouterViaOAuth(deps: OpenRouterOAuthDeps = {}):
}),
]);
const code = extractOAuthCode(callbackUrl, loopback.state);
- return await exchangeCodeForKey(code, verifier, fetchImpl);
+ return await exchangeCodeForKey(code, verifier, fetchImpl, signal);
} finally {
await loopback.cancel();
}
diff --git a/crates/openhuman-app/src/loopback_oauth.rs b/crates/openhuman-app/src/loopback_oauth.rs
index e318fd2ab2..6ba07e4d34 100644
--- a/crates/openhuman-app/src/loopback_oauth.rs
+++ b/crates/openhuman-app/src/loopback_oauth.rs
@@ -205,6 +205,30 @@ const SUCCESS_BODY: &str = "<!doctype html><meta charset=utf-8><title>Signed in<
<p style=\"margin:0;color:#6e6e73\">You can close this tab and return to OpenHuman.</p></div>\
<script>setTimeout(function(){window.close()},250)</script></body>";
+const FAILURE_BODY: &str = "<!doctype html><meta charset=utf-8><title>Sign-in not completed</title>\
+<body style=\"font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;color:#1c1c1e;background:#f5f5f7\">\
+<div style=\"text-align:center\"><h2 style=\"margin:0 0 8px\">Sign-in was not completed.</h2>\
+<p style=\"margin:0;color:#6e6e73\">No credentials were received. Return to OpenHuman to try again.</p></div></body>";
+
+/// Whether a state-matched callback actually delivered a credential. OpenRouter's
+/// Deny redirects back with nothing but the echoed `state=`, and an OAuth error
+/// carries `error=`; neither may show the "signed in" page.
+fn callback_carries_credential(query: &str) -> bool {
+ let pairs: Vec<(&str, &str)> = query.split('&').filter_map(|p| p.split_once('=')).collect();
+ !pairs.iter().any(|(k, _)| *k == "error")
+ && pairs.iter().any(|(k, v)| *k != "state" && !v.is_empty())
+}
+
+/// Page served for a state-matched callback: success only when it carried a credential.
+fn callback_body(query: &str) -> &'static str {
+ if callback_carries_credential(query) {
+ SUCCESS_BODY
+ } else {
+ log::warn!("[loopback-oauth] callback carried no credential (denied or error)");
+ FAILURE_BODY
+ }
+}
+
fn http_response(status: &str, body: &str) -> Vec<u8> {
format!(
"HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {len}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n{body}",
@@ -350,7 +374,11 @@ async fn run_accept_loop(
.await;
}
RequestOutcome::AuthCallback { callback_url } => {
- let _ = socket.write_all(&http_response("200 OK", SUCCESS_BODY)).await;
+ let query = callback_url.split_once('?').map_or("", |(_, q)| q);
+ let body = callback_body(query);
+ // Still emit: the frontend must leave its pending state and
+ // report the failure instead of waiting for the timeout.
+ let _ = socket.write_all(&http_response("200 OK", body)).await;
let _ = socket.flush().await;
if let Err(err) =
app.emit(LOOPBACK_CALLBACK_EVENT, CallbackPayload { url: callback_url })
diff --git a/crates/openhuman-app/src/loopback_oauth_tests.rs b/crates/openhuman-app/src/loopback_oauth_tests.rs
index f5518d2160..3b8eead161 100644
--- a/crates/openhuman-app/src/loopback_oauth_tests.rs
+++ b/crates/openhuman-app/src/loopback_oauth_tests.rs
@@ -146,3 +146,32 @@ async fn bind_loopback_allows_rebind_via_so_reuseaddr() {
drop(listener);
let _ = bind_loopback(port).expect("rebind on same port must succeed with SO_REUSEADDR");
}
+
+// ── callback_carries_credential ─────────────────────────────────────────
+
+#[test]
+fn deny_or_error_callback_carries_no_credential() {
+ // OpenRouter Deny: only the echoed state (observed 2026-09-15).
+ assert!(!callback_carries_credential("state=abc"), "state-only");
+ assert!(
+ !callback_carries_credential("state=abc&error=access_denied"),
+ "error param"
+ );
+ assert!(
+ !callback_carries_credential("state=abc&code="),
+ "empty code"
+ );
+}
+
+#[test]
+fn code_or_token_callback_carries_credential() {
+ assert!(callback_carries_credential("state=abc&code=xyz"), "code");
+ assert!(callback_carries_credential("token=jwt&state=abc"), "token");
+}
+
+#[test]
+fn deny_callback_serves_failure_page_not_signed_in() {
+ assert!(callback_body("state=abc").contains("Sign-in was not completed."));
+ assert!(!callback_body("state=abc").contains("signed in."));
+ assert!(callback_body("state=abc&code=xyz").contains("You're signed in."));
+}