From b494ee9f4af3114cf156c4e7a96fcc5d7b81e6ea Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 00:56:39 -0400 Subject: [PATCH 01/12] section 1: Phase 1: Shell environment owner and repo working-directory --- backend/src/db/queries.ts | 10 ++ .../src/routes/internal/git-credentials.ts | 2 +- backend/src/routes/repos.ts | 18 +--- backend/src/services/credential-provider.ts | 17 ++++ backend/src/services/repo.ts | 23 ++++- .../routes/internal/git-credentials.test.ts | 51 ++++++++++ backend/test/routes/repos.test.ts | 6 ++ .../test/services/credential-provider.test.ts | 63 +++++++++++- .../services/repo-working-directory.test.ts | 98 +++++++++++++++++++ shared/src/schemas/settings.ts | 7 ++ shared/src/types/index.ts | 2 +- 11 files changed, 280 insertions(+), 17 deletions(-) create mode 100644 backend/test/services/repo-working-directory.test.ts diff --git a/backend/src/db/queries.ts b/backend/src/db/queries.ts index c02e57ac..fe4a73f2 100644 --- a/backend/src/db/queries.ts +++ b/backend/src/db/queries.ts @@ -23,6 +23,8 @@ interface RepoRow { const REPO_GIT_CREDENTIAL_SETTING_KEY = 'gitCredentialId' +const REPO_GIT_IDENTITY_SETTING_KEY = 'gitIdentityId' + const REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY = 'sandboxGitCredentials' function rowToRepo(row: RepoRow): Repo { @@ -82,6 +84,14 @@ export function setRepoGitCredentialId(db: Database, repoId: number, credentialI setRepoSetting(db, repoId, REPO_GIT_CREDENTIAL_SETTING_KEY, credentialId) } +export function getRepoGitIdentityId(db: Database, repoId: number): string | null { + return getRepoSetting(db, repoId, REPO_GIT_IDENTITY_SETTING_KEY) +} + +export function setRepoGitIdentityId(db: Database, repoId: number, identityId: string | null): void { + setRepoSetting(db, repoId, REPO_GIT_IDENTITY_SETTING_KEY, identityId) +} + export function getRepoSandboxGitCredentials(db: Database, repoId: number): boolean | null { const value = getRepoSetting(db, repoId, REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY) if (value === null) return null diff --git a/backend/src/routes/internal/git-credentials.ts b/backend/src/routes/internal/git-credentials.ts index 53a1c470..df1185c5 100644 --- a/backend/src/routes/internal/git-credentials.ts +++ b/backend/src/routes/internal/git-credentials.ts @@ -7,7 +7,7 @@ export function createInternalGitCredentialsRoutes(db: Database) { app.get('/gh-env', (c) => { const provider = new CredentialProvider(db) - return c.json(provider.getGhCliEnv({ cwd: c.req.query('cwd') })) + return c.json(provider.getShellEnv({ cwd: c.req.query('cwd') })) }) return app diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 065af547..ff13bb32 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -18,14 +18,9 @@ import { createRepoGitRoutes } from './repo-git' import { createScheduleRoutes } from './schedules' import type { GitAuthService } from '../services/git-auth' import { ScheduleService } from '../services/schedules' -import { ensureAssistantMode, getAssistantModeStatus, buildAssistantRepo } from '../services/assistant-mode' -import { canonicalPathSync } from '../utils/fs-safe' +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), }) @@ -150,7 +145,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) @@ -270,10 +265,7 @@ app.get('/', async (c) => { const directory = parsed.data.directory const siblings = await repoService.getSiblingRepos(database, id, gitAuthService.getGitEnvironment(), openCodeClient) - const requestedDirectory = canonicalPathSync(path.resolve(directory)) - const worktree = siblings.find( - (sibling) => isWorktreeSibling(sibling) && canonicalPathSync(path.resolve(sibling.fullPath)) === requestedDirectory, - ) + const worktree = repoService.findSiblingByDirectory(siblings.filter(isWorktreeSibling), directory) if (!worktree) return c.json({ error: 'Not a deletable worktree of this repo' }, 400) try { @@ -491,7 +483,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) @@ -509,7 +501,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/credential-provider.ts b/backend/src/services/credential-provider.ts index 611b34b2..3ca9141d 100644 --- a/backend/src/services/credential-provider.ts +++ b/backend/src/services/credential-provider.ts @@ -6,6 +6,7 @@ import { getSSHCredentialsForHost, createGitEnv, createGhCliEnv, + createGitIdentityEnv, findGitHubCredential, type ResolvedGitCredential, } from '../utils/git-auth' @@ -14,6 +15,7 @@ import { logger } from '../utils/logger' import { getRepoByDirectory, getRepoGitCredentialId, + getRepoGitIdentityId, getRepoSandboxGitCredentials, listRepos, } from '../db/queries' @@ -95,6 +97,21 @@ export class CredentialProvider { return this.getGhCliEnvForContext(this.resolveContext(options)) } + getShellEnv(options: CredentialResolutionOptions = {}): Record { + return { ...this.getGhCliEnv(options), ...this.getAssignedGitIdentityEnv(options) } + } + + getAssignedGitIdentityEnv(options: CredentialResolutionOptions = {}): Record { + const repo = this.resolveRepo(options) + if (!repo) return {} + + const identityId = getRepoGitIdentityId(this.database, repo.id) + if (!identityId) return {} + + const profile = this.getPreferences().gitIdentities?.find((identity) => identity.id === identityId) + return profile ? createGitIdentityEnv(profile) : {} + } + private resolveContext(options: CredentialResolutionOptions, repo = this.resolveRepo(options)): CredentialResolutionContext { const preferences = this.getPreferences() return { diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 6a926868..98499cce 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, 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' @@ -1168,6 +1169,26 @@ export async function resolveRepoProjectId(openCodeClient: OpenCodeClient, direc return project.id } +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, diff --git a/backend/test/routes/internal/git-credentials.test.ts b/backend/test/routes/internal/git-credentials.test.ts index 4ae326be..93e4b762 100644 --- a/backend/test/routes/internal/git-credentials.test.ts +++ b/backend/test/routes/internal/git-credentials.test.ts @@ -3,6 +3,7 @@ import { Database } from 'bun:sqlite' import { migrate } from '../../../src/db/migration-runner' import { allMigrations } from '../../../src/db/migrations' import { SettingsService } from '../../../src/services/settings' +import { createRepo, setRepoGitIdentityId } from '../../../src/db/queries' import { createInternalGitCredentialsRoutes } from '../../../src/routes/internal/git-credentials' import type { GitCredential } from '@opencode-manager/shared' @@ -37,4 +38,54 @@ describe('internal git-credentials routes', () => { expect(res.status).toBe(200) expect(await res.json()).toEqual({}) }) + + it('GET /gh-env includes the assigned identity env for a repo cwd', async () => { + settingsService.updateSettings({ + gitCredentials: [ + { name: 'github', host: 'github.com', type: 'pat', token: 'ghp_test_token' } as GitCredential, + ], + gitIdentities: [{ id: 'identity-1', name: 'Alice', email: 'alice@example.com' }], + }) + const repo = createRepo(db, { + repoUrl: 'https://github.com/acme/repo.git', + localPath: 'repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + }) + setRepoGitIdentityId(db, repo.id, 'identity-1') + + const res = await app.request(`/gh-env?cwd=${encodeURIComponent(repo.fullPath)}`) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ + GH_TOKEN: 'ghp_test_token', + GITHUB_TOKEN: 'ghp_test_token', + GIT_AUTHOR_NAME: 'Alice', + GIT_AUTHOR_EMAIL: 'alice@example.com', + GIT_COMMITTER_NAME: 'Alice', + GIT_COMMITTER_EMAIL: 'alice@example.com', + }) + }) + + it('GET /gh-env omits the identity env without an assignment', async () => { + settingsService.updateSettings({ + gitCredentials: [ + { name: 'github', host: 'github.com', type: 'pat', token: 'ghp_test_token' } as GitCredential, + ], + gitIdentities: [{ id: 'identity-1', name: 'Alice', email: 'alice@example.com' }], + }) + const repo = createRepo(db, { + repoUrl: 'https://github.com/acme/repo.git', + localPath: 'repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + }) + + const res = await app.request(`/gh-env?cwd=${encodeURIComponent(repo.fullPath)}`) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' }) + }) }) diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts index 5574e819..af33e242 100644 --- a/backend/test/routes/repos.test.ts +++ b/backend/test/routes/repos.test.ts @@ -32,6 +32,8 @@ vi.mock('../../src/services/repo', () => ({ createBranch: vi.fn(), deleteRepoFiles: vi.fn(), getSiblingRepos: vi.fn(), + resolveRepoOrAssistant: vi.fn(), + findSiblingByDirectory: vi.fn(), })) vi.mock('../../src/services/assistant-mode', () => ({ @@ -79,6 +81,7 @@ 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({}) @@ -118,6 +121,9 @@ describe('Repo Routes', () => { updatedAt: Date.now(), }) vi.mocked(db.getRepoGitCredentialId).mockReturnValue(null) + vi.mocked(repoService.resolveRepoOrAssistant).mockImplementation( + (_database, id) => vi.mocked(db.getRepoById)(_database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null), + ) }) describe('POST /:id/access', () => { diff --git a/backend/test/services/credential-provider.test.ts b/backend/test/services/credential-provider.test.ts index 14096f95..49abfbee 100644 --- a/backend/test/services/credential-provider.test.ts +++ b/backend/test/services/credential-provider.test.ts @@ -4,7 +4,7 @@ import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' import { SettingsService } from '../../src/services/settings' import { CredentialProvider } from '../../src/services/credential-provider' -import { createRepo, setRepoGitCredentialId, setRepoSandboxGitCredentials } from '../../src/db/queries' +import { createRepo, setRepoGitCredentialId, setRepoGitIdentityId, setRepoSandboxGitCredentials } from '../../src/db/queries' import { SANDBOX_MAX_FORWARDED_GIT_CONFIGS } from '../../src/services/sandbox/shell-shim' import type { GitCredential } from '@opencode-manager/shared' @@ -316,4 +316,65 @@ describe('CredentialProvider', () => { } }) }) + + describe('shell env', () => { + function createGithubRepo() { + return createRepo(db, { + repoUrl: 'https://github.com/acme/repo.git', + localPath: 'repo', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + }) + } + + beforeEach(() => { + settingsService.updateSettings({ + gitCredentials: [createPatCredential('github', 'github.com', 'ghp_test_token', undefined, 'github-id')], + gitIdentities: [{ id: 'identity-1', name: 'Alice', email: 'alice@example.com' }], + }) + }) + + it('getShellEnv returns only the GH CLI env without an assigned identity', () => { + expect(provider.getShellEnv()).toEqual({ GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' }) + }) + + it('getAssignedGitIdentityEnv returns an empty object without an assignment', () => { + const repo = createGithubRepo() + expect(provider.getAssignedGitIdentityEnv({ cwd: repo.fullPath })).toEqual({}) + }) + + it('getAssignedGitIdentityEnv returns the identity env for an assigned profile', () => { + const repo = createGithubRepo() + setRepoGitIdentityId(db, repo.id, 'identity-1') + + expect(provider.getAssignedGitIdentityEnv({ cwd: repo.fullPath })).toEqual({ + GIT_AUTHOR_NAME: 'Alice', + GIT_AUTHOR_EMAIL: 'alice@example.com', + GIT_COMMITTER_NAME: 'Alice', + GIT_COMMITTER_EMAIL: 'alice@example.com', + }) + }) + + it('getShellEnv merges the GH CLI env with the assigned identity env', () => { + const repo = createGithubRepo() + setRepoGitIdentityId(db, repo.id, 'identity-1') + + expect(provider.getShellEnv({ cwd: repo.fullPath })).toEqual({ + GH_TOKEN: 'ghp_test_token', + GITHUB_TOKEN: 'ghp_test_token', + GIT_AUTHOR_NAME: 'Alice', + GIT_AUTHOR_EMAIL: 'alice@example.com', + GIT_COMMITTER_NAME: 'Alice', + GIT_COMMITTER_EMAIL: 'alice@example.com', + }) + }) + + it('getAssignedGitIdentityEnv ignores a dangling assigned identity', () => { + const repo = createGithubRepo() + setRepoGitIdentityId(db, repo.id, 'missing-identity') + + expect(provider.getAssignedGitIdentityEnv({ cwd: repo.fullPath })).toEqual({}) + }) + }) }) 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..ebd59137 --- /dev/null +++ b/backend/test/services/repo-working-directory.test.ts @@ -0,0 +1,98 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { findSiblingByDirectory, resolveRepoWorkingDirectory } from '../../src/services/repo' +import type { Repo } from '@opencode-manager/shared/types' + +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() + }) +}) diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index 82864267..516347f5 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -106,6 +106,12 @@ export const GitIdentitySchema = z.object({ export type GitIdentity = z.infer; +export const GitIdentityProfileSchema = GitIdentitySchema.extend({ + id: z.string().min(1), +}); + +export type GitIdentityProfile = z.infer; + export const ServerEnvVarSchema = z.object({ key: z.string().min(1), value: z.string(), @@ -160,6 +166,7 @@ export const UserPreferencesSchema = z.object({ gitCredentials: z.array(GitCredentialSchema).optional(), defaultGitCredentialId: z.string().optional(), gitIdentity: GitIdentitySchema.optional(), + gitIdentities: z.array(GitIdentityProfileSchema).optional(), tts: TTSConfigSchema.optional(), stt: STTConfigSchema.optional(), notifications: NotificationPreferencesSchema.optional(), diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 4c9e7a31..a895fff0 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -111,7 +111,7 @@ export interface SuccessResponse { } export type { SSHHostKeyRequest, SSHHostKeyResponse, TrustedSSHHost } from '../schemas/ssh' -export type { GitCredential } from '../schemas/settings' +export type { GitCredential, GitIdentity, GitIdentityProfile } from '../schemas/settings' export type { ProviderApiConfig, ModelConfig, From beab2646e7c98a3c3ceb7aecabb7d5baf3d0a41a Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:05:02 -0400 Subject: [PATCH 02/12] section 2: Phase 2: Terminal service, REST routes and cleanup --- backend/src/index.ts | 4 +- backend/src/routes/repo-terminals.ts | 140 +++++++++++++ backend/src/routes/repos.test.ts | 7 +- backend/src/routes/repos.ts | 18 +- backend/src/services/terminal.ts | 93 ++++++++ backend/test/routes/git.test.ts | 3 +- backend/test/routes/repo-terminals.test.ts | 233 +++++++++++++++++++++ backend/test/routes/repos.test.ts | 129 +++++++----- backend/test/services/terminal.test.ts | 184 ++++++++++++++++ backend/test/shared/terminal-title.test.ts | 62 ++++++ shared/src/schemas/index.ts | 1 + shared/src/schemas/terminal.ts | 29 +++ shared/src/types/index.ts | 7 + shared/src/utils/index.ts | 1 + shared/src/utils/terminal-title.ts | 53 +++++ 15 files changed, 907 insertions(+), 57 deletions(-) create mode 100644 backend/src/routes/repo-terminals.ts create mode 100644 backend/src/services/terminal.ts create mode 100644 backend/test/routes/repo-terminals.test.ts create mode 100644 backend/test/services/terminal.test.ts create mode 100644 backend/test/shared/terminal-title.test.ts create mode 100644 shared/src/schemas/terminal.ts create mode 100644 shared/src/utils/terminal-title.ts diff --git a/backend/src/index.ts b/backend/src/index.ts index 88cfe0f1..1963d742 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -49,6 +49,7 @@ import { createOpenCodeClient } from './services/opencode/client' import { NotificationService } from './services/notification' import { ScheduleRunner, ScheduleService } from './services/schedules' import { CredentialProvider } from './services/credential-provider' +import { TerminalService } from './services/terminal' import { ScheduleWorktreeManager } from './services/schedule-worktree' import { migrateGlobalSkills } from './services/skills' import { installAssistantWorkspace } from './services/assistant-mode' @@ -222,6 +223,7 @@ try { const settingsServiceForSchedules = new SettingsService(db) const credentialProvider = new CredentialProvider(db) +const terminalService = new TerminalService(openCodeClient, credentialProvider) const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, settingsServiceForSchedules, credentialProvider, db) const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager) const scheduleRunnerInstance = new ScheduleRunner(scheduleService) @@ -270,7 +272,7 @@ app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService)) const protectedApi = new Hono() protectedApi.use('/*', requireAuth) -protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient)) +protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, terminalService)) protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor)) protectedApi.route('/files', createFileRoutes()) protectedApi.route('/filesystem', createFilesystemRoutes()) diff --git a/backend/src/routes/repo-terminals.ts b/backend/src/routes/repo-terminals.ts new file mode 100644 index 00000000..6589157a --- /dev/null +++ b/backend/src/routes/repo-terminals.ts @@ -0,0 +1,140 @@ +import { Hono } from 'hono' +import type { Context } from 'hono' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { CreateTerminalRequestSchema, ResizeTerminalRequestSchema } from '@opencode-manager/shared/schemas' +import * as repoService from '../services/repo' +import { resolveRepoOrAssistant, resolveRepoWorkingDirectory } from '../services/repo' +import type { GitAuthService } from '../services/git-auth' +import type { OpenCodeClient } from '../services/opencode/client' +import { TerminalService, TerminalNotFoundError } from '../services/terminal' +import { handleOpenCodeError } from '../utils/route-helpers' + +export interface TerminalDirectoryDeps { + database: Database + gitAuthService: GitAuthService + openCodeClient: OpenCodeClient +} + +export interface TerminalRoutesDeps extends TerminalDirectoryDeps { + terminalService: TerminalService +} + +export async function resolveTerminalDirectory( + c: Context, + deps: TerminalDirectoryDeps, + repoIdParam: string, + directory: string | undefined, +): Promise<{ repo: Repo; directory: string } | Response> { + const id = Number.parseInt(repoIdParam, 10) + if (Number.isNaN(id)) { + return c.json({ error: 'Invalid repo id' }, 400) + } + + const repo = resolveRepoOrAssistant(deps.database, id) + if (!repo || repo.cloneStatus !== 'ready') { + return c.json({ error: 'Repo not found' }, 404) + } + + const resolved = await resolveRepoWorkingDirectory(repo, directory, () => + repoService.getSiblingRepos( + deps.database, + repo.id, + deps.gitAuthService.getGitEnvironment(), + deps.openCodeClient, + ), + ) + + if (!resolved) { + return c.json({ error: 'Directory is not part of this repository' }, 400) + } + + return { repo, directory: resolved } +} + +export function createRepoTerminalRoutes( + database: Database, + gitAuthService: GitAuthService, + openCodeClient: OpenCodeClient, + terminalService: TerminalService, +) { + const deps: TerminalRoutesDeps = { database, gitAuthService, openCodeClient, terminalService } + const app = new Hono() + + app.get('/:id/terminals', async (c) => { + const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + try { + const terminals = await deps.terminalService.list(resolved.directory) + return c.json({ terminals }) + } catch (error: unknown) { + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + app.post('/:id/terminals', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = CreateTerminalRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request' }, 400) + } + + const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), parsed.data.directory) + if (resolved instanceof Response) return resolved + + try { + const terminal = await deps.terminalService.create(resolved.directory, { + kind: 'shell', + name: parsed.data.title ?? 'Terminal', + }) + return c.json(terminal) + } catch (error: unknown) { + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + app.patch('/:id/terminals/:ptyID', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = ResizeTerminalRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request' }, 400) + } + + const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), parsed.data.directory) + if (resolved instanceof Response) return resolved + + const ptyID = c.req.param('ptyID') + + try { + await deps.terminalService.requireTerminal(resolved.directory, ptyID) + await deps.terminalService.resize(resolved.directory, ptyID, { cols: parsed.data.cols, rows: parsed.data.rows }) + return c.json({ success: true }) + } catch (error: unknown) { + if (error instanceof TerminalNotFoundError) { + return c.json({ error: error.message }, 404) + } + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + app.delete('/:id/terminals/:ptyID', async (c) => { + const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + const ptyID = c.req.param('ptyID') + + try { + await deps.terminalService.requireTerminal(resolved.directory, ptyID) + await deps.terminalService.remove(resolved.directory, ptyID) + return c.json({ success: true }) + } catch (error: unknown) { + if (error instanceof TerminalNotFoundError) { + return c.json({ error: error.message }, 404) + } + return handleOpenCodeError(c, error, 'Terminal request failed') + } + }) + + return app +} diff --git a/backend/src/routes/repos.test.ts b/backend/src/routes/repos.test.ts index eb906112..b89e8740 100644 --- a/backend/src/routes/repos.test.ts +++ b/backend/src/routes/repos.test.ts @@ -7,6 +7,7 @@ import { createRepoRoutes } from './repos' import { createRepo, getRepoById } from '../db/queries' import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client' import type { GitAuthService } from '../services/git-auth' +import type { TerminalService } from '../services/terminal' import type { OpenCodeClient } from '../services/opencode/client' import type { Repo } from '@opencode-manager/shared/types' import { getReposPath } from '@opencode-manager/shared/config/env' @@ -28,6 +29,10 @@ const stubGitAuthService = { getGitCredentials: async () => [], } as unknown as GitAuthService +const stubTerminalService = { + removeAll: mock(async () => undefined), +} as unknown as TerminalService + function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStubOpenCodeClient()): Hono { const app = new Hono() const scheduleService = { @@ -38,7 +43,7 @@ function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStub deleteSchedule: () => {}, prepareRepoDelete: () => {}, } as any - app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient)) + app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, stubTerminalService)) return app } diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index ff13bb32..921536f2 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -15,8 +15,10 @@ import { handleOpenCodeError } from '../utils/route-helpers' import { ASSISTANT_REPO_ID, isWorktreeSibling } from '@opencode-manager/shared/utils' import { isWorktreeError, openCodeLocation } from '@opencode-manager/shared/opencode' import { createRepoGitRoutes } from './repo-git' +import { createRepoTerminalRoutes } from './repo-terminals' import { createScheduleRoutes } from './schedules' import type { GitAuthService } from '../services/git-auth' +import type { TerminalService } from '../services/terminal' import { ScheduleService } from '../services/schedules' import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode' import path from 'path' @@ -32,15 +34,25 @@ function withRepoSettings(database: Database, repo: Repo): Repo { } } +async function removeDirectoryTerminals(terminalService: TerminalService, directory: string): Promise { + try { + await terminalService.removeAll(directory) + } catch (error: unknown) { + logger.warn(`Failed to remove terminals for ${directory}:`, error) + } +} + export function createRepoRoutes( database: Database, gitAuthService: GitAuthService, scheduleService: ScheduleService, openCodeClient: OpenCodeClient, + terminalService: TerminalService, ) { const app = new Hono() app.route('/', createRepoGitRoutes(database, gitAuthService)) + app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, terminalService)) app.route('/:id/schedules', createScheduleRoutes(scheduleService)) app.post('/', async (c) => { @@ -268,6 +280,8 @@ app.get('/', async (c) => { const worktree = repoService.findSiblingByDirectory(siblings.filter(isWorktreeSibling), directory) if (!worktree) return c.json({ error: 'Not a deletable worktree of this repo' }, 400) + await removeDirectoryTerminals(terminalService, worktree.fullPath) + try { const projectID = await repoService.resolveRepoProjectId(openCodeClient, repo.fullPath) await openCodeClient.api.worktree.remove({ projectID, directory: worktree.fullPath, force: true }) @@ -325,7 +339,9 @@ app.get('/', async (c) => { } scheduleService.prepareRepoDelete(id) - + + await removeDirectoryTerminals(terminalService, repo.fullPath) + await repoService.deleteRepoFiles(database, id) return c.json({ success: true }) diff --git a/backend/src/services/terminal.ts b/backend/src/services/terminal.ts new file mode 100644 index 00000000..3833b87d --- /dev/null +++ b/backend/src/services/terminal.ts @@ -0,0 +1,93 @@ +import { openCodeErrorStatus } from '@opencode-manager/shared/opencode' +import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/shared/utils' +import type { TerminalInfo, TerminalKind } from '@opencode-manager/shared/types' +import type { OpenCodeClient } from './opencode/client' +import type { CredentialProvider } from './credential-provider' + +type OpenCodePty = Awaited>['data'][number] + +export interface CreateTerminalInput { + kind: TerminalKind + name: string + actionId?: string + command?: string + args?: string[] + env?: Record +} + +export interface TerminalSize { + cols: number + rows: number +} + +export class TerminalNotFoundError extends Error { + constructor(ptyID: string) { + super(`Terminal not found: ${ptyID}`) + this.name = 'TerminalNotFoundError' + } +} + +export class TerminalService { + constructor( + private readonly openCodeClient: OpenCodeClient, + private readonly credentialProvider: CredentialProvider, + ) {} + + async list(directory: string): Promise { + const result = await this.openCodeClient.api.pty.list({ location: { directory } }) + return result.data.map((pty) => this.toTerminalInfo(pty)) + } + + async create(directory: string, input: CreateTerminalInput): Promise { + const result = await this.openCodeClient.api.pty.create({ + location: { directory }, + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + ...(input.command !== undefined ? { command: input.command } : {}), + ...(input.args !== undefined ? { args: input.args } : {}), + env: { ...this.credentialProvider.getShellEnv({ cwd: directory }), ...input.env }, + }) + return this.toTerminalInfo(result.data) + } + + async requireTerminal(directory: string, ptyID: string): Promise { + const terminals = await this.list(directory) + const terminal = terminals.find((entry) => entry.id === ptyID) + if (!terminal) { + throw new TerminalNotFoundError(ptyID) + } + return terminal + } + + async resize(directory: string, ptyID: string, size: TerminalSize): Promise { + await this.openCodeClient.api.pty.update({ ptyID, location: { directory }, size }) + } + + async remove(directory: string, ptyID: string): Promise { + await this.openCodeClient.api.pty.remove({ ptyID, location: { directory } }) + } + + async removeAll(directory: string): Promise { + const terminals = await this.list(directory) + for (const terminal of terminals) { + try { + await this.remove(directory, terminal.id) + } catch (error: unknown) { + if (openCodeErrorStatus(error) === 404) continue + throw error + } + } + } + + private toTerminalInfo(pty: OpenCodePty): TerminalInfo { + const parsed = parseTerminalTitle(pty.title) + return { + id: pty.id, + title: parsed.title, + kind: parsed.kind, + ...(parsed.actionId ? { actionId: parsed.actionId } : {}), + cwd: pty.cwd, + status: pty.status, + ...(pty.exitCode !== undefined ? { exitCode: pty.exitCode } : {}), + } + } +} diff --git a/backend/test/routes/git.test.ts b/backend/test/routes/git.test.ts index 549c6e04..c928cf57 100644 --- a/backend/test/routes/git.test.ts +++ b/backend/test/routes/git.test.ts @@ -6,6 +6,7 @@ import type { Database } from 'bun:sqlite' import type { Repo } from '../../../shared/src/types' import type { GitAuthService } from '../../src/services/git-auth' import type { ScheduleService } from '../../src/services/schedules' +import type { TerminalService } from '../../src/services/terminal' import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' vi.mock('bun:sqlite', () => ({ @@ -60,7 +61,7 @@ describe('Git Routes', () => { mockGitAuthService = { getGitEnvironment: vi.fn().mockReturnValue({}), } as unknown as GitAuthService - app = createRepoRoutes(mockDatabase, mockGitAuthService, {} as unknown as ScheduleService, createStubOpenCodeClient()) + app = createRepoRoutes(mockDatabase, mockGitAuthService, {} as unknown as ScheduleService, createStubOpenCodeClient(), {} as unknown as TerminalService) }) describe('GET /:id/git/status', () => { diff --git a/backend/test/routes/repo-terminals.test.ts b/backend/test/routes/repo-terminals.test.ts new file mode 100644 index 00000000..12539ce1 --- /dev/null +++ b/backend/test/routes/repo-terminals.test.ts @@ -0,0 +1,233 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { Hono } from 'hono' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { createRepoTerminalRoutes } from '../../src/routes/repo-terminals' +import { TerminalNotFoundError } from '../../src/services/terminal' +import type { TerminalService } from '../../src/services/terminal' +import type { GitAuthService } from '../../src/services/git-auth' +import type { OpenCodeClient } from '../../src/services/opencode/client' +import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' + +vi.mock('../../src/services/repo', () => ({ + resolveRepoOrAssistant: vi.fn(), + resolveRepoWorkingDirectory: vi.fn(), + getSiblingRepos: vi.fn(), +})) + +import { resolveRepoOrAssistant, resolveRepoWorkingDirectory, getSiblingRepos } from '../../src/services/repo' + +const database = {} as Database +const gitAuthService = { getGitEnvironment: vi.fn(() => ({})) } as unknown as GitAuthService +const openCodeClient: OpenCodeClient = createStubOpenCodeClient() + +const readyRepo = { id: 1, fullPath: '/tmp/repo', cloneStatus: 'ready' } as Repo + +const shellTerminal = { + id: 'pty-1', + title: 'Terminal', + kind: 'shell', + cwd: '/tmp/repo', + status: 'running', +} as const + +function createService(overrides: Partial = {}): TerminalService { + return { + list: vi.fn(async () => []), + create: vi.fn(async () => shellTerminal), + requireTerminal: vi.fn(async () => shellTerminal), + resize: vi.fn(async () => undefined), + remove: vi.fn(async () => undefined), + removeAll: vi.fn(async () => undefined), + ...overrides, + } as unknown as TerminalService +} + +function createApp(service: TerminalService): Hono { + const app = new Hono() + app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, service)) + return app +} + +const jsonHeaders = { 'Content-Type': 'application/json' } + +describe('Repo Terminal Routes', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(resolveRepoOrAssistant).mockImplementation((_db, id) => (id === 1 ? readyRepo : null)) + vi.mocked(resolveRepoWorkingDirectory).mockImplementation(async (_repo, directory) => { + if (directory === undefined || directory === '/tmp/repo') return '/tmp/repo' + return null + }) + vi.mocked(getSiblingRepos).mockResolvedValue([]) + }) + + describe('GET /:id/terminals', () => { + it('returns the terminals for the resolved directory', async () => { + const terminals = [{ ...shellTerminal }] + const list = vi.fn(async () => terminals) + const res = await createApp(createService({ list })).request('/1/terminals') + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ terminals }) + expect(list).toHaveBeenCalledWith('/tmp/repo') + }) + + it('returns 400 for a non-numeric repo id', async () => { + const res = await createApp(createService()).request('/abc/terminals') + expect(res.status).toBe(400) + }) + + it('returns 404 for an unknown repo', async () => { + vi.mocked(resolveRepoOrAssistant).mockReturnValue(null) + const res = await createApp(createService()).request('/2/terminals') + + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Repo not found' }) + }) + + it('returns 400 for a foreign directory', async () => { + const res = await createApp(createService()).request('/1/terminals?directory=/tmp/other') + + expect(res.status).toBe(400) + expect(await res.json()).toEqual({ error: 'Directory is not part of this repository' }) + }) + + it('returns 502 when the terminal service fails', async () => { + const list = vi.fn(async () => { + throw Object.assign(new Error('upstream failed'), { _tag: 'UnknownError' }) + }) + const res = await createApp(createService({ list })).request('/1/terminals') + + expect(res.status).toBe(502) + }) + }) + + describe('POST /:id/terminals', () => { + it('creates a shell with the default name', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createService({ create })).request('/1/terminals', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({}), + }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual(shellTerminal) + expect(create).toHaveBeenCalledWith('/tmp/repo', { kind: 'shell', name: 'Terminal' }) + }) + + it('creates a shell with the requested title and directory', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createService({ create })).request('/1/terminals', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ directory: '/tmp/repo', title: 'My shell' }), + }) + + expect(res.status).toBe(200) + expect(create).toHaveBeenCalledWith('/tmp/repo', { kind: 'shell', name: 'My shell' }) + }) + + it('returns 400 for an invalid body', async () => { + const create = vi.fn(async () => shellTerminal) + const res = await createApp(createService({ create })).request('/1/terminals', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({ title: 'a'.repeat(81) }), + }) + + expect(res.status).toBe(400) + expect(create).not.toHaveBeenCalled() + }) + + it('returns 404 for an unknown repo', async () => { + vi.mocked(resolveRepoOrAssistant).mockReturnValue(null) + const res = await createApp(createService()).request('/2/terminals', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({}), + }) + + expect(res.status).toBe(404) + }) + }) + + describe('PATCH /:id/terminals/:ptyID', () => { + it('resizes a known terminal', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const resize = vi.fn(async () => undefined) + const res = await createApp(createService({ requireTerminal, resize })).request('/1/terminals/pty-1', { + method: 'PATCH', + headers: jsonHeaders, + body: JSON.stringify({ directory: '/tmp/repo', cols: 80, rows: 24 }), + }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ success: true }) + expect(requireTerminal).toHaveBeenCalledWith('/tmp/repo', 'pty-1') + expect(resize).toHaveBeenCalledWith('/tmp/repo', 'pty-1', { cols: 80, rows: 24 }) + }) + + it('returns 400 for invalid resize bounds', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const app = createApp(createService({ requireTerminal })) + + for (const body of ['{"cols":0,"rows":24}', '{"cols":80}', '{"cols":80,"rows":501}', '{"cols":1.5,"rows":24}']) { + const res = await app.request('/1/terminals/pty-1', { method: 'PATCH', headers: jsonHeaders, body }) + expect(res.status).toBe(400) + } + + expect(requireTerminal).not.toHaveBeenCalled() + }) + + it('returns 404 for an unknown PTY id', async () => { + const requireTerminal = vi.fn(async () => { + throw new TerminalNotFoundError('missing') + }) + const res = await createApp(createService({ requireTerminal })).request('/1/terminals/missing', { + method: 'PATCH', + headers: jsonHeaders, + body: JSON.stringify({ cols: 80, rows: 24 }), + }) + + expect(res.status).toBe(404) + }) + + it('returns 400 for a foreign directory', async () => { + const res = await createApp(createService()).request('/1/terminals/pty-1', { + method: 'PATCH', + headers: jsonHeaders, + body: JSON.stringify({ directory: '/tmp/other', cols: 80, rows: 24 }), + }) + + expect(res.status).toBe(400) + }) + }) + + describe('DELETE /:id/terminals/:ptyID', () => { + it('removes a known terminal', async () => { + const requireTerminal = vi.fn(async () => shellTerminal) + const remove = vi.fn(async () => undefined) + const res = await createApp(createService({ requireTerminal, remove })).request('/1/terminals/pty-1?directory=/tmp/repo', { + method: 'DELETE', + }) + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ success: true }) + expect(requireTerminal).toHaveBeenCalledWith('/tmp/repo', 'pty-1') + expect(remove).toHaveBeenCalledWith('/tmp/repo', 'pty-1') + }) + + it('returns 404 for an unknown PTY id', async () => { + const requireTerminal = vi.fn(async () => { + throw new TerminalNotFoundError('missing') + }) + const res = await createApp(createService({ requireTerminal })).request('/1/terminals/missing', { + method: 'DELETE', + }) + + expect(res.status).toBe(404) + }) + }) +}) diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts index af33e242..3893c1fd 100644 --- a/backend/test/routes/repos.test.ts +++ b/backend/test/routes/repos.test.ts @@ -34,6 +34,7 @@ vi.mock('../../src/services/repo', () => ({ getSiblingRepos: vi.fn(), resolveRepoOrAssistant: vi.fn(), findSiblingByDirectory: vi.fn(), + resolveRepoWorkingDirectory: vi.fn(), })) vi.mock('../../src/services/assistant-mode', () => ({ @@ -77,6 +78,7 @@ import { createRepoRoutes } from '../../src/routes/repos' import { opencodeServerManager } from '../../src/services/opencode-single-server' import type { GitAuthService } from '../../src/services/git-auth' import type { ScheduleService } from '../../src/services/schedules' +import type { TerminalService } from '../../src/services/terminal' import type { AssistantModeStatus, Repo } from '@opencode-manager/shared/types' import type { OpenCodeApi } from '@opencode-manager/shared/opencode' import { ClientError } from '@opencode-manager/shared/opencode' @@ -92,6 +94,14 @@ const mockScheduleService = { prepareRepoDelete: mockPrepareRepoDelete, } as unknown as ScheduleService +const mockTerminalService = { + removeAll: vi.fn().mockResolvedValue(undefined), +} as unknown as TerminalService + +function createTestRoutes(openCodeClient: ReturnType = createStubOpenCodeClient()): ReturnType { + return createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, openCodeClient, mockTerminalService) +} + function createMockRepo(overrides: Partial = {}): Repo { return { id: 1, @@ -130,7 +140,7 @@ describe('Repo Routes', () => { it('should return 404 when repo not found', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/access', { method: 'POST' }) expect(res.status).toBe(404) @@ -153,7 +163,7 @@ describe('Repo Routes', () => { } vi.mocked(db.getRepoById).mockReturnValue(mockRepo) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/access', { method: 'POST' }) expect(res.status).toBe(200) @@ -179,7 +189,7 @@ describe('Repo Routes', () => { throw new Error('Database error') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/access', { method: 'POST' }) expect(res.status).toBe(500) @@ -192,7 +202,7 @@ describe('Repo Routes', () => { it('should return 404 when repo not found', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'GET' }) expect(res.status).toBe(404) @@ -227,7 +237,7 @@ describe('Repo Routes', () => { vi.mocked(getAssistantModeStatus).mockResolvedValue(mockStatus) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'GET' }) expect(res.status).toBe(200) @@ -243,7 +253,7 @@ describe('Repo Routes', () => { it('should return 404 when repo not found', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -282,7 +292,7 @@ describe('Repo Routes', () => { vi.mocked(ensureAssistantMode).mockResolvedValue(mockStatus) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -321,7 +331,7 @@ describe('Repo Routes', () => { vi.mocked(ensureAssistantMode).mockRejectedValue(new Error('Test error')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/assistant-mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -336,7 +346,7 @@ describe('Repo Routes', () => { it('should return 404 when repo not found', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/reset-permissions', { method: 'POST' }) expect(res.status).toBe(404) @@ -360,7 +370,7 @@ describe('Repo Routes', () => { directory: '/tmp/test-repo', project: { id: 'project-A', directory: '/tmp/test-repo', canonical: '/tmp/test-repo' }, })) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ + const app = createTestRoutes(createStubOpenCodeClient({ api: { location: { get: locationGet } } as unknown as OpenCodeApi, })) const res = await app.request('/1/reset-permissions', { method: 'POST' }) @@ -382,7 +392,7 @@ describe('Repo Routes', () => { ]) const savedRemove = vi.fn(async () => undefined) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ + const app = createTestRoutes(createStubOpenCodeClient({ api: { location: { get: locationGet }, permission: { saved: { list: savedList, remove: savedRemove } }, @@ -402,7 +412,7 @@ describe('Repo Routes', () => { describe('POST /', () => { it('should return 400 when neither repoUrl nor localPath is provided', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -418,7 +428,7 @@ describe('Repo Routes', () => { const repo = createMockRepo() vi.mocked(repoService.initLocalRepo).mockResolvedValue(repo) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -435,7 +445,7 @@ describe('Repo Routes', () => { const repo = createMockRepo({ repoUrl: 'https://github.com/test/remote' }) vi.mocked(repoService.cloneRepo).mockResolvedValue(repo) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -457,7 +467,7 @@ describe('Repo Routes', () => { it('should return 500 when repo creation throws', async () => { vi.mocked(repoService.initLocalRepo).mockRejectedValue(new Error('init failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -472,7 +482,7 @@ describe('Repo Routes', () => { describe('POST /discover', () => { it('should return 400 for an invalid body', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/discover', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -487,7 +497,7 @@ describe('Repo Routes', () => { const discovery = { repos: [createMockRepo()], discoveredCount: 1, existingCount: 0, errors: [] } vi.mocked(repoService.discoverLocalRepos).mockResolvedValue(discovery) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/discover', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -503,7 +513,7 @@ describe('Repo Routes', () => { it('should return 500 when discovery throws', async () => { vi.mocked(repoService.discoverLocalRepos).mockRejectedValue(new Error('discover failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/discover', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -524,7 +534,7 @@ describe('Repo Routes', () => { vi.mocked(repoService.getCurrentBranch).mockResolvedValue('main') vi.mocked(db.getRepoGitCredentialId).mockReturnValue('cred-1') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'GET' }) expect(res.status).toBe(200) @@ -542,7 +552,7 @@ describe('Repo Routes', () => { throw new Error('list failed') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/', { method: 'GET' }) expect(res.status).toBe(500) @@ -553,7 +563,7 @@ describe('Repo Routes', () => { describe('PUT /order', () => { it('should return 400 when order is not an array of numbers', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/order', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, @@ -565,7 +575,7 @@ describe('Repo Routes', () => { }) it('should update the repo order', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/order', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, @@ -579,7 +589,7 @@ describe('Repo Routes', () => { }) it('should return 500 when the body is not valid JSON', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/order', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, @@ -595,7 +605,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 5 })) vi.mocked(repoService.getCurrentBranch).mockResolvedValue('develop') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/5', { method: 'GET' }) expect(res.status).toBe(200) @@ -607,7 +617,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/5', { method: 'GET' }) expect(res.status).toBe(404) @@ -617,7 +627,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 5 })) vi.mocked(repoService.getCurrentBranch).mockRejectedValue(new Error('branch failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/5', { method: 'GET' }) expect(res.status).toBe(500) @@ -630,7 +640,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -644,7 +654,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) mockGetSettings.mockReturnValue({ preferences: { repoOrder: [], gitCredentials: [] }, updatedAt: Date.now() }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -663,7 +673,7 @@ describe('Repo Routes', () => { }) vi.mocked(db.getRepoGitCredentialId).mockReturnValue('cred-1') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -680,7 +690,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(db.getRepoGitCredentialId).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -696,7 +706,7 @@ describe('Repo Routes', () => { throw new Error('repo failed') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/git-credential', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -709,7 +719,7 @@ describe('Repo Routes', () => { describe('DELETE /:id', () => { it('should return 403 for the assistant repo id', async () => { - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/0', { method: 'DELETE' }) expect(res.status).toBe(403) @@ -718,7 +728,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1', { method: 'DELETE' }) expect(res.status).toBe(404) @@ -728,13 +738,26 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1', { method: 'DELETE' }) expect(res.status).toBe(200) const body = await res.json() as { success: boolean } expect(body.success).toBe(true) expect(mockPrepareRepoDelete).toHaveBeenCalledWith(1) + expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/repos/test-repo') + expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1) + }) + + it('should still delete the repo when terminal cleanup throws', async () => { + vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) + vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined) + vi.mocked(mockTerminalService.removeAll).mockRejectedValueOnce(new Error('pty cleanup failed')) + + const app = createTestRoutes() + const res = await app.request('/1', { method: 'DELETE' }) + + expect(res.status).toBe(200) expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1) }) @@ -742,7 +765,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(repoService.deleteRepoFiles).mockRejectedValue(new Error('delete failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1', { method: 'DELETE' }) expect(res.status).toBe(500) @@ -757,7 +780,7 @@ describe('Repo Routes', () => { vi.mocked(repoService.pullRepo).mockResolvedValue(undefined) vi.mocked(db.getRepoById).mockReturnValue(repo) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/3/pull', { method: 'POST' }) expect(res.status).toBe(200) @@ -769,7 +792,7 @@ describe('Repo Routes', () => { it('should return 500 when pulling throws', async () => { vi.mocked(repoService.pullRepo).mockRejectedValue(new Error('pull failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/3/pull', { method: 'POST' }) expect(res.status).toBe(500) @@ -782,7 +805,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -795,7 +818,7 @@ describe('Repo Routes', () => { it('should return 400 when the branch is missing', async () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -811,7 +834,7 @@ describe('Repo Routes', () => { vi.mocked(repoService.switchBranch).mockResolvedValue(undefined) vi.mocked(repoService.getCurrentBranch).mockResolvedValue('feature') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -828,7 +851,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(repoService.switchBranch).mockRejectedValue(new Error('switch failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/switch', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -845,7 +868,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -858,7 +881,7 @@ describe('Repo Routes', () => { it('should return 400 when the branch is missing', async () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -874,7 +897,7 @@ describe('Repo Routes', () => { vi.mocked(repoService.createBranch).mockResolvedValue(undefined) vi.mocked(repoService.getCurrentBranch).mockResolvedValue('feature') - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -891,7 +914,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(repoService.createBranch).mockRejectedValue(new Error('create failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/branch/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -908,7 +931,7 @@ describe('Repo Routes', () => { it('should return 404 when the repo does not exist', async () => { vi.mocked(db.getRepoById).mockReturnValue(null) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/download', { method: 'GET' }) expect(res.status).toBe(404) @@ -923,7 +946,7 @@ describe('Repo Routes', () => { ) vi.mocked(archiveService.deleteArchive).mockResolvedValue(undefined) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/download?includeGit=true&includePaths=src,docs', { method: 'GET' }) expect(res.status).toBe(200) @@ -946,7 +969,7 @@ describe('Repo Routes', () => { vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 })) vi.mocked(archiveService.createRepoArchive).mockRejectedValue(new Error('archive failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/1/download', { method: 'GET' }) expect(res.status).toBe(500) @@ -962,7 +985,7 @@ describe('Repo Routes', () => { throw new ClientError('Transport') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ + const app = createTestRoutes(createStubOpenCodeClient({ api: { location: { get: locationGet } } as unknown as OpenCodeApi, })) const res = await app.request('/1/reset-permissions', { method: 'POST' }) @@ -981,7 +1004,7 @@ describe('Repo Routes', () => { throw new Error('list failed') }) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient({ + const app = createTestRoutes(createStubOpenCodeClient({ api: { location: { get: locationGet }, permission: { saved: { list: savedList, remove: vi.fn() } }, @@ -1012,7 +1035,7 @@ describe('Repo Routes', () => { } vi.mocked(getAssistantModeStatus).mockResolvedValue(status) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/0/assistant-mode', { method: 'GET' }) expect(res.status).toBe(200) @@ -1035,7 +1058,7 @@ describe('Repo Routes', () => { } vi.mocked(ensureAssistantMode).mockResolvedValue(status) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/0/assistant-mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -1053,7 +1076,7 @@ describe('Repo Routes', () => { vi.mocked(buildAssistantRepo).mockReturnValue(assistantRepo) vi.mocked(getAssistantModeStatus).mockRejectedValue(new Error('assistant failed')) - const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, createStubOpenCodeClient()) + const app = createTestRoutes() const res = await app.request('/0/assistant-mode', { method: 'GET' }) expect(res.status).toBe(500) diff --git a/backend/test/services/terminal.test.ts b/backend/test/services/terminal.test.ts new file mode 100644 index 00000000..d097df48 --- /dev/null +++ b/backend/test/services/terminal.test.ts @@ -0,0 +1,184 @@ +import { describe, it, expect, vi } from 'vitest' +import { TerminalService, TerminalNotFoundError } from '../../src/services/terminal' +import type { OpenCodeClient } from '../../src/services/opencode/client' +import type { CredentialProvider } from '../../src/services/credential-provider' + +interface PtyRecord { + id: string + title: string + command: string + args: string[] + cwd: string + status: 'running' | 'exited' + pid: number + exitCode?: number +} + +function createPty(overrides: Partial = {}): PtyRecord { + return { id: 'pty-1', title: 'Terminal', command: 'sh', args: [], cwd: '/repo', status: 'running', pid: 1, ...overrides } +} + +function createClient(pty: Record): OpenCodeClient { + return { api: { pty } } as unknown as OpenCodeClient +} + +function createCredentialProvider(shellEnv: Record = {}): CredentialProvider { + return { getShellEnv: vi.fn(() => shellEnv) } as unknown as CredentialProvider +} + +describe('TerminalService', () => { + describe('list', () => { + it('passes the location and decodes each terminal title', async () => { + const list = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: [ + createPty({ id: 'a', title: 'Terminal' }), + createPty({ id: 'b', title: 'ocm:setup:Worktree setup' }), + createPty({ id: 'c', title: 'ocm:action:build:Build', status: 'exited', exitCode: 0 }), + ], + })) + const service = new TerminalService(createClient({ list }), createCredentialProvider()) + + const result = await service.list('/repo') + + expect(list).toHaveBeenCalledWith({ location: { directory: '/repo' } }) + expect(result).toEqual([ + { id: 'a', title: 'Terminal', kind: 'shell', cwd: '/repo', status: 'running' }, + { id: 'b', title: 'Worktree setup', kind: 'setup', cwd: '/repo', status: 'running' }, + { id: 'c', title: 'Build', kind: 'action', actionId: 'build', cwd: '/repo', status: 'exited', exitCode: 0 }, + ]) + }) + }) + + describe('create', () => { + it('sends the location, encoded title and merged environment', async () => { + const create = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: createPty({ id: 'pty-new', title: 'ocm:action:dev:Dev server' }), + })) + const credentialProvider = createCredentialProvider({ GH_TOKEN: 'gh' }) + const service = new TerminalService(createClient({ create }), credentialProvider) + + const result = await service.create('/repo', { + kind: 'action', + actionId: 'dev', + name: 'Dev server', + command: '/bin/sh', + args: ['-c', 'npm run dev'], + env: { FOO: 'bar' }, + }) + + expect(credentialProvider.getShellEnv).toHaveBeenCalledWith({ cwd: '/repo' }) + expect(create).toHaveBeenCalledWith({ + location: { directory: '/repo' }, + title: 'ocm:action:dev:Dev server', + command: '/bin/sh', + args: ['-c', 'npm run dev'], + env: { GH_TOKEN: 'gh', FOO: 'bar' }, + }) + expect(result).toEqual({ + id: 'pty-new', + title: 'Dev server', + kind: 'action', + actionId: 'dev', + cwd: '/repo', + status: 'running', + }) + }) + + it('omits command and args for a plain shell', async () => { + let captured: Record | undefined + const create = vi.fn(async (input: Record) => { + captured = input + return { + location: { directory: '/repo' }, + data: createPty({ id: 'pty-1', title: 'Terminal' }), + } + }) + const service = new TerminalService(createClient({ create }), createCredentialProvider()) + + await service.create('/repo', { kind: 'shell', name: 'Terminal' }) + + expect(captured).toMatchObject({ title: 'Terminal' }) + expect(captured).not.toHaveProperty('command') + expect(captured).not.toHaveProperty('args') + expect(captured?.env).toEqual({}) + }) + }) + + describe('requireTerminal', () => { + it('returns the terminal when the id exists in the directory', async () => { + const list = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: [createPty({ id: 'pty-1' })], + })) + const service = new TerminalService(createClient({ list }), createCredentialProvider()) + + await expect(service.requireTerminal('/repo', 'pty-1')).resolves.toMatchObject({ id: 'pty-1' }) + }) + + it('rejects a PTY id from another directory', async () => { + const list = vi.fn(async ({ location }: { location: { directory: string } }) => ({ + location: { directory: location.directory }, + data: location.directory === '/repo' ? [createPty({ id: 'pty-1' })] : [], + })) + const service = new TerminalService(createClient({ list }), createCredentialProvider()) + + await expect(service.requireTerminal('/other', 'pty-1')).rejects.toBeInstanceOf(TerminalNotFoundError) + }) + }) + + describe('resize', () => { + it('updates the terminal size with the location', async () => { + const update = vi.fn(async () => ({ location: { directory: '/repo' }, data: createPty() })) + const service = new TerminalService(createClient({ update }), createCredentialProvider()) + + await service.resize('/repo', 'pty-1', { cols: 120, rows: 40 }) + + expect(update).toHaveBeenCalledWith({ ptyID: 'pty-1', location: { directory: '/repo' }, size: { cols: 120, rows: 40 } }) + }) + }) + + describe('remove', () => { + it('removes the terminal with the location', async () => { + const remove = vi.fn(async () => undefined) + const service = new TerminalService(createClient({ remove }), createCredentialProvider()) + + await service.remove('/repo', 'pty-1') + + expect(remove).toHaveBeenCalledWith({ ptyID: 'pty-1', location: { directory: '/repo' } }) + }) + }) + + describe('removeAll', () => { + it('removes every terminal and tolerates a 404', async () => { + const list = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: [createPty({ id: 'a' }), createPty({ id: 'b' })], + })) + const notFound = Object.assign(new Error('not found'), { _tag: 'PtyNotFoundError' }) + const remove = vi.fn(async ({ ptyID }: { ptyID: string }) => { + if (ptyID === 'a') throw notFound + }) + const service = new TerminalService(createClient({ list, remove }), createCredentialProvider()) + + await expect(service.removeAll('/repo')).resolves.toBeUndefined() + expect(remove).toHaveBeenCalledTimes(2) + expect(remove).toHaveBeenCalledWith({ ptyID: 'a', location: { directory: '/repo' } }) + expect(remove).toHaveBeenCalledWith({ ptyID: 'b', location: { directory: '/repo' } }) + }) + + it('propagates a non-404 removal failure', async () => { + const list = vi.fn(async () => ({ + location: { directory: '/repo' }, + data: [createPty({ id: 'a' })], + })) + const remove = vi.fn(async () => { + throw new Error('boom') + }) + const service = new TerminalService(createClient({ list, remove }), createCredentialProvider()) + + await expect(service.removeAll('/repo')).rejects.toThrow('boom') + }) + }) +}) diff --git a/backend/test/shared/terminal-title.test.ts b/backend/test/shared/terminal-title.test.ts new file mode 100644 index 00000000..f5ab0c3e --- /dev/null +++ b/backend/test/shared/terminal-title.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/shared/utils' + +describe('terminal-title', () => { + describe('formatTerminalTitle', () => { + it('encodes a plain shell title as the name', () => { + expect(formatTerminalTitle({ kind: 'shell', name: 'Terminal' })).toBe('Terminal') + }) + + it('encodes a setup title with the setup prefix', () => { + expect(formatTerminalTitle({ kind: 'setup', name: 'Worktree setup' })).toBe('ocm:setup:Worktree setup') + }) + + it('encodes an action title with the action id', () => { + expect(formatTerminalTitle({ kind: 'action', name: 'Dev server', actionId: 'dev' })).toBe('ocm:action:dev:Dev server') + }) + + it('rejects an action without a valid action id', () => { + expect(() => formatTerminalTitle({ kind: 'action', name: 'Dev server' })).toThrow() + expect(() => formatTerminalTitle({ kind: 'action', name: 'Dev server', actionId: 'bad id' })).toThrow() + }) + }) + + describe('parseTerminalTitle', () => { + it('round-trips a shell title', () => { + expect(parseTerminalTitle(formatTerminalTitle({ kind: 'shell', name: 'My shell' }))).toEqual({ + kind: 'shell', + title: 'My shell', + }) + }) + + it('round-trips a setup title', () => { + expect(parseTerminalTitle(formatTerminalTitle({ kind: 'setup', name: 'Worktree setup' }))).toEqual({ + kind: 'setup', + title: 'Worktree setup', + }) + }) + + it('round-trips an action title including a colon in the name', () => { + expect(parseTerminalTitle(formatTerminalTitle({ kind: 'action', name: 'Dev: server', actionId: 'dev_1' }))).toEqual({ + kind: 'action', + title: 'Dev: server', + actionId: 'dev_1', + }) + }) + + it('treats an untagged title as a shell', () => { + expect(parseTerminalTitle('plain title')).toEqual({ kind: 'shell', title: 'plain title' }) + }) + + it('treats a malformed action id as a shell', () => { + expect(parseTerminalTitle('ocm:action:bad id:Dev server')).toEqual({ + kind: 'shell', + title: 'ocm:action:bad id:Dev server', + }) + }) + + it('treats an action prefix without a name as a shell', () => { + expect(parseTerminalTitle('ocm:action:dev')).toEqual({ kind: 'shell', title: 'ocm:action:dev' }) + }) + }) +}) diff --git a/shared/src/schemas/index.ts b/shared/src/schemas/index.ts index 67c74b35..f3511212 100644 --- a/shared/src/schemas/index.ts +++ b/shared/src/schemas/index.ts @@ -12,3 +12,4 @@ export * from './skills' export * from './internal-assistant' export * from './session-pins' export * from './logs' +export * from './terminal' diff --git a/shared/src/schemas/terminal.ts b/shared/src/schemas/terminal.ts new file mode 100644 index 00000000..b5e41e5b --- /dev/null +++ b/shared/src/schemas/terminal.ts @@ -0,0 +1,29 @@ +import { z } from 'zod' + +export const TerminalKindSchema = z.enum(['shell', 'action', 'setup']) + +export const TerminalInfoSchema = z.object({ + id: z.string(), + title: z.string(), + kind: TerminalKindSchema, + actionId: z.string().optional(), + cwd: z.string(), + status: z.enum(['running', 'exited']), + exitCode: z.number().int().optional(), +}) + +export const CreateTerminalRequestSchema = z.object({ + directory: z.string().trim().min(1).optional(), + title: z.string().trim().min(1).max(80).optional(), +}) + +export const ResizeTerminalRequestSchema = z.object({ + directory: z.string().trim().min(1).optional(), + cols: z.number().int().min(1).max(1000), + rows: z.number().int().min(1).max(500), +}) + +export type TerminalKind = z.infer +export type TerminalInfo = z.infer +export type CreateTerminalRequest = z.infer +export type ResizeTerminalRequest = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index a895fff0..b3a5055a 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -158,3 +158,10 @@ export { InstallSkillUploadRequestSchema, InstallSkillUploadManifestEntrySchema, } from '../schemas/skills' + +export type { + TerminalKind, + TerminalInfo, + CreateTerminalRequest, + ResizeTerminalRequest, +} from '../schemas/terminal' diff --git a/shared/src/utils/index.ts b/shared/src/utils/index.ts index 44daba75..46d714b0 100644 --- a/shared/src/utils/index.ts +++ b/shared/src/utils/index.ts @@ -2,3 +2,4 @@ export * from './jsonc' export * from './repo' export * from './sandbox-command' export * from './semver' +export * from './terminal-title' diff --git a/shared/src/utils/terminal-title.ts b/shared/src/utils/terminal-title.ts new file mode 100644 index 00000000..642bf4a1 --- /dev/null +++ b/shared/src/utils/terminal-title.ts @@ -0,0 +1,53 @@ +import type { TerminalKind } from '../schemas/terminal' + +const ACTION_TITLE_PREFIX = 'ocm:action:' +const SETUP_TITLE_PREFIX = 'ocm:setup:' +const ACTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/ + +export interface FormatTerminalTitleInput { + kind: TerminalKind + name: string + actionId?: string +} + +export interface ParsedTerminalTitle { + kind: TerminalKind + title: string + actionId?: string +} + +export function formatTerminalTitle(input: FormatTerminalTitleInput): string { + if (input.kind === 'action') { + if (!input.actionId || !ACTION_ID_PATTERN.test(input.actionId)) { + throw new Error('Action terminals require a valid action id') + } + return `${ACTION_TITLE_PREFIX}${input.actionId}:${input.name}` + } + + if (input.kind === 'setup') { + return `${SETUP_TITLE_PREFIX}${input.name}` + } + + return input.name +} + +export function parseTerminalTitle(raw: string): ParsedTerminalTitle { + if (raw.startsWith(ACTION_TITLE_PREFIX)) { + const rest = raw.slice(ACTION_TITLE_PREFIX.length) + const separator = rest.indexOf(':') + const actionId = separator === -1 ? rest : rest.slice(0, separator) + const title = separator === -1 ? '' : rest.slice(separator + 1) + + if (ACTION_ID_PATTERN.test(actionId) && title.length > 0) { + return { kind: 'action', title, actionId } + } + + return { kind: 'shell', title: raw } + } + + if (raw.startsWith(SETUP_TITLE_PREFIX)) { + return { kind: 'setup', title: raw.slice(SETUP_TITLE_PREFIX.length) } + } + + return { kind: 'shell', title: raw } +} From 13c29c635e7c0bba419f6c7d43a7beb66e9985cb Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:16:24 -0400 Subject: [PATCH 03/12] section 3: Phase 3: Terminal WebSocket bridge --- backend/package.json | 3 +- backend/src/index.ts | 15 +- backend/src/routes/repo-terminal-socket.ts | 114 +++++++++ backend/src/services/terminal.ts | 28 +++ backend/src/utils/websocket-bridge.ts | 85 +++++++ backend/test/index.test.ts | 2 +- .../test/routes/repo-terminal-socket.test.ts | 219 ++++++++++++++++++ backend/test/services/terminal.test.ts | 144 +++++++++++- backend/test/utils/websocket-bridge.test.ts | 135 +++++++++++ frontend/vite.config.ts | 1 + pnpm-lock.yaml | 29 ++- 11 files changed, 757 insertions(+), 18 deletions(-) create mode 100644 backend/src/routes/repo-terminal-socket.ts create mode 100644 backend/src/utils/websocket-bridge.ts create mode 100644 backend/test/routes/repo-terminal-socket.test.ts create mode 100644 backend/test/utils/websocket-bridge.test.ts 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/index.ts b/backend/src/index.ts index 1963d742..aec289f7 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' @@ -46,6 +48,7 @@ import { ensureDirectoryExists, writeFileContent, fileExists } from './services/ import { SettingsService } from './services/settings' 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' @@ -74,6 +77,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 @@ -223,7 +227,11 @@ try { const settingsServiceForSchedules = new SettingsService(db) const credentialProvider = new CredentialProvider(db) -const terminalService = new TerminalService(openCodeClient, credentialProvider) +const terminalService = new TerminalService( + openCodeClient, + credentialProvider, + () => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()), +) const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, settingsServiceForSchedules, credentialProvider, db) const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager) const scheduleRunnerInstance = new ScheduleRunner(scheduleService) @@ -272,6 +280,7 @@ app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService)) const protectedApi = new Hono() protectedApi.use('/*', requireAuth) +protectedApi.route('/repos', createRepoTerminalSocketRoutes(db, gitAuthService, openCodeClient, terminalService, upgradeWebSocket)) protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, terminalService)) protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor)) protectedApi.route('/files', createFileRoutes()) @@ -398,10 +407,12 @@ 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) + logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`) diff --git a/backend/src/routes/repo-terminal-socket.ts b/backend/src/routes/repo-terminal-socket.ts new file mode 100644 index 00000000..99059f8a --- /dev/null +++ b/backend/src/routes/repo-terminal-socket.ts @@ -0,0 +1,114 @@ +import { Hono } from 'hono' +import type { MiddlewareHandler } from 'hono' +import type { Database } from 'bun:sqlite' +import type { UpgradeWebSocket } from 'hono/ws' +import type { GitAuthService } from '../services/git-auth' +import type { OpenCodeClient } from '../services/opencode/client' +import type { TerminalService } from '../services/terminal' +import type { WebSocketBridge } from '../utils/websocket-bridge' +import { getErrorMessage } from '../utils/error-utils' +import { resolveTerminalDirectory } from './repo-terminals' + +export interface RepoTerminalSocketVariables { + terminalDirectory: string + terminalCursor: number | undefined +} + +const MAX_CLOSE_REASON_BYTES = 120 + +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, +) { + const app = new Hono<{ Variables: RepoTerminalSocketVariables }>() + const deps = { database, gitAuthService, openCodeClient } + + const validate: MiddlewareHandler<{ Variables: RepoTerminalSocketVariables }> = async (c, next) => { + const cursor = parseCursor(c.req.query('cursor')) + if (cursor === null) { + return c.json({ error: 'Invalid cursor' }, 400) + } + + const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id') ?? '', c.req.query('directory')) + 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), + }) + .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 + + const data = event.data + 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) + } + }, + onClose() { + closed = true + bridge?.close() + }, + } + }), + ) + + return app +} diff --git a/backend/src/services/terminal.ts b/backend/src/services/terminal.ts index 3833b87d..2b599e56 100644 --- a/backend/src/services/terminal.ts +++ b/backend/src/services/terminal.ts @@ -3,6 +3,7 @@ import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/share 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] @@ -31,6 +32,8 @@ 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 { @@ -78,6 +81,31 @@ export class TerminalService { } } + 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 { diff --git a/backend/src/utils/websocket-bridge.ts b/backend/src/utils/websocket-bridge.ts new file mode 100644 index 00000000..d60c8c76 --- /dev/null +++ b/backend/src/utils/websocket-bridge.ts @@ -0,0 +1,85 @@ +export interface WebSocketPeer { + send(data: string | Uint8Array): void + close(code?: number, reason?: string): void +} + +export interface WebSocketBridge { + send(data: string | ArrayBuffer | Uint8Array): void + close(): void +} + +export interface BridgeWebSocketOptions { + mapCloseCode?: (code: number) => number +} + +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, + options: BridgeWebSocketOptions = {}, +): WebSocketBridge { + upstream.binaryType = 'arraybuffer' + const mapCloseCode = options.mapCloseCode ?? defaultMapCloseCode + + 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) => { + 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)) + } + }) + + upstream.addEventListener('close', (event) => { + if (finished) return + finish() + peer.close(mapCloseCode((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/index.test.ts b/backend/test/index.test.ts index aedaadfa..306daafa 100644 --- a/backend/test/index.test.ts +++ b/backend/test/index.test.ts @@ -3,7 +3,7 @@ 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() +const serveMock = vi.fn<(options: unknown) => { on: () => void }>(() => ({ on: vi.fn() })) vi.mock('@hono/node-server', () => ({ serve: serveMock, 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..9f713dee --- /dev/null +++ b/backend/test/routes/repo-terminal-socket.test.ts @@ -0,0 +1,219 @@ +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest' +import { Hono } from 'hono' +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 = { getShellEnv: 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, + ), +) + +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) + + 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() + await closeServer(upstreamServer) + await closeServer(managerServer) +}) + +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) + }) +}) diff --git a/backend/test/services/terminal.test.ts b/backend/test/services/terminal.test.ts index d097df48..b0fdcb50 100644 --- a/backend/test/services/terminal.test.ts +++ b/backend/test/services/terminal.test.ts @@ -26,6 +26,62 @@ function createCredentialProvider(shellEnv: Record = {}): Creden return { getShellEnv: 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 +} + +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 }) + }, + } +} + describe('TerminalService', () => { describe('list', () => { it('passes the location and decodes each terminal title', async () => { @@ -37,7 +93,7 @@ describe('TerminalService', () => { createPty({ id: 'c', title: 'ocm:action:build:Build', status: 'exited', exitCode: 0 }), ], })) - const service = new TerminalService(createClient({ list }), createCredentialProvider()) + const service = createTerminalService(createClient({ list }), createCredentialProvider()) const result = await service.list('/repo') @@ -57,7 +113,7 @@ describe('TerminalService', () => { data: createPty({ id: 'pty-new', title: 'ocm:action:dev:Dev server' }), })) const credentialProvider = createCredentialProvider({ GH_TOKEN: 'gh' }) - const service = new TerminalService(createClient({ create }), credentialProvider) + const service = createTerminalService(createClient({ create }), credentialProvider) const result = await service.create('/repo', { kind: 'action', @@ -95,7 +151,7 @@ describe('TerminalService', () => { data: createPty({ id: 'pty-1', title: 'Terminal' }), } }) - const service = new TerminalService(createClient({ create }), createCredentialProvider()) + const service = createTerminalService(createClient({ create }), createCredentialProvider()) await service.create('/repo', { kind: 'shell', name: 'Terminal' }) @@ -112,7 +168,7 @@ describe('TerminalService', () => { location: { directory: '/repo' }, data: [createPty({ id: 'pty-1' })], })) - const service = new TerminalService(createClient({ list }), createCredentialProvider()) + const service = createTerminalService(createClient({ list }), createCredentialProvider()) await expect(service.requireTerminal('/repo', 'pty-1')).resolves.toMatchObject({ id: 'pty-1' }) }) @@ -122,7 +178,7 @@ describe('TerminalService', () => { location: { directory: location.directory }, data: location.directory === '/repo' ? [createPty({ id: 'pty-1' })] : [], })) - const service = new TerminalService(createClient({ list }), createCredentialProvider()) + const service = createTerminalService(createClient({ list }), createCredentialProvider()) await expect(service.requireTerminal('/other', 'pty-1')).rejects.toBeInstanceOf(TerminalNotFoundError) }) @@ -131,7 +187,7 @@ describe('TerminalService', () => { describe('resize', () => { it('updates the terminal size with the location', async () => { const update = vi.fn(async () => ({ location: { directory: '/repo' }, data: createPty() })) - const service = new TerminalService(createClient({ update }), createCredentialProvider()) + const service = createTerminalService(createClient({ update }), createCredentialProvider()) await service.resize('/repo', 'pty-1', { cols: 120, rows: 40 }) @@ -142,7 +198,7 @@ describe('TerminalService', () => { describe('remove', () => { it('removes the terminal with the location', async () => { const remove = vi.fn(async () => undefined) - const service = new TerminalService(createClient({ remove }), createCredentialProvider()) + const service = createTerminalService(createClient({ remove }), createCredentialProvider()) await service.remove('/repo', 'pty-1') @@ -160,7 +216,7 @@ describe('TerminalService', () => { const remove = vi.fn(async ({ ptyID }: { ptyID: string }) => { if (ptyID === 'a') throw notFound }) - const service = new TerminalService(createClient({ list, remove }), createCredentialProvider()) + const service = createTerminalService(createClient({ list, remove }), createCredentialProvider()) await expect(service.removeAll('/repo')).resolves.toBeUndefined() expect(remove).toHaveBeenCalledTimes(2) @@ -176,9 +232,79 @@ describe('TerminalService', () => { const remove = vi.fn(async () => { throw new Error('boom') }) - const service = new TerminalService(createClient({ list, remove }), createCredentialProvider()) + 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/utils/websocket-bridge.test.ts b/backend/test/utils/websocket-bridge.test.ts new file mode 100644 index 00000000..f7ff2a3e --- /dev/null +++ b/backend/test/utils/websocket-bridge.test.ts @@ -0,0 +1,135 @@ +import { describe, it, expect, vi } from 'vitest' +import { bridgeWebSocket, 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 }> +} + +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 }) + }, + } +} + +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('applies a custom close-code mapper', () => { + const upstream = new FakeUpstream() + const peer = createPeer() + bridgeWebSocket(asUpstream(upstream), peer, { mapCloseCode: () => 4000 }) + + upstream.emit('close', { code: 1006 }) + + expect(peer.closeCalls).toEqual([{ code: 4000, reason: undefined }]) + }) + + 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([]) + }) +}) diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 958e8cd6..ff67c7df 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -27,6 +27,7 @@ export default defineConfig(({ mode }) => { "/api": { target: `http://localhost:${backendPort}`, changeOrigin: true, + ws: true, }, }, }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d77b0f97..ff3f88c7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -27,8 +27,11 @@ importers: specifier: ^1.4.17 version: 1.4.17(@better-auth/core@1.4.17(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-call@1.1.8(zod@4.3.2))(jose@6.1.3)(kysely@0.28.10)(nanostores@1.1.0))(@better-auth/utils@0.3.0)(@better-fetch/fetch@1.1.21)(better-auth@1.4.17(better-sqlite3@12.9.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(solid-js@1.9.15)(vitest@3.2.4))(better-call@1.1.8(zod@4.3.2))(nanostores@1.1.0) '@hono/node-server': - specifier: ^1.19.5 - version: 1.19.7(hono@4.11.7) + specifier: ^1.19.17 + version: 1.19.17(hono@4.11.7) + '@hono/node-ws': + specifier: ^1.3.1 + version: 1.3.1(@hono/node-server@1.19.17(hono@4.11.7))(hono@4.11.7) '@opencode-manager/shared': specifier: workspace:* version: link:../shared @@ -1033,12 +1036,19 @@ packages: '@hexagon/base64@1.1.28': resolution: {integrity: sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==} - '@hono/node-server@1.19.7': - resolution: {integrity: sha512-vUcD0uauS7EU2caukW8z5lJKtoGMokxNbJtBiwHgpqxEXokaHCBkQUmCHhjFB1VUTWdqj25QoMkMKzgjq+uhrw==} + '@hono/node-server@1.19.17': + resolution: {integrity: sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==} engines: {node: '>=18.14.1'} peerDependencies: hono: ^4 + '@hono/node-ws@1.3.1': + resolution: {integrity: sha512-vo/MwCnpJAVHBkGzWjCJ28wF45fYHAfbPZcH2rodZODHtch2GHA94KtMfusmVycTUtsLAsaNsHhtY6P8X3RQsA==} + engines: {node: '>=18.14.1'} + peerDependencies: + '@hono/node-server': ^1.19.11 + hono: ^4.6.0 + '@hookform/resolvers@5.2.2': resolution: {integrity: sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==} peerDependencies: @@ -6191,10 +6201,19 @@ snapshots: '@hexagon/base64@1.1.28': {} - '@hono/node-server@1.19.7(hono@4.11.7)': + '@hono/node-server@1.19.17(hono@4.11.7)': dependencies: hono: 4.11.7 + '@hono/node-ws@1.3.1(@hono/node-server@1.19.17(hono@4.11.7))(hono@4.11.7)': + dependencies: + '@hono/node-server': 1.19.17(hono@4.11.7) + hono: 4.11.7 + ws: 8.21.3 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + '@hookform/resolvers@5.2.2(react-hook-form@7.69.0(react@19.2.3))(zod@4.3.2)': dependencies: '@standard-schema/utils': 0.3.0 From dc7cd2382f6b5792ebc8acd245e8d25e908c0a6f Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:24:03 -0400 Subject: [PATCH 04/12] section 4: Phase 4: Frontend terminal client and xterm view --- frontend/package.json | 3 + frontend/src/api/terminals.ts | 81 +++++++ .../src/components/terminal/TerminalView.tsx | 190 ++++++++++++++++ frontend/src/hooks/useTerminalSocket.test.tsx | 204 ++++++++++++++++++ frontend/src/hooks/useTerminalSocket.ts | 135 ++++++++++++ frontend/src/lib/terminal-protocol.test.ts | 47 ++++ frontend/src/lib/terminal-protocol.ts | 54 +++++ frontend/src/lib/terminal-theme.ts | 70 ++++++ frontend/src/lib/websocket-url.test.ts | 40 ++++ frontend/src/lib/websocket-url.ts | 8 + pnpm-lock.yaml | 24 +++ 11 files changed, 856 insertions(+) create mode 100644 frontend/src/api/terminals.ts create mode 100644 frontend/src/components/terminal/TerminalView.tsx create mode 100644 frontend/src/hooks/useTerminalSocket.test.tsx create mode 100644 frontend/src/hooks/useTerminalSocket.ts create mode 100644 frontend/src/lib/terminal-protocol.test.ts create mode 100644 frontend/src/lib/terminal-protocol.ts create mode 100644 frontend/src/lib/terminal-theme.ts create mode 100644 frontend/src/lib/websocket-url.test.ts create mode 100644 frontend/src/lib/websocket-url.ts 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/terminals.ts b/frontend/src/api/terminals.ts new file mode 100644 index 00000000..ffa31bef --- /dev/null +++ b/frontend/src/api/terminals.ts @@ -0,0 +1,81 @@ +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 directoryQuery(directory: string | undefined): string { + return directory ? `?${new URLSearchParams({ directory }).toString()}` : '' +} + +export function terminalsQueryKey(repoId: number, directory: string | undefined) { + return ['terminals', repoId, directory ?? null] as const +} + +export async function listTerminals(repoId: number, directory?: string): Promise { + const data = await fetchWrapper<{ terminals: TerminalInfo[] }>( + `${API_BASE_URL}/api/repos/${repoId}/terminals${directoryQuery(directory)}`, + ) + return data.terminals +} + +export 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), + }) +} + +export async function removeTerminal(repoId: number, ptyID: string, directory?: string): Promise { + return fetchWrapperVoid( + `${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}${directoryQuery(directory)}`, + { method: 'DELETE' }, + ) +} + +export 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: ['terminals', repoId] }) + }, + }) +} + +export 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: ['terminals', repoId] }) + }, + }) +} diff --git a/frontend/src/components/terminal/TerminalView.tsx b/frontend/src/components/terminal/TerminalView.tsx new file mode 100644 index 00000000..62892053 --- /dev/null +++ b/frontend/src/components/terminal/TerminalView.tsx @@ -0,0 +1,190 @@ +import { useCallback, useEffect, useRef } from 'react' +import { Terminal } from '@xterm/xterm' +import { FitAddon } from '@xterm/addon-fit' +import { WebLinksAddon } from '@xterm/addon-web-links' +import '@xterm/xterm/css/xterm.css' +import { resizeTerminal } from '@/api/terminals' +import { applyCtrlModifier } from '@/lib/terminal-protocol' +import { resolveTerminalTheme } from '@/lib/terminal-theme' +import { useTerminalSocket } from '@/hooks/useTerminalSocket' +import { useMobile } from '@/hooks/useMobile' +import { cn } from '@/lib/utils' + +const RESIZE_DEBOUNCE_MS = 150 + +const MONOSPACE_FONT = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace' + +function defaultOpenLink(uri: string) { + window.open(uri, '_blank', 'noopener,noreferrer') +} + +export interface TerminalViewProps { + repoId: number + directory: string | undefined + ptyID: string + active: boolean + ctrlArmed: boolean + onCtrlConsumed: () => void + onOpenLink?: (uri: string) => void + onExited: () => void +} + +export function TerminalView({ + repoId, + directory, + ptyID, + active, + ctrlArmed, + onCtrlConsumed, + onOpenLink, + onExited, +}: TerminalViewProps) { + const containerRef = useRef(null) + const terminalRef = useRef(null) + const fitAddonRef = useRef(null) + const sendRef = useRef<(data: string) => void>(() => {}) + const ctrlArmedRef = useRef(ctrlArmed) + const onCtrlConsumedRef = useRef(onCtrlConsumed) + const onOpenLinkRef = useRef(onOpenLink) + const onExitedRef = useRef(onExited) + const isMobile = useMobile() + const isMobileRef = useRef(isMobile) + + ctrlArmedRef.current = ctrlArmed + onCtrlConsumedRef.current = onCtrlConsumed + onOpenLinkRef.current = onOpenLink + onExitedRef.current = onExited + isMobileRef.current = isMobile + + const handleOutput = useCallback((text: string) => { + terminalRef.current?.write(text) + }, []) + + const handleExit = useCallback(() => { + terminalRef.current?.write('\r\n[process exited]\r\n') + onExitedRef.current() + }, []) + + const { send } = useTerminalSocket({ + repoId, + directory, + ptyID, + onOutput: handleOutput, + onExit: handleExit, + enabled: true, + }) + sendRef.current = send + + useEffect(() => { + const container = containerRef.current + if (!container) return + + const terminal = new Terminal({ + cursorBlink: true, + scrollback: 5000, + fontFamily: MONOSPACE_FONT, + fontSize: isMobileRef.current ? 12 : 13, + theme: resolveTerminalTheme(document.documentElement), + }) + const fitAddon = new FitAddon() + terminal.loadAddon(fitAddon) + terminal.loadAddon( + new WebLinksAddon((_event, uri) => { + const openLink = onOpenLinkRef.current ?? defaultOpenLink + openLink(uri) + }), + ) + terminal.open(container) + + terminalRef.current = terminal + fitAddonRef.current = fitAddon + + const dataDisposable = terminal.onData((data) => { + if (ctrlArmedRef.current) { + sendRef.current(applyCtrlModifier(data)) + onCtrlConsumedRef.current() + return + } + sendRef.current(data) + }) + + return () => { + dataDisposable.dispose() + terminal.dispose() + terminalRef.current = null + fitAddonRef.current = null + } + }, []) + + useEffect(() => { + const terminal = terminalRef.current + if (!terminal) return + terminal.options.fontSize = isMobile ? 12 : 13 + try { + fitAddonRef.current?.fit() + } catch { + return + } + }, [isMobile]) + + useEffect(() => { + const root = document.documentElement + const applyTheme = () => { + const terminal = terminalRef.current + if (!terminal) return + terminal.options.theme = resolveTerminalTheme(root) + } + const observer = new MutationObserver(applyTheme) + observer.observe(root, { attributes: true, attributeFilter: ['class', 'style'] }) + return () => observer.disconnect() + }, []) + + useEffect(() => { + const container = containerRef.current + if (!container) return + + let timer: ReturnType | null = null + + const scheduleResize = () => { + if (timer) clearTimeout(timer) + timer = setTimeout(() => { + const terminal = terminalRef.current + const fitAddon = fitAddonRef.current + if (!terminal || !fitAddon) return + try { + fitAddon.fit() + } catch { + return + } + resizeTerminal(repoId, ptyID, { directory, cols: terminal.cols, rows: terminal.rows }).catch(() => {}) + }, RESIZE_DEBOUNCE_MS) + } + + const observer = new ResizeObserver(scheduleResize) + observer.observe(container) + scheduleResize() + + return () => { + observer.disconnect() + if (timer) clearTimeout(timer) + } + }, [repoId, directory, ptyID]) + + useEffect(() => { + if (!active) return + try { + fitAddonRef.current?.fit() + } catch { + return + } + terminalRef.current?.focus() + }, [active]) + + return ( +
+ ) +} diff --git a/frontend/src/hooks/useTerminalSocket.test.tsx b/frontend/src/hooks/useTerminalSocket.test.tsx new file mode 100644 index 00000000..3e09c747 --- /dev/null +++ b/frontend/src/hooks/useTerminalSocket.test.tsx @@ -0,0 +1,204 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, renderHook } from '@testing-library/react' +import { useTerminalSocket } from './useTerminalSocket' + +class FakeWebSocket { + static CONNECTING = 0 + static OPEN = 1 + static CLOSING = 2 + static CLOSED = 3 + static instances: FakeWebSocket[] = [] + + url: string + binaryType = 'blob' + readyState = FakeWebSocket.CONNECTING + sent: string[] = [] + onopen: ((event: Event) => void) | null = null + onmessage: ((event: MessageEvent) => void) | null = null + onclose: ((event: CloseEvent) => void) | null = null + onerror: ((event: Event) => void) | null = null + + constructor(url: string) { + this.url = url + FakeWebSocket.instances.push(this) + } + + send(data: string) { + this.sent.push(data) + } + + close() { + this.readyState = FakeWebSocket.CLOSED + } + + open() { + this.readyState = FakeWebSocket.OPEN + this.onopen?.(new Event('open')) + } + + message(data: string | ArrayBuffer) { + this.onmessage?.({ data } as MessageEvent) + } + + serverClose(code: number) { + this.readyState = FakeWebSocket.CLOSED + this.onclose?.({ code } as CloseEvent) + } +} + +function metaFrame(cursor: number): ArrayBuffer { + const payload = new TextEncoder().encode(JSON.stringify({ cursor })) + const bytes = new Uint8Array(payload.length + 1) + bytes[0] = 0x00 + bytes.set(payload, 1) + return bytes.buffer +} + +function renderSocket(overrides: Partial[0]> = {}) { + return renderHook(() => + useTerminalSocket({ + repoId: 1, + directory: '/work/repo', + ptyID: 'pty-1', + onOutput: vi.fn(), + onExit: vi.fn(), + enabled: true, + ...overrides, + }), + ) +} + +describe('useTerminalSocket', () => { + beforeEach(() => { + FakeWebSocket.instances = [] + vi.stubGlobal('WebSocket', FakeWebSocket) + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + }) + + it('includes the directory in the connection url', () => { + renderSocket() + const url = new URL(FakeWebSocket.instances[0].url) + expect(url.pathname).toBe('/api/repos/1/terminals/pty-1/connect') + expect(url.searchParams.get('directory')).toBe('/work/repo') + }) + + it('accumulates the cursor and sends it when reconnecting after 1006', () => { + renderSocket() + const first = FakeWebSocket.instances[0] + + act(() => { + first.open() + first.message(metaFrame(5)) + first.message('abc') + }) + + act(() => { + first.serverClose(1006) + }) + + expect(FakeWebSocket.instances).toHaveLength(1) + act(() => { + vi.advanceTimersByTime(1000) + }) + + expect(FakeWebSocket.instances).toHaveLength(2) + const second = new URL(FakeWebSocket.instances[1].url) + expect(second.searchParams.get('cursor')).toBe('8') + expect(second.searchParams.get('directory')).toBe('/work/repo') + }) + + it('calls onExit without reconnecting on close code 4404', () => { + const onExit = vi.fn() + renderSocket({ onExit }) + + act(() => { + FakeWebSocket.instances[0].serverClose(4404) + }) + act(() => { + vi.advanceTimersByTime(60000) + }) + + expect(onExit).toHaveBeenCalledTimes(1) + expect(FakeWebSocket.instances).toHaveLength(1) + }) + + it('exhausts the retry budget when upstream connections keep failing after open', () => { + const { result } = renderSocket() + const delays = [1000, 2000, 5000, 5000, 5000] + + for (const delay of delays) { + const socket = FakeWebSocket.instances[FakeWebSocket.instances.length - 1] + act(() => { + socket.open() + socket.serverClose(1011) + }) + expect(result.current.status).toBe('reconnecting') + act(() => { + vi.advanceTimersByTime(delay) + }) + } + + const finalSocket = FakeWebSocket.instances[FakeWebSocket.instances.length - 1] + act(() => { + finalSocket.open() + finalSocket.serverClose(1011) + }) + + expect(result.current.status).toBe('closed') + expect(FakeWebSocket.instances).toHaveLength(6) + + act(() => { + vi.advanceTimersByTime(60000) + }) + expect(FakeWebSocket.instances).toHaveLength(6) + }) + + it('resets the retry budget only after a healthy upstream session', () => { + const { result } = renderSocket() + + act(() => { + FakeWebSocket.instances[0].open() + FakeWebSocket.instances[0].message(metaFrame(0)) + FakeWebSocket.instances[0].serverClose(1011) + }) + act(() => { + vi.advanceTimersByTime(1000) + }) + + expect(FakeWebSocket.instances).toHaveLength(2) + act(() => { + FakeWebSocket.instances[1].open() + FakeWebSocket.instances[1].serverClose(1011) + }) + expect(result.current.status).toBe('reconnecting') + act(() => { + vi.advanceTimersByTime(2000) + }) + + expect(FakeWebSocket.instances).toHaveLength(3) + }) + + it('forwards send to the open socket', () => { + const { result } = renderSocket() + const socket = FakeWebSocket.instances[0] + + act(() => { + socket.open() + }) + act(() => { + result.current.send('ls\n') + }) + + expect(socket.sent).toContain('ls\n') + }) + + it('does not connect when disabled', () => { + renderSocket({ enabled: false }) + expect(FakeWebSocket.instances).toHaveLength(0) + }) +}) diff --git a/frontend/src/hooks/useTerminalSocket.ts b/frontend/src/hooks/useTerminalSocket.ts new file mode 100644 index 00000000..5cf39a8d --- /dev/null +++ b/frontend/src/hooks/useTerminalSocket.ts @@ -0,0 +1,135 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { TerminalFrameDecoder } from '@/lib/terminal-protocol' +import { toWebSocketUrl } from '@/lib/websocket-url' + +export type TerminalSocketStatus = 'connecting' | 'open' | 'reconnecting' | 'closed' + +export interface UseTerminalSocketOptions { + repoId: number + directory: string | undefined + ptyID: string + onOutput: (text: string) => void + onExit: () => void + enabled: boolean +} + +const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 5000, 5000] +const TERMINAL_CLOSE_CODES = new Set([1000, 4404]) + +function buildSocketUrl( + repoId: number, + ptyID: string, + directory: string | undefined, + cursor: number | undefined, +): string { + const params = new URLSearchParams() + if (directory !== undefined) params.set('directory', directory) + if (cursor !== undefined) params.set('cursor', String(cursor)) + const query = params.toString() + return toWebSocketUrl( + `/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}/connect${query ? `?${query}` : ''}`, + ) +} + +export function useTerminalSocket({ + repoId, + directory, + ptyID, + onOutput, + onExit, + enabled, +}: UseTerminalSocketOptions) { + const socketRef = useRef(null) + const cursorRef = useRef(undefined) + const onOutputRef = useRef(onOutput) + const onExitRef = useRef(onExit) + onOutputRef.current = onOutput + onExitRef.current = onExit + + const [status, setStatus] = useState(enabled ? 'connecting' : 'closed') + + const send = useCallback((data: string) => { + const socket = socketRef.current + if (socket && socket.readyState === WebSocket.OPEN) { + socket.send(data) + } + }, []) + + useEffect(() => { + if (!enabled) { + setStatus('closed') + return + } + + let disposed = false + let attempt = 0 + let reconnectTimer: ReturnType | null = null + const decoder = new TerminalFrameDecoder() + cursorRef.current = undefined + + const connect = () => { + if (disposed) return + setStatus(attempt === 0 ? 'connecting' : 'reconnecting') + + const socket = new WebSocket(buildSocketUrl(repoId, ptyID, directory, cursorRef.current)) + socket.binaryType = 'arraybuffer' + socketRef.current = socket + + socket.onopen = () => { + if (disposed || socketRef.current !== socket) return + setStatus('open') + } + + socket.onmessage = (event) => { + if (disposed || socketRef.current !== socket) return + const frame = decoder.decode(event.data as string | ArrayBuffer) + if (frame.type === 'cursor') { + attempt = 0 + cursorRef.current = frame.cursor + return + } + cursorRef.current = (cursorRef.current ?? 0) + frame.text.length + onOutputRef.current(frame.text) + } + + socket.onclose = (event) => { + if (disposed || socketRef.current !== socket) return + socketRef.current = null + + if (TERMINAL_CLOSE_CODES.has(event.code)) { + setStatus('closed') + onExitRef.current() + return + } + + if (attempt >= RECONNECT_DELAYS_MS.length) { + setStatus('closed') + return + } + + const delay = RECONNECT_DELAYS_MS[attempt] + attempt += 1 + setStatus('reconnecting') + reconnectTimer = setTimeout(connect, delay) + } + } + + connect() + + return () => { + disposed = true + if (reconnectTimer) clearTimeout(reconnectTimer) + const socket = socketRef.current + socketRef.current = null + if (socket) { + socket.onopen = null + socket.onmessage = null + socket.onclose = null + socket.onerror = null + socket.close() + } + } + }, [repoId, directory, ptyID, enabled]) + + return { send, status } +} diff --git a/frontend/src/lib/terminal-protocol.test.ts b/frontend/src/lib/terminal-protocol.test.ts new file mode 100644 index 00000000..a23d25ee --- /dev/null +++ b/frontend/src/lib/terminal-protocol.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import { TerminalFrameDecoder, applyCtrlModifier } from './terminal-protocol' + +function metaFrame(cursor: number): ArrayBuffer { + const payload = new TextEncoder().encode(JSON.stringify({ cursor })) + const bytes = new Uint8Array(payload.length + 1) + bytes[0] = 0x00 + bytes.set(payload, 1) + return bytes.buffer +} + +describe('TerminalFrameDecoder', () => { + it('decodes the meta frame into a cursor', () => { + const decoder = new TerminalFrameDecoder() + expect(decoder.decode(metaFrame(42))).toEqual({ type: 'cursor', cursor: 42 }) + }) + + it('decodes split multibyte UTF-8 across binary frames', () => { + const decoder = new TerminalFrameDecoder() + const encoded = new TextEncoder().encode('→') + const first = encoded.slice(0, 1) + const second = encoded.slice(1) + + expect(decoder.decode(first.buffer)).toEqual({ type: 'output', text: '' }) + expect(decoder.decode(second.buffer)).toEqual({ type: 'output', text: '→' }) + }) + + it('passes string frames through', () => { + const decoder = new TerminalFrameDecoder() + expect(decoder.decode('plain text')).toEqual({ type: 'output', text: 'plain text' }) + }) +}) + +describe('applyCtrlModifier', () => { + it('maps a letter to its control code', () => { + expect(applyCtrlModifier('c')).toBe('\x03') + }) + + it('maps a control symbol to its control code', () => { + expect(applyCtrlModifier('[')).toBe('\x1b') + }) + + it('returns non-letter input unchanged', () => { + expect(applyCtrlModifier('1')).toBe('1') + expect(applyCtrlModifier('ab')).toBe('ab') + }) +}) diff --git a/frontend/src/lib/terminal-protocol.ts b/frontend/src/lib/terminal-protocol.ts new file mode 100644 index 00000000..f2cb7f39 --- /dev/null +++ b/frontend/src/lib/terminal-protocol.ts @@ -0,0 +1,54 @@ +const META_FRAME_PREFIX = 0x00 + +const CTRL_SYMBOLS: Record = { + '@': '\x00', + '[': '\x1b', + '\\': '\x1c', + ']': '\x1d', + '^': '\x1e', + '_': '\x1f', +} + +export type TerminalFrame = + | { type: 'output'; text: string } + | { type: 'cursor'; cursor: number } + +export class TerminalFrameDecoder { + private readonly decoder = new TextDecoder('utf-8') + + decode(data: string | ArrayBuffer): TerminalFrame { + if (typeof data === 'string') { + return { type: 'output', text: data } + } + + const bytes = new Uint8Array(data) + if (bytes.length > 0 && bytes[0] === META_FRAME_PREFIX) { + return this.decodeMetaFrame(bytes.subarray(1)) + } + + return { type: 'output', text: this.decoder.decode(bytes, { stream: true }) } + } + + private decodeMetaFrame(payload: Uint8Array): TerminalFrame { + try { + const parsed = JSON.parse(new TextDecoder('utf-8').decode(payload)) as { cursor?: unknown } + if (typeof parsed.cursor === 'number' && Number.isSafeInteger(parsed.cursor)) { + return { type: 'cursor', cursor: parsed.cursor } + } + } catch { + return { type: 'output', text: '' } + } + return { type: 'output', text: '' } + } +} + +export function applyCtrlModifier(data: string): string { + if (data.length !== 1) return data + + const upper = data.toUpperCase() + if (upper >= 'A' && upper <= 'Z') { + return String.fromCharCode(upper.charCodeAt(0) - 64) + } + + return CTRL_SYMBOLS[data] ?? data +} diff --git a/frontend/src/lib/terminal-theme.ts b/frontend/src/lib/terminal-theme.ts new file mode 100644 index 00000000..914226e6 --- /dev/null +++ b/frontend/src/lib/terminal-theme.ts @@ -0,0 +1,70 @@ +import type { ITheme } from '@xterm/xterm' + +const BASE_TOKENS = { + background: 'background', + foreground: 'foreground', + cursor: 'primary', + selectionBackground: 'accent', +} as const + +const ANSI_TOKENS = { + black: 'muted', + red: 'destructive', + green: 'success', + yellow: 'warning', + blue: 'info', + magenta: 'highlight', + cyan: 'syntax-property', + white: 'foreground', +} as const + +type AnsiName = keyof typeof ANSI_TOKENS + +function collectTokenColors(root: HTMLElement): Map { + const tokens = new Set([ + ...Object.values(BASE_TOKENS), + ...Object.values(ANSI_TOKENS), + ]) + + const probes = new Map() + for (const token of tokens) { + const probe = document.createElement('span') + probe.style.color = `var(--color-${token})` + probe.style.position = 'absolute' + probe.style.width = '0' + probe.style.height = '0' + probe.style.overflow = 'hidden' + probe.style.opacity = '0' + probe.style.pointerEvents = 'none' + root.appendChild(probe) + probes.set(token, probe) + } + + const colors = new Map() + for (const [token, probe] of probes) { + colors.set(token, getComputedStyle(probe).color) + root.removeChild(probe) + } + return colors +} + +function ansiTheme(colors: Map): Record}`, string | undefined> { + const theme = {} as Record}`, string | undefined> + for (const name of Object.keys(ANSI_TOKENS) as AnsiName[]) { + const color = colors.get(ANSI_TOKENS[name]) + theme[name] = color + theme[`bright${name[0].toUpperCase()}${name.slice(1)}` as `bright${Capitalize}`] = color + } + return theme +} + +export function resolveTerminalTheme(root: HTMLElement): ITheme { + const colors = collectTokenColors(root) + return { + background: colors.get(BASE_TOKENS.background), + foreground: colors.get(BASE_TOKENS.foreground), + cursor: colors.get(BASE_TOKENS.cursor), + selectionBackground: colors.get(BASE_TOKENS.selectionBackground), + ...ansiTheme(colors), + } +} diff --git a/frontend/src/lib/websocket-url.test.ts b/frontend/src/lib/websocket-url.test.ts new file mode 100644 index 00000000..002333c2 --- /dev/null +++ b/frontend/src/lib/websocket-url.test.ts @@ -0,0 +1,40 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { toWebSocketUrl } from './websocket-url' + +const state = vi.hoisted(() => ({ apiBaseUrl: '' })) + +vi.mock('@/config', () => ({ + get API_BASE_URL() { + return state.apiBaseUrl + }, +})) + +describe('toWebSocketUrl', () => { + afterEach(() => { + state.apiBaseUrl = '' + }) + + it('uses the page origin over http when no API base url is configured', () => { + expect(toWebSocketUrl('/api/repos/1/terminals/t/connect')).toBe( + 'ws://localhost/api/repos/1/terminals/t/connect', + ) + }) + + it('uses the page origin over https when no API base url is configured', () => { + const original = window.location + Object.defineProperty(window, 'location', { + configurable: true, + value: new URL('https://example.com'), + }) + try { + expect(toWebSocketUrl('/api/x')).toBe('wss://example.com/api/x') + } finally { + Object.defineProperty(window, 'location', { configurable: true, value: original }) + } + }) + + it('uses an absolute API base url and preserves the query', () => { + state.apiBaseUrl = 'https://api.example.com' + expect(toWebSocketUrl('/api/x?directory=%2Ftmp')).toBe('wss://api.example.com/api/x?directory=%2Ftmp') + }) +}) diff --git a/frontend/src/lib/websocket-url.ts b/frontend/src/lib/websocket-url.ts new file mode 100644 index 00000000..d554c1a9 --- /dev/null +++ b/frontend/src/lib/websocket-url.ts @@ -0,0 +1,8 @@ +import { API_BASE_URL } from '@/config' + +export function toWebSocketUrl(pathWithQuery: string): string { + const base = API_BASE_URL || window.location.origin + const url = new URL(pathWithQuery, base) + url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:' + return url.toString() +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ff3f88c7..294f9a94 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -153,6 +153,15 @@ importers: '@tanstack/react-query': specifier: ^5.90.5 version: 5.90.16(react@19.2.3) + '@xterm/addon-fit': + specifier: ^0.11.0 + version: 0.11.0 + '@xterm/addon-web-links': + specifier: ^0.12.0 + version: 0.12.0 + '@xterm/xterm': + specifier: ^6.0.0 + version: 6.0.0 better-auth: specifier: ^1.4.17 version: 1.4.17(better-sqlite3@12.9.0)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)(solid-js@1.9.15)(vitest@3.2.4) @@ -2541,6 +2550,15 @@ packages: '@vitest/utils@3.2.4': resolution: {integrity: sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==} + '@xterm/addon-fit@0.11.0': + resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==} + + '@xterm/addon-web-links@0.12.0': + resolution: {integrity: sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==} + + '@xterm/xterm@6.0.0': + resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==} + abbrev@4.0.0: resolution: {integrity: sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==} engines: {node: ^20.17.0 || >=22.9.0} @@ -7945,6 +7963,12 @@ snapshots: loupe: 3.2.1 tinyrainbow: 2.0.0 + '@xterm/addon-fit@0.11.0': {} + + '@xterm/addon-web-links@0.12.0': {} + + '@xterm/xterm@6.0.0': {} + abbrev@4.0.0: {} abort-controller@3.0.0: From c320e2ac7d52a1ae7fec4509bc9b0ee15d418fb7 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:40:39 -0400 Subject: [PATCH 05/12] section 5: Phase 5: Terminal panel, navigation and mobile key bar --- .../navigation/moreDrawerItems.test.ts | 24 +- .../components/navigation/moreDrawerItems.ts | 5 +- .../components/terminal/TerminalKeyBar.tsx | 70 ++++++ .../terminal/TerminalPanel.test.tsx | 192 +++++++++++++++ .../src/components/terminal/TerminalPanel.tsx | 220 ++++++++++++++++++ .../components/terminal/TerminalView.test.tsx | 133 +++++++++++ .../src/components/terminal/TerminalView.tsx | 34 ++- frontend/src/pages/AssistantRedirect.tsx | 3 + frontend/src/pages/RepoDetail.tsx | 9 + frontend/src/pages/SessionDetail.tsx | 9 + 10 files changed, 678 insertions(+), 21 deletions(-) create mode 100644 frontend/src/components/terminal/TerminalKeyBar.tsx create mode 100644 frontend/src/components/terminal/TerminalPanel.test.tsx create mode 100644 frontend/src/components/terminal/TerminalPanel.tsx create mode 100644 frontend/src/components/terminal/TerminalView.test.tsx diff --git a/frontend/src/components/navigation/moreDrawerItems.test.ts b/frontend/src/components/navigation/moreDrawerItems.test.ts index 353fed70..30bcd2dc 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(10) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[1].dialog).toBe('files') @@ -29,13 +29,15 @@ 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('settings') + expect(items[9].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(10) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[2].key).toBe('mcp') @@ -44,13 +46,15 @@ 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('settings') + expect(items[9].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(10) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[1].dialog).toBe('files') @@ -59,8 +63,10 @@ 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('settings') + expect(items[9].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..b327463e 100644 --- a/frontend/src/components/navigation/moreDrawerItems.ts +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -1,5 +1,5 @@ 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 } from 'lucide-react' import { getAssistantPath, isAssistantPath } from '@/lib/navigation' export interface MoreDrawerItem { @@ -58,6 +58,7 @@ 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' }, ...baseItems, ] @@ -76,6 +77,7 @@ 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/${sessionDetailMatch[1]}/schedules` }, { key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' }, + { key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' }, ...baseItems, ] @@ -93,6 +95,7 @@ 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' }, ...baseItems, ] diff --git a/frontend/src/components/terminal/TerminalKeyBar.tsx b/frontend/src/components/terminal/TerminalKeyBar.tsx new file mode 100644 index 00000000..b5a74675 --- /dev/null +++ b/frontend/src/components/terminal/TerminalKeyBar.tsx @@ -0,0 +1,70 @@ +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' + +interface TerminalKeyBarProps { + onSend: (data: string) => void + ctrlArmed: boolean + onToggleCtrl: () => void +} + +interface SpecialKey { + label: string + data: string + ariaLabel?: string +} + +const ESCAPE_KEY = '\x1b' +const TAB_KEY = '\t' + +const ARROW_KEYS: SpecialKey[] = [ + { label: '↑', data: '\x1b[A', ariaLabel: 'Arrow up' }, + { label: '↓', data: '\x1b[B', ariaLabel: 'Arrow down' }, + { label: '←', data: '\x1b[D', ariaLabel: 'Arrow left' }, + { label: '→', data: '\x1b[C', ariaLabel: 'Arrow right' }, +] + +const SYMBOL_KEYS: SpecialKey[] = [ + { label: '|', data: '|' }, + { label: '~', data: '~' }, + { label: '/', data: '/' }, +] + +export function TerminalKeyBar({ onSend, ctrlArmed, onToggleCtrl }: TerminalKeyBarProps) { + const renderKey = (key: SpecialKey) => ( + + ) + + return ( +
+ {renderKey({ label: 'Esc', data: ESCAPE_KEY })} + {renderKey({ label: 'Tab', data: TAB_KEY })} + + {ARROW_KEYS.map(renderKey)} + {SYMBOL_KEYS.map(renderKey)} +
+ ) +} diff --git a/frontend/src/components/terminal/TerminalPanel.test.tsx b/frontend/src/components/terminal/TerminalPanel.test.tsx new file mode 100644 index 00000000..9e7e5f87 --- /dev/null +++ b/frontend/src/components/terminal/TerminalPanel.test.tsx @@ -0,0 +1,192 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { MemoryRouter } from 'react-router-dom' +import type { TerminalInfo } from '@opencode-manager/shared/types' +import { useCreateTerminal, useRemoveTerminal, useTerminals } from '@/api/terminals' +import { useMobile } from '@/hooks/useMobile' +import { TerminalPanel } from './TerminalPanel' + +vi.mock('@/api/terminals', () => ({ + useTerminals: vi.fn(), + useCreateTerminal: vi.fn(), + useRemoveTerminal: vi.fn(), +})) + +vi.mock('@/hooks/useMobile', async () => { + const actual = await vi.importActual('@/hooks/useMobile') + return { ...actual, useMobile: vi.fn(() => false) } +}) + +vi.mock('./TerminalView', async () => { + const React = await import('react') + return { + TerminalView: React.forwardRef(function MockTerminalView( + props: { ptyID: string; active: boolean }, + ref: React.Ref, + ) { + React.useImperativeHandle(ref, () => ({ send: vi.fn() })) + return React.createElement('div', { + 'data-testid': 'terminal-view', + 'data-pty-id': props.ptyID, + 'data-active': String(props.active), + }) + }), + } +}) + +const runningTerminal: TerminalInfo = { + id: 't1', + title: 'Terminal', + kind: 'shell', + cwd: '/repo', + status: 'running', +} + +const exitedTerminal: TerminalInfo = { + id: 't2', + title: 'Build', + kind: 'action', + actionId: 'build', + cwd: '/repo', + status: 'exited', + exitCode: 0, +} + +const createMutate = vi.fn() +const removeMutate = vi.fn() +const refetch = vi.fn() + +function mockTerminalHooks( + terminals: TerminalInfo[] | undefined, + options: { isLoading?: boolean; isSuccess?: boolean } = {}, +) { + vi.mocked(useTerminals).mockReturnValue({ + data: terminals, + isLoading: options.isLoading ?? false, + isSuccess: options.isSuccess ?? terminals !== undefined, + refetch, + } as unknown as ReturnType) + vi.mocked(useCreateTerminal).mockReturnValue({ + mutate: createMutate, + isPending: false, + } as unknown as ReturnType) + vi.mocked(useRemoveTerminal).mockReturnValue({ + mutate: removeMutate, + isPending: false, + } as unknown as ReturnType) +} + +function renderPanel(initialEntry = '/repos/1?dialog=terminal', onClose = vi.fn()) { + return render( + + + , + ) +} + +describe('TerminalPanel', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(useMobile).mockReturnValue(false) + mockTerminalHooks([]) + }) + + it('auto-creates a terminal when the directory has none', () => { + mockTerminalHooks([]) + renderPanel() + + expect(createMutate).toHaveBeenCalledTimes(1) + expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object)) + }) + + it('does not auto-create while the list request is unresolved or failed', () => { + mockTerminalHooks(undefined, { isSuccess: false }) + renderPanel() + + expect(createMutate).not.toHaveBeenCalled() + }) + + it('auto-creates once the list resolves successfully empty', () => { + mockTerminalHooks(undefined, { isSuccess: false }) + const { rerender } = renderPanel() + expect(createMutate).not.toHaveBeenCalled() + + mockTerminalHooks([], { isSuccess: true }) + rerender( + + + , + ) + + expect(createMutate).toHaveBeenCalledTimes(1) + expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object)) + }) + + it('exposes an accessible name for the mobile panel close control', () => { + mockTerminalHooks([runningTerminal]) + vi.mocked(useMobile).mockReturnValue(true) + const onClose = vi.fn() + renderPanel('/repos/1?dialog=terminal', onClose) + + fireEvent.click(screen.getByRole('button', { name: 'Close terminal panel' })) + + expect(onClose).toHaveBeenCalledTimes(1) + }) + + it('activates the terminal referenced by the terminal URL param', () => { + mockTerminalHooks([runningTerminal, exitedTerminal]) + renderPanel('/repos/1?dialog=terminal&terminal=t2') + + const views = screen.getAllByTestId('terminal-view') + const active = views.find((view) => view.getAttribute('data-pty-id') === 't2') + const inactive = views.find((view) => view.getAttribute('data-pty-id') === 't1') + + expect(active).toHaveAttribute('data-active', 'true') + expect(inactive).toHaveAttribute('data-active', 'false') + }) + + it('shows an exited badge with the exit code', () => { + mockTerminalHooks([exitedTerminal]) + renderPanel() + + expect(screen.getByText('exited (0)')).toBeInTheDocument() + }) + + it('asks for confirmation before closing a running terminal', () => { + mockTerminalHooks([runningTerminal]) + renderPanel() + + fireEvent.click(screen.getByLabelText('Close Terminal')) + + expect(screen.getByText('Stop the running process?')).toBeInTheDocument() + expect(removeMutate).not.toHaveBeenCalled() + + fireEvent.click(screen.getByRole('button', { name: 'Stop' })) + + expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't1', directory: '/repo' }, expect.any(Object)) + }) + + it('removes an exited terminal without confirmation', () => { + mockTerminalHooks([exitedTerminal]) + renderPanel() + + fireEvent.click(screen.getByLabelText('Close Build')) + + expect(screen.queryByText('Stop the running process?')).not.toBeInTheDocument() + expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't2', directory: '/repo' }, expect.any(Object)) + }) + + it('renders the key bar only on mobile', () => { + mockTerminalHooks([runningTerminal]) + + vi.mocked(useMobile).mockReturnValue(false) + renderPanel() + expect(screen.queryByTestId('terminal-key-bar')).not.toBeInTheDocument() + + cleanup() + + vi.mocked(useMobile).mockReturnValue(true) + renderPanel() + expect(screen.getByTestId('terminal-key-bar')).toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/terminal/TerminalPanel.tsx b/frontend/src/components/terminal/TerminalPanel.tsx new file mode 100644 index 00000000..bbafc1bd --- /dev/null +++ b/frontend/src/components/terminal/TerminalPanel.tsx @@ -0,0 +1,220 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import type { TerminalInfo } from '@opencode-manager/shared/types' +import { Plus, SquareTerminal, X } from 'lucide-react' +import { useCreateTerminal, useRemoveTerminal, useTerminals } from '@/api/terminals' +import { Button } from '@/components/ui/button' +import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog' +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { useMobile } from '@/hooks/useMobile' +import { useUrlParams } from '@/hooks/useUrlParams' +import { cn } from '@/lib/utils' +import { TerminalKeyBar } from './TerminalKeyBar' +import { TerminalView, type TerminalViewHandle } from './TerminalView' + +interface TerminalPanelProps { + repoId: number + directory: string | undefined + isOpen: boolean + onClose: () => void + onOpenLink?: (uri: string) => void +} + +export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }: TerminalPanelProps) { + const isMobile = useMobile() + const { searchParams, updateParams } = useUrlParams() + const { data, isLoading, isSuccess, refetch } = useTerminals(repoId, directory, { + enabled: isOpen && !!directory, + refetchInterval: isOpen ? 5000 : false, + }) + const { mutate: createTerminal, isPending: isCreating } = useCreateTerminal(repoId) + const { mutate: removeTerminal, isPending: isRemoving } = useRemoveTerminal(repoId) + + const [ctrlArmed, setCtrlArmed] = useState(false) + const [pendingClose, setPendingClose] = useState(null) + const viewHandlesRef = useRef(new Map()) + const autoCreatedDirectoryRef = useRef(null) + + const terminals = useMemo(() => data ?? [], [data]) + + const selectTerminal = useCallback((id: string) => { + updateParams((params) => { + params.set('terminal', id) + }, 'replace') + }, [updateParams]) + + const requestedTerminalId = searchParams.get('terminal') + const activeTerminalId = requestedTerminalId && terminals.some((terminal) => terminal.id === requestedTerminalId) + ? requestedTerminalId + : terminals[0]?.id + + useEffect(() => { + if (!isOpen || !directory) { + autoCreatedDirectoryRef.current = null + return + } + if (!isSuccess || terminals.length > 0) return + if (autoCreatedDirectoryRef.current === directory) return + autoCreatedDirectoryRef.current = directory + createTerminal( + { directory }, + { onSuccess: (terminal) => selectTerminal(terminal.id) }, + ) + }, [isOpen, directory, isSuccess, terminals.length, createTerminal, selectTerminal]) + + const handleCreate = useCallback(() => { + createTerminal( + { directory }, + { onSuccess: (terminal) => selectTerminal(terminal.id) }, + ) + }, [createTerminal, directory, selectTerminal]) + + const performRemove = useCallback((terminal: TerminalInfo) => { + removeTerminal( + { ptyID: terminal.id, directory }, + { + onSuccess: () => { + updateParams((params) => { + if (params.get('terminal') === terminal.id) params.delete('terminal') + }, 'replace') + }, + }, + ) + }, [removeTerminal, directory, updateParams]) + + const handleCloseTab = useCallback((terminal: TerminalInfo) => { + if (terminal.status === 'running') { + setPendingClose(terminal) + return + } + performRemove(terminal) + }, [performRemove]) + + const handleKeySend = useCallback((input: string) => { + if (!activeTerminalId) return + viewHandlesRef.current.get(activeTerminalId)?.send(input) + }, [activeTerminalId]) + + const handleToggleCtrl = useCallback(() => setCtrlArmed((armed) => !armed), []) + const handleCtrlConsumed = useCallback(() => setCtrlArmed(false), []) + + return ( + { if (!open) onClose() }}> + + + + + Terminal + + {isMobile && ( + + )} + + +
+ {terminals.map((terminal) => ( +
+ + +
+ ))} + +
+ +
+ {terminals.length === 0 ? ( +
+ {isLoading || isCreating ? 'Starting terminal...' : 'No terminals'} +
+ ) : ( + terminals.map((terminal) => ( + { + if (handle) viewHandlesRef.current.set(terminal.id, handle) + else viewHandlesRef.current.delete(terminal.id) + }} + repoId={repoId} + directory={directory} + ptyID={terminal.id} + active={terminal.id === activeTerminalId} + ctrlArmed={ctrlArmed} + onCtrlConsumed={handleCtrlConsumed} + onOpenLink={onOpenLink} + onExited={() => { void refetch() }} + /> + )) + )} +
+ + {isMobile && terminals.length > 0 && ( + + )} + + { if (!open) setPendingClose(null) }} + onConfirm={() => { + if (pendingClose) performRemove(pendingClose) + setPendingClose(null) + }} + onCancel={() => setPendingClose(null)} + title="Close Terminal" + description="Stop the running process?" + confirmLabel="Stop" + pendingLabel="Stopping..." + isPending={isRemoving} + /> +
+
+ ) +} diff --git a/frontend/src/components/terminal/TerminalView.test.tsx b/frontend/src/components/terminal/TerminalView.test.tsx new file mode 100644 index 00000000..43e48e91 --- /dev/null +++ b/frontend/src/components/terminal/TerminalView.test.tsx @@ -0,0 +1,133 @@ +import { createRef, type ComponentProps } from 'react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { act, render } from '@testing-library/react' +import { TerminalView, type TerminalViewHandle } from './TerminalView' + +const xterm = vi.hoisted(() => { + const onDataHandlers: Array<(data: string) => void> = [] + return { + onDataHandlers, + write: vi.fn(), + focus: vi.fn(), + dispose: vi.fn(), + } +}) + +const socket = vi.hoisted(() => ({ send: vi.fn() })) + +vi.mock('@xterm/xterm', () => ({ + Terminal: vi.fn().mockImplementation(() => ({ + loadAddon: vi.fn(), + open: vi.fn(), + write: xterm.write, + focus: xterm.focus, + dispose: xterm.dispose, + onData: (handler: (data: string) => void) => { + xterm.onDataHandlers.push(handler) + return { dispose: vi.fn() } + }, + options: {}, + cols: 80, + rows: 24, + })), +})) + +vi.mock('@xterm/addon-fit', () => ({ + FitAddon: vi.fn().mockImplementation(() => ({ fit: vi.fn() })), +})) + +vi.mock('@xterm/addon-web-links', () => ({ + WebLinksAddon: vi.fn().mockImplementation(() => ({})), +})) + +vi.mock('@/api/terminals', () => ({ + resizeTerminal: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock('@/lib/terminal-theme', () => ({ + resolveTerminalTheme: vi.fn(() => ({})), +})) + +vi.mock('@/hooks/useTerminalSocket', () => ({ + useTerminalSocket: () => ({ send: socket.send, status: 'open' }), +})) + +function renderView(overrides: Partial> = {}) { + const ref = createRef() + const onCtrlConsumed = vi.fn() + const element = ( + + ) + const view = render(element) + return { ref, onCtrlConsumed, view } +} + +describe('TerminalView input handling', () => { + beforeEach(() => { + vi.clearAllMocks() + xterm.onDataHandlers.length = 0 + }) + + it('applies the ctrl modifier and consumes it for imperative key-bar sends', () => { + const { ref, onCtrlConsumed } = renderView({ ctrlArmed: true }) + + act(() => { + ref.current?.send('c') + }) + + expect(socket.send).toHaveBeenCalledWith('\x03') + expect(onCtrlConsumed).toHaveBeenCalledTimes(1) + }) + + it('applies the ctrl modifier to keyboard input while armed', () => { + const { onCtrlConsumed } = renderView({ ctrlArmed: true }) + + act(() => { + xterm.onDataHandlers[0]('c') + }) + + expect(socket.send).toHaveBeenCalledWith('\x03') + expect(onCtrlConsumed).toHaveBeenCalledTimes(1) + }) + + it('consumes ctrl exactly once so subsequent keyboard input is unmodified', () => { + const ref = createRef() + const onCtrlConsumed = vi.fn() + const props: ComponentProps = { + repoId: 1, + directory: '/repo', + ptyID: 't1', + active: true, + ctrlArmed: true, + onCtrlConsumed, + onExited: vi.fn(), + } + + const { rerender } = render() + + act(() => { + ref.current?.send('c') + }) + expect(socket.send).toHaveBeenLastCalledWith('\x03') + expect(onCtrlConsumed).toHaveBeenCalledTimes(1) + + rerender() + + act(() => { + xterm.onDataHandlers[xterm.onDataHandlers.length - 1]('c') + }) + + expect(socket.send).toHaveBeenLastCalledWith('c') + expect(onCtrlConsumed).toHaveBeenCalledTimes(1) + }) +}) diff --git a/frontend/src/components/terminal/TerminalView.tsx b/frontend/src/components/terminal/TerminalView.tsx index 62892053..6880835a 100644 --- a/frontend/src/components/terminal/TerminalView.tsx +++ b/frontend/src/components/terminal/TerminalView.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef } from 'react' +import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from 'react' import { Terminal } from '@xterm/xterm' import { FitAddon } from '@xterm/addon-fit' import { WebLinksAddon } from '@xterm/addon-web-links' @@ -18,6 +18,10 @@ function defaultOpenLink(uri: string) { window.open(uri, '_blank', 'noopener,noreferrer') } +export interface TerminalViewHandle { + send: (data: string) => void +} + export interface TerminalViewProps { repoId: number directory: string | undefined @@ -29,7 +33,7 @@ export interface TerminalViewProps { onExited: () => void } -export function TerminalView({ +export const TerminalView = forwardRef(function TerminalView({ repoId, directory, ptyID, @@ -38,7 +42,7 @@ export function TerminalView({ onCtrlConsumed, onOpenLink, onExited, -}: TerminalViewProps) { +}, ref) { const containerRef = useRef(null) const terminalRef = useRef(null) const fitAddonRef = useRef(null) @@ -60,6 +64,15 @@ export function TerminalView({ terminalRef.current?.write(text) }, []) + const handleInput = useCallback((data: string) => { + if (ctrlArmedRef.current) { + sendRef.current(applyCtrlModifier(data)) + onCtrlConsumedRef.current() + return + } + sendRef.current(data) + }, []) + const handleExit = useCallback(() => { terminalRef.current?.write('\r\n[process exited]\r\n') onExitedRef.current() @@ -75,6 +88,8 @@ export function TerminalView({ }) sendRef.current = send + useImperativeHandle(ref, () => ({ send: handleInput }), [handleInput]) + useEffect(() => { const container = containerRef.current if (!container) return @@ -100,12 +115,7 @@ export function TerminalView({ fitAddonRef.current = fitAddon const dataDisposable = terminal.onData((data) => { - if (ctrlArmedRef.current) { - sendRef.current(applyCtrlModifier(data)) - onCtrlConsumedRef.current() - return - } - sendRef.current(data) + handleInput(data) }) return () => { @@ -114,7 +124,7 @@ export function TerminalView({ terminalRef.current = null fitAddonRef.current = null } - }, []) + }, [handleInput]) useEffect(() => { const terminal = terminalRef.current @@ -187,4 +197,6 @@ export function TerminalView({ data-terminal-id={ptyID} /> ) -} +}) + +TerminalView.displayName = 'TerminalView' diff --git a/frontend/src/pages/AssistantRedirect.tsx b/frontend/src/pages/AssistantRedirect.tsx index d4f05bfe..bcc29d9b 100644 --- a/frontend/src/pages/AssistantRedirect.tsx +++ b/frontend/src/pages/AssistantRedirect.tsx @@ -12,6 +12,7 @@ import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet" import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog" import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog" import { SourceControlPanel } from "@/components/source-control" +import { TerminalPanel } from "@/components/terminal/TerminalPanel" import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog" import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup" import { Plus } from "lucide-react" @@ -23,6 +24,7 @@ export function AssistantRedirect() { const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp') const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills') const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl') + const [terminalOpen, setTerminalOpen] = useDialogParam('terminal') const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions') const { data: repo, isLoading: repoLoading, error: repoError } = useQuery({ @@ -92,6 +94,7 @@ export function AssistantRedirect() { /> )} setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} repoName="Assistant" /> + setTerminalOpen(false)} /> )} diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx index 9cd34326..b517f5bb 100644 --- a/frontend/src/pages/RepoDetail.tsx +++ b/frontend/src/pages/RepoDetail.tsx @@ -8,6 +8,7 @@ import { Header } from "@/components/ui/header"; import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog"; import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"; import { SourceControlPanel } from "@/components/source-control"; +import { TerminalPanel } from "@/components/terminal/TerminalPanel"; import { useCreateSession } from "@/hooks/useOpenCode"; import { useRepoActivity } from "@/hooks/useRepoActivity"; import { useCreateRepoWorkspace, useDeleteRepoWorkspaces, useRepoSiblings } from "@/hooks/useRepoSiblings"; @@ -33,6 +34,7 @@ export function RepoDetail() { const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp'); const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills'); const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl'); + const [terminalOpen, setTerminalOpen] = useDialogParam('terminal'); const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions'); const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false); const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false); @@ -291,6 +293,13 @@ export function RepoDetail() { repoName={repoName} /> + setTerminalOpen(false)} + /> + (); const [showScrollButton, setShowScrollButton] = useState(false); @@ -861,6 +863,13 @@ export function SessionDetail() { repoName={workspaceDisplayName} /> + setTerminalOpen(false)} + /> + Date: Sat, 3 Oct 2026 01:47:04 -0400 Subject: [PATCH 06/12] section 6: Phase 6: Project configuration schemas and personal action storage --- backend/src/routes/repo-git.ts | 8 +- backend/src/routes/repo-project-config.ts | 133 ++++++++++++ backend/src/routes/repos.ts | 10 + backend/src/services/git/GitService.ts | 14 ++ backend/src/services/project-config.ts | 100 +++++++++ .../test/routes/repo-project-config.test.ts | 175 ++++++++++++++++ backend/test/services/project-config.test.ts | 195 ++++++++++++++++++ shared/src/schemas/index.ts | 1 + shared/src/schemas/project-config.ts | 71 +++++++ shared/src/types/index.ts | 11 + 10 files changed, 712 insertions(+), 6 deletions(-) create mode 100644 backend/src/routes/repo-project-config.ts create mode 100644 backend/src/services/project-config.ts create mode 100644 backend/test/routes/repo-project-config.test.ts create mode 100644 backend/test/services/project-config.test.ts create mode 100644 shared/src/schemas/project-config.ts diff --git a/backend/src/routes/repo-git.ts b/backend/src/routes/repo-git.ts index b85be5ab..37ff8ab7 100644 --- a/backend/src/routes/repo-git.ts +++ b/backend/src/routes/repo-git.ts @@ -4,17 +4,13 @@ import type { ContentfulStatusCode } from 'hono/utils/http-status' import { getRepoById } from '../db/queries' import { logger } from '../utils/logger' import { parseGitError } from '../utils/git-errors' -import { GitService } from '../services/git/GitService' +import { createGitService } from '../services/git/GitService' import type { GitAuthService } from '../services/git-auth' -import { SettingsService } from '../services/settings' -import { CredentialProvider } from '../services/credential-provider' import type { GitStatusResponse } from '../types/git' export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthService) { const app = new Hono() - const settingsService = new SettingsService(database) - const credentialProvider = new CredentialProvider(database) - const git = new GitService(gitAuthService, settingsService, credentialProvider) + const git = createGitService(database, gitAuthService) app.get('/:id/git/status', async (c) => { try { diff --git a/backend/src/routes/repo-project-config.ts b/backend/src/routes/repo-project-config.ts new file mode 100644 index 00000000..58ba8158 --- /dev/null +++ b/backend/src/routes/repo-project-config.ts @@ -0,0 +1,133 @@ +import { Hono } from 'hono' +import type { Context } from 'hono' +import type { ContentfulStatusCode } from 'hono/utils/http-status' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema } from '@opencode-manager/shared/schemas' +import * as repoService from '../services/repo' +import { resolveRepoWorkingDirectory } from '../services/repo' +import { getRepoById } from '../db/queries' +import type { GitAuthService } from '../services/git-auth' +import type { OpenCodeClient } from '../services/opencode/client' +import type { TerminalService } from '../services/terminal' +import { ProjectConfigError, type ProjectConfigService } from '../services/project-config' +import { logger } from '../utils/logger' +import { getErrorMessage } from '../utils/error-utils' + +export interface RepoProjectConfigDeps { + database: Database + gitAuthService: GitAuthService + openCodeClient: OpenCodeClient + projectConfigService: ProjectConfigService + terminalService: TerminalService +} + +function handleProjectConfigError(c: Context, error: unknown): Response { + if (error instanceof ProjectConfigError) { + return c.json( + { error: error.message, code: error.code, details: error.details }, + error.status as ContentfulStatusCode, + ) + } + logger.error('Project config request failed:', error) + return c.json({ error: getErrorMessage(error) }, 500) +} + +export function createRepoProjectConfigRoutes( + database: Database, + gitAuthService: GitAuthService, + openCodeClient: OpenCodeClient, + projectConfigService: ProjectConfigService, + terminalService: TerminalService, +) { + const deps: RepoProjectConfigDeps = { + database, + gitAuthService, + openCodeClient, + projectConfigService, + terminalService, + } + const app = new Hono() + + async function resolveRepoDirectory( + c: Context, + repoIdParam: string, + directory: string | undefined, + ): Promise<{ repo: Repo; directory: string } | Response> { + const id = Number.parseInt(repoIdParam, 10) + if (Number.isNaN(id)) { + return c.json({ error: 'Invalid repo id' }, 400) + } + + const repo = getRepoById(deps.database, id) + if (!repo || repo.cloneStatus !== 'ready') { + return c.json({ error: 'Repo not found' }, 404) + } + + const resolved = await resolveRepoWorkingDirectory(repo, directory, () => + repoService.getSiblingRepos( + deps.database, + repo.id, + deps.gitAuthService.getGitEnvironment(), + deps.openCodeClient, + ), + ) + + if (!resolved) { + return c.json({ error: 'Directory is not part of this repository' }, 400) + } + + return { repo, directory: resolved } + } + + app.get('/:id/project-config', async (c) => { + const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + try { + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + + app.put('/:id/project-config/actions', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = UpdateProjectActionsRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + try { + const projectRepo = await deps.projectConfigService.resolveProjectRepo(resolved.repo) + deps.projectConfigService.setPersonalActions(projectRepo, parsed.data.actions) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + + app.put('/:id/project-config/worktree-setup', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = UpdateWorktreeSetupRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory')) + if (resolved instanceof Response) return resolved + + try { + const projectRepo = await deps.projectConfigService.resolveProjectRepo(resolved.repo) + deps.projectConfigService.setPersonalSetup(projectRepo, parsed.data.commands) + return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory)) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + + return app +} diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 921536f2..56136fa8 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -16,9 +16,12 @@ import { ASSISTANT_REPO_ID, isWorktreeSibling } from '@opencode-manager/shared/u import { isWorktreeError, openCodeLocation } from '@opencode-manager/shared/opencode' import { createRepoGitRoutes } from './repo-git' import { createRepoTerminalRoutes } from './repo-terminals' +import { createRepoProjectConfigRoutes } from './repo-project-config' import { createScheduleRoutes } from './schedules' import type { GitAuthService } from '../services/git-auth' import type { TerminalService } from '../services/terminal' +import { ProjectConfigService } from '../services/project-config' +import { createGitService } from '../services/git/GitService' import { ScheduleService } from '../services/schedules' import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode' import path from 'path' @@ -51,8 +54,15 @@ export function createRepoRoutes( ) { const app = new Hono() + const projectConfigService = new ProjectConfigService( + database, + createGitService(database, gitAuthService), + gitAuthService, + ) + app.route('/', createRepoGitRoutes(database, gitAuthService)) app.route('/', createRepoTerminalRoutes(database, gitAuthService, openCodeClient, terminalService)) + app.route('/', createRepoProjectConfigRoutes(database, gitAuthService, openCodeClient, projectConfigService, terminalService)) app.route('/:id/schedules', createScheduleRoutes(scheduleService)) app.post('/', async (c) => { diff --git a/backend/src/services/git/GitService.ts b/backend/src/services/git/GitService.ts index 7f49284e..7bd4d08e 100644 --- a/backend/src/services/git/GitService.ts +++ b/backend/src/services/git/GitService.ts @@ -12,6 +12,10 @@ import type { Database } from 'bun:sqlite' import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType, CommitDetails, CommitFile } from '../../types/git' import path from 'path' +export function createGitService(database: Database, gitAuthService: GitAuthService): GitService { + return new GitService(gitAuthService, new SettingsService(database), new CredentialProvider(database)) +} + export class GitService { constructor( private gitAuthService: GitAuthService, @@ -19,6 +23,16 @@ export class GitService { private credentialProvider: CredentialProvider ) {} + async getMainCheckoutPath(directory: string): Promise { + const env = this.gitAuthService.getGitEnvironment() + const output = await executeCommand(['git', '-C', directory, 'worktree', 'list', '--porcelain'], { env }) + const firstEntry = output.split('\n').find((line) => line.startsWith('worktree ')) + if (!firstEntry) { + throw new Error(`Unable to resolve the main checkout for ${directory}`) + } + return firstEntry.slice('worktree '.length).trim() + } + async getStatus(repoId: number, database: Database): Promise { try { const repo = getRepoById(database, repoId) diff --git a/backend/src/services/project-config.ts b/backend/src/services/project-config.ts new file mode 100644 index 00000000..0e35a05c --- /dev/null +++ b/backend/src/services/project-config.ts @@ -0,0 +1,100 @@ +import { z } from 'zod' +import type { Database } from 'bun:sqlite' +import type { Repo } from '@opencode-manager/shared/types' +import { + ProjectActionSchema, + WorktreeSetupCommandsSchema, + type ProjectAction, + type ProjectConfigResponse, +} from '@opencode-manager/shared/schemas' +import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries' +import type { GitService } from './git/GitService' +import type { GitAuthService } from './git-auth' + +const PROJECT_ACTIONS_KEY = 'projectActions' +const WORKTREE_SETUP_KEY = 'worktreeSetupCommands' +const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash' + +export class ProjectConfigError extends Error { + constructor( + public status: number, + message: string, + public code?: string, + public details?: unknown, + ) { + super(message) + this.name = 'ProjectConfigError' + } +} + +export class ProjectConfigService { + constructor( + private readonly database: Database, + private readonly git: GitService, + private readonly gitAuthService: GitAuthService, + ) {} + + async resolveProjectRepo(repo: Repo): Promise { + if (!repo.isWorktree) { + return repo + } + const mainCheckout = await this.git.getMainCheckoutPath(repo.fullPath) + return getRepoByDirectory(this.database, mainCheckout) ?? repo + } + + getPersonalActions(projectRepo: Repo): ProjectAction[] { + return this.readStoredJson(projectRepo.id, PROJECT_ACTIONS_KEY, z.array(ProjectActionSchema)) ?? [] + } + + setPersonalActions(projectRepo: Repo, actions: ProjectAction[]): void { + const ids = new Set() + for (const action of actions) { + if (ids.has(action.id)) { + throw new ProjectConfigError(400, 'Duplicate action id') + } + ids.add(action.id) + } + setRepoSetting(this.database, projectRepo.id, PROJECT_ACTIONS_KEY, JSON.stringify(actions)) + } + + getPersonalSetup(projectRepo: Repo): string[] { + return this.readStoredJson(projectRepo.id, WORKTREE_SETUP_KEY, WorktreeSetupCommandsSchema) ?? [] + } + + setPersonalSetup(projectRepo: Repo, commands: string[]): void { + setRepoSetting(this.database, projectRepo.id, WORKTREE_SETUP_KEY, JSON.stringify(commands)) + } + + async getConfig(repo: Repo, directory: string): Promise { + const projectRepo = await this.resolveProjectRepo(repo) + const actions = this.getPersonalActions(projectRepo).map((action) => ({ ...action, source: 'personal' as const })) + const worktreeSetup = this.getPersonalSetup(projectRepo).map((command) => ({ command, source: 'personal' as const })) + const hash: string | null = null + void directory + + return { + actions, + worktreeSetup, + repoFile: { + path: '.ocm/project.json', + exists: false, + trusted: hash !== null && hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY), + hash, + warnings: [], + }, + } + } + + private readStoredJson(repoId: number, key: string, schema: z.ZodType): T | null { + const raw = getRepoSetting(this.database, repoId, key) + if (!raw) { + return null + } + try { + const result = schema.safeParse(JSON.parse(raw)) + return result.success ? result.data : null + } catch { + return null + } + } +} diff --git a/backend/test/routes/repo-project-config.test.ts b/backend/test/routes/repo-project-config.test.ts new file mode 100644 index 00000000..df1f0599 --- /dev/null +++ b/backend/test/routes/repo-project-config.test.ts @@ -0,0 +1,175 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { Hono } from 'hono' +import { Database } from 'bun:sqlite' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import { createRepo } from '../../src/db/queries' +import { createRepoProjectConfigRoutes } from '../../src/routes/repo-project-config' +import { ProjectConfigService } from '../../src/services/project-config' +import { createGitService } from '../../src/services/git/GitService' +import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' +import type { GitAuthService } from '../../src/services/git-auth' +import type { TerminalService } from '../../src/services/terminal' + +vi.mock('../../src/services/repo', () => ({ + resolveRepoWorkingDirectory: vi.fn(), + getSiblingRepos: vi.fn(), +})) + +import { resolveRepoWorkingDirectory, getSiblingRepos } from '../../src/services/repo' + +const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService +const openCodeClient = createStubOpenCodeClient() +const terminalService = {} as unknown as TerminalService +const jsonHeaders = { 'Content-Type': 'application/json' } + +function createApp(db: Database): Hono { + const service = new ProjectConfigService(db, createGitService(db, gitAuthService), gitAuthService) + const app = new Hono() + app.route('/', createRepoProjectConfigRoutes(db, gitAuthService, openCodeClient, service, terminalService)) + return app +} + +function createTestDb(): Database { + const db = new Database(':memory:') + migrate(db, allMigrations) + return db +} + +function seedRepo(db: Database): void { + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) +} + +describe('Repo Project Config Routes', () => { + let db: Database + let app: Hono + + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(getSiblingRepos).mockResolvedValue([]) + vi.mocked(resolveRepoWorkingDirectory).mockImplementation(async (repo, directory) => { + if (directory === undefined || directory === repo.fullPath) return repo.fullPath + return null + }) + db = createTestDb() + app = createApp(db) + }) + + afterEach(() => { + db.close() + }) + + it('returns personal config for a ready repo', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config') + + expect(res.status).toBe(200) + const body = await res.json() as { actions: unknown[]; worktreeSetup: unknown[]; repoFile: unknown } + expect(body.actions).toEqual([]) + expect(body.worktreeSetup).toEqual([]) + expect(body.repoFile).toEqual({ + path: '.ocm/project.json', + exists: false, + trusted: false, + hash: null, + warnings: [], + }) + }) + + it('returns 404 for an unknown repo', async () => { + const res = await app.request('/999/project-config') + + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Repo not found' }) + }) + + it('returns 404 for a repo that is not ready', async () => { + createRepo(db, { localPath: 'repo-cloning', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true }) + + const res = await app.request('/1/project-config') + + expect(res.status).toBe(404) + }) + + it('returns 400 for a non-numeric repo id', async () => { + const res = await app.request('/abc/project-config') + + expect(res.status).toBe(400) + }) + + it('round-trips personal actions with the personal source', async () => { + seedRepo(db) + const action = { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false } + + const put = await app.request('/1/project-config/actions', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ actions: [action] }), + }) + expect(put.status).toBe(200) + expect((await put.json() as { actions: unknown[] }).actions).toEqual([{ ...action, source: 'personal' }]) + + const get = await app.request('/1/project-config') + expect(get.status).toBe(200) + expect((await get.json() as { actions: unknown[] }).actions).toEqual([{ ...action, source: 'personal' }]) + }) + + it('round-trips personal worktree setup commands', async () => { + seedRepo(db) + + const put = await app.request('/1/project-config/worktree-setup', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ commands: ['pnpm install', 'pnpm build'] }), + }) + expect(put.status).toBe(200) + expect((await put.json() as { worktreeSetup: unknown[] }).worktreeSetup).toEqual([ + { command: 'pnpm install', source: 'personal' }, + { command: 'pnpm build', source: 'personal' }, + ]) + + const get = await app.request('/1/project-config') + expect((await get.json() as { worktreeSetup: unknown[] }).worktreeSetup).toEqual([ + { command: 'pnpm install', source: 'personal' }, + { command: 'pnpm build', source: 'personal' }, + ]) + }) + + it('returns 400 for schema violations on actions', async () => { + seedRepo(db) + + const bodies = [ + '{}', + JSON.stringify({ actions: 'nope' }), + JSON.stringify({ actions: [{ id: 'has space', name: 'Serve', command: 'pnpm dev' }] }), + JSON.stringify({ actions: [{ id: 'serve', name: '', command: 'pnpm dev' }] }), + JSON.stringify({ actions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', icon: 'unknown' }] }), + ] + + for (const body of bodies) { + const res = await app.request('/1/project-config/actions', { method: 'PUT', headers: jsonHeaders, body }) + expect(res.status).toBe(400) + } + }) + + it('returns 400 for schema violations on worktree setup', async () => { + seedRepo(db) + + const bodies = ['{}', JSON.stringify({ commands: 'nope' }), JSON.stringify({ commands: [''] })] + + for (const body of bodies) { + const res = await app.request('/1/project-config/worktree-setup', { method: 'PUT', headers: jsonHeaders, body }) + expect(res.status).toBe(400) + } + }) + + it('returns 400 for a foreign directory', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config?directory=/tmp/other') + + expect(res.status).toBe(400) + expect(await res.json()).toEqual({ error: 'Directory is not part of this repository' }) + }) +}) diff --git a/backend/test/services/project-config.test.ts b/backend/test/services/project-config.test.ts new file mode 100644 index 00000000..c21f84e9 --- /dev/null +++ b/backend/test/services/project-config.test.ts @@ -0,0 +1,195 @@ +import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll } from 'vitest' +import { Database } from 'bun:sqlite' +import { execSync } from 'node:child_process' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import { createRepo, setRepoSetting } from '../../src/db/queries' +import { createGitService } from '../../src/services/git/GitService' +import { ProjectConfigService, ProjectConfigError } from '../../src/services/project-config' +import type { GitAuthService } from '../../src/services/git-auth' +import type { ProjectAction } from '@opencode-manager/shared/schemas' +import type { Repo } from '@opencode-manager/shared/types' + +const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService + +function createService(db: Database): ProjectConfigService { + return new ProjectConfigService(db, createGitService(db, gitAuthService), gitAuthService) +} + +function createAction(overrides: Partial = {}): ProjectAction { + return { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false, ...overrides } +} + +describe('ProjectConfigService personal settings', () => { + let db: Database + let service: ProjectConfigService + let repo: Repo + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + repo = createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + }) + + afterEach(() => { + db.close() + }) + + it('round-trips personal actions', () => { + const actions = [createAction(), createAction({ id: 'test', name: 'Test', command: 'pnpm test' })] + + service.setPersonalActions(repo, actions) + + expect(service.getPersonalActions(repo)).toEqual(actions) + }) + + it('returns personal actions through getConfig with the personal source', async () => { + service.setPersonalActions(repo, [createAction()]) + + const config = await service.getConfig(repo, repo.fullPath) + + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + expect(config.repoFile).toEqual({ + path: '.ocm/project.json', + exists: false, + trusted: false, + hash: null, + warnings: [], + }) + }) + + it('round-trips personal setup commands through getConfig', async () => { + service.setPersonalSetup(repo, ['pnpm install', 'pnpm build']) + + expect(service.getPersonalSetup(repo)).toEqual(['pnpm install', 'pnpm build']) + + const config = await service.getConfig(repo, repo.fullPath) + expect(config.worktreeSetup).toEqual([ + { command: 'pnpm install', source: 'personal' }, + { command: 'pnpm build', source: 'personal' }, + ]) + }) + + it('rejects duplicate action ids', () => { + let caught: unknown + try { + service.setPersonalActions(repo, [createAction(), createAction({ name: 'Other' })]) + } catch (error: unknown) { + caught = error + } + + expect(caught).toBeInstanceOf(ProjectConfigError) + expect((caught as ProjectConfigError).status).toBe(400) + expect((caught as ProjectConfigError).message).toBe('Duplicate action id') + }) + + it('reads corrupt stored action JSON as an empty list', () => { + setRepoSetting(db, repo.id, 'projectActions', '{not json') + + expect(service.getPersonalActions(repo)).toEqual([]) + }) + + it('reads wrongly shaped stored action JSON as an empty list', () => { + setRepoSetting(db, repo.id, 'projectActions', JSON.stringify({ id: 'serve' })) + + expect(service.getPersonalActions(repo)).toEqual([]) + }) + + it('reads corrupt stored setup JSON as an empty list', () => { + setRepoSetting(db, repo.id, 'worktreeSetupCommands', 'not-json') + + expect(service.getPersonalSetup(repo)).toEqual([]) + }) +}) + +describe('ProjectConfigService worktree resolution', () => { + let db: Database + let service: ProjectConfigService + let basePath: string + let worktreePath: string + let root: string + let baseRepo: Repo + let worktreeRepo: Repo + + beforeAll(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-project-config-'))) + basePath = path.join(root, 'base') + worktreePath = path.join(root, 'linked worktree') + + execSync(`git init "${basePath}"`) + execSync(`git -C "${basePath}" config user.email test@test.com`) + execSync(`git -C "${basePath}" config user.name Test`) + execSync(`git -C "${basePath}" commit --allow-empty -m "Initial commit"`) + execSync(`git -C "${basePath}" worktree add -b feature "${worktreePath}"`) + }) + + afterAll(() => { + fs.rmSync(root, { recursive: true, force: true }) + }) + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + baseRepo = createRepo(db, { + localPath: basePath, + sourcePath: basePath, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + worktreeRepo = createRepo(db, { + localPath: worktreePath, + sourcePath: worktreePath, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + isWorktree: true, + }) + }) + + afterEach(() => { + db.close() + }) + + it('resolves the main checkout from both the base and the linked worktree', async () => { + const git = createGitService(db, gitAuthService) + + expect(fs.realpathSync(await git.getMainCheckoutPath(basePath))).toBe(fs.realpathSync(basePath)) + expect(fs.realpathSync(await git.getMainCheckoutPath(worktreePath))).toBe(fs.realpathSync(basePath)) + }) + + it('resolves a linked worktree repo to the main checkout row', async () => { + const resolved = await service.resolveProjectRepo(worktreeRepo) + + expect(resolved.id).toBe(baseRepo.id) + }) + + it('keeps a non-worktree repo unchanged', async () => { + const resolved = await service.resolveProjectRepo(baseRepo) + + expect(resolved.id).toBe(baseRepo.id) + }) + + it('returns personal actions saved on the base repo when resolving from the worktree', async () => { + service.setPersonalActions(baseRepo, [createAction()]) + + const config = await service.getConfig(worktreeRepo, worktreePath) + + expect(config.actions).toEqual([{ ...createAction(), source: 'personal' }]) + }) + + it('returns personal setup saved on the base repo when resolving from the worktree', async () => { + service.setPersonalSetup(baseRepo, ['pnpm install']) + + const config = await service.getConfig(worktreeRepo, worktreePath) + + expect(config.worktreeSetup).toEqual([{ command: 'pnpm install', source: 'personal' }]) + }) +}) diff --git a/shared/src/schemas/index.ts b/shared/src/schemas/index.ts index f3511212..026ca535 100644 --- a/shared/src/schemas/index.ts +++ b/shared/src/schemas/index.ts @@ -13,3 +13,4 @@ export * from './internal-assistant' export * from './session-pins' export * from './logs' export * from './terminal' +export * from './project-config' diff --git a/shared/src/schemas/project-config.ts b/shared/src/schemas/project-config.ts new file mode 100644 index 00000000..3ad6763f --- /dev/null +++ b/shared/src/schemas/project-config.ts @@ -0,0 +1,71 @@ +import { z } from 'zod' + +export const ProjectActionIconSchema = z.enum([ + 'play', + 'build', + 'test', + 'lint', + 'terminal', + 'server', + 'bug', + 'rocket', +]) + +export const ProjectActionSchema = z.object({ + id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/), + name: z.string().trim().min(1).max(60), + command: z.string().trim().min(1).max(4000), + icon: ProjectActionIconSchema.optional(), + url: z.string().trim().max(500).optional(), + autoOpenUrl: z.boolean().default(false), +}) + +export const WorktreeSetupCommandsSchema = z.array(z.string().trim().min(1).max(4000)).max(20) + +export const ProjectItemSourceSchema = z.enum(['personal', 'repo']) + +export const RepoProjectFileSchema = z.looseObject({ + version: z.literal(1), + projectActions: z.array(ProjectActionSchema).optional(), + setupWorktree: WorktreeSetupCommandsSchema.optional(), +}) + +export const ProjectConfigResponseSchema = z.object({ + actions: z.array( + ProjectActionSchema.extend({ + source: ProjectItemSourceSchema, + resolvedUrl: z.string().optional(), + }), + ), + worktreeSetup: z.array( + z.object({ + command: z.string(), + source: ProjectItemSourceSchema, + }), + ), + repoFile: z.object({ + path: z.literal('.ocm/project.json'), + exists: z.boolean(), + trusted: z.boolean(), + hash: z.string().nullable(), + error: z.string().optional(), + warnings: z.array(z.string()), + }), +}) + +export const UpdateProjectActionsRequestSchema = z.object({ + actions: z.array(ProjectActionSchema).max(50), +}) + +export const UpdateWorktreeSetupRequestSchema = z.object({ + commands: WorktreeSetupCommandsSchema, +}) + +export type ProjectActionIcon = z.infer +export type ProjectAction = z.infer +export type WorktreeSetupCommands = z.infer +export type ProjectItemSource = z.infer +export type RepoProjectFile = z.infer +export type ProjectConfigResponse = z.infer +export type UpdateProjectActionsRequest = z.infer +export type UpdateWorktreeSetupRequest = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index b3a5055a..6b067f45 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -165,3 +165,14 @@ export type { CreateTerminalRequest, ResizeTerminalRequest, } from '../schemas/terminal' + +export type { + ProjectActionIcon, + ProjectAction, + WorktreeSetupCommands, + ProjectItemSource, + RepoProjectFile, + ProjectConfigResponse, + UpdateProjectActionsRequest, + UpdateWorktreeSetupRequest, +} from '../schemas/project-config' From 852797a897e9c6871c477321ec8816eecc729157 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:00:46 -0400 Subject: [PATCH 07/12] section 7: Phase 7: Committed repo file, trust and move between personal and repo --- backend/src/routes/repo-project-config.ts | 38 +- backend/src/services/project-config.ts | 319 +++++++++++++++- backend/test/mocks/bun-sqlite.ts | 25 +- .../test/routes/repo-project-config.test.ts | 112 ++++++ backend/test/services/project-config.test.ts | 354 +++++++++++++++++- shared/src/schemas/project-config.ts | 22 ++ shared/src/types/index.ts | 2 + 7 files changed, 859 insertions(+), 13 deletions(-) diff --git a/backend/src/routes/repo-project-config.ts b/backend/src/routes/repo-project-config.ts index 58ba8158..343e5b22 100644 --- a/backend/src/routes/repo-project-config.ts +++ b/backend/src/routes/repo-project-config.ts @@ -3,7 +3,7 @@ import type { Context } from 'hono' import type { ContentfulStatusCode } from 'hono/utils/http-status' import type { Database } from 'bun:sqlite' import type { Repo } from '@opencode-manager/shared/types' -import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema } from '@opencode-manager/shared/schemas' +import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema, TrustRepoConfigRequestSchema, MoveProjectItemRequestSchema } from '@opencode-manager/shared/schemas' import * as repoService from '../services/repo' import { resolveRepoWorkingDirectory } from '../services/repo' import { getRepoById } from '../db/queries' @@ -129,5 +129,41 @@ export function createRepoProjectConfigRoutes( } }) + 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 resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory) + 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 handleProjectConfigError(c, error) + } + }) + + 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 resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory) + 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 handleProjectConfigError(c, error) + } + }) + return app } diff --git a/backend/src/services/project-config.ts b/backend/src/services/project-config.ts index 0e35a05c..190324e2 100644 --- a/backend/src/services/project-config.ts +++ b/backend/src/services/project-config.ts @@ -1,19 +1,46 @@ +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, } from '@opencode-manager/shared/schemas' import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries' +import { getErrorMessage } from '../utils/error-utils' import type { GitService } from './git/GitService' import type { GitAuthService } from './git-auth' const PROJECT_ACTIONS_KEY = 'projectActions' const WORKTREE_SETUP_KEY = 'worktreeSetupCommands' const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash' +const REPO_FILE_RELATIVE_PATH = path.join('.ocm', 'project.json') + +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( @@ -67,24 +94,300 @@ export class ProjectConfigService { async getConfig(repo: Repo, directory: string): Promise { const projectRepo = await this.resolveProjectRepo(repo) - const actions = this.getPersonalActions(projectRepo).map((action) => ({ ...action, source: 'personal' as const })) - const worktreeSetup = this.getPersonalSetup(projectRepo).map((command) => ({ command, source: 'personal' as const })) - const hash: string | null = null - void directory + 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 = + repoFile.hash !== null && + repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY) return { actions, worktreeSetup, repoFile: { path: '.ocm/project.json', - exists: false, - trusted: hash !== null && hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY), - hash, - warnings: [], + exists: repoFile.exists, + trusted, + hash: repoFile.hash, + ...(repoFile.error ? { error: repoFile.error } : {}), + warnings, }, } } + readRepoFile(directory: string): RepoFileState { + const filePath = this.getRepoFilePath(directory) + if (!fs.existsSync(filePath)) { + return { exists: false, file: null, hash: null } + } + + try { + const parsed = RepoProjectFileSchema.safeParse(JSON.parse(fs.readFileSync(filePath, 'utf8'))) + if (!parsed.success) { + return { exists: true, file: null, hash: null, error: 'Invalid repository config' } + } + return { exists: true, file: parsed.data, hash: this.hashRepoFile(parsed.data) } + } catch (error: unknown) { + return { exists: true, file: null, hash: null, error: getErrorMessage(error) } + } + } + + hashRepoFile(file: RepoProjectFile): string { + const executable = { + actions: (file.projectActions ?? []).map(({ id, command, url }) => ({ id, command, url: url ?? null })), + setup: file.setupWorktree ?? [], + } + return createHash('sha256').update(JSON.stringify(executable)).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(409, 'Repository config changed', '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) + 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(409, 'Repository config is invalid') + } + + 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(404, 'Action not found') + } + const repoActions = file.projectActions ?? [] + if (repoActions.some((existing) => existing.id === action.id)) { + throw new ProjectConfigError(409, 'Action already exists in repository config') + } + const nextFile: RepoProjectFile = { ...file, projectActions: [...repoActions, action] } + this.assertRepoFileValid(nextFile) + return { + repoFile: nextFile, + personalActions: personal.filter((item) => item.id !== action.id), + trustHash: this.hashRepoFile(nextFile), + } + } + + const personal = this.getPersonalSetup(projectRepo) + const index = personal.indexOf(request.command) + if (index === -1) { + throw new ProjectConfigError(404, 'Setup command not found') + } + 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.hashRepoFile(nextFile) } + } + + private planMoveToPersonal(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit { + const file = state.file + if (!file) { + throw new ProjectConfigError(404, 'Item not found') + } + + if (request.kind === 'action') { + const repoActions = file.projectActions ?? [] + const action = repoActions.find((item) => item.id === request.id) + if (!action) { + throw new ProjectConfigError(404, 'Action not found') + } + 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.hashRepoFile(nextFile) } + : { repoFile: null, personalActions, trustHash: null } + } + + const repoSetup = file.setupWorktree ?? [] + const index = repoSetup.indexOf(request.command) + if (index === -1) { + throw new ProjectConfigError(404, 'Setup command not found') + } + 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.hashRepoFile(nextFile) } + : { repoFile: null, personalSetup, trustHash: null } + } + + 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( + 409, + 'Repository config limit exceeded', + 'PROJECT_CONFIG_LIMIT_EXCEEDED', + result.error.flatten(), + ) + } + } + + private assertPersonalSetupValid(commands: string[]): void { + const result = WorktreeSetupCommandsSchema.safeParse(commands) + if (!result.success) { + throw new ProjectConfigError( + 409, + 'Personal setup command limit exceeded', + '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 { + fs.mkdirSync(path.dirname(filePath), { recursive: true }) + const tmpPath = `${filePath}.tmp` + try { + fs.writeFileSync(tmpPath, `${JSON.stringify(file, null, 2)}\n`) + fs.renameSync(tmpPath, filePath) + } catch (error) { + fs.rmSync(tmpPath, { force: true }) + throw error + } + } + + 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) { 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/repo-project-config.test.ts b/backend/test/routes/repo-project-config.test.ts index df1f0599..38583a10 100644 --- a/backend/test/routes/repo-project-config.test.ts +++ b/backend/test/routes/repo-project-config.test.ts @@ -1,6 +1,9 @@ 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' @@ -172,4 +175,113 @@ describe('Repo Project Config Routes', () => { 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 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 }) + } + }) }) diff --git a/backend/test/services/project-config.test.ts b/backend/test/services/project-config.test.ts index c21f84e9..34f7f0d3 100644 --- a/backend/test/services/project-config.test.ts +++ b/backend/test/services/project-config.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll } from 'vitest' +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' @@ -193,3 +193,355 @@ describe('ProjectConfigService worktree resolution', () => { 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('keeps trust across a name-only edit and drops it on a command edit', 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(true) + + writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev --host' }] }) + expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false) + }) + + 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).toBeTruthy() + 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).toBeTruthy() + expect(config.actions).toEqual([]) + }) + + 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('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('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 renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { + throw new Error('disk full') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow('disk full') + renameSpy.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 renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { + throw new Error('disk full') + }) + + await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow( + 'disk full', + ) + renameSpy.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()]) + }) +}) diff --git a/shared/src/schemas/project-config.ts b/shared/src/schemas/project-config.ts index 3ad6763f..e0a774da 100644 --- a/shared/src/schemas/project-config.ts +++ b/shared/src/schemas/project-config.ts @@ -61,6 +61,26 @@ export const UpdateWorktreeSetupRequestSchema = z.object({ commands: WorktreeSetupCommandsSchema, }) +export const TrustRepoConfigRequestSchema = z.object({ + directory: z.string().optional(), + hash: z.string().regex(/^[a-f0-9]{64}$/), +}) + +export const MoveProjectItemRequestSchema = z.discriminatedUnion('kind', [ + z.object({ + kind: z.literal('action'), + id: z.string(), + to: ProjectItemSourceSchema, + directory: z.string().optional(), + }), + z.object({ + kind: z.literal('setup'), + command: z.string(), + to: ProjectItemSourceSchema, + directory: z.string().optional(), + }), +]) + export type ProjectActionIcon = z.infer export type ProjectAction = z.infer export type WorktreeSetupCommands = z.infer @@ -69,3 +89,5 @@ export type RepoProjectFile = z.infer export type ProjectConfigResponse = z.infer export type UpdateProjectActionsRequest = z.infer export type UpdateWorktreeSetupRequest = z.infer +export type TrustRepoConfigRequest = z.infer +export type MoveProjectItemRequest = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 6b067f45..0c61269b 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -175,4 +175,6 @@ export type { ProjectConfigResponse, UpdateProjectActionsRequest, UpdateWorktreeSetupRequest, + TrustRepoConfigRequest, + MoveProjectItemRequest, } from '../schemas/project-config' From d6aeafeae973829a390abc303e4259d8be52aa68 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:09:54 -0400 Subject: [PATCH 08/12] section 8: Phase 8: Run and stop project actions with URL templates --- backend/src/routes/repo-project-config.ts | 25 +- backend/src/services/project-config.ts | 97 ++++++- .../test/routes/repo-project-config.test.ts | 71 ++++- backend/test/services/project-config.test.ts | 266 +++++++++++++++++- shared/src/schemas/project-config.ts | 14 + shared/src/types/index.ts | 2 + 6 files changed, 470 insertions(+), 5 deletions(-) diff --git a/backend/src/routes/repo-project-config.ts b/backend/src/routes/repo-project-config.ts index 343e5b22..7a87dec3 100644 --- a/backend/src/routes/repo-project-config.ts +++ b/backend/src/routes/repo-project-config.ts @@ -3,7 +3,7 @@ import type { Context } from 'hono' import type { ContentfulStatusCode } from 'hono/utils/http-status' import type { Database } from 'bun:sqlite' import type { Repo } from '@opencode-manager/shared/types' -import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema, TrustRepoConfigRequestSchema, MoveProjectItemRequestSchema } from '@opencode-manager/shared/schemas' +import { UpdateProjectActionsRequestSchema, UpdateWorktreeSetupRequestSchema, TrustRepoConfigRequestSchema, MoveProjectItemRequestSchema, RunProjectActionRequestSchema } from '@opencode-manager/shared/schemas' import * as repoService from '../services/repo' import { resolveRepoWorkingDirectory } from '../services/repo' import { getRepoById } from '../db/queries' @@ -165,5 +165,28 @@ export function createRepoProjectConfigRoutes( } }) + app.post('/:id/project-config/actions/:actionId/run', async (c) => { + const body = await c.req.json().catch(() => ({})) + const parsed = RunProjectActionRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400) + } + + const resolved = await resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory) + if (resolved instanceof Response) return resolved + + try { + const response = await deps.projectConfigService.runAction( + resolved.repo, + resolved.directory, + c.req.param('actionId'), + deps.terminalService, + ) + return c.json(response) + } catch (error: unknown) { + return handleProjectConfigError(c, error) + } + }) + return app } diff --git a/backend/src/services/project-config.ts b/backend/src/services/project-config.ts index 190324e2..4404c54b 100644 --- a/backend/src/services/project-config.ts +++ b/backend/src/services/project-config.ts @@ -12,11 +12,15 @@ import { type ProjectAction, type ProjectConfigResponse, type RepoProjectFile, + type RunProjectActionResponse, } from '@opencode-manager/shared/schemas' import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries' +import { executeCommand } from '../utils/process' import { getErrorMessage } from '../utils/error-utils' +import { canonicalPathSync } from '../utils/fs-safe' import type { GitService } from './git/GitService' import type { GitAuthService } from './git-auth' +import type { TerminalService } from './terminal' const PROJECT_ACTIONS_KEY = 'projectActions' const WORKTREE_SETUP_KEY = 'worktreeSetupCommands' @@ -55,6 +59,8 @@ export class ProjectConfigError extends Error { } export class ProjectConfigService { + private readonly actionRunQueues = new Map>() + constructor( private readonly database: Database, private readonly git: GitService, @@ -124,8 +130,14 @@ export class ProjectConfigService { repoFile.hash !== null && repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY) + const resolvedActions = await Promise.all( + actions.map(async (action) => + action.url ? { ...action, resolvedUrl: await this.resolveActionUrl(action.url, directory) } : action, + ), + ) + return { - actions, + actions: resolvedActions, worktreeSetup, repoFile: { path: '.ocm/project.json', @@ -138,6 +150,89 @@ export class ProjectConfigService { } } + async resolveActionUrl(template: string, directory: string): Promise { + const withWorktree = template.replaceAll('{worktree}', path.basename(directory)) + if (!withWorktree.includes('{branch}')) { + return withWorktree + } + + try { + const branch = ( + await executeCommand(['git', '-C', directory, 'rev-parse', '--abbrev-ref', 'HEAD'], { + env: this.gitAuthService.getGitEnvironment(), + silent: true, + }) + ).trim() + return withWorktree.replaceAll('{branch}', branch) + } catch { + return template + } + } + + async runAction( + repo: Repo, + directory: string, + actionId: string, + terminalService: TerminalService, + ): Promise { + const config = await this.getConfig(repo, directory) + const action = config.actions.find((item) => item.id === actionId) + if (!action) { + throw new ProjectConfigError(404, 'Action not found') + } + + if (action.source === 'repo' && !config.repoFile.trusted) { + throw new ProjectConfigError(409, 'Repository commands are not trusted', 'REPO_CONFIG_UNTRUSTED', { + hash: config.repoFile.hash, + }) + } + + const key = this.actionRunKey(directory, actionId) + return this.enqueueActionRun(key, async () => { + const terminals = await terminalService.list(directory) + const running = terminals.find( + (terminal) => terminal.kind === 'action' && terminal.actionId === actionId && terminal.status === 'running', + ) + const terminal = + running ?? + (await terminalService.create(directory, { + kind: 'action', + actionId, + name: action.name, + command: '/bin/sh', + args: ['-c', action.command], + })) + + return { + terminal, + alreadyRunning: running !== undefined, + ...(action.resolvedUrl ? { resolvedUrl: action.resolvedUrl } : {}), + autoOpenUrl: action.autoOpenUrl, + } + }) + } + + private actionRunKey(directory: string, actionId: string): string { + const canonical = canonicalPathSync(path.resolve(directory)) + return `${canonical}\u0000${actionId}` + } + + private enqueueActionRun(key: string, operation: () => Promise): Promise { + const previous = this.actionRunQueues.get(key) ?? Promise.resolve() + const result = previous.then(operation, operation) + const tail = result.then( + () => undefined, + () => undefined, + ) + this.actionRunQueues.set(key, tail) + void tail.then(() => { + if (this.actionRunQueues.get(key) === tail) { + this.actionRunQueues.delete(key) + } + }) + return result + } + readRepoFile(directory: string): RepoFileState { const filePath = this.getRepoFilePath(directory) if (!fs.existsSync(filePath)) { diff --git a/backend/test/routes/repo-project-config.test.ts b/backend/test/routes/repo-project-config.test.ts index 38583a10..1f07bf08 100644 --- a/backend/test/routes/repo-project-config.test.ts +++ b/backend/test/routes/repo-project-config.test.ts @@ -11,8 +11,10 @@ import { createRepoProjectConfigRoutes } from '../../src/routes/repo-project-con import { ProjectConfigService } from '../../src/services/project-config' import { createGitService } from '../../src/services/git/GitService' import { createStubOpenCodeClient } from '../helpers/stub-opencode-client' +import { formatTerminalTitle } from '@opencode-manager/shared/utils' import type { GitAuthService } from '../../src/services/git-auth' -import type { TerminalService } from '../../src/services/terminal' +import type { CreateTerminalInput, TerminalService } from '../../src/services/terminal' +import type { TerminalInfo } from '@opencode-manager/shared/types' vi.mock('../../src/services/repo', () => ({ resolveRepoWorkingDirectory: vi.fn(), @@ -23,7 +25,18 @@ import { resolveRepoWorkingDirectory, getSiblingRepos } from '../../src/services const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService const openCodeClient = createStubOpenCodeClient() -const terminalService = {} as unknown as TerminalService +const terminalList = vi.fn(async (): Promise => []) +const terminalCreate = vi.fn( + async (directory: string, input: CreateTerminalInput): Promise => ({ + id: 'pty-1', + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + kind: input.kind, + ...(input.actionId ? { actionId: input.actionId } : {}), + cwd: directory, + status: 'running', + }), +) +const terminalService = { list: terminalList, create: terminalCreate } as unknown as TerminalService const jsonHeaders = { 'Content-Type': 'application/json' } function createApp(db: Database): Hono { @@ -284,4 +297,58 @@ describe('Repo Project Config Routes', () => { fs.rmSync(directory, { recursive: true, force: true }) } }) + + it('runs a personal action and returns the response shape', async () => { + seedRepo(db) + const action = { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false } + + await app.request('/1/project-config/actions', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ actions: [action] }), + }) + + const res = await app.request('/1/project-config/actions/serve/run', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({}), + }) + + expect(res.status).toBe(200) + const body = await res.json() as { + terminal: unknown + alreadyRunning: boolean + autoOpenUrl: boolean + resolvedUrl?: string + } + expect(body.alreadyRunning).toBe(false) + expect(body.autoOpenUrl).toBe(false) + expect(body.resolvedUrl).toBeUndefined() + expect(body.terminal).toMatchObject({ + id: 'pty-1', + title: 'ocm:action:serve:Serve', + kind: 'action', + actionId: 'serve', + status: 'running', + }) + expect(terminalCreate).toHaveBeenCalledWith(expect.any(String), { + kind: 'action', + actionId: 'serve', + name: 'Serve', + command: '/bin/sh', + args: ['-c', 'pnpm dev'], + }) + }) + + it('returns 404 when running an unknown action', async () => { + seedRepo(db) + + const res = await app.request('/1/project-config/actions/missing/run', { + method: 'POST', + headers: jsonHeaders, + body: JSON.stringify({}), + }) + + expect(res.status).toBe(404) + }) }) diff --git a/backend/test/services/project-config.test.ts b/backend/test/services/project-config.test.ts index 34f7f0d3..0f9e8ae4 100644 --- a/backend/test/services/project-config.test.ts +++ b/backend/test/services/project-config.test.ts @@ -10,8 +10,10 @@ import { createRepo, setRepoSetting } from '../../src/db/queries' import { createGitService } from '../../src/services/git/GitService' import { ProjectConfigService, ProjectConfigError } from '../../src/services/project-config' import type { GitAuthService } from '../../src/services/git-auth' +import type { CreateTerminalInput, TerminalService } from '../../src/services/terminal' +import { formatTerminalTitle } from '@opencode-manager/shared/utils' import type { ProjectAction } from '@opencode-manager/shared/schemas' -import type { Repo } from '@opencode-manager/shared/types' +import type { Repo, TerminalInfo } from '@opencode-manager/shared/types' const gitAuthService = { getGitEnvironment: () => ({}) } as unknown as GitAuthService @@ -23,6 +25,41 @@ function createAction(overrides: Partial = {}): ProjectAction { return { id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: false, ...overrides } } +function createDeferred() { + let resolve!: () => void + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} + +async function flushAsync(): Promise { + await new Promise((resolve) => setImmediate(resolve)) +} + +function createStatefulTerminalService(gate: { promise: Promise } | null) { + const terminals: TerminalInfo[] = [] + let created = 0 + const list = vi.fn(async (target: string) => terminals.filter((terminal) => terminal.cwd === target)) + const create = vi.fn(async (target: string, input: CreateTerminalInput): Promise => { + if (gate) { + await gate.promise + } + created += 1 + const terminal: TerminalInfo = { + id: `pty-${created}`, + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + kind: input.kind, + ...(input.actionId ? { actionId: input.actionId } : {}), + cwd: target, + status: 'running', + } + terminals.push(terminal) + return terminal + }) + return { service: { list, create } as unknown as TerminalService, list, create, terminals } +} + describe('ProjectConfigService personal settings', () => { let db: Database let service: ProjectConfigService @@ -545,3 +582,230 @@ describe('ProjectConfigService repository file', () => { expect(service.getPersonalActions(repo)).toEqual([createAction()]) }) }) + +describe('ProjectConfigService runAction', () => { + let db: Database + let service: ProjectConfigService + let repo: Repo + let directory: string + + function writeRepoFile(content: unknown): void { + const filePath = path.join(directory, '.ocm', 'project.json') + fs.mkdirSync(path.dirname(filePath), { recursive: true }) + fs.writeFileSync(filePath, JSON.stringify(content, null, 2)) + } + + function createFakeTerminalService(terminals: TerminalInfo[] = []) { + const list = vi.fn(async () => terminals) + const create = vi.fn( + async (target: string, input: CreateTerminalInput): Promise => ({ + id: 'pty-1', + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + kind: input.kind, + ...(input.actionId ? { actionId: input.actionId } : {}), + cwd: target, + status: 'running', + }), + ) + return { service: { list, create } as unknown as TerminalService, list, create } + } + + beforeEach(() => { + db = new Database(':memory:') + migrate(db, allMigrations) + service = createService(db) + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-run-action-')) + repo = createRepo(db, { + localPath: directory, + sourcePath: directory, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + isLocal: true, + }) + }) + + afterEach(() => { + db.close() + fs.rmSync(directory, { recursive: true, force: true }) + }) + + it('creates an action terminal with /bin/sh -c and the encoded action id', async () => { + service.setPersonalActions(repo, [createAction({ url: 'http://localhost:5173/{worktree}' })]) + const terminalService = createFakeTerminalService() + + const response = await service.runAction(repo, directory, 'serve', terminalService.service) + + expect(terminalService.create).toHaveBeenCalledWith(directory, { + kind: 'action', + actionId: 'serve', + name: 'Serve', + command: '/bin/sh', + args: ['-c', 'pnpm dev'], + }) + expect(response).toEqual({ + terminal: { + id: 'pty-1', + title: 'ocm:action:serve:Serve', + kind: 'action', + actionId: 'serve', + cwd: directory, + status: 'running', + }, + alreadyRunning: false, + resolvedUrl: `http://localhost:5173/${path.basename(directory)}`, + autoOpenUrl: false, + }) + }) + + it('returns an already running action terminal without creating another', async () => { + service.setPersonalActions(repo, [createAction()]) + const running: TerminalInfo = { + id: 'pty-existing', + title: 'Serve', + kind: 'action', + actionId: 'serve', + cwd: directory, + status: 'running', + } + const terminalService = createFakeTerminalService([running]) + + const response = await service.runAction(repo, directory, 'serve', terminalService.service) + + expect(terminalService.create).not.toHaveBeenCalled() + expect(response.alreadyRunning).toBe(true) + expect(response.terminal).toEqual(running) + }) + + it('returns 404 for an unknown action', async () => { + const terminalService = createFakeTerminalService() + + await expect(service.runAction(repo, directory, 'missing', terminalService.service)).rejects.toMatchObject({ + status: 404, + }) + expect(terminalService.create).not.toHaveBeenCalled() + }) + + it('rejects an untrusted repository action with the current hash', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }) + const terminalService = createFakeTerminalService() + + let caught: unknown + try { + await service.runAction(repo, directory, 'repo-serve', terminalService.service) + } catch (error: unknown) { + caught = error + } + + expect(caught).toBeInstanceOf(ProjectConfigError) + expect((caught as ProjectConfigError).status).toBe(409) + expect((caught as ProjectConfigError).code).toBe('REPO_CONFIG_UNTRUSTED') + expect((caught as ProjectConfigError).details).toMatchObject({ hash: expect.stringMatching(/^[a-f0-9]{64}$/) }) + expect(terminalService.create).not.toHaveBeenCalled() + }) + + it('runs a trusted repository action', async () => { + writeRepoFile({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }) + const first = await service.getConfig(repo, directory) + await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '') + const terminalService = createFakeTerminalService() + + const response = await service.runAction(repo, directory, 'repo-serve', terminalService.service) + + expect(response.alreadyRunning).toBe(false) + expect(terminalService.create).toHaveBeenCalledWith(directory, expect.objectContaining({ actionId: 'repo-serve' })) + }) + + it('resolves {worktree} and {branch} against a real git checkout', async () => { + const gitDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-run-branch-')) + try { + execSync(`git init "${gitDirectory}"`) + execSync(`git -C "${gitDirectory}" config user.email test@test.com`) + execSync(`git -C "${gitDirectory}" config user.name Test`) + execSync(`git -C "${gitDirectory}" commit --allow-empty -m "Initial commit"`) + execSync(`git -C "${gitDirectory}" checkout -b feature/auth`) + + const url = await service.resolveActionUrl('http://localhost:3000/{worktree}/{branch}', gitDirectory) + + expect(url).toBe(`http://localhost:3000/${path.basename(gitDirectory)}/feature/auth`) + } finally { + fs.rmSync(gitDirectory, { recursive: true, force: true }) + } + }) + + it('returns the template unchanged when the branch cannot be resolved', async () => { + const template = 'http://localhost:3000/{branch}' + + await expect(service.resolveActionUrl(template, directory)).resolves.toBe(template) + }) + + it('creates exactly one terminal when the same action runs concurrently in one directory', async () => { + service.setPersonalActions(repo, [createAction()]) + const gate = createDeferred() + const terminalService = createStatefulTerminalService(gate) + + const first = service.runAction(repo, directory, 'serve', terminalService.service) + const second = service.runAction(repo, directory, 'serve', terminalService.service) + await flushAsync() + gate.resolve() + + const [firstResult, secondResult] = await Promise.all([first, second]) + + expect(terminalService.create).toHaveBeenCalledTimes(1) + expect(firstResult.alreadyRunning).toBe(false) + expect(secondResult.alreadyRunning).toBe(true) + expect(secondResult.terminal.id).toBe(firstResult.terminal.id) + }) + + it('releases the run key after a failed create so a retry can start', async () => { + service.setPersonalActions(repo, [createAction()]) + const terminals: TerminalInfo[] = [] + let attempts = 0 + const list = vi.fn(async (target: string) => terminals.filter((terminal) => terminal.cwd === target)) + const create = vi.fn(async (target: string, input: CreateTerminalInput): Promise => { + attempts += 1 + if (attempts === 1) { + throw new Error('spawn failed') + } + const terminal: TerminalInfo = { + id: `pty-${attempts}`, + title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }), + kind: input.kind, + ...(input.actionId ? { actionId: input.actionId } : {}), + cwd: target, + status: 'running', + } + terminals.push(terminal) + return terminal + }) + const terminalService = { list, create } as unknown as TerminalService + + await expect(service.runAction(repo, directory, 'serve', terminalService)).rejects.toThrow('spawn failed') + + const response = await service.runAction(repo, directory, 'serve', terminalService) + + expect(response.alreadyRunning).toBe(false) + expect(response.terminal.id).toBe('pty-2') + expect(create).toHaveBeenCalledTimes(2) + }) + + it('does not serialize runs for different directories', async () => { + service.setPersonalActions(repo, [createAction()]) + const otherDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-run-action-other-')) + try { + const gate = createDeferred() + const terminalService = createStatefulTerminalService(gate) + + const first = service.runAction(repo, directory, 'serve', terminalService.service) + const second = service.runAction(repo, otherDirectory, 'serve', terminalService.service) + await flushAsync() + + expect(terminalService.create).toHaveBeenCalledTimes(2) + + gate.resolve() + await Promise.all([first, second]) + } finally { + fs.rmSync(otherDirectory, { recursive: true, force: true }) + } + }) +}) diff --git a/shared/src/schemas/project-config.ts b/shared/src/schemas/project-config.ts index e0a774da..cdc77db8 100644 --- a/shared/src/schemas/project-config.ts +++ b/shared/src/schemas/project-config.ts @@ -1,4 +1,5 @@ import { z } from 'zod' +import { TerminalInfoSchema } from './terminal' export const ProjectActionIconSchema = z.enum([ 'play', @@ -81,6 +82,17 @@ export const MoveProjectItemRequestSchema = z.discriminatedUnion('kind', [ }), ]) +export const RunProjectActionRequestSchema = z.object({ + directory: z.string().optional(), +}) + +export const RunProjectActionResponseSchema = z.object({ + terminal: TerminalInfoSchema, + alreadyRunning: z.boolean(), + resolvedUrl: z.string().optional(), + autoOpenUrl: z.boolean(), +}) + export type ProjectActionIcon = z.infer export type ProjectAction = z.infer export type WorktreeSetupCommands = z.infer @@ -91,3 +103,5 @@ export type UpdateProjectActionsRequest = z.infer export type TrustRepoConfigRequest = z.infer export type MoveProjectItemRequest = z.infer +export type RunProjectActionRequest = z.infer +export type RunProjectActionResponse = z.infer diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 0c61269b..ee384994 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -177,4 +177,6 @@ export type { UpdateWorktreeSetupRequest, TrustRepoConfigRequest, MoveProjectItemRequest, + RunProjectActionRequest, + RunProjectActionResponse, } from '../schemas/project-config' From 81a9f0c8ef70ed47393a761ac9cbcb07f7512ee2 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:32:44 -0400 Subject: [PATCH 09/12] section 9: Phase 9: Project actions settings dialog --- frontend/src/api/projectConfig.ts | 136 ++++ .../navigation/moreDrawerItems.test.ts | 16 +- .../components/navigation/moreDrawerItems.ts | 4 +- .../repo/RepoActionsDialog.test.tsx | 353 +++++++++++ .../src/components/repo/RepoActionsDialog.tsx | 581 ++++++++++++++++++ frontend/src/pages/RepoDetail.tsx | 9 + frontend/src/pages/SessionDetail.tsx | 9 + .../SessionDetail.assistant-loading.test.tsx | 1 + .../__tests__/SessionDetail.commands.test.tsx | 1 + .../SessionDetail.form-prompt.test.tsx | 1 + .../__tests__/SessionDetail.polling.test.tsx | 1 + .../SessionDetail.scroll-floating.test.tsx | 1 + 12 files changed, 1106 insertions(+), 7 deletions(-) create mode 100644 frontend/src/api/projectConfig.ts create mode 100644 frontend/src/components/repo/RepoActionsDialog.test.tsx create mode 100644 frontend/src/components/repo/RepoActionsDialog.tsx diff --git a/frontend/src/api/projectConfig.ts b/frontend/src/api/projectConfig.ts new file mode 100644 index 00000000..e5a0e574 --- /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 directoryQuery(directory: string | undefined): string { + return directory ? `?${new URLSearchParams({ directory }).toString()}` : '' +} + +export 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${directoryQuery(directory)}`) +} + +export function updateProjectActions( + repoId: number, + actions: ProjectAction[], + directory?: string, +): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/actions${directoryQuery(directory)}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ actions }), + }) +} + +export function updateWorktreeSetup( + repoId: number, + commands: string[], + directory?: string, +): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/worktree-setup${directoryQuery(directory)}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ commands }), + }) +} + +export 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), + }) +} + +export 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), + }) +} + +export 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: ['projectConfig', repoId] }) + }, + }) +} + +export function useUpdateWorktreeSetup(repoId: number, directory: string | undefined) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (commands: string[]) => updateWorktreeSetup(repoId, commands, directory), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] }) + }, + }) +} + +export function useTrustRepoConfig(repoId: number) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (request: TrustRepoConfigRequest) => trustRepoConfig(repoId, request), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] }) + }, + }) +} + +export function useMoveProjectItem(repoId: number) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (request: MoveProjectItemRequest) => moveProjectItem(repoId, request), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] }) + }, + }) +} + +export function useRunProjectAction(repoId: number, directory: string | undefined) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (actionId: string) => runProjectAction(repoId, actionId, directory), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] }) + queryClient.invalidateQueries({ queryKey: ['terminals', repoId] }) + }, + }) +} diff --git a/frontend/src/components/navigation/moreDrawerItems.test.ts b/frontend/src/components/navigation/moreDrawerItems.test.ts index 30bcd2dc..7dc39e72 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(10) + expect(items).toHaveLength(11) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[1].dialog).toBe('files') @@ -31,13 +31,15 @@ describe('buildMoreItems', () => { expect(items[6].dialog).toBe('sourceControl') expect(items[7].key).toBe('terminal') expect(items[7].dialog).toBe('terminal') - expect(items[8].key).toBe('settings') - expect(items[9].key).toBe('logout') + expect(items[8].key).toBe('actions') + expect(items[8].dialog).toBe('actions') + expect(items[9].key).toBe('settings') + expect(items[10].key).toBe('logout') }) it('returns session-specific items for /repos/:id/sessions/:sid', () => { const items = buildMoreItems('/repos/42/sessions/abc') - expect(items).toHaveLength(10) + expect(items).toHaveLength(11) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[2].key).toBe('mcp') @@ -48,8 +50,10 @@ describe('buildMoreItems', () => { expect(items[6].key).toBe('source-control') expect(items[7].key).toBe('terminal') expect(items[7].dialog).toBe('terminal') - expect(items[8].key).toBe('settings') - expect(items[9].key).toBe('logout') + expect(items[8].key).toBe('actions') + expect(items[8].dialog).toBe('actions') + expect(items[9].key).toBe('settings') + expect(items[10].key).toBe('logout') }) it('returns assistant workspace items for /repos/:id/assistant', () => { diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts index b327463e..168df87e 100644 --- a/frontend/src/components/navigation/moreDrawerItems.ts +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -1,5 +1,5 @@ import type { LucideIcon } from 'lucide-react' -import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home } from 'lucide-react' +import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play } from 'lucide-react' import { getAssistantPath, isAssistantPath } from '@/lib/navigation' export interface MoreDrawerItem { @@ -59,6 +59,7 @@ function buildRouteNavModel(pathname: string): NavModel { { 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' }, ...baseItems, ] @@ -78,6 +79,7 @@ function buildRouteNavModel(pathname: string): NavModel { { key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${sessionDetailMatch[1]}/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' }, ...baseItems, ] diff --git a/frontend/src/components/repo/RepoActionsDialog.test.tsx b/frontend/src/components/repo/RepoActionsDialog.test.tsx new file mode 100644 index 00000000..450e2588 --- /dev/null +++ b/frontend/src/components/repo/RepoActionsDialog.test.tsx @@ -0,0 +1,353 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { RepoActionsDialog } from './RepoActionsDialog' +import type { ProjectConfigResponse } from '@opencode-manager/shared/types' + +const mocks = vi.hoisted(() => ({ + useProjectConfig: vi.fn(), + updateActionsMutate: vi.fn(), + updateSetupMutate: vi.fn(), + trustMutate: vi.fn(), + moveMutate: vi.fn(), + showToastError: vi.fn(), +})) + +vi.mock('@/api/projectConfig', () => ({ + useProjectConfig: mocks.useProjectConfig, + useUpdateProjectActions: () => ({ mutate: mocks.updateActionsMutate, isPending: false }), + useUpdateWorktreeSetup: () => ({ mutate: mocks.updateSetupMutate, isPending: false }), + useTrustRepoConfig: () => ({ mutate: mocks.trustMutate, isPending: false }), + useMoveProjectItem: () => ({ mutate: mocks.moveMutate, isPending: false }), +})) + +vi.mock('@/lib/toast', () => ({ + showToast: { error: mocks.showToastError, success: vi.fn() }, +})) + +const HASH = 'a'.repeat(64) + +function baseConfig(overrides: Partial = {}): ProjectConfigResponse { + return { + actions: [], + worktreeSetup: [], + repoFile: { path: '.ocm/project.json', exists: false, trusted: false, hash: null, warnings: [] }, + ...overrides, + } +} + +function mockConfig(config: ProjectConfigResponse) { + mocks.useProjectConfig.mockReturnValue({ data: config, isLoading: false, error: null }) +} + +function renderDialog() { + return render( + , + ) +} + +describe('RepoActionsDialog', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('sends the full personal list when adding an action', async () => { + mockConfig( + baseConfig({ + actions: [ + { id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' }, + ], + }), + ) + const user = userEvent.setup() + renderDialog() + + await user.click(screen.getByRole('button', { name: /add action/i })) + await user.type(screen.getByLabelText('Name'), 'Dev server') + await user.type(screen.getByLabelText('Command'), 'pnpm dev') + await user.click(screen.getByRole('button', { name: /^save$/i })) + + await waitFor(() => expect(mocks.updateActionsMutate).toHaveBeenCalledTimes(1)) + const payload = mocks.updateActionsMutate.mock.calls[0][0] + expect(payload).toHaveLength(2) + expect(payload[0]).toMatchObject({ id: 'existing', name: 'Existing', command: 'echo hi' }) + expect(payload[1]).toMatchObject({ name: 'Dev server', command: 'pnpm dev' }) + }) + + it('offers no edit button for repo items but allows moving them to personal settings', () => { + mockConfig( + baseConfig({ + actions: [ + { id: 'personal-1', name: 'Personal action', command: 'echo personal', autoOpenUrl: false, source: 'personal' }, + { id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' }, + ], + }), + ) + renderDialog() + + expect(screen.getAllByRole('button', { name: /edit/i })).toHaveLength(1) + expect(screen.getByText('In repo')).toBeInTheDocument() + expect(screen.getByRole('button', { name: /move to my settings/i })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /move to repository/i })).toBeInTheDocument() + }) + + it('shows the trust banner for an untrusted repo file and sends the displayed hash', async () => { + mockConfig( + baseConfig({ + actions: [ + { id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' }, + ], + repoFile: { path: '.ocm/project.json', exists: true, trusted: false, hash: HASH, warnings: [] }, + }), + ) + const user = userEvent.setup() + renderDialog() + + expect(screen.getByText(/not trusted/i)).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: /trust these commands/i })) + + expect(mocks.trustMutate.mock.calls[0][0]).toEqual({ hash: HASH, directory: '/repo' }) + }) + + it('hides the trust banner for a trusted repo file', () => { + mockConfig( + baseConfig({ + repoFile: { path: '.ocm/project.json', exists: true, trusted: true, hash: HASH, warnings: [] }, + }), + ) + renderDialog() + + expect(screen.queryByRole('button', { name: /trust these commands/i })).not.toBeInTheDocument() + }) + + it('renders repository config parse errors', () => { + mockConfig( + baseConfig({ + repoFile: { + path: '.ocm/project.json', + exists: true, + trusted: false, + hash: null, + error: 'Invalid repository config', + warnings: [], + }, + }), + ) + renderDialog() + + expect(screen.getByRole('alert')).toHaveTextContent('Invalid repository config') + }) + + it('moves a saved personal setup command to the repository', async () => { + mockConfig( + baseConfig({ + worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], + }), + ) + const user = userEvent.setup() + renderDialog() + + await user.click(screen.getByRole('button', { name: /move to repository/i })) + + expect(mocks.moveMutate.mock.calls[0][0]).toEqual({ + kind: 'setup', + command: 'pnpm install', + to: 'repo', + directory: '/repo', + }) + }) + + it('disables moving a personal setup command while edits are unsaved', async () => { + mockConfig( + baseConfig({ + worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], + }), + ) + const user = userEvent.setup() + renderDialog() + + expect(screen.getByRole('button', { name: /move to repository/i })).toBeEnabled() + + await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile') + + expect(screen.getByRole('button', { name: /move to repository/i })).toBeDisabled() + expect(mocks.moveMutate).not.toHaveBeenCalled() + }) + + it('reports a failed action save and keeps the draft', async () => { + mockConfig( + baseConfig({ + actions: [ + { id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' }, + ], + }), + ) + mocks.updateActionsMutate.mockImplementation( + (_payload: unknown, options?: { onError?: (error: unknown) => void }) => { + options?.onError?.(new Error('Server rejected the action')) + }, + ) + const user = userEvent.setup() + renderDialog() + + await user.click(screen.getByRole('button', { name: /add action/i })) + await user.type(screen.getByLabelText('Name'), 'Dev server') + await user.type(screen.getByLabelText('Command'), 'pnpm dev') + await user.click(screen.getByRole('button', { name: /^save$/i })) + + expect(mocks.showToastError).toHaveBeenCalledWith('Server rejected the action') + expect(screen.getByLabelText('Name')).toHaveValue('Dev server') + expect(screen.getByLabelText('Command')).toHaveValue('pnpm dev') + }) + + it('reports a failed setup save and keeps edits', async () => { + mockConfig( + baseConfig({ + worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], + }), + ) + mocks.updateSetupMutate.mockImplementation( + (_commands: unknown, options?: { onError?: (error: unknown) => void }) => { + options?.onError?.(new Error('Setup save rejected')) + }, + ) + const user = userEvent.setup() + renderDialog() + + const input = screen.getByLabelText('Setup command 1') + await user.clear(input) + await user.type(input, 'pnpm ci') + await user.click(screen.getByRole('button', { name: /save setup/i })) + + expect(mocks.showToastError).toHaveBeenCalledWith('Setup save rejected') + expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci') + }) + + it('reports a failed trust attempt', async () => { + mockConfig( + baseConfig({ + actions: [ + { id: 'repo-1', name: 'Repo action', command: 'echo repo', autoOpenUrl: false, source: 'repo' }, + ], + repoFile: { path: '.ocm/project.json', exists: true, trusted: false, hash: HASH, warnings: [] }, + }), + ) + mocks.trustMutate.mockImplementation( + (_request: unknown, options?: { onError?: (error: unknown) => void }) => { + options?.onError?.(new Error('Trust rejected')) + }, + ) + const user = userEvent.setup() + renderDialog() + + await user.click(screen.getByRole('button', { name: /trust these commands/i })) + + expect(mocks.showToastError).toHaveBeenCalledWith('Trust rejected') + }) + + it('reports a failed move', async () => { + mockConfig( + baseConfig({ + actions: [ + { id: 'personal-1', name: 'Personal action', command: 'echo personal', autoOpenUrl: false, source: 'personal' }, + ], + }), + ) + mocks.moveMutate.mockImplementation( + (_request: unknown, options?: { onError?: (error: unknown) => void }) => { + options?.onError?.(new Error('Move rejected')) + }, + ) + const user = userEvent.setup() + renderDialog() + + await user.click(screen.getByRole('button', { name: /move to repository/i })) + + expect(mocks.showToastError).toHaveBeenCalledWith('Move rejected') + }) + + it('preserves unsaved setup edits when unrelated config data refetches', async () => { + mockConfig( + baseConfig({ + actions: [ + { id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' }, + ], + worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], + }), + ) + const user = userEvent.setup() + const view = renderDialog() + + await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile') + + mockConfig( + baseConfig({ + actions: [ + { id: 'existing', name: 'Existing', command: 'echo hi', autoOpenUrl: false, source: 'personal' }, + { id: 'added', name: 'Added', command: 'pnpm dev', autoOpenUrl: false, source: 'personal' }, + ], + worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], + repoFile: { path: '.ocm/project.json', exists: true, trusted: true, hash: HASH, warnings: [] }, + }), + ) + view.rerender() + + expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install --frozen-lockfile') + }) + + it('reflects persisted setup commands after a setup operation', () => { + mockConfig( + baseConfig({ + worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], + }), + ) + const view = renderDialog() + + mockConfig( + baseConfig({ + worktreeSetup: [{ command: 'pnpm ci', source: 'personal' }], + }), + ) + view.rerender() + + expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci') + }) + + it('reinitializes setup commands from persisted data when the dialog reopens', async () => { + mockConfig( + baseConfig({ + worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], + }), + ) + const user = userEvent.setup() + const view = renderDialog() + + await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile') + + view.rerender() + view.rerender() + + expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm install') + }) + + it('reinitializes setup commands when the location changes', async () => { + mockConfig( + baseConfig({ + worktreeSetup: [{ command: 'pnpm install', source: 'personal' }], + }), + ) + const user = userEvent.setup() + const view = renderDialog() + + await user.type(screen.getByLabelText('Setup command 1'), ' --frozen-lockfile') + + mockConfig( + baseConfig({ + worktreeSetup: [{ command: 'pnpm ci', source: 'personal' }], + }), + ) + view.rerender() + + expect(screen.getByLabelText('Setup command 1')).toHaveValue('pnpm ci') + }) +}) diff --git a/frontend/src/components/repo/RepoActionsDialog.tsx b/frontend/src/components/repo/RepoActionsDialog.tsx new file mode 100644 index 00000000..53ddd4f2 --- /dev/null +++ b/frontend/src/components/repo/RepoActionsDialog.tsx @@ -0,0 +1,581 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { + ArrowDown, + ArrowUp, + Bug, + CheckCircle2, + FlaskConical, + Hammer, + Loader2, + Pencil, + Play, + Plus, + Rocket, + Server, + ShieldAlert, + SquareTerminal, + Trash2, + type LucideIcon, +} from 'lucide-react' +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { Badge } from '@/components/ui/badge' +import { Input } from '@/components/ui/input' +import { Label } from '@/components/ui/label' +import { Switch } from '@/components/ui/switch' +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import { + useMoveProjectItem, + useProjectConfig, + useTrustRepoConfig, + useUpdateProjectActions, + useUpdateWorktreeSetup, +} from '@/api/projectConfig' +import { showToast } from '@/lib/toast' +import type { ProjectAction, ProjectActionIcon, ProjectItemSource } from '@opencode-manager/shared/types' + +const ACTION_ICON_OPTIONS: { value: ProjectActionIcon; label: string; Icon: LucideIcon }[] = [ + { value: 'play', label: 'Play', Icon: Play }, + { value: 'build', label: 'Build', Icon: Hammer }, + { value: 'test', label: 'Test', Icon: FlaskConical }, + { value: 'lint', label: 'Lint', Icon: CheckCircle2 }, + { value: 'terminal', label: 'Terminal', Icon: SquareTerminal }, + { value: 'server', label: 'Server', Icon: Server }, + { value: 'bug', label: 'Bug', Icon: Bug }, + { value: 'rocket', label: 'Rocket', Icon: Rocket }, +] + +function actionIcon(icon: ProjectActionIcon | undefined): LucideIcon { + return ACTION_ICON_OPTIONS.find((option) => option.value === icon)?.Icon ?? Play +} + +interface ActionDraft { + id: string + name: string + command: string + icon: ProjectActionIcon + url: string + autoOpenUrl: boolean +} + +function emptyActionDraft(): ActionDraft { + return { id: crypto.randomUUID(), name: '', command: '', icon: 'play', url: '', autoOpenUrl: false } +} + +function actionToDraft(action: ProjectAction): ActionDraft { + return { + id: action.id, + name: action.name, + command: action.command, + icon: action.icon ?? 'play', + url: action.url ?? '', + autoOpenUrl: action.autoOpenUrl, + } +} + +function actionToPayload(action: ProjectAction): ProjectAction { + const payload: ProjectAction = { + id: action.id, + name: action.name, + command: action.command, + autoOpenUrl: action.autoOpenUrl, + } + if (action.icon) payload.icon = action.icon + if (action.url) payload.url = action.url + return payload +} + +function draftToPayload(draft: ActionDraft): ProjectAction { + const payload: ProjectAction = { + id: draft.id, + name: draft.name.trim(), + command: draft.command.trim(), + icon: draft.icon, + autoOpenUrl: draft.autoOpenUrl, + } + const url = draft.url.trim() + if (url) payload.url = url + return payload +} + +function moveArrayItem(items: T[], from: number, to: number): T[] { + const next = [...items] + const [item] = next.splice(from, 1) + next.splice(to, 0, item) + return next +} + +function mutationErrorMessage(error: unknown, fallback: string): string { + return error instanceof Error ? error.message : fallback +} + +interface ActionFormProps { + draft: ActionDraft + isSaving: boolean + onChange: (draft: ActionDraft) => void + onSave: (draft: ActionDraft) => void + onCancel: () => void +} + +function ActionForm({ draft, isSaving, onChange, onSave, onCancel }: ActionFormProps) { + const canSave = draft.name.trim().length > 0 && draft.command.trim().length > 0 + + return ( +
+
+ + onChange({ ...draft, name: event.target.value })} + /> +
+
+ + onChange({ ...draft, command: event.target.value })} + /> +
+
+ + +
+
+ + onChange({ ...draft, url: event.target.value })} + /> +
+
+ + onChange({ ...draft, autoOpenUrl: checked })} + /> +
+
+ + +
+
+ ) +} + +interface RepoActionsDialogProps { + repoId: number + directory: string | undefined + open: boolean + onOpenChange: (open: boolean) => void +} + +export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: RepoActionsDialogProps) { + const configQuery = useProjectConfig(repoId, directory, open && !!directory) + const updateActions = useUpdateProjectActions(repoId, directory) + const updateSetup = useUpdateWorktreeSetup(repoId, directory) + const trustConfig = useTrustRepoConfig(repoId) + const moveItem = useMoveProjectItem(repoId) + + const [draft, setDraft] = useState(null) + const [setupCommands, setSetupCommands] = useState([]) + + const config = configQuery.data + + const personalActions = useMemo( + () => (config?.actions ?? []).filter((action) => action.source === 'personal'), + [config], + ) + const repoActions = useMemo( + () => (config?.actions ?? []).filter((action) => action.source === 'repo'), + [config], + ) + const repoSetup = useMemo( + () => (config?.worktreeSetup ?? []).filter((item) => item.source === 'repo'), + [config], + ) + const personalSetup = useMemo( + () => (config?.worktreeSetup ?? []).filter((item) => item.source === 'personal').map((item) => item.command), + [config], + ) + const personalSetupBaseline = useMemo(() => JSON.stringify(personalSetup), [personalSetup]) + const setupSyncKey = useRef(null) + + useEffect(() => { + if (!open || !config) { + setupSyncKey.current = null + return + } + const syncKey = `${directory ?? ''}\u0000${personalSetupBaseline}` + if (setupSyncKey.current === syncKey) return + setupSyncKey.current = syncKey + setSetupCommands(personalSetup) + }, [open, config, directory, personalSetup, personalSetupBaseline]) + + const setupDirty = useMemo( + () => + setupCommands.length !== personalSetup.length || + setupCommands.some((command, index) => command !== personalSetup[index]), + [setupCommands, personalSetup], + ) + + const handleSaveAction = (nextDraft: ActionDraft) => { + const payload = draftToPayload(nextDraft) + const exists = personalActions.some((action) => action.id === payload.id) + const next = exists + ? personalActions.map((action) => (action.id === payload.id ? payload : actionToPayload(action))) + : [...personalActions.map(actionToPayload), payload] + updateActions.mutate(next, { + onSuccess: () => setDraft(null), + onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to save action')), + }) + } + + const handleDeleteAction = (id: string) => { + updateActions.mutate(personalActions.filter((action) => action.id !== id).map(actionToPayload), { + onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to delete action')), + }) + } + + const handleSaveSetup = () => { + updateSetup.mutate(setupCommands.map((command) => command.trim()), { + onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to save setup commands')), + }) + } + + const handleTrust = () => { + if (!config?.repoFile.hash) return + trustConfig.mutate( + { hash: config.repoFile.hash, directory }, + { onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to trust repository commands')) }, + ) + } + + const moveAction = (action: ProjectAction, to: ProjectItemSource) => { + moveItem.mutate( + { kind: 'action', id: action.id, to, directory }, + { onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to move action')) }, + ) + } + + const moveSetup = (command: string, to: ProjectItemSource) => { + moveItem.mutate( + { kind: 'setup', command, to, directory }, + { onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to move setup command')) }, + ) + } + + const isAddingAction = draft !== null && !personalActions.some((action) => action.id === draft.id) + + return ( + + + + Project Actions + Commands and setup steps for this location. + + +
+ {configQuery.isLoading ? ( +
+ +
+ ) : !config ? ( +

+ {configQuery.error instanceof Error ? configQuery.error.message : 'No configuration available.'} +

+ ) : ( + <> +
+
+

Actions

+ +
+ + {personalActions.length === 0 && repoActions.length === 0 && ( +

No actions configured.

+ )} + + {personalActions.map((action) => { + const Icon = actionIcon(action.icon) + const isEditing = draft?.id === action.id + return ( +
+ {isEditing && draft ? ( + setDraft(null)} + /> + ) : ( + <> +
+ + {action.name} +
+

{action.command}

+ {action.url && ( +

{action.url}

+ )} +
+ + + +
+ + )} +
+ ) + })} + + {repoActions.map((action) => { + const Icon = actionIcon(action.icon) + return ( +
+
+ + {action.name} + In repo +
+

{action.command}

+ {action.url && ( +

{action.url}

+ )} + +
+ ) + })} + + {isAddingAction && draft && ( +
+ setDraft(null)} + /> +
+ )} +
+ +
+
+

Worktree setup

+

+ Commands run after a new worktree is created. Use{' '} + $ROOT_PROJECT_PATH to reference the main checkout. +

+
+ + {setupCommands.length === 0 && repoSetup.length === 0 && ( +

No setup commands.

+ )} + + {setupCommands.map((command, index) => ( +
+
+ + setSetupCommands((current) => + current.map((item, itemIndex) => (itemIndex === index ? event.target.value : item)), + ) + } + /> + + + +
+
+ +
+
+ ))} + + {repoSetup.map((item) => ( +
+
+ {item.command} + In repo +
+ +
+ ))} + +
+ + +
+
+ +
+ {config.repoFile.error && ( +

+ {config.repoFile.error} +

+ )} + {config.repoFile.warnings.map((warning) => ( +

+ {warning} +

+ ))} + {config.repoFile.exists && !config.repoFile.trusted && config.repoFile.hash && ( +
+
+ + Repository commands are not trusted +
+

+ This repository defines commands that run on your machine. Review and trust them to enable. +

+
    + {repoActions.map((action) => ( +
  • + {action.command} + {action.url ? ` — ${action.url}` : ''} +
  • + ))} + {repoSetup.map((item) => ( +
  • + {item.command} +
  • + ))} +
+ +
+ )} +
+ + )} +
+
+
+ ) +} diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx index b517f5bb..04613f71 100644 --- a/frontend/src/pages/RepoDetail.tsx +++ b/frontend/src/pages/RepoDetail.tsx @@ -6,6 +6,7 @@ import { SessionList } from "@/components/session/SessionList"; import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; import { Header } from "@/components/ui/header"; import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog"; +import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog"; import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"; import { SourceControlPanel } from "@/components/source-control"; import { TerminalPanel } from "@/components/terminal/TerminalPanel"; @@ -35,6 +36,7 @@ export function RepoDetail() { const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills'); const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl'); const [terminalOpen, setTerminalOpen] = useDialogParam('terminal'); + const [actionsDialogOpen, setActionsDialogOpen] = useDialogParam('actions'); const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions'); const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false); const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false); @@ -279,6 +281,13 @@ export function RepoDetail() { directory={composerDirectory} /> + + (); const [showScrollButton, setShowScrollButton] = useState(false); @@ -855,6 +857,13 @@ export function SessionDetail() { directory={repoDirectory} /> + + ({ vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null), })) +vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) })) vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null), diff --git a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx index fba20fc5..efe536a8 100644 --- a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx @@ -197,6 +197,7 @@ vi.mock('@/components/session/SideQuestionDialog', () => ({ SideQuestionDialog: vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) })) vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) })) vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) })) +vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) })) vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null) })) vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: vi.fn(() => null) })) vi.mock('@/components/source-control', () => ({ SourceControlPanel: vi.fn(() => null) })) diff --git a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx index 762afecd..e021fc5e 100644 --- a/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.form-prompt.test.tsx @@ -162,6 +162,7 @@ vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null), })) +vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) })) vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null), diff --git a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx index c899bbf2..ba582c7c 100644 --- a/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.polling.test.tsx @@ -129,6 +129,7 @@ vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi vi.mock('@/components/session/SessionList', () => ({ SessionList: vi.fn(() => null) })) vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) })) vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) })) +vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) })) vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null) })) vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: vi.fn(() => null) })) vi.mock('@/components/source-control', () => ({ SourceControlPanel: vi.fn(() => null) })) diff --git a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx index 0772e469..e3ba5478 100644 --- a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx @@ -156,6 +156,7 @@ vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null), })) +vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) })) vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: vi.fn(() => null), From a383e57bc53aa231fcf44be97a6e99bf3c737a70 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:07:44 -0400 Subject: [PATCH 10/12] section 16: Phase 16: Documentation, container ports and full repository checks --- Dockerfile | 2 +- backend/src/index.ts | 15 + backend/src/routes/opencode-proxy.ts | 32 +- backend/src/routes/preview.ts | 74 ++++ backend/src/routes/repos.test.ts | 34 +- backend/src/routes/repos.ts | 17 +- backend/src/services/preview/gateway.ts | 295 +++++++++++++++ backend/src/services/preview/ports.ts | 320 ++++++++++++++++ backend/src/services/project-config.ts | 45 ++- backend/src/utils/proxy-headers.ts | 40 ++ backend/test/index.test.ts | 2 +- backend/test/routes/preview.test.ts | 134 +++++++ backend/test/routes/repos.test.ts | 38 +- .../test/services/preview/gateway-ws.test.ts | 274 ++++++++++++++ backend/test/services/preview/gateway.test.ts | 258 +++++++++++++ backend/test/services/preview/ports.test.ts | 194 ++++++++++ backend/test/services/project-config.test.ts | 132 +++++++ docker-compose.yml | 1 + docs/configuration/docker.md | 12 +- docs/configuration/environment.md | 9 + docs/features/overview.md | 8 + docs/features/preview.md | 63 ++++ docs/features/project-actions.md | 107 ++++++ docs/features/sandboxing.md | 4 +- docs/features/terminal.md | 48 +++ frontend/src/api/preview.ts | 38 ++ frontend/src/api/repos.ts | 4 +- frontend/src/api/types.ts | 6 +- .../navigation/moreDrawerItems.test.ts | 16 +- .../components/navigation/moreDrawerItems.ts | 4 +- .../components/preview/PreviewPanel.test.tsx | 224 +++++++++++ .../src/components/preview/PreviewPanel.tsx | 353 ++++++++++++++++++ .../repo/CreateWorktreeDialog.test.tsx | 138 +++++++ .../components/repo/CreateWorktreeDialog.tsx | 9 +- .../repo/ProjectActionsMenu.test.tsx | 298 +++++++++++++++ .../components/repo/ProjectActionsMenu.tsx | 252 +++++++++++++ .../src/components/terminal/TerminalPanel.tsx | 9 +- frontend/src/hooks/useOpenPreview.ts | 18 + frontend/src/lib/open-url.test.ts | 34 ++ frontend/src/lib/open-url.ts | 14 + frontend/src/lib/preview-url.test.ts | 67 ++++ frontend/src/lib/preview-url.ts | 59 +++ frontend/src/lib/worktreeSetup.ts | 13 + frontend/src/pages/AssistantRedirect.tsx | 3 + frontend/src/pages/RepoDetail.tsx | 26 +- frontend/src/pages/SessionDetail.tsx | 10 + .../AssistantRedirect.preview.test.tsx | 163 ++++++++ .../RepoDetail.worktree-setup.test.tsx | 176 +++++++++ mkdocs.yml | 3 + shared/src/config/defaults.ts | 4 + shared/src/config/env.ts | 5 + shared/src/schemas/index.ts | 1 + shared/src/schemas/preview.ts | 29 ++ shared/src/schemas/project-config.ts | 12 + shared/src/types/index.ts | 8 + 55 files changed, 4095 insertions(+), 59 deletions(-) create mode 100644 backend/src/routes/preview.ts create mode 100644 backend/src/services/preview/gateway.ts create mode 100644 backend/src/services/preview/ports.ts create mode 100644 backend/src/utils/proxy-headers.ts create mode 100644 backend/test/routes/preview.test.ts create mode 100644 backend/test/services/preview/gateway-ws.test.ts create mode 100644 backend/test/services/preview/gateway.test.ts create mode 100644 backend/test/services/preview/ports.test.ts create mode 100644 docs/features/preview.md create mode 100644 docs/features/project-actions.md create mode 100644 docs/features/terminal.md create mode 100644 frontend/src/api/preview.ts create mode 100644 frontend/src/components/preview/PreviewPanel.test.tsx create mode 100644 frontend/src/components/preview/PreviewPanel.tsx create mode 100644 frontend/src/components/repo/CreateWorktreeDialog.test.tsx create mode 100644 frontend/src/components/repo/ProjectActionsMenu.test.tsx create mode 100644 frontend/src/components/repo/ProjectActionsMenu.tsx create mode 100644 frontend/src/hooks/useOpenPreview.ts create mode 100644 frontend/src/lib/open-url.test.ts create mode 100644 frontend/src/lib/open-url.ts create mode 100644 frontend/src/lib/preview-url.test.ts create mode 100644 frontend/src/lib/preview-url.ts create mode 100644 frontend/src/lib/worktreeSetup.ts create mode 100644 frontend/src/pages/__tests__/AssistantRedirect.preview.test.tsx create mode 100644 frontend/src/pages/__tests__/RepoDetail.worktree-setup.test.tsx create mode 100644 shared/src/schemas/preview.ts 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/src/index.ts b/backend/src/index.ts index aec289f7..2ded2a67 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -39,6 +39,8 @@ import { createAuthMiddleware } from './auth/middleware' import { createPromptTemplateRoutes } from './routes/prompt-templates' import { createSessionPinRoutes } from './routes/session-pins' import { createLogRoutes } from './routes/logs' +import { createPreviewRoutes } 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' @@ -268,6 +270,7 @@ sseAggregator.setScheduledSessionsResolver( void scheduleRunnerInstance.start() const settingsService = new SettingsService(db) +const previewSessionStore = new PreviewSessionStore() app.route('/api/auth', createAuthRoutes(auth)) app.route('/api/auth-info', createAuthInfoRoutes(auth, db)) @@ -296,6 +299,7 @@ protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db)) protectedApi.route('/session-pins', createSessionPinRoutes(db)) protectedApi.route('/schedules', createScheduleRoutes(scheduleService)) protectedApi.route('/logs', createLogRoutes()) +protectedApi.route('/preview', createPreviewRoutes({ store: previewSessionStore })) app.route('/api', protectedApi) @@ -415,4 +419,15 @@ const server = serve({ injectWebSocket(server) +if (ENV.PREVIEW.PORT > 0) { + const previewGateway = createPreviewGatewayApp(previewSessionStore) + const previewServer = serve({ + fetch: previewGateway.app.fetch, + port: ENV.PREVIEW.PORT, + hostname: HOST, + }) + previewGateway.injectWebSocket(previewServer) + logger.info(`Preview gateway running on http://${HOST}:${ENV.PREVIEW.PORT}`) +} + logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`) 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..935282c7 --- /dev/null +++ b/backend/src/routes/preview.ts @@ -0,0 +1,74 @@ +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 PreviewRoutesDeps { + enabled: boolean + listPorts: () => Promise + store: PreviewSessionStore +} + +function isInsideDirectory(cwd: string | null, canonicalDirectory: string | null): boolean { + if (!cwd || !canonicalDirectory) return false + const canonicalCwd = canonicalPathSync(cwd) + 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 = { + enabled: deps.enabled ?? 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 sorted = [...ports].sort((left, right) => { + const leftMatch = isInsideDirectory(left.cwd, canonicalDirectory) + const rightMatch = isInsideDirectory(right.cwd, canonicalDirectory) + if (leftMatch !== rightMatch) return leftMatch ? -1 : 1 + return left.port - right.port + }) + return c.json({ enabled: resolvedDeps.enabled, ports: sorted }) + }) + + 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.enabled) { + 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/repos.test.ts b/backend/src/routes/repos.test.ts index b89e8740..5e6afe98 100644 --- a/backend/src/routes/repos.test.ts +++ b/backend/src/routes/repos.test.ts @@ -4,7 +4,7 @@ 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 type { GitAuthService } from '../services/git-auth' import type { TerminalService } from '../services/terminal' @@ -33,7 +33,11 @@ const stubTerminalService = { removeAll: mock(async () => undefined), } as unknown as TerminalService -function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStubOpenCodeClient()): Hono { +function createTestApp( + db: Database, + openCodeClient: OpenCodeClient = createStubOpenCodeClient(), + terminalService: TerminalService = stubTerminalService, +): Hono { const app = new Hono() const scheduleService = { createSchedule: () => {}, @@ -43,7 +47,7 @@ function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStub deleteSchedule: () => {}, prepareRepoDelete: () => {}, } as any - app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, stubTerminalService)) + app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService)) return app } @@ -440,10 +444,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 56136fa8..84acb670 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -92,7 +92,17 @@ export function createRepoRoutes( { branch, directoryName, useWorktree, skipSSHVerification, baseBranch } ) } - + + if (repo.isWorktree) { + const projectRepo = await projectConfigService.resolveProjectRepo(repo) + if (projectRepo.id !== repo.id) { + return c.json({ + ...repo, + worktreeSetup: await projectConfigService.runWorktreeSetup(projectRepo, repo.fullPath, terminalService), + }) + } + } + return c.json(repo) } catch (error: unknown) { logger.error('Failed to create repo:', error) @@ -320,7 +330,10 @@ app.get('/', async (c) => { try { const projectID = await repoService.resolveRepoProjectId(openCodeClient, repo.fullPath) const worktree = await openCodeClient.api.worktree.create({ projectID }) - return c.json(worktree) + return c.json({ + ...worktree, + worktreeSetup: await projectConfigService.runWorktreeSetup(repo, worktree.directory, terminalService), + }) } catch (error: unknown) { if (isWorktreeError(error)) { return c.json({ error: error.data.message }, 409) diff --git a/backend/src/services/preview/gateway.ts b/backend/src/services/preview/gateway.ts new file mode 100644 index 00000000..23966858 --- /dev/null +++ b/backend/src/services/preview/gateway.ts @@ -0,0 +1,295 @@ +import { randomBytes } from 'node:crypto' +import { Hono } from 'hono' +import type { Context, MiddlewareHandler } from 'hono' +import { createNodeWebSocket, type NodeWebSocket } from '@hono/node-ws' +import { buildProxyResponseHeaders, filterProxyHeaders } from '../../utils/proxy-headers' +import { bridgeWebSocket, 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 = ['opencode.', '__Secure-opencode.', '__Host-opencode.'] + +export type PreviewHost = '127.0.0.1' | '::1' + +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) + } + } +} + +export function stripManagerCookies(cookieHeader: string | undefined): string | undefined { + if (!cookieHeader) return undefined + const kept = cookieHeader + .split(';') + .map((part) => part.trim()) + .filter((part) => { + if (!part) return false + const separator = part.indexOf('=') + const name = separator === -1 ? part : part.slice(0, separator) + if (name === PREVIEW_COOKIE) return false + return !MANAGER_COOKIE_PREFIXES.some((prefix) => name.startsWith(prefix)) + }) + return kept.length > 0 ? kept.join('; ') : undefined +} + +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 { + const targetHost = session.host === '::1' ? '[::1]' : 'localhost' + return `ws://${targetHost}:${session.port}${requestUrl.pathname}${requestUrl.search}` +} + +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 location = requestedPath.startsWith('/') && !requestedPath.startsWith('//') ? requestedPath : '/' + + const forwardedProto = c.req.header('x-forwarded-proto')?.toLowerCase() + const isSecure = forwardedProto === 'https' || new URL(c.req.url).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), + }) + }, + async onMessage(event) { + if (!bridge) return + const data = event.data + 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) + } + }, + 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 targetHost = session.host === '::1' ? '[::1]' : 'localhost' + const target = `http://${targetHost}:${session.port}${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}` + 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) + 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..91f4ca65 --- /dev/null +++ b/backend/src/services/preview/ports.ts @@ -0,0 +1,320 @@ +import { readFile, readdir, readlink } from 'node:fs/promises' +import { ENV } from '@opencode-manager/shared/config/env' +import { executeCommand } from '../../utils/process' + +export interface PreviewPortEntry { + port: number + host: '127.0.0.1' | '::1' + pid: number | null + command: string | null + cwd: string | null +} + +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): Promise> { + const map = new Map() + let entries: string[] + try { + entries = await deps.readdir('/proc') + } catch { + return map + } + for (const entry of entries) { + 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) + if (match?.[1]) map.set(match[1], 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 inodeToPid = await mapInodesToPids(deps) + 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 index 4404c54b..fa76c5d0 100644 --- a/backend/src/services/project-config.ts +++ b/backend/src/services/project-config.ts @@ -13,10 +13,12 @@ import { type ProjectConfigResponse, type RepoProjectFile, type RunProjectActionResponse, + type WorktreeSetupResult, } from '@opencode-manager/shared/schemas' 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 } from '../utils/fs-safe' import type { GitService } from './git/GitService' import type { GitAuthService } from './git-auth' @@ -126,9 +128,7 @@ export class ProjectConfigService { worktreeSetup.push({ command, source: 'repo' }) } - const trusted = - repoFile.hash !== null && - repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY) + const trusted = this.isRepoFileTrusted(projectRepo, repoFile) const resolvedActions = await Promise.all( actions.map(async (action) => @@ -233,6 +233,45 @@ export class ProjectConfigService { 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) } + } + } + + 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) if (!fs.existsSync(filePath)) { diff --git a/backend/src/utils/proxy-headers.ts b/backend/src/utils/proxy-headers.ts new file mode 100644 index 00000000..f9f65d83 --- /dev/null +++ b/backend/src/utils/proxy-headers.ts @@ -0,0 +1,40 @@ +export 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/test/index.test.ts b/backend/test/index.test.ts index 306daafa..b1a0a6d5 100644 --- a/backend/test/index.test.ts +++ b/backend/test/index.test.ts @@ -162,7 +162,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) diff --git a/backend/test/routes/preview.test.ts b/backend/test/routes/preview.test.ts new file mode 100644 index 00000000..98e55333 --- /dev/null +++ b/backend/test/routes/preview.test.ts @@ -0,0 +1,134 @@ +import { describe, it, expect, afterEach } from 'vitest' +import { mkdtemp, mkdir, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { ENV } from '@opencode-manager/shared/config/env' +import { createPreviewRoutes } 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({ + enabled: 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({ + enabled: 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('reports preview as disabled when the port is zero', async () => { + const app = createPreviewRoutes({ enabled: 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({ enabled: 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({ enabled: 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({ enabled: 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({ enabled: 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({ enabled: 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) + }) +}) diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts index 3893c1fd..313242f1 100644 --- a/backend/test/routes/repos.test.ts +++ b/backend/test/routes/repos.test.ts @@ -20,6 +20,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', () => ({ @@ -35,6 +37,7 @@ vi.mock('../../src/services/repo', () => ({ resolveRepoOrAssistant: vi.fn(), findSiblingByDirectory: vi.fn(), resolveRepoWorkingDirectory: vi.fn(), + resolveRepoProjectId: vi.fn(), })) vi.mock('../../src/services/assistant-mode', () => ({ @@ -96,6 +99,7 @@ const mockScheduleService = { const mockTerminalService = { removeAll: vi.fn().mockResolvedValue(undefined), + create: vi.fn(), } as unknown as TerminalService function createTestRoutes(openCodeClient: ReturnType = createStubOpenCodeClient()): ReturnType { @@ -131,6 +135,8 @@ 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), ) @@ -480,8 +486,36 @@ describe('Repo Routes', () => { }) }) - describe('POST /discover', () => { - it('should return 400 for an invalid body', async () => { + 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' }, + }) + }) + }) + + describe('POST /discover', () => { it('should return 400 for an invalid body', async () => { const app = createTestRoutes() const res = await app.request('/discover', { method: 'POST', 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..b80edeec --- /dev/null +++ b/backend/test/services/preview/gateway.test.ts @@ -0,0 +1,258 @@ +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.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, + 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('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('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..18acf84e --- /dev/null +++ b/backend/test/services/preview/ports.test.ts @@ -0,0 +1,194 @@ +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('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 index 0f9e8ae4..7ee2957c 100644 --- a/backend/test/services/project-config.test.ts +++ b/backend/test/services/project-config.test.ts @@ -809,3 +809,135 @@ describe('ProjectConfigService runAction', () => { } }) }) + +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/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..8e413310 100644 --- a/docs/configuration/environment.md +++ b/docs/configuration/environment.md @@ -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. | `5004` | +| `PREVIEW_PUBLIC_URL` | Same-site HTTPS origin that proxies the preview gateway. 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/overview.md b/docs/features/overview.md index b62c3f66..82a56576 100644 --- a/docs/features/overview.md +++ b/docs/features/overview.md @@ -23,6 +23,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..6be9d93c --- /dev/null +++ b/docs/features/preview.md @@ -0,0 +1,63 @@ +# 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. The panel lists every listening loopback port on the host, with its port number, process command, and working directory. Ports inside the selected repository or workspace directory are badged **this repo** and sorted first. + +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. + +Selecting a port creates a preview session and renders the target in a sandboxed iframe. Selecting a different port starts a new session for it. + +When preview is disabled the panel shows **Preview is disabled (PREVIEW_PORT=0)**. + +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. + +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. + +The gateway also proxies **WebSocket upgrades** on the same origin, so dev-server HMR works through the panel. + +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`. 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..ec3fc913 --- /dev/null +++ b/docs/features/project-actions.md @@ -0,0 +1,107 @@ +# 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. +- A repository action whose `id` matches a personal action is ignored, and the dialog reports a warning, so personal actions always win. + +## 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 is a hash of the file's **executable content only**: each action's `id`, `command` and `url`, plus the setup commands. Changing an action's name, icon, or `autoOpenUrl` does not affect trust; changing a command, URL, or setup command does. +- Trusting requires echoing the exact hash 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 — both Manager worktrees and OpenCode workspaces. 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..3e9ad05b 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 and assigned commit identity env through `CredentialProvider.getShellEnv` at creation | | 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 and assigned commit identity env through `CredentialProvider.getShellEnv` at creation, 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..82b9b986 --- /dev/null +++ b/docs/features/terminal.md @@ -0,0 +1,48 @@ +# 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 environment resolved for its directory: + +- the repository's GitHub token environment, so `git` and `gh` authenticate as the repo's credentials; +- the assigned git commit identity, so commits made in the terminal use the repo's configured author. + +## 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/src/api/preview.ts b/frontend/src/api/preview.ts new file mode 100644 index 00000000..0dead7d7 --- /dev/null +++ b/frontend/src/api/preview.ts @@ -0,0 +1,38 @@ +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 directoryQuery(directory: string | undefined): string { + return directory ? `?${new URLSearchParams({ directory }).toString()}` : '' +} + +export function previewPortsQueryKey(directory: string | undefined) { + return ['previewPorts', directory ?? null] as const +} + +export function listPreviewPorts(directory?: string): Promise { + return fetchWrapper(`${API_BASE_URL}/api/preview/ports${directoryQuery(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/repos.ts b/frontend/src/api/repos.ts index 5a273c85..11acecf6 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 } from '@opencode-manager/shared/types' +import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, 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/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 7dc39e72..6d26b8ef 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(11) + expect(items).toHaveLength(12) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[1].dialog).toBe('files') @@ -33,13 +33,15 @@ describe('buildMoreItems', () => { expect(items[7].dialog).toBe('terminal') expect(items[8].key).toBe('actions') expect(items[8].dialog).toBe('actions') - expect(items[9].key).toBe('settings') - expect(items[10].key).toBe('logout') + 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(11) + expect(items).toHaveLength(12) expect(items[0].key).toBe('home') expect(items[1].key).toBe('files') expect(items[2].key).toBe('mcp') @@ -52,8 +54,10 @@ describe('buildMoreItems', () => { expect(items[7].dialog).toBe('terminal') expect(items[8].key).toBe('actions') expect(items[8].dialog).toBe('actions') - expect(items[9].key).toBe('settings') - expect(items[10].key).toBe('logout') + 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 assistant workspace items for /repos/:id/assistant', () => { diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts index 168df87e..823064e2 100644 --- a/frontend/src/components/navigation/moreDrawerItems.ts +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -1,5 +1,5 @@ import type { LucideIcon } from 'lucide-react' -import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play } from 'lucide-react' +import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react' import { getAssistantPath, isAssistantPath } from '@/lib/navigation' export interface MoreDrawerItem { @@ -60,6 +60,7 @@ function buildRouteNavModel(pathname: string): NavModel { { 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, ] @@ -80,6 +81,7 @@ function buildRouteNavModel(pathname: string): NavModel { { 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, ] diff --git a/frontend/src/components/preview/PreviewPanel.test.tsx b/frontend/src/components/preview/PreviewPanel.test.tsx new file mode 100644 index 00000000..9d2d570d --- /dev/null +++ b/frontend/src/components/preview/PreviewPanel.test.tsx @@ -0,0 +1,224 @@ +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' }], +} + +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 disabled/)).toBeInTheDocument() + }) + + it('badges ports that run inside the directory', () => { + renderPanel('/repos/1?dialog=preview') + + expect(screen.getByText('this repo')).toBeInTheDocument() + }) + + 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..363622f8 --- /dev/null +++ b/frontend/src/components/preview/PreviewPanel.tsx @@ -0,0 +1,353 @@ +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 { buildPreviewStartUrl, getPreviewOrigin, isSameOriginAsManager } 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 +} + +function isInsideDirectory(cwd: string | null, directory: string | undefined): boolean { + if (!cwd || !directory) return false + if (cwd === directory) return true + const prefix = directory.endsWith('/') ? directory : `${directory}/` + return cwd.startsWith(prefix) +} + +function errorMessage(error: unknown, fallback: string): string { + return error instanceof Error ? error.message : fallback +} + +export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) { + const isMobile = useMobile() + const { searchParams, updateParams } = useUrlParams() + + const requestedPort = useMemo(() => { + const raw = searchParams.get('previewPort') + if (!raw) return undefined + const port = Number(raw) + return Number.isInteger(port) && port > 0 && port <= 65535 ? 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 portsQuery = usePreviewPorts(directory, { + enabled: isOpen, + refetchInterval: isOpen ? 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(errorMessage(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(errorMessage(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 activeSession = session && session.targetPort === requestedPort ? session : null + 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 disabled (PREVIEW_PORT=0)') + } + 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 ( +
+