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