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, View } from "react-native";
15import { useSafeAreaInsets } from "react-native-safe-area-context";
16
17import { AppText as Text } from "../../components/ui/AppText";
18import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
19import { environmentPresentations } from "../../state/presentation";
20import { useEnvironmentQuery } from "../../state/query";
21import { serverEnvironment } from "../../state/server";
22import { useEnvironmentsWithScope } from "../../state/session";
23import { useAtomCommand } from "../../state/use-atom-command";
24import { SettingsActionRow } from "./components/SettingsActionRow";
25import {
26 AndroidSettingsEnvironmentFilter,
27 SettingsEnvironmentFilterHeader,
28} from "./components/SettingsEnvironmentFilterHeader";
29import { SettingsScreen } from "./components/SettingsScreen";
30import { SettingsSection } from "./components/SettingsSection";
31import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter";
32
33export function SettingsProviderAccountsRouteScreen() {
34 const { selectedTargets } = useSettingsEnvironmentFilter();
35 const permittedEnvironments = useEnvironmentsWithScope(selectedTargets, AuthProvidersManageScope);
36 const providersByEnvironment = useAtomValue(environmentPresentations.providersByEnvironmentAtom);
37 const insets = useSafeAreaInsets();
38 return (
39 <>
40 <SettingsEnvironmentFilterHeader />
41 <SettingsScreen title="Provider accounts" trailing={<AndroidSettingsEnvironmentFilter />}>
42 <ScreenScrollView
43 className="flex-1"
44 contentInsetAdjustmentBehavior="automatic"
45 contentContainerClassName="gap-6 px-5 pt-4"
46 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
47 >
48 {selectedTargets.length === 0 ? (
49 <Text className="text-foreground-muted">Select a connected environment.</Text>
50 ) : (
51 selectedTargets.map((environment) => (
52 <SettingsSection key={environment.environmentId} title={environment.label}>
53 {!permittedEnvironments.has(environment.environmentId) ? (
54 <View className="gap-1 p-4">
55 <Text className="text-base text-foreground">Limited permissions</Text>
56 <Text className="text-sm text-foreground-muted">
57 {`This session can view ${environment.label}'s providers but can't change their settings.`}
58 </Text>
59 </View>
60 ) : (
61 <>
62 {(providersByEnvironment.get(environment.environmentId) ?? [])
63 .filter(
64 (provider) =>
65 provider.setup?.canAuthenticate ||
66 (provider.driver === "acpRegistry" && provider.installed),
67 )
68 .map((provider) => (
69 <ProviderAccount
70 key={provider.instanceId}
71 environment={environment}
72 provider={provider}
73 />
74 ))}
75 {!(providersByEnvironment.get(environment.environmentId) ?? []).some(
76 (provider) =>
77 provider.setup?.canAuthenticate ||
78 (provider.driver === "acpRegistry" && provider.installed),
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 ProviderAccount({
96 environment,
97 provider,
98}: {
99 readonly environment: SettingsTarget;
100 readonly provider: ServerProvider;
101}) {
102 const environmentId = environment.environmentId;
103 const instanceId = provider.instanceId;
104 const target = { environmentId, input: { instanceId } };
105 const auth = useEnvironmentQuery(serverEnvironment.providerAuthState(target));
106 const options = { reportFailure: false, reportDefect: false };
107 const start = useAtomCommand(serverEnvironment.startProviderAuth, options);
108 const respond = useAtomCommand(serverEnvironment.respondProviderAuth, options);
109 const complete = useAtomCommand(serverEnvironment.completeProviderAuth, options);
110 const cancel = useAtomCommand(serverEnvironment.cancelProviderAuth, options);
111 const logout = useAtomCommand(serverEnvironment.logoutProviderAuth, options);
112 const [pending, setPending] = useState(false);
113 const [choosingMethod, setChoosingMethod] = useState(false);
114 const pendingRef = useRef(false);
115 const [error, setError] = useState<string | null>(null);
116 const [draft, setDraft] = useState({ id: "", values: {} as Record<string, string> });
117 const state = auth.data;
118 const interaction = state?.interaction;
119 const draftId = `${state?.flowId ?? ""}:${interaction?.id ?? ""}`;
120 const values = draft.id === draftId ? draft.values : {};
121 const active =
122 state?.phase === "starting" || state?.phase === "waiting" || state?.phase === "verifying";
123 const signedIn =
124 provider.auth.status === "authenticated" ||
125 (provider.auth.status === "unknown" && state?.phase === "succeeded");
126 const isDiscovering =
127 provider.driver === "acpRegistry" &&
128 !active &&
129 !signedIn &&
130 !auth.error &&
131 state?.methods === undefined;
132 const needsExternalSetup =
133 !active &&
134 !signedIn &&
135 (provider.setup?.canAuthenticate === false ||
136 (provider.driver === "acpRegistry" && state?.methods?.length === 0));
137 const url =
138 interaction?.type === "browser" || interaction?.type === "deviceCode"
139 ? interaction.url
140 : state?.authorizationUrl;
141 const disabled = pending || auth.error !== null || isDiscovering;
142 async function run(command: () => Promise<AtomCommandResult<unknown, unknown>>) {
143 if (pendingRef.current) return false;
144 pendingRef.current = true;
145 setPending(true);
146 setError(null);
147 const result = await command();
148 pendingRef.current = false;
149 setPending(false);
150 if (result._tag === "Success") return true;
151 if (!isAtomCommandInterrupted(result)) {
152 const failure = squashAtomCommandFailure(result);
153 setError(failure instanceof Error ? failure.message : "Could not update provider sign-in.");
154 }
155 return false;
156 }
157 function send(response: ProviderAuthResponse) {
158 if (!state?.flowId || !interaction) return Promise.resolve(false);
159 return run(() =>
160 respond({
161 environmentId,
162 input: { instanceId, flowId: state.flowId!, interactionId: interaction.id, response },
163 }),
164 );
165 }
166 function field(name: string, label: string, secret: boolean) {
167 return (
168 <TextInput
169 accessibilityLabel={label}
170 className="rounded-lg border border-border-subtle px-3 py-2 text-base text-foreground"
171 placeholderTextColorClassName="accent-foreground-muted"
172 placeholder={label}
173 secureTextEntry={secret}
174 autoCapitalize="none"
175 autoCorrect={false}
176 editable={!disabled}
177 maxLength={secret && interaction?.type === "terminal" ? 4_095 : 16_384}
178 value={values[name] ?? ""}
179 onChangeText={(value) => setDraft({ id: draftId, values: { ...values, [name]: value } })}
180 />
181 );
182 }
183 function chooseMethod() {
184 const methods = state?.methods ?? [];
185 if (methods.length <= 1) {
186 void run(() => start(target));
187 return;
188 }
189 setChoosingMethod(true);
190 }
191 return (
192 <View className="border-b border-border-subtle">
193 <View className="gap-2 p-4">
194 <Text className="text-lg font-semibold text-foreground">
195 {provider.displayName ?? provider.driver}
196 </Text>
197 <Text accessibilityLiveRegion="polite" className="text-sm text-foreground-muted">
198 {active || state?.phase === "failed" || state?.phase === "cancelled"
199 ? state.message
200 : signedIn
201 ? "Signed in."
202 : isDiscovering
203 ? "Discovering sign-in methods…"
204 : needsExternalSetup
205 ? "No in-app sign-in advertised. Follow the provider's docs to finish setup."
206 : "Connect this provider."}
207 </Text>
208 {signedIn && !active && provider.auth.email?.trim() ? (
209 <ProviderAccountEmail key={provider.auth.email} email={provider.auth.email} />
210 ) : null}
211 {interaction?.type === "deviceCode" ? (
212 <Text selectable className="text-foreground">
213 Enter code {interaction.userCode} on the sign-in page.
214 </Text>
215 ) : null}
216 {interaction?.type === "terminal" ? (
217 <>
218 <ScrollView className="max-h-64" nestedScrollEnabled>
219 <Text selectable className="font-mono text-sm text-foreground">
220 {interaction.output.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "")}
221 </Text>
222 </ScrollView>
223 {field("input", "Terminal response", true)}
224 <SettingsActionRow
225 icon="arrow.up"
226 label="Send response"
227 disabled={disabled}
228 onPress={() => {
229 void send({ type: "terminal", data: `${values.input ?? ""}\r` }).then((sent) => {
230 if (sent) setDraft({ id: "", values: {} });
231 });
232 }}
233 />
234 </>
235 ) : null}
236 {interaction?.type === "credentials" ? (
237 <>
238 {interaction.fields.map((entry) => (
239 <View key={entry.name}>{field(entry.name, entry.label, entry.secret)}</View>
240 ))}
241 <SettingsActionRow
242 icon="person.crop.circle"
243 label="Connect"
244 disabled={disabled}
245 onPress={() => {
246 void send({ type: "credentials", values }).then((sent) => {
247 if (sent) setDraft({ id: "", values: {} });
248 });
249 }}
250 />
251 </>
252 ) : null}
253 {url && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction) ? (
254 <>
255 {field("callback", "Final localhost URL", false)}
256 <SettingsActionRow
257 icon="arrow.right"
258 label="Continue"
259 disabled={disabled || !values.callback?.trim()}
260 onPress={() => {
261 if (!state?.flowId) return;
262 void run(() =>
263 complete({
264 environmentId,
265 input: { instanceId, flowId: state.flowId!, callbackUrl: values.callback! },
266 }),
267 ).then((sent) => {
268 if (sent) setDraft({ id: "", values: {} });
269 });
270 }}
271 />
272 </>
273 ) : null}
274 {error || auth.error ? (
275 <Text accessibilityRole="alert" className="text-danger-foreground">
276 {error ?? auth.error}
277 </Text>
278 ) : null}
279 </View>
280 {choosingMethod && !active ? (
281 <View>
282 {state?.methods?.map((method) => (
283 <SettingsActionRow
284 key={method.id}
285 icon="person.crop.circle"
286 label={method.name}
287 disabled={disabled}
288 onPress={() => {
289 setChoosingMethod(false);
290 void run(() =>
291 start({ environmentId, input: { instanceId, methodId: method.id } }),
292 );
293 }}
294 />
295 ))}
296 <SettingsActionRow icon="xmark" label="Cancel" onPress={() => setChoosingMethod(false)} />
297 </View>
298 ) : null}
299 {url ? (
300 <SettingsActionRow
301 icon="globe"
302 label="Open sign-in page"
303 disabled={disabled}
304 onPress={() => {
305 void (async () => {
306 if (
307 interaction?.type === "browser" &&
308 interaction.requiresConsent &&
309 !(await send({ type: "browser", action: "accept" }))
310 )
311 return;
312 await Linking.openURL(url);
313 })().catch(() => setError("Could not open the sign-in page."));
314 }}
315 />
316 ) : null}
317 {needsExternalSetup && provider.setup?.documentationUrl ? (
318 <SettingsActionRow
319 icon="globe"
320 label="Open docs"
321 onPress={() => {
322 void Linking.openURL(provider.setup!.documentationUrl!).catch(() =>
323 setError("Could not open the provider docs."),
324 );
325 }}
326 />
327 ) : active && state?.flowId ? (
328 <SettingsActionRow
329 icon="xmark"
330 label="Cancel sign-in"
331 disabled={disabled}
332 onPress={() => {
333 void run(() => cancel({ environmentId, input: { instanceId, flowId: state.flowId! } }));
334 }}
335 />
336 ) : !active && !needsExternalSetup && provider.setup?.canAuthenticate !== false ? (
337 <SettingsActionRow
338 icon="person.crop.circle"
339 label={signedIn ? "Change account" : "Sign in"}
340 disabled={disabled || !provider.enabled || !provider.installed || state === null}
341 loading={pending}
342 onPress={chooseMethod}
343 />
344 ) : null}
345 {!active && signedIn && (provider.auth.canLogout ?? provider.setup?.canAuthenticate) ? (
346 <SettingsActionRow
347 icon="person.crop.circle"
348 label="Sign out"
349 tone="danger"
350 disabled={disabled || state === null}
351 onPress={() =>
352 Dialog.alert(
353 "Sign out?",
354 `Running threads sharing this sign-in on ${environment.label} will stop. Thread history is kept.`,
355 [
356 { text: "Cancel", style: "cancel" },
357 {
358 text: "Sign out",
359 style: "destructive",
360 onPress: () => {
361 void run(() => logout(target));
362 },
363 },
364 ],
365 )
366 }
367 />
368 ) : null}
369 </View>
370 );
371}
372
373function ProviderAccountEmail({ email }: { readonly email: string }) {
374 const [revealed, setRevealed] = useState(false);
375 return (
376 <Pressable
377 accessibilityRole="button"
378 accessibilityLabel={revealed ? "Hide account email" : "Reveal account email"}
379 onPress={() => setRevealed((value) => !value)}
380 className="min-h-[44px] justify-center"
381 >
382 <Text className="text-sm text-foreground-muted">{revealed ? email : "••••••@••••••"}</Text>
383 </Pressable>
384 );
385}