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