test(release): exercise exact native terminal packages across platforms

This commit is contained in:
Xubin Ren committed 2026-10-28 16:54:41 +08:00
1 parent 2cfb2b6d2c
commit 8ee81cc78a
5 files changed
+193 -18

No files matched your search

+10
View File
@@ -108,6 +108,15 @@ jobs:
--commit "$ACCEPTANCE_COMMIT" --gateway \
--report "$RUNNER_TEMP/native-install-report.json"
- name: Install ConPTY acceptance driver
if: runner.os == 'Windows'
run: python -m pip install --disable-pip-version-check pywinpty==3.0.5
- name: Verify packaged terminal interaction and native render latency
run: |
python tui/scripts/native_smoke.py --wheel "$ACCEPTANCE_WHEEL" \
--report "$RUNNER_TEMP/native-tui-report.json"
- name: Verify packaged upgrades and automatic service recovery
run: |
python -I scripts/verify_packaged_update.py \
@@ -123,6 +132,7 @@ jobs:
path: |
${{ runner.temp }}/native-input.json
${{ runner.temp }}/native-install-report.json
${{ runner.temp }}/native-tui-report.json
${{ runner.temp }}/packaged-update/packaged-update-report.json
${{ runner.temp }}/packaged-update/packaged-update-timings.json
${{ runner.temp }}/packaged-update/*/result.json
+2
View File
@@ -86,6 +86,8 @@ Candidate builds bundle minified JavaScript and the standalone Bun runtime with
Before release, measure TUI first-screen and Mermaid render latency on each supported target, including first and warm renders. Verify cancellation and worker restart. Retain latency distributions and record executable, ZIP and final platform-wheel sizes separately. Cross-compilation and startup probes do not replace native interactive acceptance.
Native acceptance runs `tui/scripts/native_smoke.py` against the exact input wheel. It reuses the PTY/ConPTY input, resize and terminal-restoration checks, records five first-frame samples and cold/warm Mermaid samples with system font discovery, then terminates a submitted render and verifies a fresh worker. Its small report includes wheel/executable identities and sizes; obtain ZIP sizes from that candidate's manifest. This is automated native terminal interaction with an unavailable fixture gateway, not connected-model E2E or controlled cold-OS-cache timing. The `DiagramJobs` integration tests separately cover UI-side cancellation and subsequent-job completion.
### Build the PyPI platform wheels
After `uv build` and native archive checks, from the exact release checkout:
+13 -9
View File
@@ -5,7 +5,6 @@ from __future__ import annotations
import os
import shutil
import sys
import time
from pathlib import Path
from typing import Any
@@ -54,7 +53,7 @@ def _wait_for_exit(process: Any, timeout: float) -> int:
return int(process.exitstatus or 0)
def main() -> int:
def smoke(executable: Path | None = None, *, cwd: Path = ROOT) -> float:
if os.name != "nt":
raise SystemExit("ConPTY smoke test requires Windows")
@@ -64,9 +63,10 @@ def main() -> int:
from winpty import PtyProcess # type: ignore[import-not-found]
from winpty.enums import Backend # type: ignore[import-not-found]
bun = shutil.which("bun")
if not bun:
bun = shutil.which("bun") if executable is None else None
if executable is None and not bun:
raise SystemExit("bun is required")
command = [str(executable)] if executable else [bun, str(ROOT / "src/index.ts")]
env = {
**os.environ,
"NANOBOT_TUI_WS_URL": "ws://127.0.0.1:9/ws",
@@ -84,9 +84,10 @@ def main() -> int:
}
env.pop("HERDR_ENV", None)
env.pop("HERDR_PANE_ID", None)
started = time.perf_counter()
process = PtyProcess.spawn(
[bun, "src/index.ts"],
cwd=str(ROOT),
command,
cwd=str(cwd),
env=env,
dimensions=(24, 80),
backend=Backend.ConPTY,
@@ -94,7 +95,10 @@ def main() -> int:
output: list[str] = []
try:
output.append(_wait_for(process, ENTER_ALT_SCREEN, 15))
output.append(_wait_for(process, "Ask nanobot anything", 15))
first_screen_ms = (time.perf_counter() - started) * 1000
if ENTER_ALT_SCREEN not in "".join(output):
raise AssertionError("TUI did not enter its alternate screen")
for grapheme in "abc中文🙂":
process.write(grapheme)
time.sleep(0.03)
@@ -131,8 +135,8 @@ def main() -> int:
if text.index(RESUME_COMMAND) < text.index(LEAVE_ALT_SCREEN):
raise AssertionError("TUI printed the session command before restoring the terminal")
print("ConPTY smoke test passed: Unicode input, resize, restoration, and session resume")
return 0
return first_screen_ms
if __name__ == "__main__":
sys.exit(main())
smoke()
+155
View File
@@ -0,0 +1,155 @@
"""Exercise the exact wheel's TUI without Bun/Node or a user's gateway.
Reuses the real terminal interaction smoke. Records fresh-process first-frame
and cold/warm worker samples, not cold OS-cache or connected-model latency.
Worker termination/restart is a process-boundary check; UI cancellation remains
covered by the DiagramJobs integration tests, not inferred from this probe.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
import platform
import queue
import subprocess
import tempfile
import threading
import time
from pathlib import Path
from zipfile import ZipFile
REPLY_LIMIT = 16_000_000
REQUEST = {"kind": "render", "input": {
"source": "graph TD\n A[Start] --> B{Check data}\n B -->|Pass| C[Done]",
"width": 800, "scale": 2,
"colors": {"foreground": "#202020", "muted": "#666666", "surface": "#eeeeee",
"border": "#888888", "accent": "#3366cc"},
}}
class Worker:
def __init__(self, binary: Path, directory: Path):
self.process = subprocess.Popen(
[str(binary), "--render-mermaid"], cwd=directory, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
)
self.replies: queue.Queue[bytes] = queue.Queue()
self.reader = threading.Thread(target=self.read, daemon=True)
self.reader.start()
def read(self) -> None:
assert self.process.stdout is not None
while record := self.process.stdout.readline(REPLY_LIMIT + 1):
self.replies.put(record)
if len(record) > REPLY_LIMIT:
break
self.replies.put(b"")
def send(self) -> None:
assert self.process.stdin is not None
self.process.stdin.write(json.dumps(REQUEST).encode() + b"\n")
self.process.stdin.flush()
def render(self) -> float:
started = time.perf_counter()
self.send()
record = self.replies.get(timeout=15)
if not record or len(record) > REPLY_LIMIT or not record.endswith(b"\n"):
raise AssertionError("Native worker did not return a bounded reply")
reply = json.loads(record)
if "error" in reply:
raise AssertionError(f"Native rendering failed: {reply['error']}")
image = reply["image"]
png = base64.b64decode(image["png"], validate=True)
assert png.startswith(b"\x89PNG\r\n\x1a\n")
assert 0 < image["width"] * image["height"] <= 8_000_000
assert "<text" not in image["layout"]["svg"], "Font outlines were not resolved"
return (time.perf_counter() - started) * 1000
def close(self) -> None:
if self.process.poll() is None:
self.process.terminate()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait(timeout=5)
raise AssertionError("Native worker required forced cleanup") from None
finally:
self.reader.join(timeout=5)
for pipe in (self.process.stdin, self.process.stdout):
if pipe:
pipe.close()
assert not self.reader.is_alive(), "Worker output collector survived shutdown"
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--wheel", type=Path, required=True)
parser.add_argument("--report", type=Path, required=True)
args = parser.parse_args()
wheel = args.wheel.resolve(strict=True)
report_path = args.report.resolve()
if report_path.exists():
raise ValueError("Do not overwrite prior native evidence")
with tempfile.TemporaryDirectory(prefix="nanobot-native-tui-") as temporary:
root = Path(temporary)
with ZipFile(wheel) as archive:
members = [name for name in archive.namelist()
if name.startswith("nanobot/tui/bin/nanobot-tui-")
and "/" not in name.removeprefix("nanobot/tui/bin/")
and not name.endswith((".tar.gz", ".json", ".txt"))]
if len(members) != 1:
raise ValueError("Expected one packaged native executable")
binary = root / Path(members[0]).name
binary.write_bytes(archive.read(members[0]))
binary.chmod(0o700)
commit = archive.read("nanobot/_build_commit.txt").decode().strip()
# Keep only platform identity. Never inherit daily gateway credentials,
# desktop attachment variables, config or the frontend toolchain PATH.
host = {key: value for key, value in os.environ.items()
if key.upper() in {"SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT"}}
os.environ.clear()
os.environ.update(host)
os.environ.update({"HOME": temporary, "USERPROFILE": temporary,
"TMPDIR": temporary, "TEMP": temporary, "TMP": temporary,
"XDG_CONFIG_HOME": temporary, "XDG_CACHE_HOME": temporary,
"PATH": "", "TERM": "xterm-256color", "LANG": "en_US.UTF-8"})
if os.name == "nt":
from conpty_smoke import smoke
else:
from pty_smoke import smoke
frames = [smoke(binary, cwd=root) for _ in range(5)]
worker = Worker(binary, root)
try:
renders = [worker.render() for _ in range(5)]
# Terminate a submitted request without waiting for its reply.
worker.send()
finally:
worker.close()
worker = Worker(binary, root)
try:
restarted = worker.render()
finally:
worker.close()
report = {"candidate_commit": commit, "platform": platform.system(),
"machine": platform.machine(), "wheel": wheel.name,
"wheel_sha256": hashlib.sha256(wheel.read_bytes()).hexdigest(),
"wheel_bytes": wheel.stat().st_size, "executable_bytes": binary.stat().st_size,
"executable_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(),
"first_screen_ms": frames, "render_ms_cold_then_warm": renders,
"render_after_restart_ms": restarted, "unicode_input_resize_exit": True,
"default_system_font_resolution": True, "worker_termination_restart": True,
"connected_gateway_or_model": False, "os_cache_controlled": False}
report["temporary_directory_removed"] = not root.exists()
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
+13 -9
View File
@@ -16,7 +16,6 @@ import select
import shutil
import signal
import struct
import sys
import termios
import time
from pathlib import Path
@@ -72,12 +71,13 @@ def _wait_for_exit(pid: int, timeout: float) -> int:
raise AssertionError("TUI did not exit after the exit command")
def main() -> int:
def smoke(executable: Path | None = None, *, cwd: Path = ROOT) -> float:
if os.name != "posix":
raise SystemExit("PTY smoke test requires POSIX")
bun = shutil.which("bun")
if not bun:
bun = shutil.which("bun") if executable is None else None
if executable is None and not bun:
raise SystemExit("bun is required")
command = [str(executable)] if executable else [bun, str(ROOT / "src/index.ts")]
env = {
**os.environ,
"NANOBOT_TUI_WS_URL": "ws://127.0.0.1:9/ws",
@@ -95,16 +95,20 @@ def main() -> int:
env.pop("HERDR_ENV", None)
env.pop("HERDR_PANE_ID", None)
started = time.perf_counter()
pid, master = pty.fork()
if pid == 0:
os.chdir(ROOT)
os.execvpe(bun, [bun, "src/index.ts"], env)
os.chdir(cwd)
os.execvpe(command[0], command, env)
output = bytearray()
reaped = False
try:
_resize(master, 24, 80)
output.extend(_wait_for(master, ENTER_ALT_SCREEN, 10))
output.extend(_wait_for(master, b"Ask nanobot anything", 10))
first_screen_ms = (time.perf_counter() - started) * 1000
if ENTER_ALT_SCREEN not in output:
raise AssertionError("TUI did not enter its alternate screen")
# Feed committed UTF-8 one grapheme at a time. The raw terminal stream
# should contain every glyph, even though differential rendering may
@@ -164,8 +168,8 @@ def main() -> int:
if escape in output:
raise AssertionError(f"TUI painted a fixed background: {escape!r}")
print("PTY smoke test passed: Unicode input, resize, restoration, and session resume")
return 0
return first_screen_ms
if __name__ == "__main__":
sys.exit(main())
smoke()