Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexSetupSection.tsx

1,144 lines39.8 KB

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