mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
feat(worktree): worktree tabs, server env vars, and multi-directory SSE (#240)
* loop: worktree-tabs-2 completed after 4 iterations * loop: server-env-vars completed after 7 iterations * feat(worktree): add worktree tabs and server env vars settings * refactor(worktree): multi-directory SSE support and workspace chip row * feat(workspace): collapsible workspace manager and sibling filtering * feat(workspace): workspace creation endpoint, refactored workspace manager, and tests * refactor(frontend): unify workspace label and remove dead code - extract shared workspaceLabel helper into api/repos and reuse in WorkspaceManager and RepoDetail directoryLabels - remove unused useSessions hook and subscribeToDirectory subscription - drop redundant frontend workspace dedup now guaranteed by backend - align WorktreeTabs empty-state test with create-workspace button
This commit is contained in:
1 parent
60ed756a0b
commit
b9236f7f20
38 files changed
+2423
-133
No files matched your search
@@ -0,0 +1,333 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, mock } from 'bun:test'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import { createRepoRoutes } from './repos'
|
||||
import { createRepo } from '../db/queries'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import path from 'path'
|
||||
|
||||
beforeEach(() => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: (() => null) as any,
|
||||
isGitMainCheckout: (() => Promise.resolve(false)) as any,
|
||||
}))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
mock.restore()
|
||||
})
|
||||
|
||||
const stubGitAuthService = {
|
||||
getGitEnvironment: () => ({}),
|
||||
getGitCredentials: async () => [],
|
||||
} as unknown as GitAuthService
|
||||
|
||||
function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStubOpenCodeClient({
|
||||
getJson: mock(async () => []) as any,
|
||||
})): Hono {
|
||||
const app = new Hono()
|
||||
const scheduleService = {
|
||||
createSchedule: () => {},
|
||||
getScheduleById: () => null,
|
||||
listSchedules: () => [],
|
||||
updateSchedule: () => {},
|
||||
deleteSchedule: () => {},
|
||||
} as any
|
||||
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient))
|
||||
return app
|
||||
}
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
describe('GET /api/repos/:id/siblings', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
app = createTestApp(db)
|
||||
})
|
||||
|
||||
it('returns siblings including self with currentBranch', async () => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: ((path: string) => Promise.resolve(
|
||||
path.includes('repo-unrelated') ? 'commit-B' : 'commit-A'
|
||||
)) as any,
|
||||
isGitMainCheckout: (() => Promise.resolve(false)) as any,
|
||||
}))
|
||||
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
createRepo(db, { localPath: 'repo-b', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
createRepo(db, { localPath: 'repo-c', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
createRepo(db, { localPath: 'repo-unrelated', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
|
||||
const res = await app.request('/repos/1/siblings')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as Array<{ id: number; currentBranch: string | null | undefined }>
|
||||
expect(data).toHaveLength(3)
|
||||
expect(data.map((d) => d.id).sort((a, b) => a - b)).toEqual([1, 2, 3])
|
||||
})
|
||||
|
||||
it('includes OpenCode workspaces that are not manager repo rows', async () => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: (() => Promise.resolve('commit-A')) as any,
|
||||
isGitMainCheckout: (() => Promise.resolve(false)) as any,
|
||||
}))
|
||||
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
app = createTestApp(db, createStubOpenCodeClient({
|
||||
getJson: mock(async () => ([{
|
||||
id: 'wrk_test',
|
||||
type: 'worktree',
|
||||
name: 'plugin-workspace',
|
||||
branch: 'plugin-branch',
|
||||
directory: '/tmp/plugin-workspace',
|
||||
projectID: 'commit-A',
|
||||
}])) as any,
|
||||
}))
|
||||
|
||||
const res = await app.request('/repos/1/siblings')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as Array<{ id: number; workspaceId?: string; currentBranch?: string }>
|
||||
expect(data).toHaveLength(2)
|
||||
expect(data[1]).toMatchObject({
|
||||
id: -1,
|
||||
workspaceId: 'wrk_test',
|
||||
currentBranch: 'plugin-branch',
|
||||
})
|
||||
})
|
||||
|
||||
it('deduplicates OpenCode workspaces with the same directory', async () => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: (() => Promise.resolve('commit-A')) as any,
|
||||
isGitMainCheckout: (() => Promise.resolve(false)) as any,
|
||||
}))
|
||||
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
app = createTestApp(db, createStubOpenCodeClient({
|
||||
getJson: mock(async () => ([
|
||||
{
|
||||
id: 'wrk_first',
|
||||
type: 'worktree',
|
||||
name: 'duplicate-workspace',
|
||||
branch: 'duplicate-branch',
|
||||
directory: '/tmp/duplicate-workspace',
|
||||
projectID: 'commit-A',
|
||||
},
|
||||
{
|
||||
id: 'wrk_second',
|
||||
type: 'worktree',
|
||||
name: 'duplicate-workspace',
|
||||
branch: 'duplicate-branch',
|
||||
directory: '/tmp/duplicate-workspace/',
|
||||
projectID: 'commit-A',
|
||||
},
|
||||
])) as any,
|
||||
}))
|
||||
|
||||
const res = await app.request('/repos/1/siblings')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as Array<{ workspaceId?: string }>
|
||||
expect(data.filter((entry) => entry.workspaceId)).toHaveLength(1)
|
||||
expect(data.some((entry) => entry.workspaceId === 'wrk_first')).toBe(true)
|
||||
})
|
||||
|
||||
it('excludes a workspace pointing at the repo directory so it cannot be deleted', async () => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: (() => Promise.resolve('commit-A')) as any,
|
||||
isGitMainCheckout: (() => Promise.resolve(false)) as any,
|
||||
}))
|
||||
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
const repoDirectory = path.join(getReposPath(), 'repo-a')
|
||||
app = createTestApp(db, createStubOpenCodeClient({
|
||||
getJson: mock(async () => ([{
|
||||
id: 'wrk_self',
|
||||
type: 'worktree',
|
||||
name: 'self-workspace',
|
||||
branch: 'main',
|
||||
directory: `${repoDirectory}/`,
|
||||
projectID: 'commit-A',
|
||||
}])) as any,
|
||||
}))
|
||||
|
||||
const res = await app.request('/repos/1/siblings')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as Array<{ id: number; workspaceId?: string }>
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data.some((d) => d.workspaceId === 'wrk_self')).toBe(false)
|
||||
})
|
||||
|
||||
it('excludes a workspace that is a git main checkout so the main repo cannot be deleted', async () => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: (() => Promise.resolve('commit-A')) as any,
|
||||
isGitMainCheckout: ((dir: string) =>
|
||||
Promise.resolve(dir === '/Users/dev/main-repo')) as any,
|
||||
}))
|
||||
|
||||
createRepo(db, { localPath: 'repo-wt', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
app = createTestApp(db, createStubOpenCodeClient({
|
||||
getJson: mock(async () => ([
|
||||
{
|
||||
id: 'wrk_main',
|
||||
type: 'worktree',
|
||||
name: 'main-checkout',
|
||||
branch: 'dev',
|
||||
directory: '/Users/dev/main-repo',
|
||||
projectID: 'commit-A',
|
||||
},
|
||||
{
|
||||
id: 'wrk_linked',
|
||||
type: 'worktree',
|
||||
name: 'feature',
|
||||
branch: 'feature/x',
|
||||
directory: '/Users/dev/worktrees/feature-x',
|
||||
projectID: 'commit-A',
|
||||
},
|
||||
])) as any,
|
||||
}))
|
||||
|
||||
const res = await app.request('/repos/1/siblings')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as Array<{ workspaceId?: string }>
|
||||
expect(data.some((d) => d.workspaceId === 'wrk_main')).toBe(false)
|
||||
expect(data.some((d) => d.workspaceId === 'wrk_linked')).toBe(true)
|
||||
})
|
||||
|
||||
it('excludes repos with non-matching projectID', async () => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: ((path: string) => Promise.resolve(
|
||||
path.includes('repo-only') ? 'commit-X' : 'commit-Y'
|
||||
)) as any,
|
||||
isGitMainCheckout: (() => Promise.resolve(false)) as any,
|
||||
}))
|
||||
|
||||
createRepo(db, { localPath: 'repo-only', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
createRepo(db, { localPath: 'repo-other', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
|
||||
const res = await app.request('/repos/1/siblings')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as Array<{ id: number }>
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0]!.id).toBe(1)
|
||||
})
|
||||
|
||||
it('returns empty when target has no projectID', async () => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: (() => null) as any,
|
||||
}))
|
||||
|
||||
createRepo(db, { localPath: 'repo-no-project', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
|
||||
const res = await app.request('/repos/1/siblings')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as unknown[]
|
||||
expect(data).toEqual([])
|
||||
})
|
||||
|
||||
it('returns empty when target cloneStatus !== ready', async () => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: (() => 'commit-A') as any,
|
||||
isGitMainCheckout: (() => Promise.resolve(false)) as any,
|
||||
}))
|
||||
|
||||
createRepo(db, { localPath: 'repo-cloning', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true })
|
||||
|
||||
const res = await app.request('/repos/1/siblings')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as unknown[]
|
||||
expect(data).toEqual([])
|
||||
})
|
||||
|
||||
it('returns empty when target missing', async () => {
|
||||
mock.module('../services/project-id-resolver', () => ({
|
||||
resolveProjectId: (() => 'commit-A') as any,
|
||||
isGitMainCheckout: (() => Promise.resolve(false)) as any,
|
||||
}))
|
||||
|
||||
const res = await app.request('/repos/9999/siblings')
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json() as unknown[]
|
||||
expect(data).toEqual([])
|
||||
})
|
||||
|
||||
it('invalid id returns 400', async () => {
|
||||
const res = await app.request('/repos/abc/siblings')
|
||||
expect(res.status).toBe(400)
|
||||
const data = await res.json() as { error: string }
|
||||
expect(data.error).toBe('Invalid repo id')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/repos/:id/workspaces/:workspaceId', () => {
|
||||
let db: Database
|
||||
let captured: { path: string; directory?: string } | null
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
captured = null
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('forwards workspace delete to OpenCode with repo directory', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
const forward = mock(async (req: Parameters<OpenCodeClient['forward']>[0]) => {
|
||||
captured = { path: req.path, directory: req.directory }
|
||||
return new Response(JSON.stringify({ id: 'wrk_test' }), { status: 200 })
|
||||
})
|
||||
const app = createTestApp(db, createStubOpenCodeClient({
|
||||
forward,
|
||||
}))
|
||||
|
||||
const res = await app.request('/repos/1/workspaces/wrk_test', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(captured?.path).toBe('/experimental/workspace/wrk_test')
|
||||
expect(captured?.directory?.endsWith('/repos/repo-a')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/repos/:id/workspaces', () => {
|
||||
let db: Database
|
||||
let captured: { path: string; directory?: string; body?: string } | null
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
captured = null
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('forwards workspace creation to OpenCode with repo directory', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
const forward = mock(async (req: Parameters<OpenCodeClient['forward']>[0]) => {
|
||||
captured = { path: req.path, directory: req.directory, body: req.body }
|
||||
return new Response(JSON.stringify({ id: 'wrk_test', type: 'worktree', directory: '/tmp/wrk-test' }), { status: 200 })
|
||||
})
|
||||
const app = createTestApp(db, createStubOpenCodeClient({
|
||||
forward,
|
||||
}))
|
||||
|
||||
const res = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(captured?.path).toBe('/experimental/workspace')
|
||||
expect(captured?.directory?.endsWith('/repos/repo-a')).toBe(true)
|
||||
expect(JSON.parse(captured?.body ?? '{}')).toEqual({ type: 'worktree', branch: null })
|
||||
expect(await res.json()).toMatchObject({ id: 'wrk_test', type: 'worktree' })
|
||||
})
|
||||
})
|
||||
@@ -194,6 +194,23 @@ app.get('/', async (c) => {
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/siblings', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
if (Number.isNaN(id)) return c.json({ error: 'Invalid repo id' }, 400)
|
||||
const siblings = await repoService.getSiblingRepos(
|
||||
database,
|
||||
id,
|
||||
gitAuthService.getGitEnvironment(),
|
||||
openCodeClient,
|
||||
)
|
||||
return c.json(siblings)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to list sibling repos:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/access', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
@@ -211,7 +228,63 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
app.delete('/:id/workspaces/:workspaceId', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
if (Number.isNaN(id)) return c.json({ error: 'Invalid repo id' }, 400)
|
||||
|
||||
const repo = getRepoById(database, id)
|
||||
if (!repo || repo.cloneStatus !== 'ready') return c.json({ error: 'Repo not found' }, 404)
|
||||
|
||||
const workspaceId = c.req.param('workspaceId')
|
||||
if (!workspaceId.startsWith('wrk')) return c.json({ error: 'Invalid workspace id' }, 400)
|
||||
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(workspaceId)}`,
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
return c.json({ error: await response.text() || 'Failed to delete workspace' }, response.status as ContentfulStatusCode)
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to delete workspace:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/workspaces', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
if (Number.isNaN(id)) return c.json({ error: 'Invalid repo id' }, 400)
|
||||
|
||||
const repo = getRepoById(database, id)
|
||||
if (!repo || repo.cloneStatus !== 'ready') return c.json({ error: 'Repo not found' }, 404)
|
||||
|
||||
const response = await openCodeClient.forward({
|
||||
method: 'POST',
|
||||
path: '/experimental/workspace',
|
||||
directory: repo.fullPath,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'worktree', branch: null }),
|
||||
})
|
||||
|
||||
const body = await response.text()
|
||||
if (!response.ok) {
|
||||
return c.json({ error: body || 'Failed to create workspace' }, response.status as ContentfulStatusCode)
|
||||
}
|
||||
|
||||
return c.json(body ? JSON.parse(body) : { success: true })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create workspace:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:id', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import { createSettingsRoutes } from './settings'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
|
||||
interface TestUserPreferenceRow {
|
||||
preferences: string
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
interface TestMigrationRow {
|
||||
version: number
|
||||
name: string
|
||||
applied_at: number
|
||||
}
|
||||
|
||||
interface StatementResult {
|
||||
get?: (..._params: unknown[]) => TestUserPreferenceRow | TestMigrationRow | { count: number } | { name: string } | { user_id: string; preferences: string } | undefined
|
||||
run?: (..._params: unknown[]) => { changes: number }
|
||||
all?: () => Array<unknown>
|
||||
}
|
||||
|
||||
class InMemoryDatabase {
|
||||
private userPreferences = new Map<string, TestUserPreferenceRow>()
|
||||
private schemaMigrations = new Map<number, { name: string; applied_at: number }>()
|
||||
|
||||
private normalizeSql(sql: string): string {
|
||||
return sql.trim().toLowerCase().replace(/\s+/g, ' ')
|
||||
}
|
||||
|
||||
private getMigrationRows(): TestMigrationRow[] {
|
||||
return [...this.schemaMigrations.entries()]
|
||||
.sort((a, b) => a[0] - b[0])
|
||||
.map(([version, value]) => ({
|
||||
version,
|
||||
name: value.name,
|
||||
applied_at: value.applied_at,
|
||||
}))
|
||||
}
|
||||
|
||||
private setUserPreference(userId: string, preferences: string, updatedAt: number): void {
|
||||
this.userPreferences.set(userId, { preferences, updated_at: updatedAt })
|
||||
}
|
||||
|
||||
private createStatement(sql: string): StatementResult {
|
||||
const normalizedSql = this.normalizeSql(sql)
|
||||
|
||||
if (normalizedSql === 'select version from schema_migrations order by version') {
|
||||
return {
|
||||
all: () => this.getMigrationRows(),
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('insert into schema_migrations')) {
|
||||
return {
|
||||
run: (...params: unknown[]) => {
|
||||
const [version, name, appliedAt] = params as [number, string, number]
|
||||
this.schemaMigrations.set(version, { name, applied_at: appliedAt })
|
||||
return { changes: 1 }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql === 'select preferences, updated_at from user_preferences where user_id = ?') {
|
||||
return {
|
||||
get: (...params: unknown[]) => {
|
||||
const userId = params[0]
|
||||
if (typeof userId !== 'string') {
|
||||
return undefined
|
||||
}
|
||||
return this.userPreferences.get(userId)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('insert into user_preferences')) {
|
||||
return {
|
||||
run: (...params: unknown[]) => {
|
||||
const [userId, preferences, updatedAt] = params as [string, string, number]
|
||||
this.setUserPreference(userId, preferences, updatedAt)
|
||||
return { changes: 1 }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('delete from user_preferences where user_id = ?')) {
|
||||
return {
|
||||
run: (...params: unknown[]) => {
|
||||
const userId = params[0]
|
||||
if (typeof userId !== 'string') {
|
||||
return { changes: 0 }
|
||||
}
|
||||
const hadRow = this.userPreferences.delete(userId)
|
||||
return { changes: hadRow ? 1 : 0 }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('select user_id, preferences from user_preferences')) {
|
||||
return {
|
||||
all: () => [...this.userPreferences.entries()].map(([user_id, row]) => ({
|
||||
user_id,
|
||||
preferences: row.preferences,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('pragma table_info(') || normalizedSql.includes('select name from sqlite_master')) {
|
||||
return {
|
||||
all: () => [],
|
||||
get: () => undefined,
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedSql.startsWith('select count(*) as count')) {
|
||||
return {
|
||||
get: () => ({ count: 0 }),
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSql.startsWith('create table') ||
|
||||
normalizedSql.startsWith('create index') ||
|
||||
normalizedSql.startsWith('drop table') ||
|
||||
normalizedSql.startsWith('drop index')
|
||||
) {
|
||||
return {
|
||||
run: () => ({ changes: 0 }),
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedSql.startsWith('begin transaction') ||
|
||||
normalizedSql.startsWith('commit') ||
|
||||
normalizedSql.startsWith('rollback')
|
||||
) {
|
||||
return {
|
||||
run: () => ({ changes: 0 }),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get: () => undefined,
|
||||
run: () => ({ changes: 0 }),
|
||||
all: () => [],
|
||||
}
|
||||
}
|
||||
|
||||
query(sql: string): StatementResult {
|
||||
return this.createStatement(sql)
|
||||
}
|
||||
|
||||
prepare(sql: string): StatementResult {
|
||||
return this.createStatement(sql)
|
||||
}
|
||||
|
||||
run(sql: string, ...params: unknown[]): { changes: number } {
|
||||
const statement = this.createStatement(sql)
|
||||
return statement.run ? statement.run(...params) : { changes: 0 }
|
||||
}
|
||||
|
||||
close() {
|
||||
this.userPreferences.clear()
|
||||
this.schemaMigrations.clear()
|
||||
}
|
||||
}
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: class {
|
||||
private db = new InMemoryDatabase()
|
||||
|
||||
query(sql: string) {
|
||||
return this.db.query(sql)
|
||||
}
|
||||
|
||||
prepare(sql: string) {
|
||||
return this.db.prepare(sql)
|
||||
}
|
||||
|
||||
run(sql: string, ...params: unknown[]) {
|
||||
return this.db.run(sql, ...params)
|
||||
}
|
||||
|
||||
close() {
|
||||
return this.db.close()
|
||||
}
|
||||
|
||||
exec(sql: string) {
|
||||
return this.db.run(sql)
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
const mockGitAuthService = {
|
||||
getGitEnvironment: () => ({}),
|
||||
} as unknown as GitAuthService
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
function createTestApp(db: Database): Hono {
|
||||
const app = new Hono()
|
||||
app.route('/settings', createSettingsRoutes(db, mockGitAuthService, createStubOpenCodeClient()))
|
||||
return app
|
||||
}
|
||||
|
||||
describe('settings routes — serverEnvVars', () => {
|
||||
let db: Database
|
||||
let app: Hono
|
||||
let originalWorkspacePath: string | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
app = createTestApp(db)
|
||||
originalWorkspacePath = process.env.WORKSPACE_PATH
|
||||
process.env.WORKSPACE_PATH = '/tmp/test-workspace-settings-routes'
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalWorkspacePath) {
|
||||
process.env.WORKSPACE_PATH = originalWorkspacePath
|
||||
} else {
|
||||
delete process.env.WORKSPACE_PATH
|
||||
}
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('GET / returns empty serverEnvVars by default', async () => {
|
||||
const res = await app.request('/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = (await res.json()) as { preferences: { serverEnvVars?: Array<{ key: string; value: string }> } }
|
||||
expect(data.preferences.serverEnvVars).toEqual([])
|
||||
})
|
||||
|
||||
it('PATCH / saves and returns serverEnvVars', async () => {
|
||||
const patchRes = await app.request('/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
preferences: {
|
||||
serverEnvVars: [
|
||||
{
|
||||
key: 'OPENCODE_EXPERIMENTAL_WORKSPACES',
|
||||
value: 'true',
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
expect(patchRes.status).toBe(200)
|
||||
const data = (await patchRes.json()) as { preferences: { serverEnvVars: Array<{ key: string; value: string }> } }
|
||||
expect(data.preferences.serverEnvVars).toEqual([
|
||||
{
|
||||
key: 'OPENCODE_EXPERIMENTAL_WORKSPACES',
|
||||
value: 'true',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('PATCH / persists serverEnvVars and returns on GET', async () => {
|
||||
await app.request('/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
preferences: {
|
||||
serverEnvVars: [{
|
||||
key: 'MY_FLAG',
|
||||
value: '1',
|
||||
}],
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
const res = await app.request('/settings')
|
||||
const data = (await res.json()) as { preferences: { serverEnvVars: Array<{ key: string; value: string }> } }
|
||||
|
||||
expect(data.preferences.serverEnvVars).toEqual([
|
||||
{
|
||||
key: 'MY_FLAG',
|
||||
value: '1',
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
parseSSHHost
|
||||
} from '../utils/ssh-key-manager'
|
||||
import { decryptSecret } from '../utils/crypto'
|
||||
import { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '@opencode-manager/shared'
|
||||
import { SettingsService } from './settings'
|
||||
import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import { parseJsonc } from '@opencode-manager/shared/utils'
|
||||
@@ -199,11 +200,28 @@ class OpenCodeServerManager {
|
||||
|
||||
let gitCredentials: GitCredential[] = []
|
||||
let gitIdentityEnv: Record<string, string> = {}
|
||||
let userEnvVars: Record<string, string> = {}
|
||||
if (this.db) {
|
||||
try {
|
||||
const settingsService = new SettingsService(this.db)
|
||||
const settings = settingsService.getSettings('default')
|
||||
gitCredentials = settings.preferences.gitCredentials || []
|
||||
const disabledDefaultEnvVars = new Set(settings.preferences.disabledDefaultServerEnvVars || [])
|
||||
const rawEnvVars = [
|
||||
...DEFAULT_SERVER_ENV_VARS.filter((envVar) => !disabledDefaultEnvVars.has(envVar.key)),
|
||||
...(settings.preferences.serverEnvVars || []),
|
||||
]
|
||||
if (rawEnvVars.length > 0) {
|
||||
userEnvVars = Object.fromEntries(
|
||||
rawEnvVars
|
||||
.filter(({ key }) => {
|
||||
const normalizedKey = key.trim()
|
||||
return normalizedKey !== '' && !(BLOCKED_SERVER_ENV_KEYS as readonly string[]).includes(normalizedKey)
|
||||
})
|
||||
.map(({ key, value }) => [key.trim(), value])
|
||||
)
|
||||
logger.info(`Injecting ${Object.keys(userEnvVars).length} custom server env vars`)
|
||||
}
|
||||
|
||||
const identity = await resolveGitIdentity(settings.preferences.gitIdentity, gitCredentials)
|
||||
if (identity) {
|
||||
@@ -327,6 +345,7 @@ class OpenCodeServerManager {
|
||||
stdio: isDevelopment ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
||||
env: {
|
||||
...cleanEnv,
|
||||
...userEnvVars,
|
||||
...gitEnv,
|
||||
...gitIdentityEnv,
|
||||
GIT_SSH_COMMAND: gitSshCommand,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
||||
import { mkdtempSync, rmSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import path from 'path'
|
||||
import { execSync } from 'child_process'
|
||||
import { isGitMainCheckout } from './project-id-resolver'
|
||||
|
||||
describe('isGitMainCheckout', () => {
|
||||
let base: string
|
||||
let mainRepo: string
|
||||
let worktree: string
|
||||
|
||||
beforeAll(() => {
|
||||
base = mkdtempSync(path.join(tmpdir(), 'oc-main-checkout-'))
|
||||
mainRepo = path.join(base, 'main')
|
||||
worktree = path.join(base, 'wt')
|
||||
execSync(`git init -q "${mainRepo}"`)
|
||||
execSync(`git -C "${mainRepo}" commit -q --allow-empty -m init`, {
|
||||
env: { ...process.env, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t' },
|
||||
})
|
||||
execSync(`git -C "${mainRepo}" worktree add -q "${worktree}" -b feature`)
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
rmSync(base, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('returns true for the main checkout', async () => {
|
||||
expect(await isGitMainCheckout(mainRepo)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false for a linked worktree', async () => {
|
||||
expect(await isGitMainCheckout(worktree)).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for a non-git directory', async () => {
|
||||
expect(await isGitMainCheckout(base)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { exec } from 'child_process'
|
||||
import { readFile } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { fileExists } from './file-operations'
|
||||
|
||||
const projectIdCache = new Map<string, string>()
|
||||
@@ -66,3 +67,25 @@ export async function resolveProjectId(repoFullPath: string): Promise<string | n
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const mainCheckoutCache = new Map<string, boolean>()
|
||||
|
||||
export async function isGitMainCheckout(repoFullPath: string): Promise<boolean> {
|
||||
if (mainCheckoutCache.has(repoFullPath)) {
|
||||
return mainCheckoutCache.get(repoFullPath) ?? false
|
||||
}
|
||||
try {
|
||||
const gitDir = await executeGitCommand(repoFullPath, ['rev-parse', '--absolute-git-dir'])
|
||||
const commonDir = await executeGitCommand(repoFullPath, [
|
||||
'rev-parse',
|
||||
'--path-format=absolute',
|
||||
'--git-common-dir',
|
||||
])
|
||||
const isMain = !!gitDir && !!commonDir && path.resolve(gitDir) === path.resolve(commonDir)
|
||||
mainCheckoutCache.set(repoFullPath, isMain)
|
||||
return isMain
|
||||
} catch {
|
||||
mainCheckoutCache.set(repoFullPath, false)
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import fs from 'fs/promises'
|
||||
import { existsSync, rmSync } from 'node:fs'
|
||||
import { existsSync, rmSync, realpathSync } from 'node:fs'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { ensureDirectoryExists } from './file-operations'
|
||||
import { createRepo, getRepoByLocalPath, getRepoBySourcePath, getRepoById, updateRepoStatus, updateRepoBranch, updateLastPulled, deleteRepo, getRepoByUrlAndBranch } from '../db/queries'
|
||||
@@ -14,11 +14,23 @@ import path from 'path'
|
||||
import { parseSSHHost } from '../utils/ssh-key-manager'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { sseAggregator } from './sse-aggregator'
|
||||
import { resolveProjectId, isGitMainCheckout } from './project-id-resolver'
|
||||
import { listRepos } from '../db/queries'
|
||||
import { SettingsService } from './settings'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
const GIT_CLONE_TIMEOUT = 300000
|
||||
const DEFAULT_DISCOVERY_MAX_DEPTH = 4
|
||||
const DISCOVERY_SKIP_DIRECTORIES = new Set(['.git', 'node_modules'])
|
||||
|
||||
function canonical(dir: string): string {
|
||||
try {
|
||||
return realpathSync(path.resolve(dir))
|
||||
} catch {
|
||||
return path.resolve(dir)
|
||||
}
|
||||
}
|
||||
|
||||
function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: string): Error {
|
||||
const message = originalMessage.toLowerCase()
|
||||
|
||||
@@ -1091,3 +1103,113 @@ export function isRepoInUse(db: Database, repoId: number): boolean {
|
||||
|
||||
return sseAggregator.getActiveDirectories().includes(repo.fullPath)
|
||||
}
|
||||
|
||||
export async function getSiblingRepos(
|
||||
database: Database,
|
||||
repoId: number,
|
||||
gitEnv: Record<string, string>,
|
||||
openCodeClient?: OpenCodeClient,
|
||||
): Promise<Array<Repo & { currentBranch: string | undefined }>> {
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings()
|
||||
const allRepos = listRepos(database, settings.preferences.repoOrder)
|
||||
|
||||
const target = allRepos.find((r) => r.id === repoId)
|
||||
if (!target || target.cloneStatus !== 'ready') return []
|
||||
|
||||
const targetProjectId = await resolveProjectId(target.fullPath)
|
||||
if (!targetProjectId) return []
|
||||
|
||||
const ready = allRepos.filter((r) => r.cloneStatus === 'ready')
|
||||
const withProjectIds = await Promise.all(
|
||||
ready.map(async (repo) => ({
|
||||
repo,
|
||||
projectId: await resolveProjectId(repo.fullPath).catch(() => null),
|
||||
})),
|
||||
)
|
||||
|
||||
const matching = withProjectIds
|
||||
.filter((entry) => entry.projectId === targetProjectId)
|
||||
.map((entry) => entry.repo)
|
||||
|
||||
const repoSiblings = await Promise.all(
|
||||
matching.map(async (repo) => ({
|
||||
...repo,
|
||||
currentBranch: (await getCurrentBranch(repo, gitEnv)) ?? undefined,
|
||||
})),
|
||||
)
|
||||
|
||||
if (!openCodeClient) return repoSiblings
|
||||
|
||||
try {
|
||||
const workspaces = await openCodeClient.getJson<Array<{
|
||||
id: string
|
||||
type: string
|
||||
name: string | null
|
||||
branch: string | null
|
||||
directory: string | null
|
||||
projectID: string
|
||||
}>>('/experimental/workspace', { directory: target.fullPath })
|
||||
|
||||
// Normalize paths so a workspace pointing at a real repo directory can never
|
||||
// be exposed as deletable. Deleting an OpenCode workspace recursively removes
|
||||
// its directory, so the current repo directory and all known managed repo
|
||||
// directories must be excluded regardless of trailing slashes or symlinks.
|
||||
// Workspaces that are git main checkouts (not linked worktrees) are also
|
||||
// excluded so the project's origin/main repository can never be surfaced
|
||||
// as deletable.
|
||||
const knownDirectories = new Set(repoSiblings.map((repo) => canonical(repo.fullPath)))
|
||||
const targetDirectory = canonical(target.fullPath)
|
||||
const reposRoot = canonical(getReposPath())
|
||||
|
||||
const candidates = workspaces.filter((workspace) => {
|
||||
if (workspace.projectID !== targetProjectId) return false
|
||||
if (!workspace.directory) return false
|
||||
|
||||
const workspaceDirectory = canonical(workspace.directory)
|
||||
if (workspaceDirectory === targetDirectory) return false
|
||||
if (workspaceDirectory === reposRoot) return false
|
||||
if (knownDirectories.has(workspaceDirectory)) return false
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
const mainChecks = await Promise.all(
|
||||
candidates.map((workspace) => isGitMainCheckout(workspace.directory!).catch(() => false)),
|
||||
)
|
||||
|
||||
const uniqueWorkspaces = new Map<string, typeof candidates[number]>()
|
||||
candidates
|
||||
.filter((_, index) => !mainChecks[index])
|
||||
.forEach((workspace) => {
|
||||
const directory = canonical(workspace.directory!)
|
||||
if (!uniqueWorkspaces.has(directory)) {
|
||||
uniqueWorkspaces.set(directory, workspace)
|
||||
}
|
||||
})
|
||||
|
||||
const workspaceSiblings = Array.from(uniqueWorkspaces.values())
|
||||
.map((workspace) => ({
|
||||
id: -1,
|
||||
repoUrl: target.repoUrl,
|
||||
localPath: workspace.name ?? workspace.id,
|
||||
fullPath: workspace.directory!,
|
||||
sourcePath: workspace.directory!,
|
||||
branch: workspace.branch ?? undefined,
|
||||
defaultBranch: target.defaultBranch,
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
isWorktree: true,
|
||||
isLocal: true,
|
||||
currentBranch: workspace.branch ?? undefined,
|
||||
workspaceId: workspace.id,
|
||||
workspaceType: workspace.type,
|
||||
workspaceName: workspace.name ?? undefined,
|
||||
}))
|
||||
|
||||
return [...repoSiblings, ...workspaceSiblings]
|
||||
} catch (error) {
|
||||
logger.warn('Failed to list OpenCode workspaces:', error)
|
||||
return repoSiblings
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user