GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(core): register a new ChatGPT client when adding an account (#64945) · anomalyco/opencode@23d6540

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/core
    • src/plugin/provider
      • chatgpt.ts
    • test/plugin
      • provider-chatgpt.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/plugin/provider/chatgpt.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/plugin/provider/chatgpt.ts
+56-15Lines changed: 56 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ const providerID = Provider.ID.openai
3232
const integrationID = Integration.ID.make("openai")
3333
const methodID = Integration.MethodID.make("chatgpt-token-sharing")
3434
const modelCacheKey = (clientID: string) => `models:${clientID}`
35+
// Clients whose refresh token OpenAI rejected. Signing in while the active connection is one of these reconnects it.
36+
const expiredKey = "chatgpt-expired-clients"
3537
// Used when the catalog has no Sign in with ChatGPT list. gpt-5.5 is rejected there.
3638
const fallbackModels = new Set([
3739
"gpt-5.6-luna",
@@ -94,15 +96,24 @@ const decodeCachedModels = Schema.decodeUnknownOption(Schema.Array(RemoteModel))
9496
const decodeInvalidGrant = Schema.decodeUnknownOption(
9597
Schema.fromJsonString(Schema.Struct({ error: Schema.Literal("invalid_grant") })),
9698
)
99+
const decodeExpired = Schema.decodeUnknownOption(Schema.Array(Schema.String))
100+
const expiredClients = (storage: Context["storage"]) =>
101+
storage
102+
.get(expiredKey)
103+
.pipe(Effect.map((value) => Option.getOrElse(decodeExpired(value), (): readonly string[] => [])))
104+
const Metadata = Schema.Struct({
105+
clientID: Schema.String,
106+
scopes: Schema.optional(Schema.Array(Schema.String)),
107+
email: Schema.optional(Schema.String),
108+
})
97109
const decodeMetadata = Schema.decodeUnknownOption(
98110
Schema.Struct({
99-
clientID: Schema.String,
100-
scopes: Schema.optional(Schema.Array(Schema.String)),
111+
...Metadata.fields,
101112
models: Schema.optional(Schema.Array(RemoteModel)),
102113
}),
103114
)
104115

105-
const signIn = (app: App.Info, savedClientID: () => string | undefined, storage: Context["storage"]) =>
116+
const signIn = (app: App.Info, active: () => Credential.OAuth | undefined, storage: Context["storage"]) =>
106117
({
107118
integrationID,
108119
method: {
@@ -118,7 +129,12 @@ const signIn = (app: App.Info, savedClientID: () => string | undefined, storage:
118129
const pkce = yield* Effect.promise(generatePKCE)
119130
const state = randomValue()
120131
const nonce = randomValue()
121-
const savedID = savedClientID()
132+
// Each issued client only accepts its own ChatGPT account. Signing in while connected adds another account,
133+
// which needs a new client, unless the active connection has expired and this reconnects it.
134+
const metadata = Option.getOrUndefined(decodeMetadata(active()?.metadata))
135+
const expired = yield* expiredClients(storage)
136+
const reconnect = metadata && expired.includes(metadata.clientID) ? metadata : undefined
137+
const savedID = reconnect?.clientID
122138
// `response` is the browser's pending callback request; a pasted redirect has none.
123139
const received = yield* Deferred.make<{ code: string; clientID?: string; response?: ServerResponse }, Error>()
124140
// Lazy so runtimes without a loopback listener (workerd) never evaluate node:http.
@@ -163,7 +179,7 @@ const signIn = (app: App.Info, savedClientID: () => string | undefined, storage:
163179
const redirect = `http://127.0.0.1:${port}/auth/callback`
164180
return {
165181
mode: "auto" as const,
166-
url: authorizeURL(redirect, pkce, state, nonce, savedID, hostID),
182+
url: authorizeURL(redirect, pkce, state, nonce, savedID, hostID, reconnect),
167183
instructions: "Complete authorization in your browser. This window will close automatically.",
168184
callback: Effect.gen(function* () {
169185
const result = yield* Deferred.await(received)
@@ -194,8 +210,14 @@ const signIn = (app: App.Info, savedClientID: () => string | undefined, storage:
194210
),
195211
)
196212
if (!tokens.id_token) return yield* Effect.fail(new Error("ChatGPT sign-in did not return an ID token."))
197-
yield* verifyIDToken(tokens.id_token, clientID, nonce)
198-
return credential(tokens, clientID)
213+
const email = yield* verifyIDToken(tokens.id_token, clientID, nonce)
214+
const stale = yield* expiredClients(storage)
215+
if (stale.includes(clientID))
216+
yield* storage.set(
217+
expiredKey,
218+
stale.filter((id) => id !== clientID),
219+
)
220+
return credential(tokens, { clientID, email })
199221
}).pipe(
200222
Effect.tap(() => respond()),
201223
Effect.tapError((error) => respond(error instanceof Error ? error.message : "ChatGPT sign-in failed")),
@@ -209,7 +231,17 @@ const signIn = (app: App.Info, savedClientID: () => string | undefined, storage:
209231
}),
210232
}
211233
}),
212-
refresh: (value) => refresh(value, app),
234+
refresh: (value) =>
235+
refresh(value, app).pipe(
236+
Effect.tapError((error) =>
237+
Effect.gen(function* () {
238+
const clientID = Option.getOrUndefined(decodeMetadata(value.metadata))?.clientID
239+
if (!(error instanceof SignInExpired) || !clientID) return
240+
const expired = yield* expiredClients(storage)
241+
if (!expired.includes(clientID)) yield* storage.set(expiredKey, [...expired, clientID])
242+
}),
243+
),
244+
),
213245
revoke: (value) => revoke(value, app),
214246
}) satisfies IntegrationOAuthMethodRegistration
215247

@@ -250,9 +282,7 @@ export const ChatGPTPlugin = define({
250282
})
251283

252284
yield* ctx.integration.transform((editor) => {
253-
editor.method.update(
254-
signIn(ctx.app, () => Option.getOrUndefined(decodeMetadata(chatgpt?.metadata))?.clientID, ctx.storage),
255-
)
285+
editor.method.update(signIn(ctx.app, () => chatgpt, ctx.storage))
256286
})
257287
yield* Effect.forEach(
258288
yield* credentials.list(Integration.ID.make("openai")),
@@ -424,7 +454,7 @@ export function refresh(value: Credential.OAuth, app: App.Info, url = tokenURL)
424454
},
425455
"This ChatGPT sign-in has expired or was revoked. Connect again.",
426456
)
427-
return credential(tokens, metadata.clientID, metadata.scopes)
457+
return credential(tokens, metadata)
428458
})
429459
}
430460

@@ -524,32 +554,40 @@ export function verifyIDToken(
524554
})
525555
if (typeof payload.sub !== "string" || !payload.sub.trim()) throw new Error("ID token subject is missing")
526556
if (payload.nonce !== nonce) throw new Error("ID token nonce does not match this sign-in attempt")
557+
return typeof payload.email === "string" ? payload.email : undefined
527558
},
528559
catch: (cause) => new Error("ChatGPT sign-in returned an invalid ID token.", { cause }),
529560
})
530561
}
531562

563+
class SignInExpired extends Error {}
564+
532565
// `rejected` replaces the error when OpenAI answers invalid_grant, which means different things per grant type.
533566
function request<A>(url: string, init: RequestInit, rejected?: string) {
534567
return Effect.tryPromise({
535568
try: async (signal) => {
536569
const response = await fetch(url, { ...init, signal })
537570
if (response.ok) return response.json() as Promise<A>
538-
if (rejected && Option.isSome(decodeInvalidGrant(await response.text()))) throw new Error(rejected)
571+
if (rejected && Option.isSome(decodeInvalidGrant(await response.text()))) throw new SignInExpired(rejected)
539572
throw new Error(`Request failed: ${response.status}`)
540573
},
541574
catch: (cause) => cause,
542575
})
543576
}
544577

545-
function credential(tokens: TokenResponse, clientID: string, scopes?: ReadonlyArray<string>) {
578+
// `email` preselects the account when it reconnects, and goes away with the credential on logout.
579+
function credential(tokens: TokenResponse, metadata: typeof Metadata.Type) {
546580
return Credential.OAuth.make({
547581
type: "oauth",
548582
methodID,
549583
refresh: tokens.refresh_token,
550584
access: tokens.access_token,
551585
expires: Date.now() + (tokens.expires_in ?? 3600) * 1000,
552-
metadata: { clientID, scopes: tokens.scope?.split(" ").filter(Boolean) ?? scopes ?? [] },
586+
metadata: {
587+
clientID: metadata.clientID,
588+
scopes: tokens.scope?.split(" ").filter(Boolean) ?? metadata.scopes ?? [],
589+
...(metadata.email ? { email: metadata.email } : {}),
590+
},
553591
})
554592
}
555593

@@ -575,11 +613,14 @@ function authorizeURL(
575613
nonce: string,
576614
savedID: string | undefined,
577615
hostID: string,
616+
account?: { email?: string },
578617
) {
579618
return `${issuer}/api/accounts/authorize?${new URLSearchParams({
580619
client_id: savedID ?? registrationClientID,
581620
...(savedID ? {} : { agent_name_hint: agentName }),
582621
ext_agent_host_id: hostID,
622+
// Preselect the account being reconnected.
623+
...(account?.email ? { login_hint: account.email } : {}),
583624
// Enable only for user-requested consent retries after OpenAI confirms deployment;
584625
// ordinary sign-ins must not force reconsent.
585626
// force_reconsent: "true",
Collapse file

‎packages/core/test/plugin/provider-chatgpt.test.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/plugin/provider-chatgpt.test.ts
+25-5Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,12 @@ const subscriptionCatalog = (lists: { current: Record<string, readonly string[]>
4646
get: () =>
4747
Effect.sync(() => [
4848
{
49-
info: { id: Provider.ID.openai, name: "OpenAI", activation: "auto", package: "@opencode/ai/providers/openai" },
49+
info: {
50+
id: Provider.ID.openai,
51+
name: "OpenAI",
52+
activation: "auto",
53+
package: "@opencode/ai/providers/openai",
54+
},
5055
models: [],
5156
environment: [],
5257
subscriptions: lists.current,
@@ -528,12 +533,13 @@ describe("ChatGPTPlugin", () => {
528533
}),
529534
)
530535

531-
it.effect("reauthorizes with the client ID issued to an existing ChatGPT connection", () =>
536+
it.effect("registers a new client to add an account, and reuses an expired connection's client to reconnect it", () =>
532537
Effect.gen(function* () {
533538
const credentials = yield* Credential.Service
534539
const kv = yield* KV.Service
540+
const storage = PluginHost.storage(kv, ChatGPTPlugin.id)
535541
const hostID = "urn:uuid:00000000-0000-4000-8000-000000000000"
536-
yield* PluginHost.storage(kv, ChatGPTPlugin.id).set("chatgpt-agent-host-id", hostID)
542+
yield* storage.set("chatgpt-agent-host-id", hostID)
537543
yield* credentials.create({
538544
integrationID: Integration.ID.make("openai"),
539545
value: Credential.OAuth.make({
@@ -542,13 +548,22 @@ describe("ChatGPTPlugin", () => {
542548
access: "chatgpt-token",
543549
refresh: "refresh",
544550
expires: Date.now() + 60 * 60_000,
545-
metadata: { clientID: "oaiapp_issued" },
551+
metadata: { clientID: "oaiapp_issued", email: "[email protected]" },
546552
}),
547553
})
548554
yield* addPlugin()
555+
const adding = yield* authorize()
556+
expect(adding.searchParams.get("client_id")).toBe("dynamic_agent_client")
557+
expect(adding.searchParams.get("agent_name_hint")).toBe("OpenCode")
558+
expect(adding.searchParams.get("ext_agent_host_id")).toBe(hostID)
559+
expect(adding.searchParams.has("login_hint")).toBe(false)
560+
561+
yield* storage.set("chatgpt-expired-clients", ["oaiapp_issued"])
549562
const url = yield* authorize()
550563
expect(url.searchParams.get("client_id")).toBe("oaiapp_issued")
551564
expect(url.searchParams.has("agent_name_hint")).toBe(false)
565+
expect(url.searchParams.has("id_token_hint")).toBe(false)
566+
expect(url.searchParams.get("login_hint")).toBe("[email protected]")
552567
expect(url.searchParams.get("ext_agent_host_id")).toBe(hostID)
553568
expect(new URL(url.searchParams.get("redirect_uri") ?? "").hostname).toBe("127.0.0.1")
554569
}),
@@ -557,6 +572,8 @@ describe("ChatGPTPlugin", () => {
557572
it.live("rejects a reauthorization callback that returns a different client ID", () =>
558573
Effect.gen(function* () {
559574
const credentials = yield* Credential.Service
575+
const kv = yield* KV.Service
576+
yield* PluginHost.storage(kv, ChatGPTPlugin.id).set("chatgpt-expired-clients", ["oaiapp_issued"])
560577
yield* credentials.create({
561578
integrationID: Integration.ID.make("openai"),
562579
value: Credential.OAuth.make({
@@ -955,7 +972,10 @@ describe("ChatGPTPlugin", () => {
955972
}),
956973
})
957974
yield* addPlugin().pipe(
958-
Effect.provideService(ModelsDev.Service, subscriptionCatalog({ current: { "openai-chatgpt": ["gpt-6-sol", "gpt-7"] } })),
975+
Effect.provideService(
976+
ModelsDev.Service,
977+
subscriptionCatalog({ current: { "openai-chatgpt": ["gpt-6-sol", "gpt-7"] } }),
978+
),
959979
)
960980
expect(
961981
(yield* models.available())

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.