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

ProviderSetupSection.tsx

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