fix(generate-text): resolve default model from global config catalog

This commit is contained in:
Chris Scott committed 2026-10-08 00:39:09 -04:00
1 parent a9331cb484
commit cbdaf164d9
7 files changed
+95 -14

No files matched your search

+18 -4
View File
@@ -1,5 +1,7 @@
import type { ModelRef } from '@opencode-manager/shared/opencode'
import { getOpenCodeGlobalConfigPath } from '@opencode-manager/shared/config/env'
import type { OpenCodeClient } from './client'
import { resolveOpenCodeModel } from '../opencode-models'
export class GenerateTextTimeoutError extends Error {
constructor() {
@@ -23,12 +25,24 @@ export async function generateTextWithTimeout(
})
try {
const { text } = await Promise.race([
client.api.generate.text(input, { signal: controller.signal }),
timeout,
])
const { text } = await Promise.race([generateText(client, input, controller.signal), timeout])
return text
} finally {
if (timer) clearTimeout(timer)
}
}
async function generateText(
client: OpenCodeClient,
input: { prompt: string; model?: ModelRef },
signal: AbortSignal,
): Promise<{ text: string }> {
const model = input.model ?? await resolveGenerateModel(client, signal)
return client.api.generate.text({ prompt: input.prompt, model }, { signal })
}
/** OpenCode serves generation from its global config location, so the model must be resolved there once its catalog has loaded. */
async function resolveGenerateModel(client: OpenCodeClient, signal: AbortSignal): Promise<ModelRef> {
const { providerID, id, variant } = await resolveOpenCodeModel(client, getOpenCodeGlobalConfigPath(), { signal })
return variant ? { providerID, id, variant } : { providerID, id }
}
@@ -2,6 +2,18 @@ import { vi } from 'vitest'
import type { OpenCodeApi } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from '../../src/services/opencode/client'
/** OpenCode API stubs for a catalog that has finished loading, so model resolution succeeds on the first poll. */
export function stubLoadedModelCatalog() {
const model = { providerID: 'openai', id: 'gpt-5-mini', enabled: true }
return {
config: { get: vi.fn(async () => []) },
model: {
list: vi.fn(async () => ({ data: [model] })),
default: vi.fn(async () => ({ data: model })),
},
}
}
export function createStubOpenCodeClient(overrides: Partial<OpenCodeClient> = {}): OpenCodeClient {
return {
api: {
@@ -7,6 +7,7 @@ import { allMigrations } from '../../src/db/migrations'
import { ChangeWalkthroughService } from '../../src/services/change-walkthroughs'
import { createChangeWalkthroughRoutes } from '../../src/routes/change-walkthroughs'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
const SESSION_ID = 'ses_walkthrough'
@@ -32,6 +33,7 @@ function createFakeClient(sessions: Record<string, FakeSession>) {
const client = {
api: {
...stubLoadedModelCatalog(),
session: {
get: vi.fn(async ({ sessionID }: { sessionID: string }) => {
const config = sessions[sessionID]
+3 -1
View File
@@ -4,6 +4,7 @@ import type { Database } from 'bun:sqlite'
import type { GitAuthService } from '../../src/services/git-auth'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { createRepoGitRoutes } from '../../src/routes/repo-git'
import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
import { createGitService, GitService } from '../../src/services/git/GitService'
import * as db from '../../src/db/queries'
@@ -33,6 +34,7 @@ vi.mock('../../src/utils/process', () => ({
vi.mock('@opencode-manager/shared/config/env', () => ({
getReposPath: vi.fn(() => '/repos'),
getWorkspacePath: vi.fn(() => '/tmp/test-workspace'),
getOpenCodeGlobalConfigPath: vi.fn(() => '/tmp/test-workspace/.config/opencode'),
ENV: {
OPENCODE: { PORT: 5551, HOST: '127.0.0.1' },
SERVER: { PORT: 5001, HOST: '0.0.0.0', CORS_ORIGIN: '*', NODE_ENV: 'test' },
@@ -89,7 +91,7 @@ describe('Repo Git Routes', () => {
} as unknown as GitAuthService
generateTextMock = vi.fn()
mockOpenCodeClient = {
api: { generate: { text: generateTextMock } },
api: { ...stubLoadedModelCatalog(), generate: { text: generateTextMock } },
} as unknown as OpenCodeClient
app = createRepoGitRoutes(
mockDatabase,
@@ -13,6 +13,7 @@ import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import type { SSEEvent } from '../../src/services/sse-aggregator'
import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
import {
ChangeWalkthroughError,
ChangeWalkthroughService,
@@ -58,6 +59,7 @@ function createFakeClient(sessions: Record<string, FakeSession>) {
const client = {
api: {
...stubLoadedModelCatalog(),
session: {
get: vi.fn(async ({ sessionID }: { sessionID: string }) => {
const config = sessions[sessionID]
@@ -1,20 +1,40 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import type { ModelRef } from '@opencode-manager/shared/opencode'
import { getOpenCodeGlobalConfigPath } from '@opencode-manager/shared/config/env'
import type { ModelInfo, ModelRef } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from '../../../src/services/opencode/client'
import { GenerateTextTimeoutError, generateTextWithTimeout } from '../../../src/services/opencode/generate-text'
import { MODEL_LOAD_POLL_MS } from '../../../src/services/opencode-models'
interface GenerateCall {
input: { prompt: string; model?: ModelRef }
signal: AbortSignal | undefined
}
function makeClient(impl: (call: GenerateCall) => Promise<{ text: string }>): {
const CATALOG_MODEL = { providerID: 'openai', id: 'gpt-5-mini', enabled: true } as ModelInfo
function makeClient(
impl: (call: GenerateCall) => Promise<{ text: string }>,
catalogs: ModelInfo[][] = [[CATALOG_MODEL]],
): {
client: OpenCodeClient
calls: GenerateCall[]
modelList: ReturnType<typeof vi.fn>
} {
const calls: GenerateCall[] = []
let listCall = 0
const catalogAt = () => catalogs[Math.min(listCall, catalogs.length - 1)] ?? []
const modelList = vi.fn(async () => {
const data = catalogAt()
listCall += 1
return { data }
})
const client = {
api: {
config: { get: vi.fn(async () => []) },
model: {
list: modelList,
default: vi.fn(async () => ({ data: catalogs[Math.min(listCall - 1, catalogs.length - 1)]?.[0] ?? null })),
},
generate: {
text: async (input: GenerateCall['input'], options?: { signal?: AbortSignal }) => {
const call: GenerateCall = { input, signal: options?.signal }
@@ -25,7 +45,7 @@ function makeClient(impl: (call: GenerateCall) => Promise<{ text: string }>): {
},
} as unknown as OpenCodeClient
return { client, calls }
return { client, calls, modelList }
}
describe('generateTextWithTimeout', () => {
@@ -33,23 +53,38 @@ describe('generateTextWithTimeout', () => {
vi.useRealTimers()
})
it('returns the generated text and passes the prompt with an abort signal', async () => {
const { client, calls } = makeClient(async () => ({ text: 'hello' }))
it('resolves a model from the global config catalog when none is provided', async () => {
const { client, calls, modelList } = makeClient(async () => ({ text: 'hello' }))
await expect(generateTextWithTimeout(client, { prompt: 'write' }, 1000)).resolves.toBe('hello')
expect(modelList).toHaveBeenCalledWith({ location: { directory: getOpenCodeGlobalConfigPath() } }, expect.anything())
expect(calls).toHaveLength(1)
expect(calls[0]?.input).toEqual({ prompt: 'write' })
expect(calls[0]?.input).toEqual({ prompt: 'write', model: { providerID: 'openai', id: 'gpt-5-mini' } })
expect(calls[0]?.signal).toBeInstanceOf(AbortSignal)
})
it('forwards the model when provided', async () => {
const { client, calls } = makeClient(async () => ({ text: 'hello' }))
it('waits for the model catalog to load before generating', async () => {
vi.useFakeTimers()
const { client, calls } = makeClient(async () => ({ text: 'hello' }), [[], [CATALOG_MODEL]])
const promise = generateTextWithTimeout(client, { prompt: 'write' }, 10_000)
await vi.advanceTimersByTimeAsync(0)
expect(calls).toHaveLength(0)
await vi.advanceTimersByTimeAsync(MODEL_LOAD_POLL_MS)
await expect(promise).resolves.toBe('hello')
expect(calls[0]?.input.model).toEqual({ providerID: 'openai', id: 'gpt-5-mini' })
})
it('forwards the model when provided without reading the catalog', async () => {
const { client, calls, modelList } = makeClient(async () => ({ text: 'hello' }))
const model: ModelRef = { providerID: 'anthropic', id: 'claude-sonnet-4' }
await generateTextWithTimeout(client, { prompt: 'write', model }, 1000)
expect(calls[0]?.input).toEqual({ prompt: 'write', model })
expect(modelList).not.toHaveBeenCalled()
})
it('rejects with GenerateTextTimeoutError and aborts the request after the timeout', async () => {
@@ -65,6 +100,19 @@ describe('generateTextWithTimeout', () => {
expect(calls[0]?.signal?.aborted).toBe(true)
})
it('times out while the model catalog is still loading', async () => {
vi.useFakeTimers()
const { client, calls } = makeClient(async () => ({ text: 'never' }), [[]])
const promise = generateTextWithTimeout(client, { prompt: 'write' }, 50)
const assertion = expect(promise).rejects.toBeInstanceOf(GenerateTextTimeoutError)
await vi.advanceTimersByTimeAsync(50)
await assertion
expect(calls).toHaveLength(0)
})
it('propagates a client error without waiting for the timeout', async () => {
const { client } = makeClient(async () => {
throw new Error('model unavailable')
+2 -1
View File
@@ -153,7 +153,8 @@ export const getAssistantOpenCodeDir = () => path.join(getAssistantModePath(), A
export const getOpenCodeConfigHome = () => path.join(ENV.WORKSPACE.BASE_PATH, '.config')
export const getOpenCodeStateHome = () => path.join(ENV.WORKSPACE.BASE_PATH, '.opencode', 'state')
export const getOpenCodeHealthWatchPath = () => path.join(getOpenCodeStateHome(), 'health-watch')
export const getOpenCodeGlobalSkillsPath = () => path.join(getOpenCodeConfigHome(), 'opencode', 'skills')
export const getOpenCodeGlobalConfigPath = () => path.join(getOpenCodeConfigHome(), 'opencode')
export const getOpenCodeGlobalSkillsPath = () => path.join(getOpenCodeGlobalConfigPath(), 'skills')
export const getOpenCodeDataPath = () => path.join(getOpenCodeStateHome(), 'opencode')
export const getOpenCodeModelStatePath = () => path.join(getOpenCodeDataPath(), 'model.json')
export const getOpenCodeToolOutputPath = () => path.join(getOpenCodeDataPath(), 'tool-output')