Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5 type AtomCommandResult,
6} from "@t3tools/client-runtime/state/runtime";
7import {
8 AuthProvidersManageScope,
9 isManagedDriverAllowed,
10 type ProviderAuthResponse,
11 type ServerProvider,
12} from "@t3tools/contracts";
13import { useAtomValue } from "@effect/atom-react";
14import { useRef, useState } from "react";
15import { Linking, Pressable, ScrollView, TextInput, useWindowDimensions, View } from "react-native";
16import { useSafeAreaInsets } from "react-native-safe-area-context";
17
18import type { MenuAction } from "@react-native-menu/menu";
19
20import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
21import { AppText as Text } from "../../components/ui/AppText";
22import { ControlPill } from "../../components/ui/ControlPill";
23import { Menu } from "../../components/ui/Menu";
24import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
25import { environmentPresentations } from "../../state/presentation";
26import { useEnvironmentQuery } from "../../state/query";
27import { serverEnvironment } from "../../state/server";
28import { useEnvironmentsWithScope } from "../../state/session";
29import { useAtomCommand } from "../../state/use-atom-command";
30import { ListActionRow as SettingsActionRow } from "../../components/ui/ListActionRow";
31import { useSettingsEnvironmentMenu } from "./components/SettingsEnvironmentFilterHeader";
32import { SettingsScreen } from "./components/SettingsScreen";
33import { SettingsSection } from "./components/SettingsSection";
34import { AddClaudeAccount, ClaudeAccount } from "./ClaudeAccounts";
35import { CLAUDE_DRIVER } from "./claude-accounts";
36import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter";
37
38export function SettingsProviderAccountsRouteScreen() {
39 const environmentMenu = useSettingsEnvironmentMenu();
40 const { selectedTargets } = useSettingsEnvironmentFilter();
41 const permittedEnvironments = useEnvironmentsWithScope(selectedTargets, AuthProvidersManageScope);
42 const providersByEnvironment = useAtomValue(environmentPresentations.providersByEnvironmentAtom);
43 const insets = useSafeAreaInsets();
44 return (
45 <SettingsScreen title="Providers" menus={[environmentMenu]}>
46 <ScreenScrollView
47 className="flex-1"
48 contentInsetAdjustmentBehavior="automatic"
49 contentContainerClassName="gap-6 px-5 pt-4"
50 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
51 >
52 {selectedTargets.length === 0 ? (
53 <Text className="text-foreground-muted">Select a connected environment.</Text>
54 ) : (
55 selectedTargets.map((environment) => (
56 <SettingsSection key={environment.environmentId} title={environment.label}>
57 {!permittedEnvironments.has(environment.environmentId) ? (
58 <View className="gap-1 p-4">
59 <Text className="text-base text-foreground">Limited permissions</Text>
60 <Text className="text-sm text-foreground-muted">
61 {`This session can view ${environment.label}'s providers but can't change their settings.`}
62 </Text>
63 </View>
64 ) : (
65 <EnvironmentProviders
66 environment={environment}
67 providers={managedProviders(environment, providersByEnvironment)}
68 />
69 )}
70 </SettingsSection>
71 ))
72 )}
73 </ScreenScrollView>
74 </SettingsScreen>
75 );
76}
77
78function EnvironmentProviders({
79 environment,
80 providers,
81}: {
82 readonly environment: SettingsTarget;
83 readonly providers: ReadonlyArray<ServerProvider>;
84}) {
85 const accounts = providers.filter(canManageProvider);
86 // Claude has no in-app sign-in; each account is its own instance on a signed-in config folder.
87 const claudeAccounts = providers.filter(
88 (provider) => provider.driver === CLAUDE_DRIVER && !canManageProvider(provider),
89 );
90 const canAddClaude = isManagedDriverAllowed(
91 environment.serverConfig.managedPolicy,
92 CLAUDE_DRIVER,
93 );
94 return (
95 <>
96 {accounts.map((provider, index) => (
97 <ProviderAccount
98 key={provider.instanceId}
99 environment={environment}
100 provider={provider}
101 divider={index > 0}
102 />
103 ))}
104 {accounts.length === 0 ? (
105 <Text className="p-4 text-foreground-muted">
106 Configure a provider with in-app sign-in in web or desktop Settings.
107 </Text>
108 ) : null}
109 {claudeAccounts.map((provider) => (
110 <ClaudeAccount key={provider.instanceId} environment={environment} provider={provider} />
111 ))}
112 {canAddClaude ? <AddClaudeAccount environment={environment} /> : null}
113 </>
114 );
115}
116
117/** Providers the environment's managed policy allows; the rest cannot run or sign in. */
118function managedProviders(
119 environment: SettingsTarget,
120 providersByEnvironment: ReadonlyMap<string, ReadonlyArray<ServerProvider>>,
121) {
122 return (providersByEnvironment.get(environment.environmentId) ?? []).filter((provider) =>
123 isManagedDriverAllowed(environment.serverConfig.managedPolicy, provider.driver),
124 );
125}
126
127function canManageProvider(provider: ServerProvider) {
128 return Boolean(
129 provider.setup?.canAuthenticate || (provider.driver === "acpRegistry" && provider.installed),
130 );
131}
132
133function ProviderAccount({
134 environment,
135 provider,
136 divider,
137}: {
138 readonly environment: SettingsTarget;
139 readonly provider: ServerProvider;
140 readonly divider: boolean;
141}) {
142 const environmentId = environment.environmentId;
143 const instanceId = provider.instanceId;
144 const target = { environmentId, input: { instanceId } };
145 const auth = useEnvironmentQuery(serverEnvironment.providerAuthState(target));
146 const options = { reportFailure: false, reportDefect: false };
147 const start = useAtomCommand(serverEnvironment.startProviderAuth, options);
148 const respond = useAtomCommand(serverEnvironment.respondProviderAuth, options);
149 const complete = useAtomCommand(serverEnvironment.completeProviderAuth, options);
150 const cancel = useAtomCommand(serverEnvironment.cancelProviderAuth, options);
151 const logout = useAtomCommand(serverEnvironment.logoutProviderAuth, options);
152 const removeMethod = useAtomCommand(serverEnvironment.removeProviderAuthMethod, options);
153 const canRemoveMethod = useAtomValue(
154 serverEnvironment.removeProviderAuthMethod.permissionAtom(environmentId),
155 );
156 // Matches ListRowLayout: large text stacks the action below instead of squeezing the status.
157 const stacked = useWindowDimensions().fontScale >= 1.5;
158 const [pending, setPending] = useState(false);
159 const pendingRef = useRef(false);
160 const [error, setError] = useState<string | null>(null);
161 const [draft, setDraft] = useState({ id: "", values: {} as Record<string, string> });
162 const state = auth.data;
163 const interaction = state?.interaction;
164 const draftId = `${state?.flowId ?? ""}:${interaction?.id ?? ""}`;
165 const values = draft.id === draftId ? draft.values : {};
166 const active =
167 state?.phase === "starting" || state?.phase === "waiting" || state?.phase === "verifying";
168 const signedIn =
169 provider.auth.status === "authenticated" ||
170 (provider.auth.status === "unknown" && state?.phase === "succeeded");
171 const isDiscovering =
172 provider.driver === "acpRegistry" &&
173 !active &&
174 !signedIn &&
175 !auth.error &&
176 state?.methods === undefined;
177 const needsExternalSetup =
178 !active &&
179 !signedIn &&
180 (provider.setup?.canAuthenticate === false ||
181 (provider.driver === "acpRegistry" && state?.methods?.length === 0));
182 const url =
183 interaction?.type === "browser" || interaction?.type === "deviceCode"
184 ? interaction.url
185 : state?.authorizationUrl;
186 const disabled = pending || auth.error !== null || isDiscovering;
187 async function run(command: () => Promise<AtomCommandResult<unknown, unknown>>) {
188 if (pendingRef.current) return false;
189 pendingRef.current = true;
190 setPending(true);
191 setError(null);
192 const result = await command();
193 pendingRef.current = false;
194 setPending(false);
195 if (result._tag === "Success") return true;
196 if (!isAtomCommandInterrupted(result)) {
197 const failure = squashAtomCommandFailure(result);
198 setError(failure instanceof Error ? failure.message : "Could not update provider sign-in.");
199 }
200 return false;
201 }
202 function send(response: ProviderAuthResponse) {
203 if (!state?.flowId || !interaction) return Promise.resolve(false);
204 return run(() =>
205 respond({
206 environmentId,
207 input: { instanceId, flowId: state.flowId!, interactionId: interaction.id, response },
208 }),
209 );
210 }
211 function field(name: string, label: string, secret: boolean) {
212 return (
213 <TextInput
214 accessibilityLabel={label}
215 className="rounded-lg border border-border-subtle px-3 py-2 text-base text-foreground"
216 placeholderTextColorClassName="accent-foreground-muted"
217 placeholder={label}
218 secureTextEntry={secret}
219 autoCapitalize="none"
220 autoCorrect={false}
221 editable={!disabled}
222 maxLength={secret && interaction?.type === "terminal" ? 4_095 : 16_384}
223 value={values[name] ?? ""}
224 onChangeText={(value) => setDraft({ id: draftId, values: { ...values, [name]: value } })}
225 />
226 );
227 }
228 const name = provider.displayName ?? provider.driver;
229 const email = signedIn && !active && provider.enabled ? provider.auth.email?.trim() : undefined;
230 const methods = state?.methods ?? [];
231 // The status line says why a provider that is missing or turned off can't sign in.
232 const canSignIn =
233 !active &&
234 !needsExternalSetup &&
235 provider.setup?.canAuthenticate !== false &&
236 provider.enabled &&
237 provider.installed;
238 const signInDisabled = disabled || state === null;
239 const canSignOut =
240 !active && signedIn && (provider.auth.canLogout ?? provider.setup?.canAuthenticate);
241 const showCallback =
242 Boolean(url) && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction);
243 const usesCredentials =
244 provider.driver === "antigravity" &&
245 (provider.auth.type === "gemini-api-key" || provider.auth.type === "agent-platform");
246 const status =
247 active || state?.phase === "failed" || state?.phase === "cancelled"
248 ? state.message
249 : !provider.enabled
250 ? "Turned off"
251 : signedIn
252 ? "Signed in"
253 : isDiscovering
254 ? "Discovering sign-in methods…"
255 : needsExternalSetup
256 ? "No in-app sign-in advertised. Follow the provider's docs to finish setup."
257 : !provider.installed
258 ? "Not installed"
259 : usesCredentials
260 ? "Connect to load models"
261 : "Not signed in";
262 // A provider with several sign-in methods picks one from a menu on the same control.
263 const methodActions: MenuAction[] = methods.map((method) => ({
264 id: `method:${method.id}`,
265 title: method.name,
266 }));
267 const removableMethods = methods.filter((method) => method.canRemove);
268 const removeActions: MenuAction[] = removableMethods.length
269 ? [
270 {
271 id: "remove",
272 title: "Remove incomplete connection",
273 attributes: { disabled: disabled || active || !canRemoveMethod },
274 subactions: removableMethods.map((method) => ({
275 id: `remove:${method.id}`,
276 title: method.name,
277 attributes: { destructive: true, disabled: disabled || active || !canRemoveMethod },
278 })),
279 },
280 ]
281 : [];
282 function startSignIn(methodId?: string) {
283 void run(() => start(methodId ? { environmentId, input: { instanceId, methodId } } : target));
284 }
285 function signOut() {
286 Dialog.alert(
287 "Sign out?",
288 `Running threads sharing this sign-in on ${environment.label} will stop. Thread history is kept.`,
289 [
290 { text: "Cancel", style: "cancel" },
291 {
292 text: "Sign out",
293 style: "destructive",
294 onPress: () => {
295 void run(() => logout(target));
296 },
297 },
298 ],
299 );
300 }
301 function onMenuAction(id: string) {
302 if (id === "signOut") signOut();
303 // iOS keeps a disabled submenu's children selectable, so sign-in guards here too.
304 else if (signInDisabled) return;
305 else if (id.startsWith("remove:")) {
306 if (active || !canRemoveMethod) return;
307 const methodId = id.slice("remove:".length);
308 if (!removableMethods.some((method) => method.id === methodId)) return;
309 void run(() => removeMethod({ environmentId, input: { instanceId, methodId } }));
310 } else if (id.startsWith("method:")) startSignIn(id.slice("method:".length));
311 else if (id === "change") startSignIn();
312 }
313 const accountActions: MenuAction[] = [
314 ...removeActions,
315 ...(canSignIn
316 ? [
317 {
318 id: "change",
319 title: "Change account",
320 image: "person.crop.circle",
321 attributes: { disabled: signInDisabled },
322 ...(methodActions.length > 1
323 ? {
324 subactions: methodActions.map((action) => ({
325 ...action,
326 attributes: { disabled: signInDisabled },
327 })),
328 }
329 : {}),
330 },
331 ]
332 : []),
333 ...(canSignOut
334 ? [
335 {
336 id: "signOut",
337 title: "Sign out",
338 image: "rectangle.portrait.and.arrow.right",
339 attributes: { destructive: true, disabled: disabled || state === null },
340 },
341 ]
342 : []),
343 ];
344 const trailing = pending ? (
345 <View className="h-11 w-11 items-center justify-center">
346 <AppActivityIndicator colorClassName="accent-icon" />
347 </View>
348 ) : needsExternalSetup && provider.setup?.documentationUrl ? (
349 <ControlPill
350 variant="pill"
351 label="Docs"
352 onPress={() => {
353 void Linking.openURL(provider.setup!.documentationUrl!).catch(() =>
354 setError("Could not open the provider docs."),
355 );
356 }}
357 />
358 ) : active && state?.flowId ? (
359 <ControlPill
360 variant="pill"
361 label="Cancel"
362 accessibilityLabel={`Cancel ${name} sign-in`}
363 disabled={disabled}
364 onPress={() => {
365 void run(() => cancel({ environmentId, input: { instanceId, flowId: state.flowId! } }));
366 }}
367 />
368 ) : signedIn && !active && accountActions.length > 0 ? (
369 <Menu
370 accessible
371 accessibilityRole="button"
372 accessibilityLabel={`${name} account options`}
373 title={name}
374 actions={accountActions}
375 onPressAction={({ nativeEvent }) => onMenuAction(nativeEvent.event)}
376 >
377 <ControlPill icon="ellipsis" accessibilityLabel={`${name} account options`} />
378 </Menu>
379 ) : canSignIn && !signedIn && methodActions.length > 1 && !signInDisabled ? (
380 <Menu
381 accessible
382 accessibilityRole="button"
383 accessibilityLabel={`Sign in to ${name}`}
384 title="Sign in with"
385 actions={[...methodActions, ...removeActions]}
386 onPressAction={({ nativeEvent }) => onMenuAction(nativeEvent.event)}
387 >
388 <ControlPill variant="primary" label="Sign in" accessibilityLabel={`Sign in to ${name}`} />
389 </Menu>
390 ) : canSignIn && !signedIn ? (
391 <ControlPill
392 variant="primary"
393 label={usesCredentials ? "Connect" : "Sign in"}
394 accessibilityLabel={usesCredentials ? `Connect to ${name}` : `Sign in to ${name}`}
395 disabled={signInDisabled}
396 onPress={() => startSignIn()}
397 />
398 ) : null;
399 return (
400 <View className={divider ? "border-t border-border-subtle" : undefined}>
401 <View
402 className={
403 stacked
404 ? "min-h-16 items-start gap-3 px-4 py-3"
405 : "min-h-16 flex-row items-center gap-3 px-4 py-3"
406 }
407 >
408 <ProviderAccountSummary key={email} name={name} status={status} email={email} />
409 {trailing}
410 </View>
411 {interaction?.type === "deviceCode" ||
412 interaction?.type === "terminal" ||
413 interaction?.type === "credentials" ||
414 showCallback ||
415 error ||
416 auth.error ? (
417 <View className="gap-2 px-4 pb-3">
418 {interaction?.type === "deviceCode" ? (
419 <Text selectable className="text-foreground">
420 Enter code {interaction.userCode} on the sign-in page.
421 </Text>
422 ) : null}
423 {interaction?.type === "terminal" ? (
424 <>
425 <ScrollView className="max-h-64" nestedScrollEnabled>
426 <Text selectable className="font-mono text-sm text-foreground">
427 {interaction.output.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")}
428 </Text>
429 </ScrollView>
430 {field("input", "Terminal response", true)}
431 <SettingsActionRow
432 icon="arrow.up"
433 label="Send response"
434 disabled={disabled}
435 onPress={() => {
436 void send({ type: "terminal", data: `${values.input ?? ""}\r` }).then((sent) => {
437 if (sent) setDraft({ id: "", values: {} });
438 });
439 }}
440 />
441 </>
442 ) : null}
443 {interaction?.type === "credentials" ? (
444 <>
445 {interaction.fields.map((entry) => (
446 <View key={entry.name}>{field(entry.name, entry.label, entry.secret)}</View>
447 ))}
448 <SettingsActionRow
449 icon="person.crop.circle"
450 label="Connect"
451 disabled={disabled}
452 onPress={() => {
453 void send({ type: "credentials", values }).then((sent) => {
454 if (sent) setDraft({ id: "", values: {} });
455 });
456 }}
457 />
458 </>
459 ) : null}
460 {showCallback ? (
461 <>
462 {field("callback", "Final localhost URL", false)}
463 <SettingsActionRow
464 icon="arrow.right"
465 label="Continue"
466 disabled={disabled || !values.callback?.trim()}
467 onPress={() => {
468 if (!state?.flowId) return;
469 void run(() =>
470 complete({
471 environmentId,
472 input: { instanceId, flowId: state.flowId!, callbackUrl: values.callback! },
473 }),
474 ).then((sent) => {
475 if (sent) setDraft({ id: "", values: {} });
476 });
477 }}
478 />
479 </>
480 ) : null}
481 {error || auth.error ? (
482 <Text accessibilityRole="alert" className="text-danger-foreground">
483 {error ?? auth.error}
484 </Text>
485 ) : null}
486 </View>
487 ) : null}
488 {url ? (
489 <SettingsActionRow
490 icon="globe"
491 label="Open sign-in page"
492 disabled={disabled}
493 onPress={() => {
494 void (async () => {
495 if (
496 interaction?.type === "browser" &&
497 interaction.requiresConsent &&
498 !(await send({ type: "browser", action: "accept" }))
499 )
500 return;
501 await Linking.openURL(url);
502 })().catch(() => setError("Could not open the sign-in page."));
503 }}
504 />
505 ) : null}
506 </View>
507 );
508}
509
510function ProviderAccountSummary({
511 name,
512 status,
513 email,
514}: {
515 readonly name: string;
516 readonly status: string | null | undefined;
517 readonly email: string | undefined;
518}) {
519 const [revealed, setRevealed] = useState(false);
520 const content = (
521 <>
522 <Text textRole="body" className="text-foreground" numberOfLines={1}>
523 {name}
524 </Text>
525 <Text accessibilityLiveRegion="polite" textRole="footnote" className="text-foreground-muted">
526 {email ? `${status} · ${revealed ? email : "••••••@••••••"}` : status}
527 </Text>
528 </>
529 );
530 if (!email) {
531 return (
532 <View
533 accessible
534 accessibilityLabel={[name, status].filter(Boolean).join(", ")}
535 className="min-w-0 shrink grow gap-0.5"
536 >
537 {content}
538 </View>
539 );
540 }
541 return (
542 <Pressable
543 accessibilityRole="button"
544 accessibilityLabel={[name, status, revealed ? email : null].filter(Boolean).join(", ")}
545 accessibilityHint={revealed ? "Hides the account email" : "Reveals the account email"}
546 onPress={() => setRevealed((value) => !value)}
547 className="min-w-0 shrink grow gap-0.5"
548 >
549 {content}
550 </Pressable>
551 );
552}