mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
refactor(config): make on-disk opencode.json the single source of truth (#354)
* refactor(config): make on-disk opencode.json the single source of truth Make <workspace>/.config/opencode/opencode.json the only store for the active OpenCode configuration. One owner (opencode-config-file.ts) reads, validates, writes, archives, and seeds the file; one owner (opencode-config-apply.ts) decides how an edit is applied: restart pending, or a live patch with recovery. Settings routes, the internal assistant API, the health-watch supervisor, boot, and host import all go through them, so an edit that lands on the file without going through the database is visible immediately instead of at the next Manager boot. Remove the named-config profiles. Migration 019 archives every opencode_configs row to .config/opencode-configs-archive/<name>.json, restores the default row to opencode.json when no file exists, then drops the table, its indexes, and repos.opencode_config_name. The /opencode-configs* and config/switch routes and the CreateConfigDialog/SwitchConfigDialog dialogs are gone, and the ocm tool gains GET/PUT /opencode-config backed by the same apply owner. Harden the write path: serialize and atomically write config updates while preserving the file mode, keep withFileLock usable after a rejection, route reloadConfig's cleaned-config write through the file owner, stop boot from rewriting an existing valid config when importing state, prune the health-watch directory to its newest 20 entries, resolve archive paths with realpath, and share one frontend config query across dialogs. * fix(mirror): canonicalize worktree paths before branch ownership check * refactor(config): unify opencode config apply and rollback paths - share one config route factory between public and internal mounts - capture last-known-good before every config write and restore via one helper - stop auto-restarting on save; flag restart-required fields and live-patch the rest - add CONFIG_PATCH_TIMEOUT_MS for config patch requests - extract canonicalPath helpers, health-watch artifact writer, and useProvidersWithModels hook * refactor(model-state): use OpenCode state file as model state source of truth
This commit is contained in:
1 parent
7a3c5229df
commit
295d24ced7
116 files changed
+10291
-4208
No files matched your search
@@ -1,11 +1,21 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { ensureOpenCodeModelStateTable } from '../model-state'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 12,
|
||||
name: 'opencode-model-state',
|
||||
up(db) {
|
||||
ensureOpenCodeModelStateTable(db)
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS opencode_model_state (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL DEFAULT 'default',
|
||||
recent TEXT NOT NULL DEFAULT '[]',
|
||||
favorite TEXT NOT NULL DEFAULT '[]',
|
||||
variant TEXT NOT NULL DEFAULT '{}',
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(user_id)
|
||||
)
|
||||
`)
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_opencode_model_state_user ON opencode_model_state(user_id)')
|
||||
},
|
||||
down(db) {
|
||||
db.run('DROP TABLE IF EXISTS opencode_model_state')
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { getOpenCodeConfigFilePath, getOpenCodeConfigHome } from '@opencode-manager/shared/config/env'
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
function firstExistingConfigSourcePath(): string | null {
|
||||
const candidates = [
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH,
|
||||
path.join(os.homedir(), '.config', 'opencode', 'opencode.json'),
|
||||
]
|
||||
.filter((value): value is string => Boolean(value))
|
||||
.map((value) => path.resolve(value))
|
||||
|
||||
return Array.from(new Set(candidates)).find((candidate) => existsSync(candidate)) ?? null
|
||||
}
|
||||
|
||||
function writeArchivedConfig(archiveDir: string, configName: string, content: string): void {
|
||||
const base = configName.replace(/[^A-Za-z0-9._-]/g, '_')
|
||||
try {
|
||||
writeFileSync(path.join(archiveDir, `${base}.json`), content, { flag: 'wx' })
|
||||
return
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const suffix = `${Date.now()}-${randomBytes(4).toString('hex')}`
|
||||
writeFileSync(path.join(archiveDir, `${base}-${suffix}.json`), content, { flag: 'wx' })
|
||||
}
|
||||
|
||||
function archiveConfigs(rows: Array<{ config_name: string; config_content: string }>): void {
|
||||
const archiveDir = path.join(getOpenCodeConfigHome(), 'opencode-configs-archive')
|
||||
mkdirSync(archiveDir, { recursive: true })
|
||||
for (const row of rows) {
|
||||
try {
|
||||
writeArchivedConfig(archiveDir, row.config_name, row.config_content)
|
||||
} catch (error) {
|
||||
logger.warn('Failed to archive an opencode config before dropping the table', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 19,
|
||||
name: 'drop-opencode-configs',
|
||||
|
||||
up(db) {
|
||||
const rows = db.prepare('SELECT config_name, config_content, is_default FROM opencode_configs').all() as Array<{ config_name: string; config_content: string; is_default: number | null }>
|
||||
|
||||
try {
|
||||
archiveConfigs(rows)
|
||||
} catch (error) {
|
||||
logger.warn('Failed to archive opencode configs before dropping the table', error)
|
||||
}
|
||||
|
||||
const defaultRow = rows.find(row => row.is_default)
|
||||
if (defaultRow) {
|
||||
try {
|
||||
const configFilePath = getOpenCodeConfigFilePath()
|
||||
if (!existsSync(configFilePath) && !firstExistingConfigSourcePath()) {
|
||||
mkdirSync(path.dirname(configFilePath), { recursive: true })
|
||||
writeFileSync(configFilePath, defaultRow.config_content)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to restore the default opencode config file', error)
|
||||
}
|
||||
}
|
||||
|
||||
db.run('DROP INDEX IF EXISTS idx_opencode_default')
|
||||
db.run('DROP INDEX IF EXISTS idx_opencode_user_id')
|
||||
db.run('DROP TABLE IF EXISTS opencode_configs')
|
||||
db.run('ALTER TABLE repos DROP COLUMN opencode_config_name')
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS opencode_configs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL DEFAULT 'default',
|
||||
config_name TEXT NOT NULL,
|
||||
config_content TEXT NOT NULL,
|
||||
is_default BOOLEAN DEFAULT FALSE,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(user_id, config_name)
|
||||
)
|
||||
`)
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_opencode_user_id ON opencode_configs(user_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_opencode_default ON opencode_configs(user_id, is_default)')
|
||||
db.run('ALTER TABLE repos ADD COLUMN opencode_config_name TEXT')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -0,0 +1,85 @@
|
||||
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { getOpenCodeModelStatePath } from '@opencode-manager/shared/config/env'
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
interface ModelStateRow {
|
||||
recent: string
|
||||
favorite: string
|
||||
variant: string
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
function readDefaultRow(db: Parameters<Migration['up']>[0]): ModelStateRow | undefined {
|
||||
try {
|
||||
return db.prepare("SELECT recent, favorite, variant, updated_at FROM opencode_model_state WHERE user_id = 'default'").get() as ModelStateRow | undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function parseJson<T>(value: string, fallback: T): T {
|
||||
try {
|
||||
return JSON.parse(value) as T
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
function restoreModelStateFile(row: ModelStateRow): void {
|
||||
const filePath = getOpenCodeModelStatePath()
|
||||
const fileExists = existsSync(filePath)
|
||||
|
||||
if (fileExists && statSync(filePath).mtimeMs >= row.updated_at) {
|
||||
return
|
||||
}
|
||||
|
||||
const existing = fileExists
|
||||
? parseJson<Record<string, unknown>>(readFileSync(filePath, 'utf8'), {})
|
||||
: {}
|
||||
|
||||
mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
writeFileSync(filePath, JSON.stringify({
|
||||
...existing,
|
||||
recent: parseJson<unknown[]>(row.recent, []),
|
||||
favorite: parseJson<unknown[]>(row.favorite, []),
|
||||
variant: parseJson<Record<string, unknown>>(row.variant, {}),
|
||||
}, null, 2))
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 20,
|
||||
name: 'drop-opencode-model-state',
|
||||
|
||||
up(db) {
|
||||
const row = readDefaultRow(db)
|
||||
if (row) {
|
||||
try {
|
||||
restoreModelStateFile(row)
|
||||
} catch (error) {
|
||||
logger.warn('Failed to restore the OpenCode model state file', error)
|
||||
}
|
||||
}
|
||||
|
||||
db.run('DROP INDEX IF EXISTS idx_opencode_model_state_user')
|
||||
db.run('DROP TABLE IF EXISTS opencode_model_state')
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS opencode_model_state (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL DEFAULT 'default',
|
||||
recent TEXT NOT NULL DEFAULT '[]',
|
||||
favorite TEXT NOT NULL DEFAULT '[]',
|
||||
variant TEXT NOT NULL DEFAULT '{}',
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(user_id)
|
||||
)
|
||||
`)
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_opencode_model_state_user ON opencode_model_state(user_id)')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -17,6 +17,8 @@ import migration015 from './015-schedule-worktree-isolation'
|
||||
import migration016 from './016-schedule-permission-config'
|
||||
import migration017 from './017-schedule-run-workspace-id'
|
||||
import migration018 from './018-session-pins'
|
||||
import migration019 from './019-drop-opencode-configs'
|
||||
import migration020 from './020-drop-opencode-model-state'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -37,4 +39,6 @@ export const allMigrations: Migration[] = [
|
||||
migration016,
|
||||
migration017,
|
||||
migration018,
|
||||
migration019,
|
||||
migration020,
|
||||
]
|
||||
@@ -1,140 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from './migration-runner'
|
||||
import { allMigrations } from './migrations'
|
||||
import {
|
||||
getOpenCodeModelState,
|
||||
addRecentOpenCodeModel,
|
||||
toggleFavoriteOpenCodeModel,
|
||||
setOpenCodeVariant,
|
||||
MAX_RECENT_MODELS,
|
||||
} from './model-state'
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
describe('model-state', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
})
|
||||
|
||||
describe('getOpenCodeModelState', () => {
|
||||
it('returns empty defaults when no row exists', () => {
|
||||
const state = getOpenCodeModelState(db)
|
||||
expect(state).toEqual({ recent: [], favorite: [], variant: {} })
|
||||
})
|
||||
|
||||
it('creates the model state table when an existing database is missing it', () => {
|
||||
db.run('DROP TABLE opencode_model_state')
|
||||
|
||||
const state = getOpenCodeModelState(db)
|
||||
const table = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'opencode_model_state'").get()
|
||||
|
||||
expect(state).toEqual({ recent: [], favorite: [], variant: {} })
|
||||
expect(table).toBeTruthy()
|
||||
})
|
||||
|
||||
it('returns defaults with explicit userId when no row exists', () => {
|
||||
const state = getOpenCodeModelState(db, 'user123')
|
||||
expect(state).toEqual({ recent: [], favorite: [], variant: {} })
|
||||
})
|
||||
})
|
||||
|
||||
describe('addRecentOpenCodeModel', () => {
|
||||
it('inserts new state and returns the model in recent[0]', () => {
|
||||
const model = { providerID: 'anthropic', modelID: 'claude-sonnet-4-20250514' }
|
||||
const state = addRecentOpenCodeModel(db, model)
|
||||
expect(state.recent).toHaveLength(1)
|
||||
expect(state.recent[0]).toEqual(model)
|
||||
})
|
||||
|
||||
it('deduplicates re-selections (same model added twice → length 1, model at index 0)', () => {
|
||||
const model = { providerID: 'openai', modelID: 'gpt-4o' }
|
||||
addRecentOpenCodeModel(db, model)
|
||||
const state = addRecentOpenCodeModel(db, model)
|
||||
expect(state.recent).toHaveLength(1)
|
||||
expect(state.recent[0]).toEqual(model)
|
||||
})
|
||||
|
||||
it('caps at MAX_RECENT_MODELS (insert 12 distinct, expect 10)', () => {
|
||||
for (let i = 0; i < 12; i++) {
|
||||
addRecentOpenCodeModel(db, { providerID: `provider-${i}`, modelID: `model-${i}` })
|
||||
}
|
||||
const state = getOpenCodeModelState(db)
|
||||
expect(state.recent).toHaveLength(MAX_RECENT_MODELS)
|
||||
expect(state.recent[0]).toEqual({ providerID: 'provider-11', modelID: 'model-11' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('toggleFavoriteOpenCodeModel', () => {
|
||||
it('adds when missing', () => {
|
||||
const model = { providerID: 'anthropic', modelID: 'claude' }
|
||||
const state = toggleFavoriteOpenCodeModel(db, model)
|
||||
expect(state.favorite).toHaveLength(1)
|
||||
expect(state.favorite[0]).toEqual(model)
|
||||
})
|
||||
|
||||
it('removes when present', () => {
|
||||
const model = { providerID: 'openai', modelID: 'gpt-4' }
|
||||
toggleFavoriteOpenCodeModel(db, model)
|
||||
const state = toggleFavoriteOpenCodeModel(db, model)
|
||||
expect(state.favorite).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('setOpenCodeVariant', () => {
|
||||
it('adds variant entry', () => {
|
||||
const state = setOpenCodeVariant(db, 'key1', 'variant1')
|
||||
expect(state.variant.key1).toBe('variant1')
|
||||
})
|
||||
|
||||
it('updates variant entry', () => {
|
||||
setOpenCodeVariant(db, 'key1', 'variant1')
|
||||
const state = setOpenCodeVariant(db, 'key1', 'variant2')
|
||||
expect(state.variant.key1).toBe('variant2')
|
||||
})
|
||||
|
||||
it('deletes variant when undefined', () => {
|
||||
setOpenCodeVariant(db, 'key1', 'variant1')
|
||||
const state = setOpenCodeVariant(db, 'key1', undefined)
|
||||
expect(state.variant.key1).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
it('corrupt JSON in recent column → getOpenCodeModelState returns [] for recent, preserves valid favorite', () => {
|
||||
const now = Date.now()
|
||||
db.prepare(`
|
||||
INSERT INTO opencode_model_state(user_id, recent, favorite, variant, updated_at)
|
||||
VALUES(?,?,?,?,?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET recent=excluded.recent, favorite=excluded.favorite, variant=excluded.variant, updated_at=excluded.updated_at
|
||||
`).run('default', '{ invalid json }', JSON.stringify([{ providerID: 'test', modelID: 'test' }]), '{}', now)
|
||||
|
||||
const state = getOpenCodeModelState(db)
|
||||
expect(state.recent).toEqual([])
|
||||
expect(state.favorite).toHaveLength(1)
|
||||
expect(state.favorite[0]).toEqual({ providerID: 'test', modelID: 'test' })
|
||||
})
|
||||
|
||||
it('50 concurrent addRecentOpenCodeModel calls → final recent.length <= MAX_RECENT_MODELS, no exceptions, all entries unique', async () => {
|
||||
const db = createTestDb()
|
||||
const numOps = 50
|
||||
|
||||
const operations = Array.from({ length: numOps }, (_, i) =>
|
||||
addRecentOpenCodeModel(db, { providerID: `provider-${i}`, modelID: `model-${i}` }),
|
||||
)
|
||||
|
||||
await Promise.all(operations)
|
||||
const finalState = getOpenCodeModelState(db)
|
||||
|
||||
expect(finalState.recent.length).toBeLessThanOrEqual(MAX_RECENT_MODELS)
|
||||
expect(finalState.recent.length).toBeGreaterThan(0)
|
||||
|
||||
const uniqueKeys = new Set(finalState.recent.map((m) => `${m.providerID}/${m.modelID}`))
|
||||
expect(uniqueKeys.size).toBe(finalState.recent.length)
|
||||
})
|
||||
})
|
||||
@@ -1,165 +0,0 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
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
|
||||
|
||||
const EMPTY_STATE: OpenCodeModelStateRecord = { recent: [], favorite: [], variant: {} }
|
||||
|
||||
export function ensureOpenCodeModelStateTable(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS opencode_model_state (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL DEFAULT 'default',
|
||||
recent TEXT NOT NULL DEFAULT '[]',
|
||||
favorite TEXT NOT NULL DEFAULT '[]',
|
||||
variant TEXT NOT NULL DEFAULT '{}',
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(user_id)
|
||||
)
|
||||
`)
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_opencode_model_state_user ON opencode_model_state(user_id)')
|
||||
}
|
||||
|
||||
function parseJsonSafe<T>(json: string, fallback: T): T {
|
||||
try {
|
||||
return JSON.parse(json) as T
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to parse JSON: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
export function getOpenCodeModelState(db: Database, userId = 'default'): OpenCodeModelStateRecord {
|
||||
ensureOpenCodeModelStateTable(db)
|
||||
|
||||
const row = db.prepare('SELECT recent, favorite, variant FROM opencode_model_state WHERE user_id = ?').get(userId) as
|
||||
| { recent: string; favorite: string; variant: string }
|
||||
| undefined
|
||||
|
||||
if (!row) {
|
||||
return EMPTY_STATE
|
||||
}
|
||||
|
||||
const recent = parseJsonSafe<ModelSelectionRecord[]>(row.recent, [])
|
||||
const favorite = parseJsonSafe<ModelSelectionRecord[]>(row.favorite, [])
|
||||
const variant = parseJsonSafe<Record<string, string | undefined>>(row.variant, {})
|
||||
|
||||
return { recent, favorite, variant }
|
||||
}
|
||||
|
||||
export function addRecentOpenCodeModel(
|
||||
db: Database,
|
||||
model: ModelSelectionRecord,
|
||||
userId = 'default',
|
||||
): OpenCodeModelStateRecord {
|
||||
const insertMany = db.transaction(() => {
|
||||
const current = getOpenCodeModelState(db, userId)
|
||||
const deduped = [model, ...current.recent.filter(m => m.providerID !== model.providerID || m.modelID !== model.modelID)]
|
||||
const sliced = deduped.slice(0, MAX_RECENT_MODELS)
|
||||
const now = Date.now()
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO opencode_model_state(user_id, recent, favorite, variant, updated_at)
|
||||
VALUES(?,?,?,?,?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET recent=excluded.recent, updated_at=excluded.updated_at
|
||||
`).run(userId, JSON.stringify(sliced), JSON.stringify(current.favorite), JSON.stringify(current.variant), now)
|
||||
|
||||
return { recent: sliced, favorite: current.favorite, variant: current.variant }
|
||||
})
|
||||
|
||||
return insertMany()
|
||||
}
|
||||
|
||||
export function removeRecentOpenCodeModel(
|
||||
db: Database,
|
||||
model: ModelSelectionRecord,
|
||||
userId = 'default',
|
||||
): OpenCodeModelStateRecord {
|
||||
const remove = db.transaction(() => {
|
||||
const current = getOpenCodeModelState(db, userId)
|
||||
const updated = current.recent.filter(
|
||||
m => m.providerID !== model.providerID || m.modelID !== model.modelID,
|
||||
)
|
||||
const now = Date.now()
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO opencode_model_state(user_id, recent, favorite, variant, updated_at)
|
||||
VALUES(?,?,?,?,?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET recent=excluded.recent, updated_at=excluded.updated_at
|
||||
`).run(userId, JSON.stringify(updated), JSON.stringify(current.favorite), JSON.stringify(current.variant), now)
|
||||
|
||||
return { recent: updated, favorite: current.favorite, variant: current.variant }
|
||||
})
|
||||
|
||||
return remove()
|
||||
}
|
||||
|
||||
export function toggleFavoriteOpenCodeModel(
|
||||
db: Database,
|
||||
model: ModelSelectionRecord,
|
||||
userId = 'default',
|
||||
): OpenCodeModelStateRecord {
|
||||
const toggle = db.transaction(() => {
|
||||
const current = getOpenCodeModelState(db, userId)
|
||||
const exists = current.favorite.some(
|
||||
m => m.providerID === model.providerID && m.modelID === model.modelID,
|
||||
)
|
||||
|
||||
const updated = exists
|
||||
? current.favorite.filter(m => m.providerID !== model.providerID || m.modelID !== model.modelID)
|
||||
: [...current.favorite, model]
|
||||
|
||||
const now = Date.now()
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO opencode_model_state(user_id, recent, favorite, variant, updated_at)
|
||||
VALUES(?,?,?,?,?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET favorite=excluded.favorite, updated_at=excluded.updated_at
|
||||
`).run(userId, JSON.stringify(current.recent), JSON.stringify(updated), JSON.stringify(current.variant), now)
|
||||
|
||||
return { recent: current.recent, favorite: updated, variant: current.variant }
|
||||
})
|
||||
|
||||
return toggle()
|
||||
}
|
||||
|
||||
export function setOpenCodeVariant(
|
||||
db: Database,
|
||||
key: string,
|
||||
variant: string | undefined,
|
||||
userId = 'default',
|
||||
): OpenCodeModelStateRecord {
|
||||
const setVariant = db.transaction(() => {
|
||||
const current = getOpenCodeModelState(db, userId)
|
||||
const updated = { ...current.variant }
|
||||
|
||||
if (variant === undefined) {
|
||||
delete updated[key]
|
||||
} else {
|
||||
updated[key] = variant
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
|
||||
db.prepare(`
|
||||
INSERT INTO opencode_model_state(user_id, recent, favorite, variant, updated_at)
|
||||
VALUES(?,?,?,?,?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET variant=excluded.variant, updated_at=excluded.updated_at
|
||||
`).run(userId, JSON.stringify(current.recent), JSON.stringify(current.favorite), JSON.stringify(updated), now)
|
||||
|
||||
return { recent: current.recent, favorite: current.favorite, variant: updated }
|
||||
})
|
||||
|
||||
return setVariant()
|
||||
}
|
||||
@@ -17,7 +17,6 @@ interface RepoRow {
|
||||
cloned_at: number
|
||||
last_pulled?: number
|
||||
last_accessed_at?: number
|
||||
opencode_config_name?: string
|
||||
is_worktree?: number
|
||||
is_local?: number
|
||||
}
|
||||
@@ -42,7 +41,6 @@ function rowToRepo(row: RepoRow): Repo {
|
||||
clonedAt: row.cloned_at,
|
||||
lastPulled: row.last_pulled,
|
||||
lastAccessedAt: row.last_accessed_at,
|
||||
openCodeConfigName: row.opencode_config_name,
|
||||
isWorktree: row.is_worktree ? Boolean(row.is_worktree) : undefined,
|
||||
isLocal: row.is_local ? Boolean(row.is_local) : undefined,
|
||||
}
|
||||
@@ -311,14 +309,6 @@ export function updateRepoStatus(db: Database, id: number, cloneStatus: Repo['cl
|
||||
}
|
||||
}
|
||||
|
||||
export function updateRepoConfigName(db: Database, id: number, configName: string): void {
|
||||
const stmt = db.prepare('UPDATE repos SET opencode_config_name = ? WHERE id = ?')
|
||||
const result = stmt.run(configName, id)
|
||||
if (result.changes === 0) {
|
||||
throw new Error(`Repository with id ${id} not found`)
|
||||
}
|
||||
}
|
||||
|
||||
export function updateLastPulled(db: Database, id: number): void {
|
||||
const stmt = db.prepare('UPDATE repos SET last_pulled = ? WHERE id = ?')
|
||||
const result = stmt.run(Date.now(), id)
|
||||
|
||||
@@ -3,7 +3,6 @@ import { logger } from '../utils/logger'
|
||||
import { dirname } from 'path'
|
||||
import { migrate } from './migration-runner'
|
||||
import { allMigrations } from './migrations'
|
||||
import { ensureOpenCodeModelStateTable } from './model-state'
|
||||
import { ensureAssistantRepo } from './queries'
|
||||
import { mkdirSyncSafe } from '../utils/fs-safe'
|
||||
|
||||
@@ -12,7 +11,6 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
|
||||
const db = new Database(dbPath)
|
||||
|
||||
migrate(db, allMigrations)
|
||||
ensureOpenCodeModelStateTable(db)
|
||||
|
||||
db.prepare('INSERT OR IGNORE INTO user_preferences (user_id, preferences, updated_at) VALUES (?, ?, ?)')
|
||||
.run('default', '{}', Date.now())
|
||||
|
||||
+26
-118
@@ -42,7 +42,7 @@ import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
import { createAuthenticatedOpenCodeProxyRoutes } from './routes/opencode-auth-proxy'
|
||||
import { sseAggregator } from './services/sse-aggregator'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists } from './services/file-operations'
|
||||
import { SettingsService } from './services/settings'
|
||||
import { opencodeServerManager } from './services/opencode-single-server'
|
||||
import { createOpenCodeClient } from './services/opencode/client'
|
||||
@@ -55,23 +55,15 @@ import { installAssistantWorkspace } from './services/assistant-mode'
|
||||
import { detectSandboxCapability } from './services/sandbox/capability'
|
||||
import { SandboxRuntimeService, stopWorkspaceSandboxOnShutdown } from './services/sandbox/runtime'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
|
||||
import { readOpenCodeConfigFile, writeOpenCodeConfigFile, OPENCODE_CONFIG_SEED } from './services/opencode-config-file'
|
||||
import { OpenCodeSupervisor } from './services/opencode-supervisor'
|
||||
import { OpenCodeRestartCoordinator } from './services/opencode-restart-coordinator'
|
||||
import { setOpenCodeRestartCoordinator } from './services/opencode-restart'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { parse as parseJsonc } from 'jsonc-parser'
|
||||
import { getModelStatePath, ModelStateSchema } from './routes/providers'
|
||||
import { readJsonSafe } from './utils/atomic-json'
|
||||
import {
|
||||
type OpenCodeModelStateRecord,
|
||||
} from './db/model-state'
|
||||
|
||||
import { logger } from './utils/logger'
|
||||
import {
|
||||
getWorkspacePath,
|
||||
getReposPath,
|
||||
getConfigPath,
|
||||
getOpenCodeConfigFilePath,
|
||||
getAgentsMdPath,
|
||||
getDatabasePath,
|
||||
ENV
|
||||
@@ -118,112 +110,31 @@ import { DEFAULT_AGENTS_MD } from './constants'
|
||||
let ipcServer: IPCServer | undefined
|
||||
const gitAuthService = new GitAuthService()
|
||||
let openCodeSupervisor: OpenCodeSupervisor | undefined
|
||||
async function ensureDefaultConfigExists(): Promise<void> {
|
||||
const settingsService = new SettingsService(db)
|
||||
const workspaceConfigPath = getOpenCodeConfigFilePath()
|
||||
|
||||
if (await fileExists(workspaceConfigPath)) {
|
||||
logger.info(`Found workspace config at ${workspaceConfigPath}, syncing to database...`)
|
||||
try {
|
||||
const rawContent = await readFileContent(workspaceConfigPath)
|
||||
const parsed = parseJsonc(rawContent)
|
||||
const validation = OpenCodeConfigSchema.safeParse(parsed)
|
||||
|
||||
if (!validation.success) {
|
||||
logger.warn('Workspace config has invalid structure', validation.error)
|
||||
} else {
|
||||
const existingDefault = settingsService.getOpenCodeConfigByName('default')
|
||||
if (existingDefault) {
|
||||
settingsService.updateOpenCodeConfig('default', {
|
||||
content: rawContent,
|
||||
isDefault: true,
|
||||
})
|
||||
logger.info('Updated database config from workspace file')
|
||||
} else {
|
||||
settingsService.createOpenCodeConfig({
|
||||
name: 'default',
|
||||
content: rawContent,
|
||||
isDefault: true,
|
||||
})
|
||||
logger.info('Created database config from workspace file')
|
||||
}
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to read workspace config', error)
|
||||
}
|
||||
}
|
||||
|
||||
const { configSourcePath: importConfigPath } = await getOpenCodeImportStatus()
|
||||
|
||||
if (importConfigPath) {
|
||||
logger.info(`Found importable OpenCode config at ${importConfigPath}, importing...`)
|
||||
try {
|
||||
const result = await syncOpenCodeImport({ db, overwriteState: false })
|
||||
if (result.configImported) {
|
||||
logger.info(`Imported OpenCode config from ${importConfigPath} to workspace`)
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to import OpenCode config from ${importConfigPath}`, error)
|
||||
}
|
||||
}
|
||||
|
||||
const existingDbConfigs = settingsService.getOpenCodeConfigs()
|
||||
if (existingDbConfigs.configs.length > 0) {
|
||||
const defaultConfig = settingsService.getDefaultOpenCodeConfig()
|
||||
if (defaultConfig) {
|
||||
await writeFileContent(workspaceConfigPath, defaultConfig.rawContent)
|
||||
logger.info('Wrote existing database config to workspace file')
|
||||
async function ensureOpenCodeConfigFileExists(): Promise<void> {
|
||||
const existing = await readOpenCodeConfigFile()
|
||||
if (existing) {
|
||||
if (!existing.isValid) {
|
||||
logger.warn('OpenCode config file has validation issues', existing.validationIssues)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logger.info('No existing config found, creating minimal seed config')
|
||||
const seedConfig = JSON.stringify({ $schema: 'https://opencode.ai/config.json' }, null, 2)
|
||||
settingsService.createOpenCodeConfig({
|
||||
name: 'default',
|
||||
content: seedConfig,
|
||||
isDefault: true,
|
||||
})
|
||||
await writeFileContent(workspaceConfigPath, seedConfig)
|
||||
logger.info('Created minimal seed config')
|
||||
}
|
||||
|
||||
async function backfillOpenCodeModelStateFromFile(): Promise<void> {
|
||||
try {
|
||||
const modelStatePath = getModelStatePath()
|
||||
const fileState = await readJsonSafe<OpenCodeModelStateRecord | null>(modelStatePath, null)
|
||||
|
||||
if (!fileState) {
|
||||
return
|
||||
const status = await getOpenCodeImportStatus()
|
||||
if (status.configSourcePath) {
|
||||
logger.info(`Found importable OpenCode config at ${status.configSourcePath}, importing...`)
|
||||
try {
|
||||
const result = await syncOpenCodeImport({ overwriteState: false, status })
|
||||
if (result.configImported) {
|
||||
logger.info(`Imported OpenCode config from ${status.configSourcePath} to workspace`)
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to import OpenCode config from ${status.configSourcePath}`, error)
|
||||
}
|
||||
|
||||
const existingRow = db.prepare('SELECT 1 FROM opencode_model_state WHERE user_id = ?').get('default')
|
||||
if (existingRow) {
|
||||
return
|
||||
}
|
||||
|
||||
const validated = ModelStateSchema.safeParse(fileState)
|
||||
if (!validated.success) {
|
||||
logger.warn('Model state file has invalid structure, skipping backfill', validated.error)
|
||||
return
|
||||
}
|
||||
|
||||
db.prepare(
|
||||
'INSERT INTO opencode_model_state(user_id, recent, favorite, variant, updated_at) VALUES(?,?,?,?,?)'
|
||||
).run(
|
||||
'default',
|
||||
JSON.stringify(validated.data.recent),
|
||||
JSON.stringify(validated.data.favorite),
|
||||
JSON.stringify(validated.data.variant),
|
||||
Date.now()
|
||||
)
|
||||
|
||||
logger.info('Backfilled OpenCode model state from model.json to database')
|
||||
} catch (error) {
|
||||
logger.warn('Failed to backfill OpenCode model state from file:', error)
|
||||
}
|
||||
|
||||
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED)
|
||||
logger.info('Created minimal seed config')
|
||||
}
|
||||
|
||||
async function ensureHomeStateImported(): Promise<void> {
|
||||
@@ -237,7 +148,7 @@ async function ensureHomeStateImported(): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
const result = await syncOpenCodeImport({ db, overwriteState: false })
|
||||
const result = await syncOpenCodeImport({ overwriteState: false, importConfig: false, status })
|
||||
if (result.stateImported) {
|
||||
logger.info(`Imported OpenCode state from ${status.stateSourcePath}`)
|
||||
}
|
||||
@@ -272,17 +183,14 @@ try {
|
||||
await cleanupExpiredCache()
|
||||
await sweepStaleUploadSessions()
|
||||
|
||||
await ensureDefaultConfigExists()
|
||||
await backfillOpenCodeModelStateFromFile()
|
||||
await ensureOpenCodeConfigFileExists()
|
||||
await ensureHomeStateImported()
|
||||
await ensureDefaultAgentsMdExists()
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
settingsService.initializeLastKnownGoodConfig()
|
||||
|
||||
openCodeSupervisor = new OpenCodeSupervisor(opencodeServerManager, settingsService, {
|
||||
userId: 'default'
|
||||
})
|
||||
openCodeSupervisor = new OpenCodeSupervisor(opencodeServerManager, settingsService)
|
||||
|
||||
await migrateGlobalSkills()
|
||||
|
||||
@@ -364,11 +272,11 @@ app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService))
|
||||
const protectedApi = new Hono()
|
||||
protectedApi.use('/*', requireAuth)
|
||||
|
||||
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient))
|
||||
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/files', createFileRoutes())
|
||||
protectedApi.route('/filesystem', createFilesystemRoutes())
|
||||
protectedApi.route('/providers', createProvidersRoutes(db, openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/providers', createProvidersRoutes(openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/oauth', createOAuthRoutes(openCodeClient, openCodeSupervisor))
|
||||
protectedApi.route('/tts', createTTSRoutes(db))
|
||||
protectedApi.route('/stt', createSTTRoutes(db))
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createScheduleRoutes } from '../schedules'
|
||||
import { createInternalTokenMiddleware } from '../../auth/internal-token-middleware'
|
||||
import { createInternalNotificationRoutes } from './notifications'
|
||||
import { createInternalSettingsRoutes } from './settings'
|
||||
import { createOpenCodeConfigRoutes } from '../opencode-config'
|
||||
import { createInternalRepoRoutes } from './repos'
|
||||
import { createInternalRepoSyncRoutes } from './repo-sync'
|
||||
import { createInternalRepoMirrorRoutes as mirrorRoutes } from './repo-mirror'
|
||||
@@ -28,6 +29,7 @@ export function createInternalRoutes(
|
||||
app.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
app.route('/notifications', createInternalNotificationRoutes(notificationService))
|
||||
app.route('/settings', createInternalSettingsRoutes(settingsService))
|
||||
app.route('/opencode-config', createOpenCodeConfigRoutes(settingsService, openCodeClient))
|
||||
const repos = new Hono()
|
||||
repos.route('/', createInternalRepoRoutes(db, settingsService))
|
||||
repos.route('/:id/schedules', createScheduleRoutes(scheduleService))
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import { UpdateOpenCodeConfigRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { SettingsService } from '../services/settings'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { readOpenCodeConfigFile } from '../services/opencode-config-file'
|
||||
import { applyOpenCodeConfigUpdate, toOpenCodeConfigApplyResponse } from '../services/opencode-config-apply'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
export function createOpenCodeConfigRoutes(settingsService: SettingsService, openCodeClient: OpenCodeClient) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', async (c) => {
|
||||
try {
|
||||
const config = await readOpenCodeConfigFile()
|
||||
if (!config) {
|
||||
return c.json({ error: 'No OpenCode config file found' }, 404)
|
||||
}
|
||||
return c.json(config)
|
||||
} catch (error) {
|
||||
logger.error('Failed to get OpenCode config:', error)
|
||||
return c.json({ error: 'Failed to get OpenCode config' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.put('/', async (c) => {
|
||||
let body: unknown
|
||||
try {
|
||||
body = await c.req.json()
|
||||
} catch {
|
||||
return c.json({ error: 'Invalid JSON' }, 400)
|
||||
}
|
||||
|
||||
const parsed = UpdateOpenCodeConfigRequestSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: 'Invalid config data', details: parsed.error.issues }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await applyOpenCodeConfigUpdate({
|
||||
content: parsed.data.content,
|
||||
openCodeClient,
|
||||
settingsService,
|
||||
})
|
||||
const { status, body: responseBody } = toOpenCodeConfigApplyResponse(result)
|
||||
return c.json(responseBody, status)
|
||||
} catch (error) {
|
||||
logger.error('Failed to update OpenCode config:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
|
||||
}
|
||||
return c.json({ error: 'Failed to update OpenCode config' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -1,60 +1,53 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import { createProvidersRoutes } from './providers'
|
||||
import { join, dirname } from 'node:path'
|
||||
import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { OpenCodeModelStateRecord } from '../services/opencode-model-state'
|
||||
|
||||
function createTestApp(db: Database): Hono {
|
||||
const modelStateMock = vi.hoisted(() => ({
|
||||
readOpenCodeModelState: vi.fn(),
|
||||
updateOpenCodeModelState: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../services/opencode-model-state', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../services/opencode-model-state')>()
|
||||
return {
|
||||
...actual,
|
||||
readOpenCodeModelState: modelStateMock.readOpenCodeModelState,
|
||||
updateOpenCodeModelState: modelStateMock.updateOpenCodeModelState,
|
||||
}
|
||||
})
|
||||
|
||||
function createTestApp(): Hono {
|
||||
const app = new Hono()
|
||||
app.route('/providers', createProvidersRoutes(db, createStubOpenCodeClient()))
|
||||
app.route('/providers', createProvidersRoutes(createStubOpenCodeClient()))
|
||||
return app
|
||||
}
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
describe('providers routes', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
let tmpDir: string
|
||||
let originalWorkspacePath: string | undefined
|
||||
let storedState: OpenCodeModelStateRecord
|
||||
|
||||
beforeEach(async () => {
|
||||
db = createTestDb()
|
||||
app = createTestApp(db)
|
||||
tmpDir = await mkdtemp(join(tmpdir(), 'providers-test-'))
|
||||
originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
process.env.WORKSPACE_PATH = tmpDir
|
||||
|
||||
const { getModelStatePath } = await import('./providers')
|
||||
const modelStatePath = getModelStatePath()
|
||||
const modelStateDir = dirname(modelStatePath)
|
||||
await mkdir(modelStateDir, { recursive: true })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (originalWorkspacePath) {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
} else {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
}
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
storedState = { recent: [], favorite: [], variant: {} }
|
||||
modelStateMock.readOpenCodeModelState.mockImplementation(async () => storedState)
|
||||
modelStateMock.updateOpenCodeModelState.mockImplementation(
|
||||
async (mutate: (state: OpenCodeModelStateRecord) => OpenCodeModelStateRecord) => {
|
||||
storedState = mutate(storedState)
|
||||
return storedState
|
||||
},
|
||||
)
|
||||
app = createTestApp()
|
||||
})
|
||||
|
||||
describe('GET /model-state', () => {
|
||||
it('on empty DB returns defaults', async () => {
|
||||
it('returns the state owned by the service', async () => {
|
||||
const res = await app.request('/providers/model-state')
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { recent: unknown[]; favorite: unknown[]; variant: Record<string, unknown> }
|
||||
expect(data).toEqual({ recent: [], favorite: [], variant: {} })
|
||||
expect(modelStateMock.readOpenCodeModelState).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -71,9 +64,27 @@ describe('providers routes', () => {
|
||||
expect(data.recent[0]).toEqual({ providerID: 'anthropic', modelID: 'claude' })
|
||||
})
|
||||
|
||||
it('with removeRecent removes the model', async () => {
|
||||
storedState = {
|
||||
recent: [{ providerID: 'openai', modelID: 'gpt-4' }],
|
||||
favorite: [],
|
||||
variant: {},
|
||||
}
|
||||
|
||||
const res = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ removeRecent: { providerID: 'openai', modelID: 'gpt-4' } }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { recent: Array<{ providerID: string; modelID: string }> }
|
||||
expect(data.recent).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('with favorite toggles favorite (add then remove)', async () => {
|
||||
const body = { favorite: { providerID: 'openai', modelID: 'gpt-4' } }
|
||||
|
||||
|
||||
const res1 = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -102,12 +113,11 @@ describe('providers routes', () => {
|
||||
expect(res.status).toBe(400)
|
||||
const data = (await res.json()) as { error: string }
|
||||
expect(data.error).toBe('Invalid request data')
|
||||
expect(modelStateMock.updateOpenCodeModelState).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('with corrupt model.json on disk still returns 200 and overwrites with valid JSON', async () => {
|
||||
const { getModelStatePath } = await import('./providers')
|
||||
const modelStatePath = getModelStatePath()
|
||||
await writeFile(modelStatePath, '{ invalid json content }', 'utf8')
|
||||
it('returns 500 when the service rejects', async () => {
|
||||
modelStateMock.updateOpenCodeModelState.mockRejectedValueOnce(new Error('disk full'))
|
||||
|
||||
const res = await app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
@@ -115,38 +125,9 @@ describe('providers routes', () => {
|
||||
body: JSON.stringify({ recent: { providerID: 'test', modelID: 'test' } }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { recent: Array<{ providerID: string; modelID: string }> }
|
||||
expect(data.recent).toHaveLength(1)
|
||||
|
||||
const fileContent = await Bun.file(modelStatePath).text()
|
||||
const parsed = JSON.parse(fileContent) as { recent: unknown[] }
|
||||
expect(parsed.recent).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('20 concurrent POST calls all return 200, final recent is valid and bounded', async () => {
|
||||
const numOps = 20
|
||||
|
||||
const requests = Array.from({ length: numOps }, (_, i) =>
|
||||
app.request('/providers/model-state', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ recent: { providerID: `provider-${i}`, modelID: `model-${i}` } }),
|
||||
}),
|
||||
)
|
||||
|
||||
const responses = await Promise.all(requests)
|
||||
responses.forEach((res) => {
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
const finalRes = await app.request('/providers/model-state')
|
||||
const finalData = (await finalRes.json()) as { recent: Array<{ providerID: string; modelID: string }> }
|
||||
expect(finalData.recent.length).toBeLessThanOrEqual(10)
|
||||
expect(finalData.recent.length).toBeGreaterThan(0)
|
||||
|
||||
const uniqueKeys = new Set(finalData.recent.map((m) => `${m.providerID}/${m.modelID}`))
|
||||
expect(uniqueKeys.size).toBe(finalData.recent.length)
|
||||
expect(res.status).toBe(500)
|
||||
const data = (await res.json()) as { error: string }
|
||||
expect(data.error).toBe('Failed to update OpenCode model state')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,33 +1,19 @@
|
||||
import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import path from 'path'
|
||||
import { AuthService } from '../services/auth'
|
||||
import { SetCredentialRequestSchema } from '../../../shared/src/schemas/auth'
|
||||
import { logger } from '../utils/logger'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { reloadOpenCodeConfig } from '../services/opencode-restart'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
addRecentOpenCodeModel,
|
||||
getOpenCodeModelState as readModelStateFromDb,
|
||||
removeRecentOpenCodeModel,
|
||||
toggleFavoriteOpenCodeModel,
|
||||
type OpenCodeModelStateRecord,
|
||||
} from '../db/model-state'
|
||||
import { writeJsonAtomic, withFileLock } from '../utils/atomic-json'
|
||||
|
||||
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({}),
|
||||
})
|
||||
addRecentModel,
|
||||
ModelSelectionSchema,
|
||||
readOpenCodeModelState,
|
||||
removeRecentModel,
|
||||
toggleFavoriteModel,
|
||||
updateOpenCodeModelState,
|
||||
} from '../services/opencode-model-state'
|
||||
|
||||
const UpdateModelStateSchema = z.object({
|
||||
recent: ModelSelectionSchema.optional(),
|
||||
@@ -35,35 +21,16 @@ const UpdateModelStateSchema = z.object({
|
||||
removeRecent: ModelSelectionSchema.optional(),
|
||||
}).strict()
|
||||
|
||||
export function getModelStatePath(): string {
|
||||
return path.join(getWorkspacePath(), '.opencode', 'state', 'opencode', 'model.json')
|
||||
}
|
||||
|
||||
async function mirrorModelStateToFile(state: OpenCodeModelStateRecord): Promise<void> {
|
||||
const modelStatePath = getModelStatePath()
|
||||
try {
|
||||
await withFileLock(modelStatePath, async () => {
|
||||
await writeJsonAtomic(modelStatePath, {
|
||||
recent: state.recent,
|
||||
favorite: state.favorite,
|
||||
variant: state.variant,
|
||||
})
|
||||
})
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to mirror model state to file ${modelStatePath}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
export function createProvidersRoutes(db: Database, openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
export function createProvidersRoutes(openCodeClient: OpenCodeClient, openCodeSupervisor?: OpenCodeSupervisor) {
|
||||
const app = new Hono()
|
||||
const authService = new AuthService()
|
||||
|
||||
app.get('/model-state', async (c) => {
|
||||
try {
|
||||
const state = readModelStateFromDb(db)
|
||||
const state = await readOpenCodeModelState()
|
||||
return c.json(state)
|
||||
} catch (error) {
|
||||
logger.error('Failed to read OpenCode model state from DB:', error)
|
||||
logger.error('Failed to read OpenCode model state:', error)
|
||||
return c.json({ recent: [], favorite: [], variant: {} })
|
||||
}
|
||||
})
|
||||
@@ -72,21 +39,20 @@ export function createProvidersRoutes(db: Database, openCodeClient: OpenCodeClie
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const validated = UpdateModelStateSchema.parse(body)
|
||||
|
||||
let nextState: OpenCodeModelStateRecord
|
||||
|
||||
if (validated.favorite) {
|
||||
nextState = toggleFavoriteOpenCodeModel(db, validated.favorite)
|
||||
} else if (validated.recent) {
|
||||
nextState = addRecentOpenCodeModel(db, validated.recent)
|
||||
} else if (validated.removeRecent) {
|
||||
nextState = removeRecentOpenCodeModel(db, validated.removeRecent)
|
||||
} else {
|
||||
nextState = readModelStateFromDb(db)
|
||||
}
|
||||
|
||||
await mirrorModelStateToFile(nextState)
|
||||
|
||||
|
||||
const nextState = await updateOpenCodeModelState((state) => {
|
||||
if (validated.favorite) {
|
||||
return toggleFavoriteModel(state, validated.favorite)
|
||||
}
|
||||
if (validated.recent) {
|
||||
return addRecentModel(state, validated.recent)
|
||||
}
|
||||
if (validated.removeRecent) {
|
||||
return removeRecentModel(state, validated.removeRecent)
|
||||
}
|
||||
return state
|
||||
})
|
||||
|
||||
return c.json(nextState)
|
||||
} catch (error) {
|
||||
logger.error('Failed to update OpenCode model state:', error)
|
||||
|
||||
@@ -50,6 +50,17 @@ function createTestDb(): Database {
|
||||
return db
|
||||
}
|
||||
|
||||
function createThrowingDb(): Database {
|
||||
return {
|
||||
prepare: () => {
|
||||
throw new Error('repo failed')
|
||||
},
|
||||
query: () => {
|
||||
throw new Error('repo failed')
|
||||
},
|
||||
} as unknown as Database
|
||||
}
|
||||
|
||||
describe('GET /api/repos/:id/siblings', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
@@ -268,6 +279,11 @@ describe('GET /api/repos/:id/siblings', () => {
|
||||
const data = await res.json() as { error: string }
|
||||
expect(data.error).toBe('Invalid repo id')
|
||||
})
|
||||
|
||||
it('returns 500 when listing siblings throws', async () => {
|
||||
const res = await createTestApp(createThrowingDb()).request('/repos/1/siblings')
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/repos/:id/workspaces/:workspaceId', () => {
|
||||
@@ -299,6 +315,50 @@ describe('DELETE /api/repos/:id/workspaces/:workspaceId', () => {
|
||||
expect(captured?.path).toBe('/experimental/workspace/wrk_test')
|
||||
expect(captured?.directory?.endsWith('/repos/repo-a')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns 400 for a non-numeric repo id', async () => {
|
||||
const app = createTestApp(db)
|
||||
const res = await app.request('/repos/abc/workspaces/wrk_test', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the repo is missing or not ready', async () => {
|
||||
const app = createTestApp(db)
|
||||
|
||||
const missing = await app.request('/repos/1/workspaces/wrk_test', { method: 'DELETE' })
|
||||
expect(missing.status).toBe(404)
|
||||
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true })
|
||||
const notReady = await app.request('/repos/1/workspaces/wrk_test', { method: 'DELETE' })
|
||||
expect(notReady.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 400 for an invalid workspace id', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
const app = createTestApp(db)
|
||||
const res = await app.request('/repos/1/workspaces/bad-id', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('forwards an upstream error status', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
const app = createTestApp(db, createStubOpenCodeClient({
|
||||
forward: mock(async () => new Response('bad request', { status: 400 })) as any,
|
||||
}))
|
||||
const res = await app.request('/repos/1/workspaces/wrk_test', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const data = await res.json() as { error: string }
|
||||
expect(data.error).toBe('bad request')
|
||||
})
|
||||
|
||||
it('returns 500 when reading the repo throws', async () => {
|
||||
const res = await createTestApp(createThrowingDb()).request('/repos/1/workspaces/wrk_test', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/repos/:id/workspaces', () => {
|
||||
@@ -332,6 +392,59 @@ describe('POST /api/repos/:id/workspaces', () => {
|
||||
expect(JSON.parse(captured?.body ?? '{}')).toEqual({ type: 'worktree', branch: null })
|
||||
expect(await res.json()).toMatchObject({ id: 'wrk_test', type: 'worktree' })
|
||||
})
|
||||
|
||||
it('returns 400 for a non-numeric repo id', async () => {
|
||||
const app = createTestApp(db)
|
||||
const res = await app.request('/repos/abc/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the repo is missing or not ready', async () => {
|
||||
const app = createTestApp(db)
|
||||
|
||||
const missing = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
expect(missing.status).toBe(404)
|
||||
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true })
|
||||
const notReady = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
expect(notReady.status).toBe(404)
|
||||
})
|
||||
|
||||
it('forwards an upstream error status', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
const app = createTestApp(db, createStubOpenCodeClient({
|
||||
forward: mock(async () => new Response('boom', { status: 502 })) as any,
|
||||
}))
|
||||
const res = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(502)
|
||||
const data = await res.json() as { error: string }
|
||||
expect(data.error).toBe('boom')
|
||||
})
|
||||
|
||||
it('returns 500 when the upstream body is not JSON', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
const app = createTestApp(db, createStubOpenCodeClient({
|
||||
forward: mock(async () => new Response('not-json', { status: 200 })) as any,
|
||||
}))
|
||||
const res = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
const data = await res.json() as { error: string }
|
||||
expect(data.error).toBe('Failed to create workspace')
|
||||
})
|
||||
|
||||
it('returns success for an empty upstream response body', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
const app = createTestApp(db, createStubOpenCodeClient({
|
||||
forward: mock(async () => new Response('', { status: 200 })) as any,
|
||||
}))
|
||||
const res = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ success: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/repos/:id', () => {
|
||||
@@ -402,4 +515,21 @@ describe('PATCH /api/repos/:id', () => {
|
||||
const res = await app.request('/repos/1', { method: 'PATCH', body: JSON.stringify({ name: longName }), headers: { 'Content-Type': 'application/json' } })
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 for a non-numeric repo id', async () => {
|
||||
const res = await app.request('/repos/abc', { method: 'PATCH', body: JSON.stringify({ name: 'new-name' }), headers: { 'Content-Type': 'application/json' } })
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 for an invalid body', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
|
||||
const res = await app.request('/repos/1', { method: 'PATCH', body: JSON.stringify({}), headers: { 'Content-Type': 'application/json' } })
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 500 when reading the repo throws', async () => {
|
||||
const res = await createTestApp(createThrowingDb()).request('/repos/1', { method: 'PATCH', body: JSON.stringify({ name: 'new-name' }), headers: { 'Content-Type': 'application/json' } })
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
@@ -3,17 +3,13 @@ import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema, UpdateRepoRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { listRepos, getRepoById, updateLastAccessed, updateRepoConfigName, getRepoGitCredentialId, setRepoGitCredentialId, updateRepoName } from '../db/queries'
|
||||
import { listRepos, getRepoById, updateLastAccessed, getRepoGitCredentialId, setRepoGitCredentialId, updateRepoName } from '../db/queries'
|
||||
import * as repoService from '../services/repo'
|
||||
import * as archiveService from '../services/archive'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent } from '../services/file-operations'
|
||||
import { restartOpenCodeAfterCommit } from '../services/opencode-restart'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
|
||||
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import { createRepoGitRoutes } from './repo-git'
|
||||
import { createScheduleRoutes } from './schedules'
|
||||
@@ -38,7 +34,6 @@ export function createRepoRoutes(
|
||||
gitAuthService: GitAuthService,
|
||||
scheduleService: ScheduleService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
openCodeSupervisor?: OpenCodeSupervisor,
|
||||
) {
|
||||
const app = new Hono()
|
||||
|
||||
@@ -48,7 +43,7 @@ export function createRepoRoutes(
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const { repoUrl, localPath, branch, directoryName, openCodeConfigName, useWorktree, skipSSHVerification, provider, baseBranch } = body
|
||||
const { repoUrl, localPath, branch, directoryName, useWorktree, skipSSHVerification, provider, baseBranch } = body
|
||||
|
||||
if (!repoUrl && !localPath) {
|
||||
return c.json({ error: 'Either repoUrl or localPath is required' }, 400)
|
||||
@@ -73,18 +68,6 @@ export function createRepoRoutes(
|
||||
)
|
||||
}
|
||||
|
||||
if (openCodeConfigName) {
|
||||
const settingsService = new SettingsService(database)
|
||||
const configContent = settingsService.getOpenCodeConfigContent(openCodeConfigName)
|
||||
|
||||
if (configContent) {
|
||||
const openCodeConfigPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(openCodeConfigPath, configContent)
|
||||
updateRepoConfigName(database, repo.id, openCodeConfigName)
|
||||
logger.info(`Applied config '${openCodeConfigName}' to: ${openCodeConfigPath}`)
|
||||
}
|
||||
}
|
||||
|
||||
return c.json(repo)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create repo:', error)
|
||||
@@ -366,49 +349,6 @@ app.get('/', async (c) => {
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/config/switch', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const body = await c.req.json()
|
||||
const { configName } = body
|
||||
|
||||
if (!configName) {
|
||||
return c.json({ error: 'configName is required' }, 400)
|
||||
}
|
||||
|
||||
const settingsService = new SettingsService(database)
|
||||
const configContent = settingsService.getOpenCodeConfigContent(configName)
|
||||
|
||||
if (!configContent) {
|
||||
return c.json({ error: `Config '${configName}' not found` }, 404)
|
||||
}
|
||||
|
||||
const openCodeConfigPath = getOpenCodeConfigFilePath()
|
||||
|
||||
await writeFileContent(openCodeConfigPath, configContent)
|
||||
|
||||
updateRepoConfigName(database, id, configName)
|
||||
|
||||
logger.info(`Switched config for repo ${id} to '${configName}'`)
|
||||
logger.info(`Updated OpenCode config: ${openCodeConfigPath}`)
|
||||
|
||||
logger.info('Restarting OpenCode server due to workspace config change')
|
||||
const { restartFailed, restartError } = await restartOpenCodeAfterCommit(openCodeSupervisor)
|
||||
|
||||
const updatedRepo = getRepoById(database, id)
|
||||
return c.json(restartFailed ? { ...updatedRepo, restartFailed, restartError } : updatedRepo)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to switch repo config:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/branch/switch', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
|
||||
+13
-344
@@ -7,12 +7,13 @@ import { resolve, dirname } from 'path'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent, readFileContent, fileExists } from '../services/file-operations'
|
||||
import { patchConfigWithRecovery } from '../services/opencode/config-recovery'
|
||||
import { deleteOpenCodeConfigFile } from '../services/opencode-config-file'
|
||||
import { restoreLastKnownGoodOpenCodeConfig } from '../services/opencode-config-apply'
|
||||
import { createOpenCodeConfigRoutes } from './opencode-config'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { getOpenCodeConfigFilePath, getAgentsMdPath } from '@opencode-manager/shared/config/env'
|
||||
import { getAgentsMdPath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
UserPreferencesSchema,
|
||||
OpenCodeConfigSchema,
|
||||
type SandboxPreferences,
|
||||
} from '../types/settings'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
@@ -34,7 +35,7 @@ import { sseAggregator } from '../services/sse-aggregator'
|
||||
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
||||
import { detectSandboxCapability } from '../services/sandbox/capability'
|
||||
import { getProcessIdentityAttestationError } from '../services/opencode/process-identity'
|
||||
import { restartOpenCode, restartOpenCodeAfterCommit, reloadOpenCodeConfig, getOpenCodeRestartCoordinator } from '../services/opencode-restart'
|
||||
import { restartOpenCode, reloadOpenCodeConfig, getOpenCodeRestartCoordinator } from '../services/opencode-restart'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { DEFAULT_AGENTS_MD } from '../constants'
|
||||
import { validateSSHPrivateKey } from '../utils/ssh-validation'
|
||||
@@ -84,19 +85,6 @@ function getOpenCodeInstallMethod(): string {
|
||||
return 'curl'
|
||||
}
|
||||
|
||||
function getOpenCodeConfigContentToWrite(
|
||||
rawContent: string,
|
||||
sourceConfig: Record<string, unknown>,
|
||||
appliedConfig?: Record<string, unknown>,
|
||||
removedFields?: string[],
|
||||
): string {
|
||||
if (removedFields && removedFields.length > 0) {
|
||||
return JSON.stringify(appliedConfig ?? sourceConfig, null, 2)
|
||||
}
|
||||
|
||||
return rawContent
|
||||
}
|
||||
|
||||
async function restartOpenCodeSafe(openCodeSupervisor: OpenCodeSupervisor | undefined, context: string): Promise<void> {
|
||||
try {
|
||||
await restartOpenCode(openCodeSupervisor)
|
||||
@@ -204,21 +192,6 @@ const SKILL_INSTALL_ERROR_STATUS: ReadonlyArray<readonly [string, 400 | 404 | 40
|
||||
['not a valid file', 400],
|
||||
]
|
||||
|
||||
function didConfigFieldChange(
|
||||
previous: Record<string, unknown> | undefined,
|
||||
next: Record<string, unknown> | undefined,
|
||||
field: string
|
||||
): boolean {
|
||||
return JSON.stringify(previous?.[field]) !== JSON.stringify(next?.[field])
|
||||
}
|
||||
|
||||
function needsOpenCodeRestart(
|
||||
previous: Record<string, unknown> | undefined,
|
||||
next: Record<string, unknown> | undefined
|
||||
): boolean {
|
||||
return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field))
|
||||
}
|
||||
|
||||
function sandboxEnforcementChanged(
|
||||
previous: SandboxPreferences | undefined,
|
||||
next: SandboxPreferences | undefined,
|
||||
@@ -244,10 +217,6 @@ function getMarkdownUploadManifest(manifest: ReturnType<typeof parseUploadManife
|
||||
return manifest.filter(entry => entry.relativePath.toLowerCase().endsWith('.md'))
|
||||
}
|
||||
|
||||
function hasConfiguredPlugins(config: Record<string, unknown> | undefined): boolean {
|
||||
return Array.isArray(config?.plugin) && config.plugin.length > 0
|
||||
}
|
||||
|
||||
function execWithTimeout(
|
||||
args: [executable: string, ...commandArgs: string[]],
|
||||
timeoutMs: number,
|
||||
@@ -296,19 +265,6 @@ const UpdateSettingsSchema = z.object({
|
||||
preferences: UserPreferencesSchema.partial(),
|
||||
})
|
||||
|
||||
const CreateOpenCodeConfigSchema = z.object({
|
||||
name: z.string().min(1).max(255),
|
||||
content: z.union([OpenCodeConfigSchema, z.string()]),
|
||||
isDefault: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const UpdateOpenCodeConfigSchema = z.object({
|
||||
content: z.union([OpenCodeConfigSchema, z.string()]),
|
||||
isDefault: z.boolean().optional(),
|
||||
})
|
||||
|
||||
|
||||
|
||||
const CreateCustomCommandSchema = z.object({
|
||||
name: z.string().min(1).max(255),
|
||||
description: z.string().min(1).max(1000),
|
||||
@@ -463,280 +419,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
})
|
||||
|
||||
// OpenCode Config routes
|
||||
app.get('/opencode-configs', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const configs = settingsService.getOpenCodeConfigs(userId)
|
||||
return c.json(configs)
|
||||
} catch (error) {
|
||||
logger.error('Failed to get OpenCode configs:', error)
|
||||
return c.json({ error: 'Failed to get OpenCode configs' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/opencode-configs', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const body = await c.req.json()
|
||||
const validated = CreateOpenCodeConfigSchema.parse(body)
|
||||
|
||||
if (validated.isDefault) {
|
||||
settingsService.saveLastKnownGoodConfig(userId)
|
||||
|
||||
const provisionalConfig = settingsService.createOpenCodeConfig(
|
||||
{ ...validated, isDefault: false },
|
||||
userId,
|
||||
{ suppressAutoDefault: true }
|
||||
)
|
||||
|
||||
if (hasConfiguredPlugins(provisionalConfig.content)) {
|
||||
const contentToWrite = provisionalConfig.rawContent
|
||||
const config = settingsService.updateOpenCodeConfig(provisionalConfig.name, {
|
||||
content: contentToWrite,
|
||||
isDefault: true,
|
||||
}, userId)
|
||||
|
||||
if (!config) {
|
||||
return c.json({ error: 'Failed to finalize OpenCode config creation' }, 500)
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
opencodeServerManager.clearStartupError()
|
||||
const { restartFailed, restartError } = await restartOpenCodeAfterCommit(openCodeSupervisor)
|
||||
|
||||
return c.json(restartFailed ? { ...config, restartFailed, restartError } : config)
|
||||
}
|
||||
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, provisionalConfig.content)
|
||||
if (!patchResult.success) {
|
||||
settingsService.deleteOpenCodeConfig(provisionalConfig.name, userId)
|
||||
return c.json({
|
||||
error: 'Config validation failed',
|
||||
details: patchResult.error,
|
||||
validationIssues: patchResult.details,
|
||||
removedFields: patchResult.removedFields
|
||||
}, 400)
|
||||
}
|
||||
|
||||
const contentToWrite = getOpenCodeConfigContentToWrite(
|
||||
provisionalConfig.rawContent,
|
||||
provisionalConfig.content,
|
||||
patchResult.appliedConfig,
|
||||
patchResult.removedFields,
|
||||
)
|
||||
const config = settingsService.updateOpenCodeConfig(provisionalConfig.name, {
|
||||
content: contentToWrite,
|
||||
isDefault: true,
|
||||
}, userId)
|
||||
|
||||
if (!config) {
|
||||
return c.json({ error: 'Failed to finalize OpenCode config creation' }, 500)
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
|
||||
if (patchResult.removedFields && patchResult.removedFields.length > 0) {
|
||||
logger.info(`Config applied with auto-removed fields: ${patchResult.removedFields.join(', ')}`)
|
||||
return c.json({ ...config, removedFields: patchResult.removedFields })
|
||||
}
|
||||
|
||||
return c.json(config)
|
||||
}
|
||||
|
||||
const config = settingsService.createOpenCodeConfig(validated, userId)
|
||||
return c.json(config)
|
||||
} catch (error) {
|
||||
logger.error('Failed to create OpenCode config:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
|
||||
}
|
||||
if (error instanceof Error && error.message.includes('already exists')) {
|
||||
return c.json({ error: error.message }, 409)
|
||||
}
|
||||
return c.json({ error: 'Failed to create OpenCode config' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.put('/opencode-configs/:name', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const configName = c.req.param('name')
|
||||
const body = await c.req.json()
|
||||
const validated = UpdateOpenCodeConfigSchema.parse(body)
|
||||
|
||||
const existingConfig = settingsService.getOpenCodeConfigByName(configName, userId)
|
||||
const previousContent = existingConfig?.content
|
||||
|
||||
const config = settingsService.updateOpenCodeConfig(configName, validated, userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
|
||||
if (config.isDefault) {
|
||||
const restartRequired = needsOpenCodeRestart(previousContent, config.content)
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
|
||||
if (restartRequired) {
|
||||
const contentToWrite = config.rawContent
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
logger.info('OpenCode configuration change requires a server restart; deferring until requested')
|
||||
opencodeServerManager.markRestartPending()
|
||||
return c.json({ ...config, restartRequired: true })
|
||||
} else {
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, config.content)
|
||||
if (!patchResult.success) {
|
||||
return c.json({
|
||||
error: 'Config saved but failed to apply',
|
||||
details: patchResult.error,
|
||||
validationIssues: patchResult.details,
|
||||
removedFields: patchResult.removedFields
|
||||
}, 500)
|
||||
}
|
||||
|
||||
const removedFields = patchResult.removedFields ?? []
|
||||
const contentToWrite = getOpenCodeConfigContentToWrite(
|
||||
config.rawContent,
|
||||
config.content,
|
||||
patchResult.appliedConfig,
|
||||
removedFields,
|
||||
)
|
||||
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
|
||||
if (removedFields.length > 0) {
|
||||
logger.info(`Config applied with auto-removed fields: ${removedFields.join(', ')}`)
|
||||
const persisted = settingsService.updateOpenCodeConfig(configName, { content: contentToWrite }, userId)
|
||||
if (!persisted) {
|
||||
return c.json({
|
||||
error: 'OpenCode config was removed while applying recovered fields',
|
||||
}, 409)
|
||||
}
|
||||
return c.json({ ...persisted, removedFields })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return c.json(config)
|
||||
} catch (error) {
|
||||
logger.error('Failed to update OpenCode config:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
|
||||
}
|
||||
return c.json({ error: 'Failed to update OpenCode config' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/opencode-configs/:name', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const configName = c.req.param('name')
|
||||
|
||||
const deleted = settingsService.deleteOpenCodeConfig(configName, userId)
|
||||
if (!deleted) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete OpenCode config:', error)
|
||||
return c.json({ error: 'Failed to delete OpenCode config' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/opencode-configs/:name/set-default', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const configName = c.req.param('name')
|
||||
|
||||
settingsService.saveLastKnownGoodConfig(userId)
|
||||
|
||||
const existingConfig = settingsService.getOpenCodeConfigByName(configName, userId)
|
||||
if (!existingConfig) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
|
||||
if (hasConfiguredPlugins(existingConfig.content)) {
|
||||
const contentToWrite = existingConfig.rawContent
|
||||
const config = settingsService.setDefaultOpenCodeConfig(configName, userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config '${configName}' to: ${configPath}`)
|
||||
opencodeServerManager.clearStartupError()
|
||||
const { restartFailed, restartError } = await restartOpenCodeAfterCommit(openCodeSupervisor)
|
||||
|
||||
return c.json(restartFailed ? { ...config, restartFailed, restartError } : config)
|
||||
}
|
||||
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, existingConfig.content)
|
||||
if (!patchResult.success) {
|
||||
return c.json({
|
||||
error: 'Config validation failed',
|
||||
details: patchResult.error,
|
||||
validationIssues: patchResult.details,
|
||||
removedFields: patchResult.removedFields
|
||||
}, 400)
|
||||
}
|
||||
|
||||
const contentToWrite = getOpenCodeConfigContentToWrite(
|
||||
existingConfig.rawContent,
|
||||
existingConfig.content,
|
||||
patchResult.appliedConfig,
|
||||
patchResult.removedFields,
|
||||
)
|
||||
const updatedConfig = settingsService.updateOpenCodeConfig(configName, {
|
||||
content: contentToWrite,
|
||||
}, userId)
|
||||
|
||||
if (!updatedConfig) {
|
||||
return c.json({ error: 'Failed to update OpenCode config' }, 500)
|
||||
}
|
||||
|
||||
const config = settingsService.setDefaultOpenCodeConfig(configName, userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Config not found' }, 404)
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Wrote default config '${configName}' to: ${configPath}`)
|
||||
|
||||
if (patchResult.removedFields && patchResult.removedFields.length > 0) {
|
||||
logger.info(`Config applied with auto-removed fields: ${patchResult.removedFields.join(', ')}`)
|
||||
return c.json({ ...config, removedFields: patchResult.removedFields })
|
||||
}
|
||||
|
||||
return c.json(config)
|
||||
} catch (error) {
|
||||
logger.error('Failed to set default OpenCode config:', error)
|
||||
return c.json({ error: 'Failed to set default OpenCode config' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/opencode-configs/default', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const config = settingsService.getDefaultOpenCodeConfig(userId)
|
||||
|
||||
if (!config) {
|
||||
return c.json({ error: 'No default config found' }, 404)
|
||||
}
|
||||
|
||||
return c.json(config)
|
||||
} catch (error) {
|
||||
logger.error('Failed to get default OpenCode config:', error)
|
||||
return c.json({ error: 'Failed to get default OpenCode config' }, 500)
|
||||
}
|
||||
})
|
||||
app.route('/opencode-config', createOpenCodeConfigRoutes(settingsService, openCodeClient))
|
||||
|
||||
app.post('/opencode-restart', async (c) => {
|
||||
try {
|
||||
@@ -772,14 +455,12 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
app.post('/opencode-import', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
const rawBody = c.req.header('content-type')?.includes('application/json') ? await c.req.json() : {}
|
||||
const body = SyncOpenCodeImportSchema.parse(rawBody)
|
||||
const result = await syncOpenCodeImport({
|
||||
db,
|
||||
userId,
|
||||
overwriteState: body.overwriteState ?? false,
|
||||
protectExistingState: true,
|
||||
settingsService,
|
||||
})
|
||||
|
||||
if (!result.configImported && !result.stateImported) {
|
||||
@@ -860,31 +541,21 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
app.post('/opencode-rollback', async (c) => {
|
||||
try {
|
||||
const userId = c.req.query('userId') || 'default'
|
||||
logger.info('OpenCode config rollback requested')
|
||||
|
||||
const rollbackConfig = settingsService.rollbackToLastKnownGoodHealth(userId)
|
||||
if (!rollbackConfig) {
|
||||
const restored = await restoreLastKnownGoodOpenCodeConfig(settingsService)
|
||||
if (!restored) {
|
||||
return c.json({ error: 'No previous working config available for rollback' }, 404)
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const config = settingsService.getDefaultOpenCodeConfig(userId)
|
||||
if (!config) {
|
||||
return c.json({ error: 'Failed to get default config after rollback' }, 500)
|
||||
}
|
||||
logger.info('Rolled back to the previous working config')
|
||||
|
||||
const contentToWrite = config.rawContent
|
||||
await writeFileContent(configPath, contentToWrite)
|
||||
logger.info(`Rolled back to config '${rollbackConfig}'`)
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
try {
|
||||
await reloadOpenCodeConfig(openCodeSupervisor)
|
||||
} catch (reloadError) {
|
||||
logger.error('Rollback config reload failed, attempting restart:', reloadError)
|
||||
|
||||
const deleted = settingsService.deleteFilesystemConfig()
|
||||
const deleted = await deleteOpenCodeConfigFile()
|
||||
if (deleted) {
|
||||
logger.info('Deleted filesystem config, attempting restart with fallback')
|
||||
await new Promise(r => setTimeout(r, 1000))
|
||||
@@ -894,9 +565,8 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
message: `Server restarted after deleting problematic config. DB config '${rollbackConfig}' preserved for manual recovery.`,
|
||||
message: 'Server restarted after deleting the broken config file. The previous working config remains available for rollback.',
|
||||
fallback: true,
|
||||
configName: rollbackConfig
|
||||
})
|
||||
}
|
||||
|
||||
@@ -908,8 +578,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
|
||||
|
||||
return c.json({
|
||||
success: true,
|
||||
message: `Server reloaded with previous working config: ${rollbackConfig}`,
|
||||
configName: rollbackConfig
|
||||
message: 'Server reloaded with the previous working config',
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Failed to rollback OpenCode config:', error)
|
||||
|
||||
@@ -4,10 +4,12 @@ import { readdir, stat, unlink } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { logger } from '../utils/logger'
|
||||
import { canonicalPath } from '../utils/fs-safe'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
|
||||
function resolvePath(userPath: string): string {
|
||||
return path.isAbsolute(userPath) ? userPath : path.join(getReposPath(), userPath)
|
||||
async function resolvePath(userPath: string): Promise<string> {
|
||||
const absolutePath = path.isAbsolute(userPath) ? userPath : path.join(getReposPath(), userPath)
|
||||
return canonicalPath(absolutePath)
|
||||
}
|
||||
|
||||
export interface ArchiveOptions {
|
||||
@@ -205,7 +207,7 @@ async function filterIgnoredPaths(targetPath: string, allPaths: string[], option
|
||||
}
|
||||
|
||||
export async function createRepoArchive(repoPath: string, options?: ArchiveOptions): Promise<string> {
|
||||
repoPath = resolvePath(repoPath)
|
||||
repoPath = await resolvePath(repoPath)
|
||||
const repoName = path.basename(repoPath)
|
||||
const tempFile = path.join(os.tmpdir(), `${repoName}-${Date.now()}.zip`)
|
||||
|
||||
@@ -243,7 +245,7 @@ export async function createRepoArchive(repoPath: string, options?: ArchiveOptio
|
||||
}
|
||||
|
||||
export async function createDirectoryArchive(directoryPath: string, archiveName?: string, options?: ArchiveOptions): Promise<string> {
|
||||
directoryPath = resolvePath(directoryPath)
|
||||
directoryPath = await resolvePath(directoryPath)
|
||||
const dirName = archiveName || path.basename(directoryPath)
|
||||
const tempFile = path.join(os.tmpdir(), `${dirName}-${Date.now()}.zip`)
|
||||
|
||||
@@ -300,7 +302,7 @@ export async function getArchiveSize(filePath: string): Promise<number> {
|
||||
}
|
||||
|
||||
export async function getIgnoredPathsList(directoryPath: string): Promise<string[]> {
|
||||
directoryPath = resolvePath(directoryPath)
|
||||
directoryPath = await resolvePath(directoryPath)
|
||||
logger.debug('[getIgnoredPathsList] Starting for:', directoryPath)
|
||||
const gitRoot = await findGitRoot(directoryPath)
|
||||
logger.debug('[getIgnoredPathsList] Git root:', gitRoot)
|
||||
|
||||
@@ -335,7 +335,7 @@ Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs
|
||||
{
|
||||
action: 'request',
|
||||
params: {
|
||||
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
|
||||
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
|
||||
path: string // relative internal API path; query strings allowed
|
||||
body?: object // JSON body for POST and PATCH routes
|
||||
}
|
||||
@@ -575,7 +575,7 @@ Sending is rate limited to **10 notifications per minute**. Beyond that the tool
|
||||
export function buildSettingsSkill(): string {
|
||||
return `---
|
||||
name: manager-settings
|
||||
description: Read and modify safe user preferences with the ${MANAGER_TOOL_NAME} tool
|
||||
description: Read and modify safe user preferences and the OpenCode configuration file with the ${MANAGER_TOOL_NAME} tool
|
||||
---
|
||||
|
||||
## When to Load
|
||||
@@ -591,7 +591,7 @@ Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs
|
||||
{
|
||||
action: 'request',
|
||||
params: {
|
||||
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
|
||||
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
|
||||
path: string // relative internal API path; query strings allowed
|
||||
body?: object // JSON body for POST and PATCH routes
|
||||
}
|
||||
@@ -713,10 +713,73 @@ Reload the assistant workspace by disposing the current OpenCode instance. Use t
|
||||
{ "success": true }
|
||||
\`\`\`
|
||||
|
||||
## OpenCode Configuration
|
||||
|
||||
The OpenCode configuration file on disk is the source of truth, and this endpoint is the only supported way to change it. Never edit \`opencode.json\` directly.
|
||||
|
||||
### GET /opencode-config
|
||||
|
||||
Read the current configuration file. Returns \`404\` when no config file exists yet.
|
||||
|
||||
**Response (\`OpenCodeConfigFile\`):**
|
||||
\`\`\`ts
|
||||
{
|
||||
path: string // Absolute path of the configuration file
|
||||
content: object // Parsed configuration
|
||||
rawContent: string // Raw file content, including comments
|
||||
isValid: boolean // Whether the file passes schema validation
|
||||
validationIssues?: Array<{ path: string, message: string }>
|
||||
updatedAt: number // Unix timestamp of the last write
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
**Example:**
|
||||
\`\`\`json
|
||||
{
|
||||
"action": "request",
|
||||
"params": {
|
||||
"method": "GET",
|
||||
"path": "/opencode-config"
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
### PUT /opencode-config
|
||||
|
||||
Persist a complete configuration. Read the file first, change only the keys the user asked for, and send the complete object back.
|
||||
|
||||
**Request Body:**
|
||||
\`\`\`ts
|
||||
{ content: object } // The complete configuration to persist
|
||||
\`\`\`
|
||||
|
||||
**Example:**
|
||||
\`\`\`json
|
||||
{
|
||||
"action": "request",
|
||||
"params": {
|
||||
"method": "PUT",
|
||||
"path": "/opencode-config",
|
||||
"body": {
|
||||
"content": {
|
||||
"theme": "dark"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
**Response:**
|
||||
Returns the written \`OpenCodeConfigFile\`. Adds \`restartRequired: true\` when the change needs an OpenCode server restart, and \`removedFields\` when OpenCode dropped fields it does not accept.
|
||||
|
||||
Returns \`400\` with \`validationIssues\` when OpenCode rejects the configuration.
|
||||
|
||||
When the response contains \`restartRequired: true\`, tell the user to restart the OpenCode server from Settings. Never attempt the restart yourself: it would terminate your own session.
|
||||
|
||||
## Safety
|
||||
|
||||
- This API intentionally rejects any attempt to modify credentials, API keys, or other sensitive settings
|
||||
- If you need to change credentials (Git, TTS, STT, etc.), guide the user to use the full UI
|
||||
- The settings PATCH endpoint rejects any attempt to modify credentials, API keys, or other sensitive settings; guide the user to the full UI for Git, TTS, and STT credentials
|
||||
- PUT /opencode-config writes the complete OpenCode configuration, including \`plugin\`, \`mcp\`, and \`provider\` entries; change only the keys the user explicitly asked for and never add plugins, MCP servers, or provider credentials the user did not request
|
||||
- The settings PATCH endpoint does NOT trigger OpenCode reload or restart
|
||||
`
|
||||
}
|
||||
@@ -740,7 +803,7 @@ Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs
|
||||
{
|
||||
action: 'request',
|
||||
params: {
|
||||
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
|
||||
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
|
||||
path: string // relative internal API path; query strings allowed
|
||||
body?: object // JSON body for POST and PATCH routes
|
||||
}
|
||||
@@ -779,7 +842,6 @@ List all repos available to OpenCode Manager. The repos are returned in the orde
|
||||
clonedAt: number // Unix timestamp
|
||||
lastPulled?: number
|
||||
lastAccessedAt?: number
|
||||
openCodeConfigName?: string
|
||||
isWorktree?: boolean
|
||||
isLocal?: boolean
|
||||
}>
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import type { OpenCodeConfigFile, OpenCodeConfigInput } from '../types/settings'
|
||||
import { OPENCODE_CONFIG_SEED, normalizeOpenCodeConfigContent, readOpenCodeConfigFile, withOpenCodeConfigLock, writeOpenCodeConfigFile } from './opencode-config-file'
|
||||
import { patchConfigWithRecovery, type PatchConfigValidationIssue } from './opencode/config-recovery'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { opencodeServerManager } from './opencode-single-server'
|
||||
import type { SettingsService } from './settings'
|
||||
|
||||
export type ApplyOpenCodeConfigResult =
|
||||
| { status: 'restart_pending'; config: OpenCodeConfigFile }
|
||||
| { status: 'applied'; config: OpenCodeConfigFile; removedFields: string[] }
|
||||
| { status: 'rejected'; error: string; validationIssues: PatchConfigValidationIssue[]; removedFields: string[] }
|
||||
|
||||
export interface ApplyOpenCodeConfigInput {
|
||||
content: OpenCodeConfigInput | string
|
||||
openCodeClient: OpenCodeClient
|
||||
settingsService: SettingsService
|
||||
}
|
||||
|
||||
export async function captureLastKnownGoodOpenCodeConfig(settingsService: SettingsService): Promise<OpenCodeConfigFile | null> {
|
||||
const previous = await readOpenCodeConfigFile()
|
||||
if (previous?.isValid) {
|
||||
settingsService.saveLastKnownGoodConfig(previous.rawContent)
|
||||
}
|
||||
return previous
|
||||
}
|
||||
|
||||
export async function restoreLastKnownGoodOpenCodeConfig(settingsService: SettingsService): Promise<OpenCodeConfigFile | null> {
|
||||
const lastGood = settingsService.getLastKnownGoodConfig()
|
||||
if (!lastGood) {
|
||||
return null
|
||||
}
|
||||
|
||||
const config = await withOpenCodeConfigLock(() => writeOpenCodeConfigFile(lastGood))
|
||||
opencodeServerManager.clearStartupError()
|
||||
return config
|
||||
}
|
||||
|
||||
export async function seedOpenCodeConfigFile(): Promise<OpenCodeConfigFile> {
|
||||
return withOpenCodeConfigLock(() => writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED))
|
||||
}
|
||||
|
||||
function didConfigFieldChange(
|
||||
previous: Record<string, unknown> | undefined,
|
||||
next: Record<string, unknown> | undefined,
|
||||
field: string,
|
||||
): boolean {
|
||||
return JSON.stringify(previous?.[field]) !== JSON.stringify(next?.[field])
|
||||
}
|
||||
|
||||
function needsOpenCodeRestart(
|
||||
previous: Record<string, unknown> | undefined,
|
||||
next: Record<string, unknown> | undefined,
|
||||
): boolean {
|
||||
return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field))
|
||||
}
|
||||
|
||||
export function toOpenCodeConfigApplyResponse(
|
||||
result: ApplyOpenCodeConfigResult,
|
||||
): { status: 200 | 400; body: Record<string, unknown> } {
|
||||
if (result.status === 'restart_pending') {
|
||||
return { status: 200, body: { ...result.config, restartRequired: true } }
|
||||
}
|
||||
|
||||
if (result.status === 'applied') {
|
||||
return {
|
||||
status: 200,
|
||||
body: result.removedFields.length > 0
|
||||
? { ...result.config, removedFields: result.removedFields }
|
||||
: { ...result.config },
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: 400,
|
||||
body: {
|
||||
error: 'Config validation failed',
|
||||
details: result.error,
|
||||
validationIssues: result.validationIssues,
|
||||
removedFields: result.removedFields,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyOpenCodeConfigUpdate(
|
||||
input: ApplyOpenCodeConfigInput,
|
||||
): Promise<ApplyOpenCodeConfigResult> {
|
||||
return withOpenCodeConfigLock(async () => {
|
||||
const { content, openCodeClient, settingsService } = input
|
||||
|
||||
const rawContent = normalizeOpenCodeConfigContent(content)
|
||||
const nextContent = OpenCodeConfigSchema.parse(parseJsonc(rawContent))
|
||||
|
||||
const previous = await captureLastKnownGoodOpenCodeConfig(settingsService)
|
||||
|
||||
if (needsOpenCodeRestart(previous?.content, nextContent)) {
|
||||
const config = await writeOpenCodeConfigFile(rawContent)
|
||||
opencodeServerManager.markRestartPending()
|
||||
return { status: 'restart_pending', config }
|
||||
}
|
||||
|
||||
const patchResult = await patchConfigWithRecovery(openCodeClient, nextContent)
|
||||
if (!patchResult.success) {
|
||||
return {
|
||||
status: 'rejected',
|
||||
error: patchResult.error ?? 'Config validation failed',
|
||||
validationIssues: patchResult.details ?? [],
|
||||
removedFields: patchResult.removedFields ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
const removedFields = patchResult.removedFields ?? []
|
||||
const contentToWrite = removedFields.length > 0
|
||||
? JSON.stringify(patchResult.appliedConfig ?? nextContent, null, 2)
|
||||
: rawContent
|
||||
const config = await writeOpenCodeConfigFile(contentToWrite)
|
||||
|
||||
return { status: 'applied', config, removedFields }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { readdir, rm, stat } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import type { ZodIssue } from 'zod'
|
||||
import { getOpenCodeConfigFilePath, getOpenCodeHealthWatchPath } from '@opencode-manager/shared/config/env'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import type { OpenCodeConfigFile, OpenCodeConfigInput, OpenCodeConfigValidationIssue } from '../types/settings'
|
||||
import { logger } from '../utils/logger'
|
||||
import { withFileLock } from '../utils/atomic-json'
|
||||
import { existingFileMode, writeFileAtomic } from '../utils/fs-safe'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent } from './file-operations'
|
||||
|
||||
export const OPENCODE_CONFIG_SEED = JSON.stringify({ $schema: 'https://opencode.ai/config.json' }, null, 2)
|
||||
|
||||
export const HEALTH_WATCH_MAX_ENTRIES = 20
|
||||
|
||||
export function withOpenCodeConfigLock<T>(fn: () => Promise<T>): Promise<T> {
|
||||
return withFileLock(getOpenCodeConfigFilePath(), fn)
|
||||
}
|
||||
|
||||
interface OpenCodeConfigParseResult {
|
||||
content: Record<string, unknown>
|
||||
isValid: boolean
|
||||
validationIssues?: OpenCodeConfigValidationIssue[]
|
||||
}
|
||||
|
||||
export function normalizeOpenCodeConfigContent(content: OpenCodeConfigInput | string): string {
|
||||
return typeof content === 'string' ? content : JSON.stringify(content, null, 2)
|
||||
}
|
||||
|
||||
export function toOpenCodeConfigValidationIssues(issues: ZodIssue[]): OpenCodeConfigValidationIssue[] {
|
||||
return issues.map((issue) => ({
|
||||
path: issue.path.length > 0 ? issue.path.join('.') : 'root',
|
||||
message: issue.message,
|
||||
}))
|
||||
}
|
||||
|
||||
export function parseOpenCodeConfigContent(rawContent: string): OpenCodeConfigParseResult {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = parseJsonc(rawContent)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Invalid JSONC'
|
||||
logger.error(`Failed to parse OpenCode config: ${message}`)
|
||||
return {
|
||||
content: {},
|
||||
isValid: false,
|
||||
validationIssues: [{ path: 'root', message }],
|
||||
}
|
||||
}
|
||||
|
||||
const content = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||||
? parsed as Record<string, unknown>
|
||||
: {}
|
||||
|
||||
const validated = OpenCodeConfigSchema.safeParse(parsed)
|
||||
if (validated.success) {
|
||||
return {
|
||||
content: validated.data as Record<string, unknown>,
|
||||
isValid: true,
|
||||
}
|
||||
}
|
||||
|
||||
const validationIssues = toOpenCodeConfigValidationIssues(validated.error.issues)
|
||||
logger.error(`Failed to validate OpenCode config: ${validationIssues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`)
|
||||
|
||||
return {
|
||||
content,
|
||||
isValid: false,
|
||||
validationIssues,
|
||||
}
|
||||
}
|
||||
|
||||
export async function readOpenCodeConfigFile(): Promise<OpenCodeConfigFile | null> {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
|
||||
let updatedAt: number
|
||||
try {
|
||||
const stats = await stat(configPath)
|
||||
updatedAt = stats.mtimeMs
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return null
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
const rawContent = await readFileContent(configPath)
|
||||
|
||||
return {
|
||||
path: configPath,
|
||||
rawContent,
|
||||
...parseOpenCodeConfigContent(rawContent),
|
||||
updatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeOpenCodeConfigFile(rawContent: string): Promise<OpenCodeConfigFile> {
|
||||
const parsed = OpenCodeConfigSchema.parse(parseJsonc(rawContent))
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileAtomic(configPath, rawContent, { mode: await existingFileMode(configPath) })
|
||||
|
||||
const stats = await stat(configPath)
|
||||
|
||||
return {
|
||||
path: configPath,
|
||||
rawContent,
|
||||
content: parsed as Record<string, unknown>,
|
||||
isValid: true,
|
||||
updatedAt: stats.mtimeMs,
|
||||
}
|
||||
}
|
||||
|
||||
export async function pruneHealthWatchDirectory(dirPath: string): Promise<void> {
|
||||
try {
|
||||
const entries = await readdir(dirPath, { withFileTypes: true })
|
||||
const files = await Promise.all(
|
||||
entries
|
||||
.filter((entry) => entry.isFile())
|
||||
.map(async (entry) => {
|
||||
const filePath = path.join(dirPath, entry.name)
|
||||
const fileStats = await stat(filePath)
|
||||
return { filePath, mtimeMs: fileStats.mtimeMs }
|
||||
}),
|
||||
)
|
||||
|
||||
if (files.length <= HEALTH_WATCH_MAX_ENTRIES) return
|
||||
|
||||
files.sort((left, right) => right.mtimeMs - left.mtimeMs)
|
||||
await Promise.all(
|
||||
files.slice(HEALTH_WATCH_MAX_ENTRIES).map((file) => rm(file.filePath, { force: true })),
|
||||
)
|
||||
} catch (error) {
|
||||
logger.warn('Failed to prune OpenCode health-watch directory:', error)
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeHealthWatchArtifact(
|
||||
prefix: string,
|
||||
buildContent: (timestamp: string) => string,
|
||||
): Promise<string> {
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
|
||||
const artifactPath = path.join(getOpenCodeHealthWatchPath(), `${prefix}-${timestamp}.json`)
|
||||
await ensureDirectoryExists(getOpenCodeHealthWatchPath())
|
||||
await writeFileContent(artifactPath, buildContent(timestamp))
|
||||
await pruneHealthWatchDirectory(getOpenCodeHealthWatchPath())
|
||||
return artifactPath
|
||||
}
|
||||
|
||||
export async function archiveBrokenOpenCodeConfigFile(): Promise<string | null> {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
if (!(await fileExists(configPath))) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const content = await readFileContent(configPath)
|
||||
const archivePath = await writeHealthWatchArtifact('opencode-config-broken', () => content)
|
||||
logger.warn(`Archived broken OpenCode config to ${archivePath}`)
|
||||
return archivePath
|
||||
} catch (error) {
|
||||
logger.error('Failed to archive broken OpenCode config:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteOpenCodeConfigFile(): Promise<boolean> {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
|
||||
if (!(await fileExists(configPath))) {
|
||||
logger.warn('Config file does not exist:', configPath)
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
await rm(configPath, { force: true })
|
||||
logger.info('Deleted filesystem config to allow server startup:', configPath)
|
||||
return true
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete config file:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { cp, mkdtemp, readdir, rename, rm } from 'fs/promises'
|
||||
import { Database as SQLiteDatabase, type Database } from 'bun:sqlite'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { Database as SQLiteDatabase } from 'bun:sqlite'
|
||||
import { getOpenCodeConfigFilePath, getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import { parse as parseJsonc } from 'jsonc-parser'
|
||||
import { SettingsService } from './settings'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent } from './file-operations'
|
||||
import { parseOpenCodeConfigContent, withOpenCodeConfigLock, writeOpenCodeConfigFile } from './opencode-config-file'
|
||||
import { captureLastKnownGoodOpenCodeConfig } from './opencode-config-apply'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent } from './file-operations'
|
||||
import type { SettingsService } from './settings'
|
||||
|
||||
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
|
||||
|
||||
@@ -19,10 +20,11 @@ export interface OpenCodeImportStatus {
|
||||
}
|
||||
|
||||
export interface SyncOpenCodeImportOptions {
|
||||
db: Database
|
||||
userId?: string
|
||||
overwriteState?: boolean
|
||||
protectExistingState?: boolean
|
||||
importConfig?: boolean
|
||||
status?: OpenCodeImportStatus
|
||||
settingsService?: SettingsService
|
||||
}
|
||||
|
||||
export interface SyncOpenCodeImportResult extends OpenCodeImportStatus {
|
||||
@@ -53,14 +55,11 @@ export function getImportPathCandidates(envKey: string, fallbackPath: string): s
|
||||
return Array.from(new Set(candidates))
|
||||
}
|
||||
|
||||
export async function getFirstExistingPath(paths: string[]): Promise<string | null> {
|
||||
for (const candidate of paths) {
|
||||
if (await fileExists(candidate)) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
export function getFirstExistingConfigSourcePath(): string | null {
|
||||
return getImportPathCandidates(
|
||||
'OPENCODE_IMPORT_CONFIG_PATH',
|
||||
path.join(os.homedir(), '.config', 'opencode', 'opencode.json')
|
||||
).find(candidate => existsSync(candidate)) ?? null
|
||||
}
|
||||
|
||||
async function getFirstExistingPathWithDatabase(paths: string[]): Promise<string | null> {
|
||||
@@ -140,9 +139,7 @@ export async function getOpenCodeImportStatus(): Promise<OpenCodeImportStatus> {
|
||||
const workspaceStatePath = path.join(getWorkspacePath(), '.opencode', 'state', 'opencode')
|
||||
const workspaceStateExists = await fileExists(path.join(workspaceStatePath, 'opencode.db'))
|
||||
|
||||
const configSourcePath = await getFirstExistingPath(
|
||||
getImportPathCandidates('OPENCODE_IMPORT_CONFIG_PATH', path.join(os.homedir(), '.config', 'opencode', 'opencode.json'))
|
||||
)
|
||||
const configSourcePath = getFirstExistingConfigSourcePath()
|
||||
const stateSourcePath = await getFirstExistingPathWithDatabase(
|
||||
getImportPathCandidates('OPENCODE_IMPORT_STATE_PATH', path.join(os.homedir(), '.local', 'share', 'opencode'))
|
||||
)
|
||||
@@ -156,38 +153,25 @@ export async function getOpenCodeImportStatus(): Promise<OpenCodeImportStatus> {
|
||||
}
|
||||
}
|
||||
|
||||
async function importOpenCodeConfigFromSource(db: Database, userId: string, sourcePath: string, workspaceConfigPath: string): Promise<boolean> {
|
||||
async function importOpenCodeConfigFromSource(sourcePath: string, settingsService?: SettingsService): Promise<boolean> {
|
||||
const rawContent = await readFileContent(sourcePath)
|
||||
const parsed = parseJsonc(rawContent)
|
||||
const validation = OpenCodeConfigSchema.safeParse(parsed)
|
||||
const { isValid } = parseOpenCodeConfigContent(rawContent)
|
||||
|
||||
if (!validation.success) {
|
||||
if (!isValid) {
|
||||
throw new Error('Importable OpenCode config is invalid')
|
||||
}
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
const existingDefault = settingsService.getOpenCodeConfigByName('default', userId)
|
||||
|
||||
if (existingDefault) {
|
||||
settingsService.updateOpenCodeConfig('default', {
|
||||
content: rawContent,
|
||||
isDefault: true,
|
||||
}, userId)
|
||||
} else {
|
||||
settingsService.createOpenCodeConfig({
|
||||
name: 'default',
|
||||
content: rawContent,
|
||||
isDefault: true,
|
||||
}, userId)
|
||||
}
|
||||
|
||||
await writeFileContent(workspaceConfigPath, rawContent)
|
||||
await withOpenCodeConfigLock(async () => {
|
||||
if (settingsService) {
|
||||
await captureLastKnownGoodOpenCodeConfig(settingsService)
|
||||
}
|
||||
await writeOpenCodeConfigFile(rawContent)
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
export async function syncOpenCodeImport(options: SyncOpenCodeImportOptions): Promise<SyncOpenCodeImportResult> {
|
||||
const initialStatus = await getOpenCodeImportStatus()
|
||||
const userId = options.userId || 'default'
|
||||
const initialStatus = options.status ?? await getOpenCodeImportStatus()
|
||||
const overwriteState = options.overwriteState === true
|
||||
let configImported = false
|
||||
let stateImported = false
|
||||
@@ -198,8 +182,8 @@ export async function syncOpenCodeImport(options: SyncOpenCodeImportOptions): Pr
|
||||
)
|
||||
}
|
||||
|
||||
if (initialStatus.configSourcePath) {
|
||||
configImported = await importOpenCodeConfigFromSource(options.db, userId, initialStatus.configSourcePath, initialStatus.workspaceConfigPath)
|
||||
if (options.importConfig !== false && initialStatus.configSourcePath) {
|
||||
configImported = await importOpenCodeConfigFromSource(initialStatus.configSourcePath, options.settingsService)
|
||||
}
|
||||
|
||||
if (initialStatus.stateSourcePath && (overwriteState || !initialStatus.workspaceStateExists)) {
|
||||
|
||||
@@ -7,6 +7,8 @@ export const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 15000
|
||||
export const MANAGER_TOOL_ALLOWED_ROUTES = [
|
||||
'GET /settings',
|
||||
'PATCH /settings',
|
||||
'GET /opencode-config',
|
||||
'PUT /opencode-config',
|
||||
'POST /assistant/reload',
|
||||
'GET /repos',
|
||||
'GET /repos/*/git-info',
|
||||
@@ -26,7 +28,7 @@ export const MANAGER_TOOL_ALLOWED_ROUTES = [
|
||||
'POST /repos/*/schedules/*/runs/*/cancel',
|
||||
] as const
|
||||
|
||||
export const MANAGER_TOOL_ALLOWED_METHODS = ['GET', 'POST', 'PATCH', 'DELETE'] as const
|
||||
export const MANAGER_TOOL_ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const
|
||||
|
||||
export function parseAllowedRoute(route: string): { method: string; path: string } {
|
||||
const separator = route.indexOf(' ')
|
||||
@@ -159,7 +161,7 @@ export default async function () {
|
||||
'The action runs inside OpenCode Manager itself, so it needs no token and no network access from the agent shell, and it works in sandboxed sessions and scheduled runs.',
|
||||
'Actions:',
|
||||
'- send_notification: send a push notification to every device the user has registered.',
|
||||
'- request: call an allow-listed internal API route to read and manage settings, repos, OpenCode workspaces, and schedules.',
|
||||
'- request: call an allow-listed internal API route to read and manage settings, the OpenCode configuration file, repos, OpenCode workspaces, and schedules.',
|
||||
'Allowed request routes:',
|
||||
].concat(ALLOWED_ROUTES.map(function (route) { return '- ' + route })).join('\\n'),
|
||||
args: {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { z } from 'zod'
|
||||
import { getOpenCodeModelStatePath } from '@opencode-manager/shared/config/env'
|
||||
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> {
|
||||
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 }
|
||||
}
|
||||
|
||||
export async function updateOpenCodeModelState(
|
||||
mutate: (state: OpenCodeModelStateRecord) => OpenCodeModelStateRecord,
|
||||
): Promise<OpenCodeModelStateRecord> {
|
||||
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>
|
||||
: {}
|
||||
|
||||
await writeJsonAtomic(modelStatePath, {
|
||||
...rawObject,
|
||||
recent: next.recent,
|
||||
favorite: next.favorite,
|
||||
variant: next.variant,
|
||||
})
|
||||
|
||||
return next
|
||||
})
|
||||
}
|
||||
@@ -3,7 +3,8 @@ import { lstat, realpath } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
|
||||
import { existingFileMode, mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
|
||||
import { withFileLock } from '../utils/atomic-json'
|
||||
import { getOpenCodePluginDir } from './opencode/plugin-registry'
|
||||
import {
|
||||
isRecord,
|
||||
@@ -242,14 +243,6 @@ async function restorePluginEntries(dir: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function existingFileMode(filePath: string): Promise<number | undefined> {
|
||||
try {
|
||||
return (await fs.stat(filePath)).mode & 0o777
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreEnforcementConfigSections(configPath: string): Promise<void> {
|
||||
const backupPath = `${configPath}${PLUGIN_CONFIG_BACKUP_SUFFIX}`
|
||||
if (!(await pathExists(backupPath))) return
|
||||
@@ -293,7 +286,8 @@ async function restoreEnforcementConfigSections(configPath: string): Promise<voi
|
||||
const restored = restoreEnforcementSections(currentConfig, removed)
|
||||
const restoredContent = JSON.stringify(restored, null, 2)
|
||||
if (restoredContent !== currentContent) {
|
||||
await writeFileAtomic(configPath, restoredContent, { mode: await existingFileMode(configPath) })
|
||||
const mode = await existingFileMode(configPath)
|
||||
await withFileLock(configPath, () => writeFileAtomic(configPath, restoredContent, { mode }))
|
||||
}
|
||||
await fs.rm(backupPath, { force: true })
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { opencodeServerManager } from './opencode-single-server'
|
||||
import type { OpenCodeSupervisor } from './opencode-supervisor'
|
||||
import type { OpenCodeRestartCoordinator } from './opencode-restart-coordinator'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
let restartCoordinator: OpenCodeRestartCoordinator | null = null
|
||||
|
||||
@@ -68,19 +67,6 @@ export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<
|
||||
return { resumedSessionIDs: [] }
|
||||
}
|
||||
|
||||
export async function restartOpenCodeAfterCommit(
|
||||
supervisor?: OpenCodeSupervisor,
|
||||
): Promise<{ restartFailed: boolean; restartError?: string }> {
|
||||
try {
|
||||
await restartOpenCode(supervisor)
|
||||
return { restartFailed: false }
|
||||
} catch (error) {
|
||||
const restartError = error instanceof Error ? error.message : String(error)
|
||||
logger.error('OpenCode restart failed after the change was persisted', error)
|
||||
return { restartFailed: true, restartError }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads OpenCode configuration via the non-disruptive API patch. This does
|
||||
* NOT drop the server process, so active sessions keep running and there is
|
||||
|
||||
@@ -26,12 +26,17 @@ import {
|
||||
getOpenCodeTmpHome,
|
||||
ENV,
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { ZodError } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { compareVersions } from '../utils/version-utils'
|
||||
import { patchConfigWithRecovery } from './opencode/config-recovery'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { writeFileContent } from './file-operations'
|
||||
import {
|
||||
readOpenCodeConfigFile,
|
||||
toOpenCodeConfigValidationIssues,
|
||||
withOpenCodeConfigLock,
|
||||
writeOpenCodeConfigFile,
|
||||
} from './opencode-config-file'
|
||||
import { getOrCreateInternalToken } from './internal-token'
|
||||
import { installManagedPlugins } from './opencode/plugin-registry'
|
||||
import { getOpenCodePluginDiscoveryHome, restoreQuarantinedOpenCodePlugins } from './opencode-plugin-quarantine'
|
||||
@@ -615,7 +620,7 @@ class OpenCodeServerManager {
|
||||
}
|
||||
logger.warn('Failed to install a generated OpenCode plugin (sandboxing is disabled):', error)
|
||||
}
|
||||
const configuredPlugins = await this.getConfiguredPlugins(openCodeConfigPath)
|
||||
const configuredPlugins = await this.getConfiguredPlugins()
|
||||
await this.installConfiguredPlugins(configuredPlugins)
|
||||
const configuredPluginCount = configuredPlugins.length
|
||||
const openCodeExecutable = resolveOpenCodeExecutable() ?? 'opencode'
|
||||
@@ -957,13 +962,13 @@ class OpenCodeServerManager {
|
||||
return options !== null && typeof options === 'object' && !Array.isArray(options)
|
||||
}
|
||||
|
||||
private async getConfiguredPlugins(configPath: string): Promise<OpenCodePluginSpec[]> {
|
||||
private async getConfiguredPlugins(): Promise<OpenCodePluginSpec[]> {
|
||||
try {
|
||||
const content = await fs.readFile(configPath, 'utf-8')
|
||||
const config = parseJsonc(content) as { plugin?: unknown }
|
||||
if (!Array.isArray(config.plugin)) return []
|
||||
return config.plugin
|
||||
.filter((plugin): plugin is OpenCodePluginSpec => this.isOpenCodePluginSpec(plugin))
|
||||
const file = await readOpenCodeConfigFile()
|
||||
const plugin = file?.content.plugin
|
||||
if (!Array.isArray(plugin)) return []
|
||||
return plugin
|
||||
.filter((entry): entry is OpenCodePluginSpec => this.isOpenCodePluginSpec(entry))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
@@ -1043,31 +1048,44 @@ class OpenCodeServerManager {
|
||||
try {
|
||||
logger.info('Reloading OpenCode configuration (via API)')
|
||||
try {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const fileContent = await fs.readFile(configPath, 'utf-8')
|
||||
const fileConfig = parseJsonc(fileContent) as Record<string, unknown>
|
||||
logger.info(`Read config from file for reload: ${configPath}`)
|
||||
|
||||
const patchTarget = fileConfig
|
||||
const patchResult = await patchConfigWithRecovery(this.requireClient(), patchTarget)
|
||||
if (!patchResult.success) {
|
||||
const errorMessage = patchResult.error || 'Failed to reload config'
|
||||
const validationIssues = patchResult.details || []
|
||||
const removedFields = patchResult.removedFields || []
|
||||
if (validationIssues.length > 0) {
|
||||
const issueSummary = validationIssues.map((d) => `${d.path}: ${d.message}`).join('; ')
|
||||
logger.error(`Config reload validation errors: ${issueSummary}`)
|
||||
await withOpenCodeConfigLock(async () => {
|
||||
const file = await readOpenCodeConfigFile()
|
||||
if (file === null) {
|
||||
throw new Error(`OpenCode config file not found: ${getOpenCodeConfigFilePath()}`)
|
||||
}
|
||||
if (removedFields.length > 0) {
|
||||
logger.info(`Removed fields during config reload: ${removedFields.join(', ')}`)
|
||||
}
|
||||
throw new ConfigReloadError(errorMessage, validationIssues, removedFields)
|
||||
}
|
||||
logger.info(`Read config from file for reload: ${file.path}`)
|
||||
|
||||
if (patchResult.removedFields && patchResult.removedFields.length > 0 && patchResult.appliedConfig) {
|
||||
await writeFileContent(configPath, JSON.stringify(patchResult.appliedConfig, null, 2))
|
||||
logger.info(`Persisted cleaned config to ${configPath} after removing fields: ${patchResult.removedFields.join(', ')}`)
|
||||
}
|
||||
const patchResult = await patchConfigWithRecovery(this.requireClient(), file.content)
|
||||
if (!patchResult.success) {
|
||||
const errorMessage = patchResult.error || 'Failed to reload config'
|
||||
const validationIssues = patchResult.details || []
|
||||
const removedFields = patchResult.removedFields || []
|
||||
if (validationIssues.length > 0) {
|
||||
const issueSummary = validationIssues.map((d) => `${d.path}: ${d.message}`).join('; ')
|
||||
logger.error(`Config reload validation errors: ${issueSummary}`)
|
||||
}
|
||||
if (removedFields.length > 0) {
|
||||
logger.info(`Removed fields during config reload: ${removedFields.join(', ')}`)
|
||||
}
|
||||
throw new ConfigReloadError(errorMessage, validationIssues, removedFields)
|
||||
}
|
||||
|
||||
if (patchResult.removedFields && patchResult.removedFields.length > 0 && patchResult.appliedConfig) {
|
||||
const cleanedConfigContent = JSON.stringify(patchResult.appliedConfig, null, 2)
|
||||
try {
|
||||
await writeOpenCodeConfigFile(cleanedConfigContent)
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
const validationIssues = toOpenCodeConfigValidationIssues(error.issues)
|
||||
const issueSummary = validationIssues.map((d) => `${d.path}: ${d.message}`).join('; ')
|
||||
logger.error(`Config reload validation errors: ${issueSummary}`)
|
||||
throw new ConfigReloadError('Cleaned config failed validation', validationIssues, patchResult.removedFields)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
logger.info(`Persisted cleaned config to ${file.path} after removing fields: ${patchResult.removedFields.join(', ')}`)
|
||||
}
|
||||
})
|
||||
|
||||
logger.info('OpenCode configuration reloaded successfully')
|
||||
await new Promise(r => setTimeout(r, 500))
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import path from 'path'
|
||||
import type { SettingsService } from './settings'
|
||||
import { logger } from '../utils/logger'
|
||||
import { ensureDirectoryExists, writeFileContent } from './file-operations'
|
||||
import { getOpenCodeConfigFilePath, getWorkspacePath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { archiveBrokenOpenCodeConfigFile, writeHealthWatchArtifact } from './opencode-config-file'
|
||||
import { restoreLastKnownGoodOpenCodeConfig, seedOpenCodeConfigFile } from './opencode-config-apply'
|
||||
import type { OpenCodeServerManager } from './opencode-single-server'
|
||||
|
||||
export const OPENCODE_LIFECYCLE_STATES = [
|
||||
@@ -55,7 +55,6 @@ export interface OpenCodeLifecycleStatus {
|
||||
interface OpenCodeSupervisorOptions {
|
||||
pollIntervalMs?: number
|
||||
failureThreshold?: number
|
||||
userId?: string
|
||||
watchEnabled?: boolean
|
||||
}
|
||||
|
||||
@@ -319,63 +318,30 @@ export class OpenCodeSupervisor {
|
||||
}
|
||||
|
||||
private async captureDebugSnapshot(): Promise<void> {
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
|
||||
const debugPath = path.join(getWorkspacePath(), '.opencode', 'state', 'health-watch', `opencode-health-${timestamp}.json`)
|
||||
const payload = JSON.stringify({
|
||||
await writeHealthWatchArtifact('opencode-health', (timestamp) => JSON.stringify({
|
||||
capturedAt: timestamp,
|
||||
startupError: this.openCodeServerManager.getLastStartupError(),
|
||||
lifecycleState: this.state,
|
||||
attemptedRecoveryActions: this.attemptedRecoveryActions,
|
||||
}, null, 2)
|
||||
|
||||
await ensureDirectoryExists(path.dirname(debugPath))
|
||||
await writeFileContent(debugPath, payload)
|
||||
}, null, 2))
|
||||
}
|
||||
|
||||
private async rollbackToLastKnownGood(): Promise<void> {
|
||||
this.settingsService.archiveBrokenConfig(this.userId)
|
||||
const lastGood = this.settingsService.restoreToLastKnownGoodConfig(this.userId)
|
||||
if (!lastGood) {
|
||||
await archiveBrokenOpenCodeConfigFile()
|
||||
const restored = await restoreLastKnownGoodOpenCodeConfig(this.settingsService)
|
||||
if (!restored) {
|
||||
throw new Error('No last known good config available')
|
||||
}
|
||||
|
||||
const config = this.settingsService.updateOpenCodeConfig(lastGood.configName, { content: lastGood.content }, this.userId)
|
||||
if (!config) {
|
||||
throw new Error(`Failed to restore OpenCode config '${lastGood.configName}'`)
|
||||
}
|
||||
|
||||
await this.writeConfig(lastGood.content)
|
||||
this.openCodeServerManager.clearStartupError()
|
||||
await this.openCodeServerManager.restart()
|
||||
}
|
||||
|
||||
private async seedDefaultConfig(): Promise<void> {
|
||||
const seedConfig = JSON.stringify({ $schema: 'https://opencode.ai/config.json' }, null, 2)
|
||||
const defaultConfig = this.settingsService.getDefaultOpenCodeConfig(this.userId)
|
||||
|
||||
if (defaultConfig) {
|
||||
this.settingsService.updateOpenCodeConfig(defaultConfig.name, { content: seedConfig }, this.userId)
|
||||
} else {
|
||||
this.settingsService.createOpenCodeConfig(
|
||||
{
|
||||
name: 'default',
|
||||
content: seedConfig,
|
||||
isDefault: true,
|
||||
},
|
||||
this.userId,
|
||||
)
|
||||
}
|
||||
|
||||
await this.writeConfig(seedConfig)
|
||||
await seedOpenCodeConfigFile()
|
||||
this.openCodeServerManager.clearStartupError()
|
||||
await this.openCodeServerManager.restart()
|
||||
}
|
||||
|
||||
private async writeConfig(content: string): Promise<void> {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
await writeFileContent(configPath, content)
|
||||
}
|
||||
|
||||
private startWatching(): void {
|
||||
if (!this.isWatchEnabled()) {
|
||||
logger.info('OpenCode supervisor health polling disabled')
|
||||
@@ -429,8 +395,4 @@ export class OpenCodeSupervisor {
|
||||
private getNextRecoveryAction(): OpenCodeRecoveryAction | null {
|
||||
return OPENCODE_RECOVERY_ACTIONS.find((action) => !this.attemptedRecoveryActions.includes(action)) ?? null
|
||||
}
|
||||
|
||||
private get userId(): string {
|
||||
return this.options.userId ?? 'default'
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { OpenCodeClient } from './client'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { TIMEOUTS } from '@opencode-manager/shared/config/env'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
|
||||
export type PatchConfigValidationIssue = {
|
||||
@@ -150,17 +151,41 @@ function parseErrorResponse(responseText: string): { details: PatchConfigValidat
|
||||
return { details, errorMessage }
|
||||
}
|
||||
|
||||
const CONFIG_PATCH_TIMEOUT_ERROR = `Timed out waiting for OpenCode config patch after ${TIMEOUTS.CONFIG_PATCH_TIMEOUT_MS}ms`
|
||||
|
||||
function isTimeoutError(error: unknown): boolean {
|
||||
return typeof error === 'object'
|
||||
&& error !== null
|
||||
&& 'name' in error
|
||||
&& (error as { name?: unknown }).name === 'TimeoutError'
|
||||
}
|
||||
|
||||
async function forwardConfigPatch(
|
||||
client: OpenCodeClient,
|
||||
config: Record<string, unknown>,
|
||||
): Promise<Response> {
|
||||
const signal = AbortSignal.timeout(TIMEOUTS.CONFIG_PATCH_TIMEOUT_MS)
|
||||
const response = await client.forward({
|
||||
method: 'PATCH',
|
||||
path: '/config',
|
||||
body: JSON.stringify(config),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
signal,
|
||||
})
|
||||
|
||||
if (!response.ok && signal.aborted) {
|
||||
throw new DOMException(CONFIG_PATCH_TIMEOUT_ERROR, 'TimeoutError')
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
export async function patchConfigWithRecovery(
|
||||
client: OpenCodeClient,
|
||||
config: Record<string, unknown>,
|
||||
): Promise<PatchConfigResult> {
|
||||
try {
|
||||
const response = await client.forward({
|
||||
method: 'PATCH',
|
||||
path: '/config',
|
||||
body: JSON.stringify(config),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
const response = await forwardConfigPatch(client, config)
|
||||
|
||||
if (response.ok) {
|
||||
logger.info('Patched OpenCode config via API')
|
||||
@@ -202,12 +227,7 @@ export async function patchConfigWithRecovery(
|
||||
}
|
||||
|
||||
logger.info(`Retrying config patch after removing ${removedFields.length} problematic field(s): ${removedFields.join(', ')}`)
|
||||
const retryResponse = await client.forward({
|
||||
method: 'PATCH',
|
||||
path: '/config',
|
||||
body: JSON.stringify(cleanedConfig),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
const retryResponse = await forwardConfigPatch(client, cleanedConfig)
|
||||
|
||||
if (retryResponse.ok) {
|
||||
logger.info('Patched OpenCode config via API after removing invalid fields')
|
||||
@@ -230,6 +250,11 @@ export async function patchConfigWithRecovery(
|
||||
removedFields
|
||||
}
|
||||
} catch (error) {
|
||||
if (isTimeoutError(error)) {
|
||||
logger.error(`Failed to patch OpenCode config: ${CONFIG_PATCH_TIMEOUT_ERROR}`)
|
||||
return { success: false, error: CONFIG_PATCH_TIMEOUT_ERROR }
|
||||
}
|
||||
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
||||
logger.error('Failed to patch OpenCode config:', error)
|
||||
return { success: false, error: errorMessage }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import fs from 'fs/promises'
|
||||
import { existsSync, rmSync, realpathSync } from 'node:fs'
|
||||
import { existsSync, rmSync } from 'node:fs'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { ensureDirectoryExists } from './file-operations'
|
||||
import { createRepo, getRepoByLocalPath, getRepoBySourcePath, getRepoById, updateRepoStatus, updateRepoBranch, updateLastPulled, deleteRepo, getRepoByUrlAndBranch } from '../db/queries'
|
||||
@@ -19,20 +19,12 @@ import { listRepos } from '../db/queries'
|
||||
import { listActiveScheduleRunWorkspaces } from '../db/schedules'
|
||||
import { SettingsService } from './settings'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { mkdirSafe } from '../utils/fs-safe'
|
||||
import { canonicalPathSync, mkdirSafe } from '../utils/fs-safe'
|
||||
|
||||
const GIT_CLONE_TIMEOUT = 300000
|
||||
const DEFAULT_DISCOVERY_MAX_DEPTH = 4
|
||||
const DISCOVERY_SKIP_DIRECTORIES = new Set(['.git', 'node_modules'])
|
||||
|
||||
function canonical(dir: string): string {
|
||||
try {
|
||||
return realpathSync(path.resolve(dir))
|
||||
} catch {
|
||||
return path.resolve(dir)
|
||||
}
|
||||
}
|
||||
|
||||
function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: string): Error {
|
||||
const message = originalMessage.toLowerCase()
|
||||
|
||||
@@ -1224,10 +1216,10 @@ export async function getSiblingRepos(
|
||||
// Workspaces that are git main checkouts (not linked worktrees) are also
|
||||
// excluded so the project's origin/main repository can never be surfaced
|
||||
// as deletable.
|
||||
const knownDirectories = new Set(repoSiblings.map((repo) => canonical(repo.fullPath)))
|
||||
const targetDirectory = canonical(target.fullPath)
|
||||
const reposRoot = canonical(getReposPath())
|
||||
const scheduleWorktreeRoot = canonical(getScheduleWorktreesPath())
|
||||
const knownDirectories = new Set(repoSiblings.map((repo) => canonicalPathSync(path.resolve(repo.fullPath))))
|
||||
const targetDirectory = canonicalPathSync(path.resolve(target.fullPath))
|
||||
const reposRoot = canonicalPathSync(path.resolve(getReposPath()))
|
||||
const scheduleWorktreeRoot = canonicalPathSync(path.resolve(getScheduleWorktreesPath()))
|
||||
|
||||
// Schedule runs may create their isolated worktree via the OpenCode workspace
|
||||
// API, which places it outside getScheduleWorktreesPath(). Exclude any live
|
||||
@@ -1236,14 +1228,14 @@ export async function getSiblingRepos(
|
||||
const activeRuns = listActiveScheduleRunWorkspaces(database)
|
||||
const activeRunWorkspaceIds = new Set(activeRuns.map((run) => run.workspaceId).filter((id): id is string => id !== null))
|
||||
const activeRunDirectories = new Set(
|
||||
activeRuns.map((run) => run.worktreePath).filter((p): p is string => p !== null).map((p) => canonical(p)),
|
||||
activeRuns.map((run) => run.worktreePath).filter((p): p is string => p !== null).map((p) => canonicalPathSync(path.resolve(p))),
|
||||
)
|
||||
|
||||
const candidates = workspaces.filter((workspace) => {
|
||||
if (workspace.projectID !== targetProjectId) return false
|
||||
if (!workspace.directory) return false
|
||||
|
||||
const workspaceDirectory = canonical(workspace.directory)
|
||||
const workspaceDirectory = canonicalPathSync(path.resolve(workspace.directory))
|
||||
if (workspaceDirectory === targetDirectory) return false
|
||||
if (workspaceDirectory === reposRoot) return false
|
||||
if (workspaceDirectory.startsWith(`${scheduleWorktreeRoot}${path.sep}`)) return false
|
||||
@@ -1262,7 +1254,7 @@ export async function getSiblingRepos(
|
||||
candidates
|
||||
.filter((_, index) => !mainChecks[index])
|
||||
.forEach((workspace) => {
|
||||
const directory = canonical(workspace.directory!)
|
||||
const directory = canonicalPathSync(path.resolve(workspace.directory!))
|
||||
if (!uniqueWorkspaces.has(directory)) {
|
||||
uniqueWorkspaces.set(directory, workspace)
|
||||
}
|
||||
|
||||
@@ -1,49 +1,17 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { unlinkSync, existsSync } from 'fs'
|
||||
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
|
||||
import { logger } from '../utils/logger'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
import { z } from 'zod'
|
||||
import { encryptSecret, decryptSecret } from '../utils/crypto'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import type {
|
||||
UserPreferences,
|
||||
SettingsResponse,
|
||||
CreateOpenCodeConfigRequest,
|
||||
UpdateOpenCodeConfigRequest
|
||||
import type {
|
||||
UserPreferences,
|
||||
SettingsResponse,
|
||||
} from '../types/settings'
|
||||
import {
|
||||
UserPreferencesSchema,
|
||||
OpenCodeConfigSchema,
|
||||
DEFAULT_USER_PREFERENCES,
|
||||
} from '../types/settings'
|
||||
|
||||
interface OpenCodeConfigValidationIssue {
|
||||
path: string
|
||||
message: string
|
||||
}
|
||||
|
||||
interface OpenCodeConfigWithRaw {
|
||||
id: number
|
||||
name: string
|
||||
content: Record<string, unknown>
|
||||
rawContent: string
|
||||
validationIssues?: OpenCodeConfigValidationIssue[]
|
||||
isValid: boolean
|
||||
isDefault: boolean
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
interface OpenCodeConfigResponseWithRaw {
|
||||
configs: OpenCodeConfigWithRaw[]
|
||||
defaultConfig: OpenCodeConfigWithRaw | null
|
||||
}
|
||||
|
||||
interface CreateOpenCodeConfigOptions {
|
||||
suppressAutoDefault?: boolean
|
||||
}
|
||||
|
||||
interface OpenCodeServerPasswordState {
|
||||
value: string
|
||||
createdAt: number
|
||||
@@ -56,37 +24,6 @@ export class SettingsService {
|
||||
|
||||
constructor(private db: Database) {}
|
||||
|
||||
private getValidationIssues(error: z.ZodError): OpenCodeConfigValidationIssue[] {
|
||||
return error.issues.map((issue) => ({
|
||||
path: issue.path.length > 0 ? issue.path.join('.') : 'root',
|
||||
message: issue.message,
|
||||
}))
|
||||
}
|
||||
|
||||
private parseStoredConfig(rawContent: string, configName: string): { content: Record<string, unknown>; validationIssues?: OpenCodeConfigValidationIssue[]; isValid: boolean } {
|
||||
const parsed = parseJsonc(rawContent)
|
||||
const content = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||||
? parsed as Record<string, unknown>
|
||||
: {}
|
||||
|
||||
const validated = OpenCodeConfigSchema.safeParse(parsed)
|
||||
if (validated.success) {
|
||||
return {
|
||||
content: validated.data as Record<string, unknown>,
|
||||
isValid: true,
|
||||
}
|
||||
}
|
||||
|
||||
const validationIssues = this.getValidationIssues(validated.error)
|
||||
logger.error(`Failed to validate config ${configName}: ${validationIssues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`)
|
||||
|
||||
return {
|
||||
content,
|
||||
validationIssues,
|
||||
isValid: false,
|
||||
}
|
||||
}
|
||||
|
||||
initializeLastKnownGoodConfig(userId: string = 'default'): void {
|
||||
const settings = this.getSettings(userId)
|
||||
if (settings.preferences.lastKnownGoodConfig) {
|
||||
@@ -102,6 +39,10 @@ export class SettingsService {
|
||||
}
|
||||
}
|
||||
|
||||
getLastKnownGoodConfig(): string | null {
|
||||
return SettingsService.lastKnownGoodConfigContent
|
||||
}
|
||||
|
||||
getSettings(userId: string = 'default'): SettingsResponse {
|
||||
const row = this.db
|
||||
.query('SELECT preferences, updated_at FROM user_preferences WHERE user_id = ?')
|
||||
@@ -177,433 +118,10 @@ export class SettingsService {
|
||||
}
|
||||
}
|
||||
|
||||
getOpenCodeConfigs(userId: string = 'default'): OpenCodeConfigResponseWithRaw {
|
||||
const rows = this.db
|
||||
.query('SELECT * FROM opencode_configs WHERE user_id = ? ORDER BY created_at DESC')
|
||||
.all(userId) as Array<{
|
||||
id: number
|
||||
user_id: string
|
||||
config_name: string
|
||||
config_content: string
|
||||
is_default: boolean
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}>
|
||||
|
||||
const configs: OpenCodeConfigWithRaw[] = []
|
||||
let defaultConfig: OpenCodeConfigWithRaw | null = null
|
||||
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const rawContent = row.config_content
|
||||
const parsedConfig = this.parseStoredConfig(rawContent, row.config_name)
|
||||
|
||||
const config: OpenCodeConfigWithRaw = {
|
||||
id: row.id,
|
||||
name: row.config_name,
|
||||
content: parsedConfig.content,
|
||||
rawContent: rawContent,
|
||||
validationIssues: parsedConfig.validationIssues,
|
||||
isValid: parsedConfig.isValid,
|
||||
isDefault: Boolean(row.is_default),
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}
|
||||
|
||||
configs.push(config)
|
||||
|
||||
if (config.isDefault) {
|
||||
defaultConfig = config
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Failed to parse config ${row.config_name}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
configs,
|
||||
defaultConfig,
|
||||
}
|
||||
}
|
||||
|
||||
createOpenCodeConfig(
|
||||
request: CreateOpenCodeConfigRequest,
|
||||
userId: string = 'default',
|
||||
options: CreateOpenCodeConfigOptions = {}
|
||||
): OpenCodeConfigWithRaw {
|
||||
// Check for existing config with the same name
|
||||
const existing = this.getOpenCodeConfigByName(request.name, userId)
|
||||
if (existing) {
|
||||
throw new Error(`Config with name '${request.name}' already exists`)
|
||||
}
|
||||
|
||||
const rawContent = typeof request.content === 'string'
|
||||
? request.content
|
||||
: JSON.stringify(request.content, null, 2)
|
||||
|
||||
const parsedContent = typeof request.content === 'string'
|
||||
? parseJsonc(request.content)
|
||||
: request.content
|
||||
|
||||
const contentValidated = OpenCodeConfigSchema.parse(parsedContent)
|
||||
const now = Date.now()
|
||||
|
||||
const existingCount = this.db
|
||||
.query('SELECT COUNT(*) as count FROM opencode_configs WHERE user_id = ?')
|
||||
.get(userId) as { count: number }
|
||||
|
||||
const shouldBeDefault = request.isDefault || (!options.suppressAutoDefault && existingCount.count === 0)
|
||||
|
||||
if (shouldBeDefault) {
|
||||
this.db
|
||||
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
|
||||
.run(userId)
|
||||
}
|
||||
|
||||
const result = this.db
|
||||
.query(
|
||||
`INSERT INTO opencode_configs (user_id, config_name, config_content, is_default, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.run(
|
||||
userId,
|
||||
request.name,
|
||||
rawContent,
|
||||
shouldBeDefault,
|
||||
now,
|
||||
now
|
||||
)
|
||||
|
||||
const config: OpenCodeConfigWithRaw = {
|
||||
id: result.lastInsertRowid as number,
|
||||
name: request.name,
|
||||
content: contentValidated as Record<string, unknown>,
|
||||
rawContent: rawContent,
|
||||
isValid: true,
|
||||
isDefault: shouldBeDefault,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
|
||||
logger.info(`Created OpenCode config '${config.name}' for user: ${userId}`)
|
||||
return config
|
||||
}
|
||||
|
||||
updateOpenCodeConfig(
|
||||
configName: string,
|
||||
request: UpdateOpenCodeConfigRequest,
|
||||
userId: string = 'default'
|
||||
): OpenCodeConfigWithRaw | null {
|
||||
const existing = this.db
|
||||
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?')
|
||||
.get(userId, configName) as {
|
||||
id: number
|
||||
config_content: string
|
||||
is_default: boolean
|
||||
created_at: number
|
||||
} | undefined
|
||||
|
||||
if (!existing) {
|
||||
return null
|
||||
}
|
||||
|
||||
const rawContent = typeof request.content === 'string'
|
||||
? request.content
|
||||
: JSON.stringify(request.content, null, 2)
|
||||
|
||||
const parsedContent = typeof request.content === 'string'
|
||||
? parseJsonc(request.content)
|
||||
: request.content
|
||||
|
||||
const contentValidated = OpenCodeConfigSchema.parse(parsedContent)
|
||||
const now = Date.now()
|
||||
|
||||
if (request.isDefault) {
|
||||
this.db
|
||||
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
|
||||
.run(userId)
|
||||
}
|
||||
|
||||
this.db
|
||||
.query(
|
||||
`UPDATE opencode_configs
|
||||
SET config_content = ?, is_default = ?, updated_at = ?
|
||||
WHERE user_id = ? AND config_name = ?`
|
||||
)
|
||||
.run(
|
||||
rawContent,
|
||||
request.isDefault !== undefined ? request.isDefault : existing.is_default,
|
||||
now,
|
||||
userId,
|
||||
configName
|
||||
)
|
||||
|
||||
const config: OpenCodeConfigWithRaw = {
|
||||
id: existing.id,
|
||||
name: configName,
|
||||
content: contentValidated as Record<string, unknown>,
|
||||
rawContent: rawContent,
|
||||
isValid: true,
|
||||
isDefault: request.isDefault !== undefined ? request.isDefault : existing.is_default,
|
||||
createdAt: existing.created_at,
|
||||
updatedAt: now,
|
||||
}
|
||||
|
||||
logger.info(`Updated OpenCode config '${configName}' for user: ${userId}`)
|
||||
return config
|
||||
}
|
||||
|
||||
deleteOpenCodeConfig(configName: string, userId: string = 'default'): boolean {
|
||||
const result = this.db
|
||||
.query('DELETE FROM opencode_configs WHERE user_id = ? AND config_name = ?')
|
||||
.run(userId, configName)
|
||||
|
||||
const deleted = result.changes > 0
|
||||
if (deleted) {
|
||||
logger.info(`Deleted OpenCode config '${configName}' for user: ${userId}`)
|
||||
this.ensureSingleConfigIsDefault(userId)
|
||||
}
|
||||
|
||||
return deleted
|
||||
}
|
||||
|
||||
setDefaultOpenCodeConfig(configName: string, userId: string = 'default'): OpenCodeConfigWithRaw | null {
|
||||
const existing = this.db
|
||||
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?')
|
||||
.get(userId, configName) as {
|
||||
id: number
|
||||
config_content: string
|
||||
created_at: number
|
||||
} | undefined
|
||||
|
||||
if (!existing) {
|
||||
return null
|
||||
}
|
||||
|
||||
this.db
|
||||
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
|
||||
.run(userId)
|
||||
|
||||
const now = Date.now()
|
||||
this.db
|
||||
.query(
|
||||
`UPDATE opencode_configs
|
||||
SET is_default = TRUE, updated_at = ?
|
||||
WHERE user_id = ? AND config_name = ?`
|
||||
)
|
||||
.run(now, userId, configName)
|
||||
|
||||
try {
|
||||
const rawContent = existing.config_content
|
||||
const parsedConfig = this.parseStoredConfig(rawContent, configName)
|
||||
|
||||
const config: OpenCodeConfigWithRaw = {
|
||||
id: existing.id,
|
||||
name: configName,
|
||||
content: parsedConfig.content,
|
||||
rawContent: rawContent,
|
||||
validationIssues: parsedConfig.validationIssues,
|
||||
isValid: parsedConfig.isValid,
|
||||
isDefault: true,
|
||||
createdAt: existing.created_at,
|
||||
updatedAt: now,
|
||||
}
|
||||
|
||||
logger.info(`Set '${configName}' as default OpenCode config for user: ${userId}`)
|
||||
return config
|
||||
} catch (error) {
|
||||
logger.error(`Failed to parse config ${configName}:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
getDefaultOpenCodeConfig(userId: string = 'default'): OpenCodeConfigWithRaw | null {
|
||||
const row = this.db
|
||||
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND is_default = TRUE')
|
||||
.get(userId) as {
|
||||
id: number
|
||||
config_name: string
|
||||
config_content: string
|
||||
created_at: number
|
||||
updated_at: number
|
||||
} | undefined
|
||||
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const rawContent = row.config_content
|
||||
const parsedConfig = this.parseStoredConfig(rawContent, row.config_name)
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.config_name,
|
||||
content: parsedConfig.content,
|
||||
rawContent: rawContent,
|
||||
validationIssues: parsedConfig.validationIssues,
|
||||
isValid: parsedConfig.isValid,
|
||||
isDefault: true,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Failed to parse default config:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
getOpenCodeConfigByName(configName: string, userId: string = 'default'): OpenCodeConfigWithRaw | null {
|
||||
const row = this.db
|
||||
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?')
|
||||
.get(userId, configName) as {
|
||||
id: number
|
||||
config_name: string
|
||||
config_content: string
|
||||
is_default: boolean
|
||||
created_at: number
|
||||
updated_at: number
|
||||
} | undefined
|
||||
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const rawContent = row.config_content
|
||||
const parsedConfig = this.parseStoredConfig(rawContent, configName)
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.config_name,
|
||||
content: parsedConfig.content,
|
||||
rawContent: rawContent,
|
||||
validationIssues: parsedConfig.validationIssues,
|
||||
isValid: parsedConfig.isValid,
|
||||
isDefault: Boolean(row.is_default),
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Failed to parse config ${configName}:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
getOpenCodeConfigContent(configName: string, userId: string = 'default'): string | null {
|
||||
const row = this.db
|
||||
.query('SELECT config_content FROM opencode_configs WHERE user_id = ? AND config_name = ?')
|
||||
.get(userId, configName) as { config_content: string } | undefined
|
||||
|
||||
if (!row) {
|
||||
logger.error(`Config '${configName}' not found for user ${userId}`)
|
||||
return null
|
||||
}
|
||||
|
||||
return row.config_content
|
||||
}
|
||||
|
||||
ensureSingleConfigIsDefault(userId: string = 'default'): void {
|
||||
const hasDefault = this.db
|
||||
.query('SELECT COUNT(*) as count FROM opencode_configs WHERE user_id = ? AND is_default = TRUE')
|
||||
.get(userId) as { count: number }
|
||||
|
||||
if (hasDefault.count === 0) {
|
||||
const firstConfig = this.db
|
||||
.query('SELECT config_name FROM opencode_configs WHERE user_id = ? ORDER BY created_at ASC LIMIT 1')
|
||||
.get(userId) as { config_name: string } | undefined
|
||||
|
||||
if (firstConfig) {
|
||||
this.db
|
||||
.query('UPDATE opencode_configs SET is_default = TRUE WHERE user_id = ? AND config_name = ?')
|
||||
.run(userId, firstConfig.config_name)
|
||||
logger.info(`Auto-set '${firstConfig.config_name}' as default (only config)`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
saveLastKnownGoodConfig(userId: string = 'default'): void {
|
||||
const config = this.getDefaultOpenCodeConfig(userId)
|
||||
if (config) {
|
||||
SettingsService.lastKnownGoodConfigContent = config.rawContent
|
||||
this.persistLastKnownGoodConfig(userId)
|
||||
logger.info(`Saved last known good config: ${config.name}`)
|
||||
}
|
||||
}
|
||||
|
||||
archiveBrokenConfig(userId: string = 'default'): string | null {
|
||||
const current = this.getDefaultOpenCodeConfig(userId)
|
||||
if (!current) {
|
||||
return null
|
||||
}
|
||||
|
||||
const ts = new Date().toISOString().replace(/[:.]/g, '-')
|
||||
const backupName = `${current.name}-broken-${ts}`
|
||||
try {
|
||||
this.createOpenCodeConfig(
|
||||
{
|
||||
name: backupName,
|
||||
content: current.rawContent,
|
||||
isDefault: false,
|
||||
},
|
||||
userId,
|
||||
{ suppressAutoDefault: true },
|
||||
)
|
||||
logger.warn(`Archived broken OpenCode config as '${backupName}'`)
|
||||
return backupName
|
||||
} catch (error) {
|
||||
logger.error('Failed to archive broken config:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
restoreToLastKnownGoodConfig(userId: string = 'default'): { configName: string; content: string } | null {
|
||||
if (!SettingsService.lastKnownGoodConfigContent) {
|
||||
logger.warn('No last known good config available for rollback')
|
||||
return null
|
||||
}
|
||||
|
||||
const configs = this.getOpenCodeConfigs(userId)
|
||||
const defaultConfig = configs.defaultConfig
|
||||
|
||||
if (!defaultConfig) {
|
||||
logger.error('Cannot rollback: no default config found')
|
||||
return null
|
||||
}
|
||||
|
||||
logger.info(`Restoring to last known good config for: ${defaultConfig.name}`)
|
||||
return {
|
||||
configName: defaultConfig.name,
|
||||
content: SettingsService.lastKnownGoodConfigContent
|
||||
}
|
||||
}
|
||||
|
||||
rollbackToLastKnownGoodHealth(userId: string = 'default'): string | null {
|
||||
const lastGood = this.restoreToLastKnownGoodConfig(userId)
|
||||
if (!lastGood) {
|
||||
return null
|
||||
}
|
||||
|
||||
this.updateOpenCodeConfig(lastGood.configName, { content: lastGood.content }, userId)
|
||||
return lastGood.configName
|
||||
}
|
||||
|
||||
deleteFilesystemConfig(): boolean {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
|
||||
if (!existsSync(configPath)) {
|
||||
logger.warn('Config file does not exist:', configPath)
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
unlinkSync(configPath)
|
||||
logger.info('Deleted filesystem config to allow server startup:', configPath)
|
||||
return true
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete config file:', error)
|
||||
return false
|
||||
}
|
||||
saveLastKnownGoodConfig(rawContent: string): void {
|
||||
SettingsService.lastKnownGoodConfigContent = rawContent
|
||||
this.persistLastKnownGoodConfig()
|
||||
logger.info('Saved last known good config')
|
||||
}
|
||||
|
||||
getOpenCodeServerPassword(): string {
|
||||
|
||||
@@ -98,6 +98,63 @@ describe('atomic-json', () => {
|
||||
expect(executionOrder).toEqual([1, 2, 3, 4])
|
||||
})
|
||||
|
||||
it('runs the next queued call when the previous call rejects', async () => {
|
||||
const filePath = join(tmpDir, 'reject-next.json')
|
||||
const firstError = new Error('first fails')
|
||||
let secondRan = false
|
||||
|
||||
const first = withFileLock(filePath, async () => {
|
||||
throw firstError
|
||||
})
|
||||
|
||||
const second = withFileLock(filePath, async () => {
|
||||
secondRan = true
|
||||
return 'second'
|
||||
})
|
||||
|
||||
await expect(first).rejects.toThrow('first fails')
|
||||
await expect(second).resolves.toBe('second')
|
||||
expect(secondRan).toBe(true)
|
||||
})
|
||||
|
||||
it('does not poison the lock for later calls after a rejection settles', async () => {
|
||||
const filePath = join(tmpDir, 'reject-recovery.json')
|
||||
const firstError = new Error('first fails')
|
||||
|
||||
await expect(
|
||||
withFileLock(filePath, async () => {
|
||||
throw firstError
|
||||
}),
|
||||
).rejects.toThrow('first fails')
|
||||
|
||||
await expect(withFileLock(filePath, async () => 'recovered')).resolves.toBe('recovered')
|
||||
})
|
||||
|
||||
it('serializes calls when an operation rejects', async () => {
|
||||
const filePath = join(tmpDir, 'reject-order.json')
|
||||
const executionOrder: number[] = []
|
||||
|
||||
const first = withFileLock(filePath, async () => {
|
||||
executionOrder.push(1)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
executionOrder.push(2)
|
||||
throw new Error('first fails')
|
||||
})
|
||||
|
||||
const second = withFileLock(filePath, async () => {
|
||||
executionOrder.push(3)
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
executionOrder.push(4)
|
||||
return 'second'
|
||||
})
|
||||
|
||||
const [firstResult, secondResult] = await Promise.allSettled([first, second])
|
||||
|
||||
expect(firstResult.status).toBe('rejected')
|
||||
expect(secondResult).toEqual({ status: 'fulfilled', value: 'second' })
|
||||
expect(executionOrder).toEqual([1, 2, 3, 4])
|
||||
})
|
||||
|
||||
it('concurrent stress test: 50 writes then reads', async () => {
|
||||
const filePath = join(tmpDir, 'stress.json')
|
||||
const numOps = 50
|
||||
|
||||
@@ -44,7 +44,7 @@ export async function withFileLock<T>(filePath: string, fn: () => Promise<T>): P
|
||||
}
|
||||
}
|
||||
|
||||
const newLock = previousLock ? previousLock.then(executeWithLock) : executeWithLock()
|
||||
const newLock = previousLock ? previousLock.then(executeWithLock, executeWithLock) : executeWithLock()
|
||||
fileLockPromises.set(absolutePath, newLock)
|
||||
|
||||
return newLock as Promise<T>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import path from 'path'
|
||||
import { promises as fs, mkdirSync, accessSync, constants } from 'node:fs'
|
||||
import { promises as fs, mkdirSync, accessSync, constants, realpathSync } from 'node:fs'
|
||||
|
||||
interface MkdirSafeOptions {
|
||||
mode?: number
|
||||
@@ -10,6 +10,22 @@ function isPermissionError(error: unknown): boolean {
|
||||
return code === 'EACCES' || code === 'EPERM'
|
||||
}
|
||||
|
||||
export async function canonicalPath(target: string): Promise<string> {
|
||||
try {
|
||||
return await fs.realpath(target)
|
||||
} catch {
|
||||
return target
|
||||
}
|
||||
}
|
||||
|
||||
export function canonicalPathSync(target: string): string {
|
||||
try {
|
||||
return realpathSync(target)
|
||||
} catch {
|
||||
return target
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeFileAtomic(filePath: string, content: string, options: { mode?: number } = {}): Promise<void> {
|
||||
const dir = path.dirname(filePath)
|
||||
await mkdirSafe(dir)
|
||||
@@ -23,6 +39,14 @@ export async function writeFileAtomic(filePath: string, content: string, options
|
||||
}
|
||||
}
|
||||
|
||||
export async function existingFileMode(filePath: string): Promise<number | undefined> {
|
||||
try {
|
||||
return (await fs.stat(filePath)).mode & 0o777
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export async function mkdirSafe(dirPath: string, options: MkdirSafeOptions = {}): Promise<void> {
|
||||
try {
|
||||
await fs.mkdir(dirPath, { ...options, recursive: true })
|
||||
|
||||
Reference in new issue
Block a user