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