fix(hopper): stop Linux demo children when the REA owner exits (#2499)

Bind the owned demo helper to REA's private stdin stream and unwind child
cleanup on EOF during startup or analysis. Verify graceful and SIGKILL owner
exit through real CLI/MCP workflows and preserve unrelated processes.

Assisted-by: Reimu (gensokyo-skills:reimu-incident-triage)
This commit is contained in:
Ysopwnable
2026-10-13 12:59:22 +08:00
committed by GitHub
parent d867136cec
commit c105391db5
9 changed files with 412 additions and 9 deletions
@@ -84,6 +84,7 @@ describe("Hopper bridge launcher selection", () => {
"private",
"/usr/bin/python3",
"/rea/hopper-demo-x11.py",
"--owner-stdin",
"--strategy",
"user-mount-namespace",
"--mount-private-x11",
@@ -117,6 +118,7 @@ describe("Hopper bridge launcher selection", () => {
command: "/usr/bin/python3",
args: [
"/rea/hopper-demo-x11.py",
"--owner-stdin",
"--strategy",
"direct",
"--hopper",
@@ -202,3 +204,59 @@ it("launches Hopper helpers with the caller-selected environment without restori
await launched.value.releaseLease?.();
}
});
it.skipIf(process.platform !== "linux")(
"gives the demo helper a live owner stream through Node's actual stdio transport",
async () => {
const directory = await createTestTempDirectory("rea-hopper-owner-stdio-");
const launcher = new HopperApplicationLauncher(
{
...options(process.execPath),
launchMode: "verified_linux_demo",
demoHelperPath: fileURLToPath(
new URL("../../../fixtures/hopperLifetimeLaunch.py", import.meta.url),
),
},
{
selectPrivateDisplay: async () => ({
ok: true,
strategy: "direct",
diagnostic: {
component: "hopper_private_display",
operation: "probe",
status: "ready",
failure_code: null,
reason: "ready",
socket_directory: "/tmp/.X11-unix",
socket_directory_mode: "1777",
mount_read_only: false,
effective_socket_directory_mode: "1777",
effective_mount_read_only: false,
wsl: false,
strategy: "direct",
fallback_reason: null,
xvfb_stderr_bytes: 0,
},
}),
},
);
const launched = await launcher.launch({
directory,
socketPath: join(directory, "bridge.sock"),
token: "fixture-token",
runId: randomUUID(),
});
if (!launched.ok) throw launched.error;
const supervisor = new ProviderProcessSupervisor(launched.value);
try {
expect(await supervisor.waitForOutputClose(5_000)).toBe(true);
expect(supervisor.snapshot().exitCode).toBe(0);
expect(JSON.parse(supervisor.snapshot().stdout.text)).toEqual({
owner_alive: true,
});
} finally {
await supervisor.stop();
await launched.value.releaseLease?.();
}
},
);
@@ -31,6 +31,9 @@ const dialogDetectionFixturePath = fileURLToPath(
const cleanupTimeoutFixturePath = fileURLToPath(
new URL("../../../fixtures/hopperCleanupTimeout.py", import.meta.url),
);
const ownerLifetimeFixturePath = fileURLToPath(
new URL("../../../fixtures/hopperOwnerLifetime.py", import.meta.url),
);
type DiagnosticOverrides = Partial<
Omit<HopperStartupDiagnostic, "failure_code" | "status">
@@ -107,6 +110,23 @@ describe("Hopper demo dialog detection", () => {
});
describe("Hopper process cleanup", () => {
it.skipIf(process.platform !== "linux").each(["startup", "ready"])(
"reaps only its own children when the owner pipe closes during %s",
(phase) => {
const result = spawnSync(
"/usr/bin/python3",
[ownerLifetimeFixturePath, helperPath, phase],
{ encoding: "utf8", timeout: 10_000 },
);
expect(result.status, result.stderr).toBe(0);
expect(JSON.parse(result.stdout)).toEqual({
phase,
children_cleaned: true,
sentinel_alive: true,
});
},
);
it.skipIf(process.platform !== "linux")(
"kills a child that ignores SIGTERM after the bounded timeout",
() => {
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Inspect the real Node launcher stdio with the production lifetime parser."""
import importlib.util
import json
from pathlib import Path
import sys
spec = importlib.util.spec_from_file_location(
"hopper_demo_x11", Path(__file__).resolve().parents[2] / "scripts/hopper-demo-x11.py"
)
assert spec is not None and spec.loader is not None
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
assert "--owner-stdin" in sys.argv
print(json.dumps({"owner_alive": helper.OwnerLifetime(True).alive()}))
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Exercise the production runner with real children and a simulated X11 surface."""
import argparse
import importlib.util
import json
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
import time
spec = importlib.util.spec_from_file_location("hopper_demo_x11", sys.argv[1])
assert spec is not None and spec.loader is not None
helper = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helper)
def child_command(receipt):
return [
sys.executable,
"-c",
"import os,pathlib,time;"
f"receipt=pathlib.Path({str(receipt)!r});"
"pending=receipt.with_suffix('.pending');"
"pending.write_text(str(os.getpid()));pending.replace(receipt);"
"time.sleep(100)",
]
if len(sys.argv) > 3:
phase, directory = sys.argv[2], Path(sys.argv[3])
def terminate_worker(*_):
raise SystemExit(143)
# Failed assertions in the parent must still unwind run_launch's finally.
signal.signal(signal.SIGTERM, terminate_worker)
class X11:
def XOpenDisplay(self, *_):
return 1
def XDefaultRootWindow(self, *_):
return 1
def XDisplayWidth(self, *_):
return 1280
def XDisplayHeight(self, *_):
return 1024
def XCloseDisplay(self, *_):
return 1
def start_xvfb(*_):
child = subprocess.Popen(
child_command(directory / "xvfb.pid"),
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
)
return child, ":123", directory / "Xauthority", helper.CapturedStderr(child.stderr)
helper.digest = lambda _: next(iter(helper.SUPPORTED_HOPPER_SHA256))
helper.start_xvfb = start_xvfb
helper.ctypes.CDLL = lambda _: X11()
helper.configure_x11 = lambda *_: None
helper.windows = lambda *_: []
socket = directory / "bridge.sock"
if phase == "ready":
socket.touch()
raise SystemExit(helper.run_launch(argparse.Namespace(
owner_stdin=True,
hopper=sys.executable,
socket=str(socket),
command=child_command(directory / "hopper.pid"),
)))
with tempfile.TemporaryDirectory(prefix="rea-owner-lifetime-") as root:
directory = Path(root)
sentinel = subprocess.Popen([sys.executable, "-c", "import time;time.sleep(100)"])
worker = subprocess.Popen(
[sys.executable, __file__, sys.argv[1], sys.argv[2], root],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
deadline = time.monotonic() + 5
receipts = [directory / "hopper.pid", directory / "xvfb.pid"]
while not all(receipt.exists() for receipt in receipts):
assert worker.poll() is None, worker.communicate()
assert time.monotonic() < deadline, "owned children did not start"
time.sleep(0.01)
pids = [int(receipt.read_text()) for receipt in receipts]
assert worker.poll() is None, "live owner did not retain the helper"
assert worker.stdin is not None
worker.stdin.close()
assert worker.wait(timeout=5) == 0, worker.stderr.read()
for pid in pids:
assert not Path(f"/proc/{pid}").exists(), f"owned child {pid} survived EOF"
assert sentinel.poll() is None, "unrelated process was stopped"
print(json.dumps({"phase": sys.argv[2], "children_cleaned": True, "sentinel_alive": True}))
finally:
helper.stop_process(worker)
helper.stop_process(sentinel)