fix(desktop): stop the sidecar with SIGTERM first, and free a stale WhatsApp profile (UF-046)

On macOS and Linux the shell stopped the sidecar with Child::kill(), which is
SIGKILL, so the sidecar never ran its shutdown: the processes it started (MCP
servers, a managed Ollama, the WhatsApp browser) kept running. After an app
restart the orphaned WhatsApp browser still held the session profile, and the
channel failed with "The browser is already running".

The shell now sends SIGTERM, waits up to 5 seconds for the sidecar to exit,
then sends SIGKILL; Windows keeps its kill-on-close job. For crashes, where no
shutdown runs, the WhatsApp channel stops a browser left over from an earlier
run before starting its own. It only stops a process whose command line uses
this profile and whose parent is gone; a browser another running Waggle server
owns is left alone, and the channel says so instead of retrying.
This commit is contained in:
shumeiko.it
2026-10-26 12:03:31 +01:00
parent 48bdab8087
commit 1e826aa220
8 changed files with 345 additions and 6 deletions

View File

@@ -0,0 +1,99 @@
/**
* releaseOrphanedBrowser: a WhatsApp browser left over from a sidecar that died
* without its shutdown is stopped; a browser another running server owns, or
* any other process, is left alone.
*/
import { execFileSync, spawn, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { releaseOrphanedBrowser } from '../src/local/channels/whatsapp-profile-lock.js';
const IDLE = 'setInterval(() => {}, 1000)';
function isAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
async function waitUntilGone(pid: number): Promise<boolean> {
for (let i = 0; i < 50 && isAlive(pid); i++) await new Promise(r => setTimeout(r, 100));
return !isAlive(pid);
}
describe.skipIf(process.platform === 'win32')('releaseOrphanedBrowser', () => {
let root: string;
let profileDir: string;
const started: number[] = [];
function lockTo(pid: number, host = os.hostname()): void {
fs.symlinkSync(`${host}-${pid}`, path.join(profileDir, 'SingletonLock'));
}
/** A process for this profile whose parent has exited, like the browser of a killed sidecar. */
function startOrphan(): number {
const out = execFileSync('sh', [
'-c',
`"${process.execPath}" -e "${IDLE}" -- --user-data-dir=${profileDir} >/dev/null 2>&1 & echo $!`,
], { encoding: 'utf8' });
const pid = Number(out.trim());
started.push(pid);
return pid;
}
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-wa-lock-'));
profileDir = path.join(root, 'session');
fs.mkdirSync(profileDir);
});
afterEach(() => {
for (const pid of started.splice(0)) {
try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ }
}
fs.rmSync(root, { recursive: true, force: true });
});
it('stops a browser for this profile whose parent is gone', async () => {
const pid = startOrphan();
lockTo(pid);
expect(await releaseOrphanedBrowser(profileDir, { graceMs: 3000 })).toEqual({ kind: 'released', pid });
expect(await waitUntilGone(pid)).toBe(true);
});
it('leaves a browser that a running server still owns', async () => {
const child = spawn(process.execPath, ['-e', IDLE, '--', `--user-data-dir=${profileDir}`], { stdio: 'ignore' });
started.push(child.pid!);
lockTo(child.pid!);
expect(await releaseOrphanedBrowser(profileDir)).toEqual({ kind: 'in-use', pid: child.pid });
expect(isAlive(child.pid!)).toBe(true);
});
it('leaves a process that does not use this profile', async () => {
lockTo(process.pid);
expect(await releaseOrphanedBrowser(profileDir)).toEqual({ kind: 'free' });
});
it('treats a lock whose process is gone as free', async () => {
const gone = spawnSync('true').pid;
lockTo(gone);
expect(await releaseOrphanedBrowser(profileDir)).toEqual({ kind: 'free' });
});
it('ignores a lock from another computer', async () => {
const pid = startOrphan();
lockTo(pid, 'another-host.local');
expect(await releaseOrphanedBrowser(profileDir)).toEqual({ kind: 'free' });
expect(isAlive(pid)).toBe(true);
});
});

View File

@@ -184,6 +184,41 @@ describe('WhatsAppAdapter client setup', () => {
expect(wweb.clients).toHaveLength(0);
adapter = null;
});
it('stops a browser left over from an earlier run before starting its own', async () => {
const warnings: string[] = [];
const release = vi.fn(async () => ({ kind: 'released' as const, pid: 4242 }));
adapter = new WhatsAppAdapter({
dataDir: dir,
onMessage: async () => undefined,
log: { info: () => undefined, warn: message => { warnings.push(message); } },
browserResolver: async () => CHROME,
releaseStaleBrowser: release,
backoffCapMs: 10,
});
await adapter.start();
await vi.waitFor(() => expect(wweb.clients.length).toBe(1));
expect(release).toHaveBeenCalledWith(path.join(dir, 'channels', 'whatsapp', 'session'));
expect(warnings.join('\n')).toMatch(/left over from an earlier run \(pid 4242\)/);
});
it('waits for the user when another running server holds the session', async () => {
const a = new WhatsAppAdapter({
dataDir: dir,
onMessage: async () => undefined,
log: noopLog,
browserResolver: async () => CHROME,
releaseStaleBrowser: async () => ({ kind: 'in-use', pid: 4242 }),
backoffCapMs: 10,
});
adapter = a;
await a.start();
await vi.waitFor(() => expect(a.getStatus().lastError).toMatch(/another Waggle server.*pid 4242/));
await tick(50);
expect(wweb.clients).toHaveLength(0);
});
});
describe('WhatsAppAdapter pairing + status', () => {