Skip to content

Chrome DevTools for coding agents

fix(daemon): verify process identity before treating PID file as active (#3109)

Nikolay Vitkovb608bedbaa19
diff --git a/src/bin/chrome-devtools.ts b/src/bin/chrome-devtools.ts
index 59ea2375..66729871 100644
--- a/src/bin/chrome-devtools.ts
+++ b/src/bin/chrome-devtools.ts
@@ -256,11 +256,12 @@ for (const [commandName, commandDef] of Object.entries(commands)) {
async argv => {
const sessionId = argv.sessionId as string;
try {
- const versionWarningPromise = isDaemonRunning(sessionId)
+ const daemonRunning = isDaemonRunning(sessionId);
+ const versionWarningPromise = daemonRunning
? verifyDaemonVersion(sessionId, VERSION)
: Promise.resolve(undefined);
- if (!isDaemonRunning(sessionId)) {
+ if (!daemonRunning) {
await start(serializeArgs(mcpOptions, argv), sessionId);
}
diff --git a/src/daemon/utils.ts b/src/daemon/utils.ts
index 217282c3..7e01d296 100644
--- a/src/daemon/utils.ts
+++ b/src/daemon/utils.ts
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
+import childProcess from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -93,15 +94,67 @@ export function getDaemonPid(sessionId: string): number | null {
}
}
+const verifiedDaemonPids = new Map<number, boolean>();
+
+function getProcessCommandLine(pid: number): string {
+ if (process.platform === 'linux' && fs.existsSync('/proc')) {
+ return fs
+ .readFileSync(`/proc/${pid}/cmdline`, 'utf-8')
+ .replaceAll('\0', ' ');
+ }
+ if (IS_WINDOWS) {
+ return childProcess.execFileSync(
+ 'powershell.exe',
+ [
+ '-NoProfile',
+ '-NonInteractive',
+ '-Command',
+ `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`,
+ ],
+ {
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ windowsHide: true,
+ },
+ );
+ }
+ return childProcess.execFileSync(
+ 'ps',
+ ['-p', String(pid), '-o', 'command='],
+ {
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ },
+ );
+}
+
+function isDaemonProcess(pid: number): boolean {
+ const cached = verifiedDaemonPids.get(pid);
+ if (cached !== undefined) {
+ return cached;
+ }
+ try {
+ const commandLine = getProcessCommandLine(pid).trim();
+ const isDaemon =
+ commandLine === '' || /[\\/]daemon[\\/]daemon\.js/.test(commandLine);
+ verifiedDaemonPids.set(pid, isDaemon);
+ return isDaemon;
+ } catch {
+ verifiedDaemonPids.set(pid, true);
+ return true;
+ }
+}
+
export function isDaemonRunning(sessionId: string): boolean {
assertValidSessionId(sessionId);
const pid = getDaemonPid(sessionId);
if (pid) {
try {
process.kill(pid, 0); // Throws if process doesn't exist
- return true;
+ return isDaemonProcess(pid);
} catch {
// Process is dead, stale PID file. Proceed with startup.
+ verifiedDaemonPids.delete(pid);
}
}
return false;
diff --git a/tests/daemon/client.test.ts b/tests/daemon/client.test.ts
index 8a87f128..cf4804f8 100644
--- a/tests/daemon/client.test.ts
+++ b/tests/daemon/client.test.ts
@@ -18,6 +18,7 @@ import {
verifyDaemonVersion,
} from '../../src/daemon/client.js';
import {
+ DAEMON_SCRIPT_PATH,
getDaemonPid,
getPidFilePath,
isDaemonRunning,
@@ -82,7 +83,7 @@ describe('daemon client', () => {
it('should stop and allow restarting a daemon when its socket is unreachable', async () => {
const child = spawn(
process.execPath,
- ['-e', 'setInterval(() => {}, 1000)'],
+ ['-e', 'setInterval(() => {}, 1000)', DAEMON_SCRIPT_PATH],
{
stdio: 'ignore',
},
@@ -115,6 +116,44 @@ describe('daemon client', () => {
child.kill();
}
});
+
+ it('should not signal an unrelated process when its PID is in the PID file', async () => {
+ const child = spawn(
+ process.execPath,
+ ['-e', 'setInterval(() => {}, 1000)'],
+ {
+ stdio: 'ignore',
+ },
+ );
+ child.unref();
+ const childPid = child.pid;
+ assert.ok(childPid, 'Child process should have a PID');
+
+ try {
+ const pidFilePath = getPidFilePath(sessionId);
+ mkdirSync(dirname(pidFilePath), {recursive: true, mode: 0o700});
+ writeFileSync(pidFilePath, String(childPid), 'utf-8');
+
+ await stopDaemon(sessionId);
+ assert.doesNotThrow(
+ () => process.kill(childPid, 0),
+ 'stopDaemon must not kill the unrelated process',
+ );
+
+ await startDaemon([], sessionId);
+ assert.ok(
+ isDaemonRunning(sessionId),
+ 'New daemon should start when PID file points to an unrelated process',
+ );
+ assert.notStrictEqual(getDaemonPid(sessionId), childPid);
+ assert.doesNotThrow(
+ () => process.kill(childPid, 0),
+ 'startDaemon must not kill the unrelated process',
+ );
+ } finally {
+ child.kill();
+ }
+ });
});
describe('verifyDaemonVersion', () => {
diff --git a/tests/daemon/utils.test.ts b/tests/daemon/utils.test.ts
index 24f2ad4c..c90092f3 100644
--- a/tests/daemon/utils.test.ts
+++ b/tests/daemon/utils.test.ts
@@ -5,7 +5,7 @@
*/
import assert from 'node:assert';
-import {spawn} from 'node:child_process';
+import childProcess, {spawn} from 'node:child_process';
import {once} from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
@@ -13,8 +13,11 @@ import path from 'node:path';
import process from 'node:process';
import {afterEach, beforeEach, describe, it} from 'node:test';
+import sinon from 'sinon';
+
import type {ParsedArguments} from '../../src/config/ConfigParser.js';
import {
+ DAEMON_SCRIPT_PATH,
serializeArgs,
assertValidSessionId,
getSocketPath,
@@ -283,6 +286,7 @@ describe('daemon pid handling', () => {
});
afterEach(() => {
+ sinon.restore();
if (savedXdgRuntimeDir === undefined) {
delete process.env['XDG_RUNTIME_DIR'];
} else {
@@ -342,11 +346,114 @@ describe('daemon pid handling', () => {
assert.strictEqual(isDaemonRunning(SESSION_ID), false);
});
- it('returns true when the pid file points to a live process', () => {
+ it('returns true when the pid file points to a live daemon process', () => {
+ using tempDir = createTempDir('cdm-daemon-utils-test-');
+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;
+ const child = spawn(
+ process.execPath,
+ ['-e', 'setInterval(() => {}, 1000)', DAEMON_SCRIPT_PATH],
+ {stdio: 'ignore'},
+ );
+ child.unref();
+ assert.ok(child.pid);
+ try {
+ writePidFile(SESSION_ID, `${child.pid}\n`);
+ assert.strictEqual(isDaemonRunning(SESSION_ID), true);
+ } finally {
+ child.kill();
+ }
+ });
+
+ it('caches the verified process identity across repeated checks', async () => {
+ using tempDir = createTempDir('cdm-daemon-utils-test-');
+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;
+ const child = spawn(
+ process.execPath,
+ ['-e', 'setInterval(() => {}, 1000)', DAEMON_SCRIPT_PATH],
+ {stdio: 'ignore'},
+ );
+ assert.ok(child.pid);
+ try {
+ writePidFile(SESSION_ID, `${child.pid}\n`);
+ assert.strictEqual(isDaemonRunning(SESSION_ID), true);
+
+ const readFileSyncSpy = sinon.spy(fs, 'readFileSync');
+ const execFileSyncSpy = sinon.spy(childProcess, 'execFileSync');
+
+ assert.strictEqual(isDaemonRunning(SESSION_ID), true);
+ sinon.assert.calledOnceWithExactly(
+ readFileSyncSpy,
+ getPidFilePath(SESSION_ID),
+ sinon.match('utf-8'),
+ );
+ sinon.assert.notCalled(execFileSyncSpy);
+
+ child.kill();
+ await once(child, 'exit');
+ assert.strictEqual(isDaemonRunning(SESSION_ID), false);
+ } finally {
+ child.kill();
+ child.unref();
+ }
+ });
+
+ it('returns false when the pid file points to an unrelated live process', () => {
using tempDir = createTempDir('cdm-daemon-utils-test-');
process.env['XDG_RUNTIME_DIR'] = tempDir.path;
writePidFile(SESSION_ID, `${process.pid}\n`);
- assert.strictEqual(isDaemonRunning(SESSION_ID), true);
+ assert.strictEqual(isDaemonRunning(SESSION_ID), false);
+ });
+
+ it('falls back to true when command line lookup throws for a live process', () => {
+ using tempDir = createTempDir('cdm-daemon-utils-test-');
+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;
+ const child = spawn(
+ process.execPath,
+ ['-e', 'setInterval(() => {}, 1000)'],
+ {stdio: 'ignore'},
+ );
+ child.unref();
+ assert.ok(child.pid);
+ try {
+ writePidFile(SESSION_ID, `${child.pid}\n`);
+ sinon
+ .stub(fs, 'existsSync')
+ .callThrough()
+ .withArgs('/proc')
+ .returns(false);
+ sinon
+ .stub(childProcess, 'execFileSync')
+ .throws(new Error('lookup failed'));
+
+ assert.strictEqual(isDaemonRunning(SESSION_ID), true);
+ } finally {
+ child.kill();
+ }
+ });
+
+ it('falls back to true when command line lookup returns an empty string for a live process', () => {
+ using tempDir = createTempDir('cdm-daemon-utils-test-');
+ process.env['XDG_RUNTIME_DIR'] = tempDir.path;
+ const child = spawn(
+ process.execPath,
+ ['-e', 'setInterval(() => {}, 1000)'],
+ {stdio: 'ignore'},
+ );
+ child.unref();
+ assert.ok(child.pid);
+ try {
+ writePidFile(SESSION_ID, `${child.pid}\n`);
+ sinon
+ .stub(fs, 'existsSync')
+ .callThrough()
+ .withArgs('/proc')
+ .returns(false);
+ sinon.stub(childProcess, 'execFileSync').returns('\r\n');
+
+ assert.strictEqual(isDaemonRunning(SESSION_ID), true);
+ } finally {
+ child.kill();
+ }
});
it('returns false when the pid file points to a dead process', async () => {