mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
* feat: show variant label on model picker and add folder upload for agents/commands
- Replace three-dot variant menu trigger with selected variant label
- Add POST /api/settings/opencode-directory-files/install endpoint
- Upload agents/commands markdown folders into .config/opencode/{agents,commands}/
- Reload OpenCode server after upload so files are picked up
* fix: revalidate branch/git caches when mobile sheet opens and on vcs.branch.updated SSE
- add shared invalidateRepoGitCaches() helper for consistent invalidation
- revalidate repo list when mobile repo quick-switch sheet opens
- revalidate current repo when mobile More drawer opens
- revalidate repo/git caches when Source Control dialog opens
- handle vcs.branch.updated SSE event with optimistic cache update
- use helper in branch create/switch mutations in useGit and BranchesTab
* style: make variant selector look more like a button with chevron and compact sizing
* refactor: consolidate settings editors, add folder upload support, and clean up unused code
* refactor: consolidate settings editors, add folder upload support, and clean up unused code
* feat: add opencode-directory-files listing service and consolidate settings editors
* fix: distinguish scroll from tap in suggestion popups on touch devices
* refactor: consolidate settings editors and add DirectoryFilesList component
* refactor: target repo status cache updates only to affected batch entries
* refactor: streamline settings, git hooks, and query invalidation logic
374 lines
11 KiB
TypeScript
374 lines
11 KiB
TypeScript
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
|
import { Hono } from 'hono'
|
|
import { Database } from 'bun:sqlite'
|
|
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises'
|
|
import { tmpdir } from 'os'
|
|
import { join } from 'path'
|
|
import { migrate } from '../db/migration-runner'
|
|
import { allMigrations } from '../db/migrations'
|
|
import { createSettingsRoutes } from './settings'
|
|
import { opencodeServerManager } from '../services/opencode-single-server'
|
|
import type { GitAuthService } from '../services/git-auth'
|
|
import type { OpenCodeSupervisor } from '../services/opencode-supervisor'
|
|
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, openCodeSupervisor?: OpenCodeSupervisor): Hono {
|
|
const app = new Hono()
|
|
app.route('/settings', createSettingsRoutes(db, mockGitAuthService, createStubOpenCodeClient(), openCodeSupervisor))
|
|
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',
|
|
},
|
|
])
|
|
})
|
|
})
|
|
|
|
describe('settings routes — OpenCode directory file upload', () => {
|
|
let db: Database
|
|
let app: Hono
|
|
let originalWorkspacePath: string | undefined
|
|
let workspacePath: string
|
|
const restart = vi.fn(async () => undefined)
|
|
let markRestartPendingSpy: ReturnType<typeof vi.spyOn>
|
|
|
|
beforeEach(async () => {
|
|
db = createTestDb()
|
|
restart.mockClear()
|
|
markRestartPendingSpy = vi.spyOn(opencodeServerManager, 'markRestartPending').mockImplementation(() => undefined)
|
|
originalWorkspacePath = process.env.WORKSPACE_PATH
|
|
workspacePath = await mkdtemp(join(tmpdir(), 'ocm-command-upload-'))
|
|
process.env.WORKSPACE_PATH = workspacePath
|
|
app = createTestApp(db, { restart } as unknown as OpenCodeSupervisor)
|
|
})
|
|
|
|
afterEach(async () => {
|
|
if (originalWorkspacePath) {
|
|
process.env.WORKSPACE_PATH = originalWorkspacePath
|
|
} else {
|
|
delete process.env.WORKSPACE_PATH
|
|
}
|
|
await rm(workspacePath, { recursive: true, force: true })
|
|
db.close()
|
|
markRestartPendingSpy.mockRestore()
|
|
})
|
|
|
|
it('installs uploaded command markdown files into the OpenCode commands directory', async () => {
|
|
const formData = new FormData()
|
|
formData.append('kind', 'commands')
|
|
formData.append('fileManifest', JSON.stringify([
|
|
{ fieldName: 'file0', relativePath: 'commands/git/commit.md' },
|
|
{ fieldName: 'file1', relativePath: 'commands/.DS_Store' },
|
|
]))
|
|
formData.append('file0', new File(['commit body'], 'commit.md', { type: 'text/markdown' }))
|
|
|
|
const res = await app.request('/settings/opencode-directory-files/install', {
|
|
method: 'POST',
|
|
body: formData,
|
|
})
|
|
|
|
expect(res.status).toBe(200)
|
|
await expect(res.json()).resolves.toEqual({
|
|
kind: 'commands',
|
|
filesInstalled: ['git/commit.md'],
|
|
restartRequired: true,
|
|
})
|
|
await expect(readFile(join(workspacePath, '.config/opencode/commands/git/commit.md'), 'utf8')).resolves.toBe('commit body')
|
|
expect(restart).not.toHaveBeenCalled()
|
|
expect(markRestartPendingSpy).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('lists uploaded command and agent directory files', async () => {
|
|
await mkdir(join(workspacePath, '.config/opencode/commands/git'), { recursive: true })
|
|
await mkdir(join(workspacePath, '.config/opencode/agents/team'), { recursive: true })
|
|
await writeFile(join(workspacePath, '.config/opencode/commands/git/commit.md'), 'commit body')
|
|
await writeFile(join(workspacePath, '.config/opencode/commands/git/.DS_Store'), 'metadata')
|
|
await writeFile(join(workspacePath, '.config/opencode/agents/team/planner.md'), 'planner body')
|
|
|
|
const commandsRes = await app.request('/settings/opencode-directory-files?kind=commands')
|
|
const agentsRes = await app.request('/settings/opencode-directory-files?kind=agents')
|
|
|
|
expect(commandsRes.status).toBe(200)
|
|
expect(agentsRes.status).toBe(200)
|
|
await expect(commandsRes.json()).resolves.toEqual([
|
|
{ kind: 'commands', name: 'commit', relativePath: 'git/commit.md' },
|
|
])
|
|
await expect(agentsRes.json()).resolves.toEqual([
|
|
{ kind: 'agents', name: 'planner', relativePath: 'team/planner.md' },
|
|
])
|
|
})
|
|
})
|