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:
shumeiko.it
2026-10-25 23:01:05 +01:00
parent 2e08f2ae96
commit 07a529512c
3 changed files with 104 additions and 35 deletions

View File

@@ -69,6 +69,7 @@ Baseline: commit `b20b138` of `git.os-dev.tech/oleg.m/waggle-os`.
| UF-038 | Marketplace installs never notify the running sidecar | Open | Marketplace, sidecar |
| UF-039 | A memory saved to an unknown workspace lands in personal memory | Fixed | Sidecar, memory, privacy |
| UF-040 | The support bundle never includes recent installs | Fixed | Sidecar, support |
| UF-041 | The CLI server does not exit on Ctrl+C or SIGTERM | Fixed | Sidecar, CLI |
## Entries
@@ -405,3 +406,12 @@ Entries UF-010 to UF-019 come from the UI audit `anti-slop/audit-001-2026-10-14.
- Cause: the route reads the private `db` field of the audit store and calls `prepare` on it. That field is the database wrapper (`MindDB`), which has no `prepare` method, so the call throws and the empty `catch` drops the error.
- What we did: the server's `InstallAuditStore` got `getRecentSummary()`, which returns only the timestamp, action and capability type of the latest 50 events, and the route calls it. A test checks the field and its columns.
- Recommendation: read the trail through the store's own API in the main project as well, and log errors in this route instead of dropping them.
### UF-041. The CLI server does not exit on Ctrl+C or SIGTERM
- Status: Fixed
- Found: 2026-10-25
- Where: at commit `b20b138`, `packages/server/src/local/routes/oauth.ts:67-73` (a module-level `setInterval`), together with the signal handler in `packages/server/src/local/service.ts:305-312`
- Symptom: after Ctrl+C in `npx waggle` or `npm run dev:server` the HTTP server closes, but the process keeps running until a second Ctrl+C. After SIGTERM, for example from `kill` or a process manager, it never exits. The launcher's own test left two `waggle` processes running after every test run. The desktop app is not affected: it stops the sidecar with SIGKILL.
- Cause: the OAuth routes start a cleanup interval when the module loads and never clear or unref it. The service installs SIGTERM and SIGINT handlers, which replace Node's default exit, closes the server, and relies on the event loop going empty; the interval keeps it alive.
- What we did: the interval is unref'd. A launcher test checks that the built CLI exits by itself after SIGTERM, and the launcher tests now stop `npx` and the `waggle` process it starts as one process group.
- Recommendation: unref housekeeping timers or clear them when the server closes, and consider ending the signal handler with an explicit exit.

View File

@@ -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');

View File

@@ -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 ────────────────────────────────────────────────────────────