From c2cf9b32a1d812ea39e510e6d4e223dc957c208f Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Thu, 23 Apr 2026 14:11:53 -0400 Subject: [PATCH] fix(ssh): register linked worktree paths with relay on connect (#994) --- src/main/ipc/ssh-relay-helpers.ts | 39 +++- src/main/ipc/ssh.ts | 2 +- src/main/ipc/worktree-remote.ts | 10 + src/relay/fs-handler-git-fallback.ts | 300 +++++++++++++++++++++++++++ src/relay/fs-handler-utils.ts | 24 +++ src/relay/fs-handler.ts | 20 +- 6 files changed, 386 insertions(+), 9 deletions(-) create mode 100644 src/relay/fs-handler-git-fallback.ts diff --git a/src/main/ipc/ssh-relay-helpers.ts b/src/main/ipc/ssh-relay-helpers.ts index 6aa30f966..95364c93d 100644 --- a/src/main/ipc/ssh-relay-helpers.ts +++ b/src/main/ipc/ssh-relay-helpers.ts @@ -32,16 +32,41 @@ import type { Store } from '../persistence' // session.registerRoot. This must be called after every relay deploy — both // initial connect and reconnection — because each deploy creates a fresh // RelayContext on the remote host. -export function registerRelayRoots( +// +// Registers repo roots first (synchronous notify), then discovers linked +// worktree paths via git.listWorktrees and registers those too. Linked +// worktrees can live anywhere on disk (e.g. /home/user/worktrees/feature-x) +// and would be rejected as "Path outside authorized workspace" without this. +export async function registerRelayRoots( mux: SshChannelMultiplexer, connectionId: string, store: Store -): void { - for (const repo of store.getRepos()) { - if (repo.connectionId === connectionId) { - mux.notify('session.registerRoot', { rootPath: repo.path }) - } +): Promise { + const remoteRepos = store.getRepos().filter((r) => r.connectionId === connectionId) + + for (const repo of remoteRepos) { + mux.notify('session.registerRoot', { rootPath: repo.path }) } + + // Why: git.listWorktrees is a request (not a notification) that requires + // the repo root to be registered first. Run after the repo root notify + // calls above so the relay accepts the path. + await Promise.all( + remoteRepos.map(async (repo) => { + try { + const worktrees = (await mux.request('git.listWorktrees', { + repoPath: repo.path + })) as { path: string }[] + for (const wt of worktrees) { + if (wt.path !== repo.path) { + mux.notify('session.registerRoot', { rootPath: wt.path }) + } + } + } catch { + // git worktree list may fail for folder-mode repos — not fatal + } + }) + ) } export function cleanupConnection( @@ -174,7 +199,7 @@ export async function reestablishRelayStack( activeMultiplexers.set(targetId, mux) if (store) { - registerRelayRoots(mux, targetId, store) + await registerRelayRoots(mux, targetId, store) } const ptyProvider = new SshPtyProvider(targetId, mux) diff --git a/src/main/ipc/ssh.ts b/src/main/ipc/ssh.ts index e02f0f973..071a8f686 100644 --- a/src/main/ipc/ssh.ts +++ b/src/main/ipc/ssh.ts @@ -178,7 +178,7 @@ export function registerSshHandlers( const mux = new SshChannelMultiplexer(transport) activeMultiplexers.set(args.targetId, mux) - registerRelayRoots(mux, args.targetId, store) + await registerRelayRoots(mux, args.targetId, store) const ptyProvider = new SshPtyProvider(args.targetId, mux) registerSshPtyProvider(args.targetId, ptyProvider) diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 7ff55ce1b..2cad1bf3c 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -19,6 +19,7 @@ import { gitExecFileAsync } from '../git/runner' import { isWslPath, parseWslPath, getWslHome } from '../wsl' import { createSetupRunnerScript, getEffectiveHooks, shouldRunSetupForCreate } from '../hooks' import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { getActiveMultiplexer } from './ssh' import type { SshGitProvider } from '../providers/ssh-git-provider' import { sanitizeWorktreeName, @@ -110,6 +111,15 @@ export async function createRemoteWorktree( /* best-effort */ } + // Why: the relay validates that targetDir is within a registered root. + // The new worktree lives as a sibling of the repo (repo.path/../name), + // outside the repo root. Register it before addWorktree so the relay + // accepts the path. + const mux = getActiveMultiplexer(repo.connectionId!) + if (mux) { + mux.notify('session.registerRoot', { rootPath: remotePath }) + } + // Create worktree via relay await provider.addWorktree(repo.path, branchName, remotePath, { base: baseBranch, diff --git a/src/relay/fs-handler-git-fallback.ts b/src/relay/fs-handler-git-fallback.ts new file mode 100644 index 000000000..bb84ccf55 --- /dev/null +++ b/src/relay/fs-handler-git-fallback.ts @@ -0,0 +1,300 @@ +/** + * Git-based fallbacks for file listing and text search. + * + * Why: the relay depends on ripgrep (rg) for fs.listFiles and fs.search, but + * rg is not installed on many remote machines. These functions use git ls-files + * and git grep as universal fallbacks — git is always available since this is + * a git-focused app. + */ +import { join } from 'path' +import { spawn } from 'child_process' +import { SEARCH_TIMEOUT_MS, type SearchOptions, type SearchResult } from './fs-handler-utils' + +// Why: mirrors the local HIDDEN_DIR_BLOCKLIST — tool-generated dirs that +// clutter quick-open results but should never appear in file listings. +const HIDDEN_DIR_BLOCKLIST = new Set([ + '.git', + '.next', + '.nuxt', + '.cache', + '.stably', + '.vscode', + '.idea', + '.yarn', + '.pnpm-store', + '.terraform', + '.docker', + '.husky' +]) + +function shouldIncludePath(path: string): boolean { + let start = 0 + const len = path.length + while (start < len) { + let end = path.indexOf('/', start) + if (end === -1) { + end = len + } + const segment = path.substring(start, end) + if (segment === 'node_modules' || HIDDEN_DIR_BLOCKLIST.has(segment)) { + return false + } + start = end + 1 + } + return true +} + +const REGEX_SPECIAL = '.*+?^${}()|[]\\' +function escapeRegexSource(str: string): string { + let out = '' + for (let i = 0; i < str.length; i++) { + out += REGEX_SPECIAL.includes(str[i]) ? `\\${str[i]}` : str[i] + } + return out +} + +function toGitGlobPathspec(glob: string, exclude?: boolean): string { + const needsRecursive = !glob.includes('/') + const pattern = needsRecursive ? `**/${glob}` : glob + return exclude ? `:(exclude,glob)${pattern}` : `:(glob)${pattern}` +} + +/** + * List files using `git ls-files`. Fallback when rg is not installed. + */ +export function listFilesWithGit(rootPath: string): Promise { + const files = new Set() + + const runGitLsFiles = (args: string[]): Promise => { + return new Promise((resolve) => { + let buf = '' + let done = false + const finish = (): void => { + if (done) { + return + } + done = true + clearTimeout(timer) + resolve() + } + + const processLine = (line: string): void => { + if (line.charCodeAt(line.length - 1) === 13) { + line = line.substring(0, line.length - 1) + } + if (!line) { + return + } + if (shouldIncludePath(line)) { + files.add(line) + } + } + + const child = spawn('git', ['ls-files', ...args], { + cwd: rootPath, + stdio: ['ignore', 'pipe', 'pipe'] + }) + child.stdout!.setEncoding('utf-8') + child.stdout!.on('data', (chunk: string) => { + buf += chunk + let start = 0 + let idx = buf.indexOf('\n', start) + while (idx !== -1) { + processLine(buf.substring(start, idx)) + start = idx + 1 + idx = buf.indexOf('\n', start) + } + buf = start < buf.length ? buf.substring(start) : '' + }) + child.stderr!.on('data', () => { + /* drain */ + }) + child.once('error', () => finish()) + child.once('close', () => { + if (buf) { + processLine(buf) + } + finish() + }) + const timer = setTimeout(() => child.kill(), 10_000) + }) + } + + return Promise.all([ + runGitLsFiles(['--cached', '--others', '--exclude-standard']), + runGitLsFiles(['--others', '--', '**/.env*']) + ]).then(() => Array.from(files)) +} + +type FileResult = { + filePath: string + relativePath: string + matches: { + line: number + column: number + matchLength: number + lineContent: string + }[] +} + +/** + * Text search using `git grep`. Fallback when rg is not installed. + */ +export function searchWithGitGrep( + rootPath: string, + query: string, + opts: SearchOptions +): Promise { + return new Promise((resolve) => { + const gitArgs: string[] = [ + '-c', + 'submodule.recurse=false', + 'grep', + '-n', + '-I', + '--null', + '--no-color', + '--untracked' + ] + + if (!opts.caseSensitive) { + gitArgs.push('-i') + } + if (opts.wholeWord) { + gitArgs.push('-w') + } + if (!opts.useRegex) { + gitArgs.push('--fixed-strings') + } else { + gitArgs.push('--extended-regexp') + } + + gitArgs.push('-e', query, '--') + + let hasPathspecs = false + if (opts.includePattern) { + for (const pat of opts.includePattern + .split(',') + .map((s) => s.trim()) + .filter(Boolean)) { + gitArgs.push(toGitGlobPathspec(pat)) + hasPathspecs = true + } + } + if (opts.excludePattern) { + for (const pat of opts.excludePattern + .split(',') + .map((s) => s.trim()) + .filter(Boolean)) { + gitArgs.push(toGitGlobPathspec(pat, true)) + hasPathspecs = true + } + } + if (!hasPathspecs) { + gitArgs.push('.') + } + + const fileMap = new Map() + let totalMatches = 0 + let truncated = false + let stdoutBuffer = '' + let done = false + + let pattern = opts.useRegex ? query : escapeRegexSource(query) + if (opts.wholeWord) { + pattern = `\\b${pattern}\\b` + } + const matchRegex = new RegExp(pattern, `g${opts.caseSensitive ? '' : 'i'}`) + + const resolveOnce = (): void => { + if (done) { + return + } + done = true + clearTimeout(killTimeout) + resolve({ files: Array.from(fileMap.values()), totalMatches, truncated }) + } + + const processLine = (line: string): void => { + if (!line || totalMatches >= opts.maxResults) { + return + } + + const nullIdx = line.indexOf('\0') + if (nullIdx === -1) { + return + } + const relPath = line + .substring(0, nullIdx) + .replace(/[\\/]+/g, '/') + .replace(/^\/+/, '') + const rest = line.substring(nullIdx + 1) + const colonIdx = rest.indexOf(':') + if (colonIdx === -1) { + return + } + + const lineNum = parseInt(rest.substring(0, colonIdx), 10) + if (isNaN(lineNum)) { + return + } + const lineContent = rest.substring(colonIdx + 1).replace(/\n$/, '') + + const absPath = join(rootPath, relPath) + let fileResult = fileMap.get(absPath) + if (!fileResult) { + fileResult = { filePath: absPath, relativePath: relPath, matches: [] } + fileMap.set(absPath, fileResult) + } + + matchRegex.lastIndex = 0 + let m: RegExpExecArray | null + while ((m = matchRegex.exec(lineContent)) !== null) { + fileResult.matches.push({ + line: lineNum, + column: m.index + 1, + matchLength: m[0].length, + lineContent + }) + totalMatches++ + if (totalMatches >= opts.maxResults) { + truncated = true + child.kill() + break + } + if (m[0].length === 0) { + matchRegex.lastIndex++ + } + } + } + + const child = spawn('git', gitArgs, { + cwd: rootPath, + stdio: ['ignore', 'pipe', 'pipe'] + }) + child.stdout!.setEncoding('utf-8') + child.stdout!.on('data', (chunk: string) => { + stdoutBuffer += chunk + const lines = stdoutBuffer.split('\n') + stdoutBuffer = lines.pop() ?? '' + for (const l of lines) { + processLine(l) + } + }) + child.stderr!.on('data', () => { + /* drain */ + }) + child.once('error', () => resolveOnce()) + child.once('close', () => { + if (stdoutBuffer) { + processLine(stdoutBuffer) + } + resolveOnce() + }) + + const killTimeout = setTimeout(() => { + truncated = true + child.kill() + }, SEARCH_TIMEOUT_MS) + }) +} diff --git a/src/relay/fs-handler-utils.ts b/src/relay/fs-handler-utils.ts index 96970d0f6..f400656d7 100644 --- a/src/relay/fs-handler-utils.ts +++ b/src/relay/fs-handler-utils.ts @@ -228,6 +228,30 @@ export function searchWithRg( }) } +// ─── rg availability check ────────────────────────────────────────── + +let rgAvailableCache: boolean | null = null + +export function checkRgAvailable(): Promise { + if (rgAvailableCache !== null) { + return Promise.resolve(rgAvailableCache) + } + return new Promise((resolve) => { + const child = execFile('rg', ['--version']) + child.once('error', () => { + rgAvailableCache = false + resolve(false) + }) + child.once('close', (code) => { + if (rgAvailableCache !== null) { + return + } + rgAvailableCache = code === 0 + resolve(rgAvailableCache) + }) + }) +} + // ─── rg-based file listing ─────────────────────────────────────────── /** diff --git a/src/relay/fs-handler.ts b/src/relay/fs-handler.ts index d161b3693..4a92251b0 100644 --- a/src/relay/fs-handler.ts +++ b/src/relay/fs-handler.ts @@ -19,8 +19,10 @@ import { IMAGE_MIME_TYPES, isBinaryBuffer, searchWithRg, - listFilesWithRg + listFilesWithRg, + checkRgAvailable } from './fs-handler-utils' +import { listFilesWithGit, searchWithGitGrep } from './fs-handler-git-fallback' type WatchState = { rootPath: string @@ -199,6 +201,18 @@ export class FsHandler { DEFAULT_MAX_RESULTS ) + const rgAvailable = await checkRgAvailable() + if (!rgAvailable) { + return searchWithGitGrep(rootPath, query, { + caseSensitive, + wholeWord, + useRegex, + includePattern, + excludePattern, + maxResults + }) + } + return searchWithRg(rootPath, query, { caseSensitive, wholeWord, @@ -212,6 +226,10 @@ export class FsHandler { private async listFiles(params: Record): Promise { const rootPath = params.rootPath as string await this.context.validatePathResolved(rootPath) + const rgAvailable = await checkRgAvailable() + if (!rgAvailable) { + return listFilesWithGit(rootPath) + } return listFilesWithRg(rootPath) }