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(mobile): cancel stale worktree recovery owners

Kafeifei8427fc59d2e9
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 5000c522bf..4de364e1d6 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -172,6 +172,14 @@ function PrecreatedWorktreeRecoveryBridge() {
promise: Promise<void>;
} | null>(null);
const accountId = auth.user?.id?.trim() ?? '';
+ const ownerGenerationRef = useRef({ accountId: '', generation: 0 });
+ if (ownerGenerationRef.current.accountId !== accountId) {
+ ownerGenerationRef.current = {
+ accountId,
+ generation: ownerGenerationRef.current.generation + 1,
+ };
+ }
+ const ownerGeneration = ownerGenerationRef.current.generation;
const runRecovery = useCallback(async () => {
if (
@@ -217,6 +225,13 @@ function PrecreatedWorktreeRecoveryBridge() {
getNewSessionCreationTask(record.sessionId) !== null
|| isPrecreatedWorktreeRegistrationInFlight(record.sessionId)
),
+ // Account selection updates user/token while the AuthProvider stays mounted.
+ // Fence this run against that owner generation so stable Device Link callbacks
+ // cannot retarget an old account's recovery to the new client.
+ isCurrent: () => (
+ ownerGenerationRef.current.accountId === accountId
+ && ownerGenerationRef.current.generation === ownerGeneration
+ ),
});
const tracked = {
accountId,
@@ -235,6 +250,7 @@ function PrecreatedWorktreeRecoveryBridge() {
deviceLinkStatus,
invoke,
openLink,
+ ownerGeneration,
]);
useEffect(() => {
diff --git a/apps/mobile/src/__tests__/precreatedWorktreeRecovery.test.ts b/apps/mobile/src/__tests__/precreatedWorktreeRecovery.test.ts
index 8f4cde9881..53a65e09c5 100644
--- a/apps/mobile/src/__tests__/precreatedWorktreeRecovery.test.ts
+++ b/apps/mobile/src/__tests__/precreatedWorktreeRecovery.test.ts
@@ -461,4 +461,66 @@ describe('precreated worktree recovery ledger', () => {
RECORD,
]);
});
+
+ it('cancels an old owner while retrying and lets the new owner recover its own ledger', async () => {
+ await registerPendingPrecreatedWorktree(ACCOUNT, RECORD);
+ const accountB = 'account-b';
+ const recordB = {
+ ...RECORD,
+ sessionId: 'session-b',
+ };
+ await registerPendingPrecreatedWorktree(accountB, recordB);
+
+ let currentOwner = ACCOUNT;
+ const openLinkA = vi.fn()
+ .mockRejectedValueOnce(Object.assign(new Error('device offline'), {
+ code: 'DEVICE_OFFLINE',
+ }))
+ .mockResolvedValue(undefined);
+ const sleepA = vi.fn(async () => {
+ currentOwner = accountB;
+ });
+ const isSessionClaimedA = vi.fn(async () => false);
+ const discardA = vi.fn(async () => ({ discarded: true }));
+
+ await expect(
+ recoverPendingPrecreatedWorktrees(ACCOUNT, {
+ openLink: openLinkA,
+ discardPrecreated: discardA,
+ isSessionClaimed: isSessionClaimedA,
+ sleep: sleepA,
+ isCurrent: () => currentOwner === ACCOUNT,
+ }),
+ ).resolves.toMatchObject({
+ attempted: 1,
+ recovered: 0,
+ retained: 0,
+ });
+ expect(openLinkA).toHaveBeenCalledTimes(1);
+ expect(isSessionClaimedA).not.toHaveBeenCalled();
+ expect(discardA).not.toHaveBeenCalled();
+ await expect(listPendingPrecreatedWorktrees(ACCOUNT)).resolves.toEqual([
+ RECORD,
+ ]);
+
+ const discardB = vi.fn(async () => ({ discarded: true }));
+ await expect(
+ recoverPendingPrecreatedWorktrees(accountB, {
+ openLink: vi.fn(async () => undefined),
+ discardPrecreated: discardB,
+ isSessionClaimed: vi.fn(async () => false),
+ sleep: async () => undefined,
+ isCurrent: () => currentOwner === accountB,
+ }),
+ ).resolves.toMatchObject({
+ attempted: 1,
+ recovered: 1,
+ retained: 0,
+ });
+ expect(discardB).toHaveBeenCalledWith('device-1', {
+ sessionId: recordB.sessionId,
+ path: recordB.path,
+ });
+ await expect(listPendingPrecreatedWorktrees(accountB)).resolves.toEqual([]);
+ });
});
diff --git a/apps/mobile/src/__tests__/precreatedWorktreeRecoveryBridge.test.ts b/apps/mobile/src/__tests__/precreatedWorktreeRecoveryBridge.test.ts
new file mode 100644
index 0000000000..9b5c5b14fb
--- /dev/null
+++ b/apps/mobile/src/__tests__/precreatedWorktreeRecoveryBridge.test.ts
@@ -0,0 +1,23 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+describe('precreated worktree recovery bridge', () => {
+ it('fences stable Device Link callbacks by the current account owner generation', () => {
+ const layout = readFileSync(
+ resolve(process.cwd(), 'app/_layout.tsx'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
+
+ expect(layout).toContain(
+ "const ownerGenerationRef = useRef({ accountId: '', generation: 0 });",
+ );
+ expect(layout).toContain(
+ 'ownerGenerationRef.current.accountId === accountId',
+ );
+ expect(layout).toContain(
+ 'ownerGenerationRef.current.generation === ownerGeneration',
+ );
+ expect(layout).toContain('isCurrent: () => (');
+ });
+});
diff --git a/apps/mobile/src/session/precreatedWorktreeRecovery.ts b/apps/mobile/src/session/precreatedWorktreeRecovery.ts
index 56725e2f13..1193ba44af 100644
--- a/apps/mobile/src/session/precreatedWorktreeRecovery.ts
+++ b/apps/mobile/src/session/precreatedWorktreeRecovery.ts
@@ -66,6 +66,12 @@ export interface PrecreatedWorktreeRecoveryDeps {
sleep?: (ms: number) => Promise<void>;
/** 任务仍在当前进程内时延后,避免恢复 bridge 与创建管线竞态。 */
shouldDefer?: (record: PendingPrecreatedWorktree) => boolean;
+ /**
+ * 账号 owner generation fence。账号切换后旧 run 必须在下一次远程 ownership
+ * probe / discard 前停止;否则稳定的 Device Link callback 可能取到新账号的
+ * client,对旧账号的 recoveryKey 执行 destructive discard。
+ */
+ isCurrent?: () => boolean;
}
export interface PrecreatedWorktreeRecoveryResult {
@@ -437,6 +443,10 @@ async function removeIfCurrent(
await forgetPendingPrecreatedWorktree(accountId, record);
}
+function isRecoveryCurrent(deps: PrecreatedWorktreeRecoveryDeps): boolean {
+ return deps.isCurrent?.() ?? true;
+}
+
/**
* 冷启动 / 重连时主动处理没有当前内存 task 认领的记录。
*
@@ -458,6 +468,7 @@ export async function recoverPendingPrecreatedWorktrees(
storageReadable: ledger.storageReadable,
};
for (const record of records) {
+ if (!isRecoveryCurrent(deps)) break;
if (deps.shouldDefer?.(record)) {
result.deferred += 1;
continue;
@@ -466,10 +477,16 @@ export async function recoverPendingPrecreatedWorktrees(
try {
await withTransientRemoteRetry(
async () => {
+ // Check immediately before every remote operation. The recovery bridge's
+ // openLink/invoke callbacks are stable and resolve the current client at
+ // call time, so an owner switch can otherwise retarget this old run.
+ if (!isRecoveryCurrent(deps)) return;
await deps.openLink(record.deviceId);
+ if (!isRecoveryCurrent(deps)) return;
if (await deps.isSessionClaimed(record.deviceId, record.sessionId)) {
return;
}
+ if (!isRecoveryCurrent(deps)) return;
if (typeof record.path === 'string') {
await deps.discardPrecreated(record.deviceId, {
sessionId: record.sessionId,
@@ -489,14 +506,20 @@ export async function recoverPendingPrecreatedWorktrees(
...(deps.sleep ? { sleep: deps.sleep } : {}),
},
);
+ if (!isRecoveryCurrent(deps)) break;
await removeIfCurrent(accountId, record);
result.recovered += 1;
continue;
} catch (error) {
+ // Do not let the old owner's catch path perform a second ownership probe or
+ // remove the old ledger after the auth owner has changed.
+ if (!isRecoveryCurrent(deps)) break;
// 旧工作端可能已经成功创建 session,但不认识新的 discard channel。无论
// discard 以何种错误返回都再对账一次,不能只在 PRECONDITION_FAILED 时查询。
try {
+ if (!isRecoveryCurrent(deps)) break;
if (await deps.isSessionClaimed(record.deviceId, record.sessionId)) {
+ if (!isRecoveryCurrent(deps)) break;
await removeIfCurrent(accountId, record);
result.recovered += 1;
continue;