diff --git a/backend/src/routes/repo-git.ts b/backend/src/routes/repo-git.ts index b85be5ab..37ff8ab7 100644 --- a/backend/src/routes/repo-git.ts +++ b/backend/src/routes/repo-git.ts @@ -4,17 +4,13 @@ import type { ContentfulStatusCode } from 'hono/utils/http-status' import { getRepoById } from '../db/queries' import { logger } from '../utils/logger' import { parseGitError } from '../utils/git-errors' -import { GitService } from '../services/git/GitService' +import { createGitService } from '../services/git/GitService' import type { GitAuthService } from '../services/git-auth' -import { SettingsService } from '../services/settings' -import { CredentialProvider } from '../services/credential-provider' import type { GitStatusResponse } from '../types/git' export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthService) { const app = new Hono() - const settingsService = new SettingsService(database) - const credentialProvider = new CredentialProvider(database) - const git = new GitService(gitAuthService, settingsService, credentialProvider) + const git = createGitService(database, gitAuthService) app.get('/:id/git/status', async (c) => { try { diff --git a/backend/src/routes/repo-project-config.ts b/backend/src/routes/repo-project-config.ts new file mode 100644 index 00000000..58ba8158 --- /dev/null +++ b/backend/src/routes/repo-project-config.ts @@ -0,0 +1,133 @@ +import { Hono } from 'hono' +import type { Context } from 'hono' +import type { ContentfulStatusCode } from 'hono/utils/http-status' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema } from '@opencode-manager/shared/schemas' +import * as repoService from '../services/repo' +import { resolveRepoWorkingDirectory } from '../services/repo' +import { getRepoById } from '../db/queries' +import type { GitAuthService } from '../services/git-auth' +import type { OpenCodeClient } from '../services/opencode/client' +import type { TerminalService } from '../services/terminal' +import { ProjectConfigError, type ProjectConfigService } from '../services/project-config' +import { logger } from '../utils/logger' +import { getErrorMessage } from '../utils/error-utils' + +export interface RepoProjectConfigDeps { + database: Database + gitAuthService: GitAuthService + openCodeClient: OpenCodeClient + projectConfigService: ProjectConfigService + terminalService: TerminalService +} + +function handleProjectConfigError(c: Context, error: unknown): Response { + if (error instanceof ProjectConfigError) { + return c.json( + { error: error.message, code: error.code, details: error.details }, + error.status as ContentfulStatusCode, + ) + } + logger.error('Project config request failed:', error) + return c.json({ error: getErrorMessage(error) }, 500) +} + +export function createRepoProjectConfigRoutes( + database: Database, + gitAuthService: GitAuthService, + openCodeClient: OpenCodeClient, + projectConfigService: ProjectConfigService, + terminalService: TerminalService, +) { + const deps: RepoProjectConfigDeps = { + database, + gitAuthService, + openCodeClient, + projectConfigService, + terminalService, + } + const app = new Hono() + + async function resolveRepoDirectory( + c: Context, + repoIdParam: string, + directory: string | undefined, + ): Promise<{ repo: Repo; directory: string } | Response> { + const id = Number.parseInt(repoIdParam, 10) + if (Number.isNaN(id)) { + return c.json({ error: 'Invalid repo id' }, 400) + } + + const repo = getRepoById(deps.database, id) + if (!repo || repo.cloneStatus !== 'ready') { + return c.json({ error: 'Repo not found' }, 404) + } + + const resolved = await resolveRepoWorkingDirectory(repo, directory, () => + repoService.getSiblingRepos( + deps.database, + repo.id, + deps.gitAuthService.getGitEnvironment(), + deps.openCodeClient, + ), + ) + + if (!resolved) { + return c.json({ error: 'Directory is not part of this repository' }, 400) + } + + return { repo, directory: resolved } + } + + app.get('/:id/project-config', async (c) => { + const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + try { + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + + app.put('/:id/project-config/actions', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = UpdateProjectActionsRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + try { + const projectRepo = await deps.projectConfigService.resolveProjectRepo(resolved.repo) + deps.projectConfigService.setPersonalActions(projectRepo, parsed.data.actions) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + + app.put('/:id/project-config/worktree-setup', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = UpdateWorktreeSetupRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + try { + const projectRepo = await deps.projectConfigService.resolveProjectRepo(resolved.repo) + deps.projectConfigService.setPersonalSetup(projectRepo, parsed.data.commands) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + + return app +} diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 921536f2..56136fa8 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -16,9 +16,12 @@ import { ASSISTANT_REPO_ID, isWorktreeSibling } from '@opencode-manager/shared/u import { isWorktreeError, openCodeLocation } from '@opencode-manager/shared/opencode' import { createRepoGitRoutes } from './repo-git' import { createRepoTerminalRoutes } from './repo-terminals' +import { createRepoProjectConfigRoutes } from './repo-project-config' import { createScheduleRoutes } from './schedules' import type { GitAuthService } from '../services/git-auth' import type { TerminalService } from '../services/terminal' +import { ProjectConfigService } from '../services/project-config' +import { createGitService } from '../services/git/GitService' import { ScheduleService } from '../services/schedules' import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode' import path from 'path' @@ -51,8 +54,15 @@ export function createRepoRoutes( ) { const app = new Hono() + const projectConfigService = new ProjectConfigService( + database, + createGitService(database, gitAuthService), + gitAuthService, + ) + app.route('/', createRepoGitRoutes(database, gitAuthService)) app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, terminalService)) + app.route('/', createRepoProjectConfigRoutes(database, gitAuthService, openCodeClient, projectConfigService, terminalService)) app.route('/:id/schedules', createScheduleRoutes(scheduleService)) app.post('/', async (c) => { diff --git a/backend/src/services/git/GitService.ts b/backend/src/services/git/GitService.ts index 7f49284e..7bd4d08e 100644 --- a/backend/src/services/git/GitService.ts +++ b/backend/src/services/git/GitService.ts @@ -12,6 +12,10 @@ import type { Database } from 'bun:sqlite' import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType, CommitDetails, CommitFile } from '../../types/git' import path from 'path' +export function createGitService(database: Database, gitAuthService: GitAuthService): GitService { + return new GitService(gitAuthService, new SettingsService(database), new CredentialProvider(database)) +} + export class GitService { constructor( private gitAuthService: GitAuthService, @@ -19,6 +23,16 @@ export class GitService { private credentialProvider: CredentialProvider ) {} + async getMainCheckoutPath(directory: string): Promise { + const env = this.gitAuthService.getGitEnvironment() + const output = await executeCommand(['git', '-C', directory, 'worktree', 'list', '--porcelain'], { env }) + const firstEntry = output.split('\n').find((line) => line.startsWith('worktree ')) + if (!firstEntry) { + throw new Error(`Unable to resolve the main checkout for ${directory}`) + } + return firstEntry.slice('worktree '.length).trim() + } + async getStatus(repoId: number, database: Database): Promise { try { const repo = getRepoById(database, repoId) diff --git a/backend/src/services/project-config.ts b/backend/src/services/project-config.ts new file mode 100644 index 00000000..0e35a05c --- /dev/null +++ b/backend/src/services/project-config.ts @@ -0,0 +1,100 @@ +import { z } from 'zod' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { + ProjectActionSchema, + WorktreeSetupCommandsSchema, + type ProjectAction, + type ProjectConfigResponse, +} from '@opencode-manager/shared/schemas' +import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries' +import type { GitService } from './git/GitService' +import type { GitAuthService } from './git-auth' + +const PROJECT_ACTIONS_KEY = 'projectActions' +const WORKTREE_SETUP_KEY = 'worktreeSetupCommands' +const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash' + +export class ProjectConfigError extends Error { + constructor( + public status: number, + message: string, + public code?: string, + public details?: unknown, + ) { + super(message) + this.name = 'ProjectConfigError' + } +} + +export class ProjectConfigService { + constructor( + private readonly database: Database, + private readonly git: GitService, + private readonly gitAuthService: GitAuthService, + ) {} + + async resolveProjectRepo(repo: Repo): Promise { + if (!repo.isWorktree) { + return repo + } + const mainCheckout = await this.git.getMainCheckoutPath(repo.fullPath) + return getRepoByDirectory(this.database, mainCheckout) ?? repo + } + + getPersonalActions(projectRepo: Repo): ProjectAction[] { + return this.readStoredJson(projectRepo.id, PROJECT_ACTIONS_KEY, z.array(ProjectActionSchema)) ?? [] + } + + setPersonalActions(projectRepo: Repo, actions: ProjectAction[]): void { + const ids = new Set() + for (const action of actions) { + if (ids.has(action.id)) { + throw new ProjectConfigError(400, 'Duplicate action id') + } + ids.add(action.id) + } + setRepoSetting(this.database, projectRepo.id, PROJECT_ACTIONS_KEY, JSON.stringify(actions)) + } + + getPersonalSetup(projectRepo: Repo): string[] { + return this.readStoredJson(projectRepo.id, WORKTREE_SETUP_KEY, WorktreeSetupCommandsSchema) ?? [] + } + + setPersonalSetup(projectRepo: Repo, commands: string[]): void { + setRepoSetting(this.database, projectRepo.id, WORKTREE_SETUP_KEY, JSON.stringify(commands)) + } + + async getConfig(repo: Repo, directory: string): Promise { + const projectRepo = await this.resolveProjectRepo(repo) + const actions = this.getPersonalActions(projectRepo).map((action) => ({ ...action, source: 'personal' as const })) + const worktreeSetup = this.getPersonalSetup(projectRepo).map((command) => ({ command, source: 'personal' as const })) + const hash: string | null = null + void directory + + return { + actions, + worktreeSetup, + repoFile: { + path: '.ocm/project.json', + exists: false, + trusted: hash !== null && hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY), + hash, + warnings: [], + }, + } + } + + private readStoredJson(repoId: number, key: string, schema: z.ZodType): T | null { + const raw = getRepoSetting(this.database, repoId, key) + if (!raw) { + return null + } + try { + const result = schema.safeParse(JSON.parse(raw)) + return result.success ? result.data : null + } catch { + return null + } + } +} diff --git a/backend/test/routes/repo-project-config.test.ts b/backend/test/routes/repo-project-config.test.ts new file mode 100644 index 00000000..df1f0599 --- /dev/null +++ b/backend/test/routes/repo-project-config.test.ts @@ -0,0 +1,175 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { Hono } from 'hono' +import { Database } from 'bun:sqlite' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import { createRepo } from '../../src/db/queries' +import { createRepoProjectConfigRoutes } from '../../src/routes/repo-project-config' +import { ProjectConfigService } from '../../src/services/project-config' +import { createGitService } from '../../src/services/git/GitService' +import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' +import type { GitAuthService } from '../../src/services/git-auth' +import type { TerminalService } from '../../src/services/terminal' + +vi.mock('../../src/services/repo', () => ({ + resolveRepoWorkingDirectory: vi.fn(), + getSiblingRepos: vi.fn(), +})) + +import { resolveRepoWorkingDirectory, getSiblingRepos } from '../../src/services/repo' + +const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService +const openCodeClient = createStubOpenCodeClient() +const terminalService = {} as unknown as TerminalService +const jsonHeaders = { 'Content-Type': 'application/json' } + +function createApp(db: Database): Hono { + const service = new ProjectConfigService(db, createGitService(db, gitAuthService), gitAuthService) + const app = new Hono() + app.route('/', createRepoProjectConfigRoutes(db, gitAuthService, openCodeClient, service, terminalService)) + return app +} + +function createTestDb(): Database { + const db = new Database(':memory:') + migrate(db, allMigrations) + return db +} + +function seedRepo(db: Database): void { + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) +} + +describe('Repo Project Config Routes', () => { + let db: Database + let app: Hono + + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(getSiblingRepos).mockResolvedValue([]) + vi.mocked(resolveRepoWorkingDirectory).mockImplementation(async (repo, directory) => { + if (directory === undefined || directory === repo.fullPath) return repo.fullPath + return null + }) + db = createTestDb() + app = createApp(db) + }) + + afterEach(() => { + db.close() + }) + + it('returns personal config for a ready repo', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config') + + expect(res.status).toBe(200) + const body = await res.json() as { actions: unknown[]; worktreeSetup: unknown[]; repoFile: unknown } + expect(body.actions).toEqual([]) + expect(body.worktreeSetup).toEqual([]) + expect(body.repoFile).toEqual({ + path: '.ocm/project.json', + exists: false, + trusted: false, + hash: null, + warnings: [], + }) + }) + + it('returns 404 for an unknown repo', async () => { + const res = await app.request('/999/project-config') + + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Repo not found' }) + }) + + it('returns 404 for a repo that is not ready', async () => { + createRepo(db, { localPath: 'repo-cloning', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true }) + + const res = await app.request('/1/project-config') + + expect(res.status).toBe(404) + }) + + it('returns 400 for a non-numeric repo id', async () => { + const res = await app.request('/abc/project-config') + + expect(res.status).toBe(400) + }) + + it('round-trips personal actions with the personal source', async () => { + seedRepo(db) + const action = { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false } + + const put = await app.request('/1/project-config/actions', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ actions: [action] }), + }) + expect(put.status).toBe(200) + expect((await put.json() as { actions: unknown[] }).actions).toEqual([{ ...action, source: 'personal' }]) + + const get = await app.request('/1/project-config') + expect(get.status).toBe(200) + expect((await get.json() as { actions: unknown[] }).actions).toEqual([{ ...action, source: 'personal' }]) + }) + + it('round-trips personal worktree setup commands', async () => { + seedRepo(db) + + const put = await app.request('/1/project-config/worktree-setup', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ commands: ['pnpm install', 'pnpm build'] }), + }) + expect(put.status).toBe(200) + expect((await put.json() as { worktreeSetup: unknown[] }).worktreeSetup).toEqual([ + { command: 'pnpm install', source: 'personal' }, + { command: 'pnpm build', source: 'personal' }, + ]) + + const get = await app.request('/1/project-config') + expect((await get.json() as { worktreeSetup: unknown[] }).worktreeSetup).toEqual([ + { command: 'pnpm install', source: 'personal' }, + { command: 'pnpm build', source: 'personal' }, + ]) + }) + + it('returns 400 for schema violations on actions', async () => { + seedRepo(db) + + const bodies = [ + '{}', + JSON.stringify({ actions: 'nope' }), + JSON.stringify({ actions: [{ id: 'has space', name: 'Serve', command: 'pnpm dev' }] }), + JSON.stringify({ actions: [{ id: 'serve', name: '', command: 'pnpm dev' }] }), + JSON.stringify({ actions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', icon: 'unknown' }] }), + ] + + for (const body of bodies) { + const res = await app.request('/1/project-config/actions', { method: 'PUT', headers: jsonHeaders, body }) + expect(res.status).toBe(400) + } + }) + + it('returns 400 for schema violations on worktree setup', async () => { + seedRepo(db) + + const bodies = ['{}', JSON.stringify({ commands: 'nope' }), JSON.stringify({ commands: [''] })] + + for (const body of bodies) { + const res = await app.request('/1/project-config/worktree-setup', { method: 'PUT', headers: jsonHeaders, body }) + expect(res.status).toBe(400) + } + }) + + it('returns 400 for a foreign directory', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config?directory=/tmp/other') + + expect(res.status).toBe(400) + expect(await res.json()).toEqual({ error: 'Directory is not part of this repository' }) + }) +}) diff --git a/backend/test/services/project-config.test.ts b/backend/test/services/project-config.test.ts new file mode 100644 index 00000000..c21f84e9 --- /dev/null +++ b/backend/test/services/project-config.test.ts @@ -0,0 +1,195 @@ +import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll } from 'vitest' +import { Database } from 'bun:sqlite' +import { execSync } from 'node:child_process' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import { createRepo, setRepoSetting } from '../../src/db/queries' +import { createGitService } from '../../src/services/git/GitService' +import { ProjectConfigService, ProjectConfigError } from '../../src/services/project-config' +import type { GitAuthService } from '../../src/services/git-auth' +import type { ProjectAction } from '@opencode-manager/shared/schemas' +import type { Repo } from '@opencode-manager/shared/types' + +const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService + +function createService(db: Database): ProjectConfigService { + return new ProjectConfigService(db, createGitService(db, gitAuthService), gitAuthService) +} + +function createAction(overrides: Partial = {}): ProjectAction { + return { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false, ...overrides } +} + +describe('ProjectConfigService personal settings', () => { + let db: Database + let service: ProjectConfigService + let repo: Repo + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + repo = createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + }) + + afterEach(() => { + db.close() + }) + + it('round-trips personal actions', () => { + const actions = [createAction(), createAction({ id: 'test', name: 'Test', command: 'pnpm test' })] + + service.setPersonalActions(repo, actions) + + expect(service.getPersonalActions(repo)).toEqual(actions) + }) + + it('returns personal actions through getConfig with the personal source', async () => { + service.setPersonalActions(repo, [createAction()]) + + const config = await service.getConfig(repo, repo.fullPath) + + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + expect(config.repoFile).toEqual({ + path: '.ocm/project.json', + exists: false, + trusted: false, + hash: null, + warnings: [], + }) + }) + + it('round-trips personal setup commands through getConfig', async () => { + service.setPersonalSetup(repo, ['pnpm install', 'pnpm build']) + + expect(service.getPersonalSetup(repo)).toEqual(['pnpm install', 'pnpm build']) + + const config = await service.getConfig(repo, repo.fullPath) + expect(config.worktreeSetup).toEqual([ + { command: 'pnpm install', source: 'personal' }, + { command: 'pnpm build', source: 'personal' }, + ]) + }) + + it('rejects duplicate action ids', () => { + let caught: unknown + try { + service.setPersonalActions(repo, [createAction(), createAction({ name: 'Other' })]) + } catch (error: unknown) { + caught = error + } + + expect(caught).toBeInstanceOf(ProjectConfigError) + expect((caught as ProjectConfigError).status).toBe(400) + expect((caught as ProjectConfigError).message).toBe('Duplicate action id') + }) + + it('reads corrupt stored action JSON as an empty list', () => { + setRepoSetting(db, repo.id, 'projectActions', '{not json') + + expect(service.getPersonalActions(repo)).toEqual([]) + }) + + it('reads wrongly shaped stored action JSON as an empty list', () => { + setRepoSetting(db, repo.id, 'projectActions', JSON.stringify({ id: 'serve' })) + + expect(service.getPersonalActions(repo)).toEqual([]) + }) + + it('reads corrupt stored setup JSON as an empty list', () => { + setRepoSetting(db, repo.id, 'worktreeSetupCommands', 'not-json') + + expect(service.getPersonalSetup(repo)).toEqual([]) + }) +}) + +describe('ProjectConfigService worktree resolution', () => { + let db: Database + let service: ProjectConfigService + let basePath: string + let worktreePath: string + let root: string + let baseRepo: Repo + let worktreeRepo: Repo + + beforeAll(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-project-config-'))) + basePath = path.join(root, 'base') + worktreePath = path.join(root, 'linked worktree') + + execSync(`git init "${basePath}"`) + execSync(`git -C "${basePath}" config user.email test@test.com`) + execSync(`git -C "${basePath}" config user.name Test`) + execSync(`git -C "${basePath}" commit --allow-empty -m "Initial commit"`) + execSync(`git -C "${basePath}" worktree add -b feature "${worktreePath}"`) + }) + + afterAll(() => { + fs.rmSync(root, { recursive: true, force: true }) + }) + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + baseRepo = createRepo(db, { + localPath: basePath, + sourcePath: basePath, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + worktreeRepo = createRepo(db, { + localPath: worktreePath, + sourcePath: worktreePath, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + isWorktree: true, + }) + }) + + afterEach(() => { + db.close() + }) + + it('resolves the main checkout from both the base and the linked worktree', async () => { + const git = createGitService(db, gitAuthService) + + expect(fs.realpathSync(await git.getMainCheckoutPath(basePath))).toBe(fs.realpathSync(basePath)) + expect(fs.realpathSync(await git.getMainCheckoutPath(worktreePath))).toBe(fs.realpathSync(basePath)) + }) + + it('resolves a linked worktree repo to the main checkout row', async () => { + const resolved = await service.resolveProjectRepo(worktreeRepo) + + expect(resolved.id).toBe(baseRepo.id) + }) + + it('keeps a non-worktree repo unchanged', async () => { + const resolved = await service.resolveProjectRepo(baseRepo) + + expect(resolved.id).toBe(baseRepo.id) + }) + + it('returns personal actions saved on the base repo when resolving from the worktree', async () => { + service.setPersonalActions(baseRepo, [createAction()]) + + const config = await service.getConfig(worktreeRepo, worktreePath) + + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + }) + + it('returns personal setup saved on the base repo when resolving from the worktree', async () => { + service.setPersonalSetup(baseRepo, ['pnpm install']) + + const config = await service.getConfig(worktreeRepo, worktreePath) + + expect(config.worktreeSetup).toEqual([{ command: 'pnpm install', source: 'personal' }]) + }) +}) diff --git a/shared/src/schemas/index.ts b/shared/src/schemas/index.ts index f3511212..026ca535 100644 --- a/shared/src/schemas/index.ts +++ b/shared/src/schemas/index.ts @@ -13,3 +13,4 @@ export * from './internal-assistant' export * from './session-pins' export * from './logs' export * from './terminal' +export * from './project-config' diff --git a/shared/src/schemas/project-config.ts b/shared/src/schemas/project-config.ts new file mode 100644 index 00000000..3ad6763f --- /dev/null +++ b/shared/src/schemas/project-config.ts @@ -0,0 +1,71 @@ +import { z } from 'zod' + +export const ProjectActionIconSchema = z.enum([ + 'play', + 'build', + 'test', + 'lint', + 'terminal', + 'server', + 'bug', + 'rocket', +]) + +export const ProjectActionSchema = z.object({ + id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/), + name: z.string().trim().min(1).max(60), + command: z.string().trim().min(1).max(4000), + icon: ProjectActionIconSchema.optional(), + url: z.string().trim().max(500).optional(), + autoOpenUrl: z.boolean().default(false), +}) + +export const WorktreeSetupCommandsSchema = z.array(z.string().trim().min(1).max(4000)).max(20) + +export const ProjectItemSourceSchema = z.enum(['personal', 'repo']) + +export const RepoProjectFileSchema = z.looseObject({ + version: z.literal(1), + projectActions: z.array(ProjectActionSchema).optional(), + setupWorktree: WorktreeSetupCommandsSchema.optional(), +}) + +export const ProjectConfigResponseSchema = z.object({ + actions: z.array( + ProjectActionSchema.extend({ + source: ProjectItemSourceSchema, + resolvedUrl: z.string().optional(), + }), + ), + worktreeSetup: z.array( + z.object({ + command: z.string(), + source: ProjectItemSourceSchema, + }), + ), + repoFile: z.object({ + path: z.literal('.ocm/project.json'), + exists: z.boolean(), + trusted: z.boolean(), + hash: z.string().nullable(), + error: z.string().optional(), + warnings: z.array(z.string()), + }), +}) + +export const UpdateProjectActionsRequestSchema = z.object({ + actions: z.array(ProjectActionSchema).max(50), +}) + +export const UpdateWorktreeSetupRequestSchema = z.object({ + commands: WorktreeSetupCommandsSchema, +}) + +export type ProjectActionIcon = z.infer +export type ProjectAction = z.infer +export type WorktreeSetupCommands = z.infer +export type ProjectItemSource = z.infer +export type RepoProjectFile = z.infer +export type ProjectConfigResponse = z.infer +export type UpdateProjectActionsRequest = z.infer +export type UpdateWorktreeSetupRequest = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index b3a5055a..6b067f45 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -165,3 +165,14 @@ export type { CreateTerminalRequest, ResizeTerminalRequest, } from '../schemas/terminal' + +export type { + ProjectActionIcon, + ProjectAction, + WorktreeSetupCommands, + ProjectItemSource, + RepoProjectFile, + ProjectConfigResponse, + UpdateProjectActionsRequest, + UpdateWorktreeSetupRequest, +} from '../schemas/project-config'