fix(server): let the CLI server exit on Ctrl+C and SIGTERM (UF-041)
The OAuth routes started a module-level cleanup interval that was never cleared or unref'd. The service's SIGTERM/SIGINT handler closes the server and relies on the event loop going empty, so the process kept running: a first Ctrl+C in `npx waggle` or `npm run dev:server` left it alive, and SIGTERM never ended it. The interval is now unref'd. The launcher tests left two `waggle` processes behind on every run: they stopped `npx` but not the waggle process it started. They now start it in its own process group and stop the whole group, with a SIGKILL fallback, and a new test checks that the built CLI exits by itself after SIGTERM.
This commit is contained in:
@@ -91,6 +91,9 @@ function spawnInCwd(
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
shell: process.platform === 'win32' && command.endsWith('.cmd'),
|
||||
// POSIX: a process group of its own, so stopProcess can stop npx together
|
||||
// with the waggle process it starts.
|
||||
detached: process.platform !== 'win32',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -200,25 +203,65 @@ async function waitForHealth(url: string, timeoutMs: number): Promise<Record<str
|
||||
return await res.json() as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function processGroupAlive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(-pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function stopProcess(child: ChildProcessWithoutNullStreams): Promise<void> {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
if (!child.pid) return;
|
||||
|
||||
if (process.platform === 'win32' && child.pid) {
|
||||
if (process.platform === 'win32') {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
|
||||
} else {
|
||||
child.kill('SIGTERM');
|
||||
await Promise.race([
|
||||
new Promise<void>((resolve) => child.once('exit', () => resolve())),
|
||||
new Promise<void>((resolve) => setTimeout(resolve, 5_000)),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.race([
|
||||
new Promise<void>((resolve) => child.once('exit', () => resolve())),
|
||||
new Promise<void>((resolve) => setTimeout(resolve, 5_000)),
|
||||
]);
|
||||
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill('SIGKILL');
|
||||
// npx can exit before the waggle process it started, so signal and wait for
|
||||
// the whole group rather than the direct child alone.
|
||||
const group = child.pid;
|
||||
const signalGroup = (signal: NodeJS.Signals): void => {
|
||||
try { process.kill(-group, signal); } catch { /* the group is already gone */ }
|
||||
};
|
||||
if (!processGroupAlive(group)) return;
|
||||
signalGroup('SIGTERM');
|
||||
try {
|
||||
await waitFor(() => !processGroupAlive(group), 10_000);
|
||||
} catch {
|
||||
signalGroup('SIGKILL');
|
||||
await waitFor(() => !processGroupAlive(group), 5_000);
|
||||
}
|
||||
}
|
||||
|
||||
async function providerFreeEnv(): Promise<NodeJS.ProcessEnv> {
|
||||
return {
|
||||
EMBEDDING_PROVIDER: 'mock',
|
||||
ANTHROPIC_API_KEY: '',
|
||||
OPENAI_API_KEY: '',
|
||||
GEMINI_API_KEY: '',
|
||||
GOOGLE_API_KEY: '',
|
||||
XAI_API_KEY: '',
|
||||
DEEPSEEK_API_KEY: '',
|
||||
MISTRAL_API_KEY: '',
|
||||
DASHSCOPE_API_KEY: '',
|
||||
MINIMAX_API_KEY: '',
|
||||
ZHIPU_API_KEY: '',
|
||||
MOONSHOT_API_KEY: '',
|
||||
PERPLEXITY_API_KEY: '',
|
||||
OPENROUTER_API_KEY: '',
|
||||
OLLAMA_HOST: `http://127.0.0.1:${await freePort()}`,
|
||||
VLLM_HOST: `http://127.0.0.1:${await freePort()}`,
|
||||
};
|
||||
}
|
||||
|
||||
describe('Waggle CLI Launcher', () => {
|
||||
describe('argument parsing', () => {
|
||||
it('uses default port 3333 when no arguments', () => {
|
||||
@@ -408,6 +451,40 @@ describe('Waggle CLI Launcher', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Windows has no SIGTERM: Node terminates the process outright there.
|
||||
it.skipIf(process.platform === 'win32')('exits on its own after SIGTERM once the service is ready (UF-041)', async () => {
|
||||
const home = makeHome();
|
||||
let child: ChildProcessWithoutNullStreams | undefined;
|
||||
try {
|
||||
const build = await run(bin('npm'), ['run', 'build', '--workspace', '@waggle-ai/waggle'], home);
|
||||
expect(build.status).toBe(0);
|
||||
|
||||
let output = '';
|
||||
child = spawnInCwd(
|
||||
process.execPath,
|
||||
[path.join(LAUNCHER_DIR, 'dist', 'cli.js'), '--port', String(await freePort()), '--skip-litellm', '--no-open'],
|
||||
ROOT,
|
||||
home,
|
||||
{ WAGGLE_DATA_DIR: path.join(home, 'data'), ...await providerFreeEnv() },
|
||||
);
|
||||
child.stdout.setEncoding('utf8');
|
||||
child.stderr.setEncoding('utf8');
|
||||
child.stdout.on('data', (chunk) => { output += chunk; });
|
||||
child.stderr.on('data', (chunk) => { output += chunk; });
|
||||
const exited = new Promise<void>((resolve) => child!.once('exit', () => resolve()));
|
||||
|
||||
await waitFor(() => output.includes('Press Ctrl+C to stop') || child!.exitCode !== null, 90_000);
|
||||
expect(output).toContain('Press Ctrl+C to stop');
|
||||
|
||||
child.kill('SIGTERM');
|
||||
await Promise.race([exited, new Promise<void>((resolve) => setTimeout(resolve, 10_000))]);
|
||||
expect({ exitCode: child.exitCode, signalCode: child.signalCode }).toEqual({ exitCode: 0, signalCode: null });
|
||||
} finally {
|
||||
if (child) await stopProcess(child);
|
||||
fs.rmSync(home, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
it('packs a tarball with a runnable first command', async () => {
|
||||
const home = makeHome();
|
||||
try {
|
||||
@@ -579,26 +656,7 @@ describe('Waggle CLI Launcher', () => {
|
||||
const readyFile = path.join(home, 'desktop-ready.json');
|
||||
const restartReadyFile = path.join(home, 'desktop-ready-restart.json');
|
||||
const desktopBootstrapToken = 'launcher-desktop-bootstrap-token-1234567890';
|
||||
const unreachableOllamaPort = await freePort();
|
||||
const unreachableVllmPort = await freePort();
|
||||
const providerFreeEnv = {
|
||||
EMBEDDING_PROVIDER: 'mock',
|
||||
ANTHROPIC_API_KEY: '',
|
||||
OPENAI_API_KEY: '',
|
||||
GEMINI_API_KEY: '',
|
||||
GOOGLE_API_KEY: '',
|
||||
XAI_API_KEY: '',
|
||||
DEEPSEEK_API_KEY: '',
|
||||
MISTRAL_API_KEY: '',
|
||||
DASHSCOPE_API_KEY: '',
|
||||
MINIMAX_API_KEY: '',
|
||||
ZHIPU_API_KEY: '',
|
||||
MOONSHOT_API_KEY: '',
|
||||
PERPLEXITY_API_KEY: '',
|
||||
OPENROUTER_API_KEY: '',
|
||||
OLLAMA_HOST: `http://127.0.0.1:${unreachableOllamaPort}`,
|
||||
VLLM_HOST: `http://127.0.0.1:${unreachableVllmPort}`,
|
||||
};
|
||||
const providerEnv = await providerFreeEnv();
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
child = spawnInCwd(
|
||||
@@ -612,7 +670,7 @@ describe('Waggle CLI Launcher', () => {
|
||||
WAGGLE_INSTANCE_ID: 'launcher-fallback-health',
|
||||
WAGGLE_DESKTOP_BOOTSTRAP_TOKEN: desktopBootstrapToken,
|
||||
WAGGLE_READY_FILE: readyFile,
|
||||
...providerFreeEnv,
|
||||
...providerEnv,
|
||||
},
|
||||
);
|
||||
child.stdout.setEncoding('utf8');
|
||||
@@ -713,7 +771,7 @@ describe('Waggle CLI Launcher', () => {
|
||||
WAGGLE_INSTANCE_ID: 'launcher-fallback-history-restart',
|
||||
WAGGLE_DESKTOP_BOOTSTRAP_TOKEN: desktopBootstrapToken,
|
||||
WAGGLE_READY_FILE: restartReadyFile,
|
||||
...providerFreeEnv,
|
||||
...providerEnv,
|
||||
},
|
||||
);
|
||||
child.stdout.setEncoding('utf8');
|
||||
|
||||
@@ -63,13 +63,14 @@ const OAUTH_PROVIDERS: Record<string, OAuthProviderConfig> = {
|
||||
/** In-memory store for OAuth state parameters (CSRF protection) */
|
||||
const pendingStates = new Map<string, { provider: string; createdAt: number }>();
|
||||
|
||||
// Clean up expired states every 10 minutes
|
||||
// Clean up expired states every 10 minutes. Unref'd so this housekeeping timer
|
||||
// never keeps the process alive after the server closes on SIGTERM/SIGINT.
|
||||
setInterval(() => {
|
||||
const cutoff = Date.now() - 10 * 60 * 1000;
|
||||
for (const [key, val] of pendingStates) {
|
||||
if (val.createdAt < cutoff) pendingStates.delete(key);
|
||||
}
|
||||
}, 10 * 60 * 1000);
|
||||
}, 10 * 60 * 1000).unref();
|
||||
|
||||
// ── Routes ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
Reference in New Issue
Block a user