import { describe, it, expect, beforeEach, afterEach, vi } from 'bun:test' import { Hono } from 'hono' import { Database } from 'bun:sqlite' import { readFile, writeFile } from 'fs/promises' import path from 'path' import { createInternalRoutes } from '../../src/routes/internal' import { ScheduleService } from '../../src/services/schedules' import { NotificationService } from '../../src/services/notification' import { SettingsService } from '../../src/services/settings' import { ClientError } from '@opencode-manager/shared/opencode' import type { OpenCodeClient } from '../../src/services/opencode/client' import { allMigrations } from '../../src/db/migrations' import { getOrCreateInternalToken } from '../../src/services/internal-token' import { migrate } from '../../src/db/migration-runner' import { OPENCODE_CONFIG_SEED, readOpenCodeConfigFile, writeOpenCodeConfigFile } from '../../src/services/opencode-config-file' import { createTempAssistantWorkspace } from '../helpers/assistant-workspace' import type { ScheduleWorktreeManager } from '../../src/services/schedule-worktree' describe('internal/opencode-config routes', () => { let db: Database let app: Hono let token: string let ws: Awaited> let configGetMock: ReturnType let forwardRawMock: ReturnType let locationReloadMock: ReturnType function configPath(name: string): string { return path.join(ws.workspacePath, '.config/opencode', name) } function authHeaders(): Record { return { authorization: `Bearer ${token}` } } beforeEach(async () => { ws = await createTempAssistantWorkspace() db = new Database(':memory:') migrate(db, allMigrations) configGetMock = vi.fn(() => Promise.resolve([])) forwardRawMock = vi.fn(() => Promise.resolve(new Response('{}'))) locationReloadMock = vi.fn(() => Promise.resolve()) const openCodeClient = { api: { config: { get: configGetMock }, location: { reload: locationReloadMock } }, forwardRaw: forwardRawMock, } as unknown as OpenCodeClient const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager const scheduleService = new ScheduleService(db, openCodeClient, stubWorktreeManager) const notificationService = new NotificationService(db) const settingsService = new SettingsService(db) app = new Hono() app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient)) token = getOrCreateInternalToken(db) }) afterEach(async () => { await ws.cleanup() }) it('GET /api/internal/opencode-config returns 401 without bearer token', async () => { const res = await app.request('/api/internal/opencode-config') expect(res.status).toBe(401) }) it('GET /api/internal/opencode-config returns 404 when no config file exists', async () => { const res = await app.request('/api/internal/opencode-config', { headers: authHeaders() }) expect(res.status).toBe(404) const body = await res.json() as { error: string } expect(body.error).toBe('No OpenCode config file found') }) it('GET /api/internal/opencode-config returns the merged persisted snapshot and sources', async () => { await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED, 'opencode.jsonc') const res = await app.request('/api/internal/opencode-config', { headers: authHeaders() }) expect(res.status).toBe(200) const body = await res.json() as { path: string content: Record rawContent: string isValid: boolean updatedAt: number sources: Array<{ name: string; path: string; rawContent: string }> revision: string } expect(body.path).toBe(configPath('opencode.jsonc')) expect(body.rawContent).toBe(OPENCODE_CONFIG_SEED) expect(body.content).toEqual({ $schema: 'https://opencode.ai/config.json' }) expect(body.isValid).toBe(true) expect(body.updatedAt).toBeGreaterThan(0) expect(body.sources.map((source) => source.name)).toEqual(['opencode.jsonc']) expect(body.revision).toMatch(/^[a-f0-9]{64}$/) }) it('PUT /api/internal/opencode-config writes the file and applies it through a location reload without a restart', async () => { await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED, 'opencode.jsonc') const res = await app.request('/api/internal/opencode-config', { method: 'PUT', headers: { 'content-type': 'application/json', ...authHeaders() }, body: JSON.stringify({ content: { $schema: 'https://opencode.ai/config.json', plugin: ['x'] } }), }) expect(res.status).toBe(200) const body = await res.json() as { restartRequired?: boolean; content: Record } expect(body.restartRequired).toBeUndefined() expect(body.content).toEqual({ $schema: 'https://opencode.ai/config.json', plugin: ['x'] }) expect(locationReloadMock).toHaveBeenCalledTimes(1) expect(configGetMock).not.toHaveBeenCalled() expect(forwardRawMock).not.toHaveBeenCalled() const onDisk = JSON.parse(await readFile(configPath('opencode.jsonc'), 'utf8')) as Record expect(onDisk.plugin).toEqual(['x']) }) it('PUT /api/internal/opencode-config does not report restartRequired for a comment-only edit', async () => { await writeOpenCodeConfigFile('{"theme":"dark"}', 'opencode.json') const commented = '{\n // keep this comment\n "theme": "dark"\n}\n' const res = await app.request('/api/internal/opencode-config', { method: 'PUT', headers: { 'content-type': 'application/json', ...authHeaders() }, body: JSON.stringify({ content: commented, source: 'opencode.json' }), }) expect(res.status).toBe(200) const body = await res.json() as { restartRequired?: boolean } expect(body.restartRequired).toBeUndefined() expect(locationReloadMock).not.toHaveBeenCalled() await expect(readFile(configPath('opencode.json'), 'utf8')).resolves.toBe(commented) }) it('PUT /api/internal/opencode-config forwards the requested source', async () => { await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED, 'opencode.jsonc') const submitted = '{\n "theme": "light"\n}\n' const res = await app.request('/api/internal/opencode-config', { method: 'PUT', headers: { 'content-type': 'application/json', ...authHeaders() }, body: JSON.stringify({ content: submitted, source: 'opencode.json' }), }) expect(res.status).toBe(200) await expect(readFile(configPath('opencode.json'), 'utf8')).resolves.toBe(submitted) await expect(readFile(configPath('opencode.jsonc'), 'utf8')).resolves.toBe(OPENCODE_CONFIG_SEED) }) it('PUT /api/internal/opencode-config returns 409 for a stale expectedRevision', async () => { const initial = await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED, 'opencode.jsonc') await writeFile(configPath('opencode.json'), '{"model":"a/b"}', 'utf8') const res = await app.request('/api/internal/opencode-config', { method: 'PUT', headers: { 'content-type': 'application/json', ...authHeaders() }, body: JSON.stringify({ content: { theme: 'light' }, expectedRevision: initial.revision! }), }) expect(res.status).toBe(409) const body = await res.json() as { expectedRevision: string; actualRevision: string } expect(body.expectedRevision).toBe(initial.revision!) expect(body.actualRevision).not.toBe(initial.revision!) }) it('PUT /api/internal/opencode-config returns 409 for a shadowed removal', async () => { const lower = '{"theme":"light","model":"a"}' const target = '{"model":"b"}' await writeOpenCodeConfigFile(target, 'opencode.jsonc') await writeFile(configPath('opencode.json'), lower, 'utf8') const res = await app.request('/api/internal/opencode-config', { method: 'PUT', headers: { 'content-type': 'application/json', ...authHeaders() }, body: JSON.stringify({ content: { model: 'b' } }), }) expect(res.status).toBe(409) const body = await res.json() as { error: string; paths: string[]; sources: string[] } expect(body.paths).toEqual(['theme']) expect(body.sources).toEqual(['opencode.json']) expect(body.error).toContain('Cannot remove theme') await expect(readFile(configPath('opencode.json'), 'utf8')).resolves.toBe(lower) await expect(readFile(configPath('opencode.jsonc'), 'utf8')).resolves.toBe(target) }) it('PUT /api/internal/opencode-config returns 400 for schema-invalid content', async () => { await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED, 'opencode.jsonc') const res = await app.request('/api/internal/opencode-config', { method: 'PUT', headers: { 'content-type': 'application/json', ...authHeaders() }, body: JSON.stringify({ content: { model: 5 } }), }) expect(res.status).toBe(400) }) it('PUT /api/internal/opencode-config returns 400 for an invalid JSON body', async () => { const res = await app.request('/api/internal/opencode-config', { method: 'PUT', headers: { 'content-type': 'application/json', ...authHeaders() }, body: '{', }) expect(res.status).toBe(400) const body = await res.json() as { error: string } expect(body.error).toBe('Invalid JSON') }) it('GET /api/internal/opencode-config/effective returns the running config entries without writing them back', async () => { await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED, 'opencode.jsonc') const entries = [ { type: 'document', path: configPath('opencode.jsonc'), info: { theme: 'dark' } }, { type: 'directory', path: path.join(ws.workspacePath, '.config', 'opencode') }, ] configGetMock.mockImplementation(() => Promise.resolve(entries)) const res = await app.request('/api/internal/opencode-config/effective', { headers: authHeaders() }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ entries }) expect(configGetMock).toHaveBeenCalledWith({ location: { directory: ws.workspacePath } }) const persisted = await readOpenCodeConfigFile() expect(persisted?.content).toEqual({ $schema: 'https://opencode.ai/config.json' }) }) it('GET /api/internal/opencode-config/effective returns 503 when the server is unreachable', async () => { configGetMock.mockImplementation(() => Promise.reject(new ClientError('Transport'))) const res = await app.request('/api/internal/opencode-config/effective', { headers: authHeaders() }) expect(res.status).toBe(503) const body = await res.json() as { error: string } expect(body.error).toBe('OpenCode server unavailable') }) it('GET /api/internal/opencode-config/effective returns 502 when the server rejects the request', async () => { configGetMock.mockImplementation(() => Promise.reject(new ClientError('UnexpectedStatus'))) const res = await app.request('/api/internal/opencode-config/effective', { headers: authHeaders() }) expect(res.status).toBe(502) const body = await res.json() as { error: string } expect(body.error).toBe('Failed to get effective OpenCode config') }) })