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