Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
3import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
4import {
5 ANTIGRAVITY_AUTH_METHODS,
6 AuthOrchestrationOperateScope,
7 EnvironmentId,
8 ProviderInstanceId,
9} from "@t3tools/contracts";
10import * as Schema from "effect/Schema";
11import { AsyncResult } from "effect/unstable/reactivity";
12import { useCallback, useEffect, useRef, useState } from "react";
13import { Alert, Platform, Pressable, ScrollView, View } from "react-native";
14import { useSafeAreaInsets } from "react-native-safe-area-context";
15
16import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
17import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
18import { ProviderIcon } from "../../components/ProviderIcon";
19import { cn } from "../../lib/cn";
20import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
21import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
22import { NativeStackScreenOptions } from "../../native/StackHeader";
23import { appAtomRegistry } from "../../state/atom-registry";
24import { useEnvironments } from "../../state/environments";
25import { useEnvironmentQuery } from "../../state/query";
26import { serverEnvironment } from "../../state/server";
27import { environmentSession } from "../../state/session";
28import { useAtomCommand } from "../../state/use-atom-command";
29import {
30 antigravityEnabledPatch,
31 readAntigravityAuthMethod,
32 resolveProviderSignInPresentation,
33} from "./provider-setup-state";
34
35export type ProviderSetupRouteParams = {
36 readonly environmentId: EnvironmentId;
37 readonly instanceId: ProviderInstanceId;
38};
39
40const PRIVATE_COMMAND_OPTIONS = { reportFailure: false, reportDefect: false } as const;
41const isEnvironmentId = Schema.is(EnvironmentId);
42const isProviderInstanceId = Schema.is(ProviderInstanceId);
43
44function SetupButton(props: {
45 readonly label: string;
46 readonly disabled?: boolean;
47 readonly primary?: boolean;
48 readonly destructive?: boolean;
49 readonly onPress: () => void;
50}) {
51 return (
52 <Pressable
53 accessibilityRole="button"
54 disabled={props.disabled}
55 onPress={props.onPress}
56 className={cn(
57 "min-h-11 items-center justify-center border border-white/25 px-4 py-3 active:opacity-70 disabled:opacity-40",
58 props.primary && "bg-white",
59 )}
60 >
61 <Text
62 className={cn(
63 "text-base font-t3-medium text-white",
64 props.primary && "text-black",
65 props.destructive && "text-red-400",
66 )}
67 >
68 {props.label}
69 </Text>
70 </Pressable>
71 );
72}
73
74/** The same screen stays inside Settings or the current model picker. */
75export function SettingsProviderSetupRouteScreen({
76 route,
77}: StaticScreenProps<ProviderSetupRouteParams>) {
78 if (
79 !isEnvironmentId(route.params?.environmentId) ||
80 !isProviderInstanceId(route.params?.instanceId)
81 ) {
82 return (
83 <View className="flex-1 bg-black p-5">
84 <Text className="text-base text-white">This provider link is not valid.</Text>
85 </View>
86 );
87 }
88 return (
89 <ProviderSetupScreen
90 key={`${route.params.environmentId}:${route.params.instanceId}`}
91 {...route.params}
92 />
93 );
94}
95
96function ProviderSetupScreen({ environmentId, instanceId }: ProviderSetupRouteParams) {
97 const navigation = useNavigation();
98 const insets = useSafeAreaInsets();
99 const { presentationById } = useEnvironments();
100 const environment = presentationById.get(environmentId);
101 const environmentLabel = environment?.entry.target.label ?? "this environment";
102 const isConnected = environment?.connection.phase === "connected";
103 const config = useAtomValue(serverEnvironment.configValueAtom(environmentId));
104 const provider = config?.providers.find((item) => item.instanceId === instanceId);
105 const access = useEnvironmentQuery(environmentSession.sessionStateAtom(environmentId));
106 const canOperate =
107 access.data?.authenticated === true &&
108 access.data.scopes?.includes(AuthOrchestrationOperateScope) === true;
109 const target = { environmentId, input: { instanceId } };
110 const authQuery = useEnvironmentQuery(
111 canOperate && provider?.setup?.canAuthenticate
112 ? serverEnvironment.providerAuthState(target)
113 : null,
114 );
115 const installQuery = useEnvironmentQuery(
116 canOperate && provider?.setup?.canInstall
117 ? serverEnvironment.providerInstallState(target)
118 : null,
119 );
120 const auth = authQuery.data;
121 const installation = installQuery.data;
122 const startAuth = useAtomCommand(serverEnvironment.startProviderAuth, PRIVATE_COMMAND_OPTIONS);
123 const completeAuth = useAtomCommand(
124 serverEnvironment.completeProviderAuth,
125 PRIVATE_COMMAND_OPTIONS,
126 );
127 const cancelAuth = useAtomCommand(serverEnvironment.cancelProviderAuth, PRIVATE_COMMAND_OPTIONS);
128 const logout = useAtomCommand(serverEnvironment.logoutProviderAuth, PRIVATE_COMMAND_OPTIONS);
129 const startInstall = useAtomCommand(
130 serverEnvironment.startProviderInstall,
131 PRIVATE_COMMAND_OPTIONS,
132 );
133 const cancelInstall = useAtomCommand(
134 serverEnvironment.cancelProviderInstall,
135 PRIVATE_COMMAND_OPTIONS,
136 );
137 const removeInstall = useAtomCommand(
138 serverEnvironment.removeProviderInstallation,
139 PRIVATE_COMMAND_OPTIONS,
140 );
141 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, PRIVATE_COMMAND_OPTIONS);
142 const [callbackUrl, setCallbackUrl] = useState("");
143 const [error, setError] = useState<string | null>(null);
144 const [busy, setBusy] = useState(false);
145 const busyRef = useRef(false);
146 const authActive =
147 auth?.phase === "starting" || auth?.phase === "waiting" || auth?.phase === "verifying";
148 const installActive =
149 installation?.phase === "downloading" ||
150 installation?.phase === "extracting" ||
151 installation?.phase === "verifying";
152 const controlsDisabled = busy || !isConnected || !canOperate;
153 const {
154 signedIn,
155 showSignOut,
156 message: authMessage,
157 } = resolveProviderSignInPresentation(provider, auth);
158 const authMethod = readAntigravityAuthMethod(
159 config?.settings.providerInstances[instanceId]?.config ??
160 (instanceId === "antigravity" ? config?.settings.providers.antigravity : undefined),
161 );
162 const usesBrowser = authMethod === "oauth-personal" || authMethod === "oauth-business";
163 const methodLabel =
164 ANTIGRAVITY_AUTH_METHODS.find((method) => method.value === authMethod)?.label ??
165 "Google account";
166
167 // Return URLs never enter saved drafts, navigation params, or diagnostics.
168 useEffect(() => {
169 setCallbackUrl("");
170 }, [auth?.flowId, auth?.phase]);
171
172 const perform = useCallback(
173 async (command: () => Promise<AtomCommandResult<unknown, unknown>>, failureMessage: string) => {
174 if (busyRef.current || !isConnected || !canOperate) return false;
175 busyRef.current = true;
176 setBusy(true);
177 setError(null);
178 try {
179 const result = await command();
180 if (!AsyncResult.isSuccess(result)) {
181 setError(failureMessage);
182 return false;
183 }
184 return true;
185 } catch {
186 setError(failureMessage);
187 return false;
188 } finally {
189 busyRef.current = false;
190 setBusy(false);
191 }
192 },
193 [canOperate, isConnected],
194 );
195
196 const setEnabled = (enabled: boolean) => {
197 const currentConfig = appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId));
198 const currentProvider = currentConfig?.providers.find((item) => item.instanceId === instanceId);
199 if (!currentConfig || !currentProvider) return;
200 const patch = antigravityEnabledPatch(currentConfig.settings, currentProvider, enabled);
201 if (!patch) return;
202 void perform(
203 () => updateSettings({ environmentId, input: { patch } }),
204 "Could not change this provider. Reconnect and try again.",
205 );
206 };
207
208 const title = provider?.displayName ?? "Antigravity";
209 return (
210 <View className="flex-1 bg-black">
211 <NativeStackScreenOptions
212 options={{
213 title,
214 headerShown: Platform.OS !== "android",
215 headerTransparent: false,
216 headerStyle: { backgroundColor: "#000" },
217 headerTintColor: "#fff",
218 contentStyle: { backgroundColor: "#000" },
219 }}
220 />
221 {Platform.OS === "android" ? (
222 <AndroidScreenHeader title={title} onBack={() => navigation.goBack()} />
223 ) : null}
224 <ScrollView
225 className="flex-1"
226 contentInsetAdjustmentBehavior="automatic"
227 contentContainerClassName="gap-5 px-5 pt-5"
228 contentContainerStyle={{ paddingBottom: insets.bottom + 24 }}
229 keyboardShouldPersistTaps="handled"
230 showsVerticalScrollIndicator={false}
231 >
232 <View className="flex-row items-center gap-3">
233 <ProviderIcon provider="antigravity" size={28} />
234 <Text className="min-w-0 flex-1 text-base text-white">{environmentLabel}</Text>
235 </View>
236 {!isConnected ? (
237 <Text className="text-base text-white">
238 Reconnect to this environment to continue setup.
239 </Text>
240 ) : access.error ? (
241 <View className="gap-3">
242 <Text className="text-base text-white">Could not check your environment access.</Text>
243 <SetupButton label="Retry" onPress={access.refresh} />
244 </View>
245 ) : !access.data ? (
246 <Text className="text-base text-white">Checking environment access.</Text>
247 ) : !canOperate ? (
248 <Text className="text-base text-white">
249 This connection cannot manage providers. Pair again with permission to operate this
250 environment.
251 </Text>
252 ) : null}
253 {!config ? (
254 <Text className="text-base text-white">Loading provider settings.</Text>
255 ) : !provider || provider.driver !== "antigravity" ? (
256 <Text className="text-base text-white">
257 This provider is not available on this environment.
258 </Text>
259 ) : (
260 <>
261 <View className="gap-3">
262 <Text className="text-base text-white">
263 {provider.enabled ? "Enabled" : "Disabled"}
264 {provider.installed
265 ? `. Installed${provider.version ? ` ${provider.version}` : ""}`
266 : ". Not installed"}
267 </Text>
268 <SetupButton
269 label={provider.enabled ? "Disable Antigravity" : "Enable Antigravity"}
270 disabled={controlsDisabled}
271 onPress={() => {
272 if (!provider.enabled) {
273 setEnabled(true);
274 return;
275 }
276 Alert.alert(
277 "Disable Antigravity?",
278 `This stops Antigravity sessions on ${environmentLabel}. Google credentials stay saved.`,
279 [
280 { text: "Cancel", style: "cancel" },
281 { text: "Disable", style: "destructive", onPress: () => setEnabled(false) },
282 ],
283 );
284 }}
285 />
286 </View>
287 {provider.setup?.canInstall ? (
288 <View className="gap-3 border-t border-white/20 pt-4">
289 {installActive ? (
290 <>
291 <Text accessibilityLiveRegion="polite" className="text-base text-white">
292 {installation.phase === "downloading"
293 ? `Downloading ${Math.round(installation.downloadedBytes / 1_048_576)}${installation.totalBytes === null ? "" : ` of ${Math.round(installation.totalBytes / 1_048_576)}`} MB`
294 : installation.phase === "extracting"
295 ? "Extracting Antigravity files."
296 : "Checking the Antigravity installation."}
297 </Text>
298 <SetupButton
299 label="Cancel install"
300 disabled={controlsDisabled || installation.operationId === null}
301 onPress={() => {
302 const operationId = installation.operationId;
303 if (!operationId) return;
304 void perform(
305 () =>
306 cancelInstall({ environmentId, input: { instanceId, operationId } }),
307 "Could not cancel the install. Try again.",
308 );
309 }}
310 />
311 </>
312 ) : !provider.installed ? (
313 <SetupButton
314 label={
315 installation?.phase === "failed" || installation?.phase === "cancelled"
316 ? "Retry install"
317 : "Install Antigravity"
318 }
319 primary
320 disabled={controlsDisabled || authActive}
321 onPress={() =>
322 void perform(
323 () => startInstall(target),
324 "Could not start the install. Try again.",
325 )
326 }
327 />
328 ) : null}
329 {installation?.message ? (
330 <Text className="text-sm text-white">{installation.message}</Text>
331 ) : null}
332 {installation?.canRemove && !installActive ? (
333 <SetupButton
334 label="Remove managed install"
335 destructive
336 disabled={controlsDisabled || authActive}
337 onPress={() => {
338 Alert.alert(
339 "Remove the Antigravity install?",
340 `This removes T3's managed install from ${environmentLabel}. Providers that use it will need it installed again. Google credentials and threads stay.`,
341 [
342 { text: "Cancel", style: "cancel" },
343 {
344 text: "Remove",
345 style: "destructive",
346 onPress: () =>
347 void perform(
348 () => removeInstall(target),
349 "Could not remove the managed install. Try again.",
350 ),
351 },
352 ],
353 );
354 }}
355 />
356 ) : null}
357 {installQuery.error ? (
358 <Text className="text-sm text-white">
359 Install status is unavailable. Reconnect and try again.
360 </Text>
361 ) : null}
362 </View>
363 ) : !provider.installed ? (
364 <Text className="text-base text-white">
365 Antigravity cannot be installed on this environment. Use a supported server host or
366 set an executable path in provider settings.
367 </Text>
368 ) : null}
369 {provider.setup?.canAuthenticate ? (
370 <View className="gap-3 border-t border-white/20 pt-4">
371 <Text className="text-lg font-t3-medium text-white">{methodLabel}</Text>
372 <Text className="text-base text-white">
373 {signedIn
374 ? "Signed in. Credentials stay on this environment."
375 : provider.auth.status === "unknown"
376 ? "Sign-in has not been checked."
377 : usesBrowser
378 ? "Sign in with the Google account you use for Antigravity."
379 : "Connect with the credentials set in provider settings on web or desktop."}
380 </Text>
381 {authActive ? (
382 <>
383 <Text accessibilityLiveRegion="polite" className="text-base text-white">
384 {auth.phase === "starting"
385 ? usesBrowser
386 ? "Starting Google sign-in."
387 : "Checking credentials."
388 : auth.phase === "verifying"
389 ? usesBrowser
390 ? "Checking Google sign-in."
391 : "Checking credentials."
392 : auth.authorizationUrl
393 ? "Complete sign-in in your browser."
394 : "Sign-in is open on another client. Complete it there or wait for it to expire."}
395 </Text>
396 {auth.authorizationUrl && auth.phase === "waiting" ? (
397 <>
398 <SetupButton
399 label="Open Google sign-in"
400 primary
401 disabled={controlsDisabled}
402 onPress={() => {
403 if (!auth.authorizationUrl) return;
404 void tryOpenExternalUrl(auth.authorizationUrl, "provider-auth").then(
405 (opened) => {
406 if (!opened)
407 setError(
408 "Could not open Google sign-in. Copy the link and open it in your browser.",
409 );
410 },
411 );
412 }}
413 />
414 <SetupButton
415 label="Copy sign-in link"
416 disabled={controlsDisabled}
417 onPress={() => {
418 if (!auth.authorizationUrl) return;
419 void tryCopyTextWithHaptic(auth.authorizationUrl, {
420 target: "provider-sign-in-link",
421 }).then((copied) => {
422 if (!copied) setError("Could not copy the sign-in link.");
423 });
424 }}
425 />
426 <Text className="text-sm leading-5 text-white">
427 After sign-in, the browser will open a 127.0.0.1 address that cannot load
428 on your phone. Copy that full address and paste it here.
429 </Text>
430 <TextInput
431 accessibilityLabel="Google sign-in return URL"
432 autoCapitalize="none"
433 autoComplete="off"
434 autoCorrect={false}
435 className="min-h-12 rounded-none border border-white/25 bg-black px-3 py-3 text-base text-white"
436 editable={!controlsDisabled}
437 keyboardType="url"
438 onChangeText={setCallbackUrl}
439 placeholder="http://127.0.0.1:.../"
440 textContentType="none"
441 value={callbackUrl}
442 />
443 <SetupButton
444 label="Complete sign-in"
445 primary
446 disabled={
447 controlsDisabled || callbackUrl.trim().length === 0 || !auth.flowId
448 }
449 onPress={() => {
450 const flowId = auth.flowId;
451 if (!flowId) return;
452 const submittedUrl = callbackUrl.trim();
453 setCallbackUrl("");
454 void perform(
455 () =>
456 completeAuth({
457 environmentId,
458 input: { instanceId, flowId, callbackUrl: submittedUrl },
459 }),
460 "Could not complete Google sign-in. Check the return URL and try again.",
461 );
462 }}
463 />
464 </>
465 ) : null}
466 {auth.expiresAt ? (
467 <Text className="text-sm text-white">
468 Sign-in expires at{" "}
469 {new Date(auth.expiresAt).toLocaleTimeString([], {
470 hour: "numeric",
471 minute: "2-digit",
472 })}
473 .
474 </Text>
475 ) : null}
476 {auth.flowId ? (
477 <SetupButton
478 label="Cancel sign-in"
479 disabled={controlsDisabled}
480 onPress={() => {
481 const flowId = auth.flowId;
482 if (!flowId) return;
483 setCallbackUrl("");
484 void perform(
485 () => cancelAuth({ environmentId, input: { instanceId, flowId } }),
486 "Could not cancel sign-in. Try again.",
487 );
488 }}
489 />
490 ) : null}
491 </>
492 ) : showSignOut ? (
493 <SetupButton
494 label={usesBrowser ? "Sign out of Google" : "Disconnect"}
495 destructive
496 disabled={controlsDisabled}
497 onPress={() => {
498 Alert.alert(
499 usesBrowser ? "Sign out of Google?" : "Disconnect Antigravity?",
500 `This stops Antigravity sessions for ${title} on ${environmentLabel}. Threads and files stay.`,
501 [
502 { text: "Cancel", style: "cancel" },
503 {
504 text: "Sign out",
505 style: "destructive",
506 onPress: () =>
507 void perform(
508 () => logout(target),
509 "Could not sign out of Google. Try again.",
510 ),
511 },
512 ],
513 );
514 }}
515 />
516 ) : (
517 <SetupButton
518 label={
519 usesBrowser
520 ? auth?.phase === "failed" || auth?.phase === "cancelled"
521 ? "Retry Google sign-in"
522 : "Sign in with Google"
523 : auth?.phase === "failed" || auth?.phase === "cancelled"
524 ? "Retry connection"
525 : "Connect"
526 }
527 primary
528 disabled={
529 controlsDisabled ||
530 !provider.enabled ||
531 !provider.installed ||
532 installActive ||
533 authQuery.isPending
534 }
535 onPress={() =>
536 void perform(
537 () => startAuth(target),
538 "Could not start Google sign-in. Try again.",
539 )
540 }
541 />
542 )}
543 {!provider.enabled && !signedIn ? (
544 <Text className="text-sm text-white">Enable Antigravity to sign in.</Text>
545 ) : !provider.installed && !signedIn ? (
546 <Text className="text-sm text-white">Install Antigravity to sign in.</Text>
547 ) : null}
548 {authMessage ? <Text className="text-sm text-white">{authMessage}</Text> : null}
549 {authQuery.error ? (
550 <Text className="text-sm text-white">
551 Sign-in status is unavailable. Reconnect and try again.
552 </Text>
553 ) : null}
554 </View>
555 ) : null}
556 {provider.message ? (
557 <Text className="text-sm text-white">{provider.message}</Text>
558 ) : null}
559 </>
560 )}
561 {error ? (
562 <Text accessibilityRole="alert" className="text-base text-red-400">
563 {error}
564 </Text>
565 ) : null}
566 {busy ? (
567 <Text accessibilityLiveRegion="polite" className="text-sm text-white">
568 Waiting for the environment.
569 </Text>
570 ) : null}
571 </ScrollView>
572 </View>
573 );
574}