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

CodexSetupSection.tsx

1,195 lines43.2 KB

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