mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
chore(lint): replace ESLint with Oxlint and clear anti-slop findings
This commit is contained in:
1 parent
c6c13335e5
commit
b625acfc0c
1083 files changed
+67089
-80136
No files matched your search
@@ -1,184 +1,156 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('node:fs')>()),
|
||||
existsSync: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('fs/promises', () => ({
|
||||
cp: vi.fn(),
|
||||
mkdtemp: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
rm: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn().mockImplementation(() => ({
|
||||
exec: vi.fn(),
|
||||
close: vi.fn(),
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/file-operations', () => ({
|
||||
ensureDirectoryExists: vi.fn(),
|
||||
fileExists: vi.fn(),
|
||||
readFileContent: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-config-file', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../src/services/opencode-config-file')>()),
|
||||
readOpenCodeConfigFile: vi.fn(),
|
||||
restoreOpenCodeConfigSnapshot: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: {
|
||||
clearStartupError: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@opencode-manager/shared/config/env')>()),
|
||||
getConfigPath: vi.fn(() => '/tmp/workspace/.config/opencode'),
|
||||
getOpenCodeConfigFilePath: vi.fn(() => '/tmp/workspace/.config/opencode/opencode.json'),
|
||||
getWorkspacePath: vi.fn(() => '/tmp/workspace'),
|
||||
}))
|
||||
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { readdir, rm, cp, mkdtemp, rename } from 'fs/promises'
|
||||
import { Database as SQLiteDatabase } from 'bun:sqlite'
|
||||
import { ensureDirectoryExists, fileExists, readFileContent } from '../../src/services/file-operations'
|
||||
import { readOpenCodeConfigFile, restoreOpenCodeConfigSnapshot, serializeOpenCodeConfigSnapshot } from '../../src/services/opencode-config-file'
|
||||
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { getConfigPath, getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import type { SettingsService } from '../../src/services/settings'
|
||||
import { getOpenCodeImportStatus, syncOpenCodeImport } from '../../src/services/opencode-import'
|
||||
import {
|
||||
readOpenCodeConfigFile,
|
||||
serializeOpenCodeConfigSnapshot,
|
||||
} from '../../src/services/opencode-config-file'
|
||||
import {
|
||||
getImportedSessionDirectories,
|
||||
getOpenCodeImportStatus,
|
||||
importOpenCodeStateDirectory,
|
||||
shouldImportOpenCodeStateEntry,
|
||||
syncOpenCodeImport,
|
||||
} from '../../src/services/opencode-import'
|
||||
import { applyTestEnv, createTempWorkspace, type TempWorkspace } from '../helpers/test-env'
|
||||
|
||||
const mockReaddir = readdir as unknown as ReturnType<typeof vi.fn>
|
||||
const mockExistsSync = existsSync as ReturnType<typeof vi.fn>
|
||||
const mockFileExists = fileExists as ReturnType<typeof vi.fn>
|
||||
const mockReadFileContent = readFileContent as ReturnType<typeof vi.fn>
|
||||
const mockEnsureDirectoryExists = ensureDirectoryExists as ReturnType<typeof vi.fn>
|
||||
const mockReadOpenCodeConfigFile = readOpenCodeConfigFile as ReturnType<typeof vi.fn>
|
||||
const mockWriteOpenCodeConfigFile = restoreOpenCodeConfigSnapshot as ReturnType<typeof vi.fn>
|
||||
const MockSQLiteDatabase = SQLiteDatabase as unknown as ReturnType<typeof vi.fn>
|
||||
const mockMkdtemp = mkdtemp as unknown as ReturnType<typeof vi.fn>
|
||||
const mockRename = rename as unknown as ReturnType<typeof vi.fn>
|
||||
function createStateDatabase(dbPath: string, directories: string[] = []): void {
|
||||
const db = new Database(dbPath)
|
||||
try {
|
||||
db.exec('CREATE TABLE IF NOT EXISTS session (id TEXT PRIMARY KEY NOT NULL, directory TEXT)')
|
||||
const insert = db.query('INSERT INTO session (id, directory) VALUES (?, ?)')
|
||||
directories.forEach((directory, index) => {
|
||||
insert.run(`ses_${index}`, directory)
|
||||
})
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
|
||||
describe('opencode-import service', () => {
|
||||
let workspace: TempWorkspace
|
||||
let restoreEnv: () => void
|
||||
let home: string
|
||||
let hostConfigDir: string
|
||||
let workspaceStateDir: string
|
||||
|
||||
async function writeHostConfig(name: string, content: string): Promise<string> {
|
||||
const target = path.join(hostConfigDir, name)
|
||||
await mkdir(hostConfigDir, { recursive: true })
|
||||
await writeFile(target, content, 'utf8')
|
||||
return target
|
||||
}
|
||||
|
||||
async function createHostState(directories: string[] = []): Promise<string> {
|
||||
const stateDir = path.join(home, 'host-state')
|
||||
await mkdir(stateDir, { recursive: true })
|
||||
createStateDatabase(path.join(stateDir, 'opencode.db'), directories)
|
||||
return stateDir
|
||||
}
|
||||
|
||||
function workspaceConfigPath(name: string): string {
|
||||
return path.join(getConfigPath(), name)
|
||||
}
|
||||
|
||||
async function stagedDirectories(parent: string): Promise<string[]> {
|
||||
return (await readdir(parent)).filter((name) => name.startsWith('opencode-import-'))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubEnv('OPENCODE_IMPORT_CONFIG_PATH', undefined)
|
||||
vi.stubEnv('OPENCODE_IMPORT_STATE_PATH', undefined)
|
||||
mockReadOpenCodeConfigFile.mockResolvedValue(null)
|
||||
mockReadFileContent.mockResolvedValue('{"$schema":"https://opencode.ai/config.json"}')
|
||||
mockReaddir.mockResolvedValue([])
|
||||
mockMkdtemp.mockResolvedValue('/tmp/workspace/.opencode/state/opencode-import-123')
|
||||
mockRename.mockResolvedValue(undefined)
|
||||
mockExistsSync.mockImplementation((candidate: string) => candidate === process.env.OPENCODE_IMPORT_CONFIG_PATH)
|
||||
workspace = createTempWorkspace('opencode-import-')
|
||||
home = mkdtempSync(path.join(os.tmpdir(), 'opencode-import-home-'))
|
||||
restoreEnv = applyTestEnv({
|
||||
HOME: home,
|
||||
OPENCODE_IMPORT_CONFIG_PATH: undefined,
|
||||
OPENCODE_IMPORT_STATE_PATH: undefined,
|
||||
})
|
||||
hostConfigDir = path.join(home, '.config', 'opencode')
|
||||
workspaceStateDir = path.join(getWorkspacePath(), '.opencode', 'state', 'opencode')
|
||||
})
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
afterEach(() => {
|
||||
restoreEnv()
|
||||
rmSync(home, { recursive: true, force: true })
|
||||
workspace.restore()
|
||||
})
|
||||
|
||||
it('imports every discovered global source without flattening or renaming JSONC', async () => {
|
||||
const jsonPath = path.join(os.homedir(), '.config', 'opencode', 'opencode.json')
|
||||
const jsoncPath = path.join(os.homedir(), '.config', 'opencode', 'opencode.jsonc')
|
||||
mockExistsSync.mockImplementation((candidate: string) => [jsonPath, jsoncPath].includes(candidate))
|
||||
mockFileExists.mockResolvedValue(false)
|
||||
const rawJson = '{"model":"test/lower"}'
|
||||
const rawJsonc = '{\n// keep\n"model":"test/higher"\n}'
|
||||
mockReadFileContent.mockImplementation(async (candidate: string) => candidate === jsoncPath ? rawJsonc : rawJson)
|
||||
const jsonPath = await writeHostConfig('opencode.json', rawJson)
|
||||
const jsoncPath = await writeHostConfig('opencode.jsonc', rawJsonc)
|
||||
|
||||
const result = await syncOpenCodeImport({})
|
||||
|
||||
expect(result.configSourcePaths).toEqual([jsonPath, jsoncPath])
|
||||
expect(result.configSourcePath).toBe(jsoncPath)
|
||||
expect(mockWriteOpenCodeConfigFile).toHaveBeenCalledTimes(1)
|
||||
const snapshot = mockWriteOpenCodeConfigFile.mock.calls[0]![0] as string
|
||||
expect(snapshot).toContain(JSON.stringify(rawJson))
|
||||
expect(snapshot).toContain(JSON.stringify(rawJsonc))
|
||||
expect(snapshot).toContain('opencode.jsonc')
|
||||
await expect(readFile(workspaceConfigPath('opencode.json'), 'utf8')).resolves.toBe(rawJson)
|
||||
await expect(readFile(workspaceConfigPath('opencode.jsonc'), 'utf8')).resolves.toBe(rawJsonc)
|
||||
})
|
||||
|
||||
it('preserves an explicitly imported JSONC filename', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode.jsonc'
|
||||
mockFileExists.mockResolvedValue(false)
|
||||
const submitted = '{\n// imported\n"model":"test/higher"\n}'
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.jsonc', submitted)
|
||||
|
||||
await syncOpenCodeImport({})
|
||||
|
||||
expect(mockWriteOpenCodeConfigFile).toHaveBeenCalledWith(expect.stringContaining('opencode.jsonc'))
|
||||
await expect(readFile(workspaceConfigPath('opencode.jsonc'), 'utf8')).resolves.toBe(submitted)
|
||||
})
|
||||
|
||||
it('mirrors a host config.json alongside the native sources', async () => {
|
||||
const jsonPath = path.join(os.homedir(), '.config', 'opencode', 'opencode.json')
|
||||
const legacyPath = path.join(os.homedir(), '.config', 'opencode', 'config.json')
|
||||
mockExistsSync.mockImplementation((candidate: string) => [jsonPath, legacyPath].includes(candidate))
|
||||
mockFileExists.mockResolvedValue(false)
|
||||
const rawJson = '{"model":"test/lower"}'
|
||||
const rawLegacy = '{"theme":"dark"}'
|
||||
mockReadFileContent.mockImplementation(async (candidate: string) =>
|
||||
candidate === legacyPath ? rawLegacy : rawJson)
|
||||
const jsonPath = await writeHostConfig('opencode.json', rawJson)
|
||||
const legacyPath = await writeHostConfig('config.json', rawLegacy)
|
||||
|
||||
const result = await syncOpenCodeImport({})
|
||||
|
||||
expect(result.configSourcePaths).toEqual([jsonPath, legacyPath])
|
||||
expect(result.configSourcePath).toBe(legacyPath)
|
||||
const snapshot = mockWriteOpenCodeConfigFile.mock.calls[0]![0] as string
|
||||
expect(snapshot).toContain(JSON.stringify(rawJson))
|
||||
expect(snapshot).toContain(JSON.stringify(rawLegacy))
|
||||
expect(snapshot).toContain('config.json')
|
||||
const mirrored = await readFile(workspaceConfigPath('opencode.json'), 'utf8')
|
||||
expect(mirrored).toContain('"model": "test/lower"')
|
||||
expect(mirrored).toContain('"theme": "dark"')
|
||||
await expect(readFile(workspaceConfigPath('config.json'), 'utf8')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('detects importable host config and state paths with opencode.db', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = '/import/opencode-state'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => {
|
||||
if (candidate === '/import/opencode-config/opencode.json') {
|
||||
return true
|
||||
}
|
||||
if (candidate === '/import/opencode-state') {
|
||||
return true
|
||||
}
|
||||
if (candidate === '/import/opencode-state/opencode.db') {
|
||||
return true
|
||||
}
|
||||
if (candidate === '/tmp/workspace/.opencode/state/opencode/opencode.db') {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"model":"test/lower"}')
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = await createHostState()
|
||||
await mkdir(workspaceStateDir, { recursive: true })
|
||||
createStateDatabase(path.join(workspaceStateDir, 'opencode.db'))
|
||||
|
||||
const status = await getOpenCodeImportStatus()
|
||||
|
||||
expect(status).toEqual({
|
||||
configSourcePath: '/import/opencode-config/opencode.json',
|
||||
configSourcePaths: ['/import/opencode-config/opencode.json'],
|
||||
stateSourcePath: '/import/opencode-state',
|
||||
workspaceConfigPath: '/tmp/workspace/.config/opencode/opencode.jsonc',
|
||||
configSourcePath: process.env.OPENCODE_IMPORT_CONFIG_PATH,
|
||||
configSourcePaths: [process.env.OPENCODE_IMPORT_CONFIG_PATH],
|
||||
stateSourcePath: process.env.OPENCODE_IMPORT_STATE_PATH,
|
||||
workspaceConfigPath: workspaceConfigPath('opencode.jsonc'),
|
||||
workspaceConfigPathsToRemove: [],
|
||||
workspaceStatePath: '/tmp/workspace/.opencode/state/opencode',
|
||||
workspaceStatePath: workspaceStateDir,
|
||||
workspaceStateExists: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports workspace config sources absent from the host as pending removals', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
const workspaceJsoncPath = '/tmp/workspace/.config/opencode/opencode.jsonc'
|
||||
mockExistsSync.mockImplementation((candidate: string) =>
|
||||
candidate === '/import/opencode-config/opencode.json' || candidate === workspaceJsoncPath)
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"model":"test/lower"}')
|
||||
await mkdir(getConfigPath(), { recursive: true })
|
||||
await writeFile(workspaceConfigPath('opencode.jsonc'), '{"theme":"dark"}', 'utf8')
|
||||
|
||||
const status = await getOpenCodeImportStatus()
|
||||
|
||||
expect(status.workspaceConfigPathsToRemove).toEqual([workspaceJsoncPath])
|
||||
expect(status.workspaceConfigPathsToRemove).toEqual([workspaceConfigPath('opencode.jsonc')])
|
||||
})
|
||||
|
||||
it('reports no pending removals when workspace and host share a config basename', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
const workspaceJsonPath = '/tmp/workspace/.config/opencode/opencode.json'
|
||||
mockExistsSync.mockImplementation((candidate: string) =>
|
||||
candidate === '/import/opencode-config/opencode.json' || candidate === workspaceJsonPath)
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"model":"test/lower"}')
|
||||
await mkdir(getConfigPath(), { recursive: true })
|
||||
await writeFile(workspaceConfigPath('opencode.json'), '{"theme":"dark"}', 'utf8')
|
||||
|
||||
const status = await getOpenCodeImportStatus()
|
||||
|
||||
@@ -186,8 +158,8 @@ describe('opencode-import service', () => {
|
||||
})
|
||||
|
||||
it('reports no pending removals when no host config source is detected', async () => {
|
||||
const workspaceJsoncPath = '/tmp/workspace/.config/opencode/opencode.jsonc'
|
||||
mockExistsSync.mockImplementation((candidate: string) => candidate === workspaceJsoncPath)
|
||||
await mkdir(getConfigPath(), { recursive: true })
|
||||
await writeFile(workspaceConfigPath('opencode.jsonc'), '{"theme":"dark"}', 'utf8')
|
||||
|
||||
const status = await getOpenCodeImportStatus()
|
||||
|
||||
@@ -196,92 +168,58 @@ describe('opencode-import service', () => {
|
||||
})
|
||||
|
||||
it('imports host config and state into the workspace', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = '/import/opencode-state'
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"$schema":"https://opencode.ai/config.json"}')
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = await createHostState()
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => {
|
||||
return candidate === '/import/opencode-config/opencode.json'
|
||||
|| candidate === '/import/opencode-state'
|
||||
|| candidate === '/import/opencode-state/opencode.db'
|
||||
|| candidate === '/tmp/workspace/.opencode/state/opencode/opencode.db'
|
||||
})
|
||||
|
||||
const result = await syncOpenCodeImport({
|
||||
overwriteState: true,
|
||||
})
|
||||
const result = await syncOpenCodeImport({ overwriteState: true })
|
||||
|
||||
expect(result.configImported).toBe(true)
|
||||
expect(result.stateImported).toBe(true)
|
||||
expect(result.workspaceStateExists).toBe(true)
|
||||
expect(mockWriteOpenCodeConfigFile).toHaveBeenCalledWith(
|
||||
expect.stringContaining(JSON.stringify('{"$schema":"https://opencode.ai/config.json"}'))
|
||||
)
|
||||
expect(mockEnsureDirectoryExists).toHaveBeenCalledWith('/tmp/workspace/.opencode/state')
|
||||
expect(MockSQLiteDatabase).toHaveBeenCalledWith('/import/opencode-state/opencode.db')
|
||||
expect(mockRename).toHaveBeenCalledWith(
|
||||
'/tmp/workspace/.opencode/state/opencode-import-123',
|
||||
'/tmp/workspace/.opencode/state/opencode'
|
||||
)
|
||||
await expect(readFile(workspaceConfigPath('opencode.json'), 'utf8'))
|
||||
.resolves.toBe('{"$schema":"https://opencode.ai/config.json"}')
|
||||
await expect(readFile(path.join(workspaceStateDir, 'opencode.db'))).resolves.toBeInstanceOf(Buffer)
|
||||
})
|
||||
|
||||
it('captures the previous on-disk config as last known good before importing over it', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === '/import/opencode-config/opencode.json')
|
||||
const previous = {
|
||||
path: '/tmp/workspace/.config/opencode/opencode.json',
|
||||
content: { theme: 'previous' },
|
||||
isValid: true,
|
||||
rawContent: '{"theme":"previous"}',
|
||||
updatedAt: 0,
|
||||
revision: 'rev-previous',
|
||||
sources: [{
|
||||
name: 'opencode.json' as const,
|
||||
path: '/tmp/workspace/.config/opencode/opencode.json',
|
||||
rawContent: '{"theme":"previous"}',
|
||||
content: { theme: 'previous' },
|
||||
isValid: true,
|
||||
updatedAt: 0,
|
||||
}],
|
||||
}
|
||||
mockReadOpenCodeConfigFile.mockResolvedValue(previous)
|
||||
const settingsService = { saveLastKnownGoodConfig: vi.fn() } as unknown as SettingsService
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"$schema":"https://opencode.ai/config.json"}')
|
||||
await mkdir(getConfigPath(), { recursive: true })
|
||||
await writeFile(workspaceConfigPath('opencode.jsonc'), '{"theme":"previous"}', 'utf8')
|
||||
const previous = await readOpenCodeConfigFile()
|
||||
if (previous === null) throw new Error('expected a previous workspace config to exist')
|
||||
const saveLastKnownGoodConfig = vi.fn<SettingsService['saveLastKnownGoodConfig']>()
|
||||
const settingsService = { saveLastKnownGoodConfig }
|
||||
|
||||
await syncOpenCodeImport({ overwriteState: true, settingsService })
|
||||
|
||||
expect(settingsService.saveLastKnownGoodConfig).toHaveBeenCalledWith(serializeOpenCodeConfigSnapshot(previous))
|
||||
expect(mockWriteOpenCodeConfigFile).toHaveBeenCalledWith(expect.stringContaining(JSON.stringify('{"$schema":"https://opencode.ai/config.json"}')))
|
||||
expect(saveLastKnownGoodConfig).toHaveBeenCalledWith(serializeOpenCodeConfigSnapshot(previous))
|
||||
await expect(readFile(workspaceConfigPath('opencode.json'), 'utf8'))
|
||||
.resolves.toBe('{"$schema":"https://opencode.ai/config.json"}')
|
||||
})
|
||||
|
||||
it('does not capture last known good when no previous config file exists', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === '/import/opencode-config/opencode.json')
|
||||
mockReadOpenCodeConfigFile.mockResolvedValue(null)
|
||||
const settingsService = { saveLastKnownGoodConfig: vi.fn() } as unknown as SettingsService
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"$schema":"https://opencode.ai/config.json"}')
|
||||
const saveLastKnownGoodConfig = vi.fn<SettingsService['saveLastKnownGoodConfig']>()
|
||||
const settingsService = { saveLastKnownGoodConfig }
|
||||
|
||||
await syncOpenCodeImport({ overwriteState: true, settingsService })
|
||||
|
||||
expect(settingsService.saveLastKnownGoodConfig).not.toHaveBeenCalled()
|
||||
expect(mockWriteOpenCodeConfigFile).toHaveBeenCalled()
|
||||
expect(saveLastKnownGoodConfig).not.toHaveBeenCalled()
|
||||
await expect(readFile(workspaceConfigPath('opencode.json'), 'utf8'))
|
||||
.resolves.toBe('{"$schema":"https://opencode.ai/config.json"}')
|
||||
})
|
||||
|
||||
it('does not report state imported when source db is missing', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = '/import/opencode-state'
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"$schema":"https://opencode.ai/config.json"}')
|
||||
const stateDir = path.join(home, 'host-state')
|
||||
await mkdir(stateDir, { recursive: true })
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = stateDir
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => {
|
||||
return candidate === '/import/opencode-config/opencode.json'
|
||||
|| candidate === '/import/opencode-state'
|
||||
})
|
||||
|
||||
const result = await syncOpenCodeImport({
|
||||
overwriteState: true,
|
||||
})
|
||||
const result = await syncOpenCodeImport({ overwriteState: true })
|
||||
|
||||
expect(result.configImported).toBe(true)
|
||||
expect(result.stateImported).toBe(false)
|
||||
expect(mockEnsureDirectoryExists).not.toHaveBeenCalled()
|
||||
await expect(readdir(path.join(getWorkspacePath(), '.opencode', 'state'))).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('reports the resolved import config candidate as the config source path', async () => {
|
||||
@@ -293,261 +231,154 @@ describe('opencode-import service', () => {
|
||||
})
|
||||
|
||||
it('rejects invalid importable config content with the existing error', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === '/import/opencode-config/opencode.json')
|
||||
mockReadFileContent.mockResolvedValue('{"model": 123}')
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"model": 123}')
|
||||
|
||||
await expect(syncOpenCodeImport({ overwriteState: true })).rejects.toThrow('Importable OpenCode config is invalid')
|
||||
expect(mockWriteOpenCodeConfigFile).not.toHaveBeenCalled()
|
||||
await expect(readFile(workspaceConfigPath('opencode.jsonc'), 'utf8')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('imports state without rewriting the config when importConfig is false', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = '/import/opencode-state'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => {
|
||||
return candidate === '/import/opencode-config/opencode.json'
|
||||
|| candidate === '/import/opencode-state'
|
||||
|| candidate === '/import/opencode-state/opencode.db'
|
||||
})
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"model":"test/lower"}')
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = await createHostState()
|
||||
|
||||
const result = await syncOpenCodeImport({ overwriteState: false, importConfig: false })
|
||||
|
||||
expect(result.configImported).toBe(false)
|
||||
expect(result.stateImported).toBe(true)
|
||||
expect(mockWriteOpenCodeConfigFile).not.toHaveBeenCalled()
|
||||
await expect(readFile(workspaceConfigPath('opencode.json'), 'utf8')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('reads distinct session directories from imported workspace state', async () => {
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === '/tmp/workspace/.opencode/state/opencode/opencode.db')
|
||||
await mkdir(workspaceStateDir, { recursive: true })
|
||||
createStateDatabase(path.join(workspaceStateDir, 'opencode.db'), [
|
||||
'/Users/test/project-a',
|
||||
' /Users/test/project-b/apps/web ',
|
||||
])
|
||||
|
||||
const readonlyDatabase = {
|
||||
query: vi.fn().mockReturnValue({
|
||||
all: vi.fn().mockReturnValue([
|
||||
{ directory: '/Users/test/project-a' },
|
||||
{ directory: ' /Users/test/project-b/apps/web ' },
|
||||
]),
|
||||
}),
|
||||
close: vi.fn(),
|
||||
}
|
||||
const result = await getImportedSessionDirectories()
|
||||
|
||||
MockSQLiteDatabase.mockImplementationOnce(() => readonlyDatabase)
|
||||
|
||||
const { getImportedSessionDirectories } = await import('../../src/services/opencode-import')
|
||||
const result = await getImportedSessionDirectories('/tmp/workspace/.opencode/state/opencode')
|
||||
|
||||
expect(result.directories).toEqual([
|
||||
expect(result.directories).toHaveLength(2)
|
||||
expect([...result.directories].sort()).toEqual([
|
||||
'/Users/test/project-a',
|
||||
'/Users/test/project-b/apps/web',
|
||||
])
|
||||
expect(readonlyDatabase.close).toHaveBeenCalled()
|
||||
].sort())
|
||||
})
|
||||
|
||||
it('reports stateSourcePath as null when candidate directory exists but lacks opencode.db', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = '/import/opencode-state'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => {
|
||||
if (candidate === '/import/opencode-config/opencode.json') {
|
||||
return true
|
||||
}
|
||||
if (candidate === '/import/opencode-state') {
|
||||
return true
|
||||
}
|
||||
if (candidate === '/import/opencode-state/opencode.db') {
|
||||
return false
|
||||
}
|
||||
if (candidate === '/tmp/workspace/.opencode/state/opencode/opencode.db') {
|
||||
return false
|
||||
}
|
||||
return false
|
||||
})
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"model":"test/lower"}')
|
||||
const stateDir = path.join(home, 'host-state')
|
||||
await mkdir(stateDir, { recursive: true })
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = stateDir
|
||||
|
||||
const status = await getOpenCodeImportStatus()
|
||||
|
||||
expect(status.configSourcePath).toBe('/import/opencode-config/opencode.json')
|
||||
expect(status.configSourcePath).toBe(process.env.OPENCODE_IMPORT_CONFIG_PATH)
|
||||
expect(status.stateSourcePath).toBeNull()
|
||||
expect(status.workspaceStateExists).toBe(false)
|
||||
})
|
||||
|
||||
it('prevents destructive self-import when source and target resolve to same directory', async () => {
|
||||
const { importOpenCodeStateDirectory } = await import('../../src/services/opencode-import')
|
||||
|
||||
const samePath = '/shared/opencode-state'
|
||||
mockFileExists.mockResolvedValue(true)
|
||||
mockEnsureDirectoryExists.mockResolvedValue(undefined)
|
||||
mockReaddir.mockResolvedValue([])
|
||||
|
||||
const mockRm = vi.mocked(rm)
|
||||
mockRm.mockResolvedValue(undefined)
|
||||
const samePath = path.join(home, 'shared-opencode-state')
|
||||
await mkdir(samePath, { recursive: true })
|
||||
await writeFile(path.join(samePath, 'sentinel.txt'), 'keep', 'utf8')
|
||||
|
||||
const result = await importOpenCodeStateDirectory(samePath, samePath)
|
||||
|
||||
expect(result).toBe(false)
|
||||
expect(mockRm).not.toHaveBeenCalled()
|
||||
expect(MockSQLiteDatabase).not.toHaveBeenCalled()
|
||||
await expect(readFile(path.join(samePath, 'sentinel.txt'), 'utf8')).resolves.toBe('keep')
|
||||
})
|
||||
|
||||
it('blocks import when workspace state exists and overwriteState is not enabled', async () => {
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = '/import/opencode-config/opencode.json'
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = '/import/opencode-state'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => {
|
||||
return candidate === '/import/opencode-config/opencode.json'
|
||||
|| candidate === '/import/opencode-state'
|
||||
|| candidate === '/import/opencode-state/opencode.db'
|
||||
|| candidate === '/tmp/workspace/.opencode/state/opencode/opencode.db'
|
||||
})
|
||||
process.env.OPENCODE_IMPORT_CONFIG_PATH = await writeHostConfig('opencode.json', '{"model":"test/lower"}')
|
||||
process.env.OPENCODE_IMPORT_STATE_PATH = await createHostState()
|
||||
await mkdir(workspaceStateDir, { recursive: true })
|
||||
createStateDatabase(path.join(workspaceStateDir, 'opencode.db'))
|
||||
|
||||
await expect(syncOpenCodeImport({
|
||||
overwriteState: false,
|
||||
protectExistingState: true,
|
||||
})).rejects.toThrow('OpenCode host import was blocked to protect existing workspace state')
|
||||
|
||||
expect(mockWriteOpenCodeConfigFile).not.toHaveBeenCalled()
|
||||
expect(mockEnsureDirectoryExists).not.toHaveBeenCalled()
|
||||
await expect(readFile(workspaceConfigPath('opencode.json'), 'utf8')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('stages imported state before replacing the target directory', async () => {
|
||||
const { importOpenCodeStateDirectory } = await import('../../src/services/opencode-import')
|
||||
|
||||
const sourcePath = '/import/opencode-state'
|
||||
const targetPath = '/workspace/.opencode/state/opencode'
|
||||
const stagedPath = '/workspace/.opencode/state/opencode-import-123'
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => {
|
||||
if (candidate === path.join(sourcePath, 'opencode.db')) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
mockEnsureDirectoryExists.mockResolvedValue(undefined)
|
||||
mockReaddir.mockResolvedValue([
|
||||
{ name: 'stale-file.txt', isDirectory: () => false },
|
||||
{ name: 'opencode.db', isDirectory: () => false },
|
||||
] as any)
|
||||
const mockRm = vi.mocked(rm)
|
||||
mockRm.mockResolvedValue(undefined)
|
||||
mockMkdtemp.mockResolvedValue(stagedPath)
|
||||
|
||||
const mockCp = vi.mocked(cp)
|
||||
mockCp.mockResolvedValue(undefined)
|
||||
|
||||
const mockExec = vi.fn()
|
||||
const mockClose = vi.fn()
|
||||
MockSQLiteDatabase.mockImplementationOnce(() => ({
|
||||
exec: mockExec,
|
||||
close: mockClose,
|
||||
}))
|
||||
const sourcePath = path.join(home, 'staged-source')
|
||||
const targetPath = path.join(home, 'workspace', '.opencode', 'state', 'opencode')
|
||||
await mkdir(sourcePath, { recursive: true })
|
||||
await writeFile(path.join(sourcePath, 'stale-file.txt'), 'from source', 'utf8')
|
||||
createStateDatabase(path.join(sourcePath, 'opencode.db'))
|
||||
await mkdir(targetPath, { recursive: true })
|
||||
await writeFile(path.join(targetPath, 'old-file.txt'), 'from target', 'utf8')
|
||||
|
||||
const result = await importOpenCodeStateDirectory(sourcePath, targetPath)
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect(mockCp).toHaveBeenCalledWith(
|
||||
path.join(sourcePath, 'stale-file.txt'),
|
||||
path.join(stagedPath, 'stale-file.txt'),
|
||||
expect.any(Object)
|
||||
)
|
||||
expect(mockExec).toHaveBeenCalled()
|
||||
expect(mockRm).toHaveBeenCalledWith(targetPath, { recursive: true, force: true })
|
||||
expect(mockRename).toHaveBeenCalledWith(stagedPath, targetPath)
|
||||
await expect(readFile(path.join(targetPath, 'stale-file.txt'), 'utf8')).resolves.toBe('from source')
|
||||
await expect(readFile(path.join(targetPath, 'opencode.db'))).resolves.toBeInstanceOf(Buffer)
|
||||
await expect(readFile(path.join(targetPath, 'old-file.txt'), 'utf8')).rejects.toThrow()
|
||||
await expect(readdir(path.dirname(targetPath))).resolves.toEqual(['opencode'])
|
||||
await expect(stagedDirectories(path.dirname(targetPath))).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('imports only durable host state entries and keeps nested directories named like excluded caches', async () => {
|
||||
const { importOpenCodeStateDirectory } = await import('../../src/services/opencode-import')
|
||||
const actualFs = await vi.importActual<typeof import('fs/promises')>('fs/promises')
|
||||
const rootPath = await actualFs.mkdtemp(path.join(os.tmpdir(), 'opencode-import-test-'))
|
||||
const sourcePath = path.join(rootPath, 'source')
|
||||
const targetPath = path.join(rootPath, 'workspace', '.opencode', 'state', 'opencode')
|
||||
const sourcePath = path.join(home, 'durable-source')
|
||||
const targetPath = path.join(home, 'workspace', '.opencode', 'state', 'opencode')
|
||||
|
||||
const writeSourceFile = async (relativePath: string) => {
|
||||
const filePath = path.join(sourcePath, relativePath)
|
||||
await actualFs.mkdir(path.dirname(filePath), { recursive: true })
|
||||
await actualFs.writeFile(filePath, relativePath)
|
||||
await mkdir(path.dirname(filePath), { recursive: true })
|
||||
await writeFile(filePath, relativePath)
|
||||
}
|
||||
const mockRm = vi.mocked(rm)
|
||||
|
||||
try {
|
||||
await actualFs.mkdir(path.dirname(targetPath), { recursive: true })
|
||||
for (const relativePath of [
|
||||
'opencode.db',
|
||||
'auth.json',
|
||||
'storage/x',
|
||||
'storage/log/y',
|
||||
'project/project.json',
|
||||
'plans/plan.json',
|
||||
'forge/forge.json',
|
||||
'forge.db',
|
||||
'worktree/checkout/file',
|
||||
'snapshot/snapshot',
|
||||
'repos/repo',
|
||||
'bin/binary',
|
||||
'log/server',
|
||||
'tool-output/output',
|
||||
'shell/command',
|
||||
'debug.log',
|
||||
]) {
|
||||
await writeSourceFile(relativePath)
|
||||
}
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === path.join(sourcePath, 'opencode.db'))
|
||||
mockEnsureDirectoryExists.mockResolvedValue(undefined)
|
||||
mockReaddir.mockImplementation(actualFs.readdir)
|
||||
mockMkdtemp.mockImplementation(actualFs.mkdtemp)
|
||||
mockRename.mockImplementation(actualFs.rename)
|
||||
mockRm.mockImplementation(actualFs.rm)
|
||||
vi.mocked(cp).mockImplementation(actualFs.cp)
|
||||
|
||||
const result = await importOpenCodeStateDirectory(sourcePath, targetPath)
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect((await actualFs.readdir(targetPath)).sort()).toEqual(
|
||||
['auth.json', 'forge', 'forge.db', 'plans', 'project', 'storage'].sort()
|
||||
)
|
||||
expect(await actualFs.readFile(path.join(targetPath, 'storage', 'log', 'y'), 'utf8')).toBe('storage/log/y')
|
||||
expect(MockSQLiteDatabase).toHaveBeenCalledWith(path.join(sourcePath, 'opencode.db'))
|
||||
} finally {
|
||||
await actualFs.rm(rootPath, { recursive: true, force: true })
|
||||
for (const relativePath of [
|
||||
'auth.json',
|
||||
'storage/x',
|
||||
'storage/log/y',
|
||||
'project/project.json',
|
||||
'plans/plan.json',
|
||||
'forge/forge.json',
|
||||
'forge.db',
|
||||
'worktree/checkout/file',
|
||||
'snapshot/snapshot',
|
||||
'repos/repo',
|
||||
'bin/binary',
|
||||
'log/server',
|
||||
'tool-output/output',
|
||||
'shell/command',
|
||||
'debug.log',
|
||||
]) {
|
||||
await writeSourceFile(relativePath)
|
||||
}
|
||||
createStateDatabase(path.join(sourcePath, 'opencode.db'))
|
||||
|
||||
const result = await importOpenCodeStateDirectory(sourcePath, targetPath)
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect((await readdir(targetPath)).sort()).toEqual(
|
||||
['auth.json', 'forge', 'forge.db', 'opencode.db', 'plans', 'project', 'storage'].sort(),
|
||||
)
|
||||
await expect(readFile(path.join(targetPath, 'storage', 'log', 'y'), 'utf8')).resolves.toBe('storage/log/y')
|
||||
await expect(readFile(path.join(targetPath, 'debug.log'), 'utf8')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('skips the top-level entry that contains the import destination', async () => {
|
||||
const { shouldImportOpenCodeStateEntry } = await import('../../src/services/opencode-import')
|
||||
|
||||
it('skips the top-level entry that contains the import destination', () => {
|
||||
expect(shouldImportOpenCodeStateEntry('.opencode', '/host/opencode', '/host/opencode/.opencode/state/opencode')).toBe(false)
|
||||
expect(shouldImportOpenCodeStateEntry('storage', '/host/opencode', '/host/opencode/.opencode/state/opencode')).toBe(true)
|
||||
expect(shouldImportOpenCodeStateEntry('storage', '/host/opencode', '/elsewhere/.opencode/state/opencode')).toBe(true)
|
||||
})
|
||||
|
||||
it('cleans up the staged import directory when snapshotting fails', async () => {
|
||||
const { importOpenCodeStateDirectory } = await import('../../src/services/opencode-import')
|
||||
const sourcePath = path.join(home, 'broken-source')
|
||||
const targetPath = path.join(home, 'workspace', '.opencode', 'state', 'opencode')
|
||||
await mkdir(sourcePath, { recursive: true })
|
||||
await writeFile(path.join(sourcePath, 'opencode.db'), 'not a sqlite database')
|
||||
await mkdir(targetPath, { recursive: true })
|
||||
|
||||
const sourcePath = '/import/opencode-state'
|
||||
const targetPath = '/workspace/.opencode/state/opencode'
|
||||
const stagedPath = '/workspace/.opencode/state/opencode-import-456'
|
||||
await expect(importOpenCodeStateDirectory(sourcePath, targetPath)).rejects.toThrow()
|
||||
|
||||
mockFileExists.mockImplementation(async (candidate: string) => candidate === path.join(sourcePath, 'opencode.db'))
|
||||
mockEnsureDirectoryExists.mockResolvedValue(undefined)
|
||||
mockMkdtemp.mockResolvedValue(stagedPath)
|
||||
|
||||
const mockExec = vi.fn(() => {
|
||||
throw new Error('snapshot failed')
|
||||
})
|
||||
const mockClose = vi.fn()
|
||||
MockSQLiteDatabase.mockImplementationOnce(() => ({
|
||||
exec: mockExec,
|
||||
close: mockClose,
|
||||
}))
|
||||
|
||||
const mockRm = vi.mocked(rm)
|
||||
mockRm.mockResolvedValue(undefined)
|
||||
|
||||
await expect(importOpenCodeStateDirectory(sourcePath, targetPath)).rejects.toThrow('snapshot failed')
|
||||
|
||||
expect(mockRm).toHaveBeenCalledWith(stagedPath, { recursive: true, force: true })
|
||||
expect(mockRm).not.toHaveBeenCalledWith(targetPath, { recursive: true, force: true })
|
||||
expect(mockRename).not.toHaveBeenCalled()
|
||||
await expect(readdir(path.dirname(targetPath))).resolves.toEqual(['opencode'])
|
||||
await expect(readdir(targetPath)).resolves.toEqual([])
|
||||
await expect(stagedDirectories(path.dirname(targetPath))).resolves.toEqual([])
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user