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

ProviderAuthenticationSection.tsx

514 lines19.4 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { m } from "~/i18n/messages";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6 type AtomCommandResult,
7} from "@t3tools/client-runtime/state/runtime";
8import type {
9 EnvironmentId,
10 ProviderAuthRespondInput,
11 ProviderAuthResponse,
12 ProviderInstanceId,
13 ServerProvider,
14} from "@t3tools/contracts";
15import { msg, T, useGT, useMessages, Var } from "gt-react";
16import { lazy, Suspense, useRef, useState } from "react";
17import { CopyIcon } from "lucide-react";
18​
19import { writeTextToClipboard } from "../../hooks/useCopyToClipboard";
20import { isWebUrl } from "../../browser/webUrl";
21import { ensureLocalApi } from "../../localApi";
22import { useEnvironmentQuery } from "../../state/query";
23import { serverEnvironment } from "../../state/server";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { Button } from "../ui/button";
26import { Input } from "../ui/input";
27import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
28import { SettingsRow } from "./settingsLayout";
29import { RedactedSensitiveText } from "./RedactedSensitiveText";
30import { SharedTooltipTrigger } from "../ui/shared-tooltip";
31​
32const ProviderAuthTerminal = lazy(() => import("./ProviderAuthTerminal"));
33​
34export function ProviderAuthenticationSection({
35 environmentId,
36 environmentLabel,
37 instanceId,
38 provider,
39 readOnly,
40}: {
41 readonly environmentId: EnvironmentId;
42 readonly environmentLabel: string;
43 readonly instanceId: ProviderInstanceId;
44 readonly provider: ServerProvider;
45 readonly readOnly: boolean;
46}) {
47 const gt = useGT();
48 const target = { environmentId, input: { instanceId } };
49 const query = useEnvironmentQuery(serverEnvironment.providerAuthState(target), useMessages());
50 const commands = { reportFailure: false, reportDefect: false };
51 const start = useAtomCommand(serverEnvironment.startProviderAuth, commands);
52 const respond = useAtomCommand(serverEnvironment.respondProviderAuth, commands);
53 const complete = useAtomCommand(serverEnvironment.completeProviderAuth, commands);
54 const cancel = useAtomCommand(serverEnvironment.cancelProviderAuth, commands);
55 const logout = useAtomCommand(serverEnvironment.logoutProviderAuth, commands);
56 const [methodId, setMethodId] = useState("");
57 const [draft, setDraft] = useState({ id: "", values: {} as Record<string, string> });
58 const [error, setError] = useState<string | null>(null);
59 const [pending, setPending] = useState(false);
60 const pendingRef = useRef(false);
61 const terminalQueue = useRef<ProviderAuthRespondInput[]>([]);
62 const terminalSending = useRef(false);
63 const auth = query.data;
64 const interaction = auth?.interaction;
65 const active =
66 auth?.phase === "starting" || auth?.phase === "waiting" || auth?.phase === "verifying";
67 const signedIn =
68 provider.auth.status === "authenticated" ||
69 (provider.auth.status === "unknown" && auth?.phase === "succeeded");
70 const isDiscovering =
71 provider.driver === "acpRegistry" &&
72 !active &&
73 !signedIn &&
74 !query.error &&
75 auth?.methods === undefined;
76 const needsExternalSetup =
77 !active &&
78 !signedIn &&
79 (provider.setup?.canAuthenticate === false ||
80 (provider.driver === "acpRegistry" && auth?.methods?.length === 0));
81 const usesCredentials =
82 provider.driver === "antigravity" &&
83 (provider.auth.type === "gemini-api-key" || provider.auth.type === "agent-platform");
84 const accountDescription = active
85 ? auth?.phase === "starting"
86 ? (auth.message ?? (usesCredentials ? gt`Connecting…` : gt`Starting sign-in…`))
87 : auth?.phase === "verifying"
88 ? usesCredentials
89 ? gt`Checking credentials and loading models…`
90 : gt`Checking your account…`
91 : interaction?.type === "terminal"
92 ? gt`Complete sign-in in the terminal below.`
93 : interaction?.type === "credentials"
94 ? gt`Enter your credentials below.`
95 : gt`Finish signing in in your browser.`
96 : signedIn
97 ? gt`Signed in.`
98 : isDiscovering
99 ? gt`Discovering sign-in methods…`
100 : needsExternalSetup
101 ? gt`No in-app sign-in advertised. Follow the provider's docs to finish setup.`
102 : usesCredentials
103 ? gt`Connect on ${{ environment: environmentLabel }} to load models.`
104 : gt`Sign in on ${{ environment: environmentLabel }}.`;
105 const statusMessage = auth?.phase === "failed" ? auth.message : null;
106 const disabled = readOnly || pending || query.error !== null || isDiscovering;
107 const draftId = `${auth?.flowId ?? ""}:${interaction?.id ?? ""}`;
108 const values = draft.id === draftId ? draft.values : {};
109 const url =
110 interaction?.type === "browser" || interaction?.type === "deviceCode"
111 ? interaction.url
112 : auth?.authorizationUrl;
113​
114 async function run(command: () => Promise<AtomCommandResult<unknown, unknown>>) {
115 if (pendingRef.current) return false;
116 pendingRef.current = true;
117 setPending(true);
118 setError(null);
119 let succeeded = false;
120 try {
121 const result = await command();
122 if (result._tag === "Success") succeeded = true;
123 else if (!isAtomCommandInterrupted(result)) {
124 const failure = squashAtomCommandFailure(result);
125 setError(
126 failure instanceof Error
127 ? (thrownErrorMessage(failure, m) ?? failure.message)
128 : gt`Provider sign-in failed. Try again.`,
129 );
130 }
131 } catch {
132 setError(gt`Provider sign-in failed. Try again.`);
133 }
134 pendingRef.current = false;
135 setPending(false);
136 return succeeded;
137 }
138​
139 async function send(response: ProviderAuthResponse) {
140 if (!auth?.flowId || !interaction) return false;
141 return run(() =>
142 respond({
143 environmentId,
144 input: { instanceId, flowId: auth.flowId!, interactionId: interaction.id, response },
145 }),
146 );
147 }
148​
149 async function openBrowser() {
150 if (!url || readOnly) return;
151 if (!isWebUrl(url)) {
152 setError(gt`This sign-in link is not a web address, so it was not opened.`);
153 return;
154 }
155 const requiresConsent = interaction?.type === "browser" && interaction.requiresConsent;
156 // Reserve tabs before awaiting consent; browsers block later opens.
157 const pending = requiresConsent && !window.desktopBridge ? window.open("", "_blank") : null;
158 if (pending) pending.opener = null;
159 try {
160 if (requiresConsent && !(await send({ type: "browser", action: "accept" }))) {
161 pending?.close();
162 return;
163 }
164 if (pending) pending.location.href = url;
165 else await ensureLocalApi().shell.openExternal(url);
166 setError(null);
167 } catch {
168 pending?.close();
169 setError(gt`Could not open the sign-in page. Copy the link and open it in your browser.`);
170 }
171 }
172​
173 function updateDraft(name: string, value: string) {
174 setDraft({ id: draftId, values: { ...values, [name]: value } });
175 }
176​
177 return (
178 <SettingsRow
179 title={gt`Account`}
180 description={
181 signedIn && !active && provider.auth.email?.trim() ? (
182 <span>
183 <T>
184 Signed in as{" "}
185 <RedactedSensitiveText
186 key={provider.auth.email}
187 value={provider.auth.email}
188 ariaLabel={gt`Toggle account email visibility`}
189 revealTooltip={gt`Click to reveal email`}
190 hideTooltip={gt`Click to hide email`}
191 className="max-w-full truncate"
192 />
193 </T>
194 </span>
195 ) : (
196 <span role="status">{accountDescription}</span>
197 )
198 }
199 status={
200 statusMessage ? (
201 <p role="status" className="[overflow-wrap:anywhere]">
202 {statusMessage}
203 </p>
204 ) : undefined
205 }
206 control={
207 <div className="flex min-w-0 flex-wrap items-center gap-1.5">
208 {!active && (auth?.methods?.length ?? 0) > 1 ? (
209 <Select
210 value={auth?.methods?.some((method) => method.id === methodId) ? methodId : ""}
211 disabled={disabled}
212 onValueChange={(value) => setMethodId(value ?? "")}
213 >
214 <SelectTrigger size="sm" aria-label={gt`Sign-in method`} className="w-44">
215 <SelectValue>
216 {auth?.methods?.find((method) => method.id === methodId)?.name ??
217 gt`Provider default`}
218 </SelectValue>
219 </SelectTrigger>
220 <SelectPopup>
221 <SelectItem value="">
222 <T>Provider default</T>
223 </SelectItem>
224 {auth?.methods?.map((method) => (
225 <SelectItem key={method.id} value={method.id}>
226 {method.name}
227 </SelectItem>
228 ))}
229 </SelectPopup>
230 </Select>
231 ) : null}
232 {url ? (
233 <>
234 <Button
235 size="sm"
236 variant="outline"
237 disabled={disabled}
238 onClick={() => void openBrowser()}
239 >
240 <T>Open browser</T>
241 </Button>
242 <SharedTooltipTrigger
243 render={
244 <Button
245 aria-label={gt`Copy sign-in link`}
246 size="icon-sm"
247 variant="ghost-muted"
248 disabled={disabled}
249 onClick={() => {
250 // Copy during the click to retain clipboard activation; consent must still be
251 // recorded before use.
252 const copied = writeTextToClipboard(url, {
253 target: "Provider sign-in link",
254 unavailableMessage: msg(
255 "Clipboard API is unavailable while copying Provider sign-in link.",
256 ),
257 failureMessage: msg(
258 "Failed to copy Provider sign-in link to the clipboard.",
259 ),
260 });
261 void (async () => {
262 await copied;
263 if (interaction?.type === "browser" && interaction.requiresConsent)
264 await send({ type: "browser", action: "accept" });
265 })().catch(() => setError(gt`Could not copy the sign-in link.`));
266 }}
267 >
268 <CopyIcon />
269 </Button>
270 }
271 label={
272 <>
273 <T>Copy sign-in link</T>
274 </>
275 }
276 />
277 </>
278 ) : null}
279 <>
280 {needsExternalSetup && provider.setup?.documentationUrl ? (
281 <Button
282 size="sm"
283 variant="outline"
284 render={
285 <a href={provider.setup.documentationUrl} target="_blank" rel="noreferrer" />
286 }
287 >
288 <T>Open docs</T>
289 </Button>
290 ) : active && auth?.flowId ? (
291 <Button
292 size="sm"
293 variant="ghost-muted"
294 aria-label={gt`Cancel sign-in`}
295 disabled={disabled}
296 onClick={() =>
297 void run(() =>
298 cancel({ environmentId, input: { instanceId, flowId: auth.flowId! } }),
299 )
300 }
301 >
302 <T>Cancel</T>
303 </Button>
304 ) : !active && !needsExternalSetup && provider.setup?.canAuthenticate !== false ? (
305 <Button
306 size="sm"
307 variant="outline"
308 disabled={disabled || !provider.enabled || !provider.installed || !auth}
309 onClick={() =>
310 void run(() =>
311 start({
312 environmentId,
313 input: {
314 instanceId,
315 ...(methodId && auth?.methods?.some((method) => method.id === methodId)
316 ? { methodId }
317 : {}),
318 },
319 }),
320 )
321 }
322 >
323 {signedIn
324 ? gt`Change account`
325 : auth?.phase === "failed" || auth?.phase === "cancelled"
326 ? usesCredentials
327 ? gt`Retry connection`
328 : gt`Retry sign-in`
329 : usesCredentials
330 ? gt`Connect`
331 : gt`Sign in`}
332 </Button>
333 ) : null}
334 {!active && signedIn && (provider.auth.canLogout ?? provider.setup?.canAuthenticate) ? (
335 <Button
336 size="sm"
337 variant="ghost"
338 disabled={disabled || !auth}
339 onClick={() => {
340 void ensureLocalApi()
341 .dialogs.confirm(
342 gt`Sign out of ${{ provider: provider.displayName ?? provider.driver }} on ${{ environment: environmentLabel }}? This stops running threads that share this sign-in. Thread history is kept.`,
343 )
344 .then((confirmed) => {
345 if (confirmed) void run(() => logout(target));
346 });
347 }}
348 >
349 <T>Sign out</T>
350 </Button>
351 ) : null}
352 </>
353 </div>
354 }
355 >
356 {interaction?.type === "terminal" ||
357 interaction?.type === "credentials" ||
358 interaction?.type === "deviceCode" ||
359 (url && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction)) ||
360 error ||
361 query.error ? (
362 <>
363 {interaction?.type === "deviceCode" ? (
364 <p className="py-2 text-sm text-muted-foreground">
365 <T>
366 Enter code{" "}
367 <code className="select-all font-mono text-foreground">
368 <Var>{interaction.userCode}</Var>
369 </code>{" "}
370 in your browser.
371 </T>
372 </p>
373 ) : null}
374 {interaction?.type === "terminal" ? (
375 <div className="py-2">
376 <Suspense
377 fallback={
378 <p className="text-xs text-muted-foreground">
379 <T>Loading sign-in terminal…</T>
380 </p>
381 }
382 >
383 <ProviderAuthTerminal
384 key={`${auth?.flowId}:${interaction.id}`}
385 output={interaction.output}
386 outputOffset={interaction.outputOffset}
387 onResponse={(response) => {
388 if (readOnly || !auth?.flowId) return;
389 for (
390 let offset = 0;
391 offset < Math.max(1, response.data.length);
392 offset += 4_096
393 ) {
394 terminalQueue.current.push({
395 instanceId,
396 flowId: auth.flowId,
397 interactionId: interaction.id,
398 response: {
399 ...response,
400 data: response.data.slice(offset, offset + 4_096),
401 },
402 });
403 }
404 if (terminalSending.current) return;
405 terminalSending.current = true;
406 void (async () => {
407 while (terminalQueue.current.length > 0) {
408 const input = terminalQueue.current.shift()!;
409 const result = await respond({ environmentId, input });
410 if (result._tag !== "Success") {
411 terminalQueue.current = [];
412 if (!isAtomCommandInterrupted(result))
413 setError(gt`The provider sign-in terminal is no longer available.`);
414 break;
415 }
416 }
417 })()
418 .catch(() => {
419 terminalQueue.current = [];
420 setError(gt`Could not send input to the provider sign-in terminal.`);
421 })
422 .finally(() => {
423 terminalSending.current = false;
424 });
425 }}
426 />
427 </Suspense>
428 </div>
429 ) : null}
430 {interaction?.type === "credentials" ? (
431 <form
432 className="grid gap-2 py-2 text-sm leading-normal"
433 onSubmit={(event) => {
434 event.preventDefault();
435 void send({ type: "credentials", values }).then((sent) => {
436 if (sent) setDraft({ id: "", values: {} });
437 });
438 }}
439 >
440 {interaction.fields.map((field) => (
441 <label key={field.name} className="grid gap-1">
442 {field.label}
443 <Input
444 size="sm"
445 type={field.secret ? "password" : "text"}
446 autoComplete="off"
447 value={values[field.name] ?? ""}
448 disabled={disabled}
449 maxLength={16_384}
450 onChange={(event) => updateDraft(field.name, event.target.value)}
451 />
452 </label>
453 ))}
454 <Button
455 type="submit"
456 size="sm"
457 variant="outline"
458 className="w-fit"
459 disabled={disabled}
460 >
461 <T>Connect</T>
462 </Button>
463 </form>
464 ) : null}
465 {url && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction) ? (
466 <form
467 className="grid gap-2 py-2 text-sm leading-normal"
468 onSubmit={(event) => {
469 event.preventDefault();
470 if (!auth?.flowId || !values.callback?.trim()) return;
471 void run(() =>
472 complete({
473 environmentId,
474 input: { instanceId, flowId: auth.flowId!, callbackUrl: values.callback! },
475 }),
476 ).then((sent) => {
477 if (sent) setDraft({ id: "", values: {} });
478 });
479 }}
480 >
481 <label className="grid gap-1">
482 <T>If the final localhost page does not load, paste its full URL here.</T>
483 <Input
484 size="sm"
485 id={`provider-callback-${instanceId}`}
486 type="url"
487 autoComplete="off"
488 value={values.callback ?? ""}
489 disabled={disabled}
490 maxLength={16_384}
491 onChange={(event) => updateDraft("callback", event.target.value)}
492 />
493 </label>
494 <Button
495 type="submit"
496 size="sm"
497 variant="outline"
498 className="w-fit"
499 disabled={disabled || !values.callback?.trim()}
500 >
501 <T>Continue</T>
502 </Button>
503 </form>
504 ) : null}
505 {error || query.error ? (
506 <p role="alert" className="py-2 text-xs text-destructive">
507 {error ?? query.error}
508 </p>
509 ) : null}
510 </>
511 ) : null}
512 </SettingsRow>
513 );