diff --git a/backend/src/auth/cookies.ts b/backend/src/auth/cookies.ts
new file mode 100644
index 00000000..d4e1b400
--- /dev/null
+++ b/backend/src/auth/cookies.ts
@@ -0,0 +1 @@
+export const AUTH_COOKIE_PREFIX = 'opencode'
diff --git a/backend/src/auth/index.ts b/backend/src/auth/index.ts
index 3fd64333..956f5128 100644
--- a/backend/src/auth/index.ts
+++ b/backend/src/auth/index.ts
@@ -2,7 +2,8 @@ import { betterAuth } from 'better-auth'
import { APIError } from 'better-auth/api'
import { passkey } from '@better-auth/passkey'
import { Database } from 'bun:sqlite'
-import { ENV } from '@opencode-manager/shared/config/env'
+import { ENV, getTrustedOrigins } from '@opencode-manager/shared/config/env'
+import { AUTH_COOKIE_PREFIX } from './cookies'
export type AuthInstance = ReturnType
@@ -34,14 +35,15 @@ export function createAuth(db: Database) {
}
}
- const baseURL = ENV.AUTH.TRUSTED_ORIGINS.split(',')[0]?.trim() || `http://localhost:${ENV.SERVER.PORT}`
+ const trustedOrigins = getTrustedOrigins()
+ const baseURL = trustedOrigins[0] || `http://localhost:${ENV.SERVER.PORT}`
const auth = betterAuth({
baseURL,
basePath: '/api/auth',
database: db,
secret: ENV.AUTH.SECRET,
- trustedOrigins: ENV.AUTH.TRUSTED_ORIGINS.split(',').map((o: string) => o.trim()),
+ trustedOrigins,
emailAndPassword: {
enabled: true,
minPasswordLength: 8,
@@ -90,7 +92,7 @@ export function createAuth(db: Database) {
},
},
advanced: {
- cookiePrefix: 'opencode',
+ cookiePrefix: AUTH_COOKIE_PREFIX,
useSecureCookies: ENV.AUTH.SECURE_COOKIES,
},
})
diff --git a/backend/src/auth/middleware.ts b/backend/src/auth/middleware.ts
index 544f8bdd..32cdbedd 100644
--- a/backend/src/auth/middleware.ts
+++ b/backend/src/auth/middleware.ts
@@ -1,8 +1,15 @@
import { createMiddleware } from 'hono/factory'
+import { getTrustedOrigins } from '@opencode-manager/shared/config/env'
import type { AuthInstance, Session } from './index'
import { logger } from '../utils/logger'
-export function createAuthMiddleware(auth: AuthInstance) {
+const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
+const UNTRUSTED_FETCH_SITES = new Set(['same-site', 'cross-site'])
+
+export function createAuthMiddleware(
+ auth: AuthInstance,
+ resolveTrustedOrigins: () => string[] = getTrustedOrigins,
+) {
return createMiddleware<{
Variables: {
session: Session['session']
@@ -11,6 +18,17 @@ export function createAuthMiddleware(auth: AuthInstance) {
}>(async (c, next) => {
const cookies = c.req.header('cookie')
const origin = c.req.header('origin')
+
+ const fetchSite = c.req.header('sec-fetch-site')
+ if (
+ UNSAFE_METHODS.has(c.req.method) &&
+ fetchSite !== undefined &&
+ UNTRUSTED_FETCH_SITES.has(fetchSite) &&
+ (!origin || !resolveTrustedOrigins().includes(origin))
+ ) {
+ logger.warn(`Rejected cross-site request - Path: ${c.req.path}, Method: ${c.req.method}, Origin: ${origin ?? 'none'}`)
+ return c.json({ error: 'Cross-site request rejected' }, 403)
+ }
logger.debug(`Auth check - Path: ${c.req.path}, Origin: ${origin}, Has cookies: ${!!cookies}`)
if (cookies) {
diff --git a/backend/src/index.ts b/backend/src/index.ts
index 2ded2a67..c8e98761 100644
--- a/backend/src/index.ts
+++ b/backend/src/index.ts
@@ -39,7 +39,7 @@ 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 { createPreviewRoutes, createPreviewAvailability } from './routes/preview'
import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway'
import { createInternalRoutes } from './routes/internal'
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
@@ -71,6 +71,7 @@ import {
getConfigPath,
getAgentsMdPath,
getDatabasePath,
+ getTrustedOrigins,
ENV
} from '@opencode-manager/shared/config/env'
@@ -93,7 +94,7 @@ app.use('/*', cors({
if (origin && REFLECT_ANY_ORIGIN_PREFIXES.some(prefix => c.req.path.startsWith(prefix))) {
return origin
}
- const trustedOrigins = ENV.AUTH.TRUSTED_ORIGINS.split(',').map(o => o.trim())
+ const trustedOrigins = getTrustedOrigins()
if (!origin) return trustedOrigins[0]
if (trustedOrigins.includes(origin)) return origin
return trustedOrigins[0]
@@ -271,6 +272,7 @@ void scheduleRunnerInstance.start()
const settingsService = new SettingsService(db)
const previewSessionStore = new PreviewSessionStore()
+const previewAvailability = createPreviewAvailability(false)
app.route('/api/auth', createAuthRoutes(auth))
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
@@ -299,7 +301,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 }))
+protectedApi.route('/preview', createPreviewRoutes({ store: previewSessionStore, isEnabled: previewAvailability.isEnabled }))
app.route('/api', protectedApi)
@@ -426,8 +428,16 @@ if (ENV.PREVIEW.PORT > 0) {
port: ENV.PREVIEW.PORT,
hostname: HOST,
})
+ previewServer.on('listening', () => {
+ previewAvailability.markAvailable()
+ logger.info(`Preview gateway running on http://${HOST}:${ENV.PREVIEW.PORT}`)
+ })
+ previewServer.on('error', (error: Error) => {
+ previewAvailability.markUnavailable()
+ const code = (error as NodeJS.ErrnoException).code
+ logger.warn(`Preview gateway failed to listen on port ${ENV.PREVIEW.PORT}${code ? ` (${code})` : ''}; preview disabled`)
+ })
previewGateway.injectWebSocket(previewServer)
- logger.info(`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/preview.ts b/backend/src/routes/preview.ts
index 935282c7..b5dce61d 100644
--- a/backend/src/routes/preview.ts
+++ b/backend/src/routes/preview.ts
@@ -6,15 +6,34 @@ import { canonicalPathSync } from '../utils/fs-safe'
import { listListeningPorts, isReservedPreviewPort, type PreviewPortEntry } from '../services/preview/ports'
import { PreviewSessionStore } from '../services/preview/gateway'
+export interface PreviewAvailability {
+ isEnabled: () => boolean
+ markAvailable: () => void
+ markUnavailable: () => void
+}
+
+/**
+ * Tracks whether the preview gateway is usable at request time. It starts in
+ * the given state and is flipped by the server lifecycle: available once the
+ * port is bound, unavailable after a bind error.
+ */
+export function createPreviewAvailability(initialEnabled: boolean): PreviewAvailability {
+ let enabled = initialEnabled
+ return {
+ isEnabled: () => enabled,
+ markAvailable: () => { enabled = true },
+ markUnavailable: () => { enabled = false },
+ }
+}
+
export interface PreviewRoutesDeps {
- enabled: boolean
+ isEnabled: () => boolean
listPorts: () => Promise
store: PreviewSessionStore
}
-function isInsideDirectory(cwd: string | null, canonicalDirectory: string | null): boolean {
- if (!cwd || !canonicalDirectory) return false
- const canonicalCwd = canonicalPathSync(cwd)
+function isInsideDirectory(canonicalCwd: string | null, canonicalDirectory: string | null): boolean {
+ if (!canonicalCwd || !canonicalDirectory) return false
if (canonicalCwd === canonicalDirectory) return true
const prefix = canonicalDirectory.endsWith(path.sep) ? canonicalDirectory : `${canonicalDirectory}${path.sep}`
return canonicalCwd.startsWith(prefix)
@@ -22,7 +41,7 @@ function isInsideDirectory(cwd: string | null, canonicalDirectory: string | null
export function createPreviewRoutes(deps: Partial = {}) {
const resolvedDeps: PreviewRoutesDeps = {
- enabled: deps.enabled ?? ENV.PREVIEW.PORT > 0,
+ isEnabled: deps.isEnabled ?? (() => ENV.PREVIEW.PORT > 0),
listPorts: deps.listPorts ?? (() => listListeningPorts()),
store: deps.store ?? new PreviewSessionStore(),
}
@@ -32,13 +51,15 @@ export function createPreviewRoutes(deps: Partial = {}) {
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
+ const decorated = ports.map((entry) => ({
+ ...entry,
+ inDirectory: isInsideDirectory(entry.cwd ? canonicalPathSync(entry.cwd) : null, canonicalDirectory),
+ }))
+ decorated.sort((left, right) => {
+ if (left.inDirectory !== right.inDirectory) return left.inDirectory ? -1 : 1
return left.port - right.port
})
- return c.json({ enabled: resolvedDeps.enabled, ports: sorted })
+ return c.json({ enabled: resolvedDeps.isEnabled(), ports: decorated })
})
app.post('/sessions', async (c) => {
@@ -48,7 +69,7 @@ export function createPreviewRoutes(deps: Partial = {}) {
return c.json({ error: 'Invalid request' }, 400)
}
- if (!resolvedDeps.enabled) {
+ if (!resolvedDeps.isEnabled()) {
return c.json({ error: 'Preview is disabled' }, 503)
}
diff --git a/backend/src/routes/repo-directory.ts b/backend/src/routes/repo-directory.ts
new file mode 100644
index 00000000..dae4cf28
--- /dev/null
+++ b/backend/src/routes/repo-directory.ts
@@ -0,0 +1,53 @@
+import type { Context } from 'hono'
+import type { Database } from 'bun:sqlite'
+import type { Repo } from '@opencode-manager/shared/types'
+import { getSiblingRepos, resolveRepoOrAssistant, resolveRepoWorkingDirectory } from '../services/repo'
+import { getRepoById } from '../db/queries'
+import type { GitAuthService } from '../services/git-auth'
+import type { OpenCodeClient } from '../services/opencode/client'
+
+export interface RepoDirectoryDeps {
+ database: Database
+ gitAuthService: GitAuthService
+ openCodeClient: OpenCodeClient
+}
+
+export interface RepoDirectoryOptions {
+ allowAssistant: boolean
+}
+
+export async function resolveRepoRequestDirectory(
+ c: Context,
+ deps: RepoDirectoryDeps,
+ repoIdParam: string,
+ directory: string | undefined,
+ options: RepoDirectoryOptions,
+): Promise<{ repo: Repo; directory: string } | Response> {
+ const id = Number.parseInt(repoIdParam, 10)
+ if (Number.isNaN(id)) {
+ return c.json({ error: 'Invalid repo id' }, 400)
+ }
+
+ const repo = options.allowAssistant
+ ? resolveRepoOrAssistant(deps.database, id)
+ : getRepoById(deps.database, id)
+ if (!repo || repo.cloneStatus !== 'ready') {
+ return c.json({ error: 'Repo not found' }, 404)
+ }
+
+ const resolved = await resolveRepoWorkingDirectory(repo, directory, () =>
+ getSiblingRepos(
+ deps.database,
+ repo.id,
+ deps.gitAuthService.getGitEnvironment(),
+ deps.openCodeClient,
+ { includeBranch: false },
+ ),
+ )
+
+ if (!resolved) {
+ return c.json({ error: 'Directory is not part of this repository' }, 400)
+ }
+
+ return { repo, directory: resolved }
+}
diff --git a/backend/src/routes/repo-project-config.ts b/backend/src/routes/repo-project-config.ts
index 7a87dec3..0029928c 100644
--- a/backend/src/routes/repo-project-config.ts
+++ b/backend/src/routes/repo-project-config.ts
@@ -1,18 +1,12 @@
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, TrustRepoConfigRequestSchema, MoveProjectItemRequestSchema, RunProjectActionRequestSchema } 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'
+import { handleServiceError } from '../utils/route-helpers'
+import { resolveRepoRequestDirectory } from './repo-directory'
export interface RepoProjectConfigDeps {
database: Database
@@ -22,17 +16,6 @@ export interface RepoProjectConfigDeps {
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,
@@ -49,45 +32,16 @@ export function createRepoProjectConfigRoutes(
}
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'))
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
+ allowAssistant: false,
+ })
if (resolved instanceof Response) return resolved
try {
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
} catch (error: unknown) {
- return handleProjectConfigError(c, error)
+ return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
}
})
@@ -98,7 +52,9 @@ export function createRepoProjectConfigRoutes(
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
}
- const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory'))
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
+ allowAssistant: false,
+ })
if (resolved instanceof Response) return resolved
try {
@@ -106,7 +62,7 @@ export function createRepoProjectConfigRoutes(
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)
+ return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
}
})
@@ -117,7 +73,9 @@ export function createRepoProjectConfigRoutes(
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
}
- const resolved = await resolveRepoDirectory(c, c.req.param('id'), c.req.query('directory'))
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
+ allowAssistant: false,
+ })
if (resolved instanceof Response) return resolved
try {
@@ -125,7 +83,7 @@ export function createRepoProjectConfigRoutes(
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 handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
}
})
@@ -136,14 +94,16 @@ export function createRepoProjectConfigRoutes(
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
}
- const resolved = await resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory)
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
+ allowAssistant: false,
+ })
if (resolved instanceof Response) return resolved
try {
await deps.projectConfigService.trustRepoFile(resolved.repo, resolved.directory, parsed.data.hash)
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
} catch (error: unknown) {
- return handleProjectConfigError(c, error)
+ return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
}
})
@@ -154,14 +114,16 @@ export function createRepoProjectConfigRoutes(
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
}
- const resolved = await resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory)
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
+ allowAssistant: false,
+ })
if (resolved instanceof Response) return resolved
try {
await deps.projectConfigService.moveItem(resolved.repo, resolved.directory, parsed.data)
return c.json(await deps.projectConfigService.getConfig(resolved.repo, resolved.directory))
} catch (error: unknown) {
- return handleProjectConfigError(c, error)
+ return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
}
})
@@ -172,7 +134,9 @@ export function createRepoProjectConfigRoutes(
return c.json({ error: 'Invalid request', details: parsed.error.flatten() }, 400)
}
- const resolved = await resolveRepoDirectory(c, c.req.param('id'), parsed.data.directory)
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
+ allowAssistant: false,
+ })
if (resolved instanceof Response) return resolved
try {
@@ -184,7 +148,7 @@ export function createRepoProjectConfigRoutes(
)
return c.json(response)
} catch (error: unknown) {
- return handleProjectConfigError(c, error)
+ return handleServiceError(c, error, 'Project config request failed', ProjectConfigError)
}
})
diff --git a/backend/src/routes/repo-terminal-socket.ts b/backend/src/routes/repo-terminal-socket.ts
index 635784b2..c2ec1234 100644
--- a/backend/src/routes/repo-terminal-socket.ts
+++ b/backend/src/routes/repo-terminal-socket.ts
@@ -2,25 +2,21 @@ import { Hono } from 'hono'
import type { MiddlewareHandler } from 'hono'
import type { Database } from 'bun:sqlite'
import type { UpgradeWebSocket } from 'hono/ws'
-import { ENV } from '@opencode-manager/shared/config/env'
+import { getTrustedOrigins } from '@opencode-manager/shared/config/env'
import type { GitAuthService } from '../services/git-auth'
import type { OpenCodeClient } from '../services/opencode/client'
import type { TerminalService } from '../services/terminal'
-import type { WebSocketBridge } from '../utils/websocket-bridge'
+import { forwardPeerMessage, peerBufferedAmount, type WebSocketBridge } from '../utils/websocket-bridge'
import { getErrorMessage } from '../utils/error-utils'
-import { resolveTerminalDirectory } from './repo-terminals'
+import { resolveRepoRequestDirectory } from './repo-directory'
-export interface RepoTerminalSocketVariables {
+interface RepoTerminalSocketVariables {
terminalDirectory: string
terminalCursor: number | undefined
}
const MAX_CLOSE_REASON_BYTES = 120
-const DEFAULT_TRUSTED_ORIGINS = ENV.AUTH.TRUSTED_ORIGINS.split(',')
- .map((origin) => origin.trim())
- .filter(Boolean)
-
function isAllowedUpgradeOrigin(
origin: string | undefined,
trustedOrigins: readonly string[],
@@ -50,7 +46,7 @@ export function createRepoTerminalSocketRoutes(
openCodeClient: OpenCodeClient,
terminalService: TerminalService,
upgradeWebSocket: UpgradeWebSocket,
- trustedOrigins: readonly string[] = DEFAULT_TRUSTED_ORIGINS,
+ trustedOrigins: readonly string[] = getTrustedOrigins(),
) {
const app = new Hono<{ Variables: RepoTerminalSocketVariables }>()
const deps = { database, gitAuthService, openCodeClient }
@@ -65,7 +61,9 @@ export function createRepoTerminalSocketRoutes(
return c.json({ error: 'Invalid cursor' }, 400)
}
- const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id') ?? '', c.req.query('directory'))
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id') ?? '', c.req.query('directory'), {
+ allowAssistant: true,
+ })
if (resolved instanceof Response) return resolved
c.set('terminalDirectory', resolved.directory)
@@ -91,6 +89,7 @@ export function createRepoTerminalSocketRoutes(
.connect(directory, ptyID, cursor, {
send: (data) => ws.send(data),
close: (code, reason) => ws.close(code, reason),
+ bufferedAmount: () => peerBufferedAmount(ws),
})
.then((connected) => {
if (closed) {
@@ -107,19 +106,7 @@ export function createRepoTerminalSocketRoutes(
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)
- }
+ await forwardPeerMessage(bridge, event.data)
},
onClose() {
closed = true
diff --git a/backend/src/routes/repo-terminals.ts b/backend/src/routes/repo-terminals.ts
index 6589157a..246d47d7 100644
--- a/backend/src/routes/repo-terminals.ts
+++ b/backend/src/routes/repo-terminals.ts
@@ -1,57 +1,16 @@
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'
+import { resolveRepoRequestDirectory, type RepoDirectoryDeps } from './repo-directory'
-export interface TerminalDirectoryDeps {
- database: Database
- gitAuthService: GitAuthService
- openCodeClient: OpenCodeClient
-}
-
-export interface TerminalRoutesDeps extends TerminalDirectoryDeps {
+export interface TerminalRoutesDeps extends RepoDirectoryDeps {
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,
@@ -62,7 +21,9 @@ export function createRepoTerminalRoutes(
const app = new Hono()
app.get('/:id/terminals', async (c) => {
- const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), c.req.query('directory'))
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
+ allowAssistant: true,
+ })
if (resolved instanceof Response) return resolved
try {
@@ -80,7 +41,9 @@ export function createRepoTerminalRoutes(
return c.json({ error: 'Invalid request' }, 400)
}
- const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), parsed.data.directory)
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
+ allowAssistant: true,
+ })
if (resolved instanceof Response) return resolved
try {
@@ -101,7 +64,9 @@ export function createRepoTerminalRoutes(
return c.json({ error: 'Invalid request' }, 400)
}
- const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), parsed.data.directory)
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), parsed.data.directory, {
+ allowAssistant: true,
+ })
if (resolved instanceof Response) return resolved
const ptyID = c.req.param('ptyID')
@@ -119,7 +84,9 @@ export function createRepoTerminalRoutes(
})
app.delete('/:id/terminals/:ptyID', async (c) => {
- const resolved = await resolveTerminalDirectory(c, deps, c.req.param('id'), c.req.query('directory'))
+ const resolved = await resolveRepoRequestDirectory(c, deps, c.req.param('id'), c.req.query('directory'), {
+ allowAssistant: true,
+ })
if (resolved instanceof Response) return resolved
const ptyID = c.req.param('ptyID')
diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts
index 937904b3..8fa62a28 100644
--- a/backend/src/routes/repos.ts
+++ b/backend/src/routes/repos.ts
@@ -45,6 +45,39 @@ async function removeDirectoryTerminals(terminalService: TerminalService, direct
}
}
+async function listWorkspaceSiblings(
+ database: Database,
+ repoId: number,
+ gitAuthService: GitAuthService,
+ openCodeClient: OpenCodeClient,
+): Promise> {
+ const siblings = await repoService.getSiblingRepos(
+ database,
+ repoId,
+ gitAuthService.getGitEnvironment(),
+ openCodeClient,
+ { includeBranch: false },
+ )
+ return siblings.filter(isWorktreeSibling)
+}
+
+async function removeWorkspaceSiblingTerminals(
+ database: Database,
+ repoId: number,
+ gitAuthService: GitAuthService,
+ openCodeClient: OpenCodeClient,
+ terminalService: TerminalService,
+): Promise {
+ let siblings: Array
+ try {
+ siblings = await listWorkspaceSiblings(database, repoId, gitAuthService, openCodeClient)
+ } catch (error: unknown) {
+ logger.warn(`Failed to list OpenCode workspace siblings for repo ${repoId}:`, error)
+ return
+ }
+ await Promise.all(siblings.map((sibling) => removeDirectoryTerminals(terminalService, sibling.fullPath)))
+}
+
export function createRepoRoutes(
database: Database,
gitAuthService: GitAuthService,
@@ -293,8 +326,8 @@ app.get('/', async (c) => {
if (!parsed.success) return c.json({ error: 'directory is required' }, 400)
const directory = parsed.data.directory
- const siblings = await repoService.getSiblingRepos(database, id, gitAuthService.getGitEnvironment(), openCodeClient)
- const worktree = repoService.findSiblingByDirectory(siblings.filter(isWorktreeSibling), directory)
+ const siblings = await listWorkspaceSiblings(database, id, gitAuthService, openCodeClient)
+ const worktree = repoService.findSiblingByDirectory(siblings, directory)
if (!worktree) return c.json({ error: 'Not a deletable worktree of this repo' }, 400)
await removeDirectoryTerminals(terminalService, worktree.fullPath)
@@ -362,6 +395,8 @@ app.get('/', async (c) => {
await removeDirectoryTerminals(terminalService, repo.fullPath)
+ await removeWorkspaceSiblingTerminals(database, id, gitAuthService, openCodeClient, terminalService)
+
await repoService.deleteRepoFiles(database, id)
return c.json({ success: true })
diff --git a/backend/src/services/opencode/client.ts b/backend/src/services/opencode/client.ts
index 35c2c2b3..98777a4a 100644
--- a/backend/src/services/opencode/client.ts
+++ b/backend/src/services/opencode/client.ts
@@ -1,6 +1,7 @@
import { logger } from '../../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import { createOpenCodeApi, type OpenCodeApi } from '@opencode-manager/shared/opencode'
+import { filterProxyHeaders } from '../../utils/proxy-headers'
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
import { getOpenCodeUpstreamBaseUrl, withDefaultOpenCodeDirectory } from './upstream'
@@ -73,13 +74,7 @@ export class FetchOpenCodeClient implements OpenCodeClient {
body: req.body,
})
- const filteredHeaders: Record = {}
- const skipHeaders = new Set(['connection', 'transfer-encoding', 'content-encoding', 'content-length'])
- response.headers.forEach((value, key) => {
- if (!skipHeaders.has(key.toLowerCase())) {
- filteredHeaders[key] = value
- }
- })
+ const filteredHeaders = filterProxyHeaders(response.headers)
const noBodyStatuses = new Set([101, 204, 205, 304])
if (noBodyStatuses.has(response.status)) {
diff --git a/backend/src/services/preview/gateway.ts b/backend/src/services/preview/gateway.ts
index 23966858..20387bc7 100644
--- a/backend/src/services/preview/gateway.ts
+++ b/backend/src/services/preview/gateway.ts
@@ -2,17 +2,28 @@ import { randomBytes } from 'node:crypto'
import { Hono } from 'hono'
import type { Context, MiddlewareHandler } from 'hono'
import { createNodeWebSocket, type NodeWebSocket } from '@hono/node-ws'
+import type { PreviewPort } from '@opencode-manager/shared/schemas'
+import { AUTH_COOKIE_PREFIX } from '../../auth/cookies'
import { buildProxyResponseHeaders, filterProxyHeaders } from '../../utils/proxy-headers'
-import { bridgeWebSocket, type WebSocketBridge } from '../../utils/websocket-bridge'
+import {
+ bridgeWebSocket,
+ forwardPeerMessage,
+ peerBufferedAmount,
+ type WebSocketBridge,
+} from '../../utils/websocket-bridge'
export const PREVIEW_COOKIE = 'ocm_preview'
const START_TOKEN_TTL_MS = 60_000
const SESSION_TTL_MS = 12 * 60 * 60 * 1000
-const MANAGER_COOKIE_PREFIXES = ['opencode.', '__Secure-opencode.', '__Host-opencode.']
+const MANAGER_COOKIE_PREFIXES = [
+ `${AUTH_COOKIE_PREFIX}.`,
+ `__Secure-${AUTH_COOKIE_PREFIX}.`,
+ `__Host-${AUTH_COOKIE_PREFIX}.`,
+]
-export type PreviewHost = '127.0.0.1' | '::1'
+export type PreviewHost = PreviewPort['host']
export interface PreviewSession {
id: string
@@ -76,21 +87,32 @@ export class PreviewSessionStore {
}
}
-export function stripManagerCookies(cookieHeader: string | undefined): string | undefined {
+function readCookieName(cookie: string): string {
+ const separator = cookie.indexOf('=')
+ return (separator === -1 ? cookie : cookie.slice(0, separator)).trim()
+}
+
+function isManagerCookieName(name: string): boolean {
+ return name === PREVIEW_COOKIE || MANAGER_COOKIE_PREFIXES.some((prefix) => name.startsWith(prefix))
+}
+
+function stripManagerCookies(cookieHeader: string | undefined): string | undefined {
if (!cookieHeader) return undefined
const kept = cookieHeader
.split(';')
.map((part) => part.trim())
- .filter((part) => {
- 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))
- })
+ .filter((part) => part.length > 0 && !isManagerCookieName(readCookieName(part)))
return kept.length > 0 ? kept.join('; ') : undefined
}
+function stripPreviewSetCookies(headers: Headers): void {
+ const kept = headers.getSetCookie().filter((cookie) => !isManagerCookieName(readCookieName(cookie)))
+ headers.delete('set-cookie')
+ for (const cookie of kept) {
+ headers.append('set-cookie', cookie)
+ }
+}
+
function readPreviewCookie(cookieHeader: string | undefined): string | null {
if (!cookieHeader) return null
for (const part of cookieHeader.split(';')) {
@@ -140,8 +162,24 @@ function isWebSocketUpgrade(c: Context): boolean {
}
function upstreamWebSocketUrl(session: PreviewSession, requestUrl: URL): string {
+ return `${previewUpstreamOrigin(session, 'ws')}${requestUrl.pathname}${requestUrl.search}`
+}
+
+function previewUpstreamOrigin(session: PreviewSession, protocol: 'http' | 'ws'): string {
const targetHost = session.host === '::1' ? '[::1]' : 'localhost'
- return `ws://${targetHost}:${session.port}${requestUrl.pathname}${requestUrl.search}`
+ return `${protocol}://${targetHost}:${session.port}`
+}
+
+function resolveRedirectPath(requestUrl: URL, requestedPath: string): string {
+ if (!requestedPath) return '/'
+ let resolved: URL
+ try {
+ resolved = new URL(requestedPath, requestUrl)
+ } catch {
+ return '/'
+ }
+ if (resolved.origin !== requestUrl.origin) return '/'
+ return `${resolved.pathname}${resolved.search}${resolved.hash}`
}
function parseProtocols(header: string | undefined): string[] {
@@ -163,10 +201,11 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
}
const requestedPath = c.req.query('path') ?? ''
- const location = requestedPath.startsWith('/') && !requestedPath.startsWith('//') ? requestedPath : '/'
+ const requestUrl = new URL(c.req.url)
+ const location = resolveRedirectPath(requestUrl, requestedPath)
const forwardedProto = c.req.header('x-forwarded-proto')?.toLowerCase()
- const isSecure = forwardedProto === 'https' || new URL(c.req.url).protocol === 'https:'
+ const isSecure = forwardedProto === 'https' || requestUrl.protocol === 'https:'
const cookie = `${PREVIEW_COOKIE}=${sessionId}; HttpOnly; SameSite=Lax; Path=/${isSecure ? '; Secure' : ''}`
return new Response(null, { status: 302, headers: { location, 'set-cookie': cookie } })
@@ -212,22 +251,12 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
bridge = bridgeWebSocket(upstream, {
send: (data) => ws.send(data),
close: (code, reason) => ws.close(code, reason),
+ bufferedAmount: () => peerBufferedAmount(ws),
})
},
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)
- }
+ await forwardPeerMessage(bridge, event.data)
},
onClose() {
bridge?.close()
@@ -245,8 +274,7 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
}
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 target = `${previewUpstreamOrigin(session, 'http')}${url.pathname}${url.search}`
const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
@@ -256,6 +284,7 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
headers['content-encoding'] = contentEncoding
}
headers['host'] = `localhost:${session.port}`
+ headers['accept-encoding'] = 'identity'
const strippedCookies = stripManagerCookies(cookieHeader)
if (strippedCookies) {
headers['cookie'] = strippedCookies
@@ -275,6 +304,7 @@ export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typ
})
const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers)
+ stripPreviewSetCookies(responseHeaders)
const location = responseHeaders.get('location')
if (location) {
const rewritten = rewriteLocalLocation(location, session.port)
diff --git a/backend/src/services/preview/ports.ts b/backend/src/services/preview/ports.ts
index 91f4ca65..2ddfb45c 100644
--- a/backend/src/services/preview/ports.ts
+++ b/backend/src/services/preview/ports.ts
@@ -1,14 +1,9 @@
import { readFile, readdir, readlink } from 'node:fs/promises'
import { ENV } from '@opencode-manager/shared/config/env'
+import type { PreviewPort } from '@opencode-manager/shared/schemas'
import { executeCommand } from '../../utils/process'
-export interface PreviewPortEntry {
- port: number
- host: '127.0.0.1' | '::1'
- pid: number | null
- command: string | null
- cwd: string | null
-}
+export type PreviewPortEntry = Omit
export interface ParsedProcNetSocket {
port: number
@@ -192,8 +187,9 @@ function dedupeByPort(entries: PreviewPortEntry[]): PreviewPortEntry[] {
return result
}
-async function mapInodesToPids(deps: PortDiscoveryDeps): Promise
))}
- {config.repoFile.exists && !config.repoFile.trusted && config.repoFile.hash && (
-
-
-
- Repository commands are not trusted
+ {config.repoFile.exists &&
+ !config.repoFile.trusted &&
+ config.repoFile.hash &&
+ config.repoFile.executable && (
+
+
+
+ Repository commands are not trusted
+
+
+ This repository defines commands that run on your machine. Review and trust them to enable.
+
+
+
-
- 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/components/repo/TrustExecutableList.tsx b/frontend/src/components/repo/TrustExecutableList.tsx
new file mode 100644
index 00000000..fb716380
--- /dev/null
+++ b/frontend/src/components/repo/TrustExecutableList.tsx
@@ -0,0 +1,37 @@
+import type { ProjectConfigResponse } from '@opencode-manager/shared/types'
+
+type RepoFileExecutable = NonNullable
+
+export function TrustExecutableList({ executable }: { executable: RepoFileExecutable }) {
+ return (
+
+ {executable.actions.length > 0 && (
+
+
Actions
+
+ {executable.actions.map((action) => (
+ -
+
{action.name}
+ {action.command}
+ {action.url && {action.url}
}
+ {action.autoOpenUrl && Opens URL automatically
}
+
+ ))}
+
+
+ )}
+ {executable.setup.length > 0 && (
+
+
Worktree setup commands
+
+ {executable.setup.map((command, index) => (
+ -
+ {command}
+
+ ))}
+
+
+ )}
+
+ )
+}
diff --git a/frontend/src/components/repo/projectActionIcons.ts b/frontend/src/components/repo/projectActionIcons.ts
new file mode 100644
index 00000000..3a9c98a1
--- /dev/null
+++ b/frontend/src/components/repo/projectActionIcons.ts
@@ -0,0 +1,27 @@
+import {
+ Bug,
+ CheckCircle2,
+ FlaskConical,
+ Hammer,
+ Play,
+ Rocket,
+ Server,
+ SquareTerminal,
+ type LucideIcon,
+} from 'lucide-react'
+import type { ProjectActionIcon } from '@opencode-manager/shared/types'
+
+export 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 },
+]
+
+export function actionIcon(icon: ProjectActionIcon | undefined): LucideIcon {
+ return ACTION_ICON_OPTIONS.find((option) => option.value === icon)?.Icon ?? Play
+}
diff --git a/frontend/src/components/terminal/TerminalPanel.test.tsx b/frontend/src/components/terminal/TerminalPanel.test.tsx
index 9e7e5f87..de031cee 100644
--- a/frontend/src/components/terminal/TerminalPanel.test.tsx
+++ b/frontend/src/components/terminal/TerminalPanel.test.tsx
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { 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'
@@ -91,6 +91,14 @@ describe('TerminalPanel', () => {
mockTerminalHooks([])
})
+ it('renders a loading fallback before the lazy terminal view resolves', async () => {
+ mockTerminalHooks([runningTerminal])
+ renderPanel()
+
+ expect(screen.getByText('Loading terminal...')).toBeInTheDocument()
+ expect(await screen.findAllByTestId('terminal-view')).toHaveLength(1)
+ })
+
it('auto-creates a terminal when the directory has none', () => {
mockTerminalHooks([])
renderPanel()
@@ -122,22 +130,23 @@ describe('TerminalPanel', () => {
expect(createMutate).toHaveBeenCalledWith({ directory: '/repo' }, expect.any(Object))
})
- it('exposes an accessible name for the mobile panel close control', () => {
+ it('exposes an accessible name for the mobile panel close control', async () => {
mockTerminalHooks([runningTerminal])
vi.mocked(useMobile).mockReturnValue(true)
const onClose = vi.fn()
renderPanel('/repos/1?dialog=terminal', onClose)
+ await screen.findAllByTestId('terminal-view')
fireEvent.click(screen.getByRole('button', { name: 'Close terminal panel' }))
expect(onClose).toHaveBeenCalledTimes(1)
})
- it('activates the terminal referenced by the terminal URL param', () => {
+ it('activates the terminal referenced by the terminal URL param', async () => {
mockTerminalHooks([runningTerminal, exitedTerminal])
renderPanel('/repos/1?dialog=terminal&terminal=t2')
- const views = screen.getAllByTestId('terminal-view')
+ const views = await screen.findAllByTestId('terminal-view')
const active = views.find((view) => view.getAttribute('data-pty-id') === 't2')
const inactive = views.find((view) => view.getAttribute('data-pty-id') === 't1')
@@ -145,16 +154,18 @@ describe('TerminalPanel', () => {
expect(inactive).toHaveAttribute('data-active', 'false')
})
- it('shows an exited badge with the exit code', () => {
+ it('shows an exited badge with the exit code', async () => {
mockTerminalHooks([exitedTerminal])
renderPanel()
+ await screen.findAllByTestId('terminal-view')
expect(screen.getByText('exited (0)')).toBeInTheDocument()
})
- it('asks for confirmation before closing a running terminal', () => {
+ it('asks for confirmation before closing a running terminal', async () => {
mockTerminalHooks([runningTerminal])
renderPanel()
+ await screen.findAllByTestId('terminal-view')
fireEvent.click(screen.getByLabelText('Close Terminal'))
@@ -166,9 +177,10 @@ describe('TerminalPanel', () => {
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't1', directory: '/repo' }, expect.any(Object))
})
- it('removes an exited terminal without confirmation', () => {
+ it('removes an exited terminal without confirmation', async () => {
mockTerminalHooks([exitedTerminal])
renderPanel()
+ await screen.findAllByTestId('terminal-view')
fireEvent.click(screen.getByLabelText('Close Build'))
@@ -176,17 +188,19 @@ describe('TerminalPanel', () => {
expect(removeMutate).toHaveBeenCalledWith({ ptyID: 't2', directory: '/repo' }, expect.any(Object))
})
- it('renders the key bar only on mobile', () => {
+ it('renders the key bar only on mobile', async () => {
mockTerminalHooks([runningTerminal])
vi.mocked(useMobile).mockReturnValue(false)
- renderPanel()
+ const first = renderPanel()
+ await screen.findAllByTestId('terminal-view')
expect(screen.queryByTestId('terminal-key-bar')).not.toBeInTheDocument()
- cleanup()
+ first.unmount()
vi.mocked(useMobile).mockReturnValue(true)
renderPanel()
+ await screen.findAllByTestId('terminal-view')
expect(screen.getByTestId('terminal-key-bar')).toBeInTheDocument()
})
})
diff --git a/frontend/src/components/terminal/TerminalPanel.tsx b/frontend/src/components/terminal/TerminalPanel.tsx
index b4dad2d6..068ed0b8 100644
--- a/frontend/src/components/terminal/TerminalPanel.tsx
+++ b/frontend/src/components/terminal/TerminalPanel.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { lazy, Suspense, 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'
@@ -11,17 +11,20 @@ import { useUrlParams } from '@/hooks/useUrlParams'
import { openUrlFromManager } from '@/lib/open-url'
import { cn } from '@/lib/utils'
import { TerminalKeyBar } from './TerminalKeyBar'
-import { TerminalView, type TerminalViewHandle } from './TerminalView'
+import type { TerminalViewHandle } from './TerminalView'
+
+const TerminalView = lazy(() =>
+ import('./TerminalView').then((module) => ({ default: module.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) {
+export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPanelProps) {
const isMobile = useMobile()
const { searchParams, updateParams } = useUrlParams()
const openPreview = useOpenPreview()
@@ -183,23 +186,31 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }
{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 ?? handleOpenLink}
- onExited={() => { void refetch() }}
- />
- ))
+
+ Loading terminal...
+
+ }
+ >
+ {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={handleOpenLink}
+ onExited={() => { void refetch() }}
+ />
+ ))}
+
)}
diff --git a/frontend/src/components/terminal/TerminalView.test.tsx b/frontend/src/components/terminal/TerminalView.test.tsx
index 43e48e91..e7c44f8a 100644
--- a/frontend/src/components/terminal/TerminalView.test.tsx
+++ b/frontend/src/components/terminal/TerminalView.test.tsx
@@ -1,6 +1,7 @@
import { createRef, type ComponentProps } from 'react'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render } from '@testing-library/react'
+import { resizeTerminal } from '@/api/terminals'
import { TerminalView, type TerminalViewHandle } from './TerminalView'
const xterm = vi.hoisted(() => {
@@ -64,6 +65,7 @@ function renderView(overrides: Partial> = {}
active
ctrlArmed={false}
onCtrlConsumed={onCtrlConsumed}
+ onOpenLink={vi.fn()}
onExited={vi.fn()}
{...overrides}
/>
@@ -110,6 +112,7 @@ describe('TerminalView input handling', () => {
active: true,
ctrlArmed: true,
onCtrlConsumed,
+ onOpenLink: vi.fn(),
onExited: vi.fn(),
}
@@ -131,3 +134,84 @@ describe('TerminalView input handling', () => {
expect(onCtrlConsumed).toHaveBeenCalledTimes(1)
})
})
+
+class TestResizeObserver {
+ static instances: TestResizeObserver[] = []
+ readonly callback: ResizeObserverCallback
+
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback
+ TestResizeObserver.instances.push(this)
+ }
+
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+
+ trigger() {
+ this.callback([], this as unknown as ResizeObserver)
+ }
+}
+
+function setVisibleSize(container: HTMLElement) {
+ Object.defineProperty(container, 'clientWidth', { value: 800, configurable: true })
+ Object.defineProperty(container, 'clientHeight', { value: 400, configurable: true })
+}
+
+describe('TerminalView resize', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ TestResizeObserver.instances = []
+ vi.stubGlobal('ResizeObserver', TestResizeObserver)
+ vi.useFakeTimers()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ it('sends a resize only when the fitted size changes', () => {
+ const { view } = renderView()
+ const container = view.container.querySelector('[data-terminal-id="t1"]') as HTMLElement
+ setVisibleSize(container)
+
+ act(() => {
+ vi.advanceTimersByTime(150)
+ })
+ expect(resizeTerminal).toHaveBeenCalledTimes(1)
+
+ act(() => {
+ TestResizeObserver.instances[0].trigger()
+ vi.advanceTimersByTime(150)
+ })
+ act(() => {
+ TestResizeObserver.instances[0].trigger()
+ vi.advanceTimersByTime(150)
+ })
+
+ expect(resizeTerminal).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not send a resize while the view is hidden', () => {
+ const { view } = renderView({ active: false })
+ const container = view.container.querySelector('[data-terminal-id="t1"]') as HTMLElement
+ setVisibleSize(container)
+
+ act(() => {
+ vi.advanceTimersByTime(150)
+ })
+
+ expect(resizeTerminal).not.toHaveBeenCalled()
+ })
+
+ it('does not send a resize when the container has no size', () => {
+ renderView()
+
+ act(() => {
+ vi.advanceTimersByTime(150)
+ })
+
+ expect(resizeTerminal).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/components/terminal/TerminalView.tsx b/frontend/src/components/terminal/TerminalView.tsx
index 6880835a..32a234ac 100644
--- a/frontend/src/components/terminal/TerminalView.tsx
+++ b/frontend/src/components/terminal/TerminalView.tsx
@@ -14,22 +14,18 @@ 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 TerminalViewHandle {
send: (data: string) => void
}
-export interface TerminalViewProps {
+interface TerminalViewProps {
repoId: number
directory: string | undefined
ptyID: string
active: boolean
ctrlArmed: boolean
onCtrlConsumed: () => void
- onOpenLink?: (uri: string) => void
+ onOpenLink: (uri: string) => void
onExited: () => void
}
@@ -53,12 +49,15 @@ export const TerminalView = forwardRef(fu
const onExitedRef = useRef(onExited)
const isMobile = useMobile()
const isMobileRef = useRef(isMobile)
+ const activeRef = useRef(active)
+ const lastSizeRef = useRef<{ cols: number; rows: number } | null>(null)
ctrlArmedRef.current = ctrlArmed
onCtrlConsumedRef.current = onCtrlConsumed
onOpenLinkRef.current = onOpenLink
onExitedRef.current = onExited
isMobileRef.current = isMobile
+ activeRef.current = active
const handleOutput = useCallback((text: string) => {
terminalRef.current?.write(text)
@@ -105,8 +104,7 @@ export const TerminalView = forwardRef(fu
terminal.loadAddon(fitAddon)
terminal.loadAddon(
new WebLinksAddon((_event, uri) => {
- const openLink = onOpenLinkRef.current ?? defaultOpenLink
- openLink(uri)
+ onOpenLinkRef.current(uri)
}),
)
terminal.open(container)
@@ -161,12 +159,18 @@ export const TerminalView = forwardRef(fu
const terminal = terminalRef.current
const fitAddon = fitAddonRef.current
if (!terminal || !fitAddon) return
+ if (!activeRef.current) return
+ if (container.clientWidth === 0 || container.clientHeight === 0) return
try {
fitAddon.fit()
} catch {
return
}
- resizeTerminal(repoId, ptyID, { directory, cols: terminal.cols, rows: terminal.rows }).catch(() => {})
+ const size = { cols: terminal.cols, rows: terminal.rows }
+ const lastSize = lastSizeRef.current
+ if (lastSize && lastSize.cols === size.cols && lastSize.rows === size.rows) return
+ lastSizeRef.current = size
+ resizeTerminal(repoId, ptyID, { directory, cols: size.cols, rows: size.rows }).catch(() => {})
}, RESIZE_DEBOUNCE_MS)
}
diff --git a/frontend/src/hooks/useDialogParam.test.tsx b/frontend/src/hooks/useDialogParam.test.tsx
index 67834c1b..6c31925e 100644
--- a/frontend/src/hooks/useDialogParam.test.tsx
+++ b/frontend/src/hooks/useDialogParam.test.tsx
@@ -1,8 +1,8 @@
import { useEffect, useRef, useState } from 'react'
import { renderHook, act, render, screen } from '@testing-library/react'
import { MemoryRouter, useNavigate } from 'react-router-dom'
-import { useDialogParam } from './useDialogParam'
-import { describe, it, expect } from 'vitest'
+import { dialogSearch, openDialogParam, useDialogParam } from './useDialogParam'
+import { describe, it, expect, vi } from 'vitest'
describe('useDialogParam', () => {
const createWrapper = (initialEntries?: string[]) => {
@@ -114,4 +114,48 @@ describe('useDialogParam', () => {
act(() => { screen.getByText('back').click() })
expect(screen.getByTestId('dialog-state').textContent).toBe('closed')
})
+
+ it('openDialogParam sets the dialog and extra params in one push while clearing mobileTab', () => {
+ const updateParams = vi.fn()
+ openDialogParam(updateParams, 'terminal', { terminal: 'pty-1' })
+
+ expect(updateParams).toHaveBeenCalledTimes(1)
+ const [updater, mode] = updateParams.mock.calls[0]
+ expect(mode).toBe('push')
+
+ const params = new URLSearchParams('mobileTab=more&keep=1')
+ updater(params)
+
+ expect(params.get('dialog')).toBe('terminal')
+ expect(params.get('terminal')).toBe('pty-1')
+ expect(params.get('keep')).toBe('1')
+ expect(params.has('mobileTab')).toBe(false)
+ })
+
+ it('openDialogParam without extra params only sets the dialog', () => {
+ const updateParams = vi.fn()
+ openDialogParam(updateParams, 'mcp')
+
+ const [updater] = updateParams.mock.calls[0]
+ const params = new URLSearchParams()
+ updater(params)
+
+ expect(params.get('dialog')).toBe('mcp')
+ expect([...params.keys()]).toEqual(['dialog'])
+ })
+
+ it('dialogSearch builds a query string from the dialog name and extra params', () => {
+ expect(dialogSearch('terminal')).toBe('?dialog=terminal')
+ expect(dialogSearch('terminal', { terminal: 'pty-1' })).toBe('?dialog=terminal&terminal=pty-1')
+ expect(dialogSearch('preview', { previewPort: '5173', previewPath: '/' })).toBe(
+ '?dialog=preview&previewPort=5173&previewPath=%2F',
+ )
+ })
+
+ it('dialogSearch URL-encodes extra params and omits mobileTab', () => {
+ const search = dialogSearch('terminal', { terminal: 'pty 1/2' })
+
+ expect(search).toBe('?dialog=terminal&terminal=pty+1%2F2')
+ expect(search).not.toContain('mobileTab')
+ })
})
diff --git a/frontend/src/hooks/useDialogParam.ts b/frontend/src/hooks/useDialogParam.ts
index 912facda..e0a0d7c8 100644
--- a/frontend/src/hooks/useDialogParam.ts
+++ b/frontend/src/hooks/useDialogParam.ts
@@ -1,12 +1,32 @@
import { useCallback } from 'react'
import { useUrlParams } from './useUrlParams'
+function setDialogParams(
+ params: URLSearchParams,
+ name: string,
+ extraParams?: Record,
+): void {
+ params.set('dialog', name)
+ if (extraParams) {
+ for (const [key, value] of Object.entries(extraParams)) {
+ params.set(key, value)
+ }
+ }
+}
+
+export function dialogSearch(name: string, extraParams?: Record): string {
+ const params = new URLSearchParams()
+ setDialogParams(params, name, extraParams)
+ return `?${params.toString()}`
+}
+
export function openDialogParam(
updateParams: ReturnType['updateParams'],
name: string,
+ extraParams?: Record,
): void {
updateParams((p) => {
- p.set('dialog', name)
+ setDialogParams(p, name, extraParams)
p.delete('mobileTab')
}, 'push')
}
diff --git a/frontend/src/hooks/useOpenPreview.ts b/frontend/src/hooks/useOpenPreview.ts
index de4b6bcc..8b225d06 100644
--- a/frontend/src/hooks/useOpenPreview.ts
+++ b/frontend/src/hooks/useOpenPreview.ts
@@ -1,4 +1,5 @@
import { useCallback } from 'react'
+import { openDialogParam } from './useDialogParam'
import { useUrlParams } from './useUrlParams'
export function useOpenPreview(): (port: number, path?: string) => void {
@@ -6,12 +7,10 @@ export function useOpenPreview(): (port: number, path?: string) => void {
return useCallback(
(port: number, path = '/') => {
- updateParams((params) => {
- params.set('dialog', 'preview')
- params.set('previewPort', String(port))
- params.set('previewPath', path)
- params.delete('mobileTab')
- }, 'push')
+ openDialogParam(updateParams, 'preview', {
+ previewPort: String(port),
+ previewPath: path,
+ })
},
[updateParams],
)
diff --git a/frontend/src/hooks/useOpenTerminal.test.tsx b/frontend/src/hooks/useOpenTerminal.test.tsx
new file mode 100644
index 00000000..d5892625
--- /dev/null
+++ b/frontend/src/hooks/useOpenTerminal.test.tsx
@@ -0,0 +1,38 @@
+import { describe, it, expect } from 'vitest'
+import { act } from '@testing-library/react'
+import { renderHookWithRouterAndLocation } from '@/test/test-utils'
+import { useOpenTerminal } from './useOpenTerminal'
+
+describe('useOpenTerminal', () => {
+ it('opens the terminal dialog with the terminal id', () => {
+ const { result, capturedSearch } = renderHookWithRouterAndLocation(
+ () => useOpenTerminal(),
+ ['/repos/1'],
+ )
+
+ act(() => {
+ result.current('pty-1')
+ })
+
+ const params = new URLSearchParams(capturedSearch.current)
+ expect(params.get('dialog')).toBe('terminal')
+ expect(params.get('terminal')).toBe('pty-1')
+ })
+
+ it('merges extra params and clears mobileTab in the same navigation', () => {
+ const { result, capturedSearch } = renderHookWithRouterAndLocation(
+ () => useOpenTerminal(),
+ ['/repos/1?mobileTab=more'],
+ )
+
+ act(() => {
+ result.current('pty-2', { repoTab: 'workspaces' })
+ })
+
+ const params = new URLSearchParams(capturedSearch.current)
+ expect(params.get('dialog')).toBe('terminal')
+ expect(params.get('terminal')).toBe('pty-2')
+ expect(params.get('repoTab')).toBe('workspaces')
+ expect(params.has('mobileTab')).toBe(false)
+ })
+})
diff --git a/frontend/src/hooks/useOpenTerminal.ts b/frontend/src/hooks/useOpenTerminal.ts
new file mode 100644
index 00000000..9926ec1b
--- /dev/null
+++ b/frontend/src/hooks/useOpenTerminal.ts
@@ -0,0 +1,17 @@
+import { useCallback } from 'react'
+import { openDialogParam } from './useDialogParam'
+import { useUrlParams } from './useUrlParams'
+
+export function useOpenTerminal(): (
+ terminalId: string,
+ extraParams?: Record,
+) => void {
+ const { updateParams } = useUrlParams()
+
+ return useCallback(
+ (terminalId: string, extraParams?: Record) => {
+ openDialogParam(updateParams, 'terminal', { terminal: terminalId, ...extraParams })
+ },
+ [updateParams],
+ )
+}
diff --git a/frontend/src/lib/preview-url.test.ts b/frontend/src/lib/preview-url.test.ts
index 933e80d5..a1b142df 100644
--- a/frontend/src/lib/preview-url.test.ts
+++ b/frontend/src/lib/preview-url.test.ts
@@ -4,6 +4,7 @@ import {
getPreviewOrigin,
isSameOriginAsManager,
parseLocalDevUrl,
+ parsePort,
} from './preview-url'
const managerLocation = {
@@ -12,6 +13,20 @@ const managerLocation = {
origin: 'http://manager.local:5003',
} as Location
+describe('parsePort', () => {
+ it.each([
+ ['5173', 5173],
+ ['1', 1],
+ ['65535', 65535],
+ ])('parses %s', (value, port) => {
+ expect(parsePort(value)).toBe(port)
+ })
+
+ it.each(['', '0', '65536', 'abc', '-1', '5173.5'])('rejects %s', (value) => {
+ expect(parsePort(value)).toBeNull()
+ })
+})
+
describe('parseLocalDevUrl', () => {
it.each([
['http://localhost:5173', 5173, '/'],
diff --git a/frontend/src/lib/preview-url.ts b/frontend/src/lib/preview-url.ts
index ab22fce3..d5e41f99 100644
--- a/frontend/src/lib/preview-url.ts
+++ b/frontend/src/lib/preview-url.ts
@@ -12,7 +12,7 @@ export interface PreviewOriginInput {
publicUrl: string | null
}
-function parsePort(value: string): number | null {
+export function parsePort(value: string): number | null {
if (!value) return null
const port = Number(value)
if (!Number.isInteger(port) || port < 1 || port > 65535) return null
diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx
index cba617d8..278a563e 100644
--- a/frontend/src/pages/RepoDetail.tsx
+++ b/frontend/src/pages/RepoDetail.tsx
@@ -17,7 +17,7 @@ import { useRepoActivity } from "@/hooks/useRepoActivity";
import { useCreateRepoWorkspace, useDeleteRepoWorkspaces, useRepoSiblings } from "@/hooks/useRepoSiblings";
import { useSSE } from "@/hooks/useSSE";
import { useDialogParam } from "@/hooks/useDialogParam";
-import { useUrlParams } from "@/hooks/useUrlParams";
+import { useOpenTerminal } from "@/hooks/useOpenTerminal";
import { useWorktreeTab } from "@/hooks/useWorktreeTab";
import { WorktreeTabs } from "@/components/repo/WorktreeTabs";
import { WorkspaceManager } from "@/components/repo/WorkspaceManager";
@@ -47,7 +47,7 @@ export function RepoDetail() {
const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false);
const [activeWorkspaceDirectory, setActiveWorkspaceDirectory] = useState();
const { activeTab, setActiveTab } = useWorktreeTab();
- const { updateParams } = useUrlParams();
+ const openTerminal = useOpenTerminal();
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ["repo", repoId],
@@ -143,12 +143,7 @@ export function RepoDetail() {
notifyWorktreeSetup(workspace.worktreeSetup);
if (workspace.worktreeSetup?.status === 'started') {
const terminalId = workspace.worktreeSetup.terminal.id;
- updateParams((params) => {
- params.set('repoTab', 'workspaces');
- params.set('dialog', 'terminal');
- params.set('terminal', terminalId);
- params.delete('mobileTab');
- }, 'push');
+ openTerminal(terminalId, { repoTab: 'workspaces' });
return;
}
setActiveTab('workspaces');
diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx
index 55e224a3..92aec3e4 100644
--- a/frontend/src/pages/SessionDetail.tsx
+++ b/frontend/src/pages/SessionDetail.tsx
@@ -682,7 +682,9 @@ export function SessionDetail() {
-
+ {!isAssistantSession && (
+
+ )}
-
+ {!isAssistantSession && (
+
+ )}
{
mocks.usePreviewPorts.mockReturnValue({
data: {
enabled: true,
- ports: [{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: assistantDirectory }],
+ ports: [{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: assistantDirectory, inDirectory: true }],
},
isLoading: false,
refetch: vi.fn(),
diff --git a/shared/src/config/env.ts b/shared/src/config/env.ts
index 3b5040e8..a2806c00 100644
--- a/shared/src/config/env.ts
+++ b/shared/src/config/env.ts
@@ -167,6 +167,12 @@ export const getOpenCodeConfigFilePath = () => path.join(ENV.WORKSPACE.BASE_PATH
export const getAgentsMdPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.CONFIG_DIR, 'AGENTS.md')
export const getDatabasePath = () => ENV.DATABASE.PATH
+export const getTrustedOrigins = (): string[] =>
+ ENV.AUTH.TRUSTED_ORIGINS
+ .split(',')
+ .map((origin) => origin.trim())
+ .filter((origin) => origin.length > 0)
+
export const getApiUrl = (port: number = ENV.SERVER.PORT): string => {
const host = ENV.SERVER.HOST
diff --git a/shared/src/schemas/preview.ts b/shared/src/schemas/preview.ts
index 8fbeeebd..4401cd52 100644
--- a/shared/src/schemas/preview.ts
+++ b/shared/src/schemas/preview.ts
@@ -6,6 +6,7 @@ export const PreviewPortSchema = z.object({
pid: z.number().int().nullable(),
command: z.string().nullable(),
cwd: z.string().nullable(),
+ inDirectory: z.boolean(),
})
export const PreviewPortsResponseSchema = z.object({
diff --git a/shared/src/schemas/project-config.ts b/shared/src/schemas/project-config.ts
index 35444e00..bd160556 100644
--- a/shared/src/schemas/project-config.ts
+++ b/shared/src/schemas/project-config.ts
@@ -17,7 +17,12 @@ export const ProjectActionSchema = z.object({
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(),
+ url: z
+ .string()
+ .trim()
+ .max(500)
+ .refine((value) => /^https?:\/\//i.test(value), 'URL must start with http:// or https://')
+ .optional(),
autoOpenUrl: z.boolean().default(false),
})
@@ -49,6 +54,20 @@ export const ProjectConfigResponseSchema = z.object({
exists: z.boolean(),
trusted: z.boolean(),
hash: z.string().nullable(),
+ executable: z
+ .object({
+ actions: z.array(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ command: z.string(),
+ url: z.string().nullable(),
+ autoOpenUrl: z.boolean(),
+ }),
+ ),
+ setup: z.array(z.string()),
+ })
+ .nullable(),
error: z.string().optional(),
warnings: z.array(z.string()),
}),
diff --git a/shared/src/utils/terminal-title.ts b/shared/src/utils/terminal-title.ts
index 642bf4a1..1313b119 100644
--- a/shared/src/utils/terminal-title.ts
+++ b/shared/src/utils/terminal-title.ts
@@ -1,4 +1,4 @@
-import type { TerminalKind } from '../schemas/terminal'
+import type { TerminalInfo, TerminalKind } from '../schemas/terminal'
const ACTION_TITLE_PREFIX = 'ocm:action:'
const SETUP_TITLE_PREFIX = 'ocm:setup:'
@@ -31,6 +31,12 @@ export function formatTerminalTitle(input: FormatTerminalTitleInput): string {
return input.name
}
+export type RunningActionTerminal = Pick
+
+export function isRunningActionTerminal(terminal: RunningActionTerminal, actionId: string): boolean {
+ return terminal.kind === 'action' && terminal.actionId === actionId && terminal.status === 'running'
+}
+
export function parseTerminalTitle(raw: string): ParsedTerminalTitle {
if (raw.startsWith(ACTION_TITLE_PREFIX)) {
const rest = raw.slice(ACTION_TITLE_PREFIX.length)