"""The keyboard verbs: the pointer lease, the key mirror, and the exit codes. Harness copied from ``test_pointer_verbs.py``, and the same things are real: the manager, the lease, the driver client, and the shipped dispatcher and server over a real ``AF_UNIX`` socket — plus a real compiled ``us`` keymap, so an assertion about which evdev code went on the wire is an assertion about the layout and not about a stub that agreed with it. Only the Wayland sink and the clock are substituted. Two things these tests are careful about, both of them false passes the verification doc names: * **the clock does not advance anything by itself.** A test that moves ``ManualClock`` and then asserts the lease is gone would pass against a broker that never expires anything: expiry runs in ``_expire_pointer``, from the sweeper or from the next verb, so every expiry case here calls one of those explicitly. * **a refusal is asserted by its exit code and by the sink.** "The reply said `ok: false`" is satisfied by a handler that typed the string and then errored, so the sink's call list is checked too. """ from __future__ import annotations import asyncio from pathlib import Path import pytest from fakes import KEY_A, KEY_LEFTCTRL, KEY_LEFTSHIFT, FakeDriver, us_keymap from hhstreamd.clock import ManualClock from hhstreamd.manager import ManagerConfig, ManagerError, SessionManager from hhstreamd.policy import Policy from hhstreamd.protocol import ExitCode, exit_code_for from hhstreamd.registry import ContainerState, Session, State, container_record DOWN, UP = 1, 0 def make_session(session_id: str = "foot-aaaaaa", *, container: bool = True) -> Session: return Session( id=session_id, app="foot", argv=["/usr/bin/foot"], pid=4242, pgid=4242, sid=4242, pid_starttime=918342, cmdline_sha256="9f2c", home="/home/someone", runtime_dir=f"/run/hhstream/sessions/{session_id}", created_at="2026-10-01T09:14:02Z", created_boottime=1000.0, last_activity_at="2026-10-01T09:14:02Z", last_activity_boottime=1000.0, idle_timeout_s=10800.0, state=State.READY, container=( container_record( output=f"hh-{session_id}", workspace=1000, mode=(1280, 720), created_by="broker", state=ContainerState.OWNED, ) if container else None ), ) class Harness: def __init__(self, manager: SessionManager, fake: FakeDriver, clock: ManualClock) -> None: self.manager = manager self.fake = fake self.clock = clock def add(self, session_id: str = "foot-aaaaaa", **kwargs) -> Session: return self.manager.registry.add(make_session(session_id, **kwargs)) def run(self, coro): return asyncio.run(coro) def acquire(self, session_id: str = "foot-aaaaaa") -> str: """Add the session if it is not there yet, then take the lease. Convenience, and deliberate: almost every test here is about what happens *after* a lease exists, and spelling out the `add` each time buys nothing. The tests that care about two sessions add them by hand. """ if self.manager.registry.get(session_id) is None: self.add(session_id) lease = self.run(self.manager.pointer_acquire(session_id))["lease_id"] # Acquire's own two focus warps are not what any of these tests are # about, so they are dropped here rather than skipped past in every # assertion. self.fake.sink.calls.clear() return lease def keys(self) -> list[str]: return self.manager.pointer_state()["keys"] def _harness(short_tmpdir: Path, *, keyboard: bool = True): fake = FakeDriver(short_tmpdir / "p.sock", keyboard=keyboard) clock = ManualClock(boottime=1000.0) manager = SessionManager( ManagerConfig( state_dir=short_tmpdir / "state", runtime_dir=short_tmpdir / "run", policy=Policy(), pointer_socket=fake.socket_path, pointer_ttl_s=30.0, pointer_max_s=300.0, ), clock=clock, ) try: yield Harness(manager, fake, clock) finally: if manager.driver is not None: manager.driver.close() fake.stop() @pytest.fixture def harness(short_tmpdir: Path): yield from _harness(short_tmpdir) @pytest.fixture def keyboardless(short_tmpdir: Path): """A driver whose compositor advertises no virtual-keyboard global.""" yield from _harness(short_tmpdir, keyboard=False) # --------------------------------------------------------------------------- # the lease is the pointer's # --------------------------------------------------------------------------- def test_typing_without_a_lease_is_no_lease_and_not_busy(harness): """Exit 9 and not 8: 9 says "acquire one", 8 says "wait for someone".""" harness.add() with pytest.raises(ManagerError) as exc: harness.run(harness.manager.keyboard_type("foot-aaaaaa", "nonesuch", "hello")) assert exc.value.error == "no_lease" assert exit_code_for(exc.value.error) == ExitCode.NO_LEASE assert harness.fake.sink.calls == [] def test_another_sessions_lease_is_also_no_lease(harness): harness.add("foot-aaaaaa") harness.add("foot-bbbbbb") lease = harness.acquire("foot-aaaaaa") with pytest.raises(ManagerError) as exc: harness.run(harness.manager.keyboard_type("foot-bbbbbb", lease, "hello")) # Not `pointer_busy`: B is not being told to wait its turn, it is being # told this lease id is not its own. assert exc.value.error == "no_lease" assert harness.fake.sink.calls == [] def test_a_second_acquire_while_a_key_is_held_is_busy_and_leaves_the_key(harness): harness.add("foot-aaaaaa") harness.add("foot-bbbbbb") lease = harness.acquire("foot-aaaaaa") harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down")) with pytest.raises(ManagerError) as exc: harness.run(harness.manager.pointer_acquire("foot-bbbbbb")) assert exc.value.error == "pointer_busy" assert exit_code_for(exc.value.error) == ExitCode.BUSY # Still the first holder's, and still held: a refused acquire must not # disturb a chord someone is in the middle of. assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa" assert harness.keys() == ["Shift_L"] def test_the_holder_cannot_acquire_a_second_lease_either(harness): """Unchanged by the keyboard, and asserted here because typing is where a second id would do the most damage: a half-typed chord whose lease was silently replaced fails with "stale lease" for no visible reason.""" harness.add() harness.acquire() with pytest.raises(ManagerError) as exc: harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) assert exc.value.error == "pointer_busy" # --------------------------------------------------------------------------- # what goes on the wire # --------------------------------------------------------------------------- def test_typing_a_capital_sends_the_mask_then_the_key(harness): lease = harness.acquire() reply = harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "A")) shift = us_keymap().modifier_mask("Shift_L") assert harness.fake.sink.calls == [ ("modifiers", shift, 0, 0, 0), ("key", KEY_A, DOWN), ("key", KEY_A, UP), ("modifiers", 0, 0, 0, 0), ] # No synthetic Shift keycode: this compositor does not derive the mask from # an injected key, and sending both is how a toolkit shifts twice. assert not any(c[0] == "key" and c[1] == KEY_LEFTSHIFT for c in harness.fake.sink.calls) assert reply["chars"] == 1 assert reply["keys"] == [] def test_typing_leaves_nothing_held(harness): lease = harness.acquire() harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "hello")) assert harness.keys() == [] def test_a_held_modifier_survives_a_type_and_ors_into_it(harness): lease = harness.acquire() harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Control_L", "down")) harness.fake.sink.calls.clear() reply = harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "c")) control = us_keymap().modifier_mask("Control_L") assert harness.fake.sink.calls[0] == ("modifiers", control, 0, 0, 0) # Restored to the baseline, not to zero: Control was not this type's to # lift, and `down Control_L` + `type c` + `up Control_L` is how a chord is # spelled across three CLI invocations. assert harness.fake.sink.calls[-1] == ("modifiers", control, 0, 0, 0) assert reply["keys"] == ["Control_L"] assert harness.keys() == ["Control_L"] def test_a_key_down_is_mirrored_in_the_lease_by_name(harness): lease = harness.acquire() reply = harness.run( harness.manager.keyboard_key("foot-aaaaaa", lease, "Control_L", "down") ) # The reply and the lease both speak names; only the sink sees the code. assert reply["keys"] == ["Control_L"] assert harness.keys() == ["Control_L"] assert ("key", KEY_LEFTCTRL, DOWN) in harness.fake.sink.calls def test_pointer_state_reports_held_keys_beside_held_buttons(harness): lease = harness.acquire() harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down")) harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down")) state = harness.manager.pointer_state() assert state["buttons"] == ["left"] assert state["keys"] == ["Shift_L"] def test_an_up_of_a_key_that_was_not_down_changes_nothing(harness): lease = harness.acquire() reply = harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "up")) assert reply["keys"] == [] # Nothing on the wire either: a key-up the compositor has no matching # key-down for puts its `m_pressed` out of step with ours. assert harness.fake.sink.calls == [] # --------------------------------------------------------------------------- # exit codes (the verification doc's change 1) # --------------------------------------------------------------------------- def test_an_unmappable_character_is_exit_2_and_types_nothing(harness): """The driver's token is what makes this 2 rather than 10. Without it the refusal arrives as `driver_refused`, which is exit 10 and says "the compositor failed" about a character that is simply not on the layout. `é` is the case: perfectly well formed, unmappable on `us`. """ lease = harness.acquire() with pytest.raises(ManagerError) as exc: harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "café")) assert exc.value.error == "invalid_argument" assert exit_code_for(exc.value.error) == ExitCode.USAGE # No prefix: "c", "a" and "f" must not have been typed. assert harness.fake.sink.calls == [] def test_the_refusal_does_not_carry_the_string_it_refused(harness): """A typed string is a password as often as not, and this reason is logged.""" lease = harness.acquire() with pytest.raises(ManagerError) as exc: harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "hunter2é")) assert "hunter2" not in exc.value.reason assert "é" not in exc.value.reason assert "scalar 7" in exc.value.reason def test_an_unknown_keysym_is_exit_2(harness): lease = harness.acquire() with pytest.raises(ManagerError) as exc: harness.run( harness.manager.keyboard_key("foot-aaaaaa", lease, "NoSuchKeysym", "down") ) assert exit_code_for(exc.value.error) == ExitCode.USAGE assert harness.keys() == [] @pytest.mark.parametrize( "text, fragment", [(None, "must be a string"), (7, "must be a string"), (["a"], "must be a string")], ) def test_a_text_that_is_not_a_string_is_exit_2_before_the_driver(harness, text, fragment): lease = harness.acquire() with pytest.raises(ManagerError) as exc: harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, text)) assert exc.value.error == "invalid_argument" assert fragment in exc.value.reason assert harness.fake.sink.calls == [] def test_a_string_over_the_cap_is_exit_2_at_the_broker(harness): """Checked here and not only in the driver, because only a broker-side `invalid_argument` produces exit 2 — a driver-side length refusal would arrive as a compositor failure unless it carried the token.""" from hhstreamd.manager import MAX_TYPE_SCALARS lease = harness.acquire() with pytest.raises(ManagerError) as exc: harness.run( harness.manager.keyboard_type("foot-aaaaaa", lease, "a" * (MAX_TYPE_SCALARS + 1)) ) assert exc.value.error == "invalid_argument" assert str(MAX_TYPE_SCALARS) in exc.value.reason assert harness.fake.sink.calls == [] def test_exactly_the_cap_is_accepted(harness): from hhstreamd.manager import MAX_TYPE_SCALARS lease = harness.acquire() reply = harness.run( harness.manager.keyboard_type("foot-aaaaaa", lease, "a" * MAX_TYPE_SCALARS) ) assert reply["chars"] == MAX_TYPE_SCALARS @pytest.mark.parametrize("state", [None, "sideways", "DOWN", 1]) def test_a_bad_key_state_is_exit_2(harness, state): lease = harness.acquire() with pytest.raises(ManagerError) as exc: harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "a", state)) assert exc.value.error == "invalid_argument" assert harness.fake.sink.calls == [] def test_no_keyboard_global_is_exit_10_and_the_cursor_still_works(keyboardless): """A compositor with no `zwp_virtual_keyboard_manager_v1`. Exit 10 and not 2: the caller's request was fine. And the pointer half has to keep working, which is the whole reason a missing keyboard global does not abort the driver's start-up the way a version-1 pointer manager does. """ keyboardless.add() lease = keyboardless.acquire() with pytest.raises(ManagerError) as exc: keyboardless.run(keyboardless.manager.keyboard_type("foot-aaaaaa", lease, "hi")) assert exc.value.error == "driver_refused" assert exit_code_for(exc.value.error) == ExitCode.COMPOSITOR # The cursor is unaffected. moved = keyboardless.run( keyboardless.manager.pointer_move("foot-aaaaaa", lease, x=0.25, y=0.75) ) assert moved["bookmark"]["x"] == 0.25 def test_a_refused_key_is_not_recorded_as_held(harness): """The driver first, then the mirror — the `pointer_button` order. The reverse mistake is harmless (`release_all` lifts what the *driver* recorded), but recording a key the driver refused means `release_all` later asks it to lift something it never pressed. """ lease = harness.acquire() with pytest.raises(ManagerError): harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "NoSuchKeysym", "down")) assert harness.keys() == [] assert harness.manager.pointer_state()["keys"] == [] # --------------------------------------------------------------------------- # the TTL # --------------------------------------------------------------------------- def test_typing_refreshes_the_lease(harness): """`type` goes through `_refresh`, so it moves the idle deadline. The clock is advanced in two steps with a `type` between them: 20s, type, 20s. Without the refresh that is 40s against a 30s TTL and the lease is gone; with it, the second 20s is measured from the type. """ harness.add() lease = harness.acquire() harness.clock.advance(20.0) harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "hello")) harness.clock.advance(20.0) # The next verb is what notices an expiry, so this is the honest way to ask # "is the lease still alive" -- not reading `state()`, which never expires # anything. harness.run(harness.manager._expire_pointer()) assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa" def test_the_hard_cap_still_beats_a_typing_loop(harness): harness.add() lease = harness.acquire() for _ in range(20): harness.clock.advance(20.0) with __import__("contextlib").suppress(ManagerError): harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "x")) assert harness.manager.pointer.state()["holder"] is None def test_an_expired_lease_lifts_the_key_it_left_down(harness): """The expiry contract, with a key: read before `expire()`, then one `release_all` on the driver, and the mask zeroed after the key-up.""" harness.add() lease = harness.acquire() harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down")) harness.fake.sink.calls.clear() harness.clock.advance(31.0) expired = harness.run(harness.manager._expire_pointer()) assert expired["keys_lifted"] == ["Shift_L"] assert harness.fake.sink.calls == [ ("key", KEY_LEFTSHIFT, UP), # Not optional. A virtual key-up clears no modifier state on this # compositor, so without this the next holder inherits Shift. ("modifiers", 0, 0, 0, 0), ] assert harness.manager.pointer.state()["holder"] is None assert harness.keys() == [] def test_expiry_lifts_buttons_and_keys_in_one_release_all(harness): harness.add() lease = harness.acquire() harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down")) harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Control_L", "down")) harness.fake.sink.calls.clear() harness.clock.advance(31.0) expired = harness.run(harness.manager._expire_pointer()) assert expired["buttons_lifted"] == ["left"] assert expired["keys_lifted"] == ["Control_L"] # Buttons first with their frame, then keys, then the mask. One round trip. assert [c[0] for c in harness.fake.sink.calls] == [ "button", "frame", "key", "modifiers", ] def test_a_held_key_does_not_leak_to_the_next_holder(harness): harness.add("foot-aaaaaa") harness.add("foot-bbbbbb") lease = harness.acquire("foot-aaaaaa") harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down")) harness.clock.advance(31.0) harness.run(harness.manager._expire_pointer()) harness.acquire("foot-bbbbbb") assert harness.keys() == [] def test_typing_does_not_count_as_activity(harness): """`touch` is the only mark of activity, and typing is not it. Both halves are asserted: the timestamp and the counter. A future change that moved the timestamp without counting a command would pass a counter-only test. """ session = harness.add() lease = harness.acquire() before_at = session.last_activity_at before_boottime = session.last_activity_boottime before_count = session.command_count harness.clock.advance(5.0) harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, "hello")) harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down")) assert session.last_activity_boottime == before_boottime assert session.last_activity_at == before_at assert session.command_count == before_count # --------------------------------------------------------------------------- # release, kill, and the audit # --------------------------------------------------------------------------- def test_release_lifts_held_keys_and_reports_them(harness): harness.add() lease = harness.acquire() harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down")) reply = harness.run(harness.manager.pointer_release("foot-aaaaaa", lease)) assert reply["keys_lifted"] == ["Shift_L"] assert reply["buttons_lifted"] == [] assert harness.manager.pointer_state()["keys"] == [] def test_killing_the_holder_lifts_its_keys(harness): harness.add() lease = harness.acquire() harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Control_L", "down")) harness.fake.sink.calls.clear() harness.run(harness.manager._drop_lease_for(harness.manager.registry.get("foot-aaaaaa"), "kill")) assert ("key", KEY_LEFTCTRL, UP) in harness.fake.sink.calls assert ("modifiers", 0, 0, 0, 0) in harness.fake.sink.calls assert harness.manager.pointer.state()["holder"] is None assert lease # the id is still the one we were given; nothing replayed it def test_the_audit_records_a_character_count_and_never_the_text(harness): harness.add() lease = harness.acquire() secret = "hunter2" harness.run(harness.manager.keyboard_type("foot-aaaaaa", lease, secret)) events = harness.manager.audit.tail(50, session="foot-aaaaaa") typed = [e for e in events if e.get("event") == "keyboard_type"] assert len(typed) == 1 assert typed[0]["chars"] == len(secret) assert "text" not in typed[0] # And not hiding anywhere else in the line either. assert secret not in str(typed[0]) def test_the_audit_records_a_keysym_name_which_is_not_a_secret(harness): harness.add() lease = harness.acquire() harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Return", "down")) events = harness.manager.audit.tail(50, session="foot-aaaaaa") pressed = [e for e in events if e.get("event") == "keyboard_key"] assert pressed[-1]["key"] == "Return" assert pressed[-1]["state"] == "down" def test_the_expiry_audit_event_records_the_keys_it_lifted(harness): harness.add() lease = harness.acquire() harness.run(harness.manager.keyboard_key("foot-aaaaaa", lease, "Shift_L", "down")) harness.clock.advance(31.0) harness.run(harness.manager._expire_pointer()) events = harness.manager.audit.tail(50) timeout = [e for e in events if e.get("event") == "pointer_lease_timeout"][-1] assert timeout["keys_pressed"] == ["Shift_L"] assert timeout["keys_lifted"] == ["Shift_L"] # --------------------------------------------------------------------------- # acquire takes the keyboard, not only the cursor # --------------------------------------------------------------------------- def test_acquire_sends_two_motions_so_keyboard_focus_moves(harness): """One warp is not enough, and that is measured, not assumed. Hyprland zeroes `m_mousePosDelta` when the previous cursor movement was over 0.5s ago and compares it against `follow_mouse_threshold` (0) to decide keyboard focus, so a single warp onto an idle cursor delivers `wl_pointer.enter` and no `wl_keyboard.enter`. The aimed window gets the cursor and the previously focused one keeps the keys — and then the first key of the lease goes to the wrong window. A check that only looked for pointer delivery would pass while that happened, which is why this asserts the *pair*. """ harness.add() reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) warps = harness.fake.sink.of("warp") assert len(warps) == 2, "a single warp does not move keyboard focus" # The second one is the bookmark, so a restore is not a few pixels off. assert (warps[1][2], warps[1][3]) == (0.5, 0.5) assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.5, 0.5) # And they are different *floored* pixels at the frozen 1280x720 container # mode: `mouseMoveUnified` returns before it touches the delta when the # floored position has not changed. assert round(warps[0][3] * 720) != round(warps[1][3] * 720) assert reply["focus"] == "warp" def test_the_focus_mechanism_is_recorded_in_the_audit(harness): harness.add() harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) events = harness.manager.audit.tail(50, session="foot-aaaaaa") acquired = [e for e in events if e.get("event") == "pointer_acquired"][-1] # So a session that ends up typing into the wrong window can be told apart # from one that never tried to take focus. assert acquired["focus"] == "warp"