Wait for OpenCode plugin activation before integration calls

This commit is contained in:
Chris Scott committed 2026-11-13 17:38:01 -05:00
1 parent eba86dc3fc
commit 226e13b3d1
9 files changed
+60 -216

No files matched your search

+13 -13
View File
@@ -142,6 +142,19 @@ describe('oauth routes /auth-methods', () => {
expect(res.status).toBe(502)
expect(await res.json()).toEqual({ error: 'Failed to get provider auth methods', code: 'ClientError' })
})
it('waits for plugin activation before listing the auth methods', async () => {
const client = createStubOpenCodeClient()
const providerList = vi.mocked(client.api.provider.list)
const integrationList = vi.mocked(client.api.integration.list)
integrationList.mockResolvedValueOnce({ location: LOCATION, data: [integrationFixture()] })
const res = await createOAuthApp(client).request('/oauth/auth-methods')
expect(res.status).toBe(200)
expect(integrationList).toHaveBeenCalledTimes(1)
expect(providerList).toHaveBeenCalledBefore(integrationList)
})
})
describe('oauth routes /:id/oauth/authorize', () => {
@@ -192,19 +205,6 @@ describe('oauth routes /:id/oauth/authorize', () => {
})
})
it('retries once after a loading integration becomes available', async () => {
const client = createStubOpenCodeClient()
const connect = vi.mocked(client.api.integration.oauth.connect)
connect.mockRejectedValueOnce(taggedError('IntegrationNotFoundError', 'Integration not found: github-copilot'))
const res = await authorizeRequest(createOAuthApp(client))
expect(res.status).toBe(200)
expect((await readJson(res, OAuthAuthorizeResponseSchema)).attemptID).toBe('con_stub')
expect(connect).toHaveBeenCalledTimes(2)
expect(vi.mocked(client.api.integration.get)).toHaveBeenCalledWith({ integrationID: 'github-copilot' })
})
it('returns 404 when the integration is gone', async () => {
vi.useFakeTimers()
try {
+8 -8
View File
@@ -5,7 +5,7 @@ import {
OAuthCallbackRequestSchema,
} from '../../../shared/src/schemas/auth'
import type { OpenCodeClient } from '../services/opencode/client'
import { runWhenIntegrationReady } from '../services/opencode/integration-ready'
import { awaitOpenCodePlugins } from '@opencode-manager/shared/opencode'
import { handleOpenCodeError } from '../utils/route-helpers'
export function createOAuthRoutes(openCodeClient: OpenCodeClient) {
@@ -13,6 +13,7 @@ export function createOAuthRoutes(openCodeClient: OpenCodeClient) {
app.get('/auth-methods', async (c) => {
try {
await awaitOpenCodePlugins(openCodeClient.api)
const integrations = await openCodeClient.api.integration.list()
const providers = Object.fromEntries(
integrations.data.map((integration) => [integration.id, integration.methods]),
@@ -29,13 +30,12 @@ export function createOAuthRoutes(openCodeClient: OpenCodeClient) {
const validated = OAuthAuthorizeRequestSchema.parse(body)
const integrationID = c.req.param('id')
const attempt = await runWhenIntegrationReady(openCodeClient.api, { integrationID }, () =>
openCodeClient.api.integration.oauth.connect({
integrationID,
methodID: validated.methodID,
answer: validated.answer,
}),
)
await awaitOpenCodePlugins(openCodeClient.api)
const attempt = await openCodeClient.api.integration.oauth.connect({
integrationID,
methodID: validated.methodID,
answer: validated.answer,
})
return c.json({
attemptID: attempt.data.attemptID,
+17 -40
View File
@@ -277,22 +277,6 @@ describe('providers routes', () => {
expect(await readJson(res, CredentialStatusResponseSchema)).toEqual({ hasCredentials: false })
})
it('retries once after a loading integration becomes available', async () => {
const client = createStubOpenCodeClient()
const get = vi.mocked(client.api.integration.get)
get.mockRejectedValueOnce(taggedError('IntegrationNotFoundError', 'Integration not found: anthropic'))
get.mockResolvedValue({
location: LOCATION,
data: integrationFixture({ connections: [credentialConnection('cred_1')] }),
})
const res = await createCredentialApp(client).request('/providers/anthropic/credentials/status')
expect(res.status).toBe(200)
expect(await readJson(res, CredentialStatusResponseSchema)).toEqual({ hasCredentials: true })
expect(get).toHaveBeenCalledTimes(3)
})
it('returns 404 for a missing integration', async () => {
vi.useFakeTimers()
try {
@@ -363,17 +347,29 @@ describe('providers routes', () => {
expect(vi.mocked(client.api.integration.connect.key)).not.toHaveBeenCalled()
})
it('retries once after a loading integration becomes available', async () => {
it('waits for plugin activation before connecting the key', async () => {
const client = createStubOpenCodeClient()
const providerList = vi.mocked(client.api.provider.list)
const connectKey = vi.mocked(client.api.integration.connect.key)
connectKey.mockRejectedValueOnce(taggedError('IntegrationNotFoundError', 'Integration not found: anthropic'))
const res = await connectRequest(createCredentialApp(client))
expect(res.status).toBe(200)
expect(await readJson(res, SuccessResponseSchema)).toEqual({ success: true })
expect(connectKey).toHaveBeenCalledTimes(2)
expect(vi.mocked(client.api.integration.get)).toHaveBeenCalledWith({ integrationID: 'anthropic' })
expect(connectKey).toHaveBeenCalledTimes(1)
expect(providerList).toHaveBeenCalledBefore(connectKey)
})
it('returns the plugin-activation failure without connecting the key', async () => {
const client = createStubOpenCodeClient()
vi.mocked(client.api.provider.list).mockRejectedValueOnce(
taggedError('ServiceUnavailableError', 'Plugins are still loading'),
)
const res = await connectRequest(createCredentialApp(client))
expect(res.status).toBe(502)
expect(await readJson(res, ErrorResponseSchema)).toEqual({ error: 'Plugins are still loading' })
expect(vi.mocked(client.api.integration.connect.key)).not.toHaveBeenCalled()
})
it('returns 404 for a missing integration', async () => {
@@ -448,23 +444,6 @@ describe('providers routes', () => {
expect(vi.mocked(client.api.credential.remove)).not.toHaveBeenCalled()
})
it('retries once after a loading integration becomes available', async () => {
const client = createStubOpenCodeClient()
const get = vi.mocked(client.api.integration.get)
get.mockRejectedValueOnce(taggedError('IntegrationNotFoundError', 'Integration not found: anthropic'))
get.mockResolvedValue({
location: LOCATION,
data: integrationFixture({ connections: [credentialConnection('cred_1')] }),
})
const res = await createCredentialApp(client).request('/providers/anthropic/credentials', { method: 'DELETE' })
expect(res.status).toBe(200)
expect(await readJson(res, SuccessResponseSchema)).toEqual({ success: true })
expect(vi.mocked(client.api.credential.remove)).toHaveBeenCalledWith({ credentialID: 'cred_1' })
expect(get).toHaveBeenCalledTimes(3)
})
it('returns 404 for a missing integration', async () => {
vi.useFakeTimers()
try {
@@ -534,8 +513,6 @@ describe.skipIf(!openCodeBinary)('providers routes against a real OpenCode 2 ser
const app = new Hono()
app.route('/providers', createProvidersRoutes(client))
await client.api.integration.list()
const rejected = await app.request('/providers/azure/credentials', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
+8 -10
View File
@@ -5,13 +5,13 @@ import { logger } from '../utils/logger'
import { handleOpenCodeError } from '../utils/route-helpers'
import {
addRecentModel,
awaitOpenCodePlugins,
removeRecentModel,
setModelVariant,
toggleFavoriteModel,
type IntegrationInfo,
} from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from '../services/opencode/client'
import { runWhenIntegrationReady } from '../services/opencode/integration-ready'
type IntegrationConnectKeyInput = NonNullable<Parameters<OpenCodeClient['api']['integration']['connect']['key']>[0]>
import {
@@ -80,6 +80,7 @@ export function createProvidersRoutes(openCodeClient: OpenCodeClient) {
app.get('/credentials', async (c) => {
try {
await awaitOpenCodePlugins(openCodeClient.api)
const integrations = await openCodeClient.api.integration.list()
const providers = integrations.data
.filter((integration) => credentialConnections(integration).length > 0)
@@ -93,9 +94,8 @@ export function createProvidersRoutes(openCodeClient: OpenCodeClient) {
app.get('/:id/credentials/status', async (c) => {
try {
const integrationID = c.req.param('id')
const integration = await runWhenIntegrationReady(openCodeClient.api, { integrationID }, () =>
openCodeClient.api.integration.get({ integrationID }),
)
await awaitOpenCodePlugins(openCodeClient.api)
const integration = await openCodeClient.api.integration.get({ integrationID })
return c.json({ hasCredentials: credentialConnections(integration.data).length > 0 })
} catch (error) {
return handleOpenCodeError(c, error, 'Failed to check credential status')
@@ -113,9 +113,8 @@ export function createProvidersRoutes(openCodeClient: OpenCodeClient) {
key: validated.apiKey,
answer: validated.answer,
}
await runWhenIntegrationReady(openCodeClient.api, { integrationID }, () =>
openCodeClient.api.integration.connect.key(connectInput),
)
await awaitOpenCodePlugins(openCodeClient.api)
await openCodeClient.api.integration.connect.key(connectInput)
return c.json({ success: true })
} catch (error) {
@@ -129,9 +128,8 @@ export function createProvidersRoutes(openCodeClient: OpenCodeClient) {
app.delete('/:id/credentials', async (c) => {
try {
const integrationID = c.req.param('id')
const integration = await runWhenIntegrationReady(openCodeClient.api, { integrationID }, () =>
openCodeClient.api.integration.get({ integrationID }),
)
await awaitOpenCodePlugins(openCodeClient.api)
const integration = await openCodeClient.api.integration.get({ integrationID })
for (const connection of credentialConnections(integration.data)) {
await openCodeClient.api.credential.remove({ credentialID: connection.id })
@@ -1,45 +0,0 @@
import { isIntegrationNotFoundError, type OpenCodeApi } from '@opencode-manager/shared/opencode'
export const INTEGRATION_READY_POLL_INTERVAL_MS = 100
export const INTEGRATION_READY_TIMEOUT_MS = 2000
export type IntegrationTarget = Parameters<OpenCodeApi['integration']['get']>[0]
type IntegrationReader = Pick<OpenCodeApi, 'integration'>
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function isIntegrationAvailable(api: IntegrationReader, target: IntegrationTarget): Promise<boolean | undefined> {
try {
await api.integration.get(target)
return true
} catch (error) {
return isIntegrationNotFoundError(error) ? false : undefined
}
}
async function waitForIntegration(api: IntegrationReader, target: IntegrationTarget): Promise<boolean> {
const deadline = Date.now() + INTEGRATION_READY_TIMEOUT_MS
while (Date.now() < deadline) {
await delay(INTEGRATION_READY_POLL_INTERVAL_MS)
const available = await isIntegrationAvailable(api, target)
if (available !== false) return available === true
}
return false
}
export async function runWhenIntegrationReady<T>(
api: IntegrationReader,
target: IntegrationTarget,
action: () => Promise<T>,
): Promise<T> {
try {
return await action()
} catch (error) {
if (!isIntegrationNotFoundError(error)) throw error
if (!(await waitForIntegration(api, target))) throw error
return await action()
}
}
@@ -66,6 +66,9 @@ export function createStubOpenCodeApi(overrides: OpenCodeApiOverrides = {}): Ope
connect: vi.fn(async () => undefined),
disconnect: vi.fn(async () => undefined),
})
applyNamespace(api.provider, {
list: vi.fn(async () => ({ location: { directory: '/tmp/repo' }, data: [] })),
})
applyNamespace(api.integration, {
list: vi.fn(async () => ({ location: { directory: '/tmp/repo' }, data: [] })),
get: vi.fn(async () => ({
@@ -106,6 +109,7 @@ export function createStubOpenCodeApi(overrides: OpenCodeApiOverrides = {}): Ope
applyNamespace(api.location, overrides.location)
applyNamespace(api.worktree, overrides.worktree)
applyNamespace(api.mcp, overrides.mcp)
applyNamespace(api.provider, overrides.provider)
applyNamespace(api.integration, overrides.integration)
applyNamespace(api.credential, overrides.credential)
applyNamespace(api.skill, overrides.skill)
@@ -1,98 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
INTEGRATION_READY_POLL_INTERVAL_MS,
INTEGRATION_READY_TIMEOUT_MS,
runWhenIntegrationReady,
} from '../../../src/services/opencode/integration-ready'
import { createStubOpenCodeClient } from '../../helpers/stub-opencode-client'
const TARGET = { integrationID: 'anthropic', location: { directory: '/tmp/repo' } }
function taggedError(tag: string, message: string): Error {
return Object.assign(new Error(message), { _tag: tag })
}
function notFound(): Error {
return taggedError('IntegrationNotFoundError', 'Integration not found: anthropic')
}
describe('runWhenIntegrationReady', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('returns the first result without polling', async () => {
const { api } = createStubOpenCodeClient()
const action = vi.fn(async () => 'connected')
await expect(runWhenIntegrationReady(api, TARGET, action)).resolves.toBe('connected')
expect(action).toHaveBeenCalledTimes(1)
expect(vi.mocked(api.integration.get)).not.toHaveBeenCalled()
})
it('waits for a loading integration and retries once', async () => {
const { api } = createStubOpenCodeClient()
const get = vi.mocked(api.integration.get)
get.mockRejectedValueOnce(notFound()).mockRejectedValueOnce(notFound())
const action = vi.fn<() => Promise<string>>()
.mockRejectedValueOnce(notFound())
.mockResolvedValueOnce('connected')
const result = runWhenIntegrationReady(api, TARGET, action)
await vi.advanceTimersByTimeAsync(INTEGRATION_READY_POLL_INTERVAL_MS * 3)
await expect(result).resolves.toBe('connected')
expect(get).toHaveBeenCalledTimes(3)
expect(get).toHaveBeenCalledWith(TARGET)
expect(action).toHaveBeenCalledTimes(2)
})
it('returns the original error when the integration never appears', async () => {
const { api } = createStubOpenCodeClient()
const get = vi.mocked(api.integration.get)
get.mockRejectedValue(notFound())
const original = notFound()
const action = vi.fn<() => Promise<string>>().mockRejectedValue(original)
const result = runWhenIntegrationReady(api, TARGET, action)
const assertion = expect(result).rejects.toBe(original)
await vi.advanceTimersByTimeAsync(INTEGRATION_READY_TIMEOUT_MS + INTEGRATION_READY_POLL_INTERVAL_MS)
await assertion
expect(action).toHaveBeenCalledTimes(1)
expect(get.mock.calls.length).toBeGreaterThanOrEqual(INTEGRATION_READY_TIMEOUT_MS / INTEGRATION_READY_POLL_INTERVAL_MS - 1)
expect(get.mock.calls.length).toBeLessThanOrEqual(INTEGRATION_READY_TIMEOUT_MS / INTEGRATION_READY_POLL_INTERVAL_MS)
})
it('stops polling and returns the original error when the lookup fails differently', async () => {
const { api } = createStubOpenCodeClient()
const get = vi.mocked(api.integration.get)
get.mockRejectedValue(taggedError('ServiceUnavailableError', 'down'))
const original = notFound()
const action = vi.fn<() => Promise<string>>().mockRejectedValue(original)
const result = runWhenIntegrationReady(api, TARGET, action)
const assertion = expect(result).rejects.toBe(original)
await vi.advanceTimersByTimeAsync(INTEGRATION_READY_POLL_INTERVAL_MS)
await assertion
expect(get).toHaveBeenCalledTimes(1)
expect(action).toHaveBeenCalledTimes(1)
})
it('does not retry other errors', async () => {
const { api } = createStubOpenCodeClient()
const original = taggedError('InvalidRequestError', 'Missing required form field: account')
const action = vi.fn<() => Promise<string>>().mockRejectedValue(original)
await expect(runWhenIntegrationReady(api, TARGET, action)).rejects.toBe(original)
expect(action).toHaveBeenCalledTimes(1)
expect(vi.mocked(api.integration.get)).not.toHaveBeenCalled()
})
})
+5 -1
View File
@@ -1,6 +1,7 @@
import { API_BASE_URL } from "@/config"
import { z } from "zod"
import type { FormAnswer, IntegrationInfo, IntegrationMethod } from "@opencode-manager/shared/opencode"
import { awaitOpenCodePlugins } from "@opencode-manager/shared/opencode"
import { OAuthAttemptStatusSchema, OAuthAuthorizeResponseSchema } from "@opencode-manager/shared/schemas"
import type { OAuthAttemptStatus, OAuthAuthorizeResponse } from "@opencode-manager/shared/schemas"
import { fetchWrapper, fetchWrapperVoid } from "./fetchWrapper"
@@ -147,7 +148,10 @@ export const oauthApi = {
},
getIntegrations: async (): Promise<IntegrationInfo[]> => {
const { data } = await callOpenCode((api) => api.integration.list())
const { data } = await callOpenCode(async (api) => {
await awaitOpenCodePlugins(api)
return api.integration.list()
})
return data
},
}
+5 -1
View File
@@ -49,7 +49,7 @@ export type {
V2Event,
} from '@opencode/client'
export { ClientError, isIntegrationNotFoundError, isMcpServerNotFoundError, isSessionNotFoundError, isWorktreeError } from '@opencode/client'
export { ClientError, isMcpServerNotFoundError, isSessionNotFoundError, isWorktreeError } from '@opencode/client'
export { assistantText, sessionIDFromEvent, toolContentText } from './content'
@@ -236,6 +236,10 @@ export function openCodeLocation(directory: string | undefined): OpenCodeLocatio
return directory ? { location: { directory } } : undefined
}
export async function awaitOpenCodePlugins(api: Pick<OpenCodeApi, 'provider'>): Promise<void> {
await api.provider.list()
}
interface OpenCodeErrorStatusByTag {
[tag: string]: number
}