feat: add explicit OpenCode host import and repo relink (#176)

* feat: add explicit OpenCode host import and repo relink

* fix: tighten OpenCode import and relink reporting

* Add OpenCode config schema and JSONC parser imports

* Fix repo relinking and state availability detection for config-only imports

* Remove unused exports and internalize row-shape types

* Remove unused reserveScheduleJobNextRun function

---------

Co-authored-by: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
This commit is contained in:
itz4blitzandChris Scott authored and GitHub committed 2026-04-12 10:50:37 -04:00
1 parent 173dbf578e
commit 6b1a1e2005
15 files changed
+1031 -245

No files matched your search

-58
View File
@@ -40,62 +40,4 @@ export function createAuthMiddleware(auth: AuthInstance) {
})
}
export function createOptionalAuthMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session'] | null
user: Session['user'] | null
}
}>(async (c, next) => {
try {
const session = await auth.api.getSession({
headers: c.req.raw.headers,
})
if (session) {
c.set('session', session.session as Session['session'])
c.set('user', session.user as Session['user'])
} else {
c.set('session', null)
c.set('user', null)
}
} catch {
c.set('session', null)
c.set('user', null)
}
await next()
})
}
export function createAdminMiddleware(auth: AuthInstance) {
return createMiddleware<{
Variables: {
session: Session['session']
user: Session['user']
}
}>(async (c, next) => {
let session
try {
session = await auth.api.getSession({
headers: c.req.raw.headers,
})
} catch (error) {
logger.error('Session lookup failed', { error })
return c.json({ error: 'Internal Server Error' }, 500)
}
if (!session) {
return c.json({ error: 'Unauthorized' }, 401)
}
const user = session.user as Session['user']
if (user.role !== 'admin') {
return c.json({ error: 'Forbidden: Admin access required' }, 403)
}
c.set('session', session.session as Session['session'])
c.set('user', user)
await next()
})
}
-49
View File
@@ -34,10 +34,6 @@ function markApplied(db: Database, migration: Migration): void {
.run(migration.version, migration.name, Date.now())
}
function markReverted(db: Database, version: number): void {
db.prepare('DELETE FROM schema_migrations WHERE version = ?').run(version)
}
export function migrate(db: Database, migrations: Migration[]): void {
ensureMigrationsTable(db)
@@ -70,49 +66,4 @@ export function migrate(db: Database, migrations: Migration[]): void {
logger.info('All migrations applied successfully')
}
export function rollback(db: Database, migrations: Migration[], targetVersion?: number): void {
ensureMigrationsTable(db)
const applied = getAppliedVersions(db)
const sorted = [...migrations]
.filter(m => applied.has(m.version))
.sort((a, b) => b.version - a.version)
if (sorted.length === 0) {
logger.info('No migrations to rollback')
return
}
const latest = sorted[0]
if (!latest) {
logger.info('No migrations to rollback')
return
}
const target = targetVersion ?? latest.version - 1
const toRevert = sorted.filter(m => m.version > target)
if (toRevert.length === 0) {
logger.info('No migrations to rollback')
return
}
logger.info(`Rolling back ${toRevert.length} migration(s) to version ${target}`)
for (const migration of toRevert) {
logger.info(`Reverting migration ${migration.version}: ${migration.name}`)
db.run('BEGIN TRANSACTION')
try {
migration.down(db)
markReverted(db, migration.version)
db.run('COMMIT')
logger.info(`Migration ${migration.version} reverted successfully`)
} catch (error) {
db.run('ROLLBACK')
logger.error(`Rollback of migration ${migration.version} failed:`, error)
throw error
}
}
logger.info('Rollback completed successfully')
}
+1 -1
View File
@@ -4,7 +4,7 @@ import { getReposPath } from '@opencode-manager/shared/config/env'
import { getErrorMessage } from '../utils/error-utils'
import path from 'path'
export interface RepoRow {
interface RepoRow {
id: number
repo_url?: string
local_path: string
-5
View File
@@ -204,11 +204,6 @@ export function deleteScheduleJob(db: Database, repoId: number, jobId: number):
return result.changes > 0
}
export function reserveScheduleJobNextRun(db: Database, repoId: number, jobId: number, nextRunAt: number): void {
const stmt = db.prepare('UPDATE schedule_jobs SET next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
stmt.run(nextRunAt, Date.now(), repoId, jobId)
}
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
+16 -115
View File
@@ -2,10 +2,7 @@ import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { serveStatic } from '@hono/node-server/serve-static'
import os from 'os'
import path from 'path'
import { cp, readdir, readFile, rm } from 'fs/promises'
import { Database as SQLiteDatabase } from 'bun:sqlite'
import { readFile } from 'fs/promises'
import { initializeDatabase } from './db/schema'
import { createRepoRoutes } from './routes/repos'
import { createIPCServer, type IPCServer } from './ipc/ipcServer'
@@ -47,6 +44,9 @@ import { proxyRequest, proxyMcpAuthStart, proxyMcpAuthAuthenticate } from './ser
import { NotificationService } from './services/notification'
import { ScheduleRunner, ScheduleService } from './services/schedules'
import { migrateGlobalSkills } from './services/skills'
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { parse as parseJsonc } from 'jsonc-parser'
import { logger } from './utils/logger'
import {
@@ -58,8 +58,7 @@ import {
getDatabasePath,
ENV
} from '@opencode-manager/shared/config/env'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { parse as parseJsonc } from 'jsonc-parser'
const { PORT, HOST } = ENV.SERVER
const DB_PATH = getDatabasePath()
@@ -86,72 +85,6 @@ import { DEFAULT_AGENTS_MD } from './constants'
let ipcServer: IPCServer | undefined
const gitAuthService = new GitAuthService()
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
function getImportPathCandidates(envKey: string, fallbackPath: string): string[] {
const candidates = [process.env[envKey], fallbackPath]
.filter((value): value is string => Boolean(value))
.map((value) => path.resolve(value))
return Array.from(new Set(candidates))
}
async function getFirstExistingPath(paths: string[]): Promise<string | undefined> {
for (const candidate of paths) {
if (await fileExists(candidate)) {
return candidate
}
}
return undefined
}
function escapeSqliteValue(value: string): string {
return value.replace(/'/g, "''")
}
async function copyOpenCodeStateFiles(sourcePath: string, targetPath: string): Promise<void> {
const entries = await readdir(sourcePath, { withFileTypes: true })
for (const entry of entries) {
if (OPENCODE_STATE_DB_FILENAMES.has(entry.name)) {
continue
}
await cp(path.join(sourcePath, entry.name), path.join(targetPath, entry.name), {
recursive: true,
force: false,
errorOnExist: false,
})
}
}
async function snapshotOpenCodeDatabase(sourcePath: string, targetPath: string): Promise<void> {
await rm(targetPath, { force: true })
const database = new SQLiteDatabase(sourcePath)
try {
database.exec(`VACUUM INTO '${escapeSqliteValue(targetPath)}'`)
} finally {
database.close()
}
}
async function importOpenCodeStateDirectory(sourcePath: string, targetPath: string): Promise<void> {
await ensureDirectoryExists(targetPath)
await copyOpenCodeStateFiles(sourcePath, targetPath)
const sourceDbPath = path.join(sourcePath, 'opencode.db')
if (!await fileExists(sourceDbPath)) {
return
}
await rm(path.join(targetPath, 'opencode.db-shm'), { force: true })
await rm(path.join(targetPath, 'opencode.db-wal'), { force: true })
await snapshotOpenCodeDatabase(sourceDbPath, path.join(targetPath, 'opencode.db'))
}
async function ensureDefaultConfigExists(): Promise<void> {
const settingsService = new SettingsService(db)
const workspaceConfigPath = getOpenCodeConfigFilePath()
@@ -188,36 +121,13 @@ async function ensureDefaultConfigExists(): Promise<void> {
}
}
const importConfigPath = await getFirstExistingPath(
getImportPathCandidates(
'OPENCODE_IMPORT_CONFIG_PATH',
path.join(os.homedir(), '.config/opencode/opencode.json')
)
)
const { configSourcePath: importConfigPath } = await getOpenCodeImportStatus()
if (importConfigPath) {
logger.info(`Found importable OpenCode config at ${importConfigPath}, importing...`)
try {
const rawContent = await readFileContent(importConfigPath)
const parsed = parseJsonc(rawContent)
const validation = OpenCodeConfigSchema.safeParse(parsed)
if (validation.success) {
const existingDefault = settingsService.getOpenCodeConfigByName('default')
if (existingDefault) {
settingsService.updateOpenCodeConfig('default', {
content: rawContent,
isDefault: true,
})
} else {
settingsService.createOpenCodeConfig({
name: 'default',
content: rawContent,
isDefault: true,
})
}
await writeFileContent(workspaceConfigPath, rawContent)
const result = await syncOpenCodeImport({ db, overwriteState: false })
if (result.configImported) {
logger.info(`Imported OpenCode config from ${importConfigPath} to workspace`)
return
}
@@ -249,28 +159,19 @@ async function ensureDefaultConfigExists(): Promise<void> {
async function ensureHomeStateImported(): Promise<void> {
try {
const workspaceStateRoot = path.join(getWorkspacePath(), '.opencode', 'state')
const workspaceStatePath = path.join(workspaceStateRoot, 'opencode')
const workspaceStateDbPath = path.join(workspaceStatePath, 'opencode.db')
if (await fileExists(workspaceStateDbPath)) {
const status = await getOpenCodeImportStatus()
if (status.workspaceStateExists) {
return
}
const importStatePath = await getFirstExistingPath(
getImportPathCandidates(
'OPENCODE_IMPORT_STATE_PATH',
path.join(os.homedir(), '.local', 'share', 'opencode')
)
)
if (!importStatePath) {
if (!status.stateSourcePath) {
return
}
await ensureDirectoryExists(workspaceStateRoot)
await importOpenCodeStateDirectory(importStatePath, workspaceStatePath)
logger.info(`Imported OpenCode state from ${importStatePath}`)
const result = await syncOpenCodeImport({ db, overwriteState: false })
if (result.stateImported) {
logger.info(`Imported OpenCode state from ${status.stateSourcePath}`)
}
} catch (error) {
logger.warn('Failed to import OpenCode state, continuing without imported state', error)
}
@@ -359,7 +260,7 @@ const protectedApi = new Hono()
protectedApi.use('/*', requireAuth)
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService))
protectedApi.route('/settings', createSettingsRoutes(db))
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService))
protectedApi.route('/files', createFileRoutes())
protectedApi.route('/providers', createProvidersRoutes())
protectedApi.route('/oauth', createOAuthRoutes())
+75 -1
View File
@@ -20,10 +20,13 @@ import {
} from '@opencode-manager/shared'
import { logger } from '../utils/logger'
import { opencodeServerManager } from '../services/opencode-single-server'
import type { GitAuthService } from '../services/git-auth'
import { DEFAULT_AGENTS_MD } from '../constants'
import { validateSSHPrivateKey } from '../utils/ssh-validation'
import { encryptSecret } from '../utils/crypto'
import { compareVersions, isValidVersion } from '../utils/version-utils'
import { getImportedSessionDirectories, getOpenCodeImportStatus, syncOpenCodeImport } from '../services/opencode-import'
import { relinkReposFromSessionDirectories } from '../services/repo'
import {
listManagedSkills,
getSkill,
@@ -153,6 +156,10 @@ const TestSSHConnectionSchema = z.object({
passphrase: z.string().optional(),
})
const SyncOpenCodeImportSchema = z.object({
overwriteState: z.boolean().optional(),
})
async function extractOpenCodeError(response: Response, defaultError: string): Promise<string> {
const errorObj = await response.json().catch(() => null)
@@ -161,7 +168,7 @@ async function extractOpenCodeError(response: Response, defaultError: string): P
: defaultError
}
export function createSettingsRoutes(db: Database) {
export function createSettingsRoutes(db: Database, gitAuthService: GitAuthService) {
const app = new Hono()
const settingsService = new SettingsService(db)
@@ -432,6 +439,73 @@ export function createSettingsRoutes(db: Database) {
}
})
app.get('/opencode-import/status', async (c) => {
try {
return c.json(await getOpenCodeImportStatus())
} catch (error) {
logger.error('Failed to get OpenCode import status:', error)
return c.json({
error: 'Failed to get OpenCode import status',
details: error instanceof Error ? error.message : 'Unknown error'
}, 500)
}
})
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 ?? true,
})
if (!result.configImported && !result.stateImported) {
return c.json({
error: 'No importable OpenCode host data found',
...result,
}, 404)
}
let relinkedRepos
if (result.stateImported) {
const importedSessions = await getImportedSessionDirectories(result.workspaceStatePath)
relinkedRepos = await relinkReposFromSessionDirectories(db, gitAuthService, importedSessions.directories)
} else {
relinkedRepos = {
repos: [],
relinkedCount: 0,
existingCount: 0,
nonRepoPathCount: 0,
duplicatePathCount: 0,
errors: [],
}
}
opencodeServerManager.clearStartupError()
await opencodeServerManager.restart()
return c.json({
success: true,
message: 'Imported existing OpenCode host data and restarted the server',
serverRestarted: true,
relinkedRepos,
...result,
})
} catch (error) {
logger.error('Failed to import existing OpenCode host data:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid OpenCode import request', details: error.issues }, 400)
}
return c.json({
error: 'Failed to import existing OpenCode host data',
details: error instanceof Error ? error.message : 'Unknown error'
}, 500)
}
})
app.post('/opencode-reload', async (c) => {
try {
logger.info('OpenCode configuration reload requested')
+221
View File
@@ -0,0 +1,221 @@
import os from 'os'
import path from 'path'
import { cp, readdir, rm } from 'fs/promises'
import { Database as SQLiteDatabase, type Database } from 'bun:sqlite'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
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'
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
export interface OpenCodeImportStatus {
configSourcePath: string | null
stateSourcePath: string | null
workspaceConfigPath: string
workspaceStatePath: string
workspaceStateExists: boolean
}
export interface SyncOpenCodeImportOptions {
db: Database
userId?: string
overwriteState?: boolean
}
export interface SyncOpenCodeImportResult extends OpenCodeImportStatus {
configImported: boolean
stateImported: boolean
}
export interface ImportedSessionDirectorySummary {
directories: string[]
}
export function getImportPathCandidates(envKey: string, fallbackPath: string): string[] {
const candidates = [process.env[envKey], fallbackPath]
.filter((value): value is string => Boolean(value))
.map((value) => path.resolve(value))
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
}
async function getFirstExistingPathWithDatabase(paths: string[]): Promise<string | null> {
for (const candidate of paths) {
if (await fileExists(candidate) && await fileExists(path.join(candidate, 'opencode.db'))) {
return candidate
}
}
return null
}
function escapeSqliteValue(value: string): string {
return value.replace(/'/g, "''")
}
async function copyOpenCodeStateFiles(sourcePath: string, targetPath: string): Promise<void> {
const entries = await readdir(sourcePath, { withFileTypes: true })
for (const entry of entries) {
if (OPENCODE_STATE_DB_FILENAMES.has(entry.name)) {
continue
}
await cp(path.join(sourcePath, entry.name), path.join(targetPath, entry.name), {
recursive: true,
force: true,
errorOnExist: false,
})
}
}
function snapshotOpenCodeDatabase(sourcePath: string, targetPath: string): void {
const database = new SQLiteDatabase(sourcePath)
try {
database.exec(`VACUUM INTO '${escapeSqliteValue(targetPath)}'`)
} finally {
database.close()
}
}
export async function importOpenCodeStateDirectory(sourcePath: string, targetPath: string): Promise<boolean> {
const resolvedSourcePath = path.resolve(sourcePath)
const resolvedTargetPath = path.resolve(targetPath)
const sourceDbPath = path.join(resolvedSourcePath, 'opencode.db')
if (!await fileExists(sourceDbPath)) {
return false
}
if (resolvedSourcePath === resolvedTargetPath) {
return false
}
await ensureDirectoryExists(resolvedTargetPath)
const existingEntries = await readdir(resolvedTargetPath, { withFileTypes: true })
for (const entry of existingEntries) {
if (!OPENCODE_STATE_DB_FILENAMES.has(entry.name)) {
await rm(path.join(resolvedTargetPath, entry.name), { recursive: true, force: true })
}
}
await rm(path.join(resolvedTargetPath, 'opencode.db'), { force: true })
await rm(path.join(resolvedTargetPath, 'opencode.db-shm'), { force: true })
await rm(path.join(resolvedTargetPath, 'opencode.db-wal'), { force: true })
await copyOpenCodeStateFiles(resolvedSourcePath, resolvedTargetPath)
snapshotOpenCodeDatabase(sourceDbPath, path.join(resolvedTargetPath, 'opencode.db'))
return true
}
export async function getOpenCodeImportStatus(): Promise<OpenCodeImportStatus> {
const workspaceConfigPath = getOpenCodeConfigFilePath()
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 stateSourcePath = await getFirstExistingPathWithDatabase(
getImportPathCandidates('OPENCODE_IMPORT_STATE_PATH', path.join(os.homedir(), '.local', 'share', 'opencode'))
)
return {
configSourcePath,
stateSourcePath,
workspaceConfigPath,
workspaceStatePath,
workspaceStateExists,
}
}
async function importOpenCodeConfigFromSource(db: Database, userId: string, sourcePath: string, workspaceConfigPath: string): Promise<boolean> {
const rawContent = await readFileContent(sourcePath)
const parsed = parseJsonc(rawContent)
const validation = OpenCodeConfigSchema.safeParse(parsed)
if (!validation.success) {
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)
return true
}
export async function syncOpenCodeImport(options: SyncOpenCodeImportOptions): Promise<SyncOpenCodeImportResult> {
const initialStatus = await getOpenCodeImportStatus()
const userId = options.userId || 'default'
let configImported = false
let stateImported = false
if (initialStatus.configSourcePath) {
configImported = await importOpenCodeConfigFromSource(options.db, userId, initialStatus.configSourcePath, initialStatus.workspaceConfigPath)
}
if (initialStatus.stateSourcePath && ((options.overwriteState ?? true) || !initialStatus.workspaceStateExists)) {
stateImported = await importOpenCodeStateDirectory(initialStatus.stateSourcePath, initialStatus.workspaceStatePath)
}
const finalStatus = await getOpenCodeImportStatus()
return {
...finalStatus,
configImported,
stateImported,
}
}
export async function getImportedSessionDirectories(workspaceStatePath?: string): Promise<ImportedSessionDirectorySummary> {
const statePath = workspaceStatePath || path.join(getWorkspacePath(), '.opencode', 'state', 'opencode')
const stateDbPath = path.join(statePath, 'opencode.db')
if (!await fileExists(stateDbPath)) {
return { directories: [] }
}
const database = new SQLiteDatabase(stateDbPath, { readonly: true })
try {
const rows = database
.query("SELECT DISTINCT directory FROM session WHERE directory IS NOT NULL AND TRIM(directory) != '' ORDER BY directory")
.all() as Array<{ directory: string }>
return {
directories: rows
.map((row) => row.directory.trim())
.filter(Boolean),
}
} finally {
database.close()
}
}
+80
View File
@@ -230,6 +230,16 @@ async function safeGetCurrentBranch(repoPath: string, env: Record<string, string
}
}
async function findGitRepoRoot(targetPath: string, env: Record<string, string>): Promise<string | null> {
try {
const resolvedPath = normalizeAbsolutePath(targetPath)
const repoRoot = await executeCommand(['git', '-C', resolvedPath, 'rev-parse', '--show-toplevel'], { env, silent: true })
return normalizeAbsolutePath(repoRoot.trim())
} catch {
return null
}
}
async function registerExistingLocalRepo(
database: Database,
gitAuthService: GitAuthService,
@@ -375,6 +385,76 @@ export async function discoverLocalRepos(
}
}
export async function relinkReposFromSessionDirectories(
database: Database,
gitAuthService: GitAuthService,
directories: string[]
): Promise<{
repos: Repo[]
relinkedCount: number
existingCount: number
nonRepoPathCount: number
duplicatePathCount: number
errors: Array<{ path: string; error: string }>
}> {
const env = gitAuthService.getGitEnvironment()
const errors: Array<{ path: string; error: string }> = []
const uniqueRepoRoots = new Set<string>()
let nonRepoPathCount = 0
let duplicatePathCount = 0
for (const directory of directories) {
const normalizedDirectory = normalizeInputPath(directory)
if (!normalizedDirectory) {
nonRepoPathCount += 1
continue
}
const repoRoot = await findGitRepoRoot(normalizedDirectory, env)
if (!repoRoot) {
nonRepoPathCount += 1
continue
}
if (uniqueRepoRoots.has(repoRoot)) {
duplicatePathCount += 1
continue
}
uniqueRepoRoots.add(repoRoot)
}
const repos: Repo[] = []
let relinkedCount = 0
let existingCount = 0
for (const repoRoot of Array.from(uniqueRepoRoots).sort((left, right) => left.localeCompare(right))) {
try {
const result = await registerExistingLocalRepo(database, gitAuthService, repoRoot)
repos.push(result.repo)
if (result.existed) {
existingCount += 1
} else {
relinkedCount += 1
}
} catch (error: unknown) {
errors.push({
path: repoRoot,
error: getErrorMessage(error),
})
}
}
return {
repos,
relinkedCount,
existingCount,
nonRepoPathCount,
duplicatePathCount,
errors,
}
}
async function checkoutBranchSafely(repoPath: string, branch: string, env: Record<string, string>): Promise<void> {
const sanitizedBranch = branch
.replace(/^refs\/heads\//, '')
-13
View File
@@ -354,19 +354,6 @@ describe('schedule database queries', () => {
expect(result).toBe(false)
})
it('reserves the next run time for a schedule job', () => {
const nextRunAt = Date.now() + 3600000
const stmt = {
run: vi.fn(),
}
mockDb.prepare.mockReturnValue(stmt)
schedulesDb.reserveScheduleJobNextRun(mockDb, 42, 7, nextRunAt)
expect(mockDb.prepare).toHaveBeenCalledWith('UPDATE schedule_jobs SET next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
expect(stmt.run).toHaveBeenCalledWith(nextRunAt, expect.any(Number), 42, 7)
})
it('updates the run state of a schedule job', () => {
const lastRunAt = Date.now()
const nextRunAt = Date.now() + 3600000
+155 -1
View File
@@ -65,6 +65,16 @@ vi.mock('../../src/services/opencode-single-server', () => ({
},
}))
vi.mock('../../src/services/opencode-import', () => ({
getOpenCodeImportStatus: vi.fn(),
syncOpenCodeImport: vi.fn(),
getImportedSessionDirectories: vi.fn(),
}))
vi.mock('../../src/services/repo', () => ({
relinkReposFromSessionDirectories: vi.fn(),
}))
vi.mock('@opencode-manager/shared/config/env', () => ({
getWorkspacePath: vi.fn(() => '/tmp/test-workspace'),
getReposPath: vi.fn(() => '/tmp/test-repos'),
@@ -90,6 +100,8 @@ vi.mock('@opencode-manager/shared/config/env', () => ({
}))
import { createSettingsRoutes } from '../../src/routes/settings'
import { getImportedSessionDirectories, getOpenCodeImportStatus, syncOpenCodeImport } from '../../src/services/opencode-import'
import { relinkReposFromSessionDirectories } from '../../src/services/repo'
import { opencodeServerManager } from '../../src/services/opencode-single-server'
const mockExecSync = execSync as ReturnType<typeof vi.fn>
@@ -99,6 +111,10 @@ const mockFetchVersion = opencodeServerManager.fetchVersion as ReturnType<typeof
const mockReloadConfig = opencodeServerManager.reloadConfig as ReturnType<typeof vi.fn>
const mockRestart = opencodeServerManager.restart as ReturnType<typeof vi.fn>
const mockClearStartupError = opencodeServerManager.clearStartupError as ReturnType<typeof vi.fn>
const mockGetOpenCodeImportStatus = getOpenCodeImportStatus as ReturnType<typeof vi.fn>
const mockSyncOpenCodeImport = syncOpenCodeImport as ReturnType<typeof vi.fn>
const mockGetImportedSessionDirectories = getImportedSessionDirectories as ReturnType<typeof vi.fn>
const mockRelinkReposFromSessionDirectories = relinkReposFromSessionDirectories as ReturnType<typeof vi.fn>
describe('Settings Routes - OpenCode Upgrade', () => {
let settingsApp: ReturnType<typeof createSettingsRoutes>
@@ -112,13 +128,151 @@ describe('Settings Routes - OpenCode Upgrade', () => {
mockReloadConfig.mockReset()
mockRestart.mockReset()
mockClearStartupError.mockReset()
mockGetOpenCodeImportStatus.mockReset()
mockSyncOpenCodeImport.mockReset()
mockGetImportedSessionDirectories.mockReset()
mockRelinkReposFromSessionDirectories.mockReset()
testDb = {} as any
settingsApp = createSettingsRoutes(testDb)
settingsApp = createSettingsRoutes(testDb, { getGitEnvironment: vi.fn().mockReturnValue({}) } as any)
mockReloadConfig.mockResolvedValue(undefined)
mockRestart.mockResolvedValue(undefined)
mockClearStartupError.mockReturnValue(undefined)
mockGetOpenCodeImportStatus.mockResolvedValue({
configSourcePath: null,
stateSourcePath: null,
workspaceConfigPath: '/tmp/test-workspace/.config/opencode/opencode.json',
workspaceStatePath: '/tmp/test-workspace/.opencode/state/opencode',
workspaceStateExists: false,
})
mockGetImportedSessionDirectories.mockResolvedValue({
directories: ['/Users/test/project-a', '/Users/test/project-b/apps/web'],
})
mockRelinkReposFromSessionDirectories.mockResolvedValue({
repos: [],
relinkedCount: 0,
existingCount: 0,
nonRepoPathCount: 0,
duplicatePathCount: 0,
errors: [],
})
})
describe('OpenCode import routes', () => {
it('should return import status', async () => {
mockGetOpenCodeImportStatus.mockResolvedValueOnce({
configSourcePath: '/import/opencode-config/opencode.json',
stateSourcePath: '/import/opencode-state',
workspaceConfigPath: '/tmp/test-workspace/.config/opencode/opencode.json',
workspaceStatePath: '/tmp/test-workspace/.opencode/state/opencode',
workspaceStateExists: true,
})
const req = new Request('http://localhost/opencode-import/status')
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.configSourcePath).toBe('/import/opencode-config/opencode.json')
expect(json.stateSourcePath).toBe('/import/opencode-state')
expect(mockGetOpenCodeImportStatus).toHaveBeenCalled()
})
it('should import host OpenCode data and restart the server', async () => {
mockSyncOpenCodeImport.mockResolvedValueOnce({
configSourcePath: '/import/opencode-config/opencode.json',
stateSourcePath: '/import/opencode-state',
workspaceConfigPath: '/tmp/test-workspace/.config/opencode/opencode.json',
workspaceStatePath: '/tmp/test-workspace/.opencode/state/opencode',
workspaceStateExists: true,
configImported: true,
stateImported: true,
})
const req = new Request('http://localhost/opencode-import?userId=default', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ overwriteState: true }),
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.success).toBe(true)
expect(json.serverRestarted).toBe(true)
expect(mockSyncOpenCodeImport).toHaveBeenCalledWith({
db: testDb,
userId: 'default',
overwriteState: true,
})
expect(mockGetImportedSessionDirectories).toHaveBeenCalledWith('/tmp/test-workspace/.opencode/state/opencode')
expect(mockRelinkReposFromSessionDirectories).toHaveBeenCalled()
expect(mockClearStartupError).toHaveBeenCalled()
expect(mockRestart).toHaveBeenCalled()
})
it('should return 404 when no importable host data exists', async () => {
mockSyncOpenCodeImport.mockResolvedValueOnce({
configSourcePath: null,
stateSourcePath: null,
workspaceConfigPath: '/tmp/test-workspace/.config/opencode/opencode.json',
workspaceStatePath: '/tmp/test-workspace/.opencode/state/opencode',
workspaceStateExists: true,
configImported: false,
stateImported: false,
})
const req = new Request('http://localhost/opencode-import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ overwriteState: true }),
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(404)
expect(json.error).toBe('No importable OpenCode host data found')
expect(mockRestart).not.toHaveBeenCalled()
})
it('should not call relink functions when only config is imported (stateImported: false)', async () => {
mockSyncOpenCodeImport.mockResolvedValueOnce({
configSourcePath: '/import/opencode-config/opencode.json',
stateSourcePath: '/import/opencode-state',
workspaceConfigPath: '/tmp/test-workspace/.config/opencode/opencode.json',
workspaceStatePath: '/tmp/test-workspace/.opencode/state/opencode',
workspaceStateExists: false,
configImported: true,
stateImported: false,
})
const req = new Request('http://localhost/opencode-import?userId=default', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ overwriteState: true }),
})
const res = await settingsApp.fetch(req)
const json = await res.json() as Record<string, unknown>
expect(res.status).toBe(200)
expect(json.success).toBe(true)
expect(json.serverRestarted).toBe(true)
expect(json.configImported).toBe(true)
expect(json.stateImported).toBe(false)
expect(mockGetImportedSessionDirectories).not.toHaveBeenCalled()
expect(mockRelinkReposFromSessionDirectories).not.toHaveBeenCalled()
expect(mockClearStartupError).toHaveBeenCalled()
expect(mockRestart).toHaveBeenCalled()
expect(json.relinkedRepos).toEqual({
repos: [],
relinkedCount: 0,
existingCount: 0,
nonRepoPathCount: 0,
duplicatePathCount: 0,
errors: [],
})
})
})
describe('POST /opencode-upgrade', () => {
@@ -0,0 +1,270 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Database } from 'bun:sqlite'
vi.mock('fs/promises', () => ({
cp: vi.fn(),
readdir: 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(),
writeFileContent: vi.fn(),
}))
vi.mock('../../src/services/settings', () => ({
SettingsService: vi.fn(),
}))
vi.mock('@opencode-manager/shared/config/env', () => ({
getOpenCodeConfigFilePath: vi.fn(() => '/tmp/workspace/.config/opencode/opencode.json'),
getWorkspacePath: vi.fn(() => '/tmp/workspace'),
}))
import path from 'path'
import { readdir, rm, cp } from 'fs/promises'
import { Database as SQLiteDatabase } from 'bun:sqlite'
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent } from '../../src/services/file-operations'
import { SettingsService } from '../../src/services/settings'
import { getOpenCodeImportStatus, syncOpenCodeImport } from '../../src/services/opencode-import'
const mockReaddir = readdir as unknown as ReturnType<typeof vi.fn>
const mockFileExists = fileExists as ReturnType<typeof vi.fn>
const mockReadFileContent = readFileContent as ReturnType<typeof vi.fn>
const mockWriteFileContent = writeFileContent as ReturnType<typeof vi.fn>
const mockEnsureDirectoryExists = ensureDirectoryExists as ReturnType<typeof vi.fn>
const MockSettingsService = SettingsService as unknown as ReturnType<typeof vi.fn>
const MockSQLiteDatabase = SQLiteDatabase as unknown as ReturnType<typeof vi.fn>
describe('opencode-import service', () => {
const mockDb = {} as unknown as Database
const settingsService = {
getOpenCodeConfigByName: vi.fn(),
updateOpenCodeConfig: vi.fn(),
createOpenCodeConfig: vi.fn(),
}
beforeEach(() => {
vi.clearAllMocks()
MockSettingsService.mockImplementation(() => settingsService)
mockReadFileContent.mockResolvedValue('{"$schema":"https://opencode.ai/config.json"}')
mockReaddir.mockResolvedValue([])
})
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
})
const status = await getOpenCodeImportStatus()
expect(status).toEqual({
configSourcePath: '/import/opencode-config/opencode.json',
stateSourcePath: '/import/opencode-state',
workspaceConfigPath: '/tmp/workspace/.config/opencode/opencode.json',
workspaceStatePath: '/tmp/workspace/.opencode/state/opencode',
workspaceStateExists: true,
})
})
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'
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'
})
settingsService.getOpenCodeConfigByName.mockReturnValue({ name: 'default' })
const result = await syncOpenCodeImport({
db: mockDb,
userId: 'default',
overwriteState: true,
})
expect(result.configImported).toBe(true)
expect(result.stateImported).toBe(true)
expect(result.workspaceStateExists).toBe(true)
expect(settingsService.updateOpenCodeConfig).toHaveBeenCalledWith('default', {
content: '{"$schema":"https://opencode.ai/config.json"}',
isDefault: true,
}, 'default')
expect(mockWriteFileContent).toHaveBeenCalledWith(
'/tmp/workspace/.config/opencode/opencode.json',
'{"$schema":"https://opencode.ai/config.json"}'
)
expect(mockEnsureDirectoryExists).toHaveBeenCalledWith('/tmp/workspace/.opencode/state/opencode')
expect(MockSQLiteDatabase).toHaveBeenCalledWith('/import/opencode-state/opencode.db')
})
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'
mockFileExists.mockImplementation(async (candidate: string) => {
return candidate === '/import/opencode-config/opencode.json'
|| candidate === '/import/opencode-state'
})
const result = await syncOpenCodeImport({
db: mockDb,
userId: 'default',
overwriteState: true,
})
expect(result.configImported).toBe(true)
expect(result.stateImported).toBe(false)
expect(mockEnsureDirectoryExists).not.toHaveBeenCalled()
})
it('reads distinct session directories from imported workspace state', async () => {
mockFileExists.mockImplementation(async (candidate: string) => candidate === '/tmp/workspace/.opencode/state/opencode/opencode.db')
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(),
}
MockSQLiteDatabase.mockImplementationOnce(() => readonlyDatabase)
const { getImportedSessionDirectories } = await import('../../src/services/opencode-import')
const result = await getImportedSessionDirectories('/tmp/workspace/.opencode/state/opencode')
expect(result.directories).toEqual([
'/Users/test/project-a',
'/Users/test/project-b/apps/web',
])
expect(readonlyDatabase.close).toHaveBeenCalled()
})
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
})
const status = await getOpenCodeImportStatus()
expect(status.configSourcePath).toBe('/import/opencode-config/opencode.json')
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 result = await importOpenCodeStateDirectory(samePath, samePath)
expect(result).toBe(false)
expect(mockRm).not.toHaveBeenCalled()
expect(MockSQLiteDatabase).not.toHaveBeenCalled()
})
it('removes stale non-DB artifacts before copying new state during overwrite import', async () => {
const { importOpenCodeStateDirectory } = await import('../../src/services/opencode-import')
const sourcePath = '/import/opencode-state'
const targetPath = '/workspace/.opencode/state/opencode'
mockFileExists.mockImplementation(async (candidate: string) => {
if (candidate === path.join(sourcePath, 'opencode.db')) {
return true
}
if (candidate === path.join(targetPath, 'opencode.db')) {
return true
}
return false
})
mockReaddir.mockResolvedValue([
{ name: 'stale-file.txt', isDirectory: () => false },
{ name: 'stale-folder', isDirectory: () => true },
{ name: 'opencode.db', isDirectory: () => false },
{ name: 'opencode.db-shm', isDirectory: () => false },
{ name: 'opencode.db-wal', isDirectory: () => false },
] as any)
mockEnsureDirectoryExists.mockResolvedValue(undefined)
const mockRm = vi.mocked(rm)
mockRm.mockResolvedValue(undefined)
const mockCp = vi.mocked(cp)
mockCp.mockResolvedValue(undefined)
const mockExec = vi.fn()
const mockClose = vi.fn()
MockSQLiteDatabase.mockImplementationOnce(() => ({
exec: mockExec,
close: mockClose,
}))
const result = await importOpenCodeStateDirectory(sourcePath, targetPath)
expect(result).toBe(true)
expect(mockRm).toHaveBeenCalledWith(
path.join(targetPath, 'stale-file.txt'),
{ recursive: true, force: true }
)
expect(mockRm).toHaveBeenCalledWith(
path.join(targetPath, 'stale-folder'),
{ recursive: true, force: true }
)
expect(mockCp).toHaveBeenCalled()
expect(mockExec).toHaveBeenCalled()
})
})
+72
View File
@@ -347,4 +347,76 @@ describe('repo service', () => {
},
])
})
it('relinks imported session directories to nearest git repo roots', async () => {
const { relinkReposFromSessionDirectories } = await import('../../src/services/repo')
const database = {} as never
const repoRoot = '/Users/test/projects/app-one'
const aliasPath = path.join(getReposPath(), 'app-one')
getRepoByLocalPath.mockReturnValue(null)
getRepoBySourcePath.mockReturnValue(null)
createRepo.mockImplementation((_, input) => ({
id: 5,
localPath: input.localPath,
sourcePath: input.sourcePath,
fullPath: input.sourcePath ?? path.join(getReposPath(), input.localPath),
branch: input.branch,
defaultBranch: input.defaultBranch,
cloneStatus: input.cloneStatus,
clonedAt: input.clonedAt,
isLocal: true,
isWorktree: input.isWorktree,
}))
lstat.mockImplementation(async (targetPath: string) => {
if (targetPath === repoRoot || targetPath === path.join(repoRoot, '.git')) {
return createDirectoryStat()
}
if (targetPath === aliasPath) {
throw createEnoentError(targetPath)
}
throw createEnoentError(targetPath)
})
executeCommand.mockImplementation(async (args: string[]) => {
if (args.includes('--show-toplevel')) {
if (args[2] === '/Users/test/projects/not-a-repo') {
throw new Error('not a git repository')
}
return `${repoRoot}\n`
}
if (args.includes('--git-dir')) {
return '.git'
}
if (args.includes('HEAD') && !args.includes('--abbrev-ref')) {
return 'abc123'
}
if (args.includes('--abbrev-ref')) {
return 'main'
}
return ''
})
const result = await relinkReposFromSessionDirectories(database, mockGitAuthService, [
'/Users/test/projects/app-one/apps/web',
'/Users/test/projects/app-one/packages/api',
'/Users/test/projects/not-a-repo',
])
expect(result.relinkedCount).toBe(1)
expect(result.existingCount).toBe(0)
expect(result.nonRepoPathCount).toBe(1)
expect(result.duplicatePathCount).toBe(1)
expect(result.errors).toEqual([])
expect(result.repos).toHaveLength(1)
expect(result.repos[0]?.fullPath).toBe(repoRoot)
expect(createRepo).toHaveBeenCalledTimes(1)
})
})
+14
View File
@@ -5,6 +5,8 @@ import type {
OpenCodeConfigResponse,
CreateOpenCodeConfigRequest,
UpdateOpenCodeConfigRequest,
OpenCodeImportStatus,
SyncOpenCodeImportResponse,
SkillFileInfo,
CreateSkillRequest,
UpdateSkillRequest,
@@ -145,6 +147,18 @@ export const settingsApi = {
})
},
getOpenCodeImportStatus: async (): Promise<OpenCodeImportStatus> => {
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-import/status`)
},
syncOpenCodeImport: async (overwriteState = true): Promise<SyncOpenCodeImportResponse> => {
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-import`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ overwriteState }),
})
},
getOpenCodeVersions: async (): Promise<{
versions: Array<{
version: string
+24
View File
@@ -98,3 +98,27 @@ export interface OpenCodeConfigResponse {
configs: OpenCodeConfig[]
defaultConfig: OpenCodeConfig | null
}
export interface OpenCodeImportStatus {
configSourcePath: string | null
stateSourcePath: string | null
workspaceConfigPath: string
workspaceStatePath: string
workspaceStateExists: boolean
}
export interface SyncOpenCodeImportResponse extends OpenCodeImportStatus {
success: boolean
message: string
serverRestarted: boolean
configImported: boolean
stateImported: boolean
relinkedRepos?: {
repos: Array<Record<string, unknown>>
relinkedCount: number
existingCount: number
nonRepoPathCount: number
duplicatePathCount: number
errors: Array<{ path: string; error: string }>
}
}
@@ -21,8 +21,8 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useServerHealth } from '@/hooks/useServerHealth'
import { parseJsonc, hasJsoncComments } from '@/lib/jsonc'
import { showToast } from '@/lib/toast'
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
import type { OpenCodeConfig } from '@/api/types/settings'
import { invalidateAllConfigRelatedCaches, invalidateConfigCaches } from '@/lib/queryInvalidation'
import type { OpenCodeConfig, OpenCodeImportStatus } from '@/api/types/settings'
interface Command {
template: string
@@ -83,6 +83,12 @@ export function OpenCodeConfigManager() {
staleTime: 5 * 60 * 1000,
})
const { data: importStatus, isLoading: isImportStatusLoading } = useQuery<OpenCodeImportStatus>({
queryKey: ['opencode-import-status'],
queryFn: () => settingsApi.getOpenCodeImportStatus(),
staleTime: 30 * 1000,
})
const scrollToSection = (ref: React.RefObject<HTMLButtonElement | null>) => {
if (ref.current) {
ref.current.scrollIntoView({
@@ -152,6 +158,15 @@ export function OpenCodeConfigManager() {
},
})
const syncOpenCodeImportMutation = useMutation({
mutationFn: async () => settingsApi.syncOpenCodeImport(true),
onSuccess: async () => {
await fetchConfigs()
invalidateAllConfigRelatedCaches(queryClient)
queryClient.invalidateQueries({ queryKey: ['opencode-import-status'] })
},
})
const getApiErrorMessage = (error: unknown, fallback: string): string => {
if (error && typeof error === 'object' && 'response' in error) {
const response = (error as { response?: { data?: { details?: string; error?: string } } }).response
@@ -337,6 +352,7 @@ export function OpenCodeConfigManager() {
}
const isUnhealthy = health?.opencode !== 'healthy'
const canImportFromHost = Boolean(importStatus?.configSourcePath || importStatus?.stateSourcePath)
return (
<div className="space-y-6 overflow-y-auto">
@@ -433,6 +449,91 @@ export function OpenCodeConfigManager() {
</Card>
)}
<Card>
<CardHeader className="pb-3">
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle className="text-sm sm:text-base">Existing OpenCode Host Import</CardTitle>
<p className="text-sm text-muted-foreground mt-1">
Re-import your standalone OpenCode config and session state into this workspace, then restart the server so existing chats can reconnect.
</p>
</div>
<Button
variant="outline"
size="sm"
disabled={!canImportFromHost || syncOpenCodeImportMutation.isPending || isImportStatusLoading}
onClick={async () => {
showToast.loading('Importing existing OpenCode host data...', { id: 'opencode-import' })
try {
const result = await syncOpenCodeImportMutation.mutateAsync()
const importedParts = [result.configImported && 'config', result.stateImported && 'state']
.filter(Boolean)
.join(' and ')
const relinkSummary = result.relinkedRepos
? ` Linked ${result.relinkedRepos.relinkedCount} repos, matched ${result.relinkedRepos.existingCount} existing repos, skipped ${result.relinkedRepos.nonRepoPathCount} non-repo paths, and ignored ${result.relinkedRepos.duplicatePathCount} duplicate session paths.`
: ''
showToast.success(`Imported existing OpenCode ${importedParts || 'data'} and restarted the server.${relinkSummary}`, { id: 'opencode-import' })
} catch (error) {
showToast.error(getApiErrorMessage(error, 'Failed to import existing OpenCode host data'), { id: 'opencode-import' })
}
}}
>
{syncOpenCodeImportMutation.isPending ? (
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
) : (
<Download className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
)}
<span className="text-xs sm:text-sm">Import From Host</span>
</Button>
</div>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<div className="grid gap-3 md:grid-cols-2">
<div className="rounded-lg border border-border p-3">
<p className="font-medium">Config Source</p>
<p className="mt-1 break-all text-muted-foreground">
{isImportStatusLoading ? 'Checking...' : importStatus?.configSourcePath || 'No importable OpenCode config found'}
</p>
</div>
<div className="rounded-lg border border-border p-3">
<p className="font-medium">State Source</p>
<p className="mt-1 break-all text-muted-foreground">
{isImportStatusLoading ? 'Checking...' : importStatus?.stateSourcePath || 'No importable OpenCode state found'}
</p>
</div>
</div>
<div className="rounded-lg border border-border p-3">
<p className="font-medium">Workspace State</p>
<p className="mt-1 break-all text-muted-foreground">
{importStatus?.workspaceStatePath || 'Unavailable'}
</p>
<p className="mt-2 text-xs text-muted-foreground">
{importStatus?.workspaceStateExists
? 'A workspace session database already exists. Import will replace it with the detected host state.'
: 'No workspace session database exists yet. Import will seed it from the detected host state.'}
</p>
</div>
{syncOpenCodeImportMutation.data?.relinkedRepos && (
<div className="rounded-lg border border-border p-3">
<p className="font-medium">Last Relink Result</p>
<p className="mt-1 text-muted-foreground">
Linked {syncOpenCodeImportMutation.data.relinkedRepos.relinkedCount} repos, matched {syncOpenCodeImportMutation.data.relinkedRepos.existingCount} existing repos, skipped {syncOpenCodeImportMutation.data.relinkedRepos.nonRepoPathCount} non-repo session paths, and ignored {syncOpenCodeImportMutation.data.relinkedRepos.duplicatePathCount} duplicate session paths.
</p>
{syncOpenCodeImportMutation.data.relinkedRepos.errors.length > 0 && (
<p className="mt-2 text-xs text-destructive">
{syncOpenCodeImportMutation.data.relinkedRepos.errors.length} repo paths could not be linked.
</p>
)}
</div>
)}
{!canImportFromHost && !isImportStatusLoading && (
<p className="text-xs text-muted-foreground">
No host OpenCode config or state was detected. For Docker installs, bind your host OpenCode config and state into the container before using this action.
</p>
)}
</CardContent>
</Card>
<MemoryPluginConfig
memoryPluginEnabled={configs.find(c => c.isDefault)?.content?.plugin?.includes('@opencode-manager/memory') ?? false}
onToggle={async (enabled) => {