Files
HermenixandClaude Opus 5 e6f4c3bb3f Stage 1 review fixes, and Stage 2: the broker, the CLI and the module
The Stage 1 review (docs/reviews/2026-10-04-stage1-review.md, verdict
yes-with-fixes) found a real bug, and it was the kind Stage 2 would have
cemented. All five findings:

(1) HIGH, and reproduced before fixing: `key` resolved the action and
    then used only its `code`. So `keyboard key A` sent a bare code 30
    and the window received `a`; on `de`, `at` lost its level-three mask
    and typed `q`. `type` was the only path that used the mask, which is
    why every `type` test stayed green. `key` now sends
    modifiers(baseline | mask) before the down and restores the baseline
    on the up -- the one-character `type` sequence -- and `Shift_L`
    keeps its key-then-mask order, which is the other path on purpose.

    The same hole aliased two names onto one keycode: `down A` then
    `down a` recorded both and pressed 30 twice, Hyprland dropped the
    second, and the held set lied until the lease ended. A second name
    for a code already down is now refused.

(2) HIGH: the shutdown comment claimed hyprland-conf.nix sets
    input:virtualkeyboard:release_pressed_on_close. It did not. The line
    is there now, with the note that it releases keys and still never
    clears a mask -- which is why release_all zeroes the mask on every
    path we control rather than relying on it.

(3) MEDIUM: nothing would have noticed the keymap upload stopping. A
    `main` that connected and listened without uploading passed every
    test in the tree. Now asserted on the real sink: uploaded once,
    before `listen` (one shared ordering log across both stand-ins), the
    payload NUL-terminated with `size == len(utf8) + 1` read back
    through the fd, format 1, one terminator not two, and modifiers(0)
    straight after.

(4) LOW: `key` up now forgets the name only after a successful send,
    like `button` -- otherwise a raise between the two leaves us
    believing a key is up that the compositor still has down, and
    release_all will not try again.

(5) LOW: `\r` no longer aliases to Return (CRLF would have become two
    newlines silently), and an empty layout is refused -- xkbcommon
    compiles "" as the same keymap as `us`, so `--xkb-layout ''` looked
    configured and typed `us`.

Several of the review's named false passes are closed too: Control's
mask is compared against mod_get_index("Control") rather than merely
"not Shift's"; the keymap text assertion names pc_us_inet/pc_de_inet
instead of substring-matching "us"; the capital-under-Control case
asserts the whole sequence; the exit-code mirror is compared against
hhstreamd.protocol; and the module's defaults are read out of
nix/module.nix rather than asserted against themselves.

Stage 2 proper:

  * broker verbs keyboard.key / keyboard.type, both in the mutation set,
    both through _refresh (so they refresh the lease and, like every
    pointer verb, do NOT count as activity)
  * the driver's `kind` token mapped: a bad keysym or character is
    invalid_argument (exit 2), a missing keyboard global stays
    driver_refused (exit 10). The 4096-scalar cap and the shape checks
    are broker-side, because only a broker-side invalid_argument is 2
  * keys[] on pointer.state, keys_lifted[] on pointer.release and on
    pointer_lease_timeout, one release_all for both halves
  * CLI `session keyboard type|key|down|up`, reusing the pointer lease
    and its cache; `type` takes one raw argument and interprets nothing;
    the audit records a character count and never the text
  * sessions.keyboard.{layout,model,variant,options} on the unit's argv,
    layout defaulting to "us" with a type that refuses a comma. NO
    [keyboard] TOML table: hhstreamd reads that file and the driver is a
    different unit, so it would be a setting with no effect
  * CONTRACT-sessions.md bumped to v3; README.dev.md item 3 and
    vm-pointer.nix's header corrected (both still said the conf ships
    follow_mouse = 0 and that the keyboard work would choose)

And the operator decision that acquire grabs both devices: it now sends
two warps a real pixel apart, because one warp onto an idle cursor moves
the cursor and not keyboard focus. follow_mouse_threshold = 0 is set
explicitly in hyprland-conf.nix since the second warp depends on it,
`dispatch focuswindow` is the fallback when the nudge cannot be sent,
and the reply and audit carry which mechanism ran. The acquire test
asserts the pair and that they floor to different pixels -- a test that
only saw wl_pointer.enter would pass while the first keystroke went to
the wrong window.

  nix develop -c python -m pytest tests/pointer tests/sessions/unit -q
  605 passed in 27.11s

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

542 lines
22 KiB
Python

