Files
hyprland-headless-stream-pl…/tests/sessions/unit/test_driver_client.py
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

226 lines
7.0 KiB
Python

"""The broker's end of the driver socket, against a real driver socket.
Every test here goes over an actual ``AF_UNIX`` connection to the shipped
:class:`hhstream_pointer.server.PointerServer` running the shipped
:class:`hhstream_pointer.ops.Dispatcher`. Only the Wayland sink is a
recorder. Mocking the socket would have tested that this module can call
``json.dumps``; what it has to be right about is the half of the protocol it
does not own.
"""
from __future__ import annotations
import socket
import threading
from pathlib import Path
import pytest
from fakes import FakeDriver
from hhstream_pointer.backend import CompositorUnavailable as DriverDied
from hhstream_pointer.backend import OutputUnknown
from hhstreamd.driver import DriverRejected, DriverUnavailable, PointerDriver
@pytest.fixture
def driver(short_tmpdir: Path):
fake = FakeDriver(short_tmpdir / "p.sock")
client = PointerDriver(fake.socket_path, timeout_s=5.0)
try:
yield client, fake
finally:
client.close()
fake.stop()
def test_a_warp_reaches_the_sink_as_output_local_coordinates(driver):
client, fake = driver
client.warp("hh-a", 0.25, 0.75)
assert fake.sink.calls == [("warp", "hh-a", 0.25, 0.75)]
def test_a_gesture_arrives_in_order_and_is_committed_by_a_frame(driver):
"""Nothing the driver is sent reaches the compositor until a frame."""
client, fake = driver
client.warp("hh-a", 0.5, 0.5)
client.button("left", "down")
client.button("left", "up")
client.frame()
assert fake.sink.calls == [
("warp", "hh-a", 0.5, 0.5),
("button", "hh-a", 0x110, 1),
("button", "hh-a", 0x110, 0),
("frame", "hh-a"),
]
def test_pressed_reports_what_the_driver_believes_is_down(driver):
client, _ = driver
client.warp("hh-a", 0.5, 0.5)
assert client.pressed() == []
client.button("right", "down")
client.button("middle", "down")
assert client.pressed() == ["right", "middle"]
client.button("right", "up")
assert client.pressed() == ["middle"]
def test_release_all_lifts_everything_and_says_what_it_lifted(driver):
client, fake = driver
client.warp("hh-a", 0.5, 0.5)
client.button("left", "down")
client.button("right", "down")
# One call, two lists: there is one `release_all` op and one expiry call
# site, so buttons and keys come back together rather than needing a
# second request that could be forgotten.
assert client.release_all() == (["left", "right"], [])
assert client.pressed() == []
# Lifted through the pointer each went down on, then one frame for it.
assert fake.sink.calls[-3:] == [
("button", "hh-a", 0x110, 0),
("button", "hh-a", 0x111, 0),
("frame", "hh-a"),
]
def test_release_all_on_an_idle_driver_is_an_empty_list_not_an_error(driver):
"""The expiry path calls this unconditionally; it must be safe."""
client, _ = driver
assert client.release_all() == ([], [])
def test_a_refusal_is_carried_back_and_is_not_a_lost_connection(driver):
"""``ok: false`` is the driver working, so the client must stay usable."""
client, fake = driver
with pytest.raises(DriverRejected) as exc:
client.warp("hh-a", 1.5, 0.5)
assert "0..1" in str(exc.value)
client.warp("hh-a", 0.5, 0.5)
assert fake.sink.calls == [("warp", "hh-a", 0.5, 0.5)]
def test_a_button_before_any_warp_is_refused_rather_than_aimed_at_nothing(driver):
client, _ = driver
with pytest.raises(DriverRejected) as exc:
client.button("left", "down")
assert "warp" in str(exc.value)
def test_an_unknown_output_is_a_refusal_and_leaves_the_driver_usable(driver):
"""Routine: the broker can be racing a container it just tore down."""
client, fake = driver
fake.sink.fail = OutputUnknown("no output hh-gone")
with pytest.raises(DriverRejected) as exc:
client.warp("hh-gone", 0.5, 0.5)
assert "hh-gone" in str(exc.value)
fake.sink.fail = None
client.warp("hh-a", 0.5, 0.5)
assert fake.sink.of("warp") == [("warp", "hh-a", 0.5, 0.5)]
def test_a_driver_that_dies_mid_gesture_is_unavailable_not_a_refusal(driver):
"""A lost compositor takes the driver's connection with it (by design).
The broker has to be able to tell this from a refusal, because the cursor
is now in an unknown state and the lease has to go rather than carry on.
"""
client, fake = driver
fake.sink.fail = DriverDied("the compositor hung up")
with pytest.raises(DriverUnavailable):
client.warp("hh-a", 0.5, 0.5)
def test_no_driver_at_all_is_unavailable_and_never_a_silent_no_op(short_tmpdir: Path):
client = PointerDriver(short_tmpdir / "absent.sock", timeout_s=0.5)
with pytest.raises(DriverUnavailable) as exc:
client.release_all()
assert "absent.sock" in str(exc.value)
def test_a_driver_that_restarts_is_reconnected_to_rather_than_lost(short_tmpdir: Path):
"""The held connection dies with the driver; the next verb must not."""
path = short_tmpdir / "p.sock"
first = FakeDriver(path)
client = PointerDriver(path, timeout_s=5.0)
client.warp("hh-a", 0.1, 0.1)
first.stop()
second = FakeDriver(path)
try:
client.warp("hh-a", 0.2, 0.2)
assert second.sink.calls == [("warp", "hh-a", 0.2, 0.2)]
finally:
client.close()
second.stop()
def test_a_driver_that_answers_nothing_is_unavailable_within_the_timeout(short_tmpdir: Path):
"""A wedged driver must time out, not hang the verb that called it."""
path = short_tmpdir / "mute.sock"
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
listener.bind(str(path))
listener.listen(1)
accepted: list[socket.socket] = []
def accept_and_say_nothing() -> None:
conn, _ = listener.accept()
accepted.append(conn)
thread = threading.Thread(target=accept_and_say_nothing, daemon=True)
thread.start()
client = PointerDriver(path, timeout_s=0.3)
try:
with pytest.raises(DriverUnavailable):
client.pressed()
finally:
client.close()
thread.join(timeout=5.0)
for conn in accepted:
conn.close()
listener.close()
def test_a_reply_that_is_not_the_protocol_is_unavailable_not_an_empty_answer(
short_tmpdir: Path,
):
""""I could not read the answer" must never render as "nothing was down"."""
path = short_tmpdir / "liar.sock"
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
listener.bind(str(path))
listener.listen(1)
def answer_nonsense() -> None:
conn, _ = listener.accept()
with conn:
conn.recv(4096)
conn.sendall(b'{"ok":true,"buttons":"left"}\n')
thread = threading.Thread(target=answer_nonsense, daemon=True)
thread.start()
client = PointerDriver(path, timeout_s=2.0)
try:
with pytest.raises(DriverUnavailable) as exc:
client.pressed()
assert "list of names" in str(exc.value)
finally:
client.close()
thread.join(timeout=5.0)
listener.close()