Files
hyprland-headless-stream-pl…/tests/pointer/test_lease.py
HermenixandClaude Opus 5 f931858f30 Stage 1: the driver learns to type
`zwp_virtual_keyboard_v1`, spoken by the process that already speaks
`zwlr_virtual_pointer_v1`. One device for the seat, one keymap uploaded
once, keysym names on our socket and evdev codes only on the Wayland
request -- the division buttons.py already draws.

keymap.py is the new seam, and it holds the three decisions that have a
wrong version which looks right:

  * A capital is the MASK, not a synthetic Shift keycode. Hyprland's
    virtual keyboard never runs updateXkbStateWithKey, so a virtual
    KEY_LEFTSHIFT changes no modifier state at all -- and sending both
    is how a toolkit applies Shift twice.
  * A modifier is whatever the keymap says is one, measured by pressing
    each key in a throwaway xkb state. Not a name list: `@` on `de` is a
    level-three symbol, and a Shift-only special case types the wrong
    character. (The measured set is also smaller than the canonical one,
    because no keycode on us/pc105 carries Meta or Hyper.)
  * A lock is not a modifier. Caps_Lock reports a *locked* mask, so
    `type` refuses while it is held rather than guessing the case.

The whole string resolves before anything is emitted, and every refusal
names the scalar INDEX, never the character: these messages reach the
driver's log and the string is a password as often as not.

Folding in the review's changes 1, 2, 3 and 6:

  1 a Rejected now carries a `kind`. A bad keysym or an unmappable
    character is `invalid_argument`; a missing keyboard global is
    `refused`. Without the token the broker would have to tell exit 2
    from exit 10 by reading English, and _drive maps every `ok: false`
    to driver_refused today.
  2 the keymap `size` on the wire includes the trailing NUL, and the fd
    outlives a roundtrip rather than a flush. Hyprland mmaps exactly
    that many bytes and hands the pointer to xkb_keymap_new_from_string.
  3 release_all lifts buttons, then keys in press order, then zeroes the
    mask -- and the mask only if something set it, so a compositor with
    no keyboard global still gets its buttons lifted. One release_all is
    the whole of expiry; an exception in the key half would abandon it.
  6 `key` and `type` never call _aimed(). A keyboard has no output, and
    one test deliberately never warps so that stays true.

Also: `--xkb-layout/-model/-variant/-options`, compiled BEFORE any
Wayland call so a bad layout is exit 2 rather than exit 10; a comma in
the layout refused outright, because v1 always sends group 0 and
xkbcommon would hand back a second group nothing could reach; the
keymap uploaded after connect and before listen, with one
modifiers(0,0,0,0) after it; and xkbcommon as a hard, non-optional
dependency -- an optional one would let test_keymap.py skip, and the
unmappable-character path is the one that must not rot.

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

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

345 lines
12 KiB
Python

