mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(terminal-dev-loop): address branch review findings
Security: - Reject same-site and cross-site state-changing requests on cookie-authenticated routes unless the origin is trusted - Drop Manager and ocm_preview Set-Cookie headers from preview responses - Show and hash the full executable content of .ocm/project.json at trust time - Restrict action URLs to http(s) and refuse symlinked repo config paths - Keep the preview start redirect on the gateway origin Lifecycle: - Stop terminals in OpenCode workspace siblings when a repo is deleted - Report preview as unavailable instead of crashing when the gateway port cannot be bound Performance: - Skip branch lookups when validating terminal and project-config directories - Stop the /proc scan once all listening sockets are mapped and pause port polling while a preview is open - Close slow WebSocket clients with 1013 so they reconnect with replay - Lazy-load the xterm terminal view and skip unchanged resize requests - Request uncompressed responses from preview targets Cleanup: - Share one repo directory resolver, trusted-origins parser, cookie prefix, WebSocket frame forwarder, header filter, icon map and dialog-param helper - Remove unused props, options and exports Docs: update terminal, preview, project actions, sandboxing, internal API and environment pages
This commit is contained in:
1 parent
16b91ccf02
commit
c60a9b35f2
72 files changed
+2039
-596
No files matched your search
@@ -0,0 +1 @@
|
||||
export const AUTH_COOKIE_PREFIX = 'opencode'
|
||||
@@ -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<typeof createAuth>
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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) {
|
||||
|
||||
+14
-4
@@ -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}`)
|
||||
@@ -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<PreviewPortEntry[]>
|
||||
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<PreviewRoutesDeps> = {}) {
|
||||
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<PreviewRoutesDeps> = {}) {
|
||||
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<PreviewRoutesDeps> = {}) {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
if (!resolvedDeps.enabled) {
|
||||
if (!resolvedDeps.isEnabled()) {
|
||||
return c.json({ error: 'Preview is disabled' }, 503)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -45,6 +45,39 @@ async function removeDirectoryTerminals(terminalService: TerminalService, direct
|
||||
}
|
||||
}
|
||||
|
||||
async function listWorkspaceSiblings(
|
||||
database: Database,
|
||||
repoId: number,
|
||||
gitAuthService: GitAuthService,
|
||||
openCodeClient: OpenCodeClient,
|
||||
): Promise<Array<Repo & { worktreeStrategy?: string }>> {
|
||||
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<void> {
|
||||
let siblings: Array<Repo & { worktreeStrategy?: string }>
|
||||
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 })
|
||||
|
||||
@@ -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<string, string> = {}
|
||||
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)) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<PreviewPort, 'inDirectory'>
|
||||
|
||||
export interface ParsedProcNetSocket {
|
||||
port: number
|
||||
@@ -192,8 +187,9 @@ function dedupeByPort(entries: PreviewPortEntry[]): PreviewPortEntry[] {
|
||||
return result
|
||||
}
|
||||
|
||||
async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, number>> {
|
||||
async function mapInodesToPids(deps: PortDiscoveryDeps, wantedInodes: ReadonlySet<string>): Promise<Map<string, number>> {
|
||||
const map = new Map<string, number>()
|
||||
if (wantedInodes.size === 0) return map
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = await deps.readdir('/proc')
|
||||
@@ -201,6 +197,7 @@ async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, num
|
||||
return map
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (map.size >= wantedInodes.size) break
|
||||
if (!/^\d+$/.test(entry)) continue
|
||||
const fdDir = `/proc/${entry}/fd`
|
||||
let fds: string[]
|
||||
@@ -217,7 +214,8 @@ async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, num
|
||||
continue
|
||||
}
|
||||
const match = /^socket:\[(\d+)\]$/.exec(target)
|
||||
if (match?.[1]) map.set(match[1], Number.parseInt(entry, 10))
|
||||
const inode = match?.[1]
|
||||
if (inode && wantedInodes.has(inode)) map.set(inode, Number.parseInt(entry, 10))
|
||||
}
|
||||
}
|
||||
return map
|
||||
@@ -252,7 +250,11 @@ async function listLinuxPorts(deps: PortDiscoveryDeps): Promise<PreviewPortEntry
|
||||
}
|
||||
if (sockets.length === 0) return []
|
||||
|
||||
const inodeToPid = await mapInodesToPids(deps)
|
||||
const wantedInodes = new Set<string>()
|
||||
for (const socket of sockets) {
|
||||
if (socket.inode) wantedInodes.add(socket.inode)
|
||||
}
|
||||
const inodeToPid = await mapInodesToPids(deps, wantedInodes)
|
||||
const processMeta = new Map<number, { command: string | null; cwd: string | null }>()
|
||||
const entries: PreviewPortEntry[] = []
|
||||
for (const socket of sockets) {
|
||||
|
||||
@@ -15,11 +15,12 @@ import {
|
||||
type RunProjectActionResponse,
|
||||
type WorktreeSetupResult,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { isRunningActionTerminal } from '@opencode-manager/shared/utils'
|
||||
import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import { canonicalPathSync, writeFileAtomicSync } from '../utils/fs-safe'
|
||||
import type { GitService } from './git/GitService'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import type { TerminalService } from './terminal'
|
||||
@@ -28,6 +29,7 @@ const PROJECT_ACTIONS_KEY = 'projectActions'
|
||||
const WORKTREE_SETUP_KEY = 'worktreeSetupCommands'
|
||||
const REPO_CONFIG_TRUST_KEY = 'repoConfigTrustHash'
|
||||
const REPO_FILE_RELATIVE_PATH = path.join('.ocm', 'project.json')
|
||||
const REPO_CONFIG_SYMLINK_MESSAGE = '.ocm/project.json must not be a symbolic link'
|
||||
|
||||
export interface RepoFileState {
|
||||
exists: boolean
|
||||
@@ -50,8 +52,8 @@ interface RepoFileSnapshot {
|
||||
|
||||
export class ProjectConfigError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
public status: number,
|
||||
public code?: string,
|
||||
public details?: unknown,
|
||||
) {
|
||||
@@ -85,7 +87,7 @@ export class ProjectConfigService {
|
||||
const ids = new Set<string>()
|
||||
for (const action of actions) {
|
||||
if (ids.has(action.id)) {
|
||||
throw new ProjectConfigError(400, 'Duplicate action id')
|
||||
throw new ProjectConfigError('Duplicate action id', 400)
|
||||
}
|
||||
ids.add(action.id)
|
||||
}
|
||||
@@ -144,6 +146,7 @@ export class ProjectConfigService {
|
||||
exists: repoFile.exists,
|
||||
trusted,
|
||||
hash: repoFile.hash,
|
||||
executable: repoFile.file ? this.buildRepoFileExecutable(repoFile.file) : null,
|
||||
...(repoFile.error ? { error: repoFile.error } : {}),
|
||||
warnings,
|
||||
},
|
||||
@@ -178,11 +181,11 @@ export class ProjectConfigService {
|
||||
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')
|
||||
throw new ProjectConfigError('Action not found', 404)
|
||||
}
|
||||
|
||||
if (action.source === 'repo' && !config.repoFile.trusted) {
|
||||
throw new ProjectConfigError(409, 'Repository commands are not trusted', 'REPO_CONFIG_UNTRUSTED', {
|
||||
throw new ProjectConfigError('Repository commands are not trusted', 409, 'REPO_CONFIG_UNTRUSTED', {
|
||||
hash: config.repoFile.hash,
|
||||
})
|
||||
}
|
||||
@@ -190,9 +193,7 @@ export class ProjectConfigService {
|
||||
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 running = terminals.find((terminal) => isRunningActionTerminal(terminal, actionId))
|
||||
const terminal =
|
||||
running ??
|
||||
(await terminalService.create(directory, {
|
||||
@@ -288,34 +289,53 @@ export class ProjectConfigService {
|
||||
|
||||
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 (this.isSymbolicLink(path.dirname(filePath)) || this.isSymbolicLink(filePath)) {
|
||||
return { exists: true, file: null, hash: null, error: REPO_CONFIG_SYMLINK_MESSAGE }
|
||||
}
|
||||
if (!fs.existsSync(filePath)) {
|
||||
return { exists: false, file: null, hash: null }
|
||||
}
|
||||
|
||||
let parsedJson: unknown
|
||||
try {
|
||||
parsedJson = JSON.parse(fs.readFileSync(filePath, 'utf8'))
|
||||
} catch {
|
||||
return { exists: true, file: null, hash: null, error: 'Invalid JSON' }
|
||||
}
|
||||
|
||||
const parsed = RepoProjectFileSchema.safeParse(parsedJson)
|
||||
if (!parsed.success) {
|
||||
return { exists: true, file: null, hash: null, error: 'Invalid repository config' }
|
||||
return { exists: true, file: null, hash: null, error: 'Does not match the project file schema' }
|
||||
}
|
||||
return { exists: true, file: parsed.data, hash: this.hashRepoFile(parsed.data) }
|
||||
} catch (error: unknown) {
|
||||
return { exists: true, file: null, hash: null, error: getErrorMessage(error) }
|
||||
} catch {
|
||||
return { exists: fs.existsSync(filePath), file: null, hash: null, error: 'Invalid repository config' }
|
||||
}
|
||||
}
|
||||
|
||||
buildRepoFileExecutable(file: RepoProjectFile): NonNullable<ProjectConfigResponse['repoFile']['executable']> {
|
||||
return {
|
||||
actions: (file.projectActions ?? []).map((action) => ({
|
||||
id: action.id,
|
||||
name: action.name,
|
||||
command: action.command,
|
||||
url: action.url ?? null,
|
||||
autoOpenUrl: action.autoOpenUrl,
|
||||
})),
|
||||
setup: file.setupWorktree ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
hashRepoFile(file: RepoProjectFile): string {
|
||||
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')
|
||||
return createHash('sha256').update(JSON.stringify(this.buildRepoFileExecutable(file))).digest('hex')
|
||||
}
|
||||
|
||||
async trustRepoFile(repo: Repo, directory: string, hash: string): Promise<void> {
|
||||
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')
|
||||
throw new ProjectConfigError('Repository config changed', 409, 'REPO_CONFIG_CHANGED')
|
||||
}
|
||||
this.setRepoTrust(projectRepo, repoFile.hash)
|
||||
}
|
||||
@@ -323,6 +343,7 @@ export class ProjectConfigService {
|
||||
async moveItem(repo: Repo, directory: string, request: MoveProjectItemRequest): Promise<void> {
|
||||
const projectRepo = await this.resolveProjectRepo(repo)
|
||||
const filePath = this.getRepoFilePath(directory)
|
||||
this.assertRepoFilePathNotSymlink(filePath)
|
||||
const state = this.readRepoFile(directory)
|
||||
const commit =
|
||||
request.to === 'repo'
|
||||
@@ -334,7 +355,7 @@ export class ProjectConfigService {
|
||||
|
||||
private planMoveToRepo(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit {
|
||||
if (state.exists && !state.file) {
|
||||
throw new ProjectConfigError(409, 'Repository config is invalid')
|
||||
throw new ProjectConfigError('Repository config is invalid', 409)
|
||||
}
|
||||
|
||||
const file: RepoProjectFile = state.file ? { ...state.file } : { version: 1 }
|
||||
@@ -343,11 +364,11 @@ export class ProjectConfigService {
|
||||
const personal = this.getPersonalActions(projectRepo)
|
||||
const action = personal.find((item) => item.id === request.id)
|
||||
if (!action) {
|
||||
throw new ProjectConfigError(404, 'Action not found')
|
||||
throw new ProjectConfigError('Action not found', 404)
|
||||
}
|
||||
const repoActions = file.projectActions ?? []
|
||||
if (repoActions.some((existing) => existing.id === action.id)) {
|
||||
throw new ProjectConfigError(409, 'Action already exists in repository config')
|
||||
throw new ProjectConfigError('Action already exists in repository config', 409)
|
||||
}
|
||||
const nextFile: RepoProjectFile = { ...file, projectActions: [...repoActions, action] }
|
||||
this.assertRepoFileValid(nextFile)
|
||||
@@ -361,7 +382,7 @@ export class ProjectConfigService {
|
||||
const personal = this.getPersonalSetup(projectRepo)
|
||||
const index = personal.indexOf(request.command)
|
||||
if (index === -1) {
|
||||
throw new ProjectConfigError(404, 'Setup command not found')
|
||||
throw new ProjectConfigError('Setup command not found', 404)
|
||||
}
|
||||
const nextFile: RepoProjectFile = {
|
||||
...file,
|
||||
@@ -380,14 +401,14 @@ export class ProjectConfigService {
|
||||
private planMoveToPersonal(projectRepo: Repo, state: RepoFileState, request: MoveProjectItemRequest): MoveCommit {
|
||||
const file = state.file
|
||||
if (!file) {
|
||||
throw new ProjectConfigError(404, 'Item not found')
|
||||
throw new ProjectConfigError('Item not found', 404)
|
||||
}
|
||||
|
||||
if (request.kind === 'action') {
|
||||
const repoActions = file.projectActions ?? []
|
||||
const action = repoActions.find((item) => item.id === request.id)
|
||||
if (!action) {
|
||||
throw new ProjectConfigError(404, 'Action not found')
|
||||
throw new ProjectConfigError('Action not found', 404)
|
||||
}
|
||||
const nextFile = this.pruneRepoFile({
|
||||
...file,
|
||||
@@ -406,7 +427,7 @@ export class ProjectConfigService {
|
||||
const repoSetup = file.setupWorktree ?? []
|
||||
const index = repoSetup.indexOf(request.command)
|
||||
if (index === -1) {
|
||||
throw new ProjectConfigError(404, 'Setup command not found')
|
||||
throw new ProjectConfigError('Setup command not found', 404)
|
||||
}
|
||||
const nextFile = this.pruneRepoFile({
|
||||
...file,
|
||||
@@ -494,8 +515,8 @@ export class ProjectConfigService {
|
||||
const result = RepoProjectFileSchema.safeParse(file)
|
||||
if (!result.success) {
|
||||
throw new ProjectConfigError(
|
||||
409,
|
||||
'Repository config limit exceeded',
|
||||
409,
|
||||
'PROJECT_CONFIG_LIMIT_EXCEEDED',
|
||||
result.error.flatten(),
|
||||
)
|
||||
@@ -506,8 +527,8 @@ export class ProjectConfigService {
|
||||
const result = WorktreeSetupCommandsSchema.safeParse(commands)
|
||||
if (!result.success) {
|
||||
throw new ProjectConfigError(
|
||||
409,
|
||||
'Personal setup command limit exceeded',
|
||||
409,
|
||||
'PROJECT_CONFIG_LIMIT_EXCEEDED',
|
||||
result.error.flatten(),
|
||||
)
|
||||
@@ -523,17 +544,26 @@ export class ProjectConfigService {
|
||||
}
|
||||
|
||||
private writeRepoFile(filePath: string, file: RepoProjectFile): void {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
const tmpPath = `${filePath}.tmp`
|
||||
writeFileAtomicSync(filePath, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o644 })
|
||||
}
|
||||
|
||||
private isSymbolicLink(target: string): boolean {
|
||||
try {
|
||||
fs.writeFileSync(tmpPath, `${JSON.stringify(file, null, 2)}\n`)
|
||||
fs.renameSync(tmpPath, filePath)
|
||||
return fs.lstatSync(target).isSymbolicLink()
|
||||
} catch (error) {
|
||||
fs.rmSync(tmpPath, { force: true })
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return false
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private assertRepoFilePathNotSymlink(filePath: string): void {
|
||||
if (this.isSymbolicLink(path.dirname(filePath)) || this.isSymbolicLink(filePath)) {
|
||||
throw new ProjectConfigError(REPO_CONFIG_SYMLINK_MESSAGE, 400, 'REPO_CONFIG_SYMLINK')
|
||||
}
|
||||
}
|
||||
|
||||
private snapshotFile(filePath: string): RepoFileSnapshot {
|
||||
try {
|
||||
return { exists: true, content: fs.readFileSync(filePath) }
|
||||
|
||||
@@ -1194,6 +1194,7 @@ export async function getSiblingRepos(
|
||||
repoId: number,
|
||||
gitEnv: Record<string, string>,
|
||||
openCodeClient?: OpenCodeClient,
|
||||
options: { includeBranch?: boolean } = {},
|
||||
): Promise<Array<Repo & { currentBranch: string | undefined; worktreeStrategy?: string }>> {
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings()
|
||||
@@ -1217,10 +1218,11 @@ export async function getSiblingRepos(
|
||||
.filter((entry) => entry.projectId === targetProjectId)
|
||||
.map((entry) => entry.repo)
|
||||
|
||||
const includeBranch = options.includeBranch ?? true
|
||||
const repoSiblings = await Promise.all(
|
||||
matching.map(async (repo) => ({
|
||||
...repo,
|
||||
currentBranch: (await getCurrentBranch(repo, gitEnv)) ?? undefined,
|
||||
currentBranch: includeBranch ? (await getCurrentBranch(repo, gitEnv)) ?? undefined : undefined,
|
||||
})),
|
||||
)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import path from 'path'
|
||||
import { promises as fs, mkdirSync, accessSync, constants, realpathSync } from 'node:fs'
|
||||
import { promises as fs, mkdirSync, accessSync, constants, realpathSync, writeFileSync, renameSync, rmSync } from 'node:fs'
|
||||
|
||||
interface MkdirSafeOptions {
|
||||
mode?: number
|
||||
@@ -39,6 +39,19 @@ export async function writeFileAtomic(filePath: string, content: string, options
|
||||
}
|
||||
}
|
||||
|
||||
export function writeFileAtomicSync(filePath: string, content: string, options: { mode?: number } = {}): void {
|
||||
const dir = path.dirname(filePath)
|
||||
mkdirSyncSafe(dir)
|
||||
const tempPath = path.join(dir, `.${path.basename(filePath)}.ocm-tmp-${process.pid}-${Date.now()}`)
|
||||
try {
|
||||
writeFileSync(tempPath, content, { encoding: 'utf-8', mode: options.mode ?? 0o600 })
|
||||
renameSync(tempPath, filePath)
|
||||
} catch (error) {
|
||||
rmSync(tempPath, { force: true })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function existingFileMode(filePath: string): Promise<number | undefined> {
|
||||
try {
|
||||
return (await fs.stat(filePath)).mode & 0o777
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export const HOP_BY_HOP_HEADERS = new Set([
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
|
||||
@@ -25,6 +25,8 @@ interface ServiceError {
|
||||
message: string
|
||||
statusCode?: number
|
||||
status?: number
|
||||
code?: string
|
||||
details?: unknown
|
||||
}
|
||||
|
||||
type ServiceErrorConstructor = new (message: string, statusOrStatusCode: number) => ServiceError
|
||||
@@ -36,8 +38,16 @@ export function handleServiceError(
|
||||
ErrorClass: ServiceErrorConstructor,
|
||||
) {
|
||||
if (error instanceof ErrorClass) {
|
||||
const status = (error as ServiceError).statusCode ?? (error as ServiceError).status ?? 500
|
||||
return c.json({ error: error.message }, status as ContentfulStatusCode)
|
||||
const serviceError = error as ServiceError
|
||||
const status = serviceError.statusCode ?? serviceError.status ?? 500
|
||||
return c.json(
|
||||
{
|
||||
error: error.message,
|
||||
...(serviceError.code !== undefined ? { code: serviceError.code } : {}),
|
||||
...(serviceError.details !== undefined ? { details: serviceError.details } : {}),
|
||||
},
|
||||
status as ContentfulStatusCode,
|
||||
)
|
||||
}
|
||||
logger.error(fallback, error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export interface WebSocketPeer {
|
||||
send(data: string | Uint8Array<ArrayBuffer>): void
|
||||
close(code?: number, reason?: string): void
|
||||
bufferedAmount(): number
|
||||
}
|
||||
|
||||
export interface WebSocketBridge {
|
||||
@@ -8,8 +9,28 @@ export interface WebSocketBridge {
|
||||
close(): void
|
||||
}
|
||||
|
||||
export interface BridgeWebSocketOptions {
|
||||
mapCloseCode?: (code: number) => number
|
||||
export const MAX_PEER_BUFFERED_BYTES = 4 * 1024 * 1024
|
||||
|
||||
export function peerBufferedAmount(peer: { raw?: unknown }): number {
|
||||
const raw = peer.raw as { bufferedAmount?: number } | undefined
|
||||
return typeof raw?.bufferedAmount === 'number' ? raw.bufferedAmount : 0
|
||||
}
|
||||
|
||||
export async function forwardPeerMessage(
|
||||
bridge: WebSocketBridge,
|
||||
data: string | Blob | ArrayBufferLike,
|
||||
): Promise<void> {
|
||||
if (typeof data === 'string') {
|
||||
bridge.send(data)
|
||||
return
|
||||
}
|
||||
if (data instanceof Blob) {
|
||||
bridge.send(await data.arrayBuffer())
|
||||
return
|
||||
}
|
||||
if (data instanceof ArrayBuffer) {
|
||||
bridge.send(data)
|
||||
}
|
||||
}
|
||||
|
||||
function defaultMapCloseCode(code: number): number {
|
||||
@@ -22,13 +43,8 @@ function toBytes(data: ArrayBuffer | Uint8Array): Uint8Array<ArrayBuffer> {
|
||||
return data instanceof Uint8Array ? (data as Uint8Array<ArrayBuffer>) : new Uint8Array(data)
|
||||
}
|
||||
|
||||
export function bridgeWebSocket(
|
||||
upstream: WebSocket,
|
||||
peer: WebSocketPeer,
|
||||
options: BridgeWebSocketOptions = {},
|
||||
): WebSocketBridge {
|
||||
export function bridgeWebSocket(upstream: WebSocket, peer: WebSocketPeer): WebSocketBridge {
|
||||
upstream.binaryType = 'arraybuffer'
|
||||
const mapCloseCode = options.mapCloseCode ?? defaultMapCloseCode
|
||||
|
||||
const queue: Array<string | Uint8Array> = []
|
||||
let upstreamOpen = false
|
||||
@@ -46,18 +62,24 @@ export function bridgeWebSocket(
|
||||
})
|
||||
|
||||
upstream.addEventListener('message', (event) => {
|
||||
if (finished) return
|
||||
const data = (event as MessageEvent).data
|
||||
if (typeof data === 'string') {
|
||||
peer.send(data)
|
||||
} else if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
|
||||
peer.send(toBytes(data))
|
||||
}
|
||||
if (peer.bufferedAmount() > MAX_PEER_BUFFERED_BYTES) {
|
||||
finish()
|
||||
upstream.close()
|
||||
peer.close(1013, 'Client too slow')
|
||||
}
|
||||
})
|
||||
|
||||
upstream.addEventListener('close', (event) => {
|
||||
if (finished) return
|
||||
finish()
|
||||
peer.close(mapCloseCode((event as CloseEvent).code))
|
||||
peer.close(defaultMapCloseCode((event as CloseEvent).code))
|
||||
})
|
||||
|
||||
upstream.addEventListener('error', () => {
|
||||
|
||||
@@ -31,7 +31,13 @@ const { ENV } = vi.hoisted(() => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({ ENV }))
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
ENV,
|
||||
getTrustedOrigins: () => ENV.AUTH.TRUSTED_ORIGINS
|
||||
.split(',')
|
||||
.map((origin: string) => origin.trim())
|
||||
.filter((origin: string) => origin.length > 0),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { createAuthMiddleware } from '../../src/auth/middleware'
|
||||
import type { AuthInstance, Session } from '../../src/auth'
|
||||
|
||||
const loggerMock = vi.hoisted(() => ({
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({ logger: loggerMock }))
|
||||
|
||||
const TRUSTED_ORIGIN = 'http://trusted.test'
|
||||
const UNTRUSTED_ORIGIN = 'http://untrusted.test'
|
||||
|
||||
function createSession(): Session {
|
||||
return {
|
||||
session: {
|
||||
id: 'session-1',
|
||||
userId: 'user-1',
|
||||
token: 'token-1',
|
||||
expiresAt: new Date(Date.now() + 1000),
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
user: {
|
||||
id: 'user-1',
|
||||
name: 'Test User',
|
||||
email: 'test@example.com',
|
||||
emailVerified: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
role: 'user',
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function createApp(
|
||||
getSession: (input: { headers: Headers }) => Promise<Session | null>,
|
||||
trustedOrigins: string[] = [TRUSTED_ORIGIN],
|
||||
) {
|
||||
const app = new Hono<{ Variables: { session: Session['session']; user: Session['user'] } }>()
|
||||
app.use('/*', createAuthMiddleware({ api: { getSession } } as unknown as AuthInstance, () => trustedOrigins))
|
||||
app.get('/', (c) => c.json({ userId: c.get('user').id }))
|
||||
app.post('/', (c) => c.json({ ok: true }))
|
||||
app.put('/', (c) => c.json({ ok: true }))
|
||||
app.patch('/', (c) => c.json({ ok: true }))
|
||||
app.delete('/', (c) => c.json({ ok: true }))
|
||||
return app
|
||||
}
|
||||
|
||||
describe('createAuthMiddleware same-site guard', () => {
|
||||
let getSession: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
getSession = vi.fn()
|
||||
getSession.mockResolvedValue(createSession())
|
||||
})
|
||||
|
||||
it('rejects an unsafe same-site request with an untrusted origin without looking up the session', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'POST',
|
||||
headers: { 'sec-fetch-site': 'same-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(await res.json()).toEqual({ error: 'Cross-site request rejected' })
|
||||
expect(getSession).not.toHaveBeenCalled()
|
||||
expect(loggerMock.warn).toHaveBeenCalledWith(expect.stringContaining('/'))
|
||||
})
|
||||
|
||||
it('allows an unsafe same-site request from a trusted origin', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'POST',
|
||||
headers: { 'sec-fetch-site': 'same-site', origin: TRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(getSession).toHaveBeenCalledTimes(1)
|
||||
expect(loggerMock.warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('allows a same-origin request', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'POST',
|
||||
headers: { 'sec-fetch-site': 'same-origin', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(getSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('allows an unsafe request without a Sec-Fetch-Site header', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'POST',
|
||||
headers: { origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(getSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('allows a cross-site GET so WebSocket upgrades are unaffected', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'GET',
|
||||
headers: { 'sec-fetch-site': 'cross-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(getSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects a cross-site unsafe request with no origin', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'DELETE',
|
||||
headers: { 'sec-fetch-site': 'cross-site', cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(await res.json()).toEqual({ error: 'Cross-site request rejected' })
|
||||
expect(getSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a cross-site PUT with an untrusted origin', async () => {
|
||||
const app = createApp(getSession)
|
||||
|
||||
const res = await app.request('/', {
|
||||
method: 'PUT',
|
||||
headers: { 'sec-fetch-site': 'cross-site', origin: UNTRUSTED_ORIGIN, cookie: 'opencode.session=valid' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(getSession).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getTrustedOrigins', () => {
|
||||
const originalTrustedOrigins = process.env.AUTH_TRUSTED_ORIGINS
|
||||
|
||||
afterEach(() => {
|
||||
if (originalTrustedOrigins === undefined) {
|
||||
delete process.env.AUTH_TRUSTED_ORIGINS
|
||||
} else {
|
||||
process.env.AUTH_TRUSTED_ORIGINS = originalTrustedOrigins
|
||||
}
|
||||
vi.resetModules()
|
||||
})
|
||||
|
||||
async function loadTrustedOrigins(value?: string): Promise<string[]> {
|
||||
if (value === undefined) {
|
||||
delete process.env.AUTH_TRUSTED_ORIGINS
|
||||
} else {
|
||||
process.env.AUTH_TRUSTED_ORIGINS = value
|
||||
}
|
||||
vi.resetModules()
|
||||
const { getTrustedOrigins } = await import('@opencode-manager/shared/config/env')
|
||||
return getTrustedOrigins()
|
||||
}
|
||||
|
||||
it('splits, trims, and drops empty entries', async () => {
|
||||
await expect(loadTrustedOrigins(' http://a.test ,, http://b.test ')).resolves.toEqual(['http://a.test', 'http://b.test'])
|
||||
})
|
||||
|
||||
it('returns an empty list when configured empty', async () => {
|
||||
await expect(loadTrustedOrigins('')).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('falls back to the local development origins', async () => {
|
||||
await expect(loadTrustedOrigins(undefined)).resolves.toEqual(['http://localhost:5173', 'http://localhost:5003'])
|
||||
})
|
||||
})
|
||||
@@ -3,12 +3,47 @@ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promis
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const serveMock = vi.fn<(options: unknown) => { on: () => void }>(() => ({ on: vi.fn() }))
|
||||
interface MockServeServer {
|
||||
on: (event: string, handler: (...args: unknown[]) => void) => void
|
||||
emit: (event: string, ...args: unknown[]) => void
|
||||
}
|
||||
|
||||
const serveServers = vi.hoisted(() => [] as MockServeServer[])
|
||||
|
||||
const serveMock = vi.fn<(options: unknown) => MockServeServer>(() => {
|
||||
const handlers = new Map<string, Array<(...args: unknown[]) => void>>()
|
||||
const server: MockServeServer = {
|
||||
on: (event, handler) => {
|
||||
const registered = handlers.get(event) ?? []
|
||||
registered.push(handler)
|
||||
handlers.set(event, registered)
|
||||
},
|
||||
emit: (event, ...args) => {
|
||||
for (const handler of handlers.get(event) ?? []) handler(...args)
|
||||
},
|
||||
}
|
||||
serveServers.push(server)
|
||||
return server
|
||||
})
|
||||
|
||||
vi.mock('@hono/node-server', () => ({
|
||||
serve: serveMock,
|
||||
}))
|
||||
|
||||
const previewAvailabilityInstances = vi.hoisted(() => [] as Array<{ isEnabled: () => boolean }>)
|
||||
|
||||
vi.mock('../src/routes/preview', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/routes/preview')>()
|
||||
return {
|
||||
...actual,
|
||||
createPreviewAvailability: (initialEnabled: boolean) => {
|
||||
const availability = actual.createPreviewAvailability(initialEnabled)
|
||||
previewAvailabilityInstances.push(availability)
|
||||
return availability
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const supervisorMock = vi.hoisted(() => ({
|
||||
start: vi.fn().mockResolvedValue({ healthy: true, port: 5551, state: 'running' }),
|
||||
stop: vi.fn().mockResolvedValue(undefined),
|
||||
@@ -143,6 +178,8 @@ describe('backend entrypoint', () => {
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
serveServers.length = 0
|
||||
previewAvailabilityInstances.length = 0
|
||||
tempWorkspace = await mkdtemp(join(tmpdir(), 'ocm-entrypoint-'))
|
||||
previousWorkspace = process.env.WORKSPACE_PATH
|
||||
process.env.WORKSPACE_PATH = tempWorkspace
|
||||
@@ -175,6 +212,22 @@ describe('backend entrypoint', () => {
|
||||
expect(ipcServerMock.dispose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('marks the preview gateway unavailable instead of crashing when its port cannot be bound', async () => {
|
||||
await import('../src/index')
|
||||
|
||||
expect(serveServers).toHaveLength(2)
|
||||
const availability = previewAvailabilityInstances[0]
|
||||
expect(availability?.isEnabled()).toBe(false)
|
||||
|
||||
const previewServer = serveServers[1]!
|
||||
previewServer.emit('listening')
|
||||
expect(availability?.isEnabled()).toBe(true)
|
||||
|
||||
const error = Object.assign(new Error('bind failed'), { code: 'EADDRINUSE' })
|
||||
expect(() => previewServer.emit('error', error)).not.toThrow()
|
||||
expect(availability?.isEnabled()).toBe(false)
|
||||
})
|
||||
|
||||
it('imports home state without rewriting an existing valid config', async () => {
|
||||
const configDir = join(tempWorkspace, '.config', 'opencode')
|
||||
await mkdir(configDir, { recursive: true })
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { mkdtemp, mkdir, rm } from 'node:fs/promises'
|
||||
import { mkdtemp, mkdir, rm, symlink } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { createPreviewRoutes } from '../../src/routes/preview'
|
||||
import type { PreviewPort } from '@opencode-manager/shared/schemas'
|
||||
import { createPreviewRoutes, createPreviewAvailability } from '../../src/routes/preview'
|
||||
import { PreviewSessionStore } from '../../src/services/preview/gateway'
|
||||
import type { PreviewPortEntry } from '../../src/services/preview/ports'
|
||||
|
||||
@@ -30,7 +31,7 @@ describe('Preview Routes', () => {
|
||||
await mkdir(appDir)
|
||||
|
||||
const app = createPreviewRoutes({
|
||||
enabled: true,
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [
|
||||
entry({ port: 9000, cwd: '/somewhere/else' }),
|
||||
entry({ port: 5173, cwd: appDir }),
|
||||
@@ -47,7 +48,7 @@ describe('Preview Routes', () => {
|
||||
|
||||
it('sorts by port when no directory is given', async () => {
|
||||
const app = createPreviewRoutes({
|
||||
enabled: true,
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [entry({ port: 9000 }), entry({ port: 5173 })],
|
||||
})
|
||||
|
||||
@@ -57,8 +58,60 @@ describe('Preview Routes', () => {
|
||||
expect(body.ports.map((port) => port.port)).toEqual([5173, 9000])
|
||||
})
|
||||
|
||||
it('marks entries inside the directory and sorts them first', async () => {
|
||||
const root = await makeTempDir()
|
||||
const appDir = join(root, 'app')
|
||||
await mkdir(appDir)
|
||||
|
||||
const app = createPreviewRoutes({
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [
|
||||
entry({ port: 5173, cwd: '/somewhere/else' }),
|
||||
entry({ port: 9000, cwd: appDir }),
|
||||
],
|
||||
})
|
||||
|
||||
const res = await app.request(`/ports?directory=${encodeURIComponent(root)}`)
|
||||
const body = await res.json() as { ports: PreviewPort[] }
|
||||
|
||||
expect(body.ports.map((port) => ({ port: port.port, inDirectory: port.inDirectory }))).toEqual([
|
||||
{ port: 9000, inDirectory: true },
|
||||
{ port: 5173, inDirectory: false },
|
||||
])
|
||||
})
|
||||
|
||||
it('resolves symlinked cwds before matching the directory', async () => {
|
||||
const root = await makeTempDir()
|
||||
const realDir = join(root, 'real')
|
||||
const linkDir = join(root, 'link')
|
||||
await mkdir(realDir)
|
||||
await symlink(realDir, linkDir)
|
||||
|
||||
const app = createPreviewRoutes({
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [entry({ port: 5173, cwd: linkDir })],
|
||||
})
|
||||
|
||||
const res = await app.request(`/ports?directory=${encodeURIComponent(realDir)}`)
|
||||
const body = await res.json() as { ports: PreviewPort[] }
|
||||
|
||||
expect(body.ports[0]?.inDirectory).toBe(true)
|
||||
})
|
||||
|
||||
it('marks every entry outside when no directory is given', async () => {
|
||||
const app = createPreviewRoutes({
|
||||
isEnabled: () => true,
|
||||
listPorts: async () => [entry({ port: 5173, cwd: '/repo' }), entry({ port: 9000, cwd: null })],
|
||||
})
|
||||
|
||||
const res = await app.request('/ports')
|
||||
const body = await res.json() as { ports: PreviewPort[] }
|
||||
|
||||
expect(body.ports.map((port) => port.inDirectory)).toEqual([false, false])
|
||||
})
|
||||
|
||||
it('reports preview as disabled when the port is zero', async () => {
|
||||
const app = createPreviewRoutes({ enabled: false, listPorts: async () => [] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => false, listPorts: async () => [] })
|
||||
|
||||
const res = await app.request('/ports')
|
||||
|
||||
@@ -67,7 +120,7 @@ describe('Preview Routes', () => {
|
||||
|
||||
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 app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: 5173 })], store })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -84,7 +137,7 @@ describe('Preview Routes', () => {
|
||||
})
|
||||
|
||||
it('rejects a reserved port with 400', async () => {
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: ENV.PREVIEW.PORT })] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: ENV.PREVIEW.PORT })] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -96,7 +149,7 @@ describe('Preview Routes', () => {
|
||||
})
|
||||
|
||||
it('returns 404 for a port that is not listening', async () => {
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: 5173 })] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [entry({ port: 5173 })] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -109,7 +162,7 @@ describe('Preview Routes', () => {
|
||||
})
|
||||
|
||||
it('returns 503 when preview is disabled', async () => {
|
||||
const app = createPreviewRoutes({ enabled: false, listPorts: async () => [entry({ port: 5173 })] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => false, listPorts: async () => [entry({ port: 5173 })] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -121,7 +174,7 @@ describe('Preview Routes', () => {
|
||||
})
|
||||
|
||||
it('rejects an out-of-range port with 400', async () => {
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [] })
|
||||
const app = createPreviewRoutes({ isEnabled: () => true, listPorts: async () => [] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
@@ -131,4 +184,40 @@ describe('Preview Routes', () => {
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('reads availability at request time', async () => {
|
||||
let enabled = true
|
||||
const app = createPreviewRoutes({ isEnabled: () => enabled, listPorts: async () => [entry({ port: 5173 })] })
|
||||
|
||||
const first = await app.request('/ports')
|
||||
expect((await first.json() as { enabled: boolean }).enabled).toBe(true)
|
||||
|
||||
enabled = false
|
||||
const second = await app.request('/ports')
|
||||
expect((await second.json() as { enabled: boolean }).enabled).toBe(false)
|
||||
|
||||
const disabledSession = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ port: 5173 }),
|
||||
})
|
||||
expect(disabledSession.status).toBe(503)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Preview availability', () => {
|
||||
it('starts in the provided state', () => {
|
||||
expect(createPreviewAvailability(true).isEnabled()).toBe(true)
|
||||
expect(createPreviewAvailability(false).isEnabled()).toBe(false)
|
||||
})
|
||||
|
||||
it('tracks availability transitions', () => {
|
||||
const availability = createPreviewAvailability(true)
|
||||
|
||||
availability.markUnavailable()
|
||||
expect(availability.isEnabled()).toBe(false)
|
||||
|
||||
availability.markAvailable()
|
||||
expect(availability.isEnabled()).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -89,6 +89,7 @@ describe('Repo Project Config Routes', () => {
|
||||
exists: false,
|
||||
trusted: false,
|
||||
hash: null,
|
||||
executable: null,
|
||||
warnings: [],
|
||||
})
|
||||
})
|
||||
@@ -100,6 +101,13 @@ describe('Repo Project Config Routes', () => {
|
||||
expect(await res.json()).toEqual({ error: 'Repo not found' })
|
||||
})
|
||||
|
||||
it('rejects the assistant repo id when assistant access is not allowed', async () => {
|
||||
const res = await app.request('/0/project-config')
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.json()).toEqual({ error: 'Repo not found' })
|
||||
})
|
||||
|
||||
it('returns 404 for a repo that is not ready', async () => {
|
||||
createRepo(db, { localPath: 'repo-cloning', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true })
|
||||
|
||||
@@ -214,6 +222,33 @@ describe('Repo Project Config Routes', () => {
|
||||
expect((await res.json() as { code: string }).code).toBe('REPO_CONFIG_CHANGED')
|
||||
})
|
||||
|
||||
it('returns the error code and details for an untrusted repository action', async () => {
|
||||
seedRepo(db)
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-route-untrusted-'))
|
||||
vi.mocked(resolveRepoWorkingDirectory).mockResolvedValue(directory)
|
||||
const repoFileDir = path.join(directory, '.ocm')
|
||||
fs.mkdirSync(repoFileDir, { recursive: true })
|
||||
fs.writeFileSync(
|
||||
path.join(repoFileDir, 'project.json'),
|
||||
JSON.stringify({ version: 1, projectActions: [{ id: 'repo-serve', name: 'Serve', command: 'pnpm dev' }] }),
|
||||
)
|
||||
|
||||
try {
|
||||
const res = await app.request('/1/project-config/actions/repo-serve/run', {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
const body = await res.json() as { code: string; details: { hash: string } }
|
||||
expect(body.code).toBe('REPO_CONFIG_UNTRUSTED')
|
||||
expect(body.details.hash).toMatch(/^[a-f0-9]{64}$/)
|
||||
} finally {
|
||||
fs.rmSync(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('returns 400 for an invalid move request', async () => {
|
||||
seedRepo(db)
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ const gitAuthService = { getGitEnvironment: vi.fn(() => ({})) } as unknown as Gi
|
||||
const openCodeClient: OpenCodeClient = createStubOpenCodeClient()
|
||||
|
||||
const readyRepo = { id: 1, fullPath: '/tmp/repo', cloneStatus: 'ready' } as Repo
|
||||
const assistantRepo = { id: 0, fullPath: '/tmp/repo', cloneStatus: 'ready' } as Repo
|
||||
|
||||
const shellTerminal = {
|
||||
id: 'pty-1',
|
||||
@@ -54,7 +55,9 @@ 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(resolveRepoOrAssistant).mockImplementation((_db, id) =>
|
||||
id === 1 ? readyRepo : id === 0 ? assistantRepo : null,
|
||||
)
|
||||
vi.mocked(resolveRepoWorkingDirectory).mockImplementation(async (_repo, directory) => {
|
||||
if (directory === undefined || directory === '/tmp/repo') return '/tmp/repo'
|
||||
return null
|
||||
@@ -78,6 +81,15 @@ describe('Repo Terminal Routes', () => {
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('resolves the assistant repo when assistant access is allowed', async () => {
|
||||
const terminals = [{ ...shellTerminal }]
|
||||
const list = vi.fn(async () => terminals)
|
||||
const res = await createApp(createService({ list })).request('/0/terminals')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(list).toHaveBeenCalledWith('/tmp/repo')
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown repo', async () => {
|
||||
vi.mocked(resolveRepoOrAssistant).mockReturnValue(null)
|
||||
const res = await createApp(createService()).request('/2/terminals')
|
||||
|
||||
@@ -871,6 +871,37 @@ describe('Repo Routes', () => {
|
||||
expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1)
|
||||
})
|
||||
|
||||
it('removes terminals for OpenCode workspace siblings but not manager worktree repos', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
|
||||
vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined)
|
||||
vi.mocked(repoService.getSiblingRepos).mockResolvedValue([
|
||||
{ ...createMockRepo({ id: 2, fullPath: '/tmp/repos/manager-worktree', isWorktree: true }), currentBranch: undefined },
|
||||
{ ...createMockRepo({ id: -1, fullPath: '/tmp/plugin-workspace' }), currentBranch: undefined, worktreeStrategy: 'git' },
|
||||
])
|
||||
|
||||
const app = createTestRoutes()
|
||||
const res = await app.request('/1', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/repos/test-repo')
|
||||
expect(mockTerminalService.removeAll).toHaveBeenCalledWith('/tmp/plugin-workspace')
|
||||
expect(mockTerminalService.removeAll).not.toHaveBeenCalledWith('/tmp/repos/manager-worktree')
|
||||
expect(repoService.getSiblingRepos).toHaveBeenCalledWith(mockDb, 1, {}, expect.anything(), { includeBranch: false })
|
||||
expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1)
|
||||
})
|
||||
|
||||
it('still deletes the repo when listing workspace siblings throws', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 }))
|
||||
vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined)
|
||||
vi.mocked(repoService.getSiblingRepos).mockRejectedValue(new Error('siblings failed'))
|
||||
|
||||
const app = createTestRoutes()
|
||||
const res = await app.request('/1', { method: 'DELETE' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(repoService.deleteRepoFiles).toHaveBeenCalledWith(mockDb, 1)
|
||||
})
|
||||
|
||||
it('should return 500 when removing the repo files throws', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1 }))
|
||||
vi.mocked(repoService.deleteRepoFiles).mockRejectedValue(new Error('delete failed'))
|
||||
|
||||
@@ -31,6 +31,17 @@ upstreamApp.get('/cookies', () => {
|
||||
return new Response('ok', { status: 200, headers })
|
||||
})
|
||||
|
||||
upstreamApp.get('/manager-cookies', () => {
|
||||
const headers = new Headers()
|
||||
headers.append('set-cookie', 'app=keep; Path=/')
|
||||
headers.append('set-cookie', `${PREVIEW_COOKIE}=upstream; Path=/`)
|
||||
headers.append('set-cookie', 'opencode.session_token=secret; Path=/')
|
||||
headers.append('set-cookie', '__Secure-opencode.session_token=secure; Path=/')
|
||||
headers.append('set-cookie', '__Host-opencode.session_token=host; Path=/')
|
||||
headers.set('content-type', 'text/plain')
|
||||
return new Response('ok', { status: 200, headers })
|
||||
})
|
||||
|
||||
upstreamApp.all('/*', async (c) => {
|
||||
if (c.req.path === '/r') {
|
||||
return c.redirect(`http://localhost:${upstreamPort}/done`, 302)
|
||||
@@ -42,6 +53,7 @@ upstreamApp.all('/*', async (c) => {
|
||||
search: new URL(c.req.url).search,
|
||||
host: c.req.header('host') ?? null,
|
||||
cookie: c.req.header('cookie') ?? null,
|
||||
acceptEncoding: c.req.header('accept-encoding') ?? null,
|
||||
body,
|
||||
})
|
||||
})
|
||||
@@ -129,6 +141,36 @@ describe('Preview Gateway', () => {
|
||||
expect(res.headers.get('location')).toBe('/')
|
||||
})
|
||||
|
||||
it('rejects redirect paths that resolve off-origin', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
|
||||
for (const malicious of ['/\\evil.example', '//evil.example', 'https://evil.example']) {
|
||||
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
|
||||
const res = await app.request(
|
||||
`http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent(malicious)}`,
|
||||
{ redirect: 'manual' },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(302)
|
||||
expect(res.headers.get('location')).toBe('/')
|
||||
}
|
||||
})
|
||||
|
||||
it('redirects to an allowed same-origin path with query and hash', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
|
||||
|
||||
const res = await app.request(
|
||||
`http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent('/ok?x=1#h')}`,
|
||||
{ redirect: 'manual' },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(302)
|
||||
expect(res.headers.get('location')).toBe('/ok?x=1#h')
|
||||
})
|
||||
|
||||
it('does not allow a start token to be reused', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
@@ -230,6 +272,31 @@ describe('Preview Gateway', () => {
|
||||
expect(cookies).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('drops Manager and preview Set-Cookie values from upstream responses', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, upstreamPort)
|
||||
|
||||
const res = await app.request('http://localhost/manager-cookies', { headers: { cookie } })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.getSetCookie()).toEqual(['app=keep; Path=/'])
|
||||
})
|
||||
|
||||
it('requests identity encoding from the upstream', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, upstreamPort)
|
||||
|
||||
const res = await app.request('http://localhost/echo', {
|
||||
headers: { cookie, 'accept-encoding': 'gzip, br' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { acceptEncoding: string | null }
|
||||
expect(body.acceptEncoding).toBe('identity')
|
||||
})
|
||||
|
||||
it('rewrites an absolute localhost location to its path', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
|
||||
@@ -140,6 +140,41 @@ describe('listListeningPorts', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('stops scanning process fd directories once every listening inode is mapped', async () => {
|
||||
const base = createDeps({
|
||||
files: {
|
||||
'/proc/net/tcp': [PROC_HEADER, procRow('00000000:1435', '00000000:0000', '0A', '11111')].join('\n'),
|
||||
'/proc/1234/comm': 'node\n',
|
||||
},
|
||||
links: {
|
||||
'/proc/1234/fd/3': 'socket:[11111]',
|
||||
'/proc/1234/cwd': '/home/user/project',
|
||||
'/proc/9999/fd/2': 'socket:[11111]',
|
||||
},
|
||||
dirs: {
|
||||
'/proc': ['1234', '9999'],
|
||||
'/proc/1234/fd': ['3'],
|
||||
'/proc/9999/fd': ['2'],
|
||||
},
|
||||
})
|
||||
const readdirCalls: string[] = []
|
||||
const deps: PortDiscoveryDeps = {
|
||||
...base,
|
||||
readdir: async (path) => {
|
||||
readdirCalls.push(path)
|
||||
return base.readdir(path)
|
||||
},
|
||||
}
|
||||
|
||||
const ports = await listListeningPorts(deps)
|
||||
|
||||
expect(ports).toEqual([
|
||||
{ port: 5173, host: '127.0.0.1', pid: 1234, command: 'node', cwd: '/home/user/project' },
|
||||
])
|
||||
expect(readdirCalls).toContain('/proc/1234/fd')
|
||||
expect(readdirCalls).not.toContain('/proc/9999/fd')
|
||||
})
|
||||
|
||||
it('reports an IPv6 loopback host only when the sole listener is IPv6 loopback', async () => {
|
||||
const deps = createDeps({
|
||||
files: {
|
||||
|
||||
@@ -95,6 +95,7 @@ describe('ProjectConfigService personal settings', () => {
|
||||
exists: false,
|
||||
trusted: false,
|
||||
hash: null,
|
||||
executable: null,
|
||||
warnings: [],
|
||||
})
|
||||
})
|
||||
@@ -288,17 +289,39 @@ describe('ProjectConfigService repository file', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps trust across a name-only edit and drops it on a command edit', async () => {
|
||||
it('drops trust when the name, command, or autoOpenUrl changes', async () => {
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
|
||||
const first = await service.getConfig(repo, directory)
|
||||
await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '')
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true)
|
||||
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev' }] })
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(true)
|
||||
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev --host' }] })
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false)
|
||||
|
||||
const renamed = await service.getConfig(repo, directory)
|
||||
await service.trustRepoFile(repo, directory, renamed.repoFile.hash ?? '')
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev', autoOpenUrl: true }],
|
||||
})
|
||||
expect((await service.getConfig(repo, directory)).repoFile.trusted).toBe(false)
|
||||
})
|
||||
|
||||
it('changes the hash when only the name or autoOpenUrl changes', async () => {
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev' }] })
|
||||
const base = await service.getConfig(repo, directory)
|
||||
|
||||
writeRepoFile({ version: 1, projectActions: [{ id: 'serve', name: 'Serve renamed', command: 'pnpm dev' }] })
|
||||
const renamed = await service.getConfig(repo, directory)
|
||||
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', autoOpenUrl: true }],
|
||||
})
|
||||
const autoOpen = await service.getConfig(repo, directory)
|
||||
|
||||
expect(renamed.repoFile.hash).not.toBe(base.repoFile.hash)
|
||||
expect(autoOpen.repoFile.hash).not.toBe(base.repoFile.hash)
|
||||
})
|
||||
|
||||
it('reports invalid JSON with an error and no repository items', async () => {
|
||||
@@ -307,7 +330,7 @@ describe('ProjectConfigService repository file', () => {
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.exists).toBe(true)
|
||||
expect(config.repoFile.error).toBeTruthy()
|
||||
expect(config.repoFile.error).toBe('Invalid JSON')
|
||||
expect(config.repoFile.hash).toBeNull()
|
||||
expect(config.actions).toEqual([])
|
||||
})
|
||||
@@ -317,10 +340,72 @@ describe('ProjectConfigService repository file', () => {
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBeTruthy()
|
||||
expect(config.repoFile.error).toBe('Does not match the project file schema')
|
||||
expect(config.actions).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a repository action url that is not http(s)', async () => {
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', url: 'javascript:alert(1)' }],
|
||||
})
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBe('Does not match the project file schema')
|
||||
expect(config.repoFile.executable).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts an http url template', async () => {
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [{ id: 'serve', name: 'Serve', command: 'pnpm dev', url: 'http://localhost:3000/{branch}' }],
|
||||
})
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.executable?.actions[0]?.url).toBe('http://localhost:3000/{branch}')
|
||||
})
|
||||
|
||||
it('reports a symlinked .ocm directory as invalid on read', async () => {
|
||||
const realDir = path.join(directory, 'real-ocm')
|
||||
fs.mkdirSync(realDir, { recursive: true })
|
||||
fs.writeFileSync(path.join(realDir, 'project.json'), JSON.stringify({ version: 1 }))
|
||||
fs.symlinkSync(realDir, path.join(directory, '.ocm'), 'dir')
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBe('.ocm/project.json must not be a symbolic link')
|
||||
expect(config.repoFile.hash).toBeNull()
|
||||
expect(config.repoFile.executable).toBeNull()
|
||||
})
|
||||
|
||||
it('reports a symlinked project.json as invalid on read', async () => {
|
||||
const ocmDir = path.join(directory, '.ocm')
|
||||
fs.mkdirSync(ocmDir, { recursive: true })
|
||||
const target = path.join(directory, 'target.json')
|
||||
fs.writeFileSync(target, JSON.stringify({ version: 1 }))
|
||||
fs.symlinkSync(target, path.join(ocmDir, 'project.json'))
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.error).toBe('.ocm/project.json must not be a symbolic link')
|
||||
})
|
||||
|
||||
it('refuses to move an action into a symlinked repository config', async () => {
|
||||
service.setPersonalActions(repo, [createAction()])
|
||||
const realDir = path.join(directory, 'real-ocm')
|
||||
fs.mkdirSync(realDir, { recursive: true })
|
||||
fs.writeFileSync(path.join(realDir, 'project.json'), JSON.stringify({ version: 1 }))
|
||||
fs.symlinkSync(realDir, path.join(directory, '.ocm'), 'dir')
|
||||
|
||||
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toMatchObject({
|
||||
status: 400,
|
||||
code: 'REPO_CONFIG_SYMLINK',
|
||||
})
|
||||
expect(service.getPersonalActions(repo)).toEqual([createAction()])
|
||||
})
|
||||
|
||||
it('moves an action personal to repo preserving unknown keys and marking it trusted', async () => {
|
||||
service.setPersonalActions(repo, [createAction()])
|
||||
writeRepoFile({ version: 1, customKey: 'keep-me' })
|
||||
@@ -416,6 +501,34 @@ describe('ProjectConfigService repository file', () => {
|
||||
expect(config.repoFile.warnings[0]).toContain('serve')
|
||||
})
|
||||
|
||||
it('lists every executable repository action including a shadowed one', async () => {
|
||||
service.setPersonalActions(repo, [
|
||||
createAction({ id: 'serve', name: 'Personal Serve', command: 'pnpm personal' }),
|
||||
])
|
||||
writeRepoFile({
|
||||
version: 1,
|
||||
projectActions: [
|
||||
{ id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev', url: 'https://example.com', autoOpenUrl: true },
|
||||
{ id: 'other', name: 'Other', command: 'pnpm other' },
|
||||
],
|
||||
setupWorktree: ['pnpm install'],
|
||||
})
|
||||
|
||||
const config = await service.getConfig(repo, directory)
|
||||
|
||||
expect(config.repoFile.executable).toEqual({
|
||||
actions: [
|
||||
{ id: 'serve', name: 'Repo Serve', command: 'pnpm repo-dev', url: 'https://example.com', autoOpenUrl: true },
|
||||
{ id: 'other', name: 'Other', command: 'pnpm other', url: null, autoOpenUrl: false },
|
||||
],
|
||||
setup: ['pnpm install'],
|
||||
})
|
||||
expect(config.actions).toEqual([
|
||||
{ id: 'serve', name: 'Personal Serve', command: 'pnpm personal', autoOpenUrl: false, source: 'personal' },
|
||||
{ id: 'other', name: 'Other', command: 'pnpm other', autoOpenUrl: false, source: 'repo' },
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects moving an unknown personal action', async () => {
|
||||
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'missing', to: 'repo' })).rejects.toMatchObject({
|
||||
status: 404,
|
||||
@@ -487,12 +600,13 @@ describe('ProjectConfigService repository file', () => {
|
||||
|
||||
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(() => {
|
||||
const writeSeam = service as unknown as { writeRepoFile(filePath: string, file: unknown): void }
|
||||
const writeSpy = vi.spyOn(writeSeam, 'writeRepoFile').mockImplementationOnce(() => {
|
||||
throw new Error('disk full')
|
||||
})
|
||||
|
||||
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'repo' })).rejects.toThrow('disk full')
|
||||
renameSpy.mockRestore()
|
||||
writeSpy.mockRestore()
|
||||
|
||||
expect(fs.existsSync(repoFilePath())).toBe(false)
|
||||
expect(service.getPersonalActions(repo)).toEqual([createAction()])
|
||||
@@ -531,14 +645,15 @@ describe('ProjectConfigService repository file', () => {
|
||||
],
|
||||
})
|
||||
const originalBytes = fs.readFileSync(repoFilePath(), 'utf8')
|
||||
const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
|
||||
const writeSeam = service as unknown as { writeRepoFile(filePath: string, file: unknown): void }
|
||||
const writeSpy = vi.spyOn(writeSeam, 'writeRepoFile').mockImplementationOnce(() => {
|
||||
throw new Error('disk full')
|
||||
})
|
||||
|
||||
await expect(service.moveItem(repo, directory, { kind: 'action', id: 'serve', to: 'personal' })).rejects.toThrow(
|
||||
'disk full',
|
||||
)
|
||||
renameSpy.mockRestore()
|
||||
writeSpy.mockRestore()
|
||||
|
||||
expect(fs.readFileSync(repoFilePath(), 'utf8')).toBe(originalBytes)
|
||||
expect(service.getPersonalActions(repo)).toEqual([])
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { findSiblingByDirectory, resolveRepoWorkingDirectory } from '../../src/services/repo'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { createRepo } from '../../src/db/queries'
|
||||
import { findSiblingByDirectory, getSiblingRepos, resolveRepoWorkingDirectory } from '../../src/services/repo'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
|
||||
const { executeCommand, resolveProjectId, getSettings } = vi.hoisted(() => ({
|
||||
executeCommand: vi.fn(),
|
||||
resolveProjectId: vi.fn(),
|
||||
getSettings: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/process', () => ({ executeCommand }))
|
||||
vi.mock('../../src/services/project-id-resolver', () => ({ resolveProjectId, isGitMainCheckout: vi.fn() }))
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn().mockImplementation(() => ({ getSettings })),
|
||||
}))
|
||||
|
||||
describe('resolveRepoWorkingDirectory', () => {
|
||||
let root: string
|
||||
let repoPath: string
|
||||
@@ -96,3 +112,50 @@ describe('findSiblingByDirectory', () => {
|
||||
expect(findSiblingByDirectory([sibling], path.join(root, 'missing'))).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSiblingRepos branch resolution', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
getSettings.mockReturnValue({ preferences: { repoOrder: [] }, updatedAt: Date.now() })
|
||||
resolveProjectId.mockResolvedValue('project-1')
|
||||
executeCommand.mockReset()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
function seedRepo(): Repo {
|
||||
return createRepo(db, {
|
||||
localPath: 'repo-a',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
})
|
||||
}
|
||||
|
||||
it('skips branch resolution when includeBranch is false', async () => {
|
||||
const repo = seedRepo()
|
||||
|
||||
const siblings = await getSiblingRepos(db, repo.id, {}, undefined, { includeBranch: false })
|
||||
|
||||
expect(siblings).toHaveLength(1)
|
||||
expect(siblings[0]?.currentBranch).toBeUndefined()
|
||||
expect(executeCommand).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves the branch when includeBranch is true', async () => {
|
||||
const repo = seedRepo()
|
||||
executeCommand.mockResolvedValue('feature-branch\n')
|
||||
|
||||
const siblings = await getSiblingRepos(db, repo.id, {})
|
||||
|
||||
expect(siblings).toHaveLength(1)
|
||||
expect(siblings[0]?.currentBranch).toBe('feature-branch')
|
||||
expect(executeCommand).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -65,6 +65,7 @@ interface FakePeer {
|
||||
closeCalls: Array<{ code?: number; reason?: string }>
|
||||
send(data: string | Uint8Array): void
|
||||
close(code?: number, reason?: string): void
|
||||
bufferedAmount(): number
|
||||
}
|
||||
|
||||
function createPeer(): FakePeer {
|
||||
@@ -79,6 +80,9 @@ function createPeer(): FakePeer {
|
||||
close(code, reason) {
|
||||
closeCalls.push({ code, reason })
|
||||
},
|
||||
bufferedAmount() {
|
||||
return 0
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatTerminalTitle, parseTerminalTitle } from '@opencode-manager/shared/utils'
|
||||
import { formatTerminalTitle, isRunningActionTerminal, parseTerminalTitle } from '@opencode-manager/shared/utils'
|
||||
|
||||
describe('terminal-title', () => {
|
||||
describe('formatTerminalTitle', () => {
|
||||
@@ -59,4 +59,22 @@ describe('terminal-title', () => {
|
||||
expect(parseTerminalTitle('ocm:action:dev')).toEqual({ kind: 'shell', title: 'ocm:action:dev' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('isRunningActionTerminal', () => {
|
||||
it('matches a running action terminal for the action id', () => {
|
||||
expect(isRunningActionTerminal({ kind: 'action', actionId: 'dev', status: 'running' }, 'dev')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a terminal for a different action id', () => {
|
||||
expect(isRunningActionTerminal({ kind: 'action', actionId: 'other', status: 'running' }, 'dev')).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a non-action terminal', () => {
|
||||
expect(isRunningActionTerminal({ kind: 'shell', status: 'running' }, 'dev')).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an exited action terminal', () => {
|
||||
expect(isRunningActionTerminal({ kind: 'action', actionId: 'dev', status: 'exited' }, 'dev')).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,8 @@
|
||||
import { mkdtemp, realpath, rm } from 'node:fs/promises'
|
||||
import { mkdtemp, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { canonicalPath, canonicalPathSync } from '../../src/utils/fs-safe'
|
||||
import { canonicalPath, canonicalPathSync, writeFileAtomicSync } from '../../src/utils/fs-safe'
|
||||
|
||||
describe('canonicalPath', () => {
|
||||
let workDir = ''
|
||||
@@ -29,3 +29,41 @@ describe('canonicalPath', () => {
|
||||
expect(canonicalPathSync(missing)).toBe(missing)
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeFileAtomicSync', () => {
|
||||
let workDir = ''
|
||||
|
||||
beforeEach(async () => {
|
||||
workDir = await mkdtemp(path.join(tmpdir(), 'fs-safe-atomic-'))
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(workDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('writes the content and creates missing parent directories', async () => {
|
||||
const target = path.join(workDir, 'nested', 'file.json')
|
||||
|
||||
writeFileAtomicSync(target, '{"ok":true}', { mode: 0o644 })
|
||||
|
||||
await expect(readFile(target, 'utf8')).resolves.toBe('{"ok":true}')
|
||||
expect((await stat(target)).mode & 0o777).toBe(0o644)
|
||||
})
|
||||
|
||||
it('overwrites an existing file', async () => {
|
||||
const target = path.join(workDir, 'file.txt')
|
||||
await writeFile(target, 'old')
|
||||
|
||||
writeFileAtomicSync(target, 'new')
|
||||
|
||||
await expect(readFile(target, 'utf8')).resolves.toBe('new')
|
||||
})
|
||||
|
||||
it('leaves no temp files behind', async () => {
|
||||
const target = path.join(workDir, 'file.txt')
|
||||
|
||||
writeFileAtomicSync(target, 'content')
|
||||
|
||||
await expect(readdir(workDir)).resolves.toEqual(['file.txt'])
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { bridgeWebSocket, type WebSocketPeer } from '../../src/utils/websocket-bridge'
|
||||
import {
|
||||
bridgeWebSocket,
|
||||
forwardPeerMessage,
|
||||
MAX_PEER_BUFFERED_BYTES,
|
||||
type WebSocketBridge,
|
||||
type WebSocketPeer,
|
||||
} from '../../src/utils/websocket-bridge'
|
||||
|
||||
type Listener = (event: unknown) => void
|
||||
|
||||
@@ -28,21 +34,25 @@ class FakeUpstream {
|
||||
interface FakePeer extends WebSocketPeer {
|
||||
sent: Array<string | Uint8Array>
|
||||
closeCalls: Array<{ code?: number; reason?: string }>
|
||||
buffered: number
|
||||
}
|
||||
|
||||
function createPeer(): FakePeer {
|
||||
const sent: Array<string | Uint8Array> = []
|
||||
const closeCalls: Array<{ code?: number; reason?: string }> = []
|
||||
return {
|
||||
sent,
|
||||
closeCalls,
|
||||
const peer: FakePeer = {
|
||||
sent: [],
|
||||
closeCalls: [],
|
||||
buffered: 0,
|
||||
send(data) {
|
||||
sent.push(data)
|
||||
peer.sent.push(data)
|
||||
},
|
||||
close(code, reason) {
|
||||
closeCalls.push({ code, reason })
|
||||
peer.closeCalls.push({ code, reason })
|
||||
},
|
||||
bufferedAmount() {
|
||||
return peer.buffered
|
||||
},
|
||||
}
|
||||
return peer
|
||||
}
|
||||
|
||||
function asUpstream(upstream: FakeUpstream): WebSocket {
|
||||
@@ -111,14 +121,32 @@ describe('bridgeWebSocket', () => {
|
||||
expect(peer.closeCalls).toEqual([{ code: 1011, reason: undefined }])
|
||||
})
|
||||
|
||||
it('applies a custom close-code mapper', () => {
|
||||
it('closes the upstream and peer with 1013 when the peer buffer overflows', () => {
|
||||
const upstream = new FakeUpstream()
|
||||
const peer = createPeer()
|
||||
bridgeWebSocket(asUpstream(upstream), peer, { mapCloseCode: () => 4000 })
|
||||
peer.buffered = MAX_PEER_BUFFERED_BYTES + 1
|
||||
|
||||
upstream.emit('close', { code: 1006 })
|
||||
bridgeWebSocket(asUpstream(upstream), peer)
|
||||
upstream.emit('message', { data: 'overflow' })
|
||||
|
||||
expect(peer.closeCalls).toEqual([{ code: 4000, reason: undefined }])
|
||||
expect(peer.closeCalls).toEqual([{ code: 1013, reason: 'Client too slow' }])
|
||||
expect(upstream.close).toHaveBeenCalledTimes(1)
|
||||
|
||||
upstream.emit('close', { code: 1000 })
|
||||
expect(peer.closeCalls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('keeps bridging while the peer buffer stays within the limit', () => {
|
||||
const upstream = new FakeUpstream()
|
||||
const peer = createPeer()
|
||||
peer.buffered = MAX_PEER_BUFFERED_BYTES
|
||||
|
||||
bridgeWebSocket(asUpstream(upstream), peer)
|
||||
upstream.emit('message', { data: 'within limit' })
|
||||
|
||||
expect(peer.sent).toEqual(['within limit'])
|
||||
expect(peer.closeCalls).toEqual([])
|
||||
expect(upstream.close).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('closes the upstream only once and ignores later sends', () => {
|
||||
@@ -133,3 +161,27 @@ describe('bridgeWebSocket', () => {
|
||||
expect(upstream.sent).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('forwardPeerMessage', () => {
|
||||
function createBridge(sent: Array<string | ArrayBuffer | Uint8Array>): WebSocketBridge {
|
||||
return {
|
||||
send(data) {
|
||||
sent.push(data)
|
||||
},
|
||||
close() {},
|
||||
}
|
||||
}
|
||||
|
||||
it('forwards strings, ArrayBuffers and Blobs to the bridge', async () => {
|
||||
const sent: Array<string | ArrayBuffer | Uint8Array> = []
|
||||
const bridge = createBridge(sent)
|
||||
|
||||
await forwardPeerMessage(bridge, 'plain text')
|
||||
await forwardPeerMessage(bridge, new Uint8Array([1, 2]).buffer)
|
||||
await forwardPeerMessage(bridge, new Blob(['blob body']))
|
||||
|
||||
expect(sent[0]).toBe('plain text')
|
||||
expect(sent[1]).toEqual(new Uint8Array([1, 2]).buffer)
|
||||
expect(new TextDecoder().decode(sent[2] as ArrayBuffer)).toBe('blob body')
|
||||
})
|
||||
})
|
||||
@@ -10,7 +10,7 @@ Complete reference for all configuration options.
|
||||
| `ADMIN_EMAIL` | Pre-configured admin email | - |
|
||||
| `ADMIN_PASSWORD` | Pre-configured admin password | - |
|
||||
| `ADMIN_PASSWORD_RESET` | Set to `true` to reset admin password | `false` |
|
||||
| `AUTH_TRUSTED_ORIGINS` | Comma-separated list of trusted origins (frontend + backend) | `http://localhost:5173,http://localhost:5003` |
|
||||
| `AUTH_TRUSTED_ORIGINS` | Comma-separated list of trusted origins (frontend + backend). Browser requests that change state from another site (`Sec-Fetch-Site: same-site` or `cross-site`) are rejected unless their `Origin` is listed here. Never list the preview gateway origin. | `http://localhost:5173,http://localhost:5003` |
|
||||
| `AUTH_SECURE_COOKIES` | Use secure cookies (HTTPS only) | Runtime: `true` in prod, `false` in dev; Compose: `false` unless set |
|
||||
|
||||
## OAuth Providers
|
||||
@@ -82,8 +82,8 @@ The preview gateway serves dev servers through an authenticated, separate origin
|
||||
|
||||
| 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 |
|
||||
| `PREVIEW_PORT` | Port for the preview gateway. Set to `0` to disable preview entirely. If the port is already in use, the Manager starts anyway, logs a warning and reports preview as unavailable. | `5004` |
|
||||
| `PREVIEW_PUBLIC_URL` | Same-site HTTPS origin that proxies the preview gateway; do not add it to `AUTH_TRUSTED_ORIGINS`. Set this when the Manager is served over HTTPS or behind a reverse proxy, where mixed content and third-party cookies otherwise block the preview iframe. | empty |
|
||||
|
||||
## Database
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ POST /repos/*/schedules/*/runs/*/cancel
|
||||
**Deliberately not allow-listed:**
|
||||
|
||||
- `POST /notifications/send` — use the `send_notification` action instead.
|
||||
- `GET /git-credentials/gh-env` — returns the GitHub CLI environment (`GH_TOKEN`, `GITHUB_TOKEN`) for the OpenCode host process; it must not be readable by the agent.
|
||||
- `GET /git-credentials/gh-env` — returns the shell environment for a working directory (`GH_TOKEN`, `GITHUB_TOKEN`, and the `GIT_AUTHOR_*` / `GIT_COMMITTER_*` identity when the repo has an assigned identity) for the OpenCode host process; it must not be readable by the agent.
|
||||
- `POST /sandbox/shell` — the sandbox planner's internal route that resolves and pins the shell for a `shell` call; exposing it would let the agent drive shell planning directly.
|
||||
- `/repos/*/mirror/*` — the repo mirror protocol that the `ocm` CLI uses to sync entire repositories; it can create, replace, patch, or delete whole repos, so it stays reserved for the CLI.
|
||||
|
||||
|
||||
@@ -6,19 +6,21 @@ The Preview panel lists the loopback ports that are currently listening, then pr
|
||||
|
||||
## 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.
|
||||
Open **Preview** from the desktop sidebar tool list or the **More** drawer, including in the Assistant workspace. The panel lists every listening loopback port on the host, with its port number and process command. On Linux hosts (including the Docker image) it also shows each process's working directory, and ports inside the selected repository or workspace directory are badged **this repo** and sorted first. On macOS the working directory is not available, so no port is badged. Other platforms list no ports.
|
||||
|
||||
The list excludes reserved ports — the Manager port (`PORT`, default 5003), the OpenCode server port (default 5551) and the preview gateway port itself — and only includes ports at or above 1024.
|
||||
The list excludes reserved ports — the Manager port (`PORT`, default 5003), the OpenCode server port (default 5551) and the preview gateway port itself — and only includes ports at or above 1024. Any other listening loopback port can be previewed; there is no per-port allow-list. This grants nothing an authenticated user does not already have, because the [Terminal](terminal.md) can reach the same ports.
|
||||
|
||||
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.
|
||||
While the port list is shown it refreshes every 2 seconds. It stops refreshing while a preview is open.
|
||||
|
||||
When preview is disabled the panel shows **Preview is disabled (PREVIEW_PORT=0)**.
|
||||
Selecting a port creates a preview session and renders the target in an iframe on the gateway origin. The iframe keeps that origin (`allow-same-origin`) so dev servers can use cookies and storage; isolation from the Manager comes from the separate origin, not from an opaque sandbox. Selecting a different port starts a new session for it.
|
||||
|
||||
When preview is unavailable — `PREVIEW_PORT=0`, or the gateway could not listen on its port — the panel shows **Preview is unavailable**.
|
||||
|
||||
If the requested port is not listening yet, the panel shows **Waiting for port N…** and refetches the list every 2 seconds for up to 60 seconds, then shows an error with a **Retry** button.
|
||||
|
||||
## Gateway
|
||||
|
||||
The preview gateway listens on `PREVIEW_PORT` (default 5004) on its own origin. It is a separate origin from the Manager on purpose: preview content is untrusted and must not share the Manager origin. Setting `PREVIEW_PORT=0` disables the gateway.
|
||||
The preview gateway listens on `PREVIEW_PORT` (default 5004) on its own origin. It is a separate origin from the Manager on purpose: preview content is untrusted and must not share the Manager origin. Setting `PREVIEW_PORT=0` disables the gateway. If the port is already in use, the Manager still starts, logs a warning, and reports preview as unavailable.
|
||||
|
||||
Access requires an authenticated preview session:
|
||||
|
||||
@@ -26,10 +28,16 @@ Access requires an authenticated preview session:
|
||||
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.
|
||||
Requests then carry the cookie. Manager auth cookies are stripped before proxying, because host-scoped cookies are shared across ports; the preview target never sees them. In the other direction, any `Set-Cookie` from the preview target that names a Manager auth cookie or `ocm_preview` is dropped, so preview content cannot overwrite the Manager session. The start `path` must stay on the gateway origin; anything else redirects to `/`.
|
||||
|
||||
The gateway asks the target for uncompressed responses. When you use the preview remotely, put a compressing reverse proxy in front of it.
|
||||
|
||||
The gateway also proxies **WebSocket upgrades** on the same origin, so dev-server HMR works through the panel.
|
||||
|
||||
### Isolation level
|
||||
|
||||
A gateway on another port of the same host — or a `PREVIEW_PUBLIC_URL` on a subdomain of the Manager's domain — is a different origin but the **same site** as the Manager, so the browser still sends the Manager's `SameSite=Lax` session cookie with requests from preview content. The Manager therefore rejects state-changing API requests (`POST`, `PUT`, `PATCH`, `DELETE`) whose `Sec-Fetch-Site` is `same-site` or `cross-site` unless their `Origin` is listed in `AUTH_TRUSTED_ORIGINS`. Never add the preview gateway origin to `AUTH_TRUSTED_ORIGINS`.
|
||||
|
||||
A browser can hold one preview target per gateway origin at a time: the `ocm_preview` cookie names a single session. Opening a different port replaces the current target.
|
||||
|
||||
## Opening Previews
|
||||
@@ -54,7 +62,7 @@ By default the panel builds the gateway origin as `${location.protocol}//${locat
|
||||
- **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.
|
||||
Set `PREVIEW_PUBLIC_URL` to a same-site HTTPS origin that proxies the preview gateway, for example `https://preview.example.com`. Do not add it to `AUTH_TRUSTED_ORIGINS` (see [Isolation level](#isolation-level)). The panel then builds preview URLs from that origin instead. As a fallback, **Open in new tab** opens the preview as a top-level page, where the session cookie is first-party.
|
||||
|
||||
## Related
|
||||
|
||||
|
||||
@@ -72,7 +72,12 @@ Actions defined in the repository file never run until trusted (see [Trust](#tru
|
||||
|
||||
- `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.
|
||||
- An action `url` must start with `http://` or `https://`.
|
||||
- A repository action whose `id` matches a personal action is not listed or run, and the dialog reports a warning, so personal actions always win. It is still part of the file's trusted content (see [Trust](#trust)).
|
||||
- `.ocm` and `.ocm/project.json` must be regular files and directories. A symbolic link at either path is reported as an invalid file and is never written through.
|
||||
- The file is read from the selected repository or workspace directory, so each worktree can carry its own version. Trust is stored once per project, so trusting the file in one worktree does not trust a different version of it in another.
|
||||
|
||||
Project actions are not available in the Assistant workspace.
|
||||
|
||||
## Moving Actions and Setup Commands
|
||||
|
||||
@@ -87,8 +92,9 @@ Moves are transactional: if the file write or the settings update fails, the fil
|
||||
|
||||
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.
|
||||
- Trust covers everything in the file that can run or open: each action's `id`, `name`, `command`, `url` and `autoOpenUrl` (including actions hidden because a personal action has the same `id`), plus every setup command. Changing any of these resets trust; changing an icon does not.
|
||||
- Both trust prompts — **Trust these commands** in the dialog and **Trust and run** in the header menu — list every action and setup command that trusting covers, not only the one you clicked.
|
||||
- Trusting requires echoing the exact hash of the content shown, so a file cannot be swapped between review and trust.
|
||||
- Untrusted repository commands never run — not from the header menu, and not as worktree setup commands.
|
||||
- The dialog shows the untrusted commands and a **Trust these commands** button. Attempting to run an untrusted action prompts for trust first.
|
||||
- Moving an item into the file auto-trusts it, because the user authored it.
|
||||
|
||||
@@ -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`), 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 |
|
||||
| PTY terminals (`POST /api/pty`, `POST /api/pty/:ptyID/connect`), including the Manager Terminal panel and project action terminals | No; normal OpenCode behavior, with the user's configured shell. Manager terminals and project actions receive the repo-scoped GitHub token env, and the commit identity env when the repo has an assigned identity, 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. 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.
|
||||
PTY terminals follow OpenCode's normal host-process behavior during enforcement and use the user's configured shell. This includes the Manager [Terminal panel](terminal.md) and [project actions](project-actions.md): they run as OpenCode PTYs on the host, receive the repo-scoped GitHub token env, and the commit identity env when the repo has an assigned identity, 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.
|
||||
|
||||
|
||||
@@ -39,8 +39,10 @@ Terminals run as OpenCode PTYs on the host, using the user's configured shell. T
|
||||
|
||||
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.
|
||||
- the repository's GitHub token environment (`GH_TOKEN`, `GITHUB_TOKEN`), so `gh` authenticates with the repo's GitHub credential;
|
||||
- the repository's assigned git commit identity, when one is assigned, so commits made in the terminal use that author.
|
||||
|
||||
`git` itself authenticates with the same credentials as the OpenCode server process, which the Manager configures from its saved git credentials.
|
||||
|
||||
## Related
|
||||
|
||||
|
||||
@@ -3,16 +3,14 @@ import type { CreatePreviewSessionResponse, PreviewPortsResponse } from '@openco
|
||||
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) {
|
||||
function previewPortsQueryKey(directory: string | undefined) {
|
||||
return ['previewPorts', directory ?? null] as const
|
||||
}
|
||||
|
||||
export function listPreviewPorts(directory?: string): Promise<PreviewPortsResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/preview/ports${directoryQuery(directory)}`)
|
||||
function listPreviewPorts(directory?: string): Promise<PreviewPortsResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/preview/ports`, {
|
||||
params: { directory },
|
||||
})
|
||||
}
|
||||
|
||||
export function createPreviewSession(port: number): Promise<CreatePreviewSessionResponse> {
|
||||
|
||||
@@ -9,43 +9,43 @@ import type {
|
||||
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) {
|
||||
function projectConfigQueryKey(repoId: number, directory: string | undefined) {
|
||||
return ['projectConfig', repoId, directory ?? null] as const
|
||||
}
|
||||
|
||||
export function getProjectConfig(repoId: number, directory?: string): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config${directoryQuery(directory)}`)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config`, {
|
||||
params: { directory },
|
||||
})
|
||||
}
|
||||
|
||||
export function updateProjectActions(
|
||||
function updateProjectActions(
|
||||
repoId: number,
|
||||
actions: ProjectAction[],
|
||||
directory?: string,
|
||||
): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/actions${directoryQuery(directory)}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/actions`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ actions }),
|
||||
params: { directory },
|
||||
})
|
||||
}
|
||||
|
||||
export function updateWorktreeSetup(
|
||||
function updateWorktreeSetup(
|
||||
repoId: number,
|
||||
commands: string[],
|
||||
directory?: string,
|
||||
): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/worktree-setup${directoryQuery(directory)}`, {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/worktree-setup`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ commands }),
|
||||
params: { directory },
|
||||
})
|
||||
}
|
||||
|
||||
export function trustRepoConfig(repoId: number, request: TrustRepoConfigRequest): Promise<ProjectConfigResponse> {
|
||||
function trustRepoConfig(repoId: number, request: TrustRepoConfigRequest): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/trust`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -53,7 +53,7 @@ export function trustRepoConfig(repoId: number, request: TrustRepoConfigRequest)
|
||||
})
|
||||
}
|
||||
|
||||
export function moveProjectItem(repoId: number, request: MoveProjectItemRequest): Promise<ProjectConfigResponse> {
|
||||
function moveProjectItem(repoId: number, request: MoveProjectItemRequest): Promise<ProjectConfigResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/project-config/move`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -61,7 +61,7 @@ export function moveProjectItem(repoId: number, request: MoveProjectItemRequest)
|
||||
})
|
||||
}
|
||||
|
||||
export function runProjectAction(
|
||||
function runProjectAction(
|
||||
repoId: number,
|
||||
actionId: string,
|
||||
directory?: string,
|
||||
@@ -89,7 +89,7 @@ export function useUpdateProjectActions(repoId: number, directory: string | unde
|
||||
return useMutation({
|
||||
mutationFn: (actions: ProjectAction[]) => updateProjectActions(repoId, actions, directory),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
|
||||
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, directory) })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -99,7 +99,7 @@ export function useUpdateWorktreeSetup(repoId: number, directory: string | undef
|
||||
return useMutation({
|
||||
mutationFn: (commands: string[]) => updateWorktreeSetup(repoId, commands, directory),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
|
||||
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, directory) })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -108,8 +108,8 @@ export function useTrustRepoConfig(repoId: number) {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (request: TrustRepoConfigRequest) => trustRepoConfig(repoId, request),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
|
||||
onSuccess: (_data, request) => {
|
||||
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, request.directory) })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -118,8 +118,8 @@ export function useMoveProjectItem(repoId: number) {
|
||||
const queryClient = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (request: MoveProjectItemRequest) => moveProjectItem(repoId, request),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
|
||||
onSuccess: (_data, request) => {
|
||||
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, request.directory) })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -129,7 +129,7 @@ export function useRunProjectAction(repoId: number, directory: string | undefine
|
||||
return useMutation({
|
||||
mutationFn: (actionId: string) => runProjectAction(repoId, actionId, directory),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projectConfig', repoId] })
|
||||
queryClient.invalidateQueries({ queryKey: projectConfigQueryKey(repoId, directory) })
|
||||
queryClient.invalidateQueries({ queryKey: ['terminals', repoId] })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -3,22 +3,23 @@ import type { CreateTerminalRequest, ResizeTerminalRequest, TerminalInfo } from
|
||||
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) {
|
||||
function terminalsQueryKey(repoId: number, directory: string | undefined) {
|
||||
return ['terminals', repoId, directory ?? null] as const
|
||||
}
|
||||
|
||||
export async function listTerminals(repoId: number, directory?: string): Promise<TerminalInfo[]> {
|
||||
function terminalsRepoQueryKey(repoId: number) {
|
||||
return ['terminals', repoId] as const
|
||||
}
|
||||
|
||||
async function listTerminals(repoId: number, directory?: string): Promise<TerminalInfo[]> {
|
||||
const data = await fetchWrapper<{ terminals: TerminalInfo[] }>(
|
||||
`${API_BASE_URL}/api/repos/${repoId}/terminals${directoryQuery(directory)}`,
|
||||
`${API_BASE_URL}/api/repos/${repoId}/terminals`,
|
||||
{ params: { directory } },
|
||||
)
|
||||
return data.terminals
|
||||
}
|
||||
|
||||
export async function createTerminal(repoId: number, body: CreateTerminalRequest): Promise<TerminalInfo> {
|
||||
async function createTerminal(repoId: number, body: CreateTerminalRequest): Promise<TerminalInfo> {
|
||||
return fetchWrapper<TerminalInfo>(`${API_BASE_URL}/api/repos/${repoId}/terminals`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
@@ -34,14 +35,14 @@ export async function resizeTerminal(repoId: number, ptyID: string, body: Resize
|
||||
})
|
||||
}
|
||||
|
||||
export async function removeTerminal(repoId: number, ptyID: string, directory?: string): Promise<void> {
|
||||
return fetchWrapperVoid(
|
||||
`${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}${directoryQuery(directory)}`,
|
||||
{ method: 'DELETE' },
|
||||
)
|
||||
async function removeTerminal(repoId: number, ptyID: string, directory?: string): Promise<void> {
|
||||
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}`, {
|
||||
method: 'DELETE',
|
||||
params: { directory },
|
||||
})
|
||||
}
|
||||
|
||||
export interface UseTerminalsOptions {
|
||||
interface UseTerminalsOptions {
|
||||
enabled: boolean
|
||||
refetchInterval?: number | false
|
||||
}
|
||||
@@ -60,12 +61,12 @@ export function useCreateTerminal(repoId: number) {
|
||||
return useMutation({
|
||||
mutationFn: (body: CreateTerminalRequest) => createTerminal(repoId, body),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['terminals', repoId] })
|
||||
queryClient.invalidateQueries({ queryKey: terminalsRepoQueryKey(repoId) })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export interface RemoveTerminalVariables {
|
||||
interface RemoveTerminalVariables {
|
||||
ptyID: string
|
||||
directory?: string
|
||||
}
|
||||
@@ -75,7 +76,7 @@ export function useRemoveTerminal(repoId: number) {
|
||||
return useMutation({
|
||||
mutationFn: ({ ptyID, directory }: RemoveTerminalVariables) => removeTerminal(repoId, ptyID, directory),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['terminals', repoId] })
|
||||
queryClient.invalidateQueries({ queryKey: terminalsRepoQueryKey(repoId) })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -60,9 +60,20 @@ describe('buildMoreItems', () => {
|
||||
expect(items[11].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('omits the Actions item for an Assistant session', () => {
|
||||
const items = buildMoreItems('/repos/0/sessions/abc')
|
||||
expect(items).toHaveLength(11)
|
||||
expect(items.map((item) => item.key)).not.toContain('actions')
|
||||
expect(items[7].key).toBe('terminal')
|
||||
expect(items[8].key).toBe('preview')
|
||||
expect(items[8].dialog).toBe('preview')
|
||||
expect(items[9].key).toBe('settings')
|
||||
expect(items[10].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns assistant workspace items for /repos/:id/assistant', () => {
|
||||
const items = buildMoreItems('/repos/42/assistant')
|
||||
expect(items).toHaveLength(10)
|
||||
expect(items).toHaveLength(11)
|
||||
expect(items[0].key).toBe('home')
|
||||
expect(items[1].key).toBe('files')
|
||||
expect(items[1].dialog).toBe('files')
|
||||
@@ -73,8 +84,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('preview')
|
||||
expect(items[8].dialog).toBe('preview')
|
||||
expect(items[9].key).toBe('settings')
|
||||
expect(items[10].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns only Home + Settings + Logout for /schedules', () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
|
||||
|
||||
export interface MoreDrawerItem {
|
||||
@@ -72,15 +73,19 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
|
||||
const sessionDetailMatch = /^\/repos\/(\d+)\/sessions\/[^/]+$/.exec(pathname)
|
||||
if (sessionDetailMatch) {
|
||||
const repoId = sessionDetailMatch[1]
|
||||
const isAssistantRepo = repoId === String(ASSISTANT_REPO_ID)
|
||||
const items: MoreDrawerItem[] = [
|
||||
{ key: 'files', label: 'Files', icon: Folder, dialog: 'files' },
|
||||
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
|
||||
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
|
||||
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
|
||||
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${sessionDetailMatch[1]}/schedules` },
|
||||
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${repoId}/schedules` },
|
||||
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' },
|
||||
...(isAssistantRepo
|
||||
? []
|
||||
: [{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' }]),
|
||||
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
|
||||
...baseItems,
|
||||
]
|
||||
@@ -100,6 +105,7 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: '/repos/0/schedules' },
|
||||
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
|
||||
...baseItems,
|
||||
]
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ type PreviewPortsResult = ReturnType<typeof usePreviewPorts>
|
||||
|
||||
const portsData = {
|
||||
enabled: true,
|
||||
ports: [{ port: 5173, host: '127.0.0.1' as const, pid: 10, command: 'vite', cwd: '/repo' }],
|
||||
ports: [{ port: 5173, host: '127.0.0.1' as const, pid: 10, command: 'vite', cwd: '/repo', inDirectory: true }],
|
||||
}
|
||||
|
||||
let portsState: PreviewPortsResult['data'] = portsData
|
||||
@@ -106,15 +106,43 @@ describe('PreviewPanel', () => {
|
||||
portsState = { enabled: false, ports: [] }
|
||||
renderPanel('/repos/1?dialog=preview')
|
||||
|
||||
expect(screen.getByText(/Preview is disabled/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Preview is unavailable/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('badges ports that run inside the directory', () => {
|
||||
it('badges ports marked as inside the directory', () => {
|
||||
renderPanel('/repos/1?dialog=preview')
|
||||
|
||||
expect(screen.getByText('this repo')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not badge ports marked as outside the directory', () => {
|
||||
portsState = {
|
||||
enabled: true,
|
||||
ports: [{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: '/elsewhere', inDirectory: false }],
|
||||
}
|
||||
renderPanel('/repos/1?dialog=preview')
|
||||
|
||||
expect(screen.queryByText('this repo')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('polls the port list while no preview session is active', () => {
|
||||
renderPanel('/repos/1?dialog=preview')
|
||||
|
||||
const lastOptions = vi.mocked(usePreviewPorts).mock.calls.at(-1)?.[1]
|
||||
expect(lastOptions?.enabled).toBe(true)
|
||||
expect(lastOptions?.refetchInterval).toBe(2000)
|
||||
})
|
||||
|
||||
it('stops polling once a preview session is active', async () => {
|
||||
renderPanel()
|
||||
|
||||
await screen.findByTitle('Preview')
|
||||
|
||||
const lastOptions = vi.mocked(usePreviewPorts).mock.calls.at(-1)?.[1]
|
||||
expect(lastOptions?.enabled).toBe(true)
|
||||
expect(lastOptions?.refetchInterval).toBe(false)
|
||||
})
|
||||
|
||||
it('mints a fresh session when a listed port disappears and comes back', async () => {
|
||||
const first = deferred<CreatePreviewSessionResponse>()
|
||||
const second = deferred<CreatePreviewSessionResponse>()
|
||||
|
||||
@@ -6,7 +6,8 @@ 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 { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { buildPreviewStartUrl, getPreviewOrigin, isSameOriginAsManager, parsePort } from '@/lib/preview-url'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface PreviewPanelProps {
|
||||
@@ -38,26 +39,13 @@ interface ActiveSession {
|
||||
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
|
||||
const port = parsePort(searchParams.get('previewPort') ?? '')
|
||||
return port ?? undefined
|
||||
}, [searchParams])
|
||||
const requestedPath = searchParams.get('previewPath') || '/'
|
||||
|
||||
@@ -71,9 +59,11 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
|
||||
const activePathRef = useRef<string | null>(null)
|
||||
const requestIdRef = useRef(0)
|
||||
|
||||
const activeSession = session && session.targetPort === requestedPort ? session : null
|
||||
|
||||
const portsQuery = usePreviewPorts(directory, {
|
||||
enabled: isOpen,
|
||||
refetchInterval: isOpen ? 2000 : false,
|
||||
refetchInterval: isOpen && !activeSession ? 2000 : false,
|
||||
})
|
||||
const ports = useMemo(() => portsQuery.data?.ports ?? [], [portsQuery.data])
|
||||
const enabled = portsQuery.data?.enabled ?? true
|
||||
@@ -127,7 +117,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
|
||||
if (requestIdRef.current !== requestId) return
|
||||
sessionPortRef.current = null
|
||||
activePathRef.current = null
|
||||
setSessionError(errorMessage(error, 'Failed to start preview'))
|
||||
setSessionError(getOpenCodeApiErrorMessage(error, 'Failed to start preview'))
|
||||
})
|
||||
}, [])
|
||||
|
||||
@@ -166,7 +156,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
|
||||
window.open(buildPreviewStartUrl(data, requestedPath), '_blank', 'noopener,noreferrer')
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
setSessionError(errorMessage(error, 'Failed to open preview'))
|
||||
setSessionError(getOpenCodeApiErrorMessage(error, 'Failed to open preview'))
|
||||
})
|
||||
}, [requestedPort, requestedPath])
|
||||
|
||||
@@ -180,7 +170,6 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
|
||||
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]
|
||||
@@ -200,7 +189,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
|
||||
|
||||
const body = () => {
|
||||
if (!enabled) {
|
||||
return renderMessage('Preview is disabled (PREVIEW_PORT=0)')
|
||||
return renderMessage('Preview is unavailable')
|
||||
}
|
||||
if (!requestedPort) {
|
||||
return renderMessage('Select a port to preview')
|
||||
@@ -338,7 +327,7 @@ export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps)
|
||||
>
|
||||
<span className="font-medium">:{entry.port}</span>
|
||||
{entry.command && <span className="truncate">{entry.command}</span>}
|
||||
{isInsideDirectory(entry.cwd, directory) && (
|
||||
{entry.inDirectory && (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px]">this repo</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { AlertCircle, GitBranch, Loader2 } from 'lucide-react'
|
||||
import { createRepo, listBranches } from '@/api/repos'
|
||||
import { dialogSearch } from '@/hooks/useDialogParam'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { notifyWorktreeSetup } from '@/lib/worktreeSetup'
|
||||
import { invalidateRepoGitCaches } from '@/lib/queryInvalidation'
|
||||
@@ -76,7 +77,7 @@ export function CreateWorktreeDialog({
|
||||
onOpenChange(false)
|
||||
notifyWorktreeSetup(repo.worktreeSetup)
|
||||
if (repo.worktreeSetup?.status === 'started') {
|
||||
navigate(`/repos/${repo.id}?dialog=terminal&terminal=${encodeURIComponent(repo.worktreeSetup.terminal.id)}`)
|
||||
navigate(`/repos/${repo.id}${dialogSearch('terminal', { terminal: repo.worktreeSetup.terminal.id })}`)
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
|
||||
@@ -42,6 +42,11 @@ vi.mock('@/lib/toast', () => ({
|
||||
const HASH = 'a'.repeat(64)
|
||||
const OTHER_HASH = 'b'.repeat(64)
|
||||
|
||||
const repoExecutable: NonNullable<ProjectConfigResponse['repoFile']['executable']> = {
|
||||
actions: [{ id: 'dev', name: 'Dev server', command: 'pnpm dev', url: null, autoOpenUrl: false }],
|
||||
setup: [],
|
||||
}
|
||||
|
||||
const devAction: ProjectConfigResponse['actions'][number] = {
|
||||
id: 'dev',
|
||||
name: 'Dev server',
|
||||
@@ -67,11 +72,19 @@ const runningTerminal: TerminalInfo = {
|
||||
function makeConfig(
|
||||
actions: ProjectConfigResponse['actions'],
|
||||
hash: string | null = null,
|
||||
executable: ProjectConfigResponse['repoFile']['executable'] = null,
|
||||
): ProjectConfigResponse {
|
||||
return {
|
||||
actions,
|
||||
worktreeSetup: [],
|
||||
repoFile: { path: '.ocm/project.json', exists: hash !== null, trusted: true, hash, warnings: [] },
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: hash !== null,
|
||||
trusted: true,
|
||||
hash,
|
||||
warnings: [],
|
||||
executable,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,8 +155,8 @@ describe('ProjectActionsMenu', () => {
|
||||
})
|
||||
|
||||
it('trusts the repository config after a 409 and retries the run', async () => {
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, repoExecutable))
|
||||
let runCalls = 0
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => {
|
||||
runCalls += 1
|
||||
@@ -171,10 +184,52 @@ describe('ProjectActionsMenu', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('lists every executable action and setup command, including shadowed actions', async () => {
|
||||
const executable: NonNullable<ProjectConfigResponse['repoFile']['executable']> = {
|
||||
actions: [
|
||||
{ id: 'dev', name: 'Dev server', command: 'pnpm dev', url: 'http://localhost:3000', autoOpenUrl: true },
|
||||
{ id: 'shadowed', name: 'Shadowed action', command: 'pnpm shadowed', url: null, autoOpenUrl: false },
|
||||
],
|
||||
setup: ['pnpm install'],
|
||||
}
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, executable), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, executable))
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
|
||||
const user = userEvent.setup()
|
||||
renderMenu()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Project actions' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: /dev server/i }))
|
||||
|
||||
expect(await screen.findByText('Trust repository actions')).toBeInTheDocument()
|
||||
expect(await screen.findByText('Actions')).toBeInTheDocument()
|
||||
expect(screen.getByText('Shadowed action')).toBeInTheDocument()
|
||||
expect(screen.getByText('pnpm shadowed')).toBeInTheDocument()
|
||||
expect(screen.getByText('http://localhost:3000')).toBeInTheDocument()
|
||||
expect(screen.getByText('Opens URL automatically')).toBeInTheDocument()
|
||||
expect(screen.getByText('Worktree setup commands')).toBeInTheDocument()
|
||||
expect(screen.getByText('pnpm install')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not offer trust when the snapshot has no executable commands', async () => {
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
|
||||
const user = userEvent.setup()
|
||||
renderMenu()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Project actions' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: /dev server/i }))
|
||||
|
||||
await waitFor(() => expect(mocks.showToastError).toHaveBeenCalled())
|
||||
expect(screen.queryByText('Trust repository actions')).not.toBeInTheDocument()
|
||||
expect(mocks.trustMutate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the freshly verified command when the cached config is stale', async () => {
|
||||
const staleAction: ProjectConfigResponse['actions'][number] = { ...repoAction, command: 'pnpm dev:stale' }
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([staleAction], HASH), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([staleAction], HASH, repoExecutable), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, repoExecutable))
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
|
||||
const user = userEvent.setup()
|
||||
renderMenu()
|
||||
@@ -187,8 +242,8 @@ describe('ProjectActionsMenu', () => {
|
||||
})
|
||||
|
||||
it('refuses confirmation when the fresh hash differs from the 409 hash', async () => {
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], OTHER_HASH))
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], OTHER_HASH, repoExecutable))
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
|
||||
const user = userEvent.setup()
|
||||
renderMenu()
|
||||
@@ -202,8 +257,8 @@ describe('ProjectActionsMenu', () => {
|
||||
})
|
||||
|
||||
it('refuses confirmation when the action is no longer a repository action', async () => {
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([devAction], HASH))
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([devAction], HASH, repoExecutable))
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
|
||||
const user = userEvent.setup()
|
||||
renderMenu()
|
||||
@@ -217,8 +272,8 @@ describe('ProjectActionsMenu', () => {
|
||||
})
|
||||
|
||||
it('cancels a pending confirmation when the directory changes', async () => {
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, repoExecutable))
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
|
||||
const user = userEvent.setup()
|
||||
const capturedSearch: { current: string } = { current: '' }
|
||||
@@ -237,8 +292,8 @@ describe('ProjectActionsMenu', () => {
|
||||
})
|
||||
|
||||
it('does not retry the run when the trust response arrives after switching directory', async () => {
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH))
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([repoAction], HASH, repoExecutable), isLoading: false, error: null })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([repoAction], HASH, repoExecutable))
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
|
||||
let trustOptions: { onSuccess: () => void } | undefined
|
||||
mocks.trustMutate.mockImplementation((_vars, options) => {
|
||||
|
||||
@@ -1,23 +1,12 @@
|
||||
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { TerminalInfo } from '@opencode-manager/shared/types'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { isRunningActionTerminal } from '@opencode-manager/shared/utils'
|
||||
import type {
|
||||
ProjectActionIcon,
|
||||
ProjectConfigResponse,
|
||||
RunProjectActionResponse,
|
||||
} from '@opencode-manager/shared/types'
|
||||
import {
|
||||
Bug,
|
||||
CheckCircle2,
|
||||
FlaskConical,
|
||||
Hammer,
|
||||
Play,
|
||||
Rocket,
|
||||
Server,
|
||||
Square,
|
||||
SquareTerminal,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react'
|
||||
import { Play, Square } from 'lucide-react'
|
||||
import {
|
||||
getProjectConfig,
|
||||
useProjectConfig,
|
||||
@@ -37,20 +26,13 @@ import {
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { openDialogParam } from '@/hooks/useDialogParam'
|
||||
import { useOpenPreview } from '@/hooks/useOpenPreview'
|
||||
import { useOpenTerminal } from '@/hooks/useOpenTerminal'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { openUrlFromManager } from '@/lib/open-url'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
const ACTION_ICONS: Record<ProjectActionIcon, LucideIcon> = {
|
||||
play: Play,
|
||||
build: Hammer,
|
||||
test: FlaskConical,
|
||||
lint: CheckCircle2,
|
||||
terminal: SquareTerminal,
|
||||
server: Server,
|
||||
bug: Bug,
|
||||
rocket: Rocket,
|
||||
}
|
||||
import { TrustExecutableList } from './TrustExecutableList'
|
||||
import { actionIcon } from './projectActionIcons'
|
||||
|
||||
interface ProjectActionsMenuProps {
|
||||
repoId: number
|
||||
@@ -61,7 +43,7 @@ interface PendingTrust {
|
||||
actionId: string
|
||||
hash: string
|
||||
directory: string
|
||||
command: string
|
||||
executable: NonNullable<ProjectConfigResponse['repoFile']['executable']>
|
||||
}
|
||||
|
||||
function untrustedHash(error: unknown): string | null {
|
||||
@@ -73,14 +55,11 @@ function untrustedHash(error: unknown): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
return error instanceof Error ? error.message : fallback
|
||||
}
|
||||
|
||||
export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProps) {
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const { updateParams } = useUrlParams()
|
||||
const openPreview = useOpenPreview()
|
||||
const openTerminal = useOpenTerminal()
|
||||
const configQuery = useProjectConfig(repoId, directory, menuOpen && !!directory)
|
||||
const terminalsQuery = useTerminals(repoId, directory, {
|
||||
enabled: menuOpen && !!directory,
|
||||
@@ -105,7 +84,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
|
||||
const runningByAction = useMemo(() => {
|
||||
const map = new Map<string, TerminalInfo>()
|
||||
for (const terminal of terminalsQuery.data ?? []) {
|
||||
if (terminal.kind === 'action' && terminal.actionId && terminal.status === 'running') {
|
||||
if (terminal.actionId && isRunningActionTerminal(terminal, terminal.actionId)) {
|
||||
map.set(terminal.actionId, terminal)
|
||||
}
|
||||
}
|
||||
@@ -113,15 +92,11 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
|
||||
}, [terminalsQuery.data])
|
||||
|
||||
const handleRunSuccess = useCallback((result: RunProjectActionResponse) => {
|
||||
updateParams((params) => {
|
||||
params.set('dialog', 'terminal')
|
||||
params.set('terminal', result.terminal.id)
|
||||
params.delete('mobileTab')
|
||||
}, 'push')
|
||||
openTerminal(result.terminal.id)
|
||||
if (result.autoOpenUrl && result.resolvedUrl) {
|
||||
openUrlFromManager(result.resolvedUrl, { openPreview })
|
||||
}
|
||||
}, [updateParams, openPreview])
|
||||
}, [openTerminal, openPreview])
|
||||
|
||||
const requestTrustConfirmation = useCallback(async (actionId: string, hash: string) => {
|
||||
const requestDirectory = directory
|
||||
@@ -130,7 +105,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
|
||||
try {
|
||||
snapshot = await getProjectConfig(repoId, requestDirectory)
|
||||
} catch (error) {
|
||||
showToast.error(errorMessage(error, 'Failed to verify repository actions'))
|
||||
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to verify repository actions'))
|
||||
return
|
||||
}
|
||||
const scope = scopeRef.current
|
||||
@@ -138,11 +113,12 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
|
||||
const repoAction = snapshot.actions.find(
|
||||
(action) => action.id === actionId && action.source === 'repo',
|
||||
)
|
||||
if (snapshot.repoFile.hash !== hash || !repoAction) {
|
||||
const executable = snapshot.repoFile.executable
|
||||
if (snapshot.repoFile.hash !== hash || !repoAction || !executable) {
|
||||
showToast.error('Repository actions changed. Reopen the menu to review them.')
|
||||
return
|
||||
}
|
||||
setPendingTrust({ actionId, hash, directory: requestDirectory, command: repoAction.command })
|
||||
setPendingTrust({ actionId, hash, directory: requestDirectory, executable })
|
||||
}, [directory, repoId])
|
||||
|
||||
const startRun = useCallback((actionId: string) => {
|
||||
@@ -154,7 +130,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
|
||||
void requestTrustConfirmation(actionId, hash)
|
||||
return
|
||||
}
|
||||
showToast.error(errorMessage(error, 'Failed to run action'))
|
||||
showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to run action'))
|
||||
},
|
||||
})
|
||||
}, [runAction, handleRunSuccess, requestTrustConfirmation])
|
||||
@@ -170,13 +146,13 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
|
||||
setPendingTrust(null)
|
||||
startRun(actionId)
|
||||
},
|
||||
onError: (error) => showToast.error(errorMessage(error, 'Failed to trust repository commands')),
|
||||
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to trust repository commands')),
|
||||
})
|
||||
}, [pendingTrust, trustConfig, startRun, repoId])
|
||||
|
||||
const handleStop = useCallback((terminal: TerminalInfo) => {
|
||||
removeTerminal.mutate({ ptyID: terminal.id, directory }, {
|
||||
onError: (error) => showToast.error(errorMessage(error, 'Failed to stop action')),
|
||||
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to stop action')),
|
||||
})
|
||||
}, [removeTerminal, directory])
|
||||
|
||||
@@ -206,7 +182,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
|
||||
</DropdownMenuLabel>
|
||||
) : (
|
||||
actions.map((action) => {
|
||||
const Icon = ACTION_ICONS[action.icon ?? 'play']
|
||||
const Icon = actionIcon(action.icon)
|
||||
const running = runningByAction.get(action.id)
|
||||
return (
|
||||
<Fragment key={action.id}>
|
||||
@@ -242,7 +218,7 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
|
||||
onCancel={() => setPendingTrust(null)}
|
||||
title="Trust repository actions"
|
||||
description="This repository defines commands that run on your machine."
|
||||
warning={pendingTrust?.command}
|
||||
warning={pendingTrust ? <TrustExecutableList executable={pendingTrust.executable} /> : undefined}
|
||||
confirmLabel="Trust and run"
|
||||
pendingLabel="Trusting…"
|
||||
isPending={trustConfig.isPending}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { RepoActionsDialog } from './RepoActionsDialog'
|
||||
import type { ProjectConfigResponse } from '@opencode-manager/shared/types'
|
||||
|
||||
@@ -31,7 +32,14 @@ function baseConfig(overrides: Partial<ProjectConfigResponse> = {}): ProjectConf
|
||||
return {
|
||||
actions: [],
|
||||
worktreeSetup: [],
|
||||
repoFile: { path: '.ocm/project.json', exists: false, trusted: false, hash: null, warnings: [] },
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: false,
|
||||
trusted: false,
|
||||
hash: null,
|
||||
warnings: [],
|
||||
executable: null,
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
@@ -119,7 +127,19 @@ describe('RepoActionsDialog', () => {
|
||||
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: [] },
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: true,
|
||||
trusted: false,
|
||||
hash: HASH,
|
||||
warnings: [],
|
||||
executable: {
|
||||
actions: [
|
||||
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', url: null, autoOpenUrl: false },
|
||||
],
|
||||
setup: [],
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
@@ -131,10 +151,74 @@ describe('RepoActionsDialog', () => {
|
||||
expect(mocks.trustMutate.mock.calls[0][0]).toEqual({ hash: HASH, directory: '/repo' })
|
||||
})
|
||||
|
||||
it('lists every executable action and setup command, including shadowed actions', () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
actions: [
|
||||
{ id: 'shared', name: 'My action', command: 'echo personal', autoOpenUrl: false, source: 'personal' },
|
||||
],
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: true,
|
||||
trusted: false,
|
||||
hash: HASH,
|
||||
warnings: [],
|
||||
executable: {
|
||||
actions: [
|
||||
{ id: 'shared', name: 'Repo action', command: 'echo repo', url: 'https://example.com', autoOpenUrl: true },
|
||||
],
|
||||
setup: ['pnpm install'],
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
renderDialog()
|
||||
|
||||
expect(screen.getAllByText('Actions').length).toBeGreaterThan(1)
|
||||
expect(screen.getByText('Repo action')).toBeInTheDocument()
|
||||
expect(screen.getByText('echo repo')).toBeInTheDocument()
|
||||
expect(screen.getByText('https://example.com')).toBeInTheDocument()
|
||||
expect(screen.getByText('Opens URL automatically')).toBeInTheDocument()
|
||||
expect(screen.getByText('Worktree setup commands')).toBeInTheDocument()
|
||||
expect(screen.getByText('pnpm install')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not offer trust when the repo file has no executable commands', () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
repoFile: { path: '.ocm/project.json', exists: true, trusted: false, hash: HASH, warnings: [], executable: null },
|
||||
}),
|
||||
)
|
||||
renderDialog()
|
||||
|
||||
expect(screen.queryByText(/not trusted/i)).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /trust these commands/i })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses the shared action icon map', () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
actions: [
|
||||
{ id: 'deploy', name: 'Deploy', command: 'pnpm deploy', icon: 'rocket', autoOpenUrl: false, source: 'personal' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
const { container } = renderDialog()
|
||||
|
||||
expect(container.ownerDocument.querySelector('.lucide-rocket')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('hides the trust banner for a trusted repo file', () => {
|
||||
mockConfig(
|
||||
baseConfig({
|
||||
repoFile: { path: '.ocm/project.json', exists: true, trusted: true, hash: HASH, warnings: [] },
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: true,
|
||||
trusted: true,
|
||||
hash: HASH,
|
||||
warnings: [],
|
||||
executable: null,
|
||||
},
|
||||
}),
|
||||
)
|
||||
renderDialog()
|
||||
@@ -152,6 +236,7 @@ describe('RepoActionsDialog', () => {
|
||||
hash: null,
|
||||
error: 'Invalid repository config',
|
||||
warnings: [],
|
||||
executable: null,
|
||||
},
|
||||
}),
|
||||
)
|
||||
@@ -206,7 +291,7 @@ describe('RepoActionsDialog', () => {
|
||||
)
|
||||
mocks.updateActionsMutate.mockImplementation(
|
||||
(_payload: unknown, options?: { onError?: (error: unknown) => void }) => {
|
||||
options?.onError?.(new Error('Server rejected the action'))
|
||||
options?.onError?.(new FetchError('Server rejected the action', 400))
|
||||
},
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
@@ -230,7 +315,7 @@ describe('RepoActionsDialog', () => {
|
||||
)
|
||||
mocks.updateSetupMutate.mockImplementation(
|
||||
(_commands: unknown, options?: { onError?: (error: unknown) => void }) => {
|
||||
options?.onError?.(new Error('Setup save rejected'))
|
||||
options?.onError?.(new FetchError('Setup save rejected', 400))
|
||||
},
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
@@ -251,12 +336,24 @@ describe('RepoActionsDialog', () => {
|
||||
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: [] },
|
||||
repoFile: {
|
||||
path: '.ocm/project.json',
|
||||
exists: true,
|
||||
trusted: false,
|
||||
hash: HASH,
|
||||
warnings: [],
|
||||
executable: {
|
||||
actions: [
|
||||
{ id: 'repo-1', name: 'Repo action', command: 'echo repo', url: null, autoOpenUrl: false },
|
||||
],
|
||||
setup: [],
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
mocks.trustMutate.mockImplementation(
|
||||
(_request: unknown, options?: { onError?: (error: unknown) => void }) => {
|
||||
options?.onError?.(new Error('Trust rejected'))
|
||||
options?.onError?.(new FetchError('Trust rejected', 400))
|
||||
},
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
@@ -277,7 +374,7 @@ describe('RepoActionsDialog', () => {
|
||||
)
|
||||
mocks.moveMutate.mockImplementation(
|
||||
(_request: unknown, options?: { onError?: (error: unknown) => void }) => {
|
||||
options?.onError?.(new Error('Move rejected'))
|
||||
options?.onError?.(new FetchError('Move rejected', 400))
|
||||
},
|
||||
)
|
||||
const user = userEvent.setup()
|
||||
@@ -309,7 +406,7 @@ describe('RepoActionsDialog', () => {
|
||||
{ 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: [] },
|
||||
repoFile: { path: '.ocm/project.json', exists: true, trusted: true, hash: HASH, warnings: [], executable: null },
|
||||
}),
|
||||
)
|
||||
view.rerender(<RepoActionsDialog repoId={1} directory="/repo" open onOpenChange={vi.fn()} />)
|
||||
|
||||
@@ -1,22 +1,6 @@
|
||||
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 { ArrowDown, ArrowUp, Loader2, Pencil, Plus, ShieldAlert, Trash2 } from 'lucide-react'
|
||||
import { arrayMove } from '@dnd-kit/sortable'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -32,23 +16,15 @@ import {
|
||||
useUpdateWorktreeSetup,
|
||||
} from '@/api/projectConfig'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import { randomId } from '@/lib/utils'
|
||||
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
|
||||
}
|
||||
import type {
|
||||
ProjectAction,
|
||||
ProjectActionIcon,
|
||||
ProjectItemSource,
|
||||
} from '@opencode-manager/shared/types'
|
||||
import { ACTION_ICON_OPTIONS, actionIcon } from './projectActionIcons'
|
||||
import { TrustExecutableList } from './TrustExecutableList'
|
||||
|
||||
interface ActionDraft {
|
||||
id: string
|
||||
@@ -99,17 +75,6 @@ function draftToPayload(draft: ActionDraft): ProjectAction {
|
||||
return payload
|
||||
}
|
||||
|
||||
function moveArrayItem<T>(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
|
||||
@@ -250,19 +215,19 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
|
||||
: [...personalActions.map(actionToPayload), payload]
|
||||
updateActions.mutate(next, {
|
||||
onSuccess: () => setDraft(null),
|
||||
onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to save action')),
|
||||
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(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')),
|
||||
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(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')),
|
||||
onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to save setup commands')),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -270,21 +235,21 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
|
||||
if (!config?.repoFile.hash) return
|
||||
trustConfig.mutate(
|
||||
{ hash: config.repoFile.hash, directory },
|
||||
{ onError: (error) => showToast.error(mutationErrorMessage(error, 'Failed to trust repository commands')) },
|
||||
{ onError: (error) => showToast.error(getOpenCodeApiErrorMessage(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')) },
|
||||
{ onError: (error) => showToast.error(getOpenCodeApiErrorMessage(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')) },
|
||||
{ onError: (error) => showToast.error(getOpenCodeApiErrorMessage(error, 'Failed to move setup command')) },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -454,7 +419,7 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
|
||||
variant="ghost"
|
||||
aria-label="Move up"
|
||||
disabled={index === 0}
|
||||
onClick={() => setSetupCommands((current) => moveArrayItem(current, index, index - 1))}
|
||||
onClick={() => setSetupCommands((current) => arrayMove(current, index, index - 1))}
|
||||
>
|
||||
<ArrowUp className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -464,7 +429,7 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
|
||||
variant="ghost"
|
||||
aria-label="Move down"
|
||||
disabled={index === setupCommands.length - 1}
|
||||
onClick={() => setSetupCommands((current) => moveArrayItem(current, index, index + 1))}
|
||||
onClick={() => setSetupCommands((current) => arrayMove(current, index, index + 1))}
|
||||
>
|
||||
<ArrowDown className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -545,33 +510,24 @@ export function RepoActionsDialog({ repoId, directory, open, onOpenChange }: Rep
|
||||
{warning}
|
||||
</p>
|
||||
))}
|
||||
{config.repoFile.exists && !config.repoFile.trusted && config.repoFile.hash && (
|
||||
<div className="rounded-lg border border-warning/50 bg-warning/10 p-3 space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<ShieldAlert className="h-4 w-4 text-warning" />
|
||||
Repository commands are not trusted
|
||||
{config.repoFile.exists &&
|
||||
!config.repoFile.trusted &&
|
||||
config.repoFile.hash &&
|
||||
config.repoFile.executable && (
|
||||
<div className="rounded-lg border border-warning/50 bg-warning/10 p-3 space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<ShieldAlert className="h-4 w-4 text-warning" />
|
||||
Repository commands are not trusted
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This repository defines commands that run on your machine. Review and trust them to enable.
|
||||
</p>
|
||||
<TrustExecutableList executable={config.repoFile.executable} />
|
||||
<Button type="button" size="sm" onClick={handleTrust} disabled={trustConfig.isPending}>
|
||||
Trust these commands
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This repository defines commands that run on your machine. Review and trust them to enable.
|
||||
</p>
|
||||
<ul className="space-y-1">
|
||||
{repoActions.map((action) => (
|
||||
<li key={action.id} className="font-mono text-xs">
|
||||
{action.command}
|
||||
{action.url ? ` — ${action.url}` : ''}
|
||||
</li>
|
||||
))}
|
||||
{repoSetup.map((item) => (
|
||||
<li key={item.command} className="font-mono text-xs">
|
||||
{item.command}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Button type="button" size="sm" onClick={handleTrust} disabled={trustConfig.isPending}>
|
||||
Trust these commands
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { ProjectConfigResponse } from '@opencode-manager/shared/types'
|
||||
|
||||
type RepoFileExecutable = NonNullable<ProjectConfigResponse['repoFile']['executable']>
|
||||
|
||||
export function TrustExecutableList({ executable }: { executable: RepoFileExecutable }) {
|
||||
return (
|
||||
<div className="max-h-64 space-y-3 overflow-y-auto">
|
||||
{executable.actions.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium">Actions</p>
|
||||
<ul className="space-y-1">
|
||||
{executable.actions.map((action) => (
|
||||
<li key={action.id} className="space-y-0.5">
|
||||
<p className="text-xs font-medium">{action.name}</p>
|
||||
<p className="font-mono text-xs">{action.command}</p>
|
||||
{action.url && <p className="font-mono text-xs">{action.url}</p>}
|
||||
{action.autoOpenUrl && <p className="text-xs">Opens URL automatically</p>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{executable.setup.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium">Worktree setup commands</p>
|
||||
<ul className="space-y-1">
|
||||
{executable.setup.map((command, index) => (
|
||||
<li key={`${index}-${command}`} className="font-mono text-xs">
|
||||
{command}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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'}
|
||||
</div>
|
||||
) : (
|
||||
terminals.map((terminal) => (
|
||||
<TerminalView
|
||||
key={terminal.id}
|
||||
ref={(handle) => {
|
||||
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() }}
|
||||
/>
|
||||
))
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
Loading terminal...
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{terminals.map((terminal) => (
|
||||
<TerminalView
|
||||
key={terminal.id}
|
||||
ref={(handle) => {
|
||||
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() }}
|
||||
/>
|
||||
))}
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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<ComponentProps<typeof TerminalView>> = {}
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -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<TerminalViewHandle, TerminalViewProps>(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<TerminalViewHandle, TerminalViewProps>(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<TerminalViewHandle, TerminalViewProps>(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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -1,12 +1,32 @@
|
||||
import { useCallback } from 'react'
|
||||
import { useUrlParams } from './useUrlParams'
|
||||
|
||||
function setDialogParams(
|
||||
params: URLSearchParams,
|
||||
name: string,
|
||||
extraParams?: Record<string, string>,
|
||||
): 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, string>): string {
|
||||
const params = new URLSearchParams()
|
||||
setDialogParams(params, name, extraParams)
|
||||
return `?${params.toString()}`
|
||||
}
|
||||
|
||||
export function openDialogParam(
|
||||
updateParams: ReturnType<typeof useUrlParams>['updateParams'],
|
||||
name: string,
|
||||
extraParams?: Record<string, string>,
|
||||
): void {
|
||||
updateParams((p) => {
|
||||
p.set('dialog', name)
|
||||
setDialogParams(p, name, extraParams)
|
||||
p.delete('mobileTab')
|
||||
}, 'push')
|
||||
}
|
||||
|
||||
@@ -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],
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useCallback } from 'react'
|
||||
import { openDialogParam } from './useDialogParam'
|
||||
import { useUrlParams } from './useUrlParams'
|
||||
|
||||
export function useOpenTerminal(): (
|
||||
terminalId: string,
|
||||
extraParams?: Record<string, string>,
|
||||
) => void {
|
||||
const { updateParams } = useUrlParams()
|
||||
|
||||
return useCallback(
|
||||
(terminalId: string, extraParams?: Record<string, string>) => {
|
||||
openDialogParam(updateParams, 'terminal', { terminal: terminalId, ...extraParams })
|
||||
},
|
||||
[updateParams],
|
||||
)
|
||||
}
|
||||
@@ -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, '/'],
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<string | undefined>();
|
||||
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');
|
||||
|
||||
@@ -682,7 +682,9 @@ export function SessionDetail() {
|
||||
</div>
|
||||
<Header.Actions className="gap-2 sm:gap-4">
|
||||
<div className="flex items-center gap-1">
|
||||
<ProjectActionsMenu repoId={repoId} directory={sessionDirectory} />
|
||||
{!isAssistantSession && (
|
||||
<ProjectActionsMenu repoId={repoId} directory={sessionDirectory} />
|
||||
)}
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<ContextUsageIndicator
|
||||
@@ -861,12 +863,14 @@ export function SessionDetail() {
|
||||
directory={repoDirectory}
|
||||
/>
|
||||
|
||||
<RepoActionsDialog
|
||||
repoId={repoId}
|
||||
directory={sessionDirectory}
|
||||
open={actionsDialogOpen}
|
||||
onOpenChange={setActionsDialogOpen}
|
||||
/>
|
||||
{!isAssistantSession && (
|
||||
<RepoActionsDialog
|
||||
repoId={repoId}
|
||||
directory={sessionDirectory}
|
||||
open={actionsDialogOpen}
|
||||
onOpenChange={setActionsDialogOpen}
|
||||
/>
|
||||
)}
|
||||
|
||||
<SourceControlPanel
|
||||
repoId={repoId}
|
||||
|
||||
@@ -121,7 +121,7 @@ describe('AssistantRedirect preview routing', () => {
|
||||
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(),
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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()),
|
||||
}),
|
||||
|
||||
@@ -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<TerminalInfo, 'kind' | 'actionId' | 'status'>
|
||||
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user