diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b9b05bc..97c17afa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,3 +35,20 @@ jobs: - run: pnpm typecheck - run: pnpm build + + git-status: + strategy: + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: 1 + steps: + - uses: actions/checkout@v5 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm --filter @deva/desktop test:git diff --git a/.gitignore b/.gitignore index ae0114b4..ba4aca65 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ dist/ out/ .vite/ *.tsbuildinfo +.test-out/ # Logs *.log diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c24ef821..030a4c85 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -15,6 +15,7 @@ "typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false", "typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false", "typecheck": "npm run typecheck:node && npm run typecheck:web", + "test:git": "tsc -p tsconfig.git-test.json && node --test .test-out/tests/git-status.test.js .test-out/tests/git-status-process.test.js", "build:win": "electron-vite build && electron-builder --win", "build:mac": "electron-vite build && electron-builder --mac", "build:linux": "electron-vite build && electron-builder --linux" diff --git a/apps/desktop/src/main/services/git-status-process.ts b/apps/desktop/src/main/services/git-status-process.ts new file mode 100644 index 00000000..023e8952 --- /dev/null +++ b/apps/desktop/src/main/services/git-status-process.ts @@ -0,0 +1,114 @@ +import { execFile, spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { join, win32 } from 'node:path' + +export interface GitStatusCommandResult { + code: number + stdout: string + stderr: string +} + +export const STATUS_TIMEOUT_MS = 10_000 +export const STATUS_MAX_OUTPUT_BYTES = 4 * 1024 * 1024 +const activeScans = new Set<(reason: string) => void>() + +/** Git for Windows cmd/bin launchers can outlive execFile's direct-child timeout. */ +export function resolveStatusGitPath(executable: string): string { + if (process.platform !== 'win32' || win32.basename(executable).toLowerCase() !== 'git.exe') { + return executable + } + const parent = win32.dirname(executable) + if (!['cmd', 'bin'].includes(win32.basename(parent).toLowerCase())) return executable + const root = win32.dirname(parent) + for (const arch of ['mingw64', 'mingw32']) { + const native = win32.join(root, arch, 'bin', 'git.exe') + if (existsSync(native)) return native + } + return executable +} + +/** Only terminate the tree/group created by this invocation; never kill Git by name. */ +function killOwnedTree(child: ReturnType): Promise { + const pid = child.pid + if (!pid) return Promise.resolve() + if (process.platform !== 'win32') { + try { + process.kill(-pid, 'SIGKILL') + } catch { + try { child.kill('SIGKILL') } catch { /* already exited */ } + } + return Promise.resolve() + } + return new Promise((resolve) => { + const taskkill = join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe') + execFile(taskkill, ['/PID', String(pid), '/T', '/F'], { + windowsHide: true, + timeout: 3000, + maxBuffer: 64 * 1024 + }, (error) => { + if (error) { + try { child.kill('SIGKILL') } catch { /* already exited */ } + } + resolve() + }) + }) +} + +export function cancelGitStatusScans(): void { + for (const stop of activeScans) stop('Git status scan cancelled') +} + +/** + * Read-only status commands get their own small budget, separate from writes/remotes. + * The byte cap bounds captured output, not Git's own RSS. Avoiding automatic scans is + * the primary memory protection; deadlines and owned-tree cleanup are a second line. + */ +export function runBoundedGitStatus( + executable: string, + cwd: string, + args: string[], + limits: { timeoutMs?: number; maxOutputBytes?: number } = {} +): Promise { + return new Promise((resolve) => { + const child = spawn(resolveStatusGitPath(executable), args, { + cwd, + windowsHide: true, + detached: process.platform !== 'win32', + stdio: ['ignore', 'pipe', 'pipe'], + env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' } + }) + const stdout: Buffer[] = [] + const stderr: Buffer[] = [] + let bytes = 0 + let failure = '' + let cleanup: Promise | undefined + const stop = (reason: string): void => { + if (failure) return + failure = reason + cleanup = killOwnedTree(child) + } + activeScans.add(stop) + const timer = setTimeout(() => stop('Git status scan timed out'), limits.timeoutMs ?? STATUS_TIMEOUT_MS) + const collect = (target: Buffer[], chunk: Buffer): void => { + if (failure) return + bytes += chunk.length + if (bytes > (limits.maxOutputBytes ?? STATUS_MAX_OUTPUT_BYTES)) { + stop('Git status output exceeded the safety limit') + return + } + target.push(chunk) + } + child.stdout?.on('data', (chunk: Buffer) => collect(stdout, chunk)) + child.stderr?.on('data', (chunk: Buffer) => collect(stderr, chunk)) + child.once('error', (error) => { failure ||= error.message }) + child.once('close', (code) => { + clearTimeout(timer) + activeScans.delete(stop) + void Promise.resolve(cleanup).then(() => resolve({ + code: failure ? 1 : code ?? 1, + stdout: failure ? '' : Buffer.concat(stdout).toString('utf8'), + stderr: failure || Buffer.concat(stderr).toString('utf8') + })) + }) + }) +} diff --git a/apps/desktop/src/main/services/git-status.ts b/apps/desktop/src/main/services/git-status.ts new file mode 100644 index 00000000..30f29907 --- /dev/null +++ b/apps/desktop/src/main/services/git-status.ts @@ -0,0 +1,191 @@ +import { promises as fs } from 'node:fs' +import { homedir } from 'node:os' +import { dirname, join, parse, resolve } from 'node:path' +import type { GitParsedStatus, GitStatus, GitStatusOptions } from '../../shared/git-status' +import { runBoundedGitStatus, STATUS_TIMEOUT_MS } from './git-status-process' + +const MAX_METADATA_BYTES = 4096 +const MAX_ANCESTORS = 64 + +function emptyStatus(root: string): GitStatus { + return { + isRepo: false, root, branch: null, detached: false, upstream: null, + ahead: 0, behind: 0, remotes: [], mergeInProgress: false, + staged: [], unstaged: [], conflicts: [], scanState: 'not-scanned' + } +} + +/** Never read an index, enumerate a directory, or load an arbitrarily large gitfile/HEAD. */ +async function readSmallFile(path: string): Promise { + const before = await fs.stat(path) + if (!before.isFile() || before.size > MAX_METADATA_BYTES) return null + const handle = await fs.open(path, 'r') + try { + const stat = await handle.stat() + if (!stat.isFile() || stat.size > MAX_METADATA_BYTES) return null + const buffer = Buffer.alloc(MAX_METADATA_BYTES + 1) + const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0) + return bytesRead > MAX_METADATA_BYTES ? null : buffer.subarray(0, bytesRead).toString('utf8').trim() + } finally { + await handle.close() + } +} + +/** Background discovery is bounded metadata I/O only, including linked worktrees. */ +export async function readGitMetadata(dir: string): Promise { + const absolute = resolve(dir) + let root = await fs.realpath(absolute).catch(() => absolute) + for (let depth = 0; depth < MAX_ANCESTORS; depth++) { + const marker = join(root, '.git') + let foundMarker = false + try { + const stat = await fs.stat(marker) + foundMarker = true + let gitDir = marker + if (!stat.isDirectory()) { + if (!stat.isFile() || stat.size > MAX_METADATA_BYTES) return emptyStatus(absolute) + const pointer = await readSmallFile(marker) + const match = pointer && /^gitdir: ([^\r\n\0]+)$/.exec(pointer) + if (!match) return emptyStatus(absolute) + gitDir = resolve(root, match[1]) + } + const head = await readSmallFile(join(gitDir, 'HEAD')) + const branch = head && /^ref: refs\/heads\/([^\x00-\x20\x7f]+)$/.exec(head) + const detached = Boolean(head && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(head)) + if (!branch && !detached) return emptyStatus(absolute) + return { + ...emptyStatus(root), + isRepo: true, + branch: branch ? branch[1] : null, + detached, + mergeInProgress: await fs.stat(join(gitDir, 'MERGE_HEAD')).then((s) => s.isFile(), () => false) + } + } catch (error) { + // A broken gitfile/HEAD is not permission to discover a wider parent repo. + if (foundMarker || (error as NodeJS.ErrnoException).code !== 'ENOENT') return emptyStatus(absolute) + } + const parent = dirname(root) + if (parent === root) break + root = parent + } + return emptyStatus(absolute) +} + +function pathKey(path: string): string { + const absolute = resolve(path) + return process.platform === 'win32' ? absolute.toLowerCase() : absolute +} + +/** A mistakenly initialized home/drive repository must not enumerate the whole disk. */ +export function isUnsafeStatusRoot(root: string): boolean { + const home = homedir() + const blocked = [parse(root).root, home] + if (process.platform === 'win32') { + blocked.push(dirname(home)) + for (const name of ['USERPROFILE', 'SystemRoot', 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramData']) { + const value = process.env[name] + if (value) blocked.push(value) + } + } + return blocked.some((path) => pathKey(path) === pathKey(root)) +} + +function failedStatus(summary: GitStatus, message: string): GitStatus { + return { ...summary, scanState: 'failed', scanError: message.slice(0, 4000) } +} + +interface StatusDependencies { + assertInside: (path: string) => void + insideRootFlags: (paths: string[]) => Promise + resolveGitPath: () => string | null + parseStatus: (stdout: string, root: string) => GitParsedStatus + run?: typeof runBoundedGitStatus +} + +/** One in-flight scan app-wide; same-repository callers share it, others fail fast. */ +export function createGitStatusService(deps: StatusDependencies): { + status: (dir: string, options?: GitStatusOptions) => Promise +} { + let active: { key: string; promise: Promise } | undefined + const requested = new Map>() + const run = deps.run ?? runBoundedGitStatus + + async function scan(summary: GitStatus): Promise { + try { + // Do not expand a trusted subfolder into a scan of an untrusted ancestor. + deps.assertInside(summary.root) + const git = deps.resolveGitPath() + if (!git) return failedStatus(summary, 'Git is not available') + const deadline = Date.now() + STATUS_TIMEOUT_MS + const command = async (args: string[]): Promise => { + const remaining = deadline - Date.now() + if (remaining <= 0) throw new Error('Git status scan timed out') + const result = await run(git, summary.root, args, { timeoutMs: remaining }) + if (result.code !== 0) throw new Error(result.stderr || 'Git status scan failed') + return result.stdout + } + // core.worktree / inherited GIT_* settings must not silently redirect the scan. + const top = (await command(['rev-parse', '--show-toplevel'])).trim() + const actualRoot = top && await fs.realpath(top) + if (!actualRoot || pathKey(actualRoot) !== pathKey(summary.root)) { + throw new Error('Git worktree differs from the opened repository; open its project root explicitly') + } + const output = await command([ + '-c', 'core.fsmonitor=false', 'status', '--porcelain=v2', '--branch', '--untracked-files=all', '-z' + ]) + const parsed = deps.parseStatus(output, summary.root) + const keepInside = async (list: GitStatus['staged']): Promise => { + const ok = await deps.insideRootFlags(list.map((file) => file.path)) + return list.filter((_, i) => ok[i]) + } + const [staged, unstaged, conflicts] = await Promise.all([ + keepInside(parsed.staged), keepInside(parsed.unstaged), keepInside(parsed.conflicts) + ]) + const remotes = (await command(['remote'])).split(/\r?\n/).filter(Boolean) + return { ...summary, ...parsed, staged, unstaged, conflicts, remotes, scanState: 'complete' } + } catch (error) { + return failedStatus(summary, error instanceof Error ? error.message : 'Git status scan failed') + } + } + + async function manualStatus(dir: string): Promise { + const summary = await readGitMetadata(dir) + if (!summary.isRepo) return summary + if (isUnsafeStatusRoot(summary.root)) { + return failedStatus(summary, 'Open a project repository instead of a drive, home or system directory') + } + const key = pathKey(summary.root) + if (active) { + return active.key === key + ? active.promise + : failedStatus(summary, 'Another Git status scan is already running; try again when it finishes') + } + // scan starts in a microtask so the slot exists even if a dependency throws. + const promise = Promise.resolve().then(() => scan(summary)) + active = { key, promise } + try { + return await promise + } finally { + if (active?.promise === promise) active = undefined + } + } + + return { + async status(dir, options) { + deps.assertInside(dir) + // Strict opt-in: old callers, null options and truthy strings cannot start Git. + if (options?.scan !== true) return readGitMetadata(dir) + const key = pathKey(dir) + const existing = requested.get(key) + if (existing) return existing + // Coalesce before metadata I/O too, so a quick scan cannot race its duplicate. + const promise = manualStatus(dir) + requested.set(key, promise) + try { + return await promise + } finally { + if (requested.get(key) === promise) requested.delete(key) + } + } + } +} diff --git a/apps/desktop/src/main/services/git.ts b/apps/desktop/src/main/services/git.ts index 47b46f89..192fe066 100644 --- a/apps/desktop/src/main/services/git.ts +++ b/apps/desktop/src/main/services/git.ts @@ -1,7 +1,12 @@ +import type { + GitStatusLetter, GitFileStatus, GitStatus, GitStatusOptions, GitParsedStatus +} from '../../shared/git-status' import { execFile } from 'node:child_process' import { existsSync, promises as fs } from 'node:fs' import { basename, delimiter, dirname, join, resolve } from 'node:path' -import { ipcMain } from 'electron' +import { app, ipcMain } from 'electron' +import { createGitStatusService } from './git-status' +import { cancelGitStatusScans } from './git-status-process' import { assertAllInside, assertInside, insideRootFlags } from './fs-guard' import { getConfig, getDevaHome } from './config' import { detectShells } from './shells' @@ -29,40 +34,7 @@ import { streamChat } from '../providers' // ── 导出类型(供 preload/renderer 复用;沿用 GitDiffView 现有渲染形状) ────────────── -export type GitStatusLetter = 'M' | 'A' | 'D' | 'U' | 'R' | 'C' | 'T' - -export interface GitFileStatus { - /** 绝对路径(渲染层回传给文件级操作,主进程再 assertInside 校验) */ - path: string - /** 仓库根相对路径(用于灰色路径展示与 diff pathspec) */ - rel: string - /** 文件名(basename) */ - name: string - /** 相对目录(rel 的 dirname,顶层为空串) */ - dir: string - letter: GitStatusLetter - staged: boolean - unstaged: boolean - conflicted: boolean - /** 未跟踪(新文件,git 尚无 diff → diff 视图直接读全文件当新增) */ - untracked: boolean -} - -export interface GitStatus { - isRepo: boolean - root: string - branch: string | null - detached: boolean - upstream: string | null - ahead: number - behind: number - remotes: string[] - /** 合并进行中(存在 MERGE_HEAD):UI 显示「合并中」并提供「中止合并」 */ - mergeInProgress: boolean - staged: GitFileStatus[] - unstaged: GitFileStatus[] - conflicts: GitFileStatus[] -} +export type { GitStatusLetter, GitFileStatus, GitStatus } from '../../shared/git-status' export interface GitDiffLine { type: 'ctx' | 'add' | 'del' | 'hunk' @@ -241,23 +213,6 @@ function runGitPaths(dir: string, args: string[], paths: string[]): Promise { +function parsePorcelainV2(stdout: string, root: string): GitParsedStatus { const tokens = stdout.split('\0') let branch: string | null = null let detached = false @@ -625,48 +577,17 @@ export function registerGitIpc(): void { } }) - // 核心:完整状态(分支 / upstream / ahead-behind / 分组文件) - ipcMain.handle('git:status', async (_e, dir: string): Promise => { - assertInside(dir) - const st = await runGitRaw(dir, [ - 'status', - '--porcelain=v2', - '--branch', - '--untracked-files=all', - '-z' - ]) - if (st.code !== 0) return emptyStatus(dir) // 非仓库 / 无 git - const top = await runGitRaw(dir, ['rev-parse', '--show-toplevel']) - const root = top.code === 0 && top.stdout.trim() ? resolve(top.stdout.trim()) : resolve(dir) - const parsed = parsePorcelainV2(st.stdout, root) - // 只保留落在受信根内的文件(常见情形 root===项目根,无过滤;子目录场景下过滤根外文件)。 - // 须批量判定:未跟踪文件逐个列出(-uall),大仓可达上万条,逐条 assertInside 会把主进程卡住。 - const keepInside = async (list: GitFileStatus[]): Promise => { - const ok = await insideRootFlags(list.map((f) => f.path)) - return list.filter((_, i) => ok[i]) - } - const [staged, unstaged, conflicts] = await Promise.all([ - keepInside(parsed.staged), - keepInside(parsed.unstaged), - keepInside(parsed.conflicts) - ]) - const remotes = await listRemotes(dir) - const merge = await runGitRaw(dir, ['rev-parse', '-q', '--verify', 'MERGE_HEAD']) - return { - isRepo: true, - root, - branch: parsed.branch, - detached: parsed.detached, - upstream: parsed.upstream, - ahead: parsed.ahead, - behind: parsed.behind, - remotes, - mergeInProgress: merge.code === 0, - staged, - unstaged, - conflicts - } + // Background requests read metadata only; enumeration requires a strict user opt-in. + const statusService = createGitStatusService({ + assertInside, + insideRootFlags, + resolveGitPath, + parseStatus: parsePorcelainV2 }) + app.once('before-quit', cancelGitStatusScans) + ipcMain.handle('git:status', (_e, dir: string, options?: GitStatusOptions): Promise => + statusService.status(dir, options) + ) // 文件级 diff:staged→index↔HEAD;unstaged→worktree↔index;未跟踪→读全文件当新增 ipcMain.handle( diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts index 6ce23e69..e8cf59e1 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -1,3 +1,4 @@ +import type { GitStatus, GitStatusOptions } from '../shared/git-status' import { contextBridge, ipcRenderer, webUtils } from 'electron' import type { EffortLevel } from '../shared/effort' import type { UpdateState } from '../shared/update' @@ -470,33 +471,7 @@ export interface TerminalExitPayload { exitCode: number } -/** Git「线缆类型」(与 services/git.ts 对齐,按既定模式在 preload 内复述)。 */ -export type GitStatusLetter = 'M' | 'A' | 'D' | 'U' | 'R' | 'C' | 'T' -export interface GitFileStatus { - path: string - rel: string - name: string - dir: string - letter: GitStatusLetter - staged: boolean - unstaged: boolean - conflicted: boolean - untracked: boolean -} -export interface GitStatus { - isRepo: boolean - root: string - branch: string | null - detached: boolean - upstream: string | null - ahead: number - behind: number - remotes: string[] - mergeInProgress: boolean - staged: GitFileStatus[] - unstaged: GitFileStatus[] - conflicts: GitFileStatus[] -} +export type { GitStatusLetter, GitFileStatus, GitStatus, GitStatusOptions } from '../shared/git-status' export interface GitDiffLine { type: 'ctx' | 'add' | 'del' | 'hunk' oldNo?: number @@ -961,8 +936,9 @@ const api = { git: { /** git 是否可用(定位成功 + --version 跑通) */ available: (): Promise => ipcRenderer.invoke('git:available'), - /** 完整状态(分支 / upstream / ahead-behind / 分组文件) */ - status: (dir: string): Promise => ipcRenderer.invoke('git:status', dir), + /** Metadata only by default; { scan: true } explicitly enumerates the worktree. */ + status: (dir: string, options?: GitStatusOptions): Promise => + ipcRenderer.invoke('git:status', dir, options), /** 文件级 diff(staged=index↔HEAD;否则 worktree↔index;untracked=读全文件当新增) */ diff: ( dir: string, diff --git a/apps/desktop/src/renderer/src/i18n/messages.ts b/apps/desktop/src/renderer/src/i18n/messages.ts index 1422ae8f..266a6d74 100644 --- a/apps/desktop/src/renderer/src/i18n/messages.ts +++ b/apps/desktop/src/renderer/src/i18n/messages.ts @@ -1253,6 +1253,9 @@ const zhCN: MessageTree = { }, git: { menuHint: 'Git 操作', + notScanned: '仅显示分支;点击刷新才扫描文件变更', + scanning: '正在扫描文件变更…', + scanFailed: 'Git 扫描未完成,不能确认文件变更', detached: '游离 HEAD', noBranch: '(无分支)', fetch: '获取', @@ -2771,6 +2774,9 @@ const en: MessageTree = { }, git: { menuHint: 'Git actions', + notScanned: 'Branch metadata only; click Refresh to scan file changes', + scanning: 'Scanning file changes…', + scanFailed: 'Git scan incomplete; file changes are unknown', detached: 'detached HEAD', noBranch: '(no branch)', fetch: 'Fetch', diff --git a/apps/desktop/src/renderer/src/redesign/Composer.tsx b/apps/desktop/src/renderer/src/redesign/Composer.tsx index a371a18a..860e9c2e 100644 --- a/apps/desktop/src/renderer/src/redesign/Composer.tsx +++ b/apps/desktop/src/renderer/src/redesign/Composer.tsx @@ -944,7 +944,7 @@ export const Composer = memo(function Composer({ }} > - + + )}