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

CodexSetupSection.tsx

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