Merge pull request #490 from chriswritescode-dev/om-219-cold-catalog-model-readiness

Wait for plugins before using the OpenCode default model on cold locations
This commit is contained in:
Chris Scott authored and GitHub committed 2026-11-19 18:23:08 -05:00
commit 750faf1361
3 files changed
+198 -4

No files matched your search

+31 -3
View File
@@ -80,13 +80,18 @@ function sleep(ms: number, signal: AbortSignal): Promise<void> {
})
}
type PollingResult<T> = { ok: true; value: T } | { ok: false }
type PollingResult<T> = { ok: true; value: T } | { ok: false; retry?: true }
const abortLikeErrorSchema = z.object({
name: z.string().optional(),
cause: z.unknown().optional(),
})
const pluginsActivatingErrorSchema = z.object({
_tag: z.literal('ServiceUnavailableError'),
service: z.literal('plugin'),
})
function isAbortLike(cause: unknown, signal: AbortSignal): boolean {
if (cause === signal.reason) {
return true
@@ -119,10 +124,18 @@ async function runPollingRequest<T>(
return { ok: false }
}
if (pluginsActivatingErrorSchema.safeParse(error).success) {
return { ok: false, retry: true }
}
throw error
}
}
function isRetrying<T>(result: PollingResult<T> | undefined): boolean {
return result !== undefined && !result.ok && result.retry === true
}
async function readConfiguredRef(
client: OpenCodeClient,
location: ReturnType<typeof openCodeLocation>,
@@ -164,7 +177,7 @@ export async function resolveOpenCodeModel(
break
}
const [listResult, defaultResult] = await Promise.all([
const [listResult, defaultResult, pluginResult] = await Promise.all([
runPollingRequest(
() => client.api.model.list(location, { signal }),
external,
@@ -175,6 +188,13 @@ export async function resolveOpenCodeModel(
external,
timeoutController.signal,
),
targetRef === undefined
? runPollingRequest(
() => client.api.plugin.list(location, { signal }),
external,
timeoutController.signal,
)
: undefined,
])
if (listResult.ok) {
@@ -185,6 +205,11 @@ export async function resolveOpenCodeModel(
defaultModel = defaultResult.value.data
}
if (isRetrying(listResult) || isRetrying(defaultResult) || isRetrying(pluginResult)) {
await sleep(MODEL_LOAD_POLL_MS, signal)
continue
}
if (!listResult.ok || !defaultResult.ok) {
break
}
@@ -195,8 +220,11 @@ export async function resolveOpenCodeModel(
break
}
const pluginsLoaded = pluginResult === undefined
|| (pluginResult.ok && pluginResult.value.data.length > 0)
const resolved = resolveFromLoadedModels(models, defaultModel, configuredRef, preferredRef)
if (resolved && isTargetLoaded(models, targetRef)) {
if (resolved && isTargetLoaded(models, targetRef) && pluginsLoaded) {
return resolved
}
@@ -101,6 +101,12 @@ export function createStubOpenCodeApi(overrides: OpenCodeApiOverrides = {}): Ope
applyNamespace(api.skill, {
list: vi.fn(async () => ({ location: { directory: '/tmp/repo' }, data: [] })),
})
applyNamespace(api.plugin, {
list: vi.fn<OpenCodeApi['plugin']['list']>(async () => ({
location: { directory: '/tmp/repo' },
data: [pluginInfo()],
})),
})
applyNamespace(api.server, overrides.server)
applyNamespace(api.location, overrides.location)
@@ -109,6 +115,7 @@ export function createStubOpenCodeApi(overrides: OpenCodeApiOverrides = {}): Ope
applyNamespace(api.integration, overrides.integration)
applyNamespace(api.credential, overrides.credential)
applyNamespace(api.skill, overrides.skill)
applyNamespace(api.plugin, overrides.plugin)
applyNamespace(api.pty, overrides.pty)
applyNamespace(api.generate, overrides.generate)
applyNamespace(api.session, overrides.session)
@@ -131,6 +138,17 @@ export function createStubOpenCodeClient(options: StubOpenCodeClientOptions = {}
}
}
type PluginInfo = Awaited<ReturnType<OpenCodeApi['plugin']['list']>>['data'][number]
export function pluginInfo(overrides: Partial<PluginInfo> = {}): PluginInfo {
return {
source: { type: 'builtin' },
features: {},
state: { status: 'active' },
...overrides,
}
}
export function modelInfo(overrides: Partial<ModelInfo> = {}): ModelInfo {
return {
id: 'gpt-5-mini',
+149 -1
View File
@@ -6,7 +6,7 @@ import {
MODEL_LOAD_TIMEOUT_MS,
resolveOpenCodeModel,
} from '../../src/services/opencode-models'
import { createStubOpenCodeClient, modelInfo } from '../helpers/stub-opencode-client'
import { createStubOpenCodeClient, modelInfo, pluginInfo } from '../helpers/stub-opencode-client'
const DIR = '/workspace/repos/sample-project'
const LOCATION = { directory: DIR }
@@ -26,6 +26,7 @@ interface ClientStubInput {
listError?: Error
defaultError?: Error
configError?: Error
pluginList?: OpenCodeApi['plugin']['list']
}
function createdClient(input: ClientStubInput): OpenCodeClient {
@@ -47,6 +48,7 @@ function createdClient(input: ClientStubInput): OpenCodeClient {
return input.configEntries ?? []
}),
},
plugin: input.pluginList ? { list: input.pluginList } : undefined,
},
})
}
@@ -311,6 +313,152 @@ describe('resolveOpenCodeModel', () => {
await assertion
})
it('waits for the plugin catalog before choosing a default model', async () => {
let listCalls = 0
let pluginCalls = 0
const client = createStubOpenCodeClient({
api: {
model: {
list: vi.fn<OpenCodeApi['model']['list']>(async () => {
listCalls += 1
return {
location: LOCATION,
data: listCalls === 1
? [model('openai', 'gpt-5-mini')]
: [model('openai', 'gpt-5-mini'), model('anthropic', 'claude-sonnet-4')],
}
}),
default: vi.fn<OpenCodeApi['model']['default']>(async () => ({
location: LOCATION,
data: listCalls === 1
? model('openai', 'gpt-5-mini')
: model('anthropic', 'claude-sonnet-4'),
})),
},
plugin: {
list: vi.fn<OpenCodeApi['plugin']['list']>(async () => {
pluginCalls += 1
return {
location: LOCATION,
data: pluginCalls === 1 ? [] : [pluginInfo()],
}
}),
},
config: { get: vi.fn<OpenCodeApi['config']['get']>(async () => []) },
},
})
const promise = resolveOpenCodeModel(client, DIR)
const assertion = expect(promise).resolves.toEqual({
providerID: 'anthropic',
id: 'claude-sonnet-4',
model: 'anthropic/claude-sonnet-4',
})
await vi.advanceTimersByTimeAsync(MODEL_LOAD_POLL_MS)
await assertion
expect(pluginCalls).toBe(2)
})
it('keeps polling when a catalog read reports plugins still activating', async () => {
let listCalls = 0
const client = createStubOpenCodeClient({
api: {
model: {
list: vi.fn<OpenCodeApi['model']['list']>(async () => {
listCalls += 1
if (listCalls === 1) {
throw Object.assign(new Error('Location plugins did not finish activating'), {
_tag: 'ServiceUnavailableError',
service: 'plugin',
})
}
return { location: LOCATION, data: [model('openai', 'gpt-5')] }
}),
default: vi.fn<OpenCodeApi['model']['default']>(async () => ({
location: LOCATION,
data: model('openai', 'gpt-5'),
})),
},
config: { get: vi.fn<OpenCodeApi['config']['get']>(async () => []) },
},
})
const promise = resolveOpenCodeModel(client, DIR)
const assertion = expect(promise).resolves.toEqual({
providerID: 'openai',
id: 'gpt-5',
model: 'openai/gpt-5',
})
await vi.advanceTimersByTimeAsync(MODEL_LOAD_POLL_MS)
await assertion
expect(listCalls).toBe(2)
})
it('propagates a service unavailable error from a different service', async () => {
const otherService = Object.assign(new Error('session service unavailable'), {
_tag: 'ServiceUnavailableError',
service: 'session',
})
await expect(resolveOpenCodeModel(createdClient({ models: [], listError: otherService }), DIR))
.rejects.toThrow('session service unavailable')
const missingService = Object.assign(new Error('catalog unavailable'), {
_tag: 'ServiceUnavailableError',
})
await expect(resolveOpenCodeModel(createdClient({ models: [], listError: missingService }), DIR))
.rejects.toThrow('catalog unavailable')
})
it('does not read the plugin list when a target model is requested', async () => {
const preferredPluginList = vi.fn<OpenCodeApi['plugin']['list']>(
async () => ({ location: LOCATION, data: [] }),
)
const preferredClient = createdClient({
models: [model('openai', 'gpt-5')],
pluginList: preferredPluginList,
})
await expect(resolveOpenCodeModel(preferredClient, DIR, { preferredModel: 'openai/gpt-5' }))
.resolves.toEqual({ providerID: 'openai', id: 'gpt-5', model: 'openai/gpt-5' })
expect(preferredPluginList).not.toHaveBeenCalled()
const configuredPluginList = vi.fn<OpenCodeApi['plugin']['list']>(
async () => ({ location: LOCATION, data: [] }),
)
const configuredClient = createdClient({
models: [model('openai', 'gpt-5')],
configEntries: [configEntry('openai/gpt-5')],
pluginList: configuredPluginList,
})
await expect(resolveOpenCodeModel(configuredClient, DIR))
.resolves.toEqual({ providerID: 'openai', id: 'gpt-5', model: 'openai/gpt-5' })
expect(configuredPluginList).not.toHaveBeenCalled()
})
it('falls back to the loaded default when plugins never finish loading', async () => {
const client = createdClient({
models: [model('openai', 'gpt-5-mini')],
defaultModel: model('openai', 'gpt-5-mini'),
pluginList: vi.fn<OpenCodeApi['plugin']['list']>(async () => ({ location: LOCATION, data: [] })),
})
const promise = resolveOpenCodeModel(client, DIR)
let settled = false
void promise.then(() => { settled = true }, () => { settled = true })
await vi.advanceTimersByTimeAsync(MODEL_LOAD_POLL_MS)
expect(settled).toBe(false)
const assertion = expect(promise).resolves.toEqual({
providerID: 'openai',
id: 'gpt-5-mini',
model: 'openai/gpt-5-mini',
})
await vi.advanceTimersByTimeAsync(MODEL_LOAD_TIMEOUT_MS)
await assertion
})
it('falls back to the cached catalog when a later poll stalls until the deadline', async () => {
let listCalls = 0
const client = createStubOpenCodeClient({