@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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