Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复 PID 复用导致 worktree 回收检查持续阻塞 (#4312)
DavidShenXD3d05156612d5
diff --git a/apps/desktop/src/main/__tests__/desktopProcessIdentity.test.ts b/apps/desktop/src/main/__tests__/desktopProcessIdentity.test.tsnew file mode 100644index 0000000000..507c638b69--- /dev/null+++ b/apps/desktop/src/main/__tests__/desktopProcessIdentity.test.ts@@ -0,0 +1,153 @@+import { describe, expect, it, vi } from 'vitest';++import { isReusedDesktopInstancePid, readDesktopProcessIdentity } from '../desktopProcessIdentity';++// Explicit target-platform paths; no host filesystem is accessed by these probes.+const windowsIdentity = { startedAtMs: 100_000, executablePath: 'C:\\Programs\\Cindy\\Cindy.exe' };++describe('desktop process identity probes', () => {+ it('reads only OS creation time and executable from a hidden, bounded Windows query', async () => {+ const run = vi.fn(async () => ({ stdout: JSON.stringify(windowsIdentity) }));+ expect(await readDesktopProcessIdentity(4242, 'win32', run)).toEqual(windowsIdentity);+ const [file, args, options] = run.mock.calls[0] as unknown as [string, string[], Record<string, unknown>];+ expect(file).toMatch(/\\powershell\.exe$/i);+ expect(args).toContain('Hidden');+ expect(args.at(-1)).toContain('ProcessId = 4242');+ expect(args.at(-1)).not.toContain('CommandLine');+ expect(options).toMatchObject({ timeout: 5_000, maxBuffer: 16 * 1024, windowsHide: true });+ });++ it.each(['', '{', 'null', '{}', '{"startedAtMs":0,"executablePath":"C:\\\\Cindy.exe"}',+ JSON.stringify({ ...windowsIdentity, executablePath: null }),+ JSON.stringify({ ...windowsIdentity, executablePath: 'Cindy.exe' }),+ ])('keeps missing or malformed process evidence unknown: %s', async (stdout) => {+ expect(await readDesktopProcessIdentity(4242, 'win32', async () => ({ stdout }))).toBeNull();+ });++ it('does not interpret access denial or timeout as a missing process', async () => {+ const run = vi.fn().mockRejectedValue(new Error('access denied'));+ expect(await readDesktopProcessIdentity(4242, 'win32', run)).toBeNull();+ });++ it.each([0, -1, NaN, Infinity, 1.5])('rejects invalid PID %s before executing a command', async (pid) => {+ const run = vi.fn();+ expect(await readDesktopProcessIdentity(pid, 'win32', run)).toBeNull();+ expect(run).not.toHaveBeenCalled();+ });++ it('parses POSIX birth time in UTC and retains spaces in executable paths', async () => {+ const run = vi.fn(async () => ({ stdout: 'Fri Sep 11 08:00:00 2026 /Applications/Cindy App.app/Contents/MacOS/Cindy\n' }));+ expect(await readDesktopProcessIdentity(4242, 'darwin', run)).toEqual({+ startedAtMs: Date.parse('2026-09-11T08:00:00Z'),+ executablePath: '/Applications/Cindy App.app/Contents/MacOS/Cindy',+ });+ expect(run).toHaveBeenCalledWith('ps', expect.any(Array), expect.objectContaining({+ env: expect.objectContaining({ LC_ALL: 'C', TZ: 'UTC0' }),+ }));+ });++ it('keeps truncated macOS executable evidence unknown', async () => {+ expect(await readDesktopProcessIdentity(4242, 'darwin', async () => ({+ stdout: 'Fri Sep 11 08:00:00 2026 Cindy',+ }))).toBeNull();+ });++ it.each(['/usr/bin/sleep', '/opt/Other App/other'])+ ('reads Linux executable paths from procfs when procps only returns a name: %s', async (executablePath) => {+ const ps = 'Fri Sep 11 08:00:00 2026 sleep\n';+ const run = vi.fn().mockResolvedValueOnce({ stdout: ps })+ .mockResolvedValueOnce({ stdout: `${executablePath}\n` }).mockResolvedValueOnce({ stdout: ps });+ const identity = await readDesktopProcessIdentity(4242, 'linux', run);+ expect(identity).toEqual({ startedAtMs: Date.parse('2026-09-11T08:00:00Z'), executablePath });+ expect(run).toHaveBeenNthCalledWith(2, 'readlink', ['--', '/proc/4242/exe'],+ expect.objectContaining({ timeout: 5_000, maxBuffer: 16 * 1024 }));+ expect(isReusedDesktopInstancePid({ startedAtMs: 1 }, identity!, 'linux')).toBe(true);+ });++ it.each(['/usr/bin/node', '/opt/cindy/electron'])+ ('still protects a Linux runtime identified through procfs: %s', async (executablePath) => {+ const run = vi.fn().mockResolvedValue({ stdout: 'Fri Sep 11 08:00:00 2026 runtime\n' })+ .mockResolvedValueOnce({ stdout: 'Fri Sep 11 08:00:00 2026 runtime\n' })+ .mockResolvedValueOnce({ stdout: `${executablePath}\n` });+ const identity = await readDesktopProcessIdentity(4242, 'linux', run);+ expect(identity).not.toBeNull();+ expect(isReusedDesktopInstancePid({ startedAtMs: 1 }, identity!, 'linux')).toBe(false);+ });++ it.each(['', 'sleep\n', '/usr/bin/node (deleted)\n'])+ ('keeps unusable Linux executable evidence unknown: %j', async (executable) => {+ const ps = 'Fri Sep 11 08:00:00 2026 sleep\n';+ const run = vi.fn().mockResolvedValue({ stdout: ps })+ .mockResolvedValueOnce({ stdout: ps }).mockResolvedValueOnce({ stdout: executable });+ expect(await readDesktopProcessIdentity(4242, 'linux', run)).toBeNull();+ });++ it.each(['EACCES', 'ENOENT', 'timeout'])('keeps failed Linux executable queries unknown: %s', async (reason) => {+ const run = vi.fn().mockResolvedValueOnce({ stdout: 'Fri Sep 11 08:00:00 2026 sleep\n' })+ .mockRejectedValueOnce(new Error(reason));+ expect(await readDesktopProcessIdentity(4242, 'linux', run)).toBeNull();+ });++ it.each(['', 'Fri Sep 11 08:01:00 2026 sleep\n', 'Fri Sep 11 08:00:00 2026 node\n'])+ ('rejects Linux identity if the process disappears or changes during the query: %j', async (after) => {+ const run = vi.fn().mockResolvedValueOnce({ stdout: 'Fri Sep 11 08:00:00 2026 sleep\n' })+ .mockResolvedValueOnce({ stdout: '/usr/bin/sleep\n' }).mockResolvedValueOnce({ stdout: after });+ expect(await readDesktopProcessIdentity(4242, 'linux', run)).toBeNull();+ });+});++describe('PID reuse evidence', () => {+ it('recognizes a legacy Cindy PID reused by Chrome after the record was written', () => {+ expect(isReusedDesktopInstancePid({ startedAtMs: 10_000 }, {+ startedAtMs: 100_000, executablePath: 'C:\\Chrome\\chrome.exe',+ }, 'win32')).toBe(true);+ });++ it.each([{}, { startedAtMs: null }, { startedAtMs: '1000' }, { startedAtMs: NaN },+ { startedAtMs: 0 }, { startedAtMs: 100_000 }, { startedAtMs: 200_000 },+ { startedAtMs: 99_000 }, { startedAtMs: 10_000, processIdentity: {} },+ ])('does not infer reuse from missing, overlapping, or malformed evidence: %j', (record) => {+ expect(isReusedDesktopInstancePid(record, {+ ...windowsIdentity, executablePath: 'C:\\Chrome\\chrome.exe',+ }, 'win32')).toBe(false);+ });++ it('uses the recorded OS birth rather than a later readiness heartbeat', () => {+ const identity = { startedAtMs: 100_000, executablePath: 'C:\\custom.exe' };+ expect(isReusedDesktopInstancePid({ processIdentity: identity, startedAtMs: 500_000 }, {+ ...identity, startedAtMs: 200_000,+ }, 'win32')).toBe(true);+ });++ it.each(['C:\\Programs\\Cindy\\Cindy.exe', 'C:\\tools\\electron.exe', 'C:\\nodejs\\node.exe'])+ ('keeps a possible replacement runtime protective even with a newer birth: %s', (executablePath) => {+ expect(isReusedDesktopInstancePid({ startedAtMs: 1 }, {+ startedAtMs: 100_000, executablePath,+ }, 'win32')).toBe(false);+ });++ it('preserves renamed packaged runtimes within the registered app installation', () => {+ expect(isReusedDesktopInstancePid({ startedAtMs: 1, rootDir: 'C:\\Custom App\\resources\\app.asar' }, {+ startedAtMs: 100_000, executablePath: 'C:\\Custom App\\custom.exe',+ }, 'win32')).toBe(false);+ });++ it('does not mistake Windows executable path casing for PID reuse', () => {+ const identity = { startedAtMs: 100_000, executablePath: 'C:\\Programs\\custom.exe' };+ expect(isReusedDesktopInstancePid({ processIdentity: identity }, {+ ...identity, executablePath: 'c:/programs/CUSTOM.EXE',+ }, 'win32')).toBe(false);+ });++ it('recognizes a different Windows executable even within timestamp precision', () => {+ expect(isReusedDesktopInstancePid({ processIdentity: windowsIdentity }, {+ ...windowsIdentity, executablePath: 'C:\\Chrome\\chrome.exe',+ }, 'win32')).toBe(true);+ });++ it('does not treat POSIX exec as proof that the process exited', () => {+ expect(isReusedDesktopInstancePid({ processIdentity: {+ startedAtMs: 100_000, executablePath: '/Applications/Cindy',+ } }, { startedAtMs: 100_000, executablePath: '/usr/bin/other' }, 'darwin')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/__tests__/devStartupStatus.test.ts b/apps/desktop/src/main/__tests__/devStartupStatus.test.tsindex ba8ca1a7da..f556abb28c 100644--- a/apps/desktop/src/main/__tests__/devStartupStatus.test.ts+++ b/apps/desktop/src/main/__tests__/devStartupStatus.test.ts@@ -14,6 +14,9 @@ import {} from '../devStartupStatus.js';import { withLocalProfileMigrationStartupBarrier } from '../localProfileDataMigration.js';+const readIdentity = vi.hoisted(() => vi.fn());+vi.mock('../desktopProcessIdentity.js', () => ({ readDesktopProcessIdentity: readIdentity }));+describe('devStartupStatus', () => {let tempDir: string;let statusPath: string;@@ -24,6 +27,7 @@ describe('devStartupStatus', () => {statusPath = path.join(tempDir, 'startup.json');process.env.XDT_DESKTOP_DEV_STARTUP_STATUS_FILE = statusPath;cleanup = null;+ readIdentity.mockReset().mockResolvedValue(null);});afterEach(() => {@@ -75,6 +79,84 @@ describe('devStartupStatus', () => {});});+ it('persists OS process identity through readiness updates', async () => {+ const identity = { startedAtMs: 50, executablePath: path.join(tempDir, 'Cindy') };+ readIdentity.mockResolvedValue(identity);+ cleanup = await beginDesktopDevInstance({+ userDataDir: tempDir, dbFilePrefix: 'cindy', rootDir: tempDir,+ passive: false, isolated: false, pid: 4242, startedAtMs: 100,+ });+ markDesktopDevWindowReady();+ markDesktopDevReady();+ expect(JSON.parse(fs.readFileSync(path.join(tempDir, '.dev-instances', '4242.json'), 'utf8')))+ .toMatchObject({ processIdentity: identity, startedAtMs: 100, state: 'ready' });+ });++ it('does not delay bootstrap for OS identity and preserves readiness on late enrichment', async () => {+ const identity = { startedAtMs: 50, executablePath: path.join(tempDir, 'Cindy') };+ let resolveIdentity!: (value: typeof identity) => void;+ const pending = new Promise<typeof identity>((resolve) => { resolveIdentity = resolve; });+ readIdentity.mockReturnValue(pending);+ // Must settle while the OS query is still pending, before bootstrap can+ // register its pre-ready protocols. Awaiting the probe here would deadlock.+ cleanup = await beginDesktopDevInstance({+ userDataDir: tempDir, dbFilePrefix: 'cindy', rootDir: tempDir,+ passive: false, isolated: false, pid: 4242,+ });+ const file = path.join(tempDir, '.dev-instances', '4242.json');+ expect(JSON.parse(fs.readFileSync(file, 'utf8'))).not.toHaveProperty('processIdentity');+ markDesktopDevWindowReady();+ markDesktopDevReady();+ resolveIdentity(identity);+ await pending;+ expect(JSON.parse(fs.readFileSync(file, 'utf8')))+ .toMatchObject({ state: 'ready', processIdentity: identity });+ });++ it('does not recreate the registration when an identity query completes after exit', async () => {+ let resolveIdentity!: (value: { startedAtMs: number; executablePath: string }) => void;+ const pending = new Promise<{ startedAtMs: number; executablePath: string }>((resolve) => { resolveIdentity = resolve; });+ readIdentity.mockReturnValue(pending);+ cleanup = await beginDesktopDevInstance({+ userDataDir: tempDir, dbFilePrefix: 'cindy', rootDir: tempDir,+ passive: false, isolated: false, pid: 4242,+ });+ cleanup();+ resolveIdentity({ startedAtMs: 50, executablePath: path.join(tempDir, 'Cindy') });+ await pending;+ expect(fs.existsSync(path.join(tempDir, '.dev-instances', '4242.json'))).toBe(false);+ });++ it('does not overwrite a replacement instance with a late identity result', async () => {+ let resolveIdentity!: (value: { startedAtMs: number; executablePath: string }) => void;+ const pending = new Promise<{ startedAtMs: number; executablePath: string }>((resolve) => { resolveIdentity = resolve; });+ readIdentity.mockReturnValueOnce(pending);+ const oldCleanup = await beginDesktopDevInstance({+ userDataDir: tempDir, dbFilePrefix: 'cindy', rootDir: tempDir,+ passive: false, isolated: false, pid: 4242, instanceId: 'old',+ });+ cleanup = await beginDesktopDevInstance({+ userDataDir: tempDir, dbFilePrefix: 'cindy', rootDir: tempDir,+ passive: false, isolated: false, pid: 4242, instanceId: 'replacement',+ });+ resolveIdentity({ startedAtMs: 50, executablePath: path.join(tempDir, 'old-Cindy') });+ await pending;+ oldCleanup();+ const record = JSON.parse(fs.readFileSync(path.join(tempDir, '.dev-instances', '4242.json'), 'utf8'));+ expect(record.instanceId).toBe('replacement');+ expect(record).not.toHaveProperty('processIdentity');+ });++ it('still registers when OS identity is unavailable without inventing an identity', async () => {+ cleanup = await beginDesktopDevInstance({+ userDataDir: tempDir, dbFilePrefix: 'cindy', rootDir: tempDir,+ passive: false, isolated: false, pid: 4242,+ });+ const record = JSON.parse(fs.readFileSync(path.join(tempDir, '.dev-instances', '4242.json'), 'utf8'));+ expect(record.pid).toBe(4242);+ expect(record).not.toHaveProperty('processIdentity');+ });+it('supports application readiness arriving before ready-to-show', async () => {fs.writeFileSync(statusPath, '{"state":"pending"}\n');cleanup = await beginDesktopDevInstance({diff --git a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.tsindex 1bf2bc1641..2aaa57aa7d 100644--- a/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeRuntimeSafety.test.ts@@ -5,22 +5,30 @@ import path from 'node:path';const state = vi.hoisted(() => ({ root: '' }));const notify = vi.hoisted(() => vi.fn());+const readIdentity = vi.hoisted(() => vi.fn());vi.mock('electron', () => ({ app: { getPath: () => state.root } }));vi.mock('../worktree/recycleEvents', () => ({ notifyWorktreeRecycleOpportunity: notify }));+vi.mock('../desktopProcessIdentity', async (importOriginal) => ({+ ...await importOriginal<typeof import('../desktopProcessIdentity')>(),+ readDesktopProcessIdentity: readIdentity,+}));import { acquireWorktreeRuntimeLease, releaseWorktreeRuntimeLease, readWorktreeRuntimePaths, retryPendingWorktreeRuntimeLeaseReleases } from '../worktree/runtimeLeases';import { physicalWorktreeKey, withWorktreeResourceLock } from '../worktree/resourceLock';describe('worktree runtime evidence and physical locks', () => {let worktree: string;+ const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;beforeEach(async () => {state.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-runtime-'));worktree = path.join(state.root, 'repo', '.cindy-worktrees', 'one');await fs.mkdir(path.join(worktree, 'src'), { recursive: true });await fs.mkdir(path.join(state.root, '.dev-instances'));notify.mockClear();+ readIdentity.mockReset().mockResolvedValue(null);});afterEach(async () => {+ Object.defineProperty(process, 'platform', platformDescriptor);vi.restoreAllMocks();await fs.rm(state.root, { recursive: true, force: true });});@@ -82,6 +90,121 @@ describe('worktree runtime evidence and physical locks', () => {await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'), JSON.stringify({ pid: 4242, worktreeLeaseProtocol: 1 }));await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json.bak'), JSON.stringify({ pid: 4242 }));expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ expect(readIdentity).not.toHaveBeenCalled();+ });++ it('ignores a legacy registration whose PID was reused, but keeps its detached-child lease', async () => {+ const lease = (await acquireWorktreeRuntimeLease('one', worktree))!;+ const file = path.join(state.root, '.dev-instances', '4242.json');+ const raw = JSON.stringify({ pid: 4242, startedAtMs: 10_000 });+ await fs.writeFile(file, raw);+ vi.spyOn(process, 'kill').mockReturnValue(true);+ readIdentity.mockResolvedValue({ startedAtMs: 100_000, executablePath: path.join(state.root, 'chrome.exe') });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([await physicalWorktreeKey(worktree)]));+ expect(await fs.readFile(file, 'utf8')).toBe(raw);+ await releaseWorktreeRuntimeLease(lease);+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ });++ it('keeps a real legacy Cindy instance protective', async () => {+ await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'),+ JSON.stringify({ pid: 4242, startedAtMs: 100_000 }));+ vi.spyOn(process, 'kill').mockReturnValue(true);+ readIdentity.mockResolvedValue({ startedAtMs: 99_000, executablePath: process.execPath });+ expect(await readWorktreeRuntimePaths()).toBeNull();+ });++ describe('POSIX SingletonLock PID reuse', () => {+ const raw = JSON.stringify({ pid: 4242, startedAtMs: 10_000 });+ const identity = { startedAtMs: 100_000, executablePath: '/usr/bin/other' };+ beforeEach(async () => {+ Object.defineProperty(process, 'platform', { ...platformDescriptor, value: 'darwin' });+ await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'), raw);+ vi.spyOn(process, 'kill').mockReturnValue(true);+ vi.spyOn(fs, 'readlink').mockResolvedValue('hostname-4242');+ readIdentity.mockResolvedValue(identity);+ });++ it.each(['darwin', 'linux'])('ignores a proven reused lock PID on %s while retaining detached-child leases', async (platform) => {+ Object.defineProperty(process, 'platform', { ...platformDescriptor, value: platform });+ const root = path.join(state.root, 'worktree-runtime-leases');+ await fs.mkdir(root);+ await fs.writeFile(path.join(root, `4242-${'a'.repeat(64)}.json`),+ JSON.stringify({ version: 1, pid: 4242, path: worktree }));+ expect(await readWorktreeRuntimePaths()).toEqual(new Set([worktree]));+ expect(await fs.readFile(path.join(state.root, '.dev-instances', '4242.json'), 'utf8')).toBe(raw);+ });++ it('still blocks an unrelated live lock PID without reuse evidence', async () => {+ vi.mocked(fs.readlink).mockResolvedValue('hostname-4343');+ expect(await readWorktreeRuntimePaths()).toBeNull();+ });++ it.each([null, { ...identity, executablePath: '/opt/Cindy.app/Contents/MacOS/Cindy' }])+ ('does not waive the lock when identity becomes unavailable or a runtime replaces the process: %j', async (latest) => {+ readIdentity.mockResolvedValueOnce(identity).mockResolvedValueOnce(latest);+ expect(await readWorktreeRuntimePaths()).toBeNull();+ });++ it('does not waive a lock whose target changes during revalidation', async () => {+ vi.mocked(fs.readlink).mockResolvedValueOnce('hostname-4242').mockResolvedValueOnce('hostname-4343');+ expect(await readWorktreeRuntimePaths()).toBeNull();+ });++ it.each(['replace', 'remove'])('does not waive the lock when its instance registration changes: %s', async (change) => {+ readIdentity.mockResolvedValueOnce(identity).mockImplementationOnce(async () => {+ const file = path.join(state.root, '.dev-instances', '4242.json');+ if (change === 'remove') await fs.unlink(file);+ else await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: 200_000 }));+ return identity;+ });+ expect(await readWorktreeRuntimePaths()).toBeNull();+ });+ });++ it('keeps a replacement Cindy protective before its new registration is published', async () => {+ await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'),+ JSON.stringify({ pid: 4242, startedAtMs: 1 }));+ vi.spyOn(process, 'kill').mockReturnValue(true);+ readIdentity.mockResolvedValue({ startedAtMs: 100_000, executablePath: path.join(state.root, 'Cindy.exe') });+ expect(await readWorktreeRuntimePaths()).toBeNull();+ });++ it('preserves when process identity is unavailable even for a very old registration', async () => {+ await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'),+ JSON.stringify({ pid: 4242, startedAtMs: 1 }));+ vi.spyOn(process, 'kill').mockReturnValue(true);+ expect(await readWorktreeRuntimePaths()).toBeNull();+ });++ it('rechecks liveness when the process exits during the identity query', async () => {+ await fs.writeFile(path.join(state.root, '.dev-instances', '4242.json'), JSON.stringify({ pid: 4242 }));+ vi.spyOn(process, 'kill').mockReturnValueOnce(true).mockImplementation(() => {+ throw Object.assign(new Error('exited'), { code: 'ESRCH' });+ });+ expect(await readWorktreeRuntimePaths()).toEqual(new Set());+ });++ it('does not apply stale evidence after another instance replaces the registry record', async () => {+ const file = path.join(state.root, '.dev-instances', '4242.json');+ await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: 10_000 }));+ vi.spyOn(process, 'kill').mockReturnValue(true);+ readIdentity.mockImplementation(async () => {+ await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: 200_000 }));+ return { startedAtMs: 100_000, executablePath: path.join(state.root, 'chrome.exe') };+ });+ expect(await readWorktreeRuntimePaths()).toBeNull();+ });++ it('does not trust a backup after a new primary registration appears during the probe', async () => {+ const file = path.join(state.root, '.dev-instances', '4242.json');+ await fs.writeFile(`${file}.bak`, JSON.stringify({ pid: 4242, startedAtMs: 10_000 }));+ vi.spyOn(process, 'kill').mockReturnValue(true);+ readIdentity.mockImplementation(async () => {+ await fs.writeFile(file, JSON.stringify({ pid: 4242, startedAtMs: 200_000 }));+ return { startedAtMs: 100_000, executablePath: path.join(state.root, 'chrome.exe') };+ });+ expect(await readWorktreeRuntimePaths()).toBeNull();});it('does not mistake an unreadable live lease for a stopped runtime', async () => {diff --git a/apps/desktop/src/main/desktopProcessIdentity.ts b/apps/desktop/src/main/desktopProcessIdentity.tsnew file mode 100644index 0000000000..b38c4e8021--- /dev/null+++ b/apps/desktop/src/main/desktopProcessIdentity.ts@@ -0,0 +1,114 @@+import { execFile } from 'node:child_process';+import path from 'node:path';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);++/** OS birth time and executable, not an application registration/heartbeat time. */+export interface DesktopProcessIdentity {+ startedAtMs: number;+ executablePath: string;+}++type IdentityCommand = (file: string, args: string[], options: {+ encoding: 'utf8'; timeout: number; maxBuffer: number; windowsHide: boolean;+ env?: NodeJS.ProcessEnv;+}) => Promise<{ stdout: string }>;++function validIdentity(value: unknown, platform: NodeJS.Platform): value is DesktopProcessIdentity {+ if (!value || typeof value !== 'object') return false;+ const identity = value as Partial<DesktopProcessIdentity>;+ const paths = platform === 'win32' ? path.win32 : path.posix;+ return typeof identity.startedAtMs === 'number' && Number.isFinite(identity.startedAtMs)+ && identity.startedAtMs > 0 && typeof identity.executablePath === 'string'+ && paths.isAbsolute(identity.executablePath);+}++/** Bounded, read-only probe. Missing, inaccessible and malformed results remain unknown. */+export async function readDesktopProcessIdentity(+ pid: number,+ platform: NodeJS.Platform = process.platform,+ runCommand: IdentityCommand = execFileAsync,+): Promise<DesktopProcessIdentity | null> {+ if (!Number.isSafeInteger(pid) || pid <= 0) return null;+ const options = { encoding: 'utf8' as const, timeout: 5_000, maxBuffer: 16 * 1024, windowsHide: true };+ try {+ let identity: unknown;+ if (platform === 'win32') {+ const powershell = path.win32.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');+ // No command line or environment is collected. Serialize only identity fields.+ const script = `$ErrorActionPreference = 'Stop'; `+ + `[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); `+ + `$instance = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}'; `+ + `if ($null -ne $instance) { [pscustomobject]@{ `+ + `startedAtMs = ([DateTimeOffset]$instance.CreationDate.ToUniversalTime()).ToUnixTimeMilliseconds(); `+ + `executablePath = $instance.ExecutablePath } | ConvertTo-Json -Compress }`;+ const { stdout } = await runCommand(powershell,+ ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', script], options);+ identity = JSON.parse(stdout);+ } else {+ const psArgs = ['-ww', '-p', String(pid), '-o', 'lstart=', '-o', 'comm='];+ const psOptions = { ...options, env: { ...process.env, LC_ALL: 'C', TZ: 'UTC0' } };+ const { stdout } = await runCommand('ps', psArgs, psOptions);+ const match = /^(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/.exec(stdout.trim());+ if (!match) return null;+ let executablePath = match[2];+ if (platform === 'linux') {+ // procps comm is a name, not a path. Read the kernel executable link,+ // then recheck ps so an observed process change cannot mix identities.+ const executable = await runCommand('readlink', ['--', `/proc/${pid}/exe`], options);+ executablePath = executable.stdout.replace(/\n$/, '');+ // Deleted executables carry a kernel suffix that could hide a runtime+ // name from the protection checks. Treat that evidence as unknown.+ if (executablePath.endsWith(' (deleted)')) return null;+ const after = await runCommand('ps', psArgs, psOptions);+ if (after.stdout !== stdout) return null;+ }+ identity = { startedAtMs: Date.parse(`${match[1]} UTC`), executablePath };+ }+ return validIdentity(identity, platform) ? identity : null;+ } catch {+ return null;+ }+}++/**+ * Proves PID reuse without deleting the record or releasing any detached-child lease.+ * Legacy startedAtMs was captured during registration: a substantially later OS birth+ * cannot belong to that instance. Earlier/equal times are deliberately inconclusive.+ */+export function isReusedDesktopInstancePid(+ record: { startedAtMs?: unknown; processIdentity?: unknown; rootDir?: unknown },+ current: DesktopProcessIdentity,+ platform: NodeJS.Platform = process.platform,+): boolean {+ if (!validIdentity(current, platform)) return false;+ const paths = platform === 'win32' ? path.win32 : path.posix;+ const executable = paths.normalize(current.executablePath).replaceAll('\\', '/').toLowerCase();+ // A replacement Cindy/Electron might not have published its own registration+ // yet. Such a runtime remains protective even when its birth time is newer.+ // Also retain Node launchers and executables within the recorded checkout/app.+ const name = paths.basename(current.executablePath).toLowerCase();+ if (/^(?:cindy|electron|node)(?:\.exe)?$/.test(name)+ || executable.includes('/cindy.app/') || executable.includes('/electron.app/')) return false;+ if (typeof record.rootDir === 'string' && paths.isAbsolute(record.rootDir)) {+ const root = paths.normalize(record.rootDir).replaceAll('\\', '/').toLowerCase();+ const resourcesIndex = root.indexOf('/resources/');+ const runtimeRoot = (resourcesIndex >= 0 ? root.slice(0, resourcesIndex) : root).replace(/\/$/, '');+ if (executable.startsWith(`${runtimeRoot}/`)) return false;+ }+ // ps reports whole seconds; also allow timestamp rounding in legacy records.+ const toleranceMs = 2_000;+ if (record.processIdentity !== undefined) {+ if (!validIdentity(record.processIdentity, platform)) return false;+ const previous = record.processIdentity;+ if (current.startedAtMs > previous.startedAtMs + toleranceMs) return true;+ // POSIX exec can change the executable without ending the process. Windows+ // cannot, so a different executable also disproves the recorded identity.+ return platform === 'win32'+ && path.win32.normalize(previous.executablePath).toLowerCase()+ !== path.win32.normalize(current.executablePath).toLowerCase();+ }+ return typeof record.startedAtMs === 'number' && Number.isFinite(record.startedAtMs)+ && record.startedAtMs > 0 && current.startedAtMs > record.startedAtMs + toleranceMs;+}diff --git a/apps/desktop/src/main/devStartupStatus.ts b/apps/desktop/src/main/devStartupStatus.tsindex f34e73e5d6..58e69e82ee 100644--- a/apps/desktop/src/main/devStartupStatus.ts+++ b/apps/desktop/src/main/devStartupStatus.ts@@ -5,6 +5,7 @@ import type { CindyRegion } from '@cindy/maker-shared/brand-identity';import type { DevProfileKind } from './devCliFlags.js';import { withLocalProfileMigrationStartupBarrier } from './localProfileDataMigration.js';import { atomicWriteFileSync } from './utils/atomicWriteFile.js';+import { readDesktopProcessIdentity, type DesktopProcessIdentity } from './desktopProcessIdentity.js';export type DesktopDevMode = 'remote' | 'local' | 'unknown';export type DesktopDevInstanceState = 'starting' | 'ready' | 'failed';@@ -25,6 +26,8 @@ export interface DesktopDevInstanceRecord {instanceId: string;pid: number;startedAtMs: number;+ /** Optional for legacy readers/writers; absence never claims that a PID is stale. */+ processIdentity?: DesktopProcessIdentity;updatedAtMs: number;rootDir: string;commit: string | null;@@ -167,6 +170,21 @@ export async function beginDesktopDevInstance(throw error;}+ // bootstrap-electron is loaded after registration and must install privileged+ // schemes before Electron's ready event. Never await an OS subprocess here.+ // Identity is optional evidence: enrich only the instance we still own, using+ // its latest readiness state, and never resurrect a record removed on exit.+ void readDesktopProcessIdentity(pid).then((identity) => {+ const current = trackedInstance;+ if (!identity || current?.record.instanceId !== record.instanceId) return;+ if (readJson(filePath)?.instanceId !== record.instanceId) return;+ const updated = { ...current.record, processIdentity: identity };+ atomicWriteJson(filePath, updated);+ trackedInstance = { filePath, record: updated };+ }).catch(() => {+ // Failure to enrich must not affect startup or weaken legacy PID checks.+ });+return () => {if (trackedInstance?.record.instanceId === record.instanceId) trackedInstance = null;try {diff --git a/apps/desktop/src/main/worktree/runtimeLeases.ts b/apps/desktop/src/main/worktree/runtimeLeases.tsindex 488a34ef0d..5289dafa94 100644--- a/apps/desktop/src/main/worktree/runtimeLeases.ts+++ b/apps/desktop/src/main/worktree/runtimeLeases.ts@@ -6,6 +6,7 @@ import { app } from 'electron';import { physicalWorktreeKey, withWorktreeResourceLock } from './resourceLock';import { isManagedWorktreeDirectoryName } from '../../shared/managedWorktreePaths';import { notifyWorktreeRecycleOpportunity } from './recycleEvents';+import { isReusedDesktopInstancePid, readDesktopProcessIdentity } from '../desktopProcessIdentity';function runtimeRoot(): string {return path.join(app.getPath('userData'), 'worktree-runtime-leases');@@ -125,18 +126,34 @@ export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {const registry = path.join(app.getPath('userData'), '.dev-instances');const names = new Set((await fs.readdir(registry)).map((name) => name.replace(/\.bak$/, '')));const compatiblePids = new Set([process.pid]);+ const reusedInstanceRecords = new Map<number, string>();+ const readRecord = async (name: string): Promise<string> => {+ try { return await fs.readFile(path.join(registry, name), 'utf8'); } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ return fs.readFile(path.join(registry, `${name}.bak`), 'utf8');+ }+ };for (const name of names) {const match = /^(\d+)\.json$/.exec(name);if (!match) continue;const pid = Number(match[1]);if (pid === process.pid || !pidMayBeAlive(pid)) continue;try {- let raw: string;- try { raw = await fs.readFile(path.join(registry, name), 'utf8'); } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;- raw = await fs.readFile(path.join(registry, `${name}.bak`), 'utf8');- }+ const raw = await readRecord(name);const record = JSON.parse(raw);+ if (!record || record.pid !== pid) return null;+ // Only unsupported instances can block the entire lease view. Do not add+ // an OS subprocess per compatible instance to the normal recycle path.+ if (record.worktreeLeaseProtocol !== 1) {+ const identity = await readDesktopProcessIdentity(pid);+ // A replacement instance may have registered while the OS query ran.+ if (await readRecord(name) !== raw) return null;+ if (!pidMayBeAlive(pid)) continue;+ if (identity && isReusedDesktopInstancePid(record, identity)) {+ reusedInstanceRecords.set(pid, raw);+ continue;+ }+ }if (record.worktreeLeaseProtocol !== 1 || record.pid !== pid) return null;compatiblePids.add(pid);} catch {@@ -149,7 +166,22 @@ export async function readWorktreeRuntimePaths(): Promise<Set<string> | null> {const match = /-(\d+)$/.exec(target);if (!match) return null;const pid = Number(match[1]);- if (pidMayBeAlive(pid) && !compatiblePids.has(pid)) return null;+ if (pidMayBeAlive(pid) && !compatiblePids.has(pid)) {+ const raw = reusedInstanceRecords.get(pid);+ if (!raw) return null;+ // A stale SingletonLock can reference the same reused PID as an old+ // registration. Revalidate before waiving it: another runtime or lock+ // owner may have appeared since the registry scan. Child leases below+ // remain independent protection, even when this lock is proven stale.+ try {+ const identity = await readDesktopProcessIdentity(pid);+ if (!identity || !isReusedDesktopInstancePid(JSON.parse(raw), identity)+ || await readRecord(`${pid}.json`) !== raw+ || await fs.readlink(path.join(app.getPath('userData'), 'SingletonLock')) !== target) return null;+ } catch {+ return null;+ }+ }} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return null;}