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

ProviderSetupSection.tsx

483 lines18.4 KB

1import {
2 isAtomCommandInterrupted,
3 squashAtomCommandFailure,
4 type AtomCommandResult,
5} from "@t3tools/client-runtime/state/runtime";
6import {
7 ANTIGRAVITY_AUTH_METHODS,
8 type AntigravityAuthMethod,
9 type EnvironmentId,
10 type ProviderAuthState,
11 type ProviderInstanceId,
12 type ServerProvider,
13} from "@t3tools/contracts";
14import { useRef, useState } from "react";
15​
16import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";
17import { ensureLocalApi } from "../../localApi";
18import { useEnvironmentQuery } from "../../state/query";
19import { serverEnvironment } from "../../state/server";
20import { useAtomCommand } from "../../state/use-atom-command";
21import { Button } from "../ui/button";
22import { Input } from "../ui/input";
23​
24interface ProviderSetupSectionProps {
25 readonly environmentId: EnvironmentId;
26 readonly environmentLabel: string;
27 readonly instanceId: ProviderInstanceId;
28 readonly provider: ServerProvider | undefined;
29 readonly binaryPath?: string | undefined;
30 readonly authMethod?: AntigravityAuthMethod | undefined;
31 readonly enabled: boolean;
32 readonly readOnly: boolean;
33 readonly onEnable: () => void;
35​
36const AUTH_PHASE_LABELS: Record<ProviderAuthState["phase"], string> = {
37 idle: "Sign in with your Google account.",
38 starting: "Starting Google sign-in.",
39 waiting: "Waiting for Google sign-in.",
40 verifying: "Checking Google sign-in and available models.",
41 succeeded: "Google sign-in complete.",
42 failed: "Google sign-in failed.",
43 cancelled: "Google sign-in cancelled.",
44};
45​
46/** API key methods skip the browser, so the phases read as a credential check. */
47const CREDENTIAL_PHASE_LABELS: Record<ProviderAuthState["phase"], string> = {
48 idle: "Connect with the credentials in the provider settings.",
49 starting: "Checking credentials.",
50 waiting: "Checking credentials.",
51 verifying: "Checking credentials and available models.",
52 succeeded: "Connected.",
53 failed: "Could not connect with the configured credentials.",
54 cancelled: "Connection cancelled.",
55};
56​
57/** Read the configured method from the instance config. Unknown values fall back to personal. */
58export function readAntigravityAuthMethod(config: unknown): AntigravityAuthMethod {
59 const value =
60 config !== null && typeof config === "object" && "authMethod" in config
61 ? config.authMethod
62 : undefined;
63 return (
64 ANTIGRAVITY_AUTH_METHODS.find((method) => method.value === value)?.value ?? "oauth-personal"
65 );
67​
68/** Setup state belongs to the selected environment and is never saved in client settings. */
69export function ProviderSetupSection(props: ProviderSetupSectionProps) {
70 return (
71 <section aria-label="Antigravity setup" className="grid gap-3 text-xs">
72 <p>Antigravity runs on {props.environmentLabel}.</p>
73 {!props.enabled ? (
74 <div className="flex flex-wrap items-center gap-2">
75 <span className="text-muted-foreground">Enable it to use it in threads.</span>
76 {!props.readOnly ? (
77 <Button size="xs" variant="outline" onClick={props.onEnable}>
78 Enable Antigravity
79 </Button>
80 ) : null}
81 </div>
82 ) : null}
83 {props.readOnly ? (
84 <p className="text-muted-foreground">This connection cannot change provider setup.</p>
85 ) : props.provider?.setup === undefined ? (
86 <p className="text-muted-foreground">
87 Update this environment to install Antigravity and sign in with Google here.
88 </p>
89 ) : (
90 <ProviderSetupActions
91 key={`${props.environmentId}:${props.instanceId}`}
92 environmentId={props.environmentId}
93 environmentLabel={props.environmentLabel}
94 instanceId={props.instanceId}
95 provider={props.provider}
96 binaryPath={props.binaryPath}
97 authMethod={props.authMethod ?? "oauth-personal"}
98 enabled={props.enabled}
99 />
100 )}
101 </section>
102 );
104​
105function ProviderSetupActions({
106 environmentId,
107 environmentLabel,
108 instanceId,
109 provider,
110 enabled,
111 binaryPath,
112 authMethod,
113}: Pick<
114 ProviderSetupSectionProps,
115 "environmentId" | "environmentLabel" | "instanceId" | "enabled" | "binaryPath"
116> & {
117 readonly provider: ServerProvider;
118 readonly authMethod: AntigravityAuthMethod;
119}) {
120 const target = { environmentId, input: { instanceId } };
121 const usesBrowser = authMethod === "oauth-personal" || authMethod === "oauth-business";
122 const phaseLabels = usesBrowser ? AUTH_PHASE_LABELS : CREDENTIAL_PHASE_LABELS;
123 const methodLabel =
124 ANTIGRAVITY_AUTH_METHODS.find((method) => method.value === authMethod)?.label ??
125 "Google account";
126 const authQuery = useEnvironmentQuery(serverEnvironment.providerAuthState(target));
127 const installQuery = useEnvironmentQuery(serverEnvironment.providerInstallState(target));
128 const auth = authQuery.data;
129 const installation = installQuery.data;
130 const commandOptions = { reportFailure: false, reportDefect: false };
131 const startAuth = useAtomCommand(serverEnvironment.startProviderAuth, commandOptions);
132 const completeAuth = useAtomCommand(serverEnvironment.completeProviderAuth, commandOptions);
133 const cancelAuth = useAtomCommand(serverEnvironment.cancelProviderAuth, commandOptions);
134 const logoutAuth = useAtomCommand(serverEnvironment.logoutProviderAuth, commandOptions);
135 const startInstall = useAtomCommand(serverEnvironment.startProviderInstall, commandOptions);
136 const cancelInstall = useAtomCommand(serverEnvironment.cancelProviderInstall, commandOptions);
137 const removeInstall = useAtomCommand(
138 serverEnvironment.removeProviderInstallation,
139 commandOptions,
140 );
141 const [pendingLabel, setPendingLabel] = useState<string | null>(null);
142 const pendingRef = useRef(false);
143 const [error, setError] = useState<string | null>(null);
144 const [callbackDraft, setCallbackDraft] = useState({ flowId: null as string | null, value: "" });
145 const [copiedFlowId, setCopiedFlowId] = useState<string | null>(null);
146 const callbackUrl = callbackDraft.flowId === auth?.flowId ? callbackDraft.value : "";
147 const authActive =
148 auth?.phase === "starting" || auth?.phase === "waiting" || auth?.phase === "verifying";
149 const installActive =
150 installation?.phase === "downloading" ||
151 installation?.phase === "extracting" ||
152 installation?.phase === "verifying";
153 const usesCustomBinary = Boolean(binaryPath?.trim());
154 const installed =
155 provider.installed || (!usesCustomBinary && installation?.installedVersion != null);
156 const authenticated = provider.auth.status === "authenticated";
157 const authStatusMessage =
158 auth === null
159 ? "Reading sign-in status."
160 : authActive || auth.phase === "failed" || auth.phase === "cancelled"
161 ? (auth.message ?? phaseLabels[auth.phase])
162 : authenticated
163 ? usesBrowser
164 ? "Signed in with Google."
165 : "Connected."
166 : auth.phase === "idle" && auth.message
167 ? auth.message
168 : phaseLabels.idle;
169 const authorizationUrl = auth?.phase === "waiting" ? auth.authorizationUrl : null;
170 const queryError = authQuery.error ?? installQuery.error;
171 const actionsDisabled = pendingLabel !== null || queryError !== null;
172 const installationStatusMessage =
173 installation?.phase === "downloading"
174 ? `Downloading ${(installation.downloadedBytes / 1_000_000).toFixed(1)} MB${installation.totalBytes === null ? "" : ` of ${(installation.totalBytes / 1_000_000).toFixed(1)} MB`}.`
175 : installation?.phase === "extracting"
176 ? "Extracting Antigravity."
177 : installation?.phase === "verifying"
178 ? "Checking the downloaded runtime."
179 : installed
180 ? "Antigravity is installed."
181 : usesCustomBinary
182 ? enabled
183 ? "The configured Antigravity runtime is unavailable."
184 : "The configured Antigravity runtime has not been checked."
185 : "Install the official Antigravity runtime before signing in.";
186​
187 async function runCommand<A, E>(
188 label: string,
189 request: () => Promise<AtomCommandResult<A, E>>,
190 ): Promise<boolean> {
191 if (pendingRef.current) return false;
192 pendingRef.current = true;
193 setPendingLabel(label);
194 setError(null);
195 try {
196 const result = await request();
197 if (result._tag === "Failure") {
198 if (!isAtomCommandInterrupted(result)) {
199 const failure = squashAtomCommandFailure(result);
200 setError(failure instanceof Error ? failure.message : "Provider setup failed.");
201 }
202 return false;
203 }
204 return true;
205 } catch {
206 setError("Provider setup failed. Try again.");
207 return false;
208 } finally {
209 pendingRef.current = false;
210 setPendingLabel(null);
211 }
212 }
213​
214 async function openSignInPage() {
215 if (!authorizationUrl) return;
216 try {
217 await ensureLocalApi().shell.openExternal(authorizationUrl);
218 setError(null);
219 } catch {
220 setError("Could not open the sign-in page. Copy the link and open it in your browser.");
221 }
222 }
223​
224 async function copySignInLink() {
225 if (!authorizationUrl) return;
226 try {
227 await writeTextToClipboard(authorizationUrl, "Google sign-in link");
228 setCopiedFlowId(auth?.flowId ?? null);
229 setError(null);
230 } catch {
231 setError("Could not copy the sign-in link. Use Open sign-in page.");
232 }
233 }
234​
235 async function submitCallback() {
236 const flowId = auth?.flowId;
237 if (!flowId || !callbackUrl.trim() || auth.phase !== "waiting") return;
238 const accepted = await runCommand("Checking redirect", () =>
239 completeAuth({ environmentId, input: { instanceId, flowId, callbackUrl } }),
240 );
241 if (accepted) {
242 setCallbackDraft({ flowId: null, value: "" });
243 }
244 }
245​
246 async function signOut() {
247 const confirmed = await ensureLocalApi().dialogs.confirm(
248 `${usesBrowser ? "Sign out of Google" : "Disconnect"} for ${provider.displayName ?? "Antigravity"} on ${environmentLabel}? This stops its running threads. Thread history is kept.`,
249 );
250 if (confirmed) {
251 await runCommand("Signing out", () => logoutAuth(target));
252 }
253 }
254​
255 async function removeRuntime() {
256 const confirmed = await ensureLocalApi().dialogs.confirm(
257 `Remove the downloaded Antigravity runtime from ${environmentLabel}? Google sign-in and thread history are kept.`,
258 );
259 if (confirmed) {
260 await runCommand("Removing runtime", () => removeInstall(target));
261 }
262 }
263​
264 return (
265 <div className="grid gap-3">
266 <div className="grid gap-2">
267 <p className="font-medium">Runtime</p>
268 <p role="status" className="text-muted-foreground">
269 {installationStatusMessage}
270 </p>
271 {installation?.phase === "downloading" &&
272 installation.totalBytes !== null &&
273 installation.totalBytes > 0 ? (
274 <progress
275 aria-label="Antigravity download"
276 className="h-1 w-full accent-foreground"
277 value={installation.downloadedBytes}
278 max={installation.totalBytes}
279 />
280 ) : null}
281 {installation?.message && installation.message !== installationStatusMessage ? (
282 <p className="text-muted-foreground [overflow-wrap:anywhere]">{installation.message}</p>
283 ) : null}
284 {usesCustomBinary ? (
285 <p className="text-muted-foreground">
286 This instance uses the binary path below. Installing a managed runtime does not change
287 that path.
288 </p>
289 ) : null}
290 {!installed && !usesCustomBinary && !installActive && installation?.totalBytes ? (
291 <p className="text-muted-foreground">
292 Downloads {Math.ceil(installation.totalBytes / 1_000_000)} MB from Google.
293 </p>
294 ) : null}
295 {!installed && !provider.setup?.canInstall ? (
296 <p className="text-muted-foreground">
297 Automatic installation is unavailable here. Set an existing binary path below or use a
298 supported remote environment.
299 </p>
300 ) : null}
301 <div className="flex flex-wrap gap-2">
302 {installActive && installation.operationId ? (
303 <Button
304 size="xs"
305 variant="outline"
306 disabled={actionsDisabled}
307 onClick={() => {
308 const operationId = installation.operationId;
309 if (!operationId) return;
310 void runCommand("Cancelling installation", () =>
311 cancelInstall({ environmentId, input: { instanceId, operationId } }),
312 );
313 }}
314 >
315 Cancel installation
316 </Button>
317 ) : !installActive && provider.setup?.canInstall ? (
318 <Button
319 size="xs"
320 variant="outline"
321 disabled={actionsDisabled || installation === null || authActive}
322 onClick={() => void runCommand("Starting installation", () => startInstall(target))}
323 >
324 {installation?.installedVersion
325 ? installation.version && installation.version !== installation.installedVersion
326 ? "Update Antigravity"
327 : "Reinstall Antigravity"
328 : installation?.phase === "failed" || installation?.phase === "cancelled"
329 ? "Retry installation"
330 : installed
331 ? "Install managed runtime"
332 : "Install Antigravity"}
333 </Button>
334 ) : null}
335 {installation?.canRemove && !installActive ? (
336 <Button
337 size="xs"
338 variant="ghost"
339 disabled={actionsDisabled || authActive}
340 onClick={() => void removeRuntime()}
341 >
342 Remove downloaded runtime
343 </Button>
344 ) : null}
345 </div>
346 </div>
347​
348 <div className="grid gap-2 border-t border-border/60 pt-3">
349 <p className="font-medium">{methodLabel}</p>
350 <p role="status" className="text-muted-foreground [overflow-wrap:anywhere]">
351 {authStatusMessage}
352 </p>
353 {authorizationUrl ? (
354 <>
355 <div className="flex flex-wrap gap-2">
356 <Button size="xs" variant="outline" onClick={() => void openSignInPage()}>
357 Open sign-in page
358 </Button>
359 <Button size="xs" variant="ghost" onClick={() => void copySignInLink()}>
360 {copiedFlowId === auth?.flowId ? "Link copied" : "Copy sign-in link"}
361 </Button>
362 </div>
363 {auth?.expiresAt ? (
364 <p className="text-muted-foreground">
365 Link expires at{" "}
366 <time dateTime={auth.expiresAt}>
367 {new Date(auth.expiresAt).toLocaleTimeString([], {
368 hour: "numeric",
369 minute: "2-digit",
370 })}
371 </time>
372 .
373 </p>
374 ) : null}
375 <form
376 className="grid gap-2"
377 onSubmit={(event) => {
378 event.preventDefault();
379 void submitCallback();
380 }}
381 >
382 <label htmlFor={`provider-callback-${instanceId}`}>
383 If the final localhost page does not load, paste its full URL here.
384 </label>
385 <Input
386 id={`provider-callback-${instanceId}`}
387 size="sm"
388 type="url"
389 autoComplete="off"
390 spellCheck={false}
391 placeholder="http://127.0.0.1:..."
392 value={callbackUrl}
393 maxLength={16_384}
394 disabled={actionsDisabled}
395 onChange={(event) =>
396 setCallbackDraft({ flowId: auth?.flowId ?? null, value: event.target.value })
397 }
398 />
399 <Button
400 size="xs"
401 variant="outline"
402 type="submit"
403 className="w-fit"
404 disabled={actionsDisabled || !callbackUrl.trim()}
405 >
406 Continue
407 </Button>
408 </form>
409 </>
410 ) : auth?.phase === "waiting" ? (
411 <p className="text-muted-foreground">
412 Sign-in is open in another client. Complete or cancel it there.
413 </p>
414 ) : null}
415 <div className="flex flex-wrap gap-2">
416 {authActive && auth?.flowId ? (
417 <Button
418 size="xs"
419 variant="ghost"
420 disabled={actionsDisabled}
421 onClick={() => {
422 const flowId = auth.flowId;
423 if (!flowId) return;
424 void runCommand("Cancelling sign-in", () =>
425 cancelAuth({ environmentId, input: { instanceId, flowId } }),
426 );
427 }}
428 >
429 Cancel sign-in
430 </Button>
431 ) : !authActive && !authenticated && provider.setup?.canAuthenticate ? (
432 <Button
433 size="xs"
434 variant="outline"
435 disabled={actionsDisabled || !installed || auth === null || installActive}
436 onClick={() => void runCommand("Starting sign-in", () => startAuth(target))}
437 >
438 {usesBrowser
439 ? auth?.phase === "failed" || auth?.phase === "cancelled"
440 ? "Retry Google sign-in"
441 : "Sign in with Google"
442 : auth?.phase === "failed" || auth?.phase === "cancelled"
443 ? "Retry connection"
444 : "Connect"}
445 </Button>
446 ) : null}
447 {!authActive && provider.setup?.canAuthenticate ? (
448 <Button
449 size="xs"
450 variant={authenticated ? "outline" : "ghost"}
451 disabled={actionsDisabled || auth === null}
452 onClick={() => void signOut()}
453 >
454 {usesBrowser ? "Sign out of Google" : "Disconnect"}
455 </Button>
456 ) : null}
457 </div>
458 </div>
459​
460 {pendingLabel ? <p role="status">{pendingLabel}.</p> : null}
461 {error || queryError ? (
462 <div className="grid gap-2">
463 <p role="alert" className="text-destructive [overflow-wrap:anywhere]">
464 {error ?? queryError}
465 </p>
466 {queryError ? (
467 <Button
468 size="xs"
469 variant="outline"
470 className="w-fit"
471 onClick={() => {
472 authQuery.refresh();
473 installQuery.refresh();
474 }}
475 >
476 Retry setup status
477 </Button>
478 ) : null}
479 </div>
480 ) : null}
481 </div>
482 );