The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(pm): redraw install/download progress in place on a terminal
ethernete9c7547c53e1
diff --git a/pm/cli.py b/pm/cli.pyindex a59be14c10d..a2a92d0a7e8 100644--- a/pm/cli.py+++ b/pm/cli.py@@ -8,6 +8,7 @@ import osimport shutilimport subprocessimport sys+import timefrom pathlib import Pathfrom pm.ensure import _facts, _lockfile, _store, ensure, stage_only@@ -59,28 +60,67 @@ def _fmt_bytes(n: int) -> str:return f"{n / (1024 * 1024):.1f} MiB"+def _progress_stream():+ """Stream for in-place progress, or None off a terminal. Prefer stdout;+ fall back to stderr because activate.ps1 pipes stdout through Out-Host+ while stderr stays on the console."""+ for stream in (sys.stdout, sys.stderr):+ try:+ if stream.isatty():+ return stream+ except (AttributeError, ValueError):+ continue+ return None+++def _interactive() -> bool:+ return _progress_stream() is not None++def _live_progress(name: str):"""Per-package progress for ensure(): download as % + MiB, unpack as a- phase line. Throttled to ~4 MiB steps — a slow line proves it's moving- in a piped (CI) log without flooding it (a 1 MiB tick on a 1.5 GiB- model would be ~1,500 lines)."""+ phase line. On a terminal the line redraws in place (~10 Hz); in a piped+ (CI) log each tick prints its own line, throttled to ~4 MiB steps so a+ slow line proves it's moving without flooding the log (a 1 MiB tick on a+ 1.5 GiB model would be ~1,500 lines). ``finish()`` returns the cursor to+ a clean line so the caller's status glyph starts on its own row."""last = 0+ last_time = 0.0+ stream = _progress_stream()++ def write(line: str) -> None:+ if stream is not None:+ stream.write("\r\x1b[2K" + line)+ stream.flush()+ else:+ print(line, flush=True)++ def finish() -> None:+ if stream is not None:+ stream.write("\r\x1b[2K")+ stream.flush()def report(stage: str, done: int, total: int, label: str) -> None:- nonlocal last+ nonlocal last, last_timeif stage == "unpack":last = 0- print(f" {name}: unpacking{(' ' + label) if label else ''}", flush=True)+ last_time = 0.0+ write(f" {name}: unpacking{(' ' + label) if label else ''}")returnif total <= 0:return- if done >= total or done - last >= 4 * 1024 * 1024:- last = done- print(- f" {name}: {done / total * 100:5.1f}% {_fmt_bytes(done)} / {_fmt_bytes(total)}",- flush=True,- )-+ if done < total:+ if stream is not None:+ now = time.monotonic()+ if now - last_time < 0.1:+ return+ last_time = now+ elif done - last < 4 * 1024 * 1024:+ return+ last = done+ write(f" {name}: {done / total * 100:5.1f}% {_fmt_bytes(done)} / {_fmt_bytes(total)}")++ report.finish = finish # type: ignore[attr-defined]return report@@ -90,19 +130,22 @@ def _install_names(names: list[str], target: str | None = None) -> int:failed = 0with _install_operation() as operation:for name in names:+ progress = _live_progress(name)try:if target is not None:# Cross-target staging: publish the entry, touch no facts.entry = stage_only(name, target)print(f"✓ {name} (staged for {target}: {entry.name})")else:- ensure(name, explicit=True, progress=_live_progress(name), _operation=operation)+ ensure(name, explicit=True, progress=progress, _operation=operation)if name == "python":from hermes_cli.venv_sync import publish_launcherspublish_launchers(repo_root(), create=False)+ progress.finish()print(f"✓ {name}", flush=True)except InstallError as e:+ progress.finish()print(f"✗ {e}", flush=True)failed += 1return faileddiff --git a/tests/pm/test_cli_progress.py b/tests/pm/test_cli_progress.pynew file mode 100644index 00000000000..a8acc95e711--- /dev/null+++ b/tests/pm/test_cli_progress.py@@ -0,0 +1,69 @@+"""`pm cli` progress renders in place on a terminal and line-per-tick off one."""++from __future__ import annotations++import io++from pm import cli+++def _capture(monkeypatch, *, tty: bool) -> io.StringIO:+ """Return the stream progress writes to: the live stream on a TTY, or+ stdout (via print) off one."""+ if tty:+ stream = io.StringIO()+ monkeypatch.setattr(cli, "_progress_stream", lambda: stream)+ return stream+ stdout = io.StringIO()+ monkeypatch.setattr(cli, "_progress_stream", lambda: None)+ monkeypatch.setattr(cli.sys, "stdout", stdout)+ return stdout+++def test_progress_redraws_in_place_on_a_tty(monkeypatch):+ stream = _capture(monkeypatch, tty=True)+ progress = cli._live_progress("node")+ progress("download", 0, 100 * 1024 * 1024, "")+ progress("download", 100 * 1024 * 1024, 100 * 1024 * 1024, "")+ progress.finish()+ out = stream.getvalue()+ assert "\r\x1b[2K" in out+ assert "\n" not in out # redraws, never wraps until the caller prints+ assert "100.0%" in out+++def test_progress_off_a_tty_prints_throttled_newline_lines(monkeypatch):+ stream = _capture(monkeypatch, tty=False)+ progress = cli._live_progress("node")+ progress("download", 0, 100 * 1024 * 1024, "")+ progress("download", 1 * 1024 * 1024, 100 * 1024 * 1024, "") # < 4 MiB: dropped+ progress("download", 8 * 1024 * 1024, 100 * 1024 * 1024, "")+ progress("download", 100 * 1024 * 1024, 100 * 1024 * 1024, "") # done always prints+ lines = [line for line in stream.getvalue().split("\n") if line]+ assert len(lines) == 2+ assert all("\r" not in line for line in lines)+++def test_unpack_phase_is_a_phase_line_in_both_modes(monkeypatch):+ stream = _capture(monkeypatch, tty=False)+ progress = cli._live_progress("node")+ progress("unpack", 0, 0, "1/2")+ assert "unpacking 1/2" in stream.getvalue()+++def test_progress_stream_prefers_stdout_then_stderr(monkeypatch):+ monkeypatch.setattr(cli.sys.stdout, "isatty", lambda: False)+ monkeypatch.setattr(cli.sys.stderr, "isatty", lambda: False)+ assert cli._progress_stream() is None+ monkeypatch.setattr(cli.sys.stderr, "isatty", lambda: True)+ assert cli._progress_stream() is cli.sys.stderr+ monkeypatch.setattr(cli.sys.stdout, "isatty", lambda: True)+ assert cli._progress_stream() is cli.sys.stdout+++def test_interactive_tracks_any_terminal(monkeypatch):+ monkeypatch.setattr(cli.sys.stdout, "isatty", lambda: False)+ monkeypatch.setattr(cli.sys.stderr, "isatty", lambda: False)+ assert cli._interactive() is False+ monkeypatch.setattr(cli.sys.stderr, "isatty", lambda: True)+ assert cli._interactive() is True