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

CodexSetupSection.tsx

1,165 lines42.0 KB

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 };
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;
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;
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 );
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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the in-flight setup or sign-in AbortController on unmount
319 useEffect(() => () => operation.current?.abort(), []);
320 const [autoStartHandled, setAutoStartHandled] = useState(false);
321 const installed = installation?.installedVersion != null;
322 const authenticated = provider?.auth.status === "authenticated";
323 const updateAvailable =
324 installed &&
325 installation?.source !== "local" &&
326 installation?.version != null &&
327 installation.version !== installation.installedVersion;
328 const finishingSignIn =
329 awaitingProvider !== null &&
330 !authenticated &&
331 (auth?.phase === "succeeded" || awaitingProvider === "handoff");
332 if (
333 awaitingProvider !== null &&
334 (authenticated || auth?.phase === "failed" || auth?.phase === "cancelled")
335 ) {
336 setAwaitingProvider(null);
337 }
338 // The server does not refresh the provider snapshot when a sign-in flow
339 // succeeds, and the flow can finish elsewhere (callback, pasted redirect URL).
340 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- asks the server to refresh the provider snapshot once the sign-in flow succeeds
341 useEffect(() => {
342 if (awaitingProvider && auth?.phase === "succeeded") {
343 void refreshProviders({ environmentId, input: { instanceId } });
344 }
345 }, [awaitingProvider, auth?.phase, refreshProviders, environmentId, instanceId]);
346 const startingAutomatically = autoStart && !autoStartHandled;
347 const waitingForAuthState =
348 awaitingProvider === "sign-in" && !authenticated && (auth === null || auth.phase === "idle");
349 const authInProgress =
350 finishingSignIn ||
351 waitingForAuthState ||
352 handoff !== null ||
353 auth?.phase === "starting" ||
354 auth?.phase === "waiting" ||
355 auth?.phase === "verifying";
356 const installActive =
357 installation?.phase === "downloading" ||
358 installation?.phase === "extracting" ||
359 installation?.phase === "verifying";
360 const authActive = startingAutomatically || authInProgress || (pending && !installActive);
361 const unavailable =
362 readOnly || !enabled || pending || authQuery.error !== null || installQuery.error !== null;
363 const busy = pending || authInProgress || installActive;
364​
365 const run = async <A, E>(
366 request: () => Promise<AtomCommandResult<A, E>>,
367 onSuccess?: (value: A) => void,
368 ) => {
369 if (pendingRef.current) return false;
370 pendingRef.current = true;
371 setPending(true);
372 setError(null);
373 let succeeded = false;
374 try {
375 const result = await request();
376 if (result._tag === "Failure") {
377 if (!isAtomCommandInterrupted(result)) {
378 const failure = squashAtomCommandFailure(result);
379 setError(failure instanceof Error ? failure.message : "Codex setup failed. Try again.");
380 }
381 } else {
382 succeeded = true;
383 onSuccess?.(result.value);
384 }
385 } catch {
386 setError("Codex setup failed. Try again.");
387 }
388 pendingRef.current = false;
389 setPending(false);
390 return succeeded;
391 };
392​
393 const handoffId = useId();
394 const handoffSequence = useRef(0);
395 const importedAttempt = useRef<string | null>(null);
396 const [transferFailed, setTransferFailed] = useState(false);
397 const transferProfile = async (profile: ChatGptTransferredProfile) => {
398 const succeeded = await run(() =>
399 importProfile({ environmentId, input: { instanceId, profile } }),
400 );
401 if (succeeded) {
402 setAwaitingProvider("handoff");
403 setHandoff(null);
404 }
405 setTransferFailed(!succeeded);
406 };
407 const transferFinishedProfile = useEffectEvent((profile: ChatGptTransferredProfile) =>
408 transferProfile(profile),
409 );
410 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- imports the finished handoff profile to the server once per attempt when the handoff query completes
411 useEffect(() => {
412 if (!handoff || handoffQuery.data?.phase !== "finished") return;
413 const attemptId = handoff.input.attemptId;
414 if (importedAttempt.current === attemptId) return;
415 importedAttempt.current = attemptId;
416 void transferFinishedProfile(handoffQuery.data.profile);
417 }, [handoff, handoffQuery.data]);
418 if (
419 handoff &&
420 (handoffQuery.error ||
421 (handoffQuery.data?.phase === "auth" &&
422 ["failed", "cancelled"].includes(handoffQuery.data.state.phase)))
423 ) {
424 setError(
425 handoffQuery.data?.phase === "auth"
426 ? (handoffQuery.data.state.message ?? "ChatGPT sign-in could not finish. Try again.")
427 : "ChatGPT sign-in on the primary environment was interrupted. Try again.",
428 );
429 setHandoff(null);
430 }
431 const cancelSignIn = () => {
432 setAwaitingProvider(null);
433 if (handoff) {
434 setHandoff(null);
435 return Promise.resolve();
436 }
437 return run(() => cancelAuth({ environmentId, input: { instanceId, flowId: auth!.flowId! } }));
438 };
439​
440 const receivingCallback = useRef<string | null>(null);
441 const openPage = async (
442 authorizationUrl: string,
443 flowId: string | null,
444 viaClientCallback: boolean,
445 ) => {
446 try {
447 const receive = window.desktopBridge?.receiveProviderAuthCallback;
448 if (receive && viaClientCallback && flowId) {
449 if (receivingCallback.current === authorizationUrl) {
450 await ensureLocalApi().shell.openExternal(authorizationUrl);
451 return;
452 }
453 receivingCallback.current = authorizationUrl;
454 const callbackUrl = await receive(authorizationUrl);
455 if (receivingCallback.current !== authorizationUrl) return;
456 receivingCallback.current = null;
457 await run(() =>
458 completeAuth({ environmentId, input: { instanceId, flowId, callbackUrl } }),
459 );
460 } else {
461 await ensureLocalApi().shell.openExternal(authorizationUrl);
462 }
463 } catch {
464 setError(
465 "Could not finish sign-in on this computer. Try again or paste the redirect URL below.",
466 );
467 }
468 };
469​
470 const signIn = async (methodId: string, signal: AbortSignal) => {
471 if (pendingRef.current) return;
472 setTransferFailed(false);
473 setRequestedMethodId(methodId);
474 const returnUrl = new URL(window.location.href);
475 if (returnUrl.pathname === "/welcome") returnUrl.hash = `agents:${environmentId}`;
476 if (returnUrl.pathname === "/settings/providers")
477 returnUrl.searchParams.set("instanceId", instanceId);
478 const { clientCallback, remoteWeb, primaryAuthEnvironmentId } =
479 readSignInRouting(environmentId);
480 if (primaryAuthEnvironmentId) {
481 const attemptId = `${handoffId}:${++handoffSequence.current}`;
482 await run(
483 () => reconnectProfile({ environmentId, input: { instanceId, methodId } }),
484 (profile) => {
485 const nextHandoff = {
486 environmentId: primaryAuthEnvironmentId,
487 input: {
488 instanceId,
489 environmentId,
490 attemptId,
491 returnUrl: returnUrl.toString(),
492 profile,
493 },
494 };
495 setHandoff(nextHandoff);
496 void waitForQuerySettled({
497 registry: appAtomRegistry,
498 atom: serverEnvironment.chatGptHandoffState(nextHandoff),
499 settle: settleHandoffAuthorizationPage,
500 signal,
501 }).then((page) => {
502 if (page && !signal.aborted) void openPage(page, null, false);
503 });
504 },
505 );
506 return;
507 }
508 await run(
509 () =>
510 startAuth({
511 environmentId,
512 input: {
513 instanceId,
514 methodId,
515 returnUrl: returnUrl.toString(),
516 callbackMode: clientCallback ? "client" : "server",
517 },
518 }),
519 (started) => {
520 setAwaitingProvider("sign-in");
521 const startedFlowId = started.flowId;
522 // A remote browser cannot receive the callback, so the user opens the page from the card.
523 if (remoteWeb || startedFlowId === null) return;
524 const startedPage = settleAuthorizationPage(started, startedFlowId);
525 void (
526 startedPage !== undefined
527 ? Promise.resolve(startedPage)
528 : waitForQuerySettled({
529 registry: appAtomRegistry,
530 atom: serverEnvironment.providerAuthState(target),
531 settle: (state) => settleAuthorizationPage(state, startedFlowId),
532 signal,
533 })
534 ).then((page) => {
535 if (page && !signal.aborted) void openPage(page, startedFlowId, clientCallback);
536 });
537 },
538 );
539 };
540​
541 const setup = async (methodId = "chatgpt") => {
542 if (unavailable || busy) return;
543 const signal = beginOperation();
544 if (installed && !updateAvailable) {
545 await signIn(methodId, signal);
546 return;
547 }
548 await run(
549 () => startInstall({ environmentId, input: { instanceId } }),
550 (started) => {
551 void waitForQuerySettled({
552 registry: appAtomRegistry,
553 atom: serverEnvironment.providerInstallState(target),
554 settle: (current) => settleProviderInstall(started, current),
555 signal,
556 }).then((ready) => {
557 if (ready && !signal.aborted) void signIn(methodId, signal);
558 });
559 },
560 );
561 };
562​
563 if (
564 autoStart &&
565 !autoStartHandled &&
566 !unavailable &&
567 !busy &&
568 installation !== null &&
569 provider?.setup?.canInstall
570 ) {
571 setAutoStartHandled(true);
572 }
573 const startAutomatically = useEffectEvent(() => {
574 onAutoStartConsumed();
575 void setup();
576 });
577 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- dispatches the automatic setup server command after the auto-start flag commits
578 useEffect(() => {
579 // oxlint-disable-next-line react/set-state-in-effect -- Starting setup dispatches a server command, which marks itself pending before it awaits.
580 if (autoStartHandled) startAutomatically();
581 }, [autoStartHandled]);
582​
583 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the desktop bridge provider auth callback when the URL changes or the card unmounts
584 useEffect(() => {
585 if (!clientCallback || !url || !window.desktopBridge?.cancelProviderAuthCallback) return;
586 return () => {
587 if (receivingCallback.current === url) receivingCallback.current = null;
588 void window.desktopBridge?.cancelProviderAuthCallback?.(url).catch(() => undefined);
589 };
590 }, [clientCallback, url]);
591​
592 const runtimeDescription =
593 installation?.phase === "downloading"
594 ? `Downloading ${(installation.downloadedBytes / 1_000_000).toFixed(1)}${installation.totalBytes === null ? "" : ` of ${(installation.totalBytes / 1_000_000).toFixed(1)}`} MB.`
595 : installation?.phase === "extracting"
596 ? "Installing Codex."
597 : installation?.phase === "verifying"
598 ? "Checking Codex."
599 : installed
600 ? `${installation?.source === "local" ? "Using your installed Codex" : "Managed by T3 Code"}${installation?.installedVersion ? ` · v${installation.installedVersion}` : ""}.`
601 : (installation?.message ?? "T3 Code downloads and manages Codex for you.");
602 const accountDescription = finishingSignIn ? (
603 "Finishing sign-in..."
604 ) : installActive ? (
605 runtimeDescription
606 ) : authActive || auth?.phase === "failed" || auth?.phase === "cancelled" ? (
607 auth?.phase === "waiting" && requestedAccountEmail ? (
608 `Continue as ${requestedAccountEmail} on OpenAI.`
609 ) : (
610 (auth?.message ?? "Finish signing in in your browser.")
611 )
612 ) : authenticated ? (
613 provider?.auth.email?.trim() ? (
614 <>
615 Signed in as{" "}
616 <RedactedSensitiveText
617 value={provider.auth.email.trim()}
618 ariaLabel="Toggle account email visibility"
619 revealTooltip="Click to reveal email"
620 hideTooltip="Click to hide email"
621 />
622 .
623 </>
624 ) : (
625 "Signed in with ChatGPT."
626 )
627 ) : (
628 (reconnectEmail ?? "Use your ChatGPT subscription.")
629 );
630​
631 const handoffUrl =
632 needsManualCallback && url && auth?.flowId && providerAuthReturnUrl(returnUrl.toString())
633 ? codexAuthHandoffUrl(
634 {
635 authorizationUrl: url,
636 returnUrl: returnUrl.toString(),
637 environmentId,
638 instanceId,
639 flowId: auth.flowId,
640 },
641 import.meta.env.DEV,
642 )
643 : null;
644 const waitingControl = (
645 <Button
646 size="sm"
647 variant={remoteWeb ? "default" : "outline"}
648 className={presentation === "onboarding" ? "min-w-44" : undefined}
649 disabled={
650 handoffQuery.data?.phase === "finished"
651 ? pending || !transferFailed
652 : !url || auth?.phase !== "waiting"
653 }
654 onClick={() => {
655 if (handoffQuery.data?.phase === "finished")
656 void transferProfile(handoffQuery.data.profile);
657 else if (url) void openPage(url, auth?.flowId ?? null, clientCallback);
658 }}
659 >
660 {finishingSignIn
661 ? "Finishing sign-in..."
662 : handoffQuery.data?.phase === "finished"
663 ? transferFailed
664 ? "Retry connection"
665 : "Finishing sign-in..."
666 : auth?.phase === "waiting"
667 ? remoteWeb
668 ? "Open ChatGPT sign-in"
669 : "Open sign-in page"
670 : presentation === "onboarding"
671 ? "Open sign-in page"
672 : "Signing in..."}
673 </Button>
674 );
675 const callbackCompletion =
676 !handoff && auth?.phase === "waiting" && url ? (
677 <div className="flex w-full flex-col gap-3 text-xs leading-relaxed text-muted-foreground">
678 <p>If sign-in doesn't return to T3 Code, paste the URL from the final localhost page.</p>
679 <form
680 className="flex flex-col gap-2 sm:flex-row sm:items-center"
681 onSubmit={(event) => {
682 event.preventDefault();
683 if (!auth.flowId || !callbackUrl.trim()) return;
684 const value = callbackUrl.trim();
685 const submittedFlowId = auth.flowId;
686 void run(() =>
687 completeAuth({
688 environmentId,
689 input: { instanceId, flowId: submittedFlowId, callbackUrl: value },
690 }),
691 ).then((connected) => {
692 if (connected) setCallbackDraft({ flowId: submittedFlowId, value: "" });
693 });
694 }}
695 >
696 <div className="min-w-0 flex-1">
697 <Input
698 aria-label="ChatGPT sign-in redirect URL"
699 type="password"
700 autoComplete="off"
701 placeholder="Paste the URL from the sign-in tab"
702 value={callbackUrl}
703 maxLength={16_384}
704 disabled={pending || readOnly}
705 onChange={(event) =>
706 setCallbackDraft({ flowId: auth.flowId ?? "", value: event.target.value })
707 }
708 />
709 </div>
710 <Button
711 variant="outline"
712 type="submit"
713 disabled={pending || readOnly || !callbackUrl.trim()}
714 >
715 Connect
716 </Button>
717 </form>
718 {!remoteWeb ? (
719 <div>
720 <Button
721 size="xs"
722 variant="ghost-muted"
723 onClick={() => void ensureLocalApi().shell.openExternal(url)}
724 >
725 Try sign-in in your browser
726 <ExternalLinkIcon className="size-3.5" />
727 </Button>
728 </div>
729 ) : null}
730 {handoffUrl ? (
731 <details>
732 <summary className="cursor-pointer">Other ways to connect</summary>
733 <Button className="mt-2" size="sm" variant="outline" render={<a href={handoffUrl} />}>
734 Use T3 desktop for automatic return
735 </Button>
736 </details>
737 ) : null}
738 </div>
739 ) : null;
740 const callbackHelpContent =
741 callbackCompletion && callbackHelpOpen ? (
742 <div id={callbackHelpId} className="w-full border-t border-border/50 pt-3">
743 {callbackCompletion}
744 </div>
745 ) : null;
746 const callbackFallback = needsManualCallback ? (
747 callbackCompletion
748 ) : callbackCompletion ? (
749 <div className="space-y-3 text-xs leading-relaxed text-muted-foreground">
750 <CodexSignInDescription
751 label="Having trouble signing in?"
752 expanded={callbackHelpOpen}
753 controls={callbackHelpId}
754 onToggle={() => setCallbackHelpOpen((open) => !open)}
755 />
756 {callbackHelpContent}
757 </div>
758 ) : null;
759​
760 const accountPicker = (
761 <ChatGptAccountPicker
762 open={accountPickerOpen}
763 methods={auth?.methods ?? []}
764 onClose={() => setAccountPickerOpen(false)}
765 onSelect={(methodId) => {
766 setAccountPickerOpen(false);
767 void setup(
768 auth?.methods?.some((method) => method.id === methodId)
769 ? methodId
770 : "chatgpt-change-account",
771 );
772 }}
773 />
774 );
775​
776 const logoutWarning =
777 auth?.phase === "idle" && auth.message?.startsWith("Signed out locally.") ? auth.message : null;
778​
779 if (presentation === "onboarding") {
780 const setupError =
781 logoutWarning ??
782 error ??
783 (authQuery.error || installQuery.error
784 ? "Could not read setup status. Reconnect and try again."
785 : installation?.phase === "failed"
786 ? installation.message
787 : null);
788 return (
789 <>
790 {accountPicker}
791 <CodexWelcomeCard
792 title={displayName || provider?.displayName || "Codex"}
793 description={
794 installActive ? (
795 runtimeDescription
796 ) : authenticated ? (
797 provider?.auth.email?.trim() ? (
798 <>
799 Signed in as{" "}
800 <RedactedSensitiveText
801 value={provider.auth.email.trim()}
802 ariaLabel="Toggle account email visibility"
803 revealTooltip="Click to reveal email"
804 hideTooltip="Click to hide email"
805 className="break-all"
806 />
807 .
808 </>
809 ) : (
810 "Connected to ChatGPT."
811 )
812 ) : callbackCompletion && !needsManualCallback ? (
813 <CodexSignInDescription
814 expanded={callbackHelpOpen}
815 controls={callbackHelpId}
816 onToggle={() => setCallbackHelpOpen((open) => !open)}
817 />
818 ) : startingAutomatically ||
819 waitingForAuthState ||
820 auth?.phase === "starting" ||
821 auth?.phase === "waiting" ||
822 (pending && !installActive) ? (
823 <CodexSignInDescription />
824 ) : authActive || auth?.phase === "failed" || auth?.phase === "cancelled" ? (
825 accountDescription
826 ) : (
827 "Code with your ChatGPT subscription."
828 )
829 }
830 control={
831 authenticated && !busy ? (
832 <span className="inline-flex items-center gap-1.5 text-xs font-medium text-success-foreground">
833 <CheckIcon className="size-3.5" />
834 Ready
835 </span>
836 ) : authActive ? (
837 waitingControl
838 ) : (
839 <ChatGptConnectionButton
840 size="sm"
841 disabled={
842 unavailable ||
843 busy ||
844 (!installed ? !provider?.setup?.canInstall : !provider?.setup?.canAuthenticate)
845 }
846 onClick={() => {
847 if (hasSavedAccount) setAccountPickerOpen(true);
848 else void setup();
849 }}
850 >
851 {installActive || pending
852 ? "Setting up..."
853 : hasSavedAccount
854 ? "Reconnect account"
855 : "Continue with ChatGPT"}
856 </ChatGptConnectionButton>
857 )
858 }
859 secondaryControl={
860 (authActive && !finishingSignIn) || installActive ? (
861 <Button
862 size="sm"
863 variant="ghost-muted"
864 disabled={pending || readOnly}
865 onClick={() => {
866 abortOperation();
867 if (handoff || (authActive && auth?.flowId)) void cancelSignIn();
868 else if (installation?.operationId)
869 void run(() =>
870 cancelInstall({
871 environmentId,
872 input: { instanceId, operationId: installation.operationId! },
873 }),
874 );
875 }}
876 >
877 Cancel
878 </Button>
879 ) : !authActive && !authenticated && hasSavedAccount ? (
880 <Button
881 size="sm"
882 variant="ghost-muted"
883 disabled={unavailable || busy}
884 onClick={() => void setup("chatgpt-change-account")}
885 >
886 Use a different account
887 </Button>
888 ) : !authActive && !authenticated && allowExistingCli ? (
889 <Button
890 size="sm"
891 variant="ghost-muted"
892 disabled={readOnly || busy}
893 onClick={() => onModeChange("existing")}
894 >
895 Use existing CLI
896 </Button>
897 ) : null
898 }
899 >
900 {needsManualCallback ? callbackFallback : callbackHelpContent}
901 {setupError ? (
902 <p role="alert" className="text-xs text-destructive">
903 {setupError}
904 </p>
905 ) : null}
906 </CodexWelcomeCard>
907 </>
908 );
909 }
910​
911 return (
912 <section aria-label="Codex setup" className="divide-y divide-border/50">
913 {accountPicker}
914 <SettingsRow
915 title="ChatGPT account"
916 description={accountDescription}
917 control={
918 <div className="flex flex-wrap items-center justify-end gap-2">
919 {authActive ? (
920 <>
921 {waitingControl}
922 {!finishingSignIn && (
923 <Button
924 size="sm"
925 variant="ghost"
926 disabled={pending || readOnly}
927 onClick={() => {
928 if (!handoff && !auth?.flowId) return;
929 abortOperation();
930 void cancelSignIn();
931 onSignInCancelled?.();
932 }}
933 >
934 Cancel
935 </Button>
936 )}
937 </>
938 ) : installActive ? (
939 <Button
940 size="sm"
941 variant="ghost"
942 disabled={pending || readOnly}
943 onClick={() => {
944 if (!installation?.operationId) return;
945 abortOperation();
946 void run(() =>
947 cancelInstall({
948 environmentId,
949 input: { instanceId, operationId: installation.operationId! },
950 }),
951 );
952 }}
953 >
954 Cancel
955 </Button>
956 ) : authenticated ? (
957 <>
958 <Button
959 size="sm"
960 variant="outline"
961 disabled={unavailable || busy}
962 onClick={() => setAccountPickerOpen(true)}
963 >
964 Change account
965 </Button>
966 <Button
967 size="sm"
968 variant="ghost"
969 disabled={unavailable || busy}
970 onClick={() => void run(() => logoutAuth(target))}
971 >
972 Disconnect
973 </Button>
974 </>
975 ) : (
976 <>
977 <ChatGptConnectionButton
978 size="sm"
979 disabled={
980 unavailable ||
981 busy ||
982 (!installed ? !provider?.setup?.canInstall : !provider?.setup?.canAuthenticate)
983 }
984 onClick={() => {
985 if (hasSavedAccount) setAccountPickerOpen(true);
986 else void setup();
987 }}
988 >
989 {pending
990 ? "Setting up..."
991 : hasSavedAccount
992 ? "Reconnect account"
993 : "Continue with ChatGPT"}
994 </ChatGptConnectionButton>
995 {hasSavedAccount ? (
996 <Button
997 size="sm"
998 variant="ghost"
999 disabled={unavailable || busy}
1000 onClick={() => void setup("chatgpt-change-account")}
1002 Use a different account
1003 </Button>
1004 ) : null}
1005 </>
1006 )}
1007 </div>
1009 />
1010 {authenticated ? (
1011 <div className="flex justify-end px-3 py-1 sm:px-4">
1012 <ChatGptUsageButton />
1013 </div>
1014 ) : null}
1015 {logoutWarning ? (
1016 <p role="alert" className="px-3 py-2 text-xs text-muted-foreground sm:px-4">
1017 {logoutWarning}
1018 </p>
1019 ) : null}
1020 {callbackFallback ? <div className="px-3 py-3 sm:px-4">{callbackFallback}</div> : null}
1021 {error || authQuery.error || installQuery.error || installation?.phase === "failed" ? (
1022 <p role="alert" className="px-3 py-2 text-xs text-destructive sm:px-4">
1023 {error ??
1024 (installation?.phase === "failed"
1025 ? installation.message
1026 : "Could not read Codex setup status. Reconnect and try again.")}
1027 </p>
1028 ) : null}
1029 </section>
1030 );
1032​
1033export function CodexManagedRuntimeFields({
1034 environmentId,
1035 instanceId,
1036 provider,
1037}: {
1038 readonly environmentId: EnvironmentId;
1039 readonly instanceId: ProviderInstanceId;
1040 readonly provider: ServerProvider | undefined;
1041}) {
1042 const installation = useEnvironmentQuery(
1043 serverEnvironment.providerInstallState({
1044 environmentId,
1045 input: { instanceId },
1046 }),
1047 );
1048 const executablePath = installation.data?.executablePath ?? "";
1049 return (
1050 <>
1051 <SettingsRow
1052 title="Binary path"
1053 description="Selected by T3 Code."
1054 control={
1055 <div className="w-full sm:w-80">
1056 <Input
1057 aria-label="Codex binary path"
1058 value={executablePath}
1059 title={executablePath}
1060 placeholder={installation.error ? "Could not read runtime path" : "Not installed"}
1061 disabled
1062 />
1063 </div>
1065 />
1066 <SettingsRow
1067 title="CODEX_HOME path"
1068 description="Shared Codex config, sessions, and state."
1069 control={
1070 <div className="w-full sm:w-80">
1071 <Input
1072 aria-label="Codex home path"
1073 value={provider?.runtimePaths?.homePath ?? ""}
1074 title={provider?.runtimePaths?.homePath}
1075 placeholder="Unavailable"
1076 disabled
1077 />
1078 </div>
1080 />
1081 <SettingsRow
1082 title="Shadow home path"
1083 description={
1084 provider?.runtimePaths?.shadowHomePath
1085 ? "Account-specific home sharing the Codex state above."
1086 : "This instance uses the shared Codex home directly."
1088 control={
1089 <div className="w-full sm:w-80">
1090 <Input
1091 aria-label="Codex shadow home path"
1092 value={provider?.runtimePaths?.shadowHomePath ?? ""}
1093 title={provider?.runtimePaths?.shadowHomePath ?? undefined}
1094 placeholder={provider?.runtimePaths ? "Not used" : "Unavailable"}
1095 disabled
1096 />
1097 </div>
1099 />
1100 </>
1101 );
1103​
1104function CodexSignInDescription({
1105 label = "Complete sign-in in your browser.",
1106 expanded = false,
1107 controls,
1108 onToggle,
1109}: {
1110 readonly label?: string;
1111 readonly expanded?: boolean;
1112 readonly controls?: string;
1113 readonly onToggle?: () => void;
1114}) {
1115 if (!onToggle) return <div className="leading-relaxed">{label}</div>;
1116 return (
1117 <button
1118 type="button"
1119 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"
1120 aria-label="Having trouble signing in?"
1121 aria-expanded={expanded}
1122 aria-controls={controls}
1123 onClick={onToggle}
1125 {label}
1126 <ChevronRightIcon aria-hidden className={`size-3 shrink-0 ${expanded ? "rotate-90" : ""}`} />
1127 </button>
1128 );
1130​
1131function CodexWelcomeCard({
1132 title,
1133 description,
1134 control,
1135 secondaryControl,
1136 children,
1137}: {
1138 readonly title: string;
1139 readonly description: ReactNode;
1140 readonly control?: ReactNode;
1141 readonly secondaryControl?: ReactNode;
1142 readonly children?: ReactNode;
1143}) {
1144 const footer = Children.toArray(children);
1145 return (
1146 <div className="rounded-lg border border-border bg-background px-4 py-4">
1147 <div className="flex flex-wrap items-center gap-3">
1148 <OpenAI className="size-5 shrink-0 fill-foreground" />
1149 <div className="min-w-0 flex-1">
1150 <h3 className="text-sm font-medium">{title}</h3>
1151 <div className="mt-0.5 text-xs leading-relaxed text-muted-foreground">{description}</div>
1152 </div>
1153 {control || secondaryControl ? (
1154 <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">
1155 {secondaryControl}
1156 {control}
1157 </div>
1158 ) : null}
1159 </div>
1160 {footer.length > 0 ? (
1161 <div className="ml-8 mt-2 flex flex-wrap items-center gap-2">{footer}</div>
1162 ) : null}
1163 </div>
1164 );