mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
section 2: Phase 2: Terminal service, REST routes and cleanup
This commit is contained in:
1 parent
b494ee9f4a
commit
beab2646e7
15 files changed
+907
-57
No files matched your search
@@ -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())
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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<void> {
|
||||
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 })
|
||||
|
||||
@@ -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<ReturnType<OpenCodeClient['api']['pty']['list']>>['data'][number]
|
||||
|
||||
export interface CreateTerminalInput {
|
||||
kind: TerminalKind
|
||||
name: string
|
||||
actionId?: string
|
||||
command?: string
|
||||
args?: string[]
|
||||
env?: Record<string, string>
|
||||
}
|
||||
|
||||
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<TerminalInfo[]> {
|
||||
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<TerminalInfo> {
|
||||
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<TerminalInfo> {
|
||||
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<void> {
|
||||
await this.openCodeClient.api.pty.update({ ptyID, location: { directory }, size })
|
||||
}
|
||||
|
||||
async remove(directory: string, ptyID: string): Promise<void> {
|
||||
await this.openCodeClient.api.pty.remove({ ptyID, location: { directory } })
|
||||
}
|
||||
|
||||
async removeAll(directory: string): Promise<void> {
|
||||
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 } : {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user