"""Rendering for the human views. ``--json`` output is the protocol's own objects, unmodified: a flag that reshapes the data would mean two contracts to keep in step. The tables below are for people. """ from __future__ import annotations import json import sys from typing import Any from hhstreamd.clock import format_duration #: The honest gap. Printed wherever a value is genuinely unknown, because the #: alternative — a blank cell — reads as zero or as "no", and the three columns #: added in this milestone (``WS``, ``OUTPUT``, ``POINTER``) are unknown exactly #: when the compositor could not be asked. That is the case a reader most needs #: to be able to see. DASH = "—" def dump_json(obj: Any, stream=None) -> None: print(json.dumps(obj, indent=2, sort_keys=True), file=stream or sys.stdout) def _cell(value: Any) -> str: return DASH if value is None else str(value) def render_table(rows: list[list[str]], headers: list[str]) -> str: widths = [len(h) for h in headers] for row in rows: for i, cell in enumerate(row): widths[i] = max(widths[i], len(cell)) out = [" ".join(h.ljust(widths[i]) for i, h in enumerate(headers)).rstrip()] for row in rows: out.append(" ".join(cell.ljust(widths[i]) for i, cell in enumerate(row)).rstrip()) return "\n".join(out) def pointer_cell(session_id: str, holder: Any, *, known: bool) -> str: """The ``POINTER`` column for one row (PLAN §9). Three facts, told apart on purpose: this session holds the one cursor (``held``), somebody else does and the row says who (``held:``), or nobody does (``free``). ``known=False`` is the fourth case and prints the gap marker — the broker could not be asked who holds it, which is not the same as nobody holding it. """ if not known: return DASH if holder is None: return "free" return "held" if holder == session_id else f"held:{holder}" def render_list( sessions: list[dict[str, Any]], *, pointer_holder: Any = None, pointer_known: bool = False, ) -> str: """The default view. ``EXPIRES IN`` is on it rather than behind a flag because it is the number an agent actually needs. ``WS`` / ``OUTPUT`` / ``POINTER`` are the columns PLAN §9 asks for, and they are *after* ``PID`` rather than before it: the position of the existing columns is something callers already read (and a VM check asserts on), so the new ones are appended where nothing has to shift. There is still **no ``FG`` column** (DESIGN.md §1.4, amended): it would be a sixth narrow column carrying a tri-state almost nobody branches on, and ``status`` reports foreground in a line of its own. ``WS`` and ``OUTPUT`` earn their width differently — they are how a caller finds the container to point ``grim -o`` or a pointer verb at. ``pointer_known`` exists because the ``list`` reply carries no lease state: the holder comes from a second, read-only ``pointer.state`` call, and when that call fails the column must say *unknown* rather than *free*. """ if not sessions: return "no sessions" rows = [] for s in sessions: live = s.get("live") if live: idle = format_duration(s.get("idle_s")) expires = format_duration(s.get("expires_in_s")) if s.get("expires_in_s") is None: expires = "never" else: idle = DASH left = s.get("tombstone_expires_in_s") expires = f"(tombstone, {format_duration(left)} left)" if left is not None else DASH container = s.get("container") or {} rows.append( [ _cell(s.get("id")), _cell(s.get("app")), _cell(s.get("state")), _cell(s.get("pid")) if live else DASH, _cell(s.get("workspace")), _cell(container.get("output")), pointer_cell(str(s.get("id")), pointer_holder, known=pointer_known) if live else DASH, idle, expires, ] ) return render_table( rows, ["ID", "APP", "STATE", "PID", "WS", "OUTPUT", "POINTER", "IDLE", "EXPIRES IN"], ) def render_containers(reply: dict[str, Any]) -> str: """``session container`` with no id: every container, and every orphan. The orphan list is the reason this view exists at all. ``hh-*`` outputs with no live session are the thing a start-up scan removes, and until they are printed somewhere an operator has no way to see that the compositor is carrying render targets nobody owns. """ rows = [] for row in reply.get("containers") or []: rows.append( [ _cell(row.get("id")), _cell(row.get("app")), _cell(row.get("output")), _cell(row.get("workspace")), render_mode(row.get("mode")), _cell(row.get("state")), _cell(row.get("window")), ] ) lines = [ render_table(rows, ["ID", "APP", "OUTPUT", "WS", "MODE", "STATE", "WINDOW"]) if rows else "no containers" ] lines.append(f"compositor: {_cell(reply.get('compositor'))}") if reply.get("error"): lines.append(f" {reply['error']}") in_use = reply.get("workspaces_in_use") lines.append( "workspaces: " + (", ".join(str(w) for w in in_use) if in_use else "none in use") ) orphans = reply.get("orphans") if orphans is None: # Not `[]`: "could not look" and "looked, found none" are different # claims and only one of them is reassuring. lines.append(f"orphans: {DASH} (the compositor could not be asked)") elif orphans: lines.append( f"orphans: {len(orphans)} hh-* output(s) no live session claims: " + ", ".join(orphans) ) else: lines.append("orphans: none") return "\n".join(lines) def render_container(reply: dict[str, Any]) -> str: """``session container ID``: one session's container, and its drift.""" container = reply.get("container") lines = [f"{_cell(reply.get('id'))}"] if not container: lines.append(f" container {DASH} (this session has none)") else: lines.append( f" output {_cell(container.get('output'))}" f" workspace {_cell(container.get('workspace'))}" f" mode {render_mode(container.get('mode'))}" ) lines.append( f" state {_cell(container.get('state'))}" f" created by {_cell(container.get('created_by'))}" ) lines.extend(render_diff(reply.get("diff") or [])) return "\n".join(lines) def render_diff(diff: list[dict[str, Any]]) -> list[str]: """Where the record and the compositor disagreed, with both values. An empty diff is printed, not omitted: "the record matches the compositor" is the useful answer to ``reconcile``, and silence would be read as a verb that did nothing. """ if not diff: return [" drift none (the record matches the compositor)"] lines = [" drift"] for item in diff: if item.get("error"): lines.append(f" {item.get('id')}: {item['field']} — {item['error']}") continue lines.append( f" {item.get('id')}: {item.get('field')} " f"recorded {item.get('recorded')!r}, compositor says {item.get('observed')!r}" ) return lines def render_reconcile(reply: dict[str, Any]) -> str: """``session reconcile``, with or without an id.""" if reply.get("id"): return render_container(reply) scan = reply.get("scan") or {} lines = [ f"compositor: {'reachable' if scan.get('available') else 'unreachable'}" + (f" (signature {scan['signature']})" if scan.get("signature") else ""), ] if scan.get("error"): lines.append(f" {scan['error']}") lines.append(f"quarantine: {_cell(scan.get('quarantine'))}") # The scan's four lists carry different shapes -- `removed` is a list of # output names, the others are records -- so each is rendered rather than # printed, and `failed` is last and loudest because it is the only one that # means the compositor and the registry are still out of step. for item in scan.get("adopted") or []: lines.append(f" adopted {_scan_item(item)}") for output in scan.get("removed") or []: lines.append(f" removed {output} (no live session claimed it)") for item in scan.get("orphaned") or []: lines.append(f" orphan {_scan_item(item)}") for item in scan.get("failed") or []: lines.append(f" FAILED {_scan_item(item)}") lines.extend(render_diff(reply.get("diff") or [])) return "\n".join(lines) def _scan_item(item: Any) -> str: """One entry of a reconcile scan list, whatever shape it has.""" if not isinstance(item, dict): return str(item) return " ".join(f"{key} {value}" for key, value in item.items()) def render_mode(mode: dict[str, Any] | None) -> str: """``WIDTHxHEIGHT``, or the gap marker for a container that has no mode. A degraded container records ``None`` here rather than a size it never set, so this has to be able to say so. """ if not mode: return DASH return f"{mode.get('width')}x{mode.get('height')}" def render_bookmark(bookmark: dict[str, Any] | None) -> str: """Where the cursor is, in the words the wire uses (PLAN §6.3).""" if not isinstance(bookmark, dict): return DASH x, y = bookmark.get("x"), bookmark.get("y") if not isinstance(x, (int, float)) or not isinstance(y, (int, float)): return DASH return f"{x:.4f},{y:.4f} on {bookmark.get('output')} at {bookmark.get('at')}" def render_pointer_state(reply: dict[str, Any]) -> str: holder = reply.get("holder") buttons = reply.get("buttons") or [] lines = [ f"holder {holder if holder else 'free'}", f"lease {_cell(reply.get('lease_id'))}", # Loud, because a button left down is the one pointer failure that keeps # hurting after the lease is gone. f"buttons {', '.join(buttons) if buttons else 'none down'}", f"bookmark {render_bookmark(reply.get('bookmark'))}", f"driver {_cell(reply.get('driver'))}", ] return "\n".join(lines) def render_status(session: dict[str, Any]) -> str: live = session.get("live") lines = [ f"{session.get('id')} ({session.get('app')})", f" state {session.get('state')}" + (f" [{session.get('last_error')}]" if session.get("last_error") else ""), f" pid {_cell(session.get('pid'))} pgid {_cell(session.get('pgid'))}" f" sid {_cell(session.get('sid'))}", f" argv {' '.join(session.get('argv') or []) or DASH}", f" home {_cell(session.get('home'))}", f" created {_cell(session.get('created_at'))}", f" last activity {_cell(session.get('last_activity_at'))}" f" ({session.get('command_count', 0)} command(s) counted)", f" idle {format_duration(session.get('idle_s'))}" f" of {format_duration(session.get('idle_timeout_s'))}", f" expires in {format_duration(session.get('expires_in_s'))}" if session.get("expires_in_s") is not None else " expires in never (idle timeout disabled)", f" ready signal {_cell(session.get('ready_signal'))}", f" adopted {session.get('adopted')}", ] if not live: lines.append( f" exit code {_cell(session.get('exit_code'))}" f" detected by {_cell(session.get('exit_detected_by'))}" ) if session.get("exit_detected_by") in ("pidfd", "proc_poll", "proc_check"): lines.append(" exit code unavailable (adopted process)") compositor = session.get("compositor") or {} lines.append( f" window {_cell(compositor.get('window'))}" f" workspace {_cell(compositor.get('workspace'))}" f" foreground {_cell(compositor.get('foreground'))}" ) if compositor.get("note"): lines.append(f" {compositor['note']}") events = session.get("events") or [] if events: lines.append(" recent events") for event in events[-20:]: lines.append(f" {event.get('ts')} {event.get('event')}") return "\n".join(lines) def render_gc(result: dict[str, Any]) -> str: lines = [ f"pruned {result.get('pruned', 0)} tombstone(s), " f"reconciled {len(result.get('reconciled') or [])} session(s)", f"{result.get('live', 0)} live, {result.get('tombstones', 0)} tombstone(s) remain", ] for item in result.get("reconciled") or []: lines.append(f" {item['id']}: {item['why']}") unresolved = result.get("unresolved") or [] if unresolved: # Not a routine exit: the daemon could not establish whether these pids # are still their sessions', so it signalled nothing. Said loudly # because the application may well still be running (BUG-02 item 5). lines.append( "UNRESOLVED — identity could not be established, nothing was signalled:" ) for item in unresolved: mismatched = ", ".join(item.get("mismatched") or []) or "no usable evidence" lines.append(f" {item['id']}: {item['why']} ({mismatched})") orphans = result.get("orphans") or [] if orphans: lines.append("orphaned processes (escaped the process group AND the session id):") for item in orphans: lines.append(f" {item['id']} sid {item['sid']}: pids {item['pids']}") return "\n".join(lines) #: Error names whose failure is on the *compositor* side (exit 10), annotated #: with what that means for the session. CONTRACT-sessions.md §4 makes the #: distinction load-bearing — "the session is not lost, it keeps running in #: degraded mode" — and a message that only said "error" would leave a caller #: deciding whether to restart an application that is perfectly alive. COMPOSITOR_ERRORS = { "compositor": "the compositor or the output operation failed", "compositor_unavailable": "the compositor's IPC socket could not be reached", "no_container": "this session has no container output to aim at", "driver_unavailable": "the pointer driver is not reachable", "driver_refused": "the pointer driver refused the operation", } def render_error(reply: dict[str, Any]) -> str: """The human error, saying which side of the system failed. Three classes get a named prefix because an agent (and a person) acts differently on each: a compositor failure leaves the application running, a missing lease is fixed by acquiring one, and anything else is about the session itself. """ error = reply.get("error") or "" reason = reply.get("reason") or error if error in COMPOSITOR_ERRORS: parts = [ f"compositor error: {reason}", f" {COMPOSITOR_ERRORS[error]}; the session itself is unaffected " "and keeps running (exit 10, not a session failure)", ] elif error == "no_lease": parts = [ f"no pointer lease: {reason}", " this session does not hold the one cursor (exit 9); acquire it " "first with 'pointer acquire'", ] elif error == "pointer_busy": parts = [ f"pointer busy: {reason}", " another session holds the one cursor (exit 8); wait for it to " "release or for its lease to time out", ] else: parts = [f"error: {reason}"] if reply.get("hint"): parts.append(f"hint: {reply['hint']}") return "\n".join(parts)