Files
hyprland-headless-stream-pl…/src/hhstream_session/__init__.py
T
HermenixandClaude Opus 5 850f9caa1d feat(cli): session stream and start --stream
The operator's side of the four verbs: `hhstream session stream
enable|disable|list|status`, and `start --stream [--stream-phrase]
[--stream-fps]` for the one-call case.

`stream enable` prints the URL on **stdout and nothing else**, with the detail
on stderr, so `url=$(hhstream session stream enable ID)` works -- the same shape
`start` already has for the session id. `start --stream` prints the id and then
the URL, two lines, because a caller who asked for both should not have to run
a second verb for the second one.

The phrase is a credential, and the two renderers disagree on purpose:

* `render_streams` (`stream list`) does **not** show it. A listing is what ends
  up in a shared terminal, a paste or a screenshot, so what it shows is enough
  to recognise and manage a stream -- session, output, rate, viewers, `LIVE` --
  and not enough to watch one. It also prints the daemon's reachability, because
  "two records and no daemon" is a different situation from "two records and two
  captures" and the rows alone cannot say which.
* `render_stream` (`stream status ID`) does show the URL. That question was
  asked about one session by name, which is what somebody about to watch it
  does, and making them reach for `--json` for the thing the verb is for would
  be the worse trade.

When the daemon is not publishing, `status` says so and prints no URL -- the
phrase is kept, so re-enabling restores the same one.

`start --stream` that starts the session but cannot open the stream exits 0 and
says `WARNING: the session is running but its stream was not enabled: …` on
stderr. Loudly, because the exit code is the session's and a caller who asked
for a stream must not read a 0 as one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
2026-10-11 22:48:00 +00:00

1601 lines
62 KiB
Python

"""``hhstream session …`` — the CLI handlers, as a drop-in for someone else's CLI.
The integration contract is one function::
from hhstream_session import register
register(subparsers) # subparsers from argparse's add_subparsers()
...
args = parser.parse_args()
raise SystemExit(args.func(args))
``register`` adds a single ``session`` subcommand with its own verb tree, sets
``func`` (and ``hhstream_session_handler``, for hosts that dispatch on their own
attribute) to a callable taking the parsed namespace and returning an **exit
code from the frozen table** in ``DESIGN.md`` §1.6. The registrant needs to
know nothing about the daemon beyond the socket path, which comes from
``--socket`` or ``$HHSTREAM_SOCKET``.
Nothing here is imported until a ``session`` verb actually runs: the module
imports only :mod:`hhstreamd.protocol` (framing and exit codes) and the
standard library, so a host CLI pays no startup cost and gains no new failure
mode by registering it.
**The one thing to read before using this:** ``touch`` is the only mark of
activity that exists. ``list``, ``status``, ``logs``, ``gc``, ``container``,
``reconcile`` and every ``pointer`` verb deliberately do not reset a session's
idle clock, so an agent watching or driving a long-running app must call
``touch`` or the session will be reaped on schedule. Being driven is not the
same as being wanted.
The verb tree, beyond the original eight:
session container [ID] the output and workspace a session was given
session reconcile [ID] re-read them from the compositor, report drift
session pointer acquire ID take the one cursor, aimed into ID's container
session pointer move ID ... warp, --to X,Y or --by DX,DY (0..1, per output)
session pointer click/down/up/release ID
session pointer state who holds the cursor and what is pressed
session keyboard type ID TEXT one argument, raw UTF-8, no escapes
session keyboard key ID NAME tap: down then up
session keyboard down/up ID NAME
session stream enable ID publish ID's screen behind a spoken phrase
session stream disable ID stop publishing, and forget the phrase
session stream list/status what is being published, and who is watching
The pointer *and keyboard* verbs share one precondition — the pointer lease —
and the lease id lives in :mod:`hhstream_session.lease` between invocations,
because the wire requires it on every gesture and the CLI is one process per
verb. There is no ``keyboard acquire``: one ``wl_seat`` means one keyboard
focus, and the shipped ``follow_mouse = 1`` means another session's warp
retargets the keys, so a second lease would let session B move the pointer
while session A believed it was typing into its own window.
"""
from __future__ import annotations
import argparse
import sys
import time
from typing import Any, Callable
from hhstreamd.clock import format_duration, parse_duration
from hhstreamd.protocol import ExitCode
from . import format as fmt
from . import lease
from .client import DEFAULT_SOCKET, ENV_SOCKET, ClientError, call, reply_exit_code
__all__ = ["register", "build_parser", "dispatch", "main", "ExitCode"]
#: Printed under `session --help` and under `start --help`. It is here, in two
#: places, because it is the single fact an agent gets wrong.
ACTIVITY_NOTE = (
"ACTIVITY: 'touch' is the ONLY thing that resets a session's idle clock. "
"'list', 'status', 'logs' and 'gc' do NOT count — if polling kept sessions "
"alive, an abandoned session would never be reaped. An agent that leaves an "
"app running must call 'hhstream session touch <id>' before the idle timeout "
"expires."
)
_FOLLOW_INTERVAL_S = 0.5
# --------------------------------------------------------------------------
# registration
# --------------------------------------------------------------------------
def register(subparsers: Any, *, name: str = "session") -> argparse.ArgumentParser:
"""Add the ``session`` namespace to an existing argparse subparser set.
Returns the namespace's parser, so a host that wants to add to it can.
"""
parser = subparsers.add_parser(
name,
help="manage tracked application sessions (needs the hhstream session daemon)",
description="Start, inspect, keep alive and kill tracked application sessions.",
epilog=ACTIVITY_NOTE,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
_build_namespace(parser)
return parser
def _socket_parent() -> argparse.ArgumentParser:
"""Shared ``--socket`` so it may be given before *or* after the verb.
``SUPPRESS`` matters: without it the verb-level default would overwrite a
value given at the namespace level.
"""
common = argparse.ArgumentParser(add_help=False)
common.add_argument(
"--socket",
default=argparse.SUPPRESS,
metavar="PATH",
help=f"control socket (default: ${ENV_SOCKET} or {DEFAULT_SOCKET})",
)
return common
def _build_namespace(parser: argparse.ArgumentParser) -> None:
common = _socket_parent()
parser.add_argument(
"--socket",
default=None,
metavar="PATH",
help=f"control socket (default: ${ENV_SOCKET} or {DEFAULT_SOCKET})",
)
# `hhstream session` with no verb lists, because that is what everyone
# types first.
parser.set_defaults(func=_cmd_list, hhstream_session_handler=_cmd_list, all=False, json=False)
verbs = parser.add_subparsers(dest="session_verb", metavar="VERB")
def add(name: str, handler: Callable[[argparse.Namespace], int], **kwargs: Any):
sub = verbs.add_parser(name, parents=[common], **kwargs)
sub.set_defaults(func=handler, hhstream_session_handler=handler)
sub.add_argument("--json", action="store_true", help="emit the protocol object on stdout")
return sub
# ---- start -------------------------------------------------------
start = add(
"start",
_cmd_start,
help="launch an allowlisted application as a tracked session",
description=(
"Launch an allowlisted application. Prints the bare session id on "
"stdout and human-readable detail on stderr, so $(hhstream session "
"start foo) is the id and nothing else.\n\n"
"Everything after a literal -- is passed to the application as an "
"argv list: 'session start chromium -- --new-window URL'."
),
epilog=ACTIVITY_NOTE,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
start.add_argument("app", help="an app name from the daemon's allowlist, never a path")
start.add_argument(
"argv",
nargs="*",
metavar="-- ARGV...",
help="arguments for the application, after a literal --. Passed as an "
"argv list; there is never a shell.",
)
start.add_argument(
"--idle-timeout",
type=_duration,
metavar="DURATION",
help="reap the session after this long with no 'touch' (e.g. 30s, 5m, 3h)",
)
start.add_argument(
"--wait-ready",
type=_duration,
metavar="DURATION",
help="how long to wait for the app to signal readiness",
)
home = start.add_mutually_exclusive_group()
home.add_argument(
"--home", metavar="PATH", help="run the app with this HOME instead of the inherited one"
)
home.add_argument(
"--ephemeral-home",
action="store_true",
help="give the session a private HOME and delete it when the session ends "
"(opt-in; by default the app inherits the real home directory)",
)
start.add_argument(
"--request-id",
metavar="ID",
help="deduplication token: retrying a start with the same id returns the "
"original reply instead of launching a second application",
)
start.add_argument(
"--stream",
action="store_true",
help="also enable a live stream for this session and print its URL. "
"Needs the session's container output, which this creates — which is "
"why it is a flag here rather than a second command you have to "
"sequence yourself.",
)
start.add_argument(
"--stream-phrase",
metavar="PHRASE",
help="use this phrase instead of a minted one (four words and a "
"five-character tail). It is the stream's only credential, so it is "
"held to exactly that shape.",
)
start.add_argument(
"--stream-fps",
type=int,
metavar="N",
help="frames per second for the stream (default: the broker's)",
)
start.add_argument(
"--no-container",
action="store_true",
help="start without a container (NOT IMPLEMENTED: the broker's 'start' "
"verb carries no such field — see the message it refuses with)",
)
# ---- list --------------------------------------------------------
lst = add("list", _cmd_list, help="list sessions (does NOT count as activity)")
lst.add_argument("--all", action="store_true", help="include tombstones of ended sessions")
# ---- status ------------------------------------------------------
status = add("status", _cmd_status, help="show one session (does NOT count as activity)")
status.add_argument("id", help="session id")
status.add_argument(
"--events", type=int, default=20, metavar="N", help="recent audit events to include"
)
# ---- touch -------------------------------------------------------
add(
"touch",
_cmd_touch,
help="reset the idle clock — THE ONLY MARK OF ACTIVITY",
description=(
"Reset the session's idle clock. Injects nothing, changes nothing "
"else, and is the only verb that counts as activity: an agent "
"observing a long-running application has no other way to say "
"'still working'."
),
epilog=ACTIVITY_NOTE,
formatter_class=argparse.RawDescriptionHelpFormatter,
).add_argument("id", help="session id")
# ---- kill --------------------------------------------------------
kill = add("kill", _cmd_kill, help="terminate a session and everything it spawned")
kill.add_argument("id", help="session id")
kill.add_argument(
"--grace",
type=_duration,
metavar="DURATION",
help="how long to wait after the first signal before SIGKILL (default: the daemon's)",
)
kill.add_argument(
"--signal", default="TERM", metavar="SIG", help="first signal to send (default: TERM)"
)
kill.add_argument("--request-id", metavar="ID", help="deduplication token")
# ---- gc ----------------------------------------------------------
add(
"gc",
_cmd_gc,
help="prune tombstones and reconcile the registry with /proc "
"(does NOT count as activity)",
).add_argument("--request-id", metavar="ID", help="deduplication token")
# ---- adopt -------------------------------------------------------
adopt = add("adopt", _cmd_adopt, help="bring an already-running process under management")
adopt.add_argument("--pid", type=int, required=True, help="pid to adopt")
adopt.add_argument("--app", help="name to record (default: the executable's basename)")
adopt.add_argument("--idle-timeout", type=_duration, metavar="DURATION")
adopt.add_argument("--request-id", metavar="ID", help="deduplication token")
# ---- logs --------------------------------------------------------
logs = add(
"logs",
_cmd_logs,
help="the application's captured stdout/stderr (does NOT count as activity)",
)
logs.add_argument("id", help="session id")
logs.add_argument("--lines", type=int, default=100, metavar="N", help="tail this many lines")
logs.add_argument(
"--follow", "-f", action="store_true", help="keep printing new output until interrupted"
)
# ---- container ---------------------------------------------------
container = add(
"container",
_cmd_container,
help="the output and workspace a session was given "
"(does NOT count as activity)",
description=(
"Show one session's container -- the output, workspace and mode the "
"broker created for it -- or, with no id, every container plus the "
"'hh-*' outputs no live session claims (orphans)."
),
)
container.add_argument(
"id",
nargs="?",
help="session id; omit for every container and the orphan list",
)
# ---- reconcile ---------------------------------------------------
reconcile = add(
"reconcile",
_cmd_reconcile,
help="re-read containers from the compositor and report the drift "
"(does NOT count as activity)",
description=(
"Ask the compositor where a session's window actually is and bring "
"the record up to that answer; the compositor is the authority and "
"the record is a cache of it. With no id, every live session is "
"reconciled and the start-up scan is re-run: the quarantine rule is "
"re-installed, adopted containers re-take their workspace slots, and "
"'hh-*' outputs with no live session are removed."
),
)
reconcile.add_argument("id", nargs="?", help="session id; omit for all of them")
reconcile.add_argument("--request-id", metavar="ID", help="deduplication token")
# ---- pointer -----------------------------------------------------
_build_pointer(verbs, common)
# ---- keyboard ----------------------------------------------------
_build_keyboard(verbs, common)
# ---- stream ------------------------------------------------------
_build_stream(verbs, common)
#: Button names the driver knows (``hhstream_pointer.buttons.CODES``), mirrored
#: here rather than imported: this module's whole integration promise is that it
#: imports ``hhstreamd.protocol`` and the standard library and nothing else, so
#: registering it cannot drag in the driver's Wayland dependencies. The driver
#: is still the authority -- it answers an unknown name with the set it knows --
#: and this list only buys a typo an exit 2 instead of an exit 10.
BUTTONS = ("left", "right", "middle", "side", "extra", "forward", "back", "task")
#: Axis names the driver knows (``hhstream_pointer.buttons.AXES``), mirrored for
#: the same reason and with the same caveat: the driver remains the authority.
#: Direction is the sign of the amount, so there is deliberately no "down" or
#: "up" here -- the protocol fixes positive as down (vertical) and right
#: (horizontal), and a second vocabulary over it is how a scroll ends up
#: backwards.
AXES = ("vertical", "horizontal")
def _build_pointer(verbs: Any, common: argparse.ArgumentParser) -> None:
"""``session pointer <verb>`` — the one cursor, under a lease (PLAN §6).
A nested namespace rather than seven top-level verbs because they share one
precondition that nothing else here has: the lease. Grouping them is what
makes ``pointer --help`` able to say that once.
"""
namespace = verbs.add_parser(
"pointer",
parents=[common],
help="aim and click the one cursor at a session, under a lease",
description=(
"The cursor is singular, so it is leased. 'acquire' takes it and "
"prints the lease id on stdout; the gesture verbs reuse that lease "
"and refuse (exit 9) without it; 'release' gives it back, lifting "
"anything still pressed. A lease left idle past its TTL is "
"force-released by the broker, which also lifts its buttons.\n\n"
"Coordinates are OUTPUT-NORMALISED, 0..1, within the session's own "
"container: (0,0) is its top-left corner and (1,1) its "
"bottom-right. Window-local pixel aiming is deliberately absent -- "
"the broker's IPC client carries no window geometry, so there is "
"nothing honest to convert from.\n\n"
"No pointer verb counts as activity: a session being driven is "
"still a session nobody has said they want kept. Call 'touch'."
),
epilog=ACTIVITY_NOTE,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
gestures = namespace.add_subparsers(dest="pointer_verb", metavar="VERB")
namespace.set_defaults(
func=_cmd_pointer_state, hhstream_session_handler=_cmd_pointer_state, json=False
)
def add_gesture(name: str, handler, **kwargs: Any):
sub = gestures.add_parser(name, parents=[common], **kwargs)
sub.set_defaults(func=handler, hhstream_session_handler=handler)
sub.add_argument("--json", action="store_true", help="emit the protocol object on stdout")
return sub
def with_lease(sub: argparse.ArgumentParser) -> argparse.ArgumentParser:
sub.add_argument(
"--lease",
metavar="ID",
help="the lease id from 'pointer acquire'. Omitted, the one that "
f"acquire cached is used (${lease.ENV_LEASE} overrides that).",
)
return sub
acquire = add_gesture(
"acquire",
_cmd_pointer_acquire,
help="take the cursor for a session and aim it into its container",
description=(
"Take the one cursor and warp it into this session's own output. "
"Prints the bare lease id on stdout, so $(hhstream session pointer "
"acquire ID) is the lease and nothing else, and caches it so the "
"gesture verbs below need no flag. A second acquire while someone "
"else holds it exits 8 (BUSY) naming the holder."
),
)
acquire.add_argument("id", help="session id")
acquire.add_argument(
"--ttl",
type=_duration,
metavar="DURATION",
help="idle lifetime for this lease before the broker force-releases it "
"(default: the broker's; capped by its hard maximum)",
)
acquire.add_argument(
"--no-restore",
action="store_true",
help="start at the centre of the container instead of the position this "
"session's cursor was last left at",
)
move = with_lease(add_gesture(
"move",
_cmd_pointer_move,
help="warp within the session's own output (normalised 0..1)",
description=(
"Warp the cursor inside this session's container. --to is absolute "
"and refused outside 0..1, because a caller that computed 1.4 has a "
"bug and clamping would hide it; --by is relative and IS clamped, "
"because running into the edge of the screen is what a mouse does."
),
))
move.add_argument("id", help="session id")
target = move.add_mutually_exclusive_group(required=True)
target.add_argument(
"--to", type=_point, metavar="X,Y", help="absolute, output-normalised 0..1"
)
target.add_argument(
"--by", type=_point, metavar="DX,DY", help="relative to the current bookmark"
)
click = with_lease(add_gesture(
"click",
_cmd_pointer_click,
help="press and release a button where the cursor is",
))
click.add_argument("id", help="session id")
click.add_argument(
"--button", default="left", choices=BUTTONS, metavar="B", help=_button_help()
)
scroll = with_lease(add_gesture(
"scroll",
_cmd_pointer_scroll,
help="scroll the session's screen where the cursor is",
description=(
"Scroll the session's screen. --amount is signed wheel clicks: "
"positive scrolls down (vertical) or right (horizontal), which is "
"the protocol's direction rather than a choice of ours. The cursor "
"does not move, so the resume point keeps its coordinates -- but it "
"is re-stamped, because a scroll is the session acting and a later "
"resume should know when it last did."
),
))
scroll.add_argument("id", help="session id")
scroll.add_argument(
"--axis", default="vertical", choices=AXES, metavar="A",
help="vertical (default) or horizontal",
)
scroll.add_argument(
"--amount", type=float, default=3.0, metavar="N",
help="wheel clicks, signed; positive is down/right (default: 3)",
)
for name, state in (("down", "down"), ("up", "up")):
sub = with_lease(add_gesture(
name,
_cmd_pointer_button,
help=f"hold a button {state} without releasing it"
if state == "down"
else "release a button that was held down",
description=(
"Half a click. Together with 'move' this is a drag, and the "
"lease is what makes the three calls atomic -- no other "
"session's events are interleaved. The broker lifts whatever "
"is still down on release or on a lease timeout, so a crashed "
"agent cannot leave a button pressed."
),
))
sub.set_defaults(button_state=state)
sub.add_argument("id", help="session id")
sub.add_argument(
"--button", default="left", choices=BUTTONS, metavar="B", help=_button_help()
)
release = with_lease(add_gesture(
"release",
_cmd_pointer_release,
help="give the cursor back, lifting anything still pressed",
))
release.add_argument("id", help="session id")
add_gesture(
"state",
_cmd_pointer_state,
help="who holds the cursor, and what is pressed (does NOT count as activity)",
)
#: Printed under `keyboard --help` and under every one of its verbs. It is the
#: single fact an agent gets wrong about this group, exactly as ACTIVITY_NOTE is
#: for the namespace: the keyboard has no lease of its own.
KEYBOARD_LEASE_NOTE = (
"LEASE: every keyboard verb needs the POINTER lease and refuses with exit 9 "
"until 'hhstream session pointer acquire <id>'. There is no 'keyboard "
"acquire': the compositor has one seat and one keyboard focus, and another "
"session's pointer warp would retarget the keys mid-string. 'pointer "
"release' lifts held keys as well as held buttons, and so does a lease "
"timeout."
)
def _build_keyboard(verbs: Any, common: argparse.ArgumentParser) -> None:
"""``session keyboard <verb>`` — typing into whatever the seat focuses.
A nested namespace for the same reason ``pointer`` is one: these four verbs
share a precondition nothing else here has. It is the *pointer* lease, and
saying that once in a group description is better than four times in four
help strings -- though the note is repeated per verb anyway, because
``--help`` on a leaf is what an agent actually reads.
"""
namespace = verbs.add_parser(
"keyboard",
parents=[common],
help="type into the session the seat is focused on, under the pointer lease",
description=(
"Keys go to whichever surface the compositor's one seat has focused "
"-- a virtual keyboard is seat-global and has no output argument, so "
"unlike the pointer there is nothing to aim. What aims it is the "
"pointer: 'pointer acquire' warps into the session's own container "
"and the lease is what stops another session moving focus while you "
"type.\n\n"
"NAME is an XKB keysym name, not a number: 'a', 'A', 'Return', "
"'BackSpace', 'Left', 'Control_L', 'Shift_L'. It is resolved against "
"the layout the driver uploaded (set by the operator; 'us' by "
"default), so a name that layout does not carry is exit 2.\n\n"
"TEXT is one argument of raw UTF-8 and backslash escapes are NOT "
"interpreted: a newline is a real newline in the argument and the "
"shell does the quoting. A character the layout cannot produce "
"fails the whole string and types nothing -- there is no partial "
"type.\n\n"
"No keyboard verb counts as activity, exactly as no pointer verb "
"does. Call 'touch'."
),
epilog=f"{KEYBOARD_LEASE_NOTE}\n\n{ACTIVITY_NOTE}",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
keys = namespace.add_subparsers(dest="keyboard_verb", metavar="VERB")
# With no verb, print this group's help rather than guessing: unlike
# `pointer`, there is no read-only verb here that could be the default --
# held keys are reported by `pointer state`, which is where buttons are.
namespace.set_defaults(
func=_cmd_keyboard_usage, hhstream_session_handler=_cmd_keyboard_usage, json=False
)
namespace.set_defaults(keyboard_parser=namespace)
def add_key_verb(name: str, handler, **kwargs: Any):
sub = keys.add_parser(
name,
parents=[common],
epilog=KEYBOARD_LEASE_NOTE,
formatter_class=argparse.RawDescriptionHelpFormatter,
**kwargs,
)
sub.set_defaults(func=handler, hhstream_session_handler=handler)
sub.add_argument("--json", action="store_true", help="emit the protocol object on stdout")
sub.add_argument(
"--lease",
metavar="ID",
help="the lease id from 'pointer acquire'. Omitted, the one that "
f"acquire cached is used (${lease.ENV_LEASE} overrides that).",
)
sub.add_argument("id", help="session id")
return sub
type_ = add_key_verb(
"type",
_cmd_keyboard_type,
help="type one string into the focused window",
description=(
"Type TEXT. One argument, raw UTF-8, no backslash escapes: '\n' is "
"a backslash and an n, and a newline is a newline. Capitals and "
"symbols are sent as a modifier MASK plus the letter's key, not as "
"a synthesized Shift keypress, because this compositor does not "
"derive the mask from an injected key.\n\n"
"Validation is complete before the first event: a character the "
"uploaded layout cannot produce fails the request and types "
"nothing, so there is never a half-typed prefix to clean up. On the "
"default 'us' layout that includes 'e' with an acute accent, and "
"every C0 control except newline and tab.\n\n"
"A modifier held with 'keyboard down' is a baseline: its mask is "
"ORed into every character and it is STILL HELD when this returns, "
"which is how a chord is spelled. A non-modifier key held is a "
"refusal, because the application still believes it is being held."
),
)
type_.add_argument(
"text",
help="the string to type, as ONE argument (quote it; a newline is a newline)",
)
tap = add_key_verb(
"key",
_cmd_keyboard_key,
help="tap one keysym: down then up",
description=(
"Press and release one key. This is the verb for 'Return', 'Tab', "
"'BackSpace' and the arrows -- anything 'type' cannot express "
"because it has no character."
),
)
tap.add_argument("name", help="XKB keysym name, e.g. Return, BackSpace, Left")
for verb, state in (("down", "down"), ("up", "up")):
sub = add_key_verb(
verb,
_cmd_keyboard_hold,
help=(
"hold a key down without releasing it"
if state == "down"
else "release a key that was held down"
),
description=(
"Half a tap. The justified use is a chord: 'down Control_L', "
"then 'type c', then 'up Control_L'.\n\n"
"HOLDING A NON-MODIFIER FLOODS THE WINDOW. The compositor sends "
"one key event and publishes a repeat rate; the APPLICATION "
"repeats, so a held 'a' inserts characters for as long as it is "
"down -- up to the whole lease TTL. This is not configurable "
"here: the repeats are not ours to rate-limit. Measured on this "
"build at 25/s after 600ms.\n\n"
"The broker lifts whatever is still down on 'pointer release' "
"or on a lease timeout, so a crashed agent cannot leave a key "
"held."
),
)
sub.set_defaults(key_state=state)
sub.add_argument("name", help="XKB keysym name, e.g. Control_L, Shift_L")
#: Printed under `stream --help` and under `enable`. The two facts an operator
#: gets wrong about this group, and they pull in opposite directions: the
#: phrase is a password, and *watching* is the one thing besides `touch` that
#: keeps a session alive.
STREAM_NOTE = (
"CREDENTIAL: the phrase in the URL is the stream's only protection — no "
"TLS, no second factor. Anyone who can reach the port and guess four "
"words can watch. It is never written to the audit log, and it is not "
"echoed by 'list' unless you ask for --json.\n\n"
"ACTIVITY: 'stream enable|disable|list|status' do NOT reset the idle "
"clock, like every pointer and keyboard verb. But A CONNECTED VIEWER "
"DOES: about once a minute the broker stamps 'touch' on any session "
"somebody is watching, so a session you are watching on a phone is not "
"reaped at three hours. An enabled stream with nobody watching captures "
"nothing and keeps nothing alive."
)
def _build_stream(verbs: Any, common: argparse.ArgumentParser) -> None:
"""``session stream <verb>`` — a live view of one session, behind a phrase.
A nested namespace for the reason ``pointer`` is one: these four verbs
share a precondition nothing else here has. It is the session's **container
output** — a stream never falls back to the main output, because that one
carries every other session.
"""
namespace = verbs.add_parser(
"stream",
parents=[common],
help="publish one session's screen on the LAN, behind a spoken phrase",
description=(
"A live view of one session, in a browser, at a URL whose path is "
"four words and a five-character tail. Off by default and per "
"session: a session does not stream because it exists, it streams "
"because it was switched on.\n\n"
"What is published is the session's own container output, never "
"the main one — that output carries every other session, and "
"putting it behind one session's phrase is the mistake this "
"refuses to make (exit 10 with no container).\n\n"
"The transport is MJPEG over HTTP: a browser <img> is the whole "
"client. Capture runs only while somebody is connected."
),
epilog=f"{STREAM_NOTE}\n\n{ACTIVITY_NOTE}",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
streams = namespace.add_subparsers(dest="stream_verb", metavar="VERB")
namespace.set_defaults(
func=_cmd_stream_list, hhstream_session_handler=_cmd_stream_list, json=False
)
def add_stream_verb(name: str, handler, **kwargs: Any):
sub = streams.add_parser(name, parents=[common], **kwargs)
sub.set_defaults(func=handler, hhstream_session_handler=handler)
sub.add_argument("--json", action="store_true", help="emit the protocol object on stdout")
return sub
enable = add_stream_verb(
"enable",
_cmd_stream_enable,
help="switch a session's stream on and print its URL",
description=(
"Mint a phrase, open a capture, and print the URL on stdout — so "
"$(hhstream session stream enable ID) is the URL and nothing "
"else. The phrase is kept in the session's record, so it survives "
"a broker restart and a re-enable: somebody you read it out to "
"keeps the URL you gave them.\n\n"
"Re-enabling an enabled session prints the same URL. A --phrase "
"that differs from the stored one is exit 8 rather than a silent "
"rotation, because rotating under a caller holding the old URL is "
"the one outcome neither answer can be mistaken for. 'disable' "
"then 'enable' rotates it."
),
epilog=f"{STREAM_NOTE}\n\n{ACTIVITY_NOTE}",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
enable.add_argument("id", help="session id")
enable.add_argument(
"--phrase",
metavar="PHRASE",
help="use this phrase instead of a minted one. Held to exactly the "
"generated shape (four words of 3+ letters, then a five-character "
"tail): it is a password, and a looser check would accept 'a-b-c'.",
)
enable.add_argument(
"--fps",
type=int,
metavar="N",
help="frames per second (default: the broker's; the daemon caps it)",
)
disable = add_stream_verb(
"disable",
_cmd_stream_disable,
help="switch a session's stream off and forget its phrase",
description=(
"Close the capture, drop the route, and clear the record. The "
"phrase is gone: a later 'enable' mints a new one, which is how a "
"phrase is rotated.\n\n"
"Disabling a stream the daemon has already forgotten is not an "
"error — that is the ordinary case after the daemon restarts, and "
"the record has to be cleared either way. 'detached' says which "
"happened."
),
)
disable.add_argument("id", help="session id")
add_stream_verb(
"list",
_cmd_stream_list,
help="every session with a stream (does NOT count as activity)",
description=(
"Every session a stream was enabled on, with its output, rate and "
"connected viewer count. The phrase is shown only under --json: "
"this listing is the kind of thing that ends up in a terminal "
"somebody is sharing, and the phrase is the credential.\n\n"
"'available' is whether the stream daemon could be asked at all, "
"so 'no streams' is distinguishable from 'no daemon' without "
"parsing an error."
),
)
status = add_stream_verb(
"status",
_cmd_stream_status,
help="one session's stream (does NOT count as activity)",
)
status.add_argument("id", nargs="?", help="session id; omit for all of them")
def _button_help() -> str:
return f"one of: {', '.join(BUTTONS)} (default: left)"
def _point(text: str) -> tuple[float, float]:
"""``X,Y`` as two floats.
Parsed here so a malformed pair is a usage error from argparse (exit 2)
before anything reaches the broker, and so the error names the form.
"""
parts = text.split(",")
if len(parts) != 2:
raise argparse.ArgumentTypeError(
f"expected two numbers separated by a comma, e.g. 0.5,0.5 — got {text!r}"
)
try:
return (float(parts[0]), float(parts[1]))
except ValueError:
raise argparse.ArgumentTypeError(
f"{text!r} is not a pair of numbers (coordinates are output-normalised, 0..1)"
) from None
def _duration(text: str) -> float:
try:
return parse_duration(text)
except ValueError as exc:
raise argparse.ArgumentTypeError(str(exc)) from exc
# --------------------------------------------------------------------------
# handlers
# --------------------------------------------------------------------------
def _socket_of(args: argparse.Namespace) -> str | None:
return getattr(args, "socket", None)
def _request(args: argparse.Namespace, op: str, **fields: Any) -> dict[str, Any]:
return call(op, socket_path=_socket_of(args), **fields)
def _finish(args: argparse.Namespace, reply: dict[str, Any], render) -> int:
"""Print a reply and return its exit code.
Errors always go to stderr and always carry the machine field, whatever the
output mode, because that is what an agent branches on.
"""
code = reply_exit_code(reply)
if getattr(args, "json", False):
fmt.dump_json(reply, stream=sys.stdout if reply.get("ok") else sys.stderr)
elif reply.get("ok"):
text = render(reply)
if text:
print(text)
else:
print(fmt.render_error(reply), file=sys.stderr)
return int(code)
def _guard(handler: Callable[[argparse.Namespace], int]) -> Callable[[argparse.Namespace], int]:
def wrapper(args: argparse.Namespace) -> int:
try:
return handler(args)
except ClientError as exc:
if getattr(args, "json", False):
fmt.dump_json(
{"ok": False, "error": exc.error, "reason": exc.reason, "hint": exc.hint},
stream=sys.stderr,
)
else:
print(f"error: {exc.reason}", file=sys.stderr)
if exc.hint:
print(f"hint: {exc.hint}", file=sys.stderr)
return int(exc.exit_code)
except KeyboardInterrupt:
return int(ExitCode.USAGE)
wrapper.__name__ = handler.__name__
wrapper.__doc__ = handler.__doc__
return wrapper
@_guard
def _cmd_start(args: argparse.Namespace) -> int:
# argparse has already removed the separating `--`, so what is left is the
# application's own argv, as a list. It is never joined into a string.
argv = list(args.argv or [])
if args.no_container:
# Refused rather than sent. The flag is in PLAN §9's surface, but the
# wire's `start` (CONTRACT-sessions.md §4: "existing verbs are
# unchanged") carries no `no_container` field and `SessionManager.start`
# takes no such argument, so a request carrying it would be silently
# ignored and the session would get a container anyway. A flag that
# lies about what it did is worse than one that says it cannot.
return _finish(
args,
{
"ok": False,
"error": "invalid_argument",
"reason": "--no-container is not implemented by this broker: the "
"'start' verb has no no_container field, so the request would be "
"accepted and a container created anyway",
"hint": "start without it and tear the container down with "
"'session kill', or report the gap against "
"docs/CONTRACT-sessions.md §4",
},
lambda r: "",
)
reply = _request(
args,
"start",
app=args.app,
argv=argv,
idle_timeout_s=args.idle_timeout,
wait_ready_s=args.wait_ready,
home=args.home,
ephemeral_home=args.ephemeral_home or None,
request_id=args.request_id,
stream=args.stream or None,
stream_phrase=args.stream_phrase,
stream_fps=args.stream_fps,
)
if not reply.get("ok"):
# A failed start may still have created a session (it exited at once, or
# it is slow to become ready). Print the id so it can be inspected.
if reply.get("id") and not args.json:
print(reply["id"])
return _finish(args, reply, lambda r: "")
session = reply.get("session") or {}
if args.json:
fmt.dump_json(session)
return int(ExitCode.OK)
session_id = reply.get("id") or session.get("id") or ""
# stdout is the bare id and nothing else; detail goes to stderr.
print(session_id)
print(
f"started {session.get('app')} → {session_id} "
f"(pid {session.get('pid')}, pgid {session.get('pgid')}, sid {session.get('sid')})",
file=sys.stderr,
)
print(
f"state {session.get('state')} via {session.get('ready_signal')}; "
f"idle timeout {_fmt_timeout(session.get('idle_timeout_s'))}",
file=sys.stderr,
)
print(
f"keep it alive with: hhstream session touch {session_id} "
"(the only mark of activity; list/status/logs/gc do not count)",
file=sys.stderr,
)
if args.stream:
stream = session.get("stream") or {}
error = session.get("stream_error")
if stream.get("url"):
# stdout, beside the id: the URL is the other thing a caller asked
# for, and `$(... --stream)` giving the id and the URL on two lines
# is more useful than making them run a second verb for it.
print(stream["url"])
print(
f"watching it counts as activity; stop it with: hhstream "
f"session stream disable {session_id}",
file=sys.stderr,
)
else:
# The session started. Saying so loudly, because the exit code is
# 0 and a caller who asked for a stream must not read that as one.
print(
f"WARNING: the session is running but its stream was not "
f"enabled: {error or 'the broker reported no stream'}",
file=sys.stderr,
)
return int(ExitCode.OK)
def _fmt_timeout(seconds: Any) -> str:
return "disabled" if not seconds else format_duration(seconds)
@_guard
def _cmd_list(args: argparse.Namespace) -> int:
reply = _request(args, "list", all=bool(getattr(args, "all", False)) or None)
if getattr(args, "json", False) or not reply.get("ok"):
# `--json` is the protocol's own object, unmodified: splicing the lease
# holder into it would invent a field no other caller can rely on.
return _finish(args, reply, lambda r: "")
holder, known = _pointer_holder(args)
return _finish(
args,
reply,
lambda r: fmt.render_list(
r.get("sessions") or [], pointer_holder=holder, pointer_known=known
),
)
def _pointer_holder(args: argparse.Namespace) -> tuple[Any, bool]:
"""Who holds the one cursor, for the ``POINTER`` column.
A second request, because the ``list`` reply carries no lease state and the
broker is not this slice's file to change. It is read-only and does not
count as activity (CONTRACT-sessions.md §4), so the only cost is a round
trip on a human listing — ``--json`` never makes it.
Returns ``(holder, known)``. ``known=False`` is not a failure worth exiting
over: the sessions have been listed, and the honest thing is to print the
gap marker in that one column rather than lose the whole table.
"""
try:
reply = _request(args, "pointer.state")
except ClientError:
return None, False
if not reply.get("ok") or "holder" not in reply:
return None, False
return reply.get("holder"), True
@_guard
def _cmd_status(args: argparse.Namespace) -> int:
reply = _request(args, "status", id=args.id, events=args.events)
return _finish(args, reply, lambda r: fmt.render_status(r.get("session") or {}))
@_guard
def _cmd_touch(args: argparse.Namespace) -> int:
reply = _request(args, "touch", id=args.id)
def render(r: dict[str, Any]) -> str:
session = r.get("session") or {}
return (
f"{session.get('id')}: idle clock reset; "
f"expires in {format_duration(session.get('expires_in_s'))}"
)
return _finish(args, reply, render)
def _container_teardown(session: dict[str, Any]) -> list[str]:
"""What the compositor side of a teardown left behind.
``survivors`` (processes) was already reported and ``container_survivors``
(windows the compositor still shows) was not, so a teardown that removed
the output and left a window on the screen read as a clean kill. They are
two independent sources and PLAN §4.5 requires both to agree before a
teardown is called a success.
``None`` is its own case and is *not* folded into "none": it means the
compositor could not be asked, so "no windows survived" is a claim nobody
is in a position to make.
"""
bits = []
if session.get("container_removed"):
bits.append("container removed")
if session.get("container_error"):
bits.append(f"container error: {session['container_error']}")
survivors = session.get("container_survivors")
if survivors is None:
bits.append(
"WARNING: the compositor could not be asked whether any window "
"survived the teardown"
)
elif survivors:
named = ", ".join(
f"{w.get('class') or w.get('initial_class')}@{w.get('address')} (pid {w.get('pid')})"
for w in survivors
)
bits.append(
f"WARNING: the compositor still shows {len(survivors)} window(s) "
f"after the output was removed ({named})"
)
return bits
@_guard
def _cmd_kill(args: argparse.Namespace) -> int:
reply = _request(
args,
"kill",
id=args.id,
grace_s=args.grace,
signal=args.signal,
request_id=args.request_id,
)
def render(r: dict[str, Any]) -> str:
"""Say what the daemon actually did, not merely that it finished.
The old rendering could only distinguish "signalled" from "not
signalled", and printed *the process was already gone* for both the
routine case and the case where the daemon refused to signal a live
application (BUG-02). A refusal is now an error reply and never reaches
here; what is left is reported with the signal and the process group it
went to, so "killed" cannot be read as more than it says.
"""
session = r.get("session") or {}
bits = [f"{session.get('id')}: {session.get('state')}"]
sent = session.get("signal_sent")
if sent:
bits.append(f"sent {sent} to process group {session.get('pgid')}")
if session.get("escalated_to_sigkill"):
bits.append("escalated to SIGKILL")
stragglers = session.get("stragglers") or 0
if stragglers:
bits.append(f"{stragglers} straggler(s) swept by session id")
if session.get("signalled") is False and not sent:
bits.append("nothing signalled (the process was already gone)")
survivors = session.get("survivors") or []
if survivors:
# The loudest thing this command can say: the kill did not work.
bits.append(
f"WARNING: {len(survivors)} process(es) SURVIVED "
f"({', '.join(str(p) for p in survivors)})"
)
bits.extend(_container_teardown(session))
return "; ".join(bits)
return _finish(args, reply, render)
@_guard
def _cmd_gc(args: argparse.Namespace) -> int:
reply = _request(args, "gc", request_id=args.request_id)
return _finish(args, reply, fmt.render_gc)
@_guard
def _cmd_adopt(args: argparse.Namespace) -> int:
reply = _request(
args,
"adopt",
pid=args.pid,
app=args.app,
idle_timeout_s=args.idle_timeout,
request_id=args.request_id,
)
if reply.get("ok") and not args.json:
print(reply.get("id", ""))
session = reply.get("session") or {}
print(
f"adopted pid {session.get('pid')} as {reply['id']}; "
"exit code will be unavailable (not a child of the daemon)",
file=sys.stderr,
)
return int(ExitCode.OK)
return _finish(args, reply, lambda r: "")
@_guard
def _cmd_logs(args: argparse.Namespace) -> int:
reply = _request(args, "logs", id=args.id, lines=args.lines)
if not reply.get("ok") or not args.follow:
return _finish(args, reply, lambda r: "\n".join(r.get("lines") or []))
# --follow polls from the returned offset. The daemon holds no streaming
# connection open, so a follower that dies costs the daemon nothing.
for line in reply.get("lines") or []:
print(line)
offset = reply.get("offset", 0)
try:
while True:
if reply.get("eof"):
break
time.sleep(_FOLLOW_INTERVAL_S)
reply = _request(args, "logs", id=args.id, offset=offset)
if not reply.get("ok"):
return _finish(args, reply, lambda r: "")
for line in reply.get("lines") or []:
print(line)
offset = reply.get("offset", offset)
except KeyboardInterrupt:
pass
return int(ExitCode.OK)
# --------------------------------------------------------------------------
# containers
# --------------------------------------------------------------------------
@_guard
def _cmd_container(args: argparse.Namespace) -> int:
"""One session's container, or the whole picture including orphans.
With an id this is ``container.reconcile`` and not ``container.list``, and
that is deliberate: asking "what container does this session have" is
almost always asking "where is this window *now*", and the list verb can
only report what the record remembers.
"""
if args.id is None:
reply = _request(args, "container.list")
return _finish(args, reply, fmt.render_containers)
reply = _request(args, "container.reconcile", id=args.id)
return _finish(args, reply, fmt.render_container)
@_guard
def _cmd_reconcile(args: argparse.Namespace) -> int:
reply = _request(
args, "container.reconcile", id=args.id, request_id=args.request_id
)
return _finish(args, reply, fmt.render_reconcile)
# --------------------------------------------------------------------------
# the pointer lease
# --------------------------------------------------------------------------
def _lease_of(args: argparse.Namespace, session_id: str) -> str | None:
"""The lease id for this verb: the flag, the environment, then the cache."""
explicit = getattr(args, "lease", None)
if explicit:
return explicit
return lease.recall(session_id, socket=_socket_of(args))
def _no_lease(args: argparse.Namespace, session_id: str) -> int:
"""Refuse a gesture with no lease, without troubling the broker.
Exit 9 and not 2: the caller's command line is fine, what is missing is the
lease — and 9 is precisely the code that says "acquire one and try again"
(CONTRACT-sessions.md §4). The broker would answer the same way; refusing
here means the message can name the cache, which the broker knows nothing
about.
"""
reply = {
"ok": False,
"error": "no_lease",
"reason": f"no pointer lease for {session_id} on this socket",
"hint": f"run 'pointer acquire {session_id}' first, or pass --lease "
"with the id it printed",
}
return _finish(args, reply, lambda r: "")
def _finish_gesture(
args: argparse.Namespace, reply: dict[str, Any], render, session_id: str
) -> int:
"""Print a gesture's reply, dropping a lease the broker has just disowned.
A cached lease that is refused is stale by definition — expired, released
by the sweeper, or taken over — and keeping it would make every subsequent
verb fail the same way while the fix (``acquire``) looks unnecessary.
"""
if reply.get("error") in ("no_lease", "no_such_session"):
lease.forget(session_id)
return _finish(args, reply, render)
@_guard
def _cmd_pointer_acquire(args: argparse.Namespace) -> int:
reply = _request(
args,
"pointer.acquire",
id=args.id,
ttl_s=args.ttl,
# `False` and not `None`: the wire default is to restore, so the only
# way to ask for the centre is to say so explicitly.
restore=False if args.no_restore else None,
)
if not reply.get("ok"):
return _finish(args, reply, lambda r: "")
lease_id = reply.get("lease_id") or ""
lease.remember(args.id, lease_id, socket=_socket_of(args))
if args.json:
fmt.dump_json(reply)
return int(ExitCode.OK)
# Same shape as `start`: stdout is the one token a caller needs to pass
# back, detail goes to stderr.
print(lease_id)
bookmark = reply.get("bookmark") or {}
print(
f"acquired the cursor for {reply.get('id')} on {bookmark.get('output')} "
f"at {fmt.render_bookmark(bookmark)}",
file=sys.stderr,
)
print(
f"expires in {_fmt_timeout(reply.get('expires_in_s'))} with no further "
f"pointer OR keyboard verb; release it with: hhstream session pointer "
f"release {args.id}",
file=sys.stderr,
)
return int(ExitCode.OK)
@_guard
def _cmd_pointer_move(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
absolute = getattr(args, "to", None)
relative = getattr(args, "by", None)
coordinates = (
{"x": absolute[0], "y": absolute[1]}
if absolute is not None
else {"dx": relative[0], "dy": relative[1]}
)
reply = _request(args, "pointer.move", id=args.id, lease_id=lease_id, **coordinates)
def render(r: dict[str, Any]) -> str:
return f"{r.get('id')}: cursor at {fmt.render_bookmark(r.get('bookmark'))}"
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_pointer_click(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(
args, "pointer.click", id=args.id, lease_id=lease_id, button=args.button
)
def render(r: dict[str, Any]) -> str:
return (
f"{r.get('id')}: clicked {r.get('button')} "
f"at {fmt.render_bookmark(r.get('bookmark'))}"
)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_pointer_scroll(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(
args,
"pointer.scroll",
id=args.id,
lease_id=lease_id,
axis=args.axis,
amount=args.amount,
)
def render(r: dict[str, Any]) -> str:
return (
f"{r.get('id')}: scrolled {r.get('axis')} by {r.get('amount')} "
f"at {fmt.render_bookmark(r.get('bookmark'))}"
)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_pointer_button(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(
args,
"pointer.button",
id=args.id,
lease_id=lease_id,
button=args.button,
state=args.button_state,
)
def render(r: dict[str, Any]) -> str:
down = r.get("buttons") or []
return (
f"{r.get('id')}: {args.button} {args.button_state}; "
f"held: {', '.join(down) if down else 'nothing'}"
)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_pointer_release(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(args, "pointer.release", id=args.id, lease_id=lease_id)
if reply.get("ok"):
lease.forget(args.id)
def render(r: dict[str, Any]) -> str:
lifted = r.get("buttons_lifted") or []
bits = [
f"{r.get('id')}: cursor released by {r.get('released_by')}",
f"bookmark {fmt.render_bookmark(r.get('bookmark'))}",
]
if lifted:
bits.append(f"lifted {', '.join(lifted)}")
return "; ".join(bits)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_pointer_state(args: argparse.Namespace) -> int:
reply = _request(args, "pointer.state")
return _finish(args, reply, fmt.render_pointer_state)
# --------------------------------------------------------------------------
# the keyboard, on the same lease
# --------------------------------------------------------------------------
def _cmd_keyboard_usage(args: argparse.Namespace) -> int:
"""`session keyboard` with no verb. Prints help, exits 2.
Not a default verb: the only read-only thing to say about the keyboard is
which keys are held, and that is `pointer state`, beside the buttons.
"""
parser = getattr(args, "keyboard_parser", None)
if parser is not None:
parser.print_help(sys.stderr)
return int(ExitCode.USAGE)
@_guard
def _cmd_keyboard_type(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
# `args.text` goes through untouched. No `.encode().decode('unicode_escape')`
# and no strip: the shell quoted it, and a CLI that interpreted backslashes
# would make a literal backslash-n untypeable.
reply = _request(args, "keyboard.type", id=args.id, lease_id=lease_id, text=args.text)
def render(r: dict[str, Any]) -> str:
held = r.get("keys") or []
# The COUNT, never the text: this line goes to a terminal that is
# often being logged, and the string is a password as often as not.
bits = [f"{r.get('id')}: typed {r.get('chars')} character(s)"]
if held:
bits.append(f"still held: {', '.join(held)}")
return "; ".join(bits)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_keyboard_key(args: argparse.Namespace) -> int:
"""A tap: down then up, as two wire calls.
Two calls and not a `count`-style loop in the broker, because a tap is the
only thing anyone wants and the pair is what `down`/`up` already are.
A refused `down` returns without sending the `up`, and that is deliberate:
a refusal is the broker saying the key was never pressed -- a bad keysym,
no lease -- so an `up` would ask the compositor to release something it
never had. A reply *lost* after a successful down is a connection error
rather than ``ok: false``, and the broker's own `release_all` on expiry is
what covers that; the CLI cannot, because it does not know whether the
request arrived.
"""
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
down = _request(
args, "keyboard.key", id=args.id, lease_id=lease_id, key=args.name, state="down"
)
if not down.get("ok"):
return _finish_gesture(args, down, lambda r: "", args.id)
reply = _request(
args, "keyboard.key", id=args.id, lease_id=lease_id, key=args.name, state="up"
)
def render(r: dict[str, Any]) -> str:
held = r.get("keys") or []
return (
f"{r.get('id')}: tapped {args.name}; "
f"held: {', '.join(held) if held else 'nothing'}"
)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_keyboard_hold(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(
args,
"keyboard.key",
id=args.id,
lease_id=lease_id,
key=args.name,
state=args.key_state,
)
def render(r: dict[str, Any]) -> str:
held = r.get("keys") or []
return (
f"{r.get('id')}: {args.name} {args.key_state}; "
f"held: {', '.join(held) if held else 'nothing'}"
)
return _finish_gesture(args, reply, render, args.id)
# --------------------------------------------------------------------------
# the live stream
# --------------------------------------------------------------------------
@_guard
def _cmd_stream_enable(args: argparse.Namespace) -> int:
reply = _request(
args, "stream.enable", id=args.id, phrase=args.phrase, fps=args.fps
)
if not reply.get("ok"):
return _finish(args, reply, lambda r: "")
if args.json:
fmt.dump_json(reply)
return int(ExitCode.OK)
stream = reply.get("stream") or {}
# stdout is the URL and nothing else, the same shape `start` and `pointer
# acquire` already have: one token a caller passes on, detail on stderr.
print(stream.get("url") or "")
print(
f"{reply.get('id')}: streaming output {stream.get('output')} "
f"at {stream.get('fps')} fps",
file=sys.stderr,
)
print(
"the phrase in that URL is its only protection, and watching it counts "
"as activity; stop it with: hhstream session stream disable "
f"{reply.get('id')}",
file=sys.stderr,
)
if not stream.get("attached"):
# `enable` cannot normally get here -- it had to attach to succeed --
# but a reply without it means the daemon answered and then went away,
# and a printed URL that serves nothing is worse than a warning.
print(
"WARNING: the broker recorded this stream but the daemon did not "
"confirm it is attached; the URL may not answer",
file=sys.stderr,
)
return int(ExitCode.OK)
@_guard
def _cmd_stream_disable(args: argparse.Namespace) -> int:
reply = _request(args, "stream.disable", id=args.id)
def render(r: dict[str, Any]) -> str:
detached = r.get("detached")
return (
f"{r.get('id')}: stream disabled and its phrase forgotten"
+ ("" if detached else "; the daemon had already dropped it")
)
return _finish(args, reply, render)
@_guard
def _cmd_stream_list(args: argparse.Namespace) -> int:
reply = _request(args, "stream.list")
return _finish(args, reply, fmt.render_streams)
@_guard
def _cmd_stream_status(args: argparse.Namespace) -> int:
session_id = getattr(args, "id", None)
reply = _request(args, "stream.status", id=session_id)
if session_id is None:
return _finish(args, reply, fmt.render_streams)
return _finish(args, reply, fmt.render_stream)
# --------------------------------------------------------------------------
# standalone use
# --------------------------------------------------------------------------
def build_parser(prog: str = "hhstream") -> argparse.ArgumentParser:
"""A host CLI stand-in, so the handlers can be driven without one."""
parser = argparse.ArgumentParser(prog=prog)
subparsers = parser.add_subparsers(dest="command", metavar="COMMAND")
register(subparsers)
return parser
def dispatch(args: argparse.Namespace) -> int:
"""Run the handler argparse selected. The host may call this or ``args.func``."""
handler = getattr(args, "func", None)
if handler is None:
return int(ExitCode.USAGE)
return int(handler(args))
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
if getattr(args, "command", None) is None:
parser.print_help(sys.stderr)
return int(ExitCode.USAGE)
return dispatch(args)
if __name__ == "__main__": # pragma: no cover
raise SystemExit(main())