mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-01 06:02:56 +00:00
* M1: terminals survive daemon restarts: stop reasons, detached terminal worker, kill cleanup
restart_server_request.killTerminals / shutdown_server_request.keepTerminals and server_info.features.terminalsSurviveRestart; CLI daemon restart --kill-terminals and daemon stop --keep-terminals (capability-gated). The terminal worker runs detached over an owner-only, secret-authenticated socket and is adopted on daemon start. One kill cleanup contract (the reaper) by birth time, used by the daemon, the supervisor and stopDaemonInstance. Settings offers Restart and close terminals.
* M1: fix review findings: reaper session/table retry, short-command creation order, remote kill-restart cleanup report, stop test port
* M1: fix review findings: reaper-owned cleanup record, session member identity by terminal id, unreadable cleanup records, Settings restart error rendered in the card
* M2: worker protocol versions and draining, worker runs from its own copy, desktop upgrades keep terminals, out-of-date daemon notice, docs/terminal-worker.md
- Daemon classifies live workers by protocol: adopts current, drains one version old, shuts
down older, leaves a newer one running and answers list/create with
terminal_worker_incompatible (daemon status prints it). Never more than two workers.
- esbuild worker bundle (build:lib); a built daemon copies bundle, shell integration and
node-pty into $PASEO_HOME/terminal-worker/<version>-<hash>/ and launches from it; copies no
record names are pruned.
- Desktop app_update/version_mismatch stop with keep terminals on macOS/Linux; Windows and a
daemon without the capability close them.
- Out-of-date daemon sidebar notice with Update button, worded by terminalsSurviveRestart.
- PASEO-13: unreadable worker records fail status and kill-restart retry.
- PASEO-14: a session member without a terminal id is unknown, not unrelated.
- Smoke test 46 with A/B installation fixtures and per-fixture CLI shims (PASEO-9 fold).
* M2: track in-flight worker requests without leaving an unhandled rejection
detach({ afterPendingRequests }) tracked each request with request.finally(), which rejects
with the request; a fire-and-forget send that timed out surfaced as an unhandled rejection
(worker-terminal-manager.test.ts). Track settlement only.
* M2: CI round 1 fixes: worker terminal manager in the MCP key test, status cleanup field, shared socket dir
- mcp-server.test.ts (new upstream test) built the worker manager with the old fork API;
it now starts a real detached worker in a throwaway home.
- daemon-session.test.ts expected status without terminalCleanupUnconfirmed (added in M1).
- paseo-daemon.test.ts: a home under the scratch temp dir is too long for a unix socket, so
the worker listens in the per-user paseo-<uid> directory, which outlives workers by design;
the test now requires it to be empty instead of absent.
* M2: run Windows PowerShell by its install path for process identity
server-tests (windows-latest): bootstrap-provider-availability.test.ts starts a daemon with a
PATH that holds only git, and the terminal worker failed to start: 'cannot read its own process
identity: spawn powershell.exe ENOENT'. Process inspection (managed-processes.ts inspect and the
terminal worker's process table) now runs %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe.
* M2: lifecycle e2e plain stop uses the shutdown RPC on Windows
CI round 2, server-integration (windows-latest): 'stop and stop --force never signal processes
a stale or earlier-boot record names' called stopDaemonInstance without a shutdown channel,
which Windows refuses ('has no graceful shutdown channel'). Plain stops in the file now pass
one, as the CLI does.
* M2: native notice outlet, Windows desktop-update wording, worker cap counts unconfirmed cleanups, create recovers after a drain
* M2: phone sidebar mounts the callout slot (iOS notice verified), worker record reads retry transient errors
* M2: native notice preconditions use explicit working directories, one block per terminal
* M1: compact sidebar shows only native callouts on every platform; PTY round trips in the MCP key test get a 5 s window
* ci: pin Playwright browser jobs to ubuntu-24.04
The pinned Playwright (1.58) has no ubuntu-26.04 build, and forks whose
ubuntu-latest already resolves to 26.04 fail at browser install. Job names
are unchanged, so required-check contexts still match.
* ci: use ubuntu-latest for Playwright jobs, same as upstream
Reverts the ubuntu-24.04 pin; upstream main's Playwright shards pass on ubuntu-latest.
* fix(server): keep terminal worker record IO off the daemon event loop
* fix(server): restore terminal creation after worker failure
A disconnected terminal worker remained the current manager indefinitely, leaving dead sessions listed and every later create bound to a closed socket. Confirm process death before retiring the member and use the existing single launch path for replacement. Reconnect live workers and replay their screens while preserving terminal identity.
* test(server): verify orphan cleanup during worker recovery
Recovery reaps orphaned programs before a later daemon stop. The previous fixed-delay assertion raced that cleanup and failed when it completed promptly. Verify orphan removal, same-daemon replacement creation and cleanup on normal or forced stop instead.
* test(server): isolate Windows dependency fixture setup
Build the local package registry in setup so its npm packing processes do not consume the installation journey deadline. Install the platform package used by Windows runtime fixtures directly, avoiding an unused wrapper postinstall probe without a timeout.
* test(server): wait for pending watchers before disposal
Observation admission starts before asynchronous path setup reaches watcher subscription. Disposing at the admission counter races setup and never exercises late watcher cleanup. Wait for the subscriptions to be pending before disposing.
---------
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
325 lines
13 KiB
TypeScript
325 lines
13 KiB
TypeScript
#!/usr/bin/env npx tsx
|
|
|
|
/**
|
|
* Terminals survive `paseo daemon restart` and `stop --keep-terminals`; `restart
|
|
* --kill-terminals`, `stop` and `stop --force` close them. Runs the built CLI and daemon in a
|
|
* throwaway home; every process it starts is stopped in `finally`.
|
|
*/
|
|
|
|
import assert from "node:assert/strict";
|
|
import { spawn } from "node:child_process";
|
|
import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { mkdtemp, mkdir, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { readDaemonInstance } from "@getpaseo/server/daemon-control";
|
|
import { runLocalPaseo } from "./helpers/local-cli.ts";
|
|
import { getAvailablePort } from "./helpers/network.ts";
|
|
|
|
if (process.platform === "win32") {
|
|
console.log("Skipping terminal survival CLI test on Windows (POSIX shell terminals).");
|
|
process.exit(0);
|
|
}
|
|
|
|
console.log("=== Daemon terminals survive restart ===\n");
|
|
|
|
const paseoHome = await mkdtemp(join(tmpdir(), "paseo-terminals-survive-"));
|
|
const workDir = join(paseoHome, "work");
|
|
await mkdir(workDir, { recursive: true });
|
|
const port = await getAvailablePort();
|
|
const env = {
|
|
PASEO_HOME: paseoHome,
|
|
PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0",
|
|
PASEO_DICTATION_ENABLED: "0",
|
|
PASEO_VOICE_MODE_ENABLED: "0",
|
|
// The daemon inherits this; terminals then run a plain POSIX shell with no startup files.
|
|
SHELL: "/bin/sh",
|
|
};
|
|
|
|
function isAlive(pid: number): boolean {
|
|
try {
|
|
process.kill(pid, 0);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function waitFor<T>(
|
|
probe: () => Promise<T | null | false> | T | null | false,
|
|
message: string,
|
|
timeoutMs = 30_000,
|
|
): Promise<T> {
|
|
const deadline = Date.now() + timeoutMs;
|
|
while (Date.now() < deadline) {
|
|
const value = await probe();
|
|
if (value) return value;
|
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
}
|
|
throw new Error(message);
|
|
}
|
|
|
|
async function paseo(args: string[], expectSuccess = true) {
|
|
const result = await runLocalPaseo(args, env);
|
|
if (expectSuccess) {
|
|
assert.equal(
|
|
result.exitCode,
|
|
0,
|
|
`paseo ${args.join(" ")} failed:\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`,
|
|
);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
async function json<T>(args: string[]): Promise<T> {
|
|
return JSON.parse((await paseo([...args, "--json"])).stdout) as T;
|
|
}
|
|
|
|
async function capture(terminalId: string): Promise<string> {
|
|
const { lines } = await json<{ lines: string[] }>(["terminal", "capture", terminalId]);
|
|
return lines.join("\n");
|
|
}
|
|
|
|
async function waitForScreen(terminalId: string, text: string): Promise<void> {
|
|
await waitFor(
|
|
async () => (await capture(terminalId)).includes(text),
|
|
`terminal ${terminalId} never showed ${text}:\n${await capture(terminalId)}`,
|
|
);
|
|
}
|
|
|
|
async function terminalIds(): Promise<string[]> {
|
|
return (await json<Array<{ id: string }>>(["terminal", "ls", "--all"])).map((t) => t.id);
|
|
}
|
|
|
|
// Worker records and the cleanup records a kill that could not finish leaves beside them.
|
|
function workerRecordCount(): number {
|
|
const dir = join(paseoHome, "terminal-worker");
|
|
return existsSync(dir)
|
|
? readdirSync(dir).filter((name) => /^(\d+|closing-.+)\.json$/.test(name)).length
|
|
: 0;
|
|
}
|
|
|
|
// A shell terminal that reports its pid and prints a marker.
|
|
async function openTerminal(name: string): Promise<{ id: string; pid: number }> {
|
|
const terminal = await json<{ id: string }>([
|
|
"terminal",
|
|
"create",
|
|
"--cwd",
|
|
workDir,
|
|
"--name",
|
|
name,
|
|
]);
|
|
const pidFile = join(workDir, `${name}.pid`);
|
|
await paseo([
|
|
"terminal",
|
|
"send-keys",
|
|
terminal.id,
|
|
"-l",
|
|
`echo $$ > '${pidFile}'; echo MARKER-${name}`,
|
|
]);
|
|
await paseo(["terminal", "send-keys", terminal.id, "Enter"]);
|
|
const pid = await waitFor(
|
|
() =>
|
|
existsSync(pidFile) && readFileSync(pidFile, "utf8").trim()
|
|
? Number(readFileSync(pidFile, "utf8"))
|
|
: null,
|
|
`terminal ${name} never wrote its pid`,
|
|
);
|
|
await waitForScreen(terminal.id, `MARKER-${name}`);
|
|
return { id: terminal.id, pid };
|
|
}
|
|
|
|
async function expectKept(terminal: { id: string; pid: number }, name: string, trigger: string) {
|
|
assert((await terminalIds()).includes(terminal.id), `${trigger}: terminal is still listed`);
|
|
assert(isAlive(terminal.pid), `${trigger}: terminal program is still alive`);
|
|
assert((await capture(terminal.id)).includes(`MARKER-${name}`), `${trigger}: marker is kept`);
|
|
await paseo(["terminal", "send-keys", terminal.id, "-l", `echo after-${trigger}`]);
|
|
await paseo(["terminal", "send-keys", terminal.id, "Enter"]);
|
|
await waitForScreen(terminal.id, `\nafter-${trigger}`);
|
|
}
|
|
|
|
async function expectClosed(pid: number, trigger: string) {
|
|
await waitFor(() => !isAlive(pid), `${trigger}: terminal program ${pid} is still alive`, 15_000);
|
|
}
|
|
|
|
// A zombie: a real process with a birth time that SIGKILL cannot remove while its parent (an
|
|
// exec'd `sleep` that never waits) lives. Cleanup can only report it as still alive.
|
|
async function startZombie(): Promise<{ zombiePid: number; parentPid: number }> {
|
|
const parent = spawn("/bin/sh", ["-c", "sleep 0 & echo $!; exec sleep 600"], {
|
|
stdio: ["ignore", "pipe", "ignore"],
|
|
});
|
|
const zombiePid = await new Promise<number>((resolve) => {
|
|
parent.stdout!.once("data", (chunk: Buffer) => resolve(Number(chunk.toString().trim())));
|
|
});
|
|
parent.unref();
|
|
await waitFor(
|
|
async () => (await psField(zombiePid, "stat")).startsWith("Z"),
|
|
`process ${zombiePid} never became a zombie`,
|
|
);
|
|
return { zombiePid, parentPid: parent.pid! };
|
|
}
|
|
|
|
async function psField(pid: number, field: "stat" | "lstart"): Promise<string> {
|
|
const child = spawn("ps", ["-o", `${field}=`, "-p", String(pid)], {
|
|
env: { ...process.env, LC_ALL: "C" },
|
|
stdio: ["ignore", "pipe", "ignore"],
|
|
});
|
|
let out = "";
|
|
child.stdout.on("data", (chunk: Buffer) => (out += chunk.toString()));
|
|
await new Promise((resolve) => child.once("close", resolve));
|
|
return out.trim();
|
|
}
|
|
|
|
async function goneProcessPid(): Promise<number> {
|
|
const child = spawn(process.execPath, ["-e", ""], { stdio: "ignore" });
|
|
await new Promise((resolve) => child.once("exit", resolve));
|
|
return child.pid!;
|
|
}
|
|
|
|
// A record as a dead terminal worker leaves it, naming one terminal program that is a zombie.
|
|
async function plantRecordNaming(programPid: number): Promise<void> {
|
|
const workerPid = await goneProcessPid();
|
|
const record = {
|
|
recordId: "planted-record",
|
|
pid: workerPid,
|
|
bootId: null,
|
|
createdAt: new Date().toISOString(),
|
|
identity: { startedAt: "Thu Jan 1 00:00:00 1970", commandLine: "planted-worker" },
|
|
protocolVersion: 1,
|
|
paseoVersion: "0.0.0-test",
|
|
socketPath: join(paseoHome, "planted-worker.sock"),
|
|
secret: "planted-secret",
|
|
terminals: [
|
|
{ id: "planted-terminal", pid: programPid, startedAt: await psField(programPid, "lstart") },
|
|
],
|
|
};
|
|
writeFileSync(
|
|
join(paseoHome, "terminal-worker", `${workerPid}.json`),
|
|
`${JSON.stringify(record, null, 2)}\n`,
|
|
{ mode: 0o600 },
|
|
);
|
|
}
|
|
|
|
const trackedPids: number[] = [];
|
|
|
|
try {
|
|
for (const [field, value] of [
|
|
["daemon.listen", `127.0.0.1:${port}`],
|
|
["daemon.relay.enabled", "false"],
|
|
["features.dictation.enabled", "false"],
|
|
["features.voiceMode.enabled", "false"],
|
|
] as const) {
|
|
await paseo(["daemon", "config", "set", field, value]);
|
|
}
|
|
await paseo(["daemon", "start"]);
|
|
|
|
console.log("Test 1: daemon restart keeps the terminal");
|
|
const kept = await openTerminal("kept");
|
|
trackedPids.push(kept.pid);
|
|
await paseo(["daemon", "restart", "--home", paseoHome]);
|
|
await expectKept(kept, "kept", "restart");
|
|
console.log("✓ same id, same program, marker and input after restart\n");
|
|
|
|
console.log("Test 2: stop --keep-terminals, then start, gives the terminal back");
|
|
const forceAndKeep = await paseo(
|
|
["daemon", "stop", "--home", paseoHome, "--force", "--keep-terminals"],
|
|
false,
|
|
);
|
|
assert.notEqual(forceAndKeep.exitCode, 0, "--force with --keep-terminals is refused");
|
|
await paseo(["daemon", "stop", "--home", paseoHome, "--keep-terminals"]);
|
|
assert.equal(await readDaemonInstance(paseoHome), null, "the supervisor stopped");
|
|
assert(isAlive(kept.pid), "the program outlives the stopped daemon");
|
|
await paseo(["daemon", "start"]);
|
|
await expectKept(kept, "kept", "keep-stop");
|
|
console.log("✓ adopted with the same id and still usable\n");
|
|
|
|
console.log("Test 3: a plain stop with no daemon running closes kept terminals");
|
|
await paseo(["daemon", "stop", "--home", paseoHome, "--keep-terminals"]);
|
|
assert(isAlive(kept.pid), "kept again");
|
|
await paseo(["daemon", "stop", "--home", paseoHome]);
|
|
await expectClosed(kept.pid, "stop without a supervisor");
|
|
assert.equal(workerRecordCount(), 0, "no worker record is left");
|
|
console.log("✓ closed\n");
|
|
|
|
console.log("Test 4: restart --kill-terminals closes the terminal");
|
|
await paseo(["daemon", "start"]);
|
|
const killedByRestart = await openTerminal("restart-kill");
|
|
trackedPids.push(killedByRestart.pid);
|
|
await paseo(["daemon", "restart", "--home", paseoHome, "--kill-terminals"]);
|
|
await expectClosed(killedByRestart.pid, "restart --kill-terminals");
|
|
assert.deepEqual(await terminalIds(), [], "no terminal is listed after the kill restart");
|
|
console.log("✓ closed\n");
|
|
|
|
console.log("Test 5: daemon stop closes the terminal and its worker");
|
|
const killedByStop = await openTerminal("stop-kill");
|
|
trackedPids.push(killedByStop.pid);
|
|
await paseo(["daemon", "stop", "--home", paseoHome]);
|
|
await expectClosed(killedByStop.pid, "stop");
|
|
assert.equal(workerRecordCount(), 0, "no worker record is left");
|
|
console.log("✓ closed\n");
|
|
|
|
console.log("Test 6: daemon stop --force closes the terminal");
|
|
await paseo(["daemon", "start"]);
|
|
const killedByForce = await openTerminal("force-kill");
|
|
trackedPids.push(killedByForce.pid);
|
|
await paseo(["daemon", "stop", "--home", paseoHome, "--force"]);
|
|
await expectClosed(killedByForce.pid, "stop --force");
|
|
assert.equal(workerRecordCount(), 0, "no worker record is left");
|
|
console.log("✓ closed\n");
|
|
|
|
const endpoint = `127.0.0.1:${port}`;
|
|
console.log("Test 7: restart --host --kill-terminals closes the terminal");
|
|
await paseo(["daemon", "start"]);
|
|
const killedByEndpointRestart = await openTerminal("endpoint-restart-kill");
|
|
trackedPids.push(killedByEndpointRestart.pid);
|
|
await paseo(["daemon", "restart", "--host", endpoint, "--kill-terminals"]);
|
|
await expectClosed(killedByEndpointRestart.pid, "restart --host --kill-terminals");
|
|
assert.deepEqual(await terminalIds(), [], "no terminal is listed after the kill restart");
|
|
console.log("✓ closed and confirmed by the replacement\n");
|
|
|
|
console.log("Test 8: restart --host --kill-terminals reports a process cleanup could not end");
|
|
const zombie = await startZombie();
|
|
trackedPids.push(zombie.parentPid);
|
|
await plantRecordNaming(zombie.zombiePid);
|
|
const unconfirmed = await paseo(
|
|
["daemon", "restart", "--host", endpoint, "--kill-terminals"],
|
|
false,
|
|
);
|
|
assert.notEqual(unconfirmed.exitCode, 0, "the kill restart fails");
|
|
const output = unconfirmed.stdout + unconfirmed.stderr;
|
|
assert(output.includes("Terminal cleanup was not confirmed"), `names the failure:\n${output}`);
|
|
assert(output.includes(`pid ${zombie.zombiePid}`), `names the surviving pid:\n${output}`);
|
|
process.kill(zombie.parentPid, "SIGKILL");
|
|
await expectClosed(zombie.zombiePid, "zombie reaped once its parent exits");
|
|
await paseo(["daemon", "stop", "--home", paseoHome]);
|
|
assert.equal(workerRecordCount(), 0, "the next stop retries the cleanup and retires the record");
|
|
console.log("✓ reported, then retried by stop\n");
|
|
|
|
console.log("Test 9: restart --host --kill-terminals reports a worker record it cannot read");
|
|
await paseo(["daemon", "start"]);
|
|
// A kill cleanup cannot check what an unreadable record names, and leaves nothing else
|
|
// behind, so the replacement daemon must still report it.
|
|
const unreadablePath = join(paseoHome, "terminal-worker", `${await goneProcessPid()}.json`);
|
|
writeFileSync(unreadablePath, "{ not json", { mode: 0o600 });
|
|
const unreadable = await paseo(
|
|
["daemon", "restart", "--host", endpoint, "--kill-terminals"],
|
|
false,
|
|
);
|
|
assert.notEqual(unreadable.exitCode, 0, "the kill restart fails");
|
|
const unreadableOutput = unreadable.stdout + unreadable.stderr;
|
|
assert(unreadableOutput.includes(unreadablePath), `names the record:\n${unreadableOutput}`);
|
|
assert(existsSync(unreadablePath), "the unreadable record is kept");
|
|
rmSync(unreadablePath);
|
|
await paseo(["daemon", "stop", "--home", paseoHome]);
|
|
assert.equal(workerRecordCount(), 0, "no worker record is left");
|
|
console.log("✓ reported with the record's path\n");
|
|
} finally {
|
|
await runLocalPaseo(["daemon", "stop", "--home", paseoHome, "--force"], env);
|
|
for (const pid of trackedPids) {
|
|
if (isAlive(pid)) process.kill(pid, "SIGKILL");
|
|
}
|
|
await rm(paseoHome, { recursive: true, force: true });
|
|
}
|
|
|
|
console.log("=== Daemon terminals survive restart passed ===");
|