Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): close Windows lock cleanup gaps
Yuewei-LL1b06fbb87e6b
diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.tsindex ee3b466d93..c86f4fbcff 100644--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts@@ -1807,6 +1807,79 @@ describe('legacy Ghost plugin recovery', () => {await expect(fs.access(path.join(root, __testing.CLAIM_MARKER))).rejects.toThrow();});+ it('keeps corrupt reserved sources out of a newly frozen recovery marker', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(+ root,+ 'owners',+ ownerKey,+ __testing.LEGACY_GHOST_RECOVERY_MARKER,+ );+ await writeGhostDir(root, 'brain', 'recoverable-plugin');+ await fs.mkdir(path.join(root, 'brain', 'cindy-corrupt'), { recursive: true });+ await fs.writeFile(path.join(root, 'brain', 'cindy-corrupt', 'ghost.json'), '{ nope');++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ { rejectReservedIds: true },+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 1, conflicts: 1 });++ const marker = JSON.parse(await fs.readFile(markerPath, 'utf8')) as {+ pendingIds: string[];+ failedIds?: string[];+ approvalProjectionSha256ById?: Record<string, string>;+ };+ expect(marker.pendingIds).toEqual(['recoverable-plugin']);+ expect(marker.failedIds ?? []).not.toContain('cindy-corrupt');+ expect(marker.approvalProjectionSha256ById ?? {}).not.toHaveProperty('cindy-corrupt');+ await expect(+ fs.readFile(path.join(root, 'brain', 'cindy-corrupt', 'ghost.json'), 'utf8'),+ ).resolves.toBe('{ nope');+ });++ it('removes reserved ids from a dirty marker before later fresh discovery', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(+ root,+ 'owners',+ ownerKey,+ __testing.LEGACY_GHOST_RECOVERY_MARKER,+ );+ await fs.mkdir(path.dirname(markerPath), { recursive: true });+ await fs.writeFile(markerPath, JSON.stringify({+ version: 2,+ ownerKey,+ pendingIds: ['cindy-reserved'],+ failedIds: ['cindy-reserved'],+ approvalProjectionSha256ById: { 'cindy-reserved': 'a'.repeat(64) },+ }));++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ { rejectReservedIds: true },+ ),+ ).resolves.toMatchObject({ moved: 0 });+ await expect(fs.access(markerPath)).rejects.toThrow();++ await writeGhostDir(root, 'brain', 'later-plugin');+ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ { rejectReservedIds: true },+ ),+ ).resolves.toMatchObject({ moved: 1, recoveredIds: ['later-plugin'] });+ });+it('moves builtin provisioning state with plugins before reconciliation', async () => {const root = await tempRoot();const ownerId = 'cloud-a';diff --git a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.tsindex 07536c6e65..d43461aa0d 100644--- a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts@@ -40,42 +40,24 @@ beforeEach(() => {dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cross-process-lock-'));});-async function createExitedPid(): Promise<number> {- // Strict takeover requires affirmative OS proof that the recorded owner is- // gone. A made-up large PID makes that proof depend on CIM/WMIC accepting- // the numeric value, which varies across Windows runner images. Use a PID- // this host created and observed exiting instead.- const child = spawn(process.execPath, ['-e', 'process.exit(0)'], {- windowsHide: true,- stdio: 'ignore',- });- return new Promise<number>((resolve, reject) => {- child.once('error', reject);- child.once('exit', () => {- if (!child.pid) reject(new Error('fixture child pid missing'));- else resolve(child.pid);- });- });-}-afterEach(() => {+ __testing.setProcessIdentityProbeOverride(null);fs.rmSync(dir, { recursive: true, force: true });});/** 造一把「陈旧且 owner 已死」的锁。 */async function writeStaleLock(lock: string): Promise<void> {- const exitedPid = await createExitedPid();- await fsp.writeFile(lock, JSON.stringify({ pid: exitedPid, startedAt: 1 }), 'utf8');+ await fsp.writeFile(lock, JSON.stringify({ pid: 424_242, startedAt: 1 }), 'utf8');const old = new Date(Date.now() - 60_000);await fsp.utimes(lock, old, old);}async function writeStaleStrictLock(lock: string): Promise<void> {- const exitedPid = await createExitedPid();+ __testing.setProcessIdentityProbeOverride(async () => ({ status: 'missing' }));await fsp.writeFile(lock,JSON.stringify({- pid: exitedPid,+ pid: 424_242,startedAt: 1,nonce: '00000000-0000-4000-8000-000000000001',processStartIdentity: 'start-ms:1',@@ -88,11 +70,11 @@ async function writeStaleStrictLock(lock: string): Promise<void> {}async function writeStaleReclaimGate(lock: string): Promise<void> {- const exitedPid = await createExitedPid();+ __testing.setProcessIdentityProbeOverride(async () => ({ status: 'missing' }));const gate = `${lock}.reclaim`;await fsp.writeFile(gate,- JSON.stringify({ pid: exitedPid, startedAt: 1, nonce: 'stale-gate' }),+ JSON.stringify({ pid: 424_242, startedAt: 1, nonce: 'stale-gate' }),'utf8',);const old = new Date(Date.now() - 60_000);@@ -154,13 +136,54 @@ describe('接管陈旧锁', () => {it('advisory release leaves no strict recovery artifacts and permits reacquisition', async () => {const lock = path.join(dir, 'advisory-lock');+ const gateDir = `${lock}.reclaim.d`;+ const originalRm = fsp.rm;+ let blockedGateDeletes = 0;+ let blockedGateFile: string | null = null;+ let allowBlockedGateDelete = false;+ const rmSpy = vi.spyOn(fsp, 'rm').mockImplementation((async (+ target: unknown,+ options?: unknown,+ ) => {+ if (+ typeof target === 'string'+ && path.dirname(target) === gateDir+ && path.basename(target).startsWith('gate-')+ && path.basename(target).endsWith('.json')+ ) {+ blockedGateFile ??= target;+ if (target === blockedGateFile && !allowBlockedGateDelete) {+ blockedGateDeletes += 1;+ throw Object.assign(new Error('gate temporarily busy'), { code: 'EBUSY' });+ }+ }+ return (originalRm as (...args: unknown[]) => Promise<unknown>)(target, options);+ }) as typeof fsp.rm);- await expect(- withAdvisoryCrossProcessLock(lock, { label: 'first' }, async (s) => s),- ).resolves.toEqual({ held: true });- await expect(- withAdvisoryCrossProcessLock(lock, { label: 'second' }, async (s) => s),- ).resolves.toEqual({ held: true });+ try {+ await expect(+ withAdvisoryCrossProcessLock(lock, { label: 'first' }, async (s) => s),+ ).resolves.toEqual({ held: true });+ expect(blockedGateDeletes).toBe(3);+ expect(fs.readdirSync(gateDir)).toEqual(expect.arrayContaining([+ expect.stringMatching(/^gate-.*\.json$/),+ expect.stringMatching(/^gate-.*\.json\.released$/),+ ]));+ await expect(+ withAdvisoryCrossProcessLock(lock, { label: 'second' }, async (s) => s),+ ).resolves.toEqual({ held: true });+ expect(blockedGateDeletes).toBeGreaterThan(3);+ expect(fs.readdirSync(gateDir)).toEqual(expect.arrayContaining([+ expect.stringMatching(/^gate-.*\.json$/),+ expect.stringMatching(/^gate-.*\.json\.released$/),+ ]));+ allowBlockedGateDelete = true;+ await expect(+ withAdvisoryCrossProcessLock(lock, { label: 'third' }, async (s) => s),+ ).resolves.toEqual({ held: true });+ } finally {+ rmSpy.mockRestore();+ }const artifacts = fs.readdirSync(dir).flatMap((entry) => {const candidate = path.join(dir, entry);@@ -168,9 +191,6 @@ describe('接管陈旧锁', () => {? fs.readdirSync(candidate).map((child) => path.join(entry, child)): [entry];});- // Windows can retain an already-empty directory entry briefly after the- // bounded rmdir retries. The invariant is that no owner gate or release- // marker remains; the two acquisitions above also prove immediate re-entry.expect(artifacts).toEqual([]);});@@ -397,6 +417,10 @@ describe('接管陈旧锁', () => {child.once('error', reject);});if (!child.pid) throw new Error('child pid missing');+ __testing.setProcessIdentityProbeOverride(async (pid) => ({+ status: 'found',+ identity: { key: `start-ms:${pid + 10_000}`, startedAtMs: pid + 10_000 },+ }));// The lock records a process identity that cannot match the live pid's// current identity ('start-ms:0' parses to null → never equal). This is// the only sound signal for a PID-reuse takeover: a live pid alone is@@ -430,6 +454,10 @@ describe('接管陈旧锁', () => {// identity no longer matches: the exact-identity comparison must win over// the self-pid shortcut, or strict callers stay permanently busy.const lock = path.join(dir, 'lock');+ __testing.setProcessIdentityProbeOverride(async () => ({+ status: 'found',+ identity: { key: 'start-ms:10000', startedAtMs: 10_000 },+ }));await fsp.writeFile(lock,JSON.stringify({@@ -501,7 +529,7 @@ describe('接管陈旧锁', () => {await fsp.writeFile(lock,JSON.stringify({- pid: 0x7ffffffe,+ pid: process.pid,startedAt: 1,nonce: '00000000-0000-4000-8000-000000000001',processStartIdentity: 'start-ms:1',diff --git a/apps/desktop/src/main/device-link/crossProcessLock.ts b/apps/desktop/src/main/device-link/crossProcessLock.tsindex 1650b8fad1..2957ce3662 100644--- a/apps/desktop/src/main/device-link/crossProcessLock.ts+++ b/apps/desktop/src/main/device-link/crossProcessLock.ts@@ -82,6 +82,7 @@ type ProcessIdentityProbe =| { status: 'found'; identity: ProcessIdentity }| { status: 'missing' }| { status: 'unavailable' };+type ProcessIdentityProbeOverride = (pid: number) => Promise<ProcessIdentityProbe>;type PublishedLock = {handle: Awaited<ReturnType<typeof fsp.open>>;nonce: string;@@ -112,6 +113,7 @@ type ReclaimGate = {};let currentProcessIdentityPromise: Promise<ProcessIdentity | null> | null = null;+let processIdentityProbeOverride: ProcessIdentityProbeOverride | null = null;// A release gate whose final rename/fsync failed may still be ours. Keep its// nonce so the same process can recover it before treating the gate as busy.const pendingOwnRecordRecovery = new Map<string, string>();@@ -128,10 +130,12 @@ function gateReleaseMarkerPath(gatePath: string): string {* Callers retain ownership of the degradation policy through `LockStatus`. This* path keeps the legacy canonical file shape, adding a nonce-bound owner record* and rename isolation for safe release/takeover. It deliberately avoids the- * strict tier's process-identity commands, hard-link/fsync publication and- * released-marker protocol on the ordinary hot path. Plugin approval boundaries- * require those stronger proofs, but imposing their full state machine on every- * cache/settings write enlarged the Windows failure surface.+ * strict tier's process-identity commands and hard-link/fsync publication on+ * the ordinary hot path. A nonce-bound release marker is only a Windows cleanup+ * fallback when a gate file outlives bounded deletion retries. Plugin approval+ * boundaries require the stronger protocol on every transition, but imposing+ * its full state machine on every cache/settings write enlarged the Windows+ * failure surface.*/export async function withCrossProcessLock<T>(lockPath: string,@@ -647,8 +651,21 @@ async function releaseAdvisoryReclaimGate(gate: AdvisoryReclaimGate): Promise<voconst current = await readLockRecord(gate.filePath, true);if (typeof current !== 'string' && current.nonce === gate.nonce) {await removePathWithRetry(gate.filePath);+ // A Windows filesystem filter can keep the gate file undeletable beyond+ // our bounded retry window. Publish the same nonce-bound release proof as+ // the strict tier so the next contender can distinguish this dead gate+ // from a live owner and finish the cleanup without weakening ownership.+ if (await pathExists(gate.filePath)) {+ await publishGateReleaseMarker(gate.filePath, gate.nonce).catch((error) => {+ log.warn('advisory reclaim gate release marker could not be published', error);+ });+ }+ }+ if (await pathExists(gate.filePath)) {+ pendingOwnGateCleanup.add(gate.filePath);+ } else {+ await removePathWithRetry(gateReleaseMarkerPath(gate.filePath));}- if (await pathExists(gate.filePath)) pendingOwnGateCleanup.add(gate.filePath);await removeEmptyDirectoryWithRetry(gate.dirPath);}@@ -913,7 +930,12 @@ async function findActiveReclaimGate(const expectedNonce = typeof record !== 'string' ? (record.nonce ?? undefined) : undefined;if (await hasValidGateReleaseMarker(filePath, expectedNonce)) {await removePathWithRetry(filePath);- await removePathWithRetry(gateReleaseMarkerPath(filePath));+ // Keep the release proof while Windows still retains the gate path. If+ // the marker were removed first, the next contender would reinterpret+ // the same fresh file as a live owner and block until it became stale.+ if (!(await pathExists(filePath))) {+ await removePathWithRetry(gateReleaseMarkerPath(filePath));+ }continue;}if (typeof record === 'string') {@@ -1109,7 +1131,9 @@ async function isRecordOwnerActive(// identity query decide when possible; if it also fails, the caller below// remains fail-closed.}- const identityProbe = await probeProcessIdentity(record.pid);+ const identityProbe = processIdentityProbeOverride+ ? await processIdentityProbeOverride(record.pid)+ : await probeProcessIdentity(record.pid);if (identityProbe.status === 'missing') return false;if (identityProbe.status === 'unavailable') return true;const currentIdentity = identityProbe.identity;@@ -1388,7 +1412,7 @@ async function releaseReclaimGate(gate: ReclaimGate): Promise<void> {releasedRecordDurable = true;} catch (error) {log.warn('lock reclaim gate could not be flushed before release', error);- await publishGateReleaseMarker(gate).catch((markerError) => {+ await publishGateReleaseMarker(gate.filePath, gate.lock.nonce).catch((markerError) => {log.warn('lock reclaim gate release marker could not be published', markerError);});}@@ -1402,19 +1426,19 @@ async function releaseReclaimGate(gate: ReclaimGate): Promise<void> {await removeEmptyDirectoryWithRetry(gate.dirPath);}-async function publishGateReleaseMarker(gate: ReclaimGate): Promise<void> {- const markerPath = gateReleaseMarkerPath(gate.filePath);+async function publishGateReleaseMarker(gatePath: string, nonce: string): Promise<void> {+ const markerPath = gateReleaseMarkerPath(gatePath);let handle: Awaited<ReturnType<typeof fsp.open>> | null = null;try {handle = await fsp.open(markerPath, 'wx');await writeAllAt(handle, JSON.stringify({- gateFile: path.basename(gate.filePath),- nonce: gate.lock.nonce,+ gateFile: path.basename(gatePath),+ nonce,}));await handle.sync();} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;- if (!(await hasValidGateReleaseMarker(gate.filePath, gate.lock.nonce))) throw error;+ if (!(await hasValidGateReleaseMarker(gatePath, nonce))) throw error;} finally {await handle?.close().catch(() => undefined);}@@ -1560,4 +1584,7 @@ export const __testing = {removeEmptyDirectoryWithRetry,parseRecordedProcessStartMs,processIdentitiesMatch,+ setProcessIdentityProbeOverride(override: ProcessIdentityProbeOverride | null): void {+ processIdentityProbeOverride = override;+ },};diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.tsindex 27bffeb838..900953633c 100644--- a/apps/desktop/src/main/ownerNamespaceMigration.ts+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts@@ -1511,22 +1511,38 @@ export async function recoverLegacyGhostPlugins(recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;}- const sourceDiscoveryIds = new Set([+ const discoveredSourceIds = new Set([...sharedLegacyGhosts.map((ghost) => ghost.id),...scopedLegacyGhosts.map((ghost) => ghost.id),...[...sharedDiscovery.invalidIds, ...scopedDiscovery.invalidIds].filter((id) => isValidGhostId(id)),]);+ // The durable marker is a frozen recovery capability, not merely progress+ // bookkeeping. Apply the packaged-build reserved-id policy at this queue+ // boundary so neither fresh discovery nor an older dirty marker can retain+ // an official namespace id for later recovery.+ const isRecoverableId = (id: string): boolean =>+ !options.rejectReservedIds || !isOfficialGhostId(id);+ const sourceDiscoveryIds = new Set([...discoveredSourceIds].filter(isRecoverableId));const targetDiscoveryIds = new Set(targetDiscovery.ghosts.map((ghost) => ghost.id));- const pendingRecoveryIds = new Set(recoveryMarker?.pendingIds ?? sourceDiscoveryIds);+ const pendingRecoveryIds = new Set(+ [...(recoveryMarker?.pendingIds ?? sourceDiscoveryIds)].filter(isRecoverableId),+ );const approvalProjectionSha256ById = new Map<string, string>(- Object.entries(recoveryMarker?.approvalProjectionSha256ById ?? {}),+ Object.entries(recoveryMarker?.approvalProjectionSha256ById ?? {})+ .filter(([id]) => isRecoverableId(id)),);const failedRecoveryIds = new Set(- recoveryMarker?.failedIds ??+ (recoveryMarker?.failedIds ??[...sourceDiscoveryIds].filter((id) =>[...sharedDiscovery.invalidIds, ...scopedDiscovery.invalidIds].includes(id),- ),+ )).filter(isRecoverableId),+ );+ const recoveryMarkerNeedsPolicyCleanup = recoveryMarker !== null && (+ recoveryMarker.pendingIds.some((id) => !isRecoverableId(id))+ || recoveryMarker.failedIds?.some((id) => !isRecoverableId(id)) === true+ || Object.keys(recoveryMarker.approvalProjectionSha256ById ?? {})+ .some((id) => !isRecoverableId(id)));for (const id of [...sharedDiscovery.invalidIds, ...scopedDiscovery.invalidIds]) {if (isValidGhostId(id) && pendingRecoveryIds.has(id)) failedRecoveryIds.add(id);@@ -1540,7 +1556,6 @@ export async function recoverLegacyGhostPlugins(// reject when options.rejectReservedIds is true (packaged builds).const recoveredTargetIds = (): string[] => [...pendingRecoveryIds].filter((id) =>- (!options.rejectReservedIds || !isOfficialGhostId(id)) &&(movedThisRun.has(id) || (targetDiscoveryIds.has(id) && !sourceDiscoveryIds.has(id)))).sort();@@ -1585,6 +1600,10 @@ export async function recoverLegacyGhostPlugins(discoveryInvalidCount + unexpectedFrozenIds.length;const movableById = new Map<string, ReturnType<typeof listLegacyGhostDirs>>();for (const legacy of [...eligibleSharedGhosts, ...scopedLegacyGhosts]) {+ if (options.rejectReservedIds && isOfficialGhostId(legacy.id)) {+ conflicts += 1;+ continue;+ }if (recoveryMarker && !pendingRecoveryIds.has(legacy.id)) {continue;}@@ -1593,10 +1612,6 @@ export async function recoverLegacyGhostPlugins(// but it remains inside the original frozen whitelist.failedRecoveryIds.delete(legacy.id);}- if (options.rejectReservedIds && isOfficialGhostId(legacy.id)) {- conflicts += 1;- continue;- }if ((await pathType(deps, path.join(targetRoot, legacy.id))) === 'missing') {const siblings = movableById.get(legacy.id) ?? [];siblings.push(legacy);@@ -1639,7 +1654,11 @@ export async function recoverLegacyGhostPlugins(: {}),};};- if (movableLegacyGhosts.length === 0 && !recoveryMarkerNeedsVersionUpgrade) {+ if (+ movableLegacyGhosts.length === 0+ && !recoveryMarkerNeedsVersionUpgrade+ && !recoveryMarkerNeedsPolicyCleanup+ ) {const result = buildNoMoveResult();recordLegacyGhostMigrationResult(ownerId, result, userDataDir);return result;@@ -1681,6 +1700,19 @@ export async function recoverLegacyGhostPlugins(return result;}+ if (+ recoveryMarkerNeedsPolicyCleanup+ && pendingRecoveryIds.size === 0+ && !sharedRecoveryBlocked+ ) {+ try {+ await deps.unlink(recoveryMarkerPath);+ } catch (error) {+ if (!isMissing(error)) throw error;+ }+ recoveryMarkerPersisted = false;+ }+// Freeze the complete approval projection only after passive/concurrent// ownership has been ruled out. A source that is still in the legacy root// can be re-frozen on every retry, but a target-only directory can never be@@ -1711,7 +1743,8 @@ export async function recoverLegacyGhostPlugins(if ((!recoveryMarkerPersisted ||approvalProjectionDigestsChanged ||- recoveryMarkerNeedsVersionUpgrade) &&+ recoveryMarkerNeedsVersionUpgrade ||+ recoveryMarkerNeedsPolicyCleanup) &&pendingRecoveryIds.size > 0 &&!sharedRecoveryBlocked) {