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