Skip to content

Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.

fix: preserve isolated Pilot profiles across native App reopening (#210)

澄潭dba77f3e2082
diff --git a/docs/code-map/testing.md b/docs/code-map/testing.md
index 49443269..4b71009a 100644
--- a/docs/code-map/testing.md
+++ b/docs/code-map/testing.md
@@ -23,6 +23,12 @@ identity, frozen snapshots and checks before reuse/start using fake build/launch
The separate `--real-consumer` case is required by the affected CI selection and
checks the production Rust build-script and embedding declaration; local default
checks never compile or execute those temporary Rust programs.
+The optional native App entry belongs to
+[pilot-native-app.py](../../scripts/pilot-native-app.py), with
+[fixture process regressions](../../scripts/test-pilot-native-app.py) for ordinary
+reopen, profile retention, artifact refusal and lease retirement. Actual macOS
+LaunchServices/native CU and daemon/CLI acceptance remain separate from those
+local entry tests; follow the [App lifecycle guide](../desktop-tauri-pilot.md#managed-native-app-opening-and-reopening).
[Orphaned data preparation](../../scripts/windows-dev-profile.py) preserves complete
backups after explicit user authorization; it does not establish a product scenario.
[Native Desktop session actions](../../scripts/windows-desktop-session.py) admit
diff --git a/docs/desktop-tauri-pilot.md b/docs/desktop-tauri-pilot.md
index ce32e145..1c675cca 100644
--- a/docs/desktop-tauri-pilot.md
+++ b/docs/desktop-tauri-pilot.md
@@ -121,6 +121,66 @@ START=$(python3 scripts/desktop-pilot.py start \
--process-home /absolute/offline-test-home)
```
+## Managed native App opening and reopening
+
+For native macOS CU, use an exact-candidate reusable build and explicitly request
+its App entry. Ordinary Pilot startup remains available for WebView/IPC checks.
+
+```sh
+python3 scripts/validation.py pilot-build acquire \
+ --ref refs/heads/codex/my-change --owner my-task --case native-reopen
+python3 scripts/validation.py pilot-build start \
+ --lease LEASE --case native-reopen --native-app
+```
+
+Select the returned `native_app.bundle` absolute `.app` path in native CU. The
+bundle has a unique per-session bundle identifier; its application executable,
+daemon and CLI are private copies from that one managed build, preserving their
+exact bytes and signatures with distinct file identities. Separate executable
+inodes keep macOS process paths stable when multiple Apps use the same build.
+An already staged adjacent CPA is included only after its hash/size matches the build’s frozen native-target CPA manifest; absent CPA keeps
+the existing subscription-local missing-artifact behavior. Do not copy, move or
+re-sign the entry: create a new owned entry if its identity changes. This mode requires a reusable owner lease and its recorded
+non-persistent WebView build configuration. It does not package a release App or
+alter production launch behavior.
+
+Every ordinary Finder/LaunchServices/native-CU opening passes through the same
+private launch guard. The guard checks the open registered lease, candidate,
+original and deployed executable identities, wrapper/configuration files and
+owned directories. It restores only recorded launch values: private test data,
+runtime, temporary directory, working directory and HOME/native Agent locations,
+plus explicitly captured PATH/locale settings and the diagnostic override. It
+never saves or restores the caller's authentication environment. A new private
+HOME is created unless `--process-home` explicitly selects an owned offline one.
+The non-persistent WebView store starts empty on each process launch; product
+data remains in the same test root.
+
+A process-lifetime lock prevents duplicate entry launches. Each successful reopen
+records a new generation, PID/start identity and the same profile. The existing
+process attestation admits only this Desktop and its direct daemon child; an
+unknown process or replaced artifact refuses cleanup and retains evidence.
+Native menu/window operations remain real product behavior: closing a window may
+leave Desktop running, while application quit ends that process.
+
+Use `pilot status --session SESSION` to observe a stopped instance without
+launching it. Native APIs that select, activate, open or capture an App may reopen
+it; after quit, do not use those APIs as a termination check. An intentional
+ordinary reopen is safe through the recorded entry and must then be checked
+against the same session/data root. `pilot stop` stops the verified processes but
+leaves the entry reopenable. `pilot-build finish` revokes the entry first, stops
+its owned processes, removes only the verified deployed files and then releases
+the lease. Later native opening fails closed. Session metadata and evidence stay
+available; another owner's sessions and the daily application are untouched.
+
+Before marking the native case green on the exact candidate, physically select
+and open the App, prove the real daemon/CLI and profile identities, quit and
+observe stopped state, reopen through the ordinary native entry and prove the
+same profile with no duplicate/default instance. Exercise changed-artifact
+refusal and owner-only retirement. The local fixture-process tests cover the
+entry/ownership contract but cannot establish LaunchServices, code-signing,
+physical CU selection or the real product journey. Missing Mac/native tools
+leave this acceptance unexecuted.
+
## Real page and IPC
Snapshot references reset each time. Observe, choose the current reference, wait
diff --git a/docs/validation-routing.md b/docs/validation-routing.md
index 7c9b878f..c6fa5a1f 100644
--- a/docs/validation-routing.md
+++ b/docs/validation-routing.md
@@ -678,7 +678,10 @@ source is removed; it does not launch Desktop, CPA or a provider.
Use `pilot-build start --lease LEASE --case CASE` to launch each scenario with
the existing isolated Pilot launcher. It returns the session and socket for
-`pilot-cli`. All scenarios for that lease use the same build. These managed
+`pilot-cli`. Add `--native-app` for an attested macOS App entry whose ordinary
+opening/reopening preserves the same isolated profile; see the [native App
+lifecycle](desktop-tauri-pilot.md#managed-native-app-opening-and-reopening).
+All scenarios for that lease use the same build. These managed
bundles must be launched through this entry so sessions are registered before
launch; direct `pilot start` is refused for them. There is no arbitrary command
or release-profile override in this reusable build profile.
diff --git a/issue-spec/specs/product-smoke-verification/spec.md b/issue-spec/specs/product-smoke-verification/spec.md
index c0c40097..85b295a6 100644
--- a/issue-spec/specs/product-smoke-verification/spec.md
+++ b/issue-spec/specs/product-smoke-verification/spec.md
@@ -187,6 +187,43 @@ attributable terminal results and counts, the preparation failure, and explicit
unexecuted target/doctest coverage. Completed independent targets cannot establish
complete validation when dependent targets were not admitted.
+### Requirement: Native Pilot App reopening preserves its isolated owner
+
+An explicitly requested macOS native Pilot App entry MUST belong to one registered
+open reusable-build lease and one private session. Its original/deployed Desktop,
+daemon and CLI identities, candidate, launch guard, bundle metadata and isolation
+directories MUST be verified before every initial or ordinary operating-system
+launch. The entry MUST require the managed build's attested non-persistent WebView
+configuration; ordinary production builds retain their existing launch behavior.
+
+Initial launch and ordinary reopening MUST use the same explicit test data root,
+private runtime/temporary directories, working directory and isolated HOME/native
+Agent configuration locations. Ambient authentication environment MUST NOT be
+persisted in the entry or borrowed from the operating-system launcher. Native
+reopening MUST NOT fall through to the daily/default product profile. WebView state
+remains non-persistent while the test profile's product state survives reopening.
+
+Concurrent ordinary openings MUST NOT create a second untracked instance. Each
+new process generation MUST record its PID, native start identity and exact
+executable before business actions. Each App's deployed executables MUST preserve
+attested source bytes using distinct file identities, so concurrent Apps cannot
+redirect one another's native executable path. Observation MUST NOT launch a process.
+Ordinary application quit or explicit Pilot stop leaves the open lease's entry
+reopenable. Lease finish MUST revoke the entry before process cleanup and refuse
+subsequent openings; cleanup MUST affect only verified owned processes and deployment
+files, retaining evidence and refusing unknown/reused identities or changed artifacts.
+
+#### Scenario: Native acceptance across ordinary reopen
+
+- **WHEN** an exact-candidate App is physically selected/opened, its real daemon
+ and CLI are verified, and the application is quit then opened through its
+ ordinary native entry
+- **THEN** the new recorded process uses the same isolated profile without a
+ duplicate/default instance; replaced launch artifacts are refused and owner
+ retirement stops only that instance and prevents reopening
+- **AND** local fixture-process or IPC-only success cannot establish this native
+ scenario; unavailable LaunchServices/native CU leaves it unexecuted
+
## Implementation references
- [Product control journey](../../../tools/product-e2e/tests/control_shell.rs),
diff --git a/scripts/desktop-pilot.py b/scripts/desktop-pilot.py
index 90f90d5c..91908f41 100755
--- a/scripts/desktop-pilot.py
+++ b/scripts/desktop-pilot.py
@@ -4,6 +4,7 @@
import argparse
import ctypes
import hashlib
+import importlib.util
import json
import os
from pathlib import Path
@@ -601,38 +602,45 @@ def verify_process_identity(row: dict, item: dict, expected: dict) -> None:
def record_started_processes(row: dict) -> list[int]:
- members = [item for item in process_rows() if item["pgid"] == int(row["pgid"])]
+ snapshot = process_rows()
recorded = {int(item["pid"]): item for item in row.get("process_identities", [])}
- if not members:
- return []
- leader = next((item for item in members if item["pid"] == int(row["pid"])), None)
- if leader is None:
+ exited = set()
+ for _ in range(16):
+ if any(item["pid"] in exited for item in snapshot):
+ raise ValueError("an exited PID reappeared during observation")
+ members = [item for item in snapshot if item["pgid"] == int(row["pgid"])]
+ leader = next((item for item in members if item["pid"] == int(row["pid"])), None)
+ # Prove the leader before admitting any newly observed direct child.
+ members.sort(key=lambda item: item["pid"] != int(row["pid"]))
for item in members:
- expected = recorded.get(item["pid"])
- if expected is None:
- raise ValueError(
- "Desktop leader disappeared with an unrecorded group member; refusing cleanup"
- )
- verify_process_identity(row, item, expected)
- return [item["pid"] for item in members]
- if leader["pid"] not in recorded:
- identity = capture_process_identity(row, leader, "app")
- row.setdefault("process_identities", []).append(identity)
- recorded[leader["pid"]] = identity
- else:
- verify_process_identity(row, leader, recorded[leader["pid"]])
- for item in members:
- if item["pid"] == leader["pid"]:
- continue
- if item["pid"] in recorded:
- verify_process_identity(row, item, recorded[item["pid"]])
- continue
- if item["ppid"] != int(row["pid"]):
- raise ValueError("unrecorded process is not a direct child of the launched Desktop")
- identity = capture_process_identity(row, item, "daemon")
- row["process_identities"].append(identity)
- recorded[item["pid"]] = identity
- return [item["pid"] for item in members]
+ try:
+ expected = recorded.get(item["pid"])
+ if expected is not None:
+ verify_process_identity(row, item, expected)
+ continue
+ if leader is None:
+ raise ValueError(
+ "Desktop leader disappeared with an unrecorded group member; refusing cleanup"
+ )
+ role = "app" if item["pid"] == leader["pid"] else "daemon"
+ if role == "daemon" and item["ppid"] != int(row["pid"]):
+ raise ValueError("unrecorded process is not a direct child of the launched Desktop")
+ identity = capture_process_identity(row, item, role)
+ row.setdefault("process_identities", []).append(identity)
+ recorded[item["pid"]] = identity
+ except ProcessLookupError:
+ latest = process_rows()
+ if any(current["pid"] == item["pid"] for current in latest):
+ raise
+ # Native startup/exit can finish between ps and libproc. Only a
+ # confirmed absent PID may be discarded; recheck all remaining
+ # members, including newcomers, before accepting this snapshot.
+ exited.add(item["pid"])
+ snapshot = latest
+ break
+ else:
+ return [item["pid"] for item in members]
+ raise ValueError("process membership did not stabilize during observation")
def owned_process_group(row: dict, *, stopping: bool = False) -> list[int]:
@@ -715,11 +723,29 @@ def pilot_config(args: argparse.Namespace) -> int:
return 0
+def native_app_module():
+ spec = importlib.util.spec_from_file_location(
+ "pilot_native_app", Path(__file__).with_name("pilot-native-app.py"))
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def stop_session(session_path: Path, row: dict, timeout: float = 12.0, *, revoke=False):
+ if row.get("native_app"):
+ return native_app_module().stop(session_path, timeout=timeout, revoke=revoke)
+ return stop_group(row, timeout)
+
+
def start(args: argparse.Namespace) -> int:
+ if getattr(args, "native_app", False) and sys.platform != "darwin":
+ raise ValueError("--native-app requires macOS LaunchServices")
override = diagnostic_override(args.diagnostic_level)
build = verify_managed_pilot_build(args.build_run, args.app, args.source_sha)
if build["reuse_managed"] and not getattr(args, "managed_lease", None):
raise ValueError("Reusable Pilot builds must start through pilot-build start with an owner lease")
+ if getattr(args, "native_app", False) and not build["reuse_managed"]:
+ raise ValueError("Native App entries require pilot-build start with an owner lease")
app = Path(build["artifacts"]["app"]["path"])
daemon = Path(build["artifacts"]["daemon"]["path"])
process_home = None
@@ -748,6 +774,10 @@ def start(args: argparse.Namespace) -> int:
log_path = logs / "desktop-and-daemon.log"
log_descriptor = os.open(log_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ if getattr(args, "native_app", False):
+ os.close(log_descriptor)
+ return native_app_module().start(
+ args, build, root, runtime, temporary, data, working, log_path, process_home)
environment = launch_environment(runtime, temporary, data, process_home, override)
with os.fdopen(log_descriptor, "ab", buffering=0) as output:
process = subprocess.Popen(
@@ -845,7 +875,10 @@ def start(args: argparse.Namespace) -> int:
def status(args: argparse.Namespace) -> int:
session_path, row = read_session(args.session)
- members = owned_process_group(row)
+ if row.get("native_app"):
+ row, members = native_app_module().observe(session_path)
+ else:
+ members = owned_process_group(row)
socket = Path(row["socket"])
result = {
"state": "running" if members else "stopped",
@@ -855,6 +888,7 @@ def status(args: argparse.Namespace) -> int:
"identifier": row["identifier"],
"socket": str(socket),
"socket_present": socket.exists(),
+ "native_app": row.get("native_app"),
"processes": members,
"log": row["log"],
"data_root": row["data_root"],
@@ -867,8 +901,9 @@ def status(args: argparse.Namespace) -> int:
def stop(args: argparse.Namespace) -> int:
session_path, row = read_session(args.session)
- stopped = stop_group(row, args.timeout)
- remaining = owned_process_group(row)
+ stopped = stop_session(session_path, row, args.timeout)
+ _, row = read_session(str(session_path))
+ remaining = owned_process_group(row) if row["pid"] else []
if remaining:
raise RuntimeError(f"verified process group is still running after stop: {remaining}")
result = {
@@ -923,6 +958,7 @@ def build_parser() -> argparse.ArgumentParser:
"override so the isolated root's saved value applies"
),
)
+ launch.add_argument("--native-app", action="store_true", help="create an isolated macOS App that can be reopened until lease finish")
launch.add_argument("--timeout", type=float, default=240.0)
launch.set_defaults(function=start)
inspect = subparsers.add_parser("status", help="inspect one recorded session")
diff --git a/scripts/pilot-builds.py b/scripts/pilot-builds.py
index d75a0fde..d33d3ae7 100644
--- a/scripts/pilot-builds.py
+++ b/scripts/pilot-builds.py
@@ -34,7 +34,7 @@ pilot = module("desktop-pilot")
COMMAND = ["cargo", "build", "--locked", "-p", "hiroute-desktop", "-p", "hiroute-daemon",
"-p", "hiroute-cli", "--features", "hiroute-desktop/desktop-pilot",
"--bin", "hiroute-desktop", "--bin", "hirouted", "--bin", "hiroute"]
-DRIVERS = ("pilot-builds.py", "local-rust.py", "remote-rust.py", "desktop-pilot.py", "validation-report.py")
+DRIVERS = ("pilot-builds.py", "local-rust.py", "remote-rust.py", "desktop-pilot.py", "pilot-native-app.py", "validation-report.py")
VERDICTS = ("green", "red", "expected_red", "not_executed")
DEFAULT_CPA_MANIFEST = Path("apps/desktop/src-tauri/development-cpa-artifacts.v1.json")
@@ -259,6 +259,7 @@ class Builds:
expected = self.store.record_path(row["id"]).parent / "frontend-dist"
if Path(frontend["path"]) != expected or tree_digest(expected) != frontend["sha256"]:
raise ValueError("Reusable frontend content changed")
+ return build
def acquire(self, args):
cases = sorted(set(args.case))
@@ -320,13 +321,17 @@ class Builds:
checkout=row["checkout"], cases=cases, scenario="unassessed")
def start(self, args):
+ if getattr(args, "native_app", False) and sys.platform != "darwin":
+ raise ValueError("--native-app requires macOS LaunchServices")
row = self.locate(args.lease)
with self.locked(row["pilot_reuse"]["key"]), self.store.locked(row["checkout"]):
row = self.store.load(row["id"])
owner = row["pilot_leases"][args.lease]
if owner["state"] != "open" or args.case not in owner["cases"]:
raise ValueError("Closed lease or undeclared case")
- self.verify(row, row["pilot_reuse"]["recipe"])
+ build = self.verify(row, row["pilot_reuse"]["recipe"])
+ if getattr(args, "native_app", False):
+ pilot.native_app_module().staged_cpa(build)
if args.case in owner["sessions"]:
raise ValueError("Case already started; inspect its recorded session instead of duplicating it")
root = Path("/tmp").resolve() / ("hrp-" + uuid.uuid4().hex[:12])
@@ -337,6 +342,7 @@ class Builds:
"start", "--app", str(Path(row["checkout"]) / "target/debug/hiroute-desktop"),
"--build-run", row["id"], "--source-sha", row["sha"], "--root", str(root),
"--timeout", str(args.timeout),
+ *(["--native-app"] if getattr(args, "native_app", False) else []),
*(["--data-root", args.data_root] if args.data_root else []),
*(["--process-home", args.process_home] if args.process_home else [])])
launch.managed_lease = args.lease
@@ -375,7 +381,7 @@ class Builds:
_, session = pilot.read_session(entry["session"])
if session["build_run"] != row["id"] or session["source_sha"] != row["sha"]:
raise ValueError("Session belongs to another build")
- pilot.stop_group(session)
+ pilot.stop_session(Path(entry["session"]), session, revoke=True)
diagnostics = pilot.diagnostics_index(Path(session["data_root"]))
if verdict == "green":
for role in ("desktop", "daemon"):
@@ -419,6 +425,7 @@ def main():
start.add_argument("--case", required=True)
start.add_argument("--data-root")
start.add_argument("--process-home")
+ start.add_argument("--native-app", action="store_true")
start.add_argument("--timeout", type=float, default=240)
finish = sub.add_parser("finish")
finish.add_argument("--lease", required=True)
diff --git a/scripts/pilot-native-app.py b/scripts/pilot-native-app.py
new file mode 100644
index 00000000..d68d184a
--- /dev/null
+++ b/scripts/pilot-native-app.py
@@ -0,0 +1,290 @@
+#!/usr/bin/env python3
+"""Private, source-attested macOS App entry for one reusable Pilot lease."""
+import contextlib
+import hashlib
+import fcntl
+import importlib.util
+import json
+import os
+from pathlib import Path
+import plistlib
+import platform
+import shlex
+import shutil
+import stat
+import subprocess
+import sys
+import time
+
+sys.dont_write_bytecode = True
+_spec = importlib.util.spec_from_file_location("desktop_pilot", Path(__file__).with_name("desktop-pilot.py"))
+pilot = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(pilot)
+
+
+def control(session):
+ """Serialize reopen, observation and owner shutdown, without launching on observation."""
+ pilot.read_session(str(session))
+ path = session.parent / "native-control.lock"
+ descriptor = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
+ try:
+ fcntl.flock(descriptor, fcntl.LOCK_EX)
+ yield
+ finally:
+ os.close(descriptor)
+
+
+def file_identity(path):
+ info = path.lstat()
+ if path.is_symlink() or not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid():
+ raise ValueError("Native App entry must contain owned regular files")
+ return dict(path=str(path), device=info.st_dev, inode=info.st_ino,
+ mode=stat.S_IMODE(info.st_mode), size=info.st_size,
+ mtime_ns=info.st_mtime_ns, sha256=pilot.file_sha256(path))
+
+
+def staged_cpa(build):
+ """Preserve an explicitly staged CPA only when the compiled manifest pins it."""
+ source = Path(build["artifacts"]["daemon"]["path"]).with_name("cliproxyapi")
+ if not source.exists() and not source.is_symlink():
+ return None
+ artifact = pilot.executable_artifact(source)
+ result = Path(build["result"])
+ record = json.loads(result.read_text())
+ manifest_bytes = result.with_name("cpa-manifest.json").read_bytes()
+ pinned = record.get("pilot_reuse", {}).get("recipe", {}).get("cpa_manifest", {}).get("sha256")
+ if hashlib.sha256(manifest_bytes).hexdigest() != pinned:
+ raise ValueError("Staged CPA manifest does not match the compiled build input")
+ manifest = json.loads(manifest_bytes)
+ system = "macos" if sys.platform == "darwin" else sys.platform
+ machine = platform.machine().lower()
+ arch = {"arm64": "aarch64", "amd64": "x86_64"}.get(machine, machine)
+ matches = [item for item in manifest.get("artifacts", [])
+ if item.get("os") == system and item.get("arch") == arch]
+ if manifest.get("schema") != "hiroute.desktop.cpa-artifacts/v1" or len(matches) != 1:
+ raise ValueError("Staged CPA manifest has no unique native target")
+ selected = matches[0]
+ if (selected.get("binary_name") != "cliproxyapi" or selected.get("sha256") != artifact["sha256"]
+ or selected.get("size") != artifact["size"]):
+ raise ValueError("Staged CPA does not match the compiled manifest hash/size")
+ return artifact
+
+
+def verify(row, session):
+ native = row["native_app"]
+ if native["state"] != "enabled":
+ raise ValueError("Native App entry was retired; acquire a new lease")
+ for path, identity in native["directories"].items():
+ supplied = Path(path)
+ if supplied.is_symlink() or pilot.directory_identity(supplied) != identity:
+ raise ValueError("Native App directory was replaced")
+ pilot.private_directory(supplied)
+ for expected in native["files"]:
+ if file_identity(Path(expected["path"])) != expected:
+ raise ValueError("Native App launch artifact was replaced or modified")
+ for expected in native["source_artifacts"].values():
+ pilot.artifact_is_unchanged(expected)
+ for expected in row["artifacts"].values():
+ pilot.artifact_is_unchanged(expected)
+ build = pilot.verify_managed_pilot_build(
+ row["build_run"], native["source_artifacts"]["app"]["path"], row["source_sha"])
+ if build["artifacts"] != native["source_artifacts"]:
+ raise ValueError("Native App source build changed")
+ if native["source_cpa"] is not None and staged_cpa(build) != native["source_cpa"]:
+ raise ValueError("Native App staged CPA was replaced or modified")
+ record = json.loads(Path(row["build_result"]).read_text())
+ lease = record.get("pilot_leases", {}).get(native["lease"], {})
+ if lease.get("state") != "open" or not any(
+ item.get("session") == str(session) for item in lease.get("sessions", {}).values()):
+ raise ValueError("Native App no longer belongs to an open registered lease")
+ # Managed reuse records the actual merged configuration used by the compiler.
+ checkout = Path(build["checkout"])
+ overlay = json.loads((checkout / "apps/desktop/src-tauri/tauri.pilot.conf.json").read_text())
+ production = json.loads((checkout / "apps/desktop/src-tauri/tauri.conf.json").read_text())
+ windows = production["app"]["windows"]
+ for window in windows:
+ window["incognito"] = True
+ overlay["app"]["windows"] = windows
+ overlay["build"] = {"frontendDist": str(checkout / "apps/desktop/dist")}
+ expected = hashlib.sha256(json.dumps(overlay, separators=(",", ":"), sort_keys=True).encode()).hexdigest()
+ if record.get("pilot_frontend", {}).get("tauri_config_sha256") != expected:
+ raise ValueError("Native App needs an attested non-persistent WebView configuration")
+
+
+def prepare(args, build, root, runtime, temporary, data, working, log, process_home):
+ if not build["reuse_managed"] or not getattr(args, "managed_lease", None):
+ raise ValueError("Native App entries require pilot-build start with an owner lease")
+ process_home = process_home or pilot.make_subdirectory(root, "home")
+ session = root / pilot.SESSION_FILE
+ bundle = pilot.make_subdirectory(root, "HiRoute Pilot.app")
+ contents = pilot.make_subdirectory(bundle, "Contents")
+ binaries = pilot.make_subdirectory(contents, "MacOS")
+ resources = pilot.make_subdirectory(contents, "Resources")
+ artifacts = {}
+ cpa = staged_cpa(build)
+ sources = dict(build["artifacts"])
+ if cpa is not None:
+ sources["cpa"] = cpa
+ for role, source in sources.items():
+ pilot.artifact_is_unchanged(source)
+ destination = binaries / Path(source["path"]).name
+ # macOS proc_pidpath can report another name for a shared executable
+ # inode. Each App needs its own inode as well as the exact signed bytes.
+ shutil.copy2(source["path"], destination)
+ deployed = pilot.executable_artifact(destination)
+ pilot.artifact_is_unchanged(source)
+ if (deployed["sha256"] != source["sha256"] or deployed["size"] != source["size"]
+ or (deployed["device"], deployed["inode"]) == (source["device"], source["inode"])):
+ raise ValueError("Native App needs a distinct copy of the exact source artifact")
+ artifacts[role] = deployed
+ for name in ("desktop-pilot.py", "pilot-native-app.py"):
+ shutil.copyfile(Path(__file__).with_name(name), resources / name)
+ os.chmod(resources / name, 0o600)
+ launcher = binaries / "pilot-launch"
+ launcher.write_text("#!/bin/sh\nexec " + shlex.join([
+ sys.executable, "-I", "-B", str(resources / "pilot-native-app.py"), str(session)]) + "\n")
+ os.chmod(launcher, 0o700)
+ identifier = "ai.hiroute.pilot." + root.name.removeprefix("hrp-")
+ with (contents / "Info.plist").open("wb") as output:
+ plistlib.dump(dict(CFBundleIdentifier=identifier, CFBundleExecutable="pilot-launch",
+ CFBundleName="HiRoute Pilot", CFBundleDisplayName="HiRoute Pilot",
+ CFBundlePackageType="APPL", CFBundleVersion="1",
+ NSHighResolutionCapable=True), output)
+ os.chmod(contents / "Info.plist", 0o600)
+ # Only explicit, non-authentication ambient values survive a normal OS reopen.
+ environment = {key: os.environ[key] for key in ("PATH", "LANG", "LC_ALL", "LC_CTYPE", "TZ") if key in os.environ}
+ environment.update(HOME=str(process_home), XDG_RUNTIME_DIR=str(runtime), TMPDIR=str(temporary),
+ HIROUTE_DESKTOP_TEST_ROOT=str(data), CODEX_HOME=str(process_home / ".codex"),
+ CLAUDE_CONFIG_DIR=str(process_home / ".claude"), QODER_CONFIG_DIR=str(process_home / ".qoder"),
+ PI_CODING_AGENT_DIR=str(process_home / ".pi/agent"), DSH_HOME=str(process_home / ".dsh"))
+ override = pilot.diagnostic_override(args.diagnostic_level)
+ if override is not None:
+ environment[pilot.DIAGNOSTIC_LEVEL_ENV] = override
+ row = dict(schema="hiroute.desktop-pilot-session/v2", root=str(root), owner_uid=os.geteuid(),
+ created_at_unix_ms=int(time.time() * 1000), source_sha=build["source_sha"],
+ build_run=build["run_id"], build_result=build["result"], build_result_sha256=build["result_sha256"],
+ artifacts=artifacts, identifier=pilot.IDENTIFIER, socket=str(runtime / pilot.SOCKET_NAME),
+ data_root=str(data), process_home=str(process_home), runtime_root=str(runtime),
+ temporary_directory=str(temporary), working_directory=str(working), log=str(log),
+ app=artifacts["app"]["path"], daemon=artifacts["daemon"]["path"], pid=0, pgid=0,
+ process_identities=[], diagnostic_level_selection=args.diagnostic_level,
+ diagnostic_level_override=override)
+ directories = (root, runtime, temporary, data, working, process_home, log.parent,
+ bundle, contents, binaries, resources)
+ row["native_app"] = dict(bundle=str(bundle), bundle_identifier=identifier, state="enabled",
+ lease=args.managed_lease, generation=0, environment=environment,
+ source_artifacts=build["artifacts"], source_cpa=cpa,
+ directories={str(path): pilot.directory_identity(path) for path in directories},
+ files=[file_identity(path) for path in (launcher, contents / "Info.plist",
+ resources / "desktop-pilot.py", resources / "pilot-native-app.py")])
+ pilot.write_private_json(session, row)
+ verify(row, session)
+ return session, row
+
+
+def launch(session):
+ """LaunchServices executes this entry on every ordinary native opening."""
+ with control(session):
+ _, row = pilot.read_session(str(session))
+ verify(row, session)
+ descriptor = os.open(session.parent / "native-instance.lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
+ try:
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ os.close(descriptor)
+ return 0 # Another invocation already owns this exact isolated instance.
+ if row["pid"] and pilot.owned_process_group(row):
+ os.close(descriptor)
+ raise ValueError("Previous native instance still has owned processes")
+ socket = Path(row["socket"])
+ if socket.exists():
+ info = socket.lstat()
+ if not stat.S_ISSOCK(info.st_mode) or info.st_uid != os.geteuid():
+ raise ValueError("Refusing an unowned or non-socket Pilot path")
+ socket.unlink()
+ if os.getpgrp() != os.getpid():
+ os.setsid()
+ row.update(pid=os.getpid(), pgid=os.getpid(), process_identities=[dict(
+ pid=os.getpid(), role="app", start_time=pilot.process_start_time(os.getpid()), executable=row["app"])])
+ row["native_app"]["generation"] += 1
+ pilot.write_private_json(session, row)
+ # Held by Desktop (and any inheriting children) until this launch exits.
+ os.set_inheritable(descriptor, True)
+ environment = row["native_app"]["environment"]
+ os.chdir(row["working_directory"])
+ output = os.open(row["log"], os.O_WRONLY | os.O_APPEND | os.O_NOFOLLOW)
+ os.dup2(output, 1)
+ os.dup2(output, 2)
+ os.close(output)
+ null = os.open(os.devnull, os.O_RDONLY)
+ os.dup2(null, 0)
+ os.close(null)
+ # The control descriptor closes on exec. Readers cannot observe the
+ # short Python-to-Desktop transition as an executable identity mismatch.
+ os.execve(row["app"], [row["app"]], environment)
+
+
+def observe(session):
+ with control(session):
+ _, row = pilot.read_session(str(session))
+ if not row["pid"]:
+ return row, []
+ members = pilot.record_started_processes(row)
+ pilot.write_private_json(session, row)
+ return row, members
+
+
+def stop(session, *, timeout=12.0, revoke=False):
+ with control(session):
+ _, row = pilot.read_session(str(session))
+ if revoke:
+ row["native_app"]["state"] = "retired"
+ pilot.write_private_json(session, row)
+ stopped = []
+ if row["pid"]:
+ pilot.record_started_processes(row)
+ pilot.write_private_json(session, row)
+ stopped = pilot.stop_group(row, timeout)
+ if revoke:
+ # Retired bundles keep metadata/logs, not private executable copies
+ # after the last lease's managed checkout cleanup.
+ for artifact in row["artifacts"].values():
+ path = Path(artifact["path"])
+ if path.exists() or path.is_symlink():
+ pilot.artifact_is_unchanged(artifact)
+ path.unlink()
+ row["native_app"]["deployment_removed"] = True
+ pilot.write_private_json(session, row)
+ return stopped
+
+
+def start(args, build, root, runtime, temporary, data, working, log, process_home):
+ session, row = prepare(args, build, root, runtime, temporary, data, working, log, process_home)
+ try:
+ subprocess.run(["/usr/bin/open", "-n", row["native_app"]["bundle"]], check=True, timeout=30)
+ deadline = time.monotonic() + args.timeout
+ while time.monotonic() < deadline:
+ row, members = observe(session)
+ socket = Path(row["socket"])
+ if members and socket.exists():
+ info = socket.lstat()
+ if not stat.S_ISSOCK(info.st_mode) or info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o600:
+ raise ValueError("Pilot socket must be owned by this user with mode 0600")
+ if any(item["role"] == "daemon" for item in row["process_identities"]):
+ print(json.dumps(dict(row, state="ready", session=str(session),
+ diagnostics=pilot.diagnostics_index(data)), sort_keys=True))
+ return 0
+ time.sleep(0.1)
+ raise TimeoutError(f"Native App did not become ready; inspect {session} and {log}")
+ except BaseException:
+ stop(session, revoke=True)
+ raise
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(launch(Path(sys.argv[1])))
+ except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
+ print(str(error), file=sys.stderr)
+ sys.exit(2)
diff --git a/scripts/test-desktop-pilot.py b/scripts/test-desktop-pilot.py
index 5f76446a..6948b162 100644
--- a/scripts/test-desktop-pilot.py
+++ b/scripts/test-desktop-pilot.py
@@ -117,6 +117,54 @@ class ProcessOwnershipTests(unittest.TestCase):
def executable(self, pid):
return {101: self.app, 102: self.daemon}[pid]
+ def test_observation_rechecks_after_short_lived_child_exits(self):
+ app = self.member(101, 1, 101)
+ transient = self.member(103, 101, 101)
+ daemon = self.member(102, 101, 101)
+ self.row["process_identities"] = self.row["process_identities"][:1]
+ def executable(pid):
+ if pid == 103:
+ raise ProcessLookupError("exited during identity read")
+ return self.executable(pid)
+ with mock.patch.object(pilot, "process_rows", side_effect=[[app, transient], [app, daemon]]), \
+ mock.patch.object(pilot, "process_start_time", side_effect=self.start_time), \
+ mock.patch.object(pilot, "process_executable", side_effect=executable):
+ self.assertEqual(pilot.record_started_processes(self.row), [101, 102])
+ self.assertEqual(self.row["process_identities"][1:], [{
+ "pid": 102, "role": "daemon", "start_time": "daemon-start", "executable": str(self.daemon),
+ }])
+
+ def test_observation_never_ignores_a_still_present_unresolved_pid(self):
+ app = self.member(101, 1, 101)
+ transient = self.member(103, 101, 101)
+ for latest in ([app, transient], [app, self.member(103, 1, 999)]):
+ with self.subTest(latest=latest), \
+ mock.patch.object(pilot, "process_rows", side_effect=[[app, transient], latest]), \
+ mock.patch.object(pilot, "process_start_time", side_effect=self.start_time), \
+ mock.patch.object(pilot, "process_executable", side_effect=[self.app, ProcessLookupError("unresolved")]):
+ with self.assertRaisesRegex(ProcessLookupError, "unresolved"):
+ pilot.record_started_processes(self.row)
+
+ def test_observation_refuses_a_confirmed_exited_pid_reappearing(self):
+ app = self.member(101, 1, 101)
+ first = self.member(103, 101, 101)
+ second = self.member(104, 101, 101)
+ with mock.patch.object(pilot, "process_rows", side_effect=[[app, first], [app, second], [app, first]]), \
+ mock.patch.object(pilot, "process_start_time", side_effect=self.start_time), \
+ mock.patch.object(pilot, "process_executable", side_effect=[self.app, ProcessLookupError(), self.app, ProcessLookupError()]):
+ with self.assertRaisesRegex(ValueError, "exited PID reappeared"):
+ pilot.record_started_processes(self.row)
+
+ def test_observation_rechecks_new_members_after_confirmed_exit(self):
+ app = self.member(101, 1, 101)
+ transient = self.member(103, 101, 101)
+ unknown = self.member(104, 999, 101)
+ with mock.patch.object(pilot, "process_rows", side_effect=[[app, transient], [app, unknown]]), \
+ mock.patch.object(pilot, "process_start_time", side_effect=self.start_time), \
+ mock.patch.object(pilot, "process_executable", side_effect=[self.app, ProcessLookupError("exited"), self.app]):
+ with self.assertRaisesRegex(ValueError, "not a direct child"):
+ pilot.record_started_processes(self.row)
+
def test_pid_reuse_refuses_signal(self):
members = [self.member(101, 1, 101)]
with mock.patch.object(pilot, "process_rows", return_value=members), mock.patch.object(
diff --git a/scripts/test-pilot-builds.py b/scripts/test-pilot-builds.py
index 0e3bb873..9ce36712 100644
--- a/scripts/test-pilot-builds.py
+++ b/scripts/test-pilot-builds.py
@@ -394,6 +394,33 @@ print('fixture build completed')
self.assertEqual(len(list((self.store.root / 'runs').iterdir())), 1)
self.assertEqual(len(list((self.store.root / 'checkouts').iterdir())), 0)
+ def test_native_platform_preflight_does_not_register_an_unfinishable_session(self):
+ result = self.acquire()
+ args = types.SimpleNamespace(lease=result['lease'], case='model', timeout=1,
+ data_root=None, process_home=None, native_app=True)
+ with patch.object(m.sys, 'platform', 'linux'), patch.object(m.pilot, 'start') as launch:
+ with self.assertRaisesRegex(ValueError, 'requires macOS'):
+ self.manager.start(args)
+ launch.assert_not_called()
+ owner = self.manager.locate(result['lease'])['pilot_leases'][result['lease']]
+ self.assertEqual(owner['sessions'], {})
+ self.assertEqual(self.finish(result)['cleanup'], 'removed')
+
+ def test_native_cpa_preflight_does_not_register_an_unfinishable_session(self):
+ result = self.acquire()
+ sidecar = Path(result['checkout']) / 'target/debug/cliproxyapi'
+ sidecar.write_text('unattested fixture sidecar')
+ sidecar.chmod(0o700)
+ args = types.SimpleNamespace(lease=result['lease'], case='model', timeout=1,
+ data_root=None, process_home=None, native_app=True)
+ with patch.object(m.sys, 'platform', 'darwin'), patch.object(m.pilot, 'start') as launch:
+ with self.assertRaisesRegex(ValueError, 'no unique native target'):
+ self.manager.start(args)
+ launch.assert_not_called()
+ owner = self.manager.locate(result['lease'])['pilot_leases'][result['lease']]
+ self.assertEqual(owner['sessions'], {})
+ self.assertEqual(self.finish(result)['cleanup'], 'removed')
+
def test_raw_pilot_start_cannot_create_unregistered_session(self):
result = self.acquire()
args = m.pilot.build_parser().parse_args(['start', '--build-run', result['build_run'],
diff --git a/scripts/test-pilot-native-app.py b/scripts/test-pilot-native-app.py
new file mode 100644
index 00000000..8781dfe3
--- /dev/null
+++ b/scripts/test-pilot-native-app.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python3
+"""Real local process/entry regressions with fixture executables, not macOS CU acceptance."""
+import hashlib
+import importlib.util
+import json
+import os
+import platform
+import sys
+from pathlib import Path
+import shutil
+import signal
+import subprocess
+import tempfile
+import time
+import types
+import unittest
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location('native', Path(__file__).with_name('pilot-native-app.py'))
+native = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(native)
+pilot = native.pilot
+
+FIXTURE = r'''
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+volatile sig_atomic_t stopping = 0;
+void stop(int sig) { stopping = 1; }
+int main(int argc, char **argv) {
+ signal(SIGTERM, stop);
+ if (argc > 1) { while (!stopping) pause(); return 0; }
+ char sibling[4096]; snprintf(sibling, sizeof(sibling), "%s", argv[0]);
+ char *slash = strrchr(sibling, '/'); strcpy(slash + 1, "hirouted");
+ pid_t child = fork();
+ if (!child) { execl(sibling, sibling, "--daemon", NULL); _exit(2); }
+ char evidence[4096]; snprintf(evidence, sizeof(evidence), "%s/observed", getenv("HIROUTE_DESKTOP_TEST_ROOT"));
+ FILE *out = fopen(evidence, "a");
+ fprintf(out, "%s\n%s\n%s\n%s\n", getenv("HOME"), getenv("HIROUTE_DESKTOP_TEST_ROOT"),
+ getenv("CODEX_HOME"), getenv("OPENAI_API_KEY") ? "credential-leaked" : "no-credential");
+ fclose(out);
+ while (!stopping) pause();
+ kill(child, SIGTERM); waitpid(child, NULL, 0); return 0;
+}
+'''
+
+
[email protected](shutil.which('cc'), 'a C compiler is required for real fixture process identity')
+class NativeEntry(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.compiler_temp = tempfile.TemporaryDirectory()
+ cls.binary = Path(cls.compiler_temp.name) / 'fixture'
+ subprocess.run(['cc', '-x', 'c', '-', '-o', str(cls.binary)], input=FIXTURE, text=True, check=True)
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.compiler_temp.cleanup()
+
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.base = Path(self.temp.name).resolve()
+ self.account = self.base / 'account'
+ self.account.mkdir(mode=0o700)
+ self.state = self.account / '.cache/hiroute/local-rust'
+ self.run = 'b' * 32
+ checkout = self.state / 'checkouts' / self.run
+ debug = checkout / 'target/debug'
+ debug.mkdir(parents=True)
+ result_dir = self.state / 'runs' / self.run
+ result_dir.mkdir(parents=True)
+ for directory in (self.state, self.state / 'runs', self.state / 'checkouts', result_dir):
+ directory.chmod(0o700)
+ configs = checkout / 'apps/desktop/src-tauri'
+ configs.mkdir(parents=True)
+ (configs / 'tauri.conf.json').write_text(json.dumps({'app': {'windows': [{'label': 'main'}]}}))
+ overlay = {'app': {'windows': [{'label': 'main', 'incognito': True}]}}
+ (configs / 'tauri.pilot.conf.json').write_text(json.dumps({'app': {}}))
+ overlay['build'] = {'frontendDist': str(checkout / 'apps/desktop/dist')}
+ (checkout / '.gitignore').write_text('target/\n')
+ def git(*args):
+ return subprocess.check_output(['git', '-C', str(checkout), *args], text=True).strip()
+ git('init', '-q')
+ git('config', 'user.name', 'Fixture')
+ git('config', 'user.email', '[email protected]')
+ git('config', 'core.hooksPath', '/dev/null')
+ git('add', '.')
+ git('commit', '-qm', 'fixture')
+ sha = git('rev-parse', 'HEAD')
+ for name in ('hiroute-desktop', 'hirouted', 'hiroute'):
+ shutil.copyfile(self.binary, debug / name)
+ (debug / name).chmod(0o700)
+ self.root = self.base / 'hrp-native'
+ self.root.mkdir(mode=0o700)
+ self.session = self.root / 'session.json'
+ self.record = dict(id=self.run, kind='managed', checkout=str(checkout), sha=sha,
+ command=['cargo', 'build', '--locked', '-p', 'hiroute-desktop', '-p', 'hiroute-daemon',
+ '-p', 'hiroute-cli', '--features', 'hiroute-desktop/desktop-pilot',
+ '--bin', 'hiroute-desktop', '--bin', 'hirouted', '--bin', 'hiroute'],
+ status='terminal', process_exit=0, keep=True, scenario='unassessed',
+ identity=pilot.directory_identity(checkout), target_identity=pilot.directory_identity(debug.parent),
+ debug_identity=pilot.directory_identity(debug), pilot_reuse={'fixture': True},
+ pilot_frontend={'tauri_config_sha256': hashlib.sha256(json.dumps(
+ overlay, separators=(',', ':'), sort_keys=True).encode()).hexdigest()},
+ pilot_leases={'lease': {'state': 'open', 'sessions': {'case': {'session': str(self.session)}}}})
+ self.record_path = result_dir / 'result.json'
+ self.save_record()
+ self.patch = patch.object(pilot, 'LOCAL_RUST_ROOT', self.state)
+ self.patch.start()
+ self.addCleanup(self.patch.stop)
+ self.build = pilot.verify_managed_pilot_build(self.run, str(debug / 'hiroute-desktop'), sha)
+ self.prepare_entry()
+ self.processes = []
+ self.addCleanup(self.cleanup_processes)
+
+ def prepare_entry(self):
+ directories = {name: pilot.make_subdirectory(self.root, name) for name in ('runtime', 'tmp', 'data', 'working', 'logs')}
+ log = directories['logs'] / 'desktop.log'
+ log.touch(mode=0o600)
+ with patch.dict(os.environ, {'OPENAI_API_KEY': 'fixture-secret'}):
+ self.session, self.row = native.prepare(
+ types.SimpleNamespace(managed_lease='lease', diagnostic_level='debug'), self.build, self.root,
+ directories['runtime'], directories['tmp'], directories['data'], directories['working'], log, None)
+
+ def save_record(self):
+ self.record_path.write_text(json.dumps(self.record))
+
+ def cleanup_processes(self):
+ for process in self.processes:
+ if process.poll() is None:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=5)
+ for stream in (process.stdout, process.stderr):
+ if stream is not None:
+ stream.close()
+
+ def open_entry(self):
+ environment = dict(os.environ, HOME=str(self.account), OPENAI_API_KEY='fixture-secret')
+ process = subprocess.Popen([str(Path(self.row['native_app']['bundle']) / 'Contents/MacOS/pilot-launch')],
+ env=environment, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ self.processes.append(process)
+ return process
+
+ def ready(self):
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ row, members = native.observe(self.session)
+ if len(members) == 2 and (Path(row['data_root']) / 'observed').exists():
+ return row
+ time.sleep(0.02)
+ self.fail('Fixture process did not become ready')
+
+ def test_plain_reopen_retains_profile_and_owner_cleanup_only_stops_this_instance(self):
+ unrelated = subprocess.Popen(['sleep', '60'], start_new_session=True)
+ self.processes.append(unrelated)
+ first = self.open_entry()
+ row = self.ready()
+ self.assertEqual(row['pid'], first.pid)
+ data = Path(row['data_root'])
+ (data / 'retained-setting').write_text('same-profile')
+ self.assertEqual((data / 'observed').read_text().splitlines(), [row['process_home'], row['data_root'],
+ str(Path(row['process_home']) / '.codex'), 'no-credential'])
+ # Duplicate ordinary open cannot create a second Desktop or advance generation.
+ duplicate = self.open_entry()
+ self.assertEqual(duplicate.wait(timeout=10), 0)
+ self.assertEqual(native.observe(self.session)[0]['native_app']['generation'], 1)
+ # A normal application exit leaves the entry reusable. Observation never launches.
+ os.kill(first.pid, signal.SIGTERM)
+ first.wait(timeout=5)
+ self.assertEqual(native.observe(self.session)[1], [])
+ self.assertEqual(native.observe(self.session)[0]['native_app']['generation'], 1)
+ second = self.open_entry()
+ row = self.ready()
+ self.assertEqual(row['pid'], second.pid)
+ self.assertEqual(row['native_app']['generation'], 2)
+ self.assertEqual((data / 'retained-setting').read_text(), 'same-profile')
+ self.assertEqual((data / 'observed').read_text().splitlines()[-4:], [row['process_home'], row['data_root'],
+ str(Path(row['process_home']) / '.codex'), 'no-credential'])
+ native.stop(self.session)
+ second.wait(timeout=5)
+ self.assertEqual(native.observe(self.session)[0]['native_app']['state'], 'enabled')
+ third = self.open_entry()
+ self.ready()
+ pilot.stop_session(self.session, row, revoke=True)
+ third.wait(timeout=5)
+ self.assertFalse(Path(row["app"]).exists())
+ self.assertTrue(Path(self.build["artifacts"]["app"]["path"]).is_file())
+ refused = self.open_entry()
+ self.assertEqual(refused.wait(timeout=10), 2)
+ self.assertIn(b'retired', refused.stderr.read())
+ self.assertIsNone(unrelated.poll())
+ self.assertEqual(native.observe(self.session)[1], [])
+
+ def test_replaced_deployed_artifact_refused_before_first_launch(self):
+ artifact = Path(self.row['app'])
+ artifact.unlink()
+ shutil.copyfile(self.binary, artifact)
+ artifact.chmod(0o700)
+ refused = self.open_entry()
+ self.assertEqual(refused.wait(timeout=10), 2)
+ self.assertIn(b'replaced or modified', refused.stderr.read())
+ self.assertEqual(native.observe(self.session)[0]['pid'], 0)
+
+ def test_replaced_source_artifact_and_modified_wrapper_refused(self):
+ for path in (Path(self.build['artifacts']['cli']['path']),
+ Path(self.row['native_app']['bundle']) / 'Contents/Info.plist'):
+ with self.subTest(path=path.name):
+ original = path.read_bytes()
+ original_times = (path.stat().st_atime_ns, path.stat().st_mtime_ns)
+ path.write_bytes(original + b'changed')
+ refused = self.open_entry()
+ self.assertEqual(refused.wait(timeout=10), 2)
+ self.assertEqual(native.observe(self.session)[0]['pid'], 0)
+ path.write_bytes(original)
+ os.utime(path, ns=original_times)
+
+ def test_two_native_apps_keep_distinct_executable_identities_and_retire_independently(self):
+ first_session = self.session
+ self.open_entry()
+ first = self.ready()
+ self.root = self.base / 'hrp-other'
+ self.root.mkdir(mode=0o700)
+ self.session = self.root / 'session.json'
+ self.record['pilot_leases']['lease']['sessions']['other'] = {'session': str(self.session)}
+ self.save_record()
+ self.prepare_entry()
+ for role, source in self.build['artifacts'].items():
+ one, two = first['artifacts'][role], self.row['artifacts'][role]
+ self.assertEqual(len({source['inode'], one['inode'], two['inode']}), 3)
+ self.assertEqual(source['sha256'], one['sha256'])
+ self.assertEqual(source['sha256'], two['sha256'])
+ self.open_entry()
+ second = self.ready()
+ # On macOS this also exercises proc_pidpath after another App has opened.
+ self.assertEqual(native.observe(first_session)[0]['pid'], first['pid'])
+ native.stop(first_session, revoke=True)
+ self.assertEqual(native.observe(self.session)[0]['pid'], second['pid'])
+ self.assertTrue(native.observe(self.session)[1])
+ for artifact in self.build['artifacts'].values():
+ pilot.artifact_is_unchanged(artifact)
+ native.stop(self.session, revoke=True)
+ self.assertFalse(Path(first['app']).exists())
+ self.assertFalse(Path(second['app']).exists())
+
+ def test_staged_cpa_preserves_compiled_pin_and_is_retired_with_owned_entry(self):
+ source = Path(self.build['artifacts']['daemon']['path']).with_name('cliproxyapi')
+ shutil.copyfile(self.binary, source)
+ source.chmod(0o700)
+ artifact = pilot.executable_artifact(source)
+ machine = platform.machine().lower()
+ manifest = {'schema': 'hiroute.desktop.cpa-artifacts/v1', 'artifacts': [{
+ 'os': 'macos' if sys.platform == 'darwin' else sys.platform,
+ 'arch': {'arm64': 'aarch64', 'amd64': 'x86_64'}.get(machine, machine),
+ 'binary_name': 'cliproxyapi', 'sha256': artifact['sha256'], 'size': artifact['size']}]}
+ contents = json.dumps(manifest).encode()
+ self.record_path.with_name('cpa-manifest.json').write_bytes(contents)
+ self.record['pilot_reuse']['recipe'] = {'cpa_manifest': {'sha256': hashlib.sha256(contents).hexdigest()}}
+ self.save_record()
+ shutil.rmtree(self.root) # This test has not launched the owned fixture yet.
+ self.root.mkdir(mode=0o700)
+ self.prepare_entry()
+ deployed = Path(self.row['artifacts']['cpa']['path'])
+ self.assertNotEqual(deployed.stat().st_ino, source.stat().st_ino)
+ self.assertEqual(pilot.file_sha256(deployed), artifact["sha256"])
+ native.verify(self.row, self.session)
+ self.record_path.with_name('cpa-manifest.json').write_bytes(contents + b' ')
+ with self.assertRaisesRegex(ValueError, 'compiled build input'):
+ native.verify(self.row, self.session)
+ self.record_path.with_name('cpa-manifest.json').write_bytes(contents)
+ native.stop(self.session, revoke=True)
+ self.assertFalse(deployed.exists())
+ self.assertTrue(source.is_file())
+ source.write_bytes(b'replacement')
+ with self.assertRaisesRegex(ValueError, 'compiled manifest hash/size'):
+ native.staged_cpa(self.build)
+
+ def test_closed_lease_or_missing_incognito_attestation_refused(self):
+ for mutate in ('lease', 'config'):
+ with self.subTest(mutate=mutate):
+ self.record['pilot_leases']['lease']['state'] = 'closed' if mutate == 'lease' else 'open'
+ if mutate == 'config':
+ self.record['pilot_frontend']['tauri_config_sha256'] = 'wrong'
+ self.save_record()
+ refused = self.open_entry()
+ self.assertEqual(refused.wait(timeout=10), 2)
+ self.assertEqual(native.observe(self.session)[0]['pid'], 0)
+
+ def test_unknown_process_in_group_prevents_signalling(self):
+ process = self.open_entry()
+ row = self.ready()
+ # Existing strict cleanup protects against a stale/reused process identity.
+ row['process_identities'][0]['start_time'] = 'wrong'
+ pilot.write_private_json(self.session, row)
+ with self.assertRaisesRegex(ValueError, 'reused'):
+ native.stop(self.session, revoke=True)
+ self.assertIsNone(process.poll())
+ row['process_identities'][0]['start_time'] = pilot.process_start_time(process.pid)
+ pilot.write_private_json(self.session, row)
+ native.stop(self.session, revoke=True)
+ process.wait(timeout=5)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/test-plan.py b/scripts/test-plan.py
index 76f992de..f74c74ea 100644
--- a/scripts/test-plan.py
+++ b/scripts/test-plan.py
@@ -117,6 +117,7 @@ VALIDATION_TOOLING = {"scripts/validation.py", "scripts/validation-host.py", "sc
"scripts/ci-shards.py", "scripts/test-ci-shards.py",
"scripts/pilot-builds.py", "scripts/test-pilot-builds.py",
"scripts/desktop-pilot.py", "scripts/test-desktop-pilot.py",
+ "scripts/pilot-native-app.py", "scripts/test-pilot-native-app.py",
"scripts/local-rust.py", "scripts/test-local-rust.py",
"scripts/remote-rust.py", "scripts/test-remote-rust.py",
"scripts/validation-schedule.py", "scripts/test-validation-schedule.py"}
@@ -568,7 +569,7 @@ def select(paths, full=False):
if validation_tooling:
commands.extend([["python3", "scripts/" + name] for name in
("test-validation.py", "test-console-assets.py", "test-windows-dev.py", "test-validation-report.py", "test-local-rust.py", "test-remote-rust.py", "test-validation-schedule.py",
- "test-ci-run.py", "test-ci-shards.py", "test-desktop-pilot.py", "test-pilot-builds.py")])
+ "test-ci-run.py", "test-ci-shards.py", "test-desktop-pilot.py", "test-pilot-builds.py", "test-pilot-native-app.py")])
# Local script checks stay fixture-only. Actions runs this exact required case
# through the existing tooling/affected/full gate executor, never a skipped test.
if os.environ.get("GITHUB_ACTIONS") == "true" and (full or PILOT_CONSUMER_INPUTS.intersection(paths)):
diff --git a/scripts/test-test-plan.py b/scripts/test-test-plan.py
index 2fc4063e..e39c6976 100644
--- a/scripts/test-test-plan.py
+++ b/scripts/test-test-plan.py
@@ -330,6 +330,15 @@ class SelectionTests(unittest.TestCase):
self.assertTrue(mixed['rust'])
self.assertIn('daemon', mixed['groups'])
+ def test_native_pilot_entry_selects_its_process_regressions(self):
+ for path in ('scripts/pilot-native-app.py', 'scripts/test-pilot-native-app.py'):
+ with self.subTest(path=path):
+ result = plan.select([path])
+ self.assertFalse(result['rust'])
+ self.assertFalse(result['frontend'])
+ self.assertIn(['python3', 'scripts/test-pilot-native-app.py'], result['commands'])
+ self.assertIn(['python3', 'scripts/test-validation.py'], result['commands'])
+
def test_real_pilot_manifest_consumer_is_selected_only_for_applicable_ci_plans(self):
command = ['python3', 'scripts/test-pilot-builds.py', '--real-consumer']
inputs = ('scripts/pilot-builds.py', 'scripts/test-pilot-builds.py',
diff --git a/scripts/test-validation.py b/scripts/test-validation.py
index 5f42ea67..92742b0c 100644
--- a/scripts/test-validation.py
+++ b/scripts/test-validation.py
@@ -128,7 +128,7 @@ class Routing(unittest.TestCase):
m.dispatch({'desktop': target}, 'pilot-build', ['status', '--lease', 'a' * 32])
payload = json.loads(call.call_args.kwargs['input'])
self.assertEqual(payload['name'], 'desktop')
- self.assertEqual(set(payload['bundle']), {'pilot-builds.py', 'local-rust.py', 'remote-rust.py', 'desktop-pilot.py', 'validation-report.py'})
+ self.assertEqual(set(payload['bundle']), {'pilot-builds.py', 'local-rust.py', 'remote-rust.py', 'desktop-pilot.py', 'pilot-native-app.py', 'validation-report.py'})
def test_ssh_pilot_and_build_execute_same_caller_driver_instead_of_host_checkout(self):
caller = self.root / 'caller'
@@ -154,7 +154,7 @@ pilot.record('build:' + sys.argv[1])
'''
(caller / 'scripts/desktop-pilot.py').write_text(driver)
(caller / 'scripts/pilot-builds.py').write_text(build_driver)
- for name in ('local-rust.py', 'remote-rust.py', 'validation-report.py'):
+ for name in ('local-rust.py', 'remote-rust.py', 'pilot-native-app.py', 'validation-report.py'):
(caller / 'scripts' / name).write_text('# unused fixture dependency\n')
(caller / 'scripts/validation-host.py').write_text(Path(host.__file__).read_text())
stale_driver = "raise SystemExit('stale host checkout driver was executed')\n"
@@ -216,7 +216,7 @@ pilot.record('build:' + sys.argv[1])
run.assert_not_called()
def test_bundle_is_content_addressed_immutable_and_private(self):
- sources = {name: '# fixture\n' for name in ('pilot-builds.py', 'local-rust.py', 'remote-rust.py', 'desktop-pilot.py', 'validation-report.py')}
+ sources = {name: '# fixture\n' for name in ('pilot-builds.py', 'local-rust.py', 'remote-rust.py', 'desktop-pilot.py', 'pilot-native-app.py', 'validation-report.py')}
with patch.object(host.Path, 'home', return_value=self.root):
first = host.tooling_bundle(sources)
self.assertEqual(first, host.tooling_bundle(sources))
diff --git a/scripts/validation-host.py b/scripts/validation-host.py
index 7b6e499a..5d27cd2b 100644
--- a/scripts/validation-host.py
+++ b/scripts/validation-host.py
@@ -13,7 +13,7 @@ import tempfile
def tooling_bundle(sources):
- names = {"pilot-builds.py", "local-rust.py", "remote-rust.py", "desktop-pilot.py", "validation-report.py"}
+ names = {"pilot-builds.py", "local-rust.py", "remote-rust.py", "desktop-pilot.py", "pilot-native-app.py", "validation-report.py"}
if not isinstance(sources, dict) or set(sources) != names or any(not isinstance(v, str) for v in sources.values()):
raise ValueError("Incomplete Pilot tooling bundle")
key = hashlib.sha256(json.dumps(sources, sort_keys=True).encode()).hexdigest()
diff --git a/scripts/validation.py b/scripts/validation.py
index 89847a65..1faee6d3 100644
--- a/scripts/validation.py
+++ b/scripts/validation.py
@@ -121,7 +121,7 @@ def dispatch(targets, action, arguments, frontend_dist=None, dry_run=False):
return 0
if action in ("pilot", "pilot-build"):
payload["bundle"] = {name: (REPO / "scripts" / name).read_text() for name in
- ("pilot-builds.py", "local-rust.py", "remote-rust.py", "desktop-pilot.py", "validation-report.py")}
+ ("pilot-builds.py", "local-rust.py", "remote-rust.py", "desktop-pilot.py", "pilot-native-app.py", "validation-report.py")}
if target["transport"] == "local":
argv = [sys.executable, "-c", executor]
else: