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(desktop): 禁止把 worktree 会话移动到其他项目

Zhang Yunjin974b4ea6027e
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index ed600fc05b..bba3b05c89 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -1050,6 +1050,53 @@ describe('local-db:sessions:update handler wiring', () => {
expect(h.relocate).not.toHaveBeenCalled();
expect(h.closeSession).not.toHaveBeenCalled();
});
+
+ it('refuses to move a task whose working directory is a managed worktree', async () => {
+ const worktreeDir = path.join(h.userDataDir!, '.cindy-worktrees', 'steady-goodall');
+ h.sqlite!.prepare('UPDATE sessions SET working_dir = ? WHERE id = ?').run(worktreeDir, 'cc-local');
+
+ await expect(invokeUpdate('cc-local', { workingDir: '/new/dir' }))
+ .rejects.toThrow(/cannot be moved outside its worktree/i);
+
+ // 拒绝发生在任何写库/关 runtime 之前:归属分裂的“半移动”不会落盘。
+ expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('cc-local'))
+ .toEqual({ working_dir: worktreeDir });
+ expect(h.closeSession).not.toHaveBeenCalled();
+ expect(h.relocate).not.toHaveBeenCalled();
+ });
+
+ it('refuses the same move through the shared entry point used by the MCP tools', async () => {
+ const worktreeDir = path.join(h.userDataDir!, '.cindy-worktrees', 'steady-goodall');
+ h.sqlite!.prepare('UPDATE sessions SET working_dir = ? WHERE id = ?').run(worktreeDir, 'codex-local');
+
+ // MCP 的 move_sessions 等非 IPC 调用方直接走 updateSessionInDb:守卫必须同样生效,
+ // 且让调用方看到「需要 handoff」而不是笼统的移动失败。
+ await expect(updateSessionInDb('codex-local', { workingDir: '/new/dir' }))
+ .rejects.toThrow(/worktree handoff is required/i);
+
+ expect(h.closeIdleSessionForMove).not.toHaveBeenCalled();
+ expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('codex-local'))
+ .toEqual({ working_dir: worktreeDir });
+ });
+
+ it('allows binding a task to the worktree created for it', async () => {
+ const worktreeDir = path.join(h.userDataDir!, '.cindy-worktrees', 'steady-goodall');
+
+ await invokeUpdate('cc-local', { workingDir: worktreeDir });
+
+ expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('cc-local'))
+ .toEqual({ working_dir: worktreeDir.replace(/\\/g, '/') });
+ });
+
+ it('allows a no-op move that stays inside the same worktree root', async () => {
+ const worktreeDir = path.join(h.userDataDir!, '.cindy-worktrees', 'steady-goodall');
+ h.sqlite!.prepare('UPDATE sessions SET working_dir = ? WHERE id = ?').run(worktreeDir, 'cc-local');
+
+ await invokeUpdate('cc-local', { workingDir: worktreeDir.replace(/\\/g, '/') });
+
+ expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('cc-local'))
+ .toEqual({ working_dir: worktreeDir.replace(/\\/g, '/') });
+ });
});
async function invokeSetPinnedCardSummaries(event: unknown, enabled: unknown): Promise<unknown> {
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 15f3c3808b..cd5cf4aedc 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -1722,6 +1722,10 @@ export function registerSessionIpc(
* 会话操作工具(move / pin / delete 等)共用这一条路径:路由锁 + worktree 锁、
* review 会话拒改、Pi/Codex 空闲 runtime 关闭、cc 转录目录搬迁、recent-workdir
* 维护、sessions:patched 广播与 agent-island 通知都在这里,不得另起平行写入链路。
+ *
+ * 「绑定托管 worktree 的会话不得改到该 worktree 之外」是这里的不变量,所有入口
+ * (GUI 侧栏、MCP 工具、device-link)一并生效;GUI 侧的预检只为及时反馈,规则
+ * 以本函数为准,不得在入口层另立一份。
*/
export async function updateSessionInDb(
sid: string,
@@ -1799,6 +1803,26 @@ export async function updateSessionInDb(
.where(eq(sessions.id, sid))
)[0]
: undefined;
+ // worktree-handoff:worktree 会话的工作区边界就是它绑定的 worktree。只改 workingDir
+ // 会留下「半移动」—— 侧栏按新项目归组,而聊天框底部路径、Git 上下文、worktree
+ // store 归属与回收义务仍留在旧 worktree。完整的 worktree → Local Handoff 是独立
+ // 特性(#2190/#2585,需显式处置未提交改动与 worktree 归属),落地前这里拒绝把会话
+ // 移出 worktree;worktree 创建流程(基线目录 → 自己的 worktree)与同 worktree 内的
+ // no-op 不受影响。拦截发生在关 runtime / 写库 / 转录迁移之前,拒绝不留部分写入。
+ const currentWorktreeRoot =
+ beforeMove && !beforeMove.remoteHostId && beforeMove.workingDir
+ ? managedWorktreeRoot(beforeMove.workingDir)
+ : null;
+ const targetWorktreeRoot =
+ typeof p.workingDir === 'string' && p.workingDir
+ ? managedWorktreeRoot(p.workingDir)
+ : null;
+ if (currentWorktreeRoot && currentWorktreeRoot !== targetWorktreeRoot) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'A worktree session cannot be moved outside its worktree; worktree handoff is required',
+ );
+ }
const movingLocalNonClaudeSession =
beforeMove &&
beforeMove.agentKind !== 'cc' &&
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 007608d85f..d1b9cb098c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -222,6 +222,7 @@ import {
} from './lib/sidebarCollapseConfig';
import { getSessionListCollapseView } from './lib/sessionListCollapse';
import { hasSessionSelectionModifier, type SessionClickModifiers } from './sidebar/SessionItem';
+import { isManagedWorktreeWorkingDir } from './lib/sessionMoveGuard';
import type { SessionMoveTarget } from './sidebar/sessionMoveTarget';
import {
DIALOGUE_FILTER_KEY,
@@ -2686,6 +2687,13 @@ function ExpandedView({
toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectRemoteUnsupported'));
return;
}
+ // worktree 会话的工作区就是它自己的 worktree:只改 workingDir 会造成半移动
+ // (侧栏按新项目归组,聊天框底部路径仍指旧 worktree)。handoff 是独立特性,
+ // 先按 MoveWorktreeBlocked 拒绝;移到对话不改目录,不受影响。
+ if (target.kind !== 'dialogue' && isManagedWorktreeWorkingDir(session.workingDir)) {
+ toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectWorktreeBlocked'));
+ return;
+ }
if (effectiveRunningSessionIds.has(sessionId)) {
toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectRunningBlocked'));
return;
diff --git a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
index 3ce0454412..a9fa22ed41 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx
@@ -76,6 +76,7 @@ import {
MENU_SUB_CONTENT_CLASS,
} from './sidebar/menuStyles';
import { SessionProjectMoveSubmenu } from './sidebar/SessionProjectMoveSubmenu';
+import { isManagedWorktreeWorkingDir } from './lib/sessionMoveGuard';
import type { SessionMoveTarget } from './sidebar/sessionMoveTarget';
import { SessionShareExportDialog } from './sidebar/SessionShareExportDialog';
import { SessionBranchTreeDialog } from './SessionBranchTreeDialog';
@@ -312,6 +313,12 @@ export function SessionContentHeader({
toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectRemoteUnsupported'));
return;
}
+ // 与 CCAgentSidebarUpper 同款:worktree 会话不能改 workingDir(半移动),
+ // 移到对话不改目录、仍允许。
+ if (target.kind !== 'dialogue' && isManagedWorktreeWorkingDir(session.workingDir)) {
+ toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectWorktreeBlocked'));
+ return;
+ }
if (runningSessionIds.has(session.id)) {
toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectRunningBlocked'));
return;
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionMoveGuard.test.ts b/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionMoveGuard.test.ts
new file mode 100644
index 0000000000..b953ad0491
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/__tests__/sessionMoveGuard.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { isManagedWorktreeWorkingDir } from '../sessionMoveGuard';
+
+describe('isManagedWorktreeWorkingDir', () => {
+ it('recognizes managed worktrees, legacy names and their descendants', () => {
+ expect(isManagedWorktreeWorkingDir('/repo/.cindy-worktrees/steady-goodall')).toBe(true);
+ expect(isManagedWorktreeWorkingDir('D:\\repo\\.cindy-worktrees\\steady-goodall')).toBe(true);
+ expect(isManagedWorktreeWorkingDir('/repo/.xdt-worktrees/steady-goodall/sub')).toBe(true);
+ });
+
+ it('leaves ordinary projects, user-managed worktrees and empty values alone', () => {
+ expect(isManagedWorktreeWorkingDir('/repo/src')).toBe(false);
+ expect(isManagedWorktreeWorkingDir('/repo/.worktrees/steady-goodall')).toBe(false);
+ expect(isManagedWorktreeWorkingDir('/repo/.claude/worktrees/steady-goodall')).toBe(false);
+ expect(isManagedWorktreeWorkingDir(null)).toBe(false);
+ expect(isManagedWorktreeWorkingDir(undefined)).toBe(false);
+ expect(isManagedWorktreeWorkingDir('')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionMoveGuard.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionMoveGuard.ts
new file mode 100644
index 0000000000..76bc1e1344
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionMoveGuard.ts
@@ -0,0 +1,23 @@
+/**
+ * 会话移动守卫:worktree 会话的工作区边界就是它自己的 worktree。
+ *
+ * 「移动到项目 / 选择项目文件夹」只改 `sessions.working_dir`,而会话绑定的 worktree
+ * (目录、分支、store 归属与回收义务)不会跟着走:一旦允许改到别处,侧栏按新项目归组,
+ * 聊天框底部路径、Git 上下文与 worktree 徽标却仍指旧 worktree,形成「半移动」。
+ * 完整的 worktree → Local Handoff 是独立特性(#2190 / #2585,需显式处置未提交改动),
+ * 在它落地前 GUI 与 Main(`local-db:sessions:update`)同口径拒绝。
+ *
+ * 判据只认 **Cindy 托管 worktree**(`.cindy-worktrees` / `.xdt-worktrees`)——用户自建的
+ * `.worktrees` 不在 Cindy 生命周期内,移动它不构成归属分裂。含 worktree 的子目录。
+ */
+
+import { managedWorktreeBaseRepo } from '@cindy/maker-shared/worktree-paths';
+
+/**
+ * 该 workingDir 是否落在 Cindy 托管 worktree 内(Cindy 托管根本身或其子目录)。
+ * 只做纯字符串判定,不碰文件系统;`working_dir` 缺失时返回 false。
+ */
+export function isManagedWorktreeWorkingDir(workingDir: string | null | undefined): boolean {
+ if (typeof workingDir !== 'string' || workingDir.length === 0) return false;
+ return managedWorktreeBaseRepo(workingDir) !== null;
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fbce8a009e..b8fd025956 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9763,6 +9763,7 @@
"moveToProjectRunningBlocked": "This session is running. Move it after it finishes.",
"moveToProjectAttachedBlocked": "This session is being controlled remotely. Move it after control ends.",
"moveToProjectRemoteUnsupported": "Moving remote sessions is not supported yet",
+ "moveToProjectWorktreeBlocked": "This task's working directory is a worktree, so it can't be moved to another project yet",
"openInNewWindow": "Open in new window",
"exportShare": "Export session…",
"exportHtml": "Export to HTML…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 2244e12282..b49a02a06b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9748,6 +9748,7 @@
"moveToProjectRunningBlocked": "このセッションは実行中です。完了後に移動してください。",
"moveToProjectAttachedBlocked": "このセッションはリモート操作中です。操作終了後に移動してください。",
"moveToProjectRemoteUnsupported": "リモートセッションの移動はまだサポートされていません",
+ "moveToProjectWorktreeBlocked": "このタスクの作業ディレクトリは worktree のため、他のプロジェクトへは移動できません",
"openInNewWindow": "新しいウィンドウで開く",
"exportShare": "セッションをエクスポート…",
"exportHtml": "HTML にエクスポート…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b658969371..f74aa93c17 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9748,6 +9748,7 @@
"moveToProjectRunningBlocked": "이 세션은 실행 중입니다. 완료된 후 이동하세요.",
"moveToProjectAttachedBlocked": "이 세션은 원격 연결 중입니다. 제어가 끝난 후 이동하세요.",
"moveToProjectRemoteUnsupported": "원격 세션 이동은 아직 지원하지 않습니다",
+ "moveToProjectWorktreeBlocked": "이 작업의 작업 디렉터리는 worktree이므로 다른 프로젝트로 이동할 수 없습니다",
"openInNewWindow": "새 창에서 열기",
"exportShare": "세션 내보내기…",
"exportHtml": "HTML로 내보내기…",
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 1792a08da9..0bc492264a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9744,6 +9744,7 @@
"moveToProjectRunningBlocked": "任务正在运行,结束后再移动",
"moveToProjectAttachedBlocked": "任务正在被接管,结束接管后再移动",
"moveToProjectRemoteUnsupported": "暂不支持移动远程任务",
+ "moveToProjectWorktreeBlocked": "该任务的工作目录是 worktree,暂不支持移动到其他项目",
"openInNewWindow": "在新窗口打开",
"exportShare": "导出任务…",
"exportHtml": "导出为 HTML…",
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 5391418f79..f1b9360531 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9744,6 +9744,7 @@
"moveToProjectRunningBlocked": "任務正在執行,結束後再移動",
"moveToProjectAttachedBlocked": "任務正在被接管,結束接管後再移動",
"moveToProjectRemoteUnsupported": "暫不支援移動遠端任務",
+ "moveToProjectWorktreeBlocked": "此任務的工作目錄是 worktree,暫不支援移動到其他專案",
"openInNewWindow": "在新視窗開啟",
"exportShare": "匯出任務…",
"exportHtml": "匯出為 HTML…",