Files
opencode-manager/backend/test/db/opencode-model-state-migration.test.ts
T

129 lines
4.3 KiB
TypeScript

import { Database } from 'bun:sqlite'
import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { z } from 'zod'
import { JsonValueSchema } from '@opencode-manager/shared/utils'
import { getOpenCodeModelStatePath } from '@opencode-manager/shared/config/env'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { selectRow } from '../../src/db/rows'
import { createTempWorkspace, type TempWorkspace } from '../helpers/test-env'
const ModelStateRowSchema = z.object({
recent: z.array(JsonValueSchema),
favorite: z.array(JsonValueSchema),
variant: z.record(z.string(), JsonValueSchema),
})
type ModelStateRow = z.infer<typeof ModelStateRowSchema>
const ModelStateFileSchema = ModelStateRowSchema.extend({
session: z.object({ current: z.string() }).optional(),
})
const TableNameRowSchema = z.object({ name: z.string() })
function migrateToV19(db: Database): void {
migrate(db, allMigrations.filter(migration => (migration.legacy?.version ?? Infinity) < 20))
}
function insertRow(db: Database, state: ModelStateRow, updatedAt: number): void {
db.prepare(
'INSERT INTO opencode_model_state (user_id, recent, favorite, variant, updated_at) VALUES (?, ?, ?, ?, ?)',
).run('default', JSON.stringify(state.recent), JSON.stringify(state.favorite), JSON.stringify(state.variant), updatedAt)
}
function tableExists(db: Database): boolean {
return selectRow(
db,
TableNameRowSchema,
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'opencode_model_state'",
) !== null
}
async function readModelStateFile(): Promise<z.infer<typeof ModelStateFileSchema>> {
return ModelStateFileSchema.parse(JSON.parse(await readFile(getOpenCodeModelStatePath(), 'utf8')))
}
describe('020-drop-opencode-model-state', () => {
let workspace: TempWorkspace
beforeEach(() => {
workspace = createTempWorkspace('opencode-model-state-migration-')
})
afterEach(() => {
workspace.restore()
})
it('writes the file from a newer row and drops the table', async () => {
const db = new Database(':memory:')
migrateToV19(db)
const state: ModelStateRow = {
recent: [{ providerID: 'anthropic', modelID: 'claude' }],
favorite: [{ providerID: 'openai', modelID: 'gpt-4' }],
variant: { anthropic: 'thinking' },
}
insertRow(db, state, Date.now() + 60_000)
migrate(db, allMigrations)
expect(tableExists(db)).toBe(false)
expect(await readModelStateFile()).toEqual(state)
})
it('leaves an existing newer file untouched and drops the table', async () => {
const db = new Database(':memory:')
migrateToV19(db)
const existing = JSON.stringify({
session: { current: 'abc' },
recent: [{ providerID: 'existing', modelID: 'model' }],
favorite: [],
variant: {},
})
await mkdir(path.dirname(getOpenCodeModelStatePath()), { recursive: true })
await writeFile(getOpenCodeModelStatePath(), existing)
const fileStats = await stat(getOpenCodeModelStatePath())
insertRow(db, { recent: [], favorite: [], variant: {} }, Math.floor(fileStats.mtimeMs) - 60_000)
migrate(db, allMigrations)
expect(tableExists(db)).toBe(false)
expect(await readFile(getOpenCodeModelStatePath(), 'utf8')).toBe(existing)
})
it('preserves unknown top-level keys when restoring over an older file', async () => {
const db = new Database(':memory:')
migrateToV19(db)
await mkdir(path.dirname(getOpenCodeModelStatePath()), { recursive: true })
await writeFile(getOpenCodeModelStatePath(), JSON.stringify({ session: { current: 'abc' }, recent: [] }))
const state: ModelStateRow = {
recent: [{ providerID: 'anthropic', modelID: 'claude' }],
favorite: [],
variant: {},
}
insertRow(db, state, Date.now() + 60_000)
migrate(db, allMigrations)
const file = await readModelStateFile()
expect(file.session).toEqual({ current: 'abc' })
expect(file).toMatchObject(state)
})
it('does not throw and drops the table when the table is absent', () => {
const db = new Database(':memory:')
migrateToV19(db)
db.run('DROP TABLE IF EXISTS opencode_model_state')
expect(() => migrate(db, allMigrations)).not.toThrow()
expect(tableExists(db)).toBe(false)
})
})