mcp-daemon.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /**
  2. * Shared MCP daemon — issue #411.
  3. *
  4. * Validates the daemon architecture in `src/mcp/{daemon,proxy,session,index}.ts`
  5. * AFTER the review fixes:
  6. *
  7. * - The daemon is a *detached* background process; every `serve --mcp`
  8. * invocation is a thin proxy to it. Two invocations against one project
  9. * share ONE daemon.
  10. * - Concurrent launchers converge on a single daemon (the must-fix-1
  11. * lockfile-race: an empty-pidfile window used to let a racing candidate
  12. * delete the winner's lock → two daemons).
  13. * - Killing the launcher that spawned the daemon does NOT take the daemon
  14. * down — other attached clients keep working (the must-fix-2 detach: the
  15. * in-process daemon used to die with its launcher's process group and
  16. * orphan on host SIGKILL, regressing #277).
  17. * - A stale lockfile (dead pid) is cleared; `CODEGRAPH_NO_DAEMON=1` opts out;
  18. * the proxy refuses to attach across a version mismatch; the daemon
  19. * idle-times-out after the last client leaves (so a single session can't
  20. * leak a daemon forever).
  21. *
  22. * These tests intentionally spawn real `node dist/bin/codegraph.js` processes
  23. * over real sockets/pipes — the same surface a Claude Code / Cursor / Codex
  24. * install exercises. The daemon logs to `.codegraph/daemon.log` (it has no
  25. * client stderr of its own), so daemon-side assertions read that file.
  26. *
  27. * `realRoot` vs `tempDir`: processes are spawned with the (possibly symlinked)
  28. * `tempDir` as cwd/rootUri — on macOS `os.tmpdir()` lives under `/var`, a
  29. * symlink to `/private/var`, and a spawned child's `process.cwd()` is already
  30. * realpath'd. The daemon canonicalizes the root with `realpathSync`, so all
  31. * path assertions use `realRoot` (the canonical form). That this matches end to
  32. * end is itself the proof the canonicalization works.
  33. */
  34. import { afterEach, beforeEach, describe, expect, it } from 'vitest';
  35. import { ChildProcessWithoutNullStreams, spawn } from 'child_process';
  36. import * as fs from 'fs';
  37. import * as os from 'os';
  38. import * as path from 'path';
  39. import { CodeGraph } from '../src';
  40. import { getDaemonSocketPath } from '../src/mcp/daemon-paths';
  41. const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
  42. interface SpawnedServer {
  43. child: ChildProcessWithoutNullStreams;
  44. stdout: string[];
  45. stderr: string[];
  46. }
  47. function spawnServer(cwd: string, env: NodeJS.ProcessEnv = {}): SpawnedServer {
  48. const child = spawn(process.execPath, [BIN, 'serve', '--mcp'], {
  49. cwd,
  50. stdio: ['pipe', 'pipe', 'pipe'],
  51. env: { ...process.env, ...env },
  52. }) as ChildProcessWithoutNullStreams;
  53. // Swallow spawn/EPIPE errors so killing a child mid-write can't surface as an
  54. // unhandled error that crashes the vitest worker.
  55. child.on('error', () => { /* ignore */ });
  56. child.stdin.on('error', () => { /* ignore */ });
  57. const stdout: string[] = [];
  58. const stderr: string[] = [];
  59. let stdoutBuf = '';
  60. let stderrBuf = '';
  61. child.stdout.on('data', (chunk: Buffer) => {
  62. stdoutBuf += chunk.toString('utf8');
  63. let idx: number;
  64. while ((idx = stdoutBuf.indexOf('\n')) !== -1) {
  65. stdout.push(stdoutBuf.slice(0, idx));
  66. stdoutBuf = stdoutBuf.slice(idx + 1);
  67. }
  68. });
  69. child.stderr.on('data', (chunk: Buffer) => {
  70. stderrBuf += chunk.toString('utf8');
  71. let idx: number;
  72. while ((idx = stderrBuf.indexOf('\n')) !== -1) {
  73. stderr.push(stderrBuf.slice(0, idx));
  74. stderrBuf = stderrBuf.slice(idx + 1);
  75. }
  76. });
  77. return { child, stdout, stderr };
  78. }
  79. function sendMessage(child: ChildProcessWithoutNullStreams, msg: unknown): void {
  80. try { child.stdin.write(JSON.stringify(msg) + '\n'); } catch { /* child may be gone */ }
  81. }
  82. function sendInitialize(child: ChildProcessWithoutNullStreams, rootUri: string, id: number): void {
  83. sendMessage(child, {
  84. jsonrpc: '2.0',
  85. id,
  86. method: 'initialize',
  87. params: {
  88. protocolVersion: '2024-11-05',
  89. capabilities: {},
  90. clientInfo: { name: 'test', version: '0.0.0' },
  91. rootUri,
  92. },
  93. });
  94. }
  95. /** Find a JSON-RPC response with the given id (result OR error) on stdout. */
  96. function findResponse(stdout: string[], id: number): any | null {
  97. for (const line of stdout) {
  98. if (!line.trim()) continue;
  99. try {
  100. const parsed = JSON.parse(line);
  101. if (parsed && parsed.id === id && (parsed.result !== undefined || parsed.error !== undefined)) {
  102. return parsed;
  103. }
  104. } catch { /* not JSON */ }
  105. }
  106. return null;
  107. }
  108. function waitFor<T>(
  109. predicate: () => T | undefined | null | false,
  110. timeoutMs: number,
  111. pollMs = 25,
  112. ): Promise<T> {
  113. return new Promise((resolve, reject) => {
  114. const started = Date.now();
  115. const tick = () => {
  116. let v: T | undefined | null | false;
  117. try { v = predicate(); } catch (e) { return reject(e); }
  118. if (v) return resolve(v as T);
  119. if (Date.now() - started > timeoutMs) return reject(new Error(`Timed out after ${timeoutMs}ms`));
  120. setTimeout(tick, pollMs);
  121. };
  122. tick();
  123. });
  124. }
  125. function isAlive(pid: number): boolean {
  126. try { process.kill(pid, 0); return true; } catch { return false; }
  127. }
  128. function readLockPid(root: string): number | null {
  129. try {
  130. const raw = fs.readFileSync(path.join(root, '.codegraph', 'daemon.pid'), 'utf8');
  131. const info = JSON.parse(raw);
  132. return typeof info.pid === 'number' ? info.pid : null;
  133. } catch { return null; }
  134. }
  135. /** The socket path the daemon actually bound, as it recorded in its lockfile —
  136. * robust on Windows where a recomputed pipe path can differ from the daemon's. */
  137. function readLockSocketPath(root: string): string | null {
  138. try {
  139. const raw = fs.readFileSync(path.join(root, '.codegraph', 'daemon.pid'), 'utf8');
  140. const info = JSON.parse(raw);
  141. return typeof info.socketPath === 'string' ? info.socketPath : null;
  142. } catch { return null; }
  143. }
  144. function readDaemonLog(root: string): string {
  145. try { return fs.readFileSync(path.join(root, '.codegraph', 'daemon.log'), 'utf8'); }
  146. catch { return ''; }
  147. }
  148. function countListeningLines(root: string): number {
  149. return readDaemonLog(root).split('\n').filter((l) => l.includes('[CodeGraph daemon] Listening on')).length;
  150. }
  151. function killTree(...procs: ChildProcessWithoutNullStreams[]): void {
  152. for (const p of procs) {
  153. if (!p.killed) { try { p.kill('SIGKILL'); } catch { /* gone */ } }
  154. }
  155. }
  156. async function waitProcessExit(pid: number, timeoutMs: number): Promise<boolean> {
  157. return waitFor(() => !isAlive(pid), timeoutMs).then(() => true).catch(() => false);
  158. }
  159. describe('Shared MCP daemon (issue #411)', () => {
  160. let tempDir: string; // the (possibly symlinked) path processes are spawned with
  161. let realRoot: string; // its canonical form — what the daemon keys paths on
  162. const servers: SpawnedServer[] = [];
  163. beforeEach(async () => {
  164. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-daemon-'));
  165. const cg = await CodeGraph.init(tempDir);
  166. cg.close();
  167. realRoot = fs.realpathSync(tempDir);
  168. });
  169. afterEach(async () => {
  170. killTree(...servers.map((s) => s.child));
  171. // The daemon is detached (not a tracked child) — reap it explicitly via the
  172. // pid it recorded, so a test can't leak a background daemon. Guard against
  173. // our own pid: the version-mismatch test plants `pid: process.pid` in the
  174. // lockfile, and we must never SIGKILL the vitest worker.
  175. const daemonPid = readLockPid(realRoot);
  176. if (daemonPid && daemonPid !== process.pid && isAlive(daemonPid)) {
  177. try { process.kill(daemonPid, 'SIGKILL'); } catch { /* race */ }
  178. }
  179. await new Promise((r) => setTimeout(r, 50));
  180. servers.length = 0;
  181. fs.rmSync(tempDir, { recursive: true, force: true });
  182. });
  183. it('two invocations share ONE detached daemon; both attach as proxies', async () => {
  184. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' };
  185. const first = spawnServer(tempDir, env);
  186. servers.push(first);
  187. sendInitialize(first.child, `file://${tempDir}`, 1);
  188. const firstResp = await waitFor(() => findResponse(first.stdout, 1), 10000);
  189. expect(firstResp.result.serverInfo.name).toBe('codegraph');
  190. // The launcher is a PROXY (not the daemon itself) — that's the detach fix.
  191. await waitFor(() => first.stderr.some((l) => l.includes('Attached to shared daemon')), 8000);
  192. // A detached daemon came up and recorded itself.
  193. await waitFor(() => fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid')), 8000);
  194. await waitFor(() => countListeningLines(realRoot) >= 1, 8000);
  195. const daemonPid = readLockPid(realRoot);
  196. expect(daemonPid).toBeTruthy();
  197. expect(isAlive(daemonPid!)).toBe(true);
  198. // The socket exists at the path the code computes from the canonical root.
  199. // On Windows the daemon listens on a named pipe (\\.\pipe\...), which isn't
  200. // a filesystem entry — existsSync doesn't apply there, and the "Attached to
  201. // shared daemon" proof above already confirms the proxy reached it.
  202. if (process.platform !== 'win32') {
  203. expect(fs.existsSync(getDaemonSocketPath(realRoot))).toBe(true);
  204. }
  205. // Second invocation attaches as a proxy to the SAME daemon.
  206. const second = spawnServer(tempDir, env);
  207. servers.push(second);
  208. sendInitialize(second.child, `file://${tempDir}`, 2);
  209. const secondResp = await waitFor(() => findResponse(second.stdout, 2), 10000);
  210. expect(secondResp.result.serverInfo.name).toBe('codegraph');
  211. await waitFor(() => second.stderr.some((l) => l.includes('Attached to shared daemon')), 8000);
  212. // Exactly one daemon ever bound, and it's the same pid both attached to.
  213. expect(countListeningLines(realRoot)).toBe(1);
  214. expect(readLockPid(realRoot)).toBe(daemonPid);
  215. }, 40000);
  216. it('concurrent launchers converge on a single daemon (lockfile race — must-fix 1)', async () => {
  217. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' };
  218. // Fire three launchers as close to simultaneously as possible — this is the
  219. // race window where the old code could end up with two daemons.
  220. const procs = [spawnServer(tempDir, env), spawnServer(tempDir, env), spawnServer(tempDir, env)];
  221. procs.forEach((p, i) => { servers.push(p); sendInitialize(p.child, `file://${tempDir}`, i + 1); });
  222. // All three get a valid initialize response...
  223. for (let i = 0; i < procs.length; i++) {
  224. const resp = await waitFor(() => findResponse(procs[i].stdout, i + 1), 12000);
  225. expect(resp.result.serverInfo.name).toBe('codegraph');
  226. }
  227. // ...and all three attached as proxies (none fell back / wedged).
  228. for (const p of procs) {
  229. await waitFor(() => p.stderr.some((l) => l.includes('Attached to shared daemon')), 10000);
  230. }
  231. // The decisive assertion: exactly ONE daemon bound the socket. Losing
  232. // candidates log "already holds the lock; exiting" and never listen.
  233. expect(countListeningLines(realRoot)).toBe(1);
  234. const daemonPid = readLockPid(realRoot);
  235. expect(daemonPid).toBeTruthy();
  236. expect(isAlive(daemonPid!)).toBe(true);
  237. }, 45000);
  238. it('daemon survives the first client dying; a second client keeps working (must-fix 2 / #277)', async () => {
  239. // Idle high so the daemon doesn't reap mid-test; poll fast so proxy 1
  240. // notices its dead parent quickly.
  241. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '30000', CODEGRAPH_PPID_POLL_MS: '200' };
  242. const first = spawnServer(tempDir, env);
  243. servers.push(first);
  244. sendInitialize(first.child, `file://${tempDir}`, 1);
  245. await waitFor(() => findResponse(first.stdout, 1), 10000);
  246. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  247. const daemonPid = readLockPid(realRoot)!;
  248. expect(isAlive(daemonPid)).toBe(true);
  249. const second = spawnServer(tempDir, env);
  250. servers.push(second);
  251. sendInitialize(second.child, `file://${tempDir}`, 1);
  252. await waitFor(() => findResponse(second.stdout, 1), 10000);
  253. await waitFor(() => second.stderr.some((l) => l.includes('Attached to shared daemon')), 8000);
  254. // Kill the launcher that spawned the daemon. With the old in-process design
  255. // this would take the daemon (and thus the second client) down.
  256. killTree(first.child);
  257. // The daemon is detached — it must still be alive a beat later.
  258. await new Promise((r) => setTimeout(r, 1500));
  259. expect(isAlive(daemonPid)).toBe(true);
  260. // And the second client can still drive a real tool call through it.
  261. sendMessage(second.child, { jsonrpc: '2.0', id: 2, method: 'tools/list' });
  262. const toolsResp = await waitFor(() => findResponse(second.stdout, 2), 10000);
  263. expect(Array.isArray(toolsResp.result.tools)).toBe(true);
  264. expect(toolsResp.result.tools.length).toBeGreaterThan(0);
  265. }, 45000);
  266. it('CODEGRAPH_NO_DAEMON=1 keeps each process independent (no socket/pidfile)', async () => {
  267. const env = { CODEGRAPH_NO_DAEMON: '1' };
  268. const first = spawnServer(tempDir, env);
  269. servers.push(first);
  270. sendInitialize(first.child, `file://${tempDir}`, 1);
  271. await waitFor(() => findResponse(first.stdout, 1), 10000);
  272. // Direct mode — no daemon machinery touched.
  273. expect(first.stderr.some((l) => l.includes('Attached to shared daemon'))).toBe(false);
  274. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid'))).toBe(false);
  275. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.log'))).toBe(false);
  276. }, 20000);
  277. it('clears a stale (dead-pid) lockfile and a fresh daemon takes over', async () => {
  278. // Plant a lockfile pointing at a definitely-dead pid + the real socket path.
  279. fs.writeFileSync(
  280. path.join(realRoot, '.codegraph', 'daemon.pid'),
  281. JSON.stringify({
  282. pid: 999_999,
  283. version: '0.0.0-fake',
  284. socketPath: getDaemonSocketPath(realRoot),
  285. startedAt: Date.now() - 1000,
  286. }),
  287. );
  288. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' };
  289. const server = spawnServer(tempDir, env);
  290. servers.push(server);
  291. sendInitialize(server.child, `file://${tempDir}`, 1);
  292. const resp = await waitFor(() => findResponse(server.stdout, 1), 10000).catch((e) => {
  293. throw new Error(`${(e as Error).message}\nstderr:\n${server.stderr.join('\n')}\ndaemon.log:\n${readDaemonLog(realRoot)}`);
  294. });
  295. expect(resp.result.serverInfo.name).toBe('codegraph');
  296. await waitFor(() => countListeningLines(realRoot) >= 1, 10000);
  297. // The pidfile now names a live daemon, not the planted-dead 999999.
  298. const livePid = readLockPid(realRoot);
  299. expect(livePid).not.toBe(999_999);
  300. expect(isAlive(livePid!)).toBe(true);
  301. }, 40000);
  302. it('proxy falls back to direct mode on a daemon version mismatch', async () => {
  303. const net = await import('net');
  304. const sockPath = getDaemonSocketPath(realRoot);
  305. // Plant a live-pid lockfile so the launcher treats the lock as held, and a
  306. // mini-server that answers with a mismatched-version hello.
  307. fs.writeFileSync(
  308. path.join(realRoot, '.codegraph', 'daemon.pid'),
  309. JSON.stringify({ pid: process.pid, version: '0.0.0-mismatch', socketPath: sockPath, startedAt: Date.now() }),
  310. );
  311. const miniServer = net.createServer((sock) => {
  312. sock.write(JSON.stringify({ codegraph: '0.0.0-mismatch', pid: 1, socketPath: sockPath, protocol: 1 }) + '\n');
  313. });
  314. await new Promise<void>((resolve) => miniServer.listen(sockPath, () => resolve()));
  315. try {
  316. const server = spawnServer(tempDir);
  317. servers.push(server);
  318. sendInitialize(server.child, `file://${tempDir}`, 1);
  319. // Despite the mismatched daemon, the client still gets an initialize
  320. // response — the proxy answers the handshake locally and, refusing to
  321. // attach across the version mismatch, serves the session in-process.
  322. const resp = await waitFor(() => findResponse(server.stdout, 1), 10000);
  323. expect(resp.result.serverInfo.name).toBe('codegraph');
  324. await waitFor(
  325. () => server.stderr.some((l) => l.includes('serving this session in-process')),
  326. 6000,
  327. );
  328. } finally {
  329. await new Promise<void>((resolve) => miniServer.close(() => resolve()));
  330. }
  331. }, 30000);
  332. it('reaps a client whose process died without the socket closing (liveness sweep, #692)', async () => {
  333. const net = await import('net');
  334. // Bring a daemon up via a real proxy (a live client), sweep fast.
  335. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '30000', CODEGRAPH_DAEMON_CLIENT_SWEEP_MS: '300' };
  336. const server = spawnServer(tempDir, env);
  337. servers.push(server);
  338. sendInitialize(server.child, `file://${tempDir}`, 1);
  339. await waitFor(() => findResponse(server.stdout, 1), 10000);
  340. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  341. // Connect a RAW client that announces a dead pid and then never closes its
  342. // socket — the exact phantom-client shape the sweep exists to catch. Use the
  343. // socket path the daemon recorded in its lockfile (robust on Windows, where
  344. // a recomputed named-pipe path can differ from the one the daemon bound).
  345. const sockPath = await waitFor(() => readLockSocketPath(realRoot), 8000);
  346. const raw = net.createConnection(sockPath);
  347. raw.on('error', () => { /* ignore — we destroy it ourselves */ });
  348. try {
  349. // Consume the daemon hello (one line), then send our client-hello.
  350. // Generous timeouts: the unref'd sweep interval can stretch under a busy
  351. // event loop (engine init / a loaded CI box), so don't race it tight.
  352. await new Promise<void>((resolve, reject) => {
  353. let buf = '';
  354. const to = setTimeout(() => reject(new Error('no daemon hello within 15s')), 15000);
  355. raw.on('data', (c: Buffer) => {
  356. buf += c.toString('utf8');
  357. if (buf.includes('\n')) { clearTimeout(to); resolve(); }
  358. });
  359. });
  360. raw.write(JSON.stringify({ codegraph_client: 1, pid: 999_999, hostPid: null }) + '\n');
  361. // The sweep should detect pid 999999 is dead and reap that client.
  362. await waitFor(
  363. () => readDaemonLog(realRoot).includes('Reaping client with dead peer (pid 999999'),
  364. 15000,
  365. );
  366. } finally {
  367. raw.destroy();
  368. }
  369. }, 60000);
  370. it('exits on the inactivity backstop even while a client stays connected (#692)', async () => {
  371. // Backstop short, idle timeout long: with a client connected the idle timer
  372. // never arms, so only the inactivity backstop can take the daemon down.
  373. const env = { CODEGRAPH_DAEMON_MAX_IDLE_MS: '1500', CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '60000' };
  374. const server = spawnServer(tempDir, env);
  375. servers.push(server);
  376. sendInitialize(server.child, `file://${tempDir}`, 1);
  377. await waitFor(() => findResponse(server.stdout, 1), 10000);
  378. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  379. const daemonPid = readLockPid(realRoot)!;
  380. expect(isAlive(daemonPid)).toBe(true);
  381. // Send nothing further — the client stays connected but idle. The backstop
  382. // should fire and the daemon should exit and clean up its lockfile.
  383. expect(await waitProcessExit(daemonPid, 12000)).toBe(true);
  384. expect(readDaemonLog(realRoot)).toContain('inactivity backstop');
  385. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid'))).toBe(false);
  386. }, 30000);
  387. it('daemon idle-times-out after the last client disconnects', async () => {
  388. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '800', CODEGRAPH_PPID_POLL_MS: '200' };
  389. const server = spawnServer(tempDir, env);
  390. servers.push(server);
  391. sendInitialize(server.child, `file://${tempDir}`, 1);
  392. await waitFor(() => findResponse(server.stdout, 1), 10000);
  393. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  394. const daemonPid = readLockPid(realRoot)!;
  395. // Close the only client's stdin → proxy exits → daemon refcount hits 0 →
  396. // idle timer fires → daemon exits and cleans up its lockfile.
  397. server.child.stdin.end();
  398. expect(await waitProcessExit(daemonPid, 10000)).toBe(true);
  399. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid'))).toBe(false);
  400. }, 30000);
  401. });