diff --git a/backend/src/routes/repo-project-config.ts b/backend/src/routes/repo-project-config.ts index 343e5b22..7a87dec3 100644 --- a/backend/src/routes/repo-project-config.ts +++ b/backend/src/routes/repo-project-config.ts @@ -3,7 +3,7 @@ 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, TrustRepoConfigRequestSchema, MoveProjectItemRequestSchema } from '@opencode-manager/shared/schemas' +import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema, TrustRepoConfigRequestSchema, MoveProjectItemRequestSchema, RunProjectActionRequestSchema } from '@opencode-manager/shared/schemas' import * as repoService from '../services/repo' import { resolveRepoWorkingDirectory } from '../services/repo' import { getRepoById } from '../db/queries' @@ -165,5 +165,28 @@ export function createRepoProjectConfigRoutes( } }) + app.post('/:id/project-config/actions/:actionId/run', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = RunProjectActionRequestSchema.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'), parsed.data.directory) + if (resolved instanceof Response) return resolved + + try { + const response = await deps.projectConfigService.runAction( + resolved.repo, + resolved.directory, + c.req.param('actionId'), + deps.terminalService, + ) + return c.json(response) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + return app } diff --git a/backend/src/services/project-config.ts b/backend/src/services/project-config.ts index 190324e2..4404c54b 100644 --- a/backend/src/services/project-config.ts +++ b/backend/src/services/project-config.ts @@ -12,11 +12,15 @@ import { type ProjectAction, type ProjectConfigResponse, type RepoProjectFile, + type RunProjectActionResponse, } from '@opencode-manager/shared/schemas' import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries' +import { executeCommand } from '../utils/process' import { getErrorMessage } from '../utils/error-utils' +import { canonicalPathSync } from '../utils/fs-safe' import type { GitService } from './git/GitService' import type { GitAuthService } from './git-auth' +import type { TerminalService } from './terminal' const PROJECT_ACTIONS_KEY = 'projectActions' const WORKTREE_SETUP_KEY = 'worktreeSetupCommands' @@ -55,6 +59,8 @@ export class ProjectConfigError extends Error { } export class ProjectConfigService { + private readonly actionRunQueues = new Map>() + constructor( private readonly database: Database, private readonly git: GitService, @@ -124,8 +130,14 @@ export class ProjectConfigService { repoFile.hash !== null && repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY) + const resolvedActions = await Promise.all( + actions.map(async (action) => + action.url ? { ...action, resolvedUrl: await this.resolveActionUrl(action.url, directory) } : action, + ), + ) + return { - actions, + actions: resolvedActions, worktreeSetup, repoFile: { path: '.ocm/project.json', @@ -138,6 +150,89 @@ export class ProjectConfigService { } } + async resolveActionUrl(template: string, directory: string): Promise { + const withWorktree = template.replaceAll('{worktree}', path.basename(directory)) + if (!withWorktree.includes('{branch}')) { + return withWorktree + } + + try { + const branch = ( + await executeCommand(['git', '-C', directory, 'rev-parse', '--abbrev-ref', 'HEAD'], { + env: this.gitAuthService.getGitEnvironment(), + silent: true, + }) + ).trim() + return withWorktree.replaceAll('{branch}', branch) + } catch { + return template + } + } + + async runAction( + repo: Repo, + directory: string, + actionId: string, + terminalService: TerminalService, + ): Promise { + const config = await this.getConfig(repo, directory) + const action = config.actions.find((item) => item.id === actionId) + if (!action) { + throw new ProjectConfigError(404, 'Action not found') + } + + if (action.source === 'repo' && !config.repoFile.trusted) { + throw new ProjectConfigError(409, 'Repository commands are not trusted', 'REPO_CONFIG_UNTRUSTED', { + hash: config.repoFile.hash, + }) + } + + const key = this.actionRunKey(directory, actionId) + return this.enqueueActionRun(key, async () => { + const terminals = await terminalService.list(directory) + const running = terminals.find( + (terminal) => terminal.kind === 'action' && terminal.actionId === actionId && terminal.status === 'running', + ) + const terminal = + running ?? + (await terminalService.create(directory, { + kind: 'action', + actionId, + name: action.name, + command: '/bin/sh', + args: ['-c', action.command], + })) + + return { + terminal, + alreadyRunning: running !== undefined, + ...(action.resolvedUrl ? { resolvedUrl: action.resolvedUrl } : {}), + autoOpenUrl: action.autoOpenUrl, + } + }) + } + + private actionRunKey(directory: string, actionId: string): string { + const canonical = canonicalPathSync(path.resolve(directory)) + return `${canonical}\u0000${actionId}` + } + + private enqueueActionRun(key: string, operation: () => Promise): Promise { + const previous = this.actionRunQueues.get(key) ?? Promise.resolve() + const result = previous.then(operation, operation) + const tail = result.then( + () => undefined, + () => undefined, + ) + this.actionRunQueues.set(key, tail) + void tail.then(() => { + if (this.actionRunQueues.get(key) === tail) { + this.actionRunQueues.delete(key) + } + }) + return result + } + readRepoFile(directory: string): RepoFileState { const filePath = this.getRepoFilePath(directory) if (!fs.existsSync(filePath)) { diff --git a/backend/test/routes/repo-project-config.test.ts b/backend/test/routes/repo-project-config.test.ts index 38583a10..1f07bf08 100644 --- a/backend/test/routes/repo-project-config.test.ts +++ b/backend/test/routes/repo-project-config.test.ts @@ -11,8 +11,10 @@ import { createRepoProjectConfigRoutes } from '../../src/routes/repo-project-con import { ProjectConfigService } from '../../src/services/project-config' import { createGitService } from '../../src/services/git/GitService' import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' +import { formatTerminalTitle } from '@opencode-manager/shared/utils' import type { GitAuthService } from '../../src/services/git-auth' -import type { TerminalService } from '../../src/services/terminal' +import type { CreateTerminalInput, TerminalService } from '../../src/services/terminal' +import type { TerminalInfo } from '@opencode-manager/shared/types' vi.mock('../../src/services/repo', () => ({ resolveRepoWorkingDirectory: vi.fn(), @@ -23,7 +25,18 @@ import { resolveRepoWorkingDirectory, getSiblingRepos } from '../../src/services const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService const openCodeClient = createStubOpenCodeClient() -const terminalService = {} as unknown as TerminalService +const terminalList = vi.fn(async (): Promise => []) +const terminalCreate = vi.fn( + async (directory: string, input: CreateTerminalInput): Promise => ({ + id: 'pty-1', + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + kind: input.kind, + ...(input.actionId ? { actionId: input.actionId } : {}), + cwd: directory, + status: 'running', + }), +) +const terminalService = { list: terminalList, create: terminalCreate } as unknown as TerminalService const jsonHeaders = { 'Content-Type': 'application/json' } function createApp(db: Database): Hono { @@ -284,4 +297,58 @@ describe('Repo Project Config Routes', () => { fs.rmSync(directory, { recursive: true, force: true }) } }) + + it('runs a personal action and returns the response shape', async () => { + seedRepo(db) + const action = { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false } + + await app.request('/1/project-config/actions', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ actions: [action] }), + }) + + const res = await app.request('/1/project-config/actions/serve/run', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({}), + }) + + expect(res.status).toBe(200) + const body = await res.json() as { + terminal: unknown + alreadyRunning: boolean + autoOpenUrl: boolean + resolvedUrl?: string + } + expect(body.alreadyRunning).toBe(false) + expect(body.autoOpenUrl).toBe(false) + expect(body.resolvedUrl).toBeUndefined() + expect(body.terminal).toMatchObject({ + id: 'pty-1', + title: 'ocm:action:serve:Serve', + kind: 'action', + actionId: 'serve', + status: 'running', + }) + expect(terminalCreate).toHaveBeenCalledWith(expect.any(String), { + kind: 'action', + actionId: 'serve', + name: 'Serve', + command: '/bin/sh', + args: ['-c', 'pnpm dev'], + }) + }) + + it('returns 404 when running an unknown action', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/actions/missing/run', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({}), + }) + + expect(res.status).toBe(404) + }) }) diff --git a/backend/test/services/project-config.test.ts b/backend/test/services/project-config.test.ts index 34f7f0d3..0f9e8ae4 100644 --- a/backend/test/services/project-config.test.ts +++ b/backend/test/services/project-config.test.ts @@ -10,8 +10,10 @@ 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 { CreateTerminalInput, TerminalService } from '../../src/services/terminal' +import { formatTerminalTitle } from '@opencode-manager/shared/utils' import type { ProjectAction } from '@opencode-manager/shared/schemas' -import type { Repo } from '@opencode-manager/shared/types' +import type { Repo, TerminalInfo } from '@opencode-manager/shared/types' const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService @@ -23,6 +25,41 @@ function createAction(overrides: Partial = {}): ProjectAction { return { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false, ...overrides } } +function createDeferred() { + let resolve!: () => void + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} + +async function flushAsync(): Promise { + await new Promise((resolve) => setImmediate(resolve)) +} + +function createStatefulTerminalService(gate: { promise: Promise } | null) { + const terminals: TerminalInfo[] = [] + let created = 0 + const list = vi.fn(async (target: string) => terminals.filter((terminal) => terminal.cwd === target)) + const create = vi.fn(async (target: string, input: CreateTerminalInput): Promise => { + if (gate) { + await gate.promise + } + created += 1 + const terminal: TerminalInfo = { + id: `pty-${created}`, + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + kind: input.kind, + ...(input.actionId ? { actionId: input.actionId } : {}), + cwd: target, + status: 'running', + } + terminals.push(terminal) + return terminal + }) + return { service: { list, create } as unknown as TerminalService, list, create, terminals } +} + describe('ProjectConfigService personal settings', () => { let db: Database let service: ProjectConfigService @@ -545,3 +582,230 @@ describe('ProjectConfigService repository file', () => { expect(service.getPersonalActions(repo)).toEqual([createAction()]) }) }) + +describe('ProjectConfigService runAction', () => { + let db: Database + let service: ProjectConfigService + let repo: Repo + let directory: string + + function writeRepoFile(content: unknown): void { + const filePath = path.join(directory, '.ocm', 'project.json') + fs.mkdirSync(path.dirname(filePath), { recursive: true }) + fs.writeFileSync(filePath, JSON.stringify(content, null, 2)) + } + + function createFakeTerminalService(terminals: TerminalInfo[] = []) { + const list = vi.fn(async () => terminals) + const create = vi.fn( + async (target: string, input: CreateTerminalInput): Promise => ({ + id: 'pty-1', + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + kind: input.kind, + ...(input.actionId ? { actionId: input.actionId } : {}), + cwd: target, + status: 'running', + }), + ) + return { service: { list, create } as unknown as TerminalService, list, create } + } + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-run-action-')) + repo = createRepo(db, { + localPath: directory, + sourcePath: directory, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + }) + + afterEach(() => { + db.close() + fs.rmSync(directory, { recursive: true, force: true }) + }) + + it('creates an action terminal with /bin/sh -c and the encoded action id', async () => { + service.setPersonalActions(repo, [createAction({ url: 'http://localhost:5173/{worktree}' })]) + const terminalService = createFakeTerminalService() + + const response = await service.runAction(repo, directory, 'serve', terminalService.service) + + expect(terminalService.create).toHaveBeenCalledWith(directory, { + kind: 'action', + actionId: 'serve', + name: 'Serve', + command: '/bin/sh', + args: ['-c', 'pnpm dev'], + }) + expect(response).toEqual({ + terminal: { + id: 'pty-1', + title: 'ocm:action:serve:Serve', + kind: 'action', + actionId: 'serve', + cwd: directory, + status: 'running', + }, + alreadyRunning: false, + resolvedUrl: `http://localhost:5173/${path.basename(directory)}`, + autoOpenUrl: false, + }) + }) + + it('returns an already running action terminal without creating another', async () => { + service.setPersonalActions(repo, [createAction()]) + const running: TerminalInfo = { + id: 'pty-existing', + title: 'Serve', + kind: 'action', + actionId: 'serve', + cwd: directory, + status: 'running', + } + const terminalService = createFakeTerminalService([running]) + + const response = await service.runAction(repo, directory, 'serve', terminalService.service) + + expect(terminalService.create).not.toHaveBeenCalled() + expect(response.alreadyRunning).toBe(true) + expect(response.terminal).toEqual(running) + }) + + it('returns 404 for an unknown action', async () => { + const terminalService = createFakeTerminalService() + + await expect(service.runAction(repo, directory, 'missing', terminalService.service)).rejects.toMatchObject({ + status: 404, + }) + expect(terminalService.create).not.toHaveBeenCalled() + }) + + it('rejects an untrusted repository action with the current hash', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }) + const terminalService = createFakeTerminalService() + + let caught: unknown + try { + await service.runAction(repo, directory, 'repo-serve', terminalService.service) + } catch (error: unknown) { + caught = error + } + + expect(caught).toBeInstanceOf(ProjectConfigError) + expect((caught as ProjectConfigError).status).toBe(409) + expect((caught as ProjectConfigError).code).toBe('REPO_CONFIG_UNTRUSTED') + expect((caught as ProjectConfigError).details).toMatchObject({ hash: expect.stringMatching(/^[a-f0-9]{64}$/) }) + expect(terminalService.create).not.toHaveBeenCalled() + }) + + it('runs a trusted repository action', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }) + const first = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '') + const terminalService = createFakeTerminalService() + + const response = await service.runAction(repo, directory, 'repo-serve', terminalService.service) + + expect(response.alreadyRunning).toBe(false) + expect(terminalService.create).toHaveBeenCalledWith(directory, expect.objectContaining({ actionId: 'repo-serve' })) + }) + + it('resolves {worktree} and {branch} against a real git checkout', async () => { + const gitDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-run-branch-')) + try { + execSync(`git init "${gitDirectory}"`) + execSync(`git -C "${gitDirectory}" config user.email test@test.com`) + execSync(`git -C "${gitDirectory}" config user.name Test`) + execSync(`git -C "${gitDirectory}" commit --allow-empty -m "Initial commit"`) + execSync(`git -C "${gitDirectory}" checkout -b feature/auth`) + + const url = await service.resolveActionUrl('http://localhost:3000/{worktree}/{branch}', gitDirectory) + + expect(url).toBe(`http://localhost:3000/${path.basename(gitDirectory)}/feature/auth`) + } finally { + fs.rmSync(gitDirectory, { recursive: true, force: true }) + } + }) + + it('returns the template unchanged when the branch cannot be resolved', async () => { + const template = 'http://localhost:3000/{branch}' + + await expect(service.resolveActionUrl(template, directory)).resolves.toBe(template) + }) + + it('creates exactly one terminal when the same action runs concurrently in one directory', async () => { + service.setPersonalActions(repo, [createAction()]) + const gate = createDeferred() + const terminalService = createStatefulTerminalService(gate) + + const first = service.runAction(repo, directory, 'serve', terminalService.service) + const second = service.runAction(repo, directory, 'serve', terminalService.service) + await flushAsync() + gate.resolve() + + const [firstResult, secondResult] = await Promise.all([first, second]) + + expect(terminalService.create).toHaveBeenCalledTimes(1) + expect(firstResult.alreadyRunning).toBe(false) + expect(secondResult.alreadyRunning).toBe(true) + expect(secondResult.terminal.id).toBe(firstResult.terminal.id) + }) + + it('releases the run key after a failed create so a retry can start', async () => { + service.setPersonalActions(repo, [createAction()]) + const terminals: TerminalInfo[] = [] + let attempts = 0 + const list = vi.fn(async (target: string) => terminals.filter((terminal) => terminal.cwd === target)) + const create = vi.fn(async (target: string, input: CreateTerminalInput): Promise => { + attempts += 1 + if (attempts === 1) { + throw new Error('spawn failed') + } + const terminal: TerminalInfo = { + id: `pty-${attempts}`, + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + kind: input.kind, + ...(input.actionId ? { actionId: input.actionId } : {}), + cwd: target, + status: 'running', + } + terminals.push(terminal) + return terminal + }) + const terminalService = { list, create } as unknown as TerminalService + + await expect(service.runAction(repo, directory, 'serve', terminalService)).rejects.toThrow('spawn failed') + + const response = await service.runAction(repo, directory, 'serve', terminalService) + + expect(response.alreadyRunning).toBe(false) + expect(response.terminal.id).toBe('pty-2') + expect(create).toHaveBeenCalledTimes(2) + }) + + it('does not serialize runs for different directories', async () => { + service.setPersonalActions(repo, [createAction()]) + const otherDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-run-action-other-')) + try { + const gate = createDeferred() + const terminalService = createStatefulTerminalService(gate) + + const first = service.runAction(repo, directory, 'serve', terminalService.service) + const second = service.runAction(repo, otherDirectory, 'serve', terminalService.service) + await flushAsync() + + expect(terminalService.create).toHaveBeenCalledTimes(2) + + gate.resolve() + await Promise.all([first, second]) + } finally { + fs.rmSync(otherDirectory, { recursive: true, force: true }) + } + }) +}) diff --git a/shared/src/schemas/project-config.ts b/shared/src/schemas/project-config.ts index e0a774da..cdc77db8 100644 --- a/shared/src/schemas/project-config.ts +++ b/shared/src/schemas/project-config.ts @@ -1,4 +1,5 @@ import { z } from 'zod' +import { TerminalInfoSchema } from './terminal' export const ProjectActionIconSchema = z.enum([ 'play', @@ -81,6 +82,17 @@ export const MoveProjectItemRequestSchema = z.discriminatedUnion('kind', [ }), ]) +export const RunProjectActionRequestSchema = z.object({ + directory: z.string().optional(), +}) + +export const RunProjectActionResponseSchema = z.object({ + terminal: TerminalInfoSchema, + alreadyRunning: z.boolean(), + resolvedUrl: z.string().optional(), + autoOpenUrl: z.boolean(), +}) + export type ProjectActionIcon = z.infer export type ProjectAction = z.infer export type WorktreeSetupCommands = z.infer @@ -91,3 +103,5 @@ export type UpdateProjectActionsRequest = z.infer export type TrustRepoConfigRequest = z.infer export type MoveProjectItemRequest = z.infer +export type RunProjectActionRequest = z.infer +export type RunProjectActionResponse = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 0c61269b..ee384994 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -177,4 +177,6 @@ export type { UpdateWorktreeSetupRequest, TrustRepoConfigRequest, MoveProjectItemRequest, + RunProjectActionRequest, + RunProjectActionResponse, } from '../schemas/project-config'