mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix: address findings from the full Docker evaluation of main
Critical and high: - repos: unlinking a local repo removes only the Manager reference and alias, never the repository files; confirm button reads "Unlink" - auth: rate-limit by the socket address; trust proxy headers only when AUTH_TRUSTED_PROXY_HEADERS is set (documented and forwarded in compose) - composer: per-session in-memory drafts (text, bash mode, attachments); Escape no longer clears the prompt - url params: compose same-tick updates so schedule dialogs stay closed after create/delete; delete dialog names the job Medium: - tool rows show failures (non-zero shell exit, failed exploration members) - voice conversation shows the specific error and a starting state - settings: Escape in dropdowns and the shortcut recorder no longer closes the dialog; mobile deep links open the requested section; one content tree per platform - closing pushed sheets, settings, tool panels and schedule dialogs goes back in history - login returns to the requested page; signed-out pages make no authenticated requests - action terminals keep their output (Manager-side output capture and replay) - unpushed-commit detection, commit message kept on failure - binary files with unknown extensions are detected and not editable - tool panel resizes when docked and floats as a dismissible sheet when the page is too narrow - Docker image runs tini as PID 1 Low: not-found states, add-repo and branch validation errors (4xx), search-aware empty states, mobile repo sort/filter/select cues, sidebar resize affordance and collapse shortcut, mobile unread badge, preview port filtering, terminal close handling, walkthrough empty state and helper session filtering, placeholder contrast, permission labels and focus, TTS task-list sanitizing, git identity email validation, quieter git logging, hermetic worktree tests, and accessible names for icon-only controls.
This commit is contained in:
1 parent
1c22ef6ea1
commit
4ec62cd4e7
191 files changed
+6674
-696
No files matched your search
@@ -31,6 +31,7 @@ import {
|
||||
deleteChangeWalkthroughs,
|
||||
getChangeWalkthrough,
|
||||
getChangeWalkthroughByWalkthroughSession,
|
||||
listChangeWalkthroughSessionIds,
|
||||
listChangeWalkthroughs,
|
||||
updateChangeWalkthrough,
|
||||
type ChangeWalkthroughPatch,
|
||||
@@ -56,6 +57,7 @@ import type { SettingsService } from './settings'
|
||||
import type { SSEEvent } from './sse-aggregator'
|
||||
|
||||
const WALKTHROUGH_TIMEOUT_MESSAGE = 'The walkthrough session did not publish within 15 minutes'
|
||||
const EMPTY_CHANGES_HASH = computeChangesHash([])
|
||||
|
||||
export interface ChangeWalkthroughServiceOptions {
|
||||
generationTimeoutMs?: number
|
||||
@@ -170,6 +172,11 @@ export class ChangeWalkthroughService {
|
||||
this.walkthroughsRoot = options.walkthroughsRoot ?? getWalkthroughsPath()
|
||||
}
|
||||
|
||||
/** Sessions the walkthrough runs were created in, which are helper sessions rather than user sessions. */
|
||||
listHelperSessionIds(): string[] {
|
||||
return listChangeWalkthroughSessionIds(this.db)
|
||||
}
|
||||
|
||||
async getState(
|
||||
sessionId: string,
|
||||
source: WalkthroughSource = DEFAULT_WALKTHROUGH_SOURCE,
|
||||
@@ -187,6 +194,7 @@ export class ChangeWalkthroughService {
|
||||
return {
|
||||
walkthrough,
|
||||
currentDiffHash,
|
||||
hasChanges: currentDiffHash === null || currentDiffHash !== EMPTY_CHANGES_HASH,
|
||||
stale: walkthrough !== null && currentDiffHash !== null && walkthrough.diffHash !== currentDiffHash,
|
||||
generating: walkthrough?.status === 'generating',
|
||||
running: walkthrough !== null && walkthrough.executionStartedAt !== null,
|
||||
|
||||
@@ -40,9 +40,15 @@ interface FileUploadResult {
|
||||
mimeType: string
|
||||
}
|
||||
|
||||
const BINARY_MIME_TYPE = 'application/octet-stream'
|
||||
const SNIFF_BYTE_COUNT = 8192
|
||||
const MAX_INVALID_UTF8_RATIO = 0.1
|
||||
|
||||
type DetectedMimeType = AllowedMimeType | typeof BINARY_MIME_TYPE
|
||||
|
||||
export interface RawFileMetadata {
|
||||
size: number
|
||||
mimeType: AllowedMimeType
|
||||
mimeType: DetectedMimeType
|
||||
lastModified: Date
|
||||
}
|
||||
|
||||
@@ -85,7 +91,7 @@ export async function getRawFileMetadata(userPath: string): Promise<RawFileMetad
|
||||
|
||||
return {
|
||||
size: stats.size,
|
||||
mimeType: getMimeType(validatedPath),
|
||||
mimeType: await detectMimeType(validatedPath),
|
||||
lastModified: stats.lastModified,
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -141,12 +147,10 @@ export async function getFile(userPath: string): Promise<FileInfo> {
|
||||
} else {
|
||||
// It's a file - get content
|
||||
let content = ''
|
||||
const mimeType = getMimeType(validatedPath)
|
||||
const mimeType = await detectMimeType(validatedPath)
|
||||
|
||||
if (stats.size < FILE_LIMITS.MAX_SIZE_BYTES) {
|
||||
try {
|
||||
const mimeType = getMimeType(validatedPath)
|
||||
|
||||
if (mimeType.startsWith('image/') || !mimeType.startsWith('text/')) {
|
||||
content = await readFileAsBase64(validatedPath)
|
||||
} else {
|
||||
@@ -179,7 +183,7 @@ export async function uploadFile(userPath: string, file: File, relativePath?: st
|
||||
throw new Error('File too large')
|
||||
}
|
||||
|
||||
const mimeType = (file.type || getMimeType(file.name)) as AllowedMimeType
|
||||
const mimeType = (file.type || getKnownMimeType(file.name) || 'text/plain') as AllowedMimeType
|
||||
if (!ALLOWED_MIME_TYPES.includes(mimeType) && !mimeType.startsWith('text/')) {
|
||||
throw new Error('File type not allowed')
|
||||
}
|
||||
@@ -288,7 +292,7 @@ function validatePath(userPath: string): string {
|
||||
return resolved
|
||||
}
|
||||
|
||||
function getMimeType(filePath: string): AllowedMimeType {
|
||||
function getKnownMimeType(filePath: string): AllowedMimeType | undefined {
|
||||
const ext = path.extname(filePath).toLowerCase()
|
||||
|
||||
const mimeTypes: Record<string, AllowedMimeType> = {
|
||||
@@ -315,7 +319,32 @@ function getMimeType(filePath: string): AllowedMimeType {
|
||||
'.mdx': 'text/markdown',
|
||||
}
|
||||
|
||||
return mimeTypes[ext] || 'text/plain'
|
||||
return mimeTypes[ext]
|
||||
}
|
||||
|
||||
async function detectMimeType(filePath: string): Promise<DetectedMimeType> {
|
||||
const known = getKnownMimeType(filePath)
|
||||
if (known) return known
|
||||
return isBinaryContent(await readFilePrefix(filePath)) ? BINARY_MIME_TYPE : 'text/plain'
|
||||
}
|
||||
|
||||
async function readFilePrefix(filePath: string): Promise<Buffer> {
|
||||
const handle = await fs.open(filePath, 'r')
|
||||
try {
|
||||
const buffer = Buffer.alloc(SNIFF_BYTE_COUNT)
|
||||
const { bytesRead } = await handle.read(buffer, 0, SNIFF_BYTE_COUNT, 0)
|
||||
return buffer.subarray(0, bytesRead)
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
function isBinaryContent(buffer: Buffer): boolean {
|
||||
if (buffer.length === 0) return false
|
||||
if (buffer.includes(0)) return true
|
||||
const decoded = buffer.toString('utf8')
|
||||
const invalidCharacters = decoded.split('\uFFFD').length - 1
|
||||
return invalidCharacters / decoded.length > MAX_INVALID_UTF8_RATIO
|
||||
}
|
||||
|
||||
async function readFileLinesAndCount(
|
||||
@@ -356,7 +385,7 @@ export async function getFileRange(userPath: string, startLine: number, endLine:
|
||||
|
||||
const { lines, totalLines } = await readFileLinesAndCount(validatedPath, startLine, endLine)
|
||||
const clampedEnd = Math.min(endLine, totalLines)
|
||||
const mimeType = getMimeType(validatedPath)
|
||||
const mimeType = await detectMimeType(validatedPath)
|
||||
|
||||
return {
|
||||
name: path.basename(validatedPath),
|
||||
|
||||
@@ -176,12 +176,13 @@ export class GitService {
|
||||
}
|
||||
|
||||
const repoPath = path.resolve(repo.fullPath)
|
||||
const revision = branch?.trim() || 'HEAD'
|
||||
const logArgs = [
|
||||
'git',
|
||||
'-C',
|
||||
repoPath,
|
||||
'log',
|
||||
branch?.trim() || 'HEAD',
|
||||
revision,
|
||||
`-n`,
|
||||
String(limit),
|
||||
'--format=%H|%an|%ae|%at|%s'
|
||||
@@ -210,7 +211,7 @@ export class GitService {
|
||||
}
|
||||
}
|
||||
|
||||
const unpushedCommits = await this.getUnpushedCommitHashes(repoPath, logEnv)
|
||||
const unpushedCommits = await this.getUnpushedCommitHashes(repoPath, revision, logEnv, limit)
|
||||
|
||||
return commits.map(commit => ({
|
||||
...commit,
|
||||
@@ -858,6 +859,9 @@ export class GitService {
|
||||
|
||||
return { ahead: ahead || 0, behind: behind || 0 }
|
||||
} catch (error) {
|
||||
if (isNoUpstreamError(error as Error)) {
|
||||
return { ahead: 0, behind: 0 }
|
||||
}
|
||||
logger.warn(`Could not get branch status for repo ${repoId}, returning zeros:`, error)
|
||||
return { ahead: 0, behind: 0 }
|
||||
}
|
||||
@@ -1515,16 +1519,18 @@ export class GitService {
|
||||
}
|
||||
|
||||
private async isCommitUnpushed(repoPath: string, commitHash: string, env: Record<string, string>): Promise<boolean> {
|
||||
const unpushedHashes = await this.getUnpushedCommitHashes(repoPath, env)
|
||||
const unpushedHashes = await this.getUnpushedCommitHashes(repoPath, 'HEAD', env)
|
||||
return unpushedHashes.has(commitHash)
|
||||
}
|
||||
|
||||
private async getUnpushedCommitHashes(repoPath: string, env: Record<string, string>): Promise<Set<string>> {
|
||||
private async getUnpushedCommitHashes(repoPath: string, revision: string, env: Record<string, string>, limit?: number): Promise<Set<string>> {
|
||||
try {
|
||||
const output = await executeCommand(
|
||||
['git', '-C', repoPath, 'log', '--not', '--remotes', '--format=%H'],
|
||||
{ env, silent: true }
|
||||
)
|
||||
const args = ['git', '-C', repoPath, 'log', revision, '--not', '--remotes']
|
||||
if (limit !== undefined) {
|
||||
args.push('-n', String(limit))
|
||||
}
|
||||
args.push('--format=%H')
|
||||
const output = await executeCommand(args, { env, silent: true })
|
||||
const hashes = output.trim().split('\n').filter(Boolean)
|
||||
return new Set(hashes)
|
||||
} catch {
|
||||
|
||||
@@ -96,7 +96,7 @@ function isAllowedAddress(address: string): boolean {
|
||||
address === WILDCARD_V4 ||
|
||||
address === WILDCARD_V6 ||
|
||||
address === '::1' ||
|
||||
address.startsWith('127.')
|
||||
address === '127.0.0.1'
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -27,30 +27,52 @@ const GIT_CLONE_TIMEOUT = 300000
|
||||
const DEFAULT_DISCOVERY_MAX_DEPTH = 4
|
||||
const DISCOVERY_SKIP_DIRECTORIES = new Set(['.git', 'node_modules'])
|
||||
|
||||
function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: string): Error {
|
||||
export class RepoInputError extends Error {
|
||||
readonly statusCode: 400
|
||||
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = 'RepoInputError'
|
||||
this.statusCode = 400
|
||||
}
|
||||
}
|
||||
|
||||
function notFoundOrDeniedMessage(repoUrl: string): string {
|
||||
return `Repository not found or access denied: ${repoUrl}. Check the URL and add credentials in Settings > Git Credentials if it is private.`
|
||||
}
|
||||
|
||||
function enhanceCloneError(repoUrl: string, originalMessage: string): RepoInputError {
|
||||
const message = originalMessage.toLowerCase()
|
||||
|
||||
if (message.includes('authentication failed') || message.includes('could not authenticate') || message.includes('invalid credentials')) {
|
||||
return new Error(`Authentication failed for ${repoUrl}. Please add your credentials in Settings > Git Credentials.`)
|
||||
}
|
||||
|
||||
if (message.includes('repository not found') || message.includes('404')) {
|
||||
return new Error(`Repository not found: ${repoUrl}. Check the URL and ensure you have access to it.`)
|
||||
}
|
||||
|
||||
if (isSSHUrl(repoUrl) && message.includes('permission denied')) {
|
||||
return new Error(`Access denied to ${repoUrl}. Please add your SSH credentials in Settings > Git Credentials and ensure your SSH key has access to this repository.`)
|
||||
}
|
||||
|
||||
if (isGitHubHttpsUrl(repoUrl) && (message.includes('permission denied') || message.includes('fatal'))) {
|
||||
return new Error(`Access denied to ${repoUrl}. Please add your credentials in Settings > Git Credentials and ensure you have proper access.`)
|
||||
}
|
||||
|
||||
|
||||
if (message.includes('timed out')) {
|
||||
return new Error(`Clone timed out for ${repoUrl}. The repository might be too large or there could be network issues. Try again or verify the repository exists.`)
|
||||
return new RepoInputError(`Clone timed out for ${repoUrl}. The repository might be too large or there could be network issues.`)
|
||||
}
|
||||
|
||||
return error instanceof Error ? error : new Error(originalMessage)
|
||||
|
||||
if (message.includes('could not resolve host') || message.includes('network is unreachable')) {
|
||||
return new RepoInputError(`Repository not reachable: ${repoUrl}. Check the URL and your network connection.`)
|
||||
}
|
||||
|
||||
if (message.includes('repository not found') || message.includes('not found') || message.includes('does not exist') || message.includes('404')) {
|
||||
return new RepoInputError(notFoundOrDeniedMessage(repoUrl))
|
||||
}
|
||||
|
||||
if (message.includes('permission denied')) {
|
||||
return isSSHUrl(repoUrl)
|
||||
? new RepoInputError(`Access denied to ${repoUrl}. Add your SSH credentials in Settings > Git Credentials and ensure your SSH key has access.`)
|
||||
: new RepoInputError(notFoundOrDeniedMessage(repoUrl))
|
||||
}
|
||||
|
||||
if (message.includes('authentication failed') || message.includes('could not authenticate') || message.includes('invalid credentials') || message.includes('could not read username')) {
|
||||
return isGitHubHttpsUrl(repoUrl)
|
||||
? new RepoInputError(notFoundOrDeniedMessage(repoUrl))
|
||||
: new RepoInputError(`Authentication failed for ${repoUrl}. Check your credentials in Settings > Git Credentials.`)
|
||||
}
|
||||
|
||||
if (message.includes('not a git repository') || message.includes('fatal:')) {
|
||||
return new RepoInputError(notFoundOrDeniedMessage(repoUrl))
|
||||
}
|
||||
|
||||
return new RepoInputError(`Could not clone ${repoUrl}. Check the URL and your access to it.`)
|
||||
}
|
||||
|
||||
async function hasCommits(repoPath: string, env: Record<string, string>): Promise<boolean> {
|
||||
@@ -258,12 +280,12 @@ async function registerExistingLocalRepo(
|
||||
|
||||
const exists = await pathExists(normalizedSourcePath)
|
||||
if (!exists) {
|
||||
throw new Error(`No such file or directory: '${normalizedSourcePath}'`)
|
||||
throw new RepoInputError(`No such directory: '${normalizedSourcePath}'`)
|
||||
}
|
||||
|
||||
const isGitRepo = await isValidGitRepo(normalizedSourcePath, env)
|
||||
if (!isGitRepo) {
|
||||
throw new Error(`Directory exists but is not a valid Git repository. Use folder discovery to scan nested repositories.`)
|
||||
throw new RepoInputError(`Directory is not a valid Git repository: '${normalizedSourcePath}'.`)
|
||||
}
|
||||
|
||||
if (branch) {
|
||||
@@ -317,11 +339,11 @@ export async function discoverLocalRepos(
|
||||
}> {
|
||||
const normalizedRootPath = normalizeAbsolutePath(rootPath)
|
||||
const rootStats = await fs.stat(normalizedRootPath).catch((error: unknown) => {
|
||||
throw new Error(`Failed to access '${normalizedRootPath}': ${getErrorMessage(error)}`)
|
||||
throw new RepoInputError(`Failed to access '${normalizedRootPath}': ${getErrorMessage(error)}`)
|
||||
})
|
||||
|
||||
if (!rootStats.isDirectory()) {
|
||||
throw new Error(`Path is not a directory: '${normalizedRootPath}'`)
|
||||
throw new RepoInputError(`Path is not a directory: '${normalizedRootPath}'`)
|
||||
}
|
||||
|
||||
const repoPaths: string[] = []
|
||||
@@ -687,7 +709,7 @@ export async function cloneRepo(
|
||||
try {
|
||||
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
|
||||
} catch (cloneError: unknown) {
|
||||
throw enhanceCloneError(cloneError, normalizedRepoUrl, getErrorMessage(cloneError))
|
||||
throw enhanceCloneError(normalizedRepoUrl, getErrorMessage(cloneError))
|
||||
}
|
||||
|
||||
let localBranchExists = 'missing'
|
||||
@@ -704,7 +726,7 @@ export async function cloneRepo(
|
||||
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
|
||||
}
|
||||
} else {
|
||||
throw enhanceCloneError(error, normalizedRepoUrl, getErrorMessage(error))
|
||||
throw enhanceCloneError(normalizedRepoUrl, getErrorMessage(error))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -801,7 +823,7 @@ export async function cloneRepo(
|
||||
try {
|
||||
await executeCommand(['git', 'clone', normalizedRepoUrl, worktreeDirName], { cwd: getReposPath(), env, timeout: GIT_CLONE_TIMEOUT })
|
||||
} catch (cloneError: unknown) {
|
||||
throw enhanceCloneError(cloneError, normalizedRepoUrl, getErrorMessage(cloneError))
|
||||
throw enhanceCloneError(normalizedRepoUrl, getErrorMessage(cloneError))
|
||||
}
|
||||
|
||||
let localBranchExists = 'missing'
|
||||
@@ -818,7 +840,7 @@ export async function cloneRepo(
|
||||
await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'checkout', branch])
|
||||
}
|
||||
} else {
|
||||
throw enhanceCloneError(error, normalizedRepoUrl, getErrorMessage(error))
|
||||
throw enhanceCloneError(normalizedRepoUrl, getErrorMessage(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -876,6 +898,14 @@ export async function switchBranch(
|
||||
}
|
||||
}
|
||||
|
||||
async function assertValidBranchName(branch: string): Promise<void> {
|
||||
try {
|
||||
await executeCommand(['git', 'check-ref-format', '--branch', branch], { silent: true })
|
||||
} catch {
|
||||
throw new RepoInputError(`Invalid branch name: '${branch}'.`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function createBranch(database: Database, gitAuthService: GitAuthService, repoId: number, branch: string): Promise<void> {
|
||||
const repo = getRepoById(database, repoId)
|
||||
if (!repo) {
|
||||
@@ -891,6 +921,8 @@ export async function createBranch(database: Database, gitAuthService: GitAuthSe
|
||||
.replace(/^refs\/remotes\//, '')
|
||||
.replace(/^origin\//, '')
|
||||
|
||||
await assertValidBranchName(sanitizedBranch)
|
||||
|
||||
logger.info(`Creating new branch: ${sanitizedBranch} in ${repo.localPath}`)
|
||||
await executeCommand(['git', '-C', repoPath, 'checkout', '-b', sanitizedBranch], { env })
|
||||
logger.info(`Successfully created and switched to branch: ${sanitizedBranch}`)
|
||||
@@ -944,6 +976,19 @@ export async function resolveMainCheckoutPath(worktreePath: string): Promise<str
|
||||
}
|
||||
}
|
||||
|
||||
async function removeWorkspaceAlias(aliasPath: string): Promise<void> {
|
||||
try {
|
||||
const stats = await fs.lstat(aliasPath)
|
||||
if (stats.isSymbolicLink()) {
|
||||
await fs.unlink(aliasPath)
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteRepoFiles(database: Database, repoId: number): Promise<void> {
|
||||
const repo = getRepoById(database, repoId)
|
||||
if (!repo) {
|
||||
@@ -959,9 +1004,14 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
|
||||
if (baseRepoPath) {
|
||||
await removeWorktree(baseRepoPath, fullPath)
|
||||
}
|
||||
|
||||
await executeCommand(['rm', '-rf', repo.localPath], getReposPath())
|
||||
} else if (repo.isLocal) {
|
||||
await removeWorkspaceAlias(fullPath)
|
||||
} else {
|
||||
await executeCommand(['rm', '-rf', repo.localPath], getReposPath())
|
||||
}
|
||||
|
||||
await executeCommand(['rm', '-rf', repo.localPath], getReposPath())
|
||||
deleteRepo(database, repoId)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
import {
|
||||
MAX_PEER_BUFFERED_BYTES,
|
||||
MAX_UPSTREAM_BUFFERED_BYTES,
|
||||
type WebSocketBridge,
|
||||
type WebSocketPeer,
|
||||
} from '../utils/websocket-bridge'
|
||||
|
||||
const BUFFER_LIMIT_CHARS = 256 * 1024
|
||||
const REPLAY_CHUNK_CHARS = 64 * 1024
|
||||
const MAX_CONNECT_ATTEMPTS = 3
|
||||
const RETRY_DELAY_MS = 100
|
||||
const META_FRAME_PREFIX = 0
|
||||
const MAX_REGISTERED_HUBS = 64
|
||||
const WEBSOCKET_OPEN = 1
|
||||
const WEBSOCKET_CLOSING = 2
|
||||
const WEBSOCKET_CLOSED = 3
|
||||
|
||||
type HubState = 'connecting' | 'open' | 'closed' | 'failed'
|
||||
|
||||
const META_DECODER = new TextDecoder()
|
||||
const META_ENCODER = new TextEncoder()
|
||||
|
||||
export function encodeTerminalMetaFrame(cursor: number): Uint8Array<ArrayBuffer> {
|
||||
const payload = META_ENCODER.encode(JSON.stringify({ cursor }))
|
||||
const frame = new Uint8Array(new ArrayBuffer(payload.length + 1))
|
||||
frame[0] = META_FRAME_PREFIX
|
||||
frame.set(payload, 1)
|
||||
return frame
|
||||
}
|
||||
|
||||
export interface TerminalHubOptions {
|
||||
openUpstream: () => Promise<WebSocket>
|
||||
}
|
||||
|
||||
export class TerminalHub {
|
||||
private readonly decoder = new TextDecoder()
|
||||
private readonly subscribers = new Set<WebSocketPeer>()
|
||||
private readonly pendingInput: Array<string | Uint8Array<ArrayBuffer>> = []
|
||||
private socket: WebSocket | null = null
|
||||
private state: HubState = 'connecting'
|
||||
private attempts = 0
|
||||
private retryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
private pendingInputBytes = 0
|
||||
private buffer = ''
|
||||
private bufferStart = 0
|
||||
private cursor = 0
|
||||
|
||||
constructor(private readonly options: TerminalHubOptions) {}
|
||||
|
||||
start(): Promise<void> {
|
||||
return this.connect()
|
||||
}
|
||||
|
||||
isAvailable(): boolean {
|
||||
return this.state !== 'failed'
|
||||
}
|
||||
|
||||
isEnded(): boolean {
|
||||
return this.state === 'closed' || this.state === 'failed'
|
||||
}
|
||||
|
||||
attach(peer: WebSocketPeer, cursor: number | undefined): WebSocketBridge {
|
||||
this.replay(peer, cursor)
|
||||
if (this.state === 'closed') {
|
||||
this.closePeer(peer, 1000)
|
||||
return { send: () => {}, close: () => {} }
|
||||
}
|
||||
this.subscribers.add(peer)
|
||||
return {
|
||||
send: (data) => this.write(data),
|
||||
close: () => {
|
||||
this.subscribers.delete(peer)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.clearRetry()
|
||||
if (this.state !== 'failed') this.state = 'closed'
|
||||
const socket = this.socket
|
||||
this.socket = null
|
||||
closeSocketQuietly(socket)
|
||||
const peers = [...this.subscribers]
|
||||
this.subscribers.clear()
|
||||
for (const peer of peers) this.closePeer(peer, 1000)
|
||||
}
|
||||
|
||||
private async connect(): Promise<void> {
|
||||
if (this.state !== 'connecting') return
|
||||
this.attempts += 1
|
||||
let socket: WebSocket
|
||||
try {
|
||||
socket = await this.options.openUpstream()
|
||||
} catch {
|
||||
this.retryOrFail()
|
||||
return
|
||||
}
|
||||
if (this.state !== 'connecting') {
|
||||
closeSocketQuietly(socket)
|
||||
return
|
||||
}
|
||||
this.socket = socket
|
||||
socket.binaryType = 'arraybuffer'
|
||||
socket.addEventListener('open', () => this.handleOpen(socket))
|
||||
socket.addEventListener('message', (event) => this.handleMessage(event as MessageEvent))
|
||||
socket.addEventListener('close', () => this.handleUpstreamClosed(socket))
|
||||
socket.addEventListener('error', () => this.handleUpstreamError(socket))
|
||||
const readyState = (socket as { readyState?: number }).readyState
|
||||
if (readyState === WEBSOCKET_OPEN) {
|
||||
this.handleOpen(socket)
|
||||
return
|
||||
}
|
||||
if (readyState === WEBSOCKET_CLOSING || readyState === WEBSOCKET_CLOSED) {
|
||||
this.socket = null
|
||||
this.retryOrFail()
|
||||
}
|
||||
}
|
||||
|
||||
private handleOpen(socket: WebSocket): void {
|
||||
if (this.socket !== socket || this.state !== 'connecting') return
|
||||
this.state = 'open'
|
||||
while (this.pendingInput.length > 0) {
|
||||
const item = this.pendingInput.shift()!
|
||||
this.pendingInputBytes -= byteLengthOf(item)
|
||||
try {
|
||||
socket.send(item)
|
||||
} catch {
|
||||
this.endStream()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleMessage(event: MessageEvent): void {
|
||||
const data: unknown = event.data
|
||||
if (typeof data === 'string') {
|
||||
this.appendOutput(data)
|
||||
return
|
||||
}
|
||||
let bytes: Uint8Array
|
||||
if (data instanceof ArrayBuffer) {
|
||||
bytes = new Uint8Array(data)
|
||||
} else if (data instanceof Uint8Array) {
|
||||
bytes = data
|
||||
} else {
|
||||
return
|
||||
}
|
||||
if (bytes.length > 0 && bytes[0] === META_FRAME_PREFIX) {
|
||||
this.alignToCursor(bytes.subarray(1))
|
||||
return
|
||||
}
|
||||
this.appendOutput(this.decoder.decode(bytes, { stream: true }))
|
||||
}
|
||||
|
||||
private handleUpstreamError(socket: WebSocket): void {
|
||||
if (this.socket !== socket || this.state !== 'connecting') return
|
||||
this.socket = null
|
||||
closeSocketQuietly(socket)
|
||||
this.retryOrFail()
|
||||
}
|
||||
|
||||
private handleUpstreamClosed(socket: WebSocket): void {
|
||||
if (this.socket !== socket) return
|
||||
this.socket = null
|
||||
if (this.state === 'open') {
|
||||
this.endStream()
|
||||
return
|
||||
}
|
||||
if (this.state === 'connecting') this.retryOrFail()
|
||||
}
|
||||
|
||||
private retryOrFail(): void {
|
||||
if (this.state !== 'connecting') return
|
||||
if (this.attempts >= MAX_CONNECT_ATTEMPTS) {
|
||||
this.state = 'failed'
|
||||
return
|
||||
}
|
||||
this.clearRetry()
|
||||
this.retryTimer = setTimeout(() => {
|
||||
this.retryTimer = undefined
|
||||
void this.connect()
|
||||
}, RETRY_DELAY_MS)
|
||||
}
|
||||
|
||||
private clearRetry(): void {
|
||||
if (this.retryTimer === undefined) return
|
||||
clearTimeout(this.retryTimer)
|
||||
this.retryTimer = undefined
|
||||
}
|
||||
|
||||
private endStream(): void {
|
||||
if (this.state === 'closed') return
|
||||
this.state = 'closed'
|
||||
const peers = [...this.subscribers]
|
||||
this.subscribers.clear()
|
||||
for (const peer of peers) this.closePeer(peer, 1000)
|
||||
}
|
||||
|
||||
private alignToCursor(payload: Uint8Array): void {
|
||||
try {
|
||||
const parsed = JSON.parse(META_DECODER.decode(payload)) as { cursor?: unknown }
|
||||
if (typeof parsed.cursor !== 'number' || !Number.isSafeInteger(parsed.cursor)) return
|
||||
if (parsed.cursor < this.cursor) return
|
||||
this.cursor = parsed.cursor
|
||||
this.bufferStart = Math.max(0, parsed.cursor - this.buffer.length)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private appendOutput(chunk: string): void {
|
||||
if (chunk.length === 0) return
|
||||
this.cursor += chunk.length
|
||||
this.buffer += chunk
|
||||
const excess = this.buffer.length - BUFFER_LIMIT_CHARS
|
||||
if (excess > 0) {
|
||||
this.buffer = this.buffer.slice(excess)
|
||||
this.bufferStart += excess
|
||||
}
|
||||
for (const peer of [...this.subscribers]) this.deliver(peer, chunk)
|
||||
}
|
||||
|
||||
private replay(peer: WebSocketPeer, cursor: number | undefined): void {
|
||||
const from = this.replayStart(cursor)
|
||||
const offset = Math.max(0, from - this.bufferStart)
|
||||
const replay = offset < this.buffer.length ? this.buffer.slice(offset) : ''
|
||||
for (let index = 0; index < replay.length; index += REPLAY_CHUNK_CHARS) {
|
||||
this.deliver(peer, replay.slice(index, index + REPLAY_CHUNK_CHARS))
|
||||
}
|
||||
this.deliver(peer, encodeTerminalMetaFrame(this.cursor))
|
||||
}
|
||||
|
||||
private replayStart(cursor: number | undefined): number {
|
||||
if (cursor === -1) return this.cursor
|
||||
if (cursor === undefined) return this.bufferStart
|
||||
return Math.max(cursor, this.bufferStart)
|
||||
}
|
||||
|
||||
private write(data: string | ArrayBuffer | Uint8Array<ArrayBuffer>): void {
|
||||
if (this.state === 'closed' || this.state === 'failed') return
|
||||
const payload: string | Uint8Array<ArrayBuffer> =
|
||||
typeof data === 'string' ? data : data instanceof Uint8Array ? data : new Uint8Array(data)
|
||||
if (this.state === 'open' && this.socket) {
|
||||
try {
|
||||
this.socket.send(payload)
|
||||
} catch {
|
||||
this.endStream()
|
||||
}
|
||||
return
|
||||
}
|
||||
this.pendingInput.push(payload)
|
||||
this.pendingInputBytes += byteLengthOf(payload)
|
||||
while (this.pendingInputBytes > MAX_UPSTREAM_BUFFERED_BYTES && this.pendingInput.length > 0) {
|
||||
const dropped = this.pendingInput.shift()!
|
||||
this.pendingInputBytes -= byteLengthOf(dropped)
|
||||
}
|
||||
}
|
||||
|
||||
private deliver(peer: WebSocketPeer, data: string | Uint8Array<ArrayBuffer>): void {
|
||||
try {
|
||||
peer.send(data)
|
||||
} catch {
|
||||
this.subscribers.delete(peer)
|
||||
return
|
||||
}
|
||||
if (peer.bufferedAmount() > MAX_PEER_BUFFERED_BYTES) {
|
||||
this.subscribers.delete(peer)
|
||||
this.closePeer(peer, 1013, 'Client too slow')
|
||||
}
|
||||
}
|
||||
|
||||
private closePeer(peer: WebSocketPeer, code: number, reason?: string): void {
|
||||
try {
|
||||
peer.close(code, reason)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function closeSocketQuietly(socket: { close: () => void } | null | undefined): void {
|
||||
if (!socket) return
|
||||
try {
|
||||
socket.close()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function byteLengthOf(data: string | Uint8Array<ArrayBuffer>): number {
|
||||
return typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength
|
||||
}
|
||||
|
||||
export class TerminalHubRegistry {
|
||||
private readonly hubs = new Map<string, TerminalHub>()
|
||||
|
||||
get(key: string): TerminalHub | undefined {
|
||||
return this.hubs.get(key)
|
||||
}
|
||||
|
||||
register(key: string, hub: TerminalHub): void {
|
||||
if (this.hubs.has(key)) {
|
||||
hub.dispose()
|
||||
return
|
||||
}
|
||||
if (this.hubs.size >= MAX_REGISTERED_HUBS && !this.evict()) {
|
||||
hub.dispose()
|
||||
return
|
||||
}
|
||||
this.hubs.set(key, hub)
|
||||
}
|
||||
|
||||
dispose(key: string): void {
|
||||
const hub = this.hubs.get(key)
|
||||
if (!hub) return
|
||||
this.hubs.delete(key)
|
||||
hub.dispose()
|
||||
}
|
||||
|
||||
private evict(): boolean {
|
||||
const target = [...this.hubs.entries()].find(([, hub]) => hub.isEnded())
|
||||
if (!target) return false
|
||||
this.hubs.delete(target[0])
|
||||
target[1].dispose()
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import type { OpenCodeClient } from './opencode/client'
|
||||
import type { CredentialProvider } from './credential-provider'
|
||||
import { toWebSocketUrl } from './opencode/upstream'
|
||||
import { bridgeWebSocket, type WebSocketBridge, type WebSocketPeer } from '../utils/websocket-bridge'
|
||||
import { TerminalHub, TerminalHubRegistry } from './terminal-hub'
|
||||
|
||||
type OpenCodePty = Awaited<ReturnType<OpenCodeClient['api']['pty']['list']>>['data'][number]
|
||||
type OpenCodePersistentPty = Awaited<ReturnType<OpenCodeClient['api']['experimental']['persistentPty']['list']>>[number]
|
||||
@@ -36,15 +37,28 @@ export class TerminalNotFoundError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
const DEFERRED_START_SHELL = '/bin/sh'
|
||||
const DEFERRED_START_SCRIPT = 'sleep 0.3; exec "$@"'
|
||||
const DEFERRED_START_HANDLE = 'ocm-terminal'
|
||||
const DEFERRED_START_KINDS: ReadonlySet<TerminalKind> = new Set(['action', 'setup'])
|
||||
|
||||
function deferCommandStart(command: string, args: readonly string[]): { command: string; args: string[] } {
|
||||
return {
|
||||
command: DEFERRED_START_SHELL,
|
||||
args: ['-c', DEFERRED_START_SCRIPT, DEFERRED_START_HANDLE, command, ...args],
|
||||
}
|
||||
}
|
||||
|
||||
export class TerminalService {
|
||||
constructor(
|
||||
private readonly target: TerminalTarget,
|
||||
private readonly credentialProvider: CredentialProvider,
|
||||
private readonly openSocket: (url: string) => WebSocket = (url) => new WebSocket(url),
|
||||
private readonly hubs: TerminalHubRegistry = new TerminalHubRegistry(),
|
||||
) {}
|
||||
|
||||
forTarget(target: TerminalTarget): TerminalService {
|
||||
return new TerminalService(target, this.credentialProvider, this.openSocket)
|
||||
return new TerminalService(target, this.credentialProvider, this.openSocket, this.hubs)
|
||||
}
|
||||
|
||||
async list(directory: string): Promise<TerminalInfo[]> {
|
||||
@@ -53,17 +67,39 @@ export class TerminalService {
|
||||
}
|
||||
|
||||
async create(directory: string, input: CreateTerminalInput): Promise<TerminalInfo> {
|
||||
const deferred =
|
||||
input.command !== undefined && DEFERRED_START_KINDS.has(input.kind) && process.platform !== 'win32'
|
||||
? deferCommandStart(input.command, input.args ?? [])
|
||||
: undefined
|
||||
const result = await this.target.client.api.pty.create({
|
||||
location: { directory },
|
||||
title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }),
|
||||
...(input.command !== undefined ? { command: input.command } : {}),
|
||||
...(input.args !== undefined ? { args: input.args } : {}),
|
||||
...(deferred
|
||||
? { command: deferred.command, args: deferred.args }
|
||||
: {
|
||||
...(input.command !== undefined ? { command: input.command } : {}),
|
||||
...(input.args !== undefined ? { args: input.args } : {}),
|
||||
}),
|
||||
env: {
|
||||
...(this.target.includeLocalCredentials ? this.credentialProvider.getGhCliEnv({ cwd: directory }) : {}),
|
||||
...input.env,
|
||||
},
|
||||
})
|
||||
return this.toTerminalInfo(result.data)
|
||||
const terminal = this.toTerminalInfo(result.data)
|
||||
this.recordTerminal(directory, terminal.id)
|
||||
return terminal
|
||||
}
|
||||
|
||||
private recordTerminal(directory: string, ptyID: string): void {
|
||||
const key = this.hubKey(directory, ptyID)
|
||||
if (this.hubs.get(key)) return
|
||||
const hub = new TerminalHub({ openUpstream: () => this.openUpstreamSocket(directory, ptyID, 0) })
|
||||
this.hubs.register(key, hub)
|
||||
void hub.start()
|
||||
}
|
||||
|
||||
private hubKey(directory: string, ptyID: string): string {
|
||||
return `${this.target.baseUrl()}\u0000${directory}\u0000${ptyID}`
|
||||
}
|
||||
|
||||
async requireTerminal(directory: string, ptyID: string): Promise<TerminalInfo> {
|
||||
@@ -80,7 +116,11 @@ export class TerminalService {
|
||||
}
|
||||
|
||||
async remove(directory: string, ptyID: string): Promise<void> {
|
||||
await this.target.client.api.pty.remove({ ptyID, location: { directory } })
|
||||
try {
|
||||
await this.target.client.api.pty.remove({ ptyID, location: { directory } })
|
||||
} finally {
|
||||
this.hubs.dispose(this.hubKey(directory, ptyID))
|
||||
}
|
||||
}
|
||||
|
||||
async removeAll(directory: string): Promise<void> {
|
||||
@@ -104,6 +144,19 @@ export class TerminalService {
|
||||
): Promise<WebSocketBridge> {
|
||||
await this.requireTerminal(directory, ptyID)
|
||||
|
||||
const key = this.hubKey(directory, ptyID)
|
||||
const hub = this.hubs.get(key)
|
||||
if (hub?.isAvailable()) return hub.attach(peer, cursor)
|
||||
if (hub) this.hubs.dispose(key)
|
||||
|
||||
return bridgeWebSocket(await this.openUpstreamSocket(directory, ptyID, cursor), peer)
|
||||
}
|
||||
|
||||
private async openUpstreamSocket(
|
||||
directory: string,
|
||||
ptyID: string,
|
||||
cursor: number | undefined,
|
||||
): Promise<WebSocket> {
|
||||
const result = await this.target.client.api.pty.connect.token({
|
||||
ptyID,
|
||||
location: { directory },
|
||||
@@ -117,7 +170,7 @@ export class TerminalService {
|
||||
socketUrl.searchParams.set('location[directory]', directory)
|
||||
if (cursor !== undefined) socketUrl.searchParams.set('cursor', String(cursor))
|
||||
|
||||
return bridgeWebSocket(this.openSocket(toWebSocketUrl(socketUrl.toString())), peer)
|
||||
return this.openSocket(toWebSocketUrl(socketUrl.toString()))
|
||||
}
|
||||
|
||||
private async removePersistentTerminals(directory: string): Promise<void> {
|
||||
|
||||
Reference in new issue
Block a user