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

SettingsProviderAccountsRouteScreen.tsx

506 lines18.7 KB

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