Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SettingsProviderAccountsRouteScreen.tsx

578 lines21.2 KB

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