mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
section 16: Phase 16: Documentation, container ports and full repository checks
This commit is contained in:
1 parent
81a9f0c8ef
commit
a383e57bc5
55 files changed
+4095
-59
No files matched your search
+1
-1
@@ -150,7 +150,7 @@ RUN chmod +x /docker-entrypoint.sh
|
||||
RUN mkdir -p /workspace /app/data /home/node/.cache /home/node/.opencode /home/node/.microsandbox && \
|
||||
chown -R node:node /workspace /app/data /home/node
|
||||
|
||||
EXPOSE 5003 5100 5101 5102 5103
|
||||
EXPOSE 5003 5004 5100 5101 5102 5103
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
|
||||
CMD curl -f http://localhost:5003/api/health || exit 1
|
||||
|
||||
@@ -39,6 +39,8 @@ import { createAuthMiddleware } from './auth/middleware'
|
||||
import { createPromptTemplateRoutes } from './routes/prompt-templates'
|
||||
import { createSessionPinRoutes } from './routes/session-pins'
|
||||
import { createLogRoutes } from './routes/logs'
|
||||
import { createPreviewRoutes } from './routes/preview'
|
||||
import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway'
|
||||
import { createInternalRoutes } from './routes/internal'
|
||||
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
|
||||
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
@@ -268,6 +270,7 @@ sseAggregator.setScheduledSessionsResolver(
|
||||
void scheduleRunnerInstance.start()
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
const previewSessionStore = new PreviewSessionStore()
|
||||
|
||||
app.route('/api/auth', createAuthRoutes(auth))
|
||||
app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
|
||||
@@ -296,6 +299,7 @@ protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||
protectedApi.route('/session-pins', createSessionPinRoutes(db))
|
||||
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/logs', createLogRoutes())
|
||||
protectedApi.route('/preview', createPreviewRoutes({ store: previewSessionStore }))
|
||||
|
||||
app.route('/api', protectedApi)
|
||||
|
||||
@@ -415,4 +419,15 @@ const server = serve({
|
||||
|
||||
injectWebSocket(server)
|
||||
|
||||
if (ENV.PREVIEW.PORT > 0) {
|
||||
const previewGateway = createPreviewGatewayApp(previewSessionStore)
|
||||
const previewServer = serve({
|
||||
fetch: previewGateway.app.fetch,
|
||||
port: ENV.PREVIEW.PORT,
|
||||
hostname: HOST,
|
||||
})
|
||||
previewGateway.injectWebSocket(previewServer)
|
||||
logger.info(`Preview gateway running on http://${HOST}:${ENV.PREVIEW.PORT}`)
|
||||
}
|
||||
|
||||
logger.info(`🚀 OpenCode WebUI API running on http://${HOST}:${PORT}`)
|
||||
@@ -11,21 +11,7 @@ import {
|
||||
withDefaultOpenCodeDirectory,
|
||||
} from '../services/opencode/upstream'
|
||||
import { getRepoById } from '../db/queries'
|
||||
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'te',
|
||||
'trailers',
|
||||
'upgrade',
|
||||
'transfer-encoding',
|
||||
'content-length',
|
||||
'content-encoding',
|
||||
'host',
|
||||
'authorization',
|
||||
])
|
||||
import { buildProxyResponseHeaders, filterProxyHeaders } from '../utils/proxy-headers'
|
||||
|
||||
interface ProxyRequestParts {
|
||||
method: string
|
||||
@@ -95,13 +81,7 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
const url = new URL(c.req.url)
|
||||
const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
|
||||
|
||||
const forwardedHeaders: Record<string, string> = {}
|
||||
c.req.raw.headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (!HOP_BY_HOP_HEADERS.has(lowerKey)) {
|
||||
forwardedHeaders[key] = value
|
||||
}
|
||||
})
|
||||
const forwardedHeaders = filterProxyHeaders(c.req.raw.headers)
|
||||
const headers = withDefaultOpenCodeDirectory(forwardedHeaders)
|
||||
|
||||
headers['Authorization'] = buildOpenCodeBasicAuth(settingsService.getOpenCodeServerPassword())
|
||||
@@ -140,13 +120,7 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
duplex: 'half',
|
||||
})
|
||||
|
||||
const responseHeaders: Record<string, string> = {}
|
||||
upstreamResponse.headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (!HOP_BY_HOP_HEADERS.has(lowerKey)) {
|
||||
responseHeaders[key] = value
|
||||
}
|
||||
})
|
||||
const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers)
|
||||
|
||||
return new Response(upstreamResponse.body, {
|
||||
status: upstreamResponse.status,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import path from 'node:path'
|
||||
import { Hono } from 'hono'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { CreatePreviewSessionRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import { listListeningPorts, isReservedPreviewPort, type PreviewPortEntry } from '../services/preview/ports'
|
||||
import { PreviewSessionStore } from '../services/preview/gateway'
|
||||
|
||||
export interface PreviewRoutesDeps {
|
||||
enabled: boolean
|
||||
listPorts: () => Promise<PreviewPortEntry[]>
|
||||
store: PreviewSessionStore
|
||||
}
|
||||
|
||||
function isInsideDirectory(cwd: string | null, canonicalDirectory: string | null): boolean {
|
||||
if (!cwd || !canonicalDirectory) return false
|
||||
const canonicalCwd = canonicalPathSync(cwd)
|
||||
if (canonicalCwd === canonicalDirectory) return true
|
||||
const prefix = canonicalDirectory.endsWith(path.sep) ? canonicalDirectory : `${canonicalDirectory}${path.sep}`
|
||||
return canonicalCwd.startsWith(prefix)
|
||||
}
|
||||
|
||||
export function createPreviewRoutes(deps: Partial<PreviewRoutesDeps> = {}) {
|
||||
const resolvedDeps: PreviewRoutesDeps = {
|
||||
enabled: deps.enabled ?? ENV.PREVIEW.PORT > 0,
|
||||
listPorts: deps.listPorts ?? (() => listListeningPorts()),
|
||||
store: deps.store ?? new PreviewSessionStore(),
|
||||
}
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/ports', async (c) => {
|
||||
const directory = c.req.query('directory')
|
||||
const canonicalDirectory = directory ? canonicalPathSync(directory) : null
|
||||
const ports = await resolvedDeps.listPorts()
|
||||
const sorted = [...ports].sort((left, right) => {
|
||||
const leftMatch = isInsideDirectory(left.cwd, canonicalDirectory)
|
||||
const rightMatch = isInsideDirectory(right.cwd, canonicalDirectory)
|
||||
if (leftMatch !== rightMatch) return leftMatch ? -1 : 1
|
||||
return left.port - right.port
|
||||
})
|
||||
return c.json({ enabled: resolvedDeps.enabled, ports: sorted })
|
||||
})
|
||||
|
||||
app.post('/sessions', async (c) => {
|
||||
const body = await c.req.json().catch(() => ({}))
|
||||
const parsed = CreatePreviewSessionRequestSchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
if (!resolvedDeps.enabled) {
|
||||
return c.json({ error: 'Preview is disabled' }, 503)
|
||||
}
|
||||
|
||||
if (isReservedPreviewPort(parsed.data.port)) {
|
||||
return c.json({ error: 'Port is reserved' }, 400)
|
||||
}
|
||||
|
||||
const ports = await resolvedDeps.listPorts()
|
||||
const match = ports.find((entry) => entry.port === parsed.data.port)
|
||||
if (!match) {
|
||||
return c.json({ error: `Port ${parsed.data.port} is not listening` }, 404)
|
||||
}
|
||||
|
||||
const token = resolvedDeps.store.issueStartToken({ port: match.port, host: match.host })
|
||||
return c.json({
|
||||
token,
|
||||
previewPort: ENV.PREVIEW.PORT,
|
||||
publicUrl: ENV.PREVIEW.PUBLIC_URL || null,
|
||||
})
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../db/migration-runner'
|
||||
import { allMigrations } from '../db/migrations'
|
||||
import { createRepoRoutes } from './repos'
|
||||
import { createRepo, getRepoById } from '../db/queries'
|
||||
import { createRepo, getRepoById, setRepoSetting } from '../db/queries'
|
||||
import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
@@ -33,7 +33,11 @@ const stubTerminalService = {
|
||||
removeAll: mock(async () => undefined),
|
||||
} as unknown as TerminalService
|
||||
|
||||
function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStubOpenCodeClient()): Hono {
|
||||
function createTestApp(
|
||||
db: Database,
|
||||
openCodeClient: OpenCodeClient = createStubOpenCodeClient(),
|
||||
terminalService: TerminalService = stubTerminalService,
|
||||
): Hono {
|
||||
const app = new Hono()
|
||||
const scheduleService = {
|
||||
createSchedule: () => {},
|
||||
@@ -43,7 +47,7 @@ function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStub
|
||||
deleteSchedule: () => {},
|
||||
prepareRepoDelete: () => {},
|
||||
} as any
|
||||
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, stubTerminalService))
|
||||
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService))
|
||||
return app
|
||||
}
|
||||
|
||||
@@ -440,10 +444,32 @@ describe('POST /api/repos/:id/workspaces', () => {
|
||||
const res = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ directory: '/tmp/wrk-test' })
|
||||
expect(await res.json()).toEqual({ directory: '/tmp/wrk-test', worktreeSetup: { status: 'none' } })
|
||||
expect(create).toHaveBeenCalledWith({ projectID: 'commit-A' })
|
||||
})
|
||||
|
||||
it('still returns 200 with a failed worktree setup when the setup terminal cannot start', async () => {
|
||||
createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true })
|
||||
setRepoSetting(db, 1, 'worktreeSetupCommands', JSON.stringify(['pnpm install']))
|
||||
const client = createStubOpenCodeClient()
|
||||
client.api.worktree.create = mock(async () => ({ directory: '/tmp/wrk-test' })) as any
|
||||
const failingTerminalService = {
|
||||
removeAll: mock(async () => undefined),
|
||||
create: mock(async () => {
|
||||
throw new Error('spawn failed')
|
||||
}),
|
||||
} as unknown as TerminalService
|
||||
const app = createTestApp(db, client, failingTerminalService)
|
||||
|
||||
const res = await app.request('/repos/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
directory: '/tmp/wrk-test',
|
||||
worktreeSetup: { status: 'failed', error: 'spawn failed' },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 400 for a non-numeric repo id', async () => {
|
||||
const app = createTestApp(db)
|
||||
const res = await app.request('/repos/abc/workspaces', { method: 'POST' })
|
||||
|
||||
@@ -92,7 +92,17 @@ export function createRepoRoutes(
|
||||
{ branch, directoryName, useWorktree, skipSSHVerification, baseBranch }
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
if (repo.isWorktree) {
|
||||
const projectRepo = await projectConfigService.resolveProjectRepo(repo)
|
||||
if (projectRepo.id !== repo.id) {
|
||||
return c.json({
|
||||
...repo,
|
||||
worktreeSetup: await projectConfigService.runWorktreeSetup(projectRepo, repo.fullPath, terminalService),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return c.json(repo)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to create repo:', error)
|
||||
@@ -320,7 +330,10 @@ app.get('/', async (c) => {
|
||||
try {
|
||||
const projectID = await repoService.resolveRepoProjectId(openCodeClient, repo.fullPath)
|
||||
const worktree = await openCodeClient.api.worktree.create({ projectID })
|
||||
return c.json(worktree)
|
||||
return c.json({
|
||||
...worktree,
|
||||
worktreeSetup: await projectConfigService.runWorktreeSetup(repo, worktree.directory, terminalService),
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
if (isWorktreeError(error)) {
|
||||
return c.json({ error: error.data.message }, 409)
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { Hono } from 'hono'
|
||||
import type { Context, MiddlewareHandler } from 'hono'
|
||||
import { createNodeWebSocket, type NodeWebSocket } from '@hono/node-ws'
|
||||
import { buildProxyResponseHeaders, filterProxyHeaders } from '../../utils/proxy-headers'
|
||||
import { bridgeWebSocket, type WebSocketBridge } from '../../utils/websocket-bridge'
|
||||
|
||||
export const PREVIEW_COOKIE = 'ocm_preview'
|
||||
|
||||
const START_TOKEN_TTL_MS = 60_000
|
||||
const SESSION_TTL_MS = 12 * 60 * 60 * 1000
|
||||
|
||||
const MANAGER_COOKIE_PREFIXES = ['opencode.', '__Secure-opencode.', '__Host-opencode.']
|
||||
|
||||
export type PreviewHost = '127.0.0.1' | '::1'
|
||||
|
||||
export interface PreviewSession {
|
||||
id: string
|
||||
port: number
|
||||
host: PreviewHost
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
interface StartToken {
|
||||
port: number
|
||||
host: PreviewHost
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
export interface PreviewSessionStoreOptions {
|
||||
now?: () => number
|
||||
randomToken?: () => string
|
||||
}
|
||||
|
||||
export class PreviewSessionStore {
|
||||
private readonly startTokens = new Map<string, StartToken>()
|
||||
private readonly sessions = new Map<string, PreviewSession>()
|
||||
private readonly now: () => number
|
||||
private readonly randomToken: () => string
|
||||
|
||||
constructor(options: PreviewSessionStoreOptions = {}) {
|
||||
this.now = options.now ?? Date.now
|
||||
this.randomToken = options.randomToken ?? (() => randomBytes(32).toString('base64url'))
|
||||
}
|
||||
|
||||
issueStartToken(target: { port: number; host: PreviewHost }): string {
|
||||
this.prune()
|
||||
const token = this.randomToken()
|
||||
this.startTokens.set(token, { port: target.port, host: target.host, expiresAt: this.now() + START_TOKEN_TTL_MS })
|
||||
return token
|
||||
}
|
||||
|
||||
consumeStartToken(token: string): string | null {
|
||||
this.prune()
|
||||
const entry = this.startTokens.get(token)
|
||||
if (!entry) return null
|
||||
this.startTokens.delete(token)
|
||||
const id = this.randomToken()
|
||||
this.sessions.set(id, { id, port: entry.port, host: entry.host, expiresAt: this.now() + SESSION_TTL_MS })
|
||||
return id
|
||||
}
|
||||
|
||||
getSession(id: string): PreviewSession | undefined {
|
||||
this.prune()
|
||||
return this.sessions.get(id)
|
||||
}
|
||||
|
||||
private prune(): void {
|
||||
const now = this.now()
|
||||
for (const [token, entry] of this.startTokens) {
|
||||
if (entry.expiresAt <= now) this.startTokens.delete(token)
|
||||
}
|
||||
for (const [id, session] of this.sessions) {
|
||||
if (session.expiresAt <= now) this.sessions.delete(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function stripManagerCookies(cookieHeader: string | undefined): string | undefined {
|
||||
if (!cookieHeader) return undefined
|
||||
const kept = cookieHeader
|
||||
.split(';')
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => {
|
||||
if (!part) return false
|
||||
const separator = part.indexOf('=')
|
||||
const name = separator === -1 ? part : part.slice(0, separator)
|
||||
if (name === PREVIEW_COOKIE) return false
|
||||
return !MANAGER_COOKIE_PREFIXES.some((prefix) => name.startsWith(prefix))
|
||||
})
|
||||
return kept.length > 0 ? kept.join('; ') : undefined
|
||||
}
|
||||
|
||||
function readPreviewCookie(cookieHeader: string | undefined): string | null {
|
||||
if (!cookieHeader) return null
|
||||
for (const part of cookieHeader.split(';')) {
|
||||
const trimmed = part.trim()
|
||||
const separator = trimmed.indexOf('=')
|
||||
if (separator === -1) continue
|
||||
if (trimmed.slice(0, separator) === PREVIEW_COOKIE) {
|
||||
return trimmed.slice(separator + 1)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function htmlResponse(status: number, message: string): Response {
|
||||
return new Response(`<!doctype html><html><body><p>${message}</p></body></html>`, {
|
||||
status,
|
||||
headers: { 'content-type': 'text/html; charset=utf-8' },
|
||||
})
|
||||
}
|
||||
|
||||
function rewriteLocalLocation(location: string, port: number): string | null {
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(location)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const isLocalHost =
|
||||
parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '[::1]' || parsed.hostname === '::1'
|
||||
if (!isLocalHost) return null
|
||||
const locationPort = parsed.port
|
||||
? Number.parseInt(parsed.port, 10)
|
||||
: parsed.protocol === 'https:'
|
||||
? 443
|
||||
: 80
|
||||
if (locationPort !== port) return null
|
||||
return `${parsed.pathname}${parsed.search}`
|
||||
}
|
||||
|
||||
export interface PreviewGateway {
|
||||
app: Hono
|
||||
injectWebSocket: NodeWebSocket['injectWebSocket']
|
||||
}
|
||||
|
||||
function isWebSocketUpgrade(c: Context): boolean {
|
||||
return c.req.header('upgrade')?.toLowerCase() === 'websocket'
|
||||
}
|
||||
|
||||
function upstreamWebSocketUrl(session: PreviewSession, requestUrl: URL): string {
|
||||
const targetHost = session.host === '::1' ? '[::1]' : 'localhost'
|
||||
return `ws://${targetHost}:${session.port}${requestUrl.pathname}${requestUrl.search}`
|
||||
}
|
||||
|
||||
function parseProtocols(header: string | undefined): string[] {
|
||||
if (!header) return []
|
||||
return header
|
||||
.split(',')
|
||||
.map((protocol) => protocol.trim())
|
||||
.filter((protocol) => protocol.length > 0)
|
||||
}
|
||||
|
||||
export function createPreviewGatewayApp(store: PreviewSessionStore, fetchFn: typeof fetch = fetch): PreviewGateway {
|
||||
const app = new Hono()
|
||||
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app })
|
||||
|
||||
app.get('/__ocm_preview/start', (c) => {
|
||||
const sessionId = store.consumeStartToken(c.req.query('token') ?? '')
|
||||
if (!sessionId) {
|
||||
return htmlResponse(401, 'Preview session is invalid or expired.')
|
||||
}
|
||||
|
||||
const requestedPath = c.req.query('path') ?? ''
|
||||
const location = requestedPath.startsWith('/') && !requestedPath.startsWith('//') ? requestedPath : '/'
|
||||
|
||||
const forwardedProto = c.req.header('x-forwarded-proto')?.toLowerCase()
|
||||
const isSecure = forwardedProto === 'https' || new URL(c.req.url).protocol === 'https:'
|
||||
const cookie = `${PREVIEW_COOKIE}=${sessionId}; HttpOnly; SameSite=Lax; Path=/${isSecure ? '; Secure' : ''}`
|
||||
|
||||
return new Response(null, { status: 302, headers: { location, 'set-cookie': cookie } })
|
||||
})
|
||||
|
||||
const sessionGuard: MiddlewareHandler = async (c, next) => {
|
||||
if (!isWebSocketUpgrade(c)) {
|
||||
await next()
|
||||
return
|
||||
}
|
||||
const sessionId = readPreviewCookie(c.req.header('cookie'))
|
||||
if (!sessionId || !store.getSession(sessionId)) {
|
||||
return htmlResponse(401, 'Preview session expired. Reopen it from OpenCode Manager.')
|
||||
}
|
||||
await next()
|
||||
}
|
||||
|
||||
app.get(
|
||||
'/*',
|
||||
sessionGuard,
|
||||
upgradeWebSocket((c) => {
|
||||
const requestUrl = new URL(c.req.url)
|
||||
const protocols = parseProtocols(c.req.header('sec-websocket-protocol'))
|
||||
let bridge: WebSocketBridge | undefined
|
||||
|
||||
return {
|
||||
onOpen(_event, ws) {
|
||||
const sessionId = readPreviewCookie(c.req.header('cookie'))
|
||||
const session = sessionId ? store.getSession(sessionId) : undefined
|
||||
if (!session) {
|
||||
ws.close(1011)
|
||||
return
|
||||
}
|
||||
|
||||
let upstream: WebSocket
|
||||
try {
|
||||
upstream = new WebSocket(upstreamWebSocketUrl(session, requestUrl), protocols.length > 0 ? protocols : undefined)
|
||||
} catch {
|
||||
ws.close(1011)
|
||||
return
|
||||
}
|
||||
|
||||
bridge = bridgeWebSocket(upstream, {
|
||||
send: (data) => ws.send(data),
|
||||
close: (code, reason) => ws.close(code, reason),
|
||||
})
|
||||
},
|
||||
async onMessage(event) {
|
||||
if (!bridge) return
|
||||
const data = event.data
|
||||
if (typeof data === 'string') {
|
||||
bridge.send(data)
|
||||
return
|
||||
}
|
||||
if (data instanceof Blob) {
|
||||
bridge.send(await data.arrayBuffer())
|
||||
return
|
||||
}
|
||||
if (data instanceof ArrayBuffer) {
|
||||
bridge.send(data)
|
||||
}
|
||||
},
|
||||
onClose() {
|
||||
bridge?.close()
|
||||
},
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
app.all('/*', async (c) => {
|
||||
const cookieHeader = c.req.header('cookie')
|
||||
const sessionId = readPreviewCookie(cookieHeader)
|
||||
const session = sessionId ? store.getSession(sessionId) : undefined
|
||||
if (!session) {
|
||||
return htmlResponse(401, 'Preview session expired. Reopen it from OpenCode Manager.')
|
||||
}
|
||||
|
||||
const url = new URL(c.req.url)
|
||||
const targetHost = session.host === '::1' ? '[::1]' : 'localhost'
|
||||
const target = `http://${targetHost}:${session.port}${url.pathname}${url.search}`
|
||||
|
||||
const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
|
||||
|
||||
const headers = filterProxyHeaders(c.req.raw.headers)
|
||||
const contentEncoding = hasBody ? c.req.header('content-encoding') : undefined
|
||||
if (contentEncoding) {
|
||||
headers['content-encoding'] = contentEncoding
|
||||
}
|
||||
headers['host'] = `localhost:${session.port}`
|
||||
const strippedCookies = stripManagerCookies(cookieHeader)
|
||||
if (strippedCookies) {
|
||||
headers['cookie'] = strippedCookies
|
||||
} else {
|
||||
delete headers['cookie']
|
||||
}
|
||||
headers['x-forwarded-host'] = c.req.header('host') ?? ''
|
||||
headers['x-forwarded-proto'] = c.req.header('x-forwarded-proto') ?? url.protocol.replace(':', '')
|
||||
|
||||
try {
|
||||
const upstreamResponse = await fetchFn(target, {
|
||||
method: c.req.method,
|
||||
headers,
|
||||
body: hasBody ? c.req.raw.body : undefined,
|
||||
redirect: 'manual',
|
||||
duplex: 'half',
|
||||
})
|
||||
|
||||
const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers)
|
||||
const location = responseHeaders.get('location')
|
||||
if (location) {
|
||||
const rewritten = rewriteLocalLocation(location, session.port)
|
||||
if (rewritten) responseHeaders.set('location', rewritten)
|
||||
}
|
||||
|
||||
return new Response(upstreamResponse.body, {
|
||||
status: upstreamResponse.status,
|
||||
statusText: upstreamResponse.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch {
|
||||
return htmlResponse(502, `Preview request failed: cannot reach port ${session.port}.`)
|
||||
}
|
||||
})
|
||||
|
||||
return { app, injectWebSocket }
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
import { readFile, readdir, readlink } from 'node:fs/promises'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { executeCommand } from '../../utils/process'
|
||||
|
||||
export interface PreviewPortEntry {
|
||||
port: number
|
||||
host: '127.0.0.1' | '::1'
|
||||
pid: number | null
|
||||
command: string | null
|
||||
cwd: string | null
|
||||
}
|
||||
|
||||
export interface ParsedProcNetSocket {
|
||||
port: number
|
||||
address: string
|
||||
inode: string
|
||||
}
|
||||
|
||||
export interface LsofListener {
|
||||
port: number
|
||||
address: string
|
||||
pid: number | null
|
||||
command: string | null
|
||||
}
|
||||
|
||||
export interface PortDiscoveryDeps {
|
||||
platform: NodeJS.Platform
|
||||
readFile: (path: string, encoding: 'utf8') => Promise<string>
|
||||
readdir: (path: string) => Promise<string[]>
|
||||
readlink: (path: string) => Promise<string>
|
||||
runLsof: () => Promise<string>
|
||||
}
|
||||
|
||||
const PROC_NET_FILES: ReadonlyArray<readonly [string, 4 | 6]> = [
|
||||
['/proc/net/tcp', 4],
|
||||
['/proc/net/tcp6', 6],
|
||||
]
|
||||
|
||||
const WILDCARD_V4 = '0.0.0.0'
|
||||
const WILDCARD_V6 = '::'
|
||||
|
||||
function decodeIpv4Hex(hex: string): string | null {
|
||||
if (hex.length !== 8) return null
|
||||
const octets: number[] = []
|
||||
for (let index = 6; index >= 0; index -= 2) {
|
||||
const octet = Number.parseInt(hex.slice(index, index + 2), 16)
|
||||
if (Number.isNaN(octet)) return null
|
||||
octets.push(octet)
|
||||
}
|
||||
return octets.join('.')
|
||||
}
|
||||
|
||||
function formatIpv6(groups: string[]): string {
|
||||
const normalized = groups.map((group) => group.replace(/^0+/, '') || '0')
|
||||
let bestStart = -1
|
||||
let bestLength = 0
|
||||
let currentStart = -1
|
||||
let currentLength = 0
|
||||
for (let index = 0; index < normalized.length; index += 1) {
|
||||
if (normalized[index] === '0') {
|
||||
if (currentStart === -1) {
|
||||
currentStart = index
|
||||
currentLength = 0
|
||||
}
|
||||
currentLength += 1
|
||||
if (currentLength > bestLength) {
|
||||
bestLength = currentLength
|
||||
bestStart = currentStart
|
||||
}
|
||||
} else {
|
||||
currentStart = -1
|
||||
currentLength = 0
|
||||
}
|
||||
}
|
||||
if (bestLength < 2) return normalized.join(':')
|
||||
const head = normalized.slice(0, bestStart).join(':')
|
||||
const tail = normalized.slice(bestStart + bestLength).join(':')
|
||||
return `${head}::${tail}`
|
||||
}
|
||||
|
||||
function decodeIpv6Hex(hex: string): string | null {
|
||||
if (hex.length !== 32) return null
|
||||
const groups: string[] = []
|
||||
for (let index = 0; index < 32; index += 8) {
|
||||
const word = hex.slice(index, index + 8)
|
||||
const reversed = `${word.slice(6, 8)}${word.slice(4, 6)}${word.slice(2, 4)}${word.slice(0, 2)}`
|
||||
groups.push(reversed.slice(0, 4), reversed.slice(4, 8))
|
||||
}
|
||||
return formatIpv6(groups)
|
||||
}
|
||||
|
||||
function isAllowedAddress(address: string): boolean {
|
||||
return (
|
||||
address === WILDCARD_V4 ||
|
||||
address === WILDCARD_V6 ||
|
||||
address === '::1' ||
|
||||
address.startsWith('127.')
|
||||
)
|
||||
}
|
||||
|
||||
export function isReservedPreviewPort(port: number): boolean {
|
||||
return port === ENV.SERVER.PORT || port === ENV.OPENCODE.PORT || port === ENV.PREVIEW.PORT
|
||||
}
|
||||
|
||||
export function parseProcNetTcp(text: string, family: 4 | 6): ParsedProcNetSocket[] {
|
||||
const sockets: ParsedProcNetSocket[] = []
|
||||
for (const rawLine of text.split('\n')) {
|
||||
const line = rawLine.trim()
|
||||
if (!line || line.startsWith('sl')) continue
|
||||
const parts = line.split(/\s+/)
|
||||
if (parts.length < 10) continue
|
||||
if (parts[3] !== '0A') continue
|
||||
const local = parts[1]
|
||||
if (!local) continue
|
||||
const separator = local.lastIndexOf(':')
|
||||
if (separator === -1) continue
|
||||
const addressHex = local.slice(0, separator)
|
||||
const portHex = local.slice(separator + 1)
|
||||
const port = Number.parseInt(portHex, 16)
|
||||
if (Number.isNaN(port)) continue
|
||||
const address = family === 4 ? decodeIpv4Hex(addressHex) : decodeIpv6Hex(addressHex)
|
||||
if (!address || !isAllowedAddress(address)) continue
|
||||
sockets.push({ port, address, inode: parts[9] ?? '' })
|
||||
}
|
||||
return sockets
|
||||
}
|
||||
|
||||
function parseLsofName(value: string): { address: string; port: number } | null {
|
||||
let address: string
|
||||
let portText: string
|
||||
if (value.startsWith('[')) {
|
||||
const end = value.indexOf(']')
|
||||
if (end === -1) return null
|
||||
address = value.slice(1, end)
|
||||
const rest = value.slice(end + 1)
|
||||
if (!rest.startsWith(':')) return null
|
||||
portText = rest.slice(1)
|
||||
} else {
|
||||
const separator = value.lastIndexOf(':')
|
||||
if (separator === -1) return null
|
||||
address = value.slice(0, separator)
|
||||
portText = value.slice(separator + 1)
|
||||
}
|
||||
if (address === '*') address = WILDCARD_V4
|
||||
const port = Number.parseInt(portText, 10)
|
||||
if (Number.isNaN(port)) return null
|
||||
return { address, port }
|
||||
}
|
||||
|
||||
export function parseLsofListen(output: string): LsofListener[] {
|
||||
const listeners: LsofListener[] = []
|
||||
let pid: number | null = null
|
||||
let command: string | null = null
|
||||
for (const rawLine of output.split('\n')) {
|
||||
const field = rawLine.trim()
|
||||
if (!field) continue
|
||||
const type = field[0]
|
||||
const value = field.slice(1)
|
||||
if (type === 'p') {
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
pid = Number.isNaN(parsed) ? null : parsed
|
||||
} else if (type === 'c') {
|
||||
command = value
|
||||
} else if (type === 'n') {
|
||||
const parsed = parseLsofName(value)
|
||||
if (parsed) listeners.push({ ...parsed, pid, command })
|
||||
}
|
||||
}
|
||||
return listeners
|
||||
}
|
||||
|
||||
function toHost(address: string): '127.0.0.1' | '::1' {
|
||||
return address === '::1' ? '::1' : '127.0.0.1'
|
||||
}
|
||||
|
||||
function dedupeByPort(entries: PreviewPortEntry[]): PreviewPortEntry[] {
|
||||
const byPort = new Map<number, PreviewPortEntry[]>()
|
||||
for (const entry of entries) {
|
||||
const existing = byPort.get(entry.port)
|
||||
if (existing) {
|
||||
existing.push(entry)
|
||||
} else {
|
||||
byPort.set(entry.port, [entry])
|
||||
}
|
||||
}
|
||||
const result: PreviewPortEntry[] = []
|
||||
for (const group of byPort.values()) {
|
||||
const first = group[0]!
|
||||
const onlyIpv6Loopback = group.every((entry) => entry.host === '::1')
|
||||
result.push({ ...first, host: onlyIpv6Loopback ? '::1' : '127.0.0.1' })
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async function mapInodesToPids(deps: PortDiscoveryDeps): Promise<Map<string, number>> {
|
||||
const map = new Map<string, number>()
|
||||
let entries: string[]
|
||||
try {
|
||||
entries = await deps.readdir('/proc')
|
||||
} catch {
|
||||
return map
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!/^\d+$/.test(entry)) continue
|
||||
const fdDir = `/proc/${entry}/fd`
|
||||
let fds: string[]
|
||||
try {
|
||||
fds = await deps.readdir(fdDir)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const fd of fds) {
|
||||
let target: string
|
||||
try {
|
||||
target = await deps.readlink(`${fdDir}/${fd}`)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const match = /^socket:\[(\d+)\]$/.exec(target)
|
||||
if (match?.[1]) map.set(match[1], Number.parseInt(entry, 10))
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
async function readOptional(deps: PortDiscoveryDeps, file: string): Promise<string | null> {
|
||||
try {
|
||||
return (await deps.readFile(file, 'utf8')).trim() || null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function readLinkOptional(deps: PortDiscoveryDeps, file: string): Promise<string | null> {
|
||||
try {
|
||||
return await deps.readlink(file)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function listLinuxPorts(deps: PortDiscoveryDeps): Promise<PreviewPortEntry[]> {
|
||||
const sockets: ParsedProcNetSocket[] = []
|
||||
for (const [file, family] of PROC_NET_FILES) {
|
||||
let text: string
|
||||
try {
|
||||
text = await deps.readFile(file, 'utf8')
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
sockets.push(...parseProcNetTcp(text, family))
|
||||
}
|
||||
if (sockets.length === 0) return []
|
||||
|
||||
const inodeToPid = await mapInodesToPids(deps)
|
||||
const processMeta = new Map<number, { command: string | null; cwd: string | null }>()
|
||||
const entries: PreviewPortEntry[] = []
|
||||
for (const socket of sockets) {
|
||||
const pid = inodeToPid.get(socket.inode) ?? null
|
||||
let command: string | null = null
|
||||
let cwd: string | null = null
|
||||
if (pid !== null) {
|
||||
const cached = processMeta.get(pid)
|
||||
if (cached) {
|
||||
command = cached.command
|
||||
cwd = cached.cwd
|
||||
} else {
|
||||
command = await readOptional(deps, `/proc/${pid}/comm`)
|
||||
cwd = await readLinkOptional(deps, `/proc/${pid}/cwd`)
|
||||
processMeta.set(pid, { command, cwd })
|
||||
}
|
||||
}
|
||||
entries.push({ port: socket.port, host: toHost(socket.address), pid, command, cwd })
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
async function listMacPorts(deps: PortDiscoveryDeps): Promise<PreviewPortEntry[]> {
|
||||
let output: string
|
||||
try {
|
||||
output = await deps.runLsof()
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
return parseLsofListen(output)
|
||||
.filter((listener) => isAllowedAddress(listener.address))
|
||||
.map((listener) => ({
|
||||
port: listener.port,
|
||||
host: toHost(listener.address),
|
||||
pid: listener.pid,
|
||||
command: listener.command,
|
||||
cwd: null,
|
||||
}))
|
||||
}
|
||||
|
||||
export async function listListeningPorts(deps: PortDiscoveryDeps = defaultPortDeps): Promise<PreviewPortEntry[]> {
|
||||
const entries =
|
||||
deps.platform === 'linux'
|
||||
? await listLinuxPorts(deps)
|
||||
: deps.platform === 'darwin'
|
||||
? await listMacPorts(deps)
|
||||
: []
|
||||
|
||||
return dedupeByPort(entries)
|
||||
.filter((entry) => entry.port >= 1024 && !isReservedPreviewPort(entry.port))
|
||||
.sort((left, right) => left.port - right.port)
|
||||
}
|
||||
|
||||
const defaultPortDeps: PortDiscoveryDeps = {
|
||||
platform: process.platform,
|
||||
readFile: (path, encoding) => readFile(path, encoding),
|
||||
readdir: (path) => readdir(path),
|
||||
readlink: (path) => readlink(path),
|
||||
runLsof: async () => {
|
||||
const result = await executeCommand(['lsof', '-nP', '-iTCP', '-sTCP:LISTEN', '-F', 'pcn'], {
|
||||
ignoreExitCode: true,
|
||||
})
|
||||
return typeof result === 'string' ? result : (result as { stdout: string }).stdout
|
||||
},
|
||||
}
|
||||
@@ -13,10 +13,12 @@ import {
|
||||
type ProjectConfigResponse,
|
||||
type RepoProjectFile,
|
||||
type RunProjectActionResponse,
|
||||
type WorktreeSetupResult,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { getRepoByDirectory, getRepoSetting, setRepoSetting } from '../db/queries'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import type { GitService } from './git/GitService'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
@@ -126,9 +128,7 @@ export class ProjectConfigService {
|
||||
worktreeSetup.push({ command, source: 'repo' })
|
||||
}
|
||||
|
||||
const trusted =
|
||||
repoFile.hash !== null &&
|
||||
repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY)
|
||||
const trusted = this.isRepoFileTrusted(projectRepo, repoFile)
|
||||
|
||||
const resolvedActions = await Promise.all(
|
||||
actions.map(async (action) =>
|
||||
@@ -233,6 +233,45 @@ export class ProjectConfigService {
|
||||
return result
|
||||
}
|
||||
|
||||
async runWorktreeSetup(
|
||||
projectRepo: Repo,
|
||||
worktreeDirectory: string,
|
||||
terminalService: TerminalService,
|
||||
): Promise<WorktreeSetupResult> {
|
||||
const commands = [...this.getPersonalSetup(projectRepo)]
|
||||
const repoFile = this.readRepoFile(worktreeDirectory)
|
||||
const repoCommands = repoFile.file?.setupWorktree ?? []
|
||||
const repoCommandsSkipped = repoCommands.length > 0 && !this.isRepoFileTrusted(projectRepo, repoFile)
|
||||
if (!repoCommandsSkipped) {
|
||||
commands.push(...repoCommands)
|
||||
}
|
||||
|
||||
if (commands.length === 0) {
|
||||
return repoCommandsSkipped ? { status: 'skipped', reason: 'untrusted' } : { status: 'none' }
|
||||
}
|
||||
|
||||
try {
|
||||
const terminal = await terminalService.create(worktreeDirectory, {
|
||||
kind: 'setup',
|
||||
name: 'Worktree setup',
|
||||
command: '/bin/sh',
|
||||
args: ['-c', ['set -e', ...commands].join('\n')],
|
||||
env: { ROOT_PROJECT_PATH: projectRepo.fullPath },
|
||||
})
|
||||
return { status: 'started', terminal, repoCommandsSkipped }
|
||||
} catch (error: unknown) {
|
||||
logger.warn(`Failed to start worktree setup for ${worktreeDirectory}:`, error)
|
||||
return { status: 'failed', error: getErrorMessage(error) }
|
||||
}
|
||||
}
|
||||
|
||||
private isRepoFileTrusted(projectRepo: Repo, repoFile: RepoFileState): boolean {
|
||||
return (
|
||||
repoFile.hash !== null &&
|
||||
repoFile.hash === getRepoSetting(this.database, projectRepo.id, REPO_CONFIG_TRUST_KEY)
|
||||
)
|
||||
}
|
||||
|
||||
readRepoFile(directory: string): RepoFileState {
|
||||
const filePath = this.getRepoFilePath(directory)
|
||||
if (!fs.existsSync(filePath)) {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
export const HOP_BY_HOP_HEADERS = new Set([
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'te',
|
||||
'trailers',
|
||||
'upgrade',
|
||||
'transfer-encoding',
|
||||
'content-length',
|
||||
'content-encoding',
|
||||
'host',
|
||||
'authorization',
|
||||
])
|
||||
|
||||
export function filterProxyHeaders(
|
||||
headers: Headers,
|
||||
extraExcluded: ReadonlySet<string> = new Set(),
|
||||
): Record<string, string> {
|
||||
const result: Record<string, string> = {}
|
||||
headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (HOP_BY_HOP_HEADERS.has(lowerKey) || extraExcluded.has(lowerKey)) return
|
||||
result[key] = value
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
export function buildProxyResponseHeaders(
|
||||
source: Headers,
|
||||
extraExcluded: ReadonlySet<string> = new Set(),
|
||||
): Headers {
|
||||
const excluded = new Set(extraExcluded)
|
||||
excluded.add('set-cookie')
|
||||
const headers = new Headers(filterProxyHeaders(source, excluded))
|
||||
for (const cookie of source.getSetCookie()) {
|
||||
headers.append('set-cookie', cookie)
|
||||
}
|
||||
return headers
|
||||
}
|
||||
@@ -162,7 +162,7 @@ describe('backend entrypoint', () => {
|
||||
it('initializes the workspace, registers every route group, and serves the app', async () => {
|
||||
await import('../src/index')
|
||||
|
||||
expect(serveMock).toHaveBeenCalledTimes(1)
|
||||
expect(serveMock).toHaveBeenCalledTimes(2)
|
||||
const options = serveMock.mock.calls[0]![0] as { fetch: unknown; port: number; hostname: string }
|
||||
expect(typeof options.fetch).toBe('function')
|
||||
expect(options.port).toBe(3001)
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { mkdtemp, mkdir, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { createPreviewRoutes } from '../../src/routes/preview'
|
||||
import { PreviewSessionStore } from '../../src/services/preview/gateway'
|
||||
import type { PreviewPortEntry } from '../../src/services/preview/ports'
|
||||
|
||||
function entry(overrides: Partial<PreviewPortEntry>): PreviewPortEntry {
|
||||
return { port: 5173, host: '127.0.0.1', pid: 1, command: 'node', cwd: null, ...overrides }
|
||||
}
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
async function makeTempDir(): Promise<string> {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'ocm-preview-'))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))
|
||||
})
|
||||
|
||||
describe('Preview Routes', () => {
|
||||
it('lists the directory-matching port first', async () => {
|
||||
const root = await makeTempDir()
|
||||
const appDir = join(root, 'app')
|
||||
await mkdir(appDir)
|
||||
|
||||
const app = createPreviewRoutes({
|
||||
enabled: true,
|
||||
listPorts: async () => [
|
||||
entry({ port: 9000, cwd: '/somewhere/else' }),
|
||||
entry({ port: 5173, cwd: appDir }),
|
||||
],
|
||||
})
|
||||
|
||||
const res = await app.request(`/ports?directory=${encodeURIComponent(root)}`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { enabled: boolean; ports: PreviewPortEntry[] }
|
||||
expect(body.enabled).toBe(true)
|
||||
expect(body.ports.map((port) => port.port)).toEqual([5173, 9000])
|
||||
})
|
||||
|
||||
it('sorts by port when no directory is given', async () => {
|
||||
const app = createPreviewRoutes({
|
||||
enabled: true,
|
||||
listPorts: async () => [entry({ port: 9000 }), entry({ port: 5173 })],
|
||||
})
|
||||
|
||||
const res = await app.request('/ports')
|
||||
const body = await res.json() as { ports: PreviewPortEntry[] }
|
||||
|
||||
expect(body.ports.map((port) => port.port)).toEqual([5173, 9000])
|
||||
})
|
||||
|
||||
it('reports preview as disabled when the port is zero', async () => {
|
||||
const app = createPreviewRoutes({ enabled: false, listPorts: async () => [] })
|
||||
|
||||
const res = await app.request('/ports')
|
||||
|
||||
expect(await res.json()).toEqual({ enabled: false, ports: [] })
|
||||
})
|
||||
|
||||
it('issues a preview start token for a listening port', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: 5173 })], store })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ port: 5173 }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { token: string; previewPort: number; publicUrl: string | null }
|
||||
expect(typeof body.token).toBe('string')
|
||||
expect(body.token.length).toBeGreaterThan(0)
|
||||
expect(body.previewPort).toBe(ENV.PREVIEW.PORT)
|
||||
expect(body.publicUrl).toBe(ENV.PREVIEW.PUBLIC_URL || null)
|
||||
})
|
||||
|
||||
it('rejects a reserved port with 400', async () => {
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: ENV.PREVIEW.PORT })] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ port: ENV.PREVIEW.PORT }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 for a port that is not listening', async () => {
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [entry({ port: 5173 })] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ port: 6000 }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.json()).toEqual({ error: 'Port 6000 is not listening' })
|
||||
})
|
||||
|
||||
it('returns 503 when preview is disabled', async () => {
|
||||
const app = createPreviewRoutes({ enabled: false, listPorts: async () => [entry({ port: 5173 })] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ port: 5173 }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
})
|
||||
|
||||
it('rejects an out-of-range port with 400', async () => {
|
||||
const app = createPreviewRoutes({ enabled: true, listPorts: async () => [] })
|
||||
|
||||
const res = await app.request('/sessions', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ port: 80 }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
@@ -20,6 +20,8 @@ vi.mock('../../src/db/queries', () => ({
|
||||
getRepoGitCredentialId: vi.fn(),
|
||||
setRepoGitCredentialId: vi.fn(),
|
||||
updateRepoName: vi.fn(),
|
||||
getRepoSetting: vi.fn(),
|
||||
setRepoSetting: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/repo', () => ({
|
||||
@@ -35,6 +37,7 @@ vi.mock('../../src/services/repo', () => ({
|
||||
resolveRepoOrAssistant: vi.fn(),
|
||||
findSiblingByDirectory: vi.fn(),
|
||||
resolveRepoWorkingDirectory: vi.fn(),
|
||||
resolveRepoProjectId: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/assistant-mode', () => ({
|
||||
@@ -96,6 +99,7 @@ const mockScheduleService = {
|
||||
|
||||
const mockTerminalService = {
|
||||
removeAll: vi.fn().mockResolvedValue(undefined),
|
||||
create: vi.fn(),
|
||||
} as unknown as TerminalService
|
||||
|
||||
function createTestRoutes(openCodeClient: ReturnType<typeof createStubOpenCodeClient> = createStubOpenCodeClient()): ReturnType<typeof createRepoRoutes> {
|
||||
@@ -131,6 +135,8 @@ describe('Repo Routes', () => {
|
||||
updatedAt: Date.now(),
|
||||
})
|
||||
vi.mocked(db.getRepoGitCredentialId).mockReturnValue(null)
|
||||
vi.mocked(db.getRepoSetting).mockReturnValue(null)
|
||||
vi.mocked(repoService.resolveRepoProjectId).mockResolvedValue('commit-A')
|
||||
vi.mocked(repoService.resolveRepoOrAssistant).mockImplementation(
|
||||
(_database, id) => vi.mocked(db.getRepoById)(_database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null),
|
||||
)
|
||||
@@ -480,8 +486,36 @@ describe('Repo Routes', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /discover', () => {
|
||||
it('should return 400 for an invalid body', async () => {
|
||||
describe('POST /:id/workspaces', () => {
|
||||
it('creates the workspace and returns the worktree setup result', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
|
||||
|
||||
const app = createTestRoutes()
|
||||
const res = await app.request('/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ directory: '/tmp/wrk-test', worktreeSetup: { status: 'none' } })
|
||||
})
|
||||
|
||||
it('returns 200 with a failed worktree setup when the setup terminal cannot start', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
|
||||
vi.mocked(db.getRepoSetting).mockImplementation((_database, _repoId, key) =>
|
||||
key === 'worktreeSetupCommands' ? JSON.stringify(['pnpm install']) : null,
|
||||
)
|
||||
vi.mocked(mockTerminalService.create).mockRejectedValueOnce(new Error('spawn failed'))
|
||||
|
||||
const app = createTestRoutes()
|
||||
const res = await app.request('/1/workspaces', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
directory: '/tmp/wrk-test',
|
||||
worktreeSetup: { status: 'failed', error: 'spawn failed' },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /discover', () => { it('should return 400 for an invalid body', async () => {
|
||||
const app = createTestRoutes()
|
||||
const res = await app.request('/discover', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { request as httpRequest } from 'node:http'
|
||||
import type { Server } from 'node:http'
|
||||
import type { AddressInfo } from 'node:net'
|
||||
import type { Duplex } from 'node:stream'
|
||||
import { Hono } from 'hono'
|
||||
import { serve } from '@hono/node-server'
|
||||
import { createNodeWebSocket } from '@hono/node-ws'
|
||||
import {
|
||||
createPreviewGatewayApp,
|
||||
PreviewSessionStore,
|
||||
} from '../../../src/services/preview/gateway'
|
||||
|
||||
class HandshakeError extends Error {
|
||||
constructor(readonly statusCode: number) {
|
||||
super(`WebSocket handshake failed with status ${statusCode}`)
|
||||
}
|
||||
}
|
||||
|
||||
interface ReceivedMessage {
|
||||
type: 'text' | 'binary'
|
||||
data: string | Buffer
|
||||
}
|
||||
|
||||
function encodeFrame(opcode: number, payload: Buffer): Buffer {
|
||||
const maskKey = randomBytes(4)
|
||||
const length = payload.length
|
||||
let header: Buffer
|
||||
if (length < 126) {
|
||||
header = Buffer.from([0x80 | opcode, 0x80 | length])
|
||||
} else if (length < 65536) {
|
||||
header = Buffer.alloc(4)
|
||||
header[0] = 0x80 | opcode
|
||||
header[1] = 0x80 | 126
|
||||
header.writeUInt16BE(length, 2)
|
||||
} else {
|
||||
header = Buffer.alloc(10)
|
||||
header[0] = 0x80 | opcode
|
||||
header[1] = 0x80 | 127
|
||||
header.writeBigUInt64BE(BigInt(length), 2)
|
||||
}
|
||||
const masked = Buffer.from(payload)
|
||||
for (let i = 0; i < masked.length; i += 1) {
|
||||
masked[i] = masked[i]! ^ maskKey[i % 4]!
|
||||
}
|
||||
return Buffer.concat([header, maskKey, masked])
|
||||
}
|
||||
|
||||
class RawWebSocketClient {
|
||||
private buffer = Buffer.alloc(0)
|
||||
private readonly messages: ReceivedMessage[] = []
|
||||
|
||||
private constructor(private readonly socket: Duplex, head: Buffer) {
|
||||
socket.on('data', (chunk: Buffer) => this.onData(chunk))
|
||||
if (head.length > 0) this.onData(head)
|
||||
}
|
||||
|
||||
static connect(options: { port: number; path: string; protocol?: string; cookie?: string }): Promise<RawWebSocketClient> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const headers: Record<string, string> = {
|
||||
Connection: 'Upgrade',
|
||||
Upgrade: 'websocket',
|
||||
'Sec-WebSocket-Key': randomBytes(16).toString('base64'),
|
||||
'Sec-WebSocket-Version': '13',
|
||||
}
|
||||
if (options.protocol) headers['Sec-WebSocket-Protocol'] = options.protocol
|
||||
if (options.cookie) headers.Cookie = options.cookie
|
||||
|
||||
const request = httpRequest({
|
||||
host: '127.0.0.1',
|
||||
port: options.port,
|
||||
path: options.path,
|
||||
method: 'GET',
|
||||
headers,
|
||||
})
|
||||
|
||||
let settled = false
|
||||
request.on('upgrade', (_res, socket, head) => {
|
||||
settled = true
|
||||
resolve(new RawWebSocketClient(socket, head))
|
||||
})
|
||||
request.on('response', (res) => {
|
||||
settled = true
|
||||
res.resume()
|
||||
reject(new HandshakeError(res.statusCode ?? 0))
|
||||
})
|
||||
request.on('error', (error) => {
|
||||
if (!settled) reject(error)
|
||||
})
|
||||
request.end()
|
||||
})
|
||||
}
|
||||
|
||||
send(text: string): void {
|
||||
this.socket.write(encodeFrame(0x1, Buffer.from(text, 'utf8')))
|
||||
}
|
||||
|
||||
async waitForMessage(index: number, timeoutMs = 5000): Promise<ReceivedMessage> {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
while (this.messages.length <= index) {
|
||||
if (Date.now() > deadline) throw new Error(`Timed out waiting for message ${index}`)
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
}
|
||||
return this.messages[index]!
|
||||
}
|
||||
|
||||
close(): void {
|
||||
try {
|
||||
this.socket.write(encodeFrame(0x8, Buffer.alloc(0)))
|
||||
} catch {
|
||||
this.socket.destroy()
|
||||
}
|
||||
this.socket.destroy()
|
||||
}
|
||||
|
||||
private onData(chunk: Buffer): void {
|
||||
this.buffer = Buffer.concat([this.buffer, chunk])
|
||||
for (;;) {
|
||||
if (this.buffer.length < 2) return
|
||||
const first = this.buffer[0]!
|
||||
const second = this.buffer[1]!
|
||||
const opcode = first & 0x0f
|
||||
const masked = (second & 0x80) !== 0
|
||||
let length = second & 0x7f
|
||||
let offset = 2
|
||||
if (length === 126) {
|
||||
if (this.buffer.length < 4) return
|
||||
length = this.buffer.readUInt16BE(2)
|
||||
offset = 4
|
||||
} else if (length === 127) {
|
||||
if (this.buffer.length < 10) return
|
||||
length = Number(this.buffer.readBigUInt64BE(2))
|
||||
offset = 10
|
||||
}
|
||||
let maskKey: Buffer | null = null
|
||||
if (masked) {
|
||||
if (this.buffer.length < offset + 4) return
|
||||
maskKey = this.buffer.subarray(offset, offset + 4)
|
||||
offset += 4
|
||||
}
|
||||
if (this.buffer.length < offset + length) return
|
||||
const payload = Buffer.from(this.buffer.subarray(offset, offset + length))
|
||||
this.buffer = this.buffer.subarray(offset + length)
|
||||
if (maskKey) {
|
||||
for (let i = 0; i < payload.length; i += 1) {
|
||||
payload[i] = payload[i]! ^ maskKey[i % 4]!
|
||||
}
|
||||
}
|
||||
if (opcode === 0x1) {
|
||||
this.messages.push({ type: 'text', data: payload.toString('utf8') })
|
||||
} else if (opcode === 0x2) {
|
||||
this.messages.push({ type: 'binary', data: payload })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let upstreamServer: Server
|
||||
let gatewayServer: Server
|
||||
let upstreamPort = 0
|
||||
let gatewayPort = 0
|
||||
let capturedUrl: URL | undefined
|
||||
let capturedProtocol: string | undefined
|
||||
|
||||
const store = new PreviewSessionStore()
|
||||
const gateway = createPreviewGatewayApp(store)
|
||||
|
||||
const upstreamApp = new Hono()
|
||||
const upstreamWs = createNodeWebSocket({ app: upstreamApp })
|
||||
|
||||
upstreamApp.get(
|
||||
'/*',
|
||||
upstreamWs.upgradeWebSocket((c) => {
|
||||
capturedUrl = new URL(c.req.url)
|
||||
capturedProtocol = c.req.header('sec-websocket-protocol')
|
||||
return {
|
||||
onMessage(event, ws) {
|
||||
if (typeof event.data === 'string') ws.send(event.data)
|
||||
},
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
upstreamApp.all('/*', (c) => c.json({ path: c.req.path, search: new URL(c.req.url).search }))
|
||||
|
||||
function listen(server: Server): Promise<number> {
|
||||
return new Promise((resolve) => {
|
||||
if (server.listening) {
|
||||
resolve((server.address() as AddressInfo).port)
|
||||
return
|
||||
}
|
||||
server.once('listening', () => resolve((server.address() as AddressInfo).port))
|
||||
})
|
||||
}
|
||||
|
||||
function closeServer(server: Server): Promise<void> {
|
||||
server.closeAllConnections()
|
||||
return new Promise((resolve) => server.close(() => resolve()))
|
||||
}
|
||||
|
||||
async function openSessionCookie(): Promise<string> {
|
||||
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
|
||||
const res = await gateway.app.request(
|
||||
`http://localhost/__ocm_preview/start?token=${encodeURIComponent(token)}`,
|
||||
{ redirect: 'manual' },
|
||||
)
|
||||
const setCookie = res.headers.get('set-cookie')
|
||||
if (!setCookie) throw new Error('Expected a Set-Cookie header')
|
||||
return setCookie.split(';')[0]!
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
upstreamServer = serve({ fetch: upstreamApp.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server
|
||||
upstreamWs.injectWebSocket(upstreamServer)
|
||||
upstreamPort = await listen(upstreamServer)
|
||||
|
||||
gatewayServer = serve({ fetch: gateway.app.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server
|
||||
gateway.injectWebSocket(gatewayServer)
|
||||
gatewayPort = await listen(gatewayServer)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
upstreamWs.wss.close()
|
||||
await closeServer(upstreamServer)
|
||||
await closeServer(gatewayServer)
|
||||
})
|
||||
|
||||
describe('Preview Gateway WebSocket', () => {
|
||||
it('bridges an authenticated upgrade and forwards the protocol, path and query upstream', async () => {
|
||||
const cookie = await openSessionCookie()
|
||||
|
||||
const client = await RawWebSocketClient.connect({
|
||||
port: gatewayPort,
|
||||
path: '/hmr?token=abc',
|
||||
protocol: 'vite-hmr',
|
||||
cookie,
|
||||
})
|
||||
|
||||
client.send('hello hmr')
|
||||
const message = await client.waitForMessage(0)
|
||||
|
||||
expect(message.type).toBe('text')
|
||||
expect(message.data).toBe('hello hmr')
|
||||
expect(capturedUrl?.pathname).toBe('/hmr')
|
||||
expect(capturedUrl?.search).toBe('?token=abc')
|
||||
expect(capturedProtocol).toBe('vite-hmr')
|
||||
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('fails the handshake for an upgrade without a preview session cookie', async () => {
|
||||
let failure: HandshakeError | undefined
|
||||
try {
|
||||
await RawWebSocketClient.connect({ port: gatewayPort, path: '/hmr', protocol: 'vite-hmr' })
|
||||
} catch (error) {
|
||||
failure = error as HandshakeError
|
||||
}
|
||||
|
||||
expect(failure).toBeInstanceOf(HandshakeError)
|
||||
expect(failure?.statusCode).toBe(401)
|
||||
})
|
||||
|
||||
it('still proxies a plain HTTP GET on the same path', async () => {
|
||||
const cookie = await openSessionCookie()
|
||||
|
||||
const res = await fetch(`http://127.0.0.1:${gatewayPort}/echo?q=2`, { headers: { cookie } })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { path: string; search: string }
|
||||
expect(body.path).toBe('/echo')
|
||||
expect(body.search).toBe('?q=2')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,258 @@
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
|
||||
import { createServer } from 'node:http'
|
||||
import type { Server } from 'node:http'
|
||||
import type { AddressInfo } from 'node:net'
|
||||
import { gunzipSync, gzipSync } from 'node:zlib'
|
||||
import { Hono } from 'hono'
|
||||
import { serve } from '@hono/node-server'
|
||||
import {
|
||||
createPreviewGatewayApp,
|
||||
PreviewSessionStore,
|
||||
PREVIEW_COOKIE,
|
||||
} from '../../../src/services/preview/gateway'
|
||||
|
||||
let upstreamServer: Server
|
||||
let upstreamPort = 0
|
||||
|
||||
const upstreamApp = new Hono()
|
||||
|
||||
upstreamApp.post('/gzip', async (c) => {
|
||||
const encoding = c.req.header('content-encoding') ?? null
|
||||
const bytes = Buffer.from(await c.req.arrayBuffer())
|
||||
const decoded = encoding === 'gzip' ? gunzipSync(bytes).toString('utf8') : null
|
||||
return c.json({ encoding, decoded })
|
||||
})
|
||||
|
||||
upstreamApp.get('/cookies', () => {
|
||||
const headers = new Headers()
|
||||
headers.append('set-cookie', 'session=abc; Path=/; HttpOnly')
|
||||
headers.append('set-cookie', 'csrf=def; Path=/; Expires=Wed, 21 Oct 2026 07:28:00 GMT')
|
||||
headers.set('content-type', 'text/plain')
|
||||
return new Response('ok', { status: 200, headers })
|
||||
})
|
||||
|
||||
upstreamApp.all('/*', async (c) => {
|
||||
if (c.req.path === '/r') {
|
||||
return c.redirect(`http://localhost:${upstreamPort}/done`, 302)
|
||||
}
|
||||
const body = c.req.method === 'GET' || c.req.method === 'HEAD' ? '' : await c.req.text()
|
||||
return c.json({
|
||||
method: c.req.method,
|
||||
path: c.req.path,
|
||||
search: new URL(c.req.url).search,
|
||||
host: c.req.header('host') ?? null,
|
||||
cookie: c.req.header('cookie') ?? null,
|
||||
body,
|
||||
})
|
||||
})
|
||||
|
||||
function listen(server: Server): Promise<number> {
|
||||
return new Promise((resolve) => {
|
||||
if (server.listening) {
|
||||
resolve((server.address() as AddressInfo).port)
|
||||
return
|
||||
}
|
||||
server.once('listening', () => resolve((server.address() as AddressInfo).port))
|
||||
})
|
||||
}
|
||||
|
||||
function closeServer(server: Server): Promise<void> {
|
||||
server.closeAllConnections()
|
||||
return new Promise((resolve) => server.close(() => resolve()))
|
||||
}
|
||||
|
||||
function reserveClosedPort(): Promise<number> {
|
||||
return new Promise((resolve) => {
|
||||
const server = createServer()
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const port = (server.address() as AddressInfo).port
|
||||
server.close(() => resolve(port))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function previewCookieFrom(res: Response): string {
|
||||
const setCookie = res.headers.get('set-cookie')
|
||||
if (!setCookie) throw new Error('Expected a Set-Cookie header')
|
||||
return setCookie.split(';')[0]!
|
||||
}
|
||||
|
||||
async function openSession(app: Hono, store: PreviewSessionStore, port: number): Promise<string> {
|
||||
const token = store.issueStartToken({ port, host: '127.0.0.1' })
|
||||
const res = await app.request(
|
||||
`http://localhost/__ocm_preview/start?token=${encodeURIComponent(token)}`,
|
||||
{ redirect: 'manual' },
|
||||
)
|
||||
return previewCookieFrom(res)
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
upstreamServer = serve({ fetch: upstreamApp.fetch, port: 0, hostname: '127.0.0.1' }) as unknown as Server
|
||||
upstreamPort = await listen(upstreamServer)
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await closeServer(upstreamServer)
|
||||
})
|
||||
|
||||
describe('Preview Gateway', () => {
|
||||
it('consumes the start token, sets the preview cookie, and redirects to the given path', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
|
||||
|
||||
const res = await app.request(
|
||||
`http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent('/app?x=1')}`,
|
||||
{ redirect: 'manual' },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(302)
|
||||
expect(res.headers.get('location')).toBe('/app?x=1')
|
||||
const setCookie = res.headers.get('set-cookie') ?? ''
|
||||
expect(setCookie).toContain(`${PREVIEW_COOKIE}=`)
|
||||
expect(setCookie).toContain('HttpOnly')
|
||||
expect(setCookie).toContain('SameSite=Lax')
|
||||
expect(setCookie).toContain('Path=/')
|
||||
})
|
||||
|
||||
it('redirects a protocol-relative path to the root', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
|
||||
|
||||
const res = await app.request(
|
||||
`http://localhost/__ocm_preview/start?token=${token}&path=${encodeURIComponent('//evil.example')}`,
|
||||
{ redirect: 'manual' },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(302)
|
||||
expect(res.headers.get('location')).toBe('/')
|
||||
})
|
||||
|
||||
it('does not allow a start token to be reused', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
|
||||
|
||||
const first = await app.request(`http://localhost/__ocm_preview/start?token=${token}`, { redirect: 'manual' })
|
||||
expect(first.status).toBe(302)
|
||||
|
||||
const second = await app.request(`http://localhost/__ocm_preview/start?token=${token}`, { redirect: 'manual' })
|
||||
expect(second.status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects an expired start token', async () => {
|
||||
let now = 1_000
|
||||
const store = new PreviewSessionStore({ now: () => now, randomToken: () => 'expired-token' })
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const token = store.issueStartToken({ port: upstreamPort, host: '127.0.0.1' })
|
||||
|
||||
now += 61_000
|
||||
|
||||
const res = await app.request(`http://localhost/__ocm_preview/start?token=${token}`, { redirect: 'manual' })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects a request without a preview cookie', async () => {
|
||||
const app = createPreviewGatewayApp(new PreviewSessionStore()).app
|
||||
|
||||
const res = await app.request('http://localhost/anything')
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('proxies with the localhost host header and strips Manager cookies', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, upstreamPort)
|
||||
|
||||
const res = await app.request('http://localhost/echo?q=1', {
|
||||
headers: { cookie: `${cookie}; user=abc; opencode.session_token=secret` },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { method: string; path: string; search: string; host: string; cookie: string }
|
||||
expect(body.method).toBe('GET')
|
||||
expect(body.path).toBe('/echo')
|
||||
expect(body.search).toBe('?q=1')
|
||||
expect(body.host).toBe(`localhost:${upstreamPort}`)
|
||||
expect(body.cookie).toBe('user=abc')
|
||||
})
|
||||
|
||||
it('forwards a POST body', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, upstreamPort)
|
||||
|
||||
const res = await app.request('http://localhost/echo', {
|
||||
method: 'POST',
|
||||
headers: { cookie },
|
||||
body: 'hello preview',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { method: string; body: string }
|
||||
expect(body.method).toBe('POST')
|
||||
expect(body.body).toBe('hello preview')
|
||||
})
|
||||
|
||||
it('forwards a gzip-encoded request body together with its content-encoding', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, upstreamPort)
|
||||
|
||||
const payload = 'compressed telemetry payload'
|
||||
const gzipped = gzipSync(Buffer.from(payload, 'utf8'))
|
||||
|
||||
const res = await app.request('http://localhost/gzip', {
|
||||
method: 'POST',
|
||||
headers: { cookie, 'content-encoding': 'gzip', 'content-type': 'application/json' },
|
||||
body: gzipped,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { encoding: string | null; decoded: string | null }
|
||||
expect(body.encoding).toBe('gzip')
|
||||
expect(body.decoded).toBe(payload)
|
||||
})
|
||||
|
||||
it('forwards every upstream Set-Cookie value separately and intact', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, upstreamPort)
|
||||
|
||||
const res = await app.request('http://localhost/cookies', { headers: { cookie } })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const cookies = res.headers.getSetCookie()
|
||||
expect(cookies).toContain('session=abc; Path=/; HttpOnly')
|
||||
expect(cookies).toContain('csrf=def; Path=/; Expires=Wed, 21 Oct 2026 07:28:00 GMT')
|
||||
expect(cookies).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('rewrites an absolute localhost location to its path', async () => {
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, upstreamPort)
|
||||
|
||||
const res = await app.request('http://localhost/r', {
|
||||
headers: { cookie },
|
||||
redirect: 'manual',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(302)
|
||||
expect(res.headers.get('location')).toBe('/done')
|
||||
})
|
||||
|
||||
it('returns 502 when the target port is unreachable', async () => {
|
||||
const closedPort = await reserveClosedPort()
|
||||
const store = new PreviewSessionStore()
|
||||
const app = createPreviewGatewayApp(store).app
|
||||
const cookie = await openSession(app, store, closedPort)
|
||||
|
||||
const res = await app.request('http://localhost/anything', { headers: { cookie } })
|
||||
|
||||
expect(res.status).toBe(502)
|
||||
expect(await res.text()).toContain(String(closedPort))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
isReservedPreviewPort,
|
||||
listListeningPorts,
|
||||
parseLsofListen,
|
||||
parseProcNetTcp,
|
||||
type PortDiscoveryDeps,
|
||||
} from '../../../src/services/preview/ports'
|
||||
|
||||
const PROC_HEADER = ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode'
|
||||
|
||||
function procRow(local: string, remote: string, state: string, inode: string): string {
|
||||
return ` 0: ${local} ${remote} ${state} 00000000:00000000 00:00000000 00000000 1000 0 ${inode} 1 0000000000000000 100 0 0 10 0`
|
||||
}
|
||||
|
||||
const IPV4_FIXTURE = [
|
||||
PROC_HEADER,
|
||||
procRow('00000000:1435', '00000000:0000', '0A', '11111'),
|
||||
procRow('0100007F:1F90', '00000000:0000', '0A', '22222'),
|
||||
procRow('0501A8C0:1F90', '00000000:0000', '0A', '33333'),
|
||||
procRow('0100007F:1435', '0100007F:9C40', '01', '44444'),
|
||||
].join('\n')
|
||||
|
||||
const IPV6_FIXTURE = [
|
||||
PROC_HEADER,
|
||||
procRow('00000000000000000000000001000000:0BB8', '00000000000000000000000000000000:0000', '0A', '55555'),
|
||||
procRow('00000000000000000000000000000000:1F90', '00000000000000000000000000000000:0000', '0A', '66666'),
|
||||
procRow('b80d0120000000000000000001000000:1F90', '00000000000000000000000000000000:0000', '0A', '77777'),
|
||||
].join('\n')
|
||||
|
||||
interface FakeFileSystem {
|
||||
files: Record<string, string>
|
||||
links: Record<string, string>
|
||||
dirs: Record<string, string[]>
|
||||
}
|
||||
|
||||
function createDeps(fs: FakeFileSystem, overrides: Partial<PortDiscoveryDeps> = {}): PortDiscoveryDeps {
|
||||
return {
|
||||
platform: 'linux',
|
||||
readFile: async (path) => {
|
||||
const value = fs.files[path]
|
||||
if (value === undefined) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
|
||||
return value
|
||||
},
|
||||
readdir: async (path) => {
|
||||
const value = fs.dirs[path]
|
||||
if (value === undefined) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
|
||||
return value
|
||||
},
|
||||
readlink: async (path) => {
|
||||
const value = fs.links[path]
|
||||
if (value === undefined) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
|
||||
return value
|
||||
},
|
||||
runLsof: async () => '',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('parseProcNetTcp', () => {
|
||||
it('keeps loopback and wildcard IPv4 listeners and drops other rows', () => {
|
||||
const sockets = parseProcNetTcp(IPV4_FIXTURE, 4)
|
||||
|
||||
expect(sockets).toEqual([
|
||||
{ port: 5173, address: '0.0.0.0', inode: '11111' },
|
||||
{ port: 8080, address: '127.0.0.1', inode: '22222' },
|
||||
])
|
||||
})
|
||||
|
||||
it('decodes little-endian IPv6 addresses and keeps loopback and wildcard', () => {
|
||||
const sockets = parseProcNetTcp(IPV6_FIXTURE, 6)
|
||||
|
||||
expect(sockets).toEqual([
|
||||
{ port: 3000, address: '::1', inode: '55555' },
|
||||
{ port: 8080, address: '::', inode: '66666' },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseLsofListen', () => {
|
||||
it('parses pid, command and port from field output', () => {
|
||||
const output = ['p1234', 'cnode', 'n127.0.0.1:5173', 'p5678', 'cnginx', 'n*:8080'].join('\n')
|
||||
|
||||
expect(parseLsofListen(output)).toEqual([
|
||||
{ port: 5173, address: '127.0.0.1', pid: 1234, command: 'node' },
|
||||
{ port: 8080, address: '0.0.0.0', pid: 5678, command: 'nginx' },
|
||||
])
|
||||
})
|
||||
|
||||
it('parses bracketed IPv6 names', () => {
|
||||
const output = ['p42', 'cdeno', 'n[::1]:3000'].join('\n')
|
||||
|
||||
expect(parseLsofListen(output)).toEqual([
|
||||
{ port: 3000, address: '::1', pid: 42, command: 'deno' },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('isReservedPreviewPort', () => {
|
||||
it('reserves the manager, opencode and preview ports', () => {
|
||||
expect(isReservedPreviewPort(ENV.SERVER.PORT)).toBe(true)
|
||||
expect(isReservedPreviewPort(ENV.OPENCODE.PORT)).toBe(true)
|
||||
expect(isReservedPreviewPort(ENV.PREVIEW.PORT)).toBe(true)
|
||||
expect(isReservedPreviewPort(5173)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('listListeningPorts', () => {
|
||||
it('maps inode to pid, command and cwd and excludes reserved and privileged ports', async () => {
|
||||
const deps = createDeps({
|
||||
files: {
|
||||
'/proc/net/tcp': [
|
||||
PROC_HEADER,
|
||||
procRow('00000000:1435', '00000000:0000', '0A', '11111'),
|
||||
procRow('00000000:0050', '00000000:0000', '0A', '33333'),
|
||||
procRow(`00000000:${ENV.SERVER.PORT.toString(16).toUpperCase().padStart(4, '0')}`, '00000000:0000', '0A', '22222'),
|
||||
].join('\n'),
|
||||
'/proc/1234/comm': 'node\n',
|
||||
},
|
||||
links: {
|
||||
'/proc/1234/fd/3': 'socket:[11111]',
|
||||
'/proc/1234/cwd': '/home/user/project',
|
||||
'/proc/1234/fd/4': 'socket:[33333]',
|
||||
'/proc/9999/fd/2': 'socket:[22222]',
|
||||
'/proc/9999/cwd': '/srv/api',
|
||||
'/proc/9999/comm': 'bun\n',
|
||||
},
|
||||
dirs: {
|
||||
'/proc': ['1234', '9999', 'self', 'cpuinfo'],
|
||||
'/proc/1234/fd': ['0', '3', '4'],
|
||||
'/proc/9999/fd': ['2'],
|
||||
},
|
||||
})
|
||||
|
||||
const ports = await listListeningPorts(deps)
|
||||
|
||||
expect(ports).toEqual([
|
||||
{ port: 5173, host: '127.0.0.1', pid: 1234, command: 'node', cwd: '/home/user/project' },
|
||||
])
|
||||
})
|
||||
|
||||
it('reports an IPv6 loopback host only when the sole listener is IPv6 loopback', async () => {
|
||||
const deps = createDeps({
|
||||
files: {
|
||||
'/proc/net/tcp': '',
|
||||
'/proc/net/tcp6': [
|
||||
PROC_HEADER,
|
||||
procRow('00000000000000000000000001000000:0BB8', '00000000000000000000000000000000:0000', '0A', '55555'),
|
||||
procRow('00000000000000000000000001000000:1F90', '00000000000000000000000000000000:0000', '0A', '66666'),
|
||||
procRow('00000000000000000000000000000000:1F90', '00000000000000000000000000000000:0000', '0A', '77777'),
|
||||
].join('\n'),
|
||||
'/proc/1234/comm': 'vite\n',
|
||||
},
|
||||
links: {
|
||||
'/proc/1234/fd/5': 'socket:[55555]',
|
||||
'/proc/1234/fd/6': 'socket:[66666]',
|
||||
'/proc/1234/fd/7': 'socket:[77777]',
|
||||
'/proc/1234/cwd': '/home/user/app',
|
||||
},
|
||||
dirs: {
|
||||
'/proc': ['1234'],
|
||||
'/proc/1234/fd': ['5', '6', '7'],
|
||||
},
|
||||
})
|
||||
|
||||
const ports = await listListeningPorts(deps)
|
||||
|
||||
expect(ports).toEqual([
|
||||
{ port: 3000, host: '::1', pid: 1234, command: 'vite', cwd: '/home/user/app' },
|
||||
{ port: 8080, host: '127.0.0.1', pid: 1234, command: 'vite', cwd: '/home/user/app' },
|
||||
])
|
||||
})
|
||||
|
||||
it('uses lsof on macOS with a null cwd', async () => {
|
||||
const deps = createDeps(
|
||||
{ files: {}, links: {}, dirs: {} },
|
||||
{
|
||||
platform: 'darwin',
|
||||
runLsof: async () => ['p777', 'cnode', 'n127.0.0.1:5173'].join('\n'),
|
||||
},
|
||||
)
|
||||
|
||||
expect(await listListeningPorts(deps)).toEqual([
|
||||
{ port: 5173, host: '127.0.0.1', pid: 777, command: 'node', cwd: null },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns an empty list on unsupported platforms', async () => {
|
||||
const deps = createDeps({ files: {}, links: {}, dirs: {} }, { platform: 'win32' })
|
||||
|
||||
expect(await listListeningPorts(deps)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -809,3 +809,135 @@ describe('ProjectConfigService runAction', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('ProjectConfigService runWorktreeSetup', () => {
|
||||
let db: Database
|
||||
let service: ProjectConfigService
|
||||
let repo: Repo
|
||||
let directory: string
|
||||
|
||||
function writeRepoFile(content: unknown): void {
|
||||
const filePath = path.join(directory, '.ocm', 'project.json')
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
||||
fs.writeFileSync(filePath, JSON.stringify(content, null, 2))
|
||||
}
|
||||
|
||||
function createFakeTerminalService() {
|
||||
const create = vi.fn(
|
||||
async (target: string, input: CreateTerminalInput): Promise<TerminalInfo> => ({
|
||||
id: 'pty-setup',
|
||||
title: formatTerminalTitle({ kind: input.kind, name: input.name }),
|
||||
kind: input.kind,
|
||||
cwd: target,
|
||||
status: 'running',
|
||||
}),
|
||||
)
|
||||
return { service: { create } as unknown as TerminalService, create }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
service = createService(db)
|
||||
directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ocm-worktree-setup-'))
|
||||
repo = createRepo(db, {
|
||||
localPath: directory,
|
||||
sourcePath: directory,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
fs.rmSync(directory, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('starts a setup terminal with the personal commands and ROOT_PROJECT_PATH', async () => {
|
||||
service.setPersonalSetup(repo, ['pnpm install', 'pnpm build'])
|
||||
const terminalService = createFakeTerminalService()
|
||||
|
||||
const result = await service.runWorktreeSetup(repo, directory, terminalService.service)
|
||||
|
||||
expect(terminalService.create).toHaveBeenCalledWith(directory, {
|
||||
kind: 'setup',
|
||||
name: 'Worktree setup',
|
||||
command: '/bin/sh',
|
||||
args: ['-c', 'set -e\npnpm install\npnpm build'],
|
||||
env: { ROOT_PROJECT_PATH: repo.fullPath },
|
||||
})
|
||||
expect(result).toEqual({
|
||||
status: 'started',
|
||||
terminal: {
|
||||
id: 'pty-setup',
|
||||
title: 'ocm:setup:Worktree setup',
|
||||
kind: 'setup',
|
||||
cwd: directory,
|
||||
status: 'running',
|
||||
},
|
||||
repoCommandsSkipped: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('excludes untrusted repository commands and reports them skipped', async () => {
|
||||
service.setPersonalSetup(repo, ['pnpm install'])
|
||||
writeRepoFile({ version: 1, setupWorktree: ['pnpm repo-setup'] })
|
||||
const terminalService = createFakeTerminalService()
|
||||
|
||||
const result = await service.runWorktreeSetup(repo, directory, terminalService.service)
|
||||
|
||||
expect(terminalService.create).toHaveBeenCalledWith(
|
||||
directory,
|
||||
expect.objectContaining({ args: ['-c', 'set -e\npnpm install'] }),
|
||||
)
|
||||
expect(result).toMatchObject({ status: 'started', repoCommandsSkipped: true })
|
||||
})
|
||||
|
||||
it('includes trusted repository commands', async () => {
|
||||
writeRepoFile({ version: 1, setupWorktree: ['pnpm repo-setup'] })
|
||||
const first = await service.getConfig(repo, directory)
|
||||
await service.trustRepoFile(repo, directory, first.repoFile.hash ?? '')
|
||||
const terminalService = createFakeTerminalService()
|
||||
|
||||
const result = await service.runWorktreeSetup(repo, directory, terminalService.service)
|
||||
|
||||
expect(terminalService.create).toHaveBeenCalledWith(
|
||||
directory,
|
||||
expect.objectContaining({ args: ['-c', 'set -e\npnpm repo-setup'] }),
|
||||
)
|
||||
expect(result).toMatchObject({ status: 'started', repoCommandsSkipped: false })
|
||||
})
|
||||
|
||||
it('returns skipped when the only commands are untrusted repository commands', async () => {
|
||||
writeRepoFile({ version: 1, setupWorktree: ['pnpm repo-setup'] })
|
||||
const terminalService = createFakeTerminalService()
|
||||
|
||||
const result = await service.runWorktreeSetup(repo, directory, terminalService.service)
|
||||
|
||||
expect(result).toEqual({ status: 'skipped', reason: 'untrusted' })
|
||||
expect(terminalService.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns none when no commands are configured', async () => {
|
||||
const terminalService = createFakeTerminalService()
|
||||
|
||||
const result = await service.runWorktreeSetup(repo, directory, terminalService.service)
|
||||
|
||||
expect(result).toEqual({ status: 'none' })
|
||||
expect(terminalService.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns failed when the terminal cannot be created', async () => {
|
||||
service.setPersonalSetup(repo, ['pnpm install'])
|
||||
const create = vi.fn(async () => {
|
||||
throw new Error('spawn failed')
|
||||
})
|
||||
const terminalService = { create } as unknown as TerminalService
|
||||
|
||||
const result = await service.runWorktreeSetup(repo, directory, terminalService)
|
||||
|
||||
expect(result).toEqual({ status: 'failed', error: 'spawn failed' })
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,7 @@ services:
|
||||
container_name: opencode-manager
|
||||
ports:
|
||||
- "5003:5003"
|
||||
- "5004:5004"
|
||||
- "5100:5100"
|
||||
- "5101:5101"
|
||||
- "5102:5102"
|
||||
|
||||
@@ -40,6 +40,7 @@ services:
|
||||
container_name: opencode-manager
|
||||
ports:
|
||||
- "5003:5003"
|
||||
- "5004:5004"
|
||||
- "5100:5100"
|
||||
- "5101:5101"
|
||||
- "5102:5102"
|
||||
@@ -157,7 +158,14 @@ ports:
|
||||
|
||||
### Dev Server Ports
|
||||
|
||||
Ports 5100-5103 are exposed for running dev servers inside repositories:
|
||||
Port 5004 is the [preview gateway](../features/preview.md). It proxies a running dev server through an authenticated origin and supports HMR, so it is the recommended way to view a dev server:
|
||||
|
||||
```yaml
|
||||
ports:
|
||||
- "5004:5004"
|
||||
```
|
||||
|
||||
Ports 5100-5103 remain exposed for running dev servers inside repositories and reaching them directly:
|
||||
|
||||
```yaml
|
||||
ports:
|
||||
@@ -167,6 +175,8 @@ ports:
|
||||
- "5103:5103"
|
||||
```
|
||||
|
||||
Exposing these raw ports bypasses the preview gateway's authentication and same-origin isolation. Prefer the gateway unless you need direct access to a dev server.
|
||||
|
||||
Configure your dev server to use one of these ports:
|
||||
|
||||
=== "Vite"
|
||||
|
||||
@@ -76,6 +76,15 @@ When configured, users can enable push notifications in Settings → Notificatio
|
||||
| `LOG_LEVEL` | Accepted but currently unused; debug output is controlled by `DEBUG` | `info` |
|
||||
| `DEBUG` | Enable debug logging | `false` |
|
||||
|
||||
## Preview Gateway
|
||||
|
||||
The preview gateway serves dev servers through an authenticated, separate origin (see [Preview](../features/preview.md)).
|
||||
|
||||
| Variable | Description | Default |
|
||||
|----------|-------------|---------|
|
||||
| `PREVIEW_PORT` | Port for the preview gateway. Set to `0` to disable preview entirely. | `5004` |
|
||||
| `PREVIEW_PUBLIC_URL` | Same-site HTTPS origin that proxies the preview gateway. Set this when the Manager is served over HTTPS or behind a reverse proxy, where mixed content and third-party cookies otherwise block the preview iframe. | empty |
|
||||
|
||||
## Database
|
||||
|
||||
| Variable | Description | Default |
|
||||
|
||||
@@ -23,6 +23,14 @@ OpenCode Manager provides a comprehensive web interface for managing OpenCode AI
|
||||
|
||||
[Learn more →](files.md)
|
||||
|
||||
### Terminal & Dev Loop
|
||||
|
||||
- **Terminal** — Interactive PTY terminals scoped to a repo or workspace directory, with tabs and reconnect after reload
|
||||
- **Project Actions** — Run and stop repo commands from the header menu, with shared `.ocm/project.json` actions and worktree setup commands
|
||||
- **Preview** — View a running dev server through an authenticated, same-origin-safe preview gateway with HMR support
|
||||
|
||||
[Terminal →](terminal.md) · [Project Actions →](project-actions.md) · [Preview →](preview.md)
|
||||
|
||||
### Chat & Sessions
|
||||
|
||||
- **Real-time Streaming** - Live message streaming with SSE
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Preview
|
||||
|
||||
Open a running dev server inside the WebUI through an authenticated gateway.
|
||||
|
||||
The Preview panel lists the loopback ports that are currently listening, then proxies the selected one through a dedicated gateway origin. This lets you view a Vite, Next.js, or other dev server without exposing its raw port or weakening the Manager's own origin.
|
||||
|
||||
## Port List
|
||||
|
||||
Open **Preview** from the desktop sidebar tool list or the **More** drawer. The panel lists every listening loopback port on the host, with its port number, process command, and working directory. Ports inside the selected repository or workspace directory are badged **this repo** and sorted first.
|
||||
|
||||
The list excludes reserved ports — the Manager port (`PORT`, default 5003), the OpenCode server port (default 5551) and the preview gateway port itself — and only includes ports at or above 1024.
|
||||
|
||||
Selecting a port creates a preview session and renders the target in a sandboxed iframe. Selecting a different port starts a new session for it.
|
||||
|
||||
When preview is disabled the panel shows **Preview is disabled (PREVIEW_PORT=0)**.
|
||||
|
||||
If the requested port is not listening yet, the panel shows **Waiting for port N…** and refetches the list every 2 seconds for up to 60 seconds, then shows an error with a **Retry** button.
|
||||
|
||||
## Gateway
|
||||
|
||||
The preview gateway listens on `PREVIEW_PORT` (default 5004) on its own origin. It is a separate origin from the Manager on purpose: preview content is untrusted and must not share the Manager origin. Setting `PREVIEW_PORT=0` disables the gateway.
|
||||
|
||||
Access requires an authenticated preview session:
|
||||
|
||||
1. The Manager API mints a **single-use start token** for a listening port.
|
||||
2. The browser navigates to `/__ocm_preview/start?token=…&path=…` on the gateway origin.
|
||||
3. The gateway consumes the token (it expires after 60 seconds and cannot be reused) and sets an `ocm_preview` session cookie.
|
||||
|
||||
Requests then carry the cookie. Manager auth cookies are stripped before proxying, because host-scoped cookies are shared across ports; the preview target never sees them.
|
||||
|
||||
The gateway also proxies **WebSocket upgrades** on the same origin, so dev-server HMR works through the panel.
|
||||
|
||||
A browser can hold one preview target per gateway origin at a time: the `ocm_preview` cookie names a single session. Opening a different port replaces the current target.
|
||||
|
||||
## Opening Previews
|
||||
|
||||
A preview can be opened from more than one place:
|
||||
|
||||
- **Port list** — select a port in the panel.
|
||||
- **Terminal links** — clicking a local dev URL (`http://localhost:PORT`, `127.0.0.1`, `0.0.0.0`, or `[::1]`) printed in a terminal opens the Preview panel at that port and path instead of a new browser tab. External links still open in a new tab.
|
||||
- **Project actions** — an action's resolved URL opens in the Preview panel when **Auto-open URL** is enabled.
|
||||
|
||||
## Toolbar
|
||||
|
||||
- **Path** — enter a path and press **Go** (or Enter) to start a session for that path.
|
||||
- **Reload** — remounts the iframe.
|
||||
- **Open in new tab** — creates a fresh session and opens its start URL in a new tab with `noopener`. Start tokens are single-use, so this always mints a new one.
|
||||
- **Viewport** — switch between Mobile (390 px), Tablet (820 px), and Full width.
|
||||
|
||||
## Behind HTTPS or a Reverse Proxy
|
||||
|
||||
By default the panel builds the gateway origin as `${location.protocol}//${location.hostname}:${PREVIEW_PORT}`. When the Manager is served over HTTPS (directly or behind a reverse proxy), the browser blocks the iframe for two reasons:
|
||||
|
||||
- **Mixed content** — an `https://` page cannot embed an `http://` preview.
|
||||
- **Third-party cookies** — the `ocm_preview` cookie is blocked in a cross-site iframe.
|
||||
|
||||
Set `PREVIEW_PUBLIC_URL` to a same-site HTTPS origin that proxies the preview gateway, for example `https://preview.example.com`. The panel then builds preview URLs from that origin instead. As a fallback, **Open in new tab** opens the preview as a top-level page, where the session cookie is first-party.
|
||||
|
||||
## Related
|
||||
|
||||
- [Environment Variables](../configuration/environment.md) — `PREVIEW_PORT` and `PREVIEW_PUBLIC_URL`.
|
||||
- [Docker](../configuration/docker.md) — exposing the preview gateway port.
|
||||
- [Terminal & Dev Loop](terminal.md) — start a dev server in a terminal.
|
||||
@@ -0,0 +1,107 @@
|
||||
# Project Actions
|
||||
|
||||
Define repeatable commands for a repository and run them from the header menu.
|
||||
|
||||
Project actions are long-lived commands — a dev server, a build watcher, a test runner — that run in a terminal. They are configured in one of two places:
|
||||
|
||||
- **My settings** (personal) — stored in the Manager database, keyed to the repository's main checkout, so they apply across the repository and all its worktrees.
|
||||
- **The repository file** — `.ocm/project.json` at the repo root, committed and shared with everyone who clones it.
|
||||
|
||||
Both sources are merged in the **Project Actions** dialog and the header menu.
|
||||
|
||||
## Actions
|
||||
|
||||
An action has these fields:
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| `id` | Stable identifier. Letters, digits, `_` and `-`, up to 64 characters. |
|
||||
| `name` | Label shown in the menu, up to 60 characters. |
|
||||
| `command` | Shell command, up to 4000 characters. |
|
||||
| `icon` | Optional icon: `play`, `build`, `test`, `lint`, `terminal`, `server`, `bug`, or `rocket`. |
|
||||
| `url` | Optional URL template opened for the action. |
|
||||
| `autoOpenUrl` | When enabled, the resolved URL opens automatically after the action starts. |
|
||||
|
||||
Actions run as `/bin/sh -c <command>` in a PTY. Starting an action that is already running focuses its existing terminal instead of starting a second process. Stopping an action removes its PTY.
|
||||
|
||||
### URL Templates
|
||||
|
||||
The `url` field accepts two placeholders:
|
||||
|
||||
| Placeholder | Resolves to |
|
||||
|-------------|-------------|
|
||||
| `{worktree}` | The basename of the current directory. |
|
||||
| `{branch}` | The current git branch of the directory, from `git rev-parse --abbrev-ref HEAD`. |
|
||||
|
||||
For example, `http://localhost:5173/{worktree}` becomes `http://localhost:5173/feature-login` in a worktree named `feature-login`. If `{branch}` cannot be resolved (for example, a detached HEAD with no branch), the template is left unchanged.
|
||||
|
||||
When the resolved URL is a local dev URL (`http://localhost:PORT`, `127.0.0.1`, `0.0.0.0`, or `[::1]`), it opens in the [Preview](preview.md) panel rather than a new browser tab.
|
||||
|
||||
## Running and Stopping
|
||||
|
||||
The repository and session headers show a **Project actions** play button. The menu lists every configured action:
|
||||
|
||||
- Select an action to start it. The terminal opens automatically.
|
||||
- A running action shows a dot. Select **Stop** under it to remove its PTY.
|
||||
- Select **Manage actions…** to open the Project Actions dialog.
|
||||
|
||||
Actions defined in the repository file never run until trusted (see [Trust](#trust)).
|
||||
|
||||
## Repository Configuration File
|
||||
|
||||
`.ocm/project.json` defines actions and worktree setup commands for the repository. The format:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"projectActions": [
|
||||
{
|
||||
"id": "dev",
|
||||
"name": "Dev server",
|
||||
"command": "pnpm dev",
|
||||
"icon": "server",
|
||||
"url": "http://localhost:5173/{worktree}",
|
||||
"autoOpenUrl": true
|
||||
}
|
||||
],
|
||||
"setupWorktree": [
|
||||
"pnpm install"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `version` is required and must be `1`.
|
||||
- `projectActions` and `setupWorktree` are optional. Up to 50 actions and 20 setup commands are allowed.
|
||||
- A repository action whose `id` matches a personal action is ignored, and the dialog reports a warning, so personal actions always win.
|
||||
|
||||
## Moving Actions and Setup Commands
|
||||
|
||||
The Project Actions dialog moves items between personal settings and the repository file:
|
||||
|
||||
- **Move to repository** writes the item into `.ocm/project.json` and removes it from personal settings. Because the user authored it, the file is trusted automatically.
|
||||
- **Move to my settings** removes the item from `.ocm/project.json` (deleting the file if it becomes empty) and stores it in personal settings.
|
||||
|
||||
Moves are transactional: if the file write or the settings update fails, the file is restored.
|
||||
|
||||
## Trust
|
||||
|
||||
Commands in `.ocm/project.json` run on your machine, so the Manager does not run them until you trust the file:
|
||||
|
||||
- Trust is a hash of the file's **executable content only**: each action's `id`, `command` and `url`, plus the setup commands. Changing an action's name, icon, or `autoOpenUrl` does not affect trust; changing a command, URL, or setup command does.
|
||||
- Trusting requires echoing the exact hash shown, so a file cannot be swapped between review and trust.
|
||||
- Untrusted repository commands never run — not from the header menu, and not as worktree setup commands.
|
||||
- The dialog shows the untrusted commands and a **Trust these commands** button. Attempting to run an untrusted action prompts for trust first.
|
||||
- Moving an item into the file auto-trusts it, because the user authored it.
|
||||
|
||||
## Worktree Setup Commands
|
||||
|
||||
Setup commands run once after a new working directory is created — both Manager worktrees and OpenCode workspaces. They run in a PTY with `set -e`, so the first failing command stops the rest.
|
||||
|
||||
- `$ROOT_PROJECT_PATH` is available in the environment and points at the repository's main checkout.
|
||||
- Personal setup commands always run. Repository setup commands are skipped while the file is untrusted; the skipped result is reported.
|
||||
- Setup commands are configured in the **Worktree setup** section of the Project Actions dialog.
|
||||
|
||||
## Related
|
||||
|
||||
- [Terminal & Dev Loop](terminal.md) — the PTY terminals actions run in.
|
||||
- [Preview](preview.md) — open an action's URL in the preview panel.
|
||||
@@ -18,7 +18,7 @@ The microVM sees repositories through bind mounts at the same paths used by the
|
||||
| WebUI `!command` shell mode (`POST /api/session/:sessionID/shell`) | Yes; it spawns through the same `Shell.create` path as the `shell` tool, so it is planned and routed into the microVM. It is not badged in the UI because the surface fires no `tool.execute.after` hook |
|
||||
| Shell API (`POST /api/shell`) | Yes; it spawns through the same `Shell.create` path as the `shell` tool. It is not badged in the UI because the surface fires no `tool.execute.after` hook |
|
||||
| Slash-command shell templates (`` !`cmd` ``, `POST /api/session/:sessionID/command`) | No; OpenCode expands each interpolation itself with the configured shell, directly on the host and outside `Shell.create`, so the `create.before` hook never sees it |
|
||||
| PTY terminals (`POST /api/pty`, `POST /api/pty/:ptyID/connect`) | No; normal OpenCode behavior, with the user's configured shell |
|
||||
| PTY terminals (`POST /api/pty`, `POST /api/pty/:ptyID/connect`), including the Manager Terminal panel and project action terminals | No; normal OpenCode behavior, with the user's configured shell. Manager terminals and project actions receive the repo-scoped GitHub token and assigned commit identity env through `CredentialProvider.getShellEnv` at creation |
|
||||
| OpenCode file tools | No; while enforcement is on they are denied the global configuration directory (see [Mounts and Secrets](#mounts-and-secrets)) |
|
||||
| Manager-side git operations | No |
|
||||
| Plugins and custom tools | No; normal OpenCode behavior |
|
||||
@@ -49,7 +49,7 @@ Configured extensions execute with OpenCode's normal host-process privileges. Th
|
||||
|
||||
WebUI `!command` shell mode and the shell API (`POST /api/shell`) **are** sandboxed: both spawn through the same `Shell.create` path as the `shell` tool, so they are planned and routed into the microVM.
|
||||
|
||||
PTY terminals follow OpenCode's normal host-process behavior during enforcement and use the user's configured shell. Slash-command shell templates are not sandboxed either: when a command template contains a `` !`cmd` `` interpolation, OpenCode resolves the configured shell and runs the command directly on the host before the resulting prompt is sent, without going through `Shell.create` or its `create.before` hook. That interpolation is trusted configuration outside the agent `shell` isolation boundary.
|
||||
PTY terminals follow OpenCode's normal host-process behavior during enforcement and use the user's configured shell. This includes the Manager [Terminal panel](terminal.md) and [project actions](project-actions.md): they run as OpenCode PTYs on the host, receive the repo-scoped GitHub token and assigned commit identity env through `CredentialProvider.getShellEnv` at creation, and still bypass the sandbox shell hook. Slash-command shell templates are not sandboxed either: when a command template contains a `` !`cmd` `` interpolation, OpenCode resolves the configured shell and runs the command directly on the host before the resulting prompt is sent, without going through `Shell.create` or its `create.before` hook. That interpolation is trusted configuration outside the agent `shell` isolation boundary.
|
||||
|
||||
There is no fallback to a host shell in the `Shell.create` path: the shim refuses to run without a pinned sandbox working directory, so a spawn whose plan, shim, or lock is unavailable is refused instead of running on the host.
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Terminal & Dev Loop
|
||||
|
||||
Run interactive shells against a repository or workspace directory without leaving the WebUI.
|
||||
|
||||
## Opening a Terminal
|
||||
|
||||
Open the terminal from either surface:
|
||||
|
||||
- **Desktop sidebar** — click **Terminal** in the tool list for a repository or session.
|
||||
- **More drawer** — on mobile or from the overflow menu, open **More** and select **Terminal**.
|
||||
|
||||
The terminal panel opens as a dialog. If no terminal exists for the selected directory yet, the panel starts one automatically.
|
||||
|
||||
Terminals are scoped to the selected repository or OpenCode workspace directory. A terminal opened from a repo runs in that repo's path; a terminal opened from a session runs in the session's working directory. Switching directories shows that directory's terminals.
|
||||
|
||||
## Tabs and Reconnect
|
||||
|
||||
Each terminal runs in its own tab:
|
||||
|
||||
- Click **+** to create another terminal in the same directory.
|
||||
- Click a tab to focus it.
|
||||
- Click the **×** on a tab to close it. Closing a running terminal asks for confirmation, then stops the process.
|
||||
- An exited terminal keeps its tab and shows `exited` with its exit code.
|
||||
|
||||
Terminals are backed by OpenCode PTYs, so they survive a browser close or reload: reopening the panel reattaches and replays the buffered output. They do **not** survive an OpenCode restart, which ends every PTY.
|
||||
|
||||
## Mobile Key Bar
|
||||
|
||||
On mobile, the panel shows a key bar above the keyboard with keys that are awkward to reach on a soft keyboard:
|
||||
|
||||
- **Esc**, **Tab**
|
||||
- **Ctrl** — tap to arm, then tap a key to send the modified combination; arming is consumed by the next key.
|
||||
- Arrow keys
|
||||
- `|`, `~`, `/`
|
||||
|
||||
## Runtime and Environment
|
||||
|
||||
Terminals run as OpenCode PTYs on the host, using the user's configured shell. They are **not sandboxed**: sandbox enforcement applies to agent `shell` tool calls, not to PTY terminals (see [Agent Sandboxing](sandboxing.md)).
|
||||
|
||||
Each terminal receives environment resolved for its directory:
|
||||
|
||||
- the repository's GitHub token environment, so `git` and `gh` authenticate as the repo's credentials;
|
||||
- the assigned git commit identity, so commits made in the terminal use the repo's configured author.
|
||||
|
||||
## Related
|
||||
|
||||
- [Project Actions](project-actions.md) — run and stop long-lived commands as terminals from the header menu.
|
||||
- [Preview](preview.md) — open a dev server started in a terminal.
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { CreatePreviewSessionResponse, PreviewPortsResponse } from '@opencode-manager/shared/types'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
|
||||
function directoryQuery(directory: string | undefined): string {
|
||||
return directory ? `?${new URLSearchParams({ directory }).toString()}` : ''
|
||||
}
|
||||
|
||||
export function previewPortsQueryKey(directory: string | undefined) {
|
||||
return ['previewPorts', directory ?? null] as const
|
||||
}
|
||||
|
||||
export function listPreviewPorts(directory?: string): Promise<PreviewPortsResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/preview/ports${directoryQuery(directory)}`)
|
||||
}
|
||||
|
||||
export function createPreviewSession(port: number): Promise<CreatePreviewSessionResponse> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/preview/sessions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ port }),
|
||||
})
|
||||
}
|
||||
|
||||
export interface UsePreviewPortsOptions {
|
||||
enabled: boolean
|
||||
refetchInterval?: number | false
|
||||
}
|
||||
|
||||
export function usePreviewPorts(directory: string | undefined, options: UsePreviewPortsOptions) {
|
||||
return useQuery({
|
||||
queryKey: previewPortsQueryKey(directory),
|
||||
queryFn: () => listPreviewPorts(directory),
|
||||
enabled: options.enabled,
|
||||
refetchInterval: options.refetchInterval,
|
||||
})
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import type { Repo } from './types'
|
||||
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { saveFile } from '@/lib/download'
|
||||
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest } from '@opencode-manager/shared/types'
|
||||
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, WorktreeSetupResult } from '@opencode-manager/shared/types'
|
||||
|
||||
export interface CreateRepoOptions {
|
||||
repoUrl?: string
|
||||
@@ -63,7 +63,7 @@ export async function deleteRepoWorkspace(repoId: number, directory: string): Pr
|
||||
})
|
||||
}
|
||||
|
||||
export async function createRepoWorkspace(repoId: number): Promise<RepoWorktree> {
|
||||
export async function createRepoWorkspace(repoId: number): Promise<RepoWorktree & { worktreeSetup?: WorktreeSetupResult }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import type { SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
import type { WorktreeSetupResult } from '@opencode-manager/shared/types'
|
||||
|
||||
export interface Repo {
|
||||
id: number
|
||||
name?: string
|
||||
@@ -15,10 +18,9 @@ export interface Repo {
|
||||
gitCredentialId?: string
|
||||
isWorktree?: boolean
|
||||
isLocal?: boolean
|
||||
worktreeSetup?: WorktreeSetupResult
|
||||
}
|
||||
|
||||
import type { SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
|
||||
export type Session = SessionInfo
|
||||
export type PermissionResponse = 'once' | 'always' | 'reject'
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ describe('buildMoreItems', () => {
|
||||
|
||||
it('returns repo-specific items for /repos/:id', () => {
|
||||
const items = buildMoreItems('/repos/42')
|
||||
expect(items).toHaveLength(11)
|
||||
expect(items).toHaveLength(12)
|
||||
expect(items[0].key).toBe('home')
|
||||
expect(items[1].key).toBe('files')
|
||||
expect(items[1].dialog).toBe('files')
|
||||
@@ -33,13 +33,15 @@ describe('buildMoreItems', () => {
|
||||
expect(items[7].dialog).toBe('terminal')
|
||||
expect(items[8].key).toBe('actions')
|
||||
expect(items[8].dialog).toBe('actions')
|
||||
expect(items[9].key).toBe('settings')
|
||||
expect(items[10].key).toBe('logout')
|
||||
expect(items[9].key).toBe('preview')
|
||||
expect(items[9].dialog).toBe('preview')
|
||||
expect(items[10].key).toBe('settings')
|
||||
expect(items[11].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns session-specific items for /repos/:id/sessions/:sid', () => {
|
||||
const items = buildMoreItems('/repos/42/sessions/abc')
|
||||
expect(items).toHaveLength(11)
|
||||
expect(items).toHaveLength(12)
|
||||
expect(items[0].key).toBe('home')
|
||||
expect(items[1].key).toBe('files')
|
||||
expect(items[2].key).toBe('mcp')
|
||||
@@ -52,8 +54,10 @@ describe('buildMoreItems', () => {
|
||||
expect(items[7].dialog).toBe('terminal')
|
||||
expect(items[8].key).toBe('actions')
|
||||
expect(items[8].dialog).toBe('actions')
|
||||
expect(items[9].key).toBe('settings')
|
||||
expect(items[10].key).toBe('logout')
|
||||
expect(items[9].key).toBe('preview')
|
||||
expect(items[9].dialog).toBe('preview')
|
||||
expect(items[10].key).toBe('settings')
|
||||
expect(items[11].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns assistant workspace items for /repos/:id/assistant', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play } from 'lucide-react'
|
||||
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react'
|
||||
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
|
||||
|
||||
export interface MoreDrawerItem {
|
||||
@@ -60,6 +60,7 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' },
|
||||
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
|
||||
...baseItems,
|
||||
]
|
||||
|
||||
@@ -80,6 +81,7 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' },
|
||||
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },
|
||||
...baseItems,
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types'
|
||||
import { createPreviewSession, usePreviewPorts } from '@/api/preview'
|
||||
import { PreviewPanel } from './PreviewPanel'
|
||||
|
||||
vi.mock('@/api/preview', () => ({
|
||||
usePreviewPorts: vi.fn(),
|
||||
createPreviewSession: vi.fn(),
|
||||
}))
|
||||
|
||||
type PreviewPortsResult = ReturnType<typeof usePreviewPorts>
|
||||
|
||||
const portsData = {
|
||||
enabled: true,
|
||||
ports: [{ port: 5173, host: '127.0.0.1' as const, pid: 10, command: 'vite', cwd: '/repo' }],
|
||||
}
|
||||
|
||||
let portsState: PreviewPortsResult['data'] = portsData
|
||||
|
||||
const DEFAULT_ENTRY = '/repos/1?dialog=preview&previewPort=5173'
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason?: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
function panelElement(initialEntry: string) {
|
||||
return (
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<PreviewPanel isOpen onClose={vi.fn()} directory="/repo" />
|
||||
</MemoryRouter>
|
||||
)
|
||||
}
|
||||
|
||||
function renderPanel(initialEntry = DEFAULT_ENTRY) {
|
||||
const result = render(panelElement(initialEntry))
|
||||
return {
|
||||
...result,
|
||||
refresh: () => result.rerender(panelElement(initialEntry)),
|
||||
}
|
||||
}
|
||||
|
||||
describe('PreviewPanel', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
portsState = portsData
|
||||
vi.mocked(usePreviewPorts).mockImplementation(
|
||||
() =>
|
||||
({
|
||||
data: portsState,
|
||||
isLoading: false,
|
||||
refetch: vi.fn(),
|
||||
}) as unknown as PreviewPortsResult,
|
||||
)
|
||||
vi.mocked(createPreviewSession).mockResolvedValue({ token: 'tok', previewPort: 5004, publicUrl: null })
|
||||
})
|
||||
|
||||
it('renders the iframe with the start URL and sandbox for a listed port', async () => {
|
||||
renderPanel()
|
||||
|
||||
const iframe = await screen.findByTitle('Preview')
|
||||
expect(iframe).toHaveAttribute('src', 'http://localhost:5004/__ocm_preview/start?token=tok&path=%2F')
|
||||
expect(iframe.getAttribute('sandbox')).toContain('allow-scripts')
|
||||
expect(iframe.getAttribute('sandbox')).toContain('allow-same-origin')
|
||||
})
|
||||
|
||||
it('creates a session and renders the iframe when a port is selected', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderPanel('/repos/1?dialog=preview')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /:5173/ }))
|
||||
|
||||
const iframe = await screen.findByTitle('Preview')
|
||||
expect(iframe).toHaveAttribute('src', 'http://localhost:5004/__ocm_preview/start?token=tok&path=%2F')
|
||||
expect(createPreviewSession).toHaveBeenCalledWith(5173)
|
||||
})
|
||||
|
||||
it('refuses to render an iframe when the preview origin is the manager origin', async () => {
|
||||
vi.mocked(createPreviewSession).mockResolvedValue({
|
||||
token: 'tok',
|
||||
previewPort: 5004,
|
||||
publicUrl: 'http://localhost',
|
||||
})
|
||||
renderPanel()
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/different origin/i)
|
||||
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows a waiting state for a port that is not listening', () => {
|
||||
renderPanel('/repos/1?dialog=preview&previewPort=6000')
|
||||
|
||||
expect(screen.getByText(/Waiting for port 6000/)).toBeInTheDocument()
|
||||
expect(createPreviewSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('renders the disabled state', () => {
|
||||
portsState = { enabled: false, ports: [] }
|
||||
renderPanel('/repos/1?dialog=preview')
|
||||
|
||||
expect(screen.getByText(/Preview is disabled/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('badges ports that run inside the directory', () => {
|
||||
renderPanel('/repos/1?dialog=preview')
|
||||
|
||||
expect(screen.getByText('this repo')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('mints a fresh session when a listed port disappears and comes back', async () => {
|
||||
const first = deferred<CreatePreviewSessionResponse>()
|
||||
const second = deferred<CreatePreviewSessionResponse>()
|
||||
vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
|
||||
|
||||
const panel = renderPanel()
|
||||
|
||||
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
|
||||
expect((await screen.findByTitle('Preview')).getAttribute('src')).toContain('token=tok-1')
|
||||
|
||||
portsState = { enabled: true, ports: [] }
|
||||
panel.refresh()
|
||||
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
|
||||
expect(screen.getByText(/Waiting for port 5173/)).toBeInTheDocument()
|
||||
|
||||
portsState = portsData
|
||||
panel.refresh()
|
||||
second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null })
|
||||
|
||||
expect((await screen.findByTitle('Preview')).getAttribute('src')).toContain('token=tok-2')
|
||||
expect(createPreviewSession).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('does not render the old token while a same-port path change is pending', async () => {
|
||||
const user = userEvent.setup()
|
||||
const first = deferred<CreatePreviewSessionResponse>()
|
||||
const second = deferred<CreatePreviewSessionResponse>()
|
||||
vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
|
||||
|
||||
renderPanel('/repos/1?dialog=preview&previewPort=5173&previewPath=%2F')
|
||||
|
||||
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
|
||||
expect(await screen.findByTitle('Preview')).toBeInTheDocument()
|
||||
|
||||
const pathInput = screen.getByLabelText('Preview path')
|
||||
await user.clear(pathInput)
|
||||
await user.type(pathInput, '/foo')
|
||||
await user.click(screen.getByRole('button', { name: 'Go' }))
|
||||
|
||||
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
|
||||
|
||||
second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null })
|
||||
const iframe = await screen.findByTitle('Preview')
|
||||
expect(iframe.getAttribute('src')).toContain('token=tok-2')
|
||||
expect(iframe.getAttribute('src')).toContain('path=%2Ffoo')
|
||||
})
|
||||
|
||||
it('does not replay the old token while a reload is pending', async () => {
|
||||
const user = userEvent.setup()
|
||||
const first = deferred<CreatePreviewSessionResponse>()
|
||||
const second = deferred<CreatePreviewSessionResponse>()
|
||||
vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
|
||||
|
||||
renderPanel()
|
||||
|
||||
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
|
||||
expect(await screen.findByTitle('Preview')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reload preview' }))
|
||||
|
||||
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
|
||||
|
||||
second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null })
|
||||
expect((await screen.findByTitle('Preview')).getAttribute('src')).toContain('token=tok-2')
|
||||
})
|
||||
|
||||
it('keeps the newest session when responses resolve out of order for the same port', async () => {
|
||||
const user = userEvent.setup()
|
||||
const first = deferred<CreatePreviewSessionResponse>()
|
||||
const second = deferred<CreatePreviewSessionResponse>()
|
||||
const third = deferred<CreatePreviewSessionResponse>()
|
||||
vi.mocked(createPreviewSession)
|
||||
.mockReturnValueOnce(first.promise)
|
||||
.mockReturnValueOnce(second.promise)
|
||||
.mockReturnValueOnce(third.promise)
|
||||
|
||||
renderPanel()
|
||||
|
||||
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
|
||||
await screen.findByTitle('Preview')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reload preview' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Reload preview' }))
|
||||
|
||||
third.resolve({ token: 'tok-3', previewPort: 5004, publicUrl: null })
|
||||
second.resolve({ token: 'tok-2', previewPort: 5004, publicUrl: null })
|
||||
|
||||
const iframe = await screen.findByTitle('Preview')
|
||||
expect(iframe.getAttribute('src')).toContain('token=tok-3')
|
||||
expect(iframe.getAttribute('src')).not.toContain('token=tok-2')
|
||||
})
|
||||
|
||||
it('does not mint extra sessions when the port list refetches unchanged', async () => {
|
||||
const first = deferred<CreatePreviewSessionResponse>()
|
||||
vi.mocked(createPreviewSession).mockReturnValueOnce(first.promise)
|
||||
|
||||
const panel = renderPanel()
|
||||
|
||||
first.resolve({ token: 'tok-1', previewPort: 5004, publicUrl: null })
|
||||
await screen.findByTitle('Preview')
|
||||
|
||||
panel.refresh()
|
||||
panel.refresh()
|
||||
|
||||
expect(createPreviewSession).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,353 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types'
|
||||
import { ExternalLink, Globe, Loader2, Monitor, RefreshCw, Smartphone, Tablet, X } from 'lucide-react'
|
||||
import { createPreviewSession, usePreviewPorts } from '@/api/preview'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { buildPreviewStartUrl, getPreviewOrigin, isSameOriginAsManager } from '@/lib/preview-url'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface PreviewPanelProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
directory: string | undefined
|
||||
}
|
||||
|
||||
type ViewportPreset = 'mobile' | 'tablet' | 'full'
|
||||
|
||||
const VIEWPORT_WIDTHS: Record<ViewportPreset, number | null> = {
|
||||
mobile: 390,
|
||||
tablet: 820,
|
||||
full: null,
|
||||
}
|
||||
|
||||
const VIEWPORT_PRESETS: Array<{ preset: ViewportPreset; label: string; icon: typeof Monitor }> = [
|
||||
{ preset: 'mobile', label: 'Mobile viewport', icon: Smartphone },
|
||||
{ preset: 'tablet', label: 'Tablet viewport', icon: Tablet },
|
||||
{ preset: 'full', label: 'Full width viewport', icon: Monitor },
|
||||
]
|
||||
|
||||
const PORT_WAIT_TIMEOUT_MS = 60_000
|
||||
|
||||
interface ActiveSession {
|
||||
targetPort: number
|
||||
path: string
|
||||
renderKey: number
|
||||
data: CreatePreviewSessionResponse
|
||||
}
|
||||
|
||||
function isInsideDirectory(cwd: string | null, directory: string | undefined): boolean {
|
||||
if (!cwd || !directory) return false
|
||||
if (cwd === directory) return true
|
||||
const prefix = directory.endsWith('/') ? directory : `${directory}/`
|
||||
return cwd.startsWith(prefix)
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
return error instanceof Error ? error.message : fallback
|
||||
}
|
||||
|
||||
export function PreviewPanel({ isOpen, onClose, directory }: PreviewPanelProps) {
|
||||
const isMobile = useMobile()
|
||||
const { searchParams, updateParams } = useUrlParams()
|
||||
|
||||
const requestedPort = useMemo(() => {
|
||||
const raw = searchParams.get('previewPort')
|
||||
if (!raw) return undefined
|
||||
const port = Number(raw)
|
||||
return Number.isInteger(port) && port > 0 && port <= 65535 ? port : undefined
|
||||
}, [searchParams])
|
||||
const requestedPath = searchParams.get('previewPath') || '/'
|
||||
|
||||
const [pathDraft, setPathDraft] = useState(requestedPath)
|
||||
const [viewport, setViewport] = useState<ViewportPreset>('full')
|
||||
const [session, setSession] = useState<ActiveSession | null>(null)
|
||||
const [sessionError, setSessionError] = useState<string | null>(null)
|
||||
const [waitExpired, setWaitExpired] = useState(false)
|
||||
const [retryNonce, setRetryNonce] = useState(0)
|
||||
const sessionPortRef = useRef<number | null>(null)
|
||||
const activePathRef = useRef<string | null>(null)
|
||||
const requestIdRef = useRef(0)
|
||||
|
||||
const portsQuery = usePreviewPorts(directory, {
|
||||
enabled: isOpen,
|
||||
refetchInterval: isOpen ? 2000 : false,
|
||||
})
|
||||
const ports = useMemo(() => portsQuery.data?.ports ?? [], [portsQuery.data])
|
||||
const enabled = portsQuery.data?.enabled ?? true
|
||||
const portListed = requestedPort !== undefined && ports.some((entry) => entry.port === requestedPort)
|
||||
|
||||
useEffect(() => {
|
||||
setPathDraft(requestedPath)
|
||||
}, [requestedPath])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
requestIdRef.current += 1
|
||||
sessionPortRef.current = null
|
||||
activePathRef.current = null
|
||||
setSession(null)
|
||||
setSessionError(null)
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (portListed) return
|
||||
requestIdRef.current += 1
|
||||
sessionPortRef.current = null
|
||||
activePathRef.current = null
|
||||
setSession(null)
|
||||
}, [portListed])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !requestedPort || !enabled || portListed) {
|
||||
setWaitExpired(false)
|
||||
return
|
||||
}
|
||||
setWaitExpired(false)
|
||||
const timer = setTimeout(() => setWaitExpired(true), PORT_WAIT_TIMEOUT_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [isOpen, requestedPort, enabled, portListed, retryNonce])
|
||||
|
||||
const startSession = useCallback((port: number, path: string) => {
|
||||
const requestId = requestIdRef.current + 1
|
||||
requestIdRef.current = requestId
|
||||
sessionPortRef.current = port
|
||||
activePathRef.current = path
|
||||
setSessionError(null)
|
||||
setSession(null)
|
||||
return createPreviewSession(port)
|
||||
.then((data) => {
|
||||
if (requestIdRef.current !== requestId) return
|
||||
setSession({ targetPort: port, path, renderKey: requestId, data })
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (requestIdRef.current !== requestId) return
|
||||
sessionPortRef.current = null
|
||||
activePathRef.current = null
|
||||
setSessionError(errorMessage(error, 'Failed to start preview'))
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !requestedPort || !enabled || !portListed) return
|
||||
if (sessionPortRef.current === requestedPort && activePathRef.current === requestedPath) return
|
||||
void startSession(requestedPort, requestedPath)
|
||||
}, [isOpen, requestedPort, requestedPath, enabled, portListed, startSession])
|
||||
|
||||
const selectPort = useCallback((port: number) => {
|
||||
updateParams((params) => {
|
||||
params.set('previewPort', String(port))
|
||||
params.delete('previewPath')
|
||||
}, 'replace')
|
||||
}, [updateParams])
|
||||
|
||||
const reload = useCallback(() => {
|
||||
if (!requestedPort) return
|
||||
void startSession(requestedPort, requestedPath)
|
||||
}, [requestedPort, requestedPath, startSession])
|
||||
|
||||
const handleGo = useCallback(() => {
|
||||
const nextPath = pathDraft.trim() || '/'
|
||||
updateParams((params) => {
|
||||
params.set('previewPath', nextPath)
|
||||
}, 'replace')
|
||||
if (requestedPort) {
|
||||
void startSession(requestedPort, nextPath)
|
||||
}
|
||||
}, [pathDraft, requestedPort, updateParams, startSession])
|
||||
|
||||
const handleOpenInNewTab = useCallback(() => {
|
||||
if (!requestedPort) return
|
||||
createPreviewSession(requestedPort)
|
||||
.then((data) => {
|
||||
window.open(buildPreviewStartUrl(data, requestedPath), '_blank', 'noopener,noreferrer')
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
setSessionError(errorMessage(error, 'Failed to open preview'))
|
||||
})
|
||||
}, [requestedPort, requestedPath])
|
||||
|
||||
const retry = useCallback(() => {
|
||||
if (portListed && requestedPort) {
|
||||
void startSession(requestedPort, requestedPath)
|
||||
return
|
||||
}
|
||||
setWaitExpired(false)
|
||||
setRetryNonce((nonce) => nonce + 1)
|
||||
void portsQuery.refetch()
|
||||
}, [portListed, requestedPort, requestedPath, startSession, portsQuery])
|
||||
|
||||
const activeSession = session && session.targetPort === requestedPort ? session : null
|
||||
const previewOrigin = activeSession ? getPreviewOrigin(activeSession.data) : null
|
||||
const sameOrigin = previewOrigin ? isSameOriginAsManager(previewOrigin) : false
|
||||
const viewportWidth = VIEWPORT_WIDTHS[viewport]
|
||||
|
||||
const renderMessage = (message: ReactNode, options: { retry?: boolean; alert?: boolean } = {}) => (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center text-sm text-muted-foreground">
|
||||
<div role={options.alert ? 'alert' : undefined} className="flex items-center gap-2">
|
||||
{message}
|
||||
</div>
|
||||
{options.retry && (
|
||||
<Button size="sm" variant="outline" onClick={retry}>
|
||||
Retry
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
const body = () => {
|
||||
if (!enabled) {
|
||||
return renderMessage('Preview is disabled (PREVIEW_PORT=0)')
|
||||
}
|
||||
if (!requestedPort) {
|
||||
return renderMessage('Select a port to preview')
|
||||
}
|
||||
if (!portListed) {
|
||||
if (waitExpired) {
|
||||
return renderMessage(`Port ${requestedPort} is not listening`, { retry: true, alert: true })
|
||||
}
|
||||
return renderMessage(
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Waiting for port {requestedPort}…
|
||||
</>,
|
||||
)
|
||||
}
|
||||
if (sessionError) {
|
||||
return renderMessage(sessionError, { retry: true, alert: true })
|
||||
}
|
||||
if (activeSession) {
|
||||
if (sameOrigin) {
|
||||
return renderMessage('Preview must run on a different origin than OpenCode Manager.', { alert: true })
|
||||
}
|
||||
return (
|
||||
<div className="flex h-full justify-center overflow-hidden">
|
||||
<iframe
|
||||
key={activeSession.renderKey}
|
||||
title="Preview"
|
||||
src={buildPreviewStartUrl(activeSession.data, activeSession.path)}
|
||||
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads"
|
||||
className="h-full border-0 bg-white"
|
||||
style={{ width: viewportWidth ?? '100%', maxWidth: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return renderMessage(
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Starting preview…
|
||||
</>,
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose() }}>
|
||||
<DialogContent
|
||||
mobileFullscreen
|
||||
hideCloseButton={isMobile}
|
||||
className={cn(
|
||||
'p-0 flex flex-col bg-card border-border gap-0',
|
||||
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh] sm:pb-0',
|
||||
)}
|
||||
>
|
||||
<DialogHeader className={cn('px-4 py-2 border-b border-border flex-shrink-0', isMobile && 'relative')}>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Globe className="w-5 h-5" />
|
||||
Preview
|
||||
</DialogTitle>
|
||||
{isMobile && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
aria-label="Close preview panel"
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 h-10 w-10 p-0"
|
||||
>
|
||||
<X className="h-6 w-6" />
|
||||
</Button>
|
||||
)}
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex items-center gap-2 border-b border-border px-3 py-2 flex-shrink-0">
|
||||
<input
|
||||
aria-label="Preview path"
|
||||
value={pathDraft}
|
||||
onChange={(event) => setPathDraft(event.target.value)}
|
||||
onKeyDown={(event) => { if (event.key === 'Enter') handleGo() }}
|
||||
className="h-8 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-sm"
|
||||
placeholder="/"
|
||||
/>
|
||||
<Button size="sm" variant="outline" onClick={handleGo} disabled={!requestedPort}>
|
||||
Go
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={reload}
|
||||
disabled={!requestedPort}
|
||||
aria-label="Reload preview"
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={handleOpenInNewTab}
|
||||
disabled={!requestedPort}
|
||||
aria-label="Open preview in new tab"
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
{VIEWPORT_PRESETS.map(({ preset, label, icon: Icon }) => (
|
||||
<Button
|
||||
key={preset}
|
||||
size="sm"
|
||||
variant={viewport === preset ? 'secondary' : 'ghost'}
|
||||
onClick={() => setViewport(preset)}
|
||||
aria-label={label}
|
||||
aria-pressed={viewport === preset}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{enabled && ports.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1 border-b border-border px-3 py-2 flex-shrink-0">
|
||||
{ports.map((entry) => (
|
||||
<button
|
||||
key={entry.port}
|
||||
type="button"
|
||||
onClick={() => selectPort(entry.port)}
|
||||
title={entry.cwd ?? undefined}
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors',
|
||||
entry.port === requestedPort
|
||||
? 'border-primary text-foreground'
|
||||
: 'border-border text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<span className="font-medium">:{entry.port}</span>
|
||||
{entry.command && <span className="truncate">{entry.command}</span>}
|
||||
{isInsideDirectory(entry.cwd, directory) && (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 text-[10px]">this repo</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative flex-1 min-h-0">{body()}</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { Repo } from '@/api/types'
|
||||
import { CreateWorktreeDialog } from './CreateWorktreeDialog'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createRepo: vi.fn(),
|
||||
listBranches: vi.fn(),
|
||||
navigate: vi.fn(),
|
||||
showToastSuccess: vi.fn(),
|
||||
showToastInfo: vi.fn(),
|
||||
showToastWarning: vi.fn(),
|
||||
invalidateRepoGitCaches: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
createRepo: mocks.createRepo,
|
||||
listBranches: mocks.listBranches,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
success: mocks.showToastSuccess,
|
||||
info: mocks.showToastInfo,
|
||||
warning: mocks.showToastWarning,
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/queryInvalidation', () => ({
|
||||
invalidateRepoGitCaches: mocks.invalidateRepoGitCaches,
|
||||
}))
|
||||
|
||||
vi.mock('react-router-dom', async () => {
|
||||
const actual = await vi.importActual('react-router-dom')
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => mocks.navigate,
|
||||
}
|
||||
})
|
||||
|
||||
function createWorktreeRepo(overrides: Partial<Repo> = {}): Repo {
|
||||
return {
|
||||
id: 42,
|
||||
localPath: 'repos/feature-x',
|
||||
fullPath: '/tmp/repos/feature-x',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 1,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function renderDialog() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CreateWorktreeDialog
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
repoId={1}
|
||||
repoUrl="https://github.com/test/repo"
|
||||
defaultBaseBranch="main"
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
async function submitCreate() {
|
||||
const user = userEvent.setup()
|
||||
await user.type(screen.getByPlaceholderText('feature/my-branch'), 'feature/x')
|
||||
await user.click(screen.getByRole('button', { name: 'Create Worktree' }))
|
||||
}
|
||||
|
||||
describe('CreateWorktreeDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.listBranches.mockResolvedValue({
|
||||
branches: [{ name: 'main', type: 'local', current: true }],
|
||||
status: { ahead: 0, behind: 0 },
|
||||
})
|
||||
})
|
||||
|
||||
it('navigates to the setup terminal when the worktree setup starts', async () => {
|
||||
mocks.createRepo.mockResolvedValue(
|
||||
createWorktreeRepo({
|
||||
worktreeSetup: {
|
||||
status: 'started',
|
||||
terminal: {
|
||||
id: 'pty-1',
|
||||
title: 'Worktree setup',
|
||||
kind: 'setup',
|
||||
cwd: '/tmp/repos/feature-x',
|
||||
status: 'running',
|
||||
},
|
||||
repoCommandsSkipped: false,
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
renderDialog()
|
||||
await submitCreate()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.navigate).toHaveBeenCalledWith('/repos/42?dialog=terminal&terminal=pty-1'),
|
||||
)
|
||||
})
|
||||
|
||||
it('warns without navigating when the worktree setup fails', async () => {
|
||||
mocks.createRepo.mockResolvedValue(
|
||||
createWorktreeRepo({ worktreeSetup: { status: 'failed', error: 'spawn failed' } }),
|
||||
)
|
||||
|
||||
renderDialog()
|
||||
await submitCreate()
|
||||
|
||||
await waitFor(() => expect(mocks.showToastWarning).toHaveBeenCalled())
|
||||
expect(mocks.navigate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('informs about skipped repository commands when the setup is skipped', async () => {
|
||||
mocks.createRepo.mockResolvedValue(
|
||||
createWorktreeRepo({ worktreeSetup: { status: 'skipped', reason: 'untrusted' } }),
|
||||
)
|
||||
|
||||
renderDialog()
|
||||
await submitCreate()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.showToastInfo).toHaveBeenCalledWith(
|
||||
'Repository setup commands were skipped until trusted in Actions',
|
||||
),
|
||||
)
|
||||
expect(mocks.navigate).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -7,6 +8,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { AlertCircle, GitBranch, Loader2 } from 'lucide-react'
|
||||
import { createRepo, listBranches } from '@/api/repos'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { notifyWorktreeSetup } from '@/lib/worktreeSetup'
|
||||
import { invalidateRepoGitCaches } from '@/lib/queryInvalidation'
|
||||
|
||||
interface CreateWorktreeDialogProps {
|
||||
@@ -27,6 +29,7 @@ export function CreateWorktreeDialog({
|
||||
onCreated,
|
||||
}: CreateWorktreeDialogProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
const [branchName, setBranchName] = useState('')
|
||||
const [baseBranch, setBaseBranch] = useState<string>('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -66,11 +69,15 @@ export function CreateWorktreeDialog({
|
||||
useWorktree: true,
|
||||
baseBranch: payload.base,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
onSuccess: (repo) => {
|
||||
invalidateRepoGitCaches(queryClient, repoId)
|
||||
showToast.success('Worktree created')
|
||||
onCreated?.()
|
||||
onOpenChange(false)
|
||||
notifyWorktreeSetup(repo.worktreeSetup)
|
||||
if (repo.worktreeSetup?.status === 'started') {
|
||||
navigate(`/repos/${repo.id}?dialog=terminal&terminal=${encodeURIComponent(repo.worktreeSetup.terminal.id)}`)
|
||||
}
|
||||
},
|
||||
onError: (err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create worktree')
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import type { TerminalInfo } from '@opencode-manager/shared/types'
|
||||
import type { ProjectConfigResponse } from '@opencode-manager/shared/types'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
import { LocationCatcher } from '@/test/test-utils'
|
||||
import { ProjectActionsMenu } from './ProjectActionsMenu'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useProjectConfig: vi.fn(),
|
||||
useTerminals: vi.fn(),
|
||||
getProjectConfig: vi.fn(),
|
||||
runMutate: vi.fn(),
|
||||
removeMutate: vi.fn(),
|
||||
trustMutate: vi.fn(),
|
||||
openUrlFromManager: vi.fn(),
|
||||
showToastError: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/projectConfig', () => ({
|
||||
getProjectConfig: mocks.getProjectConfig,
|
||||
useProjectConfig: mocks.useProjectConfig,
|
||||
useRunProjectAction: () => ({ mutate: mocks.runMutate, isPending: false }),
|
||||
useTrustRepoConfig: () => ({ mutate: mocks.trustMutate, isPending: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/terminals', () => ({
|
||||
useTerminals: mocks.useTerminals,
|
||||
useRemoveTerminal: () => ({ mutate: mocks.removeMutate, isPending: false }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/open-url', () => ({
|
||||
openUrlFromManager: mocks.openUrlFromManager,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { error: mocks.showToastError, success: vi.fn() },
|
||||
}))
|
||||
|
||||
const HASH = 'a'.repeat(64)
|
||||
const OTHER_HASH = 'b'.repeat(64)
|
||||
|
||||
const devAction: ProjectConfigResponse['actions'][number] = {
|
||||
id: 'dev',
|
||||
name: 'Dev server',
|
||||
command: 'pnpm dev',
|
||||
autoOpenUrl: false,
|
||||
source: 'personal',
|
||||
}
|
||||
|
||||
const repoAction: ProjectConfigResponse['actions'][number] = {
|
||||
...devAction,
|
||||
source: 'repo',
|
||||
}
|
||||
|
||||
const runningTerminal: TerminalInfo = {
|
||||
id: 'term-1',
|
||||
title: 'Dev server',
|
||||
kind: 'action',
|
||||
actionId: 'dev',
|
||||
cwd: '/repo',
|
||||
status: 'running',
|
||||
}
|
||||
|
||||
function makeConfig(
|
||||
actions: ProjectConfigResponse['actions'],
|
||||
hash: string | null = null,
|
||||
): ProjectConfigResponse {
|
||||
return {
|
||||
actions,
|
||||
worktreeSetup: [],
|
||||
repoFile: { path: '.ocm/project.json', exists: hash !== null, trusted: true, hash, warnings: [] },
|
||||
}
|
||||
}
|
||||
|
||||
function untrustedError(hash: string): FetchError {
|
||||
return new FetchError('Repository commands are not trusted', 409, 'REPO_CONFIG_UNTRUSTED', undefined, {
|
||||
details: { hash },
|
||||
})
|
||||
}
|
||||
|
||||
function menuTree(directory: string, capturedSearch: { current: string }) {
|
||||
return (
|
||||
<MemoryRouter initialEntries={['/repos/1']}>
|
||||
<LocationCatcher capturedSearch={capturedSearch} />
|
||||
<ProjectActionsMenu repoId={1} directory={directory} />
|
||||
</MemoryRouter>
|
||||
)
|
||||
}
|
||||
|
||||
function renderMenu(directory = '/repo') {
|
||||
const capturedSearch: { current: string } = { current: '' }
|
||||
const result = render(menuTree(directory, capturedSearch))
|
||||
return { ...result, capturedSearch }
|
||||
}
|
||||
|
||||
describe('ProjectActionsMenu', () => {
|
||||
beforeAll(() => {
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
Element.prototype.setPointerCapture ??= () => {}
|
||||
Element.prototype.releasePointerCapture ??= () => {}
|
||||
Element.prototype.scrollIntoView ??= () => {}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([devAction]), isLoading: false, error: null })
|
||||
mocks.useTerminals.mockReturnValue({ data: [] })
|
||||
mocks.getProjectConfig.mockResolvedValue(makeConfig([devAction]))
|
||||
})
|
||||
|
||||
it('opens the terminal panel on the run terminal when an action succeeds', async () => {
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => {
|
||||
options.onSuccess({ terminal: runningTerminal, alreadyRunning: false, autoOpenUrl: false })
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
const { capturedSearch } = renderMenu()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Project actions' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: /dev server/i }))
|
||||
|
||||
await waitFor(() => expect(capturedSearch.current).toContain('dialog=terminal'))
|
||||
expect(capturedSearch.current).toContain('terminal=term-1')
|
||||
})
|
||||
|
||||
it('shows a running dot and a Stop item that removes the running terminal', async () => {
|
||||
mocks.useTerminals.mockReturnValue({ data: [runningTerminal] })
|
||||
const user = userEvent.setup()
|
||||
renderMenu()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Project actions' }))
|
||||
|
||||
expect(await screen.findByTestId('action-running-dot')).toBeInTheDocument()
|
||||
await user.click(await screen.findByRole('menuitem', { name: /stop/i }))
|
||||
|
||||
expect(mocks.removeMutate).toHaveBeenCalledWith(
|
||||
{ ptyID: 'term-1', directory: '/repo' },
|
||||
expect.any(Object),
|
||||
)
|
||||
})
|
||||
|
||||
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))
|
||||
let runCalls = 0
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => {
|
||||
runCalls += 1
|
||||
if (runCalls === 1) {
|
||||
options.onError(untrustedError(HASH))
|
||||
return
|
||||
}
|
||||
options.onSuccess({ terminal: runningTerminal, alreadyRunning: false, autoOpenUrl: false })
|
||||
})
|
||||
mocks.trustMutate.mockImplementation((_vars, options) => options.onSuccess())
|
||||
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('pnpm dev')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: /trust and run/i }))
|
||||
|
||||
await waitFor(() => expect(mocks.runMutate).toHaveBeenCalledTimes(2))
|
||||
expect(mocks.trustMutate).toHaveBeenCalledWith(
|
||||
{ hash: HASH, directory: '/repo' },
|
||||
expect.any(Object),
|
||||
)
|
||||
})
|
||||
|
||||
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.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('pnpm dev')).toBeInTheDocument()
|
||||
expect(screen.queryByText('pnpm dev:stale')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
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.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('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.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('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.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
|
||||
const user = userEvent.setup()
|
||||
const capturedSearch: { current: string } = { current: '' }
|
||||
const { rerender } = render(menuTree('/repo', capturedSearch))
|
||||
|
||||
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()
|
||||
|
||||
rerender(menuTree('/other', capturedSearch))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText('Trust repository actions')).not.toBeInTheDocument(),
|
||||
)
|
||||
expect(mocks.trustMutate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
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.runMutate.mockImplementation((_actionId, options) => options.onError(untrustedError(HASH)))
|
||||
let trustOptions: { onSuccess: () => void } | undefined
|
||||
mocks.trustMutate.mockImplementation((_vars, options) => {
|
||||
trustOptions = options
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
const capturedSearch: { current: string } = { current: '' }
|
||||
const { rerender } = render(menuTree('/repo', capturedSearch))
|
||||
|
||||
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()
|
||||
await user.click(screen.getByRole('button', { name: /trust and run/i }))
|
||||
expect(mocks.runMutate).toHaveBeenCalledTimes(1)
|
||||
|
||||
rerender(menuTree('/other', capturedSearch))
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText('Trust repository actions')).not.toBeInTheDocument(),
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
trustOptions?.onSuccess()
|
||||
})
|
||||
expect(mocks.runMutate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('opens the resolved URL when the action opts into auto-open', async () => {
|
||||
mocks.runMutate.mockImplementation((_actionId, options) => {
|
||||
options.onSuccess({
|
||||
terminal: runningTerminal,
|
||||
alreadyRunning: false,
|
||||
resolvedUrl: 'http://localhost:3000',
|
||||
autoOpenUrl: true,
|
||||
})
|
||||
})
|
||||
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.openUrlFromManager).toHaveBeenCalledWith('http://localhost:3000', expect.any(Object)),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the empty state and manage entry when no actions are configured', async () => {
|
||||
mocks.useProjectConfig.mockReturnValue({ data: makeConfig([]), isLoading: false, error: null })
|
||||
const user = userEvent.setup()
|
||||
renderMenu()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Project actions' }))
|
||||
|
||||
expect(await screen.findByText('No actions configured')).toBeInTheDocument()
|
||||
expect(screen.getByRole('menuitem', { name: /manage actions/i })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,252 @@
|
||||
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { TerminalInfo } from '@opencode-manager/shared/types'
|
||||
import { FetchError } from '@opencode-manager/shared'
|
||||
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 {
|
||||
getProjectConfig,
|
||||
useProjectConfig,
|
||||
useRunProjectAction,
|
||||
useTrustRepoConfig,
|
||||
} from '@/api/projectConfig'
|
||||
import { useRemoveTerminal, useTerminals } from '@/api/terminals'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { openDialogParam } from '@/hooks/useDialogParam'
|
||||
import { useOpenPreview } from '@/hooks/useOpenPreview'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
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,
|
||||
}
|
||||
|
||||
interface ProjectActionsMenuProps {
|
||||
repoId: number
|
||||
directory: string | undefined
|
||||
}
|
||||
|
||||
interface PendingTrust {
|
||||
actionId: string
|
||||
hash: string
|
||||
directory: string
|
||||
command: string
|
||||
}
|
||||
|
||||
function untrustedHash(error: unknown): string | null {
|
||||
if (!(error instanceof FetchError) || error.code !== 'REPO_CONFIG_UNTRUSTED') return null
|
||||
const details = error.details
|
||||
if (details && typeof details === 'object' && typeof (details as { hash?: unknown }).hash === 'string') {
|
||||
return (details as { hash: string }).hash
|
||||
}
|
||||
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 configQuery = useProjectConfig(repoId, directory, menuOpen && !!directory)
|
||||
const terminalsQuery = useTerminals(repoId, directory, {
|
||||
enabled: menuOpen && !!directory,
|
||||
refetchInterval: menuOpen ? 5000 : false,
|
||||
})
|
||||
const runAction = useRunProjectAction(repoId, directory)
|
||||
const removeTerminal = useRemoveTerminal(repoId)
|
||||
const trustConfig = useTrustRepoConfig(repoId)
|
||||
const [pendingTrust, setPendingTrust] = useState<PendingTrust | null>(null)
|
||||
const scopeRef = useRef({ repoId, directory })
|
||||
|
||||
useEffect(() => {
|
||||
scopeRef.current = { repoId, directory }
|
||||
setPendingTrust(null)
|
||||
}, [repoId, directory])
|
||||
|
||||
const actions = useMemo<ProjectConfigResponse['actions']>(
|
||||
() => configQuery.data?.actions ?? [],
|
||||
[configQuery.data],
|
||||
)
|
||||
|
||||
const runningByAction = useMemo(() => {
|
||||
const map = new Map<string, TerminalInfo>()
|
||||
for (const terminal of terminalsQuery.data ?? []) {
|
||||
if (terminal.kind === 'action' && terminal.actionId && terminal.status === 'running') {
|
||||
map.set(terminal.actionId, terminal)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}, [terminalsQuery.data])
|
||||
|
||||
const handleRunSuccess = useCallback((result: RunProjectActionResponse) => {
|
||||
updateParams((params) => {
|
||||
params.set('dialog', 'terminal')
|
||||
params.set('terminal', result.terminal.id)
|
||||
params.delete('mobileTab')
|
||||
}, 'push')
|
||||
if (result.autoOpenUrl && result.resolvedUrl) {
|
||||
openUrlFromManager(result.resolvedUrl, { openPreview })
|
||||
}
|
||||
}, [updateParams, openPreview])
|
||||
|
||||
const requestTrustConfirmation = useCallback(async (actionId: string, hash: string) => {
|
||||
const requestDirectory = directory
|
||||
if (!requestDirectory) return
|
||||
let snapshot: ProjectConfigResponse
|
||||
try {
|
||||
snapshot = await getProjectConfig(repoId, requestDirectory)
|
||||
} catch (error) {
|
||||
showToast.error(errorMessage(error, 'Failed to verify repository actions'))
|
||||
return
|
||||
}
|
||||
const scope = scopeRef.current
|
||||
if (scope.repoId !== repoId || scope.directory !== requestDirectory) return
|
||||
const repoAction = snapshot.actions.find(
|
||||
(action) => action.id === actionId && action.source === 'repo',
|
||||
)
|
||||
if (snapshot.repoFile.hash !== hash || !repoAction) {
|
||||
showToast.error('Repository actions changed. Reopen the menu to review them.')
|
||||
return
|
||||
}
|
||||
setPendingTrust({ actionId, hash, directory: requestDirectory, command: repoAction.command })
|
||||
}, [directory, repoId])
|
||||
|
||||
const startRun = useCallback((actionId: string) => {
|
||||
runAction.mutate(actionId, {
|
||||
onSuccess: handleRunSuccess,
|
||||
onError: (error) => {
|
||||
const hash = untrustedHash(error)
|
||||
if (hash) {
|
||||
void requestTrustConfirmation(actionId, hash)
|
||||
return
|
||||
}
|
||||
showToast.error(errorMessage(error, 'Failed to run action'))
|
||||
},
|
||||
})
|
||||
}, [runAction, handleRunSuccess, requestTrustConfirmation])
|
||||
|
||||
const handleConfirmTrust = useCallback(() => {
|
||||
if (!pendingTrust) return
|
||||
const { actionId, hash, directory: trustDirectory } = pendingTrust
|
||||
const origin = { repoId, directory: trustDirectory }
|
||||
trustConfig.mutate({ hash, directory: trustDirectory }, {
|
||||
onSuccess: () => {
|
||||
const scope = scopeRef.current
|
||||
if (scope.repoId !== origin.repoId || scope.directory !== origin.directory) return
|
||||
setPendingTrust(null)
|
||||
startRun(actionId)
|
||||
},
|
||||
onError: (error) => showToast.error(errorMessage(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')),
|
||||
})
|
||||
}, [removeTerminal, directory])
|
||||
|
||||
const handleManage = useCallback(() => {
|
||||
openDialogParam(updateParams, 'actions')
|
||||
}, [updateParams])
|
||||
|
||||
if (!directory) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label="Project actions"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Play className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{actions.length === 0 ? (
|
||||
<DropdownMenuLabel className="font-normal text-muted-foreground">
|
||||
No actions configured
|
||||
</DropdownMenuLabel>
|
||||
) : (
|
||||
actions.map((action) => {
|
||||
const Icon = ACTION_ICONS[action.icon ?? 'play']
|
||||
const running = runningByAction.get(action.id)
|
||||
return (
|
||||
<Fragment key={action.id}>
|
||||
<DropdownMenuItem disabled={runAction.isPending} onSelect={() => startRun(action.id)}>
|
||||
<Icon className="mr-2 h-4 w-4" />
|
||||
<span className="truncate">{action.name}</span>
|
||||
{running && (
|
||||
<span
|
||||
data-testid="action-running-dot"
|
||||
className="ml-auto h-2 w-2 rounded-full bg-primary"
|
||||
/>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
{running && (
|
||||
<DropdownMenuItem onSelect={() => handleStop(running)}>
|
||||
<Square className="mr-2 h-4 w-4" />
|
||||
Stop
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</Fragment>
|
||||
)
|
||||
})
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onSelect={handleManage}>Manage actions…</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<ConfirmDestructiveDialog
|
||||
open={pendingTrust !== null}
|
||||
onOpenChange={(open) => { if (!open) setPendingTrust(null) }}
|
||||
onConfirm={handleConfirmTrust}
|
||||
onCancel={() => setPendingTrust(null)}
|
||||
title="Trust repository actions"
|
||||
description="This repository defines commands that run on your machine."
|
||||
warning={pendingTrust?.command}
|
||||
confirmLabel="Trust and run"
|
||||
pendingLabel="Trusting…"
|
||||
isPending={trustConfig.isPending}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import { Button } from '@/components/ui/button'
|
||||
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useOpenPreview } from '@/hooks/useOpenPreview'
|
||||
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'
|
||||
@@ -22,6 +24,7 @@ interface TerminalPanelProps {
|
||||
export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }: TerminalPanelProps) {
|
||||
const isMobile = useMobile()
|
||||
const { searchParams, updateParams } = useUrlParams()
|
||||
const openPreview = useOpenPreview()
|
||||
const { data, isLoading, isSuccess, refetch } = useTerminals(repoId, directory, {
|
||||
enabled: isOpen && !!directory,
|
||||
refetchInterval: isOpen ? 5000 : false,
|
||||
@@ -97,6 +100,10 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }
|
||||
const handleToggleCtrl = useCallback(() => setCtrlArmed((armed) => !armed), [])
|
||||
const handleCtrlConsumed = useCallback(() => setCtrlArmed(false), [])
|
||||
|
||||
const handleOpenLink = useCallback((uri: string) => {
|
||||
openUrlFromManager(uri, { openPreview })
|
||||
}, [openPreview])
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => { if (!open) onClose() }}>
|
||||
<DialogContent
|
||||
@@ -189,7 +196,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose, onOpenLink }
|
||||
active={terminal.id === activeTerminalId}
|
||||
ctrlArmed={ctrlArmed}
|
||||
onCtrlConsumed={handleCtrlConsumed}
|
||||
onOpenLink={onOpenLink}
|
||||
onOpenLink={onOpenLink ?? handleOpenLink}
|
||||
onExited={() => { void refetch() }}
|
||||
/>
|
||||
))
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useCallback } from 'react'
|
||||
import { useUrlParams } from './useUrlParams'
|
||||
|
||||
export function useOpenPreview(): (port: number, path?: string) => void {
|
||||
const { updateParams } = useUrlParams()
|
||||
|
||||
return useCallback(
|
||||
(port: number, path = '/') => {
|
||||
updateParams((params) => {
|
||||
params.set('dialog', 'preview')
|
||||
params.set('previewPort', String(port))
|
||||
params.set('previewPath', path)
|
||||
params.delete('mobileTab')
|
||||
}, 'push')
|
||||
},
|
||||
[updateParams],
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { openUrlFromManager } from './open-url'
|
||||
|
||||
describe('openUrlFromManager', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('opens an external URL in a new tab with noopener', () => {
|
||||
const open = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||
|
||||
openUrlFromManager('https://example.com/docs', {})
|
||||
|
||||
expect(open).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer')
|
||||
})
|
||||
|
||||
it('routes a local dev URL to the preview handler', () => {
|
||||
const open = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||
const openPreview = vi.fn()
|
||||
|
||||
openUrlFromManager('http://localhost:5173/app?x=1', { openPreview })
|
||||
|
||||
expect(openPreview).toHaveBeenCalledWith(5173, '/app?x=1')
|
||||
expect(open).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('falls back to a new tab for a local URL without a preview handler', () => {
|
||||
const open = vi.spyOn(window, 'open').mockImplementation(() => null)
|
||||
|
||||
openUrlFromManager('http://localhost:5173', {})
|
||||
|
||||
expect(open).toHaveBeenCalledWith('http://localhost:5173', '_blank', 'noopener,noreferrer')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
import { parseLocalDevUrl } from './preview-url'
|
||||
|
||||
export interface OpenUrlHandlers {
|
||||
openPreview?: (port: number, path: string) => void
|
||||
}
|
||||
|
||||
export function openUrlFromManager(url: string, handlers: OpenUrlHandlers): void {
|
||||
const localDevUrl = parseLocalDevUrl(url)
|
||||
if (localDevUrl && handlers.openPreview) {
|
||||
handlers.openPreview(localDevUrl.port, localDevUrl.path)
|
||||
return
|
||||
}
|
||||
window.open(url, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildPreviewStartUrl,
|
||||
getPreviewOrigin,
|
||||
isSameOriginAsManager,
|
||||
parseLocalDevUrl,
|
||||
} from './preview-url'
|
||||
|
||||
const managerLocation = {
|
||||
protocol: 'http:',
|
||||
hostname: 'manager.local',
|
||||
origin: 'http://manager.local:5003',
|
||||
} as Location
|
||||
|
||||
describe('parseLocalDevUrl', () => {
|
||||
it.each([
|
||||
['http://localhost:5173', 5173, '/'],
|
||||
['http://localhost:5173/app?x=1#top', 5173, '/app?x=1#top'],
|
||||
['https://127.0.0.1:3000/', 3000, '/'],
|
||||
['http://0.0.0.0:8080/foo', 8080, '/foo'],
|
||||
['http://[::1]:4000/bar', 4000, '/bar'],
|
||||
])('parses %s', (url, port, path) => {
|
||||
expect(parseLocalDevUrl(url)).toEqual({ port, path })
|
||||
})
|
||||
|
||||
it.each([
|
||||
'http://example.com:5173',
|
||||
'http://localhost',
|
||||
'ftp://localhost:5173',
|
||||
'not a url',
|
||||
])('rejects %s', (url) => {
|
||||
expect(parseLocalDevUrl(url)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getPreviewOrigin', () => {
|
||||
it('uses the public URL origin when set', () => {
|
||||
expect(
|
||||
getPreviewOrigin({ previewPort: 5004, publicUrl: 'https://preview.example.com/base' }, managerLocation),
|
||||
).toBe('https://preview.example.com')
|
||||
})
|
||||
|
||||
it('falls back to the manager host and preview port', () => {
|
||||
expect(
|
||||
getPreviewOrigin({ previewPort: 5004, publicUrl: null }, managerLocation),
|
||||
).toBe('http://manager.local:5004')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildPreviewStartUrl', () => {
|
||||
it('encodes the token and path against the preview origin', () => {
|
||||
const url = buildPreviewStartUrl(
|
||||
{ token: 'tok en', previewPort: 5004, publicUrl: null },
|
||||
'/a b?x=1',
|
||||
managerLocation,
|
||||
)
|
||||
|
||||
expect(url).toBe('http://manager.local:5004/__ocm_preview/start?token=tok+en&path=%2Fa+b%3Fx%3D1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isSameOriginAsManager', () => {
|
||||
it('matches the manager origin and rejects another port', () => {
|
||||
expect(isSameOriginAsManager('http://manager.local:5003', managerLocation)).toBe(true)
|
||||
expect(isSameOriginAsManager('http://manager.local:5004', managerLocation)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { CreatePreviewSessionResponse } from '@opencode-manager/shared/types'
|
||||
|
||||
const LOCAL_DEV_HOSTS = new Set(['localhost', '127.0.0.1', '0.0.0.0', '[::1]'])
|
||||
|
||||
export interface LocalDevUrl {
|
||||
port: number
|
||||
path: string
|
||||
}
|
||||
|
||||
export interface PreviewOriginInput {
|
||||
previewPort: number
|
||||
publicUrl: string | null
|
||||
}
|
||||
|
||||
function parsePort(value: string): number | null {
|
||||
if (!value) return null
|
||||
const port = Number(value)
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) return null
|
||||
return port
|
||||
}
|
||||
|
||||
export function parseLocalDevUrl(url: string): LocalDevUrl | null {
|
||||
let parsed: URL
|
||||
try {
|
||||
parsed = new URL(url)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null
|
||||
if (!LOCAL_DEV_HOSTS.has(parsed.hostname)) return null
|
||||
const port = parsePort(parsed.port)
|
||||
if (port === null) return null
|
||||
return { port, path: `${parsed.pathname}${parsed.search}${parsed.hash}` }
|
||||
}
|
||||
|
||||
export function getPreviewOrigin(input: PreviewOriginInput, location: Location = window.location): string {
|
||||
if (input.publicUrl) {
|
||||
return new URL(input.publicUrl, location.origin).origin
|
||||
}
|
||||
return `${location.protocol}//${location.hostname}:${input.previewPort}`
|
||||
}
|
||||
|
||||
export function buildPreviewStartUrl(
|
||||
session: CreatePreviewSessionResponse,
|
||||
path: string,
|
||||
location: Location = window.location,
|
||||
): string {
|
||||
const origin = getPreviewOrigin(session, location)
|
||||
const query = new URLSearchParams({ token: session.token, path })
|
||||
return `${origin}/__ocm_preview/start?${query.toString()}`
|
||||
}
|
||||
|
||||
export function isSameOriginAsManager(origin: string, location: Location = window.location): boolean {
|
||||
try {
|
||||
return new URL(origin).origin === location.origin
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { WorktreeSetupResult } from '@opencode-manager/shared/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
export function notifyWorktreeSetup(setup: WorktreeSetupResult | undefined): void {
|
||||
if (!setup) return
|
||||
if (setup.status === 'failed') {
|
||||
showToast.warning('Worktree setup failed to start')
|
||||
return
|
||||
}
|
||||
if (setup.status === 'skipped' || (setup.status === 'started' && setup.repoCommandsSkipped)) {
|
||||
showToast.info('Repository setup commands were skipped until trusted in Actions')
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog"
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"
|
||||
import { SourceControlPanel } from "@/components/source-control"
|
||||
import { TerminalPanel } from "@/components/terminal/TerminalPanel"
|
||||
import { PreviewPanel } from "@/components/preview/PreviewPanel"
|
||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"
|
||||
import { Plus } from "lucide-react"
|
||||
@@ -25,6 +26,7 @@ export function AssistantRedirect() {
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills')
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl')
|
||||
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal')
|
||||
const [previewOpen, setPreviewOpen] = useDialogParam('preview')
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions')
|
||||
|
||||
const { data: repo, isLoading: repoLoading, error: repoError } = useQuery({
|
||||
@@ -95,6 +97,7 @@ export function AssistantRedirect() {
|
||||
)}
|
||||
<SourceControlPanel repoId={repoId} isOpen={sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} repoName="Assistant" />
|
||||
<TerminalPanel repoId={0} directory={assistantDirectory} isOpen={terminalOpen} onClose={() => setTerminalOpen(false)} />
|
||||
<PreviewPanel isOpen={previewOpen} onClose={() => setPreviewOpen(false)} directory={assistantDirectory} />
|
||||
<ResetPermissionsDialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen} repoId={repoId} />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -6,15 +6,18 @@ import { SessionList } from "@/components/session/SessionList";
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
import { ProjectActionsMenu } from "@/components/repo/ProjectActionsMenu";
|
||||
import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog";
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
|
||||
import { SourceControlPanel } from "@/components/source-control";
|
||||
import { TerminalPanel } from "@/components/terminal/TerminalPanel";
|
||||
import { PreviewPanel } from "@/components/preview/PreviewPanel";
|
||||
import { useCreateSession } from "@/hooks/useOpenCode";
|
||||
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 { useWorktreeTab } from "@/hooks/useWorktreeTab";
|
||||
import { WorktreeTabs } from "@/components/repo/WorktreeTabs";
|
||||
import { WorkspaceManager } from "@/components/repo/WorkspaceManager";
|
||||
@@ -25,6 +28,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
|
||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
import { getRepoDisplayName } from "@/lib/utils";
|
||||
import { notifyWorktreeSetup } from "@/lib/worktreeSetup";
|
||||
import { isWorktreeSibling } from "@opencode-manager/shared/utils";
|
||||
|
||||
export function RepoDetail() {
|
||||
@@ -37,11 +41,13 @@ export function RepoDetail() {
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
|
||||
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal');
|
||||
const [actionsDialogOpen, setActionsDialogOpen] = useDialogParam('actions');
|
||||
const [previewOpen, setPreviewOpen] = useDialogParam('preview');
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
|
||||
const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false);
|
||||
const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false);
|
||||
const [activeWorkspaceDirectory, setActiveWorkspaceDirectory] = useState<string | undefined>();
|
||||
const { activeTab, setActiveTab } = useWorktreeTab();
|
||||
const { updateParams } = useUrlParams();
|
||||
|
||||
const { data: repo, isLoading: repoLoading } = useQuery({
|
||||
queryKey: ["repo", repoId],
|
||||
@@ -133,8 +139,19 @@ export function RepoDetail() {
|
||||
if (workspace.directory) {
|
||||
setActiveWorkspaceDirectory(workspace.directory);
|
||||
}
|
||||
setActiveTab('workspaces');
|
||||
setCreateWorkspaceOpen(false);
|
||||
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');
|
||||
return;
|
||||
}
|
||||
setActiveTab('workspaces');
|
||||
};
|
||||
|
||||
const handleOpenWorkspaceSelector = () => {
|
||||
@@ -204,6 +221,7 @@ export function RepoDetail() {
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<div className="flex items-center gap-1">
|
||||
<ProjectActionsMenu repoId={repoId} directory={composerDirectory} />
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<Button
|
||||
@@ -309,6 +327,12 @@ export function RepoDetail() {
|
||||
onClose={() => setTerminalOpen(false)}
|
||||
/>
|
||||
|
||||
<PreviewPanel
|
||||
isOpen={previewOpen}
|
||||
onClose={() => setPreviewOpen(false)}
|
||||
directory={composerDirectory}
|
||||
/>
|
||||
|
||||
<ResetPermissionsDialog
|
||||
open={resetPermissionsOpen}
|
||||
onOpenChange={setResetPermissionsOpen}
|
||||
|
||||
@@ -38,6 +38,7 @@ import { showToast } from "@/lib/toast";
|
||||
import { getWorkspaceFilePath } from "@/lib/markdownLinks";
|
||||
import { getRepoDisplayName } from "@/lib/utils";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
import { ProjectActionsMenu } from "@/components/repo/ProjectActionsMenu";
|
||||
import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog";
|
||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
|
||||
@@ -52,6 +53,7 @@ import { MinimizedFormIndicator } from "@/components/session/MinimizedFormIndica
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
import { SourceControlPanel } from "@/components/source-control";
|
||||
import { TerminalPanel } from "@/components/terminal/TerminalPanel";
|
||||
import { PreviewPanel } from "@/components/preview/PreviewPanel";
|
||||
import { SessionSendErrorBanner } from "@/components/session/SessionSendErrorBanner";
|
||||
import { BackgroundWorkBar } from "@/components/session/BackgroundWorkBar";
|
||||
import { useDialogParam } from "@/hooks/useDialogParam";
|
||||
@@ -121,6 +123,7 @@ export function SessionDetail() {
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl');
|
||||
const [terminalOpen, setTerminalOpen] = useDialogParam('terminal');
|
||||
const [actionsDialogOpen, setActionsDialogOpen] = useDialogParam('actions');
|
||||
const [previewOpen, setPreviewOpen] = useDialogParam('preview');
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
|
||||
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
|
||||
const [showScrollButton, setShowScrollButton] = useState(false);
|
||||
@@ -679,6 +682,7 @@ export function SessionDetail() {
|
||||
</div>
|
||||
<Header.Actions className="gap-2 sm:gap-4">
|
||||
<div className="flex items-center gap-1">
|
||||
<ProjectActionsMenu repoId={repoId} directory={sessionDirectory} />
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<ContextUsageIndicator
|
||||
@@ -879,6 +883,12 @@ export function SessionDetail() {
|
||||
onClose={() => setTerminalOpen(false)}
|
||||
/>
|
||||
|
||||
<PreviewPanel
|
||||
isOpen={previewOpen}
|
||||
onClose={() => setPreviewOpen(false)}
|
||||
directory={sessionDirectory}
|
||||
/>
|
||||
|
||||
<ResetPermissionsDialog
|
||||
open={resetPermissionsOpen}
|
||||
onOpenChange={setResetPermissionsOpen}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { TerminalInfo } from '@opencode-manager/shared/types'
|
||||
import type { Repo } from '@/api/types'
|
||||
import { AssistantRedirect } from '../AssistantRedirect'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getRepo: vi.fn(),
|
||||
useSSE: vi.fn(),
|
||||
useCreateSession: vi.fn(),
|
||||
useTerminals: vi.fn(),
|
||||
useCreateTerminal: vi.fn(),
|
||||
useRemoveTerminal: vi.fn(),
|
||||
usePreviewPorts: vi.fn(),
|
||||
createPreviewSession: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({ getRepo: mocks.getRepo }))
|
||||
vi.mock('@/hooks/useSSE', () => ({ useSSE: mocks.useSSE }))
|
||||
vi.mock('@/hooks/useOpenCode', () => ({ useCreateSession: mocks.useCreateSession }))
|
||||
vi.mock('@/api/terminals', () => ({
|
||||
useTerminals: mocks.useTerminals,
|
||||
useCreateTerminal: mocks.useCreateTerminal,
|
||||
useRemoveTerminal: mocks.useRemoveTerminal,
|
||||
}))
|
||||
vi.mock('@/api/preview', () => ({
|
||||
usePreviewPorts: mocks.usePreviewPorts,
|
||||
createPreviewSession: mocks.createPreviewSession,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/session/SessionList', () => ({ SessionList: () => null }))
|
||||
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: () => null }))
|
||||
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: () => null }))
|
||||
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: () => null }))
|
||||
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: () => null }))
|
||||
vi.mock('@/components/source-control', () => ({ SourceControlPanel: () => null }))
|
||||
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null }))
|
||||
|
||||
vi.mock('@/components/terminal/TerminalView', async () => {
|
||||
const React = await import('react')
|
||||
return {
|
||||
TerminalView: React.forwardRef(function MockTerminalView(
|
||||
props: { ptyID: string; onOpenLink?: (uri: string) => void },
|
||||
ref: React.Ref<unknown>,
|
||||
) {
|
||||
React.useImperativeHandle(ref, () => ({ send: vi.fn() }))
|
||||
return React.createElement(
|
||||
'div',
|
||||
{ 'data-testid': 'terminal-view', 'data-pty-id': props.ptyID },
|
||||
React.createElement(
|
||||
'button',
|
||||
{ type: 'button', onClick: () => props.onOpenLink?.('http://localhost:5173/dashboard') },
|
||||
'local-link',
|
||||
),
|
||||
React.createElement(
|
||||
'button',
|
||||
{ type: 'button', onClick: () => props.onOpenLink?.('https://example.com/docs') },
|
||||
'external-link',
|
||||
),
|
||||
)
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const assistantDirectory = '/abs/assistant'
|
||||
const baseRepo: Repo = {
|
||||
id: 0,
|
||||
name: 'Assistant',
|
||||
localPath: 'assistant',
|
||||
fullPath: assistantDirectory,
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
branch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 1,
|
||||
isWorktree: false,
|
||||
}
|
||||
|
||||
const runningTerminal: TerminalInfo = {
|
||||
id: 't1',
|
||||
title: 'Terminal',
|
||||
kind: 'shell',
|
||||
cwd: assistantDirectory,
|
||||
status: 'running',
|
||||
}
|
||||
|
||||
function LocationProbe() {
|
||||
const location = useLocation()
|
||||
return <div data-testid="location">{`${location.pathname}${location.search}`}</div>
|
||||
}
|
||||
|
||||
function renderAssistantRedirect(initialEntry = '/assistant?dialog=terminal') {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={[initialEntry]}>
|
||||
<LocationProbe />
|
||||
<AssistantRedirect />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('AssistantRedirect preview routing', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.getRepo.mockResolvedValue(baseRepo)
|
||||
mocks.useSSE.mockReturnValue(undefined)
|
||||
mocks.useCreateSession.mockReturnValue({ mutateAsync: vi.fn(), isPending: false })
|
||||
mocks.useTerminals.mockReturnValue({
|
||||
data: [runningTerminal],
|
||||
isLoading: false,
|
||||
isSuccess: true,
|
||||
refetch: vi.fn(),
|
||||
})
|
||||
mocks.useCreateTerminal.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
mocks.useRemoveTerminal.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
mocks.usePreviewPorts.mockReturnValue({
|
||||
data: {
|
||||
enabled: true,
|
||||
ports: [{ port: 5173, host: '127.0.0.1', pid: 10, command: 'vite', cwd: assistantDirectory }],
|
||||
},
|
||||
isLoading: false,
|
||||
refetch: vi.fn(),
|
||||
})
|
||||
mocks.createPreviewSession.mockResolvedValue({ token: 'tok', previewPort: 5004, publicUrl: null })
|
||||
})
|
||||
|
||||
it('opens the preview panel when a terminal localhost link is followed', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderAssistantRedirect()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'local-link' }))
|
||||
|
||||
const iframe = await screen.findByTitle('Preview')
|
||||
expect(iframe.getAttribute('src')).toContain('token=tok')
|
||||
expect(iframe.getAttribute('src')).toContain('path=%2Fdashboard')
|
||||
expect(mocks.createPreviewSession).toHaveBeenCalledWith(5173)
|
||||
|
||||
expect(screen.queryByTestId('terminal-view')).not.toBeInTheDocument()
|
||||
const location = screen.getByTestId('location').textContent ?? ''
|
||||
expect(location).toContain('dialog=preview')
|
||||
expect(location).toContain('previewPort=5173')
|
||||
expect(location).toContain('previewPath=%2Fdashboard')
|
||||
})
|
||||
|
||||
it('opens external terminal links in a new tab without mounting the preview panel', async () => {
|
||||
const user = userEvent.setup()
|
||||
const openSpy = vi.spyOn(window, 'open').mockReturnValue(null)
|
||||
renderAssistantRedirect()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'external-link' }))
|
||||
|
||||
expect(openSpy).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer')
|
||||
expect(mocks.createPreviewSession).not.toHaveBeenCalled()
|
||||
expect(screen.queryByTitle('Preview')).not.toBeInTheDocument()
|
||||
expect(screen.getByTestId('terminal-view')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('location').textContent).toContain('dialog=terminal')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { Repo } from '@/api/types'
|
||||
import { RepoDetail } from '../RepoDetail'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getRepo: vi.fn(),
|
||||
useRepoSiblings: vi.fn(),
|
||||
useCreateRepoWorkspace: vi.fn(),
|
||||
useDeleteRepoWorkspaces: vi.fn(),
|
||||
useRepoActivity: vi.fn(),
|
||||
useSSE: vi.fn(),
|
||||
useCreateSession: vi.fn(),
|
||||
createWorkspaceMutateAsync: vi.fn(),
|
||||
showToastInfo: vi.fn(),
|
||||
showToastWarning: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
getRepo: mocks.getRepo,
|
||||
workspaceLabel: (workspace: { currentBranch?: string; branch?: string; localPath?: string }) =>
|
||||
workspace.currentBranch || workspace.branch || workspace.localPath || 'workspace',
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
success: vi.fn(),
|
||||
info: mocks.showToastInfo,
|
||||
warning: mocks.showToastWarning,
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useRepoSiblings', () => ({
|
||||
useRepoSiblings: mocks.useRepoSiblings,
|
||||
useCreateRepoWorkspace: mocks.useCreateRepoWorkspace,
|
||||
useDeleteRepoWorkspaces: mocks.useDeleteRepoWorkspaces,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useRepoActivity', () => ({ useRepoActivity: mocks.useRepoActivity }))
|
||||
vi.mock('@/hooks/useSSE', () => ({ useSSE: mocks.useSSE }))
|
||||
vi.mock('@/hooks/useOpenCode', () => ({ useCreateSession: mocks.useCreateSession }))
|
||||
|
||||
vi.mock('@/components/repo/WorktreeTabs', () => ({
|
||||
WorktreeTabs: ({ onCreateWorkspace }: { onCreateWorkspace: () => void }) => (
|
||||
<button type="button" onClick={onCreateWorkspace}>New workspace</button>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/terminal/TerminalPanel', () => ({
|
||||
TerminalPanel: ({ directory, isOpen }: { directory?: string; isOpen: boolean }) => (
|
||||
<div data-testid="terminal-panel" data-directory={directory ?? ''} data-open={String(isOpen)} />
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/session/SessionList', () => ({ SessionList: () => null }))
|
||||
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: () => null }))
|
||||
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: () => null }))
|
||||
vi.mock('@/components/repo/ProjectActionsMenu', () => ({ ProjectActionsMenu: () => null }))
|
||||
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: () => null }))
|
||||
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: () => null }))
|
||||
vi.mock('@/components/source-control', () => ({ SourceControlPanel: () => null }))
|
||||
vi.mock('@/components/repo/WorkspaceManager', () => ({ WorkspaceManager: () => null }))
|
||||
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: () => null }))
|
||||
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null }))
|
||||
|
||||
const baseRepo: Repo = {
|
||||
id: 1,
|
||||
name: 'my-repo',
|
||||
localPath: 'repos/my-repo',
|
||||
fullPath: '/abs/repos/my-repo',
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
branch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 1,
|
||||
isWorktree: false,
|
||||
}
|
||||
|
||||
const newWorkspaceDirectory = '/abs/repos/my-repo-ws'
|
||||
const siblingsData: Repo[] = []
|
||||
|
||||
function LocationProbe() {
|
||||
const location = useLocation()
|
||||
return <div data-testid="location">{`${location.pathname}${location.search}`}</div>
|
||||
}
|
||||
|
||||
function renderRepoDetail() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/1']}>
|
||||
<LocationProbe />
|
||||
<Routes>
|
||||
<Route path="/repos/:id" element={<RepoDetail />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
async function startWorkspaceCreation() {
|
||||
const user = userEvent.setup()
|
||||
renderRepoDetail()
|
||||
await user.click(await screen.findByRole('button', { name: 'New workspace' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Create Workspace' }))
|
||||
}
|
||||
|
||||
describe('RepoDetail worktree setup', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.getRepo.mockResolvedValue(baseRepo)
|
||||
mocks.useRepoSiblings.mockReturnValue({ data: siblingsData })
|
||||
mocks.useDeleteRepoWorkspaces.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
mocks.useCreateSession.mockReturnValue({ mutateAsync: vi.fn(), isPending: false })
|
||||
})
|
||||
|
||||
it('switches to the new workspace terminal when setup starts from the repo tab', async () => {
|
||||
mocks.useCreateRepoWorkspace.mockReturnValue({
|
||||
mutateAsync: mocks.createWorkspaceMutateAsync,
|
||||
isPending: false,
|
||||
})
|
||||
mocks.createWorkspaceMutateAsync.mockResolvedValue({
|
||||
directory: newWorkspaceDirectory,
|
||||
worktreeSetup: {
|
||||
status: 'started',
|
||||
terminal: {
|
||||
id: 'pty-new',
|
||||
title: 'Worktree setup',
|
||||
kind: 'setup',
|
||||
cwd: newWorkspaceDirectory,
|
||||
status: 'running',
|
||||
},
|
||||
repoCommandsSkipped: false,
|
||||
},
|
||||
})
|
||||
|
||||
await startWorkspaceCreation()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('repoTab=workspaces'),
|
||||
)
|
||||
const location = screen.getByTestId('location').textContent ?? ''
|
||||
expect(location).toContain('dialog=terminal')
|
||||
expect(location).toContain('terminal=pty-new')
|
||||
expect(screen.getByTestId('terminal-panel')).toHaveAttribute(
|
||||
'data-directory',
|
||||
newWorkspaceDirectory,
|
||||
)
|
||||
})
|
||||
|
||||
it('stays on the workspace tab without a terminal when setup does not start', async () => {
|
||||
mocks.useCreateRepoWorkspace.mockReturnValue({
|
||||
mutateAsync: mocks.createWorkspaceMutateAsync,
|
||||
isPending: false,
|
||||
})
|
||||
mocks.createWorkspaceMutateAsync.mockResolvedValue({
|
||||
directory: newWorkspaceDirectory,
|
||||
worktreeSetup: { status: 'none' },
|
||||
})
|
||||
|
||||
await startWorkspaceCreation()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('repoTab=workspaces'),
|
||||
)
|
||||
expect(screen.getByTestId('location')).not.toHaveTextContent('dialog=terminal')
|
||||
expect(screen.getByTestId('terminal-panel')).toHaveAttribute(
|
||||
'data-directory',
|
||||
newWorkspaceDirectory,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -30,6 +30,9 @@ nav:
|
||||
- Overview: features/overview.md
|
||||
- Repository & Git: features/git.md
|
||||
- File Browser: features/files.md
|
||||
- Terminal & Dev Loop: features/terminal.md
|
||||
- Project Actions: features/project-actions.md
|
||||
- Preview: features/preview.md
|
||||
- Chat & Sessions: features/chat.md
|
||||
- Session Pinning: features/session-pins.md
|
||||
- Schedules & Recurring Jobs: features/schedules.md
|
||||
|
||||
@@ -18,6 +18,10 @@ export const DEFAULTS = {
|
||||
HEALTH_FAILURE_THRESHOLD: 2,
|
||||
},
|
||||
|
||||
PREVIEW: {
|
||||
PORT: 5004,
|
||||
},
|
||||
|
||||
DATABASE: {
|
||||
PATH: './data/opencode.db',
|
||||
},
|
||||
|
||||
@@ -74,6 +74,11 @@ export const ENV = {
|
||||
LEGACY_PUBLIC_URL: getEnvString('OPENCODE_PUBLIC_URL', ''),
|
||||
},
|
||||
|
||||
PREVIEW: {
|
||||
PORT: getEnvNumber('PREVIEW_PORT', DEFAULTS.PREVIEW.PORT),
|
||||
PUBLIC_URL: getEnvString('PREVIEW_PUBLIC_URL', ''),
|
||||
},
|
||||
|
||||
DATABASE: {
|
||||
PATH: getEnvString('DATABASE_PATH', DEFAULTS.DATABASE.PATH),
|
||||
},
|
||||
|
||||
@@ -14,3 +14,4 @@ export * from './session-pins'
|
||||
export * from './logs'
|
||||
export * from './terminal'
|
||||
export * from './project-config'
|
||||
export * from './preview'
|
||||
@@ -0,0 +1,29 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const PreviewPortSchema = z.object({
|
||||
port: z.number().int(),
|
||||
host: z.enum(['127.0.0.1', '::1']),
|
||||
pid: z.number().int().nullable(),
|
||||
command: z.string().nullable(),
|
||||
cwd: z.string().nullable(),
|
||||
})
|
||||
|
||||
export const PreviewPortsResponseSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
ports: z.array(PreviewPortSchema),
|
||||
})
|
||||
|
||||
export const CreatePreviewSessionRequestSchema = z.object({
|
||||
port: z.number().int().min(1024).max(65535),
|
||||
})
|
||||
|
||||
export const CreatePreviewSessionResponseSchema = z.object({
|
||||
token: z.string(),
|
||||
previewPort: z.number().int(),
|
||||
publicUrl: z.string().nullable(),
|
||||
})
|
||||
|
||||
export type PreviewPort = z.infer<typeof PreviewPortSchema>
|
||||
export type PreviewPortsResponse = z.infer<typeof PreviewPortsResponseSchema>
|
||||
export type CreatePreviewSessionRequest = z.infer<typeof CreatePreviewSessionRequestSchema>
|
||||
export type CreatePreviewSessionResponse = z.infer<typeof CreatePreviewSessionResponseSchema>
|
||||
@@ -93,6 +93,17 @@ export const RunProjectActionResponseSchema = z.object({
|
||||
autoOpenUrl: z.boolean(),
|
||||
})
|
||||
|
||||
export const WorktreeSetupResultSchema = z.discriminatedUnion('status', [
|
||||
z.object({ status: z.literal('none') }),
|
||||
z.object({
|
||||
status: z.literal('started'),
|
||||
terminal: TerminalInfoSchema,
|
||||
repoCommandsSkipped: z.boolean(),
|
||||
}),
|
||||
z.object({ status: z.literal('skipped'), reason: z.literal('untrusted') }),
|
||||
z.object({ status: z.literal('failed'), error: z.string() }),
|
||||
])
|
||||
|
||||
export type ProjectActionIcon = z.infer<typeof ProjectActionIconSchema>
|
||||
export type ProjectAction = z.infer<typeof ProjectActionSchema>
|
||||
export type WorktreeSetupCommands = z.infer<typeof WorktreeSetupCommandsSchema>
|
||||
@@ -105,3 +116,4 @@ export type TrustRepoConfigRequest = z.infer<typeof TrustRepoConfigRequestSchema
|
||||
export type MoveProjectItemRequest = z.infer<typeof MoveProjectItemRequestSchema>
|
||||
export type RunProjectActionRequest = z.infer<typeof RunProjectActionRequestSchema>
|
||||
export type RunProjectActionResponse = z.infer<typeof RunProjectActionResponseSchema>
|
||||
export type WorktreeSetupResult = z.infer<typeof WorktreeSetupResultSchema>
|
||||
@@ -166,6 +166,13 @@ export type {
|
||||
ResizeTerminalRequest,
|
||||
} from '../schemas/terminal'
|
||||
|
||||
export type {
|
||||
PreviewPort,
|
||||
PreviewPortsResponse,
|
||||
CreatePreviewSessionRequest,
|
||||
CreatePreviewSessionResponse,
|
||||
} from '../schemas/preview'
|
||||
|
||||
export type {
|
||||
ProjectActionIcon,
|
||||
ProjectAction,
|
||||
@@ -179,4 +186,5 @@ export type {
|
||||
MoveProjectItemRequest,
|
||||
RunProjectActionRequest,
|
||||
RunProjectActionResponse,
|
||||
WorktreeSetupResult,
|
||||
} from '../schemas/project-config'
|
||||
Reference in new issue
Block a user