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 归属以 worktreeStore 为准,路径比较统一走 workingDirEquals

Zhang Yunjin9c083d22da71
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b6b5ced3b8..f207ce6195 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -533,6 +533,7 @@ import {
registerWorktreeIpc,
WorktreePool,
reconcilePendingSafeDirectoryCleanups,
+ worktreeStore,
} from './worktree';
// shadow savepoint 链的启动期对账(孤儿 refs/cindy/savepoints/* 清理)
import { reconcileSavepointRefsForDeletedSessions } from './git-snapshot/savepointCleanup';
@@ -8513,6 +8514,7 @@ app.on('ready', async () => {
readHistoryLiveMessages: getSessionThinkingSnapshots,
resolveContextWindow: (session) => resolveSessionContextWindow(getActiveCatalog(), session),
requestWorktreeRecycle,
+ lookupSessionWorktreeBinding: (sessionId) => worktreeStore.get(sessionId)?.path ?? null,
cancelSessionOperations: cancelIOSSimulatorSessionOperations,
cleanupRemovedSession: cleanupIOSSimulatorRemovedSession,
closeIdleSessionForMove: async (sessionId) => {
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 0f3bbd6698..75ea02acea 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -149,6 +149,7 @@ import {
registerSessionIpc,
resumeDeletedPiSubagentCleanup,
setSessionRuntimeCleanup,
+ setSessionWorktreeBindingLookup,
setSessionWorktreeRecycle,
updateSessionInDb,
} from '../sessions';
@@ -307,11 +308,13 @@ beforeEach(() => {
setSessionRouteLockImplementation(h.routeLock);
setSessionRuntimeCleanup(h.runtimeCleanup);
setSessionWorktreeRecycle(h.requestRecycle);
+ setSessionWorktreeBindingLookup(null);
registerSessionIpc(undefined, { closeIdleSessionForMove: h.closeIdleSessionForMove });
});
afterEach(async () => {
setSessionRuntimeCleanup(null);
+ setSessionWorktreeBindingLookup(null);
setSessionWorktreeRecycle(null);
setSessionRouteLockImplementation(null);
const dir = h.userDataDir;
@@ -1091,6 +1094,38 @@ describe('local-db:sessions:update handler wiring', () => {
.toEqual({ working_dir: to.replace(/\\/g, '/') });
});
+ it('refuses further moves for a session still bound to a worktree after an earlier half-move', async () => {
+ const worktreeDir = path.join(h.userDataDir!, '.cindy-worktrees', 'steady-goodall');
+ // 旧版允许过的半移动存量行:cwd 已经落在普通项目,worktree 绑定还在旧 worktree。
+ // 只看 cwd 会漏掉这类行,归属必须问 worktreeStore(组合层注入)。
+ h.sqlite!.prepare('UPDATE sessions SET working_dir = ?, worktree_path = ? WHERE id = ?')
+ .run('/other/project', worktreeDir, 'cc-local');
+ setSessionWorktreeBindingLookup((sessionId) => (sessionId === 'cc-local' ? worktreeDir : null));
+
+ await expect(invokeUpdate('cc-local', { workingDir: '/another/project' }))
+ .rejects.toThrow(/cannot be moved outside its worktree/i);
+ expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('cc-local'))
+ .toEqual({ working_dir: '/other/project' });
+
+ // 移回它自己的 worktree 是修复而不是跨根,应当放行。
+ 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('does not treat a recycled worktree snapshot as a live binding', async () => {
+ const worktreeDir = path.join(h.userDataDir!, '.cindy-worktrees', 'recycled-name');
+ // 回收后 worktreeStore 删条目但保留 DB 快照(徽标以 store 为准):这类行不应被拦住。
+ h.sqlite!.prepare('UPDATE sessions SET working_dir = ?, worktree_path = ? WHERE id = ?')
+ .run('/other/project', worktreeDir, 'cc-local');
+ setSessionWorktreeBindingLookup(() => null);
+
+ await invokeUpdate('cc-local', { workingDir: '/another/project' });
+
+ expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('cc-local'))
+ .toEqual({ working_dir: '/another/project' });
+ });
+
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');
diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.ts
index 058cd51e46..03e8336543 100644
--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts
+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts
@@ -18,6 +18,7 @@ import {
type RegisterSessionIpcOpts,
setSessionRemovalCancelOperations,
setSessionRemovalCleanup,
+ setSessionWorktreeBindingLookup,
setSessionWorktreeRecycle,
} from './sessions';
import { registerMessageIpc } from './messages';
@@ -92,6 +93,8 @@ export interface RegisterLocalDbIpcOpts {
cleanupRemovedSession?: (sessionId: string) => Promise<void>;
/** Record worktree recycle intent before a terminal session status is persisted. */
requestWorktreeRecycle?: (sessionId: string, resources?: readonly string[]) => Promise<void>;
+ /** 当前 worktree 绑定(worktreeStore 是 source of truth,DB 只存反范式快照)。 */
+ lookupSessionWorktreeBinding?: (sessionId: string) => string | null;
/** Close a moved local Pi/Codex runtime after revalidating that its turn is idle. */
closeIdleSessionForMove?: (sessionId: string) => Promise<boolean>;
/** Reconcile persisted Host-owned task runtimes once the owner DB is readable. */
@@ -121,6 +124,7 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {
setSessionRemovalCancelOperations(opts.cancelSessionOperations ?? null);
setSessionRemovalCleanup(opts.cleanupRemovedSession ?? null);
setSessionWorktreeRecycle(opts.requestWorktreeRecycle ?? null);
+ setSessionWorktreeBindingLookup(opts.lookupSessionWorktreeBinding ?? null);
setSessionRouteLockImplementation(opts.withSessionLock ?? null);
const runEnsureReady = createOwnerEnsureCoordinator({
isOwnerCurrent: opts.isOwnerCurrent ?? (() => true),
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index cd5cf4aedc..fa418a722a 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -66,7 +66,7 @@ import {
DESKTOP_VISIBLE_SESSION_SOURCES,
isRetainableProjectSessionSource,
} from '../../../shared/sessionSource.js';
-import { normalizeWorkingDirForStorage } from '../../../shared/workingDir.js';
+import { normalizeWorkingDirForStorage, workingDirEquals } from '../../../shared/workingDir.js';
import { assertRendererSessionSourceAllowed } from './sessionSourceGuard.js';
import type { SessionReference } from '../../../shared/sessionReference.js';
import * as broadcastTap from '../../device-link/broadcast-tap.js';
@@ -149,6 +149,21 @@ let sessionRemovalCancelOperations: SessionRemovalCancelOperations | null = null
let sessionRemovalCleanup: SessionRemovalCleanup | null = null;
let sessionWorktreeRecycle: SessionWorktreeRecycle | null = null;
+/**
+ * 会话当前 worktree 绑定的查询口。source of truth 是 worktreeStore(electron-store):
+ * `sessions.worktree_path` 只是反范式快照,且回收后刻意保留历史值(徽标看 store
+ * 是否存在),所以不能用它当「是否仍持有 worktree」的判据。
+ */
+type SessionWorktreeBindingLookup = (sessionId: string) => string | null;
+let sessionWorktreeBindingLookup: SessionWorktreeBindingLookup | null = null;
+
+/** Composition-root injection keeps the localDb IPC layer independent of worktree implementation modules. */
+export function setSessionWorktreeBindingLookup(
+ lookup: SessionWorktreeBindingLookup | null,
+): void {
+ sessionWorktreeBindingLookup = lookup;
+}
+
/** Composition-root injection for Host-owned operations that must stop before worktree recycle. */
export function setSessionRemovalCancelOperations(
cancelOperations: SessionRemovalCancelOperations | null,
@@ -1809,19 +1824,28 @@ export async function updateSessionInDb(
// 特性(#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',
- );
+ //
+ // 归属以 worktreeStore(组合层注入)为真源:旧版允许过的「半移动」会给会话留下
+ // working_dir 在普通项目、绑定仍在旧 worktree 的状态,只看 cwd 会漏掉这类存量行;
+ // 反过来,DB 的 worktree_path 快照在回收后仍保留历史值,也不能当活绑定用。
+ const requestedWorkingDir = typeof p.workingDir === 'string' ? p.workingDir : null;
+ if (
+ beforeMove &&
+ !beforeMove.remoteHostId &&
+ requestedWorkingDir &&
+ !workingDirEquals(requestedWorkingDir, beforeMove.workingDir)
+ ) {
+ const boundWorktreePath = sessionWorktreeBindingLookup?.(sid) ?? null;
+ const ownedWorktreeRoot =
+ (boundWorktreePath ? managedWorktreeRoot(boundWorktreePath) : null) ??
+ (beforeMove.workingDir ? managedWorktreeRoot(beforeMove.workingDir) : null);
+ const targetWorktreeRoot = managedWorktreeRoot(requestedWorkingDir);
+ if (ownedWorktreeRoot && !workingDirEquals(ownedWorktreeRoot, targetWorktreeRoot)) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'A worktree session cannot be moved outside its worktree; worktree handoff is required',
+ );
+ }
}
const movingLocalNonClaudeSession =
beforeMove &&
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index edb788cb4f..92e6f08da7 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -13,7 +13,7 @@ import {
import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';
import { getManagedWorktreeBasePath } from '../../shared/managedWorktreePaths.js';
-import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
+import { normalizeWorkingDirForStorage, workingDirEquals } from '../../shared/workingDir.js';
import {
createHostSendFailure,
@@ -60,21 +60,6 @@ function sameDirectoryList(left: readonly string[], right: readonly string[]): b
return left.length === right.length && left.every((value, index) => value === right[index]);
}
-/**
- * 同一物理目录的不同拼写(分隔符、尾斜杠、Windows 盘符/UNC 大小写)不算目录漂移。
- * 会话移动的漂移判定必须用它 —— 纯字符串比较会在仅拼写不同时白白关掉并重建活
- * runtime。POSIX 路径保持大小写敏感(与 `projectKeys` 的 local 比较口径一致)。
- */
-function sameWorkingDir(left: string, right: string): boolean {
- const a = normalizeWorkingDirForStorage(left) ?? left;
- const b = normalizeWorkingDirForStorage(right) ?? right;
- if (a === b) return true;
- const caseFoldable = (value: string): boolean => /^[A-Za-z]:\//.test(value) || value.startsWith('//');
- return process.platform === 'win32' && caseFoldable(a) && caseFoldable(b)
- ? a.toLowerCase() === b.toLowerCase()
- : false;
-}
-
/**
* Apply the exact directory-grant subset that a session may start with. Existing local
* session rows are narrowed before the runtime is created, so a failed persist cannot
@@ -1018,7 +1003,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
((sess.agentKind === 'claude-code' || sess.agentKind === 'pi') &&
!!deps.peekWorkingDirectoryRecoveryNote?.(sessionId, sess.workDir));
const persistedDirReady =
- ok && !liveDirNeedsRecovery && fallbackDir && !sameWorkingDir(fallbackDir, sess.workDir)
+ ok && !liveDirNeedsRecovery && fallbackDir && !workingDirEquals(fallbackDir, sess.workDir)
? await isUsablePersistedWorkingDir(
sessionId,
fallbackDir,
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
index 4b121b1fe2..7e7d73010f 100644
--- 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
@@ -52,4 +52,31 @@ describe('crossesWorktreeBoundary', () => {
expect(crossesWorktreeBoundary(null, '/elsewhere')).toBe(false);
expect(crossesWorktreeBoundary('/repo/.worktrees/user-made', '/elsewhere')).toBe(false);
});
+
+ it('treats separator and Windows case variants of the same root as the same worktree', () => {
+ // 目录选择器给原生 `\` 拼写,而 working_dir 落库时是 `/`:不能因此误拦。
+ expect(
+ crossesWorktreeBoundary('D:/repo/.cindy-worktrees/steady-goodall', 'D:\\repo\\.cindy-worktrees\\steady-goodall\\tests'),
+ ).toBe(false);
+ expect(
+ crossesWorktreeBoundary('D:\\repo\\.xdt-worktrees\\legacy', 'D:/repo/.xdt-worktrees/legacy/src'),
+ ).toBe(false);
+
+ // Windows 盘符/UNC 大小写差异也不算跨根(平台显式伪造,非 Windows CI 同样执行)。
+ const host = globalThis as { electronAPI?: { platform?: string } };
+ const previous = host.electronAPI;
+ try {
+ host.electronAPI = { platform: 'win32' };
+ expect(
+ crossesWorktreeBoundary('D:/repo/.cindy-worktrees/steady-goodall', 'd:/REPO/.cindy-worktrees/steady-goodall/src'),
+ ).toBe(false);
+ // POSIX 路径大小写敏感:盘符规则不能把两个真实存在的不同目录当成同一个。
+ expect(
+ crossesWorktreeBoundary('/repo/.cindy-worktrees/steady-goodall', '/REPO/.cindy-worktrees/steady-goodall/src'),
+ ).toBe(true);
+ } finally {
+ if (previous === undefined) delete host.electronAPI;
+ else host.electronAPI = previous;
+ }
+ });
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sessionMoveGuard.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sessionMoveGuard.ts
index 658939f822..603ecb94e1 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/sessionMoveGuard.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sessionMoveGuard.ts
@@ -17,6 +17,15 @@
import { managedWorktreeBaseRepo } from '@cindy/maker-shared/worktree-paths';
+import { workingDirEquals } from '../../../../shared/workingDir';
+
+/** renderer 里判断宿主平台:优先问 bridge,单测(node 环境)回落 `process`。 */
+function isWindowsHost(): boolean {
+ const bridged = (globalThis as { electronAPI?: { platform?: string } }).electronAPI?.platform;
+ if (typeof bridged === 'string') return bridged === 'win32';
+ return typeof process !== 'undefined' && process.platform === 'win32';
+}
+
/** 反斜杠是否算分隔符:只有盘符路径(`C:\`)与反斜杠 UNC(`\\server\share`)才算。 */
function usesBackslashSeparator(value: string): boolean {
return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith('\\\\');
@@ -64,5 +73,8 @@ export function crossesWorktreeBoundary(
): boolean {
const currentRoot = managedWorktreeRootOf(currentWorkingDir);
if (currentRoot === null) return false;
- return currentRoot !== managedWorktreeRootOf(targetWorkingDir);
+ const targetRoot = managedWorktreeRootOf(targetWorkingDir);
+ // 比的是同一物理目录:分隔符风格(目录选择器给 `\`、库里存 `/`)与 Windows 盘符/
+ // UNC 大小写差异都不算跨根,比较口径与 Main 的守卫一致。
+ return targetRoot === null || !workingDirEquals(currentRoot, targetRoot, { windows: isWindowsHost() });
}
diff --git a/apps/desktop/src/shared/__tests__/workingDir.test.ts b/apps/desktop/src/shared/__tests__/workingDir.test.ts
index 2688c19e17..eed9061c80 100644
--- a/apps/desktop/src/shared/__tests__/workingDir.test.ts
+++ b/apps/desktop/src/shared/__tests__/workingDir.test.ts
@@ -4,6 +4,7 @@ import {
normalizeWorkingDirForGrouping,
normalizeWorkingDirForProjectSettings,
normalizeWorkingDirForStorage,
+ workingDirEquals,
} from '../workingDir';
describe('workingDir normalization', () => {
@@ -48,3 +49,25 @@ describe('workingDir normalization', () => {
).toBe('/repo/.claude/worktrees/manual/src');
});
});
+
+describe('workingDirEquals', () => {
+ it('ignores storage-level spelling differences on every platform', () => {
+ expect(workingDirEquals('/repo/foo', '/repo/foo/')).toBe(true);
+ expect(workingDirEquals('D:\\repo\\foo', 'D:/repo/foo', { windows: true })).toBe(true);
+ expect(workingDirEquals('\\\\?\\D:\\repo\\foo', 'D:/repo/foo')).toBe(true);
+ });
+
+ it('folds Windows drive / UNC case only when asked to', () => {
+ expect(workingDirEquals('D:/repo/foo', 'd:/REPO/FOO', { windows: true })).toBe(true);
+ expect(workingDirEquals('//server/share/foo', '//SERVER/SHARE/FOO', { windows: true })).toBe(true);
+ expect(workingDirEquals('D:/repo/foo', 'd:/REPO/FOO', { windows: false })).toBe(false);
+ // POSIX 下大小写敏感:不能把两个真实存在的不同目录当成同一个。
+ expect(workingDirEquals('/repo/foo', '/REPO/FOO', { windows: true })).toBe(false);
+ });
+
+ it('reports distinct and empty directories as not equal', () => {
+ expect(workingDirEquals('/repo/foo', '/repo/bar')).toBe(false);
+ expect(workingDirEquals('/repo/foo', null)).toBe(false);
+ expect(workingDirEquals(undefined, '')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/shared/workingDir.ts b/apps/desktop/src/shared/workingDir.ts
index a227a97020..583c80da7d 100644
--- a/apps/desktop/src/shared/workingDir.ts
+++ b/apps/desktop/src/shared/workingDir.ts
@@ -36,6 +36,34 @@ export function normalizeWorkingDirForStorage(raw: string | null | undefined): s
return out;
}
+/**
+ * 两个工作目录是否指向同一位置。
+ *
+ * 先按 storage 规则归一化(Windows 分隔符 / 长路径前缀 / 尾部斜杠),Windows 盘符与
+ * UNC 路径再按大小写不敏感比较 —— Windows 文件系统大小写不敏感,而用户从目录选择器
+ * 拿到的拼写(盘符大小写、`\` vs `/`)常常与库里存的值不同。POSIX 下反斜杠是合法
+ * 文件名字符、大小写敏感,不折叠。
+ *
+ * `windows` 默认取当前进程平台;renderer 没有 `process` 时应由调用方传入
+ * (`window.electronAPI.platform === 'win32'`)。
+ */
+export function workingDirEquals(
+ left: string | null | undefined,
+ right: string | null | undefined,
+ options: { windows?: boolean } = {},
+): boolean {
+ const a = normalizeWorkingDirForStorage(left);
+ const b = normalizeWorkingDirForStorage(right);
+ if (a === null || b === null) return false;
+ if (a === b) return true;
+ const windows =
+ options.windows ?? (typeof process !== 'undefined' && process.platform === 'win32');
+ if (!windows) return false;
+ const caseFoldable = (value: string): boolean =>
+ /^[A-Za-z]:\//.test(value) || value.startsWith('//');
+ return caseFoldable(a) && caseFoldable(b) && a.toLowerCase() === b.toLowerCase();
+}
+
/**
* Normalize the directory used to read or write project settings.
*