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