"""The lease state machine (CONTRACT-sessions.md §3.3).
There is one cursor on this compositor and every virtual pointer writes to it,
so the lease is the only thing standing between two agents and a mouse that
jumps between their windows. These tests are therefore about refusal as much as
about success: who is turned away, and with what name attached.
"""
from __future__ import annotations
import pytest
from hhstreamd.pointer import Bookmark, LeaseBusy, LeaseInvalid, PointerLease
def test_unheld_lease_reports_nothing_held(lease):
assert lease.state() == {
"holder": None,
"since": None,
"lease_id": None,
"expires_at": None,
}
assert lease.pressed() == []
assert lease.expire() is None
def test_acquire_then_release_is_a_full_cycle(lease, clock):
lease_id = lease.acquire("alpha")
assert lease.state() == {
"holder": "alpha",
"since": 1000.0,
"lease_id": lease_id,
"expires_at": 1030.0,
}
outcome = lease.release("alpha", lease_id, "done")
assert outcome.reason == "done"
assert outcome.bookmark is None
assert outcome.buttons_lifted == []
assert lease.state()["holder"] is None
# And the pointer is free again, to a different session.
assert lease.acquire("beta") != lease_id
def test_second_holder_is_rejected_by_name(lease):
lease.acquire("alpha")
with pytest.raises(LeaseBusy) as caught:
lease.acquire("beta")
assert caught.value.holder == "alpha"
assert "alpha" in str(caught.value)
def test_reacquiring_as_the_same_session_is_also_busy(lease):
"""A second lease_id for one session would invalidate the first mid-drag."""
lease.acquire("alpha")
with pytest.raises(LeaseBusy) as caught:
lease.acquire("alpha")
assert caught.value.holder == "alpha"
def test_a_verb_from_a_non_holder_is_invalid(lease):
lease_id = lease.acquire("alpha")
with pytest.raises(LeaseInvalid, match="held by alpha"):
lease.refresh("beta", lease_id)
with pytest.raises(LeaseInvalid, match="held by alpha"):
lease.release("beta", lease_id, "theft")
with pytest.raises(LeaseInvalid, match="held by alpha"):
lease.press("beta", "left")
with pytest.raises(LeaseInvalid, match="held by alpha"):
lease.unpress("beta", "left")
def test_a_verb_on_an_unheld_lease_is_invalid(lease):
with pytest.raises(LeaseInvalid, match="no pointer lease"):
lease.refresh("alpha", "whatever")
with pytest.raises(LeaseInvalid, match="no pointer lease"):
lease.press("alpha", "left")
def test_a_stale_lease_id_is_rejected(lease, clock):
"""The session is right and the id is not: the classic retry-after-expiry."""
first = lease.acquire("alpha")
lease.release("alpha", first, "done")
second = lease.acquire("alpha")
assert second != first
with pytest.raises(LeaseInvalid, match="stale lease_id"):
lease.refresh("alpha", first)
with pytest.raises(LeaseInvalid, match="stale lease_id"):
lease.release("alpha", first, "late")
with pytest.raises(LeaseInvalid, match="stale lease_id"):
lease.mark("alpha", first, Bookmark(0.5, 0.5, "hh-a", "2026-10-01T00:00:00Z"))
# The real holder is untouched by the stale caller's attempts.
lease.refresh("alpha", second)
def test_refresh_pushes_the_idle_deadline_but_not_the_hard_cap(lease, clock):
lease_id = lease.acquire("alpha")
clock.advance(20.0)
lease.refresh("alpha", lease_id)
assert lease.state()["expires_at"] == 1050.0
assert lease.expire() is None
# Keep refreshing inside the idle window, right up to the hard cap.
while clock.now < 1299.0:
clock.advance(min(20.0, 1299.0 - clock.now))
lease.refresh("alpha", lease_id)
assert lease.expire() is None
assert lease.state()["expires_at"] == 1329.0
clock.advance(1.0) # t = 1300, the hard deadline, which did not move
info = lease.expire()
assert info is not None
assert info.hard_deadline == 1300.0
def test_ttl_expiry_releases_the_lease(lease, clock):
lease_id = lease.acquire("alpha")
clock.advance(29.9)
assert lease.expire() is None
clock.advance(0.1) # exactly at the deadline, which is inclusive
info = lease.expire()
assert info is not None
assert info.session_id == "alpha"
assert info.lease_id == lease_id
assert info.acquired_at == 1000.0
assert info.expires_at == 1030.0
assert info.hard_deadline == 1300.0
assert lease.state()["holder"] is None
assert lease.expire() is None # idempotent: nothing left to reap
def test_hard_cap_expiry_beats_an_endless_refresh_loop(clock):
lease = PointerLease(ttl_s=30.0, max_s=100.0, clock=clock)
lease_id = lease.acquire("alpha")
for _ in range(9):
clock.advance(10.0)
lease.refresh("alpha", lease_id)
assert lease.expire() is None, "the idle clock keeps being pushed out"
clock.advance(10.0) # t = 1100, the hard deadline
info = lease.expire()
assert info is not None
assert info.hard_deadline == 1100.0
# The idle deadline was still in the future; the cap is what fired.
assert info.expires_at > info.hard_deadline
def test_an_expired_lease_cannot_be_refreshed_back_to_life(lease, clock):
lease_id = lease.acquire("alpha")
clock.advance(31.0)
with pytest.raises(LeaseInvalid, match="expired"):
lease.refresh("alpha", lease_id)
# Still held, because only expire() releases: the broker has to be told so
# it can lift buttons on the driver.
assert lease.state()["holder"] == "alpha"
assert lease.expire() is not None
def test_expire_does_nothing_when_nothing_is_due(lease, clock):
lease.acquire("alpha")
clock.advance(29.0)
assert lease.expire() is None
assert lease.state()["holder"] == "alpha"
def test_press_and_lift_one_button(lease):
lease_id = lease.acquire("alpha")
lease.press("alpha", "left")
assert lease.pressed() == ["left"]
assert lease.unpress("alpha", "left") == ["left"]
assert lease.pressed() == []
assert lease.release("alpha", lease_id, "done").buttons_lifted == []
def test_lifting_a_button_that_is_not_down_reports_nothing(lease):
lease.acquire("alpha")
assert lease.unpress("alpha", "left") == []
lease.press("alpha", "left")
lease.unpress("alpha", "left")
assert lease.unpress("alpha", "left") == []
def test_multiple_buttons_are_tracked_and_lifted_independently(lease):
lease_id = lease.acquire("alpha")
lease.press("alpha", "left")
lease.press("alpha", "right")
lease.press("alpha", "middle")
assert lease.pressed() == ["left", "right", "middle"]
assert lease.unpress("alpha", "right") == ["right"]
assert lease.pressed() == ["left", "middle"]
# A release lifts whatever is still down, oldest first.
outcome = lease.release("alpha", lease_id, "timeout")
assert outcome.buttons_lifted == ["left", "middle"]
assert outcome.reason == "timeout"
assert lease.pressed() == []
def test_pressing_twice_leaves_one_button_down(lease):
lease.acquire("alpha")
lease.press("alpha", "left")
lease.press("alpha", "left")
assert lease.pressed() == ["left"]
assert lease.unpress("alpha", "left") == ["left"]
assert lease.pressed() == []
def test_expiry_does_not_leak_buttons_to_the_next_holder(lease, clock):
lease.acquire("alpha")
lease.press("alpha", "left")
clock.advance(31.0)
assert lease.expire() is not None
assert lease.pressed() == []
lease.acquire("beta")
assert lease.pressed() == []
def test_bookmark_survives_to_the_release_outcome(lease):
lease_id = lease.acquire("alpha")
mark = Bookmark(x=0.25, y=0.75, output="hh-alpha", at="2026-10-01T12:00:00Z")
lease.mark("alpha", lease_id, mark)
assert lease.release("alpha", lease_id, "done").bookmark == mark
def test_a_new_lease_starts_without_the_previous_bookmark(lease):
first = lease.acquire("alpha")
lease.mark("alpha", first, Bookmark(0.25, 0.75, "hh-alpha", "2026-10-01T12:00:00Z"))
lease.release("alpha", first, "done")
second = lease.acquire("beta")
assert lease.release("beta", second, "done").bookmark is None
def test_defaults_match_the_contract():
lease = PointerLease()
assert (lease.ttl_s, lease.max_s) == (30.0, 300.0)
# -- keys: the same mirror, and the same ordering rule ----------------------
#
# PLAN §6.7 proposed a `keyboard` flag on the lease. These tests are the
# argument against it: a boolean cannot say to lift `Control_L` and not `a`,
# and it cannot say which went down first.
def test_press_and_lift_one_key(lease):
lease_id = lease.acquire("alpha")
lease.press_key("alpha", "Shift_L")
assert lease.keys_pressed() == ["Shift_L"]
assert lease.unpress_key("alpha", "Shift_L") == ["Shift_L"]
assert lease.keys_pressed() == []
assert lease.release("alpha", lease_id, "done").keys_lifted == []
def test_lifting_a_key_that_is_not_down_reports_nothing(lease):
lease.acquire("alpha")
assert lease.unpress_key("alpha", "Shift_L") == []
lease.press_key("alpha", "Shift_L")
lease.unpress_key("alpha", "Shift_L")
assert lease.unpress_key("alpha", "Shift_L") == []
def test_keys_are_kept_in_press_order(lease):
lease_id = lease.acquire("alpha")
for name in ("Control_L", "Shift_L", "a"):
lease.press_key("alpha", name)
assert lease.keys_pressed() == ["Control_L", "Shift_L", "a"]
assert lease.unpress_key("alpha", "Shift_L") == ["Shift_L"]
assert lease.keys_pressed() == ["Control_L", "a"]
outcome = lease.release("alpha", lease_id, "timeout")
assert outcome.keys_lifted == ["Control_L", "a"]
assert lease.keys_pressed() == []
def test_pressing_a_key_twice_leaves_one_down(lease):
lease.acquire("alpha")
lease.press_key("alpha", "a")
lease.press_key("alpha", "a")
assert lease.keys_pressed() == ["a"]
def test_keys_and_buttons_are_tracked_separately(lease):
lease_id = lease.acquire("alpha")
lease.press("alpha", "left")
lease.press_key("alpha", "Shift_L")
assert (lease.pressed(), lease.keys_pressed()) == (["left"], ["Shift_L"])
outcome = lease.release("alpha", lease_id, "done")
assert (outcome.buttons_lifted, outcome.keys_lifted) == (["left"], ["Shift_L"])
def test_a_non_holder_cannot_press_a_key(lease):
lease.acquire("alpha")
with pytest.raises(LeaseInvalid):
lease.press_key("beta", "a")
with pytest.raises(LeaseInvalid):
lease.unpress_key("beta", "a")
def test_expire_still_returns_no_key_list_so_the_broker_must_read_first(lease, clock):
"""CONTRACT-sessions.md §3.3, unchanged by the keyboard.
`expire()` is still `LeaseInfo` and carries neither buttons nor keys. The
ordering it forces -- read, *then* expire -- is the only thing stopping a
key from being forgotten before the driver has been told to lift it, and
widening the return would make that ordering optional.
"""
lease.acquire("alpha")
lease.press_key("alpha", "Shift_L")
clock.advance(31.0)
# The broker's order, and it is not interchangeable.
held = lease.keys_pressed()
info = lease.expire()
assert held == ["Shift_L"]
assert info is not None
assert not hasattr(info, "keys_lifted")
assert not hasattr(info, "buttons_lifted")
assert lease.keys_pressed() == []
def test_expiry_does_not_leak_keys_to_the_next_holder(lease, clock):
"""A held Shift must not become the next session's Shift."""
lease.acquire("alpha")
lease.press_key("alpha", "Shift_L")
clock.advance(31.0)
assert lease.expire() is not None
lease.acquire("beta")
assert lease.keys_pressed() == []