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