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

724 lines
27 KiB
Python

"""The pointer verbs: the lease, the bookmark, and never leaving a button down.
The broker end is real (the manager, the lease, the driver client) and so is
the driver end (the shipped dispatcher and server over a real ``AF_UNIX``
socket). Only the Wayland sink and the clock are substituted — the clock
because expiry has to be testable without sleeping for thirty seconds, and the
sink because this machine has no compositor.
"""
from __future__ import annotations
import asyncio
from pathlib import Path
import pytest
from fakes import FakeDriver
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
LEFT = 0x110
DOWN, UP = 1, 0
#: ``wl_pointer_axis``, mirrored from the driver for the same reason the button
#: codes above are: these tests assert the events, so they name the wire values.
VERTICAL, HORIZONTAL = 0, 1
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)
@pytest.fixture
def harness(short_tmpdir: Path):
fake = FakeDriver(short_tmpdir / "p.sock")
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()
# ---------------------------------------------------------------------------
# acquiring
# ---------------------------------------------------------------------------
def test_acquire_with_no_bookmark_aims_at_the_centre_of_the_container(harness):
harness.add()
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert reply["lease_id"]
assert reply["bookmark"] == {
"x": 0.5,
"y": 0.5,
"output": "hh-foot-aaaaaa",
"at": reply["bookmark"]["at"],
}
# TWO motions, and the order is the point. One warp onto an idle cursor
# delivers wl_pointer.enter and no wl_keyboard.enter: Hyprland zeroes
# `m_mousePosDelta` when the previous movement was over 0.5s ago, and
# keyboard focus is that delta against `follow_mouse_threshold`. So the
# nudge goes first and the real target second, the second motion carries a
# non-zero delta, and the cursor finishes at the bookmark.
assert harness.fake.sink.calls == [
("warp", "hh-foot-aaaaaa", 0.5, 0.504),
("frame", "hh-foot-aaaaaa"),
("warp", "hh-foot-aaaaaa", 0.5, 0.5),
("frame", "hh-foot-aaaaaa"),
]
# And the two really are different pixels at the frozen 1280x720 container
# mode: `mouseMoveUnified` returns before it touches the delta when the
# floored position has not changed, so a sub-pixel nudge would move the
# cursor and leave the keys where they were.
first, second = harness.fake.sink.of("warp")
assert round(first[3] * 720) != round(second[3] * 720)
assert reply["focus"] == "warp"
def test_acquire_restores_the_position_the_session_was_left_at(harness):
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.25, y=0.75))
harness.run(harness.manager.pointer_release("foot-aaaaaa", lease))
harness.fake.sink.calls.clear()
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.25, 0.75)
# The nudge, then the restored position. The bookmark is where the cursor
# is left, so the second warp is the one that has to be the bookmark --
# the reverse order would restore the session a few pixels off, every time.
assert harness.fake.sink.of("warp") == [
("warp", "hh-foot-aaaaaa", 0.25, 0.754),
("warp", "hh-foot-aaaaaa", 0.25, 0.75),
]
assert session.pointer["bookmark"]["x"] == 0.25
assert session.pointer["bookmark"]["y"] == 0.75
def test_restore_false_goes_to_the_centre_even_with_a_bookmark(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.1, y=0.1))
harness.run(harness.manager.pointer_release("foot-aaaaaa", lease))
harness.fake.sink.calls.clear()
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa", restore=False))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.5, 0.5)
def test_a_bookmark_from_another_output_is_not_a_position_in_this_one(harness):
"""A container is rebuilt with a new name; the old fraction is not a place."""
session = harness.add()
session.pointer = {
"bookmark": {"x": 0.9, "y": 0.9, "output": "hh-gone", "at": "2026-01-01T00:00:00Z"},
"last_released_at": None,
"released_by": None,
}
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.5, 0.5)
def test_a_second_session_is_told_who_holds_the_cursor(harness):
"""There is one cursor, so the answer is "wait", with a name attached."""
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
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
assert exc.value.fields["holder"] == "foot-aaaaaa"
def test_a_session_with_no_container_has_nowhere_to_aim(harness):
"""Aiming at "wherever the cursor is" is how a click lands next door."""
harness.add("foot-aaaaaa", container=False)
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert exc.value.error == "no_container"
assert exit_code_for(exc.value.error) == ExitCode.COMPOSITOR
def test_a_lease_that_could_not_be_aimed_is_not_left_held(harness):
harness.add()
harness.fake.stop()
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert exc.value.error == "driver_unavailable"
assert exit_code_for(exc.value.error) == ExitCode.COMPOSITOR
assert harness.manager.pointer.state()["holder"] is None
# ---------------------------------------------------------------------------
# moving
# ---------------------------------------------------------------------------
def test_every_move_writes_the_bookmark_to_the_record(harness):
"""So a broker that dies mid-gesture still leaves the last real position."""
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
for x in (0.1, 0.2, 0.3):
reply = harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=x, y=0.5))
assert reply["bookmark"]["x"] == x
assert session.pointer["bookmark"]["x"] == x
# And in the lease, which is what `release` reports.
outcome = harness.manager.pointer.release("foot-aaaaaa", lease, "test")
assert outcome.bookmark.x == 0.3
def test_a_relative_move_is_applied_to_the_bookmark_and_clamped(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
reply = harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, dx=0.25, dy=-0.25))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.75, 0.25)
# Running into the edge of the screen is what a mouse does.
reply = harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, dx=5.0, dy=-5.0))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (1.0, 0.0)
@pytest.mark.parametrize("bad", [1.4, -0.1, "0.5", True, None])
def test_an_absolute_coordinate_outside_the_frame_is_a_usage_error(harness, bad):
"""A caller that computed 1.4 has a bug; clamping it would hide it."""
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=bad, y=0.5))
assert exc.value.error == "invalid_argument"
def test_moving_without_the_lease_is_nine_and_not_eight(harness):
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_move("foot-bbbbbb", lease, x=0.5, y=0.5))
assert exc.value.error == "no_lease"
assert exit_code_for(exc.value.error) == ExitCode.NO_LEASE
def test_a_stale_lease_id_is_refused_even_for_the_holder(harness):
harness.add()
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_move("foot-aaaaaa", "not-the-lease", x=0.5, y=0.5))
assert exc.value.error == "no_lease"
# ---------------------------------------------------------------------------
# buttons
# ---------------------------------------------------------------------------
def test_a_button_goes_down_and_up_through_the_driver(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
assert harness.run(
harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down")
)["buttons"] == ["left"]
assert harness.run(
harness.manager.pointer_button("foot-aaaaaa", lease, "left", "up")
)["buttons"] == []
assert harness.fake.sink.calls == [
("button", "hh-foot-aaaaaa", LEFT, DOWN),
("frame", "hh-foot-aaaaaa"),
("button", "hh-foot-aaaaaa", LEFT, UP),
("frame", "hh-foot-aaaaaa"),
]
def test_a_click_is_a_press_and_a_release_each_committed(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
reply = harness.run(harness.manager.pointer_click("foot-aaaaaa", lease, "left", 2))
assert reply["count"] == 2
assert harness.fake.sink.calls == [
("button", "hh-foot-aaaaaa", LEFT, DOWN),
("frame", "hh-foot-aaaaaa"),
("button", "hh-foot-aaaaaa", LEFT, UP),
("frame", "hh-foot-aaaaaa"),
] * 2
assert harness.manager.pointer.pressed() == []
@pytest.mark.parametrize("bad", [0, 99, "two", True, 1.5])
def test_a_click_count_off_the_wire_is_bounded(harness, bad):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_click("foot-aaaaaa", lease, "left", bad))
assert exc.value.error == "invalid_argument"
def test_an_unknown_button_is_refused_by_the_driver_not_invented(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "pinky", "down"))
assert exc.value.error == "driver_refused"
assert harness.manager.pointer.pressed() == [], "a refused press must not be mirrored"
# ---------------------------------------------------------------------------
# releasing and expiry
# ---------------------------------------------------------------------------
def test_release_lifts_what_was_down_and_stamps_the_record(harness):
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.4, y=0.6))
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
reply = harness.run(harness.manager.pointer_release("foot-aaaaaa", lease))
assert reply["buttons_lifted"] == ["left"]
assert reply["released_by"] == "lease"
assert reply["bookmark"]["x"] == 0.4
assert session.pointer["released_by"] == "lease"
assert session.pointer["last_released_at"] == reply["released_at"]
assert harness.manager.pointer.state()["holder"] is None
def test_an_idle_lease_expires_and_the_button_it_left_down_is_lifted(harness):
"""The order is the contract's: `pressed()` is read before `expire()`,
because `expire()` drops the lease's button set with the lease."""
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
harness.clock.advance(31.0)
expired = harness.run(harness.manager._expire_pointer())
assert expired == {
"session": "foot-aaaaaa",
"lease_id": lease,
"buttons_lifted": ["left"],
# Empty, and reported rather than omitted: this lease held no key, and
# "no keys were lifted" is a different answer from "keys were not
# considered".
"keys_lifted": [],
}
assert harness.manager.pointer.state()["holder"] is None
assert harness.fake.sink.calls[-2:] == [
("button", "hh-foot-aaaaaa", LEFT, UP),
("frame", "hh-foot-aaaaaa"),
]
assert session.pointer["released_by"] == "timeout"
def test_an_expired_lease_is_noticed_by_the_next_verb_as_well(harness):
"""So the cursor is free for someone else even with no sweep in between."""
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
harness.clock.advance(31.0)
reply = harness.run(harness.manager.pointer_acquire("foot-bbbbbb"))
assert reply["id"] == "foot-bbbbbb"
assert harness.manager.pointer.state()["holder"] == "foot-bbbbbb"
def test_a_refresh_loop_still_loses_the_cursor_at_the_hard_cap(harness):
"""A stuck agent must not be able to hold the mouse forever."""
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
for _ in range(12):
harness.clock.advance(25.0)
try:
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.5, y=0.5))
except ManagerError as exc:
assert exc.error == "no_lease"
break
else: # pragma: no cover - the cap did not fire
pytest.fail("the hard cap never expired the lease")
assert harness.manager.pointer.state()["holder"] is None
def test_a_caller_supplied_ttl_applies_to_this_lease_and_then_goes_away(harness):
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
harness.run(harness.manager.pointer_acquire("foot-aaaaaa", ttl_s=5.0))
harness.clock.advance(6.0)
assert harness.run(harness.manager._expire_pointer()) is not None
assert harness.manager.pointer.ttl_s == 30.0, "the default must come back"
harness.run(harness.manager.pointer_acquire("foot-bbbbbb"))
harness.clock.advance(6.0)
assert harness.run(harness.manager._expire_pointer()) is None
def test_a_ttl_beyond_the_hard_cap_is_refused(harness):
harness.add()
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("foot-aaaaaa", ttl_s=10_000))
assert exc.value.error == "invalid_argument"
assert harness.manager.pointer.state()["holder"] is None
def test_expiry_with_no_driver_is_loud_rather_than_silent(harness, caplog):
"""A button we could not lift is the one thing that must never be quiet."""
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
harness.fake.stop()
harness.clock.advance(31.0)
with caplog.at_level("ERROR"):
harness.run(harness.manager._expire_pointer())
assert "they may still be held" in caplog.text
assert "buttons ['left']" in caplog.text
assert harness.manager.pointer.state()["holder"] is None
# ---------------------------------------------------------------------------
# the rest of the contract
# ---------------------------------------------------------------------------
def test_no_pointer_verb_counts_as_activity(harness):
"""A session being clicked in is still one nobody has asked to keep."""
session = harness.add()
before = (session.last_activity_boottime, session.command_count)
harness.clock.advance(100.0)
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.5, y=0.5))
harness.run(harness.manager.pointer_click("foot-aaaaaa", lease))
harness.manager.pointer_state()
harness.run(harness.manager.pointer_release("foot-aaaaaa", lease))
assert (session.last_activity_boottime, session.command_count) == before
def test_pointer_state_names_the_holder_and_what_is_down(harness):
harness.add()
assert harness.manager.pointer_state()["holder"] is None
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "right", "down"))
state = harness.manager.pointer_state()
assert state["holder"] == "foot-aaaaaa"
assert state["lease_id"] == lease
assert state["buttons"] == ["right"]
assert state["bookmark"]["output"] == "hh-foot-aaaaaa"
def test_a_dead_session_cannot_be_aimed_at(harness):
session = harness.add()
harness.manager.registry.terminate(session, State.EXITED)
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert exc.value.error == "session_exited"
def test_an_unknown_session_is_three_not_a_lease_error(harness):
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("nope-zzzzzz"))
assert exit_code_for(exc.value.error) == ExitCode.NO_SUCH_SESSION
def test_no_driver_configured_at_all_is_reported_as_unavailable(short_tmpdir: Path):
manager = SessionManager(
ManagerConfig(
state_dir=short_tmpdir / "state",
runtime_dir=short_tmpdir / "run",
policy=Policy(),
# Explicitly nothing, rather than the derived default.
pointer_socket=short_tmpdir / "no-driver-here.sock",
),
clock=ManualClock(boottime=1000.0),
)
manager.registry.add(make_session())
with pytest.raises(ManagerError) as exc:
asyncio.run(manager.pointer_acquire("foot-aaaaaa"))
assert exc.value.error == "driver_unavailable"
def test_releasing_with_someone_elses_lease_lifts_nothing(harness):
"""The refusal has to come before anything reaches the driver.
Otherwise ``pointer.release`` is a way for any session to drop the
holder's buttons mid-drag on its way to being told no.
"""
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
harness.fake.sink.calls.clear()
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_release("foot-bbbbbb", lease))
assert exc.value.error == "no_lease"
assert harness.fake.sink.calls == []
assert harness.manager.pointer.pressed() == ["left"]
assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa"
def test_a_stale_lease_id_cannot_release_the_current_one(harness):
harness.add()
first = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_release("foot-aaaaaa", first))
second = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_release("foot-aaaaaa", first))
assert exc.value.error == "no_lease"
assert harness.manager.pointer.state()["lease_id"] == second
def test_the_sweeper_expires_a_lease_nobody_came_back_for(short_tmpdir: Path):
"""The TTL is only a promise if something checks it unprompted.
An agent that acquired, pressed a button and died would otherwise hold the
cursor — with the button down — until some other session happened to try.
"""
fake = FakeDriver(short_tmpdir / "p.sock")
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,
# Short, so the test waits on the sweep and not on the TTL; the
# TTL itself is the injected clock's business.
pointer_sweep_s=0.01,
),
clock=clock,
)
session = manager.registry.add(make_session())
async def scenario():
lease = (await manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
await manager.pointer_button("foot-aaaaaa", lease, "left", "down")
sweeper = asyncio.create_task(manager._sweep_pointer())
clock.advance(31.0)
for _ in range(500):
await asyncio.sleep(0.01)
if manager.pointer.state()["holder"] is None:
break
sweeper.cancel()
with pytest.raises(asyncio.CancelledError):
await sweeper
try:
asyncio.run(scenario())
assert manager.pointer.state()["holder"] is None
assert fake.dispatcher._pressed == {}, "the sweep lifted it on the driver"
assert session.pointer["released_by"] == "timeout"
finally:
if manager.driver is not None:
manager.driver.close()
fake.stop()
# ---------------------------------------------------------------------------
# scrolling
# ---------------------------------------------------------------------------
def test_scroll_drives_axis_then_frame_on_the_sessions_own_output(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
reply = harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", 3))
assert (reply["axis"], reply["amount"]) == ("vertical", 3.0)
assert harness.fake.sink.calls == [
("axis", "hh-foot-aaaaaa", VERTICAL, 3.0),
("frame", "hh-foot-aaaaaa"),
]
def test_scrolling_up_is_the_sign_and_not_a_different_verb(harness):
"""One verb, one axis name, and the protocol's sign carries the direction."""
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", -3))
assert harness.fake.sink.calls == [
("axis", "hh-foot-aaaaaa", VERTICAL, -3.0),
("frame", "hh-foot-aaaaaa"),
]
def test_a_horizontal_scroll_uses_the_other_axis(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "horizontal", 2))
assert harness.fake.sink.calls == [
("axis", "hh-foot-aaaaaa", HORIZONTAL, 2.0),
("frame", "hh-foot-aaaaaa"),
]
def test_a_scroll_restamps_the_resume_point_without_moving_it(harness):
"""The cursor stays put -- and the record must not pretend otherwise."""
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
before = dict(session.pointer["bookmark"])
harness.clock.advance(7.0)
reply = harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", 3))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (before["x"], before["y"])
assert reply["bookmark"]["output"] == before["output"]
assert reply["bookmark"]["at"] != before["at"], "the session acted, so the stamp moved"
assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa"
@pytest.mark.parametrize("bad", [0, 0.0, 101, -101, "three", True, None])
def test_a_scroll_amount_off_the_wire_is_bounded(harness, bad):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", bad))
assert exc.value.error == "invalid_argument"
def test_an_unknown_axis_is_refused_by_the_driver_not_invented(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "diagonal", 3))
assert exc.value.error == "driver_refused"
assert harness.fake.sink.calls == [], "a refused scroll must emit nothing"
def test_a_scroll_without_the_lease_is_refused(harness):
session = harness.add()
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
harness.fake.sink.calls.clear()
with pytest.raises(ManagerError):
harness.run(
harness.manager.pointer_scroll("foot-aaaaaa", "not-this-lease", "vertical", 3)
)
assert harness.fake.sink.calls == []
assert session.pointer.get("bookmark") is not None, "a refused scroll changes nothing"