Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): recover Windows locks and preserve disabled receipts
Yuewei-LLd20c094fbece
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 5b26550bf5..4e562ff51f 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -3442,7 +3442,13 @@ export class GhostManager {this.receiptStore.skillSnapshotRoot(manifest.id, current.receipt.revision),));if (!snapshotHealthy) {- await this.receiptStore.write(current.receipt, { skillSourceDir: sourceDir });+ // Snapshot repair must persist the same one-way disabled merge as the+ // healthy-snapshot path. Otherwise deleting the compatibility marker+ // after this early return could silently re-enable the plugin.+ await this.receiptStore.write({+ ...current.receipt,+ enabled,+ }, { skillSourceDir: sourceDir });await this.finishTrustedBundledPublish(manifest.id, pendingPublish);this.untrustedApprovals.delete(this.isolationKey(manifest.id));return true;diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 227c0d9920..be3b0d6a6e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -3600,6 +3600,43 @@ describe('GhostManager · Host approval receipt', () => {).toContain('Approved instructions');});+ it('snapshot repair persists a one-way disable before the compatibility marker disappears', async () => {+ const manifest = skillManifest();+ await manager.install(await makeCindy('skill.cindy', manifest, skillFiles()));+ const listed = manager.list()[0];+ const source = await writeBundledSource(listed.manifest, skillFiles());+ expect(await manager.approveTrustedBundledInstall(listed.manifest, true, source)).toBe(true);++ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const disabledMarker = path.join(rootDir, listed.manifest.id, '.disabled');+ await fs.promises.writeFile(disabledMarker, '');+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });++ expect(+ await manager.approveTrustedBundledInstall(listed.manifest, false, source),+ ).toBe(true);+ expect(JSON.parse(await fs.promises.readFile(receiptPath('skilled'), 'utf8'))).toMatchObject({+ enabled: false,+ });++ await fs.promises.rm(disabledMarker);+ const restarted = new GhostManager({+ getRootDir: () => rootDir,+ getLocale: () => hostLocale,+ isTrustedBundledId: (id) => trustedBundledIds.has(id),+ isTrustedBundledSource: (id, sourceDir) =>+ trustedBundledIds.has(id) &&+ path.resolve(sourceDir) === path.resolve(workDir, 'bundled-seeds', id),+ mutateSnapshot: async (request) => {+ const { parentDir, ...workerRequest } = request;+ await runGhostSnapshotWorkerRequest(workerRequest, parentDir);+ },+ });+ await restarted.approveTrustedBundledInstall(listed.manifest, true, source);+ expect(restarted.list()[0].enabled).toBe(false);+ expect(fs.existsSync(disabledMarker)).toBe(true);+ });+it('invalidates a receipt whose skill content digests no longer match the manifest', async () => {await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));const receipt = JSON.parse(diff --git a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.tsindex 06e4e81c18..c8632bf2c7 100644--- a/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/crossProcessLock.test.ts@@ -877,4 +877,61 @@ describe('接管陈旧锁', () => {),).resolves.toBeNull();});++ it('distinguishes a missing Windows process from an unavailable identity query', async () => {+ await expect(+ __testing.readWindowsIdentityWithPowershell(+ 123,+ async () => ({ stdout: 'MISSING\r\n' }),+ ),+ ).resolves.toEqual({ status: 'missing' });+ await expect(+ __testing.readWindowsIdentityWithPowershell(+ 123,+ async () => ({ stdout: 'unexpected output' }),+ ),+ ).resolves.toEqual({ status: 'unavailable' });+ await expect(+ __testing.readWindowsIdentityWithWmic(+ 123,+ async () => ({ stdout: 'No Instance(s) Available.\r\n' }),+ ),+ ).resolves.toEqual({ status: 'missing' });+ await expect(+ __testing.readWindowsIdentityWithWmic(+ 123,+ async () => ({ stdout: 'ERROR: provider unavailable\r\n' }),+ ),+ ).resolves.toEqual({ status: 'unavailable' });+ await expect(+ __testing.probeProcessIdentity(+ 123,+ async () => ({ stdout: '' }),+ ),+ ).resolves.toEqual({ status: 'unavailable' });+ });++ it('retries transient empty-directory removal without recursive deletion', async () => {+ const gateDir = path.join(dir, 'lock.reclaim.d');+ await fsp.mkdir(gateDir);+ const originalRmdir = fsp.rmdir;+ let attempts = 0;+ const rmdirSpy = vi.spyOn(fsp, 'rmdir').mockImplementation((async (target: unknown) => {+ if (target === gateDir && attempts < 2) {+ attempts += 1;+ throw Object.assign(new Error('directory temporarily busy'), { code: 'EPERM' });+ }+ return originalRmdir(target as string);+ }) as typeof fsp.rmdir);+ const rmSpy = vi.spyOn(fsp, 'rm');+ try {+ await __testing.removeEmptyDirectoryWithRetry(gateDir);+ expect(attempts).toBe(2);+ expect(fs.existsSync(gateDir)).toBe(false);+ expect(rmSpy).not.toHaveBeenCalledWith(gateDir, expect.objectContaining({ recursive: true }));+ } finally {+ rmdirSpy.mockRestore();+ rmSpy.mockRestore();+ }+ });});diff --git a/apps/desktop/src/main/device-link/crossProcessLock.ts b/apps/desktop/src/main/device-link/crossProcessLock.tsindex 405797911b..1650b8fad1 100644--- a/apps/desktop/src/main/device-link/crossProcessLock.ts+++ b/apps/desktop/src/main/device-link/crossProcessLock.ts@@ -33,6 +33,7 @@ const MAX_TAKEOVERS = 3;const LOCK_HEARTBEAT_MS = 2_000;const LEGACY_PID_REUSE_TOLERANCE_MS = 2_000;const REMOVE_RETRY_ATTEMPTS = 3;+const EMPTY_DIR_REMOVE_RETRY_ATTEMPTS = 5;const RELEASE_GATE_WAIT_MS = 3_000;const execFileAsync = promisify(execFile);@@ -77,6 +78,10 @@ interface ProcessIdentity {key: string;startedAtMs: number | null;}+type ProcessIdentityProbe =+ | { status: 'found'; identity: ProcessIdentity }+ | { status: 'missing' }+ | { status: 'unavailable' };type PublishedLock = {handle: Awaited<ReturnType<typeof fsp.open>>;nonce: string;@@ -644,11 +649,7 @@ async function releaseAdvisoryReclaimGate(gate: AdvisoryReclaimGate): Promise<voawait removePathWithRetry(gate.filePath);}if (await pathExists(gate.filePath)) pendingOwnGateCleanup.add(gate.filePath);- try {- await fsp.rmdir(gate.dirPath);- } catch {- // Strict or advisory contenders may still be using the shared directory.- }+ await removeEmptyDirectoryWithRetry(gate.dirPath);}async function readLockRecord(@@ -1108,8 +1109,10 @@ async function isRecordOwnerActive(// identity query decide when possible; if it also fails, the caller below// remains fail-closed.}- const currentIdentity = await getProcessIdentity(record.pid);- if (!currentIdentity) return true;+ const identityProbe = await probeProcessIdentity(record.pid);+ if (identityProbe.status === 'missing') return false;+ if (identityProbe.status === 'unavailable') return true;+ const currentIdentity = identityProbe.identity;// Exact process identity is the strongest signal and must be checked before// the self-pid shortcut: after a crash + PID reuse the OS may hand our pid to// this process while the lock still records the dead instance's identity, so@@ -1146,12 +1149,20 @@ async function readProcessIdentity(pid: number,runCommand: ExecFileRunner = execFileAsync as ExecFileRunner,): Promise<ProcessIdentity | null> {+ const probe = await probeProcessIdentity(pid, runCommand);+ if (probe.status === 'found') return probe.identity;+ return pid === process.pid ? estimateCurrentProcessIdentity() : null;+}++async function probeProcessIdentity(+ pid: number,+ runCommand: ExecFileRunner = execFileAsync as ExecFileRunner,+): Promise<ProcessIdentityProbe> {if (process.platform === 'win32') {const fromPowershell = await readWindowsIdentityWithPowershell(pid, runCommand);- if (fromPowershell) return fromPowershell;+ if (fromPowershell.status !== 'unavailable') return fromPowershell;const fromWmic = await readWindowsIdentityWithWmic(pid, runCommand);- if (fromWmic) return fromWmic;- return pid === process.pid ? estimateCurrentProcessIdentity() : null;+ return fromWmic;}try {const { stdout } = await runCommand(@@ -1164,41 +1175,48 @@ async function readProcessIdentity(},);const value = stdout.trim().replace(/\s+/g, ' ');- if (!value) return pid === process.pid ? estimateCurrentProcessIdentity() : null;+ // A successful command with no parseable identity is not affirmative+ // proof that the process is gone. `process.kill(pid, 0)` already handles+ // the OS-level missing case; keep ambiguous `ps` output fail-closed.+ if (!value) return { status: 'unavailable' };const parsed = Date.parse(`${value} UTC`);- return processIdentityFromStartMs(parsed, value);+ const identity = processIdentityFromStartMs(parsed, value);+ return identity ? { status: 'found', identity } : { status: 'unavailable' };} catch {- return pid === process.pid ? estimateCurrentProcessIdentity() : null;+ return { status: 'unavailable' };}}async function readWindowsIdentityWithPowershell(pid: number,runCommand: ExecFileRunner,-): Promise<ProcessIdentity | null> {+): Promise<ProcessIdentityProbe> {try {const powershell = `${process.env.SystemRoot ?? 'C:\\Windows'}`+ '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';const script =`$p = Get-CimInstance Win32_Process -Filter \"ProcessId = ${pid}\" -ErrorAction Stop; `- + `if ($p) { $p.CreationDate.ToUniversalTime().Ticks }`;+ + `if ($null -eq $p) { 'MISSING' } else { $p.CreationDate.ToUniversalTime().Ticks }`;const { stdout } = await runCommand(powershell,['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', script],{ encoding: 'utf8', timeout: 5_000, windowsHide: true },);- const ticks = Number(stdout.trim());- if (!Number.isFinite(ticks)) return null;- return processIdentityFromStartMs(ticks / 10_000 - 62_135_596_800_000);+ const value = stdout.trim();+ if (value === 'MISSING') return { status: 'missing' };+ if (!/^\d+$/.test(value)) return { status: 'unavailable' };+ const ticks = Number(value);+ const identity = processIdentityFromStartMs(ticks / 10_000 - 62_135_596_800_000);+ return identity ? { status: 'found', identity } : { status: 'unavailable' };} catch {- return null;+ return { status: 'unavailable' };}}async function readWindowsIdentityWithWmic(pid: number,runCommand: ExecFileRunner,-): Promise<ProcessIdentity | null> {+): Promise<ProcessIdentityProbe> {try {const wmic = `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\wbem\\WMIC.exe`;const { stdout } = await runCommand(@@ -1207,7 +1225,11 @@ async function readWindowsIdentityWithWmic({ encoding: 'utf8', timeout: 5_000, windowsHide: true },);const match = stdout.match(/CreationDate=(\d{14})\.(\d{1,6})([+-]\d{3})/i);- if (!match) return null;+ if (!match) {+ return /^\s*No Instance\(s\) Available\.\s*$/i.test(stdout)+ ? { status: 'missing' }+ : { status: 'unavailable' };+ }const stamp = match[1];const micros = match[2].padEnd(6, '0');const offsetMinutes = Number(match[3]);@@ -1220,9 +1242,10 @@ async function readWindowsIdentityWithWmic(Number(stamp.slice(12, 14)),Number(micros.slice(0, 3)),);- return processIdentityFromStartMs(localMs - offsetMinutes * 60_000);+ const identity = processIdentityFromStartMs(localMs - offsetMinutes * 60_000);+ return identity ? { status: 'found', identity } : { status: 'unavailable' };} catch {- return null;+ return { status: 'unavailable' };}}@@ -1376,11 +1399,7 @@ async function releaseReclaimGate(gate: ReclaimGate): Promise<void> {} else if (!releasedRecordDurable) {await removePathWithRetry(gateReleaseMarkerPath(gate.filePath));}- try {- await fsp.rmdir(gate.dirPath);- } catch {- // Another contender may already be publishing in the directory.- }+ await removeEmptyDirectoryWithRetry(gate.dirPath);}async function publishGateReleaseMarker(gate: ReclaimGate): Promise<void> {@@ -1511,11 +1530,34 @@ async function removePathWithRetry(file: string): Promise<void> {}}+/** Retry only empty-directory removal; never delete a contender recursively. */+async function removeEmptyDirectoryWithRetry(dir: string): Promise<void> {+ for (let attempt = 0; attempt < EMPTY_DIR_REMOVE_RETRY_ATTEMPTS; attempt += 1) {+ try {+ await fsp.rmdir(dir);+ return;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (code === 'ENOENT' || code === 'ENOTDIR') return;+ if (code !== 'EPERM' && code !== 'EBUSY' && code !== 'EACCES' && code !== 'ENOTEMPTY') {+ return;+ }+ if (attempt + 1 < EMPTY_DIR_REMOVE_RETRY_ATTEMPTS) {+ await sleep(LOCK_RETRY_MS * (attempt + 1));+ }+ }+ }+}+export const __testing = {staleMs: LOCK_STALE_MS,heartbeatMs: LOCK_HEARTBEAT_MS,getProcessIdentity,readProcessIdentity,+ probeProcessIdentity,+ readWindowsIdentityWithPowershell,+ readWindowsIdentityWithWmic,+ removeEmptyDirectoryWithRetry,parseRecordedProcessStartMs,processIdentitiesMatch,};