Files
hyprland-headless-stream-pl…/tests/sessions/unit/test_pointer_verbs.py
T
HermenixandClaude Opus 5 129430bffd wire the broker to the compositor, containers and pointer
The four slices existed and nothing called them. Now the broker builds a
spatial container per session, reads back what the compositor actually did,
and aims the cursor into one container under a broker-wide lease.

Record schema 3 (registry.py): `container` {output, workspace, mode,
created_by, state}, `pointer` {bookmark, last_released_at, released_by} and
the compositor's `signature`. A v2 record is migrated on load, not refused —
its application is still running. Every field that could not be verified is
null; `container: null` means "no container", never "probably something".

Containers (new container_host.py, manager.py, launcher.py): `start`
allocates a slot from `WorkspaceAllocator`, runs `container_plan()`'s argv,
launches the app with the container stamp in its environment, then reads the
workspace, output and window back out of `clients -j`. Teardown removes the
output, releases the slot and reports survivors rather than claiming success
— and runs for an unprompted exit and for `gc` too, so no container is ever
left unattended. Broker start-up reconciles: adopt `hh-*` outputs a live
session claims, remove the rest, `contains_output()` being the only filter.
No IPC means `container: degraded` and lifecycle verbs unchanged.

The plans' argv are dispatched over the compositor's request socket rather
than by executing `hyprctl`, which is what hyprctl does with the same words;
the reply is checked, so a refused command is not recorded as a container.

Pointer (new driver.py, manager.py): a client for the driver's private
socket, and `pointer.acquire|move|button|click|release|state` on top of
`PointerLease`. The broker owns the lease, the driver executes. The bookmark
is marked on every move and before release and stored in the record, so it
survives a restart. On expiry `pressed()` is read before `expire()` and
`release_all` goes to the driver, because the lease cannot lift a button
itself; a sweep runs unprompted so the TTL is a promise.

containers.py to v2: `quarantine_plan()` -> `quarantine_argv()`, with the
before-any-per-session-rule ordering stated where the caller could get it
wrong. protocol.py: 9 NO_LEASE, 10 COMPOSITOR, the verb table, and the
`request_id` cache moved out of the server so the CLI agrees with it.

Tests: real AF_UNIX everywhere — a stateful fake compositor and the shipped
pointer driver behind a recording sink. No mocked sockets, no compositor, no
VM. 551 -> 693.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017mUq7QvQ9EZb2Wi35xj4cs
2026-10-02 19:47:33 +00:00

593 lines
21 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
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"],
}
assert harness.fake.sink.calls == [
("warp", "hh-foot-aaaaaa", 0.5, 0.5),
("frame", "hh-foot-aaaaaa"),
]
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)
assert harness.fake.sink.of("warp") == [("warp", "hh-foot-aaaaaa", 0.25, 0.75)]
assert session.pointer["bookmark"]["x"] == 0.25
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"],
}
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 "a button may still be down" 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()