Files
HermenixandClaude Opus 5 de408e4b7f 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
2026-10-03 06:58:44 +00:00

270 lines
11 KiB
Python

#!/usr/bin/env python3
"""A Wayland client that says where it was clicked, in its own words.
The VM checks need two things no application in nixpkgs gives them together:
* **a window that lands in its container.** The broker stamps a session's
identity into the environment only (``$HHSTREAM_APP_ID``, see
``hhstreamd/launcher.py``), because the alternative -- a per-app
``--app-id`` flag -- would have to come out of the allowlist. ``foot`` and
``wev`` ignore the environment and keep their own class, so their windows
match no per-session rule and are swept into quarantine. This client reads
the variable and sets ``xdg_toplevel.set_app_id`` to it, which is what the
rule ``match:initial_class ^hh-<id>$`` is written against.
* **a report of pointer events from the application's side.** PLAN §14 is
explicit that "a click lands where aimed" must be verified by reading back
*the application's* state and not by comparing pixels: a pixel comparison
proves the compositor drew a cursor, not that the client was told about a
button. Every event below is printed as the client received it, with the
surface-local coordinates the compositor sent, and flushed -- the broker
captures stdout into the session log, so ``hhstream session logs`` is the
read-back.
It is deliberately minimal and deliberately loud: it prints what it bound,
what size it was configured at, and every pointer event, so a check that fails
says whether the window was never mapped, never entered, or entered somewhere
other than where the warp aimed.
"""
from __future__ import annotations
import argparse
import mmap
import os
import signal
import struct
import sys
from pywayland.client import Display
from pywayland.protocol.wayland import WlCompositor, WlPointer, WlSeat, WlShm
from pywayland.protocol.xdg_shell import XdgWmBase
#: Opaque 32-bit colour. Something has to be in the buffer for the compositor
#: to map the surface at all, and a flat fill is the least that will do.
FILL = 0xFF3050A0
#: Fallback size for a compositor that configures 0x0 (meaning "you choose").
DEFAULT_SIZE = (640, 360)
def say(line: str) -> None:
"""One line, flushed. Unbuffered because the reader is a log tail."""
print(line, flush=True)
class Target:
def __init__(self, app_id: str, title: str, windows: int) -> None:
self.app_id = app_id
self.title = title
self.windows = windows
self.display: Display | None = None
self.compositor = None
self.shm = None
self.wm_base = None
self.seat = None
self.surfaces: list[_Window] = []
#: Last position the compositor reported, per surface, so a button
#: event can be printed with the place it happened. The protocol does
#: not put coordinates on `button`; `enter` and `motion` carry them.
self.pointer = None
# -- setup ---------------------------------------------------------
def run(self) -> int:
self.display = Display()
self.display.connect()
registry = self.display.get_registry()
registry.dispatcher["global"] = self._on_global
self.display.roundtrip()
missing = [
name
for name, value in (
("wl_compositor", self.compositor),
("wl_shm", self.shm),
("xdg_wm_base", self.wm_base),
("wl_seat", self.seat),
)
if value is None
]
if missing:
say(f"target: FATAL missing globals: {', '.join(missing)}")
return 1
self.wm_base.dispatcher["ping"] = lambda base, serial: base.pong(serial)
self.seat.dispatcher["capabilities"] = self._on_capabilities
for index in range(self.windows):
self.surfaces.append(_Window(self, index))
self.display.roundtrip()
say(f"target: app_id={self.app_id} windows={self.windows} pid={os.getpid()}")
while True:
# Blocking dispatch: this process exists to report events, so there
# is nothing to do between them and nothing to poll for.
if self.display.dispatch(block=True) < 0:
say("target: display disconnected")
return 1
def _on_global(self, registry, global_id: int, interface: str, version: int) -> None:
if interface == WlCompositor.name:
self.compositor = registry.bind(global_id, WlCompositor, min(version, 4))
elif interface == WlShm.name:
self.shm = registry.bind(global_id, WlShm, 1)
elif interface == XdgWmBase.name:
self.wm_base = registry.bind(global_id, XdgWmBase, min(version, 2))
elif interface == WlSeat.name and self.seat is None:
self.seat = registry.bind(global_id, WlSeat, min(version, 5))
def _on_capabilities(self, seat, capabilities: int) -> None:
if not capabilities & WlSeat.capability.pointer.value:
# Said out loud: a seat with no pointer capability is the headless
# case where nothing has ever created a virtual pointer, and it is
# indistinguishable from "the warp did not arrive" unless reported.
say("target: seat has no pointer capability yet")
return
if self.pointer is not None:
return
self.pointer = seat.get_pointer()
self.pointer.dispatcher["enter"] = self._on_enter
self.pointer.dispatcher["leave"] = self._on_leave
self.pointer.dispatcher["motion"] = self._on_motion
self.pointer.dispatcher["button"] = self._on_button
say("target: pointer bound")
# -- pointer -------------------------------------------------------
def _window_of(self, surface) -> "_Window | None":
for window in self.surfaces:
if window.surface == surface:
return window
return None
def _on_enter(self, pointer, serial, surface, x, y) -> None:
window = self._window_of(surface)
if window is not None:
window.at = (x, y)
say(f"pointer enter window={_name(window)} x={x:.2f} y={y:.2f}")
def _on_leave(self, pointer, serial, surface) -> None:
say(f"pointer leave window={_name(self._window_of(surface))}")
def _on_motion(self, pointer, time, x, y) -> None:
for window in self.surfaces:
# Motion carries no surface; the focused one is whichever was
# entered last, and with one window per container that is the only
# one. Recording it on all of them keeps the button line honest
# without inventing a focus model this client does not need.
window.at = (x, y)
say(f"pointer motion x={x:.2f} y={y:.2f}")
def _on_button(self, pointer, serial, time, button, state) -> None:
where = self.surfaces[0].at if self.surfaces else None
position = "x=? y=?" if where is None else f"x={where[0]:.2f} y={where[1]:.2f}"
say(
f"pointer button code={button} state="
f"{'pressed' if state else 'released'} {position}"
)
def _name(window: "_Window | None") -> str:
return "?" if window is None else str(window.index)
class _Window:
"""One toplevel: a surface, its xdg wrapper, and an shm buffer."""
def __init__(self, target: Target, index: int) -> None:
self.target = target
self.index = index
self.at: tuple[float, float] | None = None
self.size = DEFAULT_SIZE
self.buffer = None
self._pool = None
self._map: mmap.mmap | None = None
self.surface = target.compositor.create_surface()
self.xdg_surface = target.wm_base.get_xdg_surface(self.surface)
self.xdg_surface.dispatcher["configure"] = self._on_configure
self.toplevel = self.xdg_surface.get_toplevel()
# The whole reason this program exists rather than `wev`.
self.toplevel.set_app_id(target.app_id)
self.toplevel.set_title(f"{target.title}-{index}")
self.toplevel.dispatcher["configure"] = self._on_toplevel_configure
self.toplevel.dispatcher["close"] = lambda *_: sys.exit(0)
self.surface.commit()
def _on_toplevel_configure(self, toplevel, width, height, states) -> None:
if width and height:
self.size = (width, height)
def _on_configure(self, xdg_surface, serial) -> None:
xdg_surface.ack_configure(serial)
self._paint()
say(f"target: window {self.index} configured {self.size[0]}x{self.size[1]}")
def _paint(self) -> None:
width, height = self.size
stride = width * 4
size = stride * height
if self._map is None or self._map.size() < size:
self._allocate(size)
# A flat fill, written once per resize: the pixels are not the subject
# of any assertion, they only make the surface mappable.
self._map.seek(0)
self._map.write(struct.pack("<I", FILL) * (size // 4))
self.buffer = self._pool.create_buffer(
0, width, height, stride, WlShm.format.xrgb8888.value
)
self.surface.attach(self.buffer, 0, 0)
self.surface.damage(0, 0, width, height)
self.surface.commit()
def _allocate(self, size: int) -> None:
fd = os.memfd_create(f"hhs-target-{self.index}", 0)
os.ftruncate(fd, size)
self._map = mmap.mmap(fd, size)
self._pool = self.target.shm.create_pool(fd, size)
os.close(fd)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="hhs-pointer-target",
description="A Wayland window that reports the pointer events it receives.",
)
parser.add_argument(
"--app-id",
default=None,
help="xdg_toplevel app id; the default is $HHSTREAM_APP_ID, which is how "
"a session's window rule finds its container",
)
parser.add_argument("--title", default="hhs-target")
parser.add_argument(
"--windows",
type=int,
default=1,
help="how many toplevels to open, all with the same app id",
)
args = parser.parse_args(argv)
app_id = args.app_id or os.environ.get("HHSTREAM_APP_ID")
if not app_id:
print(
"hhs-pointer-target: no --app-id and no $HHSTREAM_APP_ID; refusing to "
"guess, because the app id is the whole point of this program",
file=sys.stderr,
)
return 2
# The broker kills the process group; exit on the first signal rather than
# leaving the compositor to notice a dead client.
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
signal.signal(signal.SIGINT, lambda *_: sys.exit(0))
return Target(app_id, args.title, max(1, args.windows)).run()
if __name__ == "__main__":
sys.exit(main())