Skip to content

Commit 222ba9d

Browse files
authored
fix provider oauth polling flow (anomalyco#818)
1 parent b299247 commit 222ba9d

4 files changed

Lines changed: 224 additions & 37 deletions

File tree

‎packages/app/src/app/app.tsx‎

Lines changed: 70 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ import {
6262
VARIANT_PREF_KEY,
6363
} from "./constants";
6464
import { parseMcpServersFromContent, removeMcpFromConfig, validateMcpServerName } from "./mcp";
65+
import { mapConfigProvidersToList } from "./utils/providers";
6566
import type {
6667
Client,
6768
DashboardTab,
@@ -1946,6 +1947,47 @@ export default function App() {
19461947
}
19471948
}
19481949

1950+
async function refreshProviders(options?: { dispose?: boolean }) {
1951+
const c = client();
1952+
if (!c) return null;
1953+
1954+
if (options?.dispose) {
1955+
try {
1956+
unwrap(await c.instance.dispose());
1957+
} catch {
1958+
// ignore dispose failures and try reading current state anyway
1959+
}
1960+
1961+
try {
1962+
await waitForHealthy(client() ?? c, { timeoutMs: 8_000, pollMs: 250 });
1963+
} catch {
1964+
// ignore health wait failures and still attempt provider reads
1965+
}
1966+
}
1967+
1968+
const activeClient = client() ?? c;
1969+
try {
1970+
const updated = unwrap(await activeClient.provider.list());
1971+
globalSync.set("provider", updated);
1972+
return updated;
1973+
} catch {
1974+
try {
1975+
const fallback = unwrap(await activeClient.config.providers());
1976+
const mapped = mapConfigProvidersToList(fallback.providers);
1977+
const previousConnected = providerConnectedIds();
1978+
const next = {
1979+
all: mapped,
1980+
connected: previousConnected.filter((id) => mapped.some((provider) => provider.id === id)),
1981+
default: fallback.default,
1982+
};
1983+
globalSync.set("provider", next);
1984+
return next;
1985+
} catch {
1986+
return null;
1987+
}
1988+
}
1989+
}
1990+
19491991
async function completeProviderAuthOAuth(providerId: string, methodIndex: number, code?: string) {
19501992
setProviderAuthError(null);
19511993
const c = client();
@@ -1962,13 +2004,12 @@ export default function App() {
19622004
throw new Error("OAuth method is required");
19632005
}
19642006

1965-
const waitForProviderConnection = async (timeoutMs = 15_000, pollMs = 1_000) => {
2007+
const waitForProviderConnection = async (timeoutMs = 15_000, pollMs = 2_000) => {
19662008
const startedAt = Date.now();
19672009
while (Date.now() - startedAt < timeoutMs) {
19682010
try {
1969-
const updated = unwrap(await c.provider.list()) as { connected?: string[] };
1970-
if (Array.isArray(updated.connected) && updated.connected.includes(resolved)) {
1971-
globalSync.set("provider", updated);
2011+
const updated = await refreshProviders({ dispose: true });
2012+
if (Array.isArray(updated?.connected) && updated.connected.includes(resolved)) {
19722013
return true;
19732014
}
19742015
} catch {
@@ -1979,6 +2020,11 @@ export default function App() {
19792020
return false;
19802021
};
19812022

2023+
const isPendingOauthError = (error: unknown) => {
2024+
const text = error instanceof Error ? error.message : String(error ?? "");
2025+
return /request timed out/i.test(text) || /ProviderAuthOauthMissing/i.test(text);
2026+
};
2027+
19822028
try {
19832029
const trimmedCode = code?.trim();
19842030
const result = await c.provider.oauth.callback({
@@ -1987,16 +2033,27 @@ export default function App() {
19872033
code: trimmedCode || undefined,
19882034
});
19892035
assertNoClientError(result);
1990-
const updated = unwrap(await c.provider.list());
1991-
globalSync.set("provider", updated);
1992-
return `Connected ${resolved}`;
2036+
const updated = await refreshProviders({ dispose: true });
2037+
const connectedNow = Array.isArray(updated?.connected) && updated.connected.includes(resolved);
2038+
if (connectedNow) {
2039+
return { connected: true, message: `Connected ${resolved}` };
2040+
}
2041+
const connected = await waitForProviderConnection();
2042+
if (connected) {
2043+
return { connected: true, message: `Connected ${resolved}` };
2044+
}
2045+
return { connected: false, pending: true };
19932046
} catch (error) {
1994-
const messageText = error instanceof Error ? error.message : String(error ?? "");
1995-
if (/request timed out/i.test(messageText)) {
2047+
if (isPendingOauthError(error)) {
2048+
const updated = await refreshProviders({ dispose: true });
2049+
if (Array.isArray(updated?.connected) && updated.connected.includes(resolved)) {
2050+
return { connected: true, message: `Connected ${resolved}` };
2051+
}
19962052
const connected = await waitForProviderConnection();
19972053
if (connected) {
1998-
return `Connected ${resolved}`;
2054+
return { connected: true, message: `Connected ${resolved}` };
19992055
}
2056+
return { connected: false, pending: true };
20002057
}
20012058
const message = describeProviderError(error, "Failed to complete OAuth");
20022059
setProviderAuthError(message);
@@ -2021,8 +2078,7 @@ export default function App() {
20212078
providerID: providerId,
20222079
auth: { type: "api", key: trimmed },
20232080
});
2024-
const updated = unwrap(await c.provider.list());
2025-
globalSync.set("provider", updated);
2081+
await refreshProviders({ dispose: true });
20262082
return `Connected ${providerId}`;
20272083
} catch (error) {
20282084
const message = describeProviderError(error, "Failed to save API key");
@@ -5760,6 +5816,7 @@ export default function App() {
57605816
closeProviderAuthModal,
57615817
startProviderAuth,
57625818
completeProviderAuthOAuth,
5819+
refreshProviders,
57635820
submitProviderApiKey,
57645821
view: currentView(),
57655822
setView,
@@ -6089,6 +6146,7 @@ export default function App() {
60896146
showTryNotionPrompt: tryNotionPromptVisible() && notionIsActive(),
60906147
startProviderAuth: startProviderAuth,
60916148
completeProviderAuthOAuth: completeProviderAuthOAuth,
6149+
refreshProviders: refreshProviders,
60926150
submitProviderApiKey: submitProviderApiKey,
60936151
openProviderAuthModal: openProviderAuthModal,
60946152
closeProviderAuthModal: closeProviderAuthModal,

‎packages/app/src/app/components/provider-auth-modal.tsx‎

Lines changed: 125 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { ProviderAuthAuthorization } from "@opencode-ai/sdk/v2/client";
22
import { CheckCircle2, Loader2, X } from "lucide-solid";
33
import type { ProviderListItem } from "../types";
4-
import { createEffect, createMemo, createSignal, For, Show } from "solid-js";
4+
import { createEffect, createMemo, createSignal, For, onCleanup, Show } from "solid-js";
55
import { isTauriRuntime } from "../utils";
66

77
import Button from "./button";
@@ -43,7 +43,12 @@ export type ProviderAuthModalProps = {
4343
authMethods: Record<string, ProviderAuthMethod[]>;
4444
onSelect: (providerId: string) => Promise<ProviderOAuthStartResult>;
4545
onSubmitApiKey: (providerId: string, apiKey: string) => Promise<string | void>;
46-
onSubmitOAuth: (providerId: string, methodIndex: number, code?: string) => Promise<string | void>;
46+
onSubmitOAuth: (
47+
providerId: string,
48+
methodIndex: number,
49+
code?: string
50+
) => Promise<{ connected: boolean; pending?: boolean; message?: string }>;
51+
onRefreshProviders?: () => Promise<unknown>;
4752
onClose: () => void;
4853
};
4954

@@ -109,7 +114,11 @@ export default function ProviderAuthModal(props: ProviderAuthModalProps) {
109114
const [searchQuery, setSearchQuery] = createSignal("");
110115
const [activeEntryIndex, setActiveEntryIndex] = createSignal(0);
111116
const [localError, setLocalError] = createSignal<string | null>(null);
117+
const [pollingBusy, setPollingBusy] = createSignal(false);
118+
const [oauthAutoBusy, setOauthAutoBusy] = createSignal(false);
112119
let searchInputEl: HTMLInputElement | undefined;
120+
let providerPoll: number | null = null;
121+
let oauthAutoPoll: number | null = null;
113122

114123
const selectedEntry = createMemo(() =>
115124
entries().find((entry) => entry.id === selectedProviderId()) ?? null,
@@ -178,10 +187,90 @@ export default function ProviderAuthModal(props: ProviderAuthModalProps) {
178187
!!entry?.methods?.some((method) => method.type === type);
179188

180189
const handleClose = () => {
190+
void props.onRefreshProviders?.();
191+
if (oauthAutoPoll !== null) {
192+
window.clearInterval(oauthAutoPoll);
193+
oauthAutoPoll = null;
194+
}
195+
if (providerPoll !== null) {
196+
window.clearInterval(providerPoll);
197+
providerPoll = null;
198+
}
181199
resetState();
182200
props.onClose();
183201
};
184202

203+
onCleanup(() => {
204+
if (oauthAutoPoll !== null) {
205+
window.clearInterval(oauthAutoPoll);
206+
oauthAutoPoll = null;
207+
}
208+
if (providerPoll !== null) {
209+
window.clearInterval(providerPoll);
210+
providerPoll = null;
211+
}
212+
});
213+
214+
const isOauthView = () => resolvedView() === "oauth-code" || resolvedView() === "oauth-auto";
215+
const activeProviderId = () => oauthSession()?.providerId ?? selectedProviderId();
216+
217+
const isActiveProviderConnected = () => {
218+
const id = activeProviderId();
219+
if (!id) return false;
220+
return (props.connectedProviderIds ?? []).includes(id);
221+
};
222+
223+
const pollProviders = async () => {
224+
const id = activeProviderId();
225+
if (!id) return;
226+
if (pollingBusy()) return;
227+
setPollingBusy(true);
228+
try {
229+
await props.onRefreshProviders?.();
230+
} finally {
231+
setPollingBusy(false);
232+
}
233+
if (isActiveProviderConnected()) {
234+
handleClose();
235+
}
236+
};
237+
238+
const startProviderPolling = () => {
239+
if (typeof window === "undefined") return;
240+
if (providerPoll !== null) return;
241+
void pollProviders();
242+
providerPoll = window.setInterval(() => {
243+
void pollProviders();
244+
}, 2000);
245+
};
246+
247+
const stopProviderPolling = () => {
248+
if (providerPoll !== null) {
249+
window.clearInterval(providerPoll);
250+
providerPoll = null;
251+
}
252+
};
253+
254+
createEffect(() => {
255+
if (!props.open || !isOauthView()) {
256+
stopProviderPolling();
257+
return;
258+
}
259+
if (isActiveProviderConnected()) {
260+
handleClose();
261+
return;
262+
}
263+
startProviderPolling();
264+
});
265+
266+
createEffect(() => {
267+
if (!props.open || resolvedView() !== "oauth-auto" || !oauthSession()) {
268+
stopOauthAutoPolling();
269+
return;
270+
}
271+
startOauthAutoPolling();
272+
});
273+
185274
const openOauthUrl = async (url: string) => {
186275
if (!url) return;
187276
if (isTauriRuntime()) {
@@ -196,14 +285,44 @@ export default function ProviderAuthModal(props: ProviderAuthModalProps) {
196285
const trimmedCode = code?.trim();
197286
setLocalError(null);
198287
try {
199-
await props.onSubmitOAuth(providerId, methodIndex, trimmedCode || undefined);
288+
return await props.onSubmitOAuth(providerId, methodIndex, trimmedCode || undefined);
200289
} catch (error) {
201290
const message = error instanceof Error ? error.message : "Failed to complete OAuth";
202291
setLocalError(message);
203292
throw error instanceof Error ? error : new Error(message);
204293
}
205294
};
206295

296+
const stopOauthAutoPolling = () => {
297+
if (oauthAutoPoll !== null) {
298+
window.clearInterval(oauthAutoPoll);
299+
oauthAutoPoll = null;
300+
}
301+
};
302+
303+
const attemptOauthAutoCompletion = async () => {
304+
const session = oauthSession();
305+
if (!session || oauthAutoBusy()) return;
306+
setOauthAutoBusy(true);
307+
try {
308+
const result = await submitOauth(session.providerId, session.methodIndex);
309+
if (result?.connected) {
310+
stopOauthAutoPolling();
311+
}
312+
} finally {
313+
setOauthAutoBusy(false);
314+
}
315+
};
316+
317+
const startOauthAutoPolling = () => {
318+
if (typeof window === "undefined") return;
319+
if (oauthAutoPoll !== null) return;
320+
void attemptOauthAutoCompletion();
321+
oauthAutoPoll = window.setInterval(() => {
322+
void attemptOauthAutoCompletion();
323+
}, 2000);
324+
};
325+
207326
const startOauth = async (entry: ProviderAuthEntry) => {
208327
if (actionDisabled()) return;
209328
setLocalError(null);
@@ -225,7 +344,6 @@ export default function ProviderAuthModal(props: ProviderAuthModalProps) {
225344
}
226345

227346
setView("oauth-auto");
228-
await submitOauth(entry.id, started.methodIndex);
229347
} catch (error) {
230348
const message = error instanceof Error ? error.message : "Failed to start OAuth";
231349
setLocalError(message);
@@ -304,13 +422,6 @@ export default function ProviderAuthModal(props: ProviderAuthModalProps) {
304422
await submitOauth(entry.id, session.methodIndex, trimmed);
305423
};
306424

307-
const handleOauthAutoRetry = async () => {
308-
const entry = selectedEntry();
309-
const session = oauthSession();
310-
if (!entry || !session || actionDisabled()) return;
311-
await submitOauth(entry.id, session.methodIndex);
312-
};
313-
314425
const handleBack = () => {
315426
if (resolvedView() === "oauth-code" || resolvedView() === "oauth-auto") {
316427
if (hasMethod(selectedEntry(), "api")) {
@@ -656,8 +767,8 @@ export default function ProviderAuthModal(props: ProviderAuthModalProps) {
656767
<TextInput label="Confirmation code" value={oauthDisplayCode()} readOnly class="font-mono" />
657768
</Show>
658769
<div class="flex items-center gap-2 text-xs text-gray-9">
659-
<Loader2 size={14} class={props.submitting ? "animate-spin" : ""} />
660-
<span>{props.submitting ? "Waiting for confirmation..." : "Ready to retry completion."}</span>
770+
<Loader2 size={14} class={props.submitting || pollingBusy() || oauthAutoBusy() ? "animate-spin" : ""} />
771+
<span>Checking connection status automatically...</span>
661772
</div>
662773
<div class="flex items-center justify-between gap-3">
663774
<Button
@@ -670,9 +781,7 @@ export default function ProviderAuthModal(props: ProviderAuthModalProps) {
670781
>
671782
Open browser again
672783
</Button>
673-
<Button variant="secondary" onClick={() => void handleOauthAutoRetry()} disabled={actionDisabled()}>
674-
{props.submitting ? "Waiting..." : "Retry completion"}
675-
</Button>
784+
<div class="text-[11px] text-gray-9 text-right">This window will close once the provider is connected.</div>
676785
</div>
677786
</div>
678787
</Show>

0 commit comments

Comments
 (0)