Chrome DevTools for coding agents
feat(config): add ConfigWatcher to watch config file changes (#3139)
Nikolay Vitkov9171f77c4da6
diff --git a/src/config/ConfigParser.ts b/src/config/ConfigParser.tsindex a4381ba3..cea2ed1c 100644--- a/src/config/ConfigParser.ts+++ b/src/config/ConfigParser.ts@@ -21,16 +21,13 @@ import {isReloadableOption,withoutDefaults,} from './mcp-options.js';+import {getErrorMessage} from '../utils/errorHandling.js';import {ConfigLocator} from './ConfigLocator.js';function isPlainObject(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);}-function getErrorMessage(err: unknown): string {- return err instanceof Error ? err.message : String(err);-}-function stripYargsPositionalArgs<T extends {_?: unknown; $0?: unknown}>(parsed: T,): Omit<T, '_' | '$0'> {diff --git a/src/config/ConfigWatcher.ts b/src/config/ConfigWatcher.tsnew file mode 100644index 00000000..9f234f6b--- /dev/null+++ b/src/config/ConfigWatcher.ts@@ -0,0 +1,110 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import fs from 'node:fs';+import path from 'node:path';++import {DevTools} from '../third_party/index.js';+import {getErrorMessage} from '../utils/errorHandling.js';+import {logger} from '../utils/logger.js';++const DEFAULT_DEBOUNCE_MS = 200;++/**+ * Returns undefined if the file cannot be read, for example while it is being+ * replaced.+ */+function readContent(filePath: string): string | undefined {+ try {+ return fs.readFileSync(filePath, 'utf8');+ } catch {+ return undefined;+ }+}++/**+ * Watches a config file and calls `onChange` after it was modified.+ *+ * - Symlinks are resolved once on start, and the directory of the real file is+ * watched. Watching the directory instead of the file keeps working when+ * editors save atomically by replacing the file.+ * - Events are debounced because some platforms emit several events for a+ * single change.+ * - Some platforms do not report the file name, such events are not filtered.+ * - `onChange` is only called if the content changed. For example, macOS can+ * report events that happened shortly before the watcher was started.+ */+export class ConfigWatcher implements Disposable {+ readonly #configPath: string;+ readonly #onChange: () => Promise<void>;+ readonly #debounceMs: number;+ #watcher?: fs.FSWatcher;+ #debounced?: ReturnType<typeof DevTools.Common.Debouncer.debounce>;+ #content?: string;+ #pending = Promise.resolve();++ constructor(+ configPath: string,+ onChange: () => Promise<void>,+ options: {debounceMs?: number} = {},+ ) {+ this.#configPath = configPath;+ this.#onChange = onChange;+ this.#debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;+ }++ /**+ * Starts watching the config file. Throws if `configPath` does not exist.+ */+ start(): void {+ if (this.#watcher) {+ return;+ }+ const realPath = fs.realpathSync(this.#configPath);+ const fileName = path.basename(realPath);+ this.#content = readContent(realPath);+ this.#debounced = DevTools.Common.Debouncer.debounce(() => {+ const content = readContent(realPath);+ if (content === undefined || content === this.#content) {+ return;+ }+ this.#content = content;+ this.#pending = this.#pending+ .then(() => this.#onChange())+ .catch(err => {+ console.error(`Failed to apply ${this.#configPath}:`, err);+ });+ }, this.#debounceMs);+ this.#watcher = fs.watch(+ path.dirname(realPath),+ {persistent: false},+ (_eventType, changedFileName) => {+ if (changedFileName !== null && changedFileName !== fileName) {+ return;+ }+ this.#debounced?.();+ },+ );+ this.#watcher.on('error', err => {+ console.error(+ `Stopped watching ${this.#configPath}: ${getErrorMessage(err)}`,+ );+ this.dispose();+ });+ logger?.(`Watching ${realPath} for config changes`);+ }++ dispose(): void {+ this.#debounced?.cancel();+ this.#debounced = undefined;+ this.#watcher?.close();+ this.#watcher = undefined;+ }++ [Symbol.dispose](): void {+ this.dispose();+ }+}diff --git a/src/utils/errorHandling.ts b/src/utils/errorHandling.tsindex cc697a81..a3e6734d 100644--- a/src/utils/errorHandling.ts+++ b/src/utils/errorHandling.ts@@ -7,6 +7,10 @@import process from 'node:process';import {logger} from './logger.js';+export function getErrorMessage(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}+export function setupUnhandledRejectionHandler(onCrash: () => void): void {process.on('unhandledRejection', (reason, promise) => {logger?.('Unhandled promise rejection:', promise, reason);diff --git a/tests/config/ConfigWatcher.test.ts b/tests/config/ConfigWatcher.test.tsnew file mode 100644index 00000000..2c750b9e--- /dev/null+++ b/tests/config/ConfigWatcher.test.ts@@ -0,0 +1,190 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import fs from 'node:fs';+import path from 'node:path';+import {afterEach, describe, it} from 'node:test';++import sinon from 'sinon';++import {ConfigWatcher} from '../../src/config/ConfigWatcher.js';+import {createTempDir} from '../utils.js';++const DEBOUNCE_MS = 50;+// Long enough for fs events to be delivered and the debounce to fire.+const SETTLE_MS = 500;+const POLL_TIMEOUT_MS = 5000;+const POLL_INTERVAL_MS = 20;++function wait(ms: number): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms));+}++async function waitForCall(stub: sinon.SinonStub): Promise<void> {+ const deadline = Date.now() + POLL_TIMEOUT_MS;+ while (!stub.called) {+ if (Date.now() >= deadline) {+ throw new Error('Timed out waiting for stub to be called');+ }+ await wait(POLL_INTERVAL_MS);+ }+}++function writeConfig(dir: string): string {+ const configPath = path.join(dir, 'cd4a.config.json');+ fs.writeFileSync(configPath, '{}');+ return configPath;+}++function startWatcher(+ watchedPath: string,+ onChange: () => Promise<void> = sinon.stub().resolves(),+): ConfigWatcher {+ const watcher = new ConfigWatcher(watchedPath, onChange, {+ debounceMs: DEBOUNCE_MS,+ });+ watcher.start();+ return watcher;+}++describe('ConfigWatcher', () => {+ afterEach(() => {+ sinon.restore();+ });++ it('calls onChange once for several quick writes', async () => {+ using dir = createTempDir('cd4a-watcher-');+ const configPath = writeConfig(dir.path);+ const onChange = sinon.stub().resolves();+ using watcher = startWatcher(configPath, onChange);++ fs.writeFileSync(configPath, '{"headless": true}');+ fs.writeFileSync(configPath, '{"headless": false}');+ await waitForCall(onChange);++ sinon.assert.calledOnceWithExactly(onChange);+ });++ it('detects atomic replacements', async () => {+ using dir = createTempDir('cd4a-watcher-');+ const configPath = writeConfig(dir.path);+ const onChange = sinon.stub().resolves();+ using watcher = startWatcher(configPath, onChange);++ const tempPath = path.join(dir.path, 'cd4a.config.json.tmp');+ fs.writeFileSync(tempPath, '{"headless": true}');+ fs.renameSync(tempPath, configPath);+ await waitForCall(onChange);++ sinon.assert.calledOnceWithExactly(onChange);+ });++ it('ignores other files in the directory', async () => {+ using dir = createTempDir('cd4a-watcher-');+ const configPath = writeConfig(dir.path);+ const onChange = sinon.stub().resolves();+ using watcher = startWatcher(configPath, onChange);++ fs.writeFileSync(path.join(dir.path, 'other.json'), '{}');+ await wait(SETTLE_MS);++ sinon.assert.notCalled(onChange);+ });++ it('follows symlinks to the real config file', async () => {+ using dir = createTempDir('cd4a-watcher-');+ using linkDir = createTempDir('cd4a-link-');+ const configPath = writeConfig(dir.path);+ const linkPath = path.join(linkDir.path, 'cd4a.config.json');+ fs.symlinkSync(configPath, linkPath);+ const onChange = sinon.stub().resolves();+ using watcher = startWatcher(linkPath, onChange);++ fs.writeFileSync(configPath, '{"headless": true}');+ await waitForCall(onChange);++ sinon.assert.calledOnceWithExactly(onChange);+ });++ it('does not call onChange if the content did not change', async () => {+ using dir = createTempDir('cd4a-watcher-');+ const configPath = writeConfig(dir.path);+ const onChange = sinon.stub().resolves();+ using watcher = startWatcher(configPath, onChange);++ fs.writeFileSync(configPath, '{}');+ await wait(SETTLE_MS);++ sinon.assert.notCalled(onChange);+ });++ it('does not call onChange when the config file cannot be read', async () => {+ using dir = createTempDir('cd4a-watcher-');+ const configPath = writeConfig(dir.path);+ const onChange = sinon.stub().resolves();+ using watcher = startWatcher(configPath, onChange);++ fs.unlinkSync(configPath);+ await wait(SETTLE_MS);++ sinon.assert.notCalled(onChange);+ });++ it('stops calling onChange after dispose', async () => {+ using dir = createTempDir('cd4a-watcher-');+ const configPath = writeConfig(dir.path);+ const onChange = sinon.stub().resolves();+ const watcher = startWatcher(configPath, onChange);++ watcher.dispose();+ fs.writeFileSync(configPath, '{"headless": true}');+ await wait(SETTLE_MS);++ sinon.assert.notCalled(onChange);+ });++ it('logs errors from onChange', async () => {+ using dir = createTempDir('cd4a-watcher-');+ const configPath = writeConfig(dir.path);+ const consoleError = sinon.stub(console, 'error');+ const error = new Error('apply failed');+ using watcher = startWatcher(configPath, sinon.stub().rejects(error));++ fs.writeFileSync(configPath, '{"headless": true}');+ await waitForCall(consoleError);++ sinon.assert.calledOnceWithExactly(+ consoleError,+ `Failed to apply ${configPath}:`,+ error,+ );+ });++ it('serializes overlapping onChange calls', async () => {+ using dir = createTempDir('cd4a-watcher-');+ const configPath = writeConfig(dir.path);+ const firstCall = Promise.withResolvers<void>();+ const secondCall = Promise.withResolvers<void>();+ const onChange = sinon.stub();+ onChange.onFirstCall().returns(firstCall.promise);+ onChange.onSecondCall().callsFake(async () => {+ secondCall.resolve();+ });+ using watcher = startWatcher(configPath, onChange);++ fs.writeFileSync(configPath, '{"headless": true}');+ await waitForCall(onChange);+ sinon.assert.calledOnce(onChange);++ fs.writeFileSync(configPath, '{"headless": false}');+ await wait(SETTLE_MS);+ sinon.assert.calledOnce(onChange);++ firstCall.resolve();+ await secondCall.promise;+ sinon.assert.calledTwice(onChange);+ });+});diff --git a/tests/utils/errorHandling.test.ts b/tests/utils/errorHandling.test.tsindex 4d88fa76..d02bea3a 100644--- a/tests/utils/errorHandling.test.ts+++ b/tests/utils/errorHandling.test.ts@@ -8,7 +8,20 @@ import assert from 'node:assert';import process from 'node:process';import {afterEach, beforeEach, describe, it, mock} from 'node:test';-import {setupUnhandledRejectionHandler} from '../../src/utils/errorHandling.js';+import {+ getErrorMessage,+ setupUnhandledRejectionHandler,+} from '../../src/utils/errorHandling.js';++describe('getErrorMessage', () => {+ it('returns the message for Error instances', () => {+ assert.strictEqual(getErrorMessage(new Error('boom')), 'boom');+ });++ it('converts non-Error values to strings', () => {+ assert.strictEqual(getErrorMessage('string error'), 'string error');+ });+});describe('setupUnhandledRejectionHandler', () => {let originalEnvValue: string | undefined;