diff --git a/Dockerfile b/Dockerfile index 23f1a202..2dad4aa2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -150,7 +150,7 @@ RUN chmod +x /docker-entrypoint.sh RUN mkdir -p /workspace /app/data /home/node/.cache /home/node/.opencode /home/node/.microsandbox && \ chown -R node:node /workspace /app/data /home/node -EXPOSE 5003 5100 5101 5102 5103 +EXPOSE 5003 5004 5100 5101 5102 5103 HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \ CMD curl -f http://localhost:5003/api/health || exit 1 diff --git a/backend/package.json b/backend/package.json index cfa6147a..ce4dcd59 100644 --- a/backend/package.json +++ b/backend/package.json @@ -18,7 +18,8 @@ }, "dependencies": { "@better-auth/passkey": "^1.4.17", - "@hono/node-server": "^1.19.5", + "@hono/node-server": "^1.19.17", + "@hono/node-ws": "^1.3.1", "@opencode-manager/shared": "workspace:*", "archiver": "^7.0.1", "better-auth": "^1.4.17", diff --git a/backend/src/auth/cookies.ts b/backend/src/auth/cookies.ts new file mode 100644 index 00000000..d4e1b400 --- /dev/null +++ b/backend/src/auth/cookies.ts @@ -0,0 +1 @@ +export const AUTH_COOKIE_PREFIX = 'opencode' diff --git a/backend/src/auth/index.ts b/backend/src/auth/index.ts index 3fd64333..956f5128 100644 --- a/backend/src/auth/index.ts +++ b/backend/src/auth/index.ts @@ -2,7 +2,8 @@ import { betterAuth } from 'better-auth' import { APIError } from 'better-auth/api' import { passkey } from '@better-auth/passkey' import { Database } from 'bun:sqlite' -import { ENV } from '@opencode-manager/shared/config/env' +import { ENV, getTrustedOrigins } from '@opencode-manager/shared/config/env' +import { AUTH_COOKIE_PREFIX } from './cookies' export type AuthInstance = ReturnType @@ -34,14 +35,15 @@ export function createAuth(db: Database) { } } - const baseURL = ENV.AUTH.TRUSTED_ORIGINS.split(',')[0]?.trim() || `http://localhost:${ENV.SERVER.PORT}` + const trustedOrigins = getTrustedOrigins() + const baseURL = trustedOrigins[0] || `http://localhost:${ENV.SERVER.PORT}` const auth = betterAuth({ baseURL, basePath: '/api/auth', database: db, secret: ENV.AUTH.SECRET, - trustedOrigins: ENV.AUTH.TRUSTED_ORIGINS.split(',').map((o: string) => o.trim()), + trustedOrigins, emailAndPassword: { enabled: true, minPasswordLength: 8, @@ -90,7 +92,7 @@ export function createAuth(db: Database) { }, }, advanced: { - cookiePrefix: 'opencode', + cookiePrefix: AUTH_COOKIE_PREFIX, useSecureCookies: ENV.AUTH.SECURE_COOKIES, }, }) diff --git a/backend/src/auth/middleware.ts b/backend/src/auth/middleware.ts index 544f8bdd..32cdbedd 100644 --- a/backend/src/auth/middleware.ts +++ b/backend/src/auth/middleware.ts @@ -1,8 +1,15 @@ import { createMiddleware } from 'hono/factory' +import { getTrustedOrigins } from '@opencode-manager/shared/config/env' import type { AuthInstance, Session } from './index' import { logger } from '../utils/logger' -export function createAuthMiddleware(auth: AuthInstance) { +const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']) +const UNTRUSTED_FETCH_SITES = new Set(['same-site', 'cross-site']) + +export function createAuthMiddleware( + auth: AuthInstance, + resolveTrustedOrigins: () => string[] = getTrustedOrigins, +) { return createMiddleware<{ Variables: { session: Session['session'] @@ -11,6 +18,17 @@ export function createAuthMiddleware(auth: AuthInstance) { }>(async (c, next) => { const cookies = c.req.header('cookie') const origin = c.req.header('origin') + + const fetchSite = c.req.header('sec-fetch-site') + if ( + UNSAFE_METHODS.has(c.req.method) && + fetchSite !== undefined && + UNTRUSTED_FETCH_SITES.has(fetchSite) && + (!origin || !resolveTrustedOrigins().includes(origin)) + ) { + logger.warn(`Rejected cross-site request - Path: ${c.req.path}, Method: ${c.req.method}, Origin: ${origin ?? 'none'}`) + return c.json({ error: 'Cross-site request rejected' }, 403) + } logger.debug(`Auth check - Path: ${c.req.path}, Origin: ${origin}, Has cookies: ${!!cookies}`) if (cookies) { diff --git a/backend/src/index.ts b/backend/src/index.ts index e45671e1..428542ea 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -1,10 +1,12 @@ import { serve } from '@hono/node-server' +import { createNodeWebSocket } from '@hono/node-ws' import { Hono } from 'hono' import { cors } from 'hono/cors' import { serveStatic } from '@hono/node-server/serve-static' import { readFile } from 'fs/promises' import { initializeDatabase } from './db/schema' import { createRepoRoutes } from './routes/repos' +import { createRepoTerminalSocketRoutes } from './routes/repo-terminal-socket' import { createIPCServer, type IPCServer } from './ipc/ipcServer' import { GitAuthService } from './services/git-auth' import { createSettingsRoutes } from './routes/settings' @@ -40,6 +42,8 @@ import { createSessionPermissionModeRoutes } from './routes/session-permission-m import { createSessionGoalRoutes } from './routes/session-goals' import { createMultiRunRoutes } from './routes/multi-runs' import { createLogRoutes } from './routes/logs' +import { createPreviewRoutes, createPreviewAvailability } from './routes/preview' +import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway' import { createInternalRoutes } from './routes/internal' import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers' import { createOpenCodeProxyRoutes } from './routes/opencode-proxy' @@ -52,8 +56,14 @@ import { SessionGoalService } from './services/session-goals' import { MultiRunService } from './services/multi-runs' import { opencodeServerManager } from './services/opencode-single-server' import { createOpenCodeClient } from './services/opencode/client' +import { getOpenCodeUpstreamBaseUrl } from './services/opencode/upstream' import { NotificationService } from './services/notification' import { ScheduleRunner, ScheduleService } from './services/schedules' +import { CredentialProvider } from './services/credential-provider' +import { TerminalService } from './services/terminal' +import { ProjectConfigService } from './services/project-config' +import { RepoWorkspaceService } from './services/repo-workspace' +import { createGitService } from './services/git/GitService' import { ScheduleWorktreeManager } from './services/schedule-worktree' import { migrateGlobalSkills } from './services/skills' import { installAssistantWorkspace } from './services/assistant-mode' @@ -70,6 +80,7 @@ import { getConfigPath, getAgentsMdPath, getDatabasePath, + getTrustedOrigins, ENV } from '@opencode-manager/shared/config/env' @@ -78,6 +89,7 @@ const { PORT, HOST } = ENV.SERVER const DB_PATH = getDatabasePath() const app = new Hono() +const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app }) /** * Route prefixes reachable from custom WebViews whose origin is not a @@ -91,7 +103,7 @@ app.use('/*', cors({ if (origin && REFLECT_ANY_ORIGIN_PREFIXES.some(prefix => c.req.path.startsWith(prefix))) { return origin } - const trustedOrigins = ENV.AUTH.TRUSTED_ORIGINS.split(',').map(o => o.trim()) + const trustedOrigins = getTrustedOrigins() if (!origin) return trustedOrigins[0] if (trustedOrigins.includes(origin)) return origin return trustedOrigins[0] @@ -225,6 +237,13 @@ try { logger.error('Failed to initialize workspace:', error) } +const terminalService = new TerminalService( + openCodeClient, + new CredentialProvider(db), + () => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()), +) +const projectConfigService = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService) +const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService) const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db) const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager) const scheduleRunnerInstance = new ScheduleRunner(scheduleService) @@ -243,7 +262,7 @@ const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSet }) sessionGoalService.loadOpenGoals() -const multiRunService = new MultiRunService(db, openCodeClient, gitAuthService) +const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces) sseAggregator.onEvent((directory, event) => { sessionPermissionModeService.handleEvent(directory, event).catch((err) => { @@ -298,19 +317,22 @@ sseAggregator.setScheduledSessionsResolver( void scheduleRunnerInstance.start() const settingsService = new SettingsService(db) +const previewSessionStore = new PreviewSessionStore() +const previewAvailability = createPreviewAvailability(false) app.route('/api/auth', createAuthRoutes(auth)) app.route('/api/auth-info', createAuthInfoRoutes(auth, db)) app.route('/api/health', createHealthRoutes(db, openCodeSupervisor)) app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth)) -app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService)) +app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces)) 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', createRepoTerminalSocketRoutes(db, gitAuthService, openCodeClient, terminalService, upgradeWebSocket)) +protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces)) protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor)) protectedApi.route('/files', createFileRoutes()) protectedApi.route('/filesystem', createFilesystemRoutes()) @@ -328,6 +350,7 @@ protectedApi.route('/session-goals', createSessionGoalRoutes(sessionGoalService) protectedApi.route('/multi-runs', createMultiRunRoutes(multiRunService)) protectedApi.route('/schedules', createScheduleRoutes(scheduleService)) protectedApi.route('/logs', createLogRoutes()) +protectedApi.route('/preview', createPreviewRoutes({ store: previewSessionStore, isEnabled: previewAvailability.isEnabled })) app.route('/api', protectedApi) @@ -439,10 +462,31 @@ const shutdown = async (signal: string) => { process.on('SIGTERM', () => shutdown('SIGTERM')) process.on('SIGINT', () => shutdown('SIGINT')) -serve({ +const server = serve({ fetch: app.fetch, port: PORT, hostname: HOST, }) +injectWebSocket(server) + +if (ENV.PREVIEW.PORT > 0) { + const previewGateway = createPreviewGatewayApp(previewSessionStore) + const previewServer = serve({ + fetch: previewGateway.app.fetch, + port: ENV.PREVIEW.PORT, + hostname: HOST, + }) + previewServer.on('listening', () => { + previewAvailability.markAvailable() + logger.info(`Preview gateway running on http://${HOST}:${ENV.PREVIEW.PORT}`) + }) + previewServer.on('error', (error: Error) => { + previewAvailability.markUnavailable() + const code = (error as NodeJS.ErrnoException).code + logger.warn(`Preview gateway failed to listen on port ${ENV.PREVIEW.PORT}${code ? ` (${code})` : ''}; preview disabled`) + }) + previewGateway.injectWebSocket(previewServer) +} + logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`) diff --git a/backend/src/routes/internal/index.ts b/backend/src/routes/internal/index.ts index 0f12a097..64aa096d 100644 --- a/backend/src/routes/internal/index.ts +++ b/backend/src/routes/internal/index.ts @@ -18,6 +18,7 @@ import { createInternalAssistantRoutes } from './assistant' import { createInternalGitCredentialsRoutes } from './git-credentials' import { createInternalSandboxRoutes } from './sandbox' import type { SessionPermissionModeService } from '../../services/session-permission-modes' +import type { RepoWorkspaceService } from '../../services/repo-workspace' export function createInternalRoutes( db: Database, @@ -26,6 +27,7 @@ export function createInternalRoutes( settingsService: SettingsService, openCodeClient: OpenCodeClient, permissionModes: SessionPermissionModeService, + repoWorkspaces: RepoWorkspaceService, ) { const app = new Hono() app.use('/*', createInternalTokenMiddleware(db)) @@ -40,7 +42,7 @@ export function createInternalRoutes( repos.route('/', mirrorRoutes(db)) app.route('/repos', repos) app.route('/opencode-workspaces', createInternalOpenCodeWorkspacesRoutes(db)) - app.route('/sessions', createInternalSessionRoutes(db, openCodeClient, permissionModes)) + app.route('/sessions', createInternalSessionRoutes(db, openCodeClient, permissionModes, repoWorkspaces)) app.route('/assistant', createInternalAssistantRoutes(openCodeClient)) app.route('/git-credentials', createInternalGitCredentialsRoutes(db)) app.route('/sandbox', createInternalSandboxRoutes(db)) diff --git a/backend/src/routes/internal/sessions.ts b/backend/src/routes/internal/sessions.ts index 877fc86d..fedba716 100644 --- a/backend/src/routes/internal/sessions.ts +++ b/backend/src/routes/internal/sessions.ts @@ -11,6 +11,7 @@ import { getRepoById } from '../../db/queries' import { handleOpenCodeError, parseJsonBody } from '../../utils/route-helpers' import type { OpenCodeClient } from '../../services/opencode/client' import type { SessionPermissionModeService } from '../../services/session-permission-modes' +import type { RepoWorkspaceService } from '../../services/repo-workspace' import { SessionLaunchError, SessionLauncher } from '../../services/session-launcher' import { isSessionBusy, @@ -51,9 +52,10 @@ export function createInternalSessionRoutes( db: Database, openCodeClient: OpenCodeClient, permissionModes: SessionPermissionModeService, + repoWorkspaces: RepoWorkspaceService, ) { const app = new Hono() - const sessionLauncher = new SessionLauncher(db, openCodeClient) + const sessionLauncher = new SessionLauncher(db, openCodeClient, repoWorkspaces) app.get('/', async (c) => { const parsedQuery = ListSessionsQuerySchema.safeParse(c.req.query()) diff --git a/backend/src/routes/opencode-proxy.ts b/backend/src/routes/opencode-proxy.ts index 2df821d6..6b9aa16b 100644 --- a/backend/src/routes/opencode-proxy.ts +++ b/backend/src/routes/opencode-proxy.ts @@ -11,21 +11,7 @@ import { withDefaultOpenCodeDirectory, } from '../services/opencode/upstream' import { getRepoById } from '../db/queries' - -const HOP_BY_HOP_HEADERS = new Set([ - 'connection', - 'keep-alive', - 'proxy-authenticate', - 'proxy-authorization', - 'te', - 'trailers', - 'upgrade', - 'transfer-encoding', - 'content-length', - 'content-encoding', - 'host', - 'authorization', -]) +import { buildProxyResponseHeaders, filterProxyHeaders } from '../utils/proxy-headers' interface ProxyRequestParts { method: string @@ -95,13 +81,7 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting const url = new URL(c.req.url) const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD' - const forwardedHeaders: Record = {} - c.req.raw.headers.forEach((value, key) => { - const lowerKey = key.toLowerCase() - if (!HOP_BY_HOP_HEADERS.has(lowerKey)) { - forwardedHeaders[key] = value - } - }) + const forwardedHeaders = filterProxyHeaders(c.req.raw.headers) const headers = withDefaultOpenCodeDirectory(forwardedHeaders) headers['Authorization'] = buildOpenCodeBasicAuth(settingsService.getOpenCodeServerPassword()) @@ -140,13 +120,7 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting duplex: 'half', }) - const responseHeaders: Record = {} - upstreamResponse.headers.forEach((value, key) => { - const lowerKey = key.toLowerCase() - if (!HOP_BY_HOP_HEADERS.has(lowerKey)) { - responseHeaders[key] = value - } - }) + const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers) return new Response(upstreamResponse.body, { status: upstreamResponse.status, diff --git a/backend/src/routes/preview.ts b/backend/src/routes/preview.ts new file mode 100644 index 00000000..b5dce61d --- /dev/null +++ b/backend/src/routes/preview.ts @@ -0,0 +1,95 @@ +import path from 'node:path' +import { Hono } from 'hono' +import { ENV } from '@opencode-manager/shared/config/env' +import { CreatePreviewSessionRequestSchema } from '@opencode-manager/shared/schemas' +import { canonicalPathSync } from '../utils/fs-safe' +import { listListeningPorts, isReservedPreviewPort, type PreviewPortEntry } from '../services/preview/ports' +import { PreviewSessionStore } from '../services/preview/gateway' + +export interface PreviewAvailability { + isEnabled: () => boolean + markAvailable: () => void + markUnavailable: () => void +} + +/** + * Tracks whether the preview gateway is usable at request time. It starts in + * the given state and is flipped by the server lifecycle: available once the + * port is bound, unavailable after a bind error. + */ +export function createPreviewAvailability(initialEnabled: boolean): PreviewAvailability { + let enabled = initialEnabled + return { + isEnabled: () => enabled, + markAvailable: () => { enabled = true }, + markUnavailable: () => { enabled = false }, + } +} + +export interface PreviewRoutesDeps { + isEnabled: () => boolean + listPorts: () => Promise + store: PreviewSessionStore +} + +function isInsideDirectory(canonicalCwd: string | null, canonicalDirectory: string | null): boolean { + if (!canonicalCwd || !canonicalDirectory) return false + if (canonicalCwd === canonicalDirectory) return true + const prefix = canonicalDirectory.endsWith(path.sep) ? canonicalDirectory : `${canonicalDirectory}${path.sep}` + return canonicalCwd.startsWith(prefix) +} + +export function createPreviewRoutes(deps: Partial = {}) { + const resolvedDeps: PreviewRoutesDeps = { + isEnabled: deps.isEnabled ?? (() => ENV.PREVIEW.PORT > 0), + listPorts: deps.listPorts ?? (() => listListeningPorts()), + store: deps.store ?? new PreviewSessionStore(), + } + const app = new Hono() + + app.get('/ports', async (c) => { + const directory = c.req.query('directory') + const canonicalDirectory = directory ? canonicalPathSync(directory) : null + const ports = await resolvedDeps.listPorts() + const decorated = ports.map((entry) => ({ + ...entry, + inDirectory: isInsideDirectory(entry.cwd ? canonicalPathSync(entry.cwd) : null, canonicalDirectory), + })) + decorated.sort((left, right) => { + if (left.inDirectory !== right.inDirectory) return left.inDirectory ? -1 : 1 + return left.port - right.port + }) + return c.json({ enabled: resolvedDeps.isEnabled(), ports: decorated }) + }) + + app.post('/sessions', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = CreatePreviewSessionRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request' }, 400) + } + + if (!resolvedDeps.isEnabled()) { + return c.json({ error: 'Preview is disabled' }, 503) + } + + if (isReservedPreviewPort(parsed.data.port)) { + return c.json({ error: 'Port is reserved' }, 400) + } + + const ports = await resolvedDeps.listPorts() + const match = ports.find((entry) => entry.port === parsed.data.port) + if (!match) { + return c.json({ error: `Port ${parsed.data.port} is not listening` }, 404) + } + + const token = resolvedDeps.store.issueStartToken({ port: match.port, host: match.host }) + return c.json({ + token, + previewPort: ENV.PREVIEW.PORT, + publicUrl: ENV.PREVIEW.PUBLIC_URL || null, + }) + }) + + return app +} diff --git a/backend/src/routes/repo-directory.ts b/backend/src/routes/repo-directory.ts new file mode 100644 index 00000000..dae4cf28 --- /dev/null +++ b/backend/src/routes/repo-directory.ts @@ -0,0 +1,53 @@ +import type { Context } from 'hono' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { getSiblingRepos, resolveRepoOrAssistant, resolveRepoWorkingDirectory } from '../services/repo' +import { getRepoById } from '../db/queries' +import type { GitAuthService } from '../services/git-auth' +import type { OpenCodeClient } from '../services/opencode/client' + +export interface RepoDirectoryDeps { + database: Database + gitAuthService: GitAuthService + openCodeClient: OpenCodeClient +} + +export interface RepoDirectoryOptions { + allowAssistant: boolean +} + +export async function resolveRepoRequestDirectory( + c: Context, + deps: RepoDirectoryDeps, + repoIdParam: string, + directory: string | undefined, + options: RepoDirectoryOptions, +): 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 = options.allowAssistant + ? resolveRepoOrAssistant(deps.database, id) + : getRepoById(deps.database, id) + if (!repo || repo.cloneStatus !== 'ready') { + return c.json({ error: 'Repo not found' }, 404) + } + + const resolved = await resolveRepoWorkingDirectory(repo, directory, () => + getSiblingRepos( + deps.database, + repo.id, + deps.gitAuthService.getGitEnvironment(), + deps.openCodeClient, + { includeBranch: false }, + ), + ) + + if (!resolved) { + return c.json({ error: 'Directory is not part of this repository' }, 400) + } + + return { repo, directory: resolved } +} diff --git a/backend/src/routes/repo-project-config.ts b/backend/src/routes/repo-project-config.ts new file mode 100644 index 00000000..0029928c --- /dev/null +++ b/backend/src/routes/repo-project-config.ts @@ -0,0 +1,156 @@ +import { Hono } from 'hono' +import type { Database } from 'bun:sqlite' +import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema, TrustRepoConfigRequestSchema, MoveProjectItemRequestSchema, RunProjectActionRequestSchema } from '@opencode-manager/shared/schemas' +import type { GitAuthService } from '../services/git-auth' +import type { OpenCodeClient } from '../services/opencode/client' +import type { TerminalService } from '../services/terminal' +import { ProjectConfigError, type ProjectConfigService } from '../services/project-config' +import { handleServiceError } from '../utils/route-helpers' +import { resolveRepoRequestDirectory } from './repo-directory' + +export interface RepoProjectConfigDeps { + database: Database + gitAuthService: GitAuthService + openCodeClient: OpenCodeClient + projectConfigService: ProjectConfigService + terminalService: TerminalService +} + +export function createRepoProjectConfigRoutes( + database: Database, + gitAuthService: GitAuthService, + openCodeClient: OpenCodeClient, + projectConfigService: ProjectConfigService, + terminalService: TerminalService, +) { + const deps: RepoProjectConfigDeps = { + database, + gitAuthService, + openCodeClient, + projectConfigService, + terminalService, + } + const app = new Hono() + + app.get('/:id/project-config', async (c) => { + const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), { + allowAssistant: false, + }) + if (resolved instanceof Response) return resolved + + try { + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleServiceError(c, error, 'Project config request failed', ProjectConfigError) + } + }) + + app.put('/:id/project-config/actions', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = UpdateProjectActionsRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), { + allowAssistant: false, + }) + if (resolved instanceof Response) return resolved + + try { + const projectRepo = await deps.projectConfigService.resolveProjectRepo(resolved.repo) + deps.projectConfigService.setPersonalActions(projectRepo, parsed.data.actions) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleServiceError(c, error, 'Project config request failed', ProjectConfigError) + } + }) + + app.put('/:id/project-config/worktree-setup', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = UpdateWorktreeSetupRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), { + allowAssistant: false, + }) + if (resolved instanceof Response) return resolved + + try { + const projectRepo = await deps.projectConfigService.resolveProjectRepo(resolved.repo) + deps.projectConfigService.setPersonalSetup(projectRepo, parsed.data.commands) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleServiceError(c, error, 'Project config request failed', ProjectConfigError) + } + }) + + app.post('/:id/project-config/trust', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = TrustRepoConfigRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, { + allowAssistant: false, + }) + if (resolved instanceof Response) return resolved + + try { + await deps.projectConfigService.trustRepoFile(resolved.repo, resolved.directory, parsed.data.hash) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleServiceError(c, error, 'Project config request failed', ProjectConfigError) + } + }) + + app.post('/:id/project-config/move', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = MoveProjectItemRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, { + allowAssistant: false, + }) + if (resolved instanceof Response) return resolved + + try { + await deps.projectConfigService.moveItem(resolved.repo, resolved.directory, parsed.data) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleServiceError(c, error, 'Project config request failed', ProjectConfigError) + } + }) + + 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 resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, { + allowAssistant: false, + }) + 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 handleServiceError(c, error, 'Project config request failed', ProjectConfigError) + } + }) + + return app +} diff --git a/backend/src/routes/repo-terminal-socket.ts b/backend/src/routes/repo-terminal-socket.ts new file mode 100644 index 00000000..c2ec1234 --- /dev/null +++ b/backend/src/routes/repo-terminal-socket.ts @@ -0,0 +1,120 @@ +import { Hono } from 'hono' +import type { MiddlewareHandler } from 'hono' +import type { Database } from 'bun:sqlite' +import type { UpgradeWebSocket } from 'hono/ws' +import { getTrustedOrigins } from '@opencode-manager/shared/config/env' +import type { GitAuthService } from '../services/git-auth' +import type { OpenCodeClient } from '../services/opencode/client' +import type { TerminalService } from '../services/terminal' +import { forwardPeerMessage, peerBufferedAmount, type WebSocketBridge } from '../utils/websocket-bridge' +import { getErrorMessage } from '../utils/error-utils' +import { resolveRepoRequestDirectory } from './repo-directory' + +interface RepoTerminalSocketVariables { + terminalDirectory: string + terminalCursor: number | undefined +} + +const MAX_CLOSE_REASON_BYTES = 120 + +function isAllowedUpgradeOrigin( + origin: string | undefined, + trustedOrigins: readonly string[], +): boolean { + if (origin === undefined) return true + if (origin === 'null') return false + return trustedOrigins.includes(origin) +} + +function parseCursor(raw: string | undefined): number | undefined | null { + if (raw === undefined) return undefined + if (!/^-?\d+$/.test(raw)) return null + const parsed = Number(raw) + if (!Number.isSafeInteger(parsed) || parsed < -1) return null + return parsed +} + +function truncateCloseReason(message: string): string { + const bytes = Buffer.from(message, 'utf8') + if (bytes.length <= MAX_CLOSE_REASON_BYTES) return message + return bytes.subarray(0, MAX_CLOSE_REASON_BYTES).toString('utf8') +} + +export function createRepoTerminalSocketRoutes( + database: Database, + gitAuthService: GitAuthService, + openCodeClient: OpenCodeClient, + terminalService: TerminalService, + upgradeWebSocket: UpgradeWebSocket, + trustedOrigins: readonly string[] = getTrustedOrigins(), +) { + const app = new Hono<{ Variables: RepoTerminalSocketVariables }>() + const deps = { database, gitAuthService, openCodeClient } + + const validate: MiddlewareHandler<{ Variables: RepoTerminalSocketVariables }> = async (c, next) => { + if (!isAllowedUpgradeOrigin(c.req.header('origin'), trustedOrigins)) { + return c.json({ error: 'Origin not allowed' }, 403) + } + + const cursor = parseCursor(c.req.query('cursor')) + if (cursor === null) { + return c.json({ error: 'Invalid cursor' }, 400) + } + + const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id') ?? '', c.req.query('directory'), { + allowAssistant: true, + }) + if (resolved instanceof Response) return resolved + + c.set('terminalDirectory', resolved.directory) + c.set('terminalCursor', cursor) + await next() + } + + app.get( + '/:id/terminals/:ptyID/connect', + validate, + upgradeWebSocket((c) => { + const directory = c.get('terminalDirectory') + const cursor = c.get('terminalCursor') + const ptyID = c.req.param('ptyID') + + let bridge: WebSocketBridge | undefined + let closed = false + let connectPromise: Promise = Promise.resolve() + + return { + onOpen(_event, ws) { + connectPromise = terminalService + .connect(directory, ptyID, cursor, { + send: (data) => ws.send(data), + close: (code, reason) => ws.close(code, reason), + bufferedAmount: () => peerBufferedAmount(ws), + }) + .then((connected) => { + if (closed) { + connected.close() + return + } + bridge = connected + }) + .catch((error: unknown) => { + if (closed) return + ws.close(1011, truncateCloseReason(getErrorMessage(error))) + }) + }, + async onMessage(event) { + await connectPromise + if (!bridge) return + await forwardPeerMessage(bridge, event.data) + }, + onClose() { + closed = true + bridge?.close() + }, + } + }), + ) + + return app +} diff --git a/backend/src/routes/repo-terminals.ts b/backend/src/routes/repo-terminals.ts new file mode 100644 index 00000000..246d47d7 --- /dev/null +++ b/backend/src/routes/repo-terminals.ts @@ -0,0 +1,107 @@ +import { Hono } from 'hono' +import type { Database } from 'bun:sqlite' +import { CreateTerminalRequestSchema, ResizeTerminalRequestSchema } from '@opencode-manager/shared/schemas' +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' +import { resolveRepoRequestDirectory, type RepoDirectoryDeps } from './repo-directory' + +export interface TerminalRoutesDeps extends RepoDirectoryDeps { + terminalService: TerminalService +} + +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 resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), { + allowAssistant: true, + }) + 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 resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, { + allowAssistant: true, + }) + 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 resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, { + allowAssistant: true, + }) + 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 resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), { + allowAssistant: true, + }) + 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 4f87a31e..9da42bac 100644 --- a/backend/src/routes/repos.test.ts +++ b/backend/src/routes/repos.test.ts @@ -4,9 +4,13 @@ import { Database } from 'bun:sqlite' import { migrate } from '../db/migration-runner' import { allMigrations } from '../db/migrations' import { createRepoRoutes } from './repos' -import { createRepo, getRepoById } from '../db/queries' +import { createRepo, getRepoById, setRepoSetting } from '../db/queries' import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client' +import { createGitService } from '../services/git/GitService' +import { ProjectConfigService } from '../services/project-config' +import { RepoWorkspaceService } from '../services/repo-workspace' 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' @@ -30,7 +34,15 @@ const stubGitAuthService = { getGitCredentials: async () => [], } as unknown as GitAuthService -function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStubOpenCodeClient()): Hono { +const stubTerminalService = { + removeAll: mock(async () => undefined), +} as unknown as TerminalService + +function createTestApp( + db: Database, + openCodeClient: OpenCodeClient = createStubOpenCodeClient(), + terminalService: TerminalService = stubTerminalService, +): Hono { const app = new Hono() const scheduleService = { createSchedule: () => {}, @@ -40,7 +52,9 @@ function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStub deleteSchedule: () => {}, prepareRepoDelete: () => {}, } as any - app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient)) + const projectConfigService = new ProjectConfigService(db, createGitService(stubGitAuthService), stubGitAuthService) + const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, stubGitAuthService, projectConfigService, terminalService) + app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces)) return app } @@ -437,10 +451,32 @@ describe('POST /api/repos/:id/workspaces', () => { const res = await app.request('/repos/1/workspaces', { method: 'POST' }) expect(res.status).toBe(200) - expect(await res.json()).toEqual({ directory: '/tmp/wrk-test' }) + expect(await res.json()).toEqual({ directory: '/tmp/wrk-test', worktreeSetup: { status: 'none' } }) expect(create).toHaveBeenCalledWith({ projectID: 'commit-A' }) }) + it('still returns 200 with a failed worktree setup when the setup terminal cannot start', async () => { + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + setRepoSetting(db, 1, 'worktreeSetupCommands', JSON.stringify(['pnpm install'])) + const client = createStubOpenCodeClient() + client.api.worktree.create = mock(async () => ({ directory: '/tmp/wrk-test' })) as any + const failingTerminalService = { + removeAll: mock(async () => undefined), + create: mock(async () => { + throw new Error('spawn failed') + }), + } as unknown as TerminalService + const app = createTestApp(db, client, failingTerminalService) + + const res = await app.request('/repos/1/workspaces', { method: 'POST' }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ + directory: '/tmp/wrk-test', + worktreeSetup: { status: 'failed', error: 'spawn failed' }, + }) + }) + it('returns 400 for a non-numeric repo id', async () => { const app = createTestApp(db) const res = await app.request('/repos/abc/workspaces', { method: 'POST' }) diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 790eaba2..a421a2f6 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -16,17 +16,18 @@ import { handleOpenCodeError } from '../utils/route-helpers' import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' import { isWorktreeError, openCodeLocation } from '@opencode-manager/shared/opencode' import { createRepoGitRoutes } from './repo-git' -import { createGitService } from '../services/git/GitService' +import { createRepoTerminalRoutes } from './repo-terminals' +import { createRepoProjectConfigRoutes } from './repo-project-config' import { createScheduleRoutes } from './schedules' import type { GitAuthService } from '../services/git-auth' +import type { TerminalService } from '../services/terminal' +import type { ProjectConfigService } from '../services/project-config' +import type { RepoWorkspaceService } from '../services/repo-workspace' +import { createGitService } from '../services/git/GitService' import { ScheduleService } from '../services/schedules' -import { ensureAssistantMode, getAssistantModeStatus, buildAssistantRepo } from '../services/assistant-mode' +import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode' import path from 'path' -function resolveRepo(database: Database, id: number): Repo | null { - return getRepoById(database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null) -} - const DeleteWorkspaceRequestSchema = z.object({ directory: z.string().trim().min(1), }) @@ -43,11 +44,16 @@ export function createRepoRoutes( gitAuthService: GitAuthService, scheduleService: ScheduleService, openCodeClient: OpenCodeClient, + terminalService: TerminalService, + projectConfigService: ProjectConfigService, + repoWorkspaces: RepoWorkspaceService, ) { const app = new Hono() const git = createGitService(gitAuthService) app.route('/', createRepoGitRoutes(database, git, openCodeClient)) + app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, terminalService)) + app.route('/', createRepoProjectConfigRoutes(database, gitAuthService, openCodeClient, projectConfigService, terminalService)) app.route('/:id/schedules', createScheduleRoutes(scheduleService)) app.post('/', async (c) => { @@ -77,7 +83,14 @@ export function createRepoRoutes( { branch, directoryName, useWorktree, skipSSHVerification, baseBranch } ) } - + + if (repo.isWorktree) { + return c.json({ + ...repo, + worktreeSetup: await projectConfigService.runWorktreeSetupForRepo(repo, repo.fullPath, terminalService), + }) + } + return c.json(repo) } catch (error: unknown) { logger.error('Failed to create repo:', error) @@ -152,7 +165,7 @@ app.get('/', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo: Repo | null = resolveRepo(database, id) + const repo: Repo | null = repoService.resolveRepoOrAssistant(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -319,7 +332,7 @@ app.get('/', async (c) => { if (!parsed.success) return c.json({ error: 'directory is required' }, 400) try { - await repoService.removeRepoWorkspace(database, openCodeClient, gitAuthService.getGitEnvironment(), repo, parsed.data.directory) + await repoWorkspaces.remove(repo, parsed.data.directory) } catch (error: unknown) { if (error instanceof repoService.RepoWorkspaceError) { return c.json({ error: error.message }, error.status) @@ -346,8 +359,7 @@ app.get('/', async (c) => { if (!repo || repo.cloneStatus !== 'ready') return c.json({ error: 'Repo not found' }, 404) try { - const worktree = await repoService.createRepoWorkspace(openCodeClient, repo) - return c.json(worktree) + return c.json(await repoWorkspaces.create(repo)) } catch (error: unknown) { if (isWorktreeError(error)) { return c.json({ error: error.data.message }, 409) @@ -388,6 +400,7 @@ app.get('/', async (c) => { const removeWorktree = async () => { scheduleService.prepareRepoDelete(id) + await repoWorkspaces.removeRepoTerminals(repo) await repoService.deleteRepoFiles(database, id) } @@ -563,7 +576,7 @@ app.get('/', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo: Repo | null = resolveRepo(database, id) + const repo: Repo | null = repoService.resolveRepoOrAssistant(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) @@ -581,7 +594,7 @@ app.get('/', async (c) => { try { const id = parseInt(c.req.param('id')) - const repo: Repo | null = resolveRepo(database, id) + const repo: Repo | null = repoService.resolveRepoOrAssistant(database, id) if (!repo) { return c.json({ error: 'Repo not found' }, 404) diff --git a/backend/src/services/multi-runs.ts b/backend/src/services/multi-runs.ts index 5e0369e2..9df882a8 100644 --- a/backend/src/services/multi-runs.ts +++ b/backend/src/services/multi-runs.ts @@ -13,9 +13,9 @@ import { import { getRepoById } from '../db/queries' import type { Repo } from '../types/repo' import { getErrorMessage } from '../utils/error-utils' -import type { GitAuthService } from './git-auth' import type { OpenCodeClient } from './opencode/client' -import { removeRepoWorkspace, RepoWorkspaceError } from './repo' +import { RepoWorkspaceError } from './repo' +import type { RepoWorkspaceService } from './repo-workspace' import { requireReadyRepo, SessionLauncher, SessionLaunchError, type LaunchedSession } from './session-launcher' const MULTI_RUN_LIST_LIMIT = 20 @@ -59,10 +59,10 @@ export class MultiRunService { constructor( private readonly db: Database, - private readonly openCodeClient: OpenCodeClient, - private readonly gitAuthService: GitAuthService, + openCodeClient: OpenCodeClient, + private readonly repoWorkspaces: RepoWorkspaceService, ) { - this.sessionLauncher = new SessionLauncher(db, openCodeClient) + this.sessionLauncher = new SessionLauncher(db, openCodeClient, repoWorkspaces) } async launch(request: LaunchMultiRunRequest): Promise { @@ -172,13 +172,7 @@ export class MultiRunService { } try { - await removeRepoWorkspace( - this.db, - this.openCodeClient, - this.gitAuthService.getGitEnvironment(), - repo, - entry.directory, - ) + await this.repoWorkspaces.remove(repo, entry.directory) } catch (error) { const status = error instanceof RepoWorkspaceError ? error.status : 502 throw new MultiRunError(getErrorMessage(error) || 'Failed to remove workspace', status) diff --git a/backend/src/services/opencode/client.ts b/backend/src/services/opencode/client.ts index 35c2c2b3..98777a4a 100644 --- a/backend/src/services/opencode/client.ts +++ b/backend/src/services/opencode/client.ts @@ -1,6 +1,7 @@ import { logger } from '../../utils/logger' import { ENV } from '@opencode-manager/shared/config/env' import { createOpenCodeApi, type OpenCodeApi } from '@opencode-manager/shared/opencode' +import { filterProxyHeaders } from '../../utils/proxy-headers' import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth' import { getOpenCodeUpstreamBaseUrl, withDefaultOpenCodeDirectory } from './upstream' @@ -73,13 +74,7 @@ export class FetchOpenCodeClient implements OpenCodeClient { body: req.body, }) - const filteredHeaders: Record = {} - const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length']) - response.headers.forEach((value, key) => { - if (!skipHeaders.has(key.toLowerCase())) { - filteredHeaders[key] = value - } - }) + const filteredHeaders = filterProxyHeaders(response.headers) const noBodyStatuses = new Set([101, 204, 205, 304]) if (noBodyStatuses.has(response.status)) { diff --git a/backend/src/services/preview/gateway.ts b/backend/src/services/preview/gateway.ts new file mode 100644 index 00000000..20387bc7 --- /dev/null +++ b/backend/src/services/preview/gateway.ts @@ -0,0 +1,325 @@ +import { randomBytes } from 'node:crypto' +import { Hono } from 'hono' +import type { Context, MiddlewareHandler } from 'hono' +import { createNodeWebSocket, type NodeWebSocket } from '@hono/node-ws' +import type { PreviewPort } from '@opencode-manager/shared/schemas' +import { AUTH_COOKIE_PREFIX } from '../../auth/cookies' +import { buildProxyResponseHeaders, filterProxyHeaders } from '../../utils/proxy-headers' +import { + bridgeWebSocket, + forwardPeerMessage, + peerBufferedAmount, + type WebSocketBridge, +} from '../../utils/websocket-bridge' + +export const PREVIEW_COOKIE = 'ocm_preview' + +const START_TOKEN_TTL_MS = 60_000 +const SESSION_TTL_MS = 12 * 60 * 60 * 1000 + +const MANAGER_COOKIE_PREFIXES = [ + `${AUTH_COOKIE_PREFIX}.`, + `__Secure-${AUTH_COOKIE_PREFIX}.`, + `__Host-${AUTH_COOKIE_PREFIX}.`, +] + +export type PreviewHost = PreviewPort['host'] + +export interface PreviewSession { + id: string + port: number + host: PreviewHost + expiresAt: number +} + +interface StartToken { + port: number + host: PreviewHost + expiresAt: number +} + +export interface PreviewSessionStoreOptions { + now?: () => number + randomToken?: () => string +} + +export class PreviewSessionStore { + private readonly startTokens = new Map() + private readonly sessions = new Map() + private readonly now: () => number + private readonly randomToken: () => string + + constructor(options: PreviewSessionStoreOptions = {}) { + this.now = options.now ?? Date.now + this.randomToken = options.randomToken ?? (() => randomBytes(32).toString('base64url')) + } + + issueStartToken(target: { port: number; host: PreviewHost }): string { + this.prune() + const token = this.randomToken() + this.startTokens.set(token, { port: target.port, host: target.host, expiresAt: this.now() + START_TOKEN_TTL_MS }) + return token + } + + consumeStartToken(token: string): string | null { + this.prune() + const entry = this.startTokens.get(token) + if (!entry) return null + this.startTokens.delete(token) + const id = this.randomToken() + this.sessions.set(id, { id, port: entry.port, host: entry.host, expiresAt: this.now() + SESSION_TTL_MS }) + return id + } + + getSession(id: string): PreviewSession | undefined { + this.prune() + return this.sessions.get(id) + } + + private prune(): void { + const now = this.now() + for (const [token, entry] of this.startTokens) { + if (entry.expiresAt <= now) this.startTokens.delete(token) + } + for (const [id, session] of this.sessions) { + if (session.expiresAt <= now) this.sessions.delete(id) + } + } +} + +function readCookieName(cookie: string): string { + const separator = cookie.indexOf('=') + return (separator === -1 ? cookie : cookie.slice(0, separator)).trim() +} + +function isManagerCookieName(name: string): boolean { + return name === PREVIEW_COOKIE || MANAGER_COOKIE_PREFIXES.some((prefix) => name.startsWith(prefix)) +} + +function stripManagerCookies(cookieHeader: string | undefined): string | undefined { + if (!cookieHeader) return undefined + const kept = cookieHeader + .split(';') + .map((part) => part.trim()) + .filter((part) => part.length > 0 && !isManagerCookieName(readCookieName(part))) + return kept.length > 0 ? kept.join('; ') : undefined +} + +function stripPreviewSetCookies(headers: Headers): void { + const kept = headers.getSetCookie().filter((cookie) => !isManagerCookieName(readCookieName(cookie))) + headers.delete('set-cookie') + for (const cookie of kept) { + headers.append('set-cookie', cookie) + } +} + +function readPreviewCookie(cookieHeader: string | undefined): string | null { + if (!cookieHeader) return null + for (const part of cookieHeader.split(';')) { + const trimmed = part.trim() + const separator = trimmed.indexOf('=') + if (separator === -1) continue + if (trimmed.slice(0, separator) === PREVIEW_COOKIE) { + return trimmed.slice(separator + 1) + } + } + return null +} + +function htmlResponse(status: number, message: string): Response { + return new Response(`

${message}

`, { + status, + headers: { 'content-type': 'text/html; charset=utf-8' }, + }) +} + +function rewriteLocalLocation(location: string, port: number): string | null { + let parsed: URL + try { + parsed = new URL(location) + } catch { + return null + } + const isLocalHost = + parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '[::1]' || parsed.hostname === '::1' + if (!isLocalHost) return null + const locationPort = parsed.port + ? Number.parseInt(parsed.port, 10) + : parsed.protocol === 'https:' + ? 443 + : 80 + if (locationPort !== port) return null + return `${parsed.pathname}${parsed.search}` +} + +export interface PreviewGateway { + app: Hono + injectWebSocket: NodeWebSocket['injectWebSocket'] +} + +function isWebSocketUpgrade(c: Context): boolean { + return c.req.header('upgrade')?.toLowerCase() === 'websocket' +} + +function upstreamWebSocketUrl(session: PreviewSession, requestUrl: URL): string { + return `${previewUpstreamOrigin(session, 'ws')}${requestUrl.pathname}${requestUrl.search}` +} + +function previewUpstreamOrigin(session: PreviewSession, protocol: 'http' | 'ws'): string { + const targetHost = session.host === '::1' ? '[::1]' : 'localhost' + return `${protocol}://${targetHost}:${session.port}` +} + +function resolveRedirectPath(requestUrl: URL, requestedPath: string): string { + if (!requestedPath) return '/' + let resolved: URL + try { + resolved = new URL(requestedPath, requestUrl) + } catch { + return '/' + } + if (resolved.origin !== requestUrl.origin) return '/' + return `${resolved.pathname}${resolved.search}${resolved.hash}` +} + +function parseProtocols(header: string | undefined): string[] { + if (!header) return [] + return header + .split(',') + .map((protocol) => protocol.trim()) + .filter((protocol) => protocol.length > 0) +} + +export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typeof fetch = fetch): PreviewGateway { + const app = new Hono() + const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app }) + + app.get('/__ocm_preview/start', (c) => { + const sessionId = store.consumeStartToken(c.req.query('token') ?? '') + if (!sessionId) { + return htmlResponse(401, 'Preview session is invalid or expired.') + } + + const requestedPath = c.req.query('path') ?? '' + const requestUrl = new URL(c.req.url) + const location = resolveRedirectPath(requestUrl, requestedPath) + + const forwardedProto = c.req.header('x-forwarded-proto')?.toLowerCase() + const isSecure = forwardedProto === 'https' || requestUrl.protocol === 'https:' + const cookie = `${PREVIEW_COOKIE}=${sessionId}; HttpOnly; SameSite=Lax; Path=/${isSecure ? '; Secure' : ''}` + + return new Response(null, { status: 302, headers: { location, 'set-cookie': cookie } }) + }) + + const sessionGuard: MiddlewareHandler = async (c, next) => { + if (!isWebSocketUpgrade(c)) { + await next() + return + } + const sessionId = readPreviewCookie(c.req.header('cookie')) + if (!sessionId || !store.getSession(sessionId)) { + return htmlResponse(401, 'Preview session expired. Reopen it from OpenCode Manager.') + } + await next() + } + + app.get( + '/*', + sessionGuard, + upgradeWebSocket((c) => { + const requestUrl = new URL(c.req.url) + const protocols = parseProtocols(c.req.header('sec-websocket-protocol')) + let bridge: WebSocketBridge | undefined + + return { + onOpen(_event, ws) { + const sessionId = readPreviewCookie(c.req.header('cookie')) + const session = sessionId ? store.getSession(sessionId) : undefined + if (!session) { + ws.close(1011) + return + } + + let upstream: WebSocket + try { + upstream = new WebSocket(upstreamWebSocketUrl(session, requestUrl), protocols.length > 0 ? protocols : undefined) + } catch { + ws.close(1011) + return + } + + bridge = bridgeWebSocket(upstream, { + send: (data) => ws.send(data), + close: (code, reason) => ws.close(code, reason), + bufferedAmount: () => peerBufferedAmount(ws), + }) + }, + async onMessage(event) { + if (!bridge) return + await forwardPeerMessage(bridge, event.data) + }, + onClose() { + bridge?.close() + }, + } + }), + ) + + app.all('/*', async (c) => { + const cookieHeader = c.req.header('cookie') + const sessionId = readPreviewCookie(cookieHeader) + const session = sessionId ? store.getSession(sessionId) : undefined + if (!session) { + return htmlResponse(401, 'Preview session expired. Reopen it from OpenCode Manager.') + } + + const url = new URL(c.req.url) + const target = `${previewUpstreamOrigin(session, 'http')}${url.pathname}${url.search}` + + const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD' + + const headers = filterProxyHeaders(c.req.raw.headers) + const contentEncoding = hasBody ? c.req.header('content-encoding') : undefined + if (contentEncoding) { + headers['content-encoding'] = contentEncoding + } + headers['host'] = `localhost:${session.port}` + headers['accept-encoding'] = 'identity' + const strippedCookies = stripManagerCookies(cookieHeader) + if (strippedCookies) { + headers['cookie'] = strippedCookies + } else { + delete headers['cookie'] + } + headers['x-forwarded-host'] = c.req.header('host') ?? '' + headers['x-forwarded-proto'] = c.req.header('x-forwarded-proto') ?? url.protocol.replace(':', '') + + try { + const upstreamResponse = await fetchFn(target, { + method: c.req.method, + headers, + body: hasBody ? c.req.raw.body : undefined, + redirect: 'manual', + duplex: 'half', + }) + + const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers) + stripPreviewSetCookies(responseHeaders) + const location = responseHeaders.get('location') + if (location) { + const rewritten = rewriteLocalLocation(location, session.port) + if (rewritten) responseHeaders.set('location', rewritten) + } + + return new Response(upstreamResponse.body, { + status: upstreamResponse.status, + statusText: upstreamResponse.statusText, + headers: responseHeaders, + }) + } catch { + return htmlResponse(502, `Preview request failed: cannot reach port ${session.port}.`) + } + }) + + return { app, injectWebSocket } +} diff --git a/backend/src/services/preview/ports.ts b/backend/src/services/preview/ports.ts new file mode 100644 index 00000000..2ddfb45c --- /dev/null +++ b/backend/src/services/preview/ports.ts @@ -0,0 +1,322 @@ +import { readFile, readdir, readlink } from 'node:fs/promises' +import { ENV } from '@opencode-manager/shared/config/env' +import type { PreviewPort } from '@opencode-manager/shared/schemas' +import { executeCommand } from '../../utils/process' + +export type PreviewPortEntry = Omit + +export interface ParsedProcNetSocket { + port: number + address: string + inode: string +} + +export interface LsofListener { + port: number + address: string + pid: number | null + command: string | null +} + +export interface PortDiscoveryDeps { + platform: NodeJS.Platform + readFile: (path: string, encoding: 'utf8') => Promise + readdir: (path: string) => Promise + readlink: (path: string) => Promise + runLsof: () => Promise +} + +const PROC_NET_FILES: ReadonlyArray = [ + ['/proc/net/tcp', 4], + ['/proc/net/tcp6', 6], +] + +const WILDCARD_V4 = '0.0.0.0' +const WILDCARD_V6 = '::' + +function decodeIpv4Hex(hex: string): string | null { + if (hex.length !== 8) return null + const octets: number[] = [] + for (let index = 6; index >= 0; index -= 2) { + const octet = Number.parseInt(hex.slice(index, index + 2), 16) + if (Number.isNaN(octet)) return null + octets.push(octet) + } + return octets.join('.') +} + +function formatIpv6(groups: string[]): string { + const normalized = groups.map((group) => group.replace(/^0+/, '') || '0') + let bestStart = -1 + let bestLength = 0 + let currentStart = -1 + let currentLength = 0 + for (let index = 0; index < normalized.length; index += 1) { + if (normalized[index] === '0') { + if (currentStart === -1) { + currentStart = index + currentLength = 0 + } + currentLength += 1 + if (currentLength > bestLength) { + bestLength = currentLength + bestStart = currentStart + } + } else { + currentStart = -1 + currentLength = 0 + } + } + if (bestLength < 2) return normalized.join(':') + const head = normalized.slice(0, bestStart).join(':') + const tail = normalized.slice(bestStart + bestLength).join(':') + return `${head}::${tail}` +} + +function decodeIpv6Hex(hex: string): string | null { + if (hex.length !== 32) return null + const groups: string[] = [] + for (let index = 0; index < 32; index += 8) { + const word = hex.slice(index, index + 8) + const reversed = `${word.slice(6, 8)}${word.slice(4, 6)}${word.slice(2, 4)}${word.slice(0, 2)}` + groups.push(reversed.slice(0, 4), reversed.slice(4, 8)) + } + return formatIpv6(groups) +} + +function isAllowedAddress(address: string): boolean { + return ( + address === WILDCARD_V4 || + address === WILDCARD_V6 || + address === '::1' || + address.startsWith('127.') + ) +} + +export function isReservedPreviewPort(port: number): boolean { + return port === ENV.SERVER.PORT || port === ENV.OPENCODE.PORT || port === ENV.PREVIEW.PORT +} + +export function parseProcNetTcp(text: string, family: 4 | 6): ParsedProcNetSocket[] { + const sockets: ParsedProcNetSocket[] = [] + for (const rawLine of text.split('\n')) { + const line = rawLine.trim() + if (!line || line.startsWith('sl')) continue + const parts = line.split(/\s+/) + if (parts.length < 10) continue + if (parts[3] !== '0A') continue + const local = parts[1] + if (!local) continue + const separator = local.lastIndexOf(':') + if (separator === -1) continue + const addressHex = local.slice(0, separator) + const portHex = local.slice(separator + 1) + const port = Number.parseInt(portHex, 16) + if (Number.isNaN(port)) continue + const address = family === 4 ? decodeIpv4Hex(addressHex) : decodeIpv6Hex(addressHex) + if (!address || !isAllowedAddress(address)) continue + sockets.push({ port, address, inode: parts[9] ?? '' }) + } + return sockets +} + +function parseLsofName(value: string): { address: string; port: number } | null { + let address: string + let portText: string + if (value.startsWith('[')) { + const end = value.indexOf(']') + if (end === -1) return null + address = value.slice(1, end) + const rest = value.slice(end + 1) + if (!rest.startsWith(':')) return null + portText = rest.slice(1) + } else { + const separator = value.lastIndexOf(':') + if (separator === -1) return null + address = value.slice(0, separator) + portText = value.slice(separator + 1) + } + if (address === '*') address = WILDCARD_V4 + const port = Number.parseInt(portText, 10) + if (Number.isNaN(port)) return null + return { address, port } +} + +export function parseLsofListen(output: string): LsofListener[] { + const listeners: LsofListener[] = [] + let pid: number | null = null + let command: string | null = null + for (const rawLine of output.split('\n')) { + const field = rawLine.trim() + if (!field) continue + const type = field[0] + const value = field.slice(1) + if (type === 'p') { + const parsed = Number.parseInt(value, 10) + pid = Number.isNaN(parsed) ? null : parsed + } else if (type === 'c') { + command = value + } else if (type === 'n') { + const parsed = parseLsofName(value) + if (parsed) listeners.push({ ...parsed, pid, command }) + } + } + return listeners +} + +function toHost(address: string): '127.0.0.1' | '::1' { + return address === '::1' ? '::1' : '127.0.0.1' +} + +function dedupeByPort(entries: PreviewPortEntry[]): PreviewPortEntry[] { + const byPort = new Map() + for (const entry of entries) { + const existing = byPort.get(entry.port) + if (existing) { + existing.push(entry) + } else { + byPort.set(entry.port, [entry]) + } + } + const result: PreviewPortEntry[] = [] + for (const group of byPort.values()) { + const first = group[0]! + const onlyIpv6Loopback = group.every((entry) => entry.host === '::1') + result.push({ ...first, host: onlyIpv6Loopback ? '::1' : '127.0.0.1' }) + } + return result +} + +async function mapInodesToPids(deps: PortDiscoveryDeps, wantedInodes: ReadonlySet): Promise> { + const map = new Map() + if (wantedInodes.size === 0) return map + let entries: string[] + try { + entries = await deps.readdir('/proc') + } catch { + return map + } + for (const entry of entries) { + if (map.size >= wantedInodes.size) break + if (!/^\d+$/.test(entry)) continue + const fdDir = `/proc/${entry}/fd` + let fds: string[] + try { + fds = await deps.readdir(fdDir) + } catch { + continue + } + for (const fd of fds) { + let target: string + try { + target = await deps.readlink(`${fdDir}/${fd}`) + } catch { + continue + } + const match = /^socket:\[(\d+)\]$/.exec(target) + const inode = match?.[1] + if (inode && wantedInodes.has(inode)) map.set(inode, Number.parseInt(entry, 10)) + } + } + return map +} + +async function readOptional(deps: PortDiscoveryDeps, file: string): Promise { + try { + return (await deps.readFile(file, 'utf8')).trim() || null + } catch { + return null + } +} + +async function readLinkOptional(deps: PortDiscoveryDeps, file: string): Promise { + try { + return await deps.readlink(file) + } catch { + return null + } +} + +async function listLinuxPorts(deps: PortDiscoveryDeps): Promise { + const sockets: ParsedProcNetSocket[] = [] + for (const [file, family] of PROC_NET_FILES) { + let text: string + try { + text = await deps.readFile(file, 'utf8') + } catch { + continue + } + sockets.push(...parseProcNetTcp(text, family)) + } + if (sockets.length === 0) return [] + + const wantedInodes = new Set() + for (const socket of sockets) { + if (socket.inode) wantedInodes.add(socket.inode) + } + const inodeToPid = await mapInodesToPids(deps, wantedInodes) + const processMeta = new Map() + const entries: PreviewPortEntry[] = [] + for (const socket of sockets) { + const pid = inodeToPid.get(socket.inode) ?? null + let command: string | null = null + let cwd: string | null = null + if (pid !== null) { + const cached = processMeta.get(pid) + if (cached) { + command = cached.command + cwd = cached.cwd + } else { + command = await readOptional(deps, `/proc/${pid}/comm`) + cwd = await readLinkOptional(deps, `/proc/${pid}/cwd`) + processMeta.set(pid, { command, cwd }) + } + } + entries.push({ port: socket.port, host: toHost(socket.address), pid, command, cwd }) + } + return entries +} + +async function listMacPorts(deps: PortDiscoveryDeps): Promise { + let output: string + try { + output = await deps.runLsof() + } catch { + return [] + } + return parseLsofListen(output) + .filter((listener) => isAllowedAddress(listener.address)) + .map((listener) => ({ + port: listener.port, + host: toHost(listener.address), + pid: listener.pid, + command: listener.command, + cwd: null, + })) +} + +export async function listListeningPorts(deps: PortDiscoveryDeps = defaultPortDeps): Promise { + const entries = + deps.platform === 'linux' + ? await listLinuxPorts(deps) + : deps.platform === 'darwin' + ? await listMacPorts(deps) + : [] + + return dedupeByPort(entries) + .filter((entry) => entry.port >= 1024 && !isReservedPreviewPort(entry.port)) + .sort((left, right) => left.port - right.port) +} + +const defaultPortDeps: PortDiscoveryDeps = { + platform: process.platform, + readFile: (path, encoding) => readFile(path, encoding), + readdir: (path) => readdir(path), + readlink: (path) => readlink(path), + runLsof: async () => { + const result = await executeCommand(['lsof', '-nP', '-iTCP', '-sTCP:LISTEN', '-F', 'pcn'], { + ignoreExitCode: true, + }) + return typeof result === 'string' ? result : (result as { stdout: string }).stdout + }, +} diff --git a/backend/src/services/project-config.ts b/backend/src/services/project-config.ts new file mode 100644 index 00000000..2fc2765e --- /dev/null +++ b/backend/src/services/project-config.ts @@ -0,0 +1,612 @@ +import { createHash } from 'node:crypto' +import fs from 'node:fs' +import path from 'node:path' +import { z } from 'zod' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { + ProjectActionSchema, + RepoProjectFileSchema, + WorktreeSetupCommandsSchema, + type MoveProjectItemRequest, + type ProjectAction, + type ProjectConfigResponse, + type RepoProjectFile, + type RunProjectActionResponse, + type WorktreeSetupResult, +} from '@opencode-manager/shared/schemas' +import { isRunningActionTerminal } from '@opencode-manager/shared/utils' +import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries' +import { executeCommand } from '../utils/process' +import { getErrorMessage } from '../utils/error-utils' +import { logger } from '../utils/logger' +import { canonicalPathSync, writeFileAtomicSync } 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' +const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash' +const REPO_FILE_RELATIVE_PATH = path.join('.ocm', 'project.json') +const REPO_CONFIG_SYMLINK_MESSAGE = '.ocm/project.json must not be a symbolic link' + +export interface RepoFileState { + exists: boolean + file: RepoProjectFile | null + hash: string | null + error?: string +} + +interface MoveCommit { + repoFile: RepoProjectFile | null + personalActions?: ProjectAction[] + personalSetup?: string[] + trustHash: string | null +} + +interface RepoFileSnapshot { + exists: boolean + content: Buffer | null +} + +export class ProjectConfigError extends Error { + constructor( + message: string, + public status: number, + public code?: string, + public details?: unknown, + ) { + super(message) + this.name = 'ProjectConfigError' + } +} + +export class ProjectConfigService { + private readonly actionRunQueues = new Map>() + + constructor( + private readonly database: Database, + private readonly git: GitService, + private readonly gitAuthService: GitAuthService, + ) {} + + async resolveProjectRepo(repo: Repo): Promise { + if (!repo.isWorktree) { + return repo + } + const mainCheckout = await this.git.getMainCheckoutPath(repo.fullPath) + return getRepoByDirectory(this.database, mainCheckout) ?? repo + } + + getPersonalActions(projectRepo: Repo): ProjectAction[] { + return this.readStoredJson(projectRepo.id, PROJECT_ACTIONS_KEY, z.array(ProjectActionSchema)) ?? [] + } + + setPersonalActions(projectRepo: Repo, actions: ProjectAction[]): void { + const ids = new Set() + for (const action of actions) { + if (ids.has(action.id)) { + throw new ProjectConfigError('Duplicate action id', 400) + } + ids.add(action.id) + } + setRepoSetting(this.database, projectRepo.id, PROJECT_ACTIONS_KEY, JSON.stringify(actions)) + } + + getPersonalSetup(projectRepo: Repo): string[] { + return this.readStoredJson(projectRepo.id, WORKTREE_SETUP_KEY, WorktreeSetupCommandsSchema) ?? [] + } + + setPersonalSetup(projectRepo: Repo, commands: string[]): void { + setRepoSetting(this.database, projectRepo.id, WORKTREE_SETUP_KEY, JSON.stringify(commands)) + } + + async getConfig(repo: Repo, directory: string): Promise { + const projectRepo = await this.resolveProjectRepo(repo) + const repoFile = this.readRepoFile(directory) + const warnings: string[] = [] + + const actions: ProjectConfigResponse['actions'] = this.getPersonalActions(projectRepo).map((action) => ({ + ...action, + source: 'personal' as const, + })) + const actionIds = new Set(actions.map((action) => action.id)) + + for (const action of repoFile.file?.projectActions ?? []) { + if (actionIds.has(action.id)) { + warnings.push(`Repository action "${action.id}" was ignored because a personal action uses the same id`) + continue + } + actionIds.add(action.id) + actions.push({ ...action, source: 'repo' }) + } + + const worktreeSetup: ProjectConfigResponse['worktreeSetup'] = this.getPersonalSetup(projectRepo).map((command) => ({ + command, + source: 'personal' as const, + })) + for (const command of repoFile.file?.setupWorktree ?? []) { + worktreeSetup.push({ command, source: 'repo' }) + } + + const trusted = this.isRepoFileTrusted(projectRepo, repoFile) + + const resolvedActions = await Promise.all( + actions.map(async (action) => + action.url ? { ...action, resolvedUrl: await this.resolveActionUrl(action.url, directory) } : action, + ), + ) + + return { + actions: resolvedActions, + worktreeSetup, + repoFile: { + path: '.ocm/project.json', + exists: repoFile.exists, + trusted, + hash: repoFile.hash, + executable: repoFile.file ? this.buildRepoFileExecutable(repoFile.file) : null, + ...(repoFile.error ? { error: repoFile.error } : {}), + warnings, + }, + } + } + + 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('Action not found', 404) + } + + if (action.source === 'repo' && !config.repoFile.trusted) { + throw new ProjectConfigError('Repository commands are not trusted', 409, '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) => isRunningActionTerminal(terminal, actionId)) + 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 + } + + async runWorktreeSetup( + projectRepo: Repo, + worktreeDirectory: string, + terminalService: TerminalService, + ): Promise { + const commands = [...this.getPersonalSetup(projectRepo)] + const repoFile = this.readRepoFile(worktreeDirectory) + const repoCommands = repoFile.file?.setupWorktree ?? [] + const repoCommandsSkipped = repoCommands.length > 0 && !this.isRepoFileTrusted(projectRepo, repoFile) + if (!repoCommandsSkipped) { + commands.push(...repoCommands) + } + + if (commands.length === 0) { + return repoCommandsSkipped ? { status: 'skipped', reason: 'untrusted' } : { status: 'none' } + } + + try { + const terminal = await terminalService.create(worktreeDirectory, { + kind: 'setup', + name: 'Worktree setup', + command: '/bin/sh', + args: ['-c', ['set -e', ...commands].join('\n')], + env: { ROOT_PROJECT_PATH: projectRepo.fullPath }, + }) + return { status: 'started', terminal, repoCommandsSkipped } + } catch (error: unknown) { + logger.warn(`Failed to start worktree setup for ${worktreeDirectory}:`, error) + return { status: 'failed', error: getErrorMessage(error) } + } + } + + async runWorktreeSetupForRepo( + repo: Repo, + worktreeDirectory: string, + terminalService: TerminalService, + ): Promise { + try { + const projectRepo = await this.resolveProjectRepo(repo) + return await this.runWorktreeSetup(projectRepo, worktreeDirectory, terminalService) + } catch (error: unknown) { + logger.warn(`Failed to prepare worktree setup for ${worktreeDirectory}:`, error) + return { status: 'failed', error: getErrorMessage(error) } + } + } + + private isRepoFileTrusted(projectRepo: Repo, repoFile: RepoFileState): boolean { + return ( + repoFile.hash !== null && + repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY) + ) + } + + readRepoFile(directory: string): RepoFileState { + const filePath = this.getRepoFilePath(directory) + try { + if (this.isSymbolicLink(path.dirname(filePath)) || this.isSymbolicLink(filePath)) { + return { exists: true, file: null, hash: null, error: REPO_CONFIG_SYMLINK_MESSAGE } + } + if (!fs.existsSync(filePath)) { + return { exists: false, file: null, hash: null } + } + + let parsedJson: unknown + try { + parsedJson = JSON.parse(fs.readFileSync(filePath, 'utf8')) + } catch { + return { exists: true, file: null, hash: null, error: 'Invalid JSON' } + } + + const parsed = RepoProjectFileSchema.safeParse(parsedJson) + if (!parsed.success) { + return { exists: true, file: null, hash: null, error: 'Does not match the project file schema' } + } + return { exists: true, file: parsed.data, hash: this.hashRepoFile(parsed.data) } + } catch { + return { exists: fs.existsSync(filePath), file: null, hash: null, error: 'Invalid repository config' } + } + } + + buildRepoFileExecutable(file: RepoProjectFile): NonNullable { + return { + actions: (file.projectActions ?? []).map((action) => ({ + id: action.id, + name: action.name, + command: action.command, + url: action.url ?? null, + autoOpenUrl: action.autoOpenUrl, + })), + setup: file.setupWorktree ?? [], + } + } + + hashRepoFile(file: RepoProjectFile): string { + return createHash('sha256').update(JSON.stringify(this.buildRepoFileExecutable(file))).digest('hex') + } + + async trustRepoFile(repo: Repo, directory: string, hash: string): Promise { + const projectRepo = await this.resolveProjectRepo(repo) + const repoFile = this.readRepoFile(directory) + if (repoFile.hash === null || repoFile.hash !== hash) { + throw new ProjectConfigError('Repository config changed', 409, 'REPO_CONFIG_CHANGED') + } + this.setRepoTrust(projectRepo, repoFile.hash) + } + + async moveItem(repo: Repo, directory: string, request: MoveProjectItemRequest): Promise { + const projectRepo = await this.resolveProjectRepo(repo) + const filePath = this.getRepoFilePath(directory) + this.assertRepoFilePathNotSymlink(filePath) + const state = this.readRepoFile(directory) + const commit = + request.to === 'repo' + ? this.planMoveToRepo(projectRepo, state, request) + : this.planMoveToPersonal(projectRepo, state, request) + + this.commitMove(projectRepo, filePath, commit) + } + + private planMoveToRepo(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit { + if (state.exists && !state.file) { + throw new ProjectConfigError('Repository config is invalid', 409) + } + + const file: RepoProjectFile = state.file ? { ...state.file } : { version: 1 } + + if (request.kind === 'action') { + const personal = this.getPersonalActions(projectRepo) + const action = personal.find((item) => item.id === request.id) + if (!action) { + throw new ProjectConfigError('Action not found', 404) + } + const repoActions = file.projectActions ?? [] + if (repoActions.some((existing) => existing.id === action.id)) { + throw new ProjectConfigError('Action already exists in repository config', 409) + } + const nextFile: RepoProjectFile = { ...file, projectActions: [...repoActions, action] } + this.assertRepoFileValid(nextFile) + return { + repoFile: nextFile, + personalActions: personal.filter((item) => item.id !== action.id), + trustHash: this.resolveTrustAfterMove(projectRepo, state, this.hashRepoFile(nextFile)), + } + } + + const personal = this.getPersonalSetup(projectRepo) + const index = personal.indexOf(request.command) + if (index === -1) { + throw new ProjectConfigError('Setup command not found', 404) + } + const nextFile: RepoProjectFile = { + ...file, + setupWorktree: [...(file.setupWorktree ?? []), request.command], + } + const nextPersonal = personal.filter((_, itemIndex) => itemIndex !== index) + this.assertRepoFileValid(nextFile) + this.assertPersonalSetupValid(nextPersonal) + return { + repoFile: nextFile, + personalSetup: nextPersonal, + trustHash: this.resolveTrustAfterMove(projectRepo, state, this.hashRepoFile(nextFile)), + } + } + + private planMoveToPersonal(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit { + const file = state.file + if (!file) { + throw new ProjectConfigError('Item not found', 404) + } + + if (request.kind === 'action') { + const repoActions = file.projectActions ?? [] + const action = repoActions.find((item) => item.id === request.id) + if (!action) { + throw new ProjectConfigError('Action not found', 404) + } + const nextFile = this.pruneRepoFile({ + ...file, + projectActions: repoActions.filter((item) => item.id !== action.id), + }) + const personalActions = [...this.getPersonalActions(projectRepo), action] + return nextFile + ? { + repoFile: nextFile, + personalActions, + trustHash: this.resolveTrustAfterMove(projectRepo, state, this.hashRepoFile(nextFile)), + } + : { repoFile: null, personalActions, trustHash: null } + } + + const repoSetup = file.setupWorktree ?? [] + const index = repoSetup.indexOf(request.command) + if (index === -1) { + throw new ProjectConfigError('Setup command not found', 404) + } + const nextFile = this.pruneRepoFile({ + ...file, + setupWorktree: repoSetup.filter((_, itemIndex) => itemIndex !== index), + }) + const personalSetup = [...this.getPersonalSetup(projectRepo), request.command] + this.assertPersonalSetupValid(personalSetup) + return nextFile + ? { + repoFile: nextFile, + personalSetup, + trustHash: this.resolveTrustAfterMove(projectRepo, state, this.hashRepoFile(nextFile)), + } + : { repoFile: null, personalSetup, trustHash: null } + } + + private resolveTrustAfterMove(projectRepo: Repo, state: RepoFileState, nextHash: string | null): string | null { + if (nextHash === null) { + return null + } + if (this.hasUntrustedExecutableContent(projectRepo, state)) { + return getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY) + } + return nextHash + } + + private hasUntrustedExecutableContent(projectRepo: Repo, state: RepoFileState): boolean { + if (!state.exists || !state.file) { + return false + } + const hasExecutable = + (state.file.projectActions?.length ?? 0) > 0 || (state.file.setupWorktree?.length ?? 0) > 0 + return hasExecutable && !this.isRepoFileTrusted(projectRepo, state) + } + + private pruneRepoFile(file: RepoProjectFile): RepoProjectFile | null { + const next: RepoProjectFile = { ...file } + if (next.projectActions && next.projectActions.length === 0) { + delete next.projectActions + } + if (next.setupWorktree && next.setupWorktree.length === 0) { + delete next.setupWorktree + } + if (Object.keys(next).every((key) => key === 'version')) { + return null + } + this.assertRepoFileValid(next) + return next + } + + private commitMove(projectRepo: Repo, filePath: string, commit: MoveCommit): void { + const snapshot = this.snapshotFile(filePath) + let fileMutated = false + + try { + this.database.transaction(() => { + if (commit.repoFile === null) { + fs.rmSync(filePath, { force: true }) + } else { + this.writeRepoFile(filePath, commit.repoFile) + } + fileMutated = true + + if (commit.personalActions !== undefined) { + this.setPersonalActions(projectRepo, commit.personalActions) + } + if (commit.personalSetup !== undefined) { + this.setPersonalSetup(projectRepo, commit.personalSetup) + } + this.setRepoTrust(projectRepo, commit.trustHash) + })() + } catch (error) { + if (fileMutated) { + this.restoreFile(filePath, snapshot) + } + throw error + } + + if (commit.repoFile === null) { + this.removeOcmDirIfEmpty(filePath) + } + } + + private assertRepoFileValid(file: RepoProjectFile): void { + const result = RepoProjectFileSchema.safeParse(file) + if (!result.success) { + throw new ProjectConfigError( + 'Repository config limit exceeded', + 409, + 'PROJECT_CONFIG_LIMIT_EXCEEDED', + result.error.flatten(), + ) + } + } + + private assertPersonalSetupValid(commands: string[]): void { + const result = WorktreeSetupCommandsSchema.safeParse(commands) + if (!result.success) { + throw new ProjectConfigError( + 'Personal setup command limit exceeded', + 409, + 'PROJECT_CONFIG_LIMIT_EXCEEDED', + result.error.flatten(), + ) + } + } + + private setRepoTrust(projectRepo: Repo, hash: string | null): void { + setRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY, hash) + } + + private getRepoFilePath(directory: string): string { + return path.join(directory, REPO_FILE_RELATIVE_PATH) + } + + private writeRepoFile(filePath: string, file: RepoProjectFile): void { + writeFileAtomicSync(filePath, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o644 }) + } + + private isSymbolicLink(target: string): boolean { + try { + return fs.lstatSync(target).isSymbolicLink() + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return false + } + throw error + } + } + + private assertRepoFilePathNotSymlink(filePath: string): void { + if (this.isSymbolicLink(path.dirname(filePath)) || this.isSymbolicLink(filePath)) { + throw new ProjectConfigError(REPO_CONFIG_SYMLINK_MESSAGE, 400, 'REPO_CONFIG_SYMLINK') + } + } + + private snapshotFile(filePath: string): RepoFileSnapshot { + try { + return { exists: true, content: fs.readFileSync(filePath) } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return { exists: false, content: null } + } + throw error + } + } + + private restoreFile(filePath: string, snapshot: RepoFileSnapshot): void { + if (!snapshot.exists || snapshot.content === null) { + fs.rmSync(filePath, { force: true }) + return + } + fs.mkdirSync(path.dirname(filePath), { recursive: true }) + fs.writeFileSync(filePath, snapshot.content) + } + + private removeOcmDirIfEmpty(filePath: string): void { + const dir = path.dirname(filePath) + try { + if (fs.readdirSync(dir).length === 0) { + fs.rmdirSync(dir) + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error + } + } + } + + private readStoredJson(repoId: number, key: string, schema: z.ZodType): T | null { + const raw = getRepoSetting(this.database, repoId, key) + if (!raw) { + return null + } + try { + const result = schema.safeParse(JSON.parse(raw)) + return result.success ? result.data : null + } catch { + return null + } + } +} diff --git a/backend/src/services/repo-workspace.ts b/backend/src/services/repo-workspace.ts new file mode 100644 index 00000000..07f3d32e --- /dev/null +++ b/backend/src/services/repo-workspace.ts @@ -0,0 +1,72 @@ +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { isWorktreeSibling } from '@opencode-manager/shared/utils' +import { logger } from '../utils/logger' +import type { GitAuthService } from './git-auth' +import type { OpenCodeClient } from './opencode/client' +import type { ProjectConfigService } from './project-config' +import type { TerminalService } from './terminal' +import { findSiblingByDirectory, getSiblingRepos, RepoWorkspaceError, resolveRepoProjectId } from './repo' + +/** Single owner of OpenCode workspace lifecycle side effects: worktree setup on create and terminal cleanup on remove. */ +export class RepoWorkspaceService { + constructor( + private readonly database: Database, + private readonly openCodeClient: OpenCodeClient, + private readonly gitAuthService: GitAuthService, + private readonly projectConfigService: ProjectConfigService, + private readonly terminalService: TerminalService, + ) {} + + async create(repo: Repo, options: { name?: string; ref?: string } = {}) { + const projectID = await resolveRepoProjectId(this.openCodeClient, repo.fullPath) + const worktree = await this.openCodeClient.api.worktree.create({ + projectID, + ...(options.name ? { name: options.name } : {}), + ...(options.ref ? { branch: options.ref } : {}), + }) + const worktreeSetup = await this.projectConfigService.runWorktreeSetupForRepo(repo, worktree.directory, this.terminalService) + return { ...worktree, worktreeSetup } + } + + async remove(repo: Repo, directory: string): Promise { + const worktree = findSiblingByDirectory(await this.listWorktreeSiblings(repo.id), directory) + if (!worktree) throw new RepoWorkspaceError('Not a deletable worktree of this repo', 400) + + await this.removeTerminals(worktree.fullPath) + const projectID = await resolveRepoProjectId(this.openCodeClient, repo.fullPath) + await this.openCodeClient.api.worktree.remove({ projectID, directory: worktree.fullPath, force: true }) + } + + async removeRepoTerminals(repo: Repo): Promise { + await this.removeTerminals(repo.fullPath) + + let siblings: Array<{ fullPath: string }> + try { + siblings = await this.listWorktreeSiblings(repo.id) + } catch (error: unknown) { + logger.warn(`Failed to list OpenCode workspace siblings for repo ${repo.id}:`, error) + return + } + await Promise.all(siblings.map((sibling) => this.removeTerminals(sibling.fullPath))) + } + + private async listWorktreeSiblings(repoId: number) { + const siblings = await getSiblingRepos( + this.database, + repoId, + this.gitAuthService.getGitEnvironment(), + this.openCodeClient, + { includeBranch: false }, + ) + return siblings.filter(isWorktreeSibling) + } + + private async removeTerminals(directory: string): Promise { + try { + await this.terminalService.removeAll(directory) + } catch (error: unknown) { + logger.warn(`Failed to remove terminals for ${directory}:`, error) + } + } +} diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 9dd6261c..284f112a 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -7,7 +7,7 @@ import type { Database } from 'bun:sqlite' import type { Repo, CreateRepoInput } from '../types/repo' import { logger } from '../utils/logger' import { getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env' -import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, isWorktreeSibling, SCP_STYLE_URL_PATTERN } from '@opencode-manager/shared/utils' +import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN, ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' import type { GitAuthService } from './git-auth' import { isGitHubHttpsUrl } from '../utils/git-auth' import path from 'path' @@ -18,6 +18,7 @@ import { resolveProjectId, isGitMainCheckout } from './project-id-resolver' import { listRepos } from '../db/queries' import { listActiveScheduleRunWorktreePaths } from '../db/schedules' import { SettingsService } from './settings' +import { buildAssistantRepo } from './assistant-mode' import type { OpenCodeClient } from './opencode/client' import { openCodeLocation } from '@opencode-manager/shared/opencode' import { canonicalPathSync, mkdirSafe } from '../utils/fs-safe' @@ -1207,11 +1208,32 @@ export async function resolveRepoForDirectory( return null } +export function resolveRepoOrAssistant(database: Database, id: number): Repo | null { + return getRepoById(database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null) +} + +export function findSiblingByDirectory(siblings: T[], directory: string): T | undefined { + const requestedDirectory = canonicalPathSync(path.resolve(directory)) + return siblings.find((sibling) => canonicalPathSync(path.resolve(sibling.fullPath)) === requestedDirectory) +} + +export async function resolveRepoWorkingDirectory( + repo: Repo, + directory: string | undefined, + loadSiblings: () => Promise>, +): Promise { + if (directory === undefined) return repo.fullPath + if (canonicalPathSync(path.resolve(directory)) === canonicalPathSync(path.resolve(repo.fullPath))) return repo.fullPath + + return findSiblingByDirectory(await loadSiblings(), directory)?.fullPath ?? null +} + export async function getSiblingRepos( database: Database, repoId: number, gitEnv: Record, openCodeClient?: OpenCodeClient, + options: { includeBranch?: boolean } = {}, ): Promise> { const settingsService = new SettingsService(database) const settings = settingsService.getSettings() @@ -1235,10 +1257,11 @@ export async function getSiblingRepos( .filter((entry) => entry.projectId === targetProjectId) .map((entry) => entry.repo) + const includeBranch = options.includeBranch ?? true const repoSiblings = await Promise.all( matching.map(async (repo) => ({ ...repo, - currentBranch: (await getCurrentBranch(repo, gitEnv)) ?? undefined, + currentBranch: includeBranch ? (await getCurrentBranch(repo, gitEnv)) ?? undefined : undefined, })), ) @@ -1312,34 +1335,3 @@ export class RepoWorkspaceError extends Error { this.status = status } } - -export async function createRepoWorkspace( - openCodeClient: OpenCodeClient, - repo: Repo, - options: { name?: string; ref?: string } = {}, -): Promise<{ directory: string }> { - const projectID = await resolveRepoProjectId(openCodeClient, repo.fullPath) - return openCodeClient.api.worktree.create({ - projectID, - ...(options.name ? { name: options.name } : {}), - ...(options.ref ? { branch: options.ref } : {}), - }) -} - -export async function removeRepoWorkspace( - database: Database, - openCodeClient: OpenCodeClient, - gitEnv: Record, - repo: Repo, - directory: string, -): Promise { - const siblings = await getSiblingRepos(database, repo.id, gitEnv, openCodeClient) - const requestedDirectory = canonicalPathSync(path.resolve(directory)) - const worktree = siblings.find( - (sibling) => isWorktreeSibling(sibling) && canonicalPathSync(path.resolve(sibling.fullPath)) === requestedDirectory, - ) - if (!worktree) throw new RepoWorkspaceError('Not a deletable worktree of this repo', 400) - - const projectID = await resolveRepoProjectId(openCodeClient, repo.fullPath) - await openCodeClient.api.worktree.remove({ projectID, directory: worktree.fullPath, force: true }) -} diff --git a/backend/src/services/session-launcher.ts b/backend/src/services/session-launcher.ts index d5a62bfb..b2b909da 100644 --- a/backend/src/services/session-launcher.ts +++ b/backend/src/services/session-launcher.ts @@ -6,7 +6,7 @@ import type { Repo } from '../types/repo' import { getErrorMessage } from '../utils/error-utils' import type { OpenCodeClient } from './opencode/client' import { resolveOpenCodeModel, type ResolvedOpenCodeModel } from './opencode-models' -import { createRepoWorkspace } from './repo' +import type { RepoWorkspaceService } from './repo-workspace' interface LaunchSessionInput { repoId: number @@ -54,6 +54,7 @@ export class SessionLauncher { constructor( private readonly db: Database, private readonly openCodeClient: OpenCodeClient, + private readonly repoWorkspaces: RepoWorkspaceService, ) {} async resolveModel(repo: Repo, requestedModel?: string): Promise { @@ -85,7 +86,7 @@ export class SessionLauncher { if (input.workspace) { try { - const workspace = await createRepoWorkspace(this.openCodeClient, repo, { + const workspace = await this.repoWorkspaces.create(repo, { name: sanitizeRepoDirectoryName(input.workspace.name ?? '', 'session'), ...(input.workspace.ref ? { ref: input.workspace.ref } : {}), }) diff --git a/backend/src/services/terminal.ts b/backend/src/services/terminal.ts new file mode 100644 index 00000000..cba45276 --- /dev/null +++ b/backend/src/services/terminal.ts @@ -0,0 +1,121 @@ +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' +import { bridgeWebSocket, type WebSocketBridge, type WebSocketPeer } from '../utils/websocket-bridge' + +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, + private readonly upstreamBaseUrl: () => string, + private readonly openSocket: (url: string) => WebSocket = (url) => new WebSocket(url), + ) {} + + 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.getGhCliEnv({ 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 + } + } + } + + async connect( + directory: string, + ptyID: string, + cursor: number | undefined, + peer: WebSocketPeer, + ): Promise { + await this.requireTerminal(directory, ptyID) + + const result = await this.openCodeClient.api.pty.connect.token({ + ptyID, + location: { directory }, + 'x-opencode-ticket': '1', + }) + + const base = new URL(this.upstreamBaseUrl()) + if (!base.pathname.endsWith('/')) base.pathname += '/' + const socketUrl = new URL(`api/pty/${encodeURIComponent(ptyID)}/connect`, base) + socketUrl.searchParams.set('ticket', result.data.ticket) + socketUrl.searchParams.set('location[directory]', directory) + if (cursor !== undefined) socketUrl.searchParams.set('cursor', String(cursor)) + socketUrl.protocol = socketUrl.protocol === 'https:' ? 'wss:' : 'ws:' + + return bridgeWebSocket(this.openSocket(socketUrl.toString()), peer) + } + + 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/src/utils/fs-safe.ts b/backend/src/utils/fs-safe.ts index e2bd1c81..6a591ad0 100644 --- a/backend/src/utils/fs-safe.ts +++ b/backend/src/utils/fs-safe.ts @@ -1,5 +1,5 @@ import path from 'path' -import { promises as fs, mkdirSync, accessSync, constants, realpathSync } from 'node:fs' +import { promises as fs, mkdirSync, accessSync, constants, realpathSync, writeFileSync, renameSync, rmSync } from 'node:fs' interface MkdirSafeOptions { mode?: number @@ -39,6 +39,19 @@ export async function writeFileAtomic(filePath: string, content: string, options } } +export function writeFileAtomicSync(filePath: string, content: string, options: { mode?: number } = {}): void { + const dir = path.dirname(filePath) + mkdirSyncSafe(dir) + const tempPath = path.join(dir, `.${path.basename(filePath)}.ocm-tmp-${process.pid}-${Date.now()}`) + try { + writeFileSync(tempPath, content, { encoding: 'utf-8', mode: options.mode ?? 0o600 }) + renameSync(tempPath, filePath) + } catch (error) { + rmSync(tempPath, { force: true }) + throw error + } +} + export async function existingFileMode(filePath: string): Promise { try { return (await fs.stat(filePath)).mode & 0o777 diff --git a/backend/src/utils/proxy-headers.ts b/backend/src/utils/proxy-headers.ts new file mode 100644 index 00000000..6dc9fa6a --- /dev/null +++ b/backend/src/utils/proxy-headers.ts @@ -0,0 +1,40 @@ +const HOP_BY_HOP_HEADERS = new Set([ + 'connection', + 'keep-alive', + 'proxy-authenticate', + 'proxy-authorization', + 'te', + 'trailers', + 'upgrade', + 'transfer-encoding', + 'content-length', + 'content-encoding', + 'host', + 'authorization', +]) + +export function filterProxyHeaders( + headers: Headers, + extraExcluded: ReadonlySet = new Set(), +): Record { + const result: Record = {} + headers.forEach((value, key) => { + const lowerKey = key.toLowerCase() + if (HOP_BY_HOP_HEADERS.has(lowerKey) || extraExcluded.has(lowerKey)) return + result[key] = value + }) + return result +} + +export function buildProxyResponseHeaders( + source: Headers, + extraExcluded: ReadonlySet = new Set(), +): Headers { + const excluded = new Set(extraExcluded) + excluded.add('set-cookie') + const headers = new Headers(filterProxyHeaders(source, excluded)) + for (const cookie of source.getSetCookie()) { + headers.append('set-cookie', cookie) + } + return headers +} diff --git a/backend/src/utils/route-helpers.ts b/backend/src/utils/route-helpers.ts index 6dd7c08a..297a3cf9 100644 --- a/backend/src/utils/route-helpers.ts +++ b/backend/src/utils/route-helpers.ts @@ -27,6 +27,8 @@ interface ServiceError { message: string statusCode?: number status?: number + code?: string + details?: unknown } type ServiceErrorConstructor = new (message: string, statusOrStatusCode: number) => ServiceError @@ -38,8 +40,16 @@ export function handleServiceError( ErrorClass: ServiceErrorConstructor, ) { if (error instanceof ErrorClass) { - const status = (error as ServiceError).statusCode ?? (error as ServiceError).status ?? 500 - return c.json({ error: error.message }, status as ContentfulStatusCode) + const serviceError = error as ServiceError + const status = serviceError.statusCode ?? serviceError.status ?? 500 + return c.json( + { + error: error.message, + ...(serviceError.code !== undefined ? { code: serviceError.code } : {}), + ...(serviceError.details !== undefined ? { details: serviceError.details } : {}), + }, + status as ContentfulStatusCode, + ) } logger.error(fallback, error) return c.json({ error: getErrorMessage(error) }, 500) diff --git a/backend/src/utils/websocket-bridge.ts b/backend/src/utils/websocket-bridge.ts new file mode 100644 index 00000000..3e194157 --- /dev/null +++ b/backend/src/utils/websocket-bridge.ts @@ -0,0 +1,107 @@ +export interface WebSocketPeer { + send(data: string | Uint8Array): void + close(code?: number, reason?: string): void + bufferedAmount(): number +} + +export interface WebSocketBridge { + send(data: string | ArrayBuffer | Uint8Array): void + close(): void +} + +export const MAX_PEER_BUFFERED_BYTES = 4 * 1024 * 1024 + +export function peerBufferedAmount(peer: { raw?: unknown }): number { + const raw = peer.raw as { bufferedAmount?: number } | undefined + return typeof raw?.bufferedAmount === 'number' ? raw.bufferedAmount : 0 +} + +export async function forwardPeerMessage( + bridge: WebSocketBridge, + data: string | Blob | ArrayBufferLike, +): Promise { + if (typeof data === 'string') { + bridge.send(data) + return + } + if (data instanceof Blob) { + bridge.send(await data.arrayBuffer()) + return + } + if (data instanceof ArrayBuffer) { + bridge.send(data) + } +} + +function defaultMapCloseCode(code: number): number { + if (code === 1000) return 1000 + if (code >= 4000 && code <= 4999) return code + return 1011 +} + +function toBytes(data: ArrayBuffer | Uint8Array): Uint8Array { + return data instanceof Uint8Array ? (data as Uint8Array) : new Uint8Array(data) +} + +export function bridgeWebSocket(upstream: WebSocket, peer: WebSocketPeer): WebSocketBridge { + upstream.binaryType = 'arraybuffer' + + const queue: Array = [] + let upstreamOpen = false + let finished = false + + const finish = (): void => { + finished = true + } + + upstream.addEventListener('open', () => { + upstreamOpen = true + while (queue.length > 0) { + upstream.send(queue.shift()!) + } + }) + + upstream.addEventListener('message', (event) => { + if (finished) return + const data = (event as MessageEvent).data + if (typeof data === 'string') { + peer.send(data) + } else if (data instanceof ArrayBuffer || data instanceof Uint8Array) { + peer.send(toBytes(data)) + } + if (peer.bufferedAmount() > MAX_PEER_BUFFERED_BYTES) { + finish() + upstream.close() + peer.close(1013, 'Client too slow') + } + }) + + upstream.addEventListener('close', (event) => { + if (finished) return + finish() + peer.close(defaultMapCloseCode((event as CloseEvent).code)) + }) + + upstream.addEventListener('error', () => { + if (finished) return + finish() + peer.close(1011) + }) + + return { + send(data) { + if (finished) return + const payload = typeof data === 'string' ? data : toBytes(data) + if (upstreamOpen) { + upstream.send(payload) + } else { + queue.push(payload) + } + }, + close() { + if (finished) return + finish() + upstream.close() + }, + } +} diff --git a/backend/test/auth/index.test.ts b/backend/test/auth/index.test.ts index a53e2958..dc7fc50b 100644 --- a/backend/test/auth/index.test.ts +++ b/backend/test/auth/index.test.ts @@ -31,7 +31,13 @@ const { ENV } = vi.hoisted(() => ({ }, })) -vi.mock('@opencode-manager/shared/config/env', () => ({ ENV })) +vi.mock('@opencode-manager/shared/config/env', () => ({ + ENV, + getTrustedOrigins: () => ENV.AUTH.TRUSTED_ORIGINS + .split(',') + .map((origin: string) => origin.trim()) + .filter((origin: string) => origin.length > 0), +})) vi.mock('../../src/utils/logger', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, diff --git a/backend/test/auth/middleware-same-site.test.ts b/backend/test/auth/middleware-same-site.test.ts new file mode 100644 index 00000000..336ec451 --- /dev/null +++ b/backend/test/auth/middleware-same-site.test.ts @@ -0,0 +1,186 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { Hono } from 'hono' +import { createAuthMiddleware } from '../../src/auth/middleware' +import type { AuthInstance, Session } from '../../src/auth' + +const loggerMock = vi.hoisted(() => ({ + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + debug: vi.fn(), +})) + +vi.mock('../../src/utils/logger', () => ({ logger: loggerMock })) + +const TRUSTED_ORIGIN = 'http://trusted.test' +const UNTRUSTED_ORIGIN = 'http://untrusted.test' + +function createSession(): Session { + return { + session: { + id: 'session-1', + userId: 'user-1', + token: 'token-1', + expiresAt: new Date(Date.now() + 1000), + createdAt: new Date(), + updatedAt: new Date(), + }, + user: { + id: 'user-1', + name: 'Test User', + email: 'test@example.com', + emailVerified: true, + createdAt: new Date(), + updatedAt: new Date(), + role: 'user', + }, + } +} + +function createApp( + getSession: (input: { headers: Headers }) => Promise, + trustedOrigins: string[] = [TRUSTED_ORIGIN], +) { + const app = new Hono<{ Variables: { session: Session['session']; user: Session['user'] } }>() + app.use('/*', createAuthMiddleware({ api: { getSession } } as unknown as AuthInstance, () => trustedOrigins)) + app.get('/', (c) => c.json({ userId: c.get('user').id })) + app.post('/', (c) => c.json({ ok: true })) + app.put('/', (c) => c.json({ ok: true })) + app.patch('/', (c) => c.json({ ok: true })) + app.delete('/', (c) => c.json({ ok: true })) + return app +} + +describe('createAuthMiddleware same-site guard', () => { + let getSession: ReturnType + + beforeEach(() => { + vi.clearAllMocks() + getSession = vi.fn() + getSession.mockResolvedValue(createSession()) + }) + + it('rejects an unsafe same-site request with an untrusted origin without looking up the session', async () => { + const app = createApp(getSession) + + const res = await app.request('/', { + method: 'POST', + headers: { 'sec-fetch-site': 'same-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' }, + }) + + expect(res.status).toBe(403) + expect(await res.json()).toEqual({ error: 'Cross-site request rejected' }) + expect(getSession).not.toHaveBeenCalled() + expect(loggerMock.warn).toHaveBeenCalledWith(expect.stringContaining('/')) + }) + + it('allows an unsafe same-site request from a trusted origin', async () => { + const app = createApp(getSession) + + const res = await app.request('/', { + method: 'POST', + headers: { 'sec-fetch-site': 'same-site', origin: TRUSTED_ORIGIN, cookie: 'opencode.session=valid' }, + }) + + expect(res.status).toBe(200) + expect(getSession).toHaveBeenCalledTimes(1) + expect(loggerMock.warn).not.toHaveBeenCalled() + }) + + it('allows a same-origin request', async () => { + const app = createApp(getSession) + + const res = await app.request('/', { + method: 'POST', + headers: { 'sec-fetch-site': 'same-origin', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' }, + }) + + expect(res.status).toBe(200) + expect(getSession).toHaveBeenCalledTimes(1) + }) + + it('allows an unsafe request without a Sec-Fetch-Site header', async () => { + const app = createApp(getSession) + + const res = await app.request('/', { + method: 'POST', + headers: { origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' }, + }) + + expect(res.status).toBe(200) + expect(getSession).toHaveBeenCalledTimes(1) + }) + + it('allows a cross-site GET so WebSocket upgrades are unaffected', async () => { + const app = createApp(getSession) + + const res = await app.request('/', { + method: 'GET', + headers: { 'sec-fetch-site': 'cross-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' }, + }) + + expect(res.status).toBe(200) + expect(getSession).toHaveBeenCalledTimes(1) + }) + + it('rejects a cross-site unsafe request with no origin', async () => { + const app = createApp(getSession) + + const res = await app.request('/', { + method: 'DELETE', + headers: { 'sec-fetch-site': 'cross-site', cookie: 'opencode.session=valid' }, + }) + + expect(res.status).toBe(403) + expect(await res.json()).toEqual({ error: 'Cross-site request rejected' }) + expect(getSession).not.toHaveBeenCalled() + }) + + it('rejects a cross-site PUT with an untrusted origin', async () => { + const app = createApp(getSession) + + const res = await app.request('/', { + method: 'PUT', + headers: { 'sec-fetch-site': 'cross-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' }, + }) + + expect(res.status).toBe(403) + expect(getSession).not.toHaveBeenCalled() + }) +}) + +describe('getTrustedOrigins', () => { + const originalTrustedOrigins = process.env.AUTH_TRUSTED_ORIGINS + + afterEach(() => { + if (originalTrustedOrigins === undefined) { + delete process.env.AUTH_TRUSTED_ORIGINS + } else { + process.env.AUTH_TRUSTED_ORIGINS = originalTrustedOrigins + } + vi.resetModules() + }) + + async function loadTrustedOrigins(value?: string): Promise { + if (value === undefined) { + delete process.env.AUTH_TRUSTED_ORIGINS + } else { + process.env.AUTH_TRUSTED_ORIGINS = value + } + vi.resetModules() + const { getTrustedOrigins } = await import('@opencode-manager/shared/config/env') + return getTrustedOrigins() + } + + it('splits, trims, and drops empty entries', async () => { + await expect(loadTrustedOrigins(' http://a.test ,, http://b.test ')).resolves.toEqual(['http://a.test', 'http://b.test']) + }) + + it('returns an empty list when configured empty', async () => { + await expect(loadTrustedOrigins('')).resolves.toEqual([]) + }) + + it('falls back to the local development origins', async () => { + await expect(loadTrustedOrigins(undefined)).resolves.toEqual(['http://localhost:5173', 'http://localhost:5003']) + }) +}) diff --git a/backend/test/index.test.ts b/backend/test/index.test.ts index 367e9401..b2321dba 100644 --- a/backend/test/index.test.ts +++ b/backend/test/index.test.ts @@ -3,12 +3,47 @@ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promis import { tmpdir } from 'node:os' import { join } from 'node:path' -const serveMock = vi.fn() +interface MockServeServer { + on: (event: string, handler: (...args: unknown[]) => void) => void + emit: (event: string, ...args: unknown[]) => void +} + +const serveServers = vi.hoisted(() => [] as MockServeServer[]) + +const serveMock = vi.fn<(options: unknown) => MockServeServer>(() => { + const handlers = new Map void>>() + const server: MockServeServer = { + on: (event, handler) => { + const registered = handlers.get(event) ?? [] + registered.push(handler) + handlers.set(event, registered) + }, + emit: (event, ...args) => { + for (const handler of handlers.get(event) ?? []) handler(...args) + }, + } + serveServers.push(server) + return server +}) vi.mock('@hono/node-server', () => ({ serve: serveMock, })) +const previewAvailabilityInstances = vi.hoisted(() => [] as Array<{ isEnabled: () => boolean }>) + +vi.mock('../src/routes/preview', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + createPreviewAvailability: (initialEnabled: boolean) => { + const availability = actual.createPreviewAvailability(initialEnabled) + previewAvailabilityInstances.push(availability) + return availability + }, + } +}) + const supervisorMock = vi.hoisted(() => ({ start: vi.fn().mockResolvedValue({ healthy: true, port: 5551, state: 'running' }), stop: vi.fn().mockResolvedValue(undefined), @@ -144,6 +179,8 @@ describe('backend entrypoint', () => { beforeEach(async () => { vi.resetModules() vi.clearAllMocks() + serveServers.length = 0 + previewAvailabilityInstances.length = 0 tempWorkspace = await mkdtemp(join(tmpdir(), 'ocm-entrypoint-')) previousWorkspace = process.env.WORKSPACE_PATH process.env.WORKSPACE_PATH = tempWorkspace @@ -163,7 +200,7 @@ describe('backend entrypoint', () => { it('initializes the workspace, registers every route group, and serves the app', async () => { await import('../src/index') - expect(serveMock).toHaveBeenCalledTimes(1) + expect(serveMock).toHaveBeenCalledTimes(2) const options = serveMock.mock.calls[0]![0] as { fetch: unknown; port: number; hostname: string } expect(typeof options.fetch).toBe('function') expect(options.port).toBe(3001) @@ -176,6 +213,22 @@ describe('backend entrypoint', () => { expect(ipcServerMock.dispose).not.toHaveBeenCalled() }) + it('marks the preview gateway unavailable instead of crashing when its port cannot be bound', async () => { + await import('../src/index') + + expect(serveServers).toHaveLength(2) + const availability = previewAvailabilityInstances[0] + expect(availability?.isEnabled()).toBe(false) + + const previewServer = serveServers[1]! + previewServer.emit('listening') + expect(availability?.isEnabled()).toBe(true) + + const error = Object.assign(new Error('bind failed'), { code: 'EADDRINUSE' }) + expect(() => previewServer.emit('error', error)).not.toThrow() + expect(availability?.isEnabled()).toBe(false) + }) + it('imports home state without rewriting an existing valid config', async () => { const configDir = join(tempWorkspace, '.config', 'opencode') await mkdir(configDir, { recursive: true }) diff --git a/backend/test/mocks/bun-sqlite.ts b/backend/test/mocks/bun-sqlite.ts index 724b3db8..a6b657cf 100644 --- a/backend/test/mocks/bun-sqlite.ts +++ b/backend/test/mocks/bun-sqlite.ts @@ -3,6 +3,7 @@ import { DatabaseSync } from 'node:sqlite' // Adapter to make node:sqlite compatible with bun:sqlite API export class Database { private db: DatabaseSync + private transactionDepth = 0 constructor(path: string) { this.db = new DatabaseSync(path) @@ -37,14 +38,32 @@ export class Database { transaction void>(fn: T) { return (...args: unknown[]) => { - this.db.exec('BEGIN') + const nested = this.transactionDepth > 0 + const savepoint = `ocm_sp_${this.transactionDepth}` + if (nested) { + this.db.exec(`SAVEPOINT ${savepoint}`) + } else { + this.db.exec('BEGIN') + } + this.transactionDepth += 1 try { const result = fn(...args) - this.db.exec('COMMIT') + if (nested) { + this.db.exec(`RELEASE ${savepoint}`) + } else { + this.db.exec('COMMIT') + } return result } catch (e) { - this.db.exec('ROLLBACK') + if (nested) { + this.db.exec(`ROLLBACK TO ${savepoint}`) + this.db.exec(`RELEASE ${savepoint}`) + } else { + this.db.exec('ROLLBACK') + } throw e + } finally { + this.transactionDepth -= 1 } } } diff --git a/backend/test/routes/git.test.ts b/backend/test/routes/git.test.ts index 549c6e04..4465887e 100644 --- a/backend/test/routes/git.test.ts +++ b/backend/test/routes/git.test.ts @@ -6,6 +6,9 @@ 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 type { ProjectConfigService } from '../../src/services/project-config' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' vi.mock('bun:sqlite', () => ({ @@ -60,7 +63,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, {} as unknown as ProjectConfigService, {} as unknown as RepoWorkspaceService) }) describe('GET /:id/git/status', () => { diff --git a/backend/test/routes/internal-assistant.test.ts b/backend/test/routes/internal-assistant.test.ts index b4d7f711..1de4b65f 100644 --- a/backend/test/routes/internal-assistant.test.ts +++ b/backend/test/routes/internal-assistant.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeEach, vi } from 'vitest' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { Hono } from 'hono' import { Database } from 'bun:sqlite' import { createInternalRoutes } from '../../src/routes/internal' @@ -44,7 +45,7 @@ describe('internal/assistant routes', () => { notificationService = new NotificationService(db) settingsService = new SettingsService(db) app = new Hono() - app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService)) + app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService, {} as unknown as RepoWorkspaceService)) token = getOrCreateInternalToken(db) }) diff --git a/backend/test/routes/internal-notifications.test.ts b/backend/test/routes/internal-notifications.test.ts index 2f022521..0f7cdf97 100644 --- a/backend/test/routes/internal-notifications.test.ts +++ b/backend/test/routes/internal-notifications.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeEach, vi } from 'bun:test' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { Hono } from 'hono' import { Database } from 'bun:sqlite' import { createInternalRoutes } from '../../src/routes/internal' @@ -30,7 +31,7 @@ describe('internal/notifications routes', () => { notificationService = new NotificationService(db) settingsService = new SettingsService(db) app = new Hono() - app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService)) + app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService, {} as unknown as RepoWorkspaceService)) token = getOrCreateInternalToken(db) }) diff --git a/backend/test/routes/internal-opencode-config.test.ts b/backend/test/routes/internal-opencode-config.test.ts index 185502ee..4467ac03 100644 --- a/backend/test/routes/internal-opencode-config.test.ts +++ b/backend/test/routes/internal-opencode-config.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'bun:test' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { Hono } from 'hono' import { Database } from 'bun:sqlite' import { readFile, writeFile } from 'fs/promises' @@ -60,7 +61,7 @@ describe('internal/opencode-config routes', () => { const notificationService = new NotificationService(db) const settingsService = new SettingsService(db) app = new Hono() - app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService)) + app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService, {} as unknown as RepoWorkspaceService)) token = getOrCreateInternalToken(db) }) diff --git a/backend/test/routes/internal-opencode-workspaces.test.ts b/backend/test/routes/internal-opencode-workspaces.test.ts index 7d1e740a..21b5201d 100644 --- a/backend/test/routes/internal-opencode-workspaces.test.ts +++ b/backend/test/routes/internal-opencode-workspaces.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeEach, vi } from 'vitest' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { Hono } from 'hono' import type { Database } from 'bun:sqlite' import { createInternalRoutes } from '../../src/routes/internal' @@ -83,7 +84,7 @@ describe('internal-opencode-workspaces routes', () => { forwardRaw: vi.fn(), } as unknown as OpenCodeClient app = new Hono() - app.route('/api/internal', createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService)) + app.route('/api/internal', createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService, {} as unknown as RepoWorkspaceService)) token = 'test-internal-token' }) diff --git a/backend/test/routes/internal-repos.test.ts b/backend/test/routes/internal-repos.test.ts index 2f06927f..338945b7 100644 --- a/backend/test/routes/internal-repos.test.ts +++ b/backend/test/routes/internal-repos.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeEach } from 'vitest' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { Hono } from 'hono' import { Database } from 'bun:sqlite' import { createInternalRoutes } from '../../src/routes/internal' @@ -31,7 +32,7 @@ describe('internal-repos routes', () => { notificationService = new NotificationService(db) settingsService = new SettingsService(db) app = new Hono() - app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService)) + app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService, {} as unknown as RepoWorkspaceService)) token = getOrCreateInternalToken(db) }) diff --git a/backend/test/routes/internal-sandbox.test.ts b/backend/test/routes/internal-sandbox.test.ts index 97ac967f..4a0d5bf3 100644 --- a/backend/test/routes/internal-sandbox.test.ts +++ b/backend/test/routes/internal-sandbox.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, mock, vi } from 'bun:test' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { Hono } from 'hono' import { Database } from 'bun:sqlite' import { mkdirSync, rmSync } from 'node:fs' @@ -94,7 +95,7 @@ describe('internal sandbox routes', () => { const notificationService = new NotificationService(db) settingsService = new SettingsService(db) app = new Hono() - app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService)) + app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService, {} as unknown as RepoWorkspaceService)) token = getOrCreateInternalToken(db) repoDir = path.join(getReposPath(), 'sandbox-route-test') mkdirSync(repoDir, { recursive: true }) diff --git a/backend/test/routes/internal-schedules.test.ts b/backend/test/routes/internal-schedules.test.ts index 2d5a3780..1e15ce2b 100644 --- a/backend/test/routes/internal-schedules.test.ts +++ b/backend/test/routes/internal-schedules.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeEach } from 'vitest' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { Hono } from 'hono' import { Database } from 'bun:sqlite' import { createInternalRoutes } from '../../src/routes/internal' @@ -29,7 +30,7 @@ describe('internal-schedules routes', () => { notificationService = new NotificationService(db) settingsService = new SettingsService(db) app = new Hono() - app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService)) + app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService, {} as unknown as RepoWorkspaceService)) token = getOrCreateInternalToken(db) }) diff --git a/backend/test/routes/internal-sessions.test.ts b/backend/test/routes/internal-sessions.test.ts index e19fc21a..98580c4c 100644 --- a/backend/test/routes/internal-sessions.test.ts +++ b/backend/test/routes/internal-sessions.test.ts @@ -7,6 +7,7 @@ import type { NotificationService } from '../../src/services/notification' import type { SettingsService } from '../../src/services/settings' import type { OpenCodeClient } from '../../src/services/opencode/client' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import type { Repo } from '../../src/types/repo' const mockDb = { @@ -156,7 +157,7 @@ describe('internal-sessions routes', () => { app = new Hono() app.route( '/api/internal', - createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient, permissionModes), + createInternalRoutes(mockDb, scheduleService, notificationService, settingsService, openCodeClient, permissionModes, {} as unknown as RepoWorkspaceService), ) token = 'test-internal-token' }) diff --git a/backend/test/routes/internal-settings.test.ts b/backend/test/routes/internal-settings.test.ts index 93025c6f..acf8d2cb 100644 --- a/backend/test/routes/internal-settings.test.ts +++ b/backend/test/routes/internal-settings.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeEach } from 'bun:test' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { Hono } from 'hono' import { Database } from 'bun:sqlite' import { createInternalRoutes } from '../../src/routes/internal' @@ -30,7 +31,7 @@ describe('internal/settings routes', () => { notificationService = new NotificationService(db) settingsService = new SettingsService(db) app = new Hono() - app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService)) + app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, {} as SessionPermissionModeService, {} as unknown as RepoWorkspaceService)) token = getOrCreateInternalToken(db) }) diff --git a/backend/test/routes/preview.test.ts b/backend/test/routes/preview.test.ts new file mode 100644 index 00000000..c9680051 --- /dev/null +++ b/backend/test/routes/preview.test.ts @@ -0,0 +1,223 @@ +import { describe, it, expect, afterEach } from 'vitest' +import { mkdtemp, mkdir, rm, symlink } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { ENV } from '@opencode-manager/shared/config/env' +import type { PreviewPort } from '@opencode-manager/shared/schemas' +import { createPreviewRoutes, createPreviewAvailability } from '../../src/routes/preview' +import { PreviewSessionStore } from '../../src/services/preview/gateway' +import type { PreviewPortEntry } from '../../src/services/preview/ports' + +function entry(overrides: Partial): PreviewPortEntry { + return { port: 5173, host: '127.0.0.1', pid: 1, command: 'node', cwd: null, ...overrides } +} + +const tempDirs: string[] = [] + +async function makeTempDir(): Promise { + const dir = await mkdtemp(join(tmpdir(), 'ocm-preview-')) + tempDirs.push(dir) + return dir +} + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))) +}) + +describe('Preview Routes', () => { + it('lists the directory-matching port first', async () => { + const root = await makeTempDir() + const appDir = join(root, 'app') + await mkdir(appDir) + + const app = createPreviewRoutes({ + isEnabled: () => true, + listPorts: async () => [ + entry({ port: 9000, cwd: '/somewhere/else' }), + entry({ port: 5173, cwd: appDir }), + ], + }) + + const res = await app.request(`/ports?directory=${encodeURIComponent(root)}`) + + expect(res.status).toBe(200) + const body = await res.json() as { enabled: boolean; ports: PreviewPortEntry[] } + expect(body.enabled).toBe(true) + expect(body.ports.map((port) => port.port)).toEqual([5173, 9000]) + }) + + it('sorts by port when no directory is given', async () => { + const app = createPreviewRoutes({ + isEnabled: () => true, + listPorts: async () => [entry({ port: 9000 }), entry({ port: 5173 })], + }) + + const res = await app.request('/ports') + const body = await res.json() as { ports: PreviewPortEntry[] } + + expect(body.ports.map((port) => port.port)).toEqual([5173, 9000]) + }) + + it('marks entries inside the directory and sorts them first', async () => { + const root = await makeTempDir() + const appDir = join(root, 'app') + await mkdir(appDir) + + const app = createPreviewRoutes({ + isEnabled: () => true, + listPorts: async () => [ + entry({ port: 5173, cwd: '/somewhere/else' }), + entry({ port: 9000, cwd: appDir }), + ], + }) + + const res = await app.request(`/ports?directory=${encodeURIComponent(root)}`) + const body = await res.json() as { ports: PreviewPort[] } + + expect(body.ports.map((port) => ({ port: port.port, inDirectory: port.inDirectory }))).toEqual([ + { port: 9000, inDirectory: true }, + { port: 5173, inDirectory: false }, + ]) + }) + + it('resolves symlinked cwds before matching the directory', async () => { + const root = await makeTempDir() + const realDir = join(root, 'real') + const linkDir = join(root, 'link') + await mkdir(realDir) + await symlink(realDir, linkDir) + + const app = createPreviewRoutes({ + isEnabled: () => true, + listPorts: async () => [entry({ port: 5173, cwd: linkDir })], + }) + + const res = await app.request(`/ports?directory=${encodeURIComponent(realDir)}`) + const body = await res.json() as { ports: PreviewPort[] } + + expect(body.ports[0]?.inDirectory).toBe(true) + }) + + it('marks every entry outside when no directory is given', async () => { + const app = createPreviewRoutes({ + isEnabled: () => true, + listPorts: async () => [entry({ port: 5173, cwd: '/repo' }), entry({ port: 9000, cwd: null })], + }) + + const res = await app.request('/ports') + const body = await res.json() as { ports: PreviewPort[] } + + expect(body.ports.map((port) => port.inDirectory)).toEqual([false, false]) + }) + + it('reports preview as disabled when the port is zero', async () => { + const app = createPreviewRoutes({ isEnabled: () => false, listPorts: async () => [] }) + + const res = await app.request('/ports') + + expect(await res.json()).toEqual({ enabled: false, ports: [] }) + }) + + it('issues a preview start token for a listening port', async () => { + const store = new PreviewSessionStore() + const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: 5173 })], store }) + + const res = await app.request('/sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ port: 5173 }), + }) + + expect(res.status).toBe(200) + const body = await res.json() as { token: string; previewPort: number; publicUrl: string | null } + expect(typeof body.token).toBe('string') + expect(body.token.length).toBeGreaterThan(0) + expect(body.previewPort).toBe(ENV.PREVIEW.PORT) + expect(body.publicUrl).toBe(ENV.PREVIEW.PUBLIC_URL || null) + }) + + it('rejects a reserved port with 400', async () => { + const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: ENV.PREVIEW.PORT })] }) + + const res = await app.request('/sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ port: ENV.PREVIEW.PORT }), + }) + + expect(res.status).toBe(400) + }) + + it('returns 404 for a port that is not listening', async () => { + const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: 5173 })] }) + + const res = await app.request('/sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ port: 6000 }), + }) + + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Port 6000 is not listening' }) + }) + + it('returns 503 when preview is disabled', async () => { + const app = createPreviewRoutes({ isEnabled: () => false, listPorts: async () => [entry({ port: 5173 })] }) + + const res = await app.request('/sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ port: 5173 }), + }) + + expect(res.status).toBe(503) + }) + + it('rejects an out-of-range port with 400', async () => { + const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [] }) + + const res = await app.request('/sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ port: 80 }), + }) + + expect(res.status).toBe(400) + }) + + it('reads availability at request time', async () => { + let enabled = true + const app = createPreviewRoutes({ isEnabled: () => enabled, listPorts: async () => [entry({ port: 5173 })] }) + + const first = await app.request('/ports') + expect((await first.json() as { enabled: boolean }).enabled).toBe(true) + + enabled = false + const second = await app.request('/ports') + expect((await second.json() as { enabled: boolean }).enabled).toBe(false) + + const disabledSession = await app.request('/sessions', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ port: 5173 }), + }) + expect(disabledSession.status).toBe(503) + }) +}) + +describe('Preview availability', () => { + it('starts in the provided state', () => { + expect(createPreviewAvailability(true).isEnabled()).toBe(true) + expect(createPreviewAvailability(false).isEnabled()).toBe(false) + }) + + it('tracks availability transitions', () => { + const availability = createPreviewAvailability(true) + + availability.markUnavailable() + expect(availability.isEnabled()).toBe(false) + + availability.markAvailable() + expect(availability.isEnabled()).toBe(true) + }) +}) diff --git a/backend/test/routes/repo-project-config.test.ts b/backend/test/routes/repo-project-config.test.ts new file mode 100644 index 00000000..d63117ce --- /dev/null +++ b/backend/test/routes/repo-project-config.test.ts @@ -0,0 +1,389 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { Hono } from 'hono' +import { Database } from 'bun:sqlite' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import { createRepo } from '../../src/db/queries' +import { createRepoProjectConfigRoutes } from '../../src/routes/repo-project-config' +import { ProjectConfigService } from '../../src/services/project-config' +import { createGitService } from '../../src/services/git/GitService' +import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' +import { formatTerminalTitle } from '@opencode-manager/shared/utils' +import type { GitAuthService } from '../../src/services/git-auth' +import type { CreateTerminalInput, TerminalService } from '../../src/services/terminal' +import type { TerminalInfo } from '@opencode-manager/shared/types' + +vi.mock('../../src/services/repo', () => ({ + resolveRepoWorkingDirectory: vi.fn(), + getSiblingRepos: vi.fn(), +})) + +import { resolveRepoWorkingDirectory, getSiblingRepos } from '../../src/services/repo' + +const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService +const openCodeClient = createStubOpenCodeClient() +const 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 { + const service = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService) + const app = new Hono() + app.route('/', createRepoProjectConfigRoutes(db, gitAuthService, openCodeClient, service, terminalService)) + return app +} + +function createTestDb(): Database { + const db = new Database(':memory:') + migrate(db, allMigrations) + return db +} + +function seedRepo(db: Database): void { + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) +} + +describe('Repo Project Config Routes', () => { + let db: Database + let app: Hono + + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(getSiblingRepos).mockResolvedValue([]) + vi.mocked(resolveRepoWorkingDirectory).mockImplementation(async (repo, directory) => { + if (directory === undefined || directory === repo.fullPath) return repo.fullPath + return null + }) + db = createTestDb() + app = createApp(db) + }) + + afterEach(() => { + db.close() + }) + + it('returns personal config for a ready repo', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config') + + expect(res.status).toBe(200) + const body = await res.json() as { actions: unknown[]; worktreeSetup: unknown[]; repoFile: unknown } + expect(body.actions).toEqual([]) + expect(body.worktreeSetup).toEqual([]) + expect(body.repoFile).toEqual({ + path: '.ocm/project.json', + exists: false, + trusted: false, + hash: null, + executable: null, + warnings: [], + }) + }) + + it('returns 404 for an unknown repo', async () => { + const res = await app.request('/999/project-config') + + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Repo not found' }) + }) + + it('rejects the assistant repo id when assistant access is not allowed', async () => { + const res = await app.request('/0/project-config') + + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Repo not found' }) + }) + + it('returns 404 for a repo that is not ready', async () => { + createRepo(db, { localPath: 'repo-cloning', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true }) + + const res = await app.request('/1/project-config') + + expect(res.status).toBe(404) + }) + + it('returns 400 for a non-numeric repo id', async () => { + const res = await app.request('/abc/project-config') + + expect(res.status).toBe(400) + }) + + it('round-trips personal actions with the personal source', async () => { + seedRepo(db) + const action = { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false } + + const put = await app.request('/1/project-config/actions', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ actions: [action] }), + }) + expect(put.status).toBe(200) + expect((await put.json() as { actions: unknown[] }).actions).toEqual([{ ...action, source: 'personal' }]) + + const get = await app.request('/1/project-config') + expect(get.status).toBe(200) + expect((await get.json() as { actions: unknown[] }).actions).toEqual([{ ...action, source: 'personal' }]) + }) + + it('round-trips personal worktree setup commands', async () => { + seedRepo(db) + + const put = await app.request('/1/project-config/worktree-setup', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ commands: ['pnpm install', 'pnpm build'] }), + }) + expect(put.status).toBe(200) + expect((await put.json() as { worktreeSetup: unknown[] }).worktreeSetup).toEqual([ + { command: 'pnpm install', source: 'personal' }, + { command: 'pnpm build', source: 'personal' }, + ]) + + const get = await app.request('/1/project-config') + expect((await get.json() as { worktreeSetup: unknown[] }).worktreeSetup).toEqual([ + { command: 'pnpm install', source: 'personal' }, + { command: 'pnpm build', source: 'personal' }, + ]) + }) + + it('returns 400 for schema violations on actions', async () => { + seedRepo(db) + + const bodies = [ + '{}', + JSON.stringify({ actions: 'nope' }), + JSON.stringify({ actions: [{ id: 'has space', name: 'Serve', command: 'pnpm dev' }] }), + JSON.stringify({ actions: [{ id: 'serve', name: '', command: 'pnpm dev' }] }), + JSON.stringify({ actions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', icon: 'unknown' }] }), + ] + + for (const body of bodies) { + const res = await app.request('/1/project-config/actions', { method: 'PUT', headers: jsonHeaders, body }) + expect(res.status).toBe(400) + } + }) + + it('returns 400 for schema violations on worktree setup', async () => { + seedRepo(db) + + const bodies = ['{}', JSON.stringify({ commands: 'nope' }), JSON.stringify({ commands: [''] })] + + for (const body of bodies) { + const res = await app.request('/1/project-config/worktree-setup', { method: 'PUT', headers: jsonHeaders, body }) + expect(res.status).toBe(400) + } + }) + + it('returns 400 for a foreign directory', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config?directory=/tmp/other') + + expect(res.status).toBe(400) + expect(await res.json()).toEqual({ error: 'Directory is not part of this repository' }) + }) + + it('returns 400 for an invalid trust request', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/trust', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ hash: 'not-a-hash' }), + }) + + expect(res.status).toBe(400) + }) + + it('returns 409 when trusting a stale hash', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/trust', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ hash: 'a'.repeat(64) }), + }) + + expect(res.status).toBe(409) + expect((await res.json() as { code: string }).code).toBe('REPO_CONFIG_CHANGED') + }) + + it('returns the error code and details for an untrusted repository action', async () => { + seedRepo(db) + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-route-untrusted-')) + vi.mocked(resolveRepoWorkingDirectory).mockResolvedValue(directory) + const repoFileDir = path.join(directory, '.ocm') + fs.mkdirSync(repoFileDir, { recursive: true }) + fs.writeFileSync( + path.join(repoFileDir, 'project.json'), + JSON.stringify({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }), + ) + + try { + const res = await app.request('/1/project-config/actions/repo-serve/run', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({}), + }) + + expect(res.status).toBe(409) + const body = await res.json() as { code: string; details: { hash: string } } + expect(body.code).toBe('REPO_CONFIG_UNTRUSTED') + expect(body.details.hash).toMatch(/^[a-f0-9]{64}$/) + } finally { + fs.rmSync(directory, { recursive: true, force: true }) + } + }) + + it('returns 400 for an invalid move request', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/move', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ kind: 'action', id: 'serve', to: 'nowhere' }), + }) + + expect(res.status).toBe(400) + }) + + it('returns 404 when moving an unknown item', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/move', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ kind: 'action', id: 'missing', to: 'repo' }), + }) + + expect(res.status).toBe(404) + }) + + it('moves a personal action into the repo file and returns it as trusted', async () => { + seedRepo(db) + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-route-move-')) + vi.mocked(resolveRepoWorkingDirectory).mockResolvedValue(directory) + const action = { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false } + + try { + await app.request('/1/project-config/actions', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ actions: [action] }), + }) + + const res = await app.request('/1/project-config/move', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ kind: 'action', id: 'serve', to: 'repo' }), + }) + + expect(res.status).toBe(200) + const body = await res.json() as { actions: unknown[]; repoFile: { exists: boolean; trusted: boolean } } + expect(body.repoFile.exists).toBe(true) + expect(body.repoFile.trusted).toBe(true) + expect(body.actions).toEqual([{ ...action, source: 'repo' }]) + } finally { + fs.rmSync(directory, { recursive: true, force: true }) + } + }) + + it('returns 409 when moving a setup command into a repository already at capacity', async () => { + seedRepo(db) + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-route-move-')) + vi.mocked(resolveRepoWorkingDirectory).mockResolvedValue(directory) + + try { + await app.request('/1/project-config/worktree-setup', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ commands: ['personal-cmd'] }), + }) + const repoFileDir = path.join(directory, '.ocm') + fs.mkdirSync(repoFileDir, { recursive: true }) + fs.writeFileSync( + path.join(repoFileDir, 'project.json'), + JSON.stringify({ version: 1, setupWorktree: Array.from({ length: 20 }, (_, index) => `repo-${index}`) }), + ) + + const res = await app.request('/1/project-config/move', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ kind: 'setup', command: 'personal-cmd', to: 'repo' }), + }) + + expect(res.status).toBe(409) + expect((await res.json() as { code: string }).code).toBe('PROJECT_CONFIG_LIMIT_EXCEEDED') + } finally { + 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/routes/repo-terminal-socket.test.ts b/backend/test/routes/repo-terminal-socket.test.ts new file mode 100644 index 00000000..f82c9f69 --- /dev/null +++ b/backend/test/routes/repo-terminal-socket.test.ts @@ -0,0 +1,338 @@ +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest' +import { randomBytes } from 'node:crypto' +import { request as httpRequest } from 'node:http' +import { Hono } from 'hono' +import { cors } from 'hono/cors' +import { serve } from '@hono/node-server' +import { createNodeWebSocket } from '@hono/node-ws' +import type { Server } from 'node:http' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { createRepoTerminalSocketRoutes } from '../../src/routes/repo-terminal-socket' +import { TerminalService } from '../../src/services/terminal' +import type { GitAuthService } from '../../src/services/git-auth' +import type { OpenCodeClient } from '../../src/services/opencode/client' +import type { CredentialProvider } from '../../src/services/credential-provider' + +vi.mock('../../src/services/repo', () => ({ + resolveRepoOrAssistant: vi.fn(), + resolveRepoWorkingDirectory: vi.fn(), + getSiblingRepos: vi.fn(), +})) + +import { resolveRepoOrAssistant, resolveRepoWorkingDirectory, getSiblingRepos } from '../../src/services/repo' + +const readyRepo = { id: 1, fullPath: '/tmp/repo', cloneStatus: 'ready' } as Repo +const database = {} as Database +const gitAuthService = { getGitEnvironment: vi.fn(() => ({})) } as unknown as GitAuthService + +function createPty(id: string) { + return { id, title: 'Terminal', command: 'sh', args: [], cwd: '/tmp/repo', status: 'running' as const, pid: 1 } +} + +const openCodeClient = { + api: { + pty: { + list: vi.fn(async ({ location }: { location: { directory: string } }) => ({ + location, + data: [createPty('pty-1'), createPty('pty-4404')], + })), + connect: { + token: vi.fn(async () => ({ + location: { directory: '/tmp/repo' }, + data: { ticket: 'stub-ticket', expires_in: 60 }, + })), + }, + }, + }, +} as unknown as OpenCodeClient + +const credentialProvider = { getGhCliEnv: vi.fn(() => ({})) } as unknown as CredentialProvider + +let upstreamServer: Server +let managerServer: Server +let managerPort = 0 +let upstreamBase = '' +let capturedUrl: URL | undefined + +const upstreamApp = new Hono() +const upstreamWs = createNodeWebSocket({ app: upstreamApp }) +const textEncoder = new TextEncoder() + +upstreamApp.get( + '/api/pty/:ptyID/connect', + upstreamWs.upgradeWebSocket((c) => { + capturedUrl = new URL(c.req.url) + const ptyID = c.req.param('ptyID') + return { + onOpen(_event, ws) { + if (ptyID === 'pty-4404') { + ws.close(4404, 'gone') + return + } + ws.send(new Uint8Array([0, ...textEncoder.encode('{"cursor":0}')])) + }, + onMessage(event, ws) { + if (typeof event.data === 'string') ws.send(event.data) + }, + } + }), +) + +const terminalService = new TerminalService(openCodeClient, credentialProvider, () => upstreamBase) + +const managerApp = new Hono() +const managerWs = createNodeWebSocket({ app: managerApp }) +managerApp.route( + '/', + createRepoTerminalSocketRoutes( + database, + gitAuthService, + openCodeClient, + terminalService, + managerWs.upgradeWebSocket, + ), +) + +const TRUSTED_ORIGIN = 'http://localhost:5003' +const authenticatedApp = new Hono() +const authenticatedWs = createNodeWebSocket({ app: authenticatedApp }) +authenticatedApp.use('/*', cors()) +authenticatedApp.use('/*', async (c, next) => { + const cookie = c.req.header('cookie') ?? '' + if (!cookie.includes('session=valid')) { + return c.json({ error: 'Unauthorized' }, 401) + } + await next() +}) +authenticatedApp.route( + '/', + createRepoTerminalSocketRoutes( + database, + gitAuthService, + openCodeClient, + terminalService, + authenticatedWs.upgradeWebSocket, + [TRUSTED_ORIGIN], + ), +) + +let authenticatedServer: Server +let authenticatedPort = 0 + +interface RawHandshakeResult { + upgraded: boolean + status?: number +} + +function rawHandshake(options: { port: number; path: string; origin?: string; cookie?: string }): Promise { + return new Promise((resolve, reject) => { + const headers: Record = { + Connection: 'Upgrade', + Upgrade: 'websocket', + 'Sec-WebSocket-Key': randomBytes(16).toString('base64'), + 'Sec-WebSocket-Version': '13', + } + if (options.origin !== undefined) headers.Origin = options.origin + if (options.cookie) headers.Cookie = options.cookie + + const request = httpRequest({ host: '127.0.0.1', port: options.port, path: options.path, method: 'GET', headers }) + let settled = false + request.on('upgrade', (_res, socket) => { + settled = true + socket.destroy() + resolve({ upgraded: true }) + }) + request.on('response', (res) => { + settled = true + res.resume() + resolve({ upgraded: false, status: res.statusCode }) + }) + request.on('error', (error) => { + if (!settled) reject(error) + }) + request.end() + }) +} + +function listen(server: Server): Promise { + return new Promise((resolve) => { + if (server.listening) { + resolve(readPort(server)) + return + } + server.once('listening', () => resolve(readPort(server))) + }) +} + +function readPort(server: Server): number { + const address = server.address() + if (address && typeof address === 'object') return address.port + throw new Error('Server is not listening on a TCP port') +} + +function closeServer(server: Server): Promise { + server.closeAllConnections() + return new Promise((resolve) => server.close(() => resolve())) +} + +function clientUrl(ptyID: string, directory = '/tmp/repo'): string { + const url = new URL(`ws://127.0.0.1:${managerPort}/1/terminals/${ptyID}/connect`) + url.searchParams.set('directory', directory) + return url.toString() +} + +function openEvent(socket: WebSocket): Promise { + return new Promise((resolve, reject) => { + if (socket.readyState === WebSocket.OPEN) { + resolve() + return + } + socket.addEventListener('open', () => resolve(), { once: true }) + socket.addEventListener('error', () => reject(new Error('WebSocket error before open')), { once: true }) + }) +} + +function settle(socket: WebSocket): Promise<'open' | 'error' | 'close'> { + return new Promise((resolve) => { + socket.addEventListener('open', () => resolve('open'), { once: true }) + socket.addEventListener('error', () => resolve('error'), { once: true }) + socket.addEventListener('close', () => resolve('close'), { once: true }) + }) +} + +async function waitFor(predicate: () => boolean, timeoutMs = 5000): Promise { + const start = Date.now() + while (!predicate()) { + if (Date.now() - start > timeoutMs) throw new Error('Timed out waiting for condition') + await new Promise((resolve) => setTimeout(resolve, 10)) + } +} + +beforeAll(async () => { + upstreamServer = serve({ fetch: upstreamApp.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server + upstreamWs.injectWebSocket(upstreamServer) + upstreamBase = `http://127.0.0.1:${await listen(upstreamServer)}` + + managerServer = serve({ fetch: managerApp.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server + managerWs.injectWebSocket(managerServer) + managerPort = await listen(managerServer) + + authenticatedServer = serve({ fetch: authenticatedApp.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server + authenticatedWs.injectWebSocket(authenticatedServer) + authenticatedPort = await listen(authenticatedServer) + + 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([]) +}) + +afterAll(async () => { + upstreamWs.wss.close() + managerWs.wss.close() + authenticatedWs.wss.close() + await closeServer(upstreamServer) + await closeServer(managerServer) + await closeServer(authenticatedServer) +}) + +describe('Repo Terminal Socket Route', () => { + it('bridges the binary meta frame and echoes text through the upstream', async () => { + const socket = new WebSocket(clientUrl('pty-1')) + socket.binaryType = 'arraybuffer' + const messages: Array = [] + socket.addEventListener('message', (event) => { + messages.push(event.data as string | ArrayBuffer) + }) + + await openEvent(socket) + await waitFor(() => messages.length === 1) + + const meta = messages[0] + expect(meta).toBeInstanceOf(ArrayBuffer) + const bytes = new Uint8Array(meta as ArrayBuffer) + expect(bytes[0]).toBe(0) + expect(new TextDecoder().decode(bytes.subarray(1))).toBe('{"cursor":0}') + + socket.send('echo me') + await waitFor(() => messages.length === 2) + expect(messages[1]).toBe('echo me') + + expect(capturedUrl?.searchParams.get('ticket')).toBe('stub-ticket') + expect(capturedUrl?.searchParams.get('location[directory]')).toBe('/tmp/repo') + + socket.close() + }) + + it('fails the handshake for a directory outside the repository', async () => { + const socket = new WebSocket(clientUrl('pty-1', '/tmp/other')) + + const outcome = await settle(socket) + + expect(outcome).not.toBe('open') + socket.close() + }) + + it('propagates an upstream 4404 close to the client', async () => { + const socket = new WebSocket(clientUrl('pty-4404')) + + const closeEvent = await new Promise((resolve, reject) => { + socket.addEventListener('close', (event) => resolve(event), { once: true }) + socket.addEventListener('error', () => reject(new Error('WebSocket error before close')), { once: true }) + }) + + expect(closeEvent.code).toBe(4404) + }) +}) + +describe('Repo Terminal Socket Origin validation', () => { + const path = `/1/terminals/pty-1/connect?directory=${encodeURIComponent('/tmp/repo')}` + + it('accepts a trusted Origin with a valid session cookie', async () => { + const outcome = await rawHandshake({ + port: authenticatedPort, + path, + origin: TRUSTED_ORIGIN, + cookie: 'session=valid', + }) + + expect(outcome).toEqual({ upgraded: true }) + }) + + it('allows a non-browser client without an Origin header', async () => { + const outcome = await rawHandshake({ port: authenticatedPort, path, cookie: 'session=valid' }) + + expect(outcome).toEqual({ upgraded: true }) + }) + + it('rejects an untrusted same-site Origin before the upgrade', async () => { + const outcome = await rawHandshake({ + port: authenticatedPort, + path, + origin: 'http://localhost:5004', + cookie: 'session=valid', + }) + + expect(outcome).toEqual({ upgraded: false, status: 403 }) + }) + + it('rejects a null Origin before the upgrade', async () => { + const outcome = await rawHandshake({ + port: authenticatedPort, + path, + origin: 'null', + cookie: 'session=valid', + }) + + expect(outcome).toEqual({ upgraded: false, status: 403 }) + }) + + it('rejects the upgrade without a session cookie', async () => { + const outcome = await rawHandshake({ port: authenticatedPort, path, origin: TRUSTED_ORIGIN }) + + expect(outcome).toEqual({ upgraded: false, status: 401 }) + }) +}) diff --git a/backend/test/routes/repo-terminals.test.ts b/backend/test/routes/repo-terminals.test.ts new file mode 100644 index 00000000..5e824041 --- /dev/null +++ b/backend/test/routes/repo-terminals.test.ts @@ -0,0 +1,245 @@ +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 assistantRepo = { id: 0, 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 : id === 0 ? assistantRepo : 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('resolves the assistant repo when assistant access is allowed', async () => { + const terminals = [{ ...shellTerminal }] + const list = vi.fn(async () => terminals) + const res = await createApp(createService({ list })).request('/0/terminals') + + expect(res.status).toBe(200) + expect(list).toHaveBeenCalledWith('/tmp/repo') + }) + + 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-git-identity.test.ts b/backend/test/routes/repos-git-identity.test.ts index d29b8500..04d19916 100644 --- a/backend/test/routes/repos-git-identity.test.ts +++ b/backend/test/routes/repos-git-identity.test.ts @@ -15,6 +15,9 @@ import { createWorktreeSafely } from '../../src/services/repo' import { syncManagerGitIdentityConfig } from '../../src/services/git-identity' import { createGitAuthService, cloneOrigin, createOrigin, git, uniqueName } from '../helpers/git-fixtures' import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' +import type { TerminalService } from '../../src/services/terminal' +import type { ProjectConfigService } from '../../src/services/project-config' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' const workspaceRoot = mkdtempSync(path.join(tmpdir(), 'repos-git-identity-')) const homeDir = path.join(workspaceRoot, 'home') @@ -49,7 +52,7 @@ describe('repo git identity routes', () => { mkdirSync(reposPath, { recursive: true }) const scheduleService = { prepareRepoDelete: () => {} } as unknown as Parameters[2] app = new Hono() - app.route('/repos', createRepoRoutes(db, createGitAuthService(), scheduleService, createStubOpenCodeClient())) + app.route('/repos', createRepoRoutes(db, createGitAuthService(), scheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService, {} as unknown as ProjectConfigService, {} as unknown as RepoWorkspaceService)) }) afterEach(() => { diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts index 5574e819..bb9342f4 100644 --- a/backend/test/routes/repos.test.ts +++ b/backend/test/routes/repos.test.ts @@ -1,4 +1,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' import type { Database } from 'bun:sqlite' import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' @@ -20,6 +23,8 @@ vi.mock('../../src/db/queries', () => ({ getRepoGitCredentialId: vi.fn(), setRepoGitCredentialId: vi.fn(), updateRepoName: vi.fn(), + getRepoSetting: vi.fn(), + setRepoSetting: vi.fn(), })) vi.mock('../../src/services/repo', () => ({ @@ -32,6 +37,10 @@ vi.mock('../../src/services/repo', () => ({ createBranch: vi.fn(), deleteRepoFiles: vi.fn(), getSiblingRepos: vi.fn(), + resolveRepoOrAssistant: vi.fn(), + findSiblingByDirectory: vi.fn(), + resolveRepoWorkingDirectory: vi.fn(), + resolveRepoProjectId: vi.fn(), })) vi.mock('../../src/services/assistant-mode', () => ({ @@ -73,12 +82,17 @@ import * as repoService from '../../src/services/repo' import * as archiveService from '../../src/services/archive' import { createRepoRoutes } from '../../src/routes/repos' import { opencodeServerManager } from '../../src/services/opencode-single-server' +import { ProjectConfigService } from '../../src/services/project-config' +import { RepoWorkspaceService } from '../../src/services/repo-workspace' +import { createGitService } from '../../src/services/git/GitService' 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' import { getAssistantModeStatus, ensureAssistantMode, buildAssistantRepo } from '../../src/services/assistant-mode' +import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' const mockGitAuthService = { getGitEnvironment: vi.fn().mockReturnValue({}) @@ -89,6 +103,17 @@ const mockScheduleService = { prepareRepoDelete: mockPrepareRepoDelete, } as unknown as ScheduleService +const mockTerminalService = { + removeAll: vi.fn().mockResolvedValue(undefined), + create: vi.fn(), +} as unknown as TerminalService + +function createTestRoutes(openCodeClient: ReturnType = createStubOpenCodeClient()): ReturnType { + const projectConfigService = new ProjectConfigService(mockDb, createGitService(mockGitAuthService), mockGitAuthService) + const repoWorkspaces = new RepoWorkspaceService(mockDb, openCodeClient, mockGitAuthService, projectConfigService, mockTerminalService) + return createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, openCodeClient, mockTerminalService, projectConfigService, repoWorkspaces) +} + function createMockRepo(overrides: Partial = {}): Repo { return { id: 1, @@ -118,13 +143,18 @@ describe('Repo Routes', () => { updatedAt: Date.now(), }) vi.mocked(db.getRepoGitCredentialId).mockReturnValue(null) + vi.mocked(db.getRepoSetting).mockReturnValue(null) + vi.mocked(repoService.resolveRepoProjectId).mockResolvedValue('commit-A') + vi.mocked(repoService.resolveRepoOrAssistant).mockImplementation( + (_database, id) => vi.mocked(db.getRepoById)(_database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null), + ) }) describe('POST /:id/access', () => { 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) @@ -147,7 +177,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) @@ -173,7 +203,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) @@ -186,7 +216,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) @@ -221,7 +251,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) @@ -237,7 +267,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' }, @@ -276,7 +306,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' }, @@ -315,7 +345,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' }, @@ -330,7 +360,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) @@ -354,7 +384,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' }) @@ -376,7 +406,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 } }, @@ -396,7 +426,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' }, @@ -412,7 +442,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' }, @@ -429,7 +459,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' }, @@ -451,7 +481,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' }, @@ -464,9 +494,109 @@ describe('Repo Routes', () => { }) }) - describe('POST /discover', () => { - it('should return 400 for an invalid body', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + describe('POST /:id/workspaces', () => { + it('creates the workspace and returns the worktree setup result', async () => { + vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' })) + + const app = createTestRoutes() + const res = await app.request('/1/workspaces', { method: 'POST' }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ directory: '/tmp/wrk-test', worktreeSetup: { status: 'none' } }) + }) + + it('returns 200 with a failed worktree setup when the setup terminal cannot start', async () => { + vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' })) + vi.mocked(db.getRepoSetting).mockImplementation((_database, _repoId, key) => + key === 'worktreeSetupCommands' ? JSON.stringify(['pnpm install']) : null, + ) + vi.mocked(mockTerminalService.create).mockRejectedValueOnce(new Error('spawn failed')) + + const app = createTestRoutes() + const res = await app.request('/1/workspaces', { method: 'POST' }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ + directory: '/tmp/wrk-test', + worktreeSetup: { status: 'failed', error: 'spawn failed' }, + }) + }) + + it('runs the main project setup when a linked worktree row creates a workspace', async () => { + const worktreeDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-workspace-')) + const repoFile = { version: 1 as const, setupWorktree: ['pnpm repo-setup'] } + fs.mkdirSync(path.join(worktreeDirectory, '.ocm'), { recursive: true }) + fs.writeFileSync(path.join(worktreeDirectory, '.ocm', 'project.json'), JSON.stringify(repoFile)) + const hash = new ProjectConfigService(mockDb, {} as never, mockGitAuthService).hashRepoFile(repoFile) + + vi.mocked(db.getRepoById).mockReturnValue( + createMockRepo({ id: 2, fullPath: '/tmp/repos/worktree', isWorktree: true }), + ) + vi.mocked(db.getRepoSetting).mockImplementation((_database, repoId, key) => { + if (repoId !== 1) return null + if (key === 'worktreeSetupCommands') return JSON.stringify(['pnpm install']) + if (key === 'repoConfigTrustHash') return hash + return null + }) + const mainRepo = createMockRepo({ id: 1, fullPath: '/tmp/repos/main' }) + const resolveSpy = vi + .spyOn(ProjectConfigService.prototype, 'resolveProjectRepo') + .mockResolvedValue(mainRepo) + const client = createStubOpenCodeClient() + client.api.worktree.create = vi.fn(async () => ({ directory: worktreeDirectory })) as never + vi.mocked(mockTerminalService.create).mockResolvedValue({ + id: 'pty-setup', + title: 'Worktree setup', + kind: 'setup', + cwd: worktreeDirectory, + status: 'running', + }) + + try { + const app = createTestRoutes(client) + const res = await app.request('/2/workspaces', { method: 'POST' }) + + expect(res.status).toBe(200) + const body = (await res.json()) as { worktreeSetup: { status: string; repoCommandsSkipped: boolean } } + expect(body.worktreeSetup).toMatchObject({ status: 'started', repoCommandsSkipped: false }) + expect(vi.mocked(mockTerminalService.create)).toHaveBeenCalledWith(worktreeDirectory, { + kind: 'setup', + name: 'Worktree setup', + command: '/bin/sh', + args: ['-c', 'set -e\npnpm install\npnpm repo-setup'], + env: { ROOT_PROJECT_PATH: '/tmp/repos/main' }, + }) + } finally { + resolveSpy.mockRestore() + fs.rmSync(worktreeDirectory, { recursive: true, force: true }) + } + }) + + it('returns 200 with a failed setup when resolving the main project fails', async () => { + vi.mocked(db.getRepoById).mockReturnValue( + createMockRepo({ id: 2, fullPath: '/tmp/repos/worktree', isWorktree: true }), + ) + const resolveSpy = vi + .spyOn(ProjectConfigService.prototype, 'resolveProjectRepo') + .mockRejectedValue(new Error('git unavailable')) + + try { + const app = createTestRoutes() + const res = await app.request('/2/workspaces', { method: 'POST' }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ + directory: '/tmp/wrk-test', + worktreeSetup: { status: 'failed', error: 'git unavailable' }, + }) + } finally { + resolveSpy.mockRestore() + } + }) + }) + + describe('POST /discover', () => { it('should return 400 for an invalid body', async () => { + const app = createTestRoutes() const res = await app.request('/discover', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -481,7 +611,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' }, @@ -497,7 +627,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' }, @@ -518,7 +648,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) @@ -536,7 +666,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) @@ -547,7 +677,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' }, @@ -559,7 +689,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' }, @@ -573,7 +703,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' }, @@ -589,7 +719,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) @@ -601,7 +731,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) @@ -611,7 +741,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) @@ -624,7 +754,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' }, @@ -638,7 +768,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' }, @@ -657,7 +787,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' }, @@ -674,7 +804,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' }, @@ -690,7 +820,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' }, @@ -703,7 +833,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) @@ -712,7 +842,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) @@ -722,13 +852,57 @@ 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) + }) + + it('removes terminals for OpenCode workspace siblings but not manager worktree repos', async () => { + vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' })) + vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined) + vi.mocked(repoService.getSiblingRepos).mockResolvedValue([ + { ...createMockRepo({ id: 2, fullPath: '/tmp/repos/manager-worktree', isWorktree: true }), currentBranch: undefined }, + { ...createMockRepo({ id: -1, fullPath: '/tmp/plugin-workspace' }), currentBranch: undefined, worktreeStrategy: 'git' }, + ]) + + const app = createTestRoutes() + const res = await app.request('/1', { method: 'DELETE' }) + + expect(res.status).toBe(200) + expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/repos/test-repo') + expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/plugin-workspace') + expect(mockTerminalService.removeAll).not.toHaveBeenCalledWith('/tmp/repos/manager-worktree') + expect(repoService.getSiblingRepos).toHaveBeenCalledWith(mockDb, 1, {}, expect.anything(), { includeBranch: false }) + expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1) + }) + + it('still deletes the repo when listing workspace siblings throws', async () => { + vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) + vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined) + vi.mocked(repoService.getSiblingRepos).mockRejectedValue(new Error('siblings failed')) + + const app = createTestRoutes() + const res = await app.request('/1', { method: 'DELETE' }) + + expect(res.status).toBe(200) expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1) }) @@ -736,7 +910,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) @@ -751,7 +925,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) @@ -763,7 +937,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) @@ -776,7 +950,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' }, @@ -789,7 +963,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' }, @@ -805,7 +979,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' }, @@ -822,7 +996,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' }, @@ -839,7 +1013,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' }, @@ -852,7 +1026,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' }, @@ -868,7 +1042,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' }, @@ -885,7 +1059,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' }, @@ -902,7 +1076,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) @@ -917,7 +1091,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) @@ -940,7 +1114,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) @@ -956,7 +1130,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' }) @@ -975,7 +1149,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() } }, @@ -1006,7 +1180,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) @@ -1029,7 +1203,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' }, @@ -1047,7 +1221,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/assistant-mode.test.ts b/backend/test/services/assistant-mode.test.ts index 0b10972c..fa630bac 100644 --- a/backend/test/services/assistant-mode.test.ts +++ b/backend/test/services/assistant-mode.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, beforeEach, afterEach } from 'bun:test' import type { SessionPermissionModeService } from '../../src/services/session-permission-modes' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import path from 'path' import { access, readFile, writeFile } from 'fs/promises' import { Hono } from 'hono' @@ -686,7 +687,7 @@ describe('assistant-mode end-to-end', () => { const notificationService = new NotificationService(db) const settingsService = new SettingsService(db) const app = new Hono() - app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, createOpenCodeClient(), {} as SessionPermissionModeService)) + app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, createOpenCodeClient(), {} as SessionPermissionModeService, {} as unknown as RepoWorkspaceService)) const unauth = await app.request('/api/internal/schedules/all') expect(unauth.status).toBe(401) diff --git a/backend/test/services/git/GitService.real.test.ts b/backend/test/services/git/GitService.real.test.ts index 77c19d88..f3a45adf 100644 --- a/backend/test/services/git/GitService.real.test.ts +++ b/backend/test/services/git/GitService.real.test.ts @@ -17,6 +17,9 @@ import { cloneOrigin, createCommittedRepo, createGitAuthService, createOrigin, g import { GitOperationError, parseGitError } from '../../../src/utils/git-errors' import type { GitAuthService } from '../../../src/services/git-auth' import type { Repo } from '../../../src/types/repo' +import type { TerminalService } from '../../../src/services/terminal' +import type { ProjectConfigService } from '../../../src/services/project-config' +import type { RepoWorkspaceService } from '../../../src/services/repo-workspace' const workspaceRoot = mkdtempSync(path.join(tmpdir(), 'git-service-real-')) process.env.WORKSPACE_PATH = workspaceRoot @@ -1073,7 +1076,12 @@ describe('GitService real git', () => { function createDeleteApp(): Hono { const app = new Hono() const scheduleService = { prepareRepoDelete: () => {} } as unknown as Parameters[2] - app.route('/repos', createRepoRoutes(db, gitAuth, scheduleService, createStubOpenCodeClient())) + const repoWorkspaces = { + create: async () => ({ directory: '' }), + remove: async () => undefined, + removeRepoTerminals: async () => undefined, + } as unknown as RepoWorkspaceService + app.route('/repos', createRepoRoutes(db, gitAuth, scheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService, {} as unknown as ProjectConfigService, repoWorkspaces)) return app } diff --git a/backend/test/services/multi-runs.test.ts b/backend/test/services/multi-runs.test.ts index 81e930a5..eee0f9cc 100644 --- a/backend/test/services/multi-runs.test.ts +++ b/backend/test/services/multi-runs.test.ts @@ -5,7 +5,9 @@ import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' import { createMultiRunWithEntries } from '../../src/db/multi-runs' import { MultiRunError, MultiRunService } from '../../src/services/multi-runs' -import type { GitAuthService } from '../../src/services/git-auth' +import { RepoWorkspaceError } from '../../src/services/repo' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' +import type { Repo } from '../../src/types/repo' import type { OpenCodeClient } from '../../src/services/opencode/client' const REPO_DIR = '/repos/repo-a' @@ -40,40 +42,54 @@ interface FakeMultiRunClient { client: OpenCodeClient sessionCreate: ReturnType sessionPrompt: ReturnType - worktreeCreate: ReturnType - worktreeList: ReturnType - worktreeRemove: ReturnType - workspaces: Array<{ directory: string; strategy: string }> } function createClient(): FakeMultiRunClient { let sessionCounter = 0 - const workspaces: Array<{ directory: string; strategy: string }> = [] const sessionCreate = vi.fn(async (input: { title?: string }) => { sessionCounter += 1 return { id: `ses_${sessionCounter}`, title: input?.title } }) const sessionPrompt = vi.fn(async () => ({})) - const worktreeCreate = vi.fn(async (input: { name?: string }) => { - const directory = `/worktrees/${input.name ?? 'workspace'}` - workspaces.push({ directory, strategy: 'git' }) - return { directory } - }) - const worktreeList = vi.fn(async () => workspaces) - const worktreeRemove = vi.fn(async () => undefined) const client = { api: { - location: { - get: vi.fn(async () => ({ project: { id: 'commit-A', directory: REPO_DIR, canonical: REPO_DIR } })), - }, - worktree: { create: worktreeCreate, list: worktreeList, remove: worktreeRemove }, session: { create: sessionCreate, prompt: sessionPrompt }, }, } as unknown as OpenCodeClient - return { client, sessionCreate, sessionPrompt, worktreeCreate, worktreeList, worktreeRemove, workspaces } + return { client, sessionCreate, sessionPrompt } +} + +interface FakeRepoWorkspaces { + service: RepoWorkspaceService + create: ReturnType + remove: ReturnType + removeRepoTerminals: ReturnType +} + +function createRepoWorkspaces(): FakeRepoWorkspaces { + const known = new Set() + const create = vi.fn(async (_repo: Repo, options: { name?: string } = {}) => { + const directory = `/worktrees/${options.name ?? 'workspace'}` + known.add(directory) + return { directory, worktreeSetup: { status: 'none' as const } } + }) + const remove = vi.fn(async (_repo: Repo, directory: string) => { + if (!known.has(directory)) { + throw new RepoWorkspaceError('Not a deletable worktree of this repo', 400) + } + known.delete(directory) + }) + const removeRepoTerminals = vi.fn(async () => undefined) + + return { + service: { create, remove, removeRepoTerminals } as unknown as RepoWorkspaceService, + create, + remove, + removeRepoTerminals, + } } describe('MultiRunService', () => { @@ -119,15 +135,15 @@ describe('MultiRunService', () => { return repo.id } - function createService(client: OpenCodeClient): MultiRunService { - const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService - return new MultiRunService(db, client, gitAuthService) + function createService(client: OpenCodeClient, repoWorkspaces: RepoWorkspaceService): MultiRunService { + return new MultiRunService(db, client, repoWorkspaces) } it('launches one session per model, each in its own workspace named from the group', async () => { const repoId = readyRepo() - const { client, sessionCreate, sessionPrompt, worktreeCreate } = createClient() - const service = createService(client) + const { client, sessionCreate, sessionPrompt } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -162,19 +178,20 @@ describe('MultiRunService', () => { sessionCreate.mock.calls.map((call) => `${call[0].model.providerID}/${call[0].model.id}`).sort(), ).toEqual(['openai/a', 'openai/b', 'openai/c']) - const workspaceCalls = worktreeCreate.mock.calls.map((call) => call[0]) + const workspaceCalls = repoWorkspaces.create.mock.calls.map((call) => call[1]) expect(workspaceCalls.map((call) => call.name).sort()).toEqual([ 'Feature-Sweep-1', 'Feature-Sweep-2', 'Feature-Sweep-3', ]) - expect(workspaceCalls.every((call) => call.branch === 'develop')).toBe(true) + expect(workspaceCalls.every((call) => call.ref === 'develop')).toBe(true) }) it('keeps launching the other models when one model fails', async () => { const repoId = readyRepo() - const { client, worktreeCreate } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -189,13 +206,14 @@ describe('MultiRunService', () => { expect(run.entries[1]!.sessionId).toBeNull() expect(run.entries[0]!.sessionId).toBeTruthy() expect(run.entries[2]!.sessionId).toBeTruthy() - expect(worktreeCreate).not.toHaveBeenCalled() + expect(repoWorkspaces.create).not.toHaveBeenCalled() }) it('does not create workspaces when isolation is off', async () => { const repoId = readyRepo() - const { client, worktreeCreate } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -208,12 +226,13 @@ describe('MultiRunService', () => { expect(run.entries.map((entry) => entry.status)).toEqual(['started', 'started']) expect(run.entries.every((entry) => entry.directory === REPO_DIR)).toBe(true) expect(run.entries.every((entry) => entry.isolated === false)).toBe(true) - expect(worktreeCreate).not.toHaveBeenCalled() + expect(repoWorkspaces.create).not.toHaveBeenCalled() }) it('rejects a repository that is not ready', async () => { const { client } = createClient() - const service = createService(client) + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const error = await service .launch({ repoId: 999, name: 'Sweep', prompt: 'go', models: ['openai/a'], isolate: false }) @@ -225,8 +244,9 @@ describe('MultiRunService', () => { it('removes the workspace when discarding an isolated entry', async () => { const repoId = readyRepo() - const { client, worktreeRemove } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -241,17 +261,17 @@ describe('MultiRunService', () => { const discarded = await service.discard(run.id, entry.id) expect(discarded.entries[0]!.status).toBe('discarded') - expect(worktreeRemove).toHaveBeenCalledWith({ - projectID: 'commit-A', - directory: '/worktrees/Sweep-1', - force: true, - }) + expect(repoWorkspaces.remove).toHaveBeenCalledWith( + expect.objectContaining({ id: repoId }), + '/worktrees/Sweep-1', + ) }) it('rejects discarding an entry twice', async () => { const repoId = readyRepo() - const { client, worktreeRemove } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -267,13 +287,14 @@ describe('MultiRunService', () => { expect(error).toBeInstanceOf(MultiRunError) expect(error).toMatchObject({ status: 409 }) - expect(worktreeRemove).toHaveBeenCalledTimes(1) + expect(repoWorkspaces.remove).toHaveBeenCalledTimes(1) }) it('does not remove a workspace when discarding a non-isolated entry', async () => { const repoId = readyRepo() - const { client, worktreeRemove } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -286,13 +307,14 @@ describe('MultiRunService', () => { const discarded = await service.discard(run.id, run.entries[0]!.id) expect(discarded.entries[0]!.status).toBe('discarded') - expect(worktreeRemove).not.toHaveBeenCalled() + expect(repoWorkspaces.remove).not.toHaveBeenCalled() }) it('fails only the entry whose model is unavailable and creates no workspace for it', async () => { const repoId = readyRepo() - const { client, worktreeCreate, worktreeRemove } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -309,15 +331,16 @@ describe('MultiRunService', () => { expect(run.entries[0]!.directory).toBe('/worktrees/Sweep-1') expect(run.entries[2]!.directory).toBe('/worktrees/Sweep-3') - expect(worktreeCreate).toHaveBeenCalledTimes(2) - expect(worktreeCreate.mock.calls.map((call) => call[0].name).sort()).toEqual(['Sweep-1', 'Sweep-3']) - expect(worktreeRemove).not.toHaveBeenCalled() + expect(repoWorkspaces.create).toHaveBeenCalledTimes(2) + expect(repoWorkspaces.create.mock.calls.map((call) => call[1].name).sort()).toEqual(['Sweep-1', 'Sweep-3']) + expect(repoWorkspaces.remove).not.toHaveBeenCalled() }) it('marks an isolated entry discarded when its workspace directory is gone', async () => { const repoId = readyRepo() - const { client, worktreeRemove } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -333,13 +356,14 @@ describe('MultiRunService', () => { const discarded = await service.discard(run.id, entry.id) expect(discarded.entries[0]!.status).toBe('discarded') - expect(worktreeRemove).not.toHaveBeenCalled() + expect(repoWorkspaces.remove).not.toHaveBeenCalled() }) it('maps a workspace that is not a deletable sibling to 400 and keeps the entry retryable', async () => { const repoId = readyRepo() - const { client, workspaces, worktreeRemove } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -350,21 +374,24 @@ describe('MultiRunService', () => { }) const entry = run.entries[0]! - workspaces.length = 0 + repoWorkspaces.remove.mockRejectedValueOnce( + new RepoWorkspaceError('Not a deletable worktree of this repo', 400), + ) const error = await service.discard(run.id, entry.id).catch((caught: unknown) => caught) expect(error).toBeInstanceOf(MultiRunError) expect(error).toMatchObject({ status: 400 }) - expect(worktreeRemove).not.toHaveBeenCalled() + expect(repoWorkspaces.remove).toHaveBeenCalledTimes(1) expect(service.list(repoId)[0]!.entries[0]!.status).toBe('started') }) it('records the workspace of a failed isolated launch when prompting fails and removes it on discard', async () => { const repoId = readyRepo() - const { client, sessionPrompt, worktreeRemove } = createClient() + const { client, sessionPrompt } = createClient() sessionPrompt.mockRejectedValueOnce(new Error('prompt boom')) - const service = createService(client) + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -382,14 +409,15 @@ describe('MultiRunService', () => { const discarded = await service.discard(run.id, entry.id) expect(discarded.entries[0]!.status).toBe('discarded') - expect(worktreeRemove).toHaveBeenCalledTimes(1) + expect(repoWorkspaces.remove).toHaveBeenCalledTimes(1) }) it('does not record or remove a workspace when isolated workspace creation fails', async () => { const repoId = readyRepo() - const { client, worktreeCreate, worktreeRemove } = createClient() - worktreeCreate.mockRejectedValueOnce(new Error('no workspace')) - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + repoWorkspaces.create.mockRejectedValueOnce(new Error('no workspace')) + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -406,13 +434,14 @@ describe('MultiRunService', () => { const discarded = await service.discard(run.id, entry.id) expect(discarded.entries[0]!.status).toBe('discarded') - expect(worktreeRemove).not.toHaveBeenCalled() + expect(repoWorkspaces.remove).not.toHaveBeenCalled() }) it('removes the workspace once when discards race', async () => { const repoId = readyRepo() - const { client, worktreeRemove } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -424,7 +453,7 @@ describe('MultiRunService', () => { const entry = run.entries[0]! let releaseRemoval: () => void = () => {} - worktreeRemove.mockReturnValueOnce( + repoWorkspaces.remove.mockReturnValueOnce( new Promise((resolve) => { releaseRemoval = resolve }), @@ -441,13 +470,14 @@ describe('MultiRunService', () => { const discarded = await first expect(discarded.entries[0]!.status).toBe('discarded') - expect(worktreeRemove).toHaveBeenCalledTimes(1) + expect(repoWorkspaces.remove).toHaveBeenCalledTimes(1) }) it('keeps the entry retryable when workspace removal fails', async () => { const repoId = readyRepo() - const { client, worktreeRemove } = createClient() - const service = createService(client) + const { client } = createClient() + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) const run = await service.launch({ repoId, @@ -458,7 +488,7 @@ describe('MultiRunService', () => { }) const entry = run.entries[0]! - worktreeRemove.mockRejectedValueOnce(new Error('removal failed')) + repoWorkspaces.remove.mockRejectedValueOnce(new Error('removal failed')) const error = await service.discard(run.id, entry.id).catch((caught: unknown) => caught) expect(error).toBeInstanceOf(MultiRunError) @@ -469,13 +499,14 @@ describe('MultiRunService', () => { const discarded = await service.discard(run.id, entry.id) expect(discarded.entries[0]!.status).toBe('discarded') - expect(worktreeRemove).toHaveBeenCalledTimes(2) + expect(repoWorkspaces.remove).toHaveBeenCalledTimes(2) }) it('lists the most recent groups for a repository', async () => { const repoId = readyRepo() const { client } = createClient() - const service = createService(client) + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) await service.launch({ repoId, name: 'First', prompt: 'go', models: ['openai/a'], isolate: false }) await service.launch({ repoId, name: 'Second', prompt: 'go', models: ['openai/b'], isolate: false }) @@ -503,7 +534,8 @@ describe('MultiRunService', () => { it('deletes the repository multi-run rows when the repository is deleted', async () => { const repoId = readyRepo() const { client } = createClient() - const service = createService(client) + const repoWorkspaces = createRepoWorkspaces() + const service = createService(client, repoWorkspaces.service) await service.launch({ repoId, name: 'Sweep', prompt: 'go', models: ['openai/a'], isolate: false }) diff --git a/backend/test/services/preview/gateway-ws.test.ts b/backend/test/services/preview/gateway-ws.test.ts new file mode 100644 index 00000000..00ce9ce2 --- /dev/null +++ b/backend/test/services/preview/gateway-ws.test.ts @@ -0,0 +1,274 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest' +import { randomBytes } from 'node:crypto' +import { request as httpRequest } from 'node:http' +import type { Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import type { Duplex } from 'node:stream' +import { Hono } from 'hono' +import { serve } from '@hono/node-server' +import { createNodeWebSocket } from '@hono/node-ws' +import { + createPreviewGatewayApp, + PreviewSessionStore, +} from '../../../src/services/preview/gateway' + +class HandshakeError extends Error { + constructor(readonly statusCode: number) { + super(`WebSocket handshake failed with status ${statusCode}`) + } +} + +interface ReceivedMessage { + type: 'text' | 'binary' + data: string | Buffer +} + +function encodeFrame(opcode: number, payload: Buffer): Buffer { + const maskKey = randomBytes(4) + const length = payload.length + let header: Buffer + if (length < 126) { + header = Buffer.from([0x80 | opcode, 0x80 | length]) + } else if (length < 65536) { + header = Buffer.alloc(4) + header[0] = 0x80 | opcode + header[1] = 0x80 | 126 + header.writeUInt16BE(length, 2) + } else { + header = Buffer.alloc(10) + header[0] = 0x80 | opcode + header[1] = 0x80 | 127 + header.writeBigUInt64BE(BigInt(length), 2) + } + const masked = Buffer.from(payload) + for (let i = 0; i < masked.length; i += 1) { + masked[i] = masked[i]! ^ maskKey[i % 4]! + } + return Buffer.concat([header, maskKey, masked]) +} + +class RawWebSocketClient { + private buffer = Buffer.alloc(0) + private readonly messages: ReceivedMessage[] = [] + + private constructor(private readonly socket: Duplex, head: Buffer) { + socket.on('data', (chunk: Buffer) => this.onData(chunk)) + if (head.length > 0) this.onData(head) + } + + static connect(options: { port: number; path: string; protocol?: string; cookie?: string }): Promise { + return new Promise((resolve, reject) => { + const headers: Record = { + Connection: 'Upgrade', + Upgrade: 'websocket', + 'Sec-WebSocket-Key': randomBytes(16).toString('base64'), + 'Sec-WebSocket-Version': '13', + } + if (options.protocol) headers['Sec-WebSocket-Protocol'] = options.protocol + if (options.cookie) headers.Cookie = options.cookie + + const request = httpRequest({ + host: '127.0.0.1', + port: options.port, + path: options.path, + method: 'GET', + headers, + }) + + let settled = false + request.on('upgrade', (_res, socket, head) => { + settled = true + resolve(new RawWebSocketClient(socket, head)) + }) + request.on('response', (res) => { + settled = true + res.resume() + reject(new HandshakeError(res.statusCode ?? 0)) + }) + request.on('error', (error) => { + if (!settled) reject(error) + }) + request.end() + }) + } + + send(text: string): void { + this.socket.write(encodeFrame(0x1, Buffer.from(text, 'utf8'))) + } + + async waitForMessage(index: number, timeoutMs = 5000): Promise { + const deadline = Date.now() + timeoutMs + while (this.messages.length <= index) { + if (Date.now() > deadline) throw new Error(`Timed out waiting for message ${index}`) + await new Promise((resolve) => setTimeout(resolve, 10)) + } + return this.messages[index]! + } + + close(): void { + try { + this.socket.write(encodeFrame(0x8, Buffer.alloc(0))) + } catch { + this.socket.destroy() + } + this.socket.destroy() + } + + private onData(chunk: Buffer): void { + this.buffer = Buffer.concat([this.buffer, chunk]) + for (;;) { + if (this.buffer.length < 2) return + const first = this.buffer[0]! + const second = this.buffer[1]! + const opcode = first & 0x0f + const masked = (second & 0x80) !== 0 + let length = second & 0x7f + let offset = 2 + if (length === 126) { + if (this.buffer.length < 4) return + length = this.buffer.readUInt16BE(2) + offset = 4 + } else if (length === 127) { + if (this.buffer.length < 10) return + length = Number(this.buffer.readBigUInt64BE(2)) + offset = 10 + } + let maskKey: Buffer | null = null + if (masked) { + if (this.buffer.length < offset + 4) return + maskKey = this.buffer.subarray(offset, offset + 4) + offset += 4 + } + if (this.buffer.length < offset + length) return + const payload = Buffer.from(this.buffer.subarray(offset, offset + length)) + this.buffer = this.buffer.subarray(offset + length) + if (maskKey) { + for (let i = 0; i < payload.length; i += 1) { + payload[i] = payload[i]! ^ maskKey[i % 4]! + } + } + if (opcode === 0x1) { + this.messages.push({ type: 'text', data: payload.toString('utf8') }) + } else if (opcode === 0x2) { + this.messages.push({ type: 'binary', data: payload }) + } + } + } +} + +let upstreamServer: Server +let gatewayServer: Server +let upstreamPort = 0 +let gatewayPort = 0 +let capturedUrl: URL | undefined +let capturedProtocol: string | undefined + +const store = new PreviewSessionStore() +const gateway = createPreviewGatewayApp(store) + +const upstreamApp = new Hono() +const upstreamWs = createNodeWebSocket({ app: upstreamApp }) + +upstreamApp.get( + '/*', + upstreamWs.upgradeWebSocket((c) => { + capturedUrl = new URL(c.req.url) + capturedProtocol = c.req.header('sec-websocket-protocol') + return { + onMessage(event, ws) { + if (typeof event.data === 'string') ws.send(event.data) + }, + } + }), +) + +upstreamApp.all('/*', (c) => c.json({ path: c.req.path, search: new URL(c.req.url).search })) + +function listen(server: Server): Promise { + return new Promise((resolve) => { + if (server.listening) { + resolve((server.address() as AddressInfo).port) + return + } + server.once('listening', () => resolve((server.address() as AddressInfo).port)) + }) +} + +function closeServer(server: Server): Promise { + server.closeAllConnections() + return new Promise((resolve) => server.close(() => resolve())) +} + +async function openSessionCookie(): Promise { + const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' }) + const res = await gateway.app.request( + `http://localhost/__ocm_preview/start?token=${encodeURIComponent(token)}`, + { redirect: 'manual' }, + ) + const setCookie = res.headers.get('set-cookie') + if (!setCookie) throw new Error('Expected a Set-Cookie header') + return setCookie.split(';')[0]! +} + +beforeAll(async () => { + upstreamServer = serve({ fetch: upstreamApp.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server + upstreamWs.injectWebSocket(upstreamServer) + upstreamPort = await listen(upstreamServer) + + gatewayServer = serve({ fetch: gateway.app.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server + gateway.injectWebSocket(gatewayServer) + gatewayPort = await listen(gatewayServer) +}) + +afterAll(async () => { + upstreamWs.wss.close() + await closeServer(upstreamServer) + await closeServer(gatewayServer) +}) + +describe('Preview Gateway WebSocket', () => { + it('bridges an authenticated upgrade and forwards the protocol, path and query upstream', async () => { + const cookie = await openSessionCookie() + + const client = await RawWebSocketClient.connect({ + port: gatewayPort, + path: '/hmr?token=abc', + protocol: 'vite-hmr', + cookie, + }) + + client.send('hello hmr') + const message = await client.waitForMessage(0) + + expect(message.type).toBe('text') + expect(message.data).toBe('hello hmr') + expect(capturedUrl?.pathname).toBe('/hmr') + expect(capturedUrl?.search).toBe('?token=abc') + expect(capturedProtocol).toBe('vite-hmr') + + client.close() + }) + + it('fails the handshake for an upgrade without a preview session cookie', async () => { + let failure: HandshakeError | undefined + try { + await RawWebSocketClient.connect({ port: gatewayPort, path: '/hmr', protocol: 'vite-hmr' }) + } catch (error) { + failure = error as HandshakeError + } + + expect(failure).toBeInstanceOf(HandshakeError) + expect(failure?.statusCode).toBe(401) + }) + + it('still proxies a plain HTTP GET on the same path', async () => { + const cookie = await openSessionCookie() + + const res = await fetch(`http://127.0.0.1:${gatewayPort}/echo?q=2`, { headers: { cookie } }) + + expect(res.status).toBe(200) + const body = await res.json() as { path: string; search: string } + expect(body.path).toBe('/echo') + expect(body.search).toBe('?q=2') + }) +}) diff --git a/backend/test/services/preview/gateway.test.ts b/backend/test/services/preview/gateway.test.ts new file mode 100644 index 00000000..3c4ce067 --- /dev/null +++ b/backend/test/services/preview/gateway.test.ts @@ -0,0 +1,325 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest' +import { createServer } from 'node:http' +import type { Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import { gunzipSync, gzipSync } from 'node:zlib' +import { Hono } from 'hono' +import { serve } from '@hono/node-server' +import { + createPreviewGatewayApp, + PreviewSessionStore, + PREVIEW_COOKIE, +} from '../../../src/services/preview/gateway' + +let upstreamServer: Server +let upstreamPort = 0 + +const upstreamApp = new Hono() + +upstreamApp.post('/gzip', async (c) => { + const encoding = c.req.header('content-encoding') ?? null + const bytes = Buffer.from(await c.req.arrayBuffer()) + const decoded = encoding === 'gzip' ? gunzipSync(bytes).toString('utf8') : null + return c.json({ encoding, decoded }) +}) + +upstreamApp.get('/cookies', () => { + const headers = new Headers() + headers.append('set-cookie', 'session=abc; Path=/; HttpOnly') + headers.append('set-cookie', 'csrf=def; Path=/; Expires=Wed, 21 Oct 2026 07:28:00 GMT') + headers.set('content-type', 'text/plain') + return new Response('ok', { status: 200, headers }) +}) + +upstreamApp.get('/manager-cookies', () => { + const headers = new Headers() + headers.append('set-cookie', 'app=keep; Path=/') + headers.append('set-cookie', `${PREVIEW_COOKIE}=upstream; Path=/`) + headers.append('set-cookie', 'opencode.session_token=secret; Path=/') + headers.append('set-cookie', '__Secure-opencode.session_token=secure; Path=/') + headers.append('set-cookie', '__Host-opencode.session_token=host; Path=/') + headers.set('content-type', 'text/plain') + return new Response('ok', { status: 200, headers }) +}) + +upstreamApp.all('/*', async (c) => { + if (c.req.path === '/r') { + return c.redirect(`http://localhost:${upstreamPort}/done`, 302) + } + const body = c.req.method === 'GET' || c.req.method === 'HEAD' ? '' : await c.req.text() + return c.json({ + method: c.req.method, + path: c.req.path, + search: new URL(c.req.url).search, + host: c.req.header('host') ?? null, + cookie: c.req.header('cookie') ?? null, + acceptEncoding: c.req.header('accept-encoding') ?? null, + body, + }) +}) + +function listen(server: Server): Promise { + return new Promise((resolve) => { + if (server.listening) { + resolve((server.address() as AddressInfo).port) + return + } + server.once('listening', () => resolve((server.address() as AddressInfo).port)) + }) +} + +function closeServer(server: Server): Promise { + server.closeAllConnections() + return new Promise((resolve) => server.close(() => resolve())) +} + +function reserveClosedPort(): Promise { + return new Promise((resolve) => { + const server = createServer() + server.listen(0, '127.0.0.1', () => { + const port = (server.address() as AddressInfo).port + server.close(() => resolve(port)) + }) + }) +} + +function previewCookieFrom(res: Response): string { + const setCookie = res.headers.get('set-cookie') + if (!setCookie) throw new Error('Expected a Set-Cookie header') + return setCookie.split(';')[0]! +} + +async function openSession(app: Hono, store: PreviewSessionStore, port: number): Promise { + const token = store.issueStartToken({ port, host: '127.0.0.1' }) + const res = await app.request( + `http://localhost/__ocm_preview/start?token=${encodeURIComponent(token)}`, + { redirect: 'manual' }, + ) + return previewCookieFrom(res) +} + +beforeAll(async () => { + upstreamServer = serve({ fetch: upstreamApp.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server + upstreamPort = await listen(upstreamServer) +}) + +afterAll(async () => { + await closeServer(upstreamServer) +}) + +describe('Preview Gateway', () => { + it('consumes the start token, sets the preview cookie, and redirects to the given path', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' }) + + const res = await app.request( + `http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent('/app?x=1')}`, + { redirect: 'manual' }, + ) + + expect(res.status).toBe(302) + expect(res.headers.get('location')).toBe('/app?x=1') + const setCookie = res.headers.get('set-cookie') ?? '' + expect(setCookie).toContain(`${PREVIEW_COOKIE}=`) + expect(setCookie).toContain('HttpOnly') + expect(setCookie).toContain('SameSite=Lax') + expect(setCookie).toContain('Path=/') + }) + + it('redirects a protocol-relative path to the root', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' }) + + const res = await app.request( + `http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent('//evil.example')}`, + { redirect: 'manual' }, + ) + + expect(res.status).toBe(302) + expect(res.headers.get('location')).toBe('/') + }) + + it('rejects redirect paths that resolve off-origin', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + + for (const malicious of ['/\\evil.example', '//evil.example', 'https://evil.example']) { + const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' }) + const res = await app.request( + `http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent(malicious)}`, + { redirect: 'manual' }, + ) + + expect(res.status).toBe(302) + expect(res.headers.get('location')).toBe('/') + } + }) + + it('redirects to an allowed same-origin path with query and hash', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' }) + + const res = await app.request( + `http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent('/ok?x=1#h')}`, + { redirect: 'manual' }, + ) + + expect(res.status).toBe(302) + expect(res.headers.get('location')).toBe('/ok?x=1#h') + }) + + it('does not allow a start token to be reused', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' }) + + const first = await app.request(`http://localhost/__ocm_preview/start?token=${token}`, { redirect: 'manual' }) + expect(first.status).toBe(302) + + const second = await app.request(`http://localhost/__ocm_preview/start?token=${token}`, { redirect: 'manual' }) + expect(second.status).toBe(401) + }) + + it('rejects an expired start token', async () => { + let now = 1_000 + const store = new PreviewSessionStore({ now: () => now, randomToken: () => 'expired-token' }) + const app = createPreviewGatewayApp(store).app + const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' }) + + now += 61_000 + + const res = await app.request(`http://localhost/__ocm_preview/start?token=${token}`, { redirect: 'manual' }) + expect(res.status).toBe(401) + }) + + it('rejects a request without a preview cookie', async () => { + const app = createPreviewGatewayApp(new PreviewSessionStore()).app + + const res = await app.request('http://localhost/anything') + + expect(res.status).toBe(401) + }) + + it('proxies with the localhost host header and strips Manager cookies', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const cookie = await openSession(app, store, upstreamPort) + + const res = await app.request('http://localhost/echo?q=1', { + headers: { cookie: `${cookie}; user=abc; opencode.session_token=secret` }, + }) + + expect(res.status).toBe(200) + const body = await res.json() as { method: string; path: string; search: string; host: string; cookie: string } + expect(body.method).toBe('GET') + expect(body.path).toBe('/echo') + expect(body.search).toBe('?q=1') + expect(body.host).toBe(`localhost:${upstreamPort}`) + expect(body.cookie).toBe('user=abc') + }) + + it('forwards a POST body', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const cookie = await openSession(app, store, upstreamPort) + + const res = await app.request('http://localhost/echo', { + method: 'POST', + headers: { cookie }, + body: 'hello preview', + }) + + expect(res.status).toBe(200) + const body = await res.json() as { method: string; body: string } + expect(body.method).toBe('POST') + expect(body.body).toBe('hello preview') + }) + + it('forwards a gzip-encoded request body together with its content-encoding', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const cookie = await openSession(app, store, upstreamPort) + + const payload = 'compressed telemetry payload' + const gzipped = gzipSync(Buffer.from(payload, 'utf8')) + + const res = await app.request('http://localhost/gzip', { + method: 'POST', + headers: { cookie, 'content-encoding': 'gzip', 'content-type': 'application/json' }, + body: gzipped, + }) + + expect(res.status).toBe(200) + const body = await res.json() as { encoding: string | null; decoded: string | null } + expect(body.encoding).toBe('gzip') + expect(body.decoded).toBe(payload) + }) + + it('forwards every upstream Set-Cookie value separately and intact', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const cookie = await openSession(app, store, upstreamPort) + + const res = await app.request('http://localhost/cookies', { headers: { cookie } }) + + expect(res.status).toBe(200) + const cookies = res.headers.getSetCookie() + expect(cookies).toContain('session=abc; Path=/; HttpOnly') + expect(cookies).toContain('csrf=def; Path=/; Expires=Wed, 21 Oct 2026 07:28:00 GMT') + expect(cookies).toHaveLength(2) + }) + + it('drops Manager and preview Set-Cookie values from upstream responses', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const cookie = await openSession(app, store, upstreamPort) + + const res = await app.request('http://localhost/manager-cookies', { headers: { cookie } }) + + expect(res.status).toBe(200) + expect(res.headers.getSetCookie()).toEqual(['app=keep; Path=/']) + }) + + it('requests identity encoding from the upstream', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const cookie = await openSession(app, store, upstreamPort) + + const res = await app.request('http://localhost/echo', { + headers: { cookie, 'accept-encoding': 'gzip, br' }, + }) + + expect(res.status).toBe(200) + const body = await res.json() as { acceptEncoding: string | null } + expect(body.acceptEncoding).toBe('identity') + }) + + it('rewrites an absolute localhost location to its path', async () => { + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const cookie = await openSession(app, store, upstreamPort) + + const res = await app.request('http://localhost/r', { + headers: { cookie }, + redirect: 'manual', + }) + + expect(res.status).toBe(302) + expect(res.headers.get('location')).toBe('/done') + }) + + it('returns 502 when the target port is unreachable', async () => { + const closedPort = await reserveClosedPort() + const store = new PreviewSessionStore() + const app = createPreviewGatewayApp(store).app + const cookie = await openSession(app, store, closedPort) + + const res = await app.request('http://localhost/anything', { headers: { cookie } }) + + expect(res.status).toBe(502) + expect(await res.text()).toContain(String(closedPort)) + }) +}) diff --git a/backend/test/services/preview/ports.test.ts b/backend/test/services/preview/ports.test.ts new file mode 100644 index 00000000..d95166a5 --- /dev/null +++ b/backend/test/services/preview/ports.test.ts @@ -0,0 +1,229 @@ +import { describe, it, expect } from 'vitest' +import { ENV } from '@opencode-manager/shared/config/env' +import { + isReservedPreviewPort, + listListeningPorts, + parseLsofListen, + parseProcNetTcp, + type PortDiscoveryDeps, +} from '../../../src/services/preview/ports' + +const PROC_HEADER = ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode' + +function procRow(local: string, remote: string, state: string, inode: string): string { + return ` 0: ${local} ${remote} ${state} 00000000:00000000 00:00000000 00000000 1000 0 ${inode} 1 0000000000000000 100 0 0 10 0` +} + +const IPV4_FIXTURE = [ + PROC_HEADER, + procRow('00000000:1435', '00000000:0000', '0A', '11111'), + procRow('0100007F:1F90', '00000000:0000', '0A', '22222'), + procRow('0501A8C0:1F90', '00000000:0000', '0A', '33333'), + procRow('0100007F:1435', '0100007F:9C40', '01', '44444'), +].join('\n') + +const IPV6_FIXTURE = [ + PROC_HEADER, + procRow('00000000000000000000000001000000:0BB8', '00000000000000000000000000000000:0000', '0A', '55555'), + procRow('00000000000000000000000000000000:1F90', '00000000000000000000000000000000:0000', '0A', '66666'), + procRow('b80d0120000000000000000001000000:1F90', '00000000000000000000000000000000:0000', '0A', '77777'), +].join('\n') + +interface FakeFileSystem { + files: Record + links: Record + dirs: Record +} + +function createDeps(fs: FakeFileSystem, overrides: Partial = {}): PortDiscoveryDeps { + return { + platform: 'linux', + readFile: async (path) => { + const value = fs.files[path] + if (value === undefined) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) + return value + }, + readdir: async (path) => { + const value = fs.dirs[path] + if (value === undefined) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) + return value + }, + readlink: async (path) => { + const value = fs.links[path] + if (value === undefined) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) + return value + }, + runLsof: async () => '', + ...overrides, + } +} + +describe('parseProcNetTcp', () => { + it('keeps loopback and wildcard IPv4 listeners and drops other rows', () => { + const sockets = parseProcNetTcp(IPV4_FIXTURE, 4) + + expect(sockets).toEqual([ + { port: 5173, address: '0.0.0.0', inode: '11111' }, + { port: 8080, address: '127.0.0.1', inode: '22222' }, + ]) + }) + + it('decodes little-endian IPv6 addresses and keeps loopback and wildcard', () => { + const sockets = parseProcNetTcp(IPV6_FIXTURE, 6) + + expect(sockets).toEqual([ + { port: 3000, address: '::1', inode: '55555' }, + { port: 8080, address: '::', inode: '66666' }, + ]) + }) +}) + +describe('parseLsofListen', () => { + it('parses pid, command and port from field output', () => { + const output = ['p1234', 'cnode', 'n127.0.0.1:5173', 'p5678', 'cnginx', 'n*:8080'].join('\n') + + expect(parseLsofListen(output)).toEqual([ + { port: 5173, address: '127.0.0.1', pid: 1234, command: 'node' }, + { port: 8080, address: '0.0.0.0', pid: 5678, command: 'nginx' }, + ]) + }) + + it('parses bracketed IPv6 names', () => { + const output = ['p42', 'cdeno', 'n[::1]:3000'].join('\n') + + expect(parseLsofListen(output)).toEqual([ + { port: 3000, address: '::1', pid: 42, command: 'deno' }, + ]) + }) +}) + +describe('isReservedPreviewPort', () => { + it('reserves the manager, opencode and preview ports', () => { + expect(isReservedPreviewPort(ENV.SERVER.PORT)).toBe(true) + expect(isReservedPreviewPort(ENV.OPENCODE.PORT)).toBe(true) + expect(isReservedPreviewPort(ENV.PREVIEW.PORT)).toBe(true) + expect(isReservedPreviewPort(5173)).toBe(false) + }) +}) + +describe('listListeningPorts', () => { + it('maps inode to pid, command and cwd and excludes reserved and privileged ports', async () => { + const deps = createDeps({ + files: { + '/proc/net/tcp': [ + PROC_HEADER, + procRow('00000000:1435', '00000000:0000', '0A', '11111'), + procRow('00000000:0050', '00000000:0000', '0A', '33333'), + procRow(`00000000:${ENV.SERVER.PORT.toString(16).toUpperCase().padStart(4, '0')}`, '00000000:0000', '0A', '22222'), + ].join('\n'), + '/proc/1234/comm': 'node\n', + }, + links: { + '/proc/1234/fd/3': 'socket:[11111]', + '/proc/1234/cwd': '/home/user/project', + '/proc/1234/fd/4': 'socket:[33333]', + '/proc/9999/fd/2': 'socket:[22222]', + '/proc/9999/cwd': '/srv/api', + '/proc/9999/comm': 'bun\n', + }, + dirs: { + '/proc': ['1234', '9999', 'self', 'cpuinfo'], + '/proc/1234/fd': ['0', '3', '4'], + '/proc/9999/fd': ['2'], + }, + }) + + const ports = await listListeningPorts(deps) + + expect(ports).toEqual([ + { port: 5173, host: '127.0.0.1', pid: 1234, command: 'node', cwd: '/home/user/project' }, + ]) + }) + + it('stops scanning process fd directories once every listening inode is mapped', async () => { + const base = createDeps({ + files: { + '/proc/net/tcp': [PROC_HEADER, procRow('00000000:1435', '00000000:0000', '0A', '11111')].join('\n'), + '/proc/1234/comm': 'node\n', + }, + links: { + '/proc/1234/fd/3': 'socket:[11111]', + '/proc/1234/cwd': '/home/user/project', + '/proc/9999/fd/2': 'socket:[11111]', + }, + dirs: { + '/proc': ['1234', '9999'], + '/proc/1234/fd': ['3'], + '/proc/9999/fd': ['2'], + }, + }) + const readdirCalls: string[] = [] + const deps: PortDiscoveryDeps = { + ...base, + readdir: async (path) => { + readdirCalls.push(path) + return base.readdir(path) + }, + } + + const ports = await listListeningPorts(deps) + + expect(ports).toEqual([ + { port: 5173, host: '127.0.0.1', pid: 1234, command: 'node', cwd: '/home/user/project' }, + ]) + expect(readdirCalls).toContain('/proc/1234/fd') + expect(readdirCalls).not.toContain('/proc/9999/fd') + }) + + it('reports an IPv6 loopback host only when the sole listener is IPv6 loopback', async () => { + const deps = createDeps({ + files: { + '/proc/net/tcp': '', + '/proc/net/tcp6': [ + PROC_HEADER, + procRow('00000000000000000000000001000000:0BB8', '00000000000000000000000000000000:0000', '0A', '55555'), + procRow('00000000000000000000000001000000:1F90', '00000000000000000000000000000000:0000', '0A', '66666'), + procRow('00000000000000000000000000000000:1F90', '00000000000000000000000000000000:0000', '0A', '77777'), + ].join('\n'), + '/proc/1234/comm': 'vite\n', + }, + links: { + '/proc/1234/fd/5': 'socket:[55555]', + '/proc/1234/fd/6': 'socket:[66666]', + '/proc/1234/fd/7': 'socket:[77777]', + '/proc/1234/cwd': '/home/user/app', + }, + dirs: { + '/proc': ['1234'], + '/proc/1234/fd': ['5', '6', '7'], + }, + }) + + const ports = await listListeningPorts(deps) + + expect(ports).toEqual([ + { port: 3000, host: '::1', pid: 1234, command: 'vite', cwd: '/home/user/app' }, + { port: 8080, host: '127.0.0.1', pid: 1234, command: 'vite', cwd: '/home/user/app' }, + ]) + }) + + it('uses lsof on macOS with a null cwd', async () => { + const deps = createDeps( + { files: {}, links: {}, dirs: {} }, + { + platform: 'darwin', + runLsof: async () => ['p777', 'cnode', 'n127.0.0.1:5173'].join('\n'), + }, + ) + + expect(await listListeningPorts(deps)).toEqual([ + { port: 5173, host: '127.0.0.1', pid: 777, command: 'node', cwd: null }, + ]) + }) + + it('returns an empty list on unsupported platforms', async () => { + const deps = createDeps({ files: {}, links: {}, dirs: {} }, { platform: 'win32' }) + + expect(await listListeningPorts(deps)).toEqual([]) + }) +}) diff --git a/backend/test/services/project-config.test.ts b/backend/test/services/project-config.test.ts new file mode 100644 index 00000000..8d946a05 --- /dev/null +++ b/backend/test/services/project-config.test.ts @@ -0,0 +1,1102 @@ +import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll, vi } from 'vitest' +import { Database } from 'bun:sqlite' +import { execSync } from 'node:child_process' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import { createRepo, setRepoSetting } from '../../src/db/queries' +import { createGitService } from '../../src/services/git/GitService' +import { ProjectConfigService, ProjectConfigError } from '../../src/services/project-config' +import type { GitAuthService } from '../../src/services/git-auth' +import type { CreateTerminalInput, TerminalService } from '../../src/services/terminal' +import { formatTerminalTitle } from '@opencode-manager/shared/utils' +import type { ProjectAction } from '@opencode-manager/shared/schemas' +import type { Repo, TerminalInfo } from '@opencode-manager/shared/types' + +const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService + +function createService(db: Database): ProjectConfigService { + return new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService) +} + +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 + let repo: Repo + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + repo = createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + }) + + afterEach(() => { + db.close() + }) + + it('round-trips personal actions', () => { + const actions = [createAction(), createAction({ id: 'test', name: 'Test', command: 'pnpm test' })] + + service.setPersonalActions(repo, actions) + + expect(service.getPersonalActions(repo)).toEqual(actions) + }) + + it('returns personal actions through getConfig with the personal source', async () => { + service.setPersonalActions(repo, [createAction()]) + + const config = await service.getConfig(repo, repo.fullPath) + + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + expect(config.repoFile).toEqual({ + path: '.ocm/project.json', + exists: false, + trusted: false, + hash: null, + executable: null, + warnings: [], + }) + }) + + it('round-trips personal setup commands through getConfig', async () => { + service.setPersonalSetup(repo, ['pnpm install', 'pnpm build']) + + expect(service.getPersonalSetup(repo)).toEqual(['pnpm install', 'pnpm build']) + + const config = await service.getConfig(repo, repo.fullPath) + expect(config.worktreeSetup).toEqual([ + { command: 'pnpm install', source: 'personal' }, + { command: 'pnpm build', source: 'personal' }, + ]) + }) + + it('rejects duplicate action ids', () => { + let caught: unknown + try { + service.setPersonalActions(repo, [createAction(), createAction({ name: 'Other' })]) + } catch (error: unknown) { + caught = error + } + + expect(caught).toBeInstanceOf(ProjectConfigError) + expect((caught as ProjectConfigError).status).toBe(400) + expect((caught as ProjectConfigError).message).toBe('Duplicate action id') + }) + + it('reads corrupt stored action JSON as an empty list', () => { + setRepoSetting(db, repo.id, 'projectActions', '{not json') + + expect(service.getPersonalActions(repo)).toEqual([]) + }) + + it('reads wrongly shaped stored action JSON as an empty list', () => { + setRepoSetting(db, repo.id, 'projectActions', JSON.stringify({ id: 'serve' })) + + expect(service.getPersonalActions(repo)).toEqual([]) + }) + + it('reads corrupt stored setup JSON as an empty list', () => { + setRepoSetting(db, repo.id, 'worktreeSetupCommands', 'not-json') + + expect(service.getPersonalSetup(repo)).toEqual([]) + }) +}) + +describe('ProjectConfigService worktree resolution', () => { + let db: Database + let service: ProjectConfigService + let basePath: string + let worktreePath: string + let root: string + let baseRepo: Repo + let worktreeRepo: Repo + + beforeAll(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-project-config-'))) + basePath = path.join(root, 'base') + worktreePath = path.join(root, 'linked worktree') + + execSync(`git init "${basePath}"`) + execSync(`git -C "${basePath}" config user.email test@test.com`) + execSync(`git -C "${basePath}" config user.name Test`) + execSync(`git -C "${basePath}" commit --allow-empty -m "Initial commit"`) + execSync(`git -C "${basePath}" worktree add -b feature "${worktreePath}"`) + }) + + afterAll(() => { + fs.rmSync(root, { recursive: true, force: true }) + }) + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + baseRepo = createRepo(db, { + localPath: basePath, + sourcePath: basePath, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + worktreeRepo = createRepo(db, { + localPath: worktreePath, + sourcePath: worktreePath, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + isWorktree: true, + }) + }) + + afterEach(() => { + db.close() + }) + + it('resolves the main checkout from both the base and the linked worktree', async () => { + const git = createGitService(gitAuthService) + + expect(fs.realpathSync(await git.getMainCheckoutPath(basePath))).toBe(fs.realpathSync(basePath)) + expect(fs.realpathSync(await git.getMainCheckoutPath(worktreePath))).toBe(fs.realpathSync(basePath)) + }) + + it('resolves a linked worktree repo to the main checkout row', async () => { + const resolved = await service.resolveProjectRepo(worktreeRepo) + + expect(resolved.id).toBe(baseRepo.id) + }) + + it('keeps a non-worktree repo unchanged', async () => { + const resolved = await service.resolveProjectRepo(baseRepo) + + expect(resolved.id).toBe(baseRepo.id) + }) + + it('returns personal actions saved on the base repo when resolving from the worktree', async () => { + service.setPersonalActions(baseRepo, [createAction()]) + + const config = await service.getConfig(worktreeRepo, worktreePath) + + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + }) + + it('returns personal setup saved on the base repo when resolving from the worktree', async () => { + service.setPersonalSetup(baseRepo, ['pnpm install']) + + const config = await service.getConfig(worktreeRepo, worktreePath) + + expect(config.worktreeSetup).toEqual([{ command: 'pnpm install', source: 'personal' }]) + }) +}) + +describe('ProjectConfigService repository file', () => { + let db: Database + let service: ProjectConfigService + let repo: Repo + let directory: string + + function repoFilePath(): string { + return path.join(directory, '.ocm', 'project.json') + } + + function writeRepoFile(content: unknown): void { + fs.mkdirSync(path.dirname(repoFilePath()), { recursive: true }) + fs.writeFileSync(repoFilePath(), typeof content === 'string' ? content : JSON.stringify(content, null, 2)) + } + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-repo-file-')) + 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('reports an untrusted repository file with a hash and its items', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }) + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.exists).toBe(true) + expect(config.repoFile.trusted).toBe(false) + expect(config.repoFile.hash).toMatch(/^[a-f0-9]{64}$/) + expect(config.actions).toEqual([ + { id: 'repo-serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false, source: 'repo' }, + ]) + }) + + it('rejects trusting a stale hash', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + + await expect(service.trustRepoFile(repo, directory, 'a'.repeat(64))).rejects.toMatchObject({ + status: 409, + code: 'REPO_CONFIG_CHANGED', + }) + }) + + it('drops trust when the name, command, or autoOpenUrl changes', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + const first = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '') + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true) + + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev' }] }) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false) + + const renamed = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, renamed.repoFile.hash ?? '') + writeRepoFile({ + version: 1, + projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev', autoOpenUrl: true }], + }) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false) + }) + + it('changes the hash when only the name or autoOpenUrl changes', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + const base = await service.getConfig(repo, directory) + + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev' }] }) + const renamed = await service.getConfig(repo, directory) + + writeRepoFile({ + version: 1, + projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: true }], + }) + const autoOpen = await service.getConfig(repo, directory) + + expect(renamed.repoFile.hash).not.toBe(base.repoFile.hash) + expect(autoOpen.repoFile.hash).not.toBe(base.repoFile.hash) + }) + + it('reports invalid JSON with an error and no repository items', async () => { + writeRepoFile('{not json') + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.exists).toBe(true) + expect(config.repoFile.error).toBe('Invalid JSON') + expect(config.repoFile.hash).toBeNull() + expect(config.actions).toEqual([]) + }) + + it('reports a schema-invalid file with an error and no repository items', async () => { + writeRepoFile({ version: 2 }) + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.error).toBe('Does not match the project file schema') + expect(config.actions).toEqual([]) + }) + + it('rejects a repository action url that is not http(s)', async () => { + writeRepoFile({ + version: 1, + projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', url: 'javascript:alert(1)' }], + }) + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.error).toBe('Does not match the project file schema') + expect(config.repoFile.executable).toBeNull() + }) + + it('accepts an http url template', async () => { + writeRepoFile({ + version: 1, + projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', url: 'http://localhost:3000/{branch}' }], + }) + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.executable?.actions[0]?.url).toBe('http://localhost:3000/{branch}') + }) + + it('reports a symlinked .ocm directory as invalid on read', async () => { + const realDir = path.join(directory, 'real-ocm') + fs.mkdirSync(realDir, { recursive: true }) + fs.writeFileSync(path.join(realDir, 'project.json'), JSON.stringify({ version: 1 })) + fs.symlinkSync(realDir, path.join(directory, '.ocm'), 'dir') + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.error).toBe('.ocm/project.json must not be a symbolic link') + expect(config.repoFile.hash).toBeNull() + expect(config.repoFile.executable).toBeNull() + }) + + it('reports a symlinked project.json as invalid on read', async () => { + const ocmDir = path.join(directory, '.ocm') + fs.mkdirSync(ocmDir, { recursive: true }) + const target = path.join(directory, 'target.json') + fs.writeFileSync(target, JSON.stringify({ version: 1 })) + fs.symlinkSync(target, path.join(ocmDir, 'project.json')) + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.error).toBe('.ocm/project.json must not be a symbolic link') + }) + + it('refuses to move an action into a symlinked repository config', async () => { + service.setPersonalActions(repo, [createAction()]) + const realDir = path.join(directory, 'real-ocm') + fs.mkdirSync(realDir, { recursive: true }) + fs.writeFileSync(path.join(realDir, 'project.json'), JSON.stringify({ version: 1 })) + fs.symlinkSync(realDir, path.join(directory, '.ocm'), 'dir') + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toMatchObject({ + status: 400, + code: 'REPO_CONFIG_SYMLINK', + }) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + }) + + it('moves an action personal to repo preserving unknown keys and marking it trusted', async () => { + service.setPersonalActions(repo, [createAction()]) + writeRepoFile({ version: 1, customKey: 'keep-me' }) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' }) + + const raw = JSON.parse(fs.readFileSync(repoFilePath(), 'utf8')) as { customKey: string; projectActions: unknown[] } + expect(raw.customKey).toBe('keep-me') + expect(raw.projectActions).toEqual([createAction()]) + expect(service.getPersonalActions(repo)).toEqual([]) + + const config = await service.getConfig(repo, directory) + expect(config.repoFile.trusted).toBe(true) + expect(config.actions).toEqual([{ ...createAction(), source: 'repo' }]) + }) + + it('deletes the file and .ocm directory when the last item moves back', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(fs.existsSync(path.join(directory, '.ocm'))).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + }) + + it('keeps unrelated repository setup untrusted when moving an action to personal', async () => { + writeRepoFile({ + version: 1, + projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }], + setupWorktree: ['echo unrelated'], + }) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + + const config = await service.getConfig(repo, directory) + expect(config.repoFile.trusted).toBe(false) + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + + const { service: terminalService, create } = createStatefulTerminalService(null) + const result = await service.runWorktreeSetup(repo, directory, terminalService) + expect(result).toEqual({ status: 'skipped', reason: 'untrusted' }) + expect(create).not.toHaveBeenCalled() + }) + + it('keeps unrelated repository actions untrusted when moving an action into the file', async () => { + service.setPersonalActions(repo, [ + createAction({ id: 'personal-serve', name: 'Personal Serve', command: 'pnpm personal' }), + ]) + writeRepoFile({ + version: 1, + projectActions: [{ id: 'repo-other', name: 'Other', command: 'pnpm other' }], + }) + + await service.moveItem(repo, directory, { kind: 'action', id: 'personal-serve', to: 'repo' }) + + const config = await service.getConfig(repo, directory) + expect(config.repoFile.trusted).toBe(false) + expect(config.actions).toEqual([ + { id: 'repo-other', name: 'Other', command: 'pnpm other', autoOpenUrl: false, source: 'repo' }, + { id: 'personal-serve', name: 'Personal Serve', command: 'pnpm personal', autoOpenUrl: false, source: 'repo' }, + ]) + + const { service: terminalService } = createStatefulTerminalService(null) + await expect(service.runAction(repo, directory, 'repo-other', terminalService)).rejects.toMatchObject({ + status: 409, + code: 'REPO_CONFIG_UNTRUSTED', + }) + }) + + it('moves a setup command personal to repo and back', async () => { + service.setPersonalSetup(repo, ['pnpm install']) + + await service.moveItem(repo, directory, { kind: 'setup', command: 'pnpm install', to: 'repo' }) + let config = await service.getConfig(repo, directory) + expect(config.worktreeSetup).toEqual([{ command: 'pnpm install', source: 'repo' }]) + expect(config.repoFile.trusted).toBe(true) + + await service.moveItem(repo, directory, { kind: 'setup', command: 'pnpm install', to: 'personal' }) + config = await service.getConfig(repo, directory) + expect(config.worktreeSetup).toEqual([{ command: 'pnpm install', source: 'personal' }]) + expect(config.repoFile.exists).toBe(false) + }) + + it('drops a colliding repository action and warns', async () => { + service.setPersonalActions(repo, [createAction()]) + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev' }] }) + + const config = await service.getConfig(repo, directory) + + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + expect(config.repoFile.warnings).toHaveLength(1) + expect(config.repoFile.warnings[0]).toContain('serve') + }) + + it('lists every executable repository action including a shadowed one', async () => { + service.setPersonalActions(repo, [ + createAction({ id: 'serve', name: 'Personal Serve', command: 'pnpm personal' }), + ]) + writeRepoFile({ + version: 1, + projectActions: [ + { id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev', url: 'https://example.com', autoOpenUrl: true }, + { id: 'other', name: 'Other', command: 'pnpm other' }, + ], + setupWorktree: ['pnpm install'], + }) + + const config = await service.getConfig(repo, directory) + + expect(config.repoFile.executable).toEqual({ + actions: [ + { id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev', url: 'https://example.com', autoOpenUrl: true }, + { id: 'other', name: 'Other', command: 'pnpm other', url: null, autoOpenUrl: false }, + ], + setup: ['pnpm install'], + }) + expect(config.actions).toEqual([ + { id: 'serve', name: 'Personal Serve', command: 'pnpm personal', autoOpenUrl: false, source: 'personal' }, + { id: 'other', name: 'Other', command: 'pnpm other', autoOpenUrl: false, source: 'repo' }, + ]) + }) + + it('rejects moving an unknown personal action', async () => { + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'missing', to: 'repo' })).rejects.toMatchObject({ + status: 404, + }) + }) + + it('rejects moving an unknown repository action', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'missing', to: 'personal' })).rejects.toMatchObject({ + status: 404, + }) + }) + + it('rejects moving a setup command into a repository already at capacity', async () => { + const repoCommands = Array.from({ length: 20 }, (_, index) => `repo-${index}`) + writeRepoFile({ version: 1, setupWorktree: repoCommands }) + const first = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '') + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + service.setPersonalSetup(repo, ['personal-cmd']) + + await expect( + service.moveItem(repo, directory, { kind: 'setup', command: 'personal-cmd', to: 'repo' }), + ).rejects.toMatchObject({ status: 409, code: 'PROJECT_CONFIG_LIMIT_EXCEEDED' }) + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalSetup(repo)).toEqual(['personal-cmd']) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true) + }) + + it('rejects moving a setup command into personal storage already at capacity', async () => { + const personalCommands = Array.from({ length: 20 }, (_, index) => `personal-${index}`) + service.setPersonalSetup(repo, personalCommands) + writeRepoFile({ version: 1, setupWorktree: ['repo-cmd'] }) + const first = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '') + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + + await expect( + service.moveItem(repo, directory, { kind: 'setup', command: 'repo-cmd', to: 'personal' }), + ).rejects.toMatchObject({ status: 409, code: 'PROJECT_CONFIG_LIMIT_EXCEEDED' }) + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalSetup(repo)).toEqual(personalCommands) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true) + }) + + it('allows a setup command to fill the repository up to its capacity', async () => { + writeRepoFile({ version: 1, setupWorktree: Array.from({ length: 19 }, (_, index) => `repo-${index}`) }) + service.setPersonalSetup(repo, ['personal-cmd']) + + await service.moveItem(repo, directory, { kind: 'setup', command: 'personal-cmd', to: 'repo' }) + + const raw = JSON.parse(fs.readFileSync(repoFilePath(), 'utf8')) as { setupWorktree: string[] } + expect(raw.setupWorktree).toHaveLength(20) + expect(service.getPersonalSetup(repo)).toEqual([]) + }) + + it('allows a setup command to fill personal storage up to its capacity', async () => { + service.setPersonalSetup(repo, Array.from({ length: 19 }, (_, index) => `personal-${index}`)) + writeRepoFile({ version: 1, setupWorktree: ['repo-cmd'] }) + + await service.moveItem(repo, directory, { kind: 'setup', command: 'repo-cmd', to: 'personal' }) + + expect(service.getPersonalSetup(repo)).toHaveLength(20) + expect(fs.existsSync(repoFilePath())).toBe(false) + }) + + it('restores the repository file and personal settings when the file write fails', async () => { + service.setPersonalActions(repo, [createAction()]) + const writeSeam = service as unknown as { writeRepoFile(filePath: string, file: unknown): void } + const writeSpy = vi.spyOn(writeSeam, 'writeRepoFile').mockImplementationOnce(() => { + throw new Error('disk full') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow('disk full') + writeSpy.mockRestore() + + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' }) + expect(service.getPersonalActions(repo)).toEqual([]) + expect(fs.existsSync(repoFilePath())).toBe(true) + }) + + it('keeps the repository file and personal settings when the delete fails', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + const rmSpy = vi.spyOn(fs, 'rmSync').mockImplementationOnce(() => { + throw new Error('read-only') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow( + 'read-only', + ) + rmSpy.mockRestore() + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalActions(repo)).toEqual([]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + }) + + it('keeps the repository file when the file write fails moving back', async () => { + writeRepoFile({ + version: 1, + projectActions: [ + { id: 'serve', name: 'Serve', command: 'pnpm dev' }, + { id: 'test', name: 'Test', command: 'pnpm test' }, + ], + }) + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + const writeSeam = service as unknown as { writeRepoFile(filePath: string, file: unknown): void } + const writeSpy = vi.spyOn(writeSeam, 'writeRepoFile').mockImplementationOnce(() => { + throw new Error('disk full') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow( + 'disk full', + ) + writeSpy.mockRestore() + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalActions(repo)).toEqual([]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + }) + + it('restores the repository file and personal settings when the settings write fails', async () => { + service.setPersonalActions(repo, [createAction()]) + const setSpy = vi.spyOn(service, 'setPersonalActions').mockImplementationOnce(() => { + throw new Error('settings write failed') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow( + 'settings write failed', + ) + setSpy.mockRestore() + + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' }) + expect(fs.existsSync(repoFilePath())).toBe(true) + expect(service.getPersonalActions(repo)).toEqual([]) + }) + + it('restores the repository file and rolls back personal settings when the trust write fails', async () => { + service.setPersonalActions(repo, [createAction()]) + const trustSeam = service as unknown as { setRepoTrust(repo: Repo, hash: string | null): void } + const trustSpy = vi.spyOn(trustSeam, 'setRepoTrust').mockImplementationOnce(() => { + throw new Error('trust write failed') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow( + 'trust write failed', + ) + trustSpy.mockRestore() + + expect(fs.existsSync(repoFilePath())).toBe(false) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + expect((await service.getConfig(repo, directory)).repoFile.exists).toBe(false) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' }) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true) + }) + + it('keeps the repository file when the settings write fails moving back', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + const setSpy = vi.spyOn(service, 'setPersonalActions').mockImplementationOnce(() => { + throw new Error('settings write failed') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow( + 'settings write failed', + ) + setSpy.mockRestore() + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalActions(repo)).toEqual([]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + expect(service.getPersonalActions(repo)).toEqual([createAction()]) + expect(fs.existsSync(repoFilePath())).toBe(false) + }) + + it('keeps the repository file when the trust write fails moving back', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] }) + const originalBytes = fs.readFileSync(repoFilePath(), 'utf8') + const trustSeam = service as unknown as { setRepoTrust(repo: Repo, hash: string | null): void } + const trustSpy = vi.spyOn(trustSeam, 'setRepoTrust').mockImplementationOnce(() => { + throw new Error('trust write failed') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow( + 'trust write failed', + ) + trustSpy.mockRestore() + + expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes) + expect(service.getPersonalActions(repo)).toEqual([]) + + await service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' }) + 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 }) + } + }) +}) + +describe('ProjectConfigService runWorktreeSetup', () => { + 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() { + const create = vi.fn( + async (target: string, input: CreateTerminalInput): Promise => ({ + id: 'pty-setup', + title: formatTerminalTitle({ kind: input.kind, name: input.name }), + kind: input.kind, + cwd: target, + status: 'running', + }), + ) + return { service: { create } as unknown as TerminalService, create } + } + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-worktree-setup-')) + 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('starts a setup terminal with the personal commands and ROOT_PROJECT_PATH', async () => { + service.setPersonalSetup(repo, ['pnpm install', 'pnpm build']) + const terminalService = createFakeTerminalService() + + const result = await service.runWorktreeSetup(repo, directory, terminalService.service) + + expect(terminalService.create).toHaveBeenCalledWith(directory, { + kind: 'setup', + name: 'Worktree setup', + command: '/bin/sh', + args: ['-c', 'set -e\npnpm install\npnpm build'], + env: { ROOT_PROJECT_PATH: repo.fullPath }, + }) + expect(result).toEqual({ + status: 'started', + terminal: { + id: 'pty-setup', + title: 'ocm:setup:Worktree setup', + kind: 'setup', + cwd: directory, + status: 'running', + }, + repoCommandsSkipped: false, + }) + }) + + it('excludes untrusted repository commands and reports them skipped', async () => { + service.setPersonalSetup(repo, ['pnpm install']) + writeRepoFile({ version: 1, setupWorktree: ['pnpm repo-setup'] }) + const terminalService = createFakeTerminalService() + + const result = await service.runWorktreeSetup(repo, directory, terminalService.service) + + expect(terminalService.create).toHaveBeenCalledWith( + directory, + expect.objectContaining({ args: ['-c', 'set -e\npnpm install'] }), + ) + expect(result).toMatchObject({ status: 'started', repoCommandsSkipped: true }) + }) + + it('includes trusted repository commands', async () => { + writeRepoFile({ version: 1, setupWorktree: ['pnpm repo-setup'] }) + const first = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '') + const terminalService = createFakeTerminalService() + + const result = await service.runWorktreeSetup(repo, directory, terminalService.service) + + expect(terminalService.create).toHaveBeenCalledWith( + directory, + expect.objectContaining({ args: ['-c', 'set -e\npnpm repo-setup'] }), + ) + expect(result).toMatchObject({ status: 'started', repoCommandsSkipped: false }) + }) + + it('returns skipped when the only commands are untrusted repository commands', async () => { + writeRepoFile({ version: 1, setupWorktree: ['pnpm repo-setup'] }) + const terminalService = createFakeTerminalService() + + const result = await service.runWorktreeSetup(repo, directory, terminalService.service) + + expect(result).toEqual({ status: 'skipped', reason: 'untrusted' }) + expect(terminalService.create).not.toHaveBeenCalled() + }) + + it('returns none when no commands are configured', async () => { + const terminalService = createFakeTerminalService() + + const result = await service.runWorktreeSetup(repo, directory, terminalService.service) + + expect(result).toEqual({ status: 'none' }) + expect(terminalService.create).not.toHaveBeenCalled() + }) + + it('returns failed when the terminal cannot be created', async () => { + service.setPersonalSetup(repo, ['pnpm install']) + const create = vi.fn(async () => { + throw new Error('spawn failed') + }) + const terminalService = { create } as unknown as TerminalService + + const result = await service.runWorktreeSetup(repo, directory, terminalService) + + expect(result).toEqual({ status: 'failed', error: 'spawn failed' }) + }) +}) diff --git a/backend/test/services/repo-working-directory.test.ts b/backend/test/services/repo-working-directory.test.ts new file mode 100644 index 00000000..0d055471 --- /dev/null +++ b/backend/test/services/repo-working-directory.test.ts @@ -0,0 +1,161 @@ +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { Database } from 'bun:sqlite' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import { createRepo } from '../../src/db/queries' +import { findSiblingByDirectory, getSiblingRepos, resolveRepoWorkingDirectory } from '../../src/services/repo' +import type { Repo } from '@opencode-manager/shared/types' + +const { executeCommand, resolveProjectId, getSettings } = vi.hoisted(() => ({ + executeCommand: vi.fn(), + resolveProjectId: vi.fn(), + getSettings: vi.fn(), +})) + +vi.mock('../../src/utils/process', () => ({ executeCommand })) +vi.mock('../../src/services/project-id-resolver', () => ({ resolveProjectId, isGitMainCheckout: vi.fn() })) +vi.mock('../../src/services/settings', () => ({ + SettingsService: vi.fn().mockImplementation(() => ({ getSettings })), +})) + +describe('resolveRepoWorkingDirectory', () => { + let root: string + let repoPath: string + let siblingPath: string + let unrelatedPath: string + let repoLinkPath: string + let siblingLinkPath: string + + beforeAll(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-repo-working-directory-')) + repoPath = path.join(root, 'repo') + siblingPath = path.join(root, 'sibling') + unrelatedPath = path.join(root, 'unrelated') + repoLinkPath = path.join(root, 'repo-link') + siblingLinkPath = path.join(root, 'sibling-link') + + fs.mkdirSync(repoPath) + fs.mkdirSync(siblingPath) + fs.mkdirSync(unrelatedPath) + fs.symlinkSync(repoPath, repoLinkPath, 'dir') + fs.symlinkSync(siblingPath, siblingLinkPath, 'dir') + }) + + afterAll(() => { + fs.rmSync(root, { recursive: true, force: true }) + }) + + function createRepo(): Repo { + return { fullPath: repoPath } as Repo + } + + it('returns the repo path when no directory is given', async () => { + expect(await resolveRepoWorkingDirectory(createRepo(), undefined, async () => [])).toBe(repoPath) + }) + + it('returns the repo path for the repo directory itself', async () => { + expect(await resolveRepoWorkingDirectory(createRepo(), repoPath, async () => [])).toBe(repoPath) + }) + + it('returns the repo path for a symlinked equivalent of the repo directory', async () => { + expect(await resolveRepoWorkingDirectory(createRepo(), repoLinkPath, async () => [])).toBe(repoPath) + }) + + it('returns a matching sibling path', async () => { + const siblings = [{ fullPath: siblingPath }] + expect(await resolveRepoWorkingDirectory(createRepo(), siblingPath, async () => siblings)).toBe(siblingPath) + }) + + it('matches a sibling through a symlinked directory', async () => { + const siblings = [{ fullPath: siblingPath }] + expect(await resolveRepoWorkingDirectory(createRepo(), siblingLinkPath, async () => siblings)).toBe(siblingPath) + }) + + it('returns null for an unrelated directory', async () => { + const siblings = [{ fullPath: siblingPath }] + expect(await resolveRepoWorkingDirectory(createRepo(), unrelatedPath, async () => siblings)).toBeNull() + }) +}) + +describe('findSiblingByDirectory', () => { + let root: string + let siblingPath: string + let siblingLinkPath: string + + beforeAll(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-find-sibling-')) + siblingPath = path.join(root, 'sibling') + siblingLinkPath = path.join(root, 'sibling-link') + fs.mkdirSync(siblingPath) + fs.symlinkSync(siblingPath, siblingLinkPath, 'dir') + }) + + afterAll(() => { + fs.rmSync(root, { recursive: true, force: true }) + }) + + it('returns the sibling whose canonical path matches', () => { + const sibling = { fullPath: siblingPath, id: 1 } + expect(findSiblingByDirectory([sibling], siblingPath)).toBe(sibling) + }) + + it('matches through a symlinked directory', () => { + const sibling = { fullPath: siblingPath, id: 1 } + expect(findSiblingByDirectory([sibling], siblingLinkPath)).toBe(sibling) + }) + + it('returns undefined when no sibling matches', () => { + const sibling = { fullPath: siblingPath, id: 1 } + expect(findSiblingByDirectory([sibling], path.join(root, 'missing'))).toBeUndefined() + }) +}) + +describe('getSiblingRepos branch resolution', () => { + let db: Database + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + getSettings.mockReturnValue({ preferences: { repoOrder: [] }, updatedAt: Date.now() }) + resolveProjectId.mockResolvedValue('project-1') + executeCommand.mockReset() + }) + + afterEach(() => { + db.close() + }) + + function seedRepo(): Repo { + return createRepo(db, { + localPath: 'repo-a', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + } + + it('skips branch resolution when includeBranch is false', async () => { + const repo = seedRepo() + + const siblings = await getSiblingRepos(db, repo.id, {}, undefined, { includeBranch: false }) + + expect(siblings).toHaveLength(1) + expect(siblings[0]?.currentBranch).toBeUndefined() + expect(executeCommand).not.toHaveBeenCalled() + }) + + it('resolves the branch when includeBranch is true', async () => { + const repo = seedRepo() + executeCommand.mockResolvedValue('feature-branch\n') + + const siblings = await getSiblingRepos(db, repo.id, {}) + + expect(siblings).toHaveLength(1) + expect(siblings[0]?.currentBranch).toBe('feature-branch') + expect(executeCommand).toHaveBeenCalled() + }) +}) diff --git a/backend/test/services/repo-workspace.test.ts b/backend/test/services/repo-workspace.test.ts new file mode 100644 index 00000000..ba42b846 --- /dev/null +++ b/backend/test/services/repo-workspace.test.ts @@ -0,0 +1,207 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import type { GitAuthService } from '../../src/services/git-auth' +import type { OpenCodeClient } from '../../src/services/opencode/client' +import type { ProjectConfigService } from '../../src/services/project-config' +import type { TerminalService } from '../../src/services/terminal' +import { RepoWorkspaceError } from '../../src/services/repo' +import { RepoWorkspaceService } from '../../src/services/repo-workspace' + +const mocks = vi.hoisted(() => ({ + getSiblingRepos: vi.fn(), + resolveRepoProjectId: vi.fn(), + loggerWarn: vi.fn(), +})) + +vi.mock('../../src/utils/logger', () => ({ + logger: { + info: vi.fn(), + error: vi.fn(), + warn: mocks.loggerWarn, + }, +})) + +vi.mock('../../src/services/repo', () => { + class MockRepoWorkspaceError extends Error { + readonly status = 400 + + constructor(message: string) { + super(message) + this.name = 'RepoWorkspaceError' + } + } + + return { + getSiblingRepos: mocks.getSiblingRepos, + resolveRepoProjectId: mocks.resolveRepoProjectId, + findSiblingByDirectory: (siblings: T[], directory: string): T | undefined => + siblings.find((sibling) => sibling.fullPath === directory), + RepoWorkspaceError: MockRepoWorkspaceError, + } +}) + +const REPO: Repo = { + id: 1, + localPath: 'repo-a', + fullPath: '/repos/repo-a', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: 0, +} as Repo + +const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService + +function createService(overrides: { + worktreeCreate?: ReturnType + worktreeRemove?: ReturnType + runWorktreeSetupForRepo?: ReturnType + removeAll?: ReturnType +}) { + const worktreeCreate = overrides.worktreeCreate ?? vi.fn(async () => ({ directory: '/worktrees/feature-x' })) + const worktreeRemove = overrides.worktreeRemove ?? vi.fn(async () => undefined) + const runWorktreeSetupForRepo = + overrides.runWorktreeSetupForRepo ?? vi.fn(async () => ({ status: 'started' as const })) + const removeAll = overrides.removeAll ?? vi.fn(async () => undefined) + + const openCodeClient = { + api: { worktree: { create: worktreeCreate, remove: worktreeRemove } }, + } as unknown as OpenCodeClient + const projectConfigService = { runWorktreeSetupForRepo } as unknown as ProjectConfigService + const terminalService = { removeAll } as unknown as TerminalService + + return { + service: new RepoWorkspaceService( + {} as Database, + openCodeClient, + gitAuthService, + projectConfigService, + terminalService, + ), + worktreeCreate, + worktreeRemove, + runWorktreeSetupForRepo, + removeAll, + terminalService, + } +} + +describe('RepoWorkspaceService', () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.resolveRepoProjectId.mockResolvedValue('project-1') + mocks.getSiblingRepos.mockResolvedValue([]) + }) + + describe('create', () => { + it('creates the worktree with projectID, name and branch and runs the setup', async () => { + const worktreeCreate = vi.fn(async () => ({ directory: '/worktrees/feature-x', branch: 'feature/x' })) + const runWorktreeSetupForRepo = vi.fn(async () => ({ status: 'started' as const })) + const { service, terminalService } = createService({ worktreeCreate, runWorktreeSetupForRepo }) + + const result = await service.create(REPO, { name: 'feature-x', ref: 'feature/x' }) + + expect(worktreeCreate).toHaveBeenCalledWith({ + projectID: 'project-1', + name: 'feature-x', + branch: 'feature/x', + }) + expect(runWorktreeSetupForRepo).toHaveBeenCalledWith(REPO, '/worktrees/feature-x', terminalService) + expect(result).toEqual({ + directory: '/worktrees/feature-x', + branch: 'feature/x', + worktreeSetup: { status: 'started' }, + }) + }) + + it('creates the worktree without optional options', async () => { + const worktreeCreate = vi.fn(async () => ({ directory: '/worktrees/feature-x' })) + const { service } = createService({ worktreeCreate }) + + await service.create(REPO) + + expect(worktreeCreate).toHaveBeenCalledWith({ projectID: 'project-1' }) + }) + }) + + describe('remove', () => { + it('throws a 400 when the directory is not a worktree sibling and touches nothing', async () => { + const worktreeRemove = vi.fn(async () => undefined) + const removeAll = vi.fn(async () => undefined) + mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/other', worktreeStrategy: 'git' }]) + const { service } = createService({ worktreeRemove, removeAll }) + + const error = await service.remove(REPO, '/worktrees/unknown').catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(RepoWorkspaceError) + expect(error).toMatchObject({ status: 400 }) + expect(removeAll).not.toHaveBeenCalled() + expect(worktreeRemove).not.toHaveBeenCalled() + }) + + it('removes terminals for the matched sibling before removing the worktree', async () => { + const worktreeRemove = vi.fn(async () => undefined) + const removeAll = vi.fn(async () => undefined) + mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git' }]) + const { service } = createService({ worktreeRemove, removeAll }) + + await service.remove(REPO, '/worktrees/feature-x') + + expect(removeAll).toHaveBeenCalledWith('/worktrees/feature-x') + expect(worktreeRemove).toHaveBeenCalledWith({ + projectID: 'project-1', + directory: '/worktrees/feature-x', + force: true, + }) + expect(removeAll.mock.invocationCallOrder[0]!).toBeLessThan(worktreeRemove.mock.invocationCallOrder[0]!) + }) + + it('logs a terminal removal failure and still removes the worktree', async () => { + const worktreeRemove = vi.fn(async () => undefined) + const removeAll = vi.fn(async () => { + throw new Error('pty cleanup failed') + }) + mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git' }]) + const { service } = createService({ worktreeRemove, removeAll }) + + await expect(service.remove(REPO, '/worktrees/feature-x')).resolves.toBeUndefined() + + expect(mocks.loggerWarn).toHaveBeenCalled() + expect(worktreeRemove).toHaveBeenCalledWith({ + projectID: 'project-1', + directory: '/worktrees/feature-x', + force: true, + }) + }) + }) + + describe('removeRepoTerminals', () => { + it('removes terminals for the repo directory and each worktree sibling', async () => { + const removeAll = vi.fn(async () => undefined) + mocks.getSiblingRepos.mockResolvedValue([ + { fullPath: '/worktrees/a', worktreeStrategy: 'git' }, + { fullPath: '/worktrees/b', worktreeStrategy: 'git' }, + { fullPath: '/repos/manager-worktree', isWorktree: true }, + ]) + const { service } = createService({ removeAll }) + + await service.removeRepoTerminals(REPO) + + expect(removeAll).toHaveBeenCalledWith('/repos/repo-a') + expect(removeAll).toHaveBeenCalledWith('/worktrees/a') + expect(removeAll).toHaveBeenCalledWith('/worktrees/b') + expect(removeAll).not.toHaveBeenCalledWith('/repos/manager-worktree') + }) + + it('still removes the repo terminals when listing siblings fails', async () => { + const removeAll = vi.fn(async () => undefined) + mocks.getSiblingRepos.mockRejectedValue(new Error('siblings failed')) + const { service } = createService({ removeAll }) + + await expect(service.removeRepoTerminals(REPO)).resolves.toBeUndefined() + + expect(removeAll).toHaveBeenCalledWith('/repos/repo-a') + expect(mocks.loggerWarn).toHaveBeenCalled() + }) + }) +}) diff --git a/backend/test/services/repo-workspaces.test.ts b/backend/test/services/repo-workspaces.test.ts deleted file mode 100644 index f8b8534b..00000000 --- a/backend/test/services/repo-workspaces.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import path from 'path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { Database } from 'bun:sqlite' -import { getReposPath } from '@opencode-manager/shared/config/env' -import type { OpenCodeClient } from '../../src/services/opencode/client' -import type { Repo } from '../../src/types/repo' -import { migrate } from '../../src/db/migration-runner' -import { allMigrations } from '../../src/db/migrations' - -const executeCommand = vi.fn() -const listRepos = vi.fn() -const resolveProjectId = vi.fn() -const isGitMainCheckout = vi.fn() -const getSettings = vi.fn() -const mkdirSafe = vi.fn() - -vi.mock('../../src/utils/fs-safe', () => ({ - mkdirSafe, - mkdirSyncSafe: vi.fn(), - canonicalPathSync: (target: string) => target, -})) - -vi.mock('../../src/services/settings', () => ({ - SettingsService: vi.fn().mockImplementation(() => ({ getSettings })), -})) - -vi.mock('../../src/services/project-id-resolver', () => ({ - resolveProjectId, - isGitMainCheckout, -})) - -vi.mock('../../src/utils/process', () => ({ - executeCommand, -})) - -vi.mock('../../src/db/queries', () => ({ - listRepos, -})) - -describe('repo workspace service', () => { - type WorktreeEntry = { directory: string; strategy?: string } - - let db: Database - - function createRepoRow(id: number, localPath: string, overrides: Partial = {}): Repo { - return { - id, - repoUrl: 'https://github.com/test/repo', - localPath, - fullPath: path.join(getReposPath(), localPath), - sourcePath: path.join(getReposPath(), localPath), - branch: 'main', - defaultBranch: 'main', - cloneStatus: 'ready', - clonedAt: Date.now(), - ...overrides, - } - } - - function createClient(worktrees: WorktreeEntry[], overrides: { - create?: OpenCodeClient['api']['worktree']['create'] - remove?: OpenCodeClient['api']['worktree']['remove'] - } = {}): OpenCodeClient { - return { - api: { - location: { - get: async () => ({ - directory: path.join(getReposPath(), 'repo-a'), - project: { id: 'commit-A', directory: path.join(getReposPath(), 'repo-a'), canonical: path.join(getReposPath(), 'repo-a') }, - }), - }, - worktree: { - list: async () => worktrees, - create: overrides.create ?? (async () => ({ directory: '/worktrees/feature-x' })), - remove: overrides.remove ?? (async () => undefined), - }, - }, - } as unknown as OpenCodeClient - } - - beforeEach(() => { - vi.clearAllMocks() - mkdirSafe.mockResolvedValue(undefined) - db = new Database(':memory:') - migrate(db, allMigrations) - getSettings.mockReturnValue({ preferences: { repoOrder: [] }, updatedAt: Date.now() }) - resolveProjectId.mockResolvedValue('commit-A') - isGitMainCheckout.mockResolvedValue(false) - listRepos.mockReturnValue([createRepoRow(1, 'repo-a')]) - executeCommand.mockImplementation(async (args: string[]) => { - if (args.includes('HEAD') && !args.includes('--abbrev-ref')) { - return 'abc123' - } - - if (args.includes('--abbrev-ref')) { - return 'main' - } - - return '' - }) - }) - - afterEach(() => { - db.close() - }) - - it('passes name and ref through to the worktree create call', async () => { - const { createRepoWorkspace } = await import('../../src/services/repo') - const create = vi.fn(async () => ({ directory: '/worktrees/feature-x' })) - const client = createClient([], { create }) - - const result = await createRepoWorkspace(client, createRepoRow(1, 'repo-a'), { name: 'feature-x', ref: 'feature/x' }) - - expect(create).toHaveBeenCalledWith({ projectID: 'commit-A', name: 'feature-x', branch: 'feature/x' }) - expect(result).toEqual({ directory: '/worktrees/feature-x' }) - }) - - it('creates a worktree without optional options', async () => { - const { createRepoWorkspace } = await import('../../src/services/repo') - const create = vi.fn(async () => ({ directory: '/worktrees/feature-x' })) - const client = createClient([], { create }) - - await createRepoWorkspace(client, createRepoRow(1, 'repo-a')) - - expect(create).toHaveBeenCalledWith({ projectID: 'commit-A' }) - }) - - it('rejects a directory that is not a worktree sibling of the repo', async () => { - const { removeRepoWorkspace, RepoWorkspaceError } = await import('../../src/services/repo') - const client = createClient([{ directory: '/worktrees/feature-x', strategy: 'git' }]) - - const error = await removeRepoWorkspace(db, client, {}, createRepoRow(1, 'repo-a'), '/worktrees/unknown').catch((caught: unknown) => caught) - - expect(error).toBeInstanceOf(RepoWorkspaceError) - expect(error).toMatchObject({ status: 400 }) - }) - - it('removes a matching worktree sibling with force', async () => { - const { removeRepoWorkspace } = await import('../../src/services/repo') - const remove = vi.fn(async () => undefined) - const client = createClient([{ directory: '/worktrees/feature-x', strategy: 'git' }], { remove }) - - await removeRepoWorkspace(db, client, {}, createRepoRow(1, 'repo-a'), '/worktrees/feature-x') - - expect(remove).toHaveBeenCalledWith({ projectID: 'commit-A', directory: '/worktrees/feature-x', force: true }) - }) -}) diff --git a/backend/test/services/session-launcher.test.ts b/backend/test/services/session-launcher.test.ts index e52fa29c..bc7401c7 100644 --- a/backend/test/services/session-launcher.test.ts +++ b/backend/test/services/session-launcher.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Database } from 'bun:sqlite' import type { OpenCodeClient } from '../../src/services/opencode/client' +import type { RepoWorkspaceService } from '../../src/services/repo-workspace' import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' import { createRepo } from '../../src/db/queries' @@ -20,33 +21,47 @@ interface FakeLaunchClient { client: OpenCodeClient create: ReturnType prompt: ReturnType - worktreeCreate: ReturnType } -function createClient( - overrides: { workspaceDirectory?: string; createError?: Error; worktreeCreateError?: Error } = {}, -): FakeLaunchClient { +function createClient(overrides: { createError?: Error } = {}): FakeLaunchClient { const create = vi.fn(async (input: { title?: string }) => { if (overrides.createError) throw overrides.createError return { id: 'ses_new', title: input?.title } }) const prompt = vi.fn(async () => ({})) - const worktreeCreate = vi.fn(async () => { - if (overrides.worktreeCreateError) throw overrides.worktreeCreateError - return { directory: overrides.workspaceDirectory ?? '/worktrees/feature-x' } - }) const client = { api: { - location: { - get: vi.fn(async () => ({ project: { id: 'commit-A', directory: REPO_DIR, canonical: REPO_DIR } })), - }, - worktree: { create: worktreeCreate }, session: { create, prompt }, }, } as unknown as OpenCodeClient - return { client, create, prompt, worktreeCreate } + return { client, create, prompt } +} + +interface FakeRepoWorkspaces { + service: RepoWorkspaceService + create: ReturnType + remove: ReturnType + removeRepoTerminals: ReturnType +} + +function createRepoWorkspaces( + overrides: { directory?: string; createError?: Error } = {}, +): FakeRepoWorkspaces { + const create = vi.fn(async () => { + if (overrides.createError) throw overrides.createError + return { directory: overrides.directory ?? '/worktrees/feature-x', worktreeSetup: { status: 'none' as const } } + }) + const remove = vi.fn(async () => undefined) + const removeRepoTerminals = vi.fn(async () => undefined) + + return { + service: { create, remove, removeRepoTerminals } as unknown as RepoWorkspaceService, + create, + remove, + removeRepoTerminals, + } } describe('SessionLauncher', () => { @@ -78,11 +93,13 @@ describe('SessionLauncher', () => { it('launches in the repo directory with the resolved model and sends the prompt', async () => { const repoId = readyRepo() const { client, create, prompt } = createClient() - const launcher = new SessionLauncher(db, client) + const { service, create: createWorkspace } = createRepoWorkspaces() + const launcher = new SessionLauncher(db, client, service) const result = await launcher.launch({ repoId, prompt: 'hello', title: 'T', agent: 'build', model: 'openai/gpt-5' }) expect(mocks.resolveOpenCodeModel).toHaveBeenCalledWith(client, REPO_DIR, { preferredModel: 'openai/gpt-5' }) + expect(createWorkspace).not.toHaveBeenCalled() expect(create).toHaveBeenCalledWith( expect.objectContaining({ title: 'T', @@ -104,8 +121,9 @@ describe('SessionLauncher', () => { it('launches in a new workspace and prompts there', async () => { const repoId = readyRepo() - const { client, create, worktreeCreate } = createClient() - const launcher = new SessionLauncher(db, client) + const { client, create } = createClient() + const { service, create: createWorkspace } = createRepoWorkspaces({ directory: '/worktrees/feature-x' }) + const launcher = new SessionLauncher(db, client, service) const result = await launcher.launch({ repoId, @@ -113,7 +131,10 @@ describe('SessionLauncher', () => { workspace: { name: 'feature-x', ref: 'feature/x' }, }) - expect(worktreeCreate).toHaveBeenCalledWith({ projectID: 'commit-A', name: 'feature-x', branch: 'feature/x' }) + expect(createWorkspace).toHaveBeenCalledWith( + expect.objectContaining({ id: repoId }), + { name: 'feature-x', ref: 'feature/x' }, + ) expect(mocks.resolveOpenCodeModel).toHaveBeenCalledWith(client, REPO_DIR, { preferredModel: undefined }) expect(create).toHaveBeenCalledWith(expect.objectContaining({ location: { directory: '/worktrees/feature-x' } })) expect(result).toMatchObject({ @@ -126,8 +147,9 @@ describe('SessionLauncher', () => { it('rejects an unavailable requested model before creating a workspace or session', async () => { const repoId = readyRepo() - const { client, create, worktreeCreate } = createClient() - const launcher = new SessionLauncher(db, client) + const { client, create } = createClient() + const { service, create: createWorkspace } = createRepoWorkspaces() + const launcher = new SessionLauncher(db, client, service) const error = await launcher .launch({ repoId, prompt: 'hello', model: 'openai/retired', workspace: { name: 'feature-x' } }) @@ -139,40 +161,41 @@ describe('SessionLauncher', () => { message: 'Model openai/retired is not available', workspaceDirectory: null, }) - expect(worktreeCreate).not.toHaveBeenCalled() + expect(createWorkspace).not.toHaveBeenCalled() expect(create).not.toHaveBeenCalled() }) it('slugs a raw workspace name before creating the workspace', async () => { const repoId = readyRepo() - const { client, worktreeCreate } = createClient({ workspaceDirectory: '/worktrees/Feature-Sweep' }) - const launcher = new SessionLauncher(db, client) + const { client } = createClient() + const { service, create: createWorkspace } = createRepoWorkspaces({ directory: '/worktrees/Feature-Sweep' }) + const launcher = new SessionLauncher(db, client, service) await launcher.launch({ repoId, prompt: 'hello', workspace: { name: 'Feature Sweep!' } }) - expect(worktreeCreate).toHaveBeenCalledWith({ projectID: 'commit-A', name: 'Feature-Sweep' }) + expect(createWorkspace).toHaveBeenCalledWith(expect.objectContaining({ id: repoId }), { name: 'Feature-Sweep' }) }) it('rejects a repo that is not ready', async () => { const repoId = readyRepo({ cloneStatus: 'cloning' }) const { client, create } = createClient() - const launcher = new SessionLauncher(db, client) + const { service, create: createWorkspace } = createRepoWorkspaces() + const launcher = new SessionLauncher(db, client, service) const error = await launcher.launch({ repoId, prompt: 'hello' }).catch((caught: unknown) => caught) expect(error).toBeInstanceOf(SessionLaunchError) expect(error).toMatchObject({ status: 404 }) expect(create).not.toHaveBeenCalled() + expect(createWorkspace).not.toHaveBeenCalled() expect(mocks.resolveOpenCodeModel).not.toHaveBeenCalled() }) it('keeps a created workspace and names it when session creation fails', async () => { const repoId = readyRepo() - const { client, worktreeCreate } = createClient({ - workspaceDirectory: '/worktrees/feature-x', - createError: new Error('boom'), - }) - const launcher = new SessionLauncher(db, client) + const { client } = createClient({ createError: new Error('boom') }) + const { service, create: createWorkspace } = createRepoWorkspaces({ directory: '/worktrees/feature-x' }) + const launcher = new SessionLauncher(db, client, service) const error = await launcher.launch({ repoId, prompt: 'hello', workspace: { name: 'feature-x' } }).catch( (caught: unknown) => caught, @@ -184,13 +207,14 @@ describe('SessionLauncher', () => { message: 'boom (workspace: /worktrees/feature-x)', workspaceDirectory: '/worktrees/feature-x', }) - expect(worktreeCreate).toHaveBeenCalled() + expect(createWorkspace).toHaveBeenCalled() }) it('exposes no workspace when workspace creation fails', async () => { const repoId = readyRepo() - const { client } = createClient({ worktreeCreateError: new Error('no workspace') }) - const launcher = new SessionLauncher(db, client) + const { client } = createClient() + const { service } = createRepoWorkspaces({ createError: new Error('no workspace') }) + const launcher = new SessionLauncher(db, client, service) const error = await launcher .launch({ repoId, prompt: 'hello', workspace: { name: 'feature-x' } }) diff --git a/backend/test/services/terminal.test.ts b/backend/test/services/terminal.test.ts new file mode 100644 index 00000000..75dee51b --- /dev/null +++ b/backend/test/services/terminal.test.ts @@ -0,0 +1,314 @@ +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 { getGhCliEnv: vi.fn(() => shellEnv) } as unknown as CredentialProvider +} + +function createTerminalService( + client: OpenCodeClient, + provider: CredentialProvider, + openSocket?: (url: string) => WebSocket, +): TerminalService { + return new TerminalService(client, provider, () => 'http://127.0.0.1:5551', openSocket) +} + +class FakeUpstreamSocket { + binaryType: 'blob' | 'arraybuffer' = 'blob' + readonly sent: Array = [] + readonly url: string + close = vi.fn() + private readonly listeners = new Map void>>() + + constructor(url: string) { + this.url = url + } + + addEventListener(type: string, listener: (event: unknown) => void): void { + const set = this.listeners.get(type) ?? new Set<(event: unknown) => void>() + set.add(listener) + this.listeners.set(type, set) + } + + send(data: string | Uint8Array): void { + this.sent.push(data) + } + + emit(type: string, event: unknown): void { + for (const listener of this.listeners.get(type) ?? []) listener(event) + } +} + +interface FakePeer { + sent: Array + closeCalls: Array<{ code?: number; reason?: string }> + send(data: string | Uint8Array): void + close(code?: number, reason?: string): void + bufferedAmount(): number +} + +function createPeer(): FakePeer { + const sent: Array = [] + const closeCalls: Array<{ code?: number; reason?: string }> = [] + return { + sent, + closeCalls, + send(data) { + sent.push(data) + }, + close(code, reason) { + closeCalls.push({ code, reason }) + }, + bufferedAmount() { + return 0 + }, + } +} + +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 = createTerminalService(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 = createTerminalService(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.getGhCliEnv).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 = createTerminalService(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 = createTerminalService(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 = createTerminalService(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 = createTerminalService(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 = createTerminalService(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 = createTerminalService(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 = createTerminalService(createClient({ list, remove }), createCredentialProvider()) + + await expect(service.removeAll('/repo')).rejects.toThrow('boom') + }) + }) + + describe('connect', () => { + function createConnectClient(options: { ticket?: string; terminals?: PtyRecord[] } = {}) { + const list = vi.fn(async ({ location }: { location: { directory: string } }) => ({ + location, + data: options.terminals ?? [createPty({ id: 'pty-1' })], + })) + const token = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: { ticket: options.ticket ?? 'ticket-abc', expires_in: 60 }, + })) + return { client: { api: { pty: { list, connect: { token } } } } as unknown as OpenCodeClient, list, token } + } + + it('resolves the terminal, requests a ticket, and bridges the upstream socket', async () => { + const { client, list, token } = createConnectClient() + let opened: FakeUpstreamSocket | undefined + const service = createTerminalService(client, createCredentialProvider(), (url) => { + opened = new FakeUpstreamSocket(url) + return opened as unknown as WebSocket + }) + const peer = createPeer() + + const bridge = await service.connect('/repo', 'pty-1', 12, peer) + + expect(list).toHaveBeenCalledWith({ location: { directory: '/repo' } }) + expect(token).toHaveBeenCalledWith({ + ptyID: 'pty-1', + location: { directory: '/repo' }, + 'x-opencode-ticket': '1', + }) + + expect(opened).toBeDefined() + const url = new URL(opened!.url) + expect(url.protocol).toBe('ws:') + expect(url.pathname).toBe('/api/pty/pty-1/connect') + expect(url.searchParams.get('ticket')).toBe('ticket-abc') + expect(url.searchParams.get('location[directory]')).toBe('/repo') + expect(url.searchParams.get('cursor')).toBe('12') + + opened!.emit('open', {}) + bridge.send('hello') + expect(opened!.sent).toEqual(['hello']) + + opened!.emit('message', { data: new Uint8Array([7]).buffer }) + expect(peer.sent).toEqual([new Uint8Array([7])]) + }) + + it('omits the cursor parameter when no cursor is provided', async () => { + const { client } = createConnectClient() + let opened: FakeUpstreamSocket | undefined + const service = createTerminalService(client, createCredentialProvider(), (url) => { + opened = new FakeUpstreamSocket(url) + return opened as unknown as WebSocket + }) + + await service.connect('/repo', 'pty-1', undefined, createPeer()) + + const url = new URL(opened!.url) + expect(url.searchParams.has('cursor')).toBe(false) + }) + + it('rejects an unknown terminal before requesting a ticket', async () => { + const { client, token } = createConnectClient({ terminals: [] }) + const service = createTerminalService(client, createCredentialProvider()) + + await expect(service.connect('/repo', 'missing', undefined, createPeer())).rejects.toBeInstanceOf(TerminalNotFoundError) + expect(token).not.toHaveBeenCalled() + }) + }) +}) diff --git a/backend/test/shared/terminal-title.test.ts b/backend/test/shared/terminal-title.test.ts new file mode 100644 index 00000000..39667579 --- /dev/null +++ b/backend/test/shared/terminal-title.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' +import { formatTerminalTitle, isRunningActionTerminal, 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' }) + }) + }) + + describe('isRunningActionTerminal', () => { + it('matches a running action terminal for the action id', () => { + expect(isRunningActionTerminal({ kind: 'action', actionId: 'dev', status: 'running' }, 'dev')).toBe(true) + }) + + it('rejects a terminal for a different action id', () => { + expect(isRunningActionTerminal({ kind: 'action', actionId: 'other', status: 'running' }, 'dev')).toBe(false) + }) + + it('rejects a non-action terminal', () => { + expect(isRunningActionTerminal({ kind: 'shell', status: 'running' }, 'dev')).toBe(false) + }) + + it('rejects an exited action terminal', () => { + expect(isRunningActionTerminal({ kind: 'action', actionId: 'dev', status: 'exited' }, 'dev')).toBe(false) + }) + }) +}) diff --git a/backend/test/utils/fs-safe.test.ts b/backend/test/utils/fs-safe.test.ts index e517accf..61b75494 100644 --- a/backend/test/utils/fs-safe.test.ts +++ b/backend/test/utils/fs-safe.test.ts @@ -1,8 +1,8 @@ -import { mkdtemp, realpath, rm } from 'node:fs/promises' +import { mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { canonicalPath, canonicalPathSync } from '../../src/utils/fs-safe' +import { canonicalPath, canonicalPathSync, writeFileAtomicSync } from '../../src/utils/fs-safe' describe('canonicalPath', () => { let workDir = '' @@ -29,3 +29,41 @@ describe('canonicalPath', () => { expect(canonicalPathSync(missing)).toBe(missing) }) }) + +describe('writeFileAtomicSync', () => { + let workDir = '' + + beforeEach(async () => { + workDir = await mkdtemp(path.join(tmpdir(), 'fs-safe-atomic-')) + }) + + afterEach(async () => { + await rm(workDir, { recursive: true, force: true }) + }) + + it('writes the content and creates missing parent directories', async () => { + const target = path.join(workDir, 'nested', 'file.json') + + writeFileAtomicSync(target, '{"ok":true}', { mode: 0o644 }) + + await expect(readFile(target, 'utf8')).resolves.toBe('{"ok":true}') + expect((await stat(target)).mode & 0o777).toBe(0o644) + }) + + it('overwrites an existing file', async () => { + const target = path.join(workDir, 'file.txt') + await writeFile(target, 'old') + + writeFileAtomicSync(target, 'new') + + await expect(readFile(target, 'utf8')).resolves.toBe('new') + }) + + it('leaves no temp files behind', async () => { + const target = path.join(workDir, 'file.txt') + + writeFileAtomicSync(target, 'content') + + await expect(readdir(workDir)).resolves.toEqual(['file.txt']) + }) +}) diff --git a/backend/test/utils/websocket-bridge.test.ts b/backend/test/utils/websocket-bridge.test.ts new file mode 100644 index 00000000..cdf00630 --- /dev/null +++ b/backend/test/utils/websocket-bridge.test.ts @@ -0,0 +1,187 @@ +import { describe, it, expect, vi } from 'vitest' +import { + bridgeWebSocket, + forwardPeerMessage, + MAX_PEER_BUFFERED_BYTES, + type WebSocketBridge, + type WebSocketPeer, +} from '../../src/utils/websocket-bridge' + +type Listener = (event: unknown) => void + +class FakeUpstream { + binaryType: 'blob' | 'arraybuffer' = 'blob' + sent: Array = [] + private readonly listeners = new Map>() + + addEventListener(type: string, listener: Listener): void { + const set = this.listeners.get(type) ?? new Set() + set.add(listener) + this.listeners.set(type, set) + } + + send(data: string | Uint8Array): void { + this.sent.push(data) + } + + close = vi.fn() + + emit(type: string, event: unknown): void { + for (const listener of this.listeners.get(type) ?? []) listener(event) + } +} + +interface FakePeer extends WebSocketPeer { + sent: Array + closeCalls: Array<{ code?: number; reason?: string }> + buffered: number +} + +function createPeer(): FakePeer { + const peer: FakePeer = { + sent: [], + closeCalls: [], + buffered: 0, + send(data) { + peer.sent.push(data) + }, + close(code, reason) { + peer.closeCalls.push({ code, reason }) + }, + bufferedAmount() { + return peer.buffered + }, + } + return peer +} + +function asUpstream(upstream: FakeUpstream): WebSocket { + return upstream as unknown as WebSocket +} + +describe('bridgeWebSocket', () => { + it('requests arraybuffer frames from the upstream', () => { + const upstream = new FakeUpstream() + bridgeWebSocket(asUpstream(upstream), createPeer()) + expect(upstream.binaryType).toBe('arraybuffer') + }) + + it('queues client sends until the upstream opens and preserves order', () => { + const upstream = new FakeUpstream() + const bridge = bridgeWebSocket(asUpstream(upstream), createPeer()) + + bridge.send('first') + bridge.send(new Uint8Array([1, 2])) + expect(upstream.sent).toEqual([]) + + upstream.emit('open', {}) + + expect(upstream.sent).toEqual(['first', new Uint8Array([1, 2])]) + }) + + it('forwards text as text and binary as bytes to the peer', () => { + const upstream = new FakeUpstream() + const peer = createPeer() + bridgeWebSocket(asUpstream(upstream), peer) + + upstream.emit('message', { data: 'plain text' }) + upstream.emit('message', { data: new Uint8Array([0, 1, 2]).buffer }) + + expect(peer.sent[0]).toBe('plain text') + expect(peer.sent[1]).toEqual(new Uint8Array([0, 1, 2])) + }) + + it('passes a normal close through and maps abnormal codes to 1011', () => { + const normalUpstream = new FakeUpstream() + const normalPeer = createPeer() + bridgeWebSocket(asUpstream(normalUpstream), normalPeer) + normalUpstream.emit('close', { code: 4404 }) + expect(normalPeer.closeCalls).toEqual([{ code: 4404, reason: undefined }]) + + const cleanUpstream = new FakeUpstream() + const cleanPeer = createPeer() + bridgeWebSocket(asUpstream(cleanUpstream), cleanPeer) + cleanUpstream.emit('close', { code: 1000 }) + expect(cleanPeer.closeCalls).toEqual([{ code: 1000, reason: undefined }]) + + const abnormalUpstream = new FakeUpstream() + const abnormalPeer = createPeer() + bridgeWebSocket(asUpstream(abnormalUpstream), abnormalPeer) + abnormalUpstream.emit('close', { code: 1006 }) + expect(abnormalPeer.closeCalls).toEqual([{ code: 1011, reason: undefined }]) + }) + + it('closes the peer with 1011 on an upstream error', () => { + const upstream = new FakeUpstream() + const peer = createPeer() + bridgeWebSocket(asUpstream(upstream), peer) + + upstream.emit('error', {}) + + expect(peer.closeCalls).toEqual([{ code: 1011, reason: undefined }]) + }) + + it('closes the upstream and peer with 1013 when the peer buffer overflows', () => { + const upstream = new FakeUpstream() + const peer = createPeer() + peer.buffered = MAX_PEER_BUFFERED_BYTES + 1 + + bridgeWebSocket(asUpstream(upstream), peer) + upstream.emit('message', { data: 'overflow' }) + + expect(peer.closeCalls).toEqual([{ code: 1013, reason: 'Client too slow' }]) + expect(upstream.close).toHaveBeenCalledTimes(1) + + upstream.emit('close', { code: 1000 }) + expect(peer.closeCalls).toHaveLength(1) + }) + + it('keeps bridging while the peer buffer stays within the limit', () => { + const upstream = new FakeUpstream() + const peer = createPeer() + peer.buffered = MAX_PEER_BUFFERED_BYTES + + bridgeWebSocket(asUpstream(upstream), peer) + upstream.emit('message', { data: 'within limit' }) + + expect(peer.sent).toEqual(['within limit']) + expect(peer.closeCalls).toEqual([]) + expect(upstream.close).not.toHaveBeenCalled() + }) + + it('closes the upstream only once and ignores later sends', () => { + const upstream = new FakeUpstream() + const bridge = bridgeWebSocket(asUpstream(upstream), createPeer()) + + bridge.close() + bridge.close() + bridge.send('after close') + + expect(upstream.close).toHaveBeenCalledTimes(1) + expect(upstream.sent).toEqual([]) + }) +}) + +describe('forwardPeerMessage', () => { + function createBridge(sent: Array): WebSocketBridge { + return { + send(data) { + sent.push(data) + }, + close() {}, + } + } + + it('forwards strings, ArrayBuffers and Blobs to the bridge', async () => { + const sent: Array = [] + const bridge = createBridge(sent) + + await forwardPeerMessage(bridge, 'plain text') + await forwardPeerMessage(bridge, new Uint8Array([1, 2]).buffer) + await forwardPeerMessage(bridge, new Blob(['blob body'])) + + expect(sent[0]).toBe('plain text') + expect(sent[1]).toEqual(new Uint8Array([1, 2]).buffer) + expect(new TextDecoder().decode(sent[2] as ArrayBuffer)).toBe('blob body') + }) +}) diff --git a/docker-compose.yml b/docker-compose.yml index 2935e843..c28413c3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,6 +8,7 @@ services: container_name: opencode-manager ports: - "5003:5003" + - "5004:5004" - "5100:5100" - "5101:5101" - "5102:5102" diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md index 029c2029..6318fbff 100644 --- a/docs/configuration/docker.md +++ b/docs/configuration/docker.md @@ -40,6 +40,7 @@ services: container_name: opencode-manager ports: - "5003:5003" + - "5004:5004" - "5100:5100" - "5101:5101" - "5102:5102" @@ -157,7 +158,14 @@ ports: ### Dev Server Ports -Ports 5100-5103 are exposed for running dev servers inside repositories: +Port 5004 is the [preview gateway](../features/preview.md). It proxies a running dev server through an authenticated origin and supports HMR, so it is the recommended way to view a dev server: + +```yaml +ports: + - "5004:5004" +``` + +Ports 5100-5103 remain exposed for running dev servers inside repositories and reaching them directly: ```yaml ports: @@ -167,6 +175,8 @@ ports: - "5103:5103" ``` +Exposing these raw ports bypasses the preview gateway's authentication and same-origin isolation. Prefer the gateway unless you need direct access to a dev server. + Configure your dev server to use one of these ports: === "Vite" diff --git a/docs/configuration/environment.md b/docs/configuration/environment.md index 004e9ad6..dea83f9a 100644 --- a/docs/configuration/environment.md +++ b/docs/configuration/environment.md @@ -10,7 +10,7 @@ Complete reference for all configuration options. | `ADMIN_EMAIL` | Pre-configured admin email | - | | `ADMIN_PASSWORD` | Pre-configured admin password | - | | `ADMIN_PASSWORD_RESET` | Set to `true` to reset admin password | `false` | -| `AUTH_TRUSTED_ORIGINS` | Comma-separated list of trusted origins (frontend + backend) | `http://localhost:5173,http://localhost:5003` | +| `AUTH_TRUSTED_ORIGINS` | Comma-separated list of trusted origins (frontend + backend). Browser requests that change state from another site (`Sec-Fetch-Site: same-site` or `cross-site`) are rejected unless their `Origin` is listed here. Never list the preview gateway origin. | `http://localhost:5173,http://localhost:5003` | | `AUTH_SECURE_COOKIES` | Use secure cookies (HTTPS only) | Runtime: `true` in prod, `false` in dev; Compose: `false` unless set | ## OAuth Providers @@ -76,6 +76,15 @@ When configured, users can enable push notifications in Settings → Notificatio | `LOG_LEVEL` | Accepted but currently unused; debug output is controlled by `DEBUG` | `info` | | `DEBUG` | Enable debug logging | `false` | +## Preview Gateway + +The preview gateway serves dev servers through an authenticated, separate origin (see [Preview](../features/preview.md)). + +| Variable | Description | Default | +|----------|-------------|---------| +| `PREVIEW_PORT` | Port for the preview gateway. Set to `0` to disable preview entirely. If the port is already in use, the Manager starts anyway, logs a warning and reports preview as unavailable. | `5004` | +| `PREVIEW_PUBLIC_URL` | Same-site HTTPS origin that proxies the preview gateway; do not add it to `AUTH_TRUSTED_ORIGINS`. Set this when the Manager is served over HTTPS or behind a reverse proxy, where mixed content and third-party cookies otherwise block the preview iframe. | empty | + ## Database | Variable | Description | Default | diff --git a/docs/features/assistant-internal-api.md b/docs/features/assistant-internal-api.md index f174cb2d..b05f4b9a 100644 --- a/docs/features/assistant-internal-api.md +++ b/docs/features/assistant-internal-api.md @@ -93,7 +93,7 @@ POST /sessions/*/fork **Deliberately not allow-listed:** - `POST /notifications/send` — use the `send_notification` action instead. -- `GET /git-credentials/gh-env` — returns the GitHub CLI environment (`GH_TOKEN`, `GITHUB_TOKEN`) for the OpenCode host process; it must not be readable by the agent. +- `GET /git-credentials/gh-env` — returns the GitHub CLI environment (`GH_TOKEN`, `GITHUB_TOKEN`) for a working directory for the OpenCode host process; it must not be readable by the agent. - `POST /sandbox/shell` — the sandbox planner's internal route that resolves and pins the shell for a `shell` call; exposing it would let the agent drive shell planning directly. - `/repos/*/mirror/*` — the repo mirror protocol that the `ocm` CLI uses to sync entire repositories; it can create, replace, patch, or delete whole repos, so it stays reserved for the CLI. diff --git a/docs/features/overview.md b/docs/features/overview.md index 85586807..1917d807 100644 --- a/docs/features/overview.md +++ b/docs/features/overview.md @@ -26,6 +26,14 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI [Learn more →](files.md) +### Terminal & Dev Loop + +- **Terminal** — Interactive PTY terminals scoped to a repo or workspace directory, with tabs and reconnect after reload +- **Project Actions** — Run and stop repo commands from the header menu, with shared `.ocm/project.json` actions and worktree setup commands +- **Preview** — View a running dev server through an authenticated, same-origin-safe preview gateway with HMR support + +[Terminal →](terminal.md) · [Project Actions →](project-actions.md) · [Preview →](preview.md) + ### Chat & Sessions - **Real-time Streaming** - Live message streaming with SSE diff --git a/docs/features/preview.md b/docs/features/preview.md new file mode 100644 index 00000000..63be9eac --- /dev/null +++ b/docs/features/preview.md @@ -0,0 +1,71 @@ +# Preview + +Open a running dev server inside the WebUI through an authenticated gateway. + +The Preview panel lists the loopback ports that are currently listening, then proxies the selected one through a dedicated gateway origin. This lets you view a Vite, Next.js, or other dev server without exposing its raw port or weakening the Manager's own origin. + +## Port List + +Open **Preview** from the desktop sidebar tool list or the **More** drawer, including in the Assistant workspace. The panel lists every listening loopback port on the host, with its port number and process command. On Linux hosts (including the Docker image) it also shows each process's working directory, and ports inside the selected repository or workspace directory are badged **this repo** and sorted first. On macOS the working directory is not available, so no port is badged. Other platforms list no ports. + +The list excludes reserved ports — the Manager port (`PORT`, default 5003), the OpenCode server port (default 5551) and the preview gateway port itself — and only includes ports at or above 1024. Any other listening loopback port can be previewed; there is no per-port allow-list. This grants nothing an authenticated user does not already have, because the [Terminal](terminal.md) can reach the same ports. + +While the port list is shown it refreshes every 2 seconds. It stops refreshing while a preview is open. + +Selecting a port creates a preview session and renders the target in an iframe on the gateway origin. The iframe keeps that origin (`allow-same-origin`) so dev servers can use cookies and storage; isolation from the Manager comes from the separate origin, not from an opaque sandbox. Selecting a different port starts a new session for it. + +When preview is unavailable — `PREVIEW_PORT=0`, or the gateway could not listen on its port — the panel shows **Preview is unavailable**. + +If the requested port is not listening yet, the panel shows **Waiting for port N…** and refetches the list every 2 seconds for up to 60 seconds, then shows an error with a **Retry** button. + +## Gateway + +The preview gateway listens on `PREVIEW_PORT` (default 5004) on its own origin. It is a separate origin from the Manager on purpose: preview content is untrusted and must not share the Manager origin. Setting `PREVIEW_PORT=0` disables the gateway. If the port is already in use, the Manager still starts, logs a warning, and reports preview as unavailable. + +Access requires an authenticated preview session: + +1. The Manager API mints a **single-use start token** for a listening port. +2. The browser navigates to `/__ocm_preview/start?token=…&path=…` on the gateway origin. +3. The gateway consumes the token (it expires after 60 seconds and cannot be reused) and sets an `ocm_preview` session cookie. + +Requests then carry the cookie. Manager auth cookies are stripped before proxying, because host-scoped cookies are shared across ports; the preview target never sees them. In the other direction, any `Set-Cookie` from the preview target that names a Manager auth cookie or `ocm_preview` is dropped, so preview content cannot overwrite the Manager session. The start `path` must stay on the gateway origin; anything else redirects to `/`. + +The gateway asks the target for uncompressed responses. When you use the preview remotely, put a compressing reverse proxy in front of it. + +The gateway also proxies **WebSocket upgrades** on the same origin, so dev-server HMR works through the panel. + +### Isolation level + +A gateway on another port of the same host — or a `PREVIEW_PUBLIC_URL` on a subdomain of the Manager's domain — is a different origin but the **same site** as the Manager, so the browser still sends the Manager's `SameSite=Lax` session cookie with requests from preview content. The Manager therefore rejects state-changing API requests (`POST`, `PUT`, `PATCH`, `DELETE`) whose `Sec-Fetch-Site` is `same-site` or `cross-site` unless their `Origin` is listed in `AUTH_TRUSTED_ORIGINS`. Never add the preview gateway origin to `AUTH_TRUSTED_ORIGINS`. + +A browser can hold one preview target per gateway origin at a time: the `ocm_preview` cookie names a single session. Opening a different port replaces the current target. + +## Opening Previews + +A preview can be opened from more than one place: + +- **Port list** — select a port in the panel. +- **Terminal links** — clicking a local dev URL (`http://localhost:PORT`, `127.0.0.1`, `0.0.0.0`, or `[::1]`) printed in a terminal opens the Preview panel at that port and path instead of a new browser tab. External links still open in a new tab. +- **Project actions** — an action's resolved URL opens in the Preview panel when **Auto-open URL** is enabled. + +## Toolbar + +- **Path** — enter a path and press **Go** (or Enter) to start a session for that path. +- **Reload** — remounts the iframe. +- **Open in new tab** — creates a fresh session and opens its start URL in a new tab with `noopener`. Start tokens are single-use, so this always mints a new one. +- **Viewport** — switch between Mobile (390 px), Tablet (820 px), and Full width. + +## Behind HTTPS or a Reverse Proxy + +By default the panel builds the gateway origin as `${location.protocol}//${location.hostname}:${PREVIEW_PORT}`. When the Manager is served over HTTPS (directly or behind a reverse proxy), the browser blocks the iframe for two reasons: + +- **Mixed content** — an `https://` page cannot embed an `http://` preview. +- **Third-party cookies** — the `ocm_preview` cookie is blocked in a cross-site iframe. + +Set `PREVIEW_PUBLIC_URL` to a same-site HTTPS origin that proxies the preview gateway, for example `https://preview.example.com`. Do not add it to `AUTH_TRUSTED_ORIGINS` (see [Isolation level](#isolation-level)). The panel then builds preview URLs from that origin instead. As a fallback, **Open in new tab** opens the preview as a top-level page, where the session cookie is first-party. + +## Related + +- [Environment Variables](../configuration/environment.md) — `PREVIEW_PORT` and `PREVIEW_PUBLIC_URL`. +- [Docker](../configuration/docker.md) — exposing the preview gateway port. +- [Terminal & Dev Loop](terminal.md) — start a dev server in a terminal. diff --git a/docs/features/project-actions.md b/docs/features/project-actions.md new file mode 100644 index 00000000..82afa1ef --- /dev/null +++ b/docs/features/project-actions.md @@ -0,0 +1,113 @@ +# Project Actions + +Define repeatable commands for a repository and run them from the header menu. + +Project actions are long-lived commands — a dev server, a build watcher, a test runner — that run in a terminal. They are configured in one of two places: + +- **My settings** (personal) — stored in the Manager database, keyed to the repository's main checkout, so they apply across the repository and all its worktrees. +- **The repository file** — `.ocm/project.json` at the repo root, committed and shared with everyone who clones it. + +Both sources are merged in the **Project Actions** dialog and the header menu. + +## Actions + +An action has these fields: + +| Field | Description | +|-------|-------------| +| `id` | Stable identifier. Letters, digits, `_` and `-`, up to 64 characters. | +| `name` | Label shown in the menu, up to 60 characters. | +| `command` | Shell command, up to 4000 characters. | +| `icon` | Optional icon: `play`, `build`, `test`, `lint`, `terminal`, `server`, `bug`, or `rocket`. | +| `url` | Optional URL template opened for the action. | +| `autoOpenUrl` | When enabled, the resolved URL opens automatically after the action starts. | + +Actions run as `/bin/sh -c ` in a PTY. Starting an action that is already running focuses its existing terminal instead of starting a second process. Stopping an action removes its PTY. + +### URL Templates + +The `url` field accepts two placeholders: + +| Placeholder | Resolves to | +|-------------|-------------| +| `{worktree}` | The basename of the current directory. | +| `{branch}` | The current git branch of the directory, from `git rev-parse --abbrev-ref HEAD`. | + +For example, `http://localhost:5173/{worktree}` becomes `http://localhost:5173/feature-login` in a worktree named `feature-login`. If `{branch}` cannot be resolved (for example, a detached HEAD with no branch), the template is left unchanged. + +When the resolved URL is a local dev URL (`http://localhost:PORT`, `127.0.0.1`, `0.0.0.0`, or `[::1]`), it opens in the [Preview](preview.md) panel rather than a new browser tab. + +## Running and Stopping + +The repository and session headers show a **Project actions** play button. The menu lists every configured action: + +- Select an action to start it. The terminal opens automatically. +- A running action shows a dot. Select **Stop** under it to remove its PTY. +- Select **Manage actions…** to open the Project Actions dialog. + +Actions defined in the repository file never run until trusted (see [Trust](#trust)). + +## Repository Configuration File + +`.ocm/project.json` defines actions and worktree setup commands for the repository. The format: + +```json +{ + "version": 1, + "projectActions": [ + { + "id": "dev", + "name": "Dev server", + "command": "pnpm dev", + "icon": "server", + "url": "http://localhost:5173/{worktree}", + "autoOpenUrl": true + } + ], + "setupWorktree": [ + "pnpm install" + ] +} +``` + +- `version` is required and must be `1`. +- `projectActions` and `setupWorktree` are optional. Up to 50 actions and 20 setup commands are allowed. +- An action `url` must start with `http://` or `https://`. +- A repository action whose `id` matches a personal action is not listed or run, and the dialog reports a warning, so personal actions always win. It is still part of the file's trusted content (see [Trust](#trust)). +- `.ocm` and `.ocm/project.json` must be regular files and directories. A symbolic link at either path is reported as an invalid file and is never written through. +- The file is read from the selected repository or workspace directory, so each worktree can carry its own version. Trust is stored once per project, so trusting the file in one worktree does not trust a different version of it in another. + +Project actions are not available in the Assistant workspace. + +## Moving Actions and Setup Commands + +The Project Actions dialog moves items between personal settings and the repository file: + +- **Move to repository** writes the item into `.ocm/project.json` and removes it from personal settings. Because the user authored it, the file is trusted automatically. +- **Move to my settings** removes the item from `.ocm/project.json` (deleting the file if it becomes empty) and stores it in personal settings. + +Moves are transactional: if the file write or the settings update fails, the file is restored. + +## Trust + +Commands in `.ocm/project.json` run on your machine, so the Manager does not run them until you trust the file: + +- Trust covers everything in the file that can run or open: each action's `id`, `name`, `command`, `url` and `autoOpenUrl` (including actions hidden because a personal action has the same `id`), plus every setup command. Changing any of these resets trust; changing an icon does not. +- Both trust prompts — **Trust these commands** in the dialog and **Trust and run** in the header menu — list every action and setup command that trusting covers, not only the one you clicked. +- Trusting requires echoing the exact hash of the content shown, so a file cannot be swapped between review and trust. +- Untrusted repository commands never run — not from the header menu, and not as worktree setup commands. +- The dialog shows the untrusted commands and a **Trust these commands** button. Attempting to run an untrusted action prompts for trust first. +- Moving an item into the file auto-trusts it, because the user authored it. + +## Worktree Setup Commands + +Setup commands run once after a new working directory is created — Manager worktrees and every OpenCode workspace, including workspaces created by multi-run and by agents through `ocm`. They run in a PTY with `set -e`, so the first failing command stops the rest. + +- `$ROOT_PROJECT_PATH` is available in the environment and points at the repository's main checkout. +- Personal setup commands always run. Repository setup commands are skipped while the file is untrusted; the skipped result is reported. +- Setup commands are configured in the **Worktree setup** section of the Project Actions dialog. + +## Related + +- [Terminal & Dev Loop](terminal.md) — the PTY terminals actions run in. +- [Preview](preview.md) — open an action's URL in the preview panel. diff --git a/docs/features/sandboxing.md b/docs/features/sandboxing.md index b683f980..2dfa1c4b 100644 --- a/docs/features/sandboxing.md +++ b/docs/features/sandboxing.md @@ -18,7 +18,7 @@ The microVM sees repositories through bind mounts at the same paths used by the | WebUI `!command` shell mode (`POST /api/session/:sessionID/shell`) | Yes; it spawns through the same `Shell.create` path as the `shell` tool, so it is planned and routed into the microVM. It is not badged in the UI because the surface fires no `tool.execute.after` hook | | Shell API (`POST /api/shell`) | Yes; it spawns through the same `Shell.create` path as the `shell` tool. It is not badged in the UI because the surface fires no `tool.execute.after` hook | | Slash-command shell templates (`` !`cmd` ``, `POST /api/session/:sessionID/command`) | No; OpenCode expands each interpolation itself with the configured shell, directly on the host and outside `Shell.create`, so the `create.before` hook never sees it | -| PTY terminals (`POST /api/pty`, `POST /api/pty/:ptyID/connect`) | No; normal OpenCode behavior, with the user's configured shell | +| PTY terminals (`POST /api/pty`, `POST /api/pty/:ptyID/connect`), including the Manager Terminal panel and project action terminals | No; normal OpenCode behavior, with the user's configured shell. Manager terminals and project actions receive the repo-scoped GitHub token env through `CredentialProvider.getGhCliEnv` at creation; commits take their identity from git config | | OpenCode file tools | No; while enforcement is on they are denied the global configuration directory (see [Mounts and Secrets](#mounts-and-secrets)) | | Manager-side git operations | No | | Plugins and custom tools | No; normal OpenCode behavior | @@ -49,7 +49,7 @@ Configured extensions execute with OpenCode's normal host-process privileges. Th WebUI `!command` shell mode and the shell API (`POST /api/shell`) **are** sandboxed: both spawn through the same `Shell.create` path as the `shell` tool, so they are planned and routed into the microVM. -PTY terminals follow OpenCode's normal host-process behavior during enforcement and use the user's configured shell. Slash-command shell templates are not sandboxed either: when a command template contains a `` !`cmd` `` interpolation, OpenCode resolves the configured shell and runs the command directly on the host before the resulting prompt is sent, without going through `Shell.create` or its `create.before` hook. That interpolation is trusted configuration outside the agent `shell` isolation boundary. +PTY terminals follow OpenCode's normal host-process behavior during enforcement and use the user's configured shell. This includes the Manager [Terminal panel](terminal.md) and [project actions](project-actions.md): they run as OpenCode PTYs on the host, receive the repo-scoped GitHub token env through `CredentialProvider.getGhCliEnv` at creation, take their commit identity from git config, and still bypass the sandbox shell hook. Slash-command shell templates are not sandboxed either: when a command template contains a `` !`cmd` `` interpolation, OpenCode resolves the configured shell and runs the command directly on the host before the resulting prompt is sent, without going through `Shell.create` or its `create.before` hook. That interpolation is trusted configuration outside the agent `shell` isolation boundary. There is no fallback to a host shell in the `Shell.create` path: the shim refuses to run without a pinned sandbox working directory, so a spawn whose plan, shim, or lock is unavailable is refused instead of running on the host. diff --git a/docs/features/terminal.md b/docs/features/terminal.md new file mode 100644 index 00000000..bab71f1d --- /dev/null +++ b/docs/features/terminal.md @@ -0,0 +1,47 @@ +# Terminal & Dev Loop + +Run interactive shells against a repository or workspace directory without leaving the WebUI. + +## Opening a Terminal + +Open the terminal from either surface: + +- **Desktop sidebar** — click **Terminal** in the tool list for a repository or session. +- **More drawer** — on mobile or from the overflow menu, open **More** and select **Terminal**. + +The terminal panel opens as a dialog. If no terminal exists for the selected directory yet, the panel starts one automatically. + +Terminals are scoped to the selected repository or OpenCode workspace directory. A terminal opened from a repo runs in that repo's path; a terminal opened from a session runs in the session's working directory. Switching directories shows that directory's terminals. + +## Tabs and Reconnect + +Each terminal runs in its own tab: + +- Click **+** to create another terminal in the same directory. +- Click a tab to focus it. +- Click the **×** on a tab to close it. Closing a running terminal asks for confirmation, then stops the process. +- An exited terminal keeps its tab and shows `exited` with its exit code. + +Terminals are backed by OpenCode PTYs, so they survive a browser close or reload: reopening the panel reattaches and replays the buffered output. They do **not** survive an OpenCode restart, which ends every PTY. + +## Mobile Key Bar + +On mobile, the panel shows a key bar above the keyboard with keys that are awkward to reach on a soft keyboard: + +- **Esc**, **Tab** +- **Ctrl** — tap to arm, then tap a key to send the modified combination; arming is consumed by the next key. +- Arrow keys +- `|`, `~`, `/` + +## Runtime and Environment + +Terminals run as OpenCode PTYs on the host, using the user's configured shell. They are **not sandboxed**: sandbox enforcement applies to agent `shell` tool calls, not to PTY terminals (see [Agent Sandboxing](sandboxing.md)). + +Each terminal receives the repository's GitHub token environment (`GH_TOKEN`, `GITHUB_TOKEN`) resolved for its directory, so `gh` authenticates with the repo's GitHub credential. Commits made in the terminal take their author from git config: the repository's own identity when one is set, otherwise the Manager default identity (see [Git identities](git.md)). + +`git` itself authenticates with the same credentials as the OpenCode server process, which the Manager configures from its saved git credentials. + +## Related + +- [Project Actions](project-actions.md) — run and stop long-lived commands as terminals from the header menu. +- [Preview](preview.md) — open a dev server started in a terminal. diff --git a/frontend/package.json b/frontend/package.json index 58a65cc4..ed03830f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -29,6 +29,9 @@ "@radix-ui/react-tabs": "^1.1.13", "@tailwindcss/vite": "^4.1.14", "@tanstack/react-query": "^5.90.5", + "@xterm/addon-fit": "^0.11.0", + "@xterm/addon-web-links": "^0.12.0", + "@xterm/xterm": "^6.0.0", "better-auth": "^1.4.17", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/frontend/src/api/preview.ts b/frontend/src/api/preview.ts new file mode 100644 index 00000000..4e3139f7 --- /dev/null +++ b/frontend/src/api/preview.ts @@ -0,0 +1,36 @@ +import { useQuery } from '@tanstack/react-query' +import type { CreatePreviewSessionResponse, PreviewPortsResponse } from '@opencode-manager/shared/types' +import { API_BASE_URL } from '@/config' +import { fetchWrapper } from './fetchWrapper' + +function previewPortsQueryKey(directory: string | undefined) { + return ['previewPorts', directory ?? null] as const +} + +function listPreviewPorts(directory?: string): Promise { + return fetchWrapper(`${API_BASE_URL}/api/preview/ports`, { + params: { directory }, + }) +} + +export function createPreviewSession(port: number): Promise { + return fetchWrapper(`${API_BASE_URL}/api/preview/sessions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ port }), + }) +} + +export interface UsePreviewPortsOptions { + enabled: boolean + refetchInterval?: number | false +} + +export function usePreviewPorts(directory: string | undefined, options: UsePreviewPortsOptions) { + return useQuery({ + queryKey: previewPortsQueryKey(directory), + queryFn: () => listPreviewPorts(directory), + enabled: options.enabled, + refetchInterval: options.refetchInterval, + }) +} diff --git a/frontend/src/api/projectConfig.ts b/frontend/src/api/projectConfig.ts new file mode 100644 index 00000000..7a715eb5 --- /dev/null +++ b/frontend/src/api/projectConfig.ts @@ -0,0 +1,136 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import type { + MoveProjectItemRequest, + ProjectAction, + ProjectConfigResponse, + RunProjectActionResponse, + TrustRepoConfigRequest, +} from '@opencode-manager/shared/types' +import { API_BASE_URL } from '@/config' +import { fetchWrapper } from './fetchWrapper' + +function projectConfigQueryKey(repoId: number, directory: string | undefined) { + return ['projectConfig', repoId, directory ?? null] as const +} + +export function getProjectConfig(repoId: number, directory?: string): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config`, { + params: { directory }, + }) +} + +function updateProjectActions( + repoId: number, + actions: ProjectAction[], + directory?: string, +): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/actions`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ actions }), + params: { directory }, + }) +} + +function updateWorktreeSetup( + repoId: number, + commands: string[], + directory?: string, +): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/worktree-setup`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ commands }), + params: { directory }, + }) +} + +function trustRepoConfig(repoId: number, request: TrustRepoConfigRequest): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/trust`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(request), + }) +} + +function moveProjectItem(repoId: number, request: MoveProjectItemRequest): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/move`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(request), + }) +} + +function runProjectAction( + repoId: number, + actionId: string, + directory?: string, +): Promise { + return fetchWrapper( + `${API_BASE_URL}/api/repos/${repoId}/project-config/actions/${encodeURIComponent(actionId)}/run`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ directory }), + }, + ) +} + +export function useProjectConfig(repoId: number, directory: string | undefined, enabled: boolean) { + return useQuery({ + queryKey: projectConfigQueryKey(repoId, directory), + queryFn: () => getProjectConfig(repoId, directory), + enabled, + }) +} + +export function useUpdateProjectActions(repoId: number, directory: string | undefined) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (actions: ProjectAction[]) => updateProjectActions(repoId, actions, directory), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, directory) }) + }, + }) +} + +export function useUpdateWorktreeSetup(repoId: number, directory: string | undefined) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (commands: string[]) => updateWorktreeSetup(repoId, commands, directory), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, directory) }) + }, + }) +} + +export function useTrustRepoConfig(repoId: number) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (request: TrustRepoConfigRequest) => trustRepoConfig(repoId, request), + onSuccess: (_data, request) => { + queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, request.directory) }) + }, + }) +} + +export function useMoveProjectItem(repoId: number) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (request: MoveProjectItemRequest) => moveProjectItem(repoId, request), + onSuccess: (_data, request) => { + queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, request.directory) }) + }, + }) +} + +export function useRunProjectAction(repoId: number, directory: string | undefined) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (actionId: string) => runProjectAction(repoId, actionId, directory), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, directory) }) + queryClient.invalidateQueries({ queryKey: ['terminals', repoId] }) + }, + }) +} diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index b97eddc2..3b71ec96 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -2,7 +2,7 @@ import type { Repo } from './types' import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper' import { API_BASE_URL } from '@/config' import { saveFile } from '@/lib/download' -import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity } from '@opencode-manager/shared/types' +import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity, WorktreeSetupResult } from '@opencode-manager/shared/types' export interface CreateRepoOptions { repoUrl?: string @@ -63,7 +63,7 @@ export async function deleteRepoWorkspace(repoId: number, directory: string): Pr }) } -export async function createRepoWorkspace(repoId: number): Promise { +export async function createRepoWorkspace(repoId: number): Promise { return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, { method: 'POST', }) diff --git a/frontend/src/api/terminals.ts b/frontend/src/api/terminals.ts new file mode 100644 index 00000000..20e2c1fc --- /dev/null +++ b/frontend/src/api/terminals.ts @@ -0,0 +1,82 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import type { CreateTerminalRequest, ResizeTerminalRequest, TerminalInfo } from '@opencode-manager/shared/types' +import { API_BASE_URL } from '@/config' +import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper' + +function terminalsQueryKey(repoId: number, directory: string | undefined) { + return ['terminals', repoId, directory ?? null] as const +} + +function terminalsRepoQueryKey(repoId: number) { + return ['terminals', repoId] as const +} + +async function listTerminals(repoId: number, directory?: string): Promise { + const data = await fetchWrapper<{ terminals: TerminalInfo[] }>( + `${API_BASE_URL}/api/repos/${repoId}/terminals`, + { params: { directory } }, + ) + return data.terminals +} + +async function createTerminal(repoId: number, body: CreateTerminalRequest): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/terminals`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) +} + +export async function resizeTerminal(repoId: number, ptyID: string, body: ResizeTerminalRequest): Promise { + return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) +} + +async function removeTerminal(repoId: number, ptyID: string, directory?: string): Promise { + return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}`, { + method: 'DELETE', + params: { directory }, + }) +} + +interface UseTerminalsOptions { + enabled: boolean + refetchInterval?: number | false +} + +export function useTerminals(repoId: number, directory: string | undefined, options: UseTerminalsOptions) { + return useQuery({ + queryKey: terminalsQueryKey(repoId, directory), + queryFn: () => listTerminals(repoId, directory), + enabled: options.enabled, + refetchInterval: options.refetchInterval, + }) +} + +export function useCreateTerminal(repoId: number) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (body: CreateTerminalRequest) => createTerminal(repoId, body), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: terminalsRepoQueryKey(repoId) }) + }, + }) +} + +interface RemoveTerminalVariables { + ptyID: string + directory?: string +} + +export function useRemoveTerminal(repoId: number) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: ({ ptyID, directory }: RemoveTerminalVariables) => removeTerminal(repoId, ptyID, directory), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: terminalsRepoQueryKey(repoId) }) + }, + }) +} diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index faedfe9c..47d45217 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -1,3 +1,6 @@ +import type { SessionInfo } from '@opencode-manager/shared/opencode' +import type { WorktreeSetupResult } from '@opencode-manager/shared/types' + export interface Repo { id: number name?: string @@ -15,10 +18,9 @@ export interface Repo { gitCredentialId?: string isWorktree?: boolean isLocal?: boolean + worktreeSetup?: WorktreeSetupResult } -import type { SessionInfo } from '@opencode-manager/shared/opencode' - export type Session = SessionInfo export type PermissionResponse = 'once' | 'always' | 'reject' diff --git a/frontend/src/components/navigation/moreDrawerItems.test.ts b/frontend/src/components/navigation/moreDrawerItems.test.ts index 353fed70..96700419 100644 --- a/frontend/src/components/navigation/moreDrawerItems.test.ts +++ b/frontend/src/components/navigation/moreDrawerItems.test.ts @@ -14,7 +14,7 @@ describe('buildMoreItems', () => { it('returns repo-specific items for /repos/:id', () => { const items = buildMoreItems('/repos/42') - expect(items).toHaveLength(9) + expect(items).toHaveLength(12) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[1].dialog).toBe('files') @@ -29,13 +29,19 @@ describe('buildMoreItems', () => { expect(items[5].to).toBe('/repos/42/schedules') expect(items[6].key).toBe('source-control') expect(items[6].dialog).toBe('sourceControl') - expect(items[7].key).toBe('settings') - expect(items[8].key).toBe('logout') + expect(items[7].key).toBe('terminal') + expect(items[7].dialog).toBe('terminal') + expect(items[8].key).toBe('actions') + expect(items[8].dialog).toBe('actions') + expect(items[9].key).toBe('preview') + expect(items[9].dialog).toBe('preview') + expect(items[10].key).toBe('settings') + expect(items[11].key).toBe('logout') }) it('returns session-specific items for /repos/:id/sessions/:sid', () => { const items = buildMoreItems('/repos/42/sessions/abc') - expect(items).toHaveLength(9) + expect(items).toHaveLength(12) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[2].key).toBe('mcp') @@ -44,13 +50,30 @@ describe('buildMoreItems', () => { expect(items[5].key).toBe('schedules') expect(items[5].to).toBe('/repos/42/schedules') expect(items[6].key).toBe('source-control') - expect(items[7].key).toBe('settings') - expect(items[8].key).toBe('logout') + expect(items[7].key).toBe('terminal') + expect(items[7].dialog).toBe('terminal') + expect(items[8].key).toBe('actions') + expect(items[8].dialog).toBe('actions') + expect(items[9].key).toBe('preview') + expect(items[9].dialog).toBe('preview') + expect(items[10].key).toBe('settings') + expect(items[11].key).toBe('logout') + }) + + it('omits the Actions item for an Assistant session', () => { + const items = buildMoreItems('/repos/0/sessions/abc') + expect(items).toHaveLength(11) + expect(items.map((item) => item.key)).not.toContain('actions') + expect(items[7].key).toBe('terminal') + expect(items[8].key).toBe('preview') + expect(items[8].dialog).toBe('preview') + expect(items[9].key).toBe('settings') + expect(items[10].key).toBe('logout') }) it('returns assistant workspace items for /repos/:id/assistant', () => { const items = buildMoreItems('/repos/42/assistant') - expect(items).toHaveLength(9) + expect(items).toHaveLength(11) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[1].dialog).toBe('files') @@ -59,8 +82,12 @@ describe('buildMoreItems', () => { expect(items[4].key).toBe('reset-permissions') expect(items[5].key).toBe('schedules') expect(items[6].key).toBe('source-control') - expect(items[7].key).toBe('settings') - expect(items[8].key).toBe('logout') + expect(items[7].key).toBe('terminal') + expect(items[7].dialog).toBe('terminal') + expect(items[8].key).toBe('preview') + expect(items[8].dialog).toBe('preview') + expect(items[9].key).toBe('settings') + expect(items[10].key).toBe('logout') }) it('returns only Home + Settings + Logout for /schedules', () => { diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts index 7bc85911..9d4f8cb1 100644 --- a/frontend/src/components/navigation/moreDrawerItems.ts +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -1,5 +1,6 @@ import type { LucideIcon } from 'lucide-react' -import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, Settings, LogOut, Bot, Folder, Home } from 'lucide-react' +import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react' +import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' import { getAssistantPath, isAssistantPath } from '@/lib/navigation' export interface MoreDrawerItem { @@ -58,6 +59,9 @@ function buildRouteNavModel(pathname: string): NavModel { { key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true }, { key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${id}/schedules` }, { key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' }, + { key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' }, + { key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' }, + { key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' }, ...baseItems, ] @@ -69,13 +73,20 @@ function buildRouteNavModel(pathname: string): NavModel { const sessionDetailMatch = /^\/repos\/(\d+)\/sessions\/[^/]+$/.exec(pathname) if (sessionDetailMatch) { + const repoId = sessionDetailMatch[1] + const isAssistantRepo = repoId === String(ASSISTANT_REPO_ID) const items: MoreDrawerItem[] = [ { key: 'files', label: 'Files', icon: Folder, dialog: 'files' }, { key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' }, { key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' }, { key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true }, - { key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${sessionDetailMatch[1]}/schedules` }, + { key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${repoId}/schedules` }, { key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' }, + { key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' }, + ...(isAssistantRepo + ? [] + : [{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' }]), + { key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' }, ...baseItems, ] @@ -93,6 +104,8 @@ function buildRouteNavModel(pathname: string): NavModel { { key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true }, { key: 'schedules', label: 'Schedules', icon: CalendarClock, to: '/repos/0/schedules' }, { key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' }, + { key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' }, + { key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' }, ...baseItems, ] diff --git a/frontend/src/components/preview/PreviewPanel.test.tsx b/frontend/src/components/preview/PreviewPanel.test.tsx new file mode 100644 index 00000000..b506a895 --- /dev/null +++ b/frontend/src/components/preview/PreviewPanel.test.tsx @@ -0,0 +1,252 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter } from 'react-router-dom' +import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types' +import { createPreviewSession, usePreviewPorts } from '@/api/preview' +import { PreviewPanel } from './PreviewPanel' + +vi.mock('@/api/preview', () => ({ + usePreviewPorts: vi.fn(), + createPreviewSession: vi.fn(), +})) + +type PreviewPortsResult = ReturnType + +const portsData = { + enabled: true, + ports: [{ port: 5173, host: '127.0.0.1' as const, pid: 10, command: 'vite', cwd: '/repo', inDirectory: true }], +} + +let portsState: PreviewPortsResult['data'] = portsData + +const DEFAULT_ENTRY = '/repos/1?dialog=preview&previewPort=5173' + +function deferred() { + let resolve!: (value: T) => void + let reject!: (reason?: unknown) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + +function panelElement(initialEntry: string) { + return ( + + + + ) +} + +function renderPanel(initialEntry = DEFAULT_ENTRY) { + const result = render(panelElement(initialEntry)) + return { + ...result, + refresh: () => result.rerender(panelElement(initialEntry)), + } +} + +describe('PreviewPanel', () => { + beforeEach(() => { + vi.resetAllMocks() + portsState = portsData + vi.mocked(usePreviewPorts).mockImplementation( + () => + ({ + data: portsState, + isLoading: false, + refetch: vi.fn(), + }) as unknown as PreviewPortsResult, + ) + vi.mocked(createPreviewSession).mockResolvedValue({ token: 'tok', previewPort: 5004, publicUrl: null }) + }) + + it('renders the iframe with the start URL and sandbox for a listed port', async () => { + renderPanel() + + const iframe = await screen.findByTitle('Preview') + expect(iframe).toHaveAttribute('src', 'http://localhost:5004/__ocm_preview/start?token=tok&path=%2F') + expect(iframe.getAttribute('sandbox')).toContain('allow-scripts') + expect(iframe.getAttribute('sandbox')).toContain('allow-same-origin') + }) + + it('creates a session and renders the iframe when a port is selected', async () => { + const user = userEvent.setup() + renderPanel('/repos/1?dialog=preview') + + await user.click(screen.getByRole('button', { name: /:5173/ })) + + const iframe = await screen.findByTitle('Preview') + expect(iframe).toHaveAttribute('src', 'http://localhost:5004/__ocm_preview/start?token=tok&path=%2F') + expect(createPreviewSession).toHaveBeenCalledWith(5173) + }) + + it('refuses to render an iframe when the preview origin is the manager origin', async () => { + vi.mocked(createPreviewSession).mockResolvedValue({ + token: 'tok', + previewPort: 5004, + publicUrl: 'http://localhost', + }) + renderPanel() + + expect(await screen.findByRole('alert')).toHaveTextContent(/different origin/i) + expect(screen.queryByTitle('Preview')).not.toBeInTheDocument() + }) + + it('shows a waiting state for a port that is not listening', () => { + renderPanel('/repos/1?dialog=preview&previewPort=6000') + + expect(screen.getByText(/Waiting for port 6000/)).toBeInTheDocument() + expect(createPreviewSession).not.toHaveBeenCalled() + }) + + it('renders the disabled state', () => { + portsState = { enabled: false, ports: [] } + renderPanel('/repos/1?dialog=preview') + + expect(screen.getByText(/Preview is unavailable/)).toBeInTheDocument() + }) + + it('badges ports marked as inside the directory', () => { + renderPanel('/repos/1?dialog=preview') + + expect(screen.getByText('this repo')).toBeInTheDocument() + }) + + it('does not badge ports marked as outside the directory', () => { + portsState = { + enabled: true, + ports: [{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: '/elsewhere', inDirectory: false }], + } + renderPanel('/repos/1?dialog=preview') + + expect(screen.queryByText('this repo')).not.toBeInTheDocument() + }) + + it('polls the port list while no preview session is active', () => { + renderPanel('/repos/1?dialog=preview') + + const lastOptions = vi.mocked(usePreviewPorts).mock.calls.at(-1)?.[1] + expect(lastOptions?.enabled).toBe(true) + expect(lastOptions?.refetchInterval).toBe(2000) + }) + + it('stops polling once a preview session is active', async () => { + renderPanel() + + await screen.findByTitle('Preview') + + const lastOptions = vi.mocked(usePreviewPorts).mock.calls.at(-1)?.[1] + expect(lastOptions?.enabled).toBe(true) + expect(lastOptions?.refetchInterval).toBe(false) + }) + + it('mints a fresh session when a listed port disappears and comes back', async () => { + const first = deferred() + const second = deferred() + vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise) + + const panel = renderPanel() + + first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null }) + expect((await screen.findByTitle('Preview')).getAttribute('src')).toContain('token=tok-1') + + portsState = { enabled: true, ports: [] } + panel.refresh() + expect(screen.queryByTitle('Preview')).not.toBeInTheDocument() + expect(screen.getByText(/Waiting for port 5173/)).toBeInTheDocument() + + portsState = portsData + panel.refresh() + second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null }) + + expect((await screen.findByTitle('Preview')).getAttribute('src')).toContain('token=tok-2') + expect(createPreviewSession).toHaveBeenCalledTimes(2) + }) + + it('does not render the old token while a same-port path change is pending', async () => { + const user = userEvent.setup() + const first = deferred() + const second = deferred() + vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise) + + renderPanel('/repos/1?dialog=preview&previewPort=5173&previewPath=%2F') + + first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null }) + expect(await screen.findByTitle('Preview')).toBeInTheDocument() + + const pathInput = screen.getByLabelText('Preview path') + await user.clear(pathInput) + await user.type(pathInput, '/foo') + await user.click(screen.getByRole('button', { name: 'Go' })) + + expect(screen.queryByTitle('Preview')).not.toBeInTheDocument() + + second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null }) + const iframe = await screen.findByTitle('Preview') + expect(iframe.getAttribute('src')).toContain('token=tok-2') + expect(iframe.getAttribute('src')).toContain('path=%2Ffoo') + }) + + it('does not replay the old token while a reload is pending', async () => { + const user = userEvent.setup() + const first = deferred() + const second = deferred() + vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise) + + renderPanel() + + first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null }) + expect(await screen.findByTitle('Preview')).toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Reload preview' })) + + expect(screen.queryByTitle('Preview')).not.toBeInTheDocument() + + second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null }) + expect((await screen.findByTitle('Preview')).getAttribute('src')).toContain('token=tok-2') + }) + + it('keeps the newest session when responses resolve out of order for the same port', async () => { + const user = userEvent.setup() + const first = deferred() + const second = deferred() + const third = deferred() + vi.mocked(createPreviewSession) + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + .mockReturnValueOnce(third.promise) + + renderPanel() + + first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null }) + await screen.findByTitle('Preview') + + await user.click(screen.getByRole('button', { name: 'Reload preview' })) + await user.click(screen.getByRole('button', { name: 'Reload preview' })) + + third.resolve({ token: 'tok-3', previewPort: 5004, publicUrl: null }) + second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null }) + + const iframe = await screen.findByTitle('Preview') + expect(iframe.getAttribute('src')).toContain('token=tok-3') + expect(iframe.getAttribute('src')).not.toContain('token=tok-2') + }) + + it('does not mint extra sessions when the port list refetches unchanged', async () => { + const first = deferred() + vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise) + + const panel = renderPanel() + + first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null }) + await screen.findByTitle('Preview') + + panel.refresh() + panel.refresh() + + expect(createPreviewSession).toHaveBeenCalledTimes(1) + }) +}) diff --git a/frontend/src/components/preview/PreviewPanel.tsx b/frontend/src/components/preview/PreviewPanel.tsx new file mode 100644 index 00000000..f6166c81 --- /dev/null +++ b/frontend/src/components/preview/PreviewPanel.tsx @@ -0,0 +1,342 @@ +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types' +import { ExternalLink, Globe, Loader2, Monitor, RefreshCw, Smartphone, Tablet, X } from 'lucide-react' +import { createPreviewSession, usePreviewPorts } from '@/api/preview' +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { useMobile } from '@/hooks/useMobile' +import { useUrlParams } from '@/hooks/useUrlParams' +import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors' +import { buildPreviewStartUrl, getPreviewOrigin, isSameOriginAsManager, parsePort } from '@/lib/preview-url' +import { cn } from '@/lib/utils' + +interface PreviewPanelProps { + isOpen: boolean + onClose: () => void + directory: string | undefined +} + +type ViewportPreset = 'mobile' | 'tablet' | 'full' + +const VIEWPORT_WIDTHS: Record = { + mobile: 390, + tablet: 820, + full: null, +} + +const VIEWPORT_PRESETS: Array<{ preset: ViewportPreset; label: string; icon: typeof Monitor }> = [ + { preset: 'mobile', label: 'Mobile viewport', icon: Smartphone }, + { preset: 'tablet', label: 'Tablet viewport', icon: Tablet }, + { preset: 'full', label: 'Full width viewport', icon: Monitor }, +] + +const PORT_WAIT_TIMEOUT_MS = 60_000 + +interface ActiveSession { + targetPort: number + path: string + renderKey: number + data: CreatePreviewSessionResponse +} + +export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) { + const isMobile = useMobile() + const { searchParams, updateParams } = useUrlParams() + + const requestedPort = useMemo(() => { + const port = parsePort(searchParams.get('previewPort') ?? '') + return port ?? undefined + }, [searchParams]) + const requestedPath = searchParams.get('previewPath') || '/' + + const [pathDraft, setPathDraft] = useState(requestedPath) + const [viewport, setViewport] = useState('full') + const [session, setSession] = useState(null) + const [sessionError, setSessionError] = useState(null) + const [waitExpired, setWaitExpired] = useState(false) + const [retryNonce, setRetryNonce] = useState(0) + const sessionPortRef = useRef(null) + const activePathRef = useRef(null) + const requestIdRef = useRef(0) + + const activeSession = session && session.targetPort === requestedPort ? session : null + + const portsQuery = usePreviewPorts(directory, { + enabled: isOpen, + refetchInterval: isOpen && !activeSession ? 2000 : false, + }) + const ports = useMemo(() => portsQuery.data?.ports ?? [], [portsQuery.data]) + const enabled = portsQuery.data?.enabled ?? true + const portListed = requestedPort !== undefined && ports.some((entry) => entry.port === requestedPort) + + useEffect(() => { + setPathDraft(requestedPath) + }, [requestedPath]) + + useEffect(() => { + if (!isOpen) { + requestIdRef.current += 1 + sessionPortRef.current = null + activePathRef.current = null + setSession(null) + setSessionError(null) + } + }, [isOpen]) + + useEffect(() => { + if (portListed) return + requestIdRef.current += 1 + sessionPortRef.current = null + activePathRef.current = null + setSession(null) + }, [portListed]) + + useEffect(() => { + if (!isOpen || !requestedPort || !enabled || portListed) { + setWaitExpired(false) + return + } + setWaitExpired(false) + const timer = setTimeout(() => setWaitExpired(true), PORT_WAIT_TIMEOUT_MS) + return () => clearTimeout(timer) + }, [isOpen, requestedPort, enabled, portListed, retryNonce]) + + const startSession = useCallback((port: number, path: string) => { + const requestId = requestIdRef.current + 1 + requestIdRef.current = requestId + sessionPortRef.current = port + activePathRef.current = path + setSessionError(null) + setSession(null) + return createPreviewSession(port) + .then((data) => { + if (requestIdRef.current !== requestId) return + setSession({ targetPort: port, path, renderKey: requestId, data }) + }) + .catch((error: unknown) => { + if (requestIdRef.current !== requestId) return + sessionPortRef.current = null + activePathRef.current = null + setSessionError(getOpenCodeApiErrorMessage(error, 'Failed to start preview')) + }) + }, []) + + useEffect(() => { + if (!isOpen || !requestedPort || !enabled || !portListed) return + if (sessionPortRef.current === requestedPort && activePathRef.current === requestedPath) return + void startSession(requestedPort, requestedPath) + }, [isOpen, requestedPort, requestedPath, enabled, portListed, startSession]) + + const selectPort = useCallback((port: number) => { + updateParams((params) => { + params.set('previewPort', String(port)) + params.delete('previewPath') + }, 'replace') + }, [updateParams]) + + const reload = useCallback(() => { + if (!requestedPort) return + void startSession(requestedPort, requestedPath) + }, [requestedPort, requestedPath, startSession]) + + const handleGo = useCallback(() => { + const nextPath = pathDraft.trim() || '/' + updateParams((params) => { + params.set('previewPath', nextPath) + }, 'replace') + if (requestedPort) { + void startSession(requestedPort, nextPath) + } + }, [pathDraft, requestedPort, updateParams, startSession]) + + const handleOpenInNewTab = useCallback(() => { + if (!requestedPort) return + createPreviewSession(requestedPort) + .then((data) => { + window.open(buildPreviewStartUrl(data, requestedPath), '_blank', 'noopener,noreferrer') + }) + .catch((error: unknown) => { + setSessionError(getOpenCodeApiErrorMessage(error, 'Failed to open preview')) + }) + }, [requestedPort, requestedPath]) + + const retry = useCallback(() => { + if (portListed && requestedPort) { + void startSession(requestedPort, requestedPath) + return + } + setWaitExpired(false) + setRetryNonce((nonce) => nonce + 1) + void portsQuery.refetch() + }, [portListed, requestedPort, requestedPath, startSession, portsQuery]) + + const previewOrigin = activeSession ? getPreviewOrigin(activeSession.data) : null + const sameOrigin = previewOrigin ? isSameOriginAsManager(previewOrigin) : false + const viewportWidth = VIEWPORT_WIDTHS[viewport] + + const renderMessage = (message: ReactNode, options: { retry?: boolean; alert?: boolean } = {}) => ( +
+
+ {message} +
+ {options.retry && ( + + )} +
+ ) + + const body = () => { + if (!enabled) { + return renderMessage('Preview is unavailable') + } + if (!requestedPort) { + return renderMessage('Select a port to preview') + } + if (!portListed) { + if (waitExpired) { + return renderMessage(`Port ${requestedPort} is not listening`, { retry: true, alert: true }) + } + return renderMessage( + <> + + Waiting for port {requestedPort}… + , + ) + } + if (sessionError) { + return renderMessage(sessionError, { retry: true, alert: true }) + } + if (activeSession) { + if (sameOrigin) { + return renderMessage('Preview must run on a different origin than OpenCode Manager.', { alert: true }) + } + return ( +
+