mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
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:
1 parent
3d143568c1
commit
65b72e55ae
82 files changed
+4418
-2624
No files matched your search
+134
-164
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user