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

ProviderSetupSection.tsx

481 lines18.3 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​
173 async function runCommand<A, E>(
174 label: string,
175 request: () => Promise<AtomCommandResult<A, E>>,
176 ): Promise<boolean> {
177 if (pendingRef.current) return false;
178 pendingRef.current = true;
179 setPendingLabel(label);
180 setError(null);
181 try {
182 const result = await request();
183 if (result._tag === "Failure") {
184 if (!isAtomCommandInterrupted(result)) {
185 const failure = squashAtomCommandFailure(result);
186 setError(failure instanceof Error ? failure.message : "Provider setup failed.");
187 }
188 return false;
189 }
190 return true;
191 } catch {
192 setError("Provider setup failed. Try again.");
193 return false;
194 } finally {
195 pendingRef.current = false;
196 setPendingLabel(null);
197 }
198 }
199​
200 async function openSignInPage() {
201 if (!authorizationUrl) return;
202 try {
203 await ensureLocalApi().shell.openExternal(authorizationUrl);
204 setError(null);
205 } catch {
206 setError("Could not open the sign-in page. Copy the link and open it in your browser.");
207 }
208 }
209​
210 async function copySignInLink() {
211 if (!authorizationUrl) return;
212 try {
213 await writeTextToClipboard(authorizationUrl, "Google sign-in link");
214 setCopiedFlowId(auth?.flowId ?? null);
215 setError(null);
216 } catch {
217 setError("Could not copy the sign-in link. Use Open sign-in page.");
218 }
219 }
220​
221 async function submitCallback() {
222 const flowId = auth?.flowId;
223 if (!flowId || !callbackUrl.trim() || auth.phase !== "waiting") return;
224 const accepted = await runCommand("Checking redirect", () =>
225 completeAuth({ environmentId, input: { instanceId, flowId, callbackUrl } }),
226 );
227 if (accepted) {
228 setCallbackDraft({ flowId: null, value: "" });
229 }
230 }
231​
232 async function signOut() {
233 const confirmed = await ensureLocalApi().dialogs.confirm(
234 `${usesBrowser ? "Sign out of Google" : "Disconnect"} for ${provider.displayName ?? "Antigravity"} on ${environmentLabel}? This stops its running threads. Thread history is kept.`,
235 );
236 if (confirmed) {
237 await runCommand("Signing out", () => logoutAuth(target));
238 }
239 }
240​
241 async function removeRuntime() {
242 const confirmed = await ensureLocalApi().dialogs.confirm(
243 `Remove the downloaded Antigravity runtime from ${environmentLabel}? Google sign-in and thread history are kept.`,
244 );
245 if (confirmed) {
246 await runCommand("Removing runtime", () => removeInstall(target));
247 }
248 }
249​
250 return (
251 <div className="grid gap-3">
252 <div className="grid gap-2">
253 <p className="font-medium">Runtime</p>
254 <p role="status" className="text-muted-foreground">
255 {installation?.phase === "downloading"
256 ? `Downloading ${(installation.downloadedBytes / 1_000_000).toFixed(1)} MB${installation.totalBytes === null ? "" : ` of ${(installation.totalBytes / 1_000_000).toFixed(1)} MB`}.`
257 : installation?.phase === "extracting"
258 ? "Extracting Antigravity."
259 : installation?.phase === "verifying"
260 ? "Checking the downloaded runtime."
261 : installed
262 ? "Antigravity is installed."
263 : usesCustomBinary
264 ? enabled
265 ? "The configured Antigravity runtime is unavailable."
266 : "The configured Antigravity runtime has not been checked."
267 : "Install the official Antigravity runtime before signing in."}
268 </p>
269 {installation?.phase === "downloading" &&
270 installation.totalBytes !== null &&
271 installation.totalBytes > 0 ? (
272 <progress
273 aria-label="Antigravity download"
274 className="h-1 w-full accent-foreground"
275 value={installation.downloadedBytes}
276 max={installation.totalBytes}
277 />
278 ) : null}
279 {installation?.message ? (
280 <p className="text-muted-foreground [overflow-wrap:anywhere]">{installation.message}</p>
281 ) : null}
282 {usesCustomBinary ? (
283 <p className="text-muted-foreground">
284 This instance uses the binary path below. Installing a managed runtime does not change
285 that path.
286 </p>
287 ) : null}
288 {!installed && !usesCustomBinary && !installActive && installation?.totalBytes ? (
289 <p className="text-muted-foreground">
290 Downloads {Math.ceil(installation.totalBytes / 1_000_000)} MB from Google.
291 </p>
292 ) : null}
293 {!installed && !provider.setup?.canInstall ? (
294 <p className="text-muted-foreground">
295 Automatic installation is unavailable here. Set an existing binary path below or use a
296 supported remote environment.
297 </p>
298 ) : null}
299 <div className="flex flex-wrap gap-2">
300 {installActive && installation.operationId ? (
301 <Button
302 size="xs"
303 variant="outline"
304 disabled={actionsDisabled}
305 onClick={() => {
306 const operationId = installation.operationId;
307 if (!operationId) return;
308 void runCommand("Cancelling installation", () =>
309 cancelInstall({ environmentId, input: { instanceId, operationId } }),
310 );
311 }}
312 >
313 Cancel installation
314 </Button>
315 ) : !installActive && provider.setup?.canInstall ? (
316 <Button
317 size="xs"
318 variant="outline"
319 disabled={actionsDisabled || installation === null || authActive}
320 onClick={() => void runCommand("Starting installation", () => startInstall(target))}
321 >
322 {installation?.installedVersion
323 ? installation.version && installation.version !== installation.installedVersion
324 ? "Update Antigravity"
325 : "Reinstall Antigravity"
326 : installation?.phase === "failed" || installation?.phase === "cancelled"
327 ? "Retry installation"
328 : installed
329 ? "Install managed runtime"
330 : "Install Antigravity"}
331 </Button>
332 ) : null}
333 {installation?.canRemove && !installActive ? (
334 <Button
335 size="xs"
336 variant="ghost"
337 disabled={actionsDisabled || authActive}
338 onClick={() => void removeRuntime()}
339 >
340 Remove downloaded runtime
341 </Button>
342 ) : null}
343 </div>
344 </div>
345​
346 <div className="grid gap-2 border-t border-border/60 pt-3">
347 <p className="font-medium">{methodLabel}</p>
348 <p role="status" className="text-muted-foreground [overflow-wrap:anywhere]">
349 {authStatusMessage}
350 </p>
351 {authorizationUrl ? (
352 <>
353 <div className="flex flex-wrap gap-2">
354 <Button size="xs" variant="outline" onClick={() => void openSignInPage()}>
355 Open sign-in page
356 </Button>
357 <Button size="xs" variant="ghost" onClick={() => void copySignInLink()}>
358 {copiedFlowId === auth?.flowId ? "Link copied" : "Copy sign-in link"}
359 </Button>
360 </div>
361 {auth?.expiresAt ? (
362 <p className="text-muted-foreground">
363 Link expires at{" "}
364 <time dateTime={auth.expiresAt}>
365 {new Date(auth.expiresAt).toLocaleTimeString([], {
366 hour: "numeric",
367 minute: "2-digit",
368 })}
369 </time>
370 .
371 </p>
372 ) : null}
373 <form
374 className="grid gap-2"
375 onSubmit={(event) => {
376 event.preventDefault();
377 void submitCallback();
378 }}
379 >
380 <label htmlFor={`provider-callback-${instanceId}`}>
381 If the final localhost page does not load, paste its full URL here.
382 </label>
383 <Input
384 id={`provider-callback-${instanceId}`}
385 size="sm"
386 type="url"
387 autoComplete="off"
388 spellCheck={false}
389 placeholder="http://127.0.0.1:..."
390 value={callbackUrl}
391 maxLength={16_384}
392 disabled={actionsDisabled}
393 onChange={(event) =>
394 setCallbackDraft({ flowId: auth?.flowId ?? null, value: event.target.value })
395 }
396 />
397 <Button
398 size="xs"
399 variant="outline"
400 type="submit"
401 className="w-fit"
402 disabled={actionsDisabled || !callbackUrl.trim()}
403 >
404 Continue
405 </Button>
406 </form>
407 </>
408 ) : auth?.phase === "waiting" ? (
409 <p className="text-muted-foreground">
410 Sign-in is open in another client. Complete or cancel it there.
411 </p>
412 ) : null}
413 <div className="flex flex-wrap gap-2">
414 {authActive && auth?.flowId ? (
415 <Button
416 size="xs"
417 variant="ghost"
418 disabled={actionsDisabled}
419 onClick={() => {
420 const flowId = auth.flowId;
421 if (!flowId) return;
422 void runCommand("Cancelling sign-in", () =>
423 cancelAuth({ environmentId, input: { instanceId, flowId } }),
424 );
425 }}
426 >
427 Cancel sign-in
428 </Button>
429 ) : !authActive && !authenticated && provider.setup?.canAuthenticate ? (
430 <Button
431 size="xs"
432 variant="outline"
433 disabled={actionsDisabled || !installed || auth === null || installActive}
434 onClick={() => void runCommand("Starting sign-in", () => startAuth(target))}
435 >
436 {usesBrowser
437 ? auth?.phase === "failed" || auth?.phase === "cancelled"
438 ? "Retry Google sign-in"
439 : "Sign in with Google"
440 : auth?.phase === "failed" || auth?.phase === "cancelled"
441 ? "Retry connection"
442 : "Connect"}
443 </Button>
444 ) : null}
445 {!authActive && provider.setup?.canAuthenticate ? (
446 <Button
447 size="xs"
448 variant={authenticated ? "outline" : "ghost"}
449 disabled={actionsDisabled || auth === null}
450 onClick={() => void signOut()}
451 >
452 {usesBrowser ? "Sign out of Google" : "Disconnect"}
453 </Button>
454 ) : null}
455 </div>
456 </div>
457​
458 {pendingLabel ? <p role="status">{pendingLabel}.</p> : null}
459 {error || queryError ? (
460 <div className="grid gap-2">
461 <p role="alert" className="text-destructive [overflow-wrap:anywhere]">
462 {error ?? queryError}
463 </p>
464 {queryError ? (
465 <Button
466 size="xs"
467 variant="outline"
468 className="w-fit"
469 onClick={() => {
470 authQuery.refresh();
471 installQuery.refresh();
472 }}
473 >
474 Retry setup status
475 </Button>
476 ) : null}
477 </div>
478 ) : null}
479 </div>
480 );