Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { m as resolveMessage } from "~/i18n/messages";
3import { useAtomValue } from "@effect/atom-react";
4import { AuthProvidersManageScope, ProviderDriverKind } from "@t3tools/contracts";
5import { readPreparedConnection, useEnvironmentScope } from "../../state/session";
6import {
7 isAtomCommandInterrupted,
8 squashAtomCommandFailure,
9 type AtomCommandResult,
10} from "@t3tools/client-runtime/state/runtime";
11import type {
12 ChatGptHandoffInput,
13 ChatGptTransferredProfile,
14 EnvironmentId,
15 ProviderInstanceId,
16 ServerProvider,
17} from "@t3tools/contracts";
18import { codexAuthHandoffUrl } from "@t3tools/shared/codexAuthHandoff";
19import { providerAuthReturnUrl } from "@t3tools/shared/providerAuthReturnUrl";
20import { isLoopbackHost } from "@t3tools/shared/preview";
21import { CheckIcon, ChevronRightIcon, ExternalLinkIcon } from "lucide-react";
22import {
23 Children,
24 useEffect,
25 useEffectEvent,
26 useId,
27 useRef,
28 useState,
29 type ReactNode,
30} from "react";
31import { T, useGT, useMessages } from "gt-react";
32
33import { ensureLocalApi } from "../../localApi";
34import { managedInstanceLocks, useManagedPolicy } from "../../state/managedPolicy";
35import { ManagedControl } from "../ManagedPolicy";
36import { useEnvironmentHttpBaseUrl } from "../../state/environments";
37import { environmentPresentations } from "../../state/presentation";
38import { primaryEnvironmentIdAtom } from "../../state/primaryEnvironment";
39import { useEnvironmentQuery } from "../../state/query";
40import { serverEnvironment } from "../../state/server";
41import { useAtomCommand } from "../../state/use-atom-command";
42import { appAtomRegistry } from "../../rpc/atomRegistry";
43import { waitForQuerySettled } from "../../state/waitForQuerySettled";
44import { Button } from "../ui/button";
45import { ChatGptConnectionButton } from "./ChatGptConnectionButton";
46import { ChatGptUsageButton } from "./ChatGptUsageButton";
47import { ChatGptAccountPicker } from "./ChatGptAccountPicker";
48import { Input } from "../ui/input";
49import { OpenAI } from "../Icons";
50import { RedactedSensitiveText } from "./RedactedSensitiveText";
51import { SettingsRow } from "./settingsLayout";
52import { AddCodexAccountDialog } from "./AddCodexAccountDialog";
53import { getOnboardingProviderState } from "../../onboarding/providerReadiness.logic";
54import { getProviderSummary } from "./providerStatus";
55import {
56 settleAuthorizationPage,
57 settleHandoffAuthorizationPage,
58 settleProviderInstall,
59} from "./CodexSetupSection.logic";
60
61const noop = () => undefined;
62
63const isLoopbackUrl = (url: string | null) => url !== null && isLoopbackHost(new URL(url).hostname);
64
65// A loopback server can receive the provider's callback itself, unless the
66// desktop shell offers to catch it on the client.
67const prefersClientCallback = (local: boolean) => !local || window.desktopBridge !== undefined;
68
69/**
70 * How a sign-in started now reaches the provider. Read at use time, because a
71 * sign-in can start minutes after the click that asked for it (once an install
72 * finishes), and the primary environment may have connected in between.
73 */
74function readSignInRouting(environmentId: EnvironmentId) {
75 const local = isLoopbackUrl(readPreparedConnection(environmentId)?.httpBaseUrl ?? null);
76 const clientCallback = prefersClientCallback(local);
77 const primaryEnvironmentId = appAtomRegistry.get(primaryEnvironmentIdAtom);
78 const primaryAuthEnvironmentId =
79 !local &&
80 primaryEnvironmentId !== null &&
81 appAtomRegistry.get(environmentPresentations.presentationAtom(primaryEnvironmentId))?.connection
82 .phase === "connected" &&
83 isLoopbackUrl(readPreparedConnection(primaryEnvironmentId)?.httpBaseUrl ?? null) &&
84 (window.desktopBridge !== undefined || isLoopbackHost(window.location.hostname))
85 ? primaryEnvironmentId
86 : null;
87 return {
88 clientCallback,
89 remoteWeb: clientCallback && !window.desktopBridge,
90 primaryAuthEnvironmentId,
91 };
92}
93
94interface CodexSetupSectionProps {
95 readonly environmentId: EnvironmentId;
96 readonly instanceId: ProviderInstanceId;
97 readonly provider: ServerProvider | undefined;
98 readonly mode: "managed" | "existing";
99 readonly enabled: boolean;
100 readonly readOnly?: boolean;
101 // Onboarding's "Use existing CLI" opens a terminal, which this session may not be allowed.
102 readonly existingCliDisabled?: boolean;
103 readonly presentation?: "settings" | "onboarding";
104 readonly onModeChange: (mode: "managed" | "existing") => void;
105 readonly autoStart?: boolean;
106 readonly displayName?: string | undefined;
107 readonly onAutoStartConsumed?: () => void;
108 readonly onSignInCancelled?: (() => void) | undefined;
109}
110
111export function CodexSetupSection(props: CodexSetupSectionProps) {
112 const gt = useGT();
113 const m = useMessages();
114 const [requested, setRequested] = useState(false);
115 // A policy that owns Codex's launch settings also rules out ChatGPT's own runtime.
116 const codexLocks = managedInstanceLocks(
117 useManagedPolicy(props.environmentId),
118 ProviderDriverKind.make("codex"),
119 m,
120 );
121 const chatGptDenial = codexLocks?.configKeys.has("setupMode") ? codexLocks.reason : undefined;
122 const existingState = getOnboardingProviderState(props.provider);
123 const existingReady = props.enabled && existingState === "ready";
124 const existingAuthenticated = props.provider?.auth.status === "authenticated";
125 const existingChecking = existingState === "checking";
126 const existingSummary = getProviderSummary(props.provider, m);
127 const content =
128 props.mode === "existing" && props.presentation === "onboarding" ? (
129 <CodexWelcomeCard
130 title={props.displayName || props.provider?.displayName || "Codex"}
131 description={
132 existingReady ? (
133 props.provider?.auth.email?.trim() ? (
134 <>
135 <T>
136 Signed in as{" "}
137 <RedactedSensitiveText
138 value={props.provider.auth.email.trim()}
139 ariaLabel={gt`Toggle account email visibility`}
140 revealTooltip={gt`Click to reveal email`}
141 hideTooltip={gt`Click to hide email`}
142 className="break-all"
143 />
144 .
145 </T>
146 </>
147 ) : (
148 gt`Connected with your Codex CLI.`
149 )
150 ) : existingChecking ? (
151 gt`Checking your Codex CLI...`
152 ) : props.provider?.installed ? (
153 existingSummary.headline
154 ) : (
155 gt`Code with your ChatGPT subscription.`
156 )
157 }
158 control={
159 existingReady ? (
160 <span className="inline-flex items-center gap-1.5 text-xs font-medium text-success-foreground">
161 <CheckIcon className="size-3.5" />
162 <T>Ready</T>
163 </span>
164 ) : existingChecking ? (
165 <span className="text-xs text-muted-foreground">
166 <T>Checking...</T>
167 </span>
168 ) : existingAuthenticated ? (
169 <span className="text-xs text-muted-foreground">{existingSummary.headline}</span>
170 ) : (
171 <ManagedControl reason={chatGptDenial}>
172 <ChatGptConnectionButton
173 size="sm"
174 disabled={props.readOnly}
175 onClick={() => {
176 setRequested(true);
177 props.onModeChange("managed");
178 }}
179 >
180 <T>Continue with ChatGPT</T>
181 </ChatGptConnectionButton>
182 </ManagedControl>
183 )
184 }
185 secondaryControl={
186 !existingAuthenticated && !existingReady && !existingChecking ? (
187 <Button
188 size="sm"
189 variant="ghost-muted"
190 disabled={props.existingCliDisabled}
191 onClick={() => props.onModeChange("existing")}
192 >
193 <T>Use existing CLI</T>
194 </Button>
195 ) : null
196 }
197 />
198 ) : props.mode === "existing" ? null : !props.provider?.setup?.canAuthenticate ? (
199 props.presentation === "onboarding" ? (
200 <CodexWelcomeCard
201 title={props.displayName || props.provider?.displayName || "Codex"}
202 description={<CodexSignInDescription />}
203 control={
204 <Button size="sm" variant="outline" className="min-w-44" disabled>
205 <T>Open sign-in page</T>
206 </Button>
207 }
208 secondaryControl={
209 <Button size="sm" variant="ghost-muted" disabled>
210 <T>Cancel</T>
211 </Button>
212 }
213 />
214 ) : (
215 <SettingsRow title={gt`ChatGPT account`} description={gt`Preparing sign-in.`} />
216 )
217 ) : (
218 <ManagedCodexSetup
219 key={`${props.environmentId}:${props.instanceId}`}
220 {...props}
221 autoStart={requested || props.autoStart === true}
222 onAutoStartConsumed={() => {
223 setRequested(false);
224 props.onAutoStartConsumed?.();
225 }}
226 />
227 );
228 return content;
229}
230
231export function AddManagedCodexAccountDialog({
232 environmentId,
233 onClose,
234 onAccountCreated,
235}: {
236 readonly environmentId: EnvironmentId;
237 readonly onClose: () => void;
238 readonly onAccountCreated?:
239 | ((instanceId: ProviderInstanceId, displayName: string) => void)
240 | undefined;
241}) {
242 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
243 return (
244 <AddCodexAccountDialog
245 environmentId={environmentId}
246 onClose={onClose}
247 onAccountCreated={onAccountCreated}
248 renderSetup={(instanceId, provider) => (
249 <ManagedCodexSetup
250 key={instanceId}
251 environmentId={environmentId}
252 instanceId={instanceId}
253 provider={provider}
254 mode="managed"
255 enabled
256 readOnly={!canManageProviders}
257 autoStart
258 onAutoStartConsumed={noop}
259 onModeChange={noop}
260 onSignInCancelled={onClose}
261 allowExistingCli={false}
262 />
263 )}
264 />
265 );
266}
267
268function ManagedCodexSetup({
269 environmentId,
270 instanceId,
271 provider,
272 enabled,
273 readOnly,
274 onModeChange,
275 autoStart,
276 onAutoStartConsumed,
277 allowExistingCli = true,
278 existingCliDisabled,
279 presentation,
280 displayName,
281 onSignInCancelled,
282}: CodexSetupSectionProps & {
283 readonly autoStart: boolean;
284 readonly onAutoStartConsumed: () => void;
285 readonly allowExistingCli?: boolean;
286}) {
287 const gt = useGT();
288 const target = { environmentId, input: { instanceId } };
289 const authQuery = useEnvironmentQuery(serverEnvironment.providerAuthState(target), useMessages());
290 const installQuery = useEnvironmentQuery(
291 serverEnvironment.providerInstallState(target),
292 useMessages(),
293 );
294 const [handoff, setHandoff] = useState<{
295 environmentId: EnvironmentId;
296 input: ChatGptHandoffInput;
297 } | null>(null);
298 const handoffQuery = useEnvironmentQuery(
299 handoff ? serverEnvironment.chatGptHandoffState(handoff) : null,
300 useMessages(),
301 );
302 const auth = handoffQuery.data?.phase === "auth" ? handoffQuery.data.state : authQuery.data;
303 const [accountPickerOpen, setAccountPickerOpen] = useState(false);
304 const [requestedMethodId, setRequestedMethodId] = useState("chatgpt");
305 const reconnectEmail = auth?.methods?.find((method) => method.id === "chatgpt")?.accountEmail;
306 const requestedAccountEmail = auth?.methods?.find(
307 (method) => method.id === requestedMethodId,
308 )?.accountEmail;
309 const hasSavedAccount = auth?.methods?.some((method) => method.id.startsWith("chatgpt-profile:"));
310 const url = auth?.interaction?.type === "browser" ? auth.interaction.url : auth?.authorizationUrl;
311 const installation = installQuery.data;
312 const httpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
313 const local = isLoopbackUrl(httpBaseUrl);
314 const options = { reportFailure: false, reportDefect: false };
315 const startAuth = useAtomCommand(serverEnvironment.startProviderAuth, options);
316 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, options);
317 const completeAuth = useAtomCommand(serverEnvironment.completeProviderAuth, options);
318 const cancelAuth = useAtomCommand(serverEnvironment.cancelProviderAuth, options);
319 const logoutAuth = useAtomCommand(serverEnvironment.logoutProviderAuth, options);
320 const removeAuthMethod = useAtomCommand(serverEnvironment.removeProviderAuthMethod, options);
321 const canRemoveAuthMethod = useAtomValue(
322 serverEnvironment.removeProviderAuthMethod.permissionAtom(environmentId),
323 );
324 const startInstall = useAtomCommand(serverEnvironment.startProviderInstall, options);
325 const cancelInstall = useAtomCommand(serverEnvironment.cancelProviderInstall, options);
326 const reconnectProfile = useAtomCommand(serverEnvironment.chatGptReconnectProfile, options);
327 const importProfile = useAtomCommand(serverEnvironment.chatGptImportProfile, options);
328 const clientCallback = !handoff && prefersClientCallback(local);
329 const remoteWeb = clientCallback && !window.desktopBridge;
330 const returnUrl = new URL(window.location.href);
331 if (returnUrl.pathname === "/welcome") returnUrl.hash = `agents:${environmentId}`;
332 if (returnUrl.pathname === "/settings/providers")
333 returnUrl.searchParams.set("instanceId", instanceId);
334 const needsManualCallback = remoteWeb;
335 const callbackHelpId = useId();
336 const [callbackHelpOpen, setCallbackHelpOpen] = useState(false);
337 const [callbackDraft, setCallbackDraft] = useState({ flowId: "", value: "" });
338 const callbackUrl = callbackDraft.flowId === auth?.flowId ? callbackDraft.value : "";
339 const [pending, setPending] = useState(false);
340 const [awaitingProvider, setAwaitingProvider] = useState<"sign-in" | "handoff" | null>(null);
341 const pendingRef = useRef(false);
342 const [error, setError] = useState<string | null>(null);
343 // The setup or sign-in this client started. Its follow-up steps (sign in
344 // once the install lands, open the page once the flow waits) belong to it
345 // alone, so Cancel, a new attempt, or unmounting abort them.
346 const operation = useRef<AbortController | null>(null);
347 const beginOperation = () => {
348 operation.current?.abort();
349 const controller = new AbortController();
350 operation.current = controller;
351 return controller.signal;
352 };
353 const abortOperation = () => operation.current?.abort();
354 // Once the card unmounts, nothing may start a sign-in or open a page on its behalf.
355 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the in-flight setup or sign-in AbortController on unmount
356 useEffect(() => () => operation.current?.abort(), []);
357 const [autoStartHandled, setAutoStartHandled] = useState(false);
358 const installed = installation?.installedVersion != null;
359 const authenticated = provider?.auth.status === "authenticated";
360 const updateAvailable =
361 installed &&
362 installation?.source !== "local" &&
363 installation?.version != null &&
364 installation.version !== installation.installedVersion;
365 const finishingSignIn =
366 awaitingProvider !== null &&
367 !authenticated &&
368 (auth?.phase === "succeeded" || awaitingProvider === "handoff");
369 if (
370 awaitingProvider !== null &&
371 (authenticated || auth?.phase === "failed" || auth?.phase === "cancelled")
372 ) {
373 setAwaitingProvider(null);
374 }
375 // The server does not refresh the provider snapshot when a sign-in flow
376 // succeeds, and the flow can finish elsewhere (callback, pasted redirect URL).
377 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the server to refresh the provider snapshot once the sign-in flow succeeds
378 useEffect(() => {
379 if (awaitingProvider && auth?.phase === "succeeded") {
380 void refreshProviders({ environmentId, input: { instanceId } });
381 }
382 }, [awaitingProvider, auth?.phase, refreshProviders, environmentId, instanceId]);
383 const startingAutomatically = autoStart && !autoStartHandled;
384 const waitingForAuthState =
385 awaitingProvider === "sign-in" && !authenticated && (auth === null || auth.phase === "idle");
386 const authInProgress =
387 finishingSignIn ||
388 waitingForAuthState ||
389 handoff !== null ||
390 auth?.phase === "starting" ||
391 auth?.phase === "waiting" ||
392 auth?.phase === "verifying";
393 const installActive =
394 installation?.phase === "downloading" ||
395 installation?.phase === "extracting" ||
396 installation?.phase === "verifying";
397 const authActive = startingAutomatically || authInProgress || (pending && !installActive);
398 const unavailable =
399 readOnly || !enabled || pending || authQuery.error !== null || installQuery.error !== null;
400 const busy = pending || authInProgress || installActive;
401
402 const run = async <A, E>(
403 request: () => Promise<AtomCommandResult<A, E>>,
404 onSuccess?: (value: A) => void,
405 ) => {
406 if (pendingRef.current) return false;
407 pendingRef.current = true;
408 setPending(true);
409 setError(null);
410 let succeeded = false;
411 try {
412 const result = await request();
413 if (result._tag === "Failure") {
414 if (!isAtomCommandInterrupted(result)) {
415 const failure = squashAtomCommandFailure(result);
416 setError(
417 failure instanceof Error
418 ? (thrownErrorMessage(failure, resolveMessage) ?? failure.message)
419 : gt`Codex setup failed. Try again.`,
420 );
421 }
422 } else {
423 succeeded = true;
424 onSuccess?.(result.value);
425 }
426 } catch {
427 setError(gt`Codex setup failed. Try again.`);
428 }
429 pendingRef.current = false;
430 setPending(false);
431 return succeeded;
432 };
433
434 const handoffId = useId();
435 const handoffSequence = useRef(0);
436 const importedAttempt = useRef<string | null>(null);
437 const [transferFailed, setTransferFailed] = useState(false);
438 const transferProfile = async (profile: ChatGptTransferredProfile) => {
439 const succeeded = await run(() =>
440 importProfile({ environmentId, input: { instanceId, profile } }),
441 );
442 if (succeeded) {
443 setAwaitingProvider("handoff");
444 setHandoff(null);
445 }
446 setTransferFailed(!succeeded);
447 };
448 const transferFinishedProfile = useEffectEvent((profile: ChatGptTransferredProfile) =>
449 transferProfile(profile),
450 );
451 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- imports the finished handoff profile to the server once per attempt when the handoff query completes
452 useEffect(() => {
453 if (!handoff || handoffQuery.data?.phase !== "finished") return;
454 const attemptId = handoff.input.attemptId;
455 if (importedAttempt.current === attemptId) return;
456 importedAttempt.current = attemptId;
457 void transferFinishedProfile(handoffQuery.data.profile);
458 }, [handoff, handoffQuery.data]);
459 if (
460 handoff &&
461 (handoffQuery.error ||
462 (handoffQuery.data?.phase === "auth" &&
463 ["failed", "cancelled"].includes(handoffQuery.data.state.phase)))
464 ) {
465 setError(
466 handoffQuery.data?.phase === "auth"
467 ? (handoffQuery.data.state.message ?? gt`ChatGPT sign-in could not finish. Try again.`)
468 : gt`ChatGPT sign-in on the primary environment was interrupted. Try again.`,
469 );
470 setHandoff(null);
471 }
472 const cancelSignIn = () => {
473 setAwaitingProvider(null);
474 if (handoff) {
475 setHandoff(null);
476 return Promise.resolve();
477 }
478 return run(() => cancelAuth({ environmentId, input: { instanceId, flowId: auth!.flowId! } }));
479 };
480
481 const receivingCallback = useRef<string | null>(null);
482 const openPage = async (
483 authorizationUrl: string,
484 flowId: string | null,
485 viaClientCallback: boolean,
486 ) => {
487 try {
488 const receive = window.desktopBridge?.receiveProviderAuthCallback;
489 if (receive && viaClientCallback && flowId) {
490 if (receivingCallback.current === authorizationUrl) {
491 await ensureLocalApi().shell.openExternal(authorizationUrl);
492 return;
493 }
494 receivingCallback.current = authorizationUrl;
495 const callbackUrl = await receive(authorizationUrl);
496 if (receivingCallback.current !== authorizationUrl) return;
497 receivingCallback.current = null;
498 await run(() =>
499 completeAuth({ environmentId, input: { instanceId, flowId, callbackUrl } }),
500 );
501 } else {
502 await ensureLocalApi().shell.openExternal(authorizationUrl);
503 }
504 } catch {
505 setError(gt`Could not finish sign-in on this computer. Try again.`);
506 }
507 };
508
509 const signIn = async (methodId: string, signal: AbortSignal) => {
510 if (pendingRef.current) return;
511 setTransferFailed(false);
512 setRequestedMethodId(methodId);
513 const returnUrl = new URL(window.location.href);
514 if (returnUrl.pathname === "/welcome") returnUrl.hash = `agents:${environmentId}`;
515 if (returnUrl.pathname === "/settings/providers")
516 returnUrl.searchParams.set("instanceId", instanceId);
517 const { clientCallback, remoteWeb, primaryAuthEnvironmentId } =
518 readSignInRouting(environmentId);
519 if (primaryAuthEnvironmentId) {
520 const attemptId = `${handoffId}:${++handoffSequence.current}`;
521 await run(
522 () => reconnectProfile({ environmentId, input: { instanceId, methodId } }),
523 (profile) => {
524 const nextHandoff = {
525 environmentId: primaryAuthEnvironmentId,
526 input: {
527 instanceId,
528 environmentId,
529 attemptId,
530 returnUrl: returnUrl.toString(),
531 profile,
532 },
533 };
534 setHandoff(nextHandoff);
535 void waitForQuerySettled({
536 registry: appAtomRegistry,
537 atom: serverEnvironment.chatGptHandoffState(nextHandoff),
538 settle: settleHandoffAuthorizationPage,
539 signal,
540 }).then((page) => {
541 if (page && !signal.aborted) void openPage(page, null, false);
542 });
543 },
544 );
545 return;
546 }
547 await run(
548 () =>
549 startAuth({
550 environmentId,
551 input: {
552 instanceId,
553 methodId,
554 returnUrl: returnUrl.toString(),
555 callbackMode: clientCallback ? "client" : "server",
556 },
557 }),
558 (started) => {
559 setAwaitingProvider("sign-in");
560 const startedFlowId = started.flowId;
561 // A remote browser cannot receive the callback, so the user opens the page from the card.
562 if (remoteWeb || startedFlowId === null) return;
563 const startedPage = settleAuthorizationPage(started, startedFlowId);
564 void (
565 startedPage !== undefined
566 ? Promise.resolve(startedPage)
567 : waitForQuerySettled({
568 registry: appAtomRegistry,
569 atom: serverEnvironment.providerAuthState(target),
570 settle: (state) => settleAuthorizationPage(state, startedFlowId),
571 signal,
572 })
573 ).then((page) => {
574 if (page && !signal.aborted) void openPage(page, startedFlowId, clientCallback);
575 });
576 },
577 );
578 };
579
580 const setup = async (methodId = "chatgpt") => {
581 if (unavailable || busy) return;
582 const signal = beginOperation();
583 if (installed && !updateAvailable) {
584 await signIn(methodId, signal);
585 return;
586 }
587 await run(
588 () => startInstall({ environmentId, input: { instanceId } }),
589 (started) => {
590 void waitForQuerySettled({
591 registry: appAtomRegistry,
592 atom: serverEnvironment.providerInstallState(target),
593 settle: (current) => settleProviderInstall(started, current),
594 signal,
595 }).then((ready) => {
596 if (ready && !signal.aborted) void signIn(methodId, signal);
597 });
598 },
599 );
600 };
601
602 if (
603 autoStart &&
604 !autoStartHandled &&
605 !unavailable &&
606 !busy &&
607 installation !== null &&
608 provider?.setup?.canInstall
609 ) {
610 setAutoStartHandled(true);
611 }
612 const startAutomatically = useEffectEvent(() => {
613 onAutoStartConsumed();
614 void setup();
615 });
616 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- dispatches the automatic setup server command after the auto-start flag commits
617 useEffect(() => {
618 // oxlint-disable-next-line react/set-state-in-effect -- Starting setup dispatches a server command, which marks itself pending before it awaits.
619 if (autoStartHandled) startAutomatically();
620 }, [autoStartHandled]);
621
622 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the desktop bridge provider auth callback when the URL changes or the card unmounts
623 useEffect(() => {
624 if (!clientCallback || !url || !window.desktopBridge) return;
625 return () => {
626 if (receivingCallback.current === url) receivingCallback.current = null;
627 void window.desktopBridge?.cancelProviderAuthCallback(url).catch(() => undefined);
628 };
629 }, [clientCallback, url]);
630
631 const runtimeDescription =
632 installation?.phase === "downloading"
633 ? installation.totalBytes === null
634 ? gt`Downloading ${{ downloaded: (installation.downloadedBytes / 1_000_000).toFixed(1) }} MB.`
635 : gt`Downloading ${{ downloaded: (installation.downloadedBytes / 1_000_000).toFixed(1) }} of ${{ total: (installation.totalBytes / 1_000_000).toFixed(1) }} MB.`
636 : installation?.phase === "extracting"
637 ? gt`Installing Codex.`
638 : installation?.phase === "verifying"
639 ? gt`Checking Codex.`
640 : installed
641 ? installation?.installedVersion
642 ? installation?.source === "local"
643 ? gt`Using your installed Codex · v${{ version: installation.installedVersion }}.`
644 : gt`Managed by T3 Code · v${{ version: installation.installedVersion }}.`
645 : installation?.source === "local"
646 ? gt`Using your installed Codex.`
647 : gt`Managed by T3 Code.`
648 : (installation?.message ?? gt`T3 Code downloads and manages Codex for you.`);
649 const accountDescription = finishingSignIn ? (
650 gt`Finishing sign-in...`
651 ) : installActive ? (
652 runtimeDescription
653 ) : authActive || auth?.phase === "failed" || auth?.phase === "cancelled" ? (
654 auth?.phase === "waiting" && requestedAccountEmail ? (
655 gt`Continue as ${{ email: requestedAccountEmail }} on OpenAI.`
656 ) : (
657 (auth?.message ?? gt`Finish signing in in your browser.`)
658 )
659 ) : authenticated ? (
660 provider?.auth.email?.trim() ? (
661 <>
662 <T>
663 Signed in as{" "}
664 <RedactedSensitiveText
665 value={provider.auth.email.trim()}
666 ariaLabel={gt`Toggle account email visibility`}
667 revealTooltip={gt`Click to reveal email`}
668 hideTooltip={gt`Click to hide email`}
669 />
670 .
671 </T>
672 </>
673 ) : (
674 gt`Signed in with ChatGPT.`
675 )
676 ) : (
677 (reconnectEmail ?? gt`Use your ChatGPT subscription.`)
678 );
679
680 const handoffUrl =
681 needsManualCallback && url && auth?.flowId && providerAuthReturnUrl(returnUrl.toString())
682 ? codexAuthHandoffUrl(
683 {
684 authorizationUrl: url,
685 returnUrl: returnUrl.toString(),
686 environmentId,
687 instanceId,
688 flowId: auth.flowId,
689 },
690 import.meta.env.DEV,
691 )
692 : null;
693 const waitingControl = (
694 <Button
695 size="sm"
696 variant={remoteWeb ? "default" : "outline"}
697 className={presentation === "onboarding" ? "min-w-44" : undefined}
698 disabled={
699 handoffQuery.data?.phase === "finished"
700 ? pending || !transferFailed
701 : !url || auth?.phase !== "waiting"
702 }
703 onClick={() => {
704 if (handoffQuery.data?.phase === "finished")
705 void transferProfile(handoffQuery.data.profile);
706 else if (url) void openPage(url, auth?.flowId ?? null, clientCallback);
707 }}
708 >
709 {finishingSignIn
710 ? gt`Finishing sign-in...`
711 : handoffQuery.data?.phase === "finished"
712 ? transferFailed
713 ? gt`Retry connection`
714 : gt`Finishing sign-in...`
715 : auth?.phase === "waiting"
716 ? remoteWeb
717 ? gt`Open ChatGPT sign-in`
718 : gt`Open sign-in page`
719 : presentation === "onboarding"
720 ? gt`Open sign-in page`
721 : gt`Signing in...`}
722 </Button>
723 );
724 const callbackCompletion =
725 !handoff && auth?.phase === "waiting" && url ? (
726 <div className="flex w-full flex-col gap-3 text-xs leading-relaxed text-muted-foreground">
727 <p>
728 <T>If sign-in doesn't return to T3 Code, paste the URL from the final localhost page.</T>
729 </p>
730 <form
731 className="flex flex-col gap-2 sm:flex-row sm:items-center"
732 onSubmit={(event) => {
733 event.preventDefault();
734 if (!auth.flowId || !callbackUrl.trim()) return;
735 const value = callbackUrl.trim();
736 const submittedFlowId = auth.flowId;
737 void run(() =>
738 completeAuth({
739 environmentId,
740 input: { instanceId, flowId: submittedFlowId, callbackUrl: value },
741 }),
742 ).then((connected) => {
743 if (connected) setCallbackDraft({ flowId: submittedFlowId, value: "" });
744 });
745 }}
746 >
747 <div className="min-w-0 flex-1">
748 <Input
749 aria-label={gt`ChatGPT sign-in redirect URL`}
750 type="password"
751 autoComplete="off"
752 placeholder={gt`Paste the URL from the sign-in tab`}
753 value={callbackUrl}
754 maxLength={16_384}
755 disabled={pending || readOnly}
756 onChange={(event) =>
757 setCallbackDraft({ flowId: auth.flowId ?? "", value: event.target.value })
758 }
759 />
760 </div>
761 <Button
762 variant="outline"
763 type="submit"
764 disabled={pending || readOnly || !callbackUrl.trim()}
765 >
766 <T>Connect</T>
767 </Button>
768 </form>
769 {!remoteWeb ? (
770 <div>
771 <Button
772 size="xs"
773 variant="ghost-muted"
774 onClick={() => void ensureLocalApi().shell.openExternal(url)}
775 >
776 <T>Try sign-in in your browser</T>
777 <ExternalLinkIcon className="size-3.5" />
778 </Button>
779 </div>
780 ) : null}
781 {handoffUrl ? (
782 <details>
783 <summary className="cursor-pointer">
784 <T>Other ways to connect</T>
785 </summary>
786 <Button className="mt-2" size="sm" variant="outline" render={<a href={handoffUrl} />}>
787 <T>Use T3 desktop for automatic return</T>
788 </Button>
789 </details>
790 ) : null}
791 </div>
792 ) : null;
793 const callbackHelpContent =
794 callbackCompletion && callbackHelpOpen ? (
795 <div id={callbackHelpId} className="w-full border-t border-border/50 pt-3">
796 {callbackCompletion}
797 </div>
798 ) : null;
799 const callbackFallback = needsManualCallback ? (
800 callbackCompletion
801 ) : callbackCompletion ? (
802 <div className="space-y-3 text-xs leading-relaxed text-muted-foreground">
803 <CodexSignInDescription
804 label={gt`Having trouble signing in?`}
805 expanded={callbackHelpOpen}
806 controls={callbackHelpId}
807 onToggle={() => setCallbackHelpOpen((open) => !open)}
808 />
809 {callbackHelpContent}
810 </div>
811 ) : null;
812
813 const accountPicker = (
814 <ChatGptAccountPicker
815 open={accountPickerOpen}
816 methods={auth?.methods ?? []}
817 onClose={() => setAccountPickerOpen(false)}
818 disabled={unavailable || busy}
819 canRemove={canRemoveAuthMethod}
820 error={error}
821 onRemove={(methodId) => {
822 void run(() => removeAuthMethod({ environmentId, input: { instanceId, methodId } }));
823 }}
824 onSelect={(methodId) => {
825 setAccountPickerOpen(false);
826 void setup(
827 auth?.methods?.some((method) => method.id === methodId)
828 ? methodId
829 : "chatgpt-change-account",
830 );
831 }}
832 />
833 );
834
835 const logoutWarning =
836 auth?.phase === "idle" && auth.message?.startsWith("Signed out locally.") ? auth.message : null;
837
838 if (presentation === "onboarding") {
839 const setupError =
840 logoutWarning ??
841 error ??
842 (authQuery.error || installQuery.error
843 ? gt`Could not read setup status. Reconnect and try again.`
844 : installation?.phase === "failed"
845 ? installation.message
846 : null);
847 return (
848 <>
849 {accountPicker}
850 <CodexWelcomeCard
851 title={displayName || provider?.displayName || "Codex"}
852 description={
853 installActive ? (
854 runtimeDescription
855 ) : authenticated ? (
856 provider?.auth.email?.trim() ? (
857 <>
858 <T>
859 Signed in as{" "}
860 <RedactedSensitiveText
861 value={provider.auth.email.trim()}
862 ariaLabel={gt`Toggle account email visibility`}
863 revealTooltip={gt`Click to reveal email`}
864 hideTooltip={gt`Click to hide email`}
865 className="break-all"
866 />
867 .
868 </T>
869 </>
870 ) : (
871 gt`Connected to ChatGPT.`
872 )
873 ) : callbackCompletion && !needsManualCallback ? (
874 <CodexSignInDescription
875 expanded={callbackHelpOpen}
876 controls={callbackHelpId}
877 onToggle={() => setCallbackHelpOpen((open) => !open)}
878 />
879 ) : startingAutomatically ||
880 waitingForAuthState ||
881 auth?.phase === "starting" ||
882 auth?.phase === "waiting" ||
883 (pending && !installActive) ? (
884 <CodexSignInDescription />
885 ) : authActive || auth?.phase === "failed" || auth?.phase === "cancelled" ? (
886 accountDescription
887 ) : (
888 gt`Code with your ChatGPT subscription.`
889 )
890 }
891 control={
892 authenticated && !busy ? (
893 <span className="inline-flex items-center gap-1.5 text-xs font-medium text-success-foreground">
894 <CheckIcon className="size-3.5" />
895 <T>Ready</T>
896 </span>
897 ) : authActive ? (
898 waitingControl
899 ) : (
900 <ChatGptConnectionButton
901 size="sm"
902 disabled={
903 unavailable ||
904 busy ||
905 (!installed ? !provider?.setup?.canInstall : !provider?.setup?.canAuthenticate)
906 }
907 onClick={() => {
908 if (hasSavedAccount) setAccountPickerOpen(true);
909 else void setup();
910 }}
911 >
912 {installActive || pending
913 ? gt`Setting up...`
914 : hasSavedAccount
915 ? gt`Reconnect account`
916 : gt`Continue with ChatGPT`}
917 </ChatGptConnectionButton>
918 )
919 }
920 secondaryControl={
921 (authActive && !finishingSignIn) || installActive ? (
922 <Button
923 size="sm"
924 variant="ghost-muted"
925 disabled={pending || readOnly}
926 onClick={() => {
927 abortOperation();
928 if (handoff || (authActive && auth?.flowId)) void cancelSignIn();
929 else if (installation?.operationId)
930 void run(() =>
931 cancelInstall({
932 environmentId,
933 input: { instanceId, operationId: installation.operationId! },
934 }),
935 );
936 }}
937 >
938 <T>Cancel</T>
939 </Button>
940 ) : !authActive && !authenticated && hasSavedAccount ? (
941 <Button
942 size="sm"
943 variant="ghost-muted"
944 disabled={unavailable || busy}
945 onClick={() => void setup("chatgpt-change-account")}
946 >
947 <T>Use a different account</T>
948 </Button>
949 ) : !authActive && !authenticated && allowExistingCli ? (
950 <Button
951 size="sm"
952 variant="ghost-muted"
953 disabled={readOnly || busy || existingCliDisabled}
954 onClick={() => onModeChange("existing")}
955 >
956 <T>Use existing CLI</T>
957 </Button>
958 ) : null
959 }
960 >
961 {needsManualCallback ? callbackFallback : callbackHelpContent}
962 {setupError ? (
963 <p role="alert" className="text-xs text-destructive">
964 {setupError}
965 </p>
966 ) : null}
967 </CodexWelcomeCard>
968 </>
969 );
970 }
971
972 return (
973 <section aria-label={gt`Codex setup`} className="divide-y divide-border/50">
974 {accountPicker}
975 <SettingsRow
976 title={gt`ChatGPT account`}
977 description={accountDescription}
978 control={
979 <div className="flex max-w-88 flex-wrap items-center justify-end gap-2">
980 {authActive ? (
981 <>
982 {waitingControl}
983 {!finishingSignIn && (
984 <Button
985 size="sm"
986 variant="ghost"
987 disabled={pending || readOnly}
988 onClick={() => {
989 if (!handoff && !auth?.flowId) return;
990 abortOperation();
991 void cancelSignIn();
992 onSignInCancelled?.();
993 }}
994 >
995 <T>Cancel</T>
996 </Button>
997 )}
998 </>
999 ) : installActive ? (
1000 <Button
1001 size="sm"
1002 variant="ghost"
1003 disabled={pending || readOnly}
1004 onClick={() => {
1005 if (!installation?.operationId) return;
1006 abortOperation();
1007 void run(() =>
1008 cancelInstall({
1009 environmentId,
1010 input: { instanceId, operationId: installation.operationId! },
1011 }),
1012 );
1013 }}
1014 >
1015 <T>Cancel</T>
1016 </Button>
1017 ) : authenticated ? (
1018 <>
1019 {updateAvailable ? (
1020 <Button
1021 size="sm"
1022 variant="outline"
1023 disabled={unavailable || busy}
1024 onClick={() =>
1025 void run(() => startInstall({ environmentId, input: { instanceId } }))
1026 }
1027 >
1028 <T>Update Codex</T>
1029 </Button>
1030 ) : null}
1031 <Button
1032 size="sm"
1033 variant="outline"
1034 disabled={unavailable || busy}
1035 onClick={() => setAccountPickerOpen(true)}
1036 >
1037 <T>Change account</T>
1038 </Button>
1039 <Button
1040 size="sm"
1041 variant="ghost"
1042 disabled={unavailable || busy}
1043 onClick={() => void run(() => logoutAuth(target))}
1044 >
1045 <T>Disconnect</T>
1046 </Button>
1047 </>
1048 ) : (
1049 <>
1050 <ChatGptConnectionButton
1051 size="sm"
1052 disabled={
1053 unavailable ||
1054 busy ||
1055 (!installed ? !provider?.setup?.canInstall : !provider?.setup?.canAuthenticate)
1056 }
1057 onClick={() => {
1058 if (hasSavedAccount) setAccountPickerOpen(true);
1059 else void setup();
1060 }}
1061 >
1062 {pending
1063 ? gt`Setting up...`
1064 : hasSavedAccount
1065 ? gt`Reconnect account`
1066 : gt`Continue with ChatGPT`}
1067 </ChatGptConnectionButton>
1068 {hasSavedAccount ? (
1069 <Button
1070 size="sm"
1071 variant="ghost"
1072 disabled={unavailable || busy}
1073 onClick={() => void setup("chatgpt-change-account")}
1074 >
1075 <T>Use a different account</T>
1076 </Button>
1077 ) : null}
1078 {allowExistingCli ? (
1079 <Button
1080 size="sm"
1081 variant="ghost"
1082 disabled={readOnly || busy}
1083 onClick={() => onModeChange("existing")}
1084 >
1085 <T>Use existing CLI</T>
1086 </Button>
1087 ) : null}
1088 </>
1089 )}
1090 </div>
1091 }
1092 />
1093 {authenticated ? (
1094 <div className="flex justify-end px-3 py-1 sm:px-4">
1095 <ChatGptUsageButton />
1096 </div>
1097 ) : null}
1098 {logoutWarning ? (
1099 <p role="alert" className="px-3 py-2 text-xs text-muted-foreground sm:px-4">
1100 {logoutWarning}
1101 </p>
1102 ) : null}
1103 {callbackFallback ? <div className="px-3 py-3 sm:px-4">{callbackFallback}</div> : null}
1104 {error || authQuery.error || installQuery.error || installation?.phase === "failed" ? (
1105 <p role="alert" className="px-3 py-2 text-xs text-destructive sm:px-4">
1106 {error ??
1107 (installation?.phase === "failed"
1108 ? installation.message
1109 : gt`Could not read Codex setup status. Reconnect and try again.`)}
1110 </p>
1111 ) : null}
1112 </section>
1113 );
1114}
1115
1116export function CodexManagedRuntimeFields({
1117 environmentId,
1118 instanceId,
1119 provider,
1120}: {
1121 readonly environmentId: EnvironmentId;
1122 readonly instanceId: ProviderInstanceId;
1123 readonly provider: ServerProvider | undefined;
1124}) {
1125 const gt = useGT();
1126 const installation = useEnvironmentQuery(
1127 serverEnvironment.providerInstallState({
1128 environmentId,
1129 input: { instanceId },
1130 }),
1131 useMessages(),
1132 );
1133 const executablePath = installation.data?.executablePath ?? "";
1134 return (
1135 <>
1136 <SettingsRow
1137 title={gt`Binary path`}
1138 description={gt`Selected by T3 Code.`}
1139 control={
1140 <div className="w-full sm:w-80">
1141 <Input
1142 aria-label={gt`Codex binary path`}
1143 value={executablePath}
1144 title={executablePath}
1145 placeholder={installation.error ? gt`Could not read runtime path` : gt`Not installed`}
1146 disabled
1147 />
1148 </div>
1149 }
1150 />
1151 <SettingsRow
1152 title={gt`CODEX_HOME path`}
1153 description={gt`Shared Codex config, sessions, and state.`}
1154 control={
1155 <div className="w-full sm:w-80">
1156 <Input
1157 aria-label={gt`Codex home path`}
1158 value={provider?.runtimePaths?.homePath ?? ""}
1159 title={provider?.runtimePaths?.homePath}
1160 placeholder={gt({ context: "path cannot be read" })`Unavailable`}
1161 disabled
1162 />
1163 </div>
1164 }
1165 />
1166 <SettingsRow
1167 title={gt`Shadow home path`}
1168 description={
1169 provider?.runtimePaths?.shadowHomePath
1170 ? gt`Account-specific home sharing the Codex state above.`
1171 : gt`This instance uses the shared Codex home directly.`
1172 }
1173 control={
1174 <div className="w-full sm:w-80">
1175 <Input
1176 aria-label={gt`Codex shadow home path`}
1177 value={provider?.runtimePaths?.shadowHomePath ?? ""}
1178 title={provider?.runtimePaths?.shadowHomePath ?? undefined}
1179 placeholder={
1180 provider?.runtimePaths
1181 ? gt`Not used`
1182 : gt({ context: "path cannot be read" })`Unavailable`
1183 }
1184 disabled
1185 />
1186 </div>
1187 }
1188 />
1189 </>
1190 );
1191}
1192
1193function CodexSignInDescription({
1194 label: labelOverride,
1195 expanded = false,
1196 controls,
1197 onToggle,
1198}: {
1199 readonly label?: string;
1200 readonly expanded?: boolean;
1201 readonly controls?: string;
1202 readonly onToggle?: () => void;
1203}) {
1204 const gt = useGT();
1205 const label = labelOverride ?? gt`Complete sign-in in your browser.`;
1206 if (!onToggle) return <div className="leading-relaxed">{label}</div>;
1207 return (
1208 <button
1209 type="button"
1210 className="inline-flex items-center gap-1.5 rounded-sm text-left leading-relaxed outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
1211 aria-label={gt`Having trouble signing in?`}
1212 aria-expanded={expanded}
1213 aria-controls={controls}
1214 onClick={onToggle}
1215 >
1216 {label}
1217 <ChevronRightIcon aria-hidden className={`size-3 shrink-0 ${expanded ? "rotate-90" : ""}`} />
1218 </button>
1219 );
1220}
1221
1222function CodexWelcomeCard({
1223 title,
1224 description,
1225 control,
1226 secondaryControl,
1227 children,
1228}: {
1229 readonly title: string;
1230 readonly description: ReactNode;
1231 readonly control?: ReactNode;
1232 readonly secondaryControl?: ReactNode;
1233 readonly children?: ReactNode;
1234}) {
1235 const footer = Children.toArray(children);
1236 return (
1237 <div className="rounded-lg border border-border bg-background px-4 py-4">
1238 <div className="flex flex-wrap items-center gap-3">
1239 <OpenAI className="size-5 shrink-0 fill-foreground" />
1240 <div className="min-w-0 flex-1">
1241 <h3 className="text-sm font-medium">{title}</h3>
1242 <div className="mt-0.5 text-xs leading-relaxed text-muted-foreground">{description}</div>
1243 </div>
1244 {control || secondaryControl ? (
1245 <div className="flex shrink-0 flex-wrap items-center justify-end gap-2 has-[button]:w-full has-[button]:flex-col-reverse has-[button]:items-end sm:has-[button]:w-auto sm:has-[button]:flex-row sm:has-[button]:items-center">
1246 {secondaryControl}
1247 {control}
1248 </div>
1249 ) : null}
1250 </div>
1251 {footer.length > 0 ? (
1252 <div className="ml-8 mt-2 flex flex-wrap items-center gap-2">{footer}</div>
1253 ) : null}
1254 </div>
1255 );
1256}