From 2f83f94431bebe087d129aca37eb3e59247257a1 Mon Sep 17 00:00:00 2001 From: schattgieselman-lgtm <325688637+schattgieselman-lgtm@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:41:35 +0800 Subject: [PATCH 1/2] =?UTF-8?q?refactor(git):=20=E6=8F=90=E5=8F=96?= =?UTF-8?q?=E5=85=B1=E4=BA=AB=E7=8A=B6=E6=80=81=E7=B1=BB=E5=9E=8B=E4=B8=8E?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E9=92=A9=E5=AD=90=20/=20extract=20shared=20s?= =?UTF-8?q?tatus=20types=20and=20hook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/main/services/git.ts | 36 +--------- apps/desktop/src/preload/index.ts | 29 +------- .../src/renderer/src/redesign/GitWidget.tsx | 66 +------------------ .../renderer/src/redesign/use-git-status.ts | 66 +++++++++++++++++++ apps/desktop/src/shared/git-status.ts | 35 ++++++++++ 5 files changed, 107 insertions(+), 125 deletions(-) create mode 100644 apps/desktop/src/renderer/src/redesign/use-git-status.ts create mode 100644 apps/desktop/src/shared/git-status.ts diff --git a/apps/desktop/src/main/services/git.ts b/apps/desktop/src/main/services/git.ts index 47b46f89..c5709b53 100644 --- a/apps/desktop/src/main/services/git.ts +++ b/apps/desktop/src/main/services/git.ts @@ -1,3 +1,4 @@ +import type { GitStatusLetter, GitFileStatus, GitStatus } 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' @@ -29,40 +30,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' diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts index 6ce23e69..0dceee9a 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -1,3 +1,4 @@ +import type { GitStatus } 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 } from '../shared/git-status' export interface GitDiffLine { type: 'ctx' | 'add' | 'del' | 'hunk' oldNo?: number diff --git a/apps/desktop/src/renderer/src/redesign/GitWidget.tsx b/apps/desktop/src/renderer/src/redesign/GitWidget.tsx index 33fc9dc5..ac56ce57 100644 --- a/apps/desktop/src/renderer/src/redesign/GitWidget.tsx +++ b/apps/desktop/src/renderer/src/redesign/GitWidget.tsx @@ -1,7 +1,7 @@ /** * 版本控制:分支与变更状态、工作区菜单、提交对话框(含 AI 生成提交信息)。 */ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { ArrowDownToLine, ArrowUpFromLine, @@ -37,6 +37,7 @@ import { useDialog } from '../components/DialogProvider' import { useToast, type ToastOptions } from '../components/ToastProvider' import { Modal } from '../components/Modal' import { basename } from './shell-common' +import { useGitStatus } from './use-git-status' import { type CtxEntry, ContextMenu } from './ContextMenu' /* ─────────────────────────── Git 快捷面板(IDEA 式点击浮出) ─────────────────────────── @@ -46,19 +47,6 @@ import { type CtxEntry, ContextMenu } from './ContextMenu' * 不新增任何越权面,也不弹权限框(与「全放行 + 静默硬底线」一致)。 */ -/** git 是否可用:全应用只探一次(缓存 Promise),避免每次挂载都 spawn 一次 --version。 */ -let gitAvailablePromise: Promise | null = null - -function probeGitAvailable(): Promise { - if (!gitAvailablePromise) { - gitAvailablePromise = window.deva.git - .available() - .then((r) => r.available) - .catch(() => false) - } - return gitAvailablePromise -} - /** GitFailReason → 本地化文案;缺 key 时回落到通用「操作失败」。 */ function gitReasonText(t: (k: string) => string, reason?: GitFailReason): string { const key = `cf.git.err.${reason || 'error'}` @@ -104,56 +92,6 @@ function isValidBranchName(raw: string): boolean { return !/[\s~^:?*[\\\x00-\x1f\x7f]/.test(s) } -interface GitState { - available: boolean - status: GitStatus | null - busy: boolean - refresh: () => Promise -} - -/** - * 读取某工作区的 git 状态。不轮询(status 每次 spawn git 进程,且当前无文件监听): - * 只在「挂载 / 开菜单 / 每次写操作后」拉取。用 reqRef 防竞态——快速切换工作区时旧结果不覆盖新。 - */ -function useGitStatus(root: string | null): GitState { - const [available, setAvailable] = useState(false) - const [status, setStatus] = useState(null) - const [busy, setBusy] = useState(false) - const reqRef = useRef(0) - - const refresh = useCallback(async (): Promise => { - const seq = ++reqRef.current - if (!root) { - setAvailable(false) - setStatus(null) - return - } - const ok = await probeGitAvailable() - if (seq !== reqRef.current) return - setAvailable(ok) - if (!ok) { - setStatus(null) - return - } - setBusy(true) - try { - const st = await window.deva.git.status(root) - if (seq !== reqRef.current) return - setStatus(st.isRepo ? st : null) - } catch { - if (seq === reqRef.current) setStatus(null) - } finally { - if (seq === reqRef.current) setBusy(false) - } - }, [root]) - - useEffect(() => { - void refresh() - }, [refresh]) - - return { available, status, busy, refresh } -} - /** * 挂载 chip 里的分支 pill + 快捷菜单。仅当 git 可用且目标是仓库时渲染,否则返回 null(非仓库 / 没装 git 静默隐藏)。 * 菜单复用 ContextMenu(视口定位 + 越界夹回),始终只显示一级:点「分支」原地换成分支列表(含合并分支 / 新建分支), diff --git a/apps/desktop/src/renderer/src/redesign/use-git-status.ts b/apps/desktop/src/renderer/src/redesign/use-git-status.ts new file mode 100644 index 00000000..24c7cde2 --- /dev/null +++ b/apps/desktop/src/renderer/src/redesign/use-git-status.ts @@ -0,0 +1,66 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import type { GitStatus } from '../../../shared/git-status' + +/** git 是否可用:全应用只探一次(缓存 Promise),避免每次挂载都 spawn 一次 --version。 */ +let gitAvailablePromise: Promise | null = null + +function probeGitAvailable(): Promise { + if (!gitAvailablePromise) { + gitAvailablePromise = window.deva.git + .available() + .then((r) => r.available) + .catch(() => false) + } + return gitAvailablePromise +} + +interface GitState { + available: boolean + status: GitStatus | null + busy: boolean + refresh: () => Promise +} + +/** + * 读取某工作区的 git 状态。不轮询(status 每次 spawn git 进程,且当前无文件监听): + * 只在「挂载 / 开菜单 / 每次写操作后」拉取。用 reqRef 防竞态——快速切换工作区时旧结果不覆盖新。 + */ +export function useGitStatus(root: string | null): GitState { + const [available, setAvailable] = useState(false) + const [status, setStatus] = useState(null) + const [busy, setBusy] = useState(false) + const reqRef = useRef(0) + + const refresh = useCallback(async (): Promise => { + const seq = ++reqRef.current + if (!root) { + setAvailable(false) + setStatus(null) + return + } + const ok = await probeGitAvailable() + if (seq !== reqRef.current) return + setAvailable(ok) + if (!ok) { + setStatus(null) + return + } + setBusy(true) + try { + const st = await window.deva.git.status(root) + if (seq !== reqRef.current) return + setStatus(st.isRepo ? st : null) + } catch { + if (seq === reqRef.current) setStatus(null) + } finally { + if (seq === reqRef.current) setBusy(false) + } + }, [root]) + + useEffect(() => { + void refresh() + }, [refresh]) + + return { available, status, busy, refresh } +} + diff --git a/apps/desktop/src/shared/git-status.ts b/apps/desktop/src/shared/git-status.ts new file mode 100644 index 00000000..5471cda5 --- /dev/null +++ b/apps/desktop/src/shared/git-status.ts @@ -0,0 +1,35 @@ +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[] +} + From e8420e3f339bfa8c9dd936d225c3cb59bcb61a74 Mon Sep 17 00:00:00 2001 From: schattgieselman-lgtm <325688637+schattgieselman-lgtm@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:50:04 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(git):=20=E7=A6=81=E6=AD=A2=E5=90=8E?= =?UTF-8?q?=E5=8F=B0=E5=85=A8=E9=87=8F=E6=89=AB=E6=8F=8F=E5=B9=B6=E9=99=90?= =?UTF-8?q?=E5=88=B6=E7=8A=B6=E6=80=81=E8=BF=9B=E7=A8=8B=20/=20disable=20a?= =?UTF-8?q?utomatic=20worktree=20scans=20and=20bound=20status=20processes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 后台仅读取有界元数据,手动扫描才运行 Git / read bounded metadata in the background and run Git only for explicit scans - 合并重复请求并限制扫描时长与输出,超时清理本次进程树 / coalesce duplicate requests, bound time and output, and clean up owned process trees - 区分未扫描与失败状态,提交前失败关闭,并添加跨平台回归测试 / distinguish unknown and failed states, fail closed before committing, and add cross-platform regression tests --- .github/workflows/ci.yml | 17 ++ .gitignore | 1 + apps/desktop/package.json | 1 + .../src/main/services/git-status-process.ts | 114 +++++++ apps/desktop/src/main/services/git-status.ts | 191 ++++++++++++ apps/desktop/src/main/services/git.ts | 81 ++--- apps/desktop/src/preload/index.ts | 9 +- .../desktop/src/renderer/src/i18n/messages.ts | 6 + .../src/renderer/src/redesign/Composer.tsx | 2 +- .../src/renderer/src/redesign/GitWidget.tsx | 99 ++++-- .../renderer/src/redesign/use-git-status.ts | 53 +--- apps/desktop/src/shared/git-status.ts | 12 + apps/desktop/tests/git-status-process.test.ts | 107 +++++++ apps/desktop/tests/git-status.test.ts | 284 ++++++++++++++++++ apps/desktop/tsconfig.git-test.json | 19 ++ 15 files changed, 856 insertions(+), 140 deletions(-) create mode 100644 apps/desktop/src/main/services/git-status-process.ts create mode 100644 apps/desktop/src/main/services/git-status.ts create mode 100644 apps/desktop/tests/git-status-process.test.ts create mode 100644 apps/desktop/tests/git-status.test.ts create mode 100644 apps/desktop/tsconfig.git-test.json 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 c5709b53..192fe066 100644 --- a/apps/desktop/src/main/services/git.ts +++ b/apps/desktop/src/main/services/git.ts @@ -1,8 +1,12 @@ -import type { GitStatusLetter, GitFileStatus, GitStatus } from '../../shared/git-status' +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' @@ -209,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 @@ -593,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 0dceee9a..e8cf59e1 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -1,4 +1,4 @@ -import type { GitStatus } from '../shared/git-status' +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' @@ -471,7 +471,7 @@ export interface TerminalExitPayload { exitCode: number } -export type { GitStatusLetter, GitFileStatus, GitStatus } from '../shared/git-status' +export type { GitStatusLetter, GitFileStatus, GitStatus, GitStatusOptions } from '../shared/git-status' export interface GitDiffLine { type: 'ctx' | 'add' | 'del' | 'hunk' oldNo?: number @@ -936,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({ }} > - + + )}