mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +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())
|
||||
|
||||
Reference in new issue
Block a user