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): guard legacy recovery and quarantine state

Kafeifeidbef0ea11ac6
diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
index b621cac095..8f2f513374 100644
--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts
@@ -50,7 +50,9 @@ vi.mock('../worktree/includePatternsEngine', () => ({
vi.mock('../worktree/worktreeStore', () => ({
get: (sessionId: string) => storeMap.get(sessionId) ?? null,
getAll: () => [...storeMap.values()],
- getAllPaths: () => [...storeMap.values()].map((m) => m.path),
+ getAllPaths: () => [...storeMap.values()].flatMap((m) => (
+ m.quarantinePath ? [m.path, m.quarantinePath] : [m.path]
+ )),
set: (...args: unknown[]) => storeSetMock(...args),
del: vi.fn((sessionId: string) => storeMap.delete(sessionId)),
}));
@@ -634,6 +636,72 @@ describe('removeWorktreeForSession', () => {
['worktree', 'remove', quarantinePath],
base,
);
+ expect(storeMap.get('s1')).toEqual(meta);
+ expect(storeSetMock).toHaveBeenCalledWith(
+ 's1',
+ expect.objectContaining({ quarantinePath }),
+ );
+ } finally {
+ fsSync.rmSync(tmpRoot, { recursive: true, force: true });
+ }
+ });
+
+ it('resumes a persisted quarantine path after restart while accepting the original ledger path', async () => {
+ const tmpRoot = fsSync.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-quarantine-restart-'));
+ try {
+ const base = path.join(tmpRoot, 'repo');
+ const worktreePath = path.join(base, '.xdt-worktrees', 's1');
+ const quarantinePath = `${worktreePath}.xdt-removing-crashed`;
+ fsSync.mkdirSync(quarantinePath, { recursive: true });
+ const meta: WorktreeMeta = {
+ ...makeMeta('s1'),
+ baseRepo: base,
+ path: worktreePath,
+ quarantinePath,
+ };
+ storeMap.set('s1', meta);
+
+ await expect(
+ manager.discardPrecreatedWorktree('s1', worktreePath),
+ ).resolves.toEqual({ status: 'discarded', branchDeleted: false });
+
+ expect(ignoredFilesMock).toHaveBeenCalledWith(base, quarantinePath);
+ expect(gitExecMock).toHaveBeenCalledWith(
+ ['worktree', 'remove', quarantinePath],
+ base,
+ );
+ expect(gitExecMock).not.toHaveBeenCalledWith(
+ ['worktree', 'move', worktreePath, quarantinePath],
+ base,
+ );
+ expect(storeMap.has('s1')).toBe(false);
+ } finally {
+ fsSync.rmSync(tmpRoot, { recursive: true, force: true });
+ }
+ });
+
+ it('does not move a worktree when quarantine state cannot be persisted', async () => {
+ const tmpRoot = fsSync.mkdtempSync(path.join(os.tmpdir(), 'xdt-wt-quarantine-persist-'));
+ try {
+ const base = path.join(tmpRoot, 'repo');
+ const worktreePath = path.join(base, '.xdt-worktrees', 's1');
+ fsSync.mkdirSync(worktreePath, { recursive: true });
+ const meta: WorktreeMeta = {
+ ...makeMeta('s1'),
+ baseRepo: base,
+ path: worktreePath,
+ };
+ storeMap.set('s1', meta);
+ storeSetMock.mockRejectedValueOnce(new Error('disk full'));
+
+ await expect(
+ manager.discardPrecreatedWorktree('s1', worktreePath),
+ ).resolves.toEqual({ status: 'preserved' });
+
+ expect(gitExecMock).not.toHaveBeenCalledWith(
+ ['worktree', 'move', worktreePath, expect.any(String)],
+ base,
+ );
expect(storeMap.get('s1')).toBe(meta);
} finally {
fsSync.rmSync(tmpRoot, { recursive: true, force: true });
diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.ts
index 775af9ca36..d7a6804ffb 100644
--- a/apps/desktop/src/main/worktree/WorktreeManager.ts
+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts
@@ -87,6 +87,24 @@ async function pathExists(p: string): Promise<boolean> {
}
}
+function clearQuarantinePath(meta: WorktreeMeta): WorktreeMeta {
+ const next = { ...meta };
+ delete next.quarantinePath;
+ return next;
+}
+
+function isExpectedQuarantinePath(meta: WorktreeMeta, candidate: string): boolean {
+ try {
+ return path.resolve(candidate).startsWith(`${path.resolve(meta.path)}.xdt-removing-`);
+ } catch {
+ return false;
+ }
+}
+
+function activeWorktreePath(meta: WorktreeMeta): string {
+ return meta.quarantinePath ?? meta.path;
+}
+
async function timed<T>(label: string, fn: () => Promise<T>): Promise<T> {
const startedAt = Date.now();
try {
@@ -167,6 +185,7 @@ export async function detectCwd(cwd: string): Promise<DetectCwdResp> {
isGitRepo: false,
isInsideWorktree: false,
gitInstalled: true,
+ supportsRecoveryKeyDiscard: true,
};
// 1. git --version 探测安装
try {
@@ -755,12 +774,13 @@ export async function getRemovalPreview(
): Promise<{ hasWorktree: boolean; dirty: boolean }> {
const meta = store.get(sessionId);
if (!meta || meta.ephemeral) return { hasWorktree: false, dirty: false };
+ const worktreePath = activeWorktreePath(meta);
try {
- await fs.access(meta.path);
+ await fs.access(worktreePath);
} catch {
return { hasWorktree: false, dirty: false };
}
- return { hasWorktree: true, dirty: await isWorktreeDirty(meta.path) };
+ return { hasWorktree: true, dirty: await isWorktreeDirty(worktreePath) };
}
// ── removeWorktreeForSession (无 IPC, 仅会话显式删除/归档路径调) ─────────────
@@ -817,70 +837,104 @@ async function removeWorktreeForSessionInner(
sessionId: string,
options: RemoveWorktreeOptions,
): Promise<void> {
- const meta = store.get(sessionId);
+ let meta = store.get(sessionId);
if (!meta) return;
+ if (
+ meta.quarantinePath
+ && !isExpectedQuarantinePath(meta, meta.quarantinePath)
+ ) {
+ log.warn(
+ `[worktree] preserved worktree at ${meta.path}: invalid persisted quarantine path`,
+ );
+ return;
+ }
+ const hadPersistedQuarantine = Boolean(meta.quarantinePath);
+ // A crash can happen after the quarantine marker is persisted but before Git moves
+ // the directory. Repair that preparatory state before attempting another removal.
+ if (meta.quarantinePath) {
+ const quarantineExists = await pathExists(meta.quarantinePath);
+ const originalExists = await pathExists(meta.path);
+ if (!quarantineExists && originalExists) {
+ const repaired = clearQuarantinePath(meta);
+ try {
+ await store.set(sessionId, repaired);
+ } catch (err) {
+ log.warn(
+ `[worktree] failed to clear stale quarantine marker for ${meta.path}:`,
+ err instanceof Error ? err.message : String(err),
+ );
+ return;
+ }
+ meta = repaired;
+ }
+ }
+ const removalOptions = hadPersistedQuarantine
+ ? { ...options, preserveDirty: true }
+ : options;
+ const worktreePath = activeWorktreePath(meta);
// 哨兵守卫: 用户放了 .worktree-keep ⇒ 无条件保留(必须在 dirty/stash 之前——
// 哨兵是 untracked 文件,走到 stash 会连哨兵一起收走再删目录)。
- if (hasKeepSentinel(meta.path)) {
- log.info(`[worktree] preserved worktree at ${meta.path}: has ${'.worktree-keep'} sentinel`);
+ const guardedPaths = [...new Set([meta.path, worktreePath])];
+ if (guardedPaths.some((candidate) => hasKeepSentinel(candidate))) {
+ log.info(`[worktree] preserved worktree at ${worktreePath}: has ${'.worktree-keep'} sentinel`);
return;
}
// live-ref 守卫: worktree 路径仍被其它未删除会话的 workingDir / worktreePath
// 指向时不删(典型: 用户在该目录另开了会话)。查询失败按"在用"保守处理。
const liveKeys = await loadLiveSessionPathKeys({
- contextPath: meta.path,
+ contextPath: worktreePath,
excludeSessionId: sessionId,
});
if (hasLiveSessionReference(meta, liveKeys)) {
log.info(
- `[worktree] preserved worktree at ${meta.path}: still referenced by another live session`,
+ `[worktree] preserved worktree at ${worktreePath}: still referenced by another live session`,
);
return;
}
let changedIncludeFiles: Awaited<ReturnType<typeof listChangedWorktreeIncludeFiles>>;
try {
- changedIncludeFiles = await listChangedWorktreeIncludeFiles(meta.baseRepo, meta.path);
+ changedIncludeFiles = await listChangedWorktreeIncludeFiles(meta.baseRepo, worktreePath);
} catch (err) {
log.warn(
- `[worktree] preserve worktree at ${meta.path}: include-file dirty check failed`,
+ `[worktree] preserve worktree at ${worktreePath}: include-file dirty check failed`,
err instanceof Error ? err.message : String(err),
);
return;
}
if (changedIncludeFiles.length > 0) {
log.warn(
- `[worktree] preserved worktree at ${meta.path}: changed included local files`,
+ `[worktree] preserved worktree at ${worktreePath}: changed included local files`,
changedIncludeFiles.slice(0, 10).map((f) => `${f.relpath}:${f.reason}`),
);
return;
}
- if (!(await canRemoveWorktree(options, meta.path, sessionId))) return;
+ if (!(await canRemoveWorktree(removalOptions, worktreePath, sessionId))) return;
- if (options.preserveDirty) {
+ if (removalOptions.preserveDirty) {
let ignoredFiles: string[];
try {
- ignoredFiles = await listNonReproducibleIgnoredFiles(meta.baseRepo, meta.path);
+ ignoredFiles = await listNonReproducibleIgnoredFiles(meta.baseRepo, worktreePath);
} catch (err) {
log.warn(
- `[worktree] preserve worktree at ${meta.path}: ignored-file check failed`,
+ `[worktree] preserve worktree at ${worktreePath}: ignored-file check failed`,
err instanceof Error ? err.message : String(err),
);
return;
}
if (ignoredFiles.length > 0) {
log.warn(
- `[worktree] preserved worktree at ${meta.path}: non-reproducible ignored files`,
+ `[worktree] preserved worktree at ${worktreePath}: non-reproducible ignored files`,
ignoredFiles.slice(0, 10),
);
return;
}
// ignored-file 对比可能读盘;完成后再核对一次 ownership,避免检查期间晚到的
// maker:create-session 已认领目录却仍继续删除。
- if (!(await canRemoveWorktree(options, meta.path, sessionId))) return;
+ if (!(await canRemoveWorktree(removalOptions, worktreePath, sessionId))) return;
}
const finishRemoval = async (snapshotted: boolean): Promise<void> => {
@@ -892,7 +946,7 @@ async function removeWorktreeForSessionInner(
// closeSession / snapshot 期间会话可能已恢复为 active。真正删除前再读一次状态;
// 若本轮已经 snapshot,则把内容重新 apply 回保留目录。
- if (!(await canRemoveWorktree(options, meta.path, sessionId))) {
+ if (!(await canRemoveWorktree(removalOptions, activeWorktreePath(meta), sessionId))) {
if (snapshotted) {
if (await restoreAutoStashToPreservedWorktree(meta.path, sessionId)) {
await store.set(sessionId, meta);
@@ -906,8 +960,8 @@ async function removeWorktreeForSessionInner(
return;
}
- let removalPath = meta.path;
- let quarantinePath: string | null = null;
+ let removalPath = activeWorktreePath(meta);
+ let quarantinePath: string | null = meta.quarantinePath ?? null;
const restoreQuarantine = async (): Promise<boolean> => {
if (!quarantinePath) return true;
const currentQuarantinePath = quarantinePath;
@@ -917,6 +971,14 @@ async function removeWorktreeForSessionInner(
meta.baseRepo,
);
quarantinePath = null;
+ try {
+ await store.set(sessionId, clearQuarantinePath(meta));
+ } catch (err) {
+ log.warn(
+ `[worktree] failed to clear persisted quarantine state for ${meta.path}:`,
+ err instanceof Error ? err.message : String(err),
+ );
+ }
return true;
} catch (err) {
log.error(
@@ -925,31 +987,44 @@ async function removeWorktreeForSessionInner(
);
// Preserve the actual path if the move-back itself fails; losing the
// store entry would make the quarantined user data unreachable.
- await store.set(sessionId, { ...meta, path: currentQuarantinePath });
+ try {
+ await store.set(sessionId, { ...meta, quarantinePath: currentQuarantinePath });
+ } catch (storeErr) {
+ log.error(
+ `[worktree] failed to persist quarantined worktree ${currentQuarantinePath}:`,
+ storeErr instanceof Error ? storeErr.message : String(storeErr),
+ );
+ }
return false;
}
};
- if (options.preserveDirty && await pathExists(meta.path)) {
+ if (removalOptions.preserveDirty && !quarantinePath && await pathExists(meta.path)) {
const candidate = `${meta.path}.xdt-removing-${randomUUID()}`;
try {
+ // Persist the intended quarantine path before the rename. This closes both
+ // crash windows: after the marker is written but before the move, startup
+ // can clear the stale marker because the original path still exists; after
+ // the move, startup can continue from the persisted quarantine path.
+ await store.set(sessionId, { ...meta, quarantinePath: candidate });
+ quarantinePath = candidate;
+ removalPath = candidate;
// Atomically move the registered worktree out of its user-visible path
// before the final ignored-file scan. New writes through the old path
// can no longer race the scan and the subsequent remove.
await gitExec(['worktree', 'move', meta.path, candidate], meta.baseRepo);
- quarantinePath = candidate;
- removalPath = candidate;
} catch (err) {
log.warn(
`[worktree] preserve worktree at ${meta.path}: quarantine move failed`,
err instanceof Error ? err.message : String(err),
);
+ await restoreQuarantine();
return;
}
// The move updates Git's worktree metadata, so both the final ownership
// check and ignored-file scan can use the quarantined path.
- if (!(await canRemoveWorktree(options, removalPath, sessionId))) {
+ if (!(await canRemoveWorktree(removalOptions, removalPath, sessionId))) {
await restoreQuarantine();
return;
}
@@ -973,7 +1048,7 @@ async function removeWorktreeForSessionInner(
await restoreQuarantine();
return;
}
- if (!(await canRemoveWorktree(options, removalPath, sessionId))) {
+ if (!(await canRemoveWorktree(removalOptions, removalPath, sessionId))) {
await restoreQuarantine();
return;
}
@@ -984,26 +1059,26 @@ async function removeWorktreeForSessionInner(
// 预创建补偿回收必须让 git 在删除瞬间再次确认 worktree 仍然干净:
// preserveDirty 的前置探测与这里之间可能有人刚写入文件,非强制 remove 会拒绝,
// 从而保留目录。普通会话删除已经有 auto-stash 保护,仍沿用 --force。
- const removeArgs = options.preserveDirty
+ const removeArgs = removalOptions.preserveDirty
? ['worktree', 'remove', removalPath]
- : ['worktree', 'remove', '--force', meta.path];
+ : ['worktree', 'remove', '--force', removalPath];
await gitExec(removeArgs, meta.baseRepo);
removedByGit = true;
} catch (err) {
log.warn(
- `[worktree] git worktree remove failed for ${meta.path}:`,
+ `[worktree] git worktree remove failed for ${removalPath}:`,
err instanceof Error ? err.message : String(err),
);
// preserveDirty 是补偿口的“绝不丢用户新写内容”承诺。git 拒绝非强制删除时
// 不能再用 fs.rm 绕过它,否则会重新打开 dirty check 后写入的竞态窗口。
- if (options.preserveDirty) {
+ if (removalOptions.preserveDirty) {
await restoreQuarantine();
return;
}
// fallback: fs.rm —— 必须三条校验通过
- if (isManagedWorktreePath(meta.path, meta.baseRepo, [...store.getAllPaths(), meta.path])) {
+ if (isManagedWorktreePath(removalPath, meta.baseRepo, [...store.getAllPaths(), removalPath])) {
try {
- await fs.rm(meta.path, { recursive: true, force: true });
+ await fs.rm(removalPath, { recursive: true, force: true });
// 让 git worktree 状态自洽
try {
await gitExec(['worktree', 'prune'], meta.baseRepo);
@@ -1013,14 +1088,14 @@ async function removeWorktreeForSessionInner(
removedByGit = true; // 视为已清, 走 store.del
} catch (rmErr) {
log.error(
- `[worktree] fs.rm fallback failed for ${meta.path}:`,
+ `[worktree] fs.rm fallback failed for ${removalPath}:`,
rmErr instanceof Error ? rmErr.message : String(rmErr),
);
// 不动 store, 留给用户手动清理或下次启动复用
}
} else {
log.warn(
- `[worktree] isManagedWorktreePath check failed for ${meta.path}; refusing fs.rm`,
+ `[worktree] isManagedWorktreePath check failed for ${removalPath}; refusing fs.rm`,
);
}
}
@@ -1041,17 +1116,17 @@ async function removeWorktreeForSessionInner(
}
};
- if (await isWorktreeDirty(meta.path)) {
- if (options.preserveDirty) {
+ if (await isWorktreeDirty(worktreePath)) {
+ if (removalOptions.preserveDirty) {
log.info(
- `[worktree] preserved worktree at ${meta.path}: uncommitted changes block pre-created cleanup`,
+ `[worktree] preserved worktree at ${worktreePath}: uncommitted changes block pre-created cleanup`,
);
return;
}
await withWorktreeRestoreMutation(sessionId, async () => {
- if (!(await autoStashDirtyWorktree(meta.path, sessionId))) {
+ if (!(await autoStashDirtyWorktree(worktreePath, sessionId))) {
log.warn(
- `[worktree] worktree at ${meta.path} has uncommitted changes, preserving`,
+ `[worktree] worktree at ${worktreePath} has uncommitted changes, preserving`,
);
return;
}
@@ -1104,7 +1179,12 @@ export async function discardPrecreatedWorktree(
): Promise<DiscardPrecreatedWorktreeResult> {
const meta = store.get(sessionId);
if (!meta) return { status: 'absent' };
- if (path.resolve(meta.path) !== path.resolve(expectedPath)) {
+ const expected = path.resolve(expectedPath);
+ const matchesRegisteredPath = (
+ path.resolve(meta.path) === expected
+ || (meta.quarantinePath !== undefined && path.resolve(meta.quarantinePath) === expected)
+ );
+ if (!matchesRegisteredPath) {
return { status: 'path-mismatch' };
}
if (meta.ephemeral) return { status: 'preserved' };
diff --git a/apps/desktop/src/main/worktree/liveSessionRefs.ts b/apps/desktop/src/main/worktree/liveSessionRefs.ts
index a5aa7673db..98accce668 100644
--- a/apps/desktop/src/main/worktree/liveSessionRefs.ts
+++ b/apps/desktop/src/main/worktree/liveSessionRefs.ts
@@ -90,16 +90,20 @@ export function hasLiveSessionReference(
meta: WorktreeMeta,
liveSessionPathKeys: LiveSessionPathKeys,
): boolean {
- const target = pathKey(meta.path);
- if (!target) return true;
if (!liveSessionPathKeys) return true;
- for (const candidate of liveSessionPathKeys) {
- const relative = path.relative(target, candidate);
- if (
- relative === '' ||
- (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
- ) {
- return true;
+ const targets = [meta.path, meta.quarantinePath]
+ .map((value) => pathKey(value))
+ .filter((value): value is string => value !== null);
+ if (targets.length === 0) return true;
+ for (const target of targets) {
+ for (const candidate of liveSessionPathKeys) {
+ const relative = path.relative(target, candidate);
+ if (
+ relative === '' ||
+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
+ ) {
+ return true;
+ }
}
}
return false;
diff --git a/apps/desktop/src/main/worktree/types.ts b/apps/desktop/src/main/worktree/types.ts
index 00ed886228..ec79961cdd 100644
--- a/apps/desktop/src/main/worktree/types.ts
+++ b/apps/desktop/src/main/worktree/types.ts
@@ -28,6 +28,11 @@ export interface WorktreeMeta {
* 对应本记录;不授予通用删除能力。
*/
recoveryKey?: string;
+ /**
+ * 隔离回收期间的实际 worktree 路径。保留原 path 作为外部账本的稳定定位,
+ * 进程崩溃后可从该字段继续回收 quarantine 目录。
+ */
+ quarantinePath?: string;
/** true = scheduler 创建的临时 worktree,session 关闭时可池化复用而非销毁。 */
ephemeral?: boolean;
}
@@ -79,6 +84,11 @@ export interface DetectCwdResp {
currentBranch?: string;
/** git rev-parse --show-toplevel 的结果,绝对路径。 */
repoRoot?: string;
+ /**
+ * 当前被控端是否会把 recoveryKey 持久化到 worktree 元数据,并支持按键回收。
+ * 旧 Desktop 会省略该字段;控制端必须在创建副作用前把省略视为不支持。
+ */
+ supportsRecoveryKeyDiscard?: boolean;
}
export interface ListBranchesReq {
diff --git a/apps/desktop/src/main/worktree/worktreeStore.ts b/apps/desktop/src/main/worktree/worktreeStore.ts
index 41c529face..bbdb052b23 100644
--- a/apps/desktop/src/main/worktree/worktreeStore.ts
+++ b/apps/desktop/src/main/worktree/worktreeStore.ts
@@ -78,7 +78,9 @@ export function get(sessionId: string): WorktreeMeta | null {
* 读取所有已记录的 worktree 路径(供 isManagedWorktreePath 三条校验用)。
*/
export function getAllPaths(): string[] {
- return getAll().map((m) => m.path);
+ return getAll().flatMap((m) => (
+ m.quarantinePath ? [m.path, m.quarantinePath] : [m.path]
+ ));
}
/**
diff --git a/apps/desktop/src/renderer/lib/worktree.types.ts b/apps/desktop/src/renderer/lib/worktree.types.ts
index e48a415dcc..ab5e376ed4 100644
--- a/apps/desktop/src/renderer/lib/worktree.types.ts
+++ b/apps/desktop/src/renderer/lib/worktree.types.ts
@@ -20,6 +20,8 @@ export interface WorktreeMeta {
sourceBranch: string;
/** ISO 8601 时间字符串。 */
createdAt: string;
+ /** 隔离回收期间的实际路径;正常 worktree 不设置。 */
+ quarantinePath?: string;
}
/**
@@ -63,6 +65,8 @@ export interface DetectCwdResp {
currentBranch?: string;
/** 仓库根(可能与传入 cwd 不同)。 */
repoRoot?: string;
+ /** 被控端是否支持 recoveryKey 预创建回收;旧端省略该字段。 */
+ supportsRecoveryKeyDiscard?: boolean;
}
export interface ListBranchesResp {
diff --git a/apps/mobile/src/__tests__/newSessionWorktree.test.ts b/apps/mobile/src/__tests__/newSessionWorktree.test.ts
index ee0ac1a8ff..5fefc0b402 100644
--- a/apps/mobile/src/__tests__/newSessionWorktree.test.ts
+++ b/apps/mobile/src/__tests__/newSessionWorktree.test.ts
@@ -30,6 +30,7 @@ const DETECT_OK: MobileWorktreeDetectCwdResult = {
gitInstalled: true,
currentBranch: 'feature/x',
repoRoot: '/repo/root',
+ supportsRecoveryKeyDiscard: true,
};
describe('resolveWorktreeEligibility', () => {
@@ -64,7 +65,7 @@ describe('resolveWorktreeEligibility', () => {
it('repoRoot 缺失回落 workingDir;detached HEAD 回落 HEAD(不猜 main)', () => {
expect(resolveWorktreeEligibility(
- { isGitRepo: true, isInsideWorktree: false, gitInstalled: true },
+ { ...DETECT_OK, repoRoot: undefined, currentBranch: undefined },
'/repo/app',
)).toEqual({ status: 'eligible', baseRepo: '/repo/app', sourceBranch: 'HEAD' });
expect(resolveWorktreeEligibility(
@@ -72,6 +73,13 @@ describe('resolveWorktreeEligibility', () => {
'/repo/app',
)).toEqual({ status: 'eligible', baseRepo: '/repo/app', sourceBranch: 'HEAD' });
});
+
+ it('旧 Desktop 省略 recoveryKey discard 能力时,在创建副作用前 fail closed', () => {
+ const { supportsRecoveryKeyDiscard: _ignored, ...legacyResult } = DETECT_OK;
+ expect(resolveWorktreeEligibility(legacyResult, '/repo/app')).toEqual({
+ status: 'unsupported',
+ });
+ });
});
describe('worktreeEligibilityForTarget', () => {
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index bb2685aa1c..3d5830fc3e 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -323,6 +323,11 @@ export interface MobileWorktreeDetectCwdResult {
currentBranch?: string;
/** git rev-parse --show-toplevel 结果(被控端绝对路径);worktree:create 的 baseRepo 用它。 */
repoRoot?: string;
+ /**
+ * 新版 Desktop 才会返回 true。旧端可能接受 worktree:create 的未知 recoveryKey
+ * 字段却不把它写入元数据,因此省略必须在副作用前视为不支持。
+ */
+ supportsRecoveryKeyDiscard?: boolean;
}
/** 工作端 worktree:create 元信息(形状对齐被控端 WorktreeMeta)。 */
diff --git a/apps/mobile/src/session/newSessionWorktree.ts b/apps/mobile/src/session/newSessionWorktree.ts
index 0be5e12f11..0bcfbbb875 100644
--- a/apps/mobile/src/session/newSessionWorktree.ts
+++ b/apps/mobile/src/session/newSessionWorktree.ts
@@ -71,6 +71,10 @@ export function worktreeEligibilityForTarget(
* sourceBranch 取当前分支(手机没有分支选择 UI,等价于桌面分支 chip 回填 current),
* detached HEAD 时 currentBranch 缺失,必须回落 'HEAD' 才能从当前 commit 派生;
* 不能猜 main(仓库未必有 main,也不能静默偏离当前 checkout)。
+ *
+ * recoveryKey discard 能力也是资格的一部分:旧 Desktop 可能接受 recoveryKey
+ * 字段却不持久化,create 回包丢失后无法恢复。新端通过 detect-cwd 显式返回 true;
+ * 旧端省略该字段时必须在任何 worktree:create 副作用前 fail closed。
*/
export function resolveWorktreeEligibility(
result: MobileWorktreeDetectCwdResult,
@@ -79,6 +83,7 @@ export function resolveWorktreeEligibility(
if (!result.gitInstalled) return { status: 'ineligible', reason: 'gitMissing' };
if (!result.isGitRepo) return { status: 'ineligible', reason: 'notGitRepo' };
if (result.isInsideWorktree) return { status: 'ineligible', reason: 'alreadyInWorktree' };
+ if (result.supportsRecoveryKeyDiscard !== true) return { status: 'unsupported' };
return {
status: 'eligible',
baseRepo: result.repoRoot?.trim() || workingDir,