refactor: unify model selection with the TUI

Align the manager's model selection with the OpenCode TUI: one
model.json-backed preference store, one provider catalog, one ordering
and default-ownership rule, and one set of availability, ref-formatting
and variant helpers shared across chat, schedules, agents and the goal
auditor.

- Add a shared TUI-compatible model-preference module and make the
  backend model.json store match its format.
- Consolidate the frontend provider catalog, availability check, model
  ref formatter and variant persistence into single owners.
- Drive chat, schedule, agent and goal-auditor model lists from a shared
  useModelSections hook and buildModelSections, following TUI ordering.
- Extract a shared ModelCombobox with a taller list, and list models the
  TUI way in ModelQuickSelect.
- Add a shared isRecord util and model-selection comparison helpers.
This commit is contained in:
Chris Scott committed 2026-10-06 20:44:27 -04:00
1 parent 3d143568c1
commit 65b72e55ae
82 files changed
+4418 -2624

No files matched your search

+107 -4
View File
@@ -1,4 +1,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { Hono } from 'hono'
import { createProvidersRoutes } from './providers'
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
@@ -8,15 +11,27 @@ import { buildOpenCodeBasicAuth } from '@opencode-manager/shared/opencode'
import { ClientError } from '@opencode-manager/shared/opencode'
import type { IntegrationInfo } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from '../services/opencode/client'
import type { OpenCodeModelStateRecord } from '../services/opencode-model-state'
import type { ModelPreferenceDocument } from '@opencode-manager/shared/opencode'
const modelStatePaths = vi.hoisted(() => ({ file: '' }))
vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => {
const actual = await importOriginal<typeof import('@opencode-manager/shared/config/env')>()
return {
...actual,
getOpenCodeModelStatePath: () => modelStatePaths.file,
}
})
const modelStateMock = vi.hoisted(() => ({
readOpenCodeModelState: vi.fn(),
updateOpenCodeModelState: vi.fn(),
actual: undefined as unknown,
}))
vi.mock('../services/opencode-model-state', async (importOriginal) => {
const actual = await importOriginal<typeof import('../services/opencode-model-state')>()
modelStateMock.actual = actual
return {
...actual,
readOpenCodeModelState: modelStateMock.readOpenCodeModelState,
@@ -58,14 +73,14 @@ function createCredentialApp(client: OpenCodeClient): Hono {
describe('providers routes', () => {
let app: Hono
let storedState: OpenCodeModelStateRecord
let storedState: ModelPreferenceDocument
beforeEach(() => {
vi.clearAllMocks()
storedState = { recent: [], favorite: [], variant: {} }
modelStateMock.readOpenCodeModelState.mockImplementation(async () => storedState)
modelStateMock.updateOpenCodeModelState.mockImplementation(
async (mutate: (state: OpenCodeModelStateRecord) => OpenCodeModelStateRecord) => {
async (mutate: (state: ModelPreferenceDocument) => ModelPreferenceDocument) => {
storedState = mutate(storedState)
return storedState
},
@@ -136,6 +151,44 @@ describe('providers routes', () => {
expect(data2.favorite).toHaveLength(0)
})
it('with variant persists the named variant', async () => {
const res = await app.request('/providers/model-state', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
variant: { model: { providerID: 'anthropic', modelID: 'claude' }, value: 'high' },
}),
})
expect(res.status).toBe(200)
const data = (await res.json()) as { variant: Record<string, string | undefined> }
expect(data.variant).toEqual({ 'anthropic/claude': 'high' })
})
it('with variant value omitted or null persists default', async () => {
const model = { providerID: 'anthropic', modelID: 'claude' }
const omitted = await app.request('/providers/model-state', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variant: { model } }),
})
expect(omitted.status).toBe(200)
expect(((await omitted.json()) as { variant: Record<string, string | undefined> }).variant).toEqual({
'anthropic/claude': 'default',
})
const explicitNull = await app.request('/providers/model-state', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variant: { model, value: null } }),
})
expect(explicitNull.status).toBe(200)
expect(((await explicitNull.json()) as { variant: Record<string, string | undefined> }).variant).toEqual({
'anthropic/claude': 'default',
})
})
it('with invalid body returns 400', async () => {
const res = await app.request('/providers/model-state', {
method: 'POST',
@@ -163,6 +216,56 @@ describe('providers routes', () => {
})
})
describe('model-state response contract', () => {
let workDir: string
beforeEach(async () => {
workDir = await mkdtemp(path.join(tmpdir(), 'providers-model-state-'))
modelStatePaths.file = path.join(workDir, 'model.json')
const actual = modelStateMock.actual as typeof import('../services/opencode-model-state')
modelStateMock.readOpenCodeModelState.mockImplementation(actual.readOpenCodeModelState)
modelStateMock.updateOpenCodeModelState.mockImplementation(actual.updateOpenCodeModelState)
await writeFile(
modelStatePaths.file,
JSON.stringify({ recent: [], favorite: [], variant: {}, extra: 1 }),
'utf8',
)
})
afterEach(async () => {
await rm(workDir, { recursive: true, force: true })
})
it('GET omits unknown root keys', async () => {
const res = await app.request('/providers/model-state')
expect(res.status).toBe(200)
const data = (await res.json()) as Record<string, unknown>
expect(data).toEqual({ recent: [], favorite: [], variant: {} })
expect(data).not.toHaveProperty('extra')
})
it('POST omits unknown root keys from the response but preserves them in the file', async () => {
const res = await app.request('/providers/model-state', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ recent: { providerID: 'anthropic', modelID: 'claude' } }),
})
expect(res.status).toBe(200)
const data = (await res.json()) as Record<string, unknown>
expect(data).toEqual({
recent: [{ providerID: 'anthropic', modelID: 'claude' }],
favorite: [],
variant: {},
})
expect(data).not.toHaveProperty('extra')
const file = JSON.parse(await readFile(modelStatePaths.file, 'utf8')) as { extra: unknown }
expect(file.extra).toBe(1)
})
})
describe('GET /credentials', () => {
it('lists only integrations that hold a credential connection', async () => {
const client = createStubOpenCodeClient()
+16 -6
View File
@@ -3,22 +3,29 @@ import { z } from 'zod'
import { SetCredentialRequestSchema } from '../../../shared/src/schemas/auth'
import { logger } from '../utils/logger'
import { handleOpenCodeError } from '../utils/route-helpers'
import type { IntegrationInfo } from '@opencode-manager/shared/opencode'
import {
addRecentModel,
removeRecentModel,
setModelVariant,
toggleFavoriteModel,
type IntegrationInfo,
} from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from '../services/opencode/client'
import { runWhenIntegrationReady } from '../services/opencode/integration-ready'
import {
addRecentModel,
ModelSelectionSchema,
readOpenCodeModelState,
removeRecentModel,
toggleFavoriteModel,
updateOpenCodeModelState,
} from '../services/opencode-model-state'
const UpdateModelStateSchema = z.object({
const ModelStateUpdateSchema = z.object({
recent: ModelSelectionSchema.optional(),
favorite: ModelSelectionSchema.optional(),
removeRecent: ModelSelectionSchema.optional(),
variant: z.object({
model: ModelSelectionSchema,
value: z.string().min(1).nullable().optional(),
}).optional(),
}).strict()
function credentialConnections(integration: IntegrationInfo) {
@@ -41,7 +48,7 @@ export function createProvidersRoutes(openCodeClient: OpenCodeClient) {
app.post('/model-state', async (c) => {
try {
const body = await c.req.json()
const validated = UpdateModelStateSchema.parse(body)
const validated = ModelStateUpdateSchema.parse(body)
const nextState = await updateOpenCodeModelState((state) => {
if (validated.favorite) {
@@ -53,6 +60,9 @@ export function createProvidersRoutes(openCodeClient: OpenCodeClient) {
if (validated.removeRecent) {
return removeRecentModel(state, validated.removeRecent)
}
if (validated.variant) {
return setModelVariant(state, validated.variant.model, validated.variant.value ?? undefined)
}
return state
})
+14 -75
View File
@@ -1,101 +1,40 @@
import { z } from 'zod'
import { getOpenCodeModelStatePath } from '@opencode-manager/shared/config/env'
import {
decodeModelPreference,
toModelPreference,
type ModelPreference,
type ModelPreferenceDocument,
} from '@opencode-manager/shared/opencode'
import { readJsonSafe, withFileLock, writeJsonAtomic } from '../utils/atomic-json'
import { logger } from '../utils/logger'
export const ModelSelectionSchema = z.object({
providerID: z.string().min(1),
modelID: z.string().min(1),
})
export const ModelStateSchema = z.object({
recent: z.array(ModelSelectionSchema).default([]),
favorite: z.array(ModelSelectionSchema).default([]),
variant: z.record(z.string(), z.string().optional()).default({}),
}).passthrough()
export interface ModelSelectionRecord {
providerID: string
modelID: string
}
export interface OpenCodeModelStateRecord {
recent: ModelSelectionRecord[]
favorite: ModelSelectionRecord[]
variant: Record<string, string | undefined>
}
export const MAX_RECENT_MODELS = 10
function createEmptyState(): OpenCodeModelStateRecord {
return { recent: [], favorite: [], variant: {} }
}
function toRecord(data: z.infer<typeof ModelStateSchema>): OpenCodeModelStateRecord {
return { recent: data.recent, favorite: data.favorite, variant: data.variant }
}
export async function readOpenCodeModelState(): Promise<OpenCodeModelStateRecord> {
export async function readOpenCodeModelState(): Promise<ModelPreference> {
const raw = await readJsonSafe<unknown>(getOpenCodeModelStatePath(), null)
const parsed = ModelStateSchema.safeParse(raw)
if (!parsed.success) {
if (raw !== null) {
logger.warn('OpenCode model state file has invalid structure', parsed.error)
}
return createEmptyState()
}
return toRecord(parsed.data)
}
export function addRecentModel(state: OpenCodeModelStateRecord, model: ModelSelectionRecord): OpenCodeModelStateRecord {
const deduped = [
model,
...state.recent.filter(m => m.providerID !== model.providerID || m.modelID !== model.modelID),
]
return { ...state, recent: deduped.slice(0, MAX_RECENT_MODELS) }
}
export function removeRecentModel(state: OpenCodeModelStateRecord, model: ModelSelectionRecord): OpenCodeModelStateRecord {
return {
...state,
recent: state.recent.filter(m => m.providerID !== model.providerID || m.modelID !== model.modelID),
}
}
export function toggleFavoriteModel(state: OpenCodeModelStateRecord, model: ModelSelectionRecord): OpenCodeModelStateRecord {
const exists = state.favorite.some(
m => m.providerID === model.providerID && m.modelID === model.modelID,
)
const favorite = exists
? state.favorite.filter(m => m.providerID !== model.providerID || m.modelID !== model.modelID)
: [...state.favorite, model]
return { ...state, favorite }
return toModelPreference(decodeModelPreference(raw))
}
export async function updateOpenCodeModelState(
mutate: (state: OpenCodeModelStateRecord) => OpenCodeModelStateRecord,
): Promise<OpenCodeModelStateRecord> {
mutate: (state: ModelPreferenceDocument) => ModelPreferenceDocument,
): Promise<ModelPreference> {
const modelStatePath = getOpenCodeModelStatePath()
return withFileLock(modelStatePath, async () => {
const raw = await readJsonSafe<unknown>(modelStatePath, {})
const parsed = ModelStateSchema.safeParse(raw)
const current = parsed.success ? toRecord(parsed.data) : createEmptyState()
const next = mutate(current)
const rawObject = raw && typeof raw === 'object' && !Array.isArray(raw)
? raw as Record<string, unknown>
: {}
const decoded = decodeModelPreference(raw)
const next = mutate(decoded)
await writeJsonAtomic(modelStatePath, {
...rawObject,
...decoded,
recent: next.recent,
favorite: next.favorite,
variant: next.variant,
})
return next
return toModelPreference(next)
})
}
+8 -18
View File
@@ -1,5 +1,5 @@
import type { ModelInfo, ModelRef } from '@opencode-manager/shared/opencode'
import { formatOpenCodeModelRef, openCodeLocation, parseOpenCodeModelRef, selectConfiguredModelRef } from '@opencode-manager/shared/opencode'
import { findModelInfo, formatOpenCodeModelRef, openCodeLocation, parseOpenCodeModelRef, selectConfiguredModelRef, selectEffectiveModelRef } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from './opencode/client'
export interface ResolvedOpenCodeModel {
@@ -36,7 +36,7 @@ function toResolvedModel(ref: ModelRef): ResolvedOpenCodeModel {
}
function findAvailable(models: ModelInfo[], ref: ModelRef): ModelInfo | undefined {
return models.find((model) => model.providerID === ref.providerID && model.id === ref.id)
return findModelInfo(models, { providerID: ref.providerID, modelID: ref.id })
}
function isTargetLoaded(models: ModelInfo[], targetRef: ModelRef | undefined): boolean {
@@ -49,23 +49,13 @@ function resolveFromLoadedModels(
configuredRef: ModelRef | undefined,
preferredRef: ModelRef | undefined,
): ResolvedOpenCodeModel | null {
if (preferredRef && findAvailable(models, preferredRef)) {
return toResolvedModel(preferredRef)
}
const resolved = selectEffectiveModelRef({
models,
defaultModel,
candidates: [preferredRef, configuredRef],
})
if (configuredRef && findAvailable(models, configuredRef)) {
return toResolvedModel(configuredRef)
}
if (defaultModel) {
const defaultRef: ModelRef = { providerID: defaultModel.providerID, id: defaultModel.id }
if (findAvailable(models, defaultRef)) {
return toResolvedModel(defaultRef)
}
}
const fallback = models.find((model) => model.enabled)
return fallback ? toResolvedModel({ providerID: fallback.providerID, id: fallback.id }) : null
return resolved ? toResolvedModel(resolved) : null
}
function sleep(ms: number, signal: AbortSignal): Promise<void> {
@@ -18,17 +18,16 @@ vi.mock('../../src/utils/logger', () => ({
}))
import {
MAX_RECENT_MODELS,
addRecentModel,
readOpenCodeModelState,
removeRecentModel,
toggleFavoriteModel,
type ModelPreference,
} from '@opencode-manager/shared/opencode'
import {
readOpenCodeModelState,
updateOpenCodeModelState,
type OpenCodeModelStateRecord,
} from '../../src/services/opencode-model-state'
import { logger } from '../../src/utils/logger'
const emptyState = (): OpenCodeModelStateRecord => ({ recent: [], favorite: [], variant: {} })
const emptyState = (): ModelPreference => ({ recent: [], favorite: [], variant: {} })
describe('opencode-model-state', () => {
let workDir: string
@@ -43,65 +42,6 @@ describe('opencode-model-state', () => {
await rm(workDir, { recursive: true, force: true })
})
describe('addRecentModel', () => {
it('adds a new model to the front', () => {
const state = addRecentModel(emptyState(), { providerID: 'anthropic', modelID: 'claude' })
expect(state.recent).toEqual([{ providerID: 'anthropic', modelID: 'claude' }])
})
it('deduplicates and moves a re-selected model to the front', () => {
const model = { providerID: 'openai', modelID: 'gpt-4o' }
const first = addRecentModel(emptyState(), model)
const second = addRecentModel(first, { providerID: 'anthropic', modelID: 'claude' })
const third = addRecentModel(second, model)
expect(third.recent).toEqual([
model,
{ providerID: 'anthropic', modelID: 'claude' },
])
})
it('caps recent at MAX_RECENT_MODELS', () => {
let state = emptyState()
for (let i = 0; i < MAX_RECENT_MODELS + 2; i += 1) {
state = addRecentModel(state, { providerID: `provider-${i}`, modelID: `model-${i}` })
}
expect(state.recent).toHaveLength(MAX_RECENT_MODELS)
expect(state.recent[0]).toEqual({ providerID: 'provider-11', modelID: 'model-11' })
})
})
describe('removeRecentModel', () => {
it('removes the matching model and keeps the rest', () => {
const state = {
recent: [
{ providerID: 'anthropic', modelID: 'claude' },
{ providerID: 'openai', modelID: 'gpt-4o' },
],
favorite: [],
variant: {},
}
expect(removeRecentModel(state, { providerID: 'anthropic', modelID: 'claude' }).recent).toEqual([
{ providerID: 'openai', modelID: 'gpt-4o' },
])
})
})
describe('toggleFavoriteModel', () => {
it('adds when missing', () => {
const state = toggleFavoriteModel(emptyState(), { providerID: 'anthropic', modelID: 'claude' })
expect(state.favorite).toEqual([{ providerID: 'anthropic', modelID: 'claude' }])
})
it('removes when present', () => {
const model = { providerID: 'openai', modelID: 'gpt-4' }
const added = toggleFavoriteModel(emptyState(), model)
expect(toggleFavoriteModel(added, model).favorite).toEqual([])
})
})
describe('readOpenCodeModelState', () => {
it('returns empty defaults when the file is missing', async () => {
await expect(readOpenCodeModelState()).resolves.toEqual(emptyState())
@@ -118,11 +58,27 @@ describe('opencode-model-state', () => {
await expect(readOpenCodeModelState()).resolves.toEqual(state)
})
it('warns and returns empty defaults when the file has invalid structure', async () => {
it('drops malformed entries without resetting the whole file', async () => {
await writeFile(
paths.modelState,
JSON.stringify({
recent: [{ providerID: 'a', modelID: 'b' }, { providerID: '' }],
variant: { 'a/b': 'default', x: '' },
extra: 1,
}),
'utf8',
)
const state = await readOpenCodeModelState()
expect(state.recent).toEqual([{ providerID: 'a', modelID: 'b' }])
expect(state.variant).toEqual({ 'a/b': 'default' })
expect(state).not.toHaveProperty('extra')
})
it('returns empty defaults when the file has an unexpected shape', async () => {
await writeFile(paths.modelState, JSON.stringify({ recent: 'not-an-array' }), 'utf8')
await expect(readOpenCodeModelState()).resolves.toEqual(emptyState())
expect(logger.warn).toHaveBeenCalled()
})
})
@@ -152,6 +108,21 @@ describe('opencode-model-state', () => {
expect(file.variant).toEqual({})
})
it('preserves unknown top-level keys when toggling a favorite', async () => {
await writeFile(paths.modelState, JSON.stringify({ extra: 1, recent: [] }), 'utf8')
await updateOpenCodeModelState(state =>
toggleFavoriteModel(state, { providerID: 'anthropic', modelID: 'claude' }),
)
const file = JSON.parse(await readFile(paths.modelState, 'utf8')) as {
extra: unknown
favorite: unknown[]
}
expect(file.extra).toBe(1)
expect(file.favorite).toEqual([{ providerID: 'anthropic', modelID: 'claude' }])
})
it('recovers from corrupt JSON and writes valid state', async () => {
await writeFile(paths.modelState, '{ invalid json content }', 'utf8')
@@ -174,7 +145,7 @@ describe('opencode-model-state', () => {
await Promise.all(operations)
const finalState = await readOpenCodeModelState()
expect(finalState.recent.length).toBeLessThanOrEqual(MAX_RECENT_MODELS)
expect(finalState.recent.length).toBeLessThanOrEqual(10)
expect(finalState.recent.length).toBeGreaterThan(0)
const uniqueKeys = new Set(finalState.recent.map((m) => `${m.providerID}/${m.modelID}`))
@@ -0,0 +1,493 @@
import { describe, expect, it } from 'vitest'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
import {
addRecentModel,
compareCatalogModels,
cycleModelVariant,
decodeModelPreference,
favoriteModels,
findModelInfo,
isModelFree,
isSameModelRef,
isSameModelSelection,
modelPreferenceKey,
normalizeModelVariant,
recentModels,
removeRecentModel,
selectEffectiveModelRef,
selectInteractiveModel,
selectPreferredVariant,
setModelVariant,
toModelPreference,
toggleFavoriteModel,
type ModelPreference,
} from '@opencode-manager/shared/opencode'
interface ModelInfoInput {
providerID: string
id: string
name?: string
enabled?: boolean
status?: ModelInfo['status']
variants?: string[]
released?: number
cost?: Array<{ input: number }>
}
function modelInfo(input: ModelInfoInput): ModelInfo {
return {
providerID: input.providerID,
id: input.id,
name: input.name ?? input.id,
enabled: input.enabled ?? true,
status: input.status ?? 'active',
variants: (input.variants ?? []).map((id) => ({ id })),
time: { released: input.released ?? 0 },
cost: (input.cost ?? []).map((cost) => ({
input: cost.input,
output: cost.input,
cache: { read: 0, write: 0 },
})),
} as ModelInfo
}
describe('OpenCode model preference helpers', () => {
describe('normalizeModelVariant', () => {
it('maps the explicit default variant to undefined', () => {
expect(normalizeModelVariant('default')).toBeUndefined()
})
it('passes named variants through', () => {
expect(normalizeModelVariant('high')).toBe('high')
expect(normalizeModelVariant(undefined)).toBeUndefined()
})
})
describe('modelPreferenceKey', () => {
it('joins the provider and model id', () => {
expect(modelPreferenceKey({ providerID: 'p', modelID: 'm' })).toBe('p/m')
})
})
describe('recentModels', () => {
it('prepends the model and removes duplicates', () => {
const recent = [
{ providerID: 'a', modelID: 'one' },
{ providerID: 'b', modelID: 'two' },
{ providerID: 'a', modelID: 'one' },
]
expect(recentModels({ providerID: 'a', modelID: 'one' }, recent)).toEqual([
{ providerID: 'a', modelID: 'one' },
{ providerID: 'b', modelID: 'two' },
])
})
it('caps the list at ten entries', () => {
const recent = Array.from({ length: 15 }, (_, index) => ({
providerID: 'p',
modelID: `m${index}`,
}))
const result = recentModels({ providerID: 'fresh', modelID: 'new' }, recent)
expect(result).toHaveLength(10)
expect(result[0]).toEqual({ providerID: 'fresh', modelID: 'new' })
expect(result[9]).toEqual({ providerID: 'p', modelID: 'm8' })
})
})
describe('favoriteModels', () => {
it('prepends a new favorite and removes duplicates', () => {
const favorite = [
{ providerID: 'a', modelID: 'one' },
{ providerID: 'b', modelID: 'two' },
{ providerID: 'a', modelID: 'one' },
]
expect(favoriteModels({ providerID: 'a', modelID: 'one' }, favorite, true)).toEqual([
{ providerID: 'a', modelID: 'one' },
{ providerID: 'b', modelID: 'two' },
])
})
it('removes the model when disabled', () => {
const favorite = [
{ providerID: 'a', modelID: 'one' },
{ providerID: 'b', modelID: 'two' },
]
expect(favoriteModels({ providerID: 'a', modelID: 'one' }, favorite, false)).toEqual([
{ providerID: 'b', modelID: 'two' },
])
})
})
describe('cycleModelVariant', () => {
it('skips the default variant and starts at the first named variant', () => {
expect(cycleModelVariant(undefined, ['default', 'low', 'high'])).toBe('low')
})
it('advances through named variants and wraps back to none', () => {
expect(cycleModelVariant('low', ['default', 'low', 'high'])).toBe('high')
expect(cycleModelVariant('high', ['default', 'low', 'high'])).toBeUndefined()
})
it('returns undefined when there are no named variants', () => {
expect(cycleModelVariant('low', ['default'])).toBeUndefined()
expect(cycleModelVariant(undefined, [])).toBeUndefined()
})
})
describe('decodeModelPreference', () => {
it('drops malformed entries, keeps unknown root keys and a literal default variant', () => {
const decoded = decodeModelPreference({
recent: [
{ providerID: 'a', modelID: 'b' },
{ providerID: '', modelID: 'x' },
{ providerID: 'c' },
'not-an-object',
],
favorite: [{ providerID: 'f', modelID: 'm' }],
variant: { 'a/b': 'default', 'c/d': 'high', x: '', '': 'y', z: 5 },
extra: 1,
})
expect(decoded.recent).toEqual([{ providerID: 'a', modelID: 'b' }])
expect(decoded.favorite).toEqual([{ providerID: 'f', modelID: 'm' }])
expect(decoded.variant).toEqual({ 'a/b': 'default', 'c/d': 'high' })
expect(decoded.extra).toBe(1)
})
it('returns an empty preference for a non-record value', () => {
expect(decodeModelPreference(null)).toEqual({ recent: [], favorite: [], variant: {} })
})
})
describe('isModelFree', () => {
it('is free when every cost tier has a zero input price', () => {
expect(isModelFree(modelInfo({ providerID: 'p', id: 'm', cost: [{ input: 0 }] }))).toBe(true)
})
it('is not free when any cost tier charges, or when there are no tiers', () => {
expect(isModelFree(modelInfo({ providerID: 'p', id: 'm', cost: [{ input: 0 }, { input: 3 }] }))).toBe(false)
expect(isModelFree(modelInfo({ providerID: 'p', id: 'm' }))).toBe(false)
})
})
})
describe('selectInteractiveModel', () => {
const models = [
modelInfo({ providerID: 'openai', id: 'gpt-5' }),
modelInfo({ providerID: 'anthropic', id: 'claude-sonnet-4' }),
modelInfo({ providerID: 'opencode', id: 'big-pickle' }),
]
it('prefers the current pick when it is valid', () => {
expect(
selectInteractiveModel({
models,
current: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
agentModel: { providerID: 'openai', id: 'gpt-5' },
}),
).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
it('falls through the agent model, configured model and first valid recent', () => {
expect(
selectInteractiveModel({
models,
current: { providerID: 'missing', modelID: 'none' },
agentModel: { providerID: 'anthropic', id: 'claude-sonnet-4' },
}),
).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
expect(
selectInteractiveModel({
models,
agentModel: { providerID: 'missing', id: 'none' },
configured: { providerID: 'openai', id: 'gpt-5' },
}),
).toEqual({ providerID: 'openai', modelID: 'gpt-5' })
expect(
selectInteractiveModel({
models,
configured: { providerID: 'missing', id: 'none' },
recent: [
{ providerID: 'missing', modelID: 'none' },
{ providerID: 'opencode', modelID: 'big-pickle' },
],
}),
).toEqual({ providerID: 'opencode', modelID: 'big-pickle' })
})
it('falls back to the first catalog model when nothing else is valid', () => {
expect(selectInteractiveModel({ models })).toEqual({ providerID: 'openai', modelID: 'gpt-5' })
})
it('returns undefined with no catalog models', () => {
expect(selectInteractiveModel({ models: [] })).toBeUndefined()
})
})
describe('selectPreferredVariant', () => {
const model = { providerID: 'openai', modelID: 'gpt-5' }
const info = modelInfo({ providerID: 'openai', id: 'gpt-5', variants: ['low', 'high'] })
it('lets a saved preference win', () => {
expect(
selectPreferredVariant({
model,
info,
preferences: { 'openai/gpt-5': 'high' },
agentModel: { providerID: 'openai', id: 'gpt-5', variant: 'low' },
}),
).toBe('high')
})
it('lets a saved default beat the agent variant and produce none', () => {
expect(
selectPreferredVariant({
model,
info,
preferences: { 'openai/gpt-5': 'default' },
agentModel: { providerID: 'openai', id: 'gpt-5', variant: 'high' },
}),
).toBeUndefined()
})
it('uses the agent variant when the agent model matches', () => {
expect(
selectPreferredVariant({
model,
info,
preferences: {},
agentModel: { providerID: 'openai', id: 'gpt-5', variant: 'low' },
}),
).toBe('low')
})
it('uses the configured variant when the configured model matches', () => {
expect(
selectPreferredVariant({
model,
info,
preferences: {},
agentModel: { providerID: 'openai', id: 'other', variant: 'low' },
configured: { providerID: 'openai', id: 'gpt-5', variant: 'high' },
}),
).toBe('high')
})
it('drops a variant the model does not declare', () => {
expect(
selectPreferredVariant({
model,
info,
preferences: { 'openai/gpt-5': 'medium' },
}),
).toBeUndefined()
})
})
describe('compareCatalogModels', () => {
it('orders opencode-go, then opencode, then other providers', () => {
const anthropic = modelInfo({ providerID: 'anthropic', id: 'claude', name: 'Claude' })
const opencode = modelInfo({ providerID: 'opencode', id: 'big-pickle', name: 'Big Pickle' })
const go = modelInfo({ providerID: 'opencode-go', id: 'gpt-oss', name: 'Gpt Oss' })
const sorted = [anthropic, opencode, go].sort(compareCatalogModels)
expect(sorted.map((entry) => entry.providerID)).toEqual(['opencode-go', 'opencode', 'anthropic'])
})
it('orders remaining providers by provider name', () => {
const zeta = modelInfo({ providerID: 'zeta', id: 'z', name: 'Z' })
const alpha = modelInfo({ providerID: 'alpha', id: 'a', name: 'A' })
expect([zeta, alpha].sort(compareCatalogModels).map((entry) => entry.providerID)).toEqual(['alpha', 'zeta'])
})
it('prefers a provider display name over the provider id when both are present', () => {
const byIdFirst = { providerID: 'alpha', providerName: 'Zeta', name: 'Model' }
const byNameFirst = { providerID: 'zeta', providerName: 'Alpha', name: 'Model' }
expect([byIdFirst, byNameFirst].sort(compareCatalogModels).map((entry) => entry.providerID)).toEqual([
'zeta',
'alpha',
])
})
it('orders free models first, then newest, then by name within a provider', () => {
const paidNew = modelInfo({ providerID: 'anthropic', id: 'paid-new', name: 'Paid New', released: 20, cost: [{ input: 3 }] })
const paidOld = modelInfo({ providerID: 'anthropic', id: 'paid-old', name: 'Paid Old', released: 10, cost: [{ input: 3 }] })
const free = modelInfo({ providerID: 'anthropic', id: 'free', name: 'Free', released: 1, cost: [{ input: 0 }] })
const paidTieA = modelInfo({ providerID: 'anthropic', id: 'a', name: 'Alpha', released: 5, cost: [{ input: 3 }] })
const paidTieB = modelInfo({ providerID: 'anthropic', id: 'b', name: 'Beta', released: 5, cost: [{ input: 3 }] })
const sorted = [paidNew, paidOld, free, paidTieB, paidTieA].sort(compareCatalogModels)
expect(sorted.map((entry) => entry.id)).toEqual(['free', 'paid-new', 'paid-old', 'a', 'b'])
})
})
describe('selectEffectiveModelRef', () => {
const models = [
modelInfo({ providerID: 'openai', id: 'gpt-5' }),
modelInfo({ providerID: 'openai', id: 'gpt-5-mini' }),
]
it('returns the first available candidate with its variant', () => {
expect(
selectEffectiveModelRef({
models,
defaultModel: { providerID: 'openai', id: 'gpt-5-mini' },
candidates: [
{ providerID: 'openai', id: 'missing' },
{ providerID: 'openai', id: 'gpt-5', variant: 'high' },
],
}),
).toEqual({ providerID: 'openai', id: 'gpt-5', variant: 'high' })
})
it('falls back to the default model when no candidate is available', () => {
expect(
selectEffectiveModelRef({
models,
defaultModel: { providerID: 'openai', id: 'gpt-5-mini' },
candidates: [{ providerID: 'openai', id: 'missing' }],
}),
).toEqual({ providerID: 'openai', id: 'gpt-5-mini' })
})
it('falls back to the first enabled model when the default is unavailable', () => {
expect(
selectEffectiveModelRef({
models: [modelInfo({ providerID: 'openai', id: 'gpt-5', enabled: false }), models[1]!],
defaultModel: { providerID: 'openai', id: 'retired' },
}),
).toEqual({ providerID: 'openai', id: 'gpt-5-mini' })
})
it('returns undefined when nothing is available', () => {
expect(selectEffectiveModelRef({ models: [modelInfo({ providerID: 'openai', id: 'gpt-5', enabled: false })] })).toBeUndefined()
expect(selectEffectiveModelRef({ models: [] })).toBeUndefined()
})
})
describe('isSameModelSelection', () => {
it('matches the provider and model id', () => {
expect(isSameModelSelection({ providerID: 'openai', modelID: 'gpt-5' }, { providerID: 'openai', modelID: 'gpt-5' })).toBe(true)
})
it('rejects a different provider or model id', () => {
expect(isSameModelSelection({ providerID: 'openai', modelID: 'gpt-5' }, { providerID: 'anthropic', modelID: 'gpt-5' })).toBe(false)
expect(isSameModelSelection({ providerID: 'openai', modelID: 'gpt-5' }, { providerID: 'openai', modelID: 'gpt-5-mini' })).toBe(false)
})
})
describe('isSameModelRef', () => {
it('treats two missing references as equal and one missing as different', () => {
expect(isSameModelRef(undefined, undefined)).toBe(true)
expect(isSameModelRef(null, null)).toBe(true)
expect(isSameModelRef(undefined, null)).toBe(true)
expect(isSameModelRef({ providerID: 'openai', id: 'gpt-5' }, undefined)).toBe(false)
expect(isSameModelRef(undefined, { providerID: 'openai', id: 'gpt-5' })).toBe(false)
})
it('matches the provider, id and variant', () => {
expect(isSameModelRef({ providerID: 'openai', id: 'gpt-5', variant: 'high' }, { providerID: 'openai', id: 'gpt-5', variant: 'high' })).toBe(true)
expect(isSameModelRef({ providerID: 'openai', id: 'gpt-5', variant: 'high' }, { providerID: 'openai', id: 'gpt-5' })).toBe(false)
expect(isSameModelRef({ providerID: 'openai', id: 'gpt-5' }, { providerID: 'anthropic', id: 'gpt-5' })).toBe(false)
expect(isSameModelRef({ providerID: 'openai', id: 'gpt-5' }, { providerID: 'openai', id: 'gpt-5-mini' })).toBe(false)
})
it('treats the explicit default variant as no variant', () => {
expect(isSameModelRef({ providerID: 'openai', id: 'gpt-5', variant: 'default' }, { providerID: 'openai', id: 'gpt-5' })).toBe(true)
expect(isSameModelRef({ providerID: 'openai', id: 'gpt-5', variant: 'default' }, { providerID: 'openai', id: 'gpt-5', variant: undefined })).toBe(true)
})
})
describe('findModelInfo', () => {
const entry = { ...modelInfo({ providerID: 'openai', id: 'gpt-5' }), modelID: 'gpt-5-backing' } as ModelInfo
it('matches the OpenCode key, not the backing model id', () => {
expect(findModelInfo([entry], { providerID: 'openai', modelID: 'gpt-5' })).toBe(entry)
expect(findModelInfo([entry], { providerID: 'openai', modelID: 'gpt-5-backing' })).toBeUndefined()
})
it('requires the provider to match too', () => {
expect(findModelInfo([entry], { providerID: 'anthropic', modelID: 'gpt-5' })).toBeUndefined()
})
})
describe('model preference updaters', () => {
const emptyState = (): ModelPreference => ({ recent: [], favorite: [], variant: {} })
it('addRecentModel prepends, deduplicates and preserves other keys', () => {
const model = { providerID: 'openai', modelID: 'gpt-5' }
const withExtra = { ...emptyState(), extra: 1 }
const added = addRecentModel(withExtra, model)
const reAdded = addRecentModel(addRecentModel(added, { providerID: 'anthropic', modelID: 'claude' }), model)
expect(reAdded.recent).toEqual([model, { providerID: 'anthropic', modelID: 'claude' }])
expect(reAdded.extra).toBe(1)
})
it('removeRecentModel filters by selection', () => {
const state: ModelPreference = {
recent: [
{ providerID: 'anthropic', modelID: 'claude' },
{ providerID: 'openai', modelID: 'gpt-4o' },
],
favorite: [],
variant: {},
}
expect(removeRecentModel(state, { providerID: 'anthropic', modelID: 'claude' }).recent).toEqual([
{ providerID: 'openai', modelID: 'gpt-4o' },
])
})
it('toggleFavoriteModel adds then removes', () => {
const model = { providerID: 'anthropic', modelID: 'claude' }
const added = toggleFavoriteModel(emptyState(), model)
expect(added.favorite).toEqual([model])
expect(toggleFavoriteModel(added, model).favorite).toEqual([])
})
it('setModelVariant stores default for missing values and merges the map', () => {
const state: ModelPreference = { recent: [], favorite: [], variant: { 'a/b': 'low' } }
expect(setModelVariant(state, { providerID: 'c', modelID: 'd' }, undefined).variant).toEqual({
'a/b': 'low',
'c/d': 'default',
})
expect(setModelVariant(state, { providerID: 'a', modelID: 'b' }, 'default').variant).toEqual({ 'a/b': 'default' })
expect(setModelVariant(state, { providerID: 'a', modelID: 'b' }, 'high').variant).toEqual({ 'a/b': 'high' })
})
})
describe('toModelPreference', () => {
it('returns only the recent, favorite and variant keys', () => {
const doc = {
recent: [{ providerID: 'anthropic', modelID: 'claude' }],
favorite: [{ providerID: 'openai', modelID: 'gpt-4' }],
variant: { 'anthropic/claude': 'high' },
extra: 1,
session: { current: 'abc' },
}
const preference = toModelPreference(doc)
expect(preference).toEqual({
recent: [{ providerID: 'anthropic', modelID: 'claude' }],
favorite: [{ providerID: 'openai', modelID: 'gpt-4' }],
variant: { 'anthropic/claude': 'high' },
})
expect(preference).not.toHaveProperty('extra')
expect(preference).not.toHaveProperty('session')
})
})
+39 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { formatOpenCodeModelRef, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import { configModelRef, formatOpenCodeModelRef, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
describe('OpenCode model references', () => {
describe('parseOpenCodeModelRef', () => {
@@ -57,4 +57,42 @@ describe('OpenCode model references', () => {
expect(formatOpenCodeModelRef(ref!)).toBe(model)
})
})
describe('configModelRef', () => {
it('parses a string reference', () => {
expect(configModelRef('anthropic/claude-sonnet-4')).toEqual({
providerID: 'anthropic',
id: 'claude-sonnet-4',
})
})
it('parses a string reference with a variant', () => {
expect(configModelRef('openai/gpt-5#high')).toEqual({
providerID: 'openai',
id: 'gpt-5',
variant: 'high',
})
})
it('maps an object reference with a variant', () => {
expect(configModelRef({ providerID: 'openai', model: 'gpt-5', variant: 'high' })).toEqual({
providerID: 'openai',
id: 'gpt-5',
variant: 'high',
})
})
it('maps an object reference without a variant', () => {
expect(configModelRef({ providerID: 'openai', model: 'gpt-5' })).toEqual({
providerID: 'openai',
id: 'gpt-5',
})
})
it('returns undefined for a missing or malformed reference', () => {
expect(configModelRef(undefined)).toBeUndefined()
expect(configModelRef(null)).toBeUndefined()
expect(configModelRef('openai')).toBeUndefined()
})
})
})
+134 -164
View File
@@ -1,22 +1,23 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { getOpenCodeConfigModel, getProviders, getProvidersWithModels, providerCredentialsApi, providerModelRef } from './providers'
import {
getOpenCodeConfiguredModel,
getOpenCodeServerDefaultModel,
getProviders,
modelSelectionRef,
providerCredentialsApi,
providerModelRef,
saveOpenCodeModelVariant,
} from './providers'
import { API_BASE_URL } from '@/config'
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
const { mockGetOpenCodeConfig, mockFetchWrapper, mockProviderList, mockModelList, mockConfigGet } = vi.hoisted(() => ({
mockGetOpenCodeConfig: vi.fn(),
const { mockFetchWrapper, mockProviderList, mockModelList, mockModelDefault, mockConfigGet } = vi.hoisted(() => ({
mockFetchWrapper: vi.fn(),
mockProviderList: vi.fn(),
mockModelList: vi.fn(),
mockModelDefault: vi.fn(),
mockConfigGet: vi.fn(),
}))
vi.mock('./settings', () => ({
settingsApi: {
getOpenCodeConfig: mockGetOpenCodeConfig,
},
}))
vi.mock('./fetchWrapper', () => ({
fetchWrapper: mockFetchWrapper,
}))
@@ -25,24 +26,11 @@ vi.mock('./opencodeApi', () => ({
callOpenCode: (operation: (api: unknown) => Promise<unknown>) =>
operation({
provider: { list: mockProviderList },
model: { list: mockModelList },
model: { list: mockModelList, default: mockModelDefault },
config: { get: mockConfigGet },
}),
}))
const config = makeOpenCodeConfigFile({
content: {
provider: {
openai: {
name: 'OpenAI',
models: {
'gpt-4o': { name: 'GPT-4o' },
},
},
},
},
})
function makeAnthropicModel(overrides: Record<string, unknown> = {}) {
return {
id: 'claude-sonnet-4',
@@ -77,19 +65,7 @@ describe('getProviders', () => {
mockModelList.mockResolvedValue({
location: { directory: '/repo' },
data: [
{
id: 'claude-sonnet-4',
modelID: 'claude-sonnet-4-20250514',
providerID: 'anthropic',
name: 'Claude Sonnet 4',
capabilities: { tools: true, input: ['text', 'image'], output: ['text'] },
variants: [{ id: 'thinking', settings: { reasoning: 'high' } }],
time: { released: Date.UTC(2025, 4, 22) },
cost: [{ input: 3, output: 15, cache: { read: 0.3, write: 3.75 } }],
status: 'active',
enabled: true,
limit: { context: 200000, output: 64000 },
},
makeAnthropicModel(),
{
id: 'claude-legacy',
modelID: 'claude-legacy',
@@ -107,16 +83,33 @@ describe('getProviders', () => {
})
const result = await getProviders('/repo')
expect(result.connected).toEqual(['anthropic'])
expect(result.providers).toHaveLength(1)
expect(result.providers[0].models['claude-sonnet-4']).toMatchObject({
expect(result.providers[0]).toMatchObject({ id: 'anthropic', name: 'Anthropic' })
expect(result.providers[0].models).toHaveLength(1)
expect(result.providers[0].models[0]).toMatchObject({
key: 'claude-sonnet-4',
id: 'claude-sonnet-4-20250514',
name: 'Claude Sonnet 4',
limit: { context: 200000, output: 64000 },
variants: { thinking: { reasoning: 'high' } },
released: Date.UTC(2025, 4, 22),
free: false,
})
expect(result.providers[0].models['claude-legacy']).toBeUndefined()
expect(result.models).toHaveLength(2)
})
it('flags zero-cost models as free', async () => {
mockProviderList.mockResolvedValue({
location: { directory: '/repo' },
data: [{ id: 'opencode', name: 'OpenCode', activation: 'enabled' }],
})
mockModelList.mockResolvedValue({
location: { directory: '/repo' },
data: [makeAnthropicModel({ providerID: 'opencode', cost: [{ input: 0, output: 0 }] })],
})
const result = await getProviders('/repo')
expect(result.providers[0].models[0].free).toBe(true)
})
it('excludes disabled models and disabled providers from the picker', async () => {
@@ -138,9 +131,39 @@ describe('getProviders', () => {
const result = await getProviders('/repo')
expect(result.connected).toEqual(['anthropic'])
expect(result.providers.map((provider) => provider.id)).toEqual(['anthropic'])
expect(Object.keys(result.providers[0].models)).toEqual(['claude-sonnet-4'])
expect(result.providers[0].models.map((model) => model.key)).toEqual(['claude-sonnet-4'])
})
it('sorts providers and models in the TUI order', async () => {
mockProviderList.mockResolvedValue({
location: { directory: '/repo' },
data: [
{ id: 'zeta', name: 'Zeta', activation: 'enabled' },
{ id: 'opencode', name: 'OpenCode', activation: 'enabled' },
{ id: 'alpha', name: 'Alpha', activation: 'enabled' },
{ id: 'opencode-go', name: 'OpenCode Go', activation: 'enabled' },
],
})
mockModelList.mockResolvedValue({
location: { directory: '/repo' },
data: [
makeAnthropicModel({ id: 'paid-new', modelID: 'paid-new', providerID: 'opencode', time: { released: 300 }, cost: [{ input: 1, output: 1 }] }),
makeAnthropicModel({ id: 'free', modelID: 'free', providerID: 'opencode', time: { released: 100 }, cost: [{ input: 0, output: 0 }] }),
makeAnthropicModel({ id: 'paid-old', modelID: 'paid-old', providerID: 'opencode', time: { released: 200 }, cost: [{ input: 1, output: 1 }] }),
],
})
const result = await getProviders('/repo')
expect(result.providers.map((provider) => provider.id)).toEqual([
'opencode-go',
'opencode',
'alpha',
'zeta',
])
const opencode = result.providers.find((provider) => provider.id === 'opencode')
expect(opencode?.models.map((model) => model.id)).toEqual(['free', 'paid-new', 'paid-old'])
})
it('degrades to an empty result when the upstream call fails', async () => {
@@ -148,30 +171,29 @@ describe('getProviders', () => {
await expect(getProviders('/repo')).resolves.toEqual({
providers: [],
connected: [],
models: [],
})
})
})
describe('getOpenCodeConfigModel', () => {
describe('getOpenCodeConfiguredModel', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('reads a string config model for the directory', async () => {
mockConfigGet.mockResolvedValue([{ type: 'document', info: { model: 'anthropic/claude-sonnet-4' } }])
it('keeps the variant of a string config model', async () => {
mockConfigGet.mockResolvedValue([{ type: 'document', info: { model: 'anthropic/claude-sonnet-4#thinking' } }])
await expect(getOpenCodeConfigModel('/repo')).resolves.toBe('anthropic/claude-sonnet-4')
await expect(getOpenCodeConfiguredModel('/repo')).resolves.toBe('anthropic/claude-sonnet-4#thinking')
expect(mockConfigGet).toHaveBeenCalledWith({ location: { directory: '/repo' } })
})
it('formats an object config model as provider/model', async () => {
it('formats an object config model the same way', async () => {
mockConfigGet.mockResolvedValue([
{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-4o', variant: 'high' } } },
])
await expect(getOpenCodeConfigModel()).resolves.toBe('openai/gpt-4o')
await expect(getOpenCodeConfiguredModel()).resolves.toBe('openai/gpt-4o#high')
expect(mockConfigGet).toHaveBeenCalledWith(undefined)
})
@@ -182,144 +204,86 @@ describe('getOpenCodeConfigModel', () => {
{ type: 'document', info: {} },
])
await expect(getOpenCodeConfigModel('/repo')).resolves.toBe('openai/gpt-4o')
await expect(getOpenCodeConfiguredModel('/repo')).resolves.toBe('openai/gpt-4o')
})
it('returns null when no document sets a model', async () => {
mockConfigGet.mockResolvedValue([{ type: 'document', info: {} }])
await expect(getOpenCodeConfigModel('/repo')).resolves.toBeNull()
await expect(getOpenCodeConfiguredModel('/repo')).resolves.toBeNull()
})
it('returns null when the config read fails', async () => {
mockConfigGet.mockRejectedValue(new Error('upstream down'))
await expect(getOpenCodeConfigModel('/repo')).resolves.toBeNull()
await expect(getOpenCodeConfiguredModel('/repo')).resolves.toBeNull()
})
})
describe('getProvidersWithModels', () => {
describe('getOpenCodeServerDefaultModel', () => {
const location = { location: { directory: '/repo' } }
beforeEach(() => {
vi.clearAllMocks()
mockProviderList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
mockModelList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
})
it('uses the supplied config instead of re-reading it', async () => {
const providers = await getProvidersWithModels(undefined, config)
expect(mockGetOpenCodeConfig).not.toHaveBeenCalled()
expect(providers.map((provider) => provider.id)).toEqual(['openai'])
})
it('reads the config when none is supplied', async () => {
mockGetOpenCodeConfig.mockResolvedValue(config)
const providers = await getProvidersWithModels(undefined)
expect(mockGetOpenCodeConfig).toHaveBeenCalledTimes(1)
expect(providers.map((provider) => provider.id)).toEqual(['openai'])
})
it('degrades to no configured providers when the config read fails', async () => {
mockGetOpenCodeConfig.mockRejectedValue(new Error('no config file'))
const providers = await getProvidersWithModels(undefined)
expect(providers).toEqual([])
})
it('merges configured providers from both provider and providers keys', async () => {
const configWithProviders = makeOpenCodeConfigFile({
content: {
provider: {
openai: { name: 'OpenAI', models: { 'gpt-4o': { name: 'GPT-4o' } } },
},
providers: {
anthropic: { name: 'Anthropic', models: { 'claude-sonnet-4': { name: 'Claude Sonnet 4' } } },
},
},
})
const providers = await getProvidersWithModels(undefined, configWithProviders)
expect(providers.map((provider) => provider.id).sort()).toEqual(['anthropic', 'openai'])
})
it('retains the resolved model catalog for a settings-only provider override', async () => {
mockProviderList.mockResolvedValue({
mockModelDefault.mockResolvedValue({
location: { directory: '/repo' },
data: [{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' }],
data: makeAnthropicModel({ providerID: 'openai', id: 'gpt-5', modelID: 'gpt-5' }),
})
mockModelList.mockResolvedValue({
location: { directory: '/repo' },
data: [
makeAnthropicModel(),
makeAnthropicModel({
id: 'claude-opus-4',
modelID: 'claude-opus-4-20250514',
name: 'Claude Opus 4',
}),
],
})
const configWithSettings = makeOpenCodeConfigFile({
content: { providers: { anthropic: { settings: { apiKey: 'test' } } } },
})
const providers = await getProvidersWithModels(undefined, configWithSettings)
const anthropic = providers.find((provider) => provider.id === 'anthropic')
expect(anthropic?.source).toBe('configured')
expect(anthropic?.models.map((model) => model.key).sort()).toEqual(['claude-opus-4', 'claude-sonnet-4'])
})
it('retains every resolved model and its metadata when a partial model override exists', async () => {
mockProviderList.mockResolvedValue({
location: { directory: '/repo' },
data: [{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' }],
it('returns the server default as a model ref', async () => {
await expect(getOpenCodeServerDefaultModel('/repo')).resolves.toEqual({
providerID: 'openai',
id: 'gpt-5',
})
mockModelList.mockResolvedValue({
location: { directory: '/repo' },
data: [
makeAnthropicModel(),
makeAnthropicModel({
id: 'claude-opus-4',
modelID: 'claude-opus-4-20250514',
name: 'Claude Opus 4',
}),
],
})
const configWithOverride = makeOpenCodeConfigFile({
content: { providers: { anthropic: { models: { 'claude-sonnet-4': { limit: { context: 1 } } } } } },
})
const providers = await getProvidersWithModels(undefined, configWithOverride)
const anthropic = providers.find((provider) => provider.id === 'anthropic')
expect(anthropic?.models.map((model) => model.key).sort()).toEqual(['claude-opus-4', 'claude-sonnet-4'])
const sonnet = anthropic?.models.find((model) => model.key === 'claude-sonnet-4')
expect(sonnet?.limit).toEqual({ context: 200000, output: 64000 })
expect(sonnet?.variants).toEqual({ thinking: { reasoning: 'high' } })
})
it('appends config-only model entries that the resolved catalog omits', async () => {
mockProviderList.mockResolvedValue({
location: { directory: '/repo' },
data: [{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' }],
})
mockModelList.mockResolvedValue({
location: { directory: '/repo' },
data: [makeAnthropicModel()],
})
const configWithExtraModel = makeOpenCodeConfigFile({
content: { providers: { anthropic: { models: { 'claude-custom': { name: 'Claude Custom' } } } } },
})
it('returns null when the server reports no default model', async () => {
mockModelDefault.mockResolvedValue({ location: { directory: '/repo' }, data: null })
const providers = await getProvidersWithModels(undefined, configWithExtraModel)
await expect(getOpenCodeServerDefaultModel('/repo')).resolves.toBeNull()
})
const anthropic = providers.find((provider) => provider.id === 'anthropic')
expect(anthropic?.models.map((model) => model.key).sort()).toEqual(['claude-custom', 'claude-sonnet-4'])
expect(anthropic?.models.find((model) => model.key === 'claude-custom')?.name).toBe('Claude Custom')
it('passes the location to the default model call', async () => {
await getOpenCodeServerDefaultModel('/repo')
expect(mockModelDefault).toHaveBeenCalledWith(location)
})
it('returns null when the default model read fails', async () => {
mockModelDefault.mockRejectedValue(new Error('upstream down'))
await expect(getOpenCodeServerDefaultModel('/repo')).resolves.toBeNull()
})
})
describe('saveOpenCodeModelVariant', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('posts the model and value and returns the state', async () => {
const state = { recent: [], favorite: [], variant: { 'openai/gpt-5': 'high' } }
mockFetchWrapper.mockResolvedValue(state)
await expect(saveOpenCodeModelVariant({ providerID: 'openai', modelID: 'gpt-5' }, 'high')).resolves.toEqual(state)
expect(mockFetchWrapper).toHaveBeenCalledWith(`${API_BASE_URL}/api/providers/model-state`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variant: { model: { providerID: 'openai', modelID: 'gpt-5' }, value: 'high' } }),
})
})
it('sends null when the value is omitted', async () => {
mockFetchWrapper.mockResolvedValue({ recent: [], favorite: [], variant: {} })
await saveOpenCodeModelVariant({ providerID: 'openai', modelID: 'gpt-5' })
expect(mockFetchWrapper).toHaveBeenCalledWith(`${API_BASE_URL}/api/providers/model-state`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variant: { model: { providerID: 'openai', modelID: 'gpt-5' }, value: null } }),
})
})
})
@@ -335,6 +299,12 @@ describe('providerModelRef', () => {
})
})
describe('modelSelectionRef', () => {
it('formats a selection as provider/model', () => {
expect(modelSelectionRef({ providerID: 'openai', modelID: 'gpt-5' })).toBe('openai/gpt-5')
})
})
describe('providerCredentialsApi', () => {
beforeEach(() => {
vi.clearAllMocks()
+73 -194
View File
@@ -1,12 +1,20 @@
import { API_BASE_URL } from "@/config";
import { settingsApi } from "./settings";
import { fetchWrapper } from "./fetchWrapper";
import { callOpenCode } from "./opencodeApi";
import { openCodeLocation, selectConfiguredModelRef, type FormAnswer, type ModelInfo } from "@opencode-manager/shared/opencode";
import {
compareCatalogModels,
formatOpenCodeModelRef,
isModelFree,
modelPreferenceKey,
openCodeLocation,
selectConfiguredModelRef,
type FormAnswer,
type ModelInfo,
type ModelPreference,
type ModelPreferenceModel,
type ModelRef,
} from "@opencode-manager/shared/opencode";
import type { CredentialListResponse, CredentialStatusResponse } from "@opencode-manager/shared/schemas";
import type { OpenCodeConfigFile } from "./types/settings";
export type ProviderSource = "configured" | "local" | "builtin";
export interface Model {
id: string;
@@ -16,74 +24,25 @@ export interface Model {
context: number;
output: number;
};
variants?: Record<string, Record<string, unknown>>;
released: number;
free: boolean;
}
export interface Provider {
id: string;
name: string;
api?: string;
npm?: string;
models: Record<string, Model>;
isConnected?: boolean;
}
export interface ProviderWithModels {
id: string;
name: string;
api?: string;
npm?: string;
models: Model[];
source: ProviderSource;
isConnected: boolean;
}
export interface ModelSelection {
providerID: string;
modelID: string;
}
export interface OpenCodeModelState {
recent: ModelSelection[];
favorite: ModelSelection[];
variant: Record<string, string | undefined>;
}
interface ConfigProvider {
npm?: string;
name?: string;
api?: string;
options?: {
baseURL?: string;
[key: string]: unknown;
};
models?: Record<string, ConfigModel>;
}
interface ConfigModel {
id?: string;
name?: string;
limit?: {
context?: number;
output?: number;
};
[key: string]: unknown;
}
const LOCAL_PROVIDER_IDS = ["ollama", "lmstudio", "llamacpp", "jan"];
function classifyProviderSource(providerId: string, isFromConfig: boolean): ProviderSource {
if (!isFromConfig) return "builtin";
if (LOCAL_PROVIDER_IDS.includes(providerId.toLowerCase())) return "local";
return "configured";
}
export interface ProvidersResult {
export interface ProviderCatalog {
providers: Provider[];
connected: string[];
models: ModelInfo[];
}
export type ModelSelection = ModelPreferenceModel
export type OpenCodeModelState = ModelPreference
function mapModelInfo(model: ModelInfo): Model {
return {
id: model.modelID,
@@ -93,11 +52,12 @@ function mapModelInfo(model: ModelInfo): Model {
context: model.limit.context,
output: model.limit.output,
},
variants: Object.fromEntries(model.variants.map((variant) => [variant.id, variant.settings ?? {}])),
released: model.time.released,
free: isModelFree(model),
};
}
export async function getProviders(directory?: string): Promise<ProvidersResult> {
export async function getProviders(directory?: string): Promise<ProviderCatalog> {
try {
const location = openCodeLocation(directory);
const [providerResult, modelResult] = await callOpenCode((api) =>
@@ -105,39 +65,70 @@ export async function getProviders(directory?: string): Promise<ProvidersResult>
);
const activeProviders = providerResult.data.filter((provider) => provider.activation !== "disabled");
const connected = activeProviders.map((provider) => provider.id);
const connectedSet = new Set(connected);
const providers = activeProviders.map((provider) => {
const models: Record<string, Model> = {};
for (const model of modelResult.data) {
if (model.providerID !== provider.id || model.status === "deprecated" || !model.enabled) continue;
models[model.id] = mapModelInfo(model);
}
const providers = activeProviders.map((provider): Provider => {
const models = modelResult.data
.filter((model) => model.providerID === provider.id && model.status !== "deprecated" && model.enabled)
.map(mapModelInfo);
models.sort((a, b) =>
compareCatalogModels(
{ ...a, providerID: provider.id, providerName: provider.name },
{ ...b, providerID: provider.id, providerName: provider.name },
),
);
return {
id: provider.id,
name: provider.name,
models,
isConnected: connectedSet.has(provider.id),
};
});
return { providers, connected, models: modelResult.data };
providers.sort((a, b) =>
compareCatalogModels(
{ providerID: a.id, providerName: a.name },
{ providerID: b.id, providerName: b.name },
),
);
return { providers, models: modelResult.data };
} catch {
return { providers: [], connected: [], models: [] };
return { providers: [], models: [] };
}
}
export async function getOpenCodeConfigModel(directory?: string): Promise<string | null> {
export async function getOpenCodeConfiguredModel(directory?: string): Promise<string | null> {
try {
const entries = await callOpenCode((api) => api.config.get(openCodeLocation(directory)));
const ref = selectConfiguredModelRef(entries);
return ref ? `${ref.providerID}/${ref.id}` : null;
return ref ? formatOpenCodeModelRef(ref) : null;
} catch {
return null;
}
}
export async function getOpenCodeServerDefaultModel(directory?: string): Promise<ModelRef | null> {
try {
const result = await callOpenCode((api) => api.model.default(openCodeLocation(directory)));
const model = result.data;
return model ? { providerID: model.providerID, id: model.id } : null;
} catch {
return null;
}
}
export async function saveOpenCodeModelVariant(
model: ModelSelection,
value?: string | null,
): Promise<OpenCodeModelState> {
return await fetchWrapper<OpenCodeModelState>(`${API_BASE_URL}/api/providers/model-state`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variant: { model, value: value ?? null } }),
});
}
export async function getOpenCodeModelState(): Promise<OpenCodeModelState> {
return await fetchWrapper<OpenCodeModelState>(`${API_BASE_URL}/api/providers/model-state`);
}
@@ -166,131 +157,19 @@ export async function toggleOpenCodeFavoriteModel(model: ModelSelection): Promis
});
}
async function getConfiguredProviders(connectedIds: Set<string>, config?: OpenCodeConfigFile): Promise<ProviderWithModels[]> {
try {
const resolvedConfig = config ?? await settingsApi.getOpenCodeConfig();
const configured = {
...(resolvedConfig.content.providers as Record<string, ConfigProvider> | undefined),
...(resolvedConfig.content.provider as Record<string, ConfigProvider> | undefined),
};
if (Object.keys(configured).length === 0) return [];
const result: ProviderWithModels[] = [];
for (const [providerId, providerConfig] of Object.entries(configured)) {
if (!providerConfig || typeof providerConfig !== "object") continue;
const source = classifyProviderSource(providerId, true);
const models: Model[] = [];
if (providerConfig.models) {
for (const [modelId, modelConfig] of Object.entries(providerConfig.models)) {
if (!modelConfig || typeof modelConfig !== "object") continue;
models.push({
id: typeof modelConfig.id === 'string' ? modelConfig.id : modelId,
key: modelId,
name: modelConfig.name || modelId,
limit: modelConfig.limit ? {
context: modelConfig.limit.context || 0,
output: modelConfig.limit.output || 0,
} : undefined,
});
}
}
result.push({
id: providerId,
name: providerConfig.name || providerId,
api: providerConfig.api || providerConfig.options?.baseURL,
npm: providerConfig.npm,
models,
source,
isConnected: connectedIds.has(providerId),
});
}
return result;
} catch {
// Silently return empty providers on failure - graceful degradation
return [];
}
}
export async function getProvidersWithModels(directory?: string, config?: OpenCodeConfigFile): Promise<ProviderWithModels[]> {
const { providers: resolvedProviders, connected } = await getProviders(directory);
const connectedIds = new Set(connected);
const configuredProviders = await getConfiguredProviders(connectedIds, config);
const configuredById = new Map(configuredProviders.map((provider) => [provider.id, provider]));
const resolvedIds = new Set(resolvedProviders.map((provider) => provider.id));
const mergedProviders: ProviderWithModels[] = resolvedProviders.map((provider) => {
const configured = configuredById.get(provider.id);
const resolvedModels = Object.entries(provider.models || {}).map(([id, model]) => ({
...model,
id: model.id || id,
key: id,
name: model.name || id,
}));
const resolvedModelIdentifiers = new Set(
resolvedModels.flatMap((model) => [model.key, model.id]).filter((value): value is string => Boolean(value)),
);
const configuredOnlyModels = configured
? configured.models.filter(
(model) =>
!resolvedModelIdentifiers.has(model.key ?? "") && !resolvedModelIdentifiers.has(model.id),
)
: [];
return {
id: provider.id,
name: provider.name || configured?.name || provider.id,
api: provider.api ?? configured?.api,
npm: provider.npm ?? configured?.npm,
models: [...resolvedModels, ...configuredOnlyModels],
source: configured ? configured.source : "builtin",
isConnected: provider.isConnected ?? false,
};
});
const configOnlyProviders = configuredProviders.filter((provider) => !resolvedIds.has(provider.id));
const allProviders = [...mergedProviders, ...configOnlyProviders];
allProviders.sort((a, b) => {
if (a.isConnected !== b.isConnected) {
return a.isConnected ? -1 : 1;
}
return a.name.localeCompare(b.name);
});
return allProviders;
}
export async function getModel(
providerId: string,
modelId: string,
directory?: string,
): Promise<Model | null> {
const providers = await getProvidersWithModels(directory);
const provider = providers.find((p) => p.id === providerId);
if (!provider) return null;
return provider.models.find((m) => m.id === modelId) || null;
}
export function formatModelName(model: Model): string {
return model.name || model.id;
}
export function providerModelRef(provider: { id: string }, model: { id: string; key?: string }): string {
return `${provider.id}/${model.key ?? model.id}`;
return formatOpenCodeModelRef({ providerID: provider.id, id: model.key ?? model.id });
}
export function formatProviderName(
provider: Provider | ProviderWithModels,
): string {
export function modelSelectionRef(model: ModelSelection): string {
return modelPreferenceKey(model);
}
export function formatProviderName(provider: Provider): string {
return provider.name || provider.id;
}
@@ -1,6 +1,6 @@
import { memo, useCallback, useMemo, useState } from 'react'
import { Pencil, Loader2 } from 'lucide-react'
import { assistantText } from '@opencode-manager/shared/opencode'
import { assistantText, formatOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import type {
PromptAgentAttachment,
PromptFileAttachment,
@@ -524,7 +524,7 @@ const MessageRow = memo(function MessageRow({
}
if (message.type === 'model-switched') {
return <MessageDivider label={`Model: ${message.model.providerID}/${message.model.id}`} />
return <MessageDivider label={`Model: ${formatOpenCodeModelRef(message.model)}`} />
}
if (message.type === 'location-switched') {
@@ -185,11 +185,11 @@ describe('PromptInput command submission', () => {
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
modelString: 'anthropic/claude-sonnet-4',
setModel: vi.fn(),
setActiveModel: vi.fn(),
setActiveAgent: vi.fn(),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelStateLoading: false,
isModelReady: true,
})
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: mocks.cycleVariant })
mocks.useSessionAgent.mockReturnValue({ agent: 'build' })
@@ -233,6 +233,28 @@ describe('PromptInput command submission', () => {
other.remove()
})
it('disables submit and does not run a command while the model is not ready', async () => {
mocks.useModelSelection.mockReturnValue({
model: null,
modelString: null,
setModel: vi.fn(),
setActiveAgent: vi.fn(),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelReady: false,
})
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: '/review' } })
const sendButton = screen.getByTitle('Send')
expect(sendButton).toBeDisabled()
fireEvent.click(sendButton)
expect(mocks.runCommand).not.toHaveBeenCalled()
})
it('sends parsed command attachments and offsets to runCommand without injecting the selected agent', async () => {
const { container } = renderComponent()
@@ -185,11 +185,11 @@ describe('PromptInput goal mode', () => {
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
modelString: 'anthropic/claude-sonnet-4',
setModel: vi.fn(),
setActiveModel: vi.fn(),
setActiveAgent: vi.fn(),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelStateLoading: false,
isModelReady: true,
})
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: mocks.cycleVariant })
mocks.useSessionAgent.mockReturnValue({ agent: 'build' })
@@ -171,11 +171,11 @@ describe('PromptInput agent mention submission', () => {
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
modelString: 'anthropic/claude-sonnet-4',
setModel: vi.fn(),
setActiveModel: vi.fn(),
setActiveAgent: vi.fn(),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelStateLoading: false,
isModelReady: true,
})
mocks.useVariants.mockReturnValue({ hasVariants: false, currentVariant: null, cycleVariant: vi.fn() })
mocks.useSessionAgent.mockReturnValue({ agent: 'build' })
@@ -198,11 +198,11 @@ describe('PromptInput STT Gesture Tests', () => {
model: null,
modelString: 'test-model',
setModel: vi.fn(),
setActiveModel: vi.fn().mockReturnValue(false),
setActiveAgent: vi.fn(),
recentModels: [],
favoriteModels: [],
toggleFavorite: vi.fn(),
isModelStateLoading: false,
isModelReady: true,
})
mocks.useVariants.mockReturnValue({
hasVariants: false,
+25 -50
View File
@@ -9,7 +9,6 @@ import { useSessionAgent } from '@/hooks/useSessionAgent'
import { useSTT } from '@/hooks/useSTT'
import { useUserBash } from '@/stores/userBashStore'
import { useModelStore } from '@/stores/modelStore'
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { useUIState } from '@/stores/uiStateStore'
import { useSendErrorStore } from '@/stores/sendErrorStore'
@@ -36,11 +35,11 @@ import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQu
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
import { randomId } from '@/lib/utils'
import { showToast } from '@/lib/toast'
import { formatModelName } from '@/api/providers'
import { findModelInfo } from '@opencode-manager/shared/opencode'
import { useProviders } from '@/hooks/useProviders'
import type { CommandInfo, ModelRef } from '@opencode-manager/shared/opencode'
import type { CommandInfo } from '@opencode-manager/shared/opencode'
import type { FileAttachmentInfo, ImageAttachment } from '@/api/types'
import { isBuiltinCommand, type CommandActions, type PageCommandActions } from '@/lib/builtinCommands'
@@ -313,6 +312,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}
const handleSubmit = async () => {
if (!isModelReady) return
if (!prompt.trim() && imageAttachments.length === 0) return
if (startGoal.isPending) return
@@ -336,7 +336,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
model: modelRef,
model: modelRef ?? undefined,
agent: currentMode,
delivery: 'queue',
},
@@ -345,9 +345,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
}
)
setStoredAgent(sessionID, currentMode)
if (model) {
setStoredModel({ providerID: model.providerID, modelID: model.modelID })
}
return
}
@@ -429,7 +426,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
files: parsed.files,
agents: parsed.agents,
skills: parsed.skills,
model: modelRef,
model: modelRef ?? undefined,
agent: currentMode,
},
{
@@ -446,9 +443,6 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
onScrollToBottom()
setStoredAgent(sessionID, currentMode)
if (model) {
setStoredModel({ providerID: model.providerID, modelID: model.modelID })
}
}
handleSubmitRef.current = handleSubmit
@@ -1084,33 +1078,23 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
}
}
const appliedSessionModelRef = useRef<string | undefined>(undefined)
const { data: providersData } = useProviders(directory)
const { model, modelString, setModel: setStoredModel, restoreSessionModel } = useModelSelection(directory)
const setStoreVariant = useModelStore((state) => state.setVariant)
const clearStoreVariant = useModelStore((state) => state.clearVariant)
const modelSelectionSession = useMemo(
() => (sessionID
? { id: sessionID, agent: sessionAgent.sessionAgentId, model: sessionAgent.modelRef }
: undefined),
[sessionID, sessionAgent.sessionAgentId, sessionAgent.modelRef],
)
const sessionModelSyncKey = sessionID ? `${directory ?? ''}:${sessionID}` : undefined
const { model, modelString, modelRef, setActiveAgent, isModelReady } = useModelSelection(directory, modelSelectionSession)
useEffect(() => {
if (!sessionModelSyncKey) return
if (!sessionAgent.model) return
const sessionSelectionKey = `${sessionModelSyncKey}|${sessionAgent.model.providerID}/${sessionAgent.model.modelID}|${sessionAgent.variant ?? ''}`
if (appliedSessionModelRef.current === sessionSelectionKey) return
appliedSessionModelRef.current = sessionSelectionKey
restoreSessionModel(sessionAgent.model)
if (sessionAgent.variant) {
setStoreVariant(sessionAgent.model, sessionAgent.variant)
} else {
clearStoreVariant(sessionAgent.model)
}
}, [clearStoreVariant, sessionAgent.model, sessionAgent.variant, sessionModelSyncKey, restoreSessionModel, setStoreVariant])
setActiveAgent({
id: currentMode,
model: agents.find((agent) => agent.id === currentMode)?.model,
})
}, [agents, currentMode, setActiveAgent])
const currentModel = modelString || ''
const displayModelName = useMemo(() => {
@@ -1118,30 +1102,19 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
return currentModel
}
const provider = providersData?.providers.find((item) => item.id === model.providerID)
const modelData = provider?.models?.[model.modelID]
const info = findModelInfo(providersData?.models ?? [], model)
return modelData ? formatModelName(modelData) : model.modelID || currentModel
return info?.name || model.modelID || currentModel
}, [currentModel, model, providersData])
const isMobile = useMobile()
const { setShowDialog, hasForSession: hasPermissionsForSession } = usePermissions()
const hasPendingPermissionForSession = hasPermissionsForSession(sessionID)
const { hasVariants, currentVariant, cycleVariant } = useVariants(directory)
const modelRef = useMemo<ModelRef | undefined>(
() => model
? { providerID: model.providerID, id: model.modelID, ...(currentVariant ? { variant: currentVariant } : {}) }
: undefined,
[model, currentVariant],
)
const { hasVariants, currentVariant, cycleVariant } = useVariants(directory, modelSelectionSession)
const handleAgentChange = useCallback((agentId: string) => {
setLocalMode(agentId)
setStoredAgent(sessionID, agentId)
const agent = agents.find(a => a.id === agentId)
if (agent?.model) {
setStoredModel({ providerID: agent.model.providerID, modelID: agent.model.id })
}
}, [agents, sessionID, setStoredAgent, setStoredModel])
}, [sessionID, setStoredAgent])
const handleCycleVariant = useCallback(() => {
if (!hasVariants) {
@@ -1172,7 +1145,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
const { executeCommand } = useCommandHandler({
sessionID,
directory,
model: modelRef,
model: modelRef ?? undefined,
currentAgent: currentMode,
actions: commandActionsWithPrompt,
})
@@ -1380,6 +1353,7 @@ return (
directory={directory}
open={isModelPickerOpen}
onOpenChange={setIsModelPickerOpen}
session={modelSelectionSession}
/>
</>
) : (
@@ -1412,6 +1386,7 @@ return (
directory={directory}
open={isModelPickerOpen}
onOpenChange={setIsModelPickerOpen}
session={modelSelectionSession}
>
{!isSessionActive && !hideSecondaryButtons && (
<button
@@ -1481,7 +1456,7 @@ return (
<button
data-submit-prompt
onClick={hasPendingPermissionForSession ? () => setShowDialog(true) : handleSubmit}
disabled={hasPendingPermissionForSession ? false : ((!prompt.trim() && imageAttachments.length === 0) || (isPromptSubmitPending && !isStreamingResponse))}
disabled={hasPendingPermissionForSession ? false : (!isModelReady || (!prompt.trim() && imageAttachments.length === 0) || (isPromptSubmitPending && !isStreamingResponse))}
className={`px-4 md:px-5 py-1.5 md:py-2 rounded-lg text-sm font-medium transition-colors dark:border flex-shrink-0 min-w-[52px] ${
hasPendingPermissionForSession
? 'bg-highlight hover:bg-highlight/90 border-highlight text-highlight-foreground ring-highlight/20'
@@ -6,7 +6,7 @@ import { ApiKeyDialog } from './ApiKeyDialog'
import { providerCredentialsApi } from '@/api/providers'
import { oauthApi } from '@/api/oauth'
import { FetchError } from '@/api/fetchWrapper'
import type { ProviderWithModels } from '@/api/providers'
import type { Provider } from '@/api/providers'
vi.mock('@/api/providers', () => ({
providerCredentialsApi: {
@@ -20,14 +20,14 @@ vi.mock('@/api/oauth', () => ({
},
}))
function providerFixture(id: string, name: string): ProviderWithModels {
return { id, name, models: [], source: 'builtin', isConnected: false }
function providerFixture(id: string, name: string): Provider {
return { id, name, models: [] }
}
const azureProvider = providerFixture('azure', 'Azure')
const anthropicProvider = providerFixture('anthropic', 'Anthropic')
function renderDialog(provider: ProviderWithModels, onSuccess = vi.fn()) {
function renderDialog(provider: Provider, onSuccess = vi.fn()) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
render(
<QueryClientProvider client={queryClient}>
+3 -15
View File
@@ -10,9 +10,9 @@ import {
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Loader2, Key, ExternalLink } from "lucide-react";
import { Loader2, Key } from "lucide-react";
import { providerCredentialsApi } from "@/api/providers";
import type { ProviderWithModels } from "@/api/providers";
import type { Provider } from "@/api/providers";
import { type FormAnswer, type FormValue, type IntegrationKeyMethod } from "@/api/oauth";
import { buildAnswer, hasMissingAnswers, methodIdentifier, resolveAnswers, setAnswerValue, visibleFields } from "@/lib/formFields";
import { mapOAuthError } from "@/lib/oauthErrors";
@@ -22,7 +22,7 @@ import { useProviderAuthMethods } from "@/hooks/useProviderAuthMethods";
interface ApiKeyDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
provider: ProviderWithModels | null;
provider: Provider | null;
onSuccess: () => void;
mode?: 'add' | 'edit';
}
@@ -147,18 +147,6 @@ export function ApiKeyDialog({
{error && (
<p className="text-sm text-destructive">{error}</p>
)}
{provider.api && (
<a
href={provider.api}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ExternalLink className="h-3 w-3" />
Get an API key
</a>
)}
</div>
<DialogFooter>
@@ -0,0 +1,111 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ModelCombobox } from './ModelCombobox'
import type { Provider } from '@/api/providers'
const mocks = vi.hoisted(() => ({
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
}))
vi.mock('@/hooks/useProviders', () => ({
useProviders: mocks.useProviders,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
const providers: Provider[] = [
{
id: 'anthropic',
name: 'Anthropic',
models: [
{ id: 'claude-opus-5-5', key: 'claude-opus-5-5-fast', name: 'Claude Opus 5.5', released: 0, free: false },
{ id: 'claude-sonnet', key: 'claude-sonnet', name: 'Claude Sonnet', released: 0, free: false },
{ id: 'claude-haiku', key: 'claude-haiku', name: 'Claude Haiku', released: 0, free: false },
],
},
{
id: 'openai',
name: 'OpenAI',
models: [
{ id: 'gpt-5', key: 'gpt-5', name: 'GPT-5', released: 0, free: false },
{ id: 'gpt-4o', key: 'gpt-4o', name: 'GPT-4o', released: 0, free: false },
],
},
]
describe('ModelCombobox', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useProviders.mockReturnValue({ data: { providers, models: [] } })
mocks.useOpenCodeModelState.mockReturnValue({
data: {
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }],
recent: [{ providerID: 'anthropic', modelID: 'claude-opus-5-5-fast' }],
variant: {},
},
})
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: 'openai/gpt-5' })
})
it('lists Default, Favorites, Recent, then providers in that order', async () => {
const user = userEvent.setup()
render(<ModelCombobox value="" onChange={vi.fn()} ariaLabel="Model" />)
await user.click(screen.getByRole('combobox', { name: 'Model' }))
const listbox = screen.getByRole('listbox')
const titles = ['Default', 'Favorites', 'Recent', 'Anthropic', 'OpenAI'].map((title) =>
within(listbox).getByText(title),
)
for (let index = 1; index < titles.length; index += 1) {
const follows = titles[index - 1].compareDocumentPosition(titles[index]) & Node.DOCUMENT_POSITION_FOLLOWING
expect(follows).toBeTruthy()
}
})
it('selects an aliased model by its OpenCode key', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(<ModelCombobox value="" onChange={onChange} ariaLabel="Model" />)
await user.click(screen.getByRole('combobox', { name: 'Model' }))
await user.click(screen.getByRole('option', { name: /Claude Opus 5\.5/ }))
expect(onChange).toHaveBeenCalledWith('anthropic/claude-opus-5-5-fast')
})
it('clears the value', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(<ModelCombobox value="anthropic/claude-sonnet" onChange={onChange} ariaLabel="Model" showClear />)
await user.click(screen.getByRole('button', { name: 'Clear' }))
expect(onChange).toHaveBeenCalledWith('')
})
it('shows the resolved default model when the value is empty', () => {
render(<ModelCombobox value="" onChange={vi.fn()} ariaLabel="Model" />)
expect(screen.getByRole('combobox', { name: 'Model' })).toHaveValue('Default: GPT-5')
})
it('saves an empty value when the Default entry is chosen', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(<ModelCombobox value="" onChange={onChange} ariaLabel="Model" />)
await user.click(screen.getByRole('combobox', { name: 'Model' }))
await user.click(screen.getByRole('option', { name: 'Default: GPT-5' }))
expect(onChange).toHaveBeenCalledWith('')
expect(onChange).not.toHaveBeenCalledWith('openai/gpt-5')
})
})
@@ -0,0 +1,59 @@
import { useCallback, useMemo } from 'react'
import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
import { useModelSections } from '@/hooks/useModelSections'
import { filterModelSections, toModelComboboxOptions } from '@/lib/modelSections'
interface ModelComboboxProps {
value: string
onChange: (value: string) => void
directory?: string
enabled?: boolean
placeholder?: string
allowCustomValue?: boolean
showClear?: boolean
ariaLabel?: string
id?: string
disabled?: boolean
className?: string
}
export function ModelCombobox({
value,
onChange,
directory,
enabled = true,
placeholder,
allowCustomValue,
showClear,
ariaLabel,
id,
disabled,
className,
}: ModelComboboxProps) {
const { sections, defaultModel } = useModelSections(directory, { enabled })
const options = useMemo(() => toModelComboboxOptions(sections, defaultModel), [sections, defaultModel])
const filterOptions = useCallback(
(_options: ComboboxOption[], query: string) =>
toModelComboboxOptions(filterModelSections(sections, query), defaultModel),
[sections, defaultModel],
)
return (
<Combobox
id={id}
value={value}
onChange={onChange}
options={options}
filterOptions={filterOptions}
placeholder={placeholder}
allowCustomValue={allowCustomValue}
showClear={showClear}
ariaLabel={ariaLabel}
disabled={disabled}
className={className}
listClassName="max-h-[min(24rem,60vh)]"
/>
)
}
@@ -1,21 +1,18 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ModelQuickSelect } from './ModelQuickSelect'
import { buildModelSections } from '@/lib/modelSections'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
import type { Provider } from '@/api/providers'
const mocks = vi.hoisted(() => ({
useModelSelection: vi.fn(),
useModelSections: vi.fn(),
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: () => ({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
modelString: 'anthropic/claude-sonnet-4',
recentModels: [],
favoriteModels: [],
setModel: vi.fn(),
setActiveModel: vi.fn(),
restoreSessionModel: vi.fn(),
toggleFavorite: vi.fn(),
removeRecentModel: vi.fn(),
isModelStateLoading: false,
}),
useModelSelection: mocks.useModelSelection,
}))
vi.mock('@/hooks/useVariants', () => ({
@@ -29,23 +26,103 @@ vi.mock('@/hooks/useVariants', () => ({
}),
}))
vi.mock('@/hooks/useProviders', () => ({
useProviders: () => ({
data: {
providers: [
{
id: 'anthropic',
name: 'Anthropic',
isConnected: true,
models: {
'claude-sonnet-4': { id: 'claude-sonnet-4', name: 'Claude Sonnet 4' },
},
},
],
},
}),
vi.mock('@/hooks/useModelSections', () => ({
useModelSections: mocks.useModelSections,
}))
const providers: Provider[] = [
{
id: 'opencode-go',
name: 'OpenCode Go',
models: [{ id: 'go-1', key: 'go-1', name: 'Go Model One', released: 0, free: false }],
},
{
id: 'opencode',
name: 'OpenCode',
models: [{ id: 'zen-1', key: 'zen-1', name: 'Zen One', released: 0, free: false }],
},
{
id: 'anthropic',
name: 'Anthropic',
models: [
{ id: 'claude-sonnet-4', key: 'claude-sonnet-4', name: 'Claude Sonnet 4', released: 0, free: false },
{ id: 'claude-opus-5-5', key: 'claude-opus-5-5-fast', name: 'Claude Opus 5.5', released: 0, free: false },
],
},
{
id: 'openai',
name: 'OpenAI',
models: [{ id: 'gpt-5', key: 'gpt-5', name: 'GPT-5', released: 0, free: false }],
},
]
interface Selection {
providerID: string
modelID: string
}
function selection(providerID: string, modelID: string): Selection {
return { providerID, modelID }
}
interface SelectionOptions {
favorite?: Selection[]
recent?: Selection[]
model?: Selection | null
info?: ModelInfo
}
function setModelSelection(options: SelectionOptions = {}) {
const favorite = options.favorite ?? []
const recent = options.recent ?? []
const model = options.model ?? null
const setModel = vi.fn()
const toggleFavorite = vi.fn()
const removeRecentModel = vi.fn()
const modelState = { favorite, recent, variant: {} }
mocks.useModelSelection.mockReturnValue({
model,
modelString: model ? `${model.providerID}/${model.modelID}` : null,
info: options.info,
activeAgent: null,
recentModels: recent,
favoriteModels: favorite,
configured: null,
modelState,
setModel,
setActiveAgent: vi.fn(),
toggleFavorite,
removeRecentModel,
isModelReady: true,
})
mocks.useModelSections.mockReturnValue({
providers,
sections: buildModelSections(providers, modelState),
defaultModel: null,
modelState,
isLoading: false,
})
return { setModel, toggleFavorite, removeRecentModel }
}
function sectionFor(title: string) {
const heading = screen.getByText(title)
const section = heading.closest('section')
if (!section) throw new Error(`No section for ${title}`)
return section
}
function firstOf(name: string) {
return screen.getAllByText(name)[0]
}
function isBefore(first: HTMLElement, second: HTMLElement) {
return (first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0
}
const DARK_ONLY_CLASS = /text-white|bg-zinc-950|bg-white\/|border-white\//
function findDarkOnlyClassOffenders(root: HTMLElement) {
@@ -66,6 +143,18 @@ async function openSelector(user: ReturnType<typeof userEvent.setup>) {
return screen.findByRole('dialog', { name: 'Select model' })
}
beforeAll(() => {
Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
configurable: true,
get: () => 600,
})
})
beforeEach(() => {
vi.clearAllMocks()
setModelSelection()
})
describe('ModelQuickSelect theme tokens', () => {
it('renders the quick view with theme tokens instead of dark-only classes', async () => {
const user = userEvent.setup()
@@ -113,12 +202,158 @@ describe('ModelQuickSelect controlled open', () => {
render(<ModelQuickSelect open onOpenChange={onOpenChange} />)
await user.click(screen.getByRole('button', { name: /More models/ }))
expect(screen.getByPlaceholderText('Search providers...')).toBeInTheDocument()
expect(screen.getByPlaceholderText('Search models...')).toBeInTheDocument()
await user.keyboard('{Escape}')
expect(onOpenChange).toHaveBeenCalledWith(false)
expect(screen.getByRole('button', { name: /More models/ })).toBeInTheDocument()
expect(screen.queryByPlaceholderText('Search providers...')).not.toBeInTheDocument()
expect(screen.queryByPlaceholderText('Search models...')).not.toBeInTheDocument()
})
})
describe('ModelQuickSelect quick view', () => {
it('lists every valid favorite in model.json order', () => {
setModelSelection({ favorite: [selection('anthropic', 'claude-sonnet-4'), selection('openai', 'gpt-5')] })
render(<ModelQuickSelect open />)
const section = sectionFor('Favorites')
expect(section.textContent).toContain('Claude Sonnet 4')
expect(section.textContent).toContain('GPT-5')
expect(section.textContent!.indexOf('Claude Sonnet 4')).toBeLessThan(section.textContent!.indexOf('GPT-5'))
})
it('lists the valid recents that are not favorites', () => {
setModelSelection({
favorite: [selection('anthropic', 'claude-sonnet-4')],
recent: [selection('anthropic', 'claude-sonnet-4'), selection('openai', 'gpt-5')],
})
render(<ModelQuickSelect open />)
const section = sectionFor('Recent')
expect(section.textContent).toContain('GPT-5')
expect(section.textContent).not.toContain('Claude Sonnet 4')
})
it('keeps the active model listed with its check mark', () => {
setModelSelection({
favorite: [selection('anthropic', 'claude-sonnet-4')],
model: selection('anthropic', 'claude-sonnet-4'),
})
render(<ModelQuickSelect open />)
const section = sectionFor('Favorites')
expect(section.textContent).toContain('Claude Sonnet 4')
expect(section.querySelector('.text-highlight')).not.toBeNull()
})
it('shows the first catalog models under Models when there are no favorites or recents', () => {
render(<ModelQuickSelect open />)
const section = sectionFor('Models')
expect(section.textContent).toContain('Go Model One')
expect(section.textContent).toContain('Zen One')
expect(section.textContent).toContain('Claude Sonnet 4')
expect(section.textContent).not.toContain('GPT-5')
})
it('shows the catalog name of an active model that is not in the provider sections', () => {
setModelSelection({
model: selection('openai', 'gpt-5-legacy'),
info: { providerID: 'openai', id: 'gpt-5-legacy', name: 'GPT-5 Legacy' } as ModelInfo,
})
render(<ModelQuickSelect open />)
expect(screen.getByText('GPT-5 Legacy')).toBeInTheDocument()
})
it('calls the favorite and remove-recent handlers', async () => {
const user = userEvent.setup()
const { toggleFavorite, removeRecentModel } = setModelSelection({
favorite: [selection('anthropic', 'claude-sonnet-4')],
recent: [selection('openai', 'gpt-5')],
})
render(<ModelQuickSelect open />)
await user.click(screen.getByRole('button', { name: 'Remove from favorites' }))
expect(toggleFavorite).toHaveBeenCalledWith(selection('anthropic', 'claude-sonnet-4'))
await user.click(screen.getByRole('button', { name: 'Remove from recent' }))
expect(removeRecentModel).toHaveBeenCalledWith(selection('openai', 'gpt-5'))
})
})
describe('ModelQuickSelect more models', () => {
it('lists providers in catalog order', async () => {
const user = userEvent.setup()
render(<ModelQuickSelect open />)
await user.click(screen.getByRole('button', { name: /More models/ }))
const labels = ['OpenCode Go', 'OpenCode', 'Anthropic', 'OpenAI'].map(firstOf)
for (let index = 1; index < labels.length; index += 1) {
expect(isBefore(labels[index - 1], labels[index])).toBe(true)
}
})
it('keeps a favorite visible in its provider list and count', async () => {
const user = userEvent.setup()
setModelSelection({ favorite: [selection('openai', 'gpt-5')] })
render(<ModelQuickSelect open />)
await user.click(screen.getByRole('button', { name: /More models/ }))
const providerButton = screen.getAllByRole('button', { name: /OpenAI 1 model/ })[0]
expect(providerButton).toBeInTheDocument()
await user.click(providerButton)
expect(screen.getAllByText('GPT-5').length).toBeGreaterThan(0)
})
it('searches into one flat list with favorites first', async () => {
const user = userEvent.setup()
setModelSelection({ favorite: [selection('openai', 'gpt-5')] })
render(<ModelQuickSelect open />)
await user.click(screen.getByRole('button', { name: /More models/ }))
await user.type(screen.getByPlaceholderText('Search models...'), '5')
const favorite = (await screen.findAllByText('GPT-5'))[0]
const other = screen.getAllByText('Claude Opus 5.5')[0]
expect(screen.getAllByText('GPT-5')).toHaveLength(1)
expect(isBefore(favorite, other)).toBe(true)
})
it('scopes the search to the selected provider', async () => {
const user = userEvent.setup()
render(<ModelQuickSelect open />)
await user.click(screen.getByRole('button', { name: /More models/ }))
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
await user.type(screen.getByPlaceholderText('Search models...'), '5')
expect((await screen.findAllByText('Claude Opus 5.5')).length).toBeGreaterThan(0)
expect(screen.queryByText('GPT-5')).not.toBeInTheDocument()
})
it('selects a model and closes the sheet', async () => {
const user = userEvent.setup()
const { setModel } = setModelSelection({ favorite: [selection('anthropic', 'claude-sonnet-4')] })
render(<ModelQuickSelect open />)
const section = sectionFor('Favorites')
await user.click(within(section).getByRole('button', { name: /Claude Sonnet 4/ }))
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-sonnet-4'))
})
})
+148 -294
View File
@@ -1,9 +1,9 @@
import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { Check, ChevronDown, ChevronLeft, ChevronRight, Clock, Search, Star, Trash2, X } from 'lucide-react'
import { useModelSelection } from '@/hooks/useModelSelection'
import { Check, ChevronDown, ChevronLeft, ChevronRight, Search, Star, Trash2, X, type LucideIcon } from 'lucide-react'
import { useModelSelection, type ModelSelectionSession } from '@/hooks/useModelSelection'
import { useModelSections } from '@/hooks/useModelSections'
import { useVariants } from '@/hooks/useVariants'
import { formatModelName, formatProviderName } from '@/api/providers'
import { useProviders } from '@/hooks/useProviders'
import { modelSelectionRef, type Model } from '@/api/providers'
import { BottomSheet } from '@/components/ui/bottom-sheet'
import {
DropdownMenu,
@@ -13,7 +13,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import type { Model, Provider } from '@/api/providers'
import { buildModelSections, filterModelSections, type ModelOption } from '@/lib/modelSections'
interface ModelQuickSelectProps {
directory?: string
@@ -21,6 +21,7 @@ interface ModelQuickSelectProps {
children?: React.ReactNode
open?: boolean
onOpenChange?: (open: boolean) => void
session?: ModelSelectionSession
}
interface ModelListItem {
@@ -29,13 +30,12 @@ interface ModelListItem {
key: string
displayName: string
providerName: string
searchText: string
model?: Model
}
interface ModelSection {
interface QuickModelSection {
title: string
icon: React.ReactNode
icon?: LucideIcon
models: ModelListItem[]
}
@@ -43,8 +43,6 @@ interface ProviderListItem {
id: string
label: string
count: number
isConnected: boolean
searchText: string
}
interface VirtualizedListProps<T> {
@@ -60,50 +58,15 @@ interface VirtualizedListProps<T> {
const MODEL_OPTION_ROW_HEIGHT = 60
const VIRTUAL_LIST_OVERSCAN = 8
const EMPTY_PROVIDERS: Provider[] = []
const EMPTY_MODELS: ModelListItem[] = []
const EMPTY_MODELS_BY_PROVIDER = new Map<string, ModelListItem[]>()
const EMPTY_PROVIDER_ITEMS: ProviderListItem[] = []
const ICON_BUTTON_CLASS =
'flex h-9 w-9 items-center justify-center rounded-full border border-border bg-muted text-foreground/80 hover:bg-accent'
function createSearchText(...values: string[]) {
return values.join(' ').toLowerCase()
}
function formatModelCount(count: number) {
return `${count} ${count === 1 ? 'model' : 'models'}`
}
function createModelListItem(provider: Provider, modelID: string, model: Model): ModelListItem {
const providerName = formatProviderName(provider)
const displayName = formatModelName(model)
return {
providerID: provider.id,
modelID,
key: `${provider.id}/${modelID}`,
displayName,
providerName,
searchText: createSearchText(displayName, modelID, providerName, provider.id),
model,
}
}
function createFallbackModelListItem(providerID: string, modelID: string): ModelListItem {
return {
providerID,
modelID,
key: `${providerID}/${modelID}`,
displayName: modelID,
providerName: providerID,
searchText: createSearchText(modelID, providerID),
}
}
function getSelectionKey(selection: { providerID: string, modelID: string }) {
return `${selection.providerID}/${selection.modelID}`
}
function VirtualizedList<T>({
items,
itemHeight,
@@ -193,6 +156,7 @@ export function ModelQuickSelect({
children,
open,
onOpenChange,
session,
}: ModelQuickSelectProps) {
const [internalIsOpen, setInternalIsOpen] = useState(false)
const isOpen = open ?? internalIsOpen
@@ -200,220 +164,107 @@ export function ModelQuickSelect({
const [searchQuery, setSearchQuery] = useState('')
const deferredSearchQuery = useDeferredValue(searchQuery)
const [selectedProviderId, setSelectedProviderId] = useState<string | null>(null)
const { model, modelString, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(directory)
const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(directory)
const { model, modelString, info, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(directory, session)
const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(directory, session)
const { data: providersData } = useProviders(directory)
const { providers, sections } = useModelSections(directory)
const providers = providersData?.providers ?? EMPTY_PROVIDERS
const catalogSections = useMemo(() => buildModelSections(providers, undefined), [providers])
const catalogOptions = useMemo(
() => catalogSections.flatMap((section) => section.options),
[catalogSections],
)
const toModelListItem = useCallback(
(option: ModelOption): ModelListItem => ({
providerID: option.providerID,
modelID: option.modelID,
key: option.value,
displayName: option.label,
providerName: option.providerName,
model: option.model,
}),
[],
)
const favoriteKeySet = useMemo(() => {
return new Set(favoriteModels.map(getSelectionKey))
return new Set(favoriteModels.map(modelSelectionRef))
}, [favoriteModels])
const recentKeySet = useMemo(() => {
return new Set(recentModels.map(getSelectionKey))
return new Set(recentModels.map(modelSelectionRef))
}, [recentModels])
const { providerById, providerItems } = useMemo(() => {
const nextProviderById = new Map<string, Provider>()
const nextProviderItems: ProviderListItem[] = []
const browseData = useMemo(() => {
if (!showAllModels) return null
for (const provider of providers) {
const providerName = formatProviderName(provider)
const count = Object.keys(provider.models || {}).length
nextProviderById.set(provider.id, provider)
const rowsByKey = new Map<string, ModelListItem>()
const modelsByProviderId = new Map<string, ModelListItem[]>()
const providerItems: ProviderListItem[] = []
const allModels: ModelListItem[] = []
if (count > 0) {
nextProviderItems.push({
id: provider.id,
label: providerName,
count,
isConnected: provider.isConnected ?? false,
searchText: createSearchText(providerName, provider.id),
})
}
for (const section of catalogSections) {
if (!section.providerID) continue
const items = section.options.map(toModelListItem)
for (const item of items) rowsByKey.set(item.key, item)
providerItems.push({ id: section.providerID, label: section.title, count: items.length })
modelsByProviderId.set(section.providerID, items)
allModels.push(...items)
}
nextProviderItems.sort((a, b) => {
if (a.isConnected !== b.isConnected) {
return a.isConnected ? -1 : 1
}
return a.label.localeCompare(b.label)
})
return { rowsByKey, modelsByProviderId, providerItems, allModels }
}, [showAllModels, catalogSections, toModelListItem])
return {
providerById: nextProviderById,
providerItems: nextProviderItems,
}
}, [providers])
const quickSections = useMemo((): QuickModelSection[] => {
const favorites = sections.find((section) => section.key === 'favorites')
const recent = sections.find((section) => section.key === 'recent')
const result: QuickModelSection[] = []
const toModelListItem = useCallback((selection: { providerID: string, modelID: string }): ModelListItem => {
const provider = providerById.get(selection.providerID)
const providerModel = provider?.models?.[selection.modelID]
if (!provider || !providerModel) {
return createFallbackModelListItem(selection.providerID, selection.modelID)
if (favorites) {
result.push({ title: favorites.title, icon: favorites.icon, models: favorites.options.map(toModelListItem) })
}
return createModelListItem(provider, selection.modelID, providerModel)
}, [providerById])
if (recent) {
result.push({ title: recent.title, icon: recent.icon, models: recent.options.map(toModelListItem) })
}
const quickFallbackModels = useMemo(() => {
const result: ModelListItem[] = []
for (const providerItem of providerItems) {
const provider = providerById.get(providerItem.id)
if (!provider) continue
for (const [modelID, providerModel] of Object.entries(provider.models || {})) {
result.push(createModelListItem(provider, modelID, providerModel))
if (result.length === 3) return result
if (result.length === 0) {
const models = catalogOptions.slice(0, 3).map(toModelListItem)
if (models.length > 0) {
result.push({ title: 'Models', icon: ChevronRight, models })
}
}
return result
}, [providerById, providerItems])
}, [sections, catalogOptions, toModelListItem])
const { allModels, modelsByProviderId } = useMemo(() => {
if (!showAllModels) {
return {
allModels: EMPTY_MODELS,
modelsByProviderId: EMPTY_MODELS_BY_PROVIDER,
}
}
const isSearching = deferredSearchQuery.trim().length > 0
const nextAllModels: ModelListItem[] = []
const nextModelsByProviderId = new Map<string, ModelListItem[]>()
for (const provider of providers) {
const providerModels: ModelListItem[] = []
for (const [modelID, providerModel] of Object.entries(provider.models || {})) {
const item = createModelListItem(provider, modelID, providerModel)
nextAllModels.push(item)
providerModels.push(item)
}
if (providerModels.length > 0) {
nextModelsByProviderId.set(provider.id, providerModels)
}
}
return {
allModels: nextAllModels,
modelsByProviderId: nextModelsByProviderId,
}
}, [providers, showAllModels])
const favoriteModelsWithNames = useMemo(() => {
return favoriteModels
.filter(favorite => `${favorite.providerID}/${favorite.modelID}` !== modelString)
.slice(0, 5)
.map(toModelListItem)
}, [favoriteModels, modelString, toModelListItem])
const recentModelsWithNames = useMemo(() => {
return recentModels
.filter(recent => {
const key = getSelectionKey(recent)
return key !== modelString && !favoriteKeySet.has(key)
})
.slice(0, 5)
.map(toModelListItem)
}, [favoriteKeySet, recentModels, modelString, toModelListItem])
const quickModels = useMemo(() => {
const items = [
...(model ? [toModelListItem(model)] : []),
...favoriteModelsWithNames,
...recentModelsWithNames,
...quickFallbackModels,
]
const seenKeys = new Set<string>()
const result: ModelListItem[] = []
for (const item of items) {
if (seenKeys.has(item.key)) continue
seenKeys.add(item.key)
result.push(item)
if (result.length === 3) break
}
return result
}, [favoriteModelsWithNames, model, quickFallbackModels, recentModelsWithNames, toModelListItem])
const quickSections = useMemo((): ModelSection[] => {
const sections: ModelSection[] = []
if (favoriteModelsWithNames.length > 0) {
sections.push({
title: 'Favorites',
icon: <Star className="h-3.5 w-3.5" />,
models: favoriteModelsWithNames,
})
}
if (recentModelsWithNames.length > 0) {
sections.push({
title: 'Recent',
icon: <Clock className="h-3.5 w-3.5" />,
models: recentModelsWithNames,
})
}
if (sections.length === 0 && quickModels.length > 0) {
sections.push({
title: 'Models',
icon: <ChevronRight className="h-3.5 w-3.5" />,
models: quickModels,
})
}
return sections
}, [favoriteModelsWithNames, quickModels, recentModelsWithNames])
const selectedProviderModels = useMemo(() => {
if (!selectedProviderId) return []
return modelsByProviderId.get(selectedProviderId) ?? []
}, [modelsByProviderId, selectedProviderId])
const filteredSelectedProviderModels = useMemo(() => {
const query = deferredSearchQuery.trim().toLowerCase()
if (!query) return selectedProviderModels
return selectedProviderModels.filter(item => item.searchText.includes(query))
}, [deferredSearchQuery, selectedProviderModels])
const filteredAllModels = useMemo(() => {
const query = deferredSearchQuery.trim().toLowerCase()
const items = selectedProviderId
? selectedProviderModels
: allModels
if (!query) return items
return items.filter(item => item.searchText.includes(query))
}, [allModels, deferredSearchQuery, selectedProviderId, selectedProviderModels])
const filteredProviderItems = useMemo(() => {
const query = deferredSearchQuery.trim().toLowerCase()
if (!query) return providerItems
return providerItems.filter(provider => provider.searchText.includes(query))
}, [deferredSearchQuery, providerItems])
const connectedProviderItems = useMemo(
() => filteredProviderItems.filter(p => p.isConnected),
[filteredProviderItems]
const searchSections = useMemo(
() =>
selectedProviderId
? catalogSections.filter((section) => section.providerID === selectedProviderId)
: sections,
[selectedProviderId, catalogSections, sections],
)
const availableProviderItems = useMemo(
() => filteredProviderItems.filter(p => !p.isConnected),
[filteredProviderItems]
const searchResults = useMemo(() => {
if (!isSearching) return EMPTY_MODELS
return filterModelSections(searchSections, deferredSearchQuery)
.flatMap((section) => section.options)
.map(toModelListItem)
}, [deferredSearchQuery, isSearching, searchSections, toModelListItem])
const providerItems = browseData?.providerItems ?? EMPTY_PROVIDER_ITEMS
const selectedProviderModels = useMemo(
() => (selectedProviderId ? browseData?.modelsByProviderId.get(selectedProviderId) ?? EMPTY_MODELS : EMPTY_MODELS),
[browseData, selectedProviderId]
)
const browseModels = selectedProviderId ? selectedProviderModels : browseData?.allModels ?? EMPTY_MODELS
const handleModelSelect = (providerID: string, modelID: string) => {
setModel({ providerID, modelID })
setShowAllModels(false)
@@ -501,7 +352,20 @@ export function ModelQuickSelect({
)
}
const selectedModelItem = model ? toModelListItem(model) : null
const selectedModelItem = useMemo((): ModelListItem | null => {
if (!model) return null
const key = modelString ?? modelSelectionRef(model)
const option = catalogOptions.find((candidate) => candidate.value === key)
if (option) return toModelListItem(option)
const providerName = providers.find((provider) => provider.id === model.providerID)?.name ?? model.providerID
return {
providerID: model.providerID,
modelID: model.modelID,
key,
displayName: info?.name ?? model.modelID,
providerName,
}
}, [model, modelString, info, providers, catalogOptions, toModelListItem])
const renderProviderOption = (provider: ProviderListItem) => {
return (
@@ -603,7 +467,7 @@ export function ModelQuickSelect({
<Input
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder={selectedProviderId ? 'Search models...' : 'Search providers...'}
placeholder="Search models..."
className="h-9 border-border bg-muted pl-9 text-sm text-foreground placeholder:text-muted-foreground"
autoComplete="off"
name="model-search"
@@ -652,85 +516,75 @@ export function ModelQuickSelect({
</div>
{showAllModels ? (
<div className="flex-1 flex overflow-hidden min-h-0">
{/* Provider sidebar — desktop only */}
<div className="hidden md:flex md:flex-col w-48 lg:w-56 border-r border-border overflow-y-auto flex-shrink-0">
<div className="p-3 space-y-1">
{connectedProviderItems.length > 0 && (
<>
<p className="px-3 pb-1 text-xs font-medium text-muted-foreground">Connected</p>
{connectedProviderItems.map(renderSidebarProviderOption)}
{availableProviderItems.length > 0 && <div className="mx-3 my-1 h-px bg-border" />}
</>
)}
{availableProviderItems.length > 0 && (
<>
<p className="px-3 pb-1 text-xs font-medium text-muted-foreground">Available</p>
{availableProviderItems.map(renderSidebarProviderOption)}
</>
)}
</div>
isSearching ? (
<div className="flex-1 overflow-hidden min-h-0">
<VirtualizedList
items={searchResults}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item) => renderModelOption(item)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4 pt-2"
resetKey={`${selectedProviderId ?? 'all'}:${deferredSearchQuery}`}
/>
</div>
{/* Right panel */}
<div className="flex-1 flex flex-col overflow-hidden min-w-0">
{/* Desktop: model grid */}
<div className="hidden md:block flex-1 overflow-hidden min-h-0">
<VirtualizedList
items={filteredAllModels}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item) => renderModelOption(item)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4 pt-2"
resetKey={`${selectedProviderId ?? 'all'}:${deferredSearchQuery}`}
/>
) : (
<div className="flex-1 flex overflow-hidden min-h-0">
{/* Provider sidebar — desktop only */}
<div className="hidden md:flex md:flex-col w-48 lg:w-56 border-r border-border overflow-y-auto flex-shrink-0">
<div className="p-3 space-y-1">
{providerItems.map(renderSidebarProviderOption)}
</div>
</div>
{/* Mobile: current single-column navigation */}
<div className="md:hidden flex-1 overflow-hidden min-h-0">
{selectedProviderId ? (
{/* Right panel */}
<div className="flex-1 flex flex-col overflow-hidden min-w-0">
{/* Desktop: model grid */}
<div className="hidden md:block flex-1 overflow-hidden min-h-0">
<VirtualizedList
items={filteredSelectedProviderModels}
items={browseModels}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item) => renderModelOption(item)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4"
resetKey={`${selectedProviderId}:${deferredSearchQuery}`}
className="px-4 pb-4 pt-2"
resetKey={selectedProviderId ?? 'all'}
/>
) : (
<div className="h-full overflow-y-auto px-4 pb-4">
<div className="space-y-1">
{connectedProviderItems.length > 0 && (
<>
<p className="px-1 pb-1 text-xs font-medium text-muted-foreground">Connected</p>
{connectedProviderItems.map(renderProviderOption)}
{availableProviderItems.length > 0 && <div className="-mx-4 my-2 h-px bg-border" />}
</>
)}
{availableProviderItems.length > 0 && (
<>
<p className="px-1 pb-1 text-xs font-medium text-muted-foreground">Available</p>
{availableProviderItems.map(renderProviderOption)}
</>
</div>
{/* Mobile: current single-column navigation */}
<div className="md:hidden flex-1 overflow-hidden min-h-0">
{selectedProviderId ? (
<VirtualizedList
items={selectedProviderModels}
itemHeight={MODEL_OPTION_ROW_HEIGHT}
renderItem={(item) => renderModelOption(item)}
getKey={(item) => item.key}
emptyLabel="No models found"
className="px-4 pb-4"
resetKey={selectedProviderId}
/>
) : (
<div className="h-full overflow-y-auto px-4 pb-4">
<div className="space-y-1">
{providerItems.map(renderProviderOption)}
</div>
{providerItems.length === 0 && (
<div className="py-10 text-center text-sm text-muted-foreground">No providers found</div>
)}
</div>
{filteredProviderItems.length === 0 && (
<div className="py-10 text-center text-sm text-muted-foreground">No providers found</div>
)}
</div>
)}
)}
</div>
</div>
</div>
</div>
)
) : (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden pb-safe pt-0">
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
{quickSections.map(section => (
<section key={section.title}>
<h3 className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
{section.icon}
{section.icon ? <section.icon className="h-3.5 w-3.5" /> : null}
{section.title}
</h3>
<div className="space-y-1">
@@ -12,8 +12,9 @@ const mocks = vi.hoisted(() => ({
listMultiRuns: vi.fn(),
launchMultiRun: vi.fn(),
discardMultiRunEntry: vi.fn(),
useProvidersWithModels: vi.fn(),
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
listBranches: vi.fn(),
}))
@@ -24,12 +25,13 @@ vi.mock('@/api/multiRuns', () => ({
discardMultiRunEntry: mocks.discardMultiRunEntry,
}))
vi.mock('@/hooks/useProvidersWithModels', () => ({
useProvidersWithModels: mocks.useProvidersWithModels,
vi.mock('@/hooks/useProviders', () => ({
useProviders: mocks.useProviders,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
vi.mock('@/api/repos', () => ({
@@ -49,19 +51,15 @@ const providers = [
{
id: 'openai',
name: 'OpenAI',
source: 'configured',
isConnected: true,
models: [
{ id: 'gpt-4o', name: 'GPT-4o' },
{ id: 'gpt-4.1', name: 'GPT-4.1' },
{ id: 'gpt-4o', name: 'GPT-4o', released: 0, free: false },
{ id: 'gpt-4.1', name: 'GPT-4.1', released: 0, free: false },
],
},
{
id: 'anthropic',
name: 'Anthropic',
source: 'configured',
isConnected: true,
models: [{ id: 'claude-opus', name: 'Claude Opus' }],
models: [{ id: 'claude-opus', name: 'Claude Opus', released: 0, free: false }],
},
]
@@ -147,6 +145,13 @@ async function selectSourcesAndModel(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
}
function synthesisCheckboxLabels() {
return screen
.getAllByRole('checkbox')
.map((checkbox) => checkbox.getAttribute('aria-label') ?? '')
.filter((label) => !label.includes('/'))
}
describe('FuseRunDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
@@ -157,8 +162,9 @@ describe('FuseRunDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useProvidersWithModels.mockReturnValue({ data: providers, isLoading: false })
mocks.useProviders.mockReturnValue({ data: { providers, models: [] }, isLoading: false })
mocks.useOpenCodeModelState.mockReturnValue({ data: { recent: [], favorite: [], variant: {} } })
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: null })
mocks.listBranches.mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
@@ -402,4 +408,12 @@ describe('FuseRunDialog', () => {
await screen.findByText('An earlier attempt is already running. Open it from the Fusions list.'),
).toBeInTheDocument()
})
it('lists the OpenCode default model first without repeating it', () => {
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: 'anthropic/claude-opus' })
renderFuseDialog()
expect(screen.getByText('Default')).toBeInTheDocument()
expect(synthesisCheckboxLabels()).toEqual(['Claude Opus', 'GPT-4o', 'GPT-4.1'])
})
})
@@ -10,10 +10,9 @@ import { Label } from '@/components/ui/label'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { BranchCombobox } from '@/components/repo/BranchCombobox'
import { ModelCheckboxList } from '@/components/repo/ModelCheckboxList'
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
import { useOpenCodeModelState } from '@/hooks/useModelSelection'
import { useModelSections } from '@/hooks/useModelSections'
import { useFuseMultiRun } from '@/hooks/useMultiRuns'
import { buildModelSections, filterModelSections } from '@/lib/modelSections'
import { filterModelSections } from '@/lib/modelSections'
import { randomId } from '@/lib/utils'
import {
FUSION_INSTRUCTIONS_MAX_LENGTH,
@@ -63,8 +62,7 @@ export function FuseRunDialog({
const deferredModelSearch = useDeferredValue(modelSearch)
const fuse = useFuseMultiRun(repoId)
const { data: providers } = useProvidersWithModels({ enabled: open, directory })
const { data: modelState } = useOpenCodeModelState(directory, open)
const { sections: modelSections } = useModelSections(directory, { enabled: open })
useEffect(() => {
if (!open) return
@@ -77,7 +75,6 @@ export function FuseRunDialog({
setRequestId(randomId())
}, [open, run.id, run.baseRef])
const modelSections = useMemo(() => buildModelSections(providers, modelState), [providers, modelState])
const visibleModelSections = useMemo(
() => filterModelSections(modelSections, deferredModelSearch),
[modelSections, deferredModelSearch],
@@ -41,7 +41,7 @@ export const ModelCheckboxList = memo(function ModelCheckboxList({
onCheckedChange={(next) => onToggle(option.value, next === true)}
/>
<span className="truncate">{option.label}</span>
{section.pinned ? (
{!section.providerID ? (
<span className="ml-auto shrink-0 text-xs text-muted-foreground">{option.providerName}</span>
) : null}
</label>
@@ -11,8 +11,9 @@ const mocks = vi.hoisted(() => ({
launchMultiRun: vi.fn(),
discardMultiRunEntry: vi.fn(),
fuseMultiRun: vi.fn(),
useProvidersWithModels: vi.fn(),
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
listBranches: vi.fn(),
getChangeWalkthrough: vi.fn(),
generateChangeWalkthrough: vi.fn(),
@@ -32,12 +33,13 @@ vi.mock('@/api/multiRuns', () => ({
fuseMultiRun: mocks.fuseMultiRun,
}))
vi.mock('@/hooks/useProvidersWithModels', () => ({
useProvidersWithModels: mocks.useProvidersWithModels,
vi.mock('@/hooks/useProviders', () => ({
useProviders: mocks.useProviders,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
vi.mock('@/api/repos', () => ({
@@ -62,24 +64,20 @@ const providers = [
{
id: 'openai',
name: 'OpenAI',
source: 'configured',
isConnected: true,
models: [
{ id: 'gpt-4o', name: 'GPT-4o' },
{ id: 'gpt-4o-mini', name: 'GPT-4o mini' },
{ id: 'gpt-4.1', name: 'GPT-4.1' },
{ id: 'gpt-4o', name: 'GPT-4o', released: 0, free: false },
{ id: 'gpt-4o-mini', name: 'GPT-4o mini', released: 0, free: false },
{ id: 'gpt-4.1', name: 'GPT-4.1', released: 0, free: false },
],
},
{
id: 'anthropic',
name: 'Anthropic',
source: 'configured',
isConnected: true,
models: [
{ id: 'claude-opus', name: 'Claude Opus' },
{ id: 'claude-sonnet', name: 'Claude Sonnet' },
{ id: 'claude-haiku', name: 'Claude Haiku' },
{ id: 'claude-sonnet-4-5', key: 'claude-sonnet-4.5', name: 'Claude Sonnet 4.5' },
{ id: 'claude-opus', name: 'Claude Opus', released: 0, free: false },
{ id: 'claude-sonnet', name: 'Claude Sonnet', released: 0, free: false },
{ id: 'claude-haiku', name: 'Claude Haiku', released: 0, free: false },
{ id: 'claude-sonnet-4-5', key: 'claude-sonnet-4.5', name: 'Claude Sonnet 4.5', released: 0, free: false },
],
},
]
@@ -220,8 +218,9 @@ describe('MultiRunDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useProvidersWithModels.mockReturnValue({ data: providers, isLoading: false })
mocks.useProviders.mockReturnValue({ data: { providers, models: [] }, isLoading: false })
mocks.useOpenCodeModelState.mockReturnValue({ data: { recent: [], favorite: [], variant: {} } })
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: null })
mocks.listBranches.mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
@@ -261,6 +260,22 @@ describe('MultiRunDialog', () => {
])
})
it('lists the OpenCode default model first without repeating it', () => {
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: 'anthropic/claude-sonnet' })
renderDialog()
expect(screen.getByText('Default')).toBeInTheDocument()
expect(checkboxLabels()).toEqual([
'Claude Sonnet',
'GPT-4o',
'GPT-4o mini',
'GPT-4.1',
'Claude Opus',
'Claude Haiku',
'Claude Sonnet 4.5',
])
})
it('filters models by every search term and keeps favorites first', async () => {
const user = userEvent.setup()
mocks.useOpenCodeModelState.mockReturnValue({
@@ -279,6 +294,35 @@ describe('MultiRunDialog', () => {
expect(await screen.findByText('No models match your search.')).toBeInTheDocument()
})
it('shows the provider name on every search result', async () => {
const user = userEvent.setup()
mocks.useProviders.mockReturnValue({
data: {
providers: [
{
id: 'anthropic',
name: 'Anthropic',
models: [{ id: 'claude-sonnet', name: 'Claude Sonnet', released: 0, free: false }],
},
{
id: 'openrouter',
name: 'OpenRouter',
models: [{ id: 'claude-sonnet', name: 'Claude Sonnet', released: 0, free: false }],
},
],
models: [],
},
isLoading: false,
})
renderDialog()
await user.type(screen.getByLabelText('Search models'), 'claude')
await waitFor(() => expect(checkboxLabels()).toEqual(['Claude Sonnet', 'Claude Sonnet']))
expect(screen.getByText('Anthropic')).toBeInTheDocument()
expect(screen.getByText('OpenRouter')).toBeInTheDocument()
})
it('keeps selections that are hidden by the search filter', async () => {
const user = userEvent.setup()
renderDialog()
@@ -15,10 +15,9 @@ import { BranchCombobox } from '@/components/repo/BranchCombobox'
import { ModelCheckboxList } from '@/components/repo/ModelCheckboxList'
import { FuseRunDialog } from '@/components/repo/FuseRunDialog'
import { ChangesWalkthroughDialog } from '@/components/session/ChangesWalkthroughDialog'
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
import { useOpenCodeModelState } from '@/hooks/useModelSelection'
import { useModelSections } from '@/hooks/useModelSections'
import { useDiscardMultiRunEntry, useLaunchMultiRun, useMultiRuns } from '@/hooks/useMultiRuns'
import { buildModelSections, filterModelSections } from '@/lib/modelSections'
import { filterModelSections } from '@/lib/modelSections'
import { buildSessionPath } from '@opencode-manager/shared/utils'
import {
MULTI_RUN_FUSION_MIN_SOURCES,
@@ -79,8 +78,7 @@ export function MultiRunDialog({
const [fuseRun, setFuseRun] = useState<MultiRun | null>(null)
const [walkthroughSessionId, setWalkthroughSessionId] = useState<string | null>(null)
const { data: providers } = useProvidersWithModels({ enabled: open, directory })
const { data: modelState } = useOpenCodeModelState(directory, open)
const { sections: modelSections } = useModelSections(directory, { enabled: open })
const runsQuery = useMultiRuns(repoId, open)
const launch = useLaunchMultiRun(repoId)
const discard = useDiscardMultiRunEntry(repoId)
@@ -96,7 +94,6 @@ export function MultiRunDialog({
setModelSearch('')
}, [open, defaultBaseRef])
const modelSections = useMemo(() => buildModelSections(providers, modelState), [providers, modelState])
const visibleModelSections = useMemo(
() => filterModelSections(modelSections, deferredModelSearch),
[modelSections, deferredModelSearch],
@@ -1,4 +1,5 @@
import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
import { ModelCombobox } from '@/components/model/ModelCombobox'
import { BranchCombobox } from '@/components/repo/BranchCombobox'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
@@ -20,7 +21,7 @@ type GeneralTabProps = {
agentOptions: ComboboxOption[]
model: string
onModelChange: (value: string) => void
modelOptions: ComboboxOption[]
modelDirectory?: string
enabled: boolean
onEnabledChange: (value: boolean) => void
branch: string
@@ -64,7 +65,7 @@ export function GeneralTab({
agentOptions,
model,
onModelChange,
modelOptions,
modelDirectory,
enabled,
onEnabledChange,
branch,
@@ -140,10 +141,11 @@ export function GeneralTab({
<Label htmlFor="schedule-model">Model override</Label>
<InfoHint text="Pick from detected OpenCode models or type a custom provider/model value." />
</div>
<Combobox
<ModelCombobox
id="schedule-model"
value={model}
onChange={onModelChange}
options={modelOptions}
directory={modelDirectory}
placeholder="Workspace default"
allowCustomValue
showClear
@@ -41,8 +41,8 @@ export function JobDetailTab({
isJobFetching,
}: JobDetailTabProps) {
const { scheduleTarget } = useScheduleTarget(selectedJob?.repoId)
const { availableModelKeys, configDefaultModel } = useScheduleModels(Boolean(selectedJob), scheduleTarget?.fullPath)
const resolvedModel = resolveScheduleModel(selectedJob?.model, availableModelKeys, configDefaultModel)
const { availableModels } = useScheduleModels(Boolean(selectedJob), scheduleTarget?.fullPath)
const resolvedModel = resolveScheduleModel(selectedJob?.model, availableModels)
const { data: worktrees = [] } = useScheduleWorktrees(selectedJob?.repoId, selectedJob?.id ?? null)
const removeWorktrees = useRemoveScheduleWorktrees()
const idleWorktreeCount = worktrees.filter((worktree) => !worktree.inUse).length
@@ -21,7 +21,7 @@ vi.mock('@/hooks/usePromptTemplates', () => ({
}))
vi.mock('@/api/providers', () => ({
getProvidersWithModels: () => Promise.resolve([]),
getProviders: () => Promise.resolve({ providers: [], models: [] }),
}))
vi.mock('@/hooks/useOpenCode', () => ({
@@ -18,7 +18,7 @@ vi.mock('@/hooks/usePromptTemplates', () => ({
}))
vi.mock('@/api/providers', () => ({
getProvidersWithModels: () => Promise.resolve([]),
getProviders: () => Promise.resolve({ providers: [], models: [] }),
}))
vi.mock('@/hooks/useOpenCode', () => ({
@@ -19,7 +19,7 @@ vi.mock('@/hooks/usePromptTemplates', () => ({
}))
vi.mock('@/api/providers', () => ({
getProvidersWithModels: () => Promise.resolve([]),
getProviders: () => Promise.resolve({ providers: [], models: [] }),
}))
vi.mock('@/hooks/useOpenCode', () => ({
@@ -1,18 +1,23 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ScheduleJobDialog } from './ScheduleJobDialog'
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
import type { ProviderWithModels } from '@/api/providers'
import type { Provider } from '@/api/providers'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
import type { ScheduleJob } from '@opencode-manager/shared/types'
Element.prototype.scrollIntoView = vi.fn()
const { mockGetProvidersWithModels, mockGetOpenCodeConfig, mockGetOpenCodeConfigModel, mockGetOpenCodeModelState } = vi.hoisted(() => ({
mockGetProvidersWithModels: vi.fn(),
mockGetOpenCodeConfig: vi.fn(),
mockGetOpenCodeConfigModel: vi.fn(),
const {
mockGetProviders,
mockGetOpenCodeConfiguredModel,
mockGetOpenCodeServerDefaultModel,
mockGetOpenCodeModelState,
} = vi.hoisted(() => ({
mockGetProviders: vi.fn(),
mockGetOpenCodeConfiguredModel: vi.fn(),
mockGetOpenCodeServerDefaultModel: vi.fn(),
mockGetOpenCodeModelState: vi.fn(),
}))
@@ -25,8 +30,9 @@ vi.mock('@/hooks/usePromptTemplates', () => ({
vi.mock('@/api/providers', async (importOriginal) => ({
...(await importOriginal<typeof import('@/api/providers')>()),
getProvidersWithModels: mockGetProvidersWithModels,
getOpenCodeConfigModel: mockGetOpenCodeConfigModel,
getProviders: mockGetProviders,
getOpenCodeConfiguredModel: mockGetOpenCodeConfiguredModel,
getOpenCodeServerDefaultModel: mockGetOpenCodeServerDefaultModel,
getOpenCodeModelState: mockGetOpenCodeModelState,
}))
@@ -36,7 +42,6 @@ vi.mock('@/hooks/useOpenCode', () => ({
vi.mock('@/api/settings', () => ({
settingsApi: {
getOpenCodeConfig: mockGetOpenCodeConfig,
listManagedSkills: () => Promise.resolve([]),
},
}))
@@ -46,18 +51,15 @@ vi.mock('@/api/repos', () => ({
listBranches: () => Promise.resolve({ branches: [], status: { ahead: 0, behind: 0 } }),
}))
const providers: ProviderWithModels[] = [
const providers: Provider[] = [
{
id: 'openai',
name: 'OpenAI',
env: [],
models: [{ id: 'gpt-5', key: 'gpt-5', name: 'GPT-5' }],
source: 'configured',
isConnected: true,
models: [{ id: 'gpt-5', key: 'gpt-5', name: 'GPT-5', released: 0, free: false }],
},
]
const config = makeOpenCodeConfigFile({ content: {} })
const models = [{ providerID: 'openai', id: 'gpt-5' }] as unknown as ModelInfo[]
function getJob(overrides: Partial<ScheduleJob> = {}): ScheduleJob {
return {
@@ -99,13 +101,13 @@ function createWrapper() {
describe('ScheduleJobDialog — model fallback', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetProvidersWithModels.mockResolvedValue(providers)
mockGetOpenCodeConfig.mockResolvedValue(config)
mockGetOpenCodeConfigModel.mockResolvedValue('openai/gpt-5')
mockGetProviders.mockResolvedValue({ providers, models })
mockGetOpenCodeConfiguredModel.mockResolvedValue(null)
mockGetOpenCodeServerDefaultModel.mockResolvedValue(null)
mockGetOpenCodeModelState.mockResolvedValue({ recent: [], favorite: [], variant: {} })
})
it('prefills the config default when the stored model no longer exists', async () => {
it('leaves the model at the workspace default when the stored model no longer exists', async () => {
render(
<ScheduleJobDialog
open
@@ -118,10 +120,11 @@ describe('ScheduleJobDialog — model fallback', () => {
{ wrapper: createWrapper() },
)
await waitFor(() => expect(screen.getByDisplayValue('GPT-5')).toBeInTheDocument())
await waitFor(() => expect(screen.queryByDisplayValue('openai/retired')).not.toBeInTheDocument())
expect(screen.getByPlaceholderText('Workspace default')).toBeInTheDocument()
})
it('saves the resolved config default for a stale model', async () => {
it('saves no model override for a stale model', async () => {
const user = userEvent.setup()
const onSubmit = vi.fn()
@@ -137,10 +140,11 @@ describe('ScheduleJobDialog — model fallback', () => {
{ wrapper: createWrapper() },
)
await waitFor(() => expect(screen.getByDisplayValue('GPT-5')).toBeInTheDocument())
await waitFor(() => expect(screen.queryByDisplayValue('openai/retired')).not.toBeInTheDocument())
await user.click(screen.getByRole('button', { name: 'Save changes' }))
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ model: 'openai/gpt-5' }))
expect(onSubmit).toHaveBeenCalledTimes(1)
expect(onSubmit.mock.calls[0][0].model).toBeUndefined()
})
it('keeps a stored model that is still available', async () => {
@@ -159,20 +163,7 @@ describe('ScheduleJobDialog — model fallback', () => {
await waitFor(() => expect(screen.getByDisplayValue('GPT-5')).toBeInTheDocument())
})
it('does not duplicate a configured model referenced by its backing id', async () => {
const user = userEvent.setup()
mockGetProvidersWithModels.mockResolvedValue([
{
id: 'openai',
name: 'OpenAI',
env: [],
models: [{ id: 'gpt-5-2025-08-07', key: 'gpt-5', name: 'GPT-5' }],
source: 'configured',
isConnected: true,
},
])
mockGetOpenCodeConfigModel.mockResolvedValue('openai/gpt-5-2025-08-07')
it('treats a stored backing model id as unavailable', async () => {
render(
<ScheduleJobDialog
open
@@ -185,14 +176,12 @@ describe('ScheduleJobDialog — model fallback', () => {
{ wrapper: createWrapper() },
)
const modelInput = await screen.findByDisplayValue('GPT-5')
await user.click(modelInput)
await waitFor(() => expect(screen.getAllByText('GPT-5')).toHaveLength(1))
await waitFor(() => expect(screen.queryByDisplayValue('openai/gpt-5-2025-08-07')).not.toBeInTheDocument())
expect(screen.getByPlaceholderText('Workspace default')).toBeInTheDocument()
})
it('clears a stale model when availability is confirmed empty', async () => {
mockGetProvidersWithModels.mockResolvedValue([])
it('keeps a stored model when the catalog is confirmed empty', async () => {
mockGetProviders.mockResolvedValue({ providers: [], models: [] })
render(
<ScheduleJobDialog
@@ -206,7 +195,48 @@ describe('ScheduleJobDialog — model fallback', () => {
{ wrapper: createWrapper() },
)
await waitFor(() => expect(screen.queryByDisplayValue('openai/retired')).not.toBeInTheDocument())
expect(screen.getByPlaceholderText('Workspace default')).toBeInTheDocument()
await waitFor(() => expect(screen.getByDisplayValue('openai/retired')).toBeInTheDocument())
})
it('shows Default from OpenCode when no model is configured', async () => {
const user = userEvent.setup()
mockGetProviders.mockResolvedValue({
providers: [
{
id: 'openai',
name: 'OpenAI',
models: [
{ id: 'gpt-5', key: 'gpt-5', name: 'GPT-5', released: 0, free: false },
{ id: 'gpt-4o', key: 'gpt-4o', name: 'GPT-4o', released: 0, free: false },
],
},
],
models: [
{ providerID: 'openai', id: 'gpt-5' },
{ providerID: 'openai', id: 'gpt-4o' },
] as unknown as ModelInfo[],
})
mockGetOpenCodeServerDefaultModel.mockResolvedValue({ providerID: 'openai', id: 'gpt-5' })
render(
<ScheduleJobDialog
open
onOpenChange={vi.fn()}
job={getJob()}
isSaving={false}
onSubmit={vi.fn()}
repoId={1}
/>,
{ wrapper: createWrapper() },
)
const modelInput = await screen.findByPlaceholderText('Workspace default')
await user.click(modelInput)
const listbox = await screen.findByRole('listbox')
const defaultGroup = within(listbox).getByText('Default')
const providerGroup = within(listbox).getByText('OpenAI')
expect(within(listbox).getByText('Default: GPT-5')).toBeInTheDocument()
expect(defaultGroup.compareDocumentPosition(providerGroup) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
})
})
@@ -22,7 +22,7 @@ vi.mock('@/hooks/usePromptTemplates', () => ({
}))
vi.mock('@/api/providers', () => ({
getProvidersWithModels: () => Promise.resolve([]),
getProviders: () => Promise.resolve({ providers: [], models: [] }),
}))
vi.mock('@/hooks/useOpenCode', () => ({
@@ -1,77 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ScheduleJobDialog } from './ScheduleJobDialog'
import { OPEN_CODE_CONFIG_QUERY_KEY } from '@/hooks/useOpenCodeConfigFile'
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
Element.prototype.scrollIntoView = vi.fn()
const { mockGetProvidersWithModels, mockGetOpenCodeConfig } = vi.hoisted(() => ({
mockGetProvidersWithModels: vi.fn(),
mockGetOpenCodeConfig: vi.fn(),
}))
vi.mock('@/hooks/usePromptTemplates', () => ({
usePromptTemplates: () => ({ data: [], isLoading: false }),
useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
useDeletePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
}))
vi.mock('@/api/providers', () => ({
getProvidersWithModels: mockGetProvidersWithModels,
}))
vi.mock('@/hooks/useOpenCode', () => ({
useAgents: () => ({ data: [] }),
}))
vi.mock('@/api/settings', () => ({
settingsApi: {
getOpenCodeConfig: mockGetOpenCodeConfig,
listManagedSkills: () => Promise.resolve([]),
},
}))
vi.mock('@/api/repos', () => ({
listRepos: () => Promise.resolve([]),
listBranches: () => Promise.resolve({ branches: [], status: { ahead: 0, behind: 0 } }),
}))
const config = makeOpenCodeConfigFile()
describe('ScheduleJobDialog — shared config query', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetProvidersWithModels.mockResolvedValue([])
mockGetOpenCodeConfig.mockResolvedValue(config)
})
it('feeds the cached shared config into the provider listing', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
queryClient.setQueryDefaults(OPEN_CODE_CONFIG_QUERY_KEY, { staleTime: Infinity })
queryClient.setQueryData(OPEN_CODE_CONFIG_QUERY_KEY, config)
render(
<ScheduleJobDialog
open
onOpenChange={vi.fn()}
showRepoSelector
repoId={undefined}
onRepoChange={vi.fn()}
onSubmit={vi.fn()}
isSaving={false}
/>,
{
wrapper: ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
},
)
await waitFor(() => expect(mockGetProvidersWithModels).toHaveBeenCalled())
expect(mockGetProvidersWithModels).toHaveBeenCalledWith(undefined, config)
expect(mockGetOpenCodeConfig).not.toHaveBeenCalled()
})
})
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob, ScheduleMcpServer, ScheduleWorkspaceMode } from '@opencode-manager/shared/types'
import { useScheduleModels } from '@/hooks/useScheduleModels'
import { buildScheduleModelOptions, resolveScheduleModel } from '@/lib/schedules/schedule-model'
import { resolveScheduleModel } from '@/lib/schedules/schedule-model'
import { useAgents } from '@/hooks/useOpenCode'
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
import { settingsApi } from '@/api/settings'
@@ -85,11 +85,11 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
const { scheduleTarget } = useScheduleTarget(open ? effectiveRepoId : undefined)
const scheduleDirectory = scheduleTarget?.fullPath
const { providerModels, modelState, availableModelKeys, configDefaultModel } = useScheduleModels(open, scheduleDirectory)
const { availableModels } = useScheduleModels(open, scheduleDirectory)
const resolvedModel = useMemo(
() => (modelDirty ? (model.trim() || null) : resolveScheduleModel(model, availableModelKeys, configDefaultModel)),
[model, modelDirty, availableModelKeys, configDefaultModel],
() => (modelDirty ? (model.trim() || null) : resolveScheduleModel(model, availableModels)),
[model, modelDirty, availableModels],
)
const { data: agents = [], isSuccess: agentsLoaded } = useAgents(scheduleDirectory, { enabled: !!scheduleDirectory })
@@ -129,11 +129,6 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
return [assistantOption, ...repoEntries]
}, [repos])
const modelOptions = useMemo(
() => buildScheduleModelOptions(providerModels, modelState, configDefaultModel),
[providerModels, modelState, configDefaultModel],
)
const agentOptions = useMemo<ComboboxOption[]>(() => {
return getPrimaryAgents(agents).map((agent) => ({
value: agent.id,
@@ -296,7 +291,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
agentOptions={agentOptions}
model={resolvedModel ?? ''}
onModelChange={handleModelChange}
modelOptions={modelOptions}
modelDirectory={scheduleDirectory}
enabled={enabled}
onEnabledChange={setEnabled}
branch={branch}
@@ -1,42 +1,53 @@
import { describe, it, expect, vi, beforeAll } from 'vitest'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AgentDialog } from './AgentDialog'
import type { Provider } from '@/api/providers'
vi.mock('@/hooks/useProvidersWithModels', () => ({
useProvidersWithModels: () => ({ data: [] }),
const mocks = vi.hoisted(() => ({
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
}))
const renderDialog = (editingAgent: { name: string; agent: { prompt: string; model?: string } } | null) =>
render(<AgentDialog open onOpenChange={vi.fn()} onSubmit={vi.fn()} editingAgent={editingAgent} />)
vi.mock('@/hooks/useProviders', () => ({
useProviders: mocks.useProviders,
}))
describe('AgentDialog model parsing', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
const providers: Provider[] = [
{
id: 'anthropic',
name: 'Anthropic',
models: [
{ id: 'claude-opus-5-5', key: 'claude-opus-5-5-fast', name: 'Claude Opus 5.5', released: 0, free: false },
],
},
]
describe('AgentDialog model field', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useProviders.mockReturnValue({ data: { providers, models: [] } })
mocks.useOpenCodeModelState.mockReturnValue({ data: { favorite: [], recent: [], variant: {} } })
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: null })
})
it('loads provider and model from a model reference', async () => {
renderDialog({ name: 'reviewer', agent: { prompt: 'Review code', model: 'openai/gpt-4o' } })
it('loads the stored model reference', async () => {
render(
<AgentDialog
open
onOpenChange={vi.fn()}
onSubmit={vi.fn()}
editingAgent={{ name: 'reviewer', agent: { prompt: 'Review code', model: 'openai/gpt-4o' } }}
/>,
)
await waitFor(() => expect(screen.getByPlaceholderText('Select or type provider...')).toHaveValue('openai'))
expect(screen.getByPlaceholderText('Select or type model...')).toHaveValue('gpt-4o')
})
it('keeps the variant attached to the model id', async () => {
renderDialog({ name: 'reviewer', agent: { prompt: 'Review code', model: 'openai/gpt-4o#high' } })
await waitFor(() => expect(screen.getByPlaceholderText('Select or type provider...')).toHaveValue('openai'))
expect(screen.getByPlaceholderText('Select or type model...')).toHaveValue('gpt-4o#high')
})
it('leaves provider and model empty when the agent has no model', async () => {
renderDialog({ name: 'reviewer', agent: { prompt: 'Review code' } })
await waitFor(() => expect(screen.getByPlaceholderText('Select or type provider...')).toHaveValue(''))
expect(screen.getByPlaceholderText('Select or type model...')).toHaveValue('')
await waitFor(() => expect(screen.getByLabelText('Model')).toHaveValue('openai/gpt-4o'))
})
it('round-trips a variant model reference on submit', async () => {
@@ -58,4 +69,64 @@ describe('AgentDialog model parsing', () => {
expect.objectContaining({ model: 'openai/gpt-4o#high' }),
)
})
it('loads and round-trips an object-form agent model', async () => {
const onSubmit = vi.fn()
const user = userEvent.setup()
render(
<AgentDialog
open
onOpenChange={vi.fn()}
onSubmit={onSubmit}
editingAgent={{
name: 'reviewer',
agent: { prompt: 'Review code', model: { providerID: 'openai', model: 'gpt-4o', variant: 'high' } },
}}
/>,
)
await waitFor(() => expect(screen.getByLabelText('Model')).toHaveValue('openai/gpt-4o#high'))
await user.click(screen.getByRole('button', { name: 'Update' }))
expect(onSubmit).toHaveBeenCalledWith(
'reviewer',
expect.objectContaining({ model: 'openai/gpt-4o#high' }),
)
})
it('submits no model when the field is empty', async () => {
const onSubmit = vi.fn()
const user = userEvent.setup()
render(
<AgentDialog
open
onOpenChange={vi.fn()}
onSubmit={onSubmit}
editingAgent={{ name: 'reviewer', agent: { prompt: 'Review code' } }}
/>,
)
await user.click(screen.getByRole('button', { name: 'Update' }))
const agent = onSubmit.mock.calls[0][1]
expect(agent.model).toBeUndefined()
})
it('saves the OpenCode key of an aliased model on create', async () => {
const onSubmit = vi.fn()
const user = userEvent.setup()
render(<AgentDialog open onOpenChange={vi.fn()} onSubmit={onSubmit} editingAgent={null} />)
await user.type(screen.getByLabelText('Agent Name'), 'reviewer')
await user.type(screen.getByLabelText('Prompt'), 'Review code')
await user.click(screen.getByLabelText('Model'))
await user.click(screen.getByRole('option', { name: /Claude Opus 5\.5/ }))
await user.click(screen.getByRole('button', { name: 'Create' }))
expect(onSubmit).toHaveBeenCalledWith(
'reviewer',
expect.objectContaining({ model: 'anthropic/claude-opus-5-5-fast' }),
)
})
})
+35 -100
View File
@@ -1,7 +1,7 @@
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useMemo, useEffect } from 'react'
import { useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
@@ -9,9 +9,8 @@ import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, For
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Combobox, type ComboboxOption } from '@/components/ui/combobox'
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
import { parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import { ModelCombobox } from '@/components/model/ModelCombobox'
import { configModelRef, formatOpenCodeModelRef } from '@opencode-manager/shared/opencode'
const agentFormSchema = z.object({
name: z.string().min(1, 'Agent name is required').regex(/^[a-z0-9-]+$/, 'Must be lowercase letters, numbers, and hyphens only'),
@@ -20,8 +19,7 @@ const agentFormSchema = z.object({
mode: z.enum(['subagent', 'primary', 'all']),
temperature: z.number().min(0).max(2),
topP: z.number().min(0).max(1),
modelId: z.string().optional(),
providerId: z.string().optional(),
model: z.string().optional(),
write: z.boolean(),
edit: z.boolean(),
bash: z.boolean(),
@@ -34,14 +32,14 @@ const agentFormSchema = z.object({
type AgentFormValues = z.infer<typeof agentFormSchema>
interface Agent {
interface Agent<TModel = string> {
prompt?: string
description?: string
mode?: 'subagent' | 'primary' | 'all'
temperature?: number
topP?: number
top_p?: number
model?: string
model?: TModel
tools?: Record<string, boolean>
permission?: {
edit?: 'ask' | 'allow' | 'deny'
@@ -52,41 +50,18 @@ interface Agent {
[key: string]: unknown
}
function parseModelString(model?: string): { providerId: string; modelId: string } {
const ref = model ? parseOpenCodeModelRef(model) : undefined
if (!ref) return { providerId: '', modelId: '' }
return {
providerId: ref.providerID,
modelId: ref.variant ? `${ref.id}#${ref.variant}` : ref.id,
}
}
type StoredAgent = Agent<string | { providerID: string; model: string; variant?: string }>
interface AgentDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onSubmit: (name: string, agent: Agent) => void
editingAgent?: { name: string; agent: Agent } | null
editingAgent?: { name: string; agent: StoredAgent } | null
}
export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: AgentDialogProps) {
const { data: providers } = useProvidersWithModels({ enabled: open })
const providerOptions: ComboboxOption[] = useMemo(() => {
const sourceLabels: Record<string, string> = {
configured: 'Custom',
local: 'Local',
builtin: 'Built-in',
}
return providers.map(p => ({
value: p.id,
label: p.name || p.id,
description: p.models.length > 0 ? `${p.models.length} models` : undefined,
group: sourceLabels[p.source] || 'Other',
}))
}, [providers])
const getDefaultValues = (agent?: { name: string; agent: Agent } | null): AgentFormValues => {
const parsed = parseModelString(agent?.agent.model)
const getDefaultValues = (agent?: { name: string; agent: StoredAgent } | null): AgentFormValues => {
const modelRef = configModelRef(agent?.agent.model)
return {
name: agent?.name || '',
description: agent?.agent.description || '',
@@ -94,8 +69,7 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen
mode: agent?.agent.mode || 'subagent',
temperature: agent?.agent.temperature ?? 0.7,
topP: agent?.agent.topP ?? agent?.agent.top_p ?? 1,
modelId: parsed.modelId,
providerId: parsed.providerId,
model: modelRef ? formatOpenCodeModelRef(modelRef) : '',
write: agent?.agent.tools?.write ?? true,
edit: agent?.agent.tools?.edit ?? true,
bash: agent?.agent.tools?.bash ?? true,
@@ -118,23 +92,6 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen
}
}, [open, editingAgent, form])
const selectedProviderId = form.watch('providerId')
const modelOptions: ComboboxOption[] = useMemo(() => {
const selectedProvider = providers.find(p => p.id === selectedProviderId)
if (selectedProvider && selectedProvider.models.length > 0) {
return selectedProvider.models.map(m => ({
value: m.id,
label: m.name || m.id,
}))
}
return providers.flatMap(p => p.models.map(m => ({
value: m.id,
label: m.name || m.id,
group: p.name || p.id,
})))
}, [providers, selectedProviderId])
const handleSubmit = (values: AgentFormValues) => {
const agent: Agent = {
prompt: values.prompt,
@@ -156,8 +113,8 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen
}
}
if (values.modelId && values.providerId) {
agent.model = `${values.providerId}/${values.modelId}`
if (values.model?.trim()) {
agent.model = values.model.trim()
}
onSubmit(values.name, agent)
@@ -307,50 +264,28 @@ export function AgentDialog({ open, onOpenChange, onSubmit, editingAgent }: Agen
/>
</div>
<div className="space-y-2">
<div className="text-sm font-medium">Model Configuration</div>
<div className="flex flex-col sm:grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="providerId"
render={({ field }) => (
<FormItem>
<FormLabel>Provider ID</FormLabel>
<FormControl>
<Combobox
value={field.value || ''}
onChange={field.onChange}
options={providerOptions}
placeholder="Select or type provider..."
allowCustomValue
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="modelId"
render={({ field }) => (
<FormItem>
<FormLabel>Model ID</FormLabel>
<FormControl>
<Combobox
value={field.value || ''}
onChange={field.onChange}
options={modelOptions}
placeholder="Select or type model..."
allowCustomValue
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
<FormField
control={form.control}
name="model"
render={({ field }) => (
<FormItem>
<FormLabel>Model</FormLabel>
<FormControl>
<ModelCombobox
id="agent-model"
ariaLabel="Model"
value={field.value || ''}
onChange={field.onChange}
enabled={open}
placeholder="OpenCode default"
allowCustomValue
showClear
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="space-y-2">
<div className="text-sm font-medium">Tools Configuration</div>
@@ -10,6 +10,7 @@ import { createUseSettingsMock } from '@/test/test-utils'
vi.mock('@/hooks/useSettings')
vi.mock('@/hooks/useVersionCheck')
vi.mock('@/components/model/ModelCombobox', () => ({ ModelCombobox: () => null }))
const basePreferences: UserPreferences = {
theme: 'dark',
@@ -5,7 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ProviderSettings } from './ProviderSettings'
import { getProviders, providerCredentialsApi } from '@/api/providers'
import { oauthApi } from '@/api/oauth'
import type { Provider, Model } from '@/api/providers'
import type { Provider } from '@/api/providers'
import type { OAuthAuthorizeResponse } from '@/api/oauth'
import type { ReactNode } from 'react'
@@ -88,9 +88,12 @@ function providerFixture(id: string, name: string, modelCount: number): Provider
return {
id,
name,
models: Object.fromEntries(
Array.from({ length: modelCount }, (_, index) => [`model-${index}`, {} as Model]),
),
models: Array.from({ length: modelCount }, (_, index) => ({
id: `model-${index}`,
name: `model-${index}`,
released: 0,
free: false,
})),
}
}
@@ -107,7 +110,7 @@ function mockProviderData() {
apiKeyProviderWithKey,
apiKeyProviderWithoutKey,
],
connected: [],
models: [],
})
vi.mocked(providerCredentialsApi.list).mockResolvedValue(['anthropic', 'openai'])
vi.mocked(oauthApi.getAuthMethods).mockResolvedValue({
@@ -178,7 +178,7 @@ export function ProviderSettings() {
<div className="divide-y divide-border">
{oauthProviders.map((provider) => {
const hasKey = hasCredentials(provider.id)
const modelCount = Object.keys(provider.models || {}).length
const modelCount = provider.models.length
return (
<div key={provider.id} className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-3">
@@ -288,7 +288,7 @@ export function ProviderSettings() {
</p>
) : (
apiKeyProviders.connected.map((provider) => {
const modelCount = Object.keys(provider.models || {}).length
const modelCount = provider.models.length
return (
<Card key={provider.id} className="bg-card border-border">
<CardHeader className="p-3">
@@ -375,7 +375,7 @@ export function ProviderSettings() {
</p>
) : (
filteredAvailableProviders.map((provider, index) => {
const modelCount = Object.keys(provider.models || {}).length
const modelCount = provider.models.length
return (
<div key={provider.id} className={`flex items-center justify-between gap-2 py-1.5 px-2 rounded-md hover:bg-accent/80 transition-colors ${index % 2 === 1 ? 'bg-accent/30' : ''}`}>
<div className="flex-1 min-w-0">
@@ -412,18 +412,7 @@ export function ProviderSettings() {
<ApiKeyDialog
open={apiKeyDialogOpen}
onOpenChange={handleApiKeyDialogClose}
provider={{
id: apiKeyProvider.id,
name: apiKeyProvider.name,
api: apiKeyProvider.api,
npm: apiKeyProvider.npm,
models: Object.entries(apiKeyProvider.models || {}).map(([id, model]) => ({
id,
name: model.name || id,
})),
source: 'builtin',
isConnected: hasCredentials(apiKeyProvider.id),
}}
provider={apiKeyProvider}
onSuccess={handleApiKeySuccess}
mode={apiKeyMode}
/>
@@ -4,10 +4,33 @@ import userEvent from '@testing-library/user-event'
import { SessionAutomationSettings } from './SessionAutomationSettings'
import { useSettings } from '@/hooks/useSettings'
import type { UserPreferences } from '@/api/types/settings'
import type { Provider } from '@/api/providers'
import { createUseSettingsMock } from '@/test/test-utils'
vi.mock('@/hooks/useSettings')
const mocks = vi.hoisted(() => ({
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
}))
vi.mock('@/hooks/useProviders', () => ({ useProviders: mocks.useProviders }))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
const providers: Provider[] = [
{
id: 'anthropic',
name: 'Anthropic',
models: [
{ id: 'claude-sonnet-4', key: 'claude-sonnet-4', name: 'Claude Sonnet 4', released: 0, free: false },
],
},
]
const basePreferences: UserPreferences = {
theme: 'dark',
mode: 'build',
@@ -33,6 +56,9 @@ describe('SessionAutomationSettings', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useProviders.mockReturnValue({ data: { providers, models: [] } })
mocks.useOpenCodeModelState.mockReturnValue({ data: { favorite: [], recent: [], variant: {} } })
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: null })
})
it('defaults the select to ask every time', () => {
@@ -58,26 +84,68 @@ describe('SessionAutomationSettings', () => {
expect(updateSettings).toHaveBeenCalledWith({ sessionDefaults: { permissionMode: 'auto' } })
})
it('saves the goal auditor model once on blur with the final value', () => {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
it('saves the goal auditor model chosen from the combobox after the debounce', () => {
vi.useFakeTimers()
try {
const updateSettings = vi.fn()
mockUseSettings({
preferences: { ...basePreferences, sessionDefaults: { permissionMode: 'ask', goalMaxContinuations: 20 } },
updateSettings,
})
render(<SessionAutomationSettings />)
const input = screen.getByLabelText('Goal auditor model')
fireEvent.change(input, { target: { value: 'anthropic/claude-sonnet-4' } })
fireEvent.blur(input)
fireEvent.focus(screen.getByLabelText('Goal auditor model'))
fireEvent.click(screen.getByRole('option', { name: /Claude Sonnet 4/ }))
act(() => {
vi.advanceTimersByTime(800)
})
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: 'anthropic/claude-sonnet-4',
},
})
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: 'anthropic/claude-sonnet-4',
},
})
} finally {
vi.useRealTimers()
}
})
it('clears the goal auditor model', () => {
vi.useFakeTimers()
try {
const updateSettings = vi.fn()
mockUseSettings({
preferences: {
...basePreferences,
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: 'anthropic/claude-sonnet-4',
},
},
updateSettings,
})
render(<SessionAutomationSettings />)
fireEvent.click(screen.getByRole('button', { name: 'Clear' }))
act(() => {
vi.advanceTimersByTime(800)
})
expect(updateSettings).toHaveBeenCalledTimes(1)
expect(updateSettings).toHaveBeenCalledWith({
sessionDefaults: {
permissionMode: 'ask',
goalMaxContinuations: 20,
goalAuditorModel: undefined,
},
})
} finally {
vi.useRealTimers()
}
})
it('saves the goal auditor model after the debounce without blurring', () => {
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { ModelCombobox } from '@/components/model/ModelCombobox'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import {
DEFAULT_SESSION_DEFAULTS,
@@ -128,16 +129,18 @@ export function SessionAutomationSettings() {
<div className="min-w-0 space-y-0.5">
<Label htmlFor="goalAuditorModel">Goal auditor model</Label>
<p className="text-sm text-muted-foreground">
Model that decides whether a session goal is done, as provider/model. Leave empty to use the OpenCode default model.
Model that decides whether a session goal is done. Leave empty to use the OpenCode default model.
</p>
</div>
<Input
<ModelCombobox
id="goalAuditorModel"
ariaLabel="Goal auditor model"
value={goalAuditorModel}
placeholder="provider/model"
onChange={setGoalAuditorModel}
placeholder="OpenCode default"
allowCustomValue
showClear
className="w-full shrink-0 sm:w-64"
onChange={(event) => setGoalAuditorModel(event.target.value)}
onBlur={commitGoalFields}
/>
</div>
+133 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Combobox } from './combobox'
import { Combobox, type ComboboxOption } from './combobox'
const options = [
{ value: 'builtin', label: 'Built-in Browser' },
@@ -64,4 +64,136 @@ describe('Combobox', () => {
expect(onOpen).toHaveBeenCalledTimes(2)
})
it('merges listClassName into the listbox and drops the default height', async () => {
const user = userEvent.setup()
render(
<Combobox
value="builtin"
onChange={vi.fn()}
options={options}
allowCustomValue={false}
ariaLabel="Provider"
listClassName="max-h-96"
/>,
)
await user.click(screen.getByRole('combobox', { name: 'Provider' }))
const listbox = screen.getByRole('listbox')
expect(listbox).toHaveClass('max-h-96')
expect(listbox).not.toHaveClass('max-h-60')
})
const modelOptions = [{ value: 'openai/gpt-5', label: 'GPT-5' }]
function renderCustomCombobox(onChange = vi.fn()) {
render(
<div>
<Combobox
value="openai/gpt-5"
onChange={onChange}
options={modelOptions}
allowCustomValue
ariaLabel="Model"
/>
<button type="button">Outside</button>
</div>,
)
return { input: screen.getByRole('combobox', { name: 'Model' }), onChange }
}
it('does not commit the display label on an outside click without typing', async () => {
const user = userEvent.setup()
const { input, onChange } = renderCustomCombobox()
await user.click(input)
await user.click(screen.getByRole('button', { name: 'Outside' }))
expect(onChange).not.toHaveBeenCalled()
expect(input).toHaveValue('GPT-5')
})
it('does not commit the display label on Tab without typing', async () => {
const user = userEvent.setup()
const { input, onChange } = renderCustomCombobox()
await user.click(input)
await user.keyboard('{Tab}')
expect(onChange).not.toHaveBeenCalled()
expect(input).toHaveValue('GPT-5')
})
it('commits a typed custom value on an outside click', async () => {
const user = userEvent.setup()
const { input, onChange } = renderCustomCombobox()
await user.click(input)
await user.clear(input)
await user.type(input, 'custom/x')
await user.click(screen.getByRole('button', { name: 'Outside' }))
expect(onChange).toHaveBeenLastCalledWith('custom/x')
})
it('commits a typed custom value on Tab', async () => {
const user = userEvent.setup()
const { input, onChange } = renderCustomCombobox()
await user.click(input)
await user.clear(input)
await user.type(input, 'custom/x')
await user.keyboard('{Tab}')
expect(onChange).toHaveBeenLastCalledWith('custom/x')
})
it('routes filtering through filterOptions when provided', async () => {
const user = userEvent.setup()
const filterOptions = vi.fn((list: ComboboxOption[], query: string) =>
list.filter((option) => option.label.toLowerCase().startsWith(query.toLowerCase())),
)
render(
<Combobox
value=""
onChange={vi.fn()}
options={options}
allowCustomValue={false}
ariaLabel="Provider"
filterOptions={filterOptions}
/>,
)
const input = screen.getByRole('combobox', { name: 'Provider' })
await user.click(input)
await user.type(input, 'ext')
expect(filterOptions).toHaveBeenCalled()
expect(screen.getByRole('option', { name: 'External API' })).toBeInTheDocument()
expect(screen.queryByRole('option', { name: 'Built-in Browser' })).not.toBeInTheDocument()
})
it('shows every option when the value matches a provided option without typing', async () => {
const user = userEvent.setup()
const filterOptions = vi.fn((list: ComboboxOption[]) => list.slice(0, 1))
render(
<Combobox
value="builtin"
onChange={vi.fn()}
options={options}
allowCustomValue={false}
ariaLabel="Provider"
filterOptions={filterOptions}
/>,
)
await user.click(screen.getByRole('combobox', { name: 'Provider' }))
expect(filterOptions).not.toHaveBeenCalled()
expect(screen.getByRole('option', { name: 'Built-in Browser' })).toBeInTheDocument()
expect(screen.getByRole('option', { name: 'External API' })).toBeInTheDocument()
})
})
+26 -11
View File
@@ -21,6 +21,8 @@ interface ComboboxProps {
ariaLabel?: string
onOpen?: () => void
id?: string
listClassName?: string
filterOptions?: (options: ComboboxOption[], query: string) => ComboboxOption[]
}
function getOptionLabel(options: ComboboxOption[], value: string): string {
@@ -39,6 +41,8 @@ export function Combobox({
ariaLabel,
onOpen,
id,
listClassName,
filterOptions,
}: ComboboxProps) {
const [isOpen, setIsOpen] = useState(false)
const [inputValue, setInputValue] = useState(() => getOptionLabel(options, value))
@@ -69,12 +73,16 @@ export function Combobox({
}, [options, value])
const isExactMatch = options.some(o => o.value === value || o.label === inputValue)
const filteredOptions = (isExactMatch && !isUserTyping) ? options : options.filter(option =>
option.value.toLowerCase().includes(inputValue.toLowerCase()) ||
option.label.toLowerCase().includes(inputValue.toLowerCase()) ||
(option.description?.toLowerCase().includes(inputValue.toLowerCase()))
)
const filteredOptions = (isExactMatch && !isUserTyping)
? options
: filterOptions
? filterOptions(options, inputValue)
: options.filter(option =>
option.value.toLowerCase().includes(inputValue.toLowerCase()) ||
option.label.toLowerCase().includes(inputValue.toLowerCase()) ||
(option.description?.toLowerCase().includes(inputValue.toLowerCase()))
)
const groupedOptions = filteredOptions.reduce((acc, option) => {
const group = option.group || ''
@@ -95,7 +103,7 @@ export function Combobox({
const handleClickOutside = (e: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setIsOpen(false)
if (allowCustomValue) {
if (allowCustomValue && isUserTyping) {
onChange(inputValue)
} else {
restoreSelectedLabel()
@@ -105,7 +113,7 @@ export function Combobox({
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen, inputValue, onChange, allowCustomValue, restoreSelectedLabel])
}, [isOpen, inputValue, onChange, allowCustomValue, restoreSelectedLabel, isUserTyping])
useEffect(() => {
if (!isOpen || !listRef.current) return
@@ -160,11 +168,15 @@ export function Combobox({
case 'Tab':
setIsOpen(false)
if (allowCustomValue) {
onChange(inputValue)
if (isUserTyping) {
onChange(inputValue)
} else {
restoreSelectedLabel()
}
}
break
}
}, [isOpen, selectedIndex, flatFilteredOptions, handleSelect, allowCustomValue, inputValue, onChange, restoreSelectedLabel])
}, [isOpen, selectedIndex, flatFilteredOptions, handleSelect, allowCustomValue, inputValue, onChange, restoreSelectedLabel, isUserTyping])
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value
@@ -248,7 +260,10 @@ export function Combobox({
<div
ref={listRef}
role="listbox"
className="absolute z-[150] mt-1 w-full bg-popover border border-border rounded-md shadow-lg max-h-60 overflow-y-auto"
className={cn(
'absolute z-[150] mt-1 w-full bg-popover border border-border rounded-md shadow-lg max-h-60 overflow-y-auto',
listClassName
)}
>
{Object.entries(groupedOptions).map(([group, groupOptions]) => (
<div key={group || 'default'}>
+1 -2
View File
@@ -686,7 +686,6 @@ describe('EventProvider permissions and forms', () => {
for (const queryKey of [
['provider-credentials'],
['provider-auth-methods'],
['providers-with-models'],
['opencode', 'providers'],
]) {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey })
@@ -720,7 +719,7 @@ describe('EventProvider permissions and forms', () => {
await waitFor(() => {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
})
expect(invalidateQueries).toHaveBeenCalledTimes(4)
expect(invalidateQueries).toHaveBeenCalledTimes(3)
})
it.each<[string, string[]]>([
+3 -2
View File
@@ -1,5 +1,6 @@
import { useMemo } from 'react'
import { skipToken, useQuery } from '@tanstack/react-query'
import { formatOpenCodeModelRef, findModelInfo } from '@opencode-manager/shared/opencode'
import { useProviders } from '@/hooks/useProviders'
import { sessionTranscriptQueryKey } from '@/lib/queryInvalidation'
import type { TranscriptCache } from '@/lib/session-projection'
@@ -40,12 +41,12 @@ export const useContextUsage = (sessionID: string | undefined, directory?: strin
const activeModel = latestAssistantMessage?.type === 'assistant' ? latestAssistantMessage.model : undefined
const currentModel = activeModel
? `${activeModel.providerID}/${activeModel.id}`
? formatOpenCodeModelRef(activeModel)
: null
let contextLimit: number | null = null
if (activeModel && models) {
const model = models.find(item => item.providerID === activeModel.providerID && item.id === activeModel.id)
const model = findModelInfo(models, { providerID: activeModel.providerID, modelID: activeModel.id })
if (model?.limit) {
contextLimit = model.limit.context
}
@@ -0,0 +1,61 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook } from '@testing-library/react'
import { useModelSections } from './useModelSections'
import type { Provider } from '@/api/providers'
const mocks = vi.hoisted(() => ({
useProviders: vi.fn(),
useOpenCodeModelState: vi.fn(),
useOpenCodeDefaultModel: vi.fn(),
}))
vi.mock('./useProviders', () => ({ useProviders: mocks.useProviders }))
vi.mock('./useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
}))
const providers: Provider[] = [
{
id: 'openai',
name: 'OpenAI',
models: [
{ id: 'gpt-5', key: 'gpt-5', name: 'GPT-5', released: 0, free: false },
{ id: 'gpt-4o', key: 'gpt-4o', name: 'GPT-4o', released: 0, free: false },
{ id: 'gpt-4.1', key: 'gpt-4.1', name: 'GPT-4.1', released: 0, free: false },
],
},
]
describe('useModelSections', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useProviders.mockReturnValue({ data: { providers, models: [] }, isLoading: false })
mocks.useOpenCodeModelState.mockReturnValue({
data: { favorite: [{ providerID: 'openai', modelID: 'gpt-4o' }], recent: [], variant: {} },
isLoading: false,
})
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: 'openai/gpt-5', isLoading: false })
})
it('builds sections from the catalog, model state and the default model', () => {
const { result } = renderHook(() => useModelSections('/repo'))
expect(result.current.providers).toBe(providers)
expect(result.current.sections.map((section) => section.key)).toEqual(['default', 'favorites', 'provider:openai'])
expect(result.current.defaultModel).toBe('openai/gpt-5')
expect(result.current.isLoading).toBe(false)
})
it('falls back to an empty provider list and reports loading', () => {
mocks.useProviders.mockReturnValue({ data: undefined, isLoading: true })
mocks.useOpenCodeModelState.mockReturnValue({ data: undefined, isLoading: true })
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: undefined, isLoading: true })
const { result } = renderHook(() => useModelSections('/repo'))
expect(result.current.providers).toEqual([])
expect(result.current.sections).toEqual([])
expect(result.current.isLoading).toBe(true)
})
})
+40
View File
@@ -0,0 +1,40 @@
import { useMemo } from 'react'
import { useProviders } from './useProviders'
import { useOpenCodeDefaultModel, useOpenCodeModelState } from './useModelSelection'
import { buildModelSections, type ModelSection } from '@/lib/modelSections'
import type { OpenCodeModelState, Provider } from '@/api/providers'
const EMPTY_PROVIDERS: Provider[] = []
export interface UseModelSectionsResult {
providers: Provider[]
sections: ModelSection[]
defaultModel: string | null | undefined
modelState: OpenCodeModelState | undefined
isLoading: boolean
}
export function useModelSections(
directory?: string,
options: { enabled?: boolean } = {},
): UseModelSectionsResult {
const enabled = options.enabled ?? true
const { data: catalog, isLoading: catalogLoading } = useProviders(directory, { enabled })
const { data: modelState, isLoading: modelStateLoading } = useOpenCodeModelState(directory, enabled)
const { data: defaultModel, isLoading: defaultModelLoading } = useOpenCodeDefaultModel(directory, enabled)
const providers = catalog?.providers ?? EMPTY_PROVIDERS
const sections = useMemo(
() => buildModelSections(providers, modelState, defaultModel),
[providers, modelState, defaultModel],
)
return {
providers,
sections,
defaultModel,
modelState,
isLoading: catalogLoading || modelStateLoading || defaultModelLoading,
}
}
+503 -291
View File
@@ -1,9 +1,12 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { act, renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useModelSelection } from './useModelSelection'
import { useModelSelection, useOpenCodeDefaultModel } from './useModelSelection'
import { useProviders } from './useProviders'
import { useModelStore, type ModelSelection } from '@/stores/modelStore'
import * as providersApi from '@/api/providers'
import type { Provider } from '@/api/providers'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
const createTestQueryClient = () => new QueryClient({
defaultOptions: {
@@ -18,7 +21,8 @@ vi.mock('@/api/providers', async () => {
return {
...actual,
getProviders: vi.fn(),
getOpenCodeConfigModel: vi.fn(),
getOpenCodeConfiguredModel: vi.fn(),
getOpenCodeServerDefaultModel: vi.fn(),
getOpenCodeModelState: vi.fn(),
addOpenCodeRecentModel: vi.fn(),
removeOpenCodeRecentModel: vi.fn(),
@@ -27,49 +31,57 @@ vi.mock('@/api/providers', async () => {
})
const mockGetProviders = vi.mocked(providersApi.getProviders)
const mockGetOpenCodeConfigModel = vi.mocked(providersApi.getOpenCodeConfigModel)
const mockGetOpenCodeConfiguredModel = vi.mocked(providersApi.getOpenCodeConfiguredModel)
const mockGetOpenCodeServerDefaultModel = vi.mocked(providersApi.getOpenCodeServerDefaultModel)
const mockGetOpenCodeModelState = vi.mocked(providersApi.getOpenCodeModelState)
const mockAddOpenCodeRecentModel = vi.mocked(providersApi.addOpenCodeRecentModel)
const mockRemoveOpenCodeRecentModel = vi.mocked(providersApi.removeOpenCodeRecentModel)
const mockToggleOpenCodeFavoriteModel = vi.mocked(providersApi.toggleOpenCodeFavoriteModel)
const modelInfo = (providerID: string, id: string, variants: string[] = []): ModelInfo => ({
providerID,
id,
modelID: id,
name: id,
enabled: true,
status: 'active',
variants: variants.map((variant) => ({ id: variant })),
time: { released: 0 },
cost: [],
limit: { context: 0, output: 0 },
} as unknown as ModelInfo)
const provider = (id: string, name: string, modelIDs: string[]): Provider => ({
id,
name,
models: modelIDs.map((modelID) => ({
id: modelID,
key: modelID,
name: modelID,
released: 0,
free: false,
})),
})
const emptyState = () => ({ recent: [], favorite: [], variant: {} })
describe('useModelSelection', () => {
beforeEach(() => {
vi.clearAllMocks()
useModelStore.getState().setModel({ providerID: 'test', modelID: 'test-model' })
useModelStore.getState().setActiveModel({ providerID: 'test', modelID: 'test-model' })
mockGetProviders.mockResolvedValue({
providers: [],
connected: [],
})
mockGetOpenCodeConfigModel.mockResolvedValue(null)
mockGetOpenCodeModelState.mockResolvedValue({
recent: [],
favorite: [],
variant: {},
})
mockAddOpenCodeRecentModel.mockResolvedValue({
recent: [],
favorite: [],
variant: {},
})
mockRemoveOpenCodeRecentModel.mockResolvedValue({
recent: [],
favorite: [],
variant: {},
})
mockToggleOpenCodeFavoriteModel.mockResolvedValue({
recent: [],
favorite: [],
variant: {},
})
useModelStore.setState({ newSessionPicks: {}, sessionPicks: {}, activeAgent: null })
mockGetProviders.mockResolvedValue({ providers: [], models: [] })
mockGetOpenCodeConfiguredModel.mockResolvedValue(null)
mockGetOpenCodeModelState.mockResolvedValue(emptyState())
mockAddOpenCodeRecentModel.mockResolvedValue(emptyState())
mockRemoveOpenCodeRecentModel.mockResolvedValue(emptyState())
mockToggleOpenCodeFavoriteModel.mockResolvedValue(emptyState())
})
const renderHookWithProviders = () => {
const renderHookWithProviders = (directory = '/test') => {
const queryClient = createTestQueryClient()
return renderHook(
() => useModelSelection('/test'),
() => useModelSelection(directory),
{
wrapper: ({ children }) => (
<QueryClientProvider client={queryClient}>
@@ -80,89 +92,409 @@ describe('useModelSelection', () => {
)
}
it('does not restore before providers are loaded', async () => {
mockGetProviders.mockImplementation(() => new Promise(() => {}))
const { result } = renderHookWithProviders()
const testModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
const returnValue = result.current.setActiveModel(testModel)
expect(returnValue).toBe(false)
expect(useModelStore.getState().model).not.toEqual(testModel)
})
it('restores when model exists in providers', async () => {
const providersData = {
providers: [
{
id: 'anthropic',
name: 'Anthropic',
models: {
'claude-sonnet-4': { id: 'claude-sonnet-4', name: 'Claude Sonnet 4' },
},
isConnected: true,
env: [],
options: {},
},
],
connected: ['anthropic'],
describe('new-session selection order', () => {
const anthropic = provider('anthropic', 'Anthropic', ['claude-sonnet-4'])
const openai = provider('openai', 'OpenAI', ['gpt-4o'])
const catalog = {
providers: [anthropic, openai],
models: [modelInfo('anthropic', 'claude-sonnet-4'), modelInfo('openai', 'gpt-4o')],
}
mockGetProviders.mockResolvedValue(providersData as any)
it('prefers the active agent model over the configured model', async () => {
mockGetProviders.mockResolvedValue(catalog)
mockGetOpenCodeConfiguredModel.mockResolvedValue('openai/gpt-4o')
useModelStore.getState().setActiveAgent({
id: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
})
const { result } = renderHookWithProviders()
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current).toBeDefined()
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
})
await waitFor(() => {
expect(mockGetProviders).toHaveBeenCalled()
it('prefers the configured model over the recent list', async () => {
mockGetProviders.mockResolvedValue(catalog)
mockGetOpenCodeConfiguredModel.mockResolvedValue('openai/gpt-4o')
mockGetOpenCodeModelState.mockResolvedValue({
recent: [{ providerID: 'anthropic', modelID: 'claude-sonnet-4' }],
favorite: [],
variant: {},
})
useModelStore.getState().setActiveAgent({ id: 'build' })
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
})
const testModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
const returnValue = result.current.setActiveModel(testModel)
it('uses the first valid recent and skips an invalid one', async () => {
mockGetProviders.mockResolvedValue(catalog)
mockGetOpenCodeModelState.mockResolvedValue({
recent: [
{ providerID: 'ghost', modelID: 'gone' },
{ providerID: 'openai', modelID: 'gpt-4o' },
],
favorite: [],
variant: {},
})
useModelStore.getState().setActiveAgent({ id: 'build' })
expect(returnValue).toBe(true)
expect(useModelStore.getState().model).toEqual(testModel)
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
})
it('falls back to the first catalog model', async () => {
mockGetProviders.mockResolvedValue(catalog)
useModelStore.getState().setActiveAgent({ id: 'build' })
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
})
it('remembers a user pick per directory and agent', async () => {
mockGetProviders.mockResolvedValue(catalog)
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.model).not.toBeNull()
})
act(() => {
result.current.setActiveAgent({ id: 'a' })
})
act(() => {
result.current.setModel({ providerID: 'openai', modelID: 'gpt-4o' })
})
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
act(() => {
result.current.setActiveAgent({ id: 'b' })
})
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
act(() => {
result.current.setActiveAgent({ id: 'a' })
})
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
})
it('returns null when the catalog is not loaded', () => {
mockGetProviders.mockImplementation(() => new Promise(() => {}))
const { result } = renderHookWithProviders()
expect(result.current.model).toBeNull()
})
it('does not record a recent when the active agent changes', async () => {
mockGetProviders.mockResolvedValue(catalog)
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.model).not.toBeNull()
})
act(() => {
result.current.setActiveAgent({ id: 'a', model: { providerID: 'openai', id: 'gpt-4o' } })
})
act(() => {
result.current.setActiveAgent({ id: 'b' })
})
expect(mockAddOpenCodeRecentModel).not.toHaveBeenCalled()
})
})
it('rejects unknown model after providers are loaded', async () => {
const providersData = {
providers: [
{
id: 'anthropic',
name: 'Anthropic',
models: {
'claude-sonnet-4': { id: 'claude-sonnet-4', name: 'Claude Sonnet 4' },
},
isConnected: true,
env: [],
options: {},
},
],
connected: ['anthropic'],
describe('readiness', () => {
const catalog = {
providers: [provider('anthropic', 'Anthropic', ['claude-sonnet-4'])],
models: [modelInfo('anthropic', 'claude-sonnet-4')],
}
mockGetProviders.mockResolvedValue(providersData as any)
it('is not ready and returns null while the model state loads', () => {
mockGetProviders.mockResolvedValue(catalog)
mockGetOpenCodeModelState.mockImplementation(() => new Promise(() => {}))
const { result } = renderHookWithProviders()
expect(result.current.isModelReady).toBe(false)
expect(result.current.model).toBeNull()
})
it('is not ready and returns null while the configured model loads', () => {
mockGetProviders.mockResolvedValue(catalog)
mockGetOpenCodeConfiguredModel.mockImplementation(() => new Promise(() => {}))
const { result } = renderHookWithProviders()
expect(result.current.isModelReady).toBe(false)
expect(result.current.model).toBeNull()
})
it('returns null while a directory switch serves placeholder catalog data', async () => {
const catalogA = {
providers: [provider('anthropic', 'Anthropic', ['claude-sonnet-4'])],
models: [modelInfo('anthropic', 'claude-sonnet-4')],
}
const catalogB = {
providers: [provider('openai', 'OpenAI', ['gpt-4o'])],
models: [modelInfo('openai', 'gpt-4o')],
}
let resolveB: (value: typeof catalogB) => void = () => {}
mockGetProviders.mockImplementation((directory?: string) => {
if (directory === '/b') return new Promise((resolve) => { resolveB = resolve })
return Promise.resolve(catalogA)
})
const queryClient = createTestQueryClient()
const { result, rerender } = renderHook(
({ directory }: { directory: string }) => useModelSelection(directory),
{
initialProps: { directory: '/a' },
wrapper: ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
},
)
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
rerender({ directory: '/b' })
expect(result.current.isModelReady).toBe(false)
expect(result.current.model).toBeNull()
await act(async () => {
resolveB(catalogB)
})
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
})
})
describe('session selection', () => {
const anthropic = provider('anthropic', 'Anthropic', ['claude-sonnet-4'])
const openai = provider('openai', 'OpenAI', ['gpt-4o'])
const catalog = {
providers: [anthropic, openai],
models: [modelInfo('anthropic', 'claude-sonnet-4', ['high', 'low']), modelInfo('openai', 'gpt-4o')],
}
const renderSession = (session: { id: string; agent?: string; model?: { providerID: string; id: string; variant?: string } }) => {
const queryClient = createTestQueryClient()
return renderHook(
() => useModelSelection('/test', session),
{
wrapper: ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
},
)
}
beforeEach(() => {
mockGetProviders.mockResolvedValue(catalog)
useModelStore.getState().setActiveAgent({ id: 'build' })
})
it('uses the durable session model with its variant', async () => {
const { result } = renderSession({
id: 's1',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4', variant: 'high' },
})
await waitFor(() => {
expect(result.current.selection).toEqual({
providerID: 'anthropic',
modelID: 'claude-sonnet-4',
variant: 'high',
})
})
})
it('does not write to the store when viewing a session', async () => {
const { result } = renderSession({
id: 's1',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
})
await waitFor(() => {
expect(result.current.model).not.toBeNull()
})
expect(useModelStore.getState().sessionPicks).toEqual({})
expect(useModelStore.getState().newSessionPicks).toEqual({})
})
it('prefers a session pick over the durable selection', async () => {
useModelStore.getState().setSessionPick('s1', 'build', {
providerID: 'openai',
modelID: 'gpt-4o',
})
const { result } = renderSession({
id: 's1',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
})
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
})
it('ignores the durable selection when the session agent differs from the active agent', async () => {
useModelStore.getState().setActiveAgent({ id: 'plan' })
const { result } = renderSession({
id: 's1',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
})
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
})
it('treats a default session variant as no variant without saved-preference fallback', async () => {
mockGetOpenCodeModelState.mockResolvedValue({
recent: [],
favorite: [],
variant: { 'anthropic/claude-sonnet-4': 'high' },
})
const { result } = renderSession({
id: 's1',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4', variant: 'default' },
})
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
expect(result.current.selection?.variant).toBeUndefined()
})
it('drops the session variant when the model does not declare it', async () => {
const { result } = renderSession({
id: 's1',
agent: 'build',
model: { providerID: 'openai', id: 'gpt-4o', variant: 'high' },
})
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
expect(result.current.selection?.variant).toBeUndefined()
})
it('stores an explicit pick for the session agent', async () => {
const { result } = renderSession({
id: 's1',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
})
await waitFor(() => {
expect(result.current.model).not.toBeNull()
})
act(() => {
result.current.setModel({ providerID: 'openai', modelID: 'gpt-4o' })
})
expect(useModelStore.getState().sessionPicks['s1'].build).toEqual({
providerID: 'openai',
modelID: 'gpt-4o',
})
await waitFor(() => {
expect(mockAddOpenCodeRecentModel).toHaveBeenCalledTimes(1)
})
})
it('drops the session draft when the pick equals the durable selection', async () => {
const { result } = renderSession({
id: 's1',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
})
await waitFor(() => {
expect(result.current.model).not.toBeNull()
})
act(() => {
result.current.setModel({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
expect(useModelStore.getState().sessionPicks['s1']?.build).toBeUndefined()
})
it('does not mutate picks when the active agent switches inside a session', async () => {
const { result } = renderSession({
id: 's1',
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
})
await waitFor(() => {
expect(result.current.model).not.toBeNull()
})
act(() => {
result.current.setActiveAgent({ id: 'plan' })
})
act(() => {
result.current.setActiveAgent({ id: 'build' })
})
expect(useModelStore.getState().sessionPicks).toEqual({})
expect(useModelStore.getState().newSessionPicks).toEqual({})
})
})
it('records a recent on setModel', async () => {
mockGetProviders.mockResolvedValue({ providers: [], models: [] })
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current).toBeDefined()
act(() => {
result.current.setModel({ providerID: 'openai', modelID: 'gpt-4o' })
})
await waitFor(() => {
expect(mockGetProviders).toHaveBeenCalled()
expect(mockAddOpenCodeRecentModel).toHaveBeenCalledTimes(1)
})
const initialModel = useModelStore.getState().model
const testModel: ModelSelection = { providerID: 'anthropic', modelID: 'missing-model' }
const returnValue = result.current.setActiveModel(testModel)
expect(returnValue).toBe(false)
expect(useModelStore.getState().model).toEqual(initialModel)
expect(mockAddOpenCodeRecentModel.mock.calls[0][0]).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
describe('recentModels/favoriteModels derived from React Query', () => {
@@ -180,25 +512,11 @@ describe('useModelSelection', () => {
})
mockGetProviders.mockResolvedValue({
providers: [
{
id: 'AI2',
name: 'AI2',
models: { foo: { id: 'foo', name: 'Foo' } },
isConnected: true,
env: [],
options: {},
},
{
id: 'VLLM',
name: 'VLLM',
models: { bar: { id: 'bar', name: 'Bar' } },
isConnected: true,
env: [],
options: {},
},
provider('AI2', 'AI2', ['foo']),
provider('VLLM', 'VLLM', ['bar']),
],
connected: ['AI2', 'VLLM'],
} as any)
models: [modelInfo('AI2', 'foo'), modelInfo('VLLM', 'bar')],
})
const { result } = renderHookWithProviders()
@@ -234,10 +552,7 @@ describe('useModelSelection', () => {
favorite: [{ providerID: 'VLLM', modelID: 'bar' }],
variant: {},
})
mockGetProviders.mockResolvedValue({
providers: [],
connected: [],
} as any)
mockGetProviders.mockResolvedValue({ providers: [], models: [] })
const { result } = renderHookWithProviders()
@@ -249,132 +564,7 @@ describe('useModelSelection', () => {
})
})
describe('startup model resolution', () => {
const providersData = {
providers: [
{
id: 'anthropic',
name: 'Anthropic',
models: {
'claude-sonnet-4': { id: 'claude-sonnet-4', name: 'Claude Sonnet 4' },
'claude-opus-4': { id: 'claude-opus-4', name: 'Claude Opus 4' },
},
isConnected: true,
env: [],
options: {},
},
{
id: 'openai',
name: 'OpenAI',
models: {
'gpt-4o': { id: 'gpt-4o', name: 'GPT-4o' },
},
isConnected: true,
env: [],
options: {},
},
],
connected: ['anthropic', 'openai'],
}
const recentState = (recent: ModelSelection[]) => ({ recent, favorite: [], variant: {} })
it('prefers the config model over a recent model', async () => {
mockGetProviders.mockResolvedValue(providersData as any)
mockGetOpenCodeConfigModel.mockResolvedValue('anthropic/claude-opus-4')
mockGetOpenCodeModelState.mockResolvedValue(recentState([{ providerID: 'openai', modelID: 'gpt-4o' }]))
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'anthropic', modelID: 'claude-opus-4' })
})
expect(mockGetOpenCodeConfigModel).toHaveBeenCalledWith('/test')
})
it('falls through an unavailable config model to the first valid recent model', async () => {
mockGetProviders.mockResolvedValue(providersData as any)
mockGetOpenCodeConfigModel.mockResolvedValue('anthropic/missing-model')
mockGetOpenCodeModelState.mockResolvedValue(recentState([
{ providerID: 'ghost', modelID: 'gone' },
{ providerID: 'openai', modelID: 'gpt-4o' },
]))
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
})
it('prefers a valid recent model over the first available model', async () => {
mockGetProviders.mockResolvedValue(providersData as any)
mockGetOpenCodeModelState.mockResolvedValue(recentState([{ providerID: 'openai', modelID: 'gpt-4o' }]))
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
})
it('falls back to the first available model without config or recent models', async () => {
mockGetProviders.mockResolvedValue(providersData as any)
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
})
it('waits for the config model to settle before resolving', async () => {
let resolveConfigModel: (value: string | null) => void = () => {}
mockGetProviders.mockResolvedValue(providersData as any)
mockGetOpenCodeConfigModel.mockImplementation(() => new Promise((resolve) => {
resolveConfigModel = resolve
}))
mockGetOpenCodeModelState.mockResolvedValue(recentState([
{ providerID: 'ghost', modelID: 'gone' },
{ providerID: 'openai', modelID: 'gpt-4o' },
]))
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(result.current.recentModels).toEqual([{ providerID: 'openai', modelID: 'gpt-4o' }])
})
expect(result.current.model).toEqual({ providerID: 'test', modelID: 'test-model' })
act(() => {
resolveConfigModel('anthropic/claude-opus-4')
})
await waitFor(() => {
expect(result.current.model).toEqual({ providerID: 'anthropic', modelID: 'claude-opus-4' })
})
})
it('keeps an explicit in-memory selection across a refresh', async () => {
mockGetProviders.mockResolvedValue(providersData as any)
mockGetOpenCodeModelState.mockResolvedValue({
recent: [{ providerID: 'anthropic', modelID: 'claude-sonnet-4' }],
favorite: [],
variant: {},
})
useModelStore.getState().setModel({ providerID: 'openai', modelID: 'gpt-4o' })
const { result } = renderHookWithProviders()
await waitFor(() => {
expect(mockGetProviders).toHaveBeenCalled()
})
expect(result.current.model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
})
it('toggleFavorite calls toggleOpenCodeFavoriteModel and does not mutate Zustand', async () => {
it('toggleFavorite calls toggleOpenCodeFavoriteModel and does not mutate the store', async () => {
const { result } = renderHookWithProviders()
await waitFor(() => {
@@ -388,7 +578,7 @@ describe('useModelSelection', () => {
expect(mockToggleOpenCodeFavoriteModel).toHaveBeenCalledTimes(1)
})
expect(mockToggleOpenCodeFavoriteModel.mock.calls[0][0]).toEqual(testModel)
expect(useModelStore.getState().model).not.toEqual(testModel)
expect(useModelStore.getState().newSessionPicks).toEqual({})
})
it('removes recent models optimistically and rolls back on failure', async () => {
@@ -426,63 +616,85 @@ describe('useModelSelection', () => {
expect(result.current.recentModels).toEqual([removedModel, retainedModel])
})
})
})
it('user selection still updates recents', async () => {
const providersData = {
providers: [
{
id: 'anthropic',
name: 'Anthropic',
models: {
'claude-sonnet-4': { id: 'claude-sonnet-4', name: 'Claude Sonnet 4' },
},
isConnected: true,
env: [],
options: {},
},
],
connected: ['anthropic'],
}
describe('useOpenCodeDefaultModel', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetOpenCodeConfiguredModel.mockResolvedValue(null)
mockGetOpenCodeServerDefaultModel.mockResolvedValue(null)
})
mockGetProviders.mockResolvedValue(providersData as any)
mockAddOpenCodeRecentModel.mockResolvedValue({
recent: [{ providerID: 'anthropic', modelID: 'claude-sonnet-4' }],
favorite: [],
variant: {},
const renderDefaultModel = (directory = '/test') => {
const queryClient = createTestQueryClient()
return renderHook(
() => ({
providers: useProviders(directory),
defaultModel: useOpenCodeDefaultModel(directory),
}),
{
wrapper: ({ children }) => (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
),
},
)
}
it('prefers a configured model that is listed, with its variant', async () => {
mockGetOpenCodeConfiguredModel.mockResolvedValue('anthropic/claude-sonnet-4#thinking')
mockGetProviders.mockResolvedValue({
providers: [provider('anthropic', 'Anthropic', ['claude-sonnet-4'])],
models: [modelInfo('anthropic', 'claude-sonnet-4')],
})
const { result } = renderHookWithProviders()
const { result } = renderDefaultModel()
await waitFor(() => {
expect(result.current).toBeDefined()
})
await waitFor(() => {
expect(mockGetProviders).toHaveBeenCalled()
})
const testModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
result.current.setModel(testModel)
expect(useModelStore.getState().model).toEqual(testModel)
await waitFor(() => {
expect(mockAddOpenCodeRecentModel).toHaveBeenCalled()
expect(mockAddOpenCodeRecentModel.mock.calls[0][0]).toEqual(testModel)
})
await waitFor(() => {
expect(mockAddOpenCodeRecentModel).toHaveBeenCalledTimes(1)
expect(result.current.defaultModel.data).toBe('anthropic/claude-sonnet-4#thinking')
})
})
it('restoreSessionModel sets model without requiring providers', async () => {
mockGetProviders.mockImplementation(() => new Promise(() => {}))
it('falls back to the server default when the configured model is not listed', async () => {
mockGetOpenCodeConfiguredModel.mockResolvedValue('openai/retired')
mockGetOpenCodeServerDefaultModel.mockResolvedValue({ providerID: 'openai', id: 'gpt-4o' })
mockGetProviders.mockResolvedValue({
providers: [provider('openai', 'OpenAI', ['gpt-4o'])],
models: [modelInfo('openai', 'gpt-4o')],
})
const { result } = renderHookWithProviders()
const { result } = renderDefaultModel()
const sessionModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
result.current.restoreSessionModel(sessionModel)
await waitFor(() => {
expect(result.current.defaultModel.data).toBe('openai/gpt-4o')
})
})
expect(useModelStore.getState().model).toEqual(sessionModel)
it('falls back to the first enabled model when neither is available', async () => {
mockGetProviders.mockResolvedValue({
providers: [provider('anthropic', 'Anthropic', ['claude-sonnet-4'])],
models: [modelInfo('anthropic', 'claude-sonnet-4')],
})
const { result } = renderDefaultModel()
await waitFor(() => {
expect(result.current.defaultModel.data).toBe('anthropic/claude-sonnet-4')
})
})
it('fetches the catalog once when both hooks are mounted for the same directory', async () => {
mockGetProviders.mockResolvedValue({
providers: [provider('anthropic', 'Anthropic', ['claude-sonnet-4'])],
models: [modelInfo('anthropic', 'claude-sonnet-4')],
})
const { result } = renderDefaultModel()
await waitFor(() => {
expect(result.current.defaultModel.data).toBeDefined()
})
expect(mockGetProviders).toHaveBeenCalledTimes(1)
})
})
+308 -127
View File
@@ -1,31 +1,66 @@
import { useEffect, useMemo } from 'react'
import { useMemo } from 'react'
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useModelStore, modelExists, type ModelSelection } from '@/stores/modelStore'
import { locationAgentKey, useModelStore, type ActiveAgent, type ModelPick, type ModelSelection } from '@/stores/modelStore'
import { useProviders } from './useProviders'
import { addOpenCodeRecentModel, getOpenCodeConfigModel, getOpenCodeModelState, removeOpenCodeRecentModel, toggleOpenCodeFavoriteModel, type OpenCodeModelState } from '@/api/providers'
import { isModelAvailable } from '@/lib/modelCatalog'
import {
addOpenCodeRecentModel,
getOpenCodeConfiguredModel,
getOpenCodeModelState,
getOpenCodeServerDefaultModel,
modelSelectionRef,
removeOpenCodeRecentModel,
toggleOpenCodeFavoriteModel,
type OpenCodeModelState,
} from '@/api/providers'
import {
addRecentModel,
findModelInfo,
formatOpenCodeModelRef,
isSameModelSelection,
modelPreferenceKey,
normalizeModelVariant,
parseOpenCodeModelRef,
removeRecentModel,
selectEffectiveModelRef,
selectInteractiveModel,
selectPreferredVariant,
toggleFavoriteModel,
type ModelInfo,
type ModelRef,
} from '@opencode-manager/shared/opencode'
export interface ModelSelectionSession {
id: string
agent?: string
model?: ModelRef
}
interface UseModelSelectionResult {
model: ModelSelection | null
selection: ModelPick | null
info: ModelInfo | undefined
modelString: string | null
modelRef: ModelRef | null
activeAgent: ActiveAgent | null
recentModels: ModelSelection[]
favoriteModels: ModelSelection[]
configured: ModelRef | null
modelState: OpenCodeModelState | undefined
isModelReady: boolean
setModel: (model: ModelSelection) => void
setActiveModel: (model: ModelSelection) => boolean
restoreSessionModel: (model: ModelSelection) => void
setActiveAgent: (agent: ActiveAgent) => void
toggleFavorite: (model: ModelSelection) => void
removeRecentModel: (model: ModelSelection) => void
isModelStateLoading: boolean
}
const modelStateQueryKey = ['opencode', 'model-state']
export function modelStateQueryKey() {
return ['opencode', 'model-state'] as const
}
const isSameModel = (left: ModelSelection, right: ModelSelection) => (
left.providerID === right.providerID && left.modelID === right.modelID
)
export function useOpenCodeModelState(directory?: string, enabled = true) {
export function useOpenCodeModelState(_directory?: string, enabled = true) {
return useQuery({
queryKey: [...modelStateQueryKey, directory],
queryKey: modelStateQueryKey(),
queryFn: () => getOpenCodeModelState(),
staleTime: 30000,
placeholderData: keepPreviousData,
@@ -33,167 +68,313 @@ export function useOpenCodeModelState(directory?: string, enabled = true) {
})
}
export function useOpenCodeConfigModel(directory?: string, enabled = true) {
function useOpenCodeConfiguredModel(directory?: string, enabled = true) {
return useQuery({
queryKey: ['opencode', 'config', 'model', directory],
queryFn: () => getOpenCodeConfigModel(directory),
queryFn: () => getOpenCodeConfiguredModel(directory),
staleTime: 30000,
enabled,
})
}
export function useModelSelection(directory?: string): UseModelSelectionResult {
export function useOpenCodeDefaultModel(directory?: string, enabled = true) {
const providersQuery = useProviders(directory, { enabled })
const configuredQuery = useOpenCodeConfiguredModel(directory, enabled)
const defaultQuery = useQuery({
queryKey: ['opencode', 'providers', 'default-model', directory],
queryFn: () => getOpenCodeServerDefaultModel(directory),
staleTime: 30000,
enabled,
})
const data = useMemo(() => {
if (
!providersQuery.data ||
providersQuery.isPlaceholderData ||
configuredQuery.data === undefined ||
defaultQuery.data === undefined
) {
return undefined
}
const configured = configuredQuery.data ? parseOpenCodeModelRef(configuredQuery.data) : undefined
const resolved = selectEffectiveModelRef({
models: providersQuery.data.models,
defaultModel: defaultQuery.data,
candidates: [configured],
})
return resolved ? formatOpenCodeModelRef(resolved) : null
}, [providersQuery.data, providersQuery.isPlaceholderData, configuredQuery.data, defaultQuery.data])
return {
data,
isLoading: providersQuery.isLoading || configuredQuery.isLoading || defaultQuery.isLoading,
}
}
export function useModelStateMutation<TInput>(
fetcher: (input: TInput) => Promise<OpenCodeModelState>,
applyOptimistic: (state: OpenCodeModelState, input: TInput) => OpenCodeModelState,
errorMessage: string,
) {
const queryClient = useQueryClient()
const { data: providersData } = useProviders(directory)
const {
model,
setModel: setStoreModel,
setActiveModel: setStoreActiveModel,
syncModelState,
validateAndSyncModel,
getModelString
} = useModelStore()
const { data: modelState, isLoading: isModelStateLoading } = useOpenCodeModelState(directory)
const { data: configModelString, isLoading: isConfigModelLoading } = useOpenCodeConfigModel(directory)
const updateRecentModel = useMutation({
mutationFn: addOpenCodeRecentModel,
onSuccess: (state) => {
syncModelState(state)
queryClient.setQueryData([...modelStateQueryKey, directory], state)
queryClient.invalidateQueries({ queryKey: [...modelStateQueryKey, directory] })
},
onError: (error) => {
console.error('Failed to sync recent model to backend', error)
},
})
const updateFavoriteModel = useMutation({
mutationFn: toggleOpenCodeFavoriteModel,
onSuccess: (state) => {
syncModelState(state)
queryClient.setQueryData([...modelStateQueryKey, directory], state)
queryClient.invalidateQueries({ queryKey: [...modelStateQueryKey, directory] })
},
onError: (error) => {
console.error('Failed to toggle favorite model on backend', error)
},
})
const removeRecentMutation = useMutation({
mutationFn: removeOpenCodeRecentModel,
onMutate: async (removedModel) => {
const queryKey = [...modelStateQueryKey, directory]
return useMutation({
mutationFn: fetcher,
onMutate: async (input) => {
const queryKey = modelStateQueryKey()
await queryClient.cancelQueries({ queryKey })
const previousState = queryClient.getQueryData<OpenCodeModelState>(queryKey)
if (previousState) {
const nextState: OpenCodeModelState = {
...previousState,
recent: previousState.recent.filter((model) => !isSameModel(model, removedModel)),
}
queryClient.setQueryData(queryKey, nextState)
syncModelState(nextState)
}
if (previousState) queryClient.setQueryData(queryKey, applyOptimistic(previousState, input))
return { previousState }
},
onSuccess: (state) => {
syncModelState(state)
queryClient.setQueryData([...modelStateQueryKey, directory], state)
queryClient.invalidateQueries({ queryKey: [...modelStateQueryKey, directory] })
queryClient.setQueryData(modelStateQueryKey(), state)
},
onError: (error, _removedModel, context) => {
onError: (error, _input, context) => {
if (context?.previousState) {
syncModelState(context.previousState)
queryClient.setQueryData([...modelStateQueryKey, directory], context.previousState)
queryClient.setQueryData(modelStateQueryKey(), context.previousState)
}
console.error('Failed to remove recent model on backend', error)
console.error(errorMessage, error)
},
})
}
const providers = providersData?.providers
interface PreferredSelectionContext {
models: ModelInfo[]
agentModel?: ModelRef
configured: ModelRef | null
preferences?: Record<string, string | undefined>
}
function preferredSelection(context: PreferredSelectionContext, model: ModelSelection): ModelPick {
return {
...model,
variant: selectPreferredVariant({
model,
info: findModelInfo(context.models, model),
preferences: context.preferences,
agentModel: context.agentModel,
configured: context.configured,
}),
}
}
interface ResolveSelectionInput extends PreferredSelectionContext {
agentID?: string
newSessionPick?: ModelPick
sessionPicks?: Record<string, ModelPick | undefined>
session?: ModelSelectionSession
recent: ModelSelection[]
}
function resolveSelection(input: ResolveSelectionInput): ModelPick | undefined {
const { models, session } = input
if (session) {
const sessionPick = input.agentID ? input.sessionPicks?.[input.agentID] : undefined
const durable: ModelPick | undefined = session.model
? {
providerID: session.model.providerID,
modelID: session.model.id,
variant: normalizeModelVariant(session.model.variant),
}
: undefined
const durableUsable = !session.agent || session.agent === input.agentID
const selected = [sessionPick, durableUsable ? durable : undefined].find(
(candidate): candidate is ModelPick =>
candidate !== undefined && findModelInfo(models, candidate) !== undefined,
)
if (selected) {
const info = findModelInfo(models, selected)
const variant = normalizeModelVariant(selected.variant)
return {
providerID: selected.providerID,
modelID: selected.modelID,
variant: info?.variants.some((entry) => entry.id === variant) ? variant : undefined,
}
}
}
const model = selectInteractiveModel({
models,
current: input.newSessionPick,
agentModel: input.agentModel,
configured: input.configured,
recent: input.recent,
})
return model ? preferredSelection(input, model) : undefined
}
function selectionKey(value: ModelPick): string {
return `${modelPreferenceKey(value)}:${normalizeModelVariant(value.variant) ?? 'default'}`
}
export function useModelSelection(
directory?: string,
session?: ModelSelectionSession,
): UseModelSelectionResult {
const { data: catalog, isPlaceholderData: catalogIsPlaceholder } = useProviders(directory)
const activeAgent = useModelStore((state) => state.activeAgent)
const newSessionPicks = useModelStore((state) => state.newSessionPicks)
const sessionPicks = useModelStore((state) => state.sessionPicks)
const setNewSessionPick = useModelStore((state) => state.setNewSessionPick)
const setSessionPick = useModelStore((state) => state.setSessionPick)
const setActiveAgent = useModelStore((state) => state.setActiveAgent)
const { data: modelState } = useOpenCodeModelState()
const { data: configModelString } = useOpenCodeConfiguredModel(directory)
const isModelReady = Boolean(
catalog &&
!catalogIsPlaceholder &&
modelState !== undefined &&
configModelString !== undefined,
)
const recentModels = useMemo(() => {
const raw = modelState?.recent ?? []
if (!providers || providers.length === 0) return raw
return raw.filter((m) => modelExists(m, providers))
}, [modelState?.recent, providers])
if (!catalog || catalog.models.length === 0) return raw
return raw.filter((model) => isModelAvailable(catalog.models, model))
}, [modelState?.recent, catalog])
const favoriteModels = useMemo(() => {
const raw = modelState?.favorite ?? []
if (!providers || providers.length === 0) return raw
return raw.filter((m) => modelExists(m, providers))
}, [modelState?.favorite, providers])
if (!catalog || catalog.models.length === 0) return raw
return raw.filter((model) => isModelAvailable(catalog.models, model))
}, [modelState?.favorite, catalog])
const firstAvailableModelString = providersData?.providers
.map((provider) => {
const modelID = Object.keys(provider.models || {})[0]
return modelID ? `${provider.id}/${modelID}` : null
})
.find((value): value is string => Boolean(value))
const configured = useMemo(
() => (configModelString ? parseOpenCodeModelRef(configModelString) ?? null : null),
[configModelString],
)
useEffect(() => {
if (isModelStateLoading || isConfigModelLoading) return
validateAndSyncModel(
configModelString ?? undefined,
providersData?.providers,
modelState?.recent ?? [],
firstAvailableModelString,
const key = locationAgentKey(directory, activeAgent?.id)
const selection = useMemo(() => {
if (!isModelReady || !catalog) return null
return (
resolveSelection({
models: catalog.models,
agentID: activeAgent?.id,
agentModel: activeAgent?.model,
newSessionPick: newSessionPicks[key],
sessionPicks: session?.id ? sessionPicks[session.id] : undefined,
session,
configured,
recent: modelState?.recent ?? [],
preferences: modelState?.variant,
}) ?? null
)
}, [isModelStateLoading, isConfigModelLoading, modelState?.recent, configModelString, firstAvailableModelString, providersData, validateAndSyncModel])
}, [
activeAgent?.id,
activeAgent?.model,
catalog,
configured,
isModelReady,
key,
modelState?.recent,
modelState?.variant,
newSessionPicks,
session,
sessionPicks,
])
useEffect(() => {
if (modelState) {
syncModelState(modelState)
}
}, [modelState, syncModelState])
const info = useMemo(
() => (selection ? findModelInfo(catalog?.models ?? [], selection) : undefined),
[catalog, selection],
)
const model = selection
? { providerID: selection.providerID, modelID: selection.modelID }
: null
const updateRecentModel = useModelStateMutation(
addOpenCodeRecentModel,
(state, nextModel) => addRecentModel(state, nextModel),
'Failed to sync recent model to backend',
)
const updateFavoriteModel = useModelStateMutation(
toggleOpenCodeFavoriteModel,
(state, nextModel) => toggleFavoriteModel(state, nextModel),
'Failed to toggle favorite model on backend',
)
const removeRecentMutation = useModelStateMutation(
removeOpenCodeRecentModel,
(state, nextModel) => removeRecentModel(state, nextModel),
'Failed to remove recent model on backend',
)
const preferred = (target: ModelSelection): ModelPick => {
if (!catalog) return { ...target }
return preferredSelection(
{
models: catalog.models,
agentModel: activeAgent?.model,
configured,
preferences: modelState?.variant,
},
target,
)
}
const setSessionDraft = (agentID: string, next: ModelPick) => {
if (!session) return
const durable: ModelPick | undefined = session.model
? {
providerID: session.model.providerID,
modelID: session.model.id,
variant: normalizeModelVariant(session.model.variant),
}
: undefined
const durableUsable = !session.agent || session.agent === agentID
const drop = Boolean(durableUsable && durable && selectionKey(durable) === selectionKey(next))
setSessionPick(session.id, agentID, drop ? undefined : next)
}
const setModel = (nextModel: ModelSelection) => {
setStoreModel(nextModel)
if (session?.id && activeAgent?.id) {
const next = selection && isSameModelSelection(selection, nextModel)
? { ...selection }
: preferred(nextModel)
setSessionDraft(activeAgent.id, next)
} else {
setNewSessionPick(key, nextModel)
}
updateRecentModel.mutate(nextModel)
}
const setActiveModel = (nextModel: ModelSelection): boolean => {
const providers = providersData?.providers
if (!providers) return false
const isAvailable = providers.some(
(provider) => provider.id === nextModel.providerID && provider.models && nextModel.modelID in provider.models
)
if (!isAvailable) return false
setStoreActiveModel(nextModel)
return true
}
const restoreSessionModel = (sessionModel: ModelSelection): void => {
setStoreActiveModel(sessionModel)
}
const toggleFavorite = (nextModel: ModelSelection) => {
updateFavoriteModel.mutate(nextModel)
}
const removeRecentModel = (nextModel: ModelSelection) => {
const removeRecent = (nextModel: ModelSelection) => {
removeRecentMutation.mutate(nextModel)
}
return {
model,
modelString: getModelString(),
selection,
info,
modelString: model ? modelSelectionRef(model) : null,
modelRef: selection
? {
providerID: selection.providerID,
id: selection.modelID,
...(selection.variant ? { variant: selection.variant } : {}),
}
: null,
activeAgent,
recentModels,
favoriteModels,
configured,
modelState,
isModelReady,
setModel,
setActiveModel,
restoreSessionModel,
setActiveAgent,
toggleFavorite,
removeRecentModel,
isModelStateLoading,
removeRecentModel: removeRecent,
}
}
+8 -11
View File
@@ -20,6 +20,7 @@ import {
} from "../api/opencode";
import { FetchError } from "../api/fetchWrapper";
import type { ModelRef, SessionInfo } from "@opencode-manager/shared/opencode";
import { isSameModelRef } from "@opencode-manager/shared/opencode";
import { parseNetworkError, isGatewayTimeout } from "../lib/opencode-errors";
import { showToast } from "../lib/toast";
import { useSendErrorStore } from "../stores/sendErrorStore";
@@ -32,12 +33,6 @@ import { SESSION_PINS_QUERY_KEY } from "./useSessionPins";
import { admitInboxItem, type TranscriptCache } from "../lib/session-projection";
import type { SessionPin } from "@opencode-manager/shared/schemas";
const isSameModelRef = (left: ModelRef, right: ModelRef | undefined) =>
right !== undefined &&
left.providerID === right.providerID &&
left.id === right.id &&
left.variant === right.variant;
const SESSION_LIST_PAGE_SIZE = 25
const EMPTY_SESSIONS: SessionInfo[] = []
@@ -327,14 +322,16 @@ export const useSyncSessionSelection = (directory?: string) => {
sessionQueryKey(sessionID, directory),
);
if (model && !isSameModelRef(model, session?.model)) {
await switchSessionModel(sessionID, model);
patchCachedSessionSelection(queryClient, sessionID, directory, { model });
}
let agentChanged = false;
if (agent && agent !== session?.agent) {
await switchSessionAgent(sessionID, agent);
patchCachedSessionSelection(queryClient, sessionID, directory, { agent });
agentChanged = true;
}
if (model && (agentChanged || !isSameModelRef(model, session?.model))) {
await switchSessionModel(sessionID, model);
patchCachedSessionSelection(queryClient, sessionID, directory, { model });
}
},
[queryClient, directory],
+2 -1
View File
@@ -1,4 +1,4 @@
import { useQuery } from '@tanstack/react-query'
import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { getProviders } from '@/api/providers'
interface UseProvidersOptions {
@@ -11,5 +11,6 @@ export function useProviders(directory?: string, options: UseProvidersOptions =
queryFn: () => getProviders(directory),
enabled: options.enabled ?? true,
staleTime: 30000,
placeholderData: keepPreviousData,
})
}
@@ -1,113 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { useProvidersWithModels } from './useProvidersWithModels'
import type { ProviderWithModels } from '@/api/providers'
const mocks = vi.hoisted(() => ({
getProvidersWithModels: vi.fn(),
}))
vi.mock('@/api/providers', () => ({
getProvidersWithModels: mocks.getProvidersWithModels,
}))
vi.mock('@/hooks/useOpenCodeConfigFile', () => ({
useOpenCodeConfigFile: () => ({ data: undefined, isLoading: false }),
}))
function provider(id: string, modelIds: string[]): ProviderWithModels {
return {
id,
name: id,
models: modelIds.map((modelId) => ({ id: modelId, name: modelId })),
source: 'builtin',
isConnected: true,
}
}
const CATALOGS: Record<string, ProviderWithModels[]> = {
'/repo-a': [provider('a-provider', ['a-model'])],
'/repo-b': [provider('b-provider', ['b-model'])],
default: [provider('default-provider', ['default-model'])],
}
function Consumer({ testId, directory, keyParts }: { testId: string; directory?: string; keyParts?: readonly unknown[] }) {
const { data } = useProvidersWithModels({ enabled: true, directory, keyParts })
return (
<div data-testid={testId}>
{data.map((entry) => `${entry.id}:${entry.models.map((model) => model.id).join('+')}`).join(',')}
</div>
)
}
function createWrapper() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
describe('useProvidersWithModels', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.getProvidersWithModels.mockImplementation(async (directory?: string) => CATALOGS[directory ?? 'default'] ?? [])
})
it('scopes the cache by directory so a new directory is fetched even while the previous location is fresh', async () => {
const wrapper = createWrapper()
const { rerender } = render(
<>
<Consumer testId="scoped" directory="/repo-a" />
<Consumer testId="default" />
</>,
{ wrapper },
)
await waitFor(() => {
expect(screen.getByTestId('scoped')).toHaveTextContent('a-provider:a-model')
})
expect(screen.getByTestId('default')).toHaveTextContent('default-provider:default-model')
expect(mocks.getProvidersWithModels).toHaveBeenCalledWith('/repo-a', undefined)
expect(mocks.getProvidersWithModels).toHaveBeenCalledWith(undefined, undefined)
mocks.getProvidersWithModels.mockClear()
rerender(
<>
<Consumer testId="scoped" directory="/repo-b" />
<Consumer testId="default" />
</>,
)
await waitFor(() => {
expect(screen.getByTestId('scoped')).toHaveTextContent('b-provider:b-model')
})
expect(screen.getByTestId('default')).toHaveTextContent('default-provider:default-model')
expect(mocks.getProvidersWithModels).toHaveBeenCalledWith('/repo-b', undefined)
expect(mocks.getProvidersWithModels).toHaveBeenCalledTimes(1)
})
it('shares one fetch per directory and keeps the default location and keyParts callers distinct', async () => {
const wrapper = createWrapper()
render(
<>
<Consumer testId="scoped-one" directory="/repo-a" />
<Consumer testId="scoped-two" directory="/repo-a" />
<Consumer testId="keyed" directory="/repo-a" keyParts={['schedule-models']} />
<Consumer testId="default" />
</>,
{ wrapper },
)
await waitFor(() => {
expect(screen.getByTestId('scoped-one')).toHaveTextContent('a-provider:a-model')
})
expect(screen.getByTestId('scoped-two')).toHaveTextContent('a-provider:a-model')
expect(screen.getByTestId('keyed')).toHaveTextContent('a-provider:a-model')
expect(screen.getByTestId('default')).toHaveTextContent('default-provider:default-model')
expect(mocks.getProvidersWithModels).toHaveBeenCalledTimes(3)
})
})
@@ -1,24 +0,0 @@
import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { getProvidersWithModels } from '@/api/providers'
import { useOpenCodeConfigFile } from '@/hooks/useOpenCodeConfigFile'
interface UseProvidersWithModelsOptions {
enabled: boolean
directory?: string
keyParts?: readonly unknown[]
}
export function useProvidersWithModels({ enabled, directory, keyParts }: UseProvidersWithModelsOptions) {
const { data: config, isLoading: isConfigLoading } = useOpenCodeConfigFile(enabled)
const query = useQuery({
queryKey: ['providers-with-models', directory ?? null, ...(keyParts ?? [])],
queryFn: () => getProvidersWithModels(directory, config),
enabled: enabled && !isConfigLoading,
staleTime: 5 * 60 * 1000,
gcTime: 10 * 60 * 1000,
placeholderData: keepPreviousData,
})
return { ...query, data: query.data ?? [] }
}
+25 -1
View File
@@ -90,6 +90,24 @@ describe('useRefreshMessage', () => {
expect(mocks.switchSessionAgent).not.toHaveBeenCalled()
})
it('preserves the session variant when resending with the same full ref', async () => {
setSession(sessionInfo({
model: { providerID: 'anthropic', id: 'claude-sonnet-4', variant: 'high' },
}))
const { result } = renderRefresh()
await result.current.mutateAsync({
assistantMessageID: 'assistant-1',
userMessageContent: 'edited text',
model: 'anthropic/claude-sonnet-4#high',
agent: 'build',
})
expect(mocks.switchSessionModel).not.toHaveBeenCalled()
expect(mocks.switchSessionAgent).not.toHaveBeenCalled()
})
it('switches the model before resending when the edited message model changed', async () => {
setSession(sessionInfo())
@@ -125,6 +143,12 @@ describe('useRefreshMessage', () => {
})
expect(mocks.switchSessionAgent).toHaveBeenCalledWith('test-session', 'plan')
expect(mocks.switchSessionModel).not.toHaveBeenCalled()
expect(mocks.switchSessionModel).toHaveBeenCalledWith('test-session', {
providerID: 'anthropic',
id: 'claude-sonnet-4',
})
expect(mocks.switchSessionAgent.mock.invocationCallOrder[0]).toBeLessThan(
mocks.switchSessionModel.mock.invocationCallOrder[0],
)
})
})
+9 -21
View File
@@ -1,27 +1,15 @@
import { useMemo } from 'react'
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
import { useOpenCodeConfigModel, useOpenCodeModelState } from '@/hooks/useModelSelection'
import { buildAvailableModelKeys } from '@/lib/schedules/schedule-model'
import { useProviders } from '@/hooks/useProviders'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
export function useScheduleModels(enabled: boolean, directory?: string) {
const providersQuery = useProvidersWithModels({
enabled,
directory,
keyParts: ['schedule-models'],
})
const { data: modelState } = useOpenCodeModelState(directory, enabled)
const { data: configDefaultModel = null, isLoading: configLoading } = useOpenCodeConfigModel(directory, enabled)
const providerModels = providersQuery.data
const availableModelKeys = useMemo(
() => (providersQuery.isSuccess ? buildAvailableModelKeys(providerModels) : null),
[providersQuery.isSuccess, providerModels],
)
const providersQuery = useProviders(directory, { enabled })
const availableModels: ModelInfo[] | null =
providersQuery.isSuccess && !providersQuery.isPlaceholderData
? providersQuery.data?.models ?? []
: null
return {
providerModels,
modelState,
availableModelKeys,
configDefaultModel,
isLoading: providersQuery.isLoading || configLoading,
availableModels,
isLoading: providersQuery.isLoading,
}
}
+53 -6
View File
@@ -174,7 +174,35 @@ describe('useSendPrompt', () => {
})
expect(mocks.switchSessionAgent).toHaveBeenCalledWith('test-session', 'plan')
expect(mocks.switchSessionModel).not.toHaveBeenCalled()
expect(mocks.switchSessionModel).toHaveBeenCalledWith('test-session', {
providerID: 'anthropic',
id: 'claude-sonnet-4',
})
expect(mocks.switchSessionAgent.mock.invocationCallOrder[0]).toBeLessThan(
mocks.switchSessionModel.mock.invocationCallOrder[0],
)
})
it('switches the agent before the model when both changed', async () => {
setSession(sessionInfo({
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
}))
const { result } = renderHookWithProviders()
await result.current.mutateAsync({
sessionID: 'test-session',
text: 'Hello',
model: { providerID: 'openai', id: 'gpt-4' },
agent: 'plan',
})
expect(mocks.switchSessionAgent).toHaveBeenCalledWith('test-session', 'plan')
expect(mocks.switchSessionModel).toHaveBeenCalledWith('test-session', { providerID: 'openai', id: 'gpt-4' })
expect(mocks.switchSessionAgent.mock.invocationCallOrder[0]).toBeLessThan(
mocks.switchSessionModel.mock.invocationCallOrder[0],
)
})
it('switches back to a previously cached model after an intermediate switch', async () => {
@@ -226,9 +254,9 @@ describe('useSendPrompt', () => {
).toEqual({ providerID: 'anthropic', id: 'claude-sonnet-4' })
})
it('keeps a successful model switch when the following agent switch fails', async () => {
it('keeps a successful agent switch when the following model switch fails', async () => {
setSession(sessionInfo({ agent: 'build', model: { providerID: 'anthropic', id: 'claude-sonnet-4' } }))
mocks.switchSessionAgent.mockRejectedValueOnce(new Error('agent switch failed'))
mocks.switchSessionModel.mockRejectedValueOnce(new Error('model switch failed'))
const { result } = renderHookWithProviders()
@@ -239,7 +267,7 @@ describe('useSendPrompt', () => {
model: { providerID: 'openai', id: 'gpt-4' },
agent: 'plan',
}),
).rejects.toThrow('agent switch failed')
).rejects.toThrow('model switch failed')
const cached = queryClient.getQueryData<{ model?: unknown; agent?: string }>([
'opencode',
@@ -247,8 +275,27 @@ describe('useSendPrompt', () => {
'test-session',
'/test',
])
expect(cached?.model).toEqual({ providerID: 'openai', id: 'gpt-4' })
expect(cached?.agent).toBe('build')
expect(cached?.agent).toBe('plan')
expect(cached?.model).toEqual({ providerID: 'anthropic', id: 'claude-sonnet-4' })
})
it('does not switch the session model when the variant matches the durable selection', async () => {
setSession(sessionInfo({
agent: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4', variant: 'high' },
}))
const { result } = renderHookWithProviders()
await result.current.mutateAsync({
sessionID: 'test-session',
text: 'Hello',
model: { providerID: 'anthropic', id: 'claude-sonnet-4', variant: 'high' },
agent: 'build',
})
expect(mocks.switchSessionModel).not.toHaveBeenCalled()
expect(mocks.switchSessionAgent).not.toHaveBeenCalled()
})
it('adds the returned inbox item to the transcript pending state immediately', async () => {
+13 -2
View File
@@ -2,6 +2,7 @@ import { useMemo, useEffect } from 'react'
import { useSession, useAgents } from './useOpenCode'
import { useSessionAgentStore } from '@/stores/sessionAgentStore'
import { getPrimaryAgents } from '@/lib/primaryAgents'
import type { ModelRef } from '@opencode-manager/shared/opencode'
interface AgentInfo {
id: string
@@ -41,6 +42,8 @@ interface SessionAgentResult {
agent: string
model: { providerID: string; modelID: string } | undefined
variant: string | undefined
sessionAgentId: string | undefined
modelRef: ModelRef | undefined
}
export function useSessionAgent(
@@ -69,8 +72,10 @@ export function useSessionAgent(
agent: sessionAgent ?? fallbackAgent ?? defaultAgent,
model,
variant: session?.model?.variant,
sessionAgentId: session?.agent,
modelRef: session?.model,
}
}, [sessionAgent, fallbackAgent, defaultAgent, session?.model])
}, [sessionAgent, fallbackAgent, defaultAgent, session?.model, session?.agent])
useEffect(() => {
if (session?.agent && sessionID) {
@@ -78,5 +83,11 @@ export function useSessionAgent(
}
}, [session?.agent, sessionID, setAgent])
return { agent: result.agent, model: result.model, variant: result.variant }
return {
agent: result.agent,
model: result.model,
variant: result.variant,
sessionAgentId: result.sessionAgentId,
modelRef: result.modelRef,
}
}
+323
View File
@@ -0,0 +1,323 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { act, renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { useVariants } from './useVariants'
import { useModelStore } from '@/stores/modelStore'
import { modelStateQueryKey, useModelSelection, type ModelSelectionSession } from './useModelSelection'
import * as providersApi from '@/api/providers'
import type { Provider } from '@/api/providers'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
vi.mock('@/api/providers', async () => {
const actual = await vi.importActual('@/api/providers')
return {
...actual,
getProviders: vi.fn(),
getOpenCodeConfiguredModel: vi.fn(),
getOpenCodeModelState: vi.fn(),
saveOpenCodeModelVariant: vi.fn(),
addOpenCodeRecentModel: vi.fn(),
removeOpenCodeRecentModel: vi.fn(),
toggleOpenCodeFavoriteModel: vi.fn(),
}
})
const mockGetProviders = vi.mocked(providersApi.getProviders)
const mockGetOpenCodeConfiguredModel = vi.mocked(providersApi.getOpenCodeConfiguredModel)
const mockGetOpenCodeModelState = vi.mocked(providersApi.getOpenCodeModelState)
const mockSaveOpenCodeModelVariant = vi.mocked(providersApi.saveOpenCodeModelVariant)
const mockAddOpenCodeRecentModel = vi.mocked(providersApi.addOpenCodeRecentModel)
const PROVIDER_ID = 'anthropic'
const MODEL_ID = 'claude-sonnet-4'
const MODEL_KEY = `${PROVIDER_ID}/${MODEL_ID}`
const DIRECTORY = '/test'
const AGENT_ID = 'build'
const modelInfo = (variants: string[]): ModelInfo => ({
providerID: PROVIDER_ID,
id: MODEL_ID,
modelID: MODEL_ID,
name: MODEL_ID,
enabled: true,
status: 'active',
variants: variants.map((id) => ({ id })),
time: { released: 0 },
cost: [],
limit: { context: 0, output: 0 },
} as unknown as ModelInfo)
const provider = (): Provider => ({
id: PROVIDER_ID,
name: 'Anthropic',
models: [{ id: MODEL_ID, key: MODEL_ID, name: MODEL_ID, released: 0, free: false }],
})
const emptyState = () => ({ recent: [], favorite: [], variant: {} })
const createQueryClient = () => new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const createWrapper = (queryClient: QueryClient) =>
({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
const renderUseVariants = (queryClient: QueryClient, session?: ModelSelectionSession) =>
renderHook(() => useVariants(DIRECTORY, session), { wrapper: createWrapper(queryClient) })
const selectAgentModel = (variant?: string) => {
useModelStore.getState().setActiveAgent({
id: AGENT_ID,
model: { providerID: PROVIDER_ID, id: MODEL_ID, ...(variant ? { variant } : {}) },
})
}
describe('useVariants', () => {
beforeEach(() => {
vi.clearAllMocks()
useModelStore.setState({ newSessionPicks: {}, sessionPicks: {}, activeAgent: null })
mockGetProviders.mockResolvedValue({
providers: [provider()],
models: [modelInfo(['default', 'high', 'low'])],
})
mockGetOpenCodeConfiguredModel.mockResolvedValue(null)
mockGetOpenCodeModelState.mockResolvedValue(emptyState())
mockSaveOpenCodeModelVariant.mockImplementation(async (model, value) => ({
recent: [],
favorite: [],
variant: { [`${model.providerID}/${model.modelID}`]: value ?? 'default' },
}))
})
it('uses the saved model.json variant when the selection has no variant', async () => {
selectAgentModel()
mockGetOpenCodeModelState.mockResolvedValue({
recent: [],
favorite: [],
variant: { [MODEL_KEY]: 'high' },
})
const { result } = renderUseVariants(createQueryClient())
await waitFor(() => expect(result.current.currentVariant).toBe('high'))
})
it('treats a saved default as no variant, beating the agent variant', async () => {
selectAgentModel('high')
mockGetOpenCodeModelState.mockResolvedValue({
recent: [],
favorite: [],
variant: { [MODEL_KEY]: 'default' },
})
const { result } = renderUseVariants(createQueryClient())
await waitFor(() => expect(result.current.hasVariants).toBe(true))
expect(result.current.currentVariant).toBeUndefined()
})
it('falls back to the agent variant when nothing is saved', async () => {
selectAgentModel('high')
const { result } = renderUseVariants(createQueryClient())
await waitFor(() => expect(result.current.currentVariant).toBe('high'))
})
it('falls back to the configured variant when the agent has none', async () => {
selectAgentModel()
mockGetOpenCodeConfiguredModel.mockResolvedValue(`${MODEL_KEY}#low`)
const { result } = renderUseVariants(createQueryClient())
await waitFor(() => expect(result.current.currentVariant).toBe('low'))
})
it('ignores a variant that is not in the model variants', async () => {
selectAgentModel('turbo')
const { result } = renderUseVariants(createQueryClient())
await waitFor(() => expect(result.current.hasVariants).toBe(true))
expect(result.current.currentVariant).toBeUndefined()
})
it('uses the durable session variant over the saved preference', async () => {
selectAgentModel()
mockGetOpenCodeModelState.mockResolvedValue({
recent: [],
favorite: [],
variant: { [MODEL_KEY]: 'low' },
})
const { result } = renderUseVariants(createQueryClient(), {
id: 's1',
agent: AGENT_ID,
model: { providerID: PROVIDER_ID, id: MODEL_ID, variant: 'high' },
})
await waitFor(() => expect(result.current.currentVariant).toBe('high'))
})
it('stores a session variant on the session pick and persists it', async () => {
selectAgentModel()
const { result } = renderUseVariants(createQueryClient(), {
id: 's1',
agent: AGENT_ID,
model: { providerID: PROVIDER_ID, id: MODEL_ID },
})
await waitFor(() => expect(result.current.hasVariants).toBe(true))
act(() => {
result.current.setVariant('high')
})
expect(useModelStore.getState().sessionPicks.s1[AGENT_ID].variant).toBe('high')
await waitFor(() => {
expect(mockSaveOpenCodeModelVariant).toHaveBeenCalledWith(
{ providerID: PROVIDER_ID, modelID: MODEL_ID },
'high',
)
})
act(() => {
result.current.clearVariant()
})
expect(useModelStore.getState().sessionPicks.s1[AGENT_ID].variant).toBeUndefined()
await waitFor(() => {
expect(mockSaveOpenCodeModelVariant).toHaveBeenLastCalledWith(
{ providerID: PROVIDER_ID, modelID: MODEL_ID },
undefined,
)
})
})
it('persists the variant outside a session and drives the selection from the preference', async () => {
selectAgentModel()
const queryClient = createQueryClient()
const { result } = renderUseVariants(queryClient)
await waitFor(() => expect(result.current.hasVariants).toBe(true))
act(() => {
result.current.setVariant('high')
})
await waitFor(() => expect(result.current.currentVariant).toBe('high'))
expect(useModelStore.getState().newSessionPicks).toEqual({})
await waitFor(() => {
expect(mockSaveOpenCodeModelVariant).toHaveBeenCalledWith(
{ providerID: PROVIDER_ID, modelID: MODEL_ID },
'high',
)
})
act(() => {
result.current.clearVariant()
})
await waitFor(() => expect(result.current.currentVariant).toBeUndefined())
})
it('cycles through named variants and wraps back to none', async () => {
selectAgentModel()
const { result } = renderUseVariants(createQueryClient())
await waitFor(() => expect(result.current.hasVariants).toBe(true))
act(() => {
result.current.cycleVariant()
})
await waitFor(() => expect(result.current.currentVariant).toBe('high'))
act(() => {
result.current.cycleVariant()
})
await waitFor(() => expect(result.current.currentVariant).toBe('low'))
act(() => {
result.current.cycleVariant()
})
await waitFor(() => expect(result.current.currentVariant).toBeUndefined())
})
it('rolls back the optimistic variant when the save fails', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
selectAgentModel()
mockGetOpenCodeModelState.mockResolvedValue({
recent: [],
favorite: [],
variant: { [MODEL_KEY]: 'low' },
})
let rejectSave: (error: Error) => void = () => {}
mockSaveOpenCodeModelVariant.mockImplementation(() => new Promise((_, reject) => {
rejectSave = reject
}))
const queryClient = createQueryClient()
const { result } = renderUseVariants(queryClient)
await waitFor(() => expect(result.current.currentVariant).toBe('low'))
act(() => {
result.current.setVariant('high')
})
await waitFor(() => {
expect(queryClient.getQueryData<{ variant: Record<string, string> }>(modelStateQueryKey())?.variant)
.toEqual({ [MODEL_KEY]: 'high' })
})
act(() => {
rejectSave(new Error('save failed'))
})
await waitFor(() => {
expect(queryClient.getQueryData<{ variant: Record<string, string> }>(modelStateQueryKey())?.variant)
.toEqual({ [MODEL_KEY]: 'low' })
})
})
it('keeps the durable session variant after setModel records the same model as a recent', async () => {
selectAgentModel()
mockGetOpenCodeModelState.mockResolvedValue({
recent: [],
favorite: [],
variant: { [MODEL_KEY]: 'low' },
})
mockAddOpenCodeRecentModel.mockResolvedValue({
recent: [{ providerID: PROVIDER_ID, modelID: MODEL_ID }],
favorite: [],
variant: { [MODEL_KEY]: 'low' },
})
const session: ModelSelectionSession = {
id: 's1',
agent: AGENT_ID,
model: { providerID: PROVIDER_ID, id: MODEL_ID, variant: 'high' },
}
const { result } = renderHook(
() => ({ variants: useVariants(DIRECTORY, session), selection: useModelSelection(DIRECTORY, session) }),
{ wrapper: createWrapper(createQueryClient()) },
)
await waitFor(() => expect(result.current.variants.currentVariant).toBe('high'))
act(() => {
result.current.selection.setModel({ providerID: PROVIDER_ID, modelID: MODEL_ID })
})
await waitFor(() => expect(result.current.variants.currentVariant).toBe('high'))
expect(useModelStore.getState().sessionPicks.s1?.[AGENT_ID]).toBeUndefined()
})
})
+44 -56
View File
@@ -1,7 +1,12 @@
import { useMemo } from 'react'
import { useModelSelection } from './useModelSelection'
import { useModelStore } from '@/stores/modelStore'
import { useProviders } from './useProviders'
import { useCallback, useMemo } from 'react'
import { useModelSelection, useModelStateMutation, type ModelSelectionSession } from './useModelSelection'
import { useModelStore, type ModelSelection } from '@/stores/modelStore'
import { saveOpenCodeModelVariant } from '@/api/providers'
import {
cycleModelVariant,
normalizeModelVariant,
setModelVariant,
} from '@opencode-manager/shared/opencode'
export interface UseVariantsResult {
availableVariants: string[]
@@ -12,67 +17,50 @@ export interface UseVariantsResult {
hasVariants: boolean
}
export function useVariants(directory?: string): UseVariantsResult {
const { model } = useModelSelection(directory)
const { setVariant: setStoreVariant, clearVariant: clearStoreVariant } = useModelStore()
interface SaveVariantInput {
model: ModelSelection
value: string | undefined
}
const { data: providersData, isLoading } = useProviders(directory, { enabled: !!model })
export function useVariants(
directory?: string,
session?: ModelSelectionSession,
): UseVariantsResult {
const { model, selection, info } = useModelSelection(directory, session)
const activeAgent = useModelStore((state) => state.activeAgent)
const setSessionPick = useModelStore((state) => state.setSessionPick)
const currentModel = useMemo(() => {
if (!model || isLoading || !providersData?.providers || providersData.providers.length === 0) return null
for (const provider of providersData.providers) {
if (provider.id === model.providerID && provider.models) {
const modelData = provider.models[model.modelID]
if (modelData) {
return modelData
}
}
}
return null
}, [model, providersData, isLoading])
const availableVariants = useMemo(() => {
if (!currentModel?.variants) return []
return Object.keys(currentModel.variants)
}, [currentModel])
const currentVariant = useModelStore((state) =>
model ? state.variants[`${model.providerID}/${model.modelID}`] : undefined
const availableVariants = useMemo(
() => info?.variants.map((variant) => variant.id).filter((id) => id !== 'default') ?? [],
[info],
)
const setVariant = useMemo(
() => (variant: string | undefined) => {
const currentVariant = selection?.variant
const saveVariant = useModelStateMutation(
({ model, value }: SaveVariantInput) => saveOpenCodeModelVariant(model, value),
(state, input: SaveVariantInput) => setModelVariant(state, input.model, input.value),
'Failed to save model variant to backend',
)
const setVariant = useCallback(
(variant: string | undefined) => {
if (!model) return
setStoreVariant(model, variant)
},
[model, setStoreVariant],
)
const cycleVariant = useMemo(() => {
return () => {
if (!model || availableVariants.length === 0) return
if (!currentVariant) {
setStoreVariant(model, availableVariants[0])
} else {
const currentIndex = availableVariants.indexOf(currentVariant)
if (currentIndex === availableVariants.length - 1) {
clearStoreVariant(model)
} else {
setStoreVariant(model, availableVariants[currentIndex + 1])
}
if (session?.id && activeAgent?.id) {
setSessionPick(session.id, activeAgent.id, { ...model, variant: normalizeModelVariant(variant) })
}
}
}, [model, availableVariants, currentVariant, setStoreVariant, clearStoreVariant])
const clearVariant = useMemo(
() => () => {
if (!model) return
clearStoreVariant(model)
saveVariant.mutate({ model, value: variant })
},
[model, clearStoreVariant],
[activeAgent?.id, model, saveVariant, session?.id, setSessionPick],
)
const cycleVariant = useCallback(
() => setVariant(cycleModelVariant(currentVariant, availableVariants)),
[availableVariants, currentVariant, setVariant],
)
const clearVariant = useCallback(() => setVariant(undefined), [setVariant])
return {
availableVariants,
currentVariant,
+52
View File
@@ -0,0 +1,52 @@
import { describe, it, expect } from 'vitest'
import { isModelAvailable } from './modelCatalog'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
const models = [
{ providerID: 'openai', id: 'gpt-5' },
{ providerID: 'anthropic', id: 'claude-sonnet-4-20250514' },
] as unknown as ModelInfo[]
describe('isModelAvailable', () => {
it('accepts a selection that matches the OpenCode key', () => {
expect(isModelAvailable(models, { providerID: 'openai', modelID: 'gpt-5' })).toBe(true)
})
it('rejects a selection that matches only the backing model id', () => {
expect(isModelAvailable(models, { providerID: 'openai', modelID: 'gpt-5-2025-08-07' })).toBe(false)
})
it('accepts a string ref that matches the OpenCode key', () => {
expect(isModelAvailable(models, 'openai/gpt-5')).toBe(true)
})
it('accepts a string ref with a variant suffix', () => {
expect(isModelAvailable(models, 'openai/gpt-5#high')).toBe(true)
})
it('rejects a string ref that matches only the backing model id', () => {
expect(isModelAvailable(models, 'openai/gpt-5-2025-08-07')).toBe(false)
})
it('rejects an unknown provider', () => {
expect(isModelAvailable(models, { providerID: 'ghost', modelID: 'gpt-5' })).toBe(false)
})
it('rejects an unknown model', () => {
expect(isModelAvailable(models, { providerID: 'openai', modelID: 'missing' })).toBe(false)
})
it('rejects an unparsable string ref', () => {
expect(isModelAvailable(models, 'gpt-5')).toBe(false)
expect(isModelAvailable(models, '')).toBe(false)
})
it('rejects a null ref', () => {
expect(isModelAvailable(models, null)).toBe(false)
})
it('rejects every ref when the catalog is empty', () => {
expect(isModelAvailable([], { providerID: 'openai', modelID: 'gpt-5' })).toBe(false)
expect(isModelAvailable([], 'openai/gpt-5')).toBe(false)
})
})
+20
View File
@@ -0,0 +1,20 @@
import {
findModelInfo,
parseOpenCodeModelRef,
type ModelInfo,
type ModelPreferenceModel,
} from '@opencode-manager/shared/opencode'
function toSelection(ref: string): ModelPreferenceModel | null {
const parsed = parseOpenCodeModelRef(ref)
return parsed ? { providerID: parsed.providerID, modelID: parsed.id } : null
}
export function isModelAvailable(
models: ModelInfo[],
ref: string | ModelPreferenceModel | null | undefined,
): boolean {
if (!ref) return false
const selection = typeof ref === 'string' ? toSelection(ref) : ref
return selection !== null && findModelInfo(models, selection) !== undefined
}
+242
View File
@@ -0,0 +1,242 @@
import { describe, it, expect } from 'vitest'
import { buildModelSections, filterModelSections, toModelComboboxOptions } from './modelSections'
import type { Model, Provider } from '@/api/providers'
function makeModel(id: string, overrides: Partial<Model> = {}): Model {
return { id, key: id, name: id, released: 0, free: false, ...overrides }
}
function makeProvider(id: string, name: string, models: Model[]): Provider {
return { id, name, models }
}
const providers = [
makeProvider('openai', 'OpenAI', [
makeModel('gpt-5', { name: 'GPT-5' }),
makeModel('gpt-4o', { name: 'GPT-4o' }),
makeModel('gpt-4o-mini', { name: 'GPT-4o mini' }),
]),
makeProvider('anthropic', 'Anthropic', [
makeModel('claude-opus', { name: 'Claude Opus' }),
makeModel('claude-sonnet', { name: 'Claude Sonnet' }),
makeModel('claude-haiku', { name: 'Claude Haiku' }),
]),
]
function valuesOf(sections: ReturnType<typeof buildModelSections>, key: string): string[] {
return sections.find((section) => section.key === key)?.options.map((option) => option.value) ?? []
}
describe('buildModelSections', () => {
it('orders default, favorites, recent, then providers', () => {
const sections = buildModelSections(
providers,
{
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }],
recent: [{ providerID: 'openai', modelID: 'gpt-4o' }],
variant: {},
},
'openai/gpt-5',
)
expect(sections.map((section) => section.key)).toEqual([
'default',
'favorites',
'recent',
'provider:openai',
'provider:anthropic',
])
expect(valuesOf(sections, 'default')).toEqual(['openai/gpt-5'])
expect(valuesOf(sections, 'favorites')).toEqual(['anthropic/claude-sonnet'])
expect(valuesOf(sections, 'recent')).toEqual(['openai/gpt-4o'])
})
it('keeps the catalog order inside provider sections', () => {
const sections = buildModelSections(providers, undefined)
expect(valuesOf(sections, 'provider:openai')).toEqual(['openai/gpt-5', 'openai/gpt-4o', 'openai/gpt-4o-mini'])
expect(valuesOf(sections, 'provider:anthropic')).toEqual([
'anthropic/claude-opus',
'anthropic/claude-sonnet',
'anthropic/claude-haiku',
])
})
it('tags provider sections with their provider id', () => {
const sections = buildModelSections(providers, undefined)
expect(sections.find((section) => section.key === 'provider:openai')?.providerID).toBe('openai')
expect(sections.find((section) => section.key === 'favorites')).toBeUndefined()
})
it('excludes favorites, recents and the default base model from provider sections', () => {
const sections = buildModelSections(
providers,
{
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }],
recent: [{ providerID: 'openai', modelID: 'gpt-4o' }],
variant: {},
},
'openai/gpt-5',
)
const providerValues = sections
.filter((section) => section.providerID)
.flatMap((section) => section.options.map((option) => option.value))
expect(providerValues).not.toContain('openai/gpt-5')
expect(providerValues).not.toContain('openai/gpt-4o')
expect(providerValues).not.toContain('anthropic/claude-sonnet')
expect(providerValues).toEqual(['openai/gpt-4o-mini', 'anthropic/claude-opus', 'anthropic/claude-haiku'])
})
it('keeps the plain base model in provider sections when the default carries a variant', () => {
const sections = buildModelSections(providers, undefined, 'openai/gpt-5#high')
expect(valuesOf(sections, 'default')).toEqual(['openai/gpt-5#high'])
expect(valuesOf(sections, 'provider:openai')).toContain('openai/gpt-5')
})
it('lists each favorite once and excludes it from the recent section', () => {
const sections = buildModelSections(providers, {
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }],
recent: [
{ providerID: 'anthropic', modelID: 'claude-sonnet' },
{ providerID: 'openai', modelID: 'gpt-4o' },
],
variant: {},
})
expect(valuesOf(sections, 'favorites')).toEqual(['anthropic/claude-sonnet'])
expect(valuesOf(sections, 'recent')).toEqual(['openai/gpt-4o'])
})
it('drops favorites and recents that are not in the catalog', () => {
const sections = buildModelSections(providers, {
favorite: [{ providerID: 'missing', modelID: 'gone' }],
recent: [{ providerID: 'openai', modelID: 'retired' }],
variant: {},
})
expect(sections.some((section) => section.key === 'favorites')).toBe(false)
expect(sections.some((section) => section.key === 'recent')).toBe(false)
})
it('keeps the full default ref including its variant', () => {
const sections = buildModelSections(providers, undefined, 'openai/gpt-5#high')
expect(sections[0].key).toBe('default')
expect(sections[0].options[0].value).toBe('openai/gpt-5#high')
expect(sections[0].options[0].label).toBe('GPT-5')
})
it('omits the default section when the model is not in the catalog', () => {
expect(buildModelSections(providers, undefined, 'openai/retired').some((section) => section.key === 'default')).toBe(false)
expect(buildModelSections(providers, undefined, 'not-a-ref').some((section) => section.key === 'default')).toBe(false)
expect(buildModelSections(providers, undefined).some((section) => section.key === 'default')).toBe(false)
})
it('carries the provider id, the OpenCode key and the catalog model on every option', () => {
const aliased = [
makeProvider('anthropic', 'Anthropic', [
makeModel('claude-sonnet-4-5-20250929', { key: 'claude-sonnet-4.5', name: 'Claude Sonnet 4.5' }),
]),
]
const sections = buildModelSections(aliased, undefined, 'anthropic/claude-sonnet-4.5')
const defaultOption = sections[0].options[0]
expect(defaultOption.providerID).toBe('anthropic')
expect(defaultOption.modelID).toBe('claude-sonnet-4.5')
expect(defaultOption.value).toBe('anthropic/claude-sonnet-4.5')
expect(defaultOption.providerName).toBe('Anthropic')
expect(defaultOption.model.id).toBe('claude-sonnet-4-5-20250929')
})
})
describe('filterModelSections', () => {
it('returns one flat results section with favorites first', () => {
const sections = buildModelSections(providers, {
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }],
recent: [],
variant: {},
})
const results = filterModelSections(sections, 'claude')
expect(results).toHaveLength(1)
expect(results[0].key).toBe('results')
expect(results[0].options.map((option) => option.label)).toEqual(['Claude Sonnet', 'Claude Haiku', 'Claude Opus'])
expect(results[0].options[0].providerName).toBe('Anthropic')
})
it('sorts non-favorite matches by name without provider grouping', () => {
const sections = buildModelSections(providers, undefined)
const results = filterModelSections(sections, 'gpt')
expect(results[0].options.map((option) => option.value)).toEqual([
'openai/gpt-4o',
'openai/gpt-4o-mini',
'openai/gpt-5',
])
})
it('matches every search term', () => {
const sections = buildModelSections(providers, undefined)
expect(filterModelSections(sections, 'openai gpt-4o').map((section) => section.options.map((option) => option.value))).toEqual([
['openai/gpt-4o', 'openai/gpt-4o-mini'],
])
})
it('returns nothing when no option matches', () => {
expect(filterModelSections(buildModelSections(providers, undefined), 'zzz')).toEqual([])
})
it('returns the sections unchanged for an empty query', () => {
const sections = buildModelSections(providers, undefined)
expect(filterModelSections(sections, ' ')).toBe(sections)
})
})
describe('toModelComboboxOptions', () => {
it('maps each option to the section title group and its own value as the description', () => {
const sections = buildModelSections(
providers,
{
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }],
recent: [],
variant: {},
},
'openai/gpt-5',
)
const options = toModelComboboxOptions(sections, 'openai/gpt-5')
expect(options[0]).toEqual({ value: '', label: 'Default: GPT-5', description: undefined, group: 'Default' })
expect(options[1]).toEqual({
value: 'anthropic/claude-sonnet',
label: 'Claude Sonnet',
description: 'anthropic/claude-sonnet',
group: 'Favorites',
})
expect(options.find((option) => option.value === 'openai/gpt-4o-mini')).toEqual({
value: 'openai/gpt-4o-mini',
label: 'GPT-4o mini',
description: 'openai/gpt-4o-mini',
group: 'OpenAI',
})
})
it('leaves the default ref untouched when no default is resolved', () => {
const sections = buildModelSections(providers, undefined, 'openai/gpt-5')
expect(toModelComboboxOptions(sections)[0]).toEqual({
value: 'openai/gpt-5',
label: 'GPT-5',
description: 'openai/gpt-5',
group: 'Default',
})
})
})
+79 -17
View File
@@ -1,17 +1,23 @@
import { Clock, Star, type LucideIcon } from 'lucide-react'
import type { ComboboxOption } from '@/components/ui/combobox'
import {
formatModelName,
formatProviderName,
providerModelRef,
type Model,
type ModelSelection,
type OpenCodeModelState,
type ProviderWithModels,
type Provider,
} from '@/api/providers'
import { compareCatalogModels, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
export interface ModelOption {
value: string
label: string
providerID: string
modelID: string
providerName: string
model: Model
searchText: string
}
@@ -19,25 +25,52 @@ export interface ModelSection {
key: string
title: string
icon?: LucideIcon
pinned: boolean
providerID?: string
options: ModelOption[]
}
export function buildModelSections(providers: ProviderWithModels[], modelState: OpenCodeModelState | undefined): ModelSection[] {
function createOption(provider: Provider, model: Model, value: string): ModelOption {
const label = formatModelName(model)
const providerName = formatProviderName(provider)
return {
value,
label,
providerID: provider.id,
modelID: model.key ?? model.id,
providerName,
model,
searchText: `${label} ${value} ${providerName}`.toLowerCase(),
}
}
export function buildModelSections(
providers: Provider[],
modelState: OpenCodeModelState | undefined,
defaultModel?: string | null,
): ModelSection[] {
const optionsByValue = new Map<string, ModelOption>()
const providerSections = providers.map((provider): ModelSection => {
const providerName = formatProviderName(provider)
const options = provider.models.map((model) => {
const label = formatModelName(model)
const value = providerModelRef(provider, model)
const option = { value, label, providerName, searchText: `${label} ${value} ${providerName}`.toLowerCase() }
optionsByValue.set(value, option)
const option = createOption(provider, model, providerModelRef(provider, model))
optionsByValue.set(option.value, option)
return option
})
return { key: `provider:${provider.id}`, title: providerName, pinned: false, options }
return { key: `provider:${provider.id}`, providerID: provider.id, title: formatProviderName(provider), options }
})
const pinnedValues = new Set<string>()
const defaultOption = (() => {
if (!defaultModel) return undefined
const parsed = parseOpenCodeModelRef(defaultModel)
if (!parsed) return undefined
const provider = providers.find((entry) => entry.id === parsed.providerID)
const model = provider?.models.find((entry) => (entry.key ?? entry.id) === parsed.id)
if (!provider || !model) return undefined
if (!parsed.variant) pinnedValues.add(providerModelRef(provider, model))
return createOption(provider, model, defaultModel)
})()
const pinOptions = (selections: ModelSelection[] = []) =>
selections.flatMap((selection) => {
const option = optionsByValue.get(providerModelRef({ id: selection.providerID }, { id: selection.modelID }))
@@ -49,8 +82,9 @@ export function buildModelSections(providers: ProviderWithModels[], modelState:
const favoriteOptions = pinOptions(modelState?.favorite)
const recentOptions = pinOptions(modelState?.recent)
const sections: ModelSection[] = [
{ key: 'favorites', title: 'Favorites', icon: Star, pinned: true, options: favoriteOptions },
{ key: 'recent', title: 'Recent', icon: Clock, pinned: true, options: recentOptions },
...(defaultOption ? [{ key: 'default', title: 'Default', options: [defaultOption] }] : []),
{ key: 'favorites', title: 'Favorites', icon: Star, options: favoriteOptions },
{ key: 'recent', title: 'Recent', icon: Clock, options: recentOptions },
...providerSections.map((section) => ({
...section,
options: section.options.filter((option) => !pinnedValues.has(option.value)),
@@ -59,14 +93,42 @@ export function buildModelSections(providers: ProviderWithModels[], modelState:
return sections.filter((section) => section.options.length > 0)
}
function compareSearchMatches(a: ModelOption, b: ModelOption): number {
return compareCatalogModels(
{ name: a.label, free: a.model.free, released: a.model.released },
{ name: b.label, free: b.model.free, released: b.model.released },
)
}
export function filterModelSections(sections: ModelSection[], query: string): ModelSection[] {
const terms = query.toLowerCase().split(/\s+/).filter(Boolean)
if (terms.length === 0) return sections
return sections
.map((section) => ({
...section,
options: section.options.filter((option) => terms.every((term) => option.searchText.includes(term))),
}))
.filter((section) => section.options.length > 0)
const favoriteValues = new Set(
sections.find((section) => section.key === 'favorites')?.options.map((option) => option.value) ?? [],
)
const matches = sections
.flatMap((section) => section.options)
.filter((option) => terms.every((term) => option.searchText.includes(term)))
.sort(compareSearchMatches)
const results = [
...matches.filter((option) => favoriteValues.has(option.value)),
...matches.filter((option) => !favoriteValues.has(option.value)),
]
if (results.length === 0) return []
return [{ key: 'results', title: 'Results', options: results }]
}
export function toModelComboboxOptions(sections: ModelSection[], defaultRef?: string | null): ComboboxOption[] {
return sections.flatMap((section) =>
section.options.map((option) => {
const isDefault = defaultRef != null && option.value === defaultRef
return {
value: isDefault ? '' : option.value,
label: isDefault ? `Default: ${option.label}` : option.label,
description: isDefault ? undefined : option.value,
group: section.title,
}
}),
)
}
+1 -2
View File
@@ -91,7 +91,6 @@ describe('invalidateProviderCaches', () => {
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-credentials'] })
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-auth-methods'] })
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['providers-with-models'] })
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['providers'] })
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['providers-for-execution-model'] })
@@ -116,7 +115,7 @@ describe('invalidateProviderCachesDebounced', () => {
vi.advanceTimersByTime(200)
expect(invalidateQueries).toHaveBeenCalledTimes(4)
expect(invalidateQueries).toHaveBeenCalledTimes(3)
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
})
})
-1
View File
@@ -30,7 +30,6 @@ export function invalidateChildSessionCaches(queryClient: QueryClient, sessionID
export function invalidateProviderCaches(queryClient: QueryClient) {
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
queryClient.invalidateQueries({ queryKey: ['provider-auth-methods'] })
queryClient.invalidateQueries({ queryKey: ['providers-with-models'] })
queryClient.invalidateQueries({ queryKey: ['opencode', 'providers'] })
}
@@ -1,93 +1,41 @@
import { describe, it, expect } from 'vitest'
import {
buildAvailableModelKeys,
buildScheduleModelOptions,
resolveScheduleModel,
} from './schedule-model'
import type { ProviderWithModels } from '@/api/providers'
import { resolveScheduleModel } from './schedule-model'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
function makeProvider(id: string, models: Array<{ id: string; key?: string }>): ProviderWithModels {
return {
id,
name: id,
env: [],
models: models.map((model) => ({ ...model, name: model.key ?? model.id })),
source: 'builtin',
isConnected: true,
}
function model(providerID: string, id: string): ModelInfo {
return { providerID, id } as unknown as ModelInfo
}
describe('buildAvailableModelKeys', () => {
it('collects provider/model keys and backing model ids', () => {
const keys = buildAvailableModelKeys([
makeProvider('openai', [{ id: 'backing-gpt-5', key: 'gpt-5' }]),
makeProvider('anthropic', [{ id: 'claude-sonnet-4' }]),
])
expect(keys).toEqual(new Set([
'openai/gpt-5',
'openai/backing-gpt-5',
'anthropic/claude-sonnet-4',
]))
})
})
describe('buildScheduleModelOptions', () => {
const providers = [
makeProvider('anthropic', [{ id: 'claude-opus' }, { id: 'claude-sonnet' }]),
makeProvider('openai', [{ id: 'backing-gpt-5', key: 'gpt-5' }, { id: 'gpt-5-mini' }]),
]
it('orders default, favorites, and recents ahead of providers without duplicates', () => {
const options = buildScheduleModelOptions(
providers,
{
favorite: [{ providerID: 'openai', modelID: 'gpt-5-mini' }],
recent: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }, { providerID: 'openai', modelID: 'gpt-5' }],
variant: {},
},
'openai/backing-gpt-5',
)
expect(options.map((option) => [option.group, option.value])).toEqual([
['Default', 'openai/backing-gpt-5'],
['Favorites', 'openai/gpt-5-mini'],
['Recent', 'anthropic/claude-sonnet'],
['anthropic', 'anthropic/claude-opus'],
])
})
it('keeps an unknown default model selectable', () => {
const options = buildScheduleModelOptions(providers, undefined, 'custom/model-x')
expect(options[0]).toEqual({ value: 'custom/model-x', label: 'model-x', description: 'custom/model-x', group: 'Default' })
})
})
describe('resolveScheduleModel', () => {
const available = new Set(['openai/gpt-5', 'openai/gpt-5-mini'])
const models: ModelInfo[] = [model('openai', 'gpt-5'), model('openai', 'gpt-5-mini')]
it('keeps a stored model that is still available', () => {
expect(resolveScheduleModel('openai/gpt-5-mini', available, 'openai/gpt-5')).toBe('openai/gpt-5-mini')
expect(resolveScheduleModel('openai/gpt-5-mini', models)).toBe('openai/gpt-5-mini')
})
it('falls back to the config default when the stored model is gone', () => {
expect(resolveScheduleModel('openai/retired', available, 'openai/gpt-5')).toBe('openai/gpt-5')
it('keeps a stored model with a variant suffix', () => {
expect(resolveScheduleModel('openai/gpt-5#high', models)).toBe('openai/gpt-5#high')
})
it('returns null when neither the stored model nor the config default is available', () => {
expect(resolveScheduleModel('openai/retired', available, 'openai/also-retired')).toBeNull()
it('drops a stored model that is no longer available without a fallback', () => {
expect(resolveScheduleModel('openai/retired', models)).toBeNull()
})
it('drops a stored model that matches only the backing model id', () => {
expect(resolveScheduleModel('openai/gpt-5-2025-08-07', models)).toBeNull()
})
it('treats an empty stored model as the workspace default', () => {
expect(resolveScheduleModel('', available, 'openai/gpt-5')).toBeNull()
expect(resolveScheduleModel(null, available, 'openai/gpt-5')).toBeNull()
expect(resolveScheduleModel('', models)).toBeNull()
expect(resolveScheduleModel(' ', models)).toBeNull()
expect(resolveScheduleModel(null, models)).toBeNull()
})
it('keeps the stored model while availability is unknown', () => {
expect(resolveScheduleModel('openai/retired', null, 'openai/gpt-5')).toBe('openai/retired')
expect(resolveScheduleModel('openai/retired', null)).toBe('openai/retired')
})
it('drops the stored model when availability is confirmed empty', () => {
expect(resolveScheduleModel('openai/retired', new Set(), 'openai/gpt-5')).toBeNull()
it('keeps the stored model when the catalog is empty', () => {
expect(resolveScheduleModel('openai/retired', [])).toBe('openai/retired')
})
})
+5 -56
View File
@@ -1,7 +1,5 @@
import type { OpenCodeModelState, ProviderWithModels } from '@/api/providers'
import { providerModelRef } from '@/api/providers'
import type { ComboboxOption } from '@/components/ui/combobox'
import { buildModelSections } from '@/lib/modelSections'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
import { isModelAvailable } from '@/lib/modelCatalog'
function normalizeModel(model: unknown): string | null {
if (typeof model !== 'string') return null
@@ -9,61 +7,12 @@ function normalizeModel(model: unknown): string | null {
return trimmed ? trimmed : null
}
export function buildAvailableModelKeys(providers: ProviderWithModels[]): Set<string> {
const keys = new Set<string>()
for (const provider of providers) {
for (const model of provider.models) {
keys.add(providerModelRef(provider, model))
keys.add(`${provider.id}/${model.id}`)
}
}
return keys
}
function findProviderModel(providers: ProviderWithModels[], ref: string) {
const [providerId, ...modelParts] = ref.split('/')
const modelId = modelParts.join('/')
const provider = providers.find((candidate) => candidate.id === providerId)
const model = provider?.models.find((candidate) => candidate.key === modelId || candidate.id === modelId)
return provider && model ? { value: providerModelRef(provider, model), label: model.name || modelId } : { value: ref, label: modelId || ref }
}
/** Builds schedule model options with the default, favorite, and recent models ahead of the provider groups. */
export function buildScheduleModelOptions(
providers: ProviderWithModels[],
modelState: OpenCodeModelState | undefined,
defaultModel: string | null | undefined,
): ComboboxOption[] {
const normalizedDefault = normalizeModel(defaultModel)
const defaultModelMatch = normalizedDefault ? findProviderModel(providers, normalizedDefault) : null
const sectionOptions = buildModelSections(providers, modelState).flatMap((section) =>
section.options
.filter((option) => option.value !== defaultModelMatch?.value)
.map((option) => ({
value: option.value,
label: option.label,
description: option.value,
group: section.title,
})),
)
if (!normalizedDefault || !defaultModelMatch) return sectionOptions
return [
{ value: normalizedDefault, label: defaultModelMatch.label, description: normalizedDefault, group: 'Default' },
...sectionOptions,
]
}
export function resolveScheduleModel(
storedModel: string | null | undefined,
availableModelKeys: ReadonlySet<string> | null,
configDefaultModel: string | null | undefined,
availableModels: ModelInfo[] | null,
): string | null {
const stored = normalizeModel(storedModel)
if (!stored) return null
if (availableModelKeys === null) return stored
if (availableModelKeys.has(stored)) return stored
const configDefault = normalizeModel(configDefaultModel)
if (configDefault && availableModelKeys.has(configDefault)) return configDefault
return null
if (availableModels === null || availableModels.length === 0) return stored
return isModelAvailable(availableModels, stored) ? stored : null
}
+7 -2
View File
@@ -49,6 +49,7 @@ import type { PageCommandActions } from "@/lib/builtinCommands";
import { useRedoMessage, useUndoMessage } from "@/hooks/useUndoMessage";
import { usePermissions, useForms } from "@/contexts/EventContext";
import type { FormInfo, SessionMessageInfo } from "@opencode-manager/shared/opencode";
import { formatOpenCodeModelRef } from "@opencode-manager/shared/opencode";
import { FormPrompt } from "@/components/session/FormPrompt";
import { MinimizedFormIndicator } from "@/components/session/MinimizedFormIndicator";
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
@@ -259,7 +260,11 @@ export function SessionDetail() {
const interruptSession = useInterruptSession();
const { mutateAsync: updateSessionAsync } = useUpdateSession(sessionDirectory);
const { mutateAsync: createSessionAsync } = useCreateSession(sessionDirectory);
const { modelString } = useModelSelection(sessionDirectory);
const modelSelectionSession = useMemo(
() => (sessionId ? { id: sessionId, agent: session?.agent, model: session?.model } : undefined),
[sessionId, session?.agent, session?.model],
);
const { modelRef } = useModelSelection(sessionDirectory, modelSelectionSession);
const setSessionStatus = useSessionStatus((state) => state.setStatus);
const isEditingMessage = useUIState((state) => state.isEditingMessage);
const setActivePromptFileBasePath = useUIState((state) => state.setActivePromptFileBasePath);
@@ -723,7 +728,7 @@ export function SessionDetail() {
onFileClick={handleFileClick}
onChildSessionClick={handleChildSessionClick}
onUndoMessage={handleUndoMessage}
model={modelString || undefined}
model={modelRef ? formatOpenCodeModelRef(modelRef) : undefined}
/>
) : null}
</div>
@@ -36,7 +36,7 @@ vi.mock('@/hooks/useSessionTranscript', () => ({
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
useModelSelection: vi.fn(() => ({ model: null, modelString: null, modelRef: null })),
}))
vi.mock('@/hooks/useTTS', () => ({
@@ -99,7 +99,7 @@ vi.mock('@/hooks/useSessionTranscript', () => ({
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
useModelSelection: vi.fn(() => ({ model: null, modelString: null, modelRef: null })),
}))
vi.mock('@/hooks/useTTS', () => ({
@@ -59,7 +59,7 @@ vi.mock('@/hooks/useSessionTranscript', () => ({
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
useModelSelection: vi.fn(() => ({ model: null, modelString: null, modelRef: null })),
}))
vi.mock('@/hooks/useTTS', () => ({
@@ -38,7 +38,7 @@ vi.mock('@/hooks/useSessionTranscript', () => ({
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
useModelSelection: vi.fn(() => ({ model: null, modelString: null, modelRef: null })),
}))
vi.mock('@/hooks/useTTS', () => ({
@@ -54,7 +54,7 @@ vi.mock('@/hooks/useSessionTranscript', () => ({
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
useModelSelection: vi.fn(() => ({ model: null, modelString: null, modelRef: null })),
}))
vi.mock('@/hooks/useTTS', () => ({
+100 -366
View File
@@ -1,408 +1,142 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { useModelStore, modelExists } from '@/stores/modelStore'
import type { Provider } from '@/api/providers'
import { describe, it, expect, beforeEach } from 'vitest'
import { locationAgentKey, useModelStore } from '@/stores/modelStore'
beforeEach(() => {
useModelStore.setState({
model: null,
variants: {},
lastConfigModel: undefined,
const resetStore = () => {
useModelStore.setState({ newSessionPicks: {}, sessionPicks: {}, activeAgent: null })
}
describe('locationAgentKey', () => {
it('combines the directory and agent id', () => {
expect(locationAgentKey('/repo', 'build')).toBe(JSON.stringify(['/repo', 'build']))
})
it('normalizes missing values', () => {
expect(locationAgentKey(undefined, undefined)).toBe(JSON.stringify(['', '']))
expect(locationAgentKey(undefined, 'build')).toBe(JSON.stringify(['', 'build']))
})
})
function makeProvider(overrides: Partial<Provider>): Provider {
return {
id: overrides.id ?? 'test-provider',
name: overrides.name ?? 'Test Provider',
models: overrides.models ?? {},
isConnected: true,
...overrides,
}
}
describe('setNewSessionPick', () => {
beforeEach(resetStore)
const openaiProviders = [
makeProvider({
id: 'openai',
models: { 'gpt-4o': { id: 'gpt-4o', name: 'GPT-4o' } },
}),
]
describe('validateAndSyncModel', () => {
beforeEach(() => {
useModelStore.setState({
model: null,
variants: {},
lastConfigModel: undefined,
})
it('stores a selection under its key', () => {
useModelStore.getState().setNewSessionPick('key', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
expect(useModelStore.getState().newSessionPicks.key).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
it('falls back to syncFromConfig when providers is undefined', () => {
useModelStore.getState().validateAndSyncModel('anthropic/claude-sonnet-4', undefined)
expect(useModelStore.getState().model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
it('stores the variant with the selection', () => {
useModelStore.getState().setNewSessionPick('key', { providerID: 'anthropic', modelID: 'claude-sonnet-4', variant: 'high' })
expect(useModelStore.getState().newSessionPicks.key.variant).toBe('high')
})
it('uses config model when current model is missing and config is valid', () => {
useModelStore.setState({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
})
useModelStore.getState().validateAndSyncModel('openai/gpt-4o', openaiProviders)
expect(useModelStore.getState().model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
it('uses first valid recent model when config is invalid', () => {
useModelStore.setState({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
})
useModelStore.getState().validateAndSyncModel('nonexistent/model', openaiProviders, [
{ providerID: 'nonexistent', modelID: 'model' },
{ providerID: 'openai', modelID: 'gpt-4o' },
])
expect(useModelStore.getState().model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
it('uses fallback model when config and recent are invalid', () => {
useModelStore.setState({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
})
useModelStore.getState().validateAndSyncModel(
'nonexistent/model',
openaiProviders,
[{ providerID: 'nonexistent', modelID: 'model' }],
'openai/gpt-4o'
)
expect(useModelStore.getState().model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
it('leaves model null when config, recent, and fallback are all invalid', () => {
useModelStore.setState({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
})
useModelStore.getState().validateAndSyncModel(
'nonexistent/model',
openaiProviders,
[{ providerID: 'nonexistent', modelID: 'model' }],
'nonexistent/fallback'
)
expect(useModelStore.getState().model).toBeNull()
})
it('does not override a current model that exists in providers', () => {
useModelStore.setState({
model: { providerID: 'openai', modelID: 'gpt-4o' },
})
useModelStore.getState().validateAndSyncModel(
'nonexistent/model',
openaiProviders,
[{ providerID: 'nonexistent', modelID: 'model' }],
'nonexistent/fallback'
)
expect(useModelStore.getState().model).toEqual({ providerID: 'openai', modelID: 'gpt-4o' })
})
it('clears stale hydrated model when nothing resolves', () => {
const providers = [
makeProvider({
id: 'openrouter',
models: { 'qwen/qwen3-235b-a22b': { id: 'qwen/qwen3-235b-a22b', name: 'Qwen3 235B' } },
}),
]
useModelStore.setState({
model: { providerID: 'openrouter', modelID: 'qwen/qwen3-35b' },
})
useModelStore.getState().validateAndSyncModel(undefined, providers)
expect(useModelStore.getState().model).toBeNull()
})
it('is idempotent when re-running with same valid state', () => {
const providers = [
makeProvider({
id: 'anthropic',
models: { 'claude-sonnet-4': { id: 'claude-sonnet-4', name: 'Claude Sonnet 4' } },
}),
]
useModelStore.setState({
model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' },
})
useModelStore.getState().validateAndSyncModel('anthropic/claude-sonnet-4', providers)
const afterFirst = useModelStore.getState()
it('does not notify subscribers when the selection is unchanged', () => {
useModelStore.getState().setNewSessionPick('key', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
let updateCount = 0
const unsubscribe = useModelStore.subscribe(() => {
updateCount++
})
useModelStore.getState().validateAndSyncModel('anthropic/claude-sonnet-4', providers)
useModelStore.getState().setNewSessionPick('key', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
unsubscribe()
const afterSecond = useModelStore.getState()
expect(updateCount).toBe(0)
expect(afterSecond.model).toEqual(afterFirst.model)
})
})
describe('setModel', () => {
beforeEach(() => {
useModelStore.setState({
model: null,
variants: {},
lastConfigModel: undefined,
it('treats a default variant as no variant for equality', () => {
useModelStore.getState().setNewSessionPick('key', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
let updateCount = 0
const unsubscribe = useModelStore.subscribe(() => {
updateCount++
})
})
it('sets the model', () => {
const model = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
useModelStore.getState().setModel(model)
expect(useModelStore.getState().model).toEqual(model)
})
it('replaces the previous model', () => {
useModelStore.setState({ model: { providerID: 'openai', modelID: 'gpt-4o' } })
useModelStore.getState().setModel({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
expect(useModelStore.getState().model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
})
describe('setActiveModel', () => {
beforeEach(() => {
useModelStore.setState({
model: null,
variants: {},
lastConfigModel: undefined,
})
})
it('sets the active model', () => {
const model = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
useModelStore.getState().setActiveModel(model)
expect(useModelStore.getState().model).toEqual(model)
})
})
describe('syncFromConfig', () => {
beforeEach(() => {
useModelStore.setState({
model: null,
variants: {},
lastConfigModel: undefined,
})
})
it('sets model and lastConfigModel from valid config string', () => {
useModelStore.getState().syncFromConfig('anthropic/claude-sonnet-4')
expect(useModelStore.getState().model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
expect(useModelStore.getState().lastConfigModel).toBe('anthropic/claude-sonnet-4')
})
it('does nothing when same config already synced', () => {
useModelStore.setState({ model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' }, lastConfigModel: 'anthropic/claude-sonnet-4' })
useModelStore.getState().syncFromConfig('anthropic/claude-sonnet-4')
expect(useModelStore.getState().lastConfigModel).toBe('anthropic/claude-sonnet-4')
})
it('updates when force is true even if same config', () => {
useModelStore.setState({ model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' }, lastConfigModel: 'anthropic/claude-sonnet-4' })
useModelStore.getState().syncFromConfig('anthropic/claude-sonnet-4', true)
expect(useModelStore.getState().lastConfigModel).toBe('anthropic/claude-sonnet-4')
})
it('handles invalid config string gracefully', () => {
useModelStore.getState().syncFromConfig('invalid')
expect(useModelStore.getState().model).toBeNull()
expect(useModelStore.getState().lastConfigModel).toBe('invalid')
})
it('strips a model variant when syncing the config model', () => {
useModelStore.getState().syncFromConfig('anthropic/claude-sonnet-4#high')
expect(useModelStore.getState().model).toEqual({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })
})
it('keeps slashes inside the model id when syncing the config model', () => {
useModelStore.getState().syncFromConfig('openrouter/anthropic/claude-sonnet-4')
expect(useModelStore.getState().model).toEqual({
providerID: 'openrouter',
modelID: 'anthropic/claude-sonnet-4',
})
})
it('handles undefined config string', () => {
useModelStore.getState().syncFromConfig(undefined)
expect(useModelStore.getState().lastConfigModel).toBeUndefined()
})
})
describe('getModelString', () => {
beforeEach(() => {
useModelStore.setState({
model: null,
variants: {},
lastConfigModel: undefined,
})
})
it('returns null when no model selected', () => {
expect(useModelStore.getState().getModelString()).toBeNull()
})
it('returns providerID/modelID string when model is set', () => {
useModelStore.setState({ model: { providerID: 'anthropic', modelID: 'claude-sonnet-4' } })
expect(useModelStore.getState().getModelString()).toBe('anthropic/claude-sonnet-4')
})
})
describe('variants', () => {
beforeEach(() => {
useModelStore.setState({
model: null,
variants: {},
lastConfigModel: undefined,
})
})
it('setVariant stores variant for model', () => {
const model = { providerID: 'openai', modelID: 'gpt-4o' }
useModelStore.getState().setVariant(model, 'gpt-4o-2024-05-13')
expect(useModelStore.getState().variants['openai/gpt-4o']).toBe('gpt-4o-2024-05-13')
})
it('getVariant returns variant for model', () => {
const model = { providerID: 'openai', modelID: 'gpt-4o' }
useModelStore.getState().setVariant(model, 'gpt-4o-2024-05-13')
expect(useModelStore.getState().getVariant(model)).toBe('gpt-4o-2024-05-13')
})
it('getVariant returns undefined when no variant set', () => {
expect(useModelStore.getState().getVariant({ providerID: 'anthropic', modelID: 'claude-sonnet-4' })).toBeUndefined()
})
it('clearVariant removes variant for model', () => {
const model = { providerID: 'openai', modelID: 'gpt-4o' }
useModelStore.getState().setVariant(model, 'gpt-4o-2024-05-13')
useModelStore.getState().clearVariant(model)
expect(useModelStore.getState().variants['openai/gpt-4o']).toBeUndefined()
})
it('clearVariant is idempotent', () => {
const model = { providerID: 'openai', modelID: 'gpt-4o' }
expect(() => useModelStore.getState().clearVariant(model)).not.toThrow()
})
it('clearVariant does not notify subscribers when variant is already absent', () => {
const model = { providerID: 'openai', modelID: 'gpt-4o' }
const listener = vi.fn()
const unsubscribe = useModelStore.subscribe(listener)
useModelStore.getState().clearVariant(model)
useModelStore.getState().setNewSessionPick('key', { providerID: 'anthropic', modelID: 'claude-sonnet-4', variant: 'default' })
unsubscribe()
expect(listener).not.toHaveBeenCalled()
expect(updateCount).toBe(0)
})
it('setVariant does not notify subscribers when variant is unchanged', () => {
const model = { providerID: 'openai', modelID: 'gpt-4o' }
useModelStore.getState().setVariant(model, 'gpt-4o-2024-05-13')
const listener = vi.fn()
const unsubscribe = useModelStore.subscribe(listener)
it('updates when only the variant changes', () => {
useModelStore.getState().setNewSessionPick('key', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
useModelStore.getState().setNewSessionPick('key', { providerID: 'anthropic', modelID: 'claude-sonnet-4', variant: 'high' })
expect(useModelStore.getState().newSessionPicks.key.variant).toBe('high')
})
})
useModelStore.getState().setVariant(model, 'gpt-4o-2024-05-13')
describe('setSessionPick', () => {
beforeEach(resetStore)
it('stores a per-session agent selection', () => {
useModelStore.getState().setSessionPick('session-1', 'build', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
expect(useModelStore.getState().sessionPicks['session-1'].build).toEqual({
providerID: 'anthropic',
modelID: 'claude-sonnet-4',
})
})
it('keeps selections for different agents independent', () => {
useModelStore.getState().setSessionPick('session-1', 'build', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
useModelStore.getState().setSessionPick('session-1', 'plan', { providerID: 'openai', modelID: 'gpt-4o' })
expect(useModelStore.getState().sessionPicks['session-1'].build.modelID).toBe('claude-sonnet-4')
expect(useModelStore.getState().sessionPicks['session-1'].plan.modelID).toBe('gpt-4o')
})
it('removes the selection when set to undefined', () => {
useModelStore.getState().setSessionPick('session-1', 'build', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
useModelStore.getState().setSessionPick('session-1', 'build', undefined)
expect(useModelStore.getState().sessionPicks['session-1'].build).toBeUndefined()
})
it('does not notify subscribers when the selection is unchanged', () => {
useModelStore.getState().setSessionPick('session-1', 'build', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
let updateCount = 0
const unsubscribe = useModelStore.subscribe(() => {
updateCount++
})
useModelStore.getState().setSessionPick('session-1', 'build', { providerID: 'anthropic', modelID: 'claude-sonnet-4' })
unsubscribe()
expect(listener).not.toHaveBeenCalled()
expect(updateCount).toBe(0)
})
})
describe('syncModelState', () => {
beforeEach(() => {
useModelStore.setState({
model: null,
variants: {},
lastConfigModel: undefined,
describe('setActiveAgent', () => {
beforeEach(resetStore)
it('stores the active agent', () => {
useModelStore.getState().setActiveAgent({ id: 'build', model: { providerID: 'anthropic', id: 'claude-sonnet-4' } })
expect(useModelStore.getState().activeAgent).toEqual({
id: 'build',
model: { providerID: 'anthropic', id: 'claude-sonnet-4' },
})
})
it('merges variants from model state', () => {
useModelStore.getState().syncModelState({
recent: [],
favorite: [],
variant: { 'anthropic/claude-sonnet-4': 'claude-sonnet-4-20250514' },
it('does not notify subscribers when the id and model ref are unchanged', () => {
useModelStore.getState().setActiveAgent({ id: 'build', model: { providerID: 'anthropic', id: 'claude-sonnet-4' } })
let updateCount = 0
const unsubscribe = useModelStore.subscribe(() => {
updateCount++
})
expect(useModelStore.getState().variants['anthropic/claude-sonnet-4']).toBe('claude-sonnet-4-20250514')
useModelStore.getState().setActiveAgent({ id: 'build', model: { providerID: 'anthropic', id: 'claude-sonnet-4' } })
unsubscribe()
expect(updateCount).toBe(0)
})
it('existing store variants take precedence over incoming variants', () => {
useModelStore.setState({ variants: { 'anthropic/claude-sonnet-4': 'existing-variant' } })
useModelStore.getState().syncModelState({
recent: [],
favorite: [],
variant: { 'anthropic/claude-sonnet-4': 'incoming-variant' },
})
expect(useModelStore.getState().variants['anthropic/claude-sonnet-4']).toBe('existing-variant')
it('updates when the agent model ref changes', () => {
useModelStore.getState().setActiveAgent({ id: 'build', model: { providerID: 'anthropic', id: 'claude-sonnet-4' } })
useModelStore.getState().setActiveAgent({ id: 'build', model: { providerID: 'openai', id: 'gpt-4o' } })
expect(useModelStore.getState().activeAgent?.model).toEqual({ providerID: 'openai', id: 'gpt-4o' })
})
it('ignores recent and favorite fields from model state', () => {
useModelStore.getState().syncModelState({
recent: [{ providerID: 'openai', modelID: 'gpt-4o' }],
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet-4' }],
variant: {},
})
const state = useModelStore.getState() as Record<string, unknown>
expect(state).not.toHaveProperty('recentModels')
expect(state).not.toHaveProperty('favoriteModels')
})
})
describe('modelExists', () => {
const providers = [
makeProvider({
id: 'openai',
models: { 'gpt-4o': { id: 'gpt-4o', name: 'GPT-4o' } },
}),
makeProvider({
id: 'anthropic',
models: { 'claude-sonnet-4': { id: 'claude-sonnet-4', name: 'Claude Sonnet 4' } },
}),
]
it('returns true when provider and model exist', () => {
expect(modelExists({ providerID: 'openai', modelID: 'gpt-4o' }, providers)).toBe(true)
})
it('returns false when provider does not exist', () => {
expect(modelExists({ providerID: 'nonexistent', modelID: 'gpt-4o' }, providers)).toBe(false)
})
it('returns false when model does not exist in provider', () => {
expect(modelExists({ providerID: 'openai', modelID: 'nonexistent' }, providers)).toBe(false)
})
it('returns false when model is null', () => {
expect(modelExists(null, providers)).toBe(false)
})
it('returns false when providers list is empty', () => {
expect(modelExists({ providerID: 'openai', modelID: 'gpt-4o' }, [])).toBe(false)
it('updates when the agent id changes', () => {
useModelStore.getState().setActiveAgent({ id: 'build', model: { providerID: 'anthropic', id: 'claude-sonnet-4' } })
useModelStore.getState().setActiveAgent({ id: 'plan', model: { providerID: 'anthropic', id: 'claude-sonnet-4' } })
expect(useModelStore.getState().activeAgent?.id).toBe('plan')
})
})
+51 -135
View File
@@ -1,157 +1,73 @@
import { create } from 'zustand'
import { parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import type { Provider } from '@/api/providers'
import { isSameModelRef, isSameModelSelection, normalizeModelVariant } from '@opencode-manager/shared/opencode'
import type { ModelRef } from '@opencode-manager/shared/opencode'
import type { ModelSelection } from '@/api/providers'
export interface ModelSelection {
providerID: string
modelID: string
export type { ModelSelection }
export type ModelPick = ModelSelection & { variant?: string }
export interface ActiveAgent {
id: string
model?: ModelRef
}
interface ModelStore {
model: ModelSelection | null
variants: Record<string, string | undefined>
lastConfigModel: string | undefined
setModel: (model: ModelSelection) => void
setActiveModel: (model: ModelSelection) => void
syncModelState: (state: { recent: ModelSelection[], favorite: ModelSelection[], variant: Record<string, string | undefined> }) => void
syncFromConfig: (configModel: string | undefined, force?: boolean) => void
validateAndSyncModel: (configModel: string | undefined, providers?: Provider[], recent?: ModelSelection[], fallbackModel?: string) => void
getModelString: () => string | null
setVariant: (model: ModelSelection, variant: string | undefined) => void
getVariant: (model: ModelSelection) => string | undefined
clearVariant: (model: ModelSelection) => void
newSessionPicks: Record<string, ModelPick>
sessionPicks: Record<string, Record<string, ModelPick>>
activeAgent: ActiveAgent | null
setNewSessionPick: (key: string, selection: ModelPick) => void
setSessionPick: (sessionID: string, agentID: string, selection: ModelPick | undefined) => void
setActiveAgent: (agent: ActiveAgent) => void
}
export function modelExists(model: ModelSelection | null, providers: Provider[]): boolean {
if (!model) return false
return providers.some(
(p) => p.id === model.providerID && p.models && model.modelID in p.models
export function locationAgentKey(directory: string | undefined, agentID: string | undefined): string {
return JSON.stringify([directory ?? '', agentID ?? ''])
}
function isSamePick(left: ModelPick | undefined, right: ModelPick | undefined): boolean {
if (!left || !right) return left === right
return (
isSameModelSelection(left, right) &&
normalizeModelVariant(left.variant) === normalizeModelVariant(right.variant)
)
}
function modelSelectionFromString(model: string): ModelSelection | null {
const ref = parseOpenCodeModelRef(model)
return ref ? { providerID: ref.providerID, modelID: ref.id } : null
}
function mergeVariants(
current: Record<string, string | undefined>,
incoming: Record<string, string | undefined>
): Record<string, string | undefined> | undefined {
const next = { ...incoming, ...current }
const currentKeys = Object.keys(current)
const nextKeys = Object.keys(next)
if (currentKeys.length !== nextKeys.length) return next
return nextKeys.some((key) => current[key] !== next[key]) ? next : undefined
}
if (typeof localStorage !== 'undefined') localStorage.removeItem('opencode-model-selection')
export const useModelStore = create<ModelStore>()((set, get) => ({
model: null,
variants: {},
lastConfigModel: undefined,
newSessionPicks: {},
sessionPicks: {},
activeAgent: null,
setModel: (model: ModelSelection) => {
set({ model })
setNewSessionPick: (key, selection) => {
if (isSamePick(get().newSessionPicks[key], selection)) return
set((state) => ({ newSessionPicks: { ...state.newSessionPicks, [key]: selection } }))
},
setActiveModel: (model: ModelSelection) => {
set({ model })
},
syncModelState: (modelState) => {
const variants = mergeVariants(get().variants, modelState.variant)
if (variants) {
set({ variants })
}
},
syncFromConfig: (configModel: string | undefined, force = false) => {
const state = get()
if (!force && state.lastConfigModel === configModel) return
if (configModel) {
const parsed = modelSelectionFromString(configModel)
if (parsed) {
set({ model: parsed, lastConfigModel: configModel })
return
}
}
set({ lastConfigModel: configModel })
},
validateAndSyncModel: (configModel: string | undefined, providers?: Provider[], recent: ModelSelection[] = [], fallbackModel?: string) => {
if (!providers) {
if (configModel) {
get().syncFromConfig(configModel)
}
setSessionPick: (sessionID, agentID, selection) => {
const current = get().sessionPicks[sessionID]?.[agentID]
if (selection === undefined) {
if (current === undefined) return
set((state) => {
const next = { ...state.sessionPicks[sessionID] }
delete next[agentID]
return { sessionPicks: { ...state.sessionPicks, [sessionID]: next } }
})
return
}
const state = get()
if (state.model && modelExists(state.model, providers)) return
const parsedConfig = configModel ? modelSelectionFromString(configModel) : null
if (parsedConfig && modelExists(parsedConfig, providers)) {
get().syncFromConfig(configModel, true)
return
}
const recentModel = recent.find((model) => modelExists(model, providers))
if (recentModel) {
set({ model: recentModel, lastConfigModel: configModel })
return
}
const parsedFallback = fallbackModel ? modelSelectionFromString(fallbackModel) : null
if (parsedFallback && modelExists(parsedFallback, providers)) {
set({ model: parsedFallback, lastConfigModel: configModel })
return
}
if (state.model === null && state.lastConfigModel === configModel) return
set({ model: null, lastConfigModel: configModel })
if (isSamePick(current, selection)) return
set((state) => ({
sessionPicks: {
...state.sessionPicks,
[sessionID]: { ...state.sessionPicks[sessionID], [agentID]: selection },
},
}))
},
getModelString: () => {
const { model } = get()
if (!model) return null
return `${model.providerID}/${model.modelID}`
},
setVariant: (model: ModelSelection, variant: string | undefined) => {
const key = `${model.providerID}/${model.modelID}`
if (get().variants[key] === variant) return
set((state) => {
return {
variants: {
...state.variants,
[key]: variant,
},
}
})
},
getVariant: (model: ModelSelection) => {
const state = get()
const key = `${model.providerID}/${model.modelID}`
return state.variants[key]
},
clearVariant: (model: ModelSelection) => {
const key = `${model.providerID}/${model.modelID}`
if (!(key in get().variants)) return
set((state) => {
const newVariants = { ...state.variants }
delete newVariants[key]
return {
variants: newVariants,
}
})
setActiveAgent: (agent) => {
const current = get().activeAgent
if (current && current.id === agent.id && isSameModelRef(current.model, agent.model)) return
set({ activeAgent: agent })
},
}))
+25 -1
View File
@@ -48,7 +48,31 @@ export { ClientError, isIntegrationNotFoundError, isMcpServerNotFoundError, isSe
export { assistantText, sessionIDFromEvent, toolContentText } from './content'
export { formatOpenCodeModelRef, parseOpenCodeModelRef, selectConfiguredModelRef } from './modelRef'
export { configModelRef, formatOpenCodeModelRef, parseOpenCodeModelRef, selectConfiguredModelRef } from './modelRef'
export {
addRecentModel,
compareCatalogModels,
cycleModelVariant,
decodeModelPreference,
favoriteModels,
findModelInfo,
isModelFree,
isSameModelRef,
isSameModelSelection,
modelPreferenceKey,
normalizeModelVariant,
recentModels,
removeRecentModel,
selectEffectiveModelRef,
selectInteractiveModel,
selectPreferredVariant,
setModelVariant,
toModelPreference,
toggleFavoriteModel,
} from './modelPreference'
export type { ModelPreference, ModelPreferenceDocument, ModelPreferenceModel } from './modelPreference'
export {
MCP_OAUTH_CALLBACK_PATH,
+1 -4
View File
@@ -1,4 +1,5 @@
import type { ConfigEntry, McpServer } from '@opencode/client'
import { isRecord } from '../utils/record'
export const MCP_OAUTH_CALLBACK_PATH = '/api/mcp-oauth-proxy/callback'
@@ -18,10 +19,6 @@ export function mcpOAuthRedirectUri(origin: string): string {
return new URL(MCP_OAUTH_CALLBACK_PATH, origin).toString()
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isMcpServerConfig(value: unknown): value is McpServerConfig {
return isRecord(value) && (value.type === 'local' || value.type === 'remote')
}
+245
View File
@@ -0,0 +1,245 @@
import type { ModelInfo, ModelRef } from '@opencode/client'
import { isRecord } from '../utils/record'
export type ModelPreferenceModel = {
providerID: string
modelID: string
}
export type ModelPreference = {
recent: ModelPreferenceModel[]
favorite: ModelPreferenceModel[]
variant: Record<string, string | undefined>
}
export type ModelPreferenceDocument = Record<string, unknown> & ModelPreference
function models(value: unknown): ModelPreferenceModel[] {
if (!Array.isArray(value)) return []
return value.flatMap((item): ModelPreferenceModel[] => {
if (!isRecord(item)) return []
if (typeof item.providerID !== 'string' || item.providerID.length === 0) return []
if (typeof item.modelID !== 'string' || item.modelID.length === 0) return []
return [{ providerID: item.providerID, modelID: item.modelID }]
})
}
function variants(value: unknown): Record<string, string | undefined> {
if (!isRecord(value)) return {}
return Object.fromEntries(
Object.entries(value).flatMap(([key, item]) => {
if (key.length === 0 || typeof item !== 'string' || item.length === 0) return []
return [[key, item]] as const
}),
)
}
export function normalizeModelVariant(value: string | undefined): string | undefined {
return value === 'default' ? undefined : value
}
export function modelPreferenceKey(model: ModelPreferenceModel): string {
return `${model.providerID}/${model.modelID}`
}
export function isSameModelSelection(a: ModelPreferenceModel, b: ModelPreferenceModel): boolean {
return a.providerID === b.providerID && a.modelID === b.modelID
}
export function isSameModelRef(a: ModelRef | undefined | null, b: ModelRef | undefined | null): boolean {
if (!a || !b) return !a && !b
return (
a.providerID === b.providerID &&
a.id === b.id &&
normalizeModelVariant(a.variant) === normalizeModelVariant(b.variant)
)
}
export function findModelInfo(models: ModelInfo[], selection: ModelPreferenceModel): ModelInfo | undefined {
return models.find((model) => model.providerID === selection.providerID && model.id === selection.modelID)
}
export function recentModels(model: ModelPreferenceModel, recent: ModelPreferenceModel[]): ModelPreferenceModel[] {
const seen = new Set<string>()
return [model, ...recent]
.filter((item) => {
const key = modelPreferenceKey(item)
if (seen.has(key)) return false
seen.add(key)
return true
})
.slice(0, 10)
.map((item) => ({ providerID: item.providerID, modelID: item.modelID }))
}
export function favoriteModels(
model: ModelPreferenceModel,
favorite: ModelPreferenceModel[],
enabled: boolean,
): ModelPreferenceModel[] {
const current = favorite.filter((item) => modelPreferenceKey(item) !== modelPreferenceKey(model))
return enabled ? [model, ...current] : current
}
export function addRecentModel<T extends ModelPreference>(state: T, model: ModelPreferenceModel): T {
return { ...state, recent: recentModels(model, state.recent) }
}
export function removeRecentModel<T extends ModelPreference>(state: T, model: ModelPreferenceModel): T {
return { ...state, recent: state.recent.filter((item) => !isSameModelSelection(item, model)) }
}
export function toggleFavoriteModel<T extends ModelPreference>(state: T, model: ModelPreferenceModel): T {
const exists = state.favorite.some((item) => isSameModelSelection(item, model))
return { ...state, favorite: favoriteModels(model, state.favorite, !exists) }
}
export function setModelVariant<T extends ModelPreference>(
state: T,
model: ModelPreferenceModel,
value: string | undefined,
): T {
return {
...state,
variant: { ...state.variant, [modelPreferenceKey(model)]: normalizeModelVariant(value) ?? 'default' },
}
}
export function cycleModelVariant(current: string | undefined, variants: string[]): string | undefined {
const named = variants.filter((variant) => variant !== 'default')
if (named.length === 0) return undefined
const value = normalizeModelVariant(current)
if (value === undefined) return named[0]
const index = named.indexOf(value)
if (index === -1 || index === named.length - 1) return undefined
return named[index + 1]
}
export function decodeModelPreference(value: unknown): ModelPreferenceDocument {
const root = isRecord(value) ? value : {}
return {
...root,
recent: models(root.recent),
favorite: models(root.favorite),
variant: variants(root.variant),
}
}
export function toModelPreference(doc: ModelPreference): ModelPreference {
return { recent: doc.recent, favorite: doc.favorite, variant: doc.variant }
}
export function isModelFree(info: { cost: Array<{ input: number }> }): boolean {
return info.cost.length > 0 && info.cost.every((cost) => cost.input === 0)
}
function refSelection(ref: ModelRef): ModelPreferenceModel {
return { providerID: ref.providerID, modelID: ref.id }
}
interface SelectInteractiveModelOptions {
models: ModelInfo[]
current?: ModelPreferenceModel | null
agentModel?: ModelRef | null
configured?: ModelRef | null
recent?: ModelPreferenceModel[]
}
export function selectInteractiveModel(options: SelectInteractiveModelOptions): ModelPreferenceModel | undefined {
const candidates: Array<ModelPreferenceModel | undefined> = [
options.current ?? undefined,
options.agentModel ? refSelection(options.agentModel) : undefined,
options.configured ? refSelection(options.configured) : undefined,
...(options.recent ?? []),
]
const selected = candidates.find(
(candidate): candidate is ModelPreferenceModel =>
candidate !== undefined && findModelInfo(options.models, candidate) !== undefined,
)
if (selected) return selected
const first = options.models[0]
return first ? { providerID: first.providerID, modelID: first.id } : undefined
}
interface SelectPreferredVariantOptions {
model: ModelPreferenceModel
info?: ModelInfo | null
preferences?: Record<string, string | undefined> | null
agentModel?: ModelRef | null
configured?: ModelRef | null
}
export function selectPreferredVariant(options: SelectPreferredVariantOptions): string | undefined {
const { model, info, agentModel, configured } = options
const preferences = options.preferences ?? {}
const saved = preferences[modelPreferenceKey(model)]
const agentVariant =
agentModel && isSameModelSelection(model, refSelection(agentModel)) ? agentModel.variant : undefined
const configuredVariant =
configured && isSameModelSelection(model, refSelection(configured)) ? configured.variant : undefined
const variant = normalizeModelVariant(saved ?? agentVariant ?? configuredVariant)
return info?.variants.some((entry) => entry.id === variant) ? variant : undefined
}
interface CatalogSortEntry {
providerID?: string
providerName?: string
name?: string
cost?: Array<{ input: number }>
time?: { released: number }
free?: boolean
released?: number
}
function providerRank(providerID: string | undefined): number {
if (providerID === 'opencode-go') return 0
if (providerID === 'opencode') return 1
return 2
}
function catalogEntryFree(entry: CatalogSortEntry): boolean {
if (entry.free !== undefined) return entry.free
return entry.cost !== undefined && isModelFree({ cost: entry.cost })
}
function catalogEntryReleased(entry: CatalogSortEntry): number {
return entry.released ?? entry.time?.released ?? 0
}
export function compareCatalogModels(a: CatalogSortEntry, b: CatalogSortEntry): number {
const provider = providerRank(a.providerID) - providerRank(b.providerID)
if (provider !== 0) return provider
const providerName = (a.providerName ?? a.providerID ?? '').localeCompare(b.providerName ?? b.providerID ?? '')
if (providerName !== 0) return providerName
const free = Number(catalogEntryFree(b)) - Number(catalogEntryFree(a))
if (free !== 0) return free
const release = catalogEntryReleased(b) - catalogEntryReleased(a)
if (release !== 0) return release
return (a.name ?? '').localeCompare(b.name ?? '')
}
interface SelectEffectiveModelRefOptions {
models: ModelInfo[]
defaultModel?: ModelRef | null
candidates?: Array<ModelRef | undefined | null>
}
export function selectEffectiveModelRef(options: SelectEffectiveModelRefOptions): ModelRef | undefined {
const { models, defaultModel } = options
for (const candidate of options.candidates ?? []) {
if (candidate && findModelInfo(models, refSelection(candidate)) !== undefined) return candidate
}
if (defaultModel && findModelInfo(models, refSelection(defaultModel)) !== undefined) return defaultModel
const fallback = models.find((model) => model.enabled)
return fallback ? { providerID: fallback.providerID, id: fallback.id } : undefined
}
+12 -6
View File
@@ -22,12 +22,9 @@ export function formatOpenCodeModelRef(ref: ModelRef): string {
return ref.variant ? `${ref.providerID}/${ref.id}#${ref.variant}` : `${ref.providerID}/${ref.id}`
}
export function selectConfiguredModelRef(entries: ConfigEntry[]): ModelRef | undefined {
const model = entries.reduce<ConfigDocumentModel>(
(current, entry) => (entry.type === 'document' && entry.info.model ? entry.info.model : current),
undefined,
)
export function configModelRef(
model: string | { providerID: string; model: string; variant?: string } | undefined | null,
): ModelRef | undefined {
if (!model) return undefined
if (typeof model === 'string') return parseOpenCodeModelRef(model)
@@ -37,3 +34,12 @@ export function selectConfiguredModelRef(entries: ConfigEntry[]): ModelRef | und
...(model.variant ? { variant: model.variant } : {}),
}
}
export function selectConfiguredModelRef(entries: ConfigEntry[]): ModelRef | undefined {
const model = entries.reduce<ConfigDocumentModel>(
(current, entry) => (entry.type === 'document' && entry.info.model ? entry.info.model : current),
undefined,
)
return configModelRef(model)
}
+1
View File
@@ -1,4 +1,5 @@
export * from './jsonc'
export * from './record'
export * from './repo'
export * from './sandbox-command'
export * from './semver'
+3
View File
@@ -0,0 +1,3 @@
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}