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 · anomalyco/opencode@80bc0bd

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
+44-7Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ const newAccountMethodID = Integration.MethodID.make("chatgpt-token-sharing-new"
3636
// the client instead of registering another app in the user's ChatGPT settings.
3737
const profilesKey = "chatgpt-profiles"
3838
const lastClientKey = "chatgpt-last-client"
39+
// Clients whose refresh token OpenAI rejected. Signing in again while only these are saved reconnects one of them.
40+
const expiredKey = "chatgpt-expired-clients"
3941
const modelCacheKey = (clientID: string) => `models:${clientID}`
4042
// Used when the catalog has no Sign in with ChatGPT list. gpt-5.5 is rejected there.
4143
const fallbackModels = new Set([
@@ -101,6 +103,11 @@ const decodeInvalidGrant = Schema.decodeUnknownOption(
101103
)
102104
const Profile = Schema.Struct({ subject: Schema.String, email: Schema.optional(Schema.String), idToken: Schema.String })
103105
const decodeProfiles = Schema.decodeUnknownOption(Schema.Record(Schema.String, Profile))
106+
const decodeExpired = Schema.decodeUnknownOption(Schema.Array(Schema.String))
107+
const expiredClients = (storage: Context["storage"]) =>
108+
storage
109+
.get(expiredKey)
110+
.pipe(Effect.map((value) => Option.getOrElse(decodeExpired(value), (): readonly string[] => [])))
104111
const decodeMetadata = Schema.decodeUnknownOption(
105112
Schema.Struct({
106113
clientID: Schema.String,
@@ -111,7 +118,7 @@ const decodeMetadata = Schema.decodeUnknownOption(
111118

112119
const signIn = (
113120
app: App.Info,
114-
savedClientID: () => string | undefined,
121+
savedClients: () => Effect.Effect<ReadonlyArray<string>>,
115122
storage: Context["storage"],
116123
newAccount = false,
117124
) =>
@@ -132,7 +139,10 @@ const signIn = (
132139
const nonce = randomValue()
133140
const profiles = Option.getOrUndefined(decodeProfiles(yield* storage.get(profilesKey)))
134141
const last = yield* storage.get(lastClientKey)
135-
const savedID = newAccount ? undefined : (savedClientID() ?? (typeof last === "string" ? last : undefined))
142+
const expired = yield* expiredClients(storage)
143+
// A working saved account means this sign-in adds another one, which needs its own client.
144+
const adding = (yield* savedClients()).some((id) => !expired.includes(id))
145+
const savedID = newAccount || adding || typeof last !== "string" ? undefined : last
136146
const profile = savedID ? profiles?.[savedID] : undefined
137147
// `response` is the browser's pending callback request; a pasted redirect has none.
138148
const received = yield* Deferred.make<{ code: string; clientID?: string; response?: ServerResponse }, Error>()
@@ -218,6 +228,12 @@ const signIn = (
218228
const saved = Option.getOrUndefined(decodeProfiles(yield* storage.get(profilesKey)))
219229
yield* storage.set(profilesKey, { ...saved, [clientID]: { ...identity, idToken: tokens.id_token } })
220230
yield* storage.set(lastClientKey, clientID)
231+
const stale = yield* expiredClients(storage)
232+
if (stale.includes(clientID))
233+
yield* storage.set(
234+
expiredKey,
235+
stale.filter((id) => id !== clientID),
236+
)
221237
return credential(tokens, clientID)
222238
}).pipe(
223239
Effect.tap(() => respond()),
@@ -232,7 +248,17 @@ const signIn = (
232248
}),
233249
}
234250
}),
235-
refresh: (value) => refresh(value, app),
251+
refresh: (value) =>
252+
refresh(value, app).pipe(
253+
Effect.tapError((error) =>
254+
Effect.gen(function* () {
255+
const clientID = Option.getOrUndefined(decodeMetadata(value.metadata))?.clientID
256+
if (!(error instanceof SignInExpired) || !clientID) return
257+
const expired = yield* expiredClients(storage)
258+
if (!expired.includes(clientID)) yield* storage.set(expiredKey, [...expired, clientID])
259+
}),
260+
),
261+
),
236262
revoke: (value) => revoke(value, app),
237263
}) satisfies IntegrationOAuthMethodRegistration
238264

@@ -281,10 +307,19 @@ export const ChatGPTPlugin = define({
281307
return !Equal.equals(previous, source)
282308
})
283309

284-
const activeClientID = () => Option.getOrUndefined(decodeMetadata(chatgpt?.metadata))?.clientID
310+
const savedClients = () =>
311+
credentials.list(integrationID).pipe(
312+
Effect.map((entries) =>
313+
entries.flatMap((entry) => {
314+
if (entry.value.type !== "oauth" || entry.value.methodID !== methodID) return []
315+
const clientID = Option.getOrUndefined(decodeMetadata(entry.value.metadata))?.clientID
316+
return clientID ? [clientID] : []
317+
}),
318+
),
319+
)
285320
yield* ctx.integration.transform((editor) => {
286-
editor.method.update(signIn(ctx.app, activeClientID, ctx.storage))
287-
if (known) editor.method.update(signIn(ctx.app, activeClientID, ctx.storage, true))
321+
editor.method.update(signIn(ctx.app, savedClients, ctx.storage))
322+
if (known) editor.method.update(signIn(ctx.app, savedClients, ctx.storage, true))
288323
})
289324
yield* Effect.forEach(
290325
yield* credentials.list(Integration.ID.make("openai")),
@@ -562,13 +597,15 @@ export function verifyIDToken(
562597
})
563598
}
564599

600+
class SignInExpired extends Error {}
601+
565602
// `rejected` replaces the error when OpenAI answers invalid_grant, which means different things per grant type.
566603
function request<A>(url: string, init: RequestInit, rejected?: string) {
567604
return Effect.tryPromise({
568605
try: async (signal) => {
569606
const response = await fetch(url, { ...init, signal })
570607
if (response.ok) return response.json() as Promise<A>
571-
if (rejected && Option.isSome(decodeInvalidGrant(await response.text()))) throw new Error(rejected)
608+
if (rejected && Option.isSome(decodeInvalidGrant(await response.text()))) throw new SignInExpired(rejected)
572609
throw new Error(`Request failed: ${response.status}`)
573610
},
574611
catch: (cause) => cause,
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
+20-4Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,12 @@ const subscriptionCatalog = (lists: { current: Record<string, readonly string[]>
5353
get: () =>
5454
Effect.sync(() => [
5555
{
56-
info: { id: Provider.ID.openai, name: "OpenAI", activation: "auto", package: "@opencode/ai/providers/openai" },
56+
info: {
57+
id: Provider.ID.openai,
58+
name: "OpenAI",
59+
activation: "auto",
60+
package: "@opencode/ai/providers/openai",
61+
},
5762
models: [],
5863
environment: [],
5964
subscriptions: lists.current,
@@ -541,12 +546,13 @@ describe("ChatGPTPlugin", () => {
541546
}),
542547
)
543548

544-
it.effect("reauthorizes with the client ID issued to an existing ChatGPT connection", () =>
549+
it.effect("registers a new client to add an account, and reuses an expired account's client to reconnect it", () =>
545550
Effect.gen(function* () {
546551
const credentials = yield* Credential.Service
547552
const kv = yield* KV.Service
553+
const storage = PluginHost.storage(kv, ChatGPTPlugin.id)
548554
const hostID = "urn:uuid:00000000-0000-4000-8000-000000000000"
549-
yield* PluginHost.storage(kv, ChatGPTPlugin.id).set("chatgpt-agent-host-id", hostID)
555+
yield* storage.set("chatgpt-agent-host-id", hostID)
550556
yield* credentials.create({
551557
integrationID: Integration.ID.make("openai"),
552558
value: Credential.OAuth.make({
@@ -559,6 +565,11 @@ describe("ChatGPTPlugin", () => {
559565
}),
560566
})
561567
yield* addPlugin()
568+
const adding = yield* authorize()
569+
expect(adding.searchParams.get("client_id")).toBe("dynamic_agent_client")
570+
expect(adding.searchParams.get("agent_name_hint")).toBe("OpenCode")
571+
572+
yield* storage.set("chatgpt-expired-clients", ["oaiapp_issued"])
562573
const url = yield* authorize()
563574
expect(url.searchParams.get("client_id")).toBe("oaiapp_issued")
564575
expect(url.searchParams.has("agent_name_hint")).toBe(false)
@@ -633,6 +644,8 @@ describe("ChatGPTPlugin", () => {
633644
it.live("rejects a reauthorization callback that returns a different client ID", () =>
634645
Effect.gen(function* () {
635646
const credentials = yield* Credential.Service
647+
const kv = yield* KV.Service
648+
yield* PluginHost.storage(kv, ChatGPTPlugin.id).set("chatgpt-expired-clients", ["oaiapp_issued"])
636649
yield* credentials.create({
637650
integrationID: Integration.ID.make("openai"),
638651
value: Credential.OAuth.make({
@@ -1031,7 +1044,10 @@ describe("ChatGPTPlugin", () => {
10311044
}),
10321045
})
10331046
yield* addPlugin().pipe(
1034-
Effect.provideService(ModelsDev.Service, subscriptionCatalog({ current: { "openai-chatgpt": ["gpt-6-sol", "gpt-7"] } })),
1047+
Effect.provideService(
1048+
ModelsDev.Service,
1049+
subscriptionCatalog({ current: { "openai-chatgpt": ["gpt-6-sol", "gpt-7"] } }),
1050+
),
10351051
)
10361052
expect(
10371053
(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.