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

@@ -27,6 +27,7 @@ import type {
} from './types.js';
import { chunkText } from './types.js';
import { resolveWhatsAppBrowser, WhatsAppBrowserError } from './whatsapp-browser.js';
import { releaseOrphanedBrowser, type ProfileLockState } from './whatsapp-profile-lock.js';
/** WhatsApp accepts ~65k; 4000 keeps replies phone-readable. */
export const WHATSAPP_MAX_TEXT = 4000;
@@ -103,6 +104,8 @@ export interface WhatsAppAdapterOptions {
browserResolver?: WaBrowserResolver;
/** Test seam. */
clientFactory?: WaClientFactory;
/** Test seam: frees the session profile from a browser left by an earlier run. */
releaseStaleBrowser?: (profileDir: string) => Promise<ProfileLockState>;
backoffCapMs?: number;
}
@@ -114,6 +117,7 @@ export class WhatsAppAdapter implements ChannelAdapter {
private readonly log: WhatsAppAdapterOptions['log'];
private readonly browserResolver: WaBrowserResolver;
private readonly clientFactory: WaClientFactory;
private readonly releaseStaleBrowser: (profileDir: string) => Promise<ProfileLockState>;
private readonly backoffCap: number;
private running = false;
@@ -136,6 +140,7 @@ export class WhatsAppAdapter implements ChannelAdapter {
await resolveWhatsAppBrowser({ dataDir: opts.dataDir, onProgress })
).executablePath);
this.clientFactory = opts.clientFactory ?? defaultClientFactory;
this.releaseStaleBrowser = opts.releaseStaleBrowser ?? (profileDir => releaseOrphanedBrowser(profileDir));
this.backoffCap = opts.backoffCapMs ?? BACKOFF_CAP_MS;
this.backoff = Math.min(BACKOFF_START_MS, this.backoffCap);
}
@@ -208,6 +213,21 @@ export class WhatsAppAdapter implements ChannelAdapter {
let client: WaClientLike;
try {
this.detail = 'Starting the browser';
// LocalAuth keeps the profile in <authDir>/session.
const lock = await this.releaseStaleBrowser(path.join(this.authDir, 'session'));
if (!current()) return;
if (lock.kind === 'in-use') {
// Another server's live session: taking it over would only make the two
// stop each other's WhatsApp, so wait for the user instead.
this.handleDrop(
`another Waggle server on this computer is running WhatsApp with this session (browser pid ${lock.pid}); stop WhatsApp there, then start it here`,
false,
);
return;
}
if (lock.kind === 'released') {
this.log.warn(`[whatsapp] stopped a browser left over from an earlier run (pid ${lock.pid})`);
}
client = await this.clientFactory({ authDir: this.authDir, executablePath });
} catch (e: unknown) {
if (current()) this.handleDrop(e instanceof Error ? e.message : String(e), true);

View File

@@ -0,0 +1,111 @@
/**
* A WhatsApp browser left over from an earlier run keeps the session profile
* locked, and a new browser for the same profile refuses to start ("The
* browser is already running"). That happens when the sidecar dies without its
* shutdown, for example after a crash or a forced quit.
*
* Chrome marks a profile in use with a SingletonLock symlink to
* "<hostname>-<pid>". When that pid is a browser for this profile and the
* process that started it is gone, the browser is an orphan and is stopped. A
* browser whose parent is still a Node process belongs to another running
* Waggle server and is left alone. Windows keeps no such symlink, and there the
* desktop shell's job object ends the browser together with the sidecar.
*/
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
export type ProfileLockState =
| { kind: 'free' }
| { kind: 'released'; pid: number }
| { kind: 'in-use'; pid: number };
export interface ProcessInfo {
ppid: number;
command: string;
}
export interface ProfileLockOptions {
hostname?: string;
/** Parent pid and full command line of a live process, or null once it is gone. */
inspect?: (pid: number) => ProcessInfo | null;
/** How long the orphan gets to exit after SIGTERM before SIGKILL. */
graceMs?: number;
}
function inspectProcess(pid: number): ProcessInfo | null {
try {
const out = execFileSync('ps', ['-ww', '-o', 'ppid=,command=', '-p', String(pid)], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
const match = /^(\d+)\s+([\s\S]*)$/.exec(out);
return match ? { ppid: Number(match[1]), command: match[2] } : null;
} catch {
// ps exits non-zero when the pid does not exist.
return null;
}
}
function isAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function usesProfile(command: string, profileDir: string): boolean {
const flag = `--user-data-dir=${profileDir}`;
const at = command.indexOf(flag);
if (at < 0) return false;
const next = command.charAt(at + flag.length);
return next === '' || next === ' ';
}
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
export async function releaseOrphanedBrowser(
profileDir: string,
opts: ProfileLockOptions = {},
): Promise<ProfileLockState> {
if (process.platform === 'win32') return { kind: 'free' };
let target: string;
try {
target = fs.readlinkSync(path.join(profileDir, 'SingletonLock'));
} catch {
return { kind: 'free' };
}
const dash = target.lastIndexOf('-');
const pid = Number(target.slice(dash + 1));
if (dash <= 0 || !Number.isInteger(pid) || pid <= 0) return { kind: 'free' };
if (target.slice(0, dash) !== (opts.hostname ?? os.hostname())) return { kind: 'free' };
const inspect = opts.inspect ?? inspectProcess;
const browser = inspect(pid);
// A dead pid is a stale lock that Chrome clears itself; a different process
// under a reused pid is not ours.
if (!browser || !usesProfile(browser.command, profileDir)) return { kind: 'free' };
const parent = browser.ppid > 1 ? inspect(browser.ppid) : null;
if (parent && /(^|\/)node(\s|$)/.test(parent.command)) return { kind: 'in-use', pid };
try {
process.kill(pid, 'SIGTERM');
} catch {
return { kind: 'free' };
}
const deadline = Date.now() + (opts.graceMs ?? 5_000);
while (isAlive(pid) && Date.now() < deadline) await sleep(100);
if (isAlive(pid)) {
try {
process.kill(pid, 'SIGKILL');
} catch {
// Exited between the check and the signal.
}
}
return { kind: 'released', pid };
}

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', () => {