Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(worktree): 防止分支刷新破坏其他检出目录与忽略文件

fmfsaisaic5766f953182
diff --git a/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts b/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts
index db79ce4274..1558b8a9dc 100644
--- a/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/branchSync.git-integration.test.ts
@@ -214,3 +214,72 @@ it('disables a branch with no upstream when only a non-origin remote is configur
git(f.repo, 'remote', 'rename', 'origin', 'upstream');
expect((await readBranchSyncStatus(f.req)).blocked).toBe('no-remote');
});
+
+// PR #7059 regressions, git-integration tier: preflight checks alone cannot
+// protect duplicate checkouts, ignored local files, or a checkout before writing.
+// Existing clean/dirty fast-forward cases do not exercise these Git behaviors.
+it('refuses a branch forced into multiple worktrees without changing either checkout', async () => {
+ const f = fixture();
+ const checkout = path.join(root, 'duplicate-checkout');
+ git(f.repo, 'worktree', 'add', '--force', checkout, f.branch);
+ f.advance();
+ const snapshot = (cwd: string) => ({
+ head: git(cwd, 'rev-parse', 'HEAD'),
+ index: git(cwd, 'ls-files', '--stage'),
+ bytes: fs.readFileSync(path.join(cwd, 'base'), 'utf8'),
+ });
+ const before = [snapshot(f.repo), snapshot(checkout)];
+ expect((await readBranchSyncStatus(f.req)).blocked).toBe('multiple-checkouts');
+ expect(await syncBranch(f.req)).toMatchObject({
+ updated: 0,
+ status: { blocked: 'multiple-checkouts' },
+ });
+ expect([snapshot(f.repo), snapshot(checkout)]).toEqual(before);
+ expect(git(f.repo, 'rev-parse', f.branch)).toBe(before[0].head);
+});
+
+it('refuses to overwrite an ignored file with a remotely tracked file', async () => {
+ const f = fixture();
+ f.advance('config.json');
+ fs.appendFileSync(
+ path.resolve(f.repo, git(f.repo, 'rev-parse', '--git-path', 'info/exclude')),
+ '\nconfig.json\n',
+ );
+ fs.writeFileSync(path.join(f.repo, 'config.json'), 'local ignored configuration');
+ const before = git(f.repo, 'rev-parse', 'HEAD');
+ const index = git(f.repo, 'ls-files', '--stage');
+ expect(git(f.repo, 'status', '--porcelain')).toBe('');
+ expect(await syncBranch(f.req)).toMatchObject({ updated: 0, status: { blocked: 'conflict' } });
+ expect(git(f.repo, 'rev-parse', 'HEAD')).toBe(before);
+ expect(git(f.repo, 'ls-files', '--stage')).toBe(index);
+ expect(fs.readFileSync(path.join(f.repo, 'config.json'), 'utf8')).toBe(
+ 'local ignored configuration',
+ );
+});
+
+it('refuses an unchecked-branch write if another worktree checks it out after preflight', async () => {
+ const f = fixture();
+ f.advance();
+ const before = git(f.repo, 'rev-parse', f.branch);
+ git(f.repo, 'checkout', 'main');
+ const checkout = path.join(root, 'late-checkout');
+ let index: string | undefined;
+ const realGit = gitModule.gitExec;
+ const spy = vi.spyOn(gitModule, 'gitExec').mockImplementation(async (args, cwd, opts) => {
+ if (args[0] === 'fetch' && args.includes('.')) {
+ git(f.repo, 'worktree', 'add', checkout, f.branch);
+ index = git(checkout, 'ls-files', '--stage');
+ }
+ return realGit(args, cwd, opts);
+ });
+ try {
+ expect(await syncBranch(f.req)).toMatchObject({ updated: 0, status: { blocked: 'changed' } });
+ expect(index).toBeDefined();
+ expect(git(f.repo, 'rev-parse', f.branch)).toBe(before);
+ expect(git(checkout, 'rev-parse', 'HEAD')).toBe(before);
+ expect(git(checkout, 'ls-files', '--stage')).toBe(index);
+ expect(fs.readFileSync(path.join(checkout, 'base'), 'utf8')).toBe('base');
+ } finally {
+ spy.mockRestore();
+ }
+});
diff --git a/apps/desktop/src/main/worktree/branchSync.ts b/apps/desktop/src/main/worktree/branchSync.ts
index 50cbc57689..042ac09806 100644
--- a/apps/desktop/src/main/worktree/branchSync.ts
+++ b/apps/desktop/src/main/worktree/branchSync.ts
@@ -92,13 +92,16 @@ export async function readBranchSyncStatus(req: BranchSyncRequest): Promise<Bran
const worktrees = (
await gitExec(['worktree', 'list', '--porcelain', '-z'], baseRepo, localOpts)
).stdout;
+ const checkouts: string[] = [];
for (const block of worktrees.split('\0\0')) {
const fields = block.split('\0');
if (fields.includes(`branch ${localRef}`)) {
- status.checkoutPath = fields.find((s) => s.startsWith('worktree '))?.slice(9);
- break;
+ const checkout = fields.find((s) => s.startsWith('worktree '))?.slice(9);
+ if (checkout) checkouts.push(checkout);
}
}
+ if (checkouts.length > 1) return { ...status, blocked: 'multiple-checkouts' };
+ status.checkoutPath = checkouts[0];
}
const dirty = status.checkoutPath
? dirtyPaths(
@@ -207,7 +210,14 @@ async function syncBranchOnce(req: BranchSyncRequest): Promise<BranchSyncResult>
if ((await git(status.checkoutPath, 'symbolic-ref', 'HEAD')) !== `refs/heads/${req.branch}`)
throw new Error('The checked-out branch changed; retry');
try {
- await git(status.checkoutPath, 'merge', '--ff-only', '--no-autostash', next);
+ await git(
+ status.checkoutPath,
+ 'merge',
+ '--ff-only',
+ '--no-autostash',
+ '--no-overwrite-ignore',
+ next,
+ );
} catch (error) {
const refreshed = await readBranchSyncStatus(req);
if (refreshed.blocked) return { status: refreshed, updated: 0 };
@@ -216,7 +226,24 @@ async function syncBranchOnce(req: BranchSyncRequest): Promise<BranchSyncResult>
throw error;
}
} else {
- await git(req.baseRepo, 'update-ref', `refs/heads/${req.branch}`, next, old);
+ try {
+ // Local fetch refuses non-fast-forwards and branches checked out in any
+ // worktree at write time. update-ref has no checkout guard.
+ await git(
+ req.baseRepo,
+ 'fetch',
+ '--no-tags',
+ '--recurse-submodules=no',
+ '.',
+ `${next}:refs/heads/${req.branch}`,
+ );
+ } catch (error) {
+ const refreshed = await readBranchSyncStatus(req);
+ if (refreshed.blocked) return { status: refreshed, updated: 0 };
+ if (refreshed.checkoutPath)
+ return { status: { ...refreshed, blocked: 'changed' }, updated: 0 };
+ throw error;
+ }
}
return { status: await readBranchSyncStatus(req), updated };
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 492ffdda8d..fd17bb8541 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -11367,6 +11367,8 @@
}
},
"branchSync": {
+ "multiple-checkouts": "{{branch}} is checked out in multiple directories and cannot be updated safely",
+ "changed": "The branch state changed. Please retry.",
"action": "Fetch the latest commits for {{remoteBranch}} from {{remote}} and update local {{branch}}",
"remoteAction": "Fetch the latest commits for {{remoteBranch}} from {{remote}}",
"checkedOut": "{{branch}} is checked out in “{{directory}}”. Its files will also update; your uncommitted changes will be preserved.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 4a22b0644b..ad22c3bd58 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -11332,6 +11332,8 @@
}
},
"branchSync": {
+ "multiple-checkouts": "{{branch}} は複数のディレクトリで開かれているため、安全に更新できません",
+ "changed": "ブランチの状態が変わりました。再試行してください",
"action": "{{remote}} から {{remoteBranch}} の最新コミットを取得し、ローカルの {{branch}} を更新",
"remoteAction": "{{remote}} から {{remoteBranch}} の最新コミットを取得",
"checkedOut": "{{branch}} は「{{directory}}」で使用中です。そのファイルも更新されます。未コミットの変更は保持されます。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 93e3e33218..90e8a6a942 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -11332,6 +11332,8 @@
}
},
"branchSync": {
+ "multiple-checkouts": "{{branch}} 브랜치가 여러 디렉터리에 열려 있어 안전하게 업데이트할 수 없습니다",
+ "changed": "브랜치 상태가 변경되었습니다. 다시 시도해 주세요",
"action": "{{remote}}에서 {{remoteBranch}}의 최신 커밋을 가져와 로컬 {{branch}} 업데이트",
"remoteAction": "{{remote}}에서 {{remoteBranch}}의 최신 커밋 가져오기",
"checkedOut": "{{branch}}은(는) “{{directory}}”에서 사용 중입니다. 해당 파일도 업데이트되며 커밋하지 않은 변경 사항은 유지됩니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index c8c818d7bd..a7f3677ffb 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -11332,6 +11332,8 @@
}
},
"branchSync": {
+ "multiple-checkouts": "{{branch}} 同时在多个目录里打开,没法安全更新",
+ "changed": "分支状态已变化,请重试",
"action": "从 {{remote}} 拉取 {{remoteBranch}} 的最新提交,并更新本地 {{branch}}",
"remoteAction": "从 {{remote}} 拉取 {{remoteBranch}} 的最新提交",
"checkedOut": "{{branch}} 正在「{{directory}}」里使用,那里的文件会一起更新,你没提交的改动不受影响",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index a3937013be..e7ac8939d4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -11332,6 +11332,8 @@
}
},
"branchSync": {
+ "multiple-checkouts": "{{branch}} 同時在多個目錄中開啟,無法安全更新",
+ "changed": "分支狀態已變更,請重試",
"action": "從 {{remote}} 取得 {{remoteBranch}} 的最新提交,並更新本機 {{branch}}",
"remoteAction": "從 {{remote}} 取得 {{remoteBranch}} 的最新提交",
"checkedOut": "{{branch}} 正在「{{directory}}」中使用,那裡的檔案會一起更新,你尚未提交的變更不受影響",
diff --git a/apps/desktop/src/shared/worktreeBranchSync.ts b/apps/desktop/src/shared/worktreeBranchSync.ts
index ba8a974779..df067dce33 100644
--- a/apps/desktop/src/shared/worktreeBranchSync.ts
+++ b/apps/desktop/src/shared/worktreeBranchSync.ts
@@ -13,7 +13,14 @@ export interface BranchSyncStatus {
behind: number;
dirtyFiles: number;
checkoutPath?: string;
- blocked?: 'no-remote' | 'missing-remote' | 'diverged' | 'conflict' | 'not-local';
+ blocked?:
+ | 'no-remote'
+ | 'missing-remote'
+ | 'diverged'
+ | 'conflict'
+ | 'not-local'
+ | 'multiple-checkouts'
+ | 'changed';
}
export interface BranchSyncResult {
status: BranchSyncStatus;