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

CodexSetupSection.tsx

1,184 lines42.7 KB

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