@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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