feat(codex): connect ChatGPT accounts with managed authentication #14290
Mergedjuliusmarmingemerged 7 commits into
main fromrefs/pull/14290/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +31,21 @@31+ const settings = yield* ServerSettingsService;32+ const runtime = yield* makeCodexManagedRuntime({33+ instanceId,34+ enabled,35+ config,36+ environment: mergeProviderInstanceEnvironment(input.environment),37+ });38+ const continuationIdentity = codexContinuationIdentity(runtime.homeLayout);39+ const stamp = withInstanceIdentity({40+ instanceId,41+ driverKind: DRIVER,42+ displayName,43+ accentColor,44+ continuationGroupKey: continuationIdentity.continuationKey,45+ });46+ const setup = { canAuthenticate: true, canInstall: true };47+ const runtimePaths = {48+ homePath: runtime.homeLayout.sharedHomePath,49+ shadowHomePath: runtime.homeLayout.mode === "authOverlay" ? runtime.homePath : null,50+ };51+ const pending = makePendingCodexProvider({ ...config, customModels: [] }).pipe(@@ -19,3 +24,7 @@1924 function WelcomeRouteView() {2025 const { authGateState } = Route.useRouteContext();2126 const navigate = useNavigate();27+ const hash = useLocation({ select: (location) => location.hash });28+ const resumeEnvironmentId = hash.startsWith("agents:")29+ ? Option.getOrUndefined(decodeEnvironmentId(hash.slice("agents:".length)))30+ : undefined;@@ -0,0 +637,21 @@637+ }638+ return yield* SubscriptionRef.get(state);639+ }),640+ );641+ });642+643+ const remove = Effect.fn("CodexInstallation.remove")(644+ function* (protectedBinaryPaths: ReadonlyArray<string> = []) {645+ yield* gate.withPermit(646+ Effect.gen(function* () {647+ if (isRunning(yield* SubscriptionRef.get(state)) || leases > 0) {648+ return yield* installationError(649+ "remove",650+ "Stop Codex sessions and sign-in flows before removing its managed runtime.",651+ );652+ }653+ const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);654+ if (Option.isSome(realManaged)) {655+ for (const binary of protectedBinaryPaths) {656+ const resolved = yield* fs.realPath(binary).pipe(Effect.option);657+ const candidate = Option.getOrElse(resolved, () => path.resolve(binary));@@ -0,0 +885,21 @@885+ );886+ }887+888+ return (889+ <section aria-label="Codex setup" className="divide-y divide-border/50">890+ {accountPicker}891+ <SettingsRow892+ title="ChatGPT account"893+ description={accountDescription}894+ control={895+ <div className="flex flex-wrap items-center justify-end gap-2">896+ {authActive ? (897+ <>898+ {waitingControl}899+ {!finishingSignIn && (900+ <Button901+ size="sm"902+ variant="ghost"903+ disabled={pending || readOnly}904+ onClick={() => {905+ if (!handoff && !auth?.flowId) return;apps/web/src/routes/__root.tsx line 222Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -216,3 +218,4 @@216218 <EnvironmentThemeSync />217219 <GlassAppearanceSync />218220 <FontAppearanceSync />221+ <ProviderAuthCallbackCoordinator />@@ -53,3 +53,21 @@5353 if (search.machine) next.machine = search.machine;5454 return next;5555 }56+57+/** Provider configuration always belongs to one environment, including project scopes. */58+export function selectSingleEnvironmentScope(59+ search: SettingsScopeSearch,60+ scope: ResolvedSettingsScope,61+ environments: readonly {62+ readonly environmentId: EnvironmentPresentation["environmentId"];63+ readonly connection: Pick<EnvironmentPresentation["connection"], "phase">;64+ }[],65+ primaryEnvironmentId: string | null,66+): SettingsScopeSearch {67+ if (search.machine || scope.kind === "unavailable") return search;68+ const selectedIds = new Set(scope.environmentIds);69+ const candidates = environments.filter((environment) =>70+ selectedIds.has(environment.environmentId),71+ );72+ const selected =73+ candidates.find((environment) => environment.environmentId === primaryEnvironmentId) ??@@ -139,0 +170,21 @@170+ };171+ const resumeProviderAuth = (value: string | undefined) => {172+ const destination = providerAuthReturnUrl(value);173+ const expectedOrigin = `${ElectronProtocol.getDesktopScheme(environment.isDevelopment)}://app`;174+ if (!destination?.startsWith(`${expectedOrigin}/`)) return false;175+ void runPromise(176+ Effect.gen(function* () {177+ const mainWindow = yield* electronWindow.currentMainOrFirst;178+ if (Option.isNone(mainWindow)) return;179+ yield* Effect.promise(() => mainWindow.value.loadURL(destination));180+ yield* electronWindow.reveal(mainWindow.value);181+ }).pipe(182+ Effect.catchCause((cause) =>183+ Effect.logWarning("Could not return to provider setup", cause),184+ ),185+ ),186+ );187+ return true;188+ };189+ const args = yield* HostProcessArguments;190+ args.some((value) => startProviderAuthHandoff(value));@@ -2508,3 +2510,4 @@25082510 providerAuth.complete(input, currentSessionId),25092511 { "rpc.aggregate": "provider" },25102512 ),2513+ [WS_METHODS.chatGptReconnectProfile]: (input) => providerAuth.reconnectProfile(input),@@ -717,12 +736,9 @@717- serverConfig.settings,718- serverConfig.environment.platform.os,719- )720- : resolveOnboardingProviderInstallCommand(721- driver,722- serverConfig.environment.platform.os,723- ),724- keybindings: serverConfig.keybindings,725- });726- }}727- />728- ))}736+ {primaryAgents.map(({ driver, provider, instanceId }) =>737+ driver === "codex" && serverConfig !== null ? (738+ <OnboardingCodexSetup739+ key={instanceId ?? driver}740+ environmentId={environmentId}741+ provider={provider}742+ serverConfig={serverConfig}743+ createdAccount={instanceId === createdAccount?.instanceId ? createdAccount : null}744+ onAutoStartConsumed={() =>@@ -0,0 +489,21 @@489+ )490+ return;491+ setAutoStartHandled(true);492+ onAutoStartConsumed();493+ void setup();494+ }, [495+ autoStart,496+ autoStartHandled,497+ unavailable,498+ busy,499+ installation,500+ provider?.setup?.canInstall,501+ onAutoStartConsumed,502+ setup,503+ ]);504+505+ useEffect(() => {506+ if (!continueWithSignIn.current || pending || installActive) return;507+ if (installation?.phase === "failed" || installation?.phase === "cancelled") {508+ continueWithSignIn.current = null;509+ } else if (installed) {@@ -0,0 +885,21 @@885+ );886+ }887+888+ return (889+ <section aria-label="Codex setup" className="divide-y divide-border/50">890+ {accountPicker}891+ <SettingsRow892+ title="ChatGPT account"893+ description={accountDescription}894+ control={895+ <div className="flex flex-wrap items-center justify-end gap-2">896+ {authActive ? (897+ <>898+ {waitingControl}899+ {!finishingSignIn && (900+ <Button901+ size="sm"902+ variant="ghost"903+ disabled={pending || readOnly}904+ onClick={() => {905+ if (!handoff && !auth?.flowId) return;apps/server/src/provider/Drivers/CodexManagedProvider.ts line 124Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +104,21 @@104+ },105+ externalUsage: { label: "ChatGPT usage", url: "https://chatgpt.com/#settings/Usage" },106+ };107+ const managedAuth = {108+ subscriptionSharing: true,109+ profileId: saved.value.clientId,110+ status: "authenticated" as const,111+ type: "chatgpt",112+ label: "ChatGPT",113+ ...(saved.value.email?.trim() ? { email: saved.value.email.trim() } : {}),114+ };115+ return yield* runtime.auth.controller.withAccess!(runtime.resolve).pipe(116+ Effect.flatMap((effective) =>117+ Effect.gen(function* () {118+ const draft = yield* checkCodexProviderStatus(119+ effective.config,120+ undefined,121+ effective.environment,122+ managedAuth,123+ );124+ const models = yield* chatGptModels(
- @@ -0,0 +1040,21 @@1040+ />1041+ </div>1042+ }1043+ />1044+ <SettingsRow1045+ title="CODEX_HOME path"1046+ description="Shared Codex config, sessions, and state."1047+ control={1048+ <div className="w-full sm:w-80">1049+ <Input1050+ aria-label="Codex home path"1051+ value={provider?.runtimePaths?.homePath ?? ""}1052+ title={provider?.runtimePaths?.homePath}1053+ placeholder="Unavailable"1054+ disabled1055+ />1056+ </div>1057+ }1058+ />1059+ <SettingsRow1060+ title="Shadow home path"
- @@ -0,0 +106,21 @@106+ operation: Schema.String,107+ detail: Schema.String,108+ cause: Schema.optional(Schema.Defect()),109+ },110+) {111+ override get message() {112+ return this.detail;113+ }114+}115+const isInstallationError = Schema.is(CodexInstallationError);116+const installationError = (operation: string, detail: string, cause?: unknown) =>117+ new CodexInstallationError({ operation, detail, ...(cause === undefined ? {} : { cause }) });118+const wrapFailure = (operation: string, detail: string) => (cause: unknown) =>119+ isInstallationError(cause) ? cause : installationError(operation, detail, cause);120+export interface CodexExecutable {121+ readonly executablePath: string;122+ readonly source: "managed" | "local";123+ readonly version: string;124+ readonly managedVersionDirectory: string | null;125+}126+interface CodexInstallationService {@@ -0,0 +56,21 @@56+ const resolve = Effect.gen(function* () {57+ const executable = yield* installation.acquire().pipe(58+ Effect.mapError(59+ () =>60+ new ProviderSetupError({61+ instanceId: options.instanceId,62+ operation: "install",63+ detail: "Set up managed Codex before starting a session.",64+ }),65+ ),66+ );67+ const credentials = yield* auth.access;68+ yield* materializeCodexShadowHome(homeLayout).pipe(69+ Effect.provideService(FileSystem.FileSystem, fs),70+ Effect.provideService(Path.Path, path),71+ Effect.mapError(72+ (cause) =>73+ new ProviderSetupError({74+ instanceId: options.instanceId,75+ operation: "runtime",76+ detail: cause.message,@@ -0,0 +1,17 @@1+import { ProviderSetupError, type CodexAuthCallbackInput } from "@t3tools/contracts";2+import { receiveCodexAuthCallback } from "@t3tools/shared/codexAuthCallback";3+import { codexAuthorizationRequest } from "@t3tools/shared/codexAuthHandoff";4+import { providerAuthReturnUrl } from "@t3tools/shared/providerAuthReturnUrl";5+import { isLoopbackHost } from "@t3tools/shared/preview";6+import * as Deferred from "effect/Deferred";7+import * as Effect from "effect/Effect";8+import * as Fiber from "effect/Fiber";9+import * as Stream from "effect/Stream";10+11+/** A connected local environment receives the callback; only the remote environment owns tokens. */12+export function subscribeCodexAuthCallback(input: CodexAuthCallbackInput) {13+ const failure = (error: unknown) =>14+ new ProviderSetupError({15+ instanceId: input.instanceId,16+ operation: "callback",17+ detail:
- @@ -180,3 +185,7 @@180185 const outputPath = yield* writeTempFile(operation, "codex-output", "");181186182187 const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {188+ const resolved = resolveRuntime189+ ? yield* resolveRuntime.pipe(190+ Effect.mapError(191+ (cause) => new TextGenerationError({ operation, detail: cause.detail }),
juliusmarminge merged this27bdf1a
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed