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

+228 -335
View File
@@ -10,8 +10,8 @@ vi.mock('@opencode-manager/shared/config/env', () => ({
ENV: {
SERVER: { PORT: 5003, HOST: '0.0.0.0', NODE_ENV: 'test' },
AUTH: { TRUSTED_ORIGINS: 'http://localhost:5173', SECRET: 'test-secret-for-encryption-key-32c' },
WORKSPACE: { BASE_PATH: '/test/workspace', REPOS_DIR: 'repos', CONFIG_DIR: 'config', AUTH_FILE: 'auth.json' },
OPENCODE: { PORT: 5551, HOST: '127.0.0.1', SERVER_PASSWORD: '', SERVER_USERNAME: 'opencode' },
WORKSPACE: { BASE_PATH: '/test/workspace', REPOS_DIR: 'repos', CONFIG_DIR: 'config' },
OPENCODE: { PORT: 5551, HOST: '127.0.0.1', SERVER_PASSWORD: '' },
DATABASE: { PATH: ':memory:' },
FILE_LIMITS: {
MAX_SIZE_BYTES: 1024 * 1024,
@@ -32,242 +32,14 @@ vi.mock('../../../src/utils/logger', () => ({
},
}))
import { createOpenCodeClient, FetchOpenCodeClient, UpstreamError } from '../../../src/services/opencode/client'
import { createOpenCodeClient, FetchOpenCodeClient } from '../../../src/services/opencode/client'
import { ENV } from '@opencode-manager/shared/config/env'
import { openCodeLocation } from '@opencode-manager/shared/opencode'
describe('OpenCodeClient', () => {
const baseUrl = 'http://127.0.0.1:5551'
const basicAuth = 'Basic dXNlcjpwYXNz'
describe('forward', () => {
it('should resolve basic auth dynamically for each request', async () => {
const capturedAuthHeaders: Array<string | undefined> = []
const passwords = ['first-password', 'second-password']
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
capturedAuthHeaders.push((init?.headers as Record<string, string>).Authorization)
return new Response(JSON.stringify({}), { status: 200 })
}
const client = new FetchOpenCodeClient({
baseUrl,
basicAuth: null,
passwordResolver: () => passwords.shift() ?? '',
fetchFn: fetchFn as unknown as typeof fetch,
})
await client.forward({ method: 'GET', path: '/config' })
await client.forward({ method: 'GET', path: '/config' })
expect(capturedAuthHeaders).toEqual([
`Basic ${Buffer.from('opencode:first-password').toString('base64')}`,
`Basic ${Buffer.from('opencode:second-password').toString('base64')}`,
])
})
it('should build URL from baseUrl and path, inject auth when present, and strip hop-by-hop headers', async () => {
const mockResponse = new Response(JSON.stringify({ data: 'test' }), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Content-Length': '100',
'Content-Encoding': 'gzip',
'Transfer-Encoding': 'chunked',
'Connection': 'keep-alive',
},
})
let capturedUrl: URL | undefined
let capturedInit: RequestInit | undefined
const fetchFn = async (input: URL | Request | string, init?: RequestInit) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
capturedInit = init
return mockResponse
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth, fetchFn: fetchFn as unknown as typeof fetch })
const result = await client.forward({
method: 'POST',
path: '/config',
body: 'request-body-content',
headers: { 'X-Caller': 'caller-value' },
})
expect(capturedUrl?.toString()).toBe(baseUrl + '/config')
expect(capturedInit?.method).toBe('POST')
expect(capturedInit?.body).toBe('request-body-content')
expect(capturedInit?.headers).toEqual(expect.objectContaining({
Authorization: basicAuth,
'X-Caller': 'caller-value',
}))
const resultHeaders: Record<string, string> = {}
result.headers.forEach((value, key) => {
resultHeaders[key] = value
})
expect(resultHeaders['content-length']).toBeUndefined()
expect(resultHeaders['content-encoding']).toBeUndefined()
expect(resultHeaders['transfer-encoding']).toBeUndefined()
expect(resultHeaders['connection']).toBeUndefined()
expect(resultHeaders['content-type']).toBe('application/json')
})
it('should return 502 JSON Response when fetchFn throws', async () => {
const fetchFn = async () => {
throw new Error('Network error')
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
const result = await client.forward({
method: 'GET',
path: '/config',
})
expect(result.status).toBe(502)
const body = await result.json()
expect(body).toEqual({ error: 'Proxy request failed' })
})
it('should honour directory by adding URL-encoded query param and preserve existing query string', async () => {
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
let capturedUrl: URL | undefined
const fetchFn = async (input: URL | Request | string) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
return mockResponse
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
await client.forward({
method: 'GET',
path: '/config?foo=bar',
directory: '/test/dir',
})
expect(capturedUrl?.searchParams.get('directory')).toBe('/test/dir')
expect(capturedUrl?.searchParams.get('foo')).toBe('bar')
})
it('should forward an AbortSignal to fetchFn when provided', async () => {
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
let capturedInit: RequestInit | undefined
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
capturedInit = init
return mockResponse
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
const controller = new AbortController()
await client.forward({ method: 'GET', path: '/doc', signal: controller.signal })
expect(capturedInit?.signal).toBe(controller.signal)
})
it('should return 502 Response when fetchFn rejects with AbortError', async () => {
const fetchFn = async (_input: URL | Request | string, init?: RequestInit) => {
const signal = init?.signal
if (signal?.aborted) {
throw Object.assign(new Error('Aborted'), { name: 'AbortError' })
}
return new Response(JSON.stringify({}), { status: 200 })
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
const controller = new AbortController()
controller.abort()
const result = await client.forward({ method: 'GET', path: '/doc', signal: controller.signal })
expect(result.status).toBe(502)
const body = await result.json()
expect(body).toEqual({ error: 'Proxy request failed' })
})
})
describe('createOpenCodeClient', () => {
it('uses loopback connect host when OPENCODE_HOST binds externally', async () => {
const originalFetch = globalThis.fetch
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '0.0.0.0', configurable: true, writable: true })
let capturedUrl: URL | undefined
const fetchFn = async (input: URL | Request | string) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
return new Response(JSON.stringify({}), { status: 200 })
}
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
try {
const client = createOpenCodeClient('testpassword')
await client.forward({ method: 'GET', path: '/doc' })
expect(capturedUrl?.origin).toBe('http://127.0.0.1:5551')
} finally {
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '127.0.0.1', configurable: true, writable: true })
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
})
it('honours an explicit host override instead of OPENCODE_HOST', async () => {
const originalFetch = globalThis.fetch
const originalHost = ENV.OPENCODE.HOST
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '192.168.1.10', configurable: true, writable: true })
let capturedUrl: URL | undefined
const fetchFn = async (input: URL | Request | string) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
return new Response(JSON.stringify({}), { status: 200 })
}
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
try {
const client = createOpenCodeClient('testpassword', '127.0.0.1')
await client.forward({ method: 'GET', path: '/doc' })
expect(capturedUrl?.origin).toBe('http://127.0.0.1:5551')
} finally {
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: originalHost, configurable: true, writable: true })
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
})
it('brackets an IPv6 loopback host in the request URL', async () => {
const originalFetch = globalThis.fetch
let capturedUrl: URL | undefined
const fetchFn = async (input: URL | Request | string) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
return new Response(JSON.stringify({}), { status: 200 })
}
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
try {
const client = createOpenCodeClient('testpassword', '::1')
await client.forward({ method: 'GET', path: '/doc' })
expect(capturedUrl?.origin).toBe('http://[::1]:5551')
} finally {
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
})
it('resolves a lazy host override on every request', async () => {
const originalFetch = globalThis.fetch
const hosts: string[] = []
let currentHost = '192.168.1.10'
const fetchFn = async (input: URL | Request | string) => {
hosts.push(input instanceof URL ? input.hostname : new URL(input.toString()).hostname)
return new Response(JSON.stringify({}), { status: 200 })
}
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
try {
const client = createOpenCodeClient('testpassword', () => currentHost)
await client.forward({ method: 'GET', path: '/doc' })
currentHost = '127.0.0.1'
await client.forward({ method: 'GET', path: '/doc' })
expect(hosts).toEqual(['192.168.1.10', '127.0.0.1'])
} finally {
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
})
})
describe('forwardRaw', () => {
it('should strip /api/opencode prefix from path, preserve search string, and strip host/connection/authorization headers', async () => {
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
@@ -301,6 +73,22 @@ describe('OpenCodeClient', () => {
expect((capturedInit?.headers as Record<string, string>)['host']).toBeUndefined()
expect((capturedInit?.headers as Record<string, string>)['connection']).toBeUndefined()
expect((capturedInit?.headers as Record<string, string>)['authorization']).toBeUndefined()
expect((capturedInit?.headers as Record<string, string>)['x-opencode-directory']).toBe(encodeURIComponent('/test/workspace'))
})
it('keeps a caller-supplied x-opencode-directory header', async () => {
let capturedInit: RequestInit | undefined
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
capturedInit = init
return new Response(JSON.stringify({}), { status: 200 })
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
await client.forwardRaw(new Request('http://localhost:5003/api/opencode/api/config', {
headers: { 'X-OpenCode-Directory': '%2Frepo%2Fb' },
}))
expect((capturedInit?.headers as Record<string, string>)['x-opencode-directory']).toBe('%2Frepo%2Fb')
})
it('should read body for POST but not for GET/HEAD', async () => {
@@ -335,132 +123,237 @@ describe('OpenCodeClient', () => {
expect(capturedBodies[1]).toBeUndefined()
expect(capturedBodies[2]).toBeUndefined()
})
})
describe('getJson', () => {
it('should return parsed body on 200', async () => {
const mockData = { config: 'test' }
const mockResponse = new Response(JSON.stringify(mockData), { status: 200 })
const fetchFn = async () => mockResponse
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
it('should resolve basic auth dynamically for each request', async () => {
const capturedAuthHeaders: Array<string | undefined> = []
const passwords = ['first-password', 'second-password']
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
capturedAuthHeaders.push((init?.headers as Record<string, string>).Authorization)
return new Response(JSON.stringify({}), { status: 200 })
}
const client = new FetchOpenCodeClient({
baseUrl,
basicAuth: null,
passwordResolver: () => passwords.shift() ?? '',
fetchFn: fetchFn as unknown as typeof fetch,
})
const result = await client.getJson('/config')
expect(result).toEqual(mockData)
await client.forwardRaw(new Request('http://localhost:5003/api/opencode/config'))
await client.forwardRaw(new Request('http://localhost:5003/api/opencode/config'))
expect(capturedAuthHeaders).toEqual([
`Basic ${Buffer.from('opencode:first-password').toString('base64')}`,
`Basic ${Buffer.from('opencode:second-password').toString('base64')}`,
])
})
it('should throw UpstreamError on 404 with status and bodyText', async () => {
const mockResponse = new Response('Not found', { status: 404 })
const fetchFn = async () => {
it('should inject auth when present and strip hop-by-hop response headers', async () => {
const mockResponse = new Response(JSON.stringify({ data: 'test' }), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Content-Length': '100',
'Content-Encoding': 'gzip',
'Transfer-Encoding': 'chunked',
'Connection': 'keep-alive',
},
})
let capturedUrl: URL | undefined
let capturedInit: RequestInit | undefined
const fetchFn = async (input: URL | Request | string, init?: RequestInit) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
capturedInit = init
return mockResponse
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth, fetchFn: fetchFn as unknown as typeof fetch })
const result = await client.forwardRaw(new Request('http://localhost:5003/api/opencode/config?foo=bar', {
method: 'POST',
body: 'request-body-content',
headers: { 'X-Caller': 'caller-value' },
}))
expect(capturedUrl?.toString()).toBe(baseUrl + '/config?foo=bar')
expect(capturedInit?.method).toBe('POST')
expect(capturedInit?.body).toBe('request-body-content')
expect(capturedInit?.headers).toEqual(expect.objectContaining({
Authorization: basicAuth,
'x-caller': 'caller-value',
}))
const resultHeaders: Record<string, string> = {}
result.headers.forEach((value, key) => {
resultHeaders[key] = value
})
expect(resultHeaders['content-length']).toBeUndefined()
expect(resultHeaders['content-encoding']).toBeUndefined()
expect(resultHeaders['transfer-encoding']).toBeUndefined()
expect(resultHeaders['connection']).toBeUndefined()
expect(resultHeaders['content-type']).toBe('application/json')
})
it('should return a 502 JSON Response when fetchFn throws', async () => {
const fetchFn = async () => {
throw new Error('Network error')
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
let caughtErr: UpstreamError | undefined
const result = await client.forwardRaw(new Request('http://localhost:5003/api/opencode/config'))
expect(result.status).toBe(502)
const body = await result.json()
expect(body).toEqual({ error: 'Proxy request failed' })
})
})
describe('api', () => {
const serverInfo = { version: '2.0.15', pid: 1234, urls: ['http://127.0.0.1:5551'], paths: { tmp: '/tmp' } }
it('probes GET /api/info with the resolver password on every call', async () => {
const capturedUrls: string[] = []
const capturedAuthHeaders: Array<string | undefined> = []
const passwords = ['first-password', 'second-password']
const fetchFn = async (input: URL | Request | string, init?: RequestInit) => {
capturedUrls.push(input instanceof URL ? input.toString() : input.toString())
capturedAuthHeaders.push(new Headers(init?.headers).get('authorization') ?? undefined)
return new Response(JSON.stringify(serverInfo), { status: 200, headers: { 'Content-Type': 'application/json' } })
}
const client = new FetchOpenCodeClient({
baseUrl,
basicAuth: null,
passwordResolver: () => passwords.shift() ?? '',
fetchFn: fetchFn as unknown as typeof fetch,
})
await client.api.server.info()
await client.api.server.info()
expect(capturedUrls).toEqual([`${baseUrl}/api/info`, `${baseUrl}/api/info`])
expect(capturedAuthHeaders).toEqual([
`Basic ${Buffer.from('opencode:first-password').toString('base64')}`,
`Basic ${Buffer.from('opencode:second-password').toString('base64')}`,
])
})
it('scopes location-less requests to the workspace and leaves explicit locations to the query', async () => {
const captured: Array<{ url: string; directory: string | null }> = []
const fetchFn = async (input: URL | Request | string, init?: RequestInit) => {
captured.push({ url: input.toString(), directory: new Headers(init?.headers).get('x-opencode-directory') })
return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'Content-Type': 'application/json' } })
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
await client.api.integration.list().catch(() => undefined)
await client.api.skill.list(openCodeLocation('/repo/a')).catch(() => undefined)
expect(captured[0]).toEqual({ url: `${baseUrl}/api/integration`, directory: encodeURIComponent('/test/workspace') })
expect(captured[1]?.url).toBe(`${baseUrl}/api/skill?location%5Bdirectory%5D=%2Frepo%2Fa`)
})
it('fails the info probe when the upstream answers 401', async () => {
const fetchFn = async () => new Response(JSON.stringify({ error: 'unauthorized' }), { status: 401 })
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
await expect(client.api.server.info()).rejects.toThrow()
})
it('fails the info probe when the upstream answers HTML', async () => {
const fetchFn = async () => new Response('<!doctype html><html></html>', {
status: 200,
headers: { 'Content-Type': 'text/html' },
})
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
await expect(client.api.server.info()).rejects.toThrow()
})
})
describe('createOpenCodeClient', () => {
it('uses loopback connect host when OPENCODE_HOST binds externally', async () => {
const originalFetch = globalThis.fetch
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '0.0.0.0', configurable: true, writable: true })
let capturedUrl: URL | undefined
const fetchFn = async (input: URL | Request | string) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
return new Response(JSON.stringify({}), { status: 200 })
}
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
try {
await client.getJson('/not-found')
} catch (err) {
caughtErr = err as UpstreamError
const client = createOpenCodeClient('testpassword')
await client.forwardRaw(new Request('http://localhost:5003/api/opencode/doc'))
expect(capturedUrl?.origin).toBe('http://127.0.0.1:5551')
} finally {
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '127.0.0.1', configurable: true, writable: true })
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
expect(caughtErr).toBeDefined()
expect(caughtErr?.status).toBe(404)
expect(caughtErr?.bodyText).toBe('Not found')
})
})
describe('postJson', () => {
it('should post JSON with Content-Type header and merge caller headers', async () => {
const mockResponse = new Response(JSON.stringify({ success: true }), { status: 200 })
let capturedInit: RequestInit | undefined
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
capturedInit = init
return mockResponse
it('honours an explicit host override instead of OPENCODE_HOST', async () => {
const originalFetch = globalThis.fetch
const originalHost = ENV.OPENCODE.HOST
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: '192.168.1.10', configurable: true, writable: true })
let capturedUrl: URL | undefined
const fetchFn = async (input: URL | Request | string) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
return new Response(JSON.stringify({}), { status: 200 })
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
await client.postJson('/test', { data: 'test' }, {
headers: { 'X-Custom': 'value' },
})
try {
const client = createOpenCodeClient('testpassword', '127.0.0.1')
await client.forwardRaw(new Request('http://localhost:5003/api/opencode/doc'))
expect(capturedInit?.headers).toEqual({
'Content-Type': 'application/json',
'X-Custom': 'value',
})
expect(capturedInit?.body).toBe(JSON.stringify({ data: 'test' }))
})
it('should throw UpstreamError on 500', async () => {
const mockResponse = new Response('Internal error', { status: 500 })
const fetchFn = async () => mockResponse
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
await expect(client.postJson('/test', {})).rejects.toThrow(UpstreamError)
})
})
describe('setProviderAuth', () => {
it('should return true on 200', async () => {
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
const fetchFn = async () => mockResponse
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
const result = await client.setProviderAuth('test-provider', 'api-key')
expect(result).toBe(true)
})
it('should return false on 401', async () => {
const mockResponse = new Response(JSON.stringify({}), { status: 401 })
const fetchFn = async () => mockResponse
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
const result = await client.setProviderAuth('test-provider', 'api-key')
expect(result).toBe(false)
})
it('should return false when fetchFn throws', async () => {
const fetchFn = async () => {
throw new Error('Network error')
expect(capturedUrl?.origin).toBe('http://127.0.0.1:5551')
} finally {
Object.defineProperty(ENV.OPENCODE, 'HOST', { value: originalHost, configurable: true, writable: true })
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
const result = await client.setProviderAuth('test-provider', 'api-key')
expect(result).toBe(false)
})
})
describe('deleteProviderAuth', () => {
it('should return true on 200 with DELETE method and no body', async () => {
const mockResponse = new Response(JSON.stringify({}), { status: 200 })
let capturedInit: RequestInit | undefined
const fetchFn = async (_: URL | Request | string, init?: RequestInit) => {
capturedInit = init
return mockResponse
it('brackets an IPv6 loopback host in the request URL', async () => {
const originalFetch = globalThis.fetch
let capturedUrl: URL | undefined
const fetchFn = async (input: URL | Request | string) => {
capturedUrl = input instanceof URL ? input : new URL(input.toString())
return new Response(JSON.stringify({}), { status: 200 })
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
const result = await client.deleteProviderAuth('test-provider')
expect(result).toBe(true)
expect(capturedInit?.method).toBe('DELETE')
expect(capturedInit?.body).toBeUndefined()
})
try {
const client = createOpenCodeClient('testpassword', '::1')
await client.forwardRaw(new Request('http://localhost:5003/api/opencode/doc'))
it('should return false on 401', async () => {
const mockResponse = new Response(JSON.stringify({}), { status: 401 })
const fetchFn = async () => mockResponse
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
const result = await client.deleteProviderAuth('test-provider')
expect(result).toBe(false)
})
it('should return false when fetchFn throws', async () => {
const fetchFn = async () => {
throw new Error('Network error')
expect(capturedUrl?.origin).toBe('http://[::1]:5551')
} finally {
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
const client = new FetchOpenCodeClient({ baseUrl, basicAuth: '', fetchFn: fetchFn as unknown as typeof fetch })
})
const result = await client.deleteProviderAuth('test-provider')
expect(result).toBe(false)
it('resolves a lazy host override on every request', async () => {
const originalFetch = globalThis.fetch
const hosts: string[] = []
let currentHost = '192.168.1.10'
const fetchFn = async (input: URL | Request | string) => {
hosts.push(input instanceof URL ? input.hostname : new URL(input.toString()).hostname)
return new Response(JSON.stringify({}), { status: 200 })
}
Object.defineProperty(globalThis, 'fetch', { value: fetchFn, configurable: true, writable: true })
try {
const client = createOpenCodeClient('testpassword', () => currentHost)
await client.forwardRaw(new Request('http://localhost:5003/api/opencode/doc'))
currentHost = '127.0.0.1'
await client.forwardRaw(new Request('http://localhost:5003/api/opencode/doc'))
expect(hosts).toEqual(['192.168.1.10', '127.0.0.1'])
} finally {
Object.defineProperty(globalThis, 'fetch', { value: originalFetch, configurable: true, writable: true })
}
})
})
})
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
INTEGRATION_READY_POLL_INTERVAL_MS,
INTEGRATION_READY_TIMEOUT_MS,
runWhenIntegrationReady,
} from '../../../src/services/opencode/integration-ready'
import { createStubOpenCodeClient } from '../../helpers/stub-opencode-client'
const TARGET = { integrationID: 'anthropic', location: { directory: '/tmp/repo' } }
function taggedError(tag: string, message: string): Error {
return Object.assign(new Error(message), { _tag: tag })
}
function notFound(): Error {
return taggedError('IntegrationNotFoundError', 'Integration not found: anthropic')
}
describe('runWhenIntegrationReady', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('returns the first result without polling', async () => {
const { api } = createStubOpenCodeClient()
const action = vi.fn(async () => 'connected')
await expect(runWhenIntegrationReady(api, TARGET, action)).resolves.toBe('connected')
expect(action).toHaveBeenCalledTimes(1)
expect(vi.mocked(api.integration.get)).not.toHaveBeenCalled()
})
it('waits for a loading integration and retries once', async () => {
const { api } = createStubOpenCodeClient()
const get = vi.mocked(api.integration.get)
get.mockRejectedValueOnce(notFound()).mockRejectedValueOnce(notFound())
const action = vi.fn<() => Promise<string>>()
.mockRejectedValueOnce(notFound())
.mockResolvedValueOnce('connected')
const result = runWhenIntegrationReady(api, TARGET, action)
await vi.advanceTimersByTimeAsync(INTEGRATION_READY_POLL_INTERVAL_MS * 3)
await expect(result).resolves.toBe('connected')
expect(get).toHaveBeenCalledTimes(3)
expect(get).toHaveBeenCalledWith(TARGET)
expect(action).toHaveBeenCalledTimes(2)
})
it('returns the original error when the integration never appears', async () => {
const { api } = createStubOpenCodeClient()
const get = vi.mocked(api.integration.get)
get.mockRejectedValue(notFound())
const original = notFound()
const action = vi.fn<() => Promise<string>>().mockRejectedValue(original)
const result = runWhenIntegrationReady(api, TARGET, action)
const assertion = expect(result).rejects.toBe(original)
await vi.advanceTimersByTimeAsync(INTEGRATION_READY_TIMEOUT_MS + INTEGRATION_READY_POLL_INTERVAL_MS)
await assertion
expect(action).toHaveBeenCalledTimes(1)
expect(get.mock.calls.length).toBeGreaterThanOrEqual(INTEGRATION_READY_TIMEOUT_MS / INTEGRATION_READY_POLL_INTERVAL_MS - 1)
expect(get.mock.calls.length).toBeLessThanOrEqual(INTEGRATION_READY_TIMEOUT_MS / INTEGRATION_READY_POLL_INTERVAL_MS)
})
it('stops polling and returns the original error when the lookup fails differently', async () => {
const { api } = createStubOpenCodeClient()
const get = vi.mocked(api.integration.get)
get.mockRejectedValue(taggedError('ServiceUnavailableError', 'down'))
const original = notFound()
const action = vi.fn<() => Promise<string>>().mockRejectedValue(original)
const result = runWhenIntegrationReady(api, TARGET, action)
const assertion = expect(result).rejects.toBe(original)
await vi.advanceTimersByTimeAsync(INTEGRATION_READY_POLL_INTERVAL_MS)
await assertion
expect(get).toHaveBeenCalledTimes(1)
expect(action).toHaveBeenCalledTimes(1)
})
it('does not retry other errors', async () => {
const { api } = createStubOpenCodeClient()
const original = taggedError('InvalidRequestError', 'Missing required form field: account')
const action = vi.fn<() => Promise<string>>().mockRejectedValue(original)
await expect(runWhenIntegrationReady(api, TARGET, action)).rejects.toBe(original)
expect(action).toHaveBeenCalledTimes(1)
expect(vi.mocked(api.integration.get)).not.toHaveBeenCalled()
})
})
@@ -1,6 +1,6 @@
import { describe, it, expect, afterEach } from 'vitest'
import { ENV } from '@opencode-manager/shared/config/env'
import { getOpenCodeUpstreamBaseUrl } from '../../../src/services/opencode/upstream'
import { ENV, getWorkspacePath } from '@opencode-manager/shared/config/env'
import { getOpenCodeUpstreamBaseUrl, withDefaultOpenCodeDirectory } from '../../../src/services/opencode/upstream'
const originalHost = ENV.OPENCODE.HOST
@@ -44,3 +44,17 @@ describe('getOpenCodeUpstreamBaseUrl', () => {
expect(getOpenCodeUpstreamBaseUrl(() => '10.0.0.5')).toBe(`http://10.0.0.5:${ENV.OPENCODE.PORT}`)
})
})
describe('withDefaultOpenCodeDirectory', () => {
it('scopes a request without a directory header to the workspace', () => {
expect(withDefaultOpenCodeDirectory({ accept: 'application/json' })).toEqual({
accept: 'application/json',
'x-opencode-directory': encodeURIComponent(getWorkspacePath()),
})
})
it('keeps a caller-supplied directory header regardless of its case', () => {
const headers = { 'X-OpenCode-Directory': '%2Frepo' }
expect(withDefaultOpenCodeDirectory(headers)).toBe(headers)
})
})