Skip to content

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

fix(settings): address review on OpenRouter sign-in cancellation

M3gA-Mindf11a0ed69a1e
diff --git a/app/src/components/settings/panels/AIPanel.tsx b/app/src/components/settings/panels/AIPanel.tsx
index df4f6d38c4..9f1e31680e 100644
--- a/app/src/components/settings/panels/AIPanel.tsx
+++ b/app/src/components/settings/panels/AIPanel.tsx
@@ -475,11 +475,15 @@ const AIPanel = ({
keyDialogFor === 'openrouter' && !pendingLocalLabel
? {
label: t('settings.ai.signInWithOpenRouter'),
- onClick: async () => {
+ onClick: async ({ onPersisting }) => {
const controller = new AbortController();
openRouterOauthAbortRef.current = controller;
try {
const apiKey = await connectOpenRouterViaOAuth({ signal: controller.signal });
+ // A key exists now and cancelling cannot undo saving it, so a
+ // cancel that already landed wins and later ones are locked out.
+ if (controller.signal.aborted) return;
+ onPersisting();
await connectProvider({
slug: 'openrouter',
value: apiKey,
diff --git a/app/src/components/settings/panels/__tests__/AIPanel.test.tsx b/app/src/components/settings/panels/__tests__/AIPanel.test.tsx
index cf56629bc1..0b8faee2b3 100644
--- a/app/src/components/settings/panels/__tests__/AIPanel.test.tsx
+++ b/app/src/components/settings/panels/__tests__/AIPanel.test.tsx
@@ -1475,6 +1475,24 @@ describe('AIPanel', () => {
expect(setCloudProviderKey).not.toHaveBeenCalled();
});
+ // Regression (review on #6265): once the key exists, Cancel must not close the
+ // dialog while it is being saved, or the provider is added after a "cancel".
+ it('locks the dialog while an OpenRouter OAuth key is being saved', async () => {
+ vi.mocked(loadAISettings).mockResolvedValue({ ...baseSettings, cloudProviders: [] });
+ vi.mocked(connectOpenRouterViaOAuth).mockResolvedValue('sk-or-from-oauth');
+ vi.mocked(setCloudProviderKey).mockImplementationOnce(() => new Promise(() => {}));
+
+ 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(setCloudProviderKey).toHaveBeenCalledWith('openrouter', 'sk-or-from-oauth')
+ );
+ expect(within(dialog).getByRole('button', { name: /^Cancel$/i })).toBeDisabled();
+ });
+
// 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 1950d83b3f..abc1188262 100644
--- a/app/src/components/settings/panels/ai/ProviderConnectControls.tsx
+++ b/app/src/components/settings/panels/ai/ProviderConnectControls.tsx
@@ -52,7 +52,12 @@ export const ProviderKeyDialog = ({
initialValue?: string;
/** Pre-populate the API key field in `endpointKeyMode`. */
initialKeyValue?: string;
- oauthAction?: { label: string; description?: string; onClick: () => Promise<void> | void } | null;
+ oauthAction?: {
+ label: string;
+ description?: string;
+ /** `onPersisting` locks the dialog once a credential exists and is being saved. */
+ onClick: (hooks: { onPersisting: () => void }) => Promise<void> | void;
+ } | null;
/** Register or remove the provider after the core OAuth operation succeeds. */
openAiOAuth?: {
onCompleted: () => Promise<void> | void;
@@ -146,7 +151,7 @@ export const ProviderKeyDialog = ({
setError(null);
setPhase('oauth');
try {
- await oauthAction.onClick();
+ await oauthAction.onClick({ onPersisting: () => setPhase('saving') });
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.warn('[ai-settings] provider oauth failed', {
diff --git a/app/src/utils/__tests__/openrouterOAuth.test.ts b/app/src/utils/__tests__/openrouterOAuth.test.ts
index 38516ad57f..108de6ff0f 100644
--- a/app/src/utils/__tests__/openrouterOAuth.test.ts
+++ b/app/src/utils/__tests__/openrouterOAuth.test.ts
@@ -178,4 +178,34 @@ describe('connectOpenRouterViaOAuth', () => {
await expect(promise).rejects.toThrow('OpenRouter OAuth was cancelled.');
expect(cancel).toHaveBeenCalledTimes(1);
});
+
+ it('cancels when the flow is aborted while the browser is still opening', async () => {
+ const cancel = vi.fn().mockResolvedValue(undefined);
+ const controller = new AbortController();
+
+ const promise = 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().mockImplementation(() => new Promise(() => {})),
+ cancel,
+ }),
+ // The abort lands after the listener is up but before the callback race exists.
+ openExternalUrl: vi.fn().mockImplementation(async () => controller.abort()),
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ });
+
+ const outcome = await Promise.race([
+ promise.then(
+ () => 'resolved',
+ (err: Error) => err.message
+ ),
+ new Promise(resolve => setTimeout(() => resolve('still pending'), 50)),
+ ]);
+ expect(outcome).toBe('OpenRouter OAuth was cancelled.');
+ expect(cancel).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/app/src/utils/openrouterOAuth.ts b/app/src/utils/openrouterOAuth.ts
index 68ea0cdf6b..22993f90b4 100644
--- a/app/src/utils/openrouterOAuth.ts
+++ b/app/src/utils/openrouterOAuth.ts
@@ -148,6 +148,12 @@ export async function connectOpenRouterViaOAuth(deps: OpenRouterOAuthDeps = {}):
loopback.awaitCallback(),
new Promise<string>((_, reject) => {
if (!signal) return;
+ // An abort while the challenge was built or the browser was opening has
+ // already fired, so a listener added now would never run.
+ if (signal.aborted) {
+ reject(new Error('OpenRouter OAuth was cancelled.'));
+ return;
+ }
const onAbort = () => {
signal.removeEventListener('abort', onAbort);
reject(new Error('OpenRouter OAuth was cancelled.'));
diff --git a/crates/openhuman-app/src/loopback_oauth.rs b/crates/openhuman-app/src/loopback_oauth.rs
index 6ba07e4d34..3b2f1613e3 100644
--- a/crates/openhuman-app/src/loopback_oauth.rs
+++ b/crates/openhuman-app/src/loopback_oauth.rs
@@ -212,11 +212,14 @@ const FAILURE_BODY: &str = "<!doctype html><meta charset=utf-8><title>Sign-in no
/// 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.
+/// carries `error=`; neither may show the "signed in" page. Only a non-empty
+/// `code` (OAuth / PKCE) or `token` (backend login) counts as a credential.
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())
+ && pairs
+ .iter()
+ .any(|(k, v)| matches!(*k, "code" | "token") && !v.is_empty())
}
/// Page served for a state-matched callback: success only when it carried a credential.
diff --git a/crates/openhuman-app/src/loopback_oauth_tests.rs b/crates/openhuman-app/src/loopback_oauth_tests.rs
index 3b8eead161..bd2845d2a9 100644
--- a/crates/openhuman-app/src/loopback_oauth_tests.rs
+++ b/crates/openhuman-app/src/loopback_oauth_tests.rs
@@ -161,6 +161,10 @@ fn deny_or_error_callback_carries_no_credential() {
!callback_carries_credential("state=abc&code="),
"empty code"
);
+ assert!(
+ !callback_carries_credential("state=abc&scope=openid"),
+ "non-credential param"
+ );
}
#[test]