diff --git a/backend/src/index.ts b/backend/src/index.ts index 88cfe0f1..1963d742 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -49,6 +49,7 @@ import { createOpenCodeClient } from './services/opencode/client' import { NotificationService } from './services/notification' import { ScheduleRunner, ScheduleService } from './services/schedules' import { CredentialProvider } from './services/credential-provider' +import { TerminalService } from './services/terminal' import { ScheduleWorktreeManager } from './services/schedule-worktree' import { migrateGlobalSkills } from './services/skills' import { installAssistantWorkspace } from './services/assistant-mode' @@ -222,6 +223,7 @@ try { const settingsServiceForSchedules = new SettingsService(db) const credentialProvider = new CredentialProvider(db) +const terminalService = new TerminalService(openCodeClient, credentialProvider) const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, settingsServiceForSchedules, credentialProvider, db) const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager) const scheduleRunnerInstance = new ScheduleRunner(scheduleService) @@ -270,7 +272,7 @@ app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService)) const protectedApi = new Hono() protectedApi.use('/*', requireAuth) -protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient)) +protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, terminalService)) protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor)) protectedApi.route('/files', createFileRoutes()) protectedApi.route('/filesystem', createFilesystemRoutes()) diff --git a/backend/src/routes/repo-terminals.ts b/backend/src/routes/repo-terminals.ts new file mode 100644 index 00000000..6589157a --- /dev/null +++ b/backend/src/routes/repo-terminals.ts @@ -0,0 +1,140 @@ +import { Hono } from 'hono' +import type { Context } from 'hono' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { CreateTerminalRequestSchema, ResizeTerminalRequestSchema } from '@opencode-manager/shared/schemas' +import * as repoService from '../services/repo' +import { resolveRepoOrAssistant, resolveRepoWorkingDirectory } from '../services/repo' +import type { GitAuthService } from '../services/git-auth' +import type { OpenCodeClient } from '../services/opencode/client' +import { TerminalService, TerminalNotFoundError } from '../services/terminal' +import { handleOpenCodeError } from '../utils/route-helpers' + +export interface TerminalDirectoryDeps { + database: Database + gitAuthService: GitAuthService + openCodeClient: OpenCodeClient +} + +export interface TerminalRoutesDeps extends TerminalDirectoryDeps { + terminalService: TerminalService +} + +export async function resolveTerminalDirectory( + c: Context, + deps: TerminalDirectoryDeps, + 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 = resolveRepoOrAssistant(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 } +} + +export function createRepoTerminalRoutes( + database: Database, + gitAuthService: GitAuthService, + openCodeClient: OpenCodeClient, + terminalService: TerminalService, +) { + const deps: TerminalRoutesDeps = { database, gitAuthService, openCodeClient, terminalService } + const app = new Hono() + + app.get('/:id/terminals', async (c) => { + const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + try { + const terminals = await deps.terminalService.list(resolved.directory) + return c.json({ terminals }) + } catch (error: unknown) { + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + app.post('/:id/terminals', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = CreateTerminalRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request' }, 400) + } + + const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), parsed.data.directory) + if (resolved instanceof Response) return resolved + + try { + const terminal = await deps.terminalService.create(resolved.directory, { + kind: 'shell', + name: parsed.data.title ?? 'Terminal', + }) + return c.json(terminal) + } catch (error: unknown) { + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + app.patch('/:id/terminals/:ptyID', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = ResizeTerminalRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request' }, 400) + } + + const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), parsed.data.directory) + if (resolved instanceof Response) return resolved + + const ptyID = c.req.param('ptyID') + + try { + await deps.terminalService.requireTerminal(resolved.directory, ptyID) + await deps.terminalService.resize(resolved.directory, ptyID, { cols: parsed.data.cols, rows: parsed.data.rows }) + return c.json({ success: true }) + } catch (error: unknown) { + if (error instanceof TerminalNotFoundError) { + return c.json({ error: error.message }, 404) + } + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + app.delete('/:id/terminals/:ptyID', async (c) => { + const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + const ptyID = c.req.param('ptyID') + + try { + await deps.terminalService.requireTerminal(resolved.directory, ptyID) + await deps.terminalService.remove(resolved.directory, ptyID) + return c.json({ success: true }) + } catch (error: unknown) { + if (error instanceof TerminalNotFoundError) { + return c.json({ error: error.message }, 404) + } + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + return app +} diff --git a/backend/src/routes/repos.test.ts b/backend/src/routes/repos.test.ts index eb906112..b89e8740 100644 --- a/backend/src/routes/repos.test.ts +++ b/backend/src/routes/repos.test.ts @@ -7,6 +7,7 @@ import { createRepoRoutes } from './repos' import { createRepo, getRepoById } from '../db/queries' import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client' import type { GitAuthService } from '../services/git-auth' +import type { TerminalService } from '../services/terminal' import type { OpenCodeClient } from '../services/opencode/client' import type { Repo } from '@opencode-manager/shared/types' import { getReposPath } from '@opencode-manager/shared/config/env' @@ -28,6 +29,10 @@ const stubGitAuthService = { getGitCredentials: async () => [], } as unknown as GitAuthService +const stubTerminalService = { + removeAll: mock(async () => undefined), +} as unknown as TerminalService + function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStubOpenCodeClient()): Hono { const app = new Hono() const scheduleService = { @@ -38,7 +43,7 @@ function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStub deleteSchedule: () => {}, prepareRepoDelete: () => {}, } as any - app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient)) + app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, stubTerminalService)) return app } diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index ff13bb32..921536f2 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -15,8 +15,10 @@ import { handleOpenCodeError } from '../utils/route-helpers' import { ASSISTANT_REPO_ID, isWorktreeSibling } from '@opencode-manager/shared/utils' import { isWorktreeError, openCodeLocation } from '@opencode-manager/shared/opencode' import { createRepoGitRoutes } from './repo-git' +import { createRepoTerminalRoutes } from './repo-terminals' import { createScheduleRoutes } from './schedules' import type { GitAuthService } from '../services/git-auth' +import type { TerminalService } from '../services/terminal' import { ScheduleService } from '../services/schedules' import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode' import path from 'path' @@ -32,15 +34,25 @@ function withRepoSettings(database: Database, repo: Repo): Repo { } } +async function removeDirectoryTerminals(terminalService: TerminalService, directory: string): Promise { + try { + await terminalService.removeAll(directory) + } catch (error: unknown) { + logger.warn(`Failed to remove terminals for ${directory}:`, error) + } +} + export function createRepoRoutes( database: Database, gitAuthService: GitAuthService, scheduleService: ScheduleService, openCodeClient: OpenCodeClient, + terminalService: TerminalService, ) { const app = new Hono() app.route('/', createRepoGitRoutes(database, gitAuthService)) + app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, terminalService)) app.route('/:id/schedules', createScheduleRoutes(scheduleService)) app.post('/', async (c) => { @@ -268,6 +280,8 @@ app.get('/', async (c) => { const worktree = repoService.findSiblingByDirectory(siblings.filter(isWorktreeSibling), directory) if (!worktree) return c.json({ error: 'Not a deletable worktree of this repo' }, 400) + await removeDirectoryTerminals(terminalService, worktree.fullPath) + try { const projectID = await repoService.resolveRepoProjectId(openCodeClient, repo.fullPath) await openCodeClient.api.worktree.remove({ projectID, directory: worktree.fullPath, force: true }) @@ -325,7 +339,9 @@ app.get('/', async (c) => { } scheduleService.prepareRepoDelete(id) - + + await removeDirectoryTerminals(terminalService, repo.fullPath) + await repoService.deleteRepoFiles(database, id) return c.json({ success: true }) diff --git a/backend/src/services/terminal.ts b/backend/src/services/terminal.ts new file mode 100644 index 00000000..3833b87d --- /dev/null +++ b/backend/src/services/terminal.ts @@ -0,0 +1,93 @@ +import { openCodeErrorStatus } from '@opencode-manager/shared/opencode' +import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/shared/utils' +import type { TerminalInfo, TerminalKind } from '@opencode-manager/shared/types' +import type { OpenCodeClient } from './opencode/client' +import type { CredentialProvider } from './credential-provider' + +type OpenCodePty = Awaited>['data'][number] + +export interface CreateTerminalInput { + kind: TerminalKind + name: string + actionId?: string + command?: string + args?: string[] + env?: Record +} + +export interface TerminalSize { + cols: number + rows: number +} + +export class TerminalNotFoundError extends Error { + constructor(ptyID: string) { + super(`Terminal not found: ${ptyID}`) + this.name = 'TerminalNotFoundError' + } +} + +export class TerminalService { + constructor( + private readonly openCodeClient: OpenCodeClient, + private readonly credentialProvider: CredentialProvider, + ) {} + + async list(directory: string): Promise { + const result = await this.openCodeClient.api.pty.list({ location: { directory } }) + return result.data.map((pty) => this.toTerminalInfo(pty)) + } + + async create(directory: string, input: CreateTerminalInput): Promise { + const result = await this.openCodeClient.api.pty.create({ + location: { directory }, + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + ...(input.command !== undefined ? { command: input.command } : {}), + ...(input.args !== undefined ? { args: input.args } : {}), + env: { ...this.credentialProvider.getShellEnv({ cwd: directory }), ...input.env }, + }) + return this.toTerminalInfo(result.data) + } + + async requireTerminal(directory: string, ptyID: string): Promise { + const terminals = await this.list(directory) + const terminal = terminals.find((entry) => entry.id === ptyID) + if (!terminal) { + throw new TerminalNotFoundError(ptyID) + } + return terminal + } + + async resize(directory: string, ptyID: string, size: TerminalSize): Promise { + await this.openCodeClient.api.pty.update({ ptyID, location: { directory }, size }) + } + + async remove(directory: string, ptyID: string): Promise { + await this.openCodeClient.api.pty.remove({ ptyID, location: { directory } }) + } + + async removeAll(directory: string): Promise { + const terminals = await this.list(directory) + for (const terminal of terminals) { + try { + await this.remove(directory, terminal.id) + } catch (error: unknown) { + if (openCodeErrorStatus(error) === 404) continue + throw error + } + } + } + + private toTerminalInfo(pty: OpenCodePty): TerminalInfo { + const parsed = parseTerminalTitle(pty.title) + return { + id: pty.id, + title: parsed.title, + kind: parsed.kind, + ...(parsed.actionId ? { actionId: parsed.actionId } : {}), + cwd: pty.cwd, + status: pty.status, + ...(pty.exitCode !== undefined ? { exitCode: pty.exitCode } : {}), + } + } +} diff --git a/backend/test/routes/git.test.ts b/backend/test/routes/git.test.ts index 549c6e04..c928cf57 100644 --- a/backend/test/routes/git.test.ts +++ b/backend/test/routes/git.test.ts @@ -6,6 +6,7 @@ import type { Database } from 'bun:sqlite' import type { Repo } from '../../../shared/src/types' import type { GitAuthService } from '../../src/services/git-auth' import type { ScheduleService } from '../../src/services/schedules' +import type { TerminalService } from '../../src/services/terminal' import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' vi.mock('bun:sqlite', () => ({ @@ -60,7 +61,7 @@ describe('Git Routes', () => { mockGitAuthService = { getGitEnvironment: vi.fn().mockReturnValue({}), } as unknown as GitAuthService - app = createRepoRoutes(mockDatabase, mockGitAuthService, {} as unknown as ScheduleService, createStubOpenCodeClient()) + app = createRepoRoutes(mockDatabase, mockGitAuthService, {} as unknown as ScheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService) }) describe('GET /:id/git/status', () => { diff --git a/backend/test/routes/repo-terminals.test.ts b/backend/test/routes/repo-terminals.test.ts new file mode 100644 index 00000000..12539ce1 --- /dev/null +++ b/backend/test/routes/repo-terminals.test.ts @@ -0,0 +1,233 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { Hono } from 'hono' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { createRepoTerminalRoutes } from '../../src/routes/repo-terminals' +import { TerminalNotFoundError } from '../../src/services/terminal' +import type { TerminalService } from '../../src/services/terminal' +import type { GitAuthService } from '../../src/services/git-auth' +import type { OpenCodeClient } from '../../src/services/opencode/client' +import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' + +vi.mock('../../src/services/repo', () => ({ + resolveRepoOrAssistant: vi.fn(), + resolveRepoWorkingDirectory: vi.fn(), + getSiblingRepos: vi.fn(), +})) + +import { resolveRepoOrAssistant, resolveRepoWorkingDirectory, getSiblingRepos } from '../../src/services/repo' + +const database = {} as Database +const gitAuthService = { getGitEnvironment: vi.fn(() => ({})) } as unknown as GitAuthService +const openCodeClient: OpenCodeClient = createStubOpenCodeClient() + +const readyRepo = { id: 1, fullPath: '/tmp/repo', cloneStatus: 'ready' } as Repo + +const shellTerminal = { + id: 'pty-1', + title: 'Terminal', + kind: 'shell', + cwd: '/tmp/repo', + status: 'running', +} as const + +function createService(overrides: Partial = {}): TerminalService { + return { + list: vi.fn(async () => []), + create: vi.fn(async () => shellTerminal), + requireTerminal: vi.fn(async () => shellTerminal), + resize: vi.fn(async () => undefined), + remove: vi.fn(async () => undefined), + removeAll: vi.fn(async () => undefined), + ...overrides, + } as unknown as TerminalService +} + +function createApp(service: TerminalService): Hono { + const app = new Hono() + app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, service)) + return app +} + +const jsonHeaders = { 'Content-Type': 'application/json' } + +describe('Repo Terminal Routes', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(resolveRepoOrAssistant).mockImplementation((_db, id) => (id === 1 ? readyRepo : null)) + vi.mocked(resolveRepoWorkingDirectory).mockImplementation(async (_repo, directory) => { + if (directory === undefined || directory === '/tmp/repo') return '/tmp/repo' + return null + }) + vi.mocked(getSiblingRepos).mockResolvedValue([]) + }) + + describe('GET /:id/terminals', () => { + it('returns the terminals for the resolved directory', async () => { + const terminals = [{ ...shellTerminal }] + const list = vi.fn(async () => terminals) + const res = await createApp(createService({ list })).request('/1/terminals') + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ terminals }) + expect(list).toHaveBeenCalledWith('/tmp/repo') + }) + + it('returns 400 for a non-numeric repo id', async () => { + const res = await createApp(createService()).request('/abc/terminals') + expect(res.status).toBe(400) + }) + + it('returns 404 for an unknown repo', async () => { + vi.mocked(resolveRepoOrAssistant).mockReturnValue(null) + const res = await createApp(createService()).request('/2/terminals') + + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Repo not found' }) + }) + + it('returns 400 for a foreign directory', async () => { + const res = await createApp(createService()).request('/1/terminals?directory=/tmp/other') + + expect(res.status).toBe(400) + expect(await res.json()).toEqual({ error: 'Directory is not part of this repository' }) + }) + + it('returns 502 when the terminal service fails', async () => { + const list = vi.fn(async () => { + throw Object.assign(new Error('upstream failed'), { _tag: 'UnknownError' }) + }) + const res = await createApp(createService({ list })).request('/1/terminals') + + expect(res.status).toBe(502) + }) + }) + + describe('POST /:id/terminals', () => { + it('creates a shell with the default name', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createService({ create })).request('/1/terminals', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({}), + }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual(shellTerminal) + expect(create).toHaveBeenCalledWith('/tmp/repo', { kind: 'shell', name: 'Terminal' }) + }) + + it('creates a shell with the requested title and directory', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createService({ create })).request('/1/terminals', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ directory: '/tmp/repo', title: 'My shell' }), + }) + + expect(res.status).toBe(200) + expect(create).toHaveBeenCalledWith('/tmp/repo', { kind: 'shell', name: 'My shell' }) + }) + + it('returns 400 for an invalid body', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createService({ create })).request('/1/terminals', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ title: 'a'.repeat(81) }), + }) + + expect(res.status).toBe(400) + expect(create).not.toHaveBeenCalled() + }) + + it('returns 404 for an unknown repo', async () => { + vi.mocked(resolveRepoOrAssistant).mockReturnValue(null) + const res = await createApp(createService()).request('/2/terminals', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({}), + }) + + expect(res.status).toBe(404) + }) + }) + + describe('PATCH /:id/terminals/:ptyID', () => { + it('resizes a known terminal', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const resize = vi.fn(async () => undefined) + const res = await createApp(createService({ requireTerminal, resize })).request('/1/terminals/pty-1', { + method: 'PATCH', + headers: jsonHeaders, + body: JSON.stringify({ directory: '/tmp/repo', cols: 80, rows: 24 }), + }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ success: true }) + expect(requireTerminal).toHaveBeenCalledWith('/tmp/repo', 'pty-1') + expect(resize).toHaveBeenCalledWith('/tmp/repo', 'pty-1', { cols: 80, rows: 24 }) + }) + + it('returns 400 for invalid resize bounds', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const app = createApp(createService({ requireTerminal })) + + for (const body of ['{"cols":0,"rows":24}', '{"cols":80}', '{"cols":80,"rows":501}', '{"cols":1.5,"rows":24}']) { + const res = await app.request('/1/terminals/pty-1', { method: 'PATCH', headers: jsonHeaders, body }) + expect(res.status).toBe(400) + } + + expect(requireTerminal).not.toHaveBeenCalled() + }) + + it('returns 404 for an unknown PTY id', async () => { + const requireTerminal = vi.fn(async () => { + throw new TerminalNotFoundError('missing') + }) + const res = await createApp(createService({ requireTerminal })).request('/1/terminals/missing', { + method: 'PATCH', + headers: jsonHeaders, + body: JSON.stringify({ cols: 80, rows: 24 }), + }) + + expect(res.status).toBe(404) + }) + + it('returns 400 for a foreign directory', async () => { + const res = await createApp(createService()).request('/1/terminals/pty-1', { + method: 'PATCH', + headers: jsonHeaders, + body: JSON.stringify({ directory: '/tmp/other', cols: 80, rows: 24 }), + }) + + expect(res.status).toBe(400) + }) + }) + + describe('DELETE /:id/terminals/:ptyID', () => { + it('removes a known terminal', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const remove = vi.fn(async () => undefined) + const res = await createApp(createService({ requireTerminal, remove })).request('/1/terminals/pty-1?directory=/tmp/repo', { + method: 'DELETE', + }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ success: true }) + expect(requireTerminal).toHaveBeenCalledWith('/tmp/repo', 'pty-1') + expect(remove).toHaveBeenCalledWith('/tmp/repo', 'pty-1') + }) + + it('returns 404 for an unknown PTY id', async () => { + const requireTerminal = vi.fn(async () => { + throw new TerminalNotFoundError('missing') + }) + const res = await createApp(createService({ requireTerminal })).request('/1/terminals/missing', { + method: 'DELETE', + }) + + expect(res.status).toBe(404) + }) + }) +}) diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts index af33e242..3893c1fd 100644 --- a/backend/test/routes/repos.test.ts +++ b/backend/test/routes/repos.test.ts @@ -34,6 +34,7 @@ vi.mock('../../src/services/repo', () => ({ getSiblingRepos: vi.fn(), resolveRepoOrAssistant: vi.fn(), findSiblingByDirectory: vi.fn(), + resolveRepoWorkingDirectory: vi.fn(), })) vi.mock('../../src/services/assistant-mode', () => ({ @@ -77,6 +78,7 @@ import { createRepoRoutes } from '../../src/routes/repos' import { opencodeServerManager } from '../../src/services/opencode-single-server' import type { GitAuthService } from '../../src/services/git-auth' import type { ScheduleService } from '../../src/services/schedules' +import type { TerminalService } from '../../src/services/terminal' import type { AssistantModeStatus, Repo } from '@opencode-manager/shared/types' import type { OpenCodeApi } from '@opencode-manager/shared/opencode' import { ClientError } from '@opencode-manager/shared/opencode' @@ -92,6 +94,14 @@ const mockScheduleService = { prepareRepoDelete: mockPrepareRepoDelete, } as unknown as ScheduleService +const mockTerminalService = { + removeAll: vi.fn().mockResolvedValue(undefined), +} as unknown as TerminalService + +function createTestRoutes(openCodeClient: ReturnType = createStubOpenCodeClient()): ReturnType { + return createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, openCodeClient, mockTerminalService) +} + function createMockRepo(overrides: Partial = {}): Repo { return { id: 1, @@ -130,7 +140,7 @@ describe('Repo Routes', () => { it('should return 404 when repo not found', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/access', { method: 'POST' }) expect(res.status).toBe(404) @@ -153,7 +163,7 @@ describe('Repo Routes', () => { } vi.mocked(db.getRepoById).mockReturnValue(mockRepo) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/access', { method: 'POST' }) expect(res.status).toBe(200) @@ -179,7 +189,7 @@ describe('Repo Routes', () => { throw new Error('Database error') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/access', { method: 'POST' }) expect(res.status).toBe(500) @@ -192,7 +202,7 @@ describe('Repo Routes', () => { it('should return 404 when repo not found', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'GET' }) expect(res.status).toBe(404) @@ -227,7 +237,7 @@ describe('Repo Routes', () => { vi.mocked(getAssistantModeStatus).mockResolvedValue(mockStatus) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'GET' }) expect(res.status).toBe(200) @@ -243,7 +253,7 @@ describe('Repo Routes', () => { it('should return 404 when repo not found', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -282,7 +292,7 @@ describe('Repo Routes', () => { vi.mocked(ensureAssistantMode).mockResolvedValue(mockStatus) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -321,7 +331,7 @@ describe('Repo Routes', () => { vi.mocked(ensureAssistantMode).mockRejectedValue(new Error('Test error')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -336,7 +346,7 @@ describe('Repo Routes', () => { it('should return 404 when repo not found', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/reset-permissions', { method: 'POST' }) expect(res.status).toBe(404) @@ -360,7 +370,7 @@ describe('Repo Routes', () => { directory: '/tmp/test-repo', project: { id: 'project-A', directory: '/tmp/test-repo', canonical: '/tmp/test-repo' }, })) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ + const app = createTestRoutes(createStubOpenCodeClient({ api: { location: { get: locationGet } } as unknown as OpenCodeApi, })) const res = await app.request('/1/reset-permissions', { method: 'POST' }) @@ -382,7 +392,7 @@ describe('Repo Routes', () => { ]) const savedRemove = vi.fn(async () => undefined) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ + const app = createTestRoutes(createStubOpenCodeClient({ api: { location: { get: locationGet }, permission: { saved: { list: savedList, remove: savedRemove } }, @@ -402,7 +412,7 @@ describe('Repo Routes', () => { describe('POST /', () => { it('should return 400 when neither repoUrl nor localPath is provided', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -418,7 +428,7 @@ describe('Repo Routes', () => { const repo = createMockRepo() vi.mocked(repoService.initLocalRepo).mockResolvedValue(repo) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -435,7 +445,7 @@ describe('Repo Routes', () => { const repo = createMockRepo({ repoUrl: 'https://github.com/test/remote' }) vi.mocked(repoService.cloneRepo).mockResolvedValue(repo) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -457,7 +467,7 @@ describe('Repo Routes', () => { it('should return 500 when repo creation throws', async () => { vi.mocked(repoService.initLocalRepo).mockRejectedValue(new Error('init failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -472,7 +482,7 @@ describe('Repo Routes', () => { describe('POST /discover', () => { it('should return 400 for an invalid body', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/discover', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -487,7 +497,7 @@ describe('Repo Routes', () => { const discovery = { repos: [createMockRepo()], discoveredCount: 1, existingCount: 0, errors: [] } vi.mocked(repoService.discoverLocalRepos).mockResolvedValue(discovery) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/discover', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -503,7 +513,7 @@ describe('Repo Routes', () => { it('should return 500 when discovery throws', async () => { vi.mocked(repoService.discoverLocalRepos).mockRejectedValue(new Error('discover failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/discover', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -524,7 +534,7 @@ describe('Repo Routes', () => { vi.mocked(repoService.getCurrentBranch).mockResolvedValue('main') vi.mocked(db.getRepoGitCredentialId).mockReturnValue('cred-1') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'GET' }) expect(res.status).toBe(200) @@ -542,7 +552,7 @@ describe('Repo Routes', () => { throw new Error('list failed') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'GET' }) expect(res.status).toBe(500) @@ -553,7 +563,7 @@ describe('Repo Routes', () => { describe('PUT /order', () => { it('should return 400 when order is not an array of numbers', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/order', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, @@ -565,7 +575,7 @@ describe('Repo Routes', () => { }) it('should update the repo order', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/order', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, @@ -579,7 +589,7 @@ describe('Repo Routes', () => { }) it('should return 500 when the body is not valid JSON', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/order', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, @@ -595,7 +605,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 5 })) vi.mocked(repoService.getCurrentBranch).mockResolvedValue('develop') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/5', { method: 'GET' }) expect(res.status).toBe(200) @@ -607,7 +617,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/5', { method: 'GET' }) expect(res.status).toBe(404) @@ -617,7 +627,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 5 })) vi.mocked(repoService.getCurrentBranch).mockRejectedValue(new Error('branch failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/5', { method: 'GET' }) expect(res.status).toBe(500) @@ -630,7 +640,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -644,7 +654,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) mockGetSettings.mockReturnValue({ preferences: { repoOrder: [], gitCredentials: [] }, updatedAt: Date.now() }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -663,7 +673,7 @@ describe('Repo Routes', () => { }) vi.mocked(db.getRepoGitCredentialId).mockReturnValue('cred-1') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -680,7 +690,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(db.getRepoGitCredentialId).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -696,7 +706,7 @@ describe('Repo Routes', () => { throw new Error('repo failed') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -709,7 +719,7 @@ describe('Repo Routes', () => { describe('DELETE /:id', () => { it('should return 403 for the assistant repo id', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/0', { method: 'DELETE' }) expect(res.status).toBe(403) @@ -718,7 +728,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1', { method: 'DELETE' }) expect(res.status).toBe(404) @@ -728,13 +738,26 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1', { method: 'DELETE' }) expect(res.status).toBe(200) const body = await res.json() as { success: boolean } expect(body.success).toBe(true) expect(mockPrepareRepoDelete).toHaveBeenCalledWith(1) + expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/repos/test-repo') + expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1) + }) + + it('should still delete the repo when terminal cleanup throws', async () => { + vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) + vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined) + vi.mocked(mockTerminalService.removeAll).mockRejectedValueOnce(new Error('pty cleanup failed')) + + const app = createTestRoutes() + const res = await app.request('/1', { method: 'DELETE' }) + + expect(res.status).toBe(200) expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1) }) @@ -742,7 +765,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(repoService.deleteRepoFiles).mockRejectedValue(new Error('delete failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1', { method: 'DELETE' }) expect(res.status).toBe(500) @@ -757,7 +780,7 @@ describe('Repo Routes', () => { vi.mocked(repoService.pullRepo).mockResolvedValue(undefined) vi.mocked(db.getRepoById).mockReturnValue(repo) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/3/pull', { method: 'POST' }) expect(res.status).toBe(200) @@ -769,7 +792,7 @@ describe('Repo Routes', () => { it('should return 500 when pulling throws', async () => { vi.mocked(repoService.pullRepo).mockRejectedValue(new Error('pull failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/3/pull', { method: 'POST' }) expect(res.status).toBe(500) @@ -782,7 +805,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -795,7 +818,7 @@ describe('Repo Routes', () => { it('should return 400 when the branch is missing', async () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -811,7 +834,7 @@ describe('Repo Routes', () => { vi.mocked(repoService.switchBranch).mockResolvedValue(undefined) vi.mocked(repoService.getCurrentBranch).mockResolvedValue('feature') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -828,7 +851,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(repoService.switchBranch).mockRejectedValue(new Error('switch failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -845,7 +868,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -858,7 +881,7 @@ describe('Repo Routes', () => { it('should return 400 when the branch is missing', async () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -874,7 +897,7 @@ describe('Repo Routes', () => { vi.mocked(repoService.createBranch).mockResolvedValue(undefined) vi.mocked(repoService.getCurrentBranch).mockResolvedValue('feature') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -891,7 +914,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(repoService.createBranch).mockRejectedValue(new Error('create failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -908,7 +931,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/download', { method: 'GET' }) expect(res.status).toBe(404) @@ -923,7 +946,7 @@ describe('Repo Routes', () => { ) vi.mocked(archiveService.deleteArchive).mockResolvedValue(undefined) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/download?includeGit=true&includePaths=src,docs', { method: 'GET' }) expect(res.status).toBe(200) @@ -946,7 +969,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(archiveService.createRepoArchive).mockRejectedValue(new Error('archive failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/download', { method: 'GET' }) expect(res.status).toBe(500) @@ -962,7 +985,7 @@ describe('Repo Routes', () => { throw new ClientError('Transport') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ + const app = createTestRoutes(createStubOpenCodeClient({ api: { location: { get: locationGet } } as unknown as OpenCodeApi, })) const res = await app.request('/1/reset-permissions', { method: 'POST' }) @@ -981,7 +1004,7 @@ describe('Repo Routes', () => { throw new Error('list failed') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ + const app = createTestRoutes(createStubOpenCodeClient({ api: { location: { get: locationGet }, permission: { saved: { list: savedList, remove: vi.fn() } }, @@ -1012,7 +1035,7 @@ describe('Repo Routes', () => { } vi.mocked(getAssistantModeStatus).mockResolvedValue(status) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/0/assistant-mode', { method: 'GET' }) expect(res.status).toBe(200) @@ -1035,7 +1058,7 @@ describe('Repo Routes', () => { } vi.mocked(ensureAssistantMode).mockResolvedValue(status) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/0/assistant-mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -1053,7 +1076,7 @@ describe('Repo Routes', () => { vi.mocked(buildAssistantRepo).mockReturnValue(assistantRepo) vi.mocked(getAssistantModeStatus).mockRejectedValue(new Error('assistant failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/0/assistant-mode', { method: 'GET' }) expect(res.status).toBe(500) diff --git a/backend/test/services/terminal.test.ts b/backend/test/services/terminal.test.ts new file mode 100644 index 00000000..d097df48 --- /dev/null +++ b/backend/test/services/terminal.test.ts @@ -0,0 +1,184 @@ +import { describe, it, expect, vi } from 'vitest' +import { TerminalService, TerminalNotFoundError } from '../../src/services/terminal' +import type { OpenCodeClient } from '../../src/services/opencode/client' +import type { CredentialProvider } from '../../src/services/credential-provider' + +interface PtyRecord { + id: string + title: string + command: string + args: string[] + cwd: string + status: 'running' | 'exited' + pid: number + exitCode?: number +} + +function createPty(overrides: Partial = {}): PtyRecord { + return { id: 'pty-1', title: 'Terminal', command: 'sh', args: [], cwd: '/repo', status: 'running', pid: 1, ...overrides } +} + +function createClient(pty: Record): OpenCodeClient { + return { api: { pty } } as unknown as OpenCodeClient +} + +function createCredentialProvider(shellEnv: Record = {}): CredentialProvider { + return { getShellEnv: vi.fn(() => shellEnv) } as unknown as CredentialProvider +} + +describe('TerminalService', () => { + describe('list', () => { + it('passes the location and decodes each terminal title', async () => { + const list = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: [ + createPty({ id: 'a', title: 'Terminal' }), + createPty({ id: 'b', title: 'ocm:setup:Worktree setup' }), + createPty({ id: 'c', title: 'ocm:action:build:Build', status: 'exited', exitCode: 0 }), + ], + })) + const service = new TerminalService(createClient({ list }), createCredentialProvider()) + + const result = await service.list('/repo') + + expect(list).toHaveBeenCalledWith({ location: { directory: '/repo' } }) + expect(result).toEqual([ + { id: 'a', title: 'Terminal', kind: 'shell', cwd: '/repo', status: 'running' }, + { id: 'b', title: 'Worktree setup', kind: 'setup', cwd: '/repo', status: 'running' }, + { id: 'c', title: 'Build', kind: 'action', actionId: 'build', cwd: '/repo', status: 'exited', exitCode: 0 }, + ]) + }) + }) + + describe('create', () => { + it('sends the location, encoded title and merged environment', async () => { + const create = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: createPty({ id: 'pty-new', title: 'ocm:action:dev:Dev server' }), + })) + const credentialProvider = createCredentialProvider({ GH_TOKEN: 'gh' }) + const service = new TerminalService(createClient({ create }), credentialProvider) + + const result = await service.create('/repo', { + kind: 'action', + actionId: 'dev', + name: 'Dev server', + command: '/bin/sh', + args: ['-c', 'npm run dev'], + env: { FOO: 'bar' }, + }) + + expect(credentialProvider.getShellEnv).toHaveBeenCalledWith({ cwd: '/repo' }) + expect(create).toHaveBeenCalledWith({ + location: { directory: '/repo' }, + title: 'ocm:action:dev:Dev server', + command: '/bin/sh', + args: ['-c', 'npm run dev'], + env: { GH_TOKEN: 'gh', FOO: 'bar' }, + }) + expect(result).toEqual({ + id: 'pty-new', + title: 'Dev server', + kind: 'action', + actionId: 'dev', + cwd: '/repo', + status: 'running', + }) + }) + + it('omits command and args for a plain shell', async () => { + let captured: Record | undefined + const create = vi.fn(async (input: Record) => { + captured = input + return { + location: { directory: '/repo' }, + data: createPty({ id: 'pty-1', title: 'Terminal' }), + } + }) + const service = new TerminalService(createClient({ create }), createCredentialProvider()) + + await service.create('/repo', { kind: 'shell', name: 'Terminal' }) + + expect(captured).toMatchObject({ title: 'Terminal' }) + expect(captured).not.toHaveProperty('command') + expect(captured).not.toHaveProperty('args') + expect(captured?.env).toEqual({}) + }) + }) + + describe('requireTerminal', () => { + it('returns the terminal when the id exists in the directory', async () => { + const list = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: [createPty({ id: 'pty-1' })], + })) + const service = new TerminalService(createClient({ list }), createCredentialProvider()) + + await expect(service.requireTerminal('/repo', 'pty-1')).resolves.toMatchObject({ id: 'pty-1' }) + }) + + it('rejects a PTY id from another directory', async () => { + const list = vi.fn(async ({ location }: { location: { directory: string } }) => ({ + location: { directory: location.directory }, + data: location.directory === '/repo' ? [createPty({ id: 'pty-1' })] : [], + })) + const service = new TerminalService(createClient({ list }), createCredentialProvider()) + + await expect(service.requireTerminal('/other', 'pty-1')).rejects.toBeInstanceOf(TerminalNotFoundError) + }) + }) + + describe('resize', () => { + it('updates the terminal size with the location', async () => { + const update = vi.fn(async () => ({ location: { directory: '/repo' }, data: createPty() })) + const service = new TerminalService(createClient({ update }), createCredentialProvider()) + + await service.resize('/repo', 'pty-1', { cols: 120, rows: 40 }) + + expect(update).toHaveBeenCalledWith({ ptyID: 'pty-1', location: { directory: '/repo' }, size: { cols: 120, rows: 40 } }) + }) + }) + + describe('remove', () => { + it('removes the terminal with the location', async () => { + const remove = vi.fn(async () => undefined) + const service = new TerminalService(createClient({ remove }), createCredentialProvider()) + + await service.remove('/repo', 'pty-1') + + expect(remove).toHaveBeenCalledWith({ ptyID: 'pty-1', location: { directory: '/repo' } }) + }) + }) + + describe('removeAll', () => { + it('removes every terminal and tolerates a 404', async () => { + const list = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: [createPty({ id: 'a' }), createPty({ id: 'b' })], + })) + const notFound = Object.assign(new Error('not found'), { _tag: 'PtyNotFoundError' }) + const remove = vi.fn(async ({ ptyID }: { ptyID: string }) => { + if (ptyID === 'a') throw notFound + }) + const service = new TerminalService(createClient({ list, remove }), createCredentialProvider()) + + await expect(service.removeAll('/repo')).resolves.toBeUndefined() + expect(remove).toHaveBeenCalledTimes(2) + expect(remove).toHaveBeenCalledWith({ ptyID: 'a', location: { directory: '/repo' } }) + expect(remove).toHaveBeenCalledWith({ ptyID: 'b', location: { directory: '/repo' } }) + }) + + it('propagates a non-404 removal failure', async () => { + const list = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: [createPty({ id: 'a' })], + })) + const remove = vi.fn(async () => { + throw new Error('boom') + }) + const service = new TerminalService(createClient({ list, remove }), createCredentialProvider()) + + await expect(service.removeAll('/repo')).rejects.toThrow('boom') + }) + }) +}) diff --git a/backend/test/shared/terminal-title.test.ts b/backend/test/shared/terminal-title.test.ts new file mode 100644 index 00000000..f5ab0c3e --- /dev/null +++ b/backend/test/shared/terminal-title.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/shared/utils' + +describe('terminal-title', () => { + describe('formatTerminalTitle', () => { + it('encodes a plain shell title as the name', () => { + expect(formatTerminalTitle({ kind: 'shell', name: 'Terminal' })).toBe('Terminal') + }) + + it('encodes a setup title with the setup prefix', () => { + expect(formatTerminalTitle({ kind: 'setup', name: 'Worktree setup' })).toBe('ocm:setup:Worktree setup') + }) + + it('encodes an action title with the action id', () => { + expect(formatTerminalTitle({ kind: 'action', name: 'Dev server', actionId: 'dev' })).toBe('ocm:action:dev:Dev server') + }) + + it('rejects an action without a valid action id', () => { + expect(() => formatTerminalTitle({ kind: 'action', name: 'Dev server' })).toThrow() + expect(() => formatTerminalTitle({ kind: 'action', name: 'Dev server', actionId: 'bad id' })).toThrow() + }) + }) + + describe('parseTerminalTitle', () => { + it('round-trips a shell title', () => { + expect(parseTerminalTitle(formatTerminalTitle({ kind: 'shell', name: 'My shell' }))).toEqual({ + kind: 'shell', + title: 'My shell', + }) + }) + + it('round-trips a setup title', () => { + expect(parseTerminalTitle(formatTerminalTitle({ kind: 'setup', name: 'Worktree setup' }))).toEqual({ + kind: 'setup', + title: 'Worktree setup', + }) + }) + + it('round-trips an action title including a colon in the name', () => { + expect(parseTerminalTitle(formatTerminalTitle({ kind: 'action', name: 'Dev: server', actionId: 'dev_1' }))).toEqual({ + kind: 'action', + title: 'Dev: server', + actionId: 'dev_1', + }) + }) + + it('treats an untagged title as a shell', () => { + expect(parseTerminalTitle('plain title')).toEqual({ kind: 'shell', title: 'plain title' }) + }) + + it('treats a malformed action id as a shell', () => { + expect(parseTerminalTitle('ocm:action:bad id:Dev server')).toEqual({ + kind: 'shell', + title: 'ocm:action:bad id:Dev server', + }) + }) + + it('treats an action prefix without a name as a shell', () => { + expect(parseTerminalTitle('ocm:action:dev')).toEqual({ kind: 'shell', title: 'ocm:action:dev' }) + }) + }) +}) diff --git a/shared/src/schemas/index.ts b/shared/src/schemas/index.ts index 67c74b35..f3511212 100644 --- a/shared/src/schemas/index.ts +++ b/shared/src/schemas/index.ts @@ -12,3 +12,4 @@ export * from './skills' export * from './internal-assistant' export * from './session-pins' export * from './logs' +export * from './terminal' diff --git a/shared/src/schemas/terminal.ts b/shared/src/schemas/terminal.ts new file mode 100644 index 00000000..b5e41e5b --- /dev/null +++ b/shared/src/schemas/terminal.ts @@ -0,0 +1,29 @@ +import { z } from 'zod' + +export const TerminalKindSchema = z.enum(['shell', 'action', 'setup']) + +export const TerminalInfoSchema = z.object({ + id: z.string(), + title: z.string(), + kind: TerminalKindSchema, + actionId: z.string().optional(), + cwd: z.string(), + status: z.enum(['running', 'exited']), + exitCode: z.number().int().optional(), +}) + +export const CreateTerminalRequestSchema = z.object({ + directory: z.string().trim().min(1).optional(), + title: z.string().trim().min(1).max(80).optional(), +}) + +export const ResizeTerminalRequestSchema = z.object({ + directory: z.string().trim().min(1).optional(), + cols: z.number().int().min(1).max(1000), + rows: z.number().int().min(1).max(500), +}) + +export type TerminalKind = z.infer +export type TerminalInfo = z.infer +export type CreateTerminalRequest = z.infer +export type ResizeTerminalRequest = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index a895fff0..b3a5055a 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -158,3 +158,10 @@ export { InstallSkillUploadRequestSchema, InstallSkillUploadManifestEntrySchema, } from '../schemas/skills' + +export type { + TerminalKind, + TerminalInfo, + CreateTerminalRequest, + ResizeTerminalRequest, +} from '../schemas/terminal' diff --git a/shared/src/utils/index.ts b/shared/src/utils/index.ts index 44daba75..46d714b0 100644 --- a/shared/src/utils/index.ts +++ b/shared/src/utils/index.ts @@ -2,3 +2,4 @@ export * from './jsonc' export * from './repo' export * from './sandbox-command' export * from './semver' +export * from './terminal-title' diff --git a/shared/src/utils/terminal-title.ts b/shared/src/utils/terminal-title.ts new file mode 100644 index 00000000..642bf4a1 --- /dev/null +++ b/shared/src/utils/terminal-title.ts @@ -0,0 +1,53 @@ +import type { TerminalKind } from '../schemas/terminal' + +const ACTION_TITLE_PREFIX = 'ocm:action:' +const SETUP_TITLE_PREFIX = 'ocm:setup:' +const ACTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/ + +export interface FormatTerminalTitleInput { + kind: TerminalKind + name: string + actionId?: string +} + +export interface ParsedTerminalTitle { + kind: TerminalKind + title: string + actionId?: string +} + +export function formatTerminalTitle(input: FormatTerminalTitleInput): string { + if (input.kind === 'action') { + if (!input.actionId || !ACTION_ID_PATTERN.test(input.actionId)) { + throw new Error('Action terminals require a valid action id') + } + return `${ACTION_TITLE_PREFIX}${input.actionId}:${input.name}` + } + + if (input.kind === 'setup') { + return `${SETUP_TITLE_PREFIX}${input.name}` + } + + return input.name +} + +export function parseTerminalTitle(raw: string): ParsedTerminalTitle { + if (raw.startsWith(ACTION_TITLE_PREFIX)) { + const rest = raw.slice(ACTION_TITLE_PREFIX.length) + const separator = rest.indexOf(':') + const actionId = separator === -1 ? rest : rest.slice(0, separator) + const title = separator === -1 ? '' : rest.slice(separator + 1) + + if (ACTION_ID_PATTERN.test(actionId) && title.length > 0) { + return { kind: 'action', title, actionId } + } + + return { kind: 'shell', title: raw } + } + + if (raw.startsWith(SETUP_TITLE_PREFIX)) { + return { kind: 'setup', title: raw.slice(SETUP_TITLE_PREFIX.length) } + } + + return { kind: 'shell', title: raw } +}