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

ProviderSetupSection.tsx

352 lines13.9 KB

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