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