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