import { describe, expect, test, vi } from 'vitest' import { NodeContextHost, spawnHostedContext } from '../src/node-host.js' describe('ContextHost lifecycle', () => { test('rejects a concurrent duplicate before spawning another child', async () => { const host = new NodeContextHost() const params = { key: 'shared', command: process.execPath, args: ['-e', 'setTimeout(() => {}, 200)'], } const first = host.addLocalContext(params) const second = host.addLocalContext(params) let rejected = false void second.catch(() => { rejected = true }) await Promise.resolve() expect(rejected).toBe(true) await first await host.dispose() }) test('old child exit cannot remove a replacement with the same key', async () => { const host = new NodeContextHost() await host.addLocalContext({ key: 'shared', command: process.execPath, args: ['-e', "process.on('SIGTERM', () => {}); setTimeout(() => process.exit(0), 500)"], }) await new Promise((resolve) => setTimeout(resolve, 200)) const oldRemoval = host.remove('shared') const replacement = await host.addLocalContext({ key: 'shared', command: process.execPath, args: ['-e', 'setInterval(() => {}, 1e9)'], }) await oldRemoval await new Promise((resolve) => setTimeout(resolve, 20)) expect(host.getContext('shared').client).toBe(replacement) await host.dispose() }) test('reaps a context and emits context:failed when its child exits non-zero, with no unhandled rejection', async () => { const unhandled: Array = [] const onUnhandled = (reason: unknown) => unhandled.push(reason) process.on('unhandledRejection', onUnhandled) const host = new NodeContextHost() const failures: Array<{ key: string; error: Error }> = [] host.events.on('context:failed', (data) => { failures.push(data) }) await host.addLocalContext({ key: 'boom', command: process.execPath, args: ['-e', 'process.exit(1)'], }) await vi.waitFor(() => { expect(failures).toHaveLength(1) }) expect(failures[0]?.key).toBe('boom') expect(host.getContextKeys()).not.toContain('boom') // Give any stray rejection a tick to surface. await new Promise((resolve) => setTimeout(resolve, 50)) process.off('unhandledRejection', onUnhandled) expect(unhandled).toHaveLength(0) await host.dispose() }) test('emits context:added and context:removed without context:failed on a clean removal', async () => { const host = new NodeContextHost() const added: Array = [] const removed: Array = [] let failed = 0 host.events.on('context:added', ({ key }) => { added.push(key) }) host.events.on('context:removed', ({ key }) => { removed.push(key) }) host.events.on('context:failed', () => { failed += 1 }) await host.addLocalContext({ key: 'alive', command: process.execPath, args: ['-e', 'setInterval(() => {}, 1e9)'], }) expect(added).toContain('alive') await host.remove('alive') expect(removed).toContain('alive') // Killing our own child (SIGTERM) must not be reported as a failure. await new Promise((resolve) => setTimeout(resolve, 50)) expect(failed).toBe(0) await host.dispose() }) }) describe('ContextHost.setup race', () => { test('throws a clear error if the context is removed during listTools', async () => { const host = new NodeContextHost() await host.addLocalContext({ key: 'racy', command: process.execPath, // Minimal server that responds to initialize + tools/list slowly enough // for the remove below to land first is hard to time deterministically; // instead drive the race directly by removing mid-setup. args: ['-e', 'setInterval(() => {}, 1e9)'], }) // Start setup, then remove before it can assign tools. const setupPromise = host.setup({ key: 'racy' }).catch((err: Error) => err) await host.remove('racy') const result = await setupPromise if (result instanceof Error) { expect(result.message).toContain('was removed during setup') } // Either it raced and threw the clear error, or it finished before remove -- // in both cases there must be no leftover context and no TypeError. expect(host.getContextKeys()).not.toContain('racy') await host.dispose() }) }) describe('spawnHostedContext dispose escalation', () => { test('escalates to SIGKILL when the child ignores SIGTERM, and awaits real exit', async () => { // Child traps SIGTERM and never exits on its own. const ctx = await spawnHostedContext({ command: process.execPath, args: ['-e', "process.on('SIGTERM', () => {}); setInterval(() => {}, 1e9)"], killTimeout: 300, }) // Give the child process time to finish V8 startup and register its // SIGTERM handler before we dispose. On a fast machine the 'spawn' event // fires before the child script has run, so without this wait SIGTERM // would arrive before process.on('SIGTERM', …) executes and the default // handler would terminate the child immediately. await new Promise((resolve) => setTimeout(resolve, 200)) const start = Date.now() await ctx.disposer.dispose() const elapsed = Date.now() - start // dispose must have waited for the kill deadline, then SIGKILLed and // awaited the real exit -- i.e. it did not resolve immediately. expect(elapsed).toBeGreaterThanOrEqual(250) }) test('exits on SIGTERM without escalating for a well-behaved child', async () => { const ctx = await spawnHostedContext({ command: process.execPath, args: ['-e', 'setInterval(() => {}, 1e9)'], killTimeout: 2000, }) const start = Date.now() await ctx.disposer.dispose() // Resolves well before the 2s deadline because SIGTERM is honoured. expect(Date.now() - start).toBeLessThan(1500) }) })