feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)

* feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.

* refactor(opencode): reload config in place and drop v1 compatibility shims

Route config/skill/AGENTS.md changes through the OpenCode location reload
API instead of a full server restart, stop auto-resuming interrupted
sessions, remove the restart coordinator and v1 MCP/version shims, and pin
support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries,
service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers.

* refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows

- extract shared semver and model-ref utilities, reuse across version checks
- share the OpenCode release download script across Docker, entrypoint, dev setup
- unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN
- scope the repo proxy location rewrite and surface ocm proxy errors
- rework frontend session projection, permission lookup, and cache invalidation

* fix(schedules): reject unavailable agents before creating a session

* feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-26 13:16:45 -04:00
1 parent 6c2ebd764b
commit dacde879d6
383 files changed
+29905 -46566

No files matched your search

+328 -3
View File
@@ -1,10 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { getProvidersWithModels } from './providers'
import { getOpenCodeConfigModel, getProviders, getProvidersWithModels, providerCredentialsApi } from './providers'
import { API_BASE_URL } from '@/config'
import { makeOpenCodeConfigFile } from '@/test/fixtures/opencode-config'
const { mockGetOpenCodeConfig, mockFetchWrapper } = vi.hoisted(() => ({
const { mockGetOpenCodeConfig, mockFetchWrapper, mockProviderList, mockModelList, mockConfigGet } = vi.hoisted(() => ({
mockGetOpenCodeConfig: vi.fn(),
mockFetchWrapper: vi.fn(),
mockProviderList: vi.fn(),
mockModelList: vi.fn(),
mockConfigGet: vi.fn(),
}))
vi.mock('./settings', () => ({
@@ -17,6 +21,15 @@ vi.mock('./fetchWrapper', () => ({
fetchWrapper: mockFetchWrapper,
}))
vi.mock('./opencodeApi', () => ({
callOpenCode: (operation: (api: unknown) => Promise<unknown>) =>
operation({
provider: { list: mockProviderList },
model: { list: mockModelList },
config: { get: mockConfigGet },
}),
}))
const config = makeOpenCodeConfigFile({
content: {
provider: {
@@ -30,10 +43,166 @@ const config = makeOpenCodeConfigFile({
},
})
function makeAnthropicModel(overrides: Record<string, unknown> = {}) {
return {
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 },
...overrides,
}
}
describe('getProviders', () => {
beforeEach(() => {
vi.clearAllMocks()
mockProviderList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
mockModelList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
})
it('maps V2 providers and models into the UI shape', async () => {
mockProviderList.mockResolvedValue({
location: { directory: '/repo' },
data: [
{ id: 'anthropic', name: 'Anthropic', activation: 'enabled', package: '@opencode/ai/providers/anthropic' },
],
})
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 },
},
{
id: 'claude-legacy',
modelID: 'claude-legacy',
providerID: 'anthropic',
name: 'Claude Legacy',
capabilities: { tools: false, input: ['text'], output: ['text'] },
variants: [],
time: { released: 0 },
cost: [],
status: 'deprecated',
enabled: true,
limit: { context: 1, output: 1 },
},
],
})
const result = await getProviders('/repo')
expect(result.connected).toEqual(['anthropic'])
expect(result.providers).toHaveLength(1)
expect(result.providers[0].models['claude-sonnet-4']).toMatchObject({
key: 'claude-sonnet-4',
id: 'claude-sonnet-4-20250514',
name: 'Claude Sonnet 4',
limit: { context: 200000, output: 64000 },
variants: { thinking: { reasoning: 'high' } },
})
expect(result.providers[0].models['claude-legacy']).toBeUndefined()
})
it('excludes disabled models and disabled providers from the picker', async () => {
mockProviderList.mockResolvedValue({
location: { directory: '/repo' },
data: [
{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' },
{ id: 'disabled-provider', name: 'Disabled', activation: 'disabled' },
],
})
mockModelList.mockResolvedValue({
location: { directory: '/repo' },
data: [
makeAnthropicModel(),
makeAnthropicModel({ id: 'claude-disabled', modelID: 'claude-disabled', enabled: false }),
makeAnthropicModel({ id: 'claude-off-provider', modelID: 'claude-off-provider', providerID: 'disabled-provider' }),
],
})
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'])
})
it('degrades to an empty result when the upstream call fails', async () => {
mockProviderList.mockRejectedValue(new Error('upstream down'))
await expect(getProviders('/repo')).resolves.toEqual({
providers: [],
connected: [],
models: [],
})
})
})
describe('getOpenCodeConfigModel', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('reads a string config model for the directory', async () => {
mockConfigGet.mockResolvedValue([{ type: 'document', info: { model: 'anthropic/claude-sonnet-4' } }])
await expect(getOpenCodeConfigModel('/repo')).resolves.toBe('anthropic/claude-sonnet-4')
expect(mockConfigGet).toHaveBeenCalledWith({ location: { directory: '/repo' } })
})
it('formats an object config model as provider/model', async () => {
mockConfigGet.mockResolvedValue([
{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-4o', variant: 'high' } } },
])
await expect(getOpenCodeConfigModel()).resolves.toBe('openai/gpt-4o')
expect(mockConfigGet).toHaveBeenCalledWith(undefined)
})
it('uses the last document that sets a model', async () => {
mockConfigGet.mockResolvedValue([
{ type: 'document', info: { model: 'anthropic/claude-sonnet-4' } },
{ type: 'document', info: { model: { providerID: 'openai', model: 'gpt-4o' } } },
{ type: 'document', info: {} },
])
await expect(getOpenCodeConfigModel('/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()
})
it('returns null when the config read fails', async () => {
mockConfigGet.mockRejectedValue(new Error('upstream down'))
await expect(getOpenCodeConfigModel('/repo')).resolves.toBeNull()
})
})
describe('getProvidersWithModels', () => {
beforeEach(() => {
vi.clearAllMocks()
mockFetchWrapper.mockResolvedValue({ all: [], connected: [], default: {} })
mockProviderList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
mockModelList.mockResolvedValue({ location: { directory: '/repo' }, data: [] })
})
it('uses the supplied config instead of re-reading it', async () => {
@@ -59,4 +228,160 @@ describe('getProvidersWithModels', () => {
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({
location: { directory: '/repo' },
data: [{ id: 'anthropic', name: 'Anthropic', activation: 'enabled' }],
})
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' }],
})
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' } } } } },
})
const providers = await getProvidersWithModels(undefined, configWithExtraModel)
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')
})
})
describe('providerCredentialsApi', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('lists provider ids with credentials from the Manager response', async () => {
mockFetchWrapper.mockResolvedValue({ providers: ['anthropic', 'openai'] })
await expect(providerCredentialsApi.list()).resolves.toEqual(['anthropic', 'openai'])
expect(mockFetchWrapper).toHaveBeenCalledWith(`${API_BASE_URL}/api/providers/credentials`)
})
it('reports credential status from the Manager response', async () => {
mockFetchWrapper.mockResolvedValue({ hasCredentials: true })
await expect(providerCredentialsApi.getStatus('anthropic')).resolves.toBe(true)
expect(mockFetchWrapper).toHaveBeenCalledWith(
`${API_BASE_URL}/api/providers/anthropic/credentials/status`
)
})
it('posts the api key to the provider credential route', async () => {
mockFetchWrapper.mockResolvedValue({ success: true })
await providerCredentialsApi.set('anthropic', 'sk-ant-test')
expect(mockFetchWrapper).toHaveBeenCalledWith(
`${API_BASE_URL}/api/providers/anthropic/credentials`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ apiKey: 'sk-ant-test' }),
}
)
})
it('posts the key method form answer alongside the api key', async () => {
mockFetchWrapper.mockResolvedValue({ success: true })
await providerCredentialsApi.set('azure', 'az-test', { resourceName: 'my-models' })
expect(mockFetchWrapper).toHaveBeenCalledWith(
`${API_BASE_URL}/api/providers/azure/credentials`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ apiKey: 'az-test', answer: { resourceName: 'my-models' } }),
}
)
})
it('deletes credentials through the provider credential route', async () => {
mockFetchWrapper.mockResolvedValue({ success: true })
await providerCredentialsApi.delete('anthropic')
expect(mockFetchWrapper).toHaveBeenCalledWith(
`${API_BASE_URL}/api/providers/anthropic/credentials`,
{ method: 'DELETE' }
)
})
})