Skip to content

Commit 69b84f5

Browse files
committed
fix(providers): allow removing incomplete ChatGPT connections
1 parent 83a3674 commit 69b84f5

17 files changed

Lines changed: 286 additions & 6 deletions

File tree

‎apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,10 @@ function ProviderAccount({
149149
const complete = useAtomCommand(serverEnvironment.completeProviderAuth, options);
150150
const cancel = useAtomCommand(serverEnvironment.cancelProviderAuth, options);
151151
const logout = useAtomCommand(serverEnvironment.logoutProviderAuth, options);
152+
const removeMethod = useAtomCommand(serverEnvironment.removeProviderAuthMethod, options);
153+
const canRemoveMethod = useAtomValue(
154+
serverEnvironment.removeProviderAuthMethod.permissionAtom(environmentId),
155+
);
152156
// Matches ListRowLayout: large text stacks the action below instead of squeezing the status.
153157
const stacked = useWindowDimensions().fontScale >= 1.5;
154158
const [pending, setPending] = useState(false);
@@ -260,6 +264,21 @@ function ProviderAccount({
260264
id: `method:${method.id}`,
261265
title: method.name,
262266
}));
267+
const removableMethods = methods.filter((method) => method.canRemove);
268+
const removeActions: MenuAction[] = removableMethods.length
269+
? [
270+
{
271+
id: "remove",
272+
title: "Remove incomplete connection",
273+
attributes: { disabled: disabled || active || !canRemoveMethod },
274+
subactions: removableMethods.map((method) => ({
275+
id: `remove:${method.id}`,
276+
title: method.name,
277+
attributes: { destructive: true, disabled: disabled || active || !canRemoveMethod },
278+
})),
279+
},
280+
]
281+
: [];
263282
function startSignIn(methodId?: string) {
264283
void run(() => start(methodId ? { environmentId, input: { instanceId, methodId } } : target));
265284
}
@@ -283,10 +302,16 @@ function ProviderAccount({
283302
if (id === "signOut") signOut();
284303
// iOS keeps a disabled submenu's children selectable, so sign-in guards here too.
285304
else if (signInDisabled) return;
286-
else if (id.startsWith("method:")) startSignIn(id.slice("method:".length));
305+
else if (id.startsWith("remove:")) {
306+
if (active || !canRemoveMethod) return;
307+
const methodId = id.slice("remove:".length);
308+
if (!removableMethods.some((method) => method.id === methodId)) return;
309+
void run(() => removeMethod({ environmentId, input: { instanceId, methodId } }));
310+
} else if (id.startsWith("method:")) startSignIn(id.slice("method:".length));
287311
else if (id === "change") startSignIn();
288312
}
289313
const accountActions: MenuAction[] = [
314+
...removeActions,
290315
...(canSignIn
291316
? [
292317
{
@@ -357,7 +382,7 @@ function ProviderAccount({
357382
accessibilityRole="button"
358383
accessibilityLabel={`Sign in to ${name}`}
359384
title="Sign in with"
360-
actions={methodActions}
385+
actions={[...methodActions, ...removeActions]}
361386
onPressAction={({ nativeEvent }) => onMenuAction(nativeEvent.event)}
362387
>
363388
<ControlPill variant="primary" label="Sign in" accessibilityLabel={`Sign in to ${name}`} />

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ export const RPC_REQUIRED_SCOPES = {
7474
[WS_METHODS.chatGptHandoffSubscribe]: AuthProvidersManageScope,
7575
[WS_METHODS.providerAuthRespond]: AuthProvidersManageScope,
7676
[WS_METHODS.providerAuthCancel]: AuthProvidersManageScope,
77+
[WS_METHODS.providerAuthRemoveMethod]: AuthProvidersManageScope,
7778
[WS_METHODS.providerAuthLogout]: AuthProvidersManageScope,
7879
[WS_METHODS.providerAuthSubscribe]: AuthProvidersManageScope,
7980
[WS_METHODS.providerInstallStart]: AuthProvidersManageScope,

‎apps/server/src/observability/RpcInstrumentation.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ const RPC_AGGREGATES = {
4646
[WS_METHODS.chatGptHandoffSubscribe]: "provider",
4747
[WS_METHODS.providerAuthRespond]: "provider",
4848
[WS_METHODS.providerAuthCancel]: "provider",
49+
[WS_METHODS.providerAuthRemoveMethod]: "provider",
4950
[WS_METHODS.providerAuthLogout]: "provider",
5051
[WS_METHODS.providerAuthSubscribe]: "provider",
5152
[WS_METHODS.providerInstallStart]: "provider",

‎apps/server/src/provider/CodexChatGptAuth.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1379,6 +1379,70 @@ it.effect("an expired initial code retains the issued ID for a fresh authorizati
13791379
),
13801380
);
13811381

1382+
it.effect.each([false, true])(
1383+
"removes only the selected incomplete connection across restart (authenticated: %s)",
1384+
(authenticated) =>
1385+
provision(
1386+
Effect.gen(function* () {
1387+
const h = yield* makeHarness;
1388+
if (authenticated) {
1389+
yield* h.signIn;
1390+
yield* h.phase("succeeded");
1391+
}
1392+
const credentials = yield* h.auth.read;
1393+
h.setCallbackClientId("oaiapp_failed");
1394+
h.setCodeError("invalid_grant");
1395+
yield* h.changeAccount;
1396+
const failed = yield* h.phase("failed");
1397+
const methodId = "chatgpt-profile:oaiapp_failed";
1398+
assert.isTrue(failed.methods!.find((method) => method.id === methodId)?.canRemove);
1399+
h.setCallbackClientId("oaiapp_other_failed");
1400+
yield* h.changeAccount;
1401+
yield* h.phase("failed");
1402+
const { waiting } = yield* h.startRemote(methodId);
1403+
const busy = yield* Effect.flip(h.auth.controller.removeMethod!(methodId));
1404+
assert.include(busy.detail, "Finish or cancel");
1405+
yield* h.auth.controller.cancel("owner", waiting.flowId!);
1406+
const removed = yield* h.auth.controller.removeMethod!(methodId);
1407+
assert.isFalse(removed.methods!.some((method) => method.id === methodId));
1408+
assert.isTrue(
1409+
removed.methods!.some((method) => method.id === "chatgpt-profile:oaiapp_other_failed"),
1410+
);
1411+
assert.deepEqual(yield* h.auth.read, credentials);
1412+
h.setCallbackClientId("oaiapp_new_failed");
1413+
yield* h.changeAccount;
1414+
const next = yield* h.phase("failed");
1415+
const profiles = next.methods!.filter((method) => method.id.startsWith("chatgpt-profile:"));
1416+
assert.strictEqual(new Set(profiles.map((method) => method.name)).size, profiles.length);
1417+
yield* h.auth.controller.removeMethod!("chatgpt-profile:oaiapp_new_failed");
1418+
const last = yield* h.auth.controller.removeMethod!("chatgpt-profile:oaiapp_other_failed");
1419+
assert.strictEqual(
1420+
last.methods!.filter((method) => method.id.startsWith("chatgpt-profile:")).length,
1421+
authenticated ? 1 : 0,
1422+
);
1423+
const restarted = yield* h.recreateAuth;
1424+
yield* restarted.controller.refreshMethods!;
1425+
const state = yield* restarted.controller.subscribe("owner").pipe(Stream.runHead);
1426+
assert.deepEqual(Option.getOrThrow(state).methods, last.methods);
1427+
if (authenticated) {
1428+
assert.isFalse(
1429+
last.methods!.find((method) => method.id === "chatgpt-profile:oaiapp_test")?.canRemove,
1430+
);
1431+
yield* Effect.flip(h.auth.controller.removeMethod!("chatgpt-profile:oaiapp_test"));
1432+
yield* h.auth.controller.logout(Effect.void);
1433+
}
1434+
h.setCodeError(undefined);
1435+
h.setCallbackClientId("oaiapp_test");
1436+
yield* h.signIn;
1437+
yield* h.phase("succeeded");
1438+
assert.strictEqual(
1439+
h.authorizationRequests.at(-1)!.searchParams.get("client_id"),
1440+
authenticated ? "oaiapp_test" : "dynamic_agent_client",
1441+
);
1442+
}),
1443+
),
1444+
);
1445+
13821446
it.effect("identity-only sign-in requests consent on an explicit retry, then rechecks scopes", () =>
13831447
provision(
13841448
Effect.gen(function* () {

‎apps/server/src/provider/CodexChatGptAuth.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,12 +387,17 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
387387
);
388388
const saveRegistration = Effect.fnUntraced(function* (profile: typeof Registration.Type) {
389389
const saved = yield* readRegistrations;
390+
let connectionNumber = saved.profiles.length + 1;
391+
while (
392+
saved.profiles.some((entry) => entry.connectionLabel === `Connection ${connectionNumber}`)
393+
)
394+
connectionNumber++;
390395
profile = {
391396
...profile,
392397
connectionLabel:
393398
saved.profiles.find((entry) => entry.clientId === profile.clientId)?.connectionLabel ??
394399
profile.connectionLabel ??
395-
`Connection ${saved.profiles.length + 1}`,
400+
`Connection ${connectionNumber}`,
396401
};
397402
yield* encodeRegistration({
398403
profiles: [profile, ...saved.profiles.filter((entry) => entry.clientId !== profile.clientId)],
@@ -911,6 +916,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
911916
methods: Effect.gen(function* () {
912917
const saved = yield* readRegistrations;
913918
const active = Option.getOrUndefined(yield* read);
919+
const sessions = (yield* readSessions).sessions;
914920
const current = saved.profiles.find(
915921
(profile) => profile.clientId === (active?.clientId ?? saved.lastClientId),
916922
);
@@ -933,6 +939,9 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
933939
},
934940
...profiles.slice(0, 30).map((profile) => ({
935941
id: profileMethodId(profile.clientId),
942+
canRemove:
943+
profile.subject === undefined &&
944+
!sessions.some((session) => session.clientId === profile.clientId),
936945
name: `${profile.email ?? "ChatGPT account"} · ${profile.connectionLabel}`,
937946
...(profile.email ? { accountEmail: profile.email } : {}),
938947
description: "Reuse this account's original sign-in registration.",
@@ -962,6 +971,45 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
962971
context.expiresAt,
963972
),
964973
),
974+
removeMethod: Effect.fn("CodexChatGptAuth.removeMethod")(function (methodId) {
975+
return lock.withPermit(
976+
withSessionLock(
977+
Effect.gen(function* () {
978+
const saved = yield* readRegistrations;
979+
const profile = saved.profiles.find(
980+
(entry) => profileMethodId(entry.clientId) === methodId,
981+
);
982+
if (
983+
!profile ||
984+
profile.subject !== undefined ||
985+
(yield* readSessions).sessions.some(
986+
(session) => session.clientId === profile.clientId,
987+
)
988+
)
989+
return yield* failure(
990+
"removeMethod",
991+
"Only incomplete ChatGPT connections can be removed.",
992+
);
993+
const profiles = saved.profiles.filter((entry) => entry.clientId !== profile.clientId);
994+
yield* encodeRegistration({
995+
profiles,
996+
lastClientId:
997+
saved.lastClientId === profile.clientId
998+
? (profiles[0]?.clientId ?? null)
999+
: saved.lastClientId,
1000+
}).pipe(
1001+
Effect.flatMap((json) => registrationStore.set(new TextEncoder().encode(json))),
1002+
Effect.mapError(() =>
1003+
failure(
1004+
"removeMethod",
1005+
"Could not remove the saved ChatGPT connection. Try again.",
1006+
),
1007+
),
1008+
);
1009+
}),
1010+
),
1011+
);
1012+
}),
9651013
logout: lock.withPermit(withSessionLock(logout)),
9661014
});
9671015
const reconnectProfile = Effect.fnUntraced(function* (methodId: string) {

‎apps/server/src/provider/ProviderAuthService.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ export class ProviderAuthService extends Context.Service<
5151
input: ProviderAuthTarget & { readonly flowId: string },
5252
ownerSessionId: string,
5353
) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
54+
readonly removeMethod: (
55+
input: ProviderAuthTarget & { readonly methodId: string },
56+
) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
5457
readonly logout: (
5558
input: ProviderAuthTarget,
5659
) => Effect.Effect<ProviderAuthState, ProviderSetupError>;
@@ -170,7 +173,7 @@ export const makeProviderAuthService = Effect.gen(function* () {
170173

171174
const checkSharedBinding = Effect.fnUntraced(function* (
172175
instanceId: ProviderInstanceId,
173-
operation: "start" | "logout",
176+
operation: "start" | "logout" | "removeMethod",
174177
auth: ProviderAuthController,
175178
) {
176179
const binding = auth.credentialBinding;
@@ -257,6 +260,21 @@ export const makeProviderAuthService = Effect.gen(function* () {
257260
const auth = yield* getController(input.instanceId, "cancel");
258261
return yield* auth.cancel(ownerSessionId, input.flowId);
259262
}),
263+
removeMethod: Effect.fn("ProviderAuthService.removeMethod")(function (input) {
264+
return credentialChanges.withPermit(
265+
Effect.gen(function* () {
266+
const auth = yield* getController(input.instanceId, "removeMethod");
267+
yield* checkSharedBinding(input.instanceId, "removeMethod", auth);
268+
if (!auth.removeMethod)
269+
return yield* new ProviderSetupError({
270+
instanceId: input.instanceId,
271+
operation: "removeMethod",
272+
detail: "This provider does not support removing saved sign-in methods.",
273+
});
274+
return yield* auth.removeMethod(input.methodId);
275+
}),
276+
);
277+
}),
260278
logout: Effect.fn("ProviderAuthService.logout")(function* (input) {
261279
return yield* credentialChanges.withPermit(
262280
Effect.gen(function* () {

‎apps/server/src/ws.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2646,6 +2646,7 @@ export const layerWsRpc = (
26462646
[WS_METHODS.chatGptHandoffSubscribe]: (input) =>
26472647
subscribeChatGptHandoff(input, currentSessionId),
26482648
[WS_METHODS.providerAuthCancel]: (input) => providerAuth.cancel(input, currentSessionId),
2649+
[WS_METHODS.providerAuthRemoveMethod]: (input) => providerAuth.removeMethod(input),
26492650
[WS_METHODS.providerAuthLogout]: (input) => providerAuth.logout(input),
26502651
[WS_METHODS.providerAuthSubscribe]: (input) =>
26512652
providerAuth.subscribe(input, currentSessionId),

‎apps/web/src/components/settings/ChatGptAccountPicker.tsx‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,27 @@ import {
99
DialogDescription,
1010
DialogFooter,
1111
} from "../ui/dialog";
12+
import { Button } from "../ui/button";
1213
import { ChatGptConnectionButton } from "./ChatGptConnectionButton";
1314

1415
export function ChatGptAccountPicker({
1516
open,
1617
methods,
1718
onClose,
1819
onSelect,
20+
onRemove,
21+
disabled,
22+
canRemove,
23+
error,
1924
}: {
2025
open: boolean;
2126
methods: readonly ProviderAuthMethod[];
2227
onClose: () => void;
2328
onSelect: (methodId: string) => void;
29+
onRemove: (methodId: string) => void;
30+
disabled: boolean;
31+
canRemove: boolean;
32+
error: string | null;
2433
}) {
2534
const profiles = methods.filter((method) => method.id.startsWith("chatgpt-profile:"));
2635
const [selection, setSelection] = useState<string | null>(null);
@@ -47,6 +56,7 @@ export function ChatGptAccountPicker({
4756
<div className="px-6 pb-6">
4857
<RadioGroup
4958
aria-label="ChatGPT account to connect"
59+
disabled={disabled}
5060
value={selectedMethodId}
5161
onValueChange={(value) => setSelection(value)}
5262
>
@@ -65,8 +75,22 @@ export function ChatGptAccountPicker({
6575
</label>
6676
</RadioGroup>
6777
</div>
78+
{error ? (
79+
<p role="alert" className="px-6 pb-3 text-sm text-destructive">
80+
{error}
81+
</p>
82+
) : null}
6883
<DialogFooter>
69-
<ChatGptConnectionButton onClick={() => onSelect(selectedMethodId)} />
84+
{profiles.find((profile) => profile.id === selectedMethodId)?.canRemove ? (
85+
<Button
86+
variant="ghost"
87+
disabled={disabled || !canRemove}
88+
onClick={() => onRemove(selectedMethodId)}
89+
>
90+
Remove connection
91+
</Button>
92+
) : null}
93+
<ChatGptConnectionButton disabled={disabled} onClick={() => onSelect(selectedMethodId)} />
7094
</DialogFooter>
7195
</DialogPopup>
7296
</Dialog>

‎apps/web/src/components/settings/CodexSetupSection.tsx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { useAtomValue } from "@effect/atom-react";
12
import { AuthProvidersManageScope, ProviderDriverKind } from "@t3tools/contracts";
23
import { readPreparedConnection, useEnvironmentScope } from "../../state/session";
34
import {
@@ -293,6 +294,10 @@ function ManagedCodexSetup({
293294
const completeAuth = useAtomCommand(serverEnvironment.completeProviderAuth, options);
294295
const cancelAuth = useAtomCommand(serverEnvironment.cancelProviderAuth, options);
295296
const logoutAuth = useAtomCommand(serverEnvironment.logoutProviderAuth, options);
297+
const removeAuthMethod = useAtomCommand(serverEnvironment.removeProviderAuthMethod, options);
298+
const canRemoveAuthMethod = useAtomValue(
299+
serverEnvironment.removeProviderAuthMethod.permissionAtom(environmentId),
300+
);
296301
const startInstall = useAtomCommand(serverEnvironment.startProviderInstall, options);
297302
const cancelInstall = useAtomCommand(serverEnvironment.cancelProviderInstall, options);
298303
const reconnectProfile = useAtomCommand(serverEnvironment.chatGptReconnectProfile, options);
@@ -771,6 +776,12 @@ function ManagedCodexSetup({
771776
open={accountPickerOpen}
772777
methods={auth?.methods ?? []}
773778
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+
}}
774785
onSelect={(methodId) => {
775786
setAccountPickerOpen(false);
776787
void setup(

0 commit comments

Comments
 (0)