"""A compositor and a pointer driver that are real sockets and nothing else.
Both fakes bind an actual ``AF_UNIX`` listener and speak the real wire format.
Nothing here patches :mod:`socket`, :mod:`subprocess` or any method on the code
under test: a mock would pass while the things that actually break — a half-
closed request, a reply that is prose where JSON was promised, a driver that
went away mid-gesture — went untested. This is the same choice ``tests/ipc``
made, for the same reason.
What they prove and what they do not:
* :class:`FakeCompositor` proves the **wiring** — that the broker sends the
plan's commands in the plan's order, parses what comes back and writes the
compositor's answer rather than its own intention into the record. It does
not prove that Hyprland agrees: it answers ``ok`` because it was asked
politely, and the real compositor's behaviour for ``output create headless``
is marked unverified in the plan. Every test here is a test of this broker.
* :class:`FakeDriver` runs the **real dispatcher** from
:mod:`hhstream_pointer.ops`, behind the **real handler wrapper** from
:mod:`hhstream_pointer.__main__` and the **real server** from
:mod:`hhstream_pointer.server`, with only the Wayland sink replaced by a
recorder. So the protocol, the framing, the driver's own button bookkeeping
and — importantly — which backend failures become ``ok: false`` and which
kill the connection are the shipped ones; only the compositor is absent.
The **keymap is real too**, a compiled ``us`` layout rather than a stub,
because what these tests assert about the keyboard is which evdev code and
which modifier mask went on the wire — and a stub would answer whatever the
test expected. ``keyboard=False`` builds a driver with no keyboard at all,
which is the compositor-has-no-global case.
"""
from __future__ import annotations
import json
import socket
import threading
from pathlib import Path
from typing import Any
import pytest
from hhstream_pointer import keymap as keymaps
from hhstream_pointer.__main__ import _handler
from hhstream_pointer.ops import Dispatcher
from hhstream_pointer.server import PointerServer
#: evdev codes the keyboard tests name. From ``linux/input-event-codes.h``,
#: and the values that cross the Wayland request -- never XKB keycodes, which
#: are 8 higher and never leave the driver.
KEY_A = 30
KEY_LEFTSHIFT = 42
KEY_LEFTCTRL = 29
_us_keymap: keymaps.Keymap | None = None
def us_keymap() -> keymaps.Keymap:
"""One compiled ``us`` keymap, shared.
Compiling is the slow part (xkbcommon reads the rules files), and the
object is immutable once built -- it is a lookup table plus the keymap text
-- so one per process is right. Shared deliberately rather than per-fixture
for the same reason the driver builds it once at start-up: a *second*
keymap in a process would be a second answer to "which code is `z`".
"""
global _us_keymap
if _us_keymap is None:
_us_keymap = keymaps.build(layout="us")
return _us_keymap
#: Linux's sun_path is 108 bytes including the NUL.
SUN_PATH_MAX = 107
#: The pid the fake gives a window it conjures for a window rule. Fixed, and
#: not the session's: the compositor is the authority on what is on screen, and
#: a fake that echoed the broker's own pid back could not catch a broker that
#: wrote its intention into the record instead of the read-back.
WINDOW_PID = 424242
def check_path(path: Path) -> None:
if len(str(path).encode()) > SUN_PATH_MAX:
pytest.skip(f"socket path too long for AF_UNIX ({len(str(path))} bytes): {path}")
class FakeCompositor:
"""A Hyprland request socket with state: outputs, workspaces and windows.
Laid out the way Hyprland lays one out — ``<runtime>/hypr/<signature>/
.socket.sock`` — so the broker's own discovery finds it, and answering
``j/monitors``, ``j/workspaces``, ``j/clients`` with JSON of the shape
``-j`` produces.
It is stateful because the interesting assertions are about state: an
``output create`` has to show up in the next ``monitors``, an ``output
remove`` has to make it and its windows disappear, and an orphan scan is
only meaningful against a compositor that still has the orphan.
"""
def __init__(self, runtime_dir: Path, signature: str = "fake_1700000000") -> None:
self.runtime_dir = Path(runtime_dir)
self.signature = signature
self.directory = self.runtime_dir / "hypr" / signature
self.directory.mkdir(parents=True, exist_ok=True)
self.socket_path = self.directory / ".socket.sock"
check_path(self.socket_path)
#: Commands received, in order, exactly as they arrived on the wire.
self.commands: list[str] = []
#: ``initial_class`` -> ``(workspace, monitor)`` from the window rules.
self.rules: dict[str, tuple[int, str]] = {}
#: Commands to answer with prose instead of ``ok`` (a refusal).
self.refuse: set[str] = set()
#: When true, installing an anchored window rule also conjures the
#: window it describes — which is what a compositor with a cooperating
#: application does, and what the read-back path needs to have happen.
self.auto_window = True
self._lock = threading.Lock()
self._monitors: list[dict[str, Any]] = [
{
"id": 0,
"name": "HEADLESS-1",
"x": 0,
"y": 0,
"width": 1920,
"height": 1080,
"scale": 1.0,
"activeWorkspace": {"id": 1, "name": "1"},
}
]
self._workspaces: list[dict[str, Any]] = [
{"id": 1, "name": "1", "monitor": "HEADLESS-1", "windows": 0}
]
self._clients: list[dict[str, Any]] = []
self._next_address = 0x1000
self._stop = threading.Event()
self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._sock.bind(str(self.socket_path))
self._sock.listen(8)
self._sock.settimeout(0.05)
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
# -- inspection, for the tests ---------------------------------------
def outputs(self) -> list[str]:
with self._lock:
return [m["name"] for m in self._monitors]
def workspaces_on(self, output: str) -> list[int]:
with self._lock:
return [w["id"] for w in self._workspaces if w["monitor"] == output]
def windows(self) -> list[str]:
with self._lock:
return [c["initialClass"] for c in self._clients]
def add_output(self, name: str) -> None:
"""Create an output behind the broker's back — an orphan from a crash."""
with self._lock:
self._create_output(name)
def add_window(
self, initial_class: str, workspace: int, monitor: str, *, pid: int = WINDOW_PID
) -> str:
with self._lock:
return self._create_window(initial_class, workspace, monitor, pid)
def focus(self, output: str, workspace: int) -> None:
"""Make ``workspace`` the active one on ``output`` (the foreground join)."""
with self._lock:
for monitor in self._monitors:
if monitor["name"] == output:
monitor["activeWorkspace"] = {"id": workspace, "name": str(workspace)}
def stop(self) -> None:
self._stop.set()
self._sock.close()
self._thread.join(timeout=5.0)
# -- the socket -------------------------------------------------------
def _serve(self) -> None:
while not self._stop.is_set():
try:
conn, _ = self._sock.accept()
except (TimeoutError, socket.timeout):
continue
except OSError:
return
try:
self._handle(conn)
finally:
conn.close()
def _handle(self, conn: socket.socket) -> None:
# The client half-closes after writing, so the request ends at EOF.
conn.settimeout(5.0)
received = b""
while True:
try:
chunk = conn.recv(4096)
except OSError:
return
if not chunk:
break
received += chunk
text = received.decode("utf-8", errors="replace")
flags, separator, command = text.partition("/")
if not separator:
flags, command = "", text
command = command.strip()
with self._lock:
self.commands.append(command)
reply = self._reply(command)
try:
conn.sendall(reply.encode())
except OSError:
pass
# -- the command set --------------------------------------------------
def _reply(self, command: str) -> str:
if command in self.refuse:
return "Invalid command"
if command == "version":
return "Hyprland 0.56.2 built from branch at commit 0000000\nTag: v0.56.2\n"
if command == "monitors":
return json.dumps(self._monitors)
if command == "workspaces":
return json.dumps(self._workspaces)
if command == "clients":
return json.dumps(self._clients)
if command == "cursorpos":
return json.dumps({"x": 0, "y": 0})
words = command.split()
if words[:3] == ["output", "create", "headless"] and len(words) == 4:
self._create_output(words[3])
return "ok"
if words[:2] == ["output", "remove"] and len(words) == 3:
return "ok" if self._remove_output(words[2]) else f"no such output {words[2]}"
if words[:2] == ["dispatch", "movetoworkspacesilent"] and len(words) == 3:
return self._move_to_workspace(words[2])
if words[:2] == ["dispatch", "workspace"] and len(words) == 3:
return self._show_workspace(words[2])
if words[:1] == ["keyword"]:
return self._keyword(command[len("keyword") :].strip())
return f"unknown request {command!r}"
# -- dispatches -------------------------------------------------------
def _move_to_workspace(self, spec: str) -> str:
"""``<workspace>,address:<addr>`` -- what the broker claims with.
Moving a window is the one thing that puts a real application on its
desk, because no allowlisted app carries the class the rule matches.
"""
workspace_text, _, address = spec.partition(",address:")
if not workspace_text.isdigit() or not address:
return f"malformed move {spec!r}"
client = next((c for c in self._clients if c["address"] == address), None)
if client is None:
return f"no such window {address}"
workspace = int(workspace_text)
monitor = next(
(m["name"] for m in self._monitors if m["id"] == client["monitor"]), None
)
if not any(w["id"] == workspace for w in self._workspaces):
self._workspaces.append(
{"id": workspace, "name": str(workspace), "monitor": monitor, "windows": 0}
)
for entry in self._workspaces:
if entry["id"] == client["workspace"]["id"]:
entry["windows"] = max(0, entry["windows"] - 1)
if entry["id"] == workspace:
entry["windows"] += 1
client["workspace"] = {"id": workspace, "name": str(workspace)}
return "ok"
def _show_workspace(self, workspace_text: str) -> str:
"""``workspace <n>`` -- makes that workspace the visible one.
Only meaningful on the output that holds it, which is how Hyprland
behaves: the workspace's own monitor switches to it.
"""
if not workspace_text.lstrip("-").isdigit():
return f"malformed workspace {workspace_text!r}"
workspace = int(workspace_text)
holder = next((w["monitor"] for w in self._workspaces if w["id"] == workspace), None)
if holder is None:
return f"no such workspace {workspace}"
for monitor in self._monitors:
if monitor["name"] == holder:
monitor["activeWorkspace"] = {"id": workspace, "name": str(workspace)}
return "ok"
def _keyword(self, rest: str) -> str:
name, _, body = rest.partition(" ")
if name == "workspace":
return self._keyword_workspace(body)
if name == "windowrule":
return self._keyword_windowrule(body)
if name == "monitor":
return self._keyword_monitor(body)
return f"unknown keyword {name!r}"
def _keyword_workspace(self, body: str) -> str:
# `<n>, monitor:<name>, default:true, persistent:true`
parts = [p.strip() for p in body.split(",")]
slot = int(parts[0])
monitor = next((p.split(":", 1)[1] for p in parts if p.startswith("monitor:")), None)
if monitor is None:
return "workspace rule has no monitor"
if not any(w["id"] == slot for w in self._workspaces):
self._workspaces.append(
{"id": slot, "name": str(slot), "monitor": monitor, "windows": 0}
)
return "ok"
def _keyword_windowrule(self, body: str) -> str:
# `match:initial_class ^hh-x$, workspace 1000, monitor hh-x`
parts = [p.strip() for p in body.split(",")]
match = parts[0]
if not match.startswith("match:initial_class "):
return "unsupported rule"
pattern = match[len("match:initial_class ") :]
workspace = next((p[len("workspace ") :] for p in parts if p.startswith("workspace ")), None)
monitor = next((p[len("monitor ") :] for p in parts if p.startswith("monitor ")), None)
if pattern == ".*" or monitor is None or workspace is None:
# The quarantine backstop: recorded so a test can assert it was
# installed, and first, but it conjures nothing.
self.rules[pattern] = (0, workspace or "")
return "ok"
initial_class = pattern.strip("^$")
self.rules[initial_class] = (int(workspace), monitor)
if self.auto_window:
self._create_window(initial_class, int(workspace), monitor, WINDOW_PID)
return "ok"
def _keyword_monitor(self, body: str) -> str:
# `<name>,<w>x<h>,auto,1`
parts = body.split(",")
name = parts[0]
width, _, height = parts[1].partition("x")
for monitor in self._monitors:
if monitor["name"] == name:
monitor["width"] = int(width)
monitor["height"] = int(height)
return "ok"
return f"no such monitor {name}"
# -- state ------------------------------------------------------------
def _create_output(self, name: str) -> None:
if any(m["name"] == name for m in self._monitors):
return
self._monitors.append(
{
"id": len(self._monitors),
"name": name,
"x": 1920 * len(self._monitors),
"y": 0,
"width": 1280,
"height": 720,
"scale": 1.0,
"activeWorkspace": None,
}
)
def _remove_output(self, name: str) -> bool:
before = len(self._monitors)
self._monitors = [m for m in self._monitors if m["name"] != name]
if len(self._monitors) == before:
return False
gone = {w["id"] for w in self._workspaces if w["monitor"] == name}
self._workspaces = [w for w in self._workspaces if w["monitor"] != name]
# Hyprland destroys a window with its surface; the fake destroys the
# ones that were on the output's workspaces, which is the behaviour the
# teardown cross-check is written against.
self._clients = [c for c in self._clients if c["workspace"]["id"] not in gone]
return True
def _create_window(self, initial_class: str, workspace: int, monitor: str, pid: int) -> str:
self._next_address += 0x10
address = hex(self._next_address)
self._clients.append(
{
"address": address,
"mapped": True,
"hidden": False,
"at": [0, 0],
"size": [1280, 720],
"workspace": {"id": workspace, "name": str(workspace)},
"monitor": next(
(m["id"] for m in self._monitors if m["name"] == monitor), 0
),
"class": initial_class,
"initialClass": initial_class,
"title": "a window, with a comma in its title",
"pid": pid,
}
)
for entry in self._workspaces:
if entry["id"] == workspace:
entry["windows"] += 1
# A window that maps makes its workspace the active one on its output,
# which is what the `foreground` join reads.
for entry in self._monitors:
if entry["name"] == monitor:
entry["activeWorkspace"] = {"id": workspace, "name": str(workspace)}
return address
class RecordingSink:
"""A :class:`hhstream_pointer.ops.PointerSink` that writes nothing anywhere."""
def __init__(self, *, keyboard: bool = True) -> None:
self.calls: list[tuple] = []
#: Whether a virtual keyboard was created at start-up. False is the
#: compositor-with-no-global case, which must leave the cursor working.
self.keyboard = keyboard
#: An exception to raise from the next call. The shipped driver
#: answers an ``OutputUnknown`` on the wire and lets anything else
#: take the connection down, so which one is raised here decides which
#: of the broker's two failure paths is being tested.
self.fail: Exception | None = None
def motion_absolute(self, output: str, x: float, y: float) -> None:
self._check()
self.calls.append(("warp", output, round(x, 6), round(y, 6)))
def button(self, output: str, code: int, state: int) -> None:
self._check()
self.calls.append(("button", output, code, state))
def axis(self, output: str, axis: int, value: float) -> None:
self._check()
self.calls.append(("axis", output, axis, value))
def frame(self, output: str) -> None:
self._check()
self.calls.append(("frame", output))
# -- the keyboard half -------------------------------------------------
#
# No output on either of these, and that is the assertion as much as the
# recording: a virtual keyboard is seat-global, so a sink that accepted an
# output would let a per-output implementation look correct.
def has_keyboard(self) -> bool:
return self.keyboard
def key(self, code: int, state: int) -> None:
self._check()
self.calls.append(("key", code, state))
def modifiers(self, depressed: int, latched: int, locked: int, group: int) -> None:
self._check()
self.calls.append(("modifiers", depressed, latched, locked, group))
def _check(self) -> None:
if self.fail is not None:
raise self.fail
def of(self, kind: str) -> list[tuple]:
return [c for c in self.calls if c[0] == kind]
class FakeDriver:
"""The shipped driver with its Wayland sink replaced by a recorder.
The dispatcher, the handler wrapper and the per-connection protocol loop
are the shipped ones. The **accept loop** is not: ``serve_forever`` blocks
in ``accept()`` for ever by design, and closing a listening socket does not
reliably wake a thread already inside it, so a fake that used it would cost
every test the stop timeout. Four lines with a poll interval replace it;
everything a test is actually asserting about still runs the real code.
"""
def __init__(self, socket_path: Path, *, keyboard: bool = True) -> None:
check_path(Path(socket_path))
self.socket_path = Path(socket_path)
self.sink = RecordingSink(keyboard=keyboard)
self.dispatcher = Dispatcher(self.sink, us_keymap() if keyboard else None)
self.server = PointerServer(self.socket_path, _handler(self.dispatcher))
self.server.listen()
self.connections: list[socket.socket] = []
self._stop = threading.Event()
self._listener = self.server._sock
self._listener.settimeout(0.05)
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def _serve(self) -> None:
while not self._stop.is_set():
try:
conn, _ = self._listener.accept()
except (TimeoutError, socket.timeout):
continue
except OSError:
return
conn.settimeout(None)
self.connections.append(conn)
try:
self.server._serve_connection(conn)
except Exception:
# The shipped `main` lets a backend failure out of the serve
# loop and exits with code 10 — a driver talking to a dead
# display has nothing useful left to say. The fake ends its
# thread for the same reason, so the broker sees the same
# thing: a connection that closed without answering.
return
finally:
conn.close()
def stop(self) -> None:
"""Stop the way a killed process stops: listener *and* connections.
The shipped driver never has to do this — the kernel closes its fds
when it exits — but a fake that left the broker's held connection open
would not look like a driver that restarted, which is one of the
things the client has to get right.
"""
self._stop.set()
for conn in self.connections:
try:
conn.shutdown(socket.SHUT_RDWR)
except OSError:
pass
conn.close()
self._thread.join(timeout=5.0)
self.server.close()