Files
orca/src/main/ipc/filesystem.ts
T
2026-05-16 04:44:44 -04:00

1039 lines
36 KiB
TypeScript

/* eslint-disable max-lines */
import { ipcMain, shell } from 'electron'
import { readdir, readFile, writeFile, stat, lstat, open } from 'fs/promises'
import { extname, join } from 'path'
import type { ChildProcess } from 'child_process'
import { wslAwareSpawn } from '../git/runner'
import { parseWslPath, toWindowsWslPath } from '../wsl'
import type { Store } from '../persistence'
import type {
DirEntry,
GitBranchCompareResult,
GitCommitCompareResult,
GitConflictOperation,
GitDiffResult,
GitPushTarget,
GitUpstreamStatus,
GitStatusResult,
MarkdownDocument,
SearchOptions,
SearchResult
} from '../../shared/types'
import type { GitHistoryOptions, GitHistoryResult } from '../../shared/git-history'
import {
buildRgArgs,
createAccumulator,
DEFAULT_SEARCH_MAX_RESULTS,
finalize,
ingestRgJsonLine,
SEARCH_TIMEOUT_MS
} from '../../shared/text-search'
import {
getStatus,
detectConflictOperation,
getDiff,
commitChanges,
stageFile,
unstageFile,
bulkStageFiles,
bulkUnstageFiles,
bulkDiscardChanges,
discardChanges,
getStagedCommitContext,
getBranchCompare,
getBranchDiff,
getCommitCompare,
getCommitDiff
} from '../git/status'
import { getHistory } from '../git/history'
import {
cancelGenerateCommitMessageLocal,
generateCommitMessageFromContext,
resolveCommitMessageSettings,
type GenerateCommitMessageResult
} from '../text-generation/commit-message-text-generation'
import { getUpstreamStatus } from '../git/upstream'
import { gitFetch, gitPull, gitPush } from '../git/remote'
import { assertGitPushTargetShape } from '../../shared/git-push-target-validation'
import { validateGitPushTarget } from '../git/push-target-validation'
import { getRemoteFileUrl } from '../git/repo'
import {
resolveAuthorizedPath,
resolveRegisteredWorktreePath,
validateGitRelativeFilePath,
isENOENT,
authorizeExternalPath
} from './filesystem-auth'
import { listQuickOpenFiles } from './filesystem-list-files'
import { registerFilesystemMutationHandlers } from './filesystem-mutations'
import { searchWithGitGrep } from './filesystem-search-git'
import { listMarkdownDocuments, markdownDocumentsFromRelativePaths } from './markdown-documents'
import { checkRgAvailable } from './rg-availability'
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
import {
prepareLocalCommitMessageAgentEnv,
type CommitMessageAgentEnvironmentResolvers
} from '../text-generation/commit-message-agent-environment'
// Why: Monaco has large-file optimizations like VS Code; blocking at 5MB makes
// ordinary JSON/log files inaccessible before the editor can degrade features.
const MAX_TEXT_FILE_SIZE = 50 * 1024 * 1024 // 50MB
const BINARY_PROBE_BYTES = 8192
const FULL_GIT_OBJECT_ID_PATTERN = /^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/
// Why: previewable binaries (PDFs, images) are rendered by the viewer as
// base64 blobs, not parsed as text — 5MB is tight for real-world PDFs, and
// raising this cap only affects binary preview, not text/search paths.
// The relay (SSH) uses a smaller 10MB cap because its JSON-RPC frames are
// bounded by MAX_MESSAGE_SIZE = 16MB; the local IPC path has no such limit,
// so 50MB covers real-world PDFs (specs, datasheets, image-heavy contracts).
// See src/relay/fs-handler-utils.ts for the remote-side reasoning.
const MAX_PREVIEWABLE_BINARY_SIZE = 50 * 1024 * 1024 // 50MB
const PREVIEWABLE_BINARY_MIME_TYPES: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
'.ico': 'image/x-icon',
'.pdf': 'application/pdf'
}
function validateFullGitObjectId(value: string, label: string): string {
if (!FULL_GIT_OBJECT_ID_PATTERN.test(value)) {
throw new Error(`${label} must be a full git object id`)
}
return value
}
/**
* Check if a buffer appears to be binary (contains null bytes in first 8KB).
*/
function isBinaryBuffer(buffer: Buffer): boolean {
const len = Math.min(buffer.length, 8192)
for (let i = 0; i < len; i++) {
if (buffer[i] === 0) {
return true
}
}
return false
}
async function isBinaryFilePrefix(filePath: string): Promise<boolean> {
const handle = await open(filePath, 'r')
try {
const probe = Buffer.alloc(BINARY_PROBE_BYTES)
const { bytesRead } = await handle.read(probe, 0, probe.length, 0)
return isBinaryBuffer(probe.subarray(0, bytesRead))
} finally {
await handle.close()
}
}
async function isDirectoryEntry(
dirPath: string,
entry: { name: string; isDirectory(): boolean; isSymbolicLink(): boolean },
resolveEntryPath: (entryPath: string) => Promise<string>
): Promise<boolean> {
if (entry.isDirectory()) {
return true
}
if (!entry.isSymbolicLink()) {
return false
}
try {
// Why: directory symlinks inside a workspace should navigate like folders
// without bypassing the local authorized-path boundary.
const entryPath = await resolveEntryPath(join(dirPath, entry.name))
return (await stat(entryPath)).isDirectory()
} catch {
return false
}
}
export function registerFilesystemHandlers(
store: Store,
commitMessageAgentEnv?: CommitMessageAgentEnvironmentResolvers
): void {
const activeTextSearches = new Map<string, ChildProcess>()
// ─── Filesystem ─────────────────────────────────────────
ipcMain.handle(
'fs:readDir',
async (_event, args: { dirPath: string; connectionId?: string }): Promise<DirEntry[]> => {
if (args.connectionId) {
const provider = getSshFilesystemProvider(args.connectionId)
if (!provider) {
throw new Error(`No filesystem provider for connection "${args.connectionId}"`)
}
return provider.readDir(args.dirPath)
}
const dirPath = await resolveAuthorizedPath(args.dirPath, store)
const entries = await readdir(dirPath, { withFileTypes: true })
const mapped = await Promise.all(
entries.map(async (entry) => ({
name: entry.name,
isDirectory: await isDirectoryEntry(dirPath, entry, (entryPath) =>
resolveAuthorizedPath(entryPath, store)
),
isSymlink: entry.isSymbolicLink()
}))
)
return mapped.sort((a, b) => {
if (a.isDirectory !== b.isDirectory) {
return a.isDirectory ? -1 : 1
}
return a.name.localeCompare(b.name)
})
}
)
ipcMain.handle(
'fs:readFile',
async (
_event,
args: { filePath: string; connectionId?: string }
): Promise<{ content: string; isBinary: boolean; isImage?: boolean; mimeType?: string }> => {
if (args.connectionId) {
const provider = getSshFilesystemProvider(args.connectionId)
if (!provider) {
throw new Error(`No filesystem provider for connection "${args.connectionId}"`)
}
return provider.readFile(args.filePath)
}
const filePath = await resolveAuthorizedPath(args.filePath, store)
const stats = await stat(filePath)
const mimeType = PREVIEWABLE_BINARY_MIME_TYPES[extname(filePath).toLowerCase()]
const sizeLimit = mimeType ? MAX_PREVIEWABLE_BINARY_SIZE : MAX_TEXT_FILE_SIZE
if (stats.size > sizeLimit) {
throw new Error(
`File too large: ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds ${sizeLimit / 1024 / 1024}MB limit`
)
}
if (mimeType) {
const buffer = await readFile(filePath)
return {
content: buffer.toString('base64'),
isBinary: true,
// Why: the renderer/store contract already keys previewable binary
// rendering off `isImage`. Keep that legacy flag for PDFs too so the
// new preview path stays compatible with existing callers.
isImage: true,
mimeType
}
}
// Why: the text cap is intentionally larger than the old binary cap.
// Probe unknown large files first so archives do not get fully buffered
// just to discover they are not editable text.
if (stats.size > BINARY_PROBE_BYTES && (await isBinaryFilePrefix(filePath))) {
return { content: '', isBinary: true }
}
const buffer = await readFile(filePath)
if (isBinaryBuffer(buffer)) {
return { content: '', isBinary: true }
}
return { content: buffer.toString('utf-8'), isBinary: false }
}
)
ipcMain.handle(
'fs:listMarkdownDocuments',
async (
_event,
args: { rootPath: string; connectionId?: string }
): Promise<MarkdownDocument[]> => {
if (args.connectionId) {
const provider = getSshFilesystemProvider(args.connectionId)
if (!provider) {
throw new Error(`No filesystem provider for connection "${args.connectionId}"`)
}
const relativePaths = await provider.listFiles(args.rootPath)
return markdownDocumentsFromRelativePaths(args.rootPath, relativePaths)
}
const rootPath = await resolveRegisteredWorktreePath(args.rootPath, store)
return listMarkdownDocuments(rootPath)
}
)
ipcMain.handle(
'fs:writeFile',
async (
_event,
args: { filePath: string; content: string; connectionId?: string }
): Promise<void> => {
if (args.connectionId) {
const provider = getSshFilesystemProvider(args.connectionId)
if (!provider) {
throw new Error(`No filesystem provider for connection "${args.connectionId}"`)
}
return provider.writeFile(args.filePath, args.content)
}
const filePath = await resolveAuthorizedPath(args.filePath, store)
try {
const fileStats = await lstat(filePath)
if (fileStats.isDirectory()) {
throw new Error('Cannot write to a directory')
}
} catch (error) {
if (!isENOENT(error)) {
throw error
}
}
await writeFile(filePath, args.content, 'utf-8')
}
)
ipcMain.handle(
'fs:deletePath',
async (
_event,
args: { targetPath: string; connectionId?: string; recursive?: boolean }
): Promise<void> => {
if (args.connectionId) {
const provider = getSshFilesystemProvider(args.connectionId)
if (!provider) {
throw new Error(`No filesystem provider for connection "${args.connectionId}"`)
}
return provider.deletePath(args.targetPath, args.recursive)
}
// Why: deleting must operate on the symlink itself, not its target.
// Following the link with realpath() would trash the real file — which
// could be another file inside the worktree, or a path outside all
// allowed roots that we would never be able to delete again.
const targetPath = await resolveAuthorizedPath(args.targetPath, store, {
preserveSymlink: true
})
// Why: once auto-refresh exists, an external delete can race with a
// UI-initiated delete. Swallowing ENOENT keeps the action idempotent
// from the user's perspective (design §7.1).
try {
await shell.trashItem(targetPath)
} catch (error) {
if (isENOENT(error)) {
return
}
throw error
}
}
)
registerFilesystemMutationHandlers(store)
ipcMain.handle('fs:authorizeExternalPath', (_event, args: { targetPath: string }): void => {
authorizeExternalPath(args.targetPath)
})
ipcMain.handle(
'fs:stat',
async (
_event,
args: { filePath: string; connectionId?: string }
): Promise<{ size: number; isDirectory: boolean; mtime: number }> => {
if (args.connectionId) {
const provider = getSshFilesystemProvider(args.connectionId)
if (!provider) {
throw new Error(`No filesystem provider for connection "${args.connectionId}"`)
}
const s = await provider.stat(args.filePath)
return { size: s.size, isDirectory: s.type === 'directory', mtime: s.mtime }
}
const filePath = await resolveAuthorizedPath(args.filePath, store)
const stats = await stat(filePath)
return {
size: stats.size,
isDirectory: stats.isDirectory(),
mtime: stats.mtimeMs
}
}
)
// ─── Search ────────────────────────────────────────────
ipcMain.handle(
'fs:search',
async (event, args: SearchOptions & { connectionId?: string }): Promise<SearchResult> => {
if (args.connectionId) {
const provider = getSshFilesystemProvider(args.connectionId)
if (!provider) {
throw new Error(`No filesystem provider for connection "${args.connectionId}"`)
}
return provider.search(args)
}
const rootPath = await resolveAuthorizedPath(args.rootPath, store)
const maxResults = Math.max(
1,
Math.min(args.maxResults ?? DEFAULT_SEARCH_MAX_RESULTS, DEFAULT_SEARCH_MAX_RESULTS)
)
const searchKey = `${event.sender.id}:${rootPath}`
// Why: checking rg availability upfront avoids a race condition where
// spawn('rg') emits 'close' before 'error' on some platforms, causing
// the handler to resolve with empty results before the git-grep
// fallback can run. The result is cached after the first check.
const rgAvailable = await checkRgAvailable(rootPath)
if (!rgAvailable) {
return searchWithGitGrep(rootPath, args, maxResults)
}
return new Promise((resolvePromise) => {
const rgArgs = buildRgArgs(args.query, rootPath, args)
// Why: search requests are fired on each query/options change. If the
// previous ripgrep process keeps running, it can continue streaming and
// parsing thousands of matches on the Electron main thread after the UI
// no longer cares about that result, which is exactly the freeze users
// experience in large repos.
activeTextSearches.get(searchKey)?.kill()
const acc = createAccumulator()
let stdoutBuffer = ''
let resolved = false
let child: ChildProcess | null = null
// Why: when rg runs inside WSL, output paths are Linux-native
// (e.g. /home/user/repo/src/file.ts). Translate them back to
// Windows UNC paths so path.relative() and Node fs APIs work.
const wslInfo = parseWslPath(rootPath)
const transformAbsPath = wslInfo
? (p: string): string => toWindowsWslPath(p, wslInfo.distro)
: undefined
const resolveOnce = (): void => {
if (resolved) {
return
}
resolved = true
if (activeTextSearches.get(searchKey) === child) {
activeTextSearches.delete(searchKey)
}
clearTimeout(killTimeout)
resolvePromise(finalize(acc))
}
const processLine = (line: string): void => {
const verdict = ingestRgJsonLine(line, rootPath, acc, maxResults, transformAbsPath)
if (verdict === 'stop') {
child?.kill()
}
}
const nextChild = wslAwareSpawn('rg', rgArgs, {
cwd: rootPath,
stdio: ['ignore', 'pipe', 'pipe']
})
child = nextChild
activeTextSearches.set(searchKey, nextChild)
nextChild.stdout!.setEncoding('utf-8')
nextChild.stdout!.on('data', (chunk: string) => {
stdoutBuffer += chunk
const lines = stdoutBuffer.split('\n')
stdoutBuffer = lines.pop() ?? ''
for (const line of lines) {
processLine(line)
}
})
nextChild.stderr!.on('data', () => {
// Drain stderr so rg cannot block on a full pipe.
})
nextChild.once('error', () => {
resolveOnce()
})
nextChild.once('close', () => {
if (stdoutBuffer) {
processLine(stdoutBuffer)
}
resolveOnce()
})
// Why: if the timeout fires, the child is killed and results are partial.
// We must mark them as truncated so the UI can indicate incomplete results.
const killTimeout = setTimeout(() => {
acc.truncated = true
child?.kill()
}, SEARCH_TIMEOUT_MS)
})
}
)
// ─── List all files (for quick-open) ─────────────────────
ipcMain.handle(
'fs:listFiles',
async (
_event,
args: { rootPath: string; connectionId?: string; excludePaths?: string[] }
): Promise<string[]> => {
if (args.connectionId) {
const provider = getSshFilesystemProvider(args.connectionId)
// Why: when the SSH connection is not yet established (cold start) or
// temporarily disconnected, return [] so quick-open shows "No matching
// files" instead of an error banner. The file list will repopulate when
// the user re-opens quick-open after the connection is restored.
if (!provider) {
return []
}
// Why: forward excludePaths through to the remote provider.
// Dropping it here would silently double-scan nested linked worktrees
// over SSH and contribute to timeout-induced partial results.
return provider.listFiles(args.rootPath, { excludePaths: args.excludePaths })
}
return listQuickOpenFiles(args.rootPath, store, args.excludePaths)
}
)
// ─── Git operations ─────────────────────────────────────
ipcMain.handle(
'git:status',
async (
_event,
args: { worktreePath: string; connectionId?: string; includeIgnored?: boolean }
): Promise<GitStatusResult> => {
const options = { includeIgnored: args.includeIgnored ?? false }
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.getStatus(args.worktreePath, options)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
return getStatus(worktreePath, options)
}
)
ipcMain.handle(
'git:history',
async (
_event,
args: { worktreePath: string; connectionId?: string } & GitHistoryOptions
): Promise<GitHistoryResult> => {
const options: GitHistoryOptions = { limit: args.limit, baseRef: args.baseRef }
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.getHistory(args.worktreePath, options)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
return getHistory(worktreePath, options)
}
)
// Why: lightweight fs-only check for conflict operation state. Used to poll
// non-active worktrees so their "Rebasing"/"Merging" badges clear when the
// operation finishes, without running a full `git status`.
ipcMain.handle(
'git:conflictOperation',
async (
_event,
args: { worktreePath: string; connectionId?: string }
): Promise<GitConflictOperation> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.detectConflictOperation(args.worktreePath)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
return detectConflictOperation(worktreePath)
}
)
ipcMain.handle(
'git:diff',
async (
_event,
args: {
worktreePath: string
filePath: string
staged: boolean
compareAgainstHead?: boolean
connectionId?: string
}
): Promise<GitDiffResult> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.getDiff(
args.worktreePath,
args.filePath,
args.staged,
args.compareAgainstHead
)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
const filePath = validateGitRelativeFilePath(worktreePath, args.filePath)
return getDiff(worktreePath, filePath, args.staged, args.compareAgainstHead)
}
)
ipcMain.handle(
'git:commit',
async (
_event,
args: { worktreePath: string; message: string; connectionId?: string }
): Promise<{ success: boolean; error?: string }> => {
// Why: validate at the IPC boundary so the renderer gets a clear error instead of an opaque execFile failure.
if (typeof args.message !== 'string' || args.message.trim().length === 0) {
throw new Error('Commit message is required')
}
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.commit(args.worktreePath, args.message)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
return commitChanges(worktreePath, args.message)
}
)
ipcMain.handle(
'git:generateCommitMessage',
async (
_event,
args: {
worktreePath: string
connectionId?: string
}
): Promise<GenerateCommitMessageResult> => {
const resolvedSettings = resolveCommitMessageSettings(store.getSettings())
if (!resolvedSettings.ok) {
return { success: false, error: resolvedSettings.error }
}
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
return {
success: false,
error: `No git provider for connection "${args.connectionId}"`
}
}
let context
try {
context = await provider.getStagedCommitContext(args.worktreePath)
} catch (error) {
console.error('[filesystem] Failed to read remote staged commit context:', error)
return {
success: false,
error: 'Failed to read staged changes.'
}
}
if (!context) {
return { success: false, error: 'No staged changes to summarize.' }
}
return generateCommitMessageFromContext(context, resolvedSettings.params, {
kind: 'remote',
cwd: args.worktreePath,
execute: (plan, cwd, timeoutMs) =>
provider.executeCommitMessagePlan(plan, cwd, timeoutMs),
missingBinaryLocation: 'remote PATH'
})
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
let context
try {
context = await getStagedCommitContext(worktreePath)
} catch (error) {
console.error('[filesystem] Failed to read staged commit context:', error)
return {
success: false,
error: 'Failed to read staged changes.'
}
}
if (!context) {
return { success: false, error: 'No staged changes to summarize.' }
}
const localEnv = await prepareLocalCommitMessageAgentEnv(
resolvedSettings.params.agentId,
commitMessageAgentEnv
)
if (!localEnv.ok) {
return { success: false, error: localEnv.error }
}
return generateCommitMessageFromContext(context, resolvedSettings.params, {
kind: 'local',
cwd: worktreePath,
...(localEnv.env ? { env: localEnv.env } : {})
})
}
)
ipcMain.handle(
'git:cancelGenerateCommitMessage',
async (_event, args: { worktreePath: string; connectionId?: string }): Promise<void> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
return
}
await provider.cancelGenerateCommitMessage(args.worktreePath)
return
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
cancelGenerateCommitMessageLocal(worktreePath)
}
)
ipcMain.handle(
'git:branchCompare',
async (
_event,
args: { worktreePath: string; baseRef: string; connectionId?: string }
): Promise<GitBranchCompareResult> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.getBranchCompare(args.worktreePath, args.baseRef)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
return getBranchCompare(worktreePath, args.baseRef)
}
)
ipcMain.handle(
'git:commitCompare',
async (
_event,
args: { worktreePath: string; commitId: string; connectionId?: string }
): Promise<GitCommitCompareResult> => {
const commitId = validateFullGitObjectId(args.commitId, 'commitId')
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.getCommitCompare(args.worktreePath, commitId)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
return getCommitCompare(worktreePath, commitId)
}
)
ipcMain.handle(
'git:upstreamStatus',
async (
_event,
args: { worktreePath: string; connectionId?: string }
): Promise<GitUpstreamStatus> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.getUpstreamStatus(args.worktreePath)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
return getUpstreamStatus(worktreePath)
}
)
ipcMain.handle(
'git:fetch',
async (_event, args: { worktreePath: string; connectionId?: string }): Promise<void> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.fetchRemote(args.worktreePath)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
await gitFetch(worktreePath)
}
)
ipcMain.handle(
'git:push',
async (
_event,
args: {
worktreePath: string
publish?: boolean
connectionId?: string
pushTarget?: GitPushTarget
}
): Promise<void> => {
// Why: coerce to strict boolean at the IPC boundary so a malformed
// renderer payload (e.g. string 'false') can't silently enable
// --set-upstream mode. Mirrors the relay handler in src/relay/git-handler.ts.
const publish = args.publish === true
if (args.connectionId) {
if (args.pushTarget) {
assertGitPushTargetShape(args.pushTarget)
}
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.pushBranch(args.worktreePath, publish, args.pushTarget)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
if (args.pushTarget) {
await validateGitPushTarget(worktreePath, args.pushTarget)
}
await gitPush(worktreePath, publish, args.pushTarget)
}
)
ipcMain.handle(
'git:pull',
async (_event, args: { worktreePath: string; connectionId?: string }): Promise<void> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.pullBranch(args.worktreePath)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
await gitPull(worktreePath)
}
)
ipcMain.handle(
'git:branchDiff',
async (
_event,
args: {
worktreePath: string
compare: {
baseRef: string
baseOid: string
headOid: string
mergeBase: string
}
filePath: string
oldPath?: string
connectionId?: string
}
): Promise<GitDiffResult> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
const results = await provider.getBranchDiff(args.worktreePath, args.compare.mergeBase, {
includePatch: true,
filePath: args.filePath,
oldPath: args.oldPath
})
return (
results[0] ?? {
kind: 'text',
originalContent: '',
modifiedContent: '',
originalIsBinary: false,
modifiedIsBinary: false
}
)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
const filePath = validateGitRelativeFilePath(worktreePath, args.filePath)
const oldPath = args.oldPath
? validateGitRelativeFilePath(worktreePath, args.oldPath)
: undefined
return getBranchDiff(worktreePath, {
mergeBase: args.compare.mergeBase,
headOid: args.compare.headOid,
filePath,
oldPath
})
}
)
ipcMain.handle(
'git:commitDiff',
async (
_event,
args: {
worktreePath: string
commitOid: string
parentOid?: string | null
filePath: string
oldPath?: string
connectionId?: string
}
): Promise<GitDiffResult> => {
const commitOid = validateFullGitObjectId(args.commitOid, 'commitOid')
const parentOid = args.parentOid ? validateFullGitObjectId(args.parentOid, 'parentOid') : null
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.getCommitDiff(args.worktreePath, {
commitOid,
parentOid,
filePath: args.filePath,
oldPath: args.oldPath
})
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
const filePath = validateGitRelativeFilePath(worktreePath, args.filePath)
const oldPath = args.oldPath
? validateGitRelativeFilePath(worktreePath, args.oldPath)
: undefined
return getCommitDiff(worktreePath, {
commitOid,
parentOid,
filePath,
oldPath
})
}
)
ipcMain.handle(
'git:stage',
async (
_event,
args: { worktreePath: string; filePath: string; connectionId?: string }
): Promise<void> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.stageFile(args.worktreePath, args.filePath)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
const filePath = validateGitRelativeFilePath(worktreePath, args.filePath)
await stageFile(worktreePath, filePath)
}
)
ipcMain.handle(
'git:unstage',
async (
_event,
args: { worktreePath: string; filePath: string; connectionId?: string }
): Promise<void> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.unstageFile(args.worktreePath, args.filePath)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
const filePath = validateGitRelativeFilePath(worktreePath, args.filePath)
await unstageFile(worktreePath, filePath)
}
)
ipcMain.handle(
'git:discard',
async (
_event,
args: { worktreePath: string; filePath: string; connectionId?: string }
): Promise<void> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.discardChanges(args.worktreePath, args.filePath)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
const filePath = validateGitRelativeFilePath(worktreePath, args.filePath)
await discardChanges(worktreePath, filePath)
}
)
ipcMain.handle(
'git:bulkDiscard',
async (
_event,
args: { worktreePath: string; filePaths: string[]; connectionId?: string }
): Promise<void> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.bulkDiscardChanges(args.worktreePath, args.filePaths)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
const filePaths = args.filePaths.map((p) => validateGitRelativeFilePath(worktreePath, p))
await bulkDiscardChanges(worktreePath, filePaths)
}
)
ipcMain.handle(
'git:bulkStage',
async (
_event,
args: { worktreePath: string; filePaths: string[]; connectionId?: string }
): Promise<void> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.bulkStageFiles(args.worktreePath, args.filePaths)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
const filePaths = args.filePaths.map((p) => validateGitRelativeFilePath(worktreePath, p))
await bulkStageFiles(worktreePath, filePaths)
}
)
ipcMain.handle(
'git:bulkUnstage',
async (
_event,
args: { worktreePath: string; filePaths: string[]; connectionId?: string }
): Promise<void> => {
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.bulkUnstageFiles(args.worktreePath, args.filePaths)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
const filePaths = args.filePaths.map((p) => validateGitRelativeFilePath(worktreePath, p))
await bulkUnstageFiles(worktreePath, filePaths)
}
)
ipcMain.handle(
'git:remoteFileUrl',
async (
_event,
args: { worktreePath: string; relativePath: string; line: number; connectionId?: string }
): Promise<string | null> => {
// Why: remote repos can't use the local hosted-git-info approach because
// the .git/config lives on the remote. Route through the relay's git.exec
// to fetch the remote URL and build the file link server-side.
if (args.connectionId) {
const provider = getSshGitProvider(args.connectionId)
if (!provider) {
throw new Error(`No git provider for connection "${args.connectionId}"`)
}
return provider.getRemoteFileUrl(args.worktreePath, args.relativePath, args.line)
}
const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store)
return getRemoteFileUrl(worktreePath, args.relativePath, args.line)
}
)
}