mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-19 03:40:50 +00:00
fix(hub,cli): keep inactive file previews available through runner (#1727)
* fix(hub,cli): keep inactive file previews available through runner * fix(cli): bound runner workspace file reads * fix(cli): constrain runner git fallback pathspecs * fix(cli): allow dot-prefixed workspace paths
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { basename, extname } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { constants } from 'node:fs'
|
||||
import { open } from 'node:fs/promises'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { asString, isObject } from '@hapi/protocol'
|
||||
@@ -8,10 +9,14 @@ import { asString, isObject } from '@hapi/protocol'
|
||||
* Read a regular file through one open descriptor: size is taken from the fd
|
||||
* (not a separate pathname `lstat`), then the buffer is allocated to that size
|
||||
* only. Rejects if the file grows/shrinks while reading so a TOCTOU swap cannot
|
||||
* force an unbounded `readFile` allocation.
|
||||
* force an unbounded `readFile` allocation. Non-blocking open prevents a FIFO
|
||||
* or other special file from hanging the caller before its type can be checked.
|
||||
*/
|
||||
export async function readBoundedRegularFile(path: string, maxBytes: number): Promise<Buffer> {
|
||||
const handle = await open(path, 'r')
|
||||
const flags = process.platform === 'win32'
|
||||
? 'r'
|
||||
: constants.O_RDONLY | constants.O_NONBLOCK
|
||||
const handle = await open(path, flags)
|
||||
try {
|
||||
const info = await handle.stat()
|
||||
if (!info.isFile()) {
|
||||
|
||||
@@ -45,7 +45,7 @@ function validateFilePath(filePath: string, workingDirectory: string): string |
|
||||
return null
|
||||
}
|
||||
|
||||
async function runGitCommand(
|
||||
export async function runGitCommand(
|
||||
args: string[],
|
||||
cwd: string,
|
||||
timeout?: number
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { execFile } from 'node:child_process'
|
||||
import { mkdir, mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods'
|
||||
import { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager'
|
||||
import { MachinePathPolicy } from '@/api/machinePathPolicy'
|
||||
import { MAX_WORKSPACE_FILE_BYTES, registerWorkspaceFileHandlers, type WorkspaceFilePathPolicy } from './workspaceFileHandlers'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
async function callWorkspaceHandler(
|
||||
rpc: RpcHandlerManager,
|
||||
method: string,
|
||||
params: unknown,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const response = await rpc.handleRequest({
|
||||
method: `machine-test:${method}`,
|
||||
params: JSON.stringify(params),
|
||||
})
|
||||
return JSON.parse(response) as Record<string, unknown>
|
||||
}
|
||||
|
||||
describe('workspace file RPC handlers', () => {
|
||||
let rootDir: string
|
||||
let rpc: RpcHandlerManager
|
||||
|
||||
beforeEach(async () => {
|
||||
rootDir = await mkdtemp(join(tmpdir(), 'hapi-workspace-file-handler-'))
|
||||
await mkdir(join(rootDir, 'src'))
|
||||
await writeFile(join(rootDir, 'src', 'index.ts'), 'export const answer = 42\n')
|
||||
await writeFile(join(rootDir, '.env.example'), 'EXAMPLE=true\n')
|
||||
|
||||
rpc = new RpcHandlerManager({ scopePrefix: 'machine-test' })
|
||||
const pathPolicy = new MachinePathPolicy({ workspaceRoots: [rootDir] })
|
||||
registerWorkspaceFileHandlers(rpc, pathPolicy)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(rootDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('registers all read-only workspace operations on the machine scope', () => {
|
||||
expect(rpc.hasHandler(RPC_METHODS.WorkspaceReadFile)).toBe(true)
|
||||
expect(rpc.hasHandler(RPC_METHODS.WorkspaceListDirectory)).toBe(true)
|
||||
expect(rpc.hasHandler(RPC_METHODS.WorkspaceStatFiles)).toBe(true)
|
||||
expect(rpc.hasHandler(RPC_METHODS.WorkspaceGitStatus)).toBe(true)
|
||||
expect(rpc.hasHandler(RPC_METHODS.WorkspaceGitDiffNumstat)).toBe(true)
|
||||
expect(rpc.hasHandler(RPC_METHODS.WorkspaceGitDiffFile)).toBe(true)
|
||||
expect(rpc.hasHandler(RPC_METHODS.WorkspaceRipgrep)).toBe(true)
|
||||
})
|
||||
|
||||
it('lists, reads, and stats files beneath the requested workspace', async () => {
|
||||
const list = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceListDirectory, {
|
||||
cwd: rootDir,
|
||||
path: '',
|
||||
})
|
||||
expect(list.success).toBe(true)
|
||||
expect((list.entries as Array<{ name: string }>).map((entry) => entry.name).sort()).toEqual([
|
||||
'.env.example',
|
||||
'src',
|
||||
])
|
||||
|
||||
const read = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceReadFile, {
|
||||
cwd: rootDir,
|
||||
path: 'src/index.ts',
|
||||
})
|
||||
expect(read).toMatchObject({
|
||||
success: true,
|
||||
content: Buffer.from('export const answer = 42\n').toString('base64'),
|
||||
size: 25,
|
||||
})
|
||||
expect(read.modified).toEqual(expect.any(Number))
|
||||
|
||||
const stats = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceStatFiles, {
|
||||
cwd: rootDir,
|
||||
paths: ['src/index.ts', 'missing.ts'],
|
||||
})
|
||||
expect(stats).toMatchObject({
|
||||
success: true,
|
||||
entries: [
|
||||
{ path: 'src/index.ts', size: 25 },
|
||||
{ path: 'missing.ts' },
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects oversized and non-regular files before reading them', async () => {
|
||||
const oversizedPath = join(rootDir, 'oversized.bin')
|
||||
await writeFile(oversizedPath, '')
|
||||
await truncate(oversizedPath, MAX_WORKSPACE_FILE_BYTES + 1)
|
||||
|
||||
const oversized = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceReadFile, {
|
||||
cwd: rootDir,
|
||||
path: 'oversized.bin',
|
||||
})
|
||||
expect(oversized).toEqual({ success: false, error: 'File is too large to display inline' })
|
||||
|
||||
const directoryPath = join(rootDir, 'not-a-file')
|
||||
await mkdir(directoryPath)
|
||||
const directory = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceReadFile, {
|
||||
cwd: rootDir,
|
||||
path: 'not-a-file',
|
||||
})
|
||||
expect(directory).toEqual({ success: false, error: 'Path is not a regular file' })
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
const fifoPath = join(rootDir, 'named-pipe')
|
||||
await execFileAsync('mkfifo', [fifoPath])
|
||||
const fifo = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceReadFile, {
|
||||
cwd: rootDir,
|
||||
path: 'named-pipe',
|
||||
})
|
||||
expect(fifo).toEqual({ success: false, error: 'Path is not a regular file' })
|
||||
}
|
||||
})
|
||||
|
||||
it('passes workspace paths to the runner policy without trimming them', async () => {
|
||||
const checkedPaths: string[] = []
|
||||
const pathPolicy: WorkspaceFilePathPolicy = {
|
||||
resolveForCheck: async (path) => {
|
||||
checkedPaths.push(path)
|
||||
return rootDir
|
||||
},
|
||||
isWithinSpawnRoots: () => true,
|
||||
}
|
||||
rpc = new RpcHandlerManager({ scopePrefix: 'machine-test' })
|
||||
registerWorkspaceFileHandlers(rpc, pathPolicy)
|
||||
|
||||
const workspacePath = `${rootDir} `
|
||||
const result = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceListDirectory, {
|
||||
cwd: workspacePath,
|
||||
path: '',
|
||||
})
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
expect(checkedPaths[0]).toBe(workspacePath)
|
||||
})
|
||||
|
||||
it('allows valid workspace paths beginning with two dots', async () => {
|
||||
await writeFile(join(rootDir, '..notes.txt'), 'notes\n')
|
||||
await mkdir(join(rootDir, '..assets'))
|
||||
await writeFile(join(rootDir, '..assets', 'file.txt'), 'asset\n')
|
||||
|
||||
const note = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceReadFile, {
|
||||
cwd: rootDir,
|
||||
path: '..notes.txt',
|
||||
})
|
||||
expect(note).toMatchObject({
|
||||
success: true,
|
||||
content: Buffer.from('notes\n').toString('base64'),
|
||||
})
|
||||
|
||||
const asset = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceReadFile, {
|
||||
cwd: rootDir,
|
||||
path: '..assets/file.txt',
|
||||
})
|
||||
expect(asset).toMatchObject({
|
||||
success: true,
|
||||
content: Buffer.from('asset\n').toString('base64'),
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects workspace roots outside the runner allowlist', async () => {
|
||||
const outsideDir = await mkdtemp(join(tmpdir(), 'hapi-workspace-file-outside-'))
|
||||
try {
|
||||
await writeFile(join(outsideDir, 'secret.txt'), 'secret')
|
||||
const result = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceReadFile, {
|
||||
cwd: outsideDir,
|
||||
path: 'secret.txt',
|
||||
})
|
||||
expect(result).toEqual({ success: false, error: 'Path is outside workspace roots' })
|
||||
} finally {
|
||||
await rm(outsideDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects file paths that escape the session workspace', async () => {
|
||||
const outsideFile = join(tmpdir(), `hapi-workspace-file-secret-${Date.now()}.txt`)
|
||||
await writeFile(outsideFile, 'secret')
|
||||
try {
|
||||
rpc = new RpcHandlerManager({ scopePrefix: 'machine-test' })
|
||||
registerWorkspaceFileHandlers(rpc, new MachinePathPolicy({ workspaceRoots: [tmpdir()] }))
|
||||
const result = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceReadFile, {
|
||||
cwd: rootDir,
|
||||
path: `../${outsideFile.split(/[\\/]/).pop()}`,
|
||||
})
|
||||
expect(result).toEqual({ success: false, error: 'Path is outside the session workspace' })
|
||||
} finally {
|
||||
await rm(outsideFile, { force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('runs Git and ripgrep against the requested workspace without a session CLI', async () => {
|
||||
await execFileAsync('git', ['init', '-q'], { cwd: rootDir })
|
||||
await execFileAsync('git', ['add', '.'], { cwd: rootDir })
|
||||
await execFileAsync('git', [
|
||||
'-c', 'user.name=HAPI test',
|
||||
'-c', 'user.email=hapi-test@example.invalid',
|
||||
'commit', '-qm', 'initial'
|
||||
], { cwd: rootDir })
|
||||
await writeFile(join(rootDir, 'src', 'index.ts'), 'export const answer = 43\n')
|
||||
|
||||
const status = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceGitStatus, { cwd: rootDir })
|
||||
expect(status).toMatchObject({ success: true })
|
||||
expect(status.stdout).toContain('src/index.ts')
|
||||
|
||||
const diffNumstat = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceGitDiffNumstat, {
|
||||
cwd: rootDir,
|
||||
staged: false,
|
||||
})
|
||||
expect(diffNumstat).toMatchObject({ success: true })
|
||||
expect(diffNumstat.stdout).toContain('src/index.ts')
|
||||
|
||||
const diffFile = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceGitDiffFile, {
|
||||
cwd: rootDir,
|
||||
filePath: 'src/index.ts',
|
||||
staged: false,
|
||||
})
|
||||
expect(diffFile).toMatchObject({ success: true })
|
||||
expect(diffFile.stdout).toContain('diff --git')
|
||||
|
||||
const ripgrep = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceRipgrep, {
|
||||
cwd: rootDir,
|
||||
args: ['--files'],
|
||||
fileSearch: { query: 'src/*.ts', limit: 10 },
|
||||
})
|
||||
expect(ripgrep).toMatchObject({ success: true })
|
||||
expect(String(ripgrep.stdout).replaceAll('\\', '/')).toContain('src/index.ts')
|
||||
})
|
||||
|
||||
it('keeps Git fallback operations inside a nested session workspace', async () => {
|
||||
const workspaceDir = join(rootDir, 'nested-workspace')
|
||||
await mkdir(workspaceDir)
|
||||
await writeFile(join(rootDir, 'sibling.txt'), 'sibling initial\n')
|
||||
await writeFile(join(workspaceDir, 'inside.txt'), 'inside initial\n')
|
||||
|
||||
await execFileAsync('git', ['init', '-q'], { cwd: rootDir })
|
||||
await execFileAsync('git', ['add', '.'], { cwd: rootDir })
|
||||
await execFileAsync('git', [
|
||||
'-c', 'user.name=HAPI test',
|
||||
'-c', 'user.email=hapi-test@example.invalid',
|
||||
'commit', '-qm', 'initial'
|
||||
], { cwd: rootDir })
|
||||
|
||||
await writeFile(join(rootDir, 'sibling.txt'), 'sibling changed\n')
|
||||
await writeFile(join(workspaceDir, 'inside.txt'), 'inside changed\n')
|
||||
|
||||
const status = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceGitStatus, { cwd: workspaceDir })
|
||||
expect(status).toMatchObject({ success: true })
|
||||
expect(String(status.stdout)).toContain('inside.txt')
|
||||
expect(String(status.stdout)).not.toContain('sibling.txt')
|
||||
|
||||
const unstagedNumstat = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceGitDiffNumstat, {
|
||||
cwd: workspaceDir,
|
||||
staged: false,
|
||||
})
|
||||
expect(unstagedNumstat).toMatchObject({ success: true })
|
||||
expect(String(unstagedNumstat.stdout)).toContain('inside.txt')
|
||||
expect(String(unstagedNumstat.stdout)).not.toContain('sibling.txt')
|
||||
|
||||
await execFileAsync('git', ['add', join('nested-workspace', 'inside.txt')], { cwd: rootDir })
|
||||
await writeFile(join(workspaceDir, 'inside.txt'), 'inside staged and changed\n')
|
||||
const stagedNumstat = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceGitDiffNumstat, {
|
||||
cwd: workspaceDir,
|
||||
staged: true,
|
||||
})
|
||||
expect(stagedNumstat).toMatchObject({ success: true })
|
||||
expect(String(stagedNumstat.stdout)).toContain('inside.txt')
|
||||
expect(String(stagedNumstat.stdout)).not.toContain('sibling.txt')
|
||||
|
||||
const insideDiff = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceGitDiffFile, {
|
||||
cwd: workspaceDir,
|
||||
filePath: 'inside.txt',
|
||||
staged: false,
|
||||
})
|
||||
expect(insideDiff).toMatchObject({ success: true })
|
||||
expect(String(insideDiff.stdout)).toContain('inside staged and changed')
|
||||
|
||||
for (const filePath of [':(top)sibling.txt', ':(exclude)sibling.txt']) {
|
||||
const escapedDiff = await callWorkspaceHandler(rpc, RPC_METHODS.WorkspaceGitDiffFile, {
|
||||
cwd: workspaceDir,
|
||||
filePath,
|
||||
staged: false,
|
||||
})
|
||||
expect(escapedDiff).toMatchObject({ success: true })
|
||||
expect(String(escapedDiff.stdout)).not.toContain('sibling changed')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,342 @@
|
||||
import { readdir, stat } from 'node:fs/promises'
|
||||
import { isAbsolute, join, relative, resolve, sep } from 'node:path'
|
||||
import type {
|
||||
CommandResponse,
|
||||
DirectoryEntry,
|
||||
FileReadResponse,
|
||||
ListDirectoryResponse,
|
||||
StatFilesResponse,
|
||||
} from '@hapi/protocol/apiTypes'
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods'
|
||||
import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager'
|
||||
import { runGitCommand } from './handlers/git'
|
||||
import { run as runRipgrep, runFileSearch, type FileSearchOptions } from '@/modules/ripgrep/index'
|
||||
import { MAX_GENERATED_IMAGE_BYTES, readBoundedRegularFile } from './generatedImages'
|
||||
import { getErrorMessage, rpcError } from './rpcResponses'
|
||||
|
||||
/**
|
||||
* The runner is the authority for resolving and enforcing workspace paths.
|
||||
* Keeping this interface small lets the machine client own the policy while
|
||||
* these handlers remain focused on read-only file operations.
|
||||
*/
|
||||
export type WorkspaceFilePathPolicy = {
|
||||
resolveForCheck: (path: string) => Promise<string>
|
||||
isWithinSpawnRoots: (path: string) => boolean
|
||||
}
|
||||
|
||||
type WorkspaceReadFileRequest = {
|
||||
cwd?: unknown
|
||||
path?: unknown
|
||||
}
|
||||
|
||||
type WorkspaceListDirectoryRequest = {
|
||||
cwd?: unknown
|
||||
path?: unknown
|
||||
}
|
||||
|
||||
type WorkspaceStatFilesRequest = {
|
||||
cwd?: unknown
|
||||
paths?: unknown
|
||||
}
|
||||
|
||||
type WorkspaceGitStatusRequest = {
|
||||
cwd?: unknown
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
type WorkspaceGitDiffNumstatRequest = {
|
||||
cwd?: unknown
|
||||
staged?: boolean
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
type WorkspaceGitDiffFileRequest = {
|
||||
cwd?: unknown
|
||||
filePath?: unknown
|
||||
staged?: boolean
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
type WorkspaceRipgrepRequest = {
|
||||
cwd?: unknown
|
||||
args?: unknown
|
||||
fileSearch?: FileSearchOptions
|
||||
}
|
||||
|
||||
type ResolvedWorkspaceCwd = { cwd: string } | { error: string }
|
||||
type ResolvedWorkspacePath = { cwd: string; path: string } | { error: string }
|
||||
|
||||
const OUTSIDE_WORKSPACE_ERROR = 'Path is outside workspace roots'
|
||||
const OUTSIDE_SESSION_WORKSPACE_ERROR = 'Path is outside the session workspace'
|
||||
export const MAX_WORKSPACE_FILE_BYTES = MAX_GENERATED_IMAGE_BYTES
|
||||
|
||||
function isWithinRoot(root: string, target: string): boolean {
|
||||
const child = relative(root, target)
|
||||
return child === '' || (child !== '..' && !child.startsWith(`..${sep}`) && !isAbsolute(child))
|
||||
}
|
||||
|
||||
async function resolveWorkspaceCwd(
|
||||
pathPolicy: WorkspaceFilePathPolicy,
|
||||
value: unknown,
|
||||
): Promise<ResolvedWorkspaceCwd> {
|
||||
const raw = typeof value === 'string' ? value : ''
|
||||
if (!raw) {
|
||||
return { error: 'Workspace path is required' }
|
||||
}
|
||||
|
||||
const cwd = await pathPolicy.resolveForCheck(raw)
|
||||
if (!pathPolicy.isWithinSpawnRoots(cwd)) {
|
||||
return { error: OUTSIDE_WORKSPACE_ERROR }
|
||||
}
|
||||
|
||||
return { cwd }
|
||||
}
|
||||
|
||||
async function resolveWorkspacePath(
|
||||
pathPolicy: WorkspaceFilePathPolicy,
|
||||
cwdValue: unknown,
|
||||
pathValue: unknown,
|
||||
options?: { allowEmptyPath?: boolean },
|
||||
): Promise<ResolvedWorkspacePath> {
|
||||
const cwd = await resolveWorkspaceCwd(pathPolicy, cwdValue)
|
||||
if ('error' in cwd) {
|
||||
return cwd
|
||||
}
|
||||
|
||||
const rawPath = typeof pathValue === 'string' ? pathValue : ''
|
||||
if (!options?.allowEmptyPath && !rawPath) {
|
||||
return { error: 'Path is required' }
|
||||
}
|
||||
|
||||
const path = await pathPolicy.resolveForCheck(resolve(cwd.cwd, rawPath || '.'))
|
||||
if (!pathPolicy.isWithinSpawnRoots(path)) {
|
||||
return { error: OUTSIDE_WORKSPACE_ERROR }
|
||||
}
|
||||
if (!isWithinRoot(cwd.cwd, path)) {
|
||||
return { error: OUTSIDE_SESSION_WORKSPACE_ERROR }
|
||||
}
|
||||
|
||||
return { cwd: cwd.cwd, path }
|
||||
}
|
||||
|
||||
async function listDirectory(path: string): Promise<ListDirectoryResponse> {
|
||||
const entries = await readdir(path, { withFileTypes: true })
|
||||
const directoryEntries: DirectoryEntry[] = await Promise.all(
|
||||
entries.map(async (entry) => {
|
||||
const fullPath = join(path, entry.name)
|
||||
let type: DirectoryEntry['type'] = 'other'
|
||||
let size: number | undefined
|
||||
let modified: number | undefined
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
type = 'directory'
|
||||
} else if (entry.isFile()) {
|
||||
type = 'file'
|
||||
}
|
||||
|
||||
if (!entry.isSymbolicLink()) {
|
||||
try {
|
||||
const stats = await stat(fullPath)
|
||||
size = stats.size
|
||||
modified = stats.mtime.getTime()
|
||||
} catch {
|
||||
// Keep the entry visible even when metadata is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
return { name: entry.name, type, size, modified }
|
||||
}),
|
||||
)
|
||||
|
||||
directoryEntries.sort((left, right) => {
|
||||
if (left.type === 'directory' && right.type !== 'directory') return -1
|
||||
if (left.type !== 'directory' && right.type === 'directory') return 1
|
||||
return left.name.localeCompare(right.name)
|
||||
})
|
||||
|
||||
return { success: true, entries: directoryEntries }
|
||||
}
|
||||
|
||||
/**
|
||||
* Register read-only workspace operations on the machine-scoped runner
|
||||
* socket. These are deliberately separate from session-scoped RPCs so an
|
||||
* inactive session can still inspect its current workspace while its CLI is
|
||||
* no longer connected.
|
||||
*/
|
||||
export function registerWorkspaceFileHandlers(
|
||||
rpcHandlerManager: RpcHandlerManager,
|
||||
pathPolicy: WorkspaceFilePathPolicy,
|
||||
): void {
|
||||
rpcHandlerManager.registerHandler<WorkspaceReadFileRequest, FileReadResponse>(
|
||||
RPC_METHODS.WorkspaceReadFile,
|
||||
async (data) => {
|
||||
const resolved = await resolveWorkspacePath(pathPolicy, data.cwd, data.path)
|
||||
if ('error' in resolved) {
|
||||
return rpcError(resolved.error)
|
||||
}
|
||||
|
||||
try {
|
||||
const stats = await stat(resolved.path)
|
||||
if (!stats.isFile()) {
|
||||
throw new Error('Path is not a regular file')
|
||||
}
|
||||
const buffer = await readBoundedRegularFile(resolved.path, MAX_WORKSPACE_FILE_BYTES)
|
||||
return {
|
||||
success: true,
|
||||
content: buffer.toString('base64'),
|
||||
size: stats.size,
|
||||
modified: stats.mtime.getTime(),
|
||||
}
|
||||
} catch (error) {
|
||||
return rpcError(getErrorMessage(error, 'Failed to read file'))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
rpcHandlerManager.registerHandler<WorkspaceListDirectoryRequest, ListDirectoryResponse>(
|
||||
RPC_METHODS.WorkspaceListDirectory,
|
||||
async (data) => {
|
||||
const resolved = await resolveWorkspacePath(pathPolicy, data.cwd, data.path, { allowEmptyPath: true })
|
||||
if ('error' in resolved) {
|
||||
return rpcError(resolved.error)
|
||||
}
|
||||
|
||||
try {
|
||||
return await listDirectory(resolved.path)
|
||||
} catch (error) {
|
||||
return rpcError(getErrorMessage(error, 'Failed to list directory'))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
rpcHandlerManager.registerHandler<WorkspaceStatFilesRequest, StatFilesResponse>(
|
||||
RPC_METHODS.WorkspaceStatFiles,
|
||||
async (data) => {
|
||||
if (!Array.isArray(data.paths) || data.paths.length > 500) {
|
||||
return rpcError('Invalid file paths')
|
||||
}
|
||||
if (!data.paths.every((path): path is string => typeof path === 'string')) {
|
||||
return rpcError('Invalid file paths')
|
||||
}
|
||||
|
||||
const cwd = await resolveWorkspaceCwd(pathPolicy, data.cwd)
|
||||
if ('error' in cwd) {
|
||||
return rpcError(cwd.error)
|
||||
}
|
||||
|
||||
const resolvedPaths: Array<{ requested: string; path: string }> = []
|
||||
for (const requested of data.paths) {
|
||||
const path = await pathPolicy.resolveForCheck(resolve(cwd.cwd, requested))
|
||||
if (!pathPolicy.isWithinSpawnRoots(path)) {
|
||||
return rpcError(OUTSIDE_WORKSPACE_ERROR)
|
||||
}
|
||||
if (!isWithinRoot(cwd.cwd, path)) {
|
||||
return rpcError(OUTSIDE_SESSION_WORKSPACE_ERROR)
|
||||
}
|
||||
resolvedPaths.push({ requested, path })
|
||||
}
|
||||
|
||||
const entries = await Promise.all(resolvedPaths.map(async ({ requested, path }) => {
|
||||
try {
|
||||
const stats = await stat(path)
|
||||
return {
|
||||
path: requested,
|
||||
size: stats.size,
|
||||
modified: stats.mtime.getTime(),
|
||||
}
|
||||
} catch {
|
||||
return { path: requested }
|
||||
}
|
||||
}))
|
||||
|
||||
return { success: true, entries }
|
||||
},
|
||||
)
|
||||
|
||||
rpcHandlerManager.registerHandler<WorkspaceGitStatusRequest, CommandResponse>(
|
||||
RPC_METHODS.WorkspaceGitStatus,
|
||||
async (data) => {
|
||||
const resolved = await resolveWorkspaceCwd(pathPolicy, data.cwd)
|
||||
if ('error' in resolved) {
|
||||
return rpcError(resolved.error)
|
||||
}
|
||||
|
||||
try {
|
||||
return await runGitCommand(
|
||||
['status', '--porcelain=v2', '--branch', '--untracked-files=all', '--', '.'],
|
||||
resolved.cwd,
|
||||
data.timeout,
|
||||
)
|
||||
} catch (error) {
|
||||
return rpcError(getErrorMessage(error, 'Command failed'))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
rpcHandlerManager.registerHandler<WorkspaceGitDiffNumstatRequest, CommandResponse>(
|
||||
RPC_METHODS.WorkspaceGitDiffNumstat,
|
||||
async (data) => {
|
||||
const resolved = await resolveWorkspaceCwd(pathPolicy, data.cwd)
|
||||
if ('error' in resolved) {
|
||||
return rpcError(resolved.error)
|
||||
}
|
||||
|
||||
const args = data.staged
|
||||
? ['diff', '--cached', '--numstat', '--', '.']
|
||||
: ['diff', '--numstat', '--', '.']
|
||||
try {
|
||||
return await runGitCommand(args, resolved.cwd, data.timeout)
|
||||
} catch (error) {
|
||||
return rpcError(getErrorMessage(error, 'Command failed'))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
rpcHandlerManager.registerHandler<WorkspaceGitDiffFileRequest, CommandResponse>(
|
||||
RPC_METHODS.WorkspaceGitDiffFile,
|
||||
async (data) => {
|
||||
const filePath = typeof data.filePath === 'string' ? data.filePath : ''
|
||||
const resolved = await resolveWorkspacePath(pathPolicy, data.cwd, filePath)
|
||||
if ('error' in resolved) {
|
||||
return rpcError(resolved.error)
|
||||
}
|
||||
|
||||
const args = data.staged
|
||||
? ['--literal-pathspecs', 'diff', '--cached', '--no-ext-diff', '--', filePath]
|
||||
: ['--literal-pathspecs', 'diff', '--no-ext-diff', '--', filePath]
|
||||
try {
|
||||
return await runGitCommand(args, resolved.cwd, data.timeout)
|
||||
} catch (error) {
|
||||
return rpcError(getErrorMessage(error, 'Command failed'))
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
rpcHandlerManager.registerHandler<WorkspaceRipgrepRequest, CommandResponse>(
|
||||
RPC_METHODS.WorkspaceRipgrep,
|
||||
async (data) => {
|
||||
if (!Array.isArray(data.args) || !data.args.every((arg): arg is string => typeof arg === 'string')) {
|
||||
return rpcError('Invalid ripgrep arguments')
|
||||
}
|
||||
|
||||
const resolved = await resolveWorkspaceCwd(pathPolicy, data.cwd)
|
||||
if ('error' in resolved) {
|
||||
return rpcError(resolved.error)
|
||||
}
|
||||
|
||||
try {
|
||||
const result = data.fileSearch
|
||||
? await runFileSearch(data.args, { ...data.fileSearch, cwd: resolved.cwd })
|
||||
: await runRipgrep(data.args, { cwd: resolved.cwd })
|
||||
return {
|
||||
success: true,
|
||||
exitCode: result.exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
}
|
||||
} catch (error) {
|
||||
return rpcError(getErrorMessage(error, 'Failed to run ripgrep'))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user