the surface: CLI verbs, the module's options, and three checks the compositor votes in
Everything below the CLI was merged and green against fakes; none of it was
reachable and none of it had ever met a compositor. This wires it up and then
puts the compositor in a position to disagree.
CLI (src/hhstream/cli.py, src/hhstream_session/**)
session container [ID], session reconcile [ID], and the seven pointer verbs
from PLAN §9. `start` still prints the bare session id and nothing else.
`list` gains WS / OUTPUT / POINTER, with the gap marker where a value is
genuinely unknown rather than a blank that reads as zero -- the POINTER
column needs a second, read-only `pointer.state` call because the `list`
reply carries no lease state.
The lease id is cached in `hhstream_session.lease` (under
$XDG_RUNTIME_DIR), because PLAN §9's gesture verbs take no --lease and the
wire requires a lease_id on every one of them; --lease and $HHSTREAM_LEASE
override it, and a `no_lease` refusal drops the stale entry.
Exit codes are the contract's: a gesture with no lease is 9 and never
reaches the broker, and a compositor failure is 10 with a message that says
the session is still running. `kill` now warns about
`session.container_survivors` -- windows the compositor still shows -- and
distinguishes `null` ("could not ask") from `[]`.
`shot`/`record --output NAME` capture one container through `grim -o`; the
frame socket publishes the main output only, so it cannot do it.
Module (nix/module.nix)
sessions.containers.{enable,max,mode,workspaceBase},
sessions.pointer.{enable,leaseTtl,leaseMax}, rendered into the generated
TOML with §10's key names. hhstream-pointer.service: the operator's account,
supplementary group hhstream, After=/BindsTo= the compositor,
Restart=on-failure, KillMode=process, and the command line §3.4 freezes.
tmpfiles for /run/hhstream plus RuntimeDirectoryPreserve on the broker,
without which restarting the broker deletes the driver's socket out from
under it. The runtime-directory length assertion is untouched.
And ExecStartPost on the compositor, opening its IPC directory to its own
group: Hyprland creates <runtime>/hypr with S_IRWXU, so the broker -- a
different account by design -- could not reach the request or event socket
at all, and degraded silently exactly as it is built to.
Checks (checks/**)
vm-ipc: both sockets at their frozen names, measured against sun_path's 108
bytes, and a socket2 subscriber that receives an openwindow for a window the
test creates. The subscriber is the shipped HyprlandIPC, not a second
implementation: this check exists to prove that this client hears this
compositor.
vm-containers: one hh-* output per session at the container mode, the window
on it, a second window of the same application beside it, an unmatched
window quarantined, grim -o isolating one container, teardown removing the
output and freeing the slot. PLAN experiment 3 is answered: `hyprctl output
create headless` works.
vm-pointer: a version-2 virtual pointer, a warp and a click whose
coordinates the *application* reports, BUSY naming the holder, an expired
lease swept with its held button lifted, and a broker restart that leaves
the lock free, the bookmark intact and the driver reachable.
checks/lib gains the guest the three share, their test-script helpers (no
assertions live there), an event-socket subscriber and a Wayland client that
says where it was clicked -- nothing in nixpkgs both honours
$HHSTREAM_APP_ID and reports pointer events.
Reported, not worked around: the broker reads none of the container or
pointer config (policy.py takes [defaults] and [apps] only), `start` has no
no_container field so --no-container is refused rather than silently ignored,
and nix/hyprland-conf.nix sets input:follow_mouse = 0, which sends pointer
events to the focused window only -- measured, with the cursor at the aimed
pixel and no client told. README.dev.md has the evidence for each.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WQy29x9AfHWyzNd1f7XPGK
This commit is contained in:
1 parent
57fdd4f636
commit
de408e4b7f
19 files changed
+4304
-98
No files matched your search
+109
-12
@@ -4,10 +4,16 @@ Four verbs that work whether or not the session daemon is running, and one
|
||||
namespace that needs it:
|
||||
|
||||
hhstream status is the session up, and can I reach it?
|
||||
hhstream shot one frame of the screen
|
||||
hhstream shot one frame of the screen, or of one output
|
||||
hhstream run -- CMD... launch a GUI app into the session (unmanaged)
|
||||
hhstream record film the screen for N seconds
|
||||
hhstream session ... managed application sessions (start/list/touch/kill)
|
||||
hhstream session ... managed sessions: start/list/kill, their
|
||||
containers, and the pointer lease
|
||||
|
||||
``shot`` and ``record`` read the published *main* output off the frame socket.
|
||||
``--output NAME`` instead captures one output in isolation through ``grim -o``,
|
||||
which is how a single session's container is looked at (PLAN §5.4); the frame
|
||||
socket cannot do it, because the publisher serves one output and one frame slot.
|
||||
|
||||
``run`` and ``session start`` both put an application on the screen; they are
|
||||
deliberately different. ``run`` is the primitive: it execs and forgets, nothing
|
||||
@@ -54,6 +60,12 @@ DEFAULT_UNITS = ("hyprland-headless.service", "hyprland-headless-stream.service"
|
||||
ENV_UNITS = "HHSTREAM_UNITS"
|
||||
|
||||
FFMPEG = "ffmpeg"
|
||||
#: The screenshot tool used for `--output NAME`. The frame socket publishes the
|
||||
#: *main* output and nothing else (docs/CONTRACT.md), so a per-container frame
|
||||
#: cannot come from it; `grim -o <name>` is the one thing that can capture a
|
||||
#: single output in isolation (PLAN §5.4), and it is already the module's
|
||||
#: default capture backend, so this adds no dependency.
|
||||
GRIM = "grim"
|
||||
|
||||
|
||||
# ── access ─────────────────────────────────────────────────────────────────
|
||||
@@ -157,6 +169,31 @@ def env_for_session(runtime_dir: str) -> dict[str, str]:
|
||||
}
|
||||
|
||||
|
||||
def capture_output(runtime_dir: str, output: str, destination: pathlib.Path) -> None:
|
||||
"""One frame of a single output, through ``grim -o``.
|
||||
|
||||
Raises :class:`SystemExit` with the tool's own words. ``grim`` says
|
||||
``unknown output`` for a container that no longer exists, which is the
|
||||
message a caller needs — far better than this wrapper's guess at what went
|
||||
wrong, and the reason stderr is passed through verbatim.
|
||||
"""
|
||||
|
||||
if shutil.which(GRIM) is None:
|
||||
sys.exit(f"hhstream: {GRIM} is not on PATH, and --output needs it")
|
||||
env = dict(os.environ)
|
||||
env.update(env_for_session(runtime_dir))
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
done = subprocess.run(
|
||||
[GRIM, "-o", output, str(destination)], env=env, capture_output=True, text=True
|
||||
)
|
||||
if done.returncode != 0:
|
||||
detail = (done.stderr or done.stdout or "").strip()
|
||||
sys.exit(
|
||||
f"hhstream: could not capture output {output!r}: "
|
||||
f"{detail or f'{GRIM} exited {done.returncode}'}"
|
||||
)
|
||||
|
||||
|
||||
# ── verbs ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -187,6 +224,14 @@ def cmd_status(args: argparse.Namespace) -> int:
|
||||
|
||||
|
||||
def cmd_shot(args: argparse.Namespace) -> int:
|
||||
runtime_dir = str(pathlib.Path(args.frame_socket).parent)
|
||||
if args.output:
|
||||
# A named output does not come off the frame socket: the publisher
|
||||
# serves the main output, one frame slot, no selection (PLAN §5.4).
|
||||
out = pathlib.Path(args.out or f"hhstream-{args.output}.png")
|
||||
capture_output(runtime_dir, args.output, out)
|
||||
print(out)
|
||||
return 0
|
||||
hello, payloads = read_frames(args.frame_socket, count=1, timeout=args.timeout)
|
||||
if not payloads:
|
||||
print("hhstream: the publisher sent no frame", file=sys.stderr)
|
||||
@@ -220,17 +265,21 @@ def cmd_record(args: argparse.Namespace) -> int:
|
||||
) / f"hhstream-rec-{os.getpid()}"
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
hello, first = read_frames(args.frame_socket, count=1, timeout=args.timeout)
|
||||
ext = frame_extension(hello)
|
||||
if first:
|
||||
(work / f"frame-{1:05d}.{ext}").write_bytes(first[0])
|
||||
if args.output:
|
||||
ext = "png"
|
||||
count, elapsed = record_output(args, work, ext)
|
||||
else:
|
||||
hello, first = read_frames(args.frame_socket, count=1, timeout=args.timeout)
|
||||
ext = frame_extension(hello)
|
||||
if first:
|
||||
(work / f"frame-{1:05d}.{ext}").write_bytes(first[0])
|
||||
|
||||
count = len(first)
|
||||
started = time.monotonic()
|
||||
for payload in stream_frames(args.frame_socket, max(0.0, args.seconds - 0.05)):
|
||||
count += 1
|
||||
(work / f"frame-{count:05d}.{ext}").write_bytes(payload)
|
||||
elapsed = max(time.monotonic() - started, 0.001)
|
||||
count = len(first)
|
||||
started = time.monotonic()
|
||||
for payload in stream_frames(args.frame_socket, max(0.0, args.seconds - 0.05)):
|
||||
count += 1
|
||||
(work / f"frame-{count:05d}.{ext}").write_bytes(payload)
|
||||
elapsed = max(time.monotonic() - started, 0.001)
|
||||
|
||||
if count == 0:
|
||||
print(f"hhstream: read no frames in {args.seconds}s", file=sys.stderr)
|
||||
@@ -258,6 +307,31 @@ def cmd_record(args: argparse.Namespace) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def record_output(args: argparse.Namespace, work: pathlib.Path, ext: str) -> tuple[int, float]:
|
||||
"""Frames of one named output, one ``grim`` run per frame.
|
||||
|
||||
Honest about being the slow path. There is no streaming capture of a single
|
||||
output here: the frame server publishes the main one, and a per-output
|
||||
screencopy client is a program this repository does not have. One ``grim``
|
||||
per frame costs a process spawn and a full screencopy round trip, so the
|
||||
achieved rate is well under ``--seconds * fps`` — which is exactly why the
|
||||
encoder below uses the *measured* rate and the caller is told both numbers.
|
||||
"""
|
||||
|
||||
runtime_dir = str(pathlib.Path(args.frame_socket).parent)
|
||||
interval = 1.0 / max(args.fps, 1)
|
||||
count = 0
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < args.seconds:
|
||||
due = time.monotonic() + interval
|
||||
count += 1
|
||||
capture_output(runtime_dir, args.output, work / f"frame-{count:05d}.{ext}")
|
||||
# Never a negative sleep, and never a busy loop: a grim run slower than
|
||||
# the interval simply sets the rate.
|
||||
time.sleep(max(0.0, due - time.monotonic()))
|
||||
return count, max(time.monotonic() - started, 0.001)
|
||||
|
||||
|
||||
# ── parser ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -297,6 +371,14 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
|
||||
shot = verbs.add_parser("shot", help="write one frame of the screen")
|
||||
shot.add_argument("--out", metavar="FILE", help="where to write it (default: ./hhstream-frame.*)")
|
||||
shot.add_argument(
|
||||
"--output",
|
||||
metavar="NAME",
|
||||
help="capture this output alone (e.g. a session's container, "
|
||||
"hh-<session-id>) through grim, instead of reading the published main "
|
||||
"output off the frame socket. 'hhstream session container' lists the "
|
||||
"names.",
|
||||
)
|
||||
|
||||
run = verbs.add_parser("run", help="launch a GUI app into the session (unmanaged)")
|
||||
run.add_argument("argv", nargs="*", metavar="-- CMD...", help="the command, after a literal --")
|
||||
@@ -306,6 +388,21 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
record.add_argument("--out", metavar="FILE", help="output mp4 (default: ./hhstream-recording.mp4)")
|
||||
record.add_argument("--work-dir", metavar="DIR", help="where frames go (default: a temp dir)")
|
||||
record.add_argument("--keep", action="store_true", help="keep the frames after encoding")
|
||||
record.add_argument(
|
||||
"--output",
|
||||
metavar="NAME",
|
||||
help="film this output alone (e.g. hh-<session-id>) by running grim per "
|
||||
"frame, instead of reading the published main output off the frame "
|
||||
"socket. Markedly slower; the encoded rate is the measured one.",
|
||||
)
|
||||
record.add_argument(
|
||||
"--fps",
|
||||
type=float,
|
||||
default=10.0,
|
||||
metavar="N",
|
||||
help="target frames per second for --output (default: %(default)s); "
|
||||
"ignored without it, where the publisher sets the rate",
|
||||
)
|
||||
|
||||
# The managed namespace. It brings its own --socket (the *control* socket,
|
||||
# which is a different socket from the frame one) and its own exit codes.
|
||||
|
||||
@@ -21,9 +21,24 @@ 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`` and ``gc`` deliberately do
|
||||
not reset a session's idle clock, so an agent watching a long-running app must
|
||||
call ``touch`` or the session will be reaped on schedule.
|
||||
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
|
||||
|
||||
The pointer verbs share one precondition — the 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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,6 +52,7 @@ 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"]
|
||||
@@ -164,6 +180,12 @@ def _build_namespace(parser: argparse.ArgumentParser) -> None:
|
||||
help="deduplication token: retrying a start with the same id returns the "
|
||||
"original reply instead of launching a second application",
|
||||
)
|
||||
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)")
|
||||
@@ -232,6 +254,219 @@ def _build_namespace(parser: argparse.ArgumentParser) -> None:
|
||||
"--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)
|
||||
|
||||
|
||||
#: 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")
|
||||
|
||||
|
||||
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()
|
||||
)
|
||||
|
||||
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)",
|
||||
)
|
||||
|
||||
|
||||
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:
|
||||
@@ -300,6 +535,27 @@ 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",
|
||||
@@ -349,7 +605,40 @@ def _fmt_timeout(seconds: Any) -> str:
|
||||
@_guard
|
||||
def _cmd_list(args: argparse.Namespace) -> int:
|
||||
reply = _request(args, "list", all=bool(getattr(args, "all", False)) or None)
|
||||
return _finish(args, reply, lambda r: fmt.render_list(r.get("sessions") or []))
|
||||
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
|
||||
@@ -372,6 +661,43 @@ def _cmd_touch(args: argparse.Namespace) -> int:
|
||||
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(
|
||||
@@ -413,6 +739,7 @@ def _cmd_kill(args: argparse.Namespace) -> int:
|
||||
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)
|
||||
@@ -472,6 +799,210 @@ def _cmd_logs(args: argparse.Namespace) -> int:
|
||||
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 verb; release it with: hhstream session pointer 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_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)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# standalone use
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
+263
-10
@@ -13,6 +13,11 @@ 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 = "—"
|
||||
|
||||
|
||||
@@ -35,19 +40,48 @@ def render_table(rows: list[list[str]], headers: list[str]) -> str:
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def render_list(sessions: list[dict[str, Any]]) -> str:
|
||||
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:<id>``), 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.
|
||||
|
||||
There is **no ``FG`` column** (DESIGN.md §1.4, amended): foreground-ness
|
||||
needs compositor IPC, which this milestone does not have, so the column was
|
||||
``?`` on every row of every listing — a header and six columns of width
|
||||
paying for no information, and a reader who has to learn that ``?`` means
|
||||
*unknown* rather than *no*. ``foreground`` stays in the record and in
|
||||
``status``, where it is one line among many and can become real without
|
||||
changing the shape of this table.
|
||||
``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:
|
||||
@@ -64,17 +98,193 @@ def render_list(sessions: list[dict[str, Any]]) -> str:
|
||||
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", "IDLE", "EXPIRES IN"])
|
||||
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:
|
||||
@@ -148,8 +358,51 @@ def render_gc(result: dict[str, Any]) -> str:
|
||||
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:
|
||||
parts = [f"error: {reply.get('reason') or reply.get('error')}"]
|
||||
"""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)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Where the CLI keeps the lease id between two invocations.
|
||||
|
||||
The contract's pointer surface (PLAN §9) is flagless::
|
||||
|
||||
hhstream session pointer acquire ID
|
||||
hhstream session pointer move ID --to 0.5,0.5
|
||||
hhstream session pointer release ID
|
||||
|
||||
but the wire (CONTRACT-sessions.md §4) requires a ``lease_id`` on every gesture
|
||||
verb, and the CLI is one process per verb: by the time ``move`` runs, the
|
||||
``acquire`` that was handed the lease id has exited. Something has to remember
|
||||
it, and the three candidates are a flag on every verb (which the frozen surface
|
||||
does not have), the broker (which deliberately refuses to infer a holder — that
|
||||
is what makes a stale lease detectable), or here.
|
||||
|
||||
So: ``acquire`` writes the lease id, the gesture verbs read it, ``release`` and
|
||||
every ``no_lease`` refusal delete it. ``--lease`` and ``$HHSTREAM_LEASE``
|
||||
override it, because an agent that holds the id already should not have to care
|
||||
that this file exists.
|
||||
|
||||
It is a **cache, not state**: every entry is re-checked by the broker on the
|
||||
next verb, and a stale one costs one refusal (exit 9) and is then dropped. It
|
||||
lives under ``$XDG_RUNTIME_DIR``, so a reboot takes it with the leases it
|
||||
describes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
#: Overrides the directory below. Exists for tests and for an operator running
|
||||
#: two brokers on one machine; the socket path is part of each entry anyway, so
|
||||
#: the usual reason to move it is isolation, not correctness.
|
||||
ENV_LEASE_DIR = "HHSTREAM_LEASE_DIR"
|
||||
#: One lease id, for a caller that would rather pass it than let us cache it.
|
||||
ENV_LEASE = "HHSTREAM_LEASE"
|
||||
|
||||
FILENAME = "pointer-leases.json"
|
||||
|
||||
|
||||
def lease_dir() -> Path:
|
||||
"""The directory the cache lives in — per user, and not world-readable.
|
||||
|
||||
``$XDG_RUNTIME_DIR`` is the right home: it is already per-user, already
|
||||
private, and already emptied on logout. The fallbacks exist because an
|
||||
agent reached over ``ssh`` or from a cron job often has neither it nor
|
||||
``/run/user/<uid>``, and a lease it cannot cache would make the flagless
|
||||
surface unusable exactly where it is most needed.
|
||||
"""
|
||||
|
||||
override = os.environ.get(ENV_LEASE_DIR)
|
||||
if override:
|
||||
return Path(override)
|
||||
runtime = os.environ.get("XDG_RUNTIME_DIR")
|
||||
if runtime and os.path.isdir(runtime):
|
||||
return Path(runtime) / "hhstream"
|
||||
uid_runtime = Path(f"/run/user/{os.getuid()}")
|
||||
if uid_runtime.is_dir():
|
||||
return uid_runtime / "hhstream"
|
||||
return Path(tempfile.gettempdir()) / f"hhstream-{os.getuid()}"
|
||||
|
||||
|
||||
def _path() -> Path:
|
||||
return lease_dir() / FILENAME
|
||||
|
||||
|
||||
def _load() -> dict[str, Any]:
|
||||
try:
|
||||
with open(_path(), encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
except (OSError, ValueError):
|
||||
# Unreadable or corrupt is the same as empty: the broker is the
|
||||
# authority on who holds the lease, and losing the cache costs one
|
||||
# extra `acquire`.
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _store(entries: dict[str, Any]) -> None:
|
||||
path = _path()
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
# Written through a temporary file in the same directory so a crash
|
||||
# mid-write leaves the previous cache rather than a truncated one.
|
||||
handle, temporary = tempfile.mkstemp(dir=path.parent, prefix=".leases-")
|
||||
with os.fdopen(handle, "w", encoding="utf-8") as fh:
|
||||
json.dump(entries, fh)
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, path)
|
||||
except OSError:
|
||||
# A cache that cannot be written is not an error worth failing a warp
|
||||
# over; the caller is told the lease id on stdout either way.
|
||||
pass
|
||||
|
||||
|
||||
def remember(session_id: str, lease_id: str, *, socket: str | None) -> None:
|
||||
entries = _load()
|
||||
entries[session_id] = {"lease_id": lease_id, "socket": socket}
|
||||
_store(entries)
|
||||
|
||||
|
||||
def recall(session_id: str, *, socket: str | None) -> str | None:
|
||||
"""The cached lease for this session on this socket, or ``None``.
|
||||
|
||||
The socket is part of the match: a lease id from another broker is not a
|
||||
lease here, and offering it would turn a clear "acquire first" into a
|
||||
confusing "that is not your lease".
|
||||
"""
|
||||
|
||||
explicit = os.environ.get(ENV_LEASE)
|
||||
if explicit:
|
||||
return explicit
|
||||
entry = _load().get(session_id)
|
||||
if not isinstance(entry, dict):
|
||||
return None
|
||||
if entry.get("socket") != socket:
|
||||
return None
|
||||
lease_id = entry.get("lease_id")
|
||||
return lease_id if isinstance(lease_id, str) and lease_id else None
|
||||
|
||||
|
||||
def forget(session_id: str) -> None:
|
||||
entries = _load()
|
||||
if entries.pop(session_id, None) is not None:
|
||||
_store(entries)
|
||||
Reference in new issue
Block a user