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 // Matches ListRowLayout: large text stacks the action below instead of squeezing the status.
153 const stacked = useWindowDimensions().fontScale >= 1.5;
154 const [pending, setPending] = useState(false);
155 const pendingRef = useRef(false);
156 const [error, setError] = useState<string | null>(null);
157 const [draft, setDraft] = useState({ id: "", values: {} as Record<string, string> });
158 const state = auth.data;
159 const interaction = state?.interaction;
160 const draftId = `${state?.flowId ?? ""}:${interaction?.id ?? ""}`;
161 const values = draft.id === draftId ? draft.values : {};
162 const active =
163 state?.phase === "starting" || state?.phase === "waiting" || state?.phase === "verifying";
164 const signedIn =
165 provider.auth.status === "authenticated" ||
166 (provider.auth.status === "unknown" && state?.phase === "succeeded");
167 const isDiscovering =
168 provider.driver === "acpRegistry" &&
169 !active &&
170 !signedIn &&
171 !auth.error &&
172 state?.methods === undefined;
173 const needsExternalSetup =
174 !active &&
175 !signedIn &&
176 (provider.setup?.canAuthenticate === false ||
177 (provider.driver === "acpRegistry" && state?.methods?.length === 0));
178 const url =
179 interaction?.type === "browser" || interaction?.type === "deviceCode"
180 ? interaction.url
181 : state?.authorizationUrl;
182 const disabled = pending || auth.error !== null || isDiscovering;
183 async function run(command: () => Promise<AtomCommandResult<unknown, unknown>>) {
184 if (pendingRef.current) return false;
185 pendingRef.current = true;
186 setPending(true);
187 setError(null);
188 const result = await command();
189 pendingRef.current = false;
190 setPending(false);
191 if (result._tag === "Success") return true;
192 if (!isAtomCommandInterrupted(result)) {
193 const failure = squashAtomCommandFailure(result);
194 setError(failure instanceof Error ? failure.message : "Could not update provider sign-in.");
195 }
196 return false;
197 }
198 function send(response: ProviderAuthResponse) {
199 if (!state?.flowId || !interaction) return Promise.resolve(false);
200 return run(() =>
201 respond({
202 environmentId,
203 input: { instanceId, flowId: state.flowId!, interactionId: interaction.id, response },
204 }),
205 );
206 }
207 function field(name: string, label: string, secret: boolean) {
208 return (
209 <TextInput
210 accessibilityLabel={label}
211 className="rounded-lg border border-border-subtle px-3 py-2 text-base text-foreground"
212 placeholderTextColorClassName="accent-foreground-muted"
213 placeholder={label}
214 secureTextEntry={secret}
215 autoCapitalize="none"
216 autoCorrect={false}
217 editable={!disabled}
218 maxLength={secret && interaction?.type === "terminal" ? 4_095 : 16_384}
219 value={values[name] ?? ""}
220 onChangeText={(value) => setDraft({ id: draftId, values: { ...values, [name]: value } })}
221 />
222 );
223 }
224 const name = provider.displayName ?? provider.driver;
225 const email = signedIn && !active && provider.enabled ? provider.auth.email?.trim() : undefined;
226 const methods = state?.methods ?? [];
227 // The status line says why a provider that is missing or turned off can't sign in.
228 const canSignIn =
229 !active &&
230 !needsExternalSetup &&
231 provider.setup?.canAuthenticate !== false &&
232 provider.enabled &&
233 provider.installed;
234 const signInDisabled = disabled || state === null;
235 const canSignOut =
236 !active && signedIn && (provider.auth.canLogout ?? provider.setup?.canAuthenticate);
237 const showCallback =
238 Boolean(url) && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction);
239 const usesCredentials =
240 provider.driver === "antigravity" &&
241 (provider.auth.type === "gemini-api-key" || provider.auth.type === "agent-platform");
242 const status =
243 active || state?.phase === "failed" || state?.phase === "cancelled"
244 ? state.message
245 : !provider.enabled
246 ? "Turned off"
247 : signedIn
248 ? "Signed in"
249 : isDiscovering
250 ? "Discovering sign-in methods…"
251 : needsExternalSetup
252 ? "No in-app sign-in advertised. Follow the provider's docs to finish setup."
253 : !provider.installed
254 ? "Not installed"
255 : usesCredentials
256 ? "Connect to load models"
257 : "Not signed in";
258 // A provider with several sign-in methods picks one from a menu on the same control.
259 const methodActions: MenuAction[] = methods.map((method) => ({
260 id: `method:${method.id}`,
261 title: method.name,
262 }));
263 function startSignIn(methodId?: string) {
264 void run(() => start(methodId ? { environmentId, input: { instanceId, methodId } } : target));
265 }
266 function signOut() {
267 Dialog.alert(
268 "Sign out?",
269 `Running threads sharing this sign-in on ${environment.label} will stop. Thread history is kept.`,
270 [
271 { text: "Cancel", style: "cancel" },
272 {
273 text: "Sign out",
274 style: "destructive",
275 onPress: () => {
276 void run(() => logout(target));
277 },
278 },
279 ],
280 );
281 }
282 function onMenuAction(id: string) {
283 if (id === "signOut") signOut();
284 // iOS keeps a disabled submenu's children selectable, so sign-in guards here too.
285 else if (signInDisabled) return;
286 else if (id.startsWith("method:")) startSignIn(id.slice("method:".length));
287 else if (id === "change") startSignIn();
288 }
289 const accountActions: MenuAction[] = [
290 ...(canSignIn
291 ? [
292 {
293 id: "change",
294 title: "Change account",
295 image: "person.crop.circle",
296 attributes: { disabled: signInDisabled },
297 ...(methodActions.length > 1
298 ? {
299 subactions: methodActions.map((action) => ({
300 ...action,
301 attributes: { disabled: signInDisabled },
302 })),
303 }
304 : {}),
305 },
306 ]
307 : []),
308 ...(canSignOut
309 ? [
310 {
311 id: "signOut",
312 title: "Sign out",
313 image: "rectangle.portrait.and.arrow.right",
314 attributes: { destructive: true, disabled: disabled || state === null },
315 },
316 ]
317 : []),
318 ];
319 const trailing = pending ? (
320 <View className="h-11 w-11 items-center justify-center">
321 <AppActivityIndicator colorClassName="accent-icon" />
322 </View>
323 ) : needsExternalSetup && provider.setup?.documentationUrl ? (
324 <ControlPill
325 variant="pill"
326 label="Docs"
327 onPress={() => {
328 void Linking.openURL(provider.setup!.documentationUrl!).catch(() =>
329 setError("Could not open the provider docs."),
330 );
331 }}
332 />
333 ) : active && state?.flowId ? (
334 <ControlPill
335 variant="pill"
336 label="Cancel"
337 accessibilityLabel={`Cancel ${name} sign-in`}
338 disabled={disabled}
339 onPress={() => {
340 void run(() => cancel({ environmentId, input: { instanceId, flowId: state.flowId! } }));
341 }}
342 />
343 ) : signedIn && !active && accountActions.length > 0 ? (
344 <Menu
345 accessible
346 accessibilityRole="button"
347 accessibilityLabel={`${name} account options`}
348 title={name}
349 actions={accountActions}
350 onPressAction={({ nativeEvent }) => onMenuAction(nativeEvent.event)}
351 >
352 <ControlPill icon="ellipsis" accessibilityLabel={`${name} account options`} />
353 </Menu>
354 ) : canSignIn && !signedIn && methodActions.length > 1 && !signInDisabled ? (
355 <Menu
356 accessible
357 accessibilityRole="button"
358 accessibilityLabel={`Sign in to ${name}`}
359 title="Sign in with"
360 actions={methodActions}
361 onPressAction={({ nativeEvent }) => onMenuAction(nativeEvent.event)}
362 >
363 <ControlPill variant="primary" label="Sign in" accessibilityLabel={`Sign in to ${name}`} />
364 </Menu>
365 ) : canSignIn && !signedIn ? (
366 <ControlPill
367 variant="primary"
368 label={usesCredentials ? "Connect" : "Sign in"}
369 accessibilityLabel={usesCredentials ? `Connect to ${name}` : `Sign in to ${name}`}
370 disabled={signInDisabled}
371 onPress={() => startSignIn()}
372 />
373 ) : null;
374 return (
375 <View className={divider ? "border-t border-border-subtle" : undefined}>
376 <View
377 className={
378 stacked
379 ? "min-h-16 items-start gap-3 px-4 py-3"
380 : "min-h-16 flex-row items-center gap-3 px-4 py-3"
381 }
382 >
383 <ProviderAccountSummary key={email} name={name} status={status} email={email} />
384 {trailing}
385 </View>
386 {interaction?.type === "deviceCode" ||
387 interaction?.type === "terminal" ||
388 interaction?.type === "credentials" ||
389 showCallback ||
390 error ||
391 auth.error ? (
392 <View className="gap-2 px-4 pb-3">
393 {interaction?.type === "deviceCode" ? (
394 <Text selectable className="text-foreground">
395 Enter code {interaction.userCode} on the sign-in page.
396 </Text>
397 ) : null}
398 {interaction?.type === "terminal" ? (
399 <>
400 <ScrollView className="max-h-64" nestedScrollEnabled>
401 <Text selectable className="font-mono text-sm text-foreground">
402 {interaction.output.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")}
403 </Text>
404 </ScrollView>
405 {field("input", "Terminal response", true)}
406 <SettingsActionRow
407 icon="arrow.up"
408 label="Send response"
409 disabled={disabled}
410 onPress={() => {
411 void send({ type: "terminal", data: `${values.input ?? ""}\r` }).then((sent) => {
412 if (sent) setDraft({ id: "", values: {} });
413 });
414 }}
415 />
416 </>
417 ) : null}
418 {interaction?.type === "credentials" ? (
419 <>
420 {interaction.fields.map((entry) => (
421 <View key={entry.name}>{field(entry.name, entry.label, entry.secret)}</View>
422 ))}
423 <SettingsActionRow
424 icon="person.crop.circle"
425 label="Connect"
426 disabled={disabled}
427 onPress={() => {
428 void send({ type: "credentials", values }).then((sent) => {
429 if (sent) setDraft({ id: "", values: {} });
430 });
431 }}
432 />
433 </>
434 ) : null}
435 {showCallback ? (
436 <>
437 {field("callback", "Final localhost URL", false)}
438 <SettingsActionRow
439 icon="arrow.right"
440 label="Continue"
441 disabled={disabled || !values.callback?.trim()}
442 onPress={() => {
443 if (!state?.flowId) return;
444 void run(() =>
445 complete({
446 environmentId,
447 input: { instanceId, flowId: state.flowId!, callbackUrl: values.callback! },
448 }),
449 ).then((sent) => {
450 if (sent) setDraft({ id: "", values: {} });
451 });
452 }}
453 />
454 </>
455 ) : null}
456 {error || auth.error ? (
457 <Text accessibilityRole="alert" className="text-danger-foreground">
458 {error ?? auth.error}
459 </Text>
460 ) : null}
461 </View>
462 ) : null}
463 {url ? (
464 <SettingsActionRow
465 icon="globe"
466 label="Open sign-in page"
467 disabled={disabled}
468 onPress={() => {
469 void (async () => {
470 if (
471 interaction?.type === "browser" &&
472 interaction.requiresConsent &&
473 !(await send({ type: "browser", action: "accept" }))
474 )
475 return;
476 await Linking.openURL(url);
477 })().catch(() => setError("Could not open the sign-in page."));
478 }}
479 />
480 ) : null}
481 </View>
482 );
483}
484
485function ProviderAccountSummary({
486 name,
487 status,
488 email,
489}: {
490 readonly name: string;
491 readonly status: string | null | undefined;
492 readonly email: string | undefined;
493}) {
494 const [revealed, setRevealed] = useState(false);
495 const content = (
496 <>
497 <Text textRole="body" className="text-foreground" numberOfLines={1}>
498 {name}
499 </Text>
500 <Text accessibilityLiveRegion="polite" textRole="footnote" className="text-foreground-muted">
501 {email ? `${status} · ${revealed ? email : "••••••@••••••"}` : status}
502 </Text>
503 </>
504 );
505 if (!email) {
506 return (
507 <View
508 accessible
509 accessibilityLabel={[name, status].filter(Boolean).join(", ")}
510 className="min-w-0 shrink grow gap-0.5"
511 >
512 {content}
513 </View>
514 );
515 }
516 return (
517 <Pressable
518 accessibilityRole="button"
519 accessibilityLabel={[name, status, revealed ? email : null].filter(Boolean).join(", ")}
520 accessibilityHint={revealed ? "Hides the account email" : "Reveals the account email"}
521 onPress={() => setRevealed((value) => !value)}
522 className="min-w-0 shrink grow gap-0.5"
523 >
524 {content}
525 </Pressable>
526 );
527}