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

ProviderSetupSection.tsx

326 lines12.3 KB

1import {
2 isAtomCommandInterrupted,
3 settlePromise,
4 squashAtomCommandFailure,
5 type AtomCommandResult,
6} from "@t3tools/client-runtime/state/runtime";
7import {
8 ANTIGRAVITY_AUTH_METHODS,
9 type AntigravityAuthMethod,
10 type EnvironmentId,
11 type ProviderInstanceId,
12 type ServerProvider,
13} from "@t3tools/contracts";
14import { useRef, useState } from "react";
15import { Trash2Icon } from "lucide-react";
16​
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 { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
23import { SettingsRow } from "./settingsLayout";
24import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection";
25​
26interface ProviderSetupSectionProps {
27 readonly environmentId: EnvironmentId;
28 readonly environmentLabel: string;
29 readonly instanceId: ProviderInstanceId;
30 readonly provider: ServerProvider | undefined;
31 readonly binaryPath?: string | undefined;
32 readonly authMethod?: AntigravityAuthMethod | undefined;
33 readonly enabled: boolean;
34 readonly readOnly: boolean;
35 readonly onEnable: () => void;
37​
38export function readAntigravityAuthMethod(config: unknown): AntigravityAuthMethod {
39 const value =
40 config !== null && typeof config === "object" && "authMethod" in config
41 ? config.authMethod
42 : undefined;
43 return (
44 ANTIGRAVITY_AUTH_METHODS.find((method) => method.value === value)?.value ?? "oauth-personal"
45 );
47​
48export function ProviderSetupSection(props: ProviderSetupSectionProps) {
49 return (
50 <section
51 aria-label="Antigravity setup"
52 className="@container/setup divide-y divide-border/50 text-xs"
53 >
54 <SettingsRow
55 className="@max-lg/setup:[&>div:first-child]:flex @max-lg/setup:[&>div:first-child]:items-stretch @max-lg/setup:[&>div:first-child]:gap-3"
56 title="Environment"
57 description="Device that runs this provider."
58 control={
59 <div className="flex min-w-0 flex-col gap-2 sm:items-end">
60 <span className="text-muted-foreground [overflow-wrap:anywhere]">
61 {props.environmentLabel}
62 </span>
63 {!props.enabled && !props.readOnly ? (
64 <Button size="sm" variant="outline" onClick={props.onEnable}>
65 Enable Antigravity
66 </Button>
67 ) : null}
68 </div>
69 }
70 />
71 {props.readOnly ? (
72 <SettingsRow title="Setup unavailable" description="Provider setup is read-only." />
73 ) : props.provider?.setup === undefined ? (
74 <SettingsRow
75 title="Update required"
76 description="Update this environment to manage Antigravity."
77 />
78 ) : (
79 <ProviderSetupActions
80 key={`${props.environmentId}:${props.instanceId}`}
81 environmentId={props.environmentId}
82 environmentLabel={props.environmentLabel}
83 instanceId={props.instanceId}
84 provider={props.provider}
85 binaryPath={props.binaryPath}
86 authMethod={props.authMethod ?? "oauth-personal"}
87 enabled={props.enabled}
88 />
89 )}
90 </section>
91 );
93​
94function ProviderSetupActions({
95 environmentId,
96 environmentLabel,
97 instanceId,
98 provider,
99 enabled,
100 binaryPath,
101}: Pick<
102 ProviderSetupSectionProps,
103 "environmentId" | "environmentLabel" | "instanceId" | "enabled" | "binaryPath"
104> & {
105 readonly provider: ServerProvider;
106 readonly authMethod: AntigravityAuthMethod;
107}) {
108 const target = { environmentId, input: { instanceId } };
109 const authQuery = useEnvironmentQuery(serverEnvironment.providerAuthState(target));
110 const installQuery = useEnvironmentQuery(serverEnvironment.providerInstallState(target));
111 const auth = authQuery.data;
112 const installation = installQuery.data;
113 const commandOptions = { reportFailure: false, reportDefect: false };
114 const startInstall = useAtomCommand(serverEnvironment.startProviderInstall, commandOptions);
115 const cancelInstall = useAtomCommand(serverEnvironment.cancelProviderInstall, commandOptions);
116 const removeInstall = useAtomCommand(
117 serverEnvironment.removeProviderInstallation,
118 commandOptions,
119 );
120 const [pendingLabel, setPendingLabel] = useState<string | null>(null);
121 const pendingRef = useRef(false);
122 const [error, setError] = useState<string | null>(null);
123 const authActive =
124 auth?.phase === "starting" || auth?.phase === "waiting" || auth?.phase === "verifying";
125 const installActive =
126 installation?.phase === "downloading" ||
127 installation?.phase === "extracting" ||
128 installation?.phase === "verifying";
129 const usesCustomBinary = Boolean(binaryPath?.trim());
130 const installed =
131 provider.installed || (!usesCustomBinary && installation?.installedVersion != null);
132 const queryError = authQuery.error ?? installQuery.error;
133 const actionsDisabled = pendingLabel !== null || queryError !== null;
134 const installationStatusMessage =
135 installation?.phase === "downloading"
136 ? `Downloading ${(installation.downloadedBytes / 1_000_000).toFixed(1)} MB${installation.totalBytes === null ? "" : ` of ${(installation.totalBytes / 1_000_000).toFixed(1)} MB`}.`
137 : installation?.phase === "extracting"
138 ? "Extracting Antigravity."
139 : installation?.phase === "verifying"
140 ? "Checking the downloaded runtime."
141 : installed
142 ? "Installed."
143 : usesCustomBinary
144 ? enabled
145 ? "The configured Antigravity runtime is unavailable."
146 : "The configured Antigravity runtime has not been checked."
147 : installation?.totalBytes
148 ? `${Math.ceil(installation.totalBytes / 1_000_000)} MB download.`
149 : "Not installed.";
150​
151 async function runCommand<A, E>(
152 label: string,
153 request: () => Promise<AtomCommandResult<A, E>>,
154 ): Promise<boolean> {
155 if (pendingRef.current) return false;
156 pendingRef.current = true;
157 setPendingLabel(label);
158 setError(null);
159 const settled = await settlePromise(request);
160 pendingRef.current = false;
161 setPendingLabel(null);
162 if (settled._tag === "Failure") {
163 setError("Provider setup failed. Try again.");
164 return false;
165 }
166 const result = settled.value;
167 if (result._tag === "Failure") {
168 if (!isAtomCommandInterrupted(result)) {
169 const failure = squashAtomCommandFailure(result);
170 setError(failure instanceof Error ? failure.message : "Provider setup failed.");
171 }
172 return false;
173 }
174 return true;
175 }
176​
177 async function removeRuntime() {
178 const confirmed = await ensureLocalApi().dialogs.confirm(
179 `Remove the downloaded Antigravity runtime from ${environmentLabel}? Google sign-in and thread history are kept.`,
180 );
181 if (confirmed) {
182 await runCommand("Removing runtime", () => removeInstall(target));
183 }
184 }
185​
186 return (
187 <div className="divide-y divide-border/50">
188 <SettingsRow
189 title="Runtime"
190 className="@max-lg/setup:[&>div:first-child]:flex @max-lg/setup:[&>div:first-child]:items-stretch @max-lg/setup:[&>div:first-child]:gap-3"
191 description="Install and manage Antigravity."
192 status={
193 <div className="space-y-2">
194 {usesCustomBinary ? (
195 <p className="text-muted-foreground">
196 Uses the custom binary path below. Installation keeps that path.
197 </p>
198 ) : null}
199 {!installed && !provider.setup?.canInstall ? (
200 <p className="text-muted-foreground">
201 Automatic installation unavailable. Set a binary path or use another environment.
202 </p>
203 ) : null}
204 </div>
205 }
206 control={
207 <div className="flex w-full min-w-0 flex-col gap-2 @min-[32rem]/settings-row:w-56 @min-[32rem]/settings-row:text-right">
208 <p role="status" className="min-h-4 text-muted-foreground tabular-nums">
209 {installationStatusMessage}
210 </p>
211 <div className="h-1">
212 {installation?.phase === "downloading" &&
213 installation.totalBytes !== null &&
214 installation.totalBytes > 0 ? (
215 <progress
216 aria-label="Antigravity download"
217 className="block h-1 w-full accent-foreground"
218 value={installation.downloadedBytes}
219 max={installation.totalBytes}
220 />
221 ) : null}
222 </div>
223 {!installActive &&
224 installation?.message &&
225 installation.message !== installationStatusMessage ? (
226 <p className="text-muted-foreground [overflow-wrap:anywhere]">
227 {installation.message}
228 </p>
229 ) : null}
230 <div className="grid min-h-7 grid-cols-[1.75rem_minmax(0,1fr)] gap-2">
231 <div className="col-start-2 row-start-1 grid">
232 {installActive && installation.operationId ? (
233 <Button
234 size="sm"
235 variant="outline"
236 disabled={actionsDisabled}
237 onClick={() => {
238 const operationId = installation.operationId;
239 if (!operationId) return;
240 void runCommand("Cancelling installation", () =>
241 cancelInstall({ environmentId, input: { instanceId, operationId } }),
242 );
243 }}
244 >
245 Cancel installation
246 </Button>
247 ) : !installActive && provider.setup?.canInstall ? (
248 <Button
249 size="sm"
250 variant="outline"
251 disabled={actionsDisabled || installation === null || authActive}
252 onClick={() =>
253 void runCommand("Starting installation", () => startInstall(target))
254 }
255 >
256 {installation?.installedVersion
257 ? installation.version &&
258 installation.version !== installation.installedVersion
259 ? "Update Antigravity"
260 : "Reinstall Antigravity"
261 : installation?.phase === "failed" || installation?.phase === "cancelled"
262 ? "Retry installation"
263 : installed
264 ? "Install managed runtime"
265 : "Install Antigravity"}
266 </Button>
267 ) : null}
268 </div>
269 {installation?.canRemove && !installActive ? (
270 <Tooltip>
271 <TooltipTrigger
272 render={
273 <Button
274 size="icon-sm"
275 variant="ghost"
276 className="col-start-1 row-start-1"
277 aria-label="Remove downloaded runtime"
278 disabled={actionsDisabled || authActive}
279 onClick={() => void removeRuntime()}
280 />
281 }
282 >
283 <Trash2Icon className="size-3.5" />
284 </TooltipTrigger>
285 <TooltipPopup>Remove downloaded runtime</TooltipPopup>
286 </Tooltip>
287 ) : null}
288 </div>
289 </div>
290 }
291 />
292​
293 <ProviderAuthenticationSection
294 environmentId={environmentId}
295 environmentLabel={environmentLabel}
296 instanceId={instanceId}
297 provider={provider}
298 readOnly={false}
299 />
300​
301 <p className="sr-only" role="status">
302 {pendingLabel ? `${pendingLabel}.` : null}
303 </p>
304 {error || queryError ? (
305 <div className="grid gap-2 px-3 py-3 sm:px-4">
306 <p role="alert" className="text-destructive [overflow-wrap:anywhere]">
307 {error ?? queryError}
308 </p>
309 {queryError ? (
310 <Button
311 size="sm"
312 variant="outline"
313 className="w-fit"
314 onClick={() => {
315 authQuery.refresh();
316 installQuery.refresh();
317 }}
318 >
319 Retry setup status
320 </Button>
321 ) : null}
322 </div>
323 ) : null}
324 </div>
325 );