# checks..vm-pointer -- the lease, the driver, and a click that lands. # # The lease's arithmetic is already proved by the unit suite with an injected # clock. What no fake can prove is the half this check is for: that a warp # through `zwlr_virtual_pointer_v1` reaches a real compositor, that the # coordinates are the *output's* and not the desktop's, and that the button # the broker sent arrives at the application underneath it. # # ─── "A CLICK LANDS WHERE IT WAS AIMED", AND WHY NOT PIXELS ────────────────── # PLAN §14 says this must be verified by reading back the application's own # state. A pixel comparison would prove the compositor drew a cursor # somewhere; it would not prove any client was told about a button, and a # cursor drawn at the right place with no `wl_pointer.button` delivered is # precisely the failure a virtual pointer bound to the wrong output produces. # # So the victim is `hhs-pointer-target` (checks/lib/pointer_target.py), a # Wayland client that prints every pointer event it receives with the # surface-local coordinates the compositor sent it. The broker captures its # stdout into the session log, so `hhstream session logs` is the read-back, # and the assertion is on numbers the *client* reported. # # It also reads `$HHSTREAM_APP_ID` and sets its own `xdg_toplevel` app id from # it, which is what gets its window into the container the pointer aims at. # `foot` and `wev` cannot: they ignore the environment, so their windows are # quarantined and there would be nothing under the cursor. See vm-containers. # ───────────────────────────────────────────────────────────────────────────── # # The expiry subtest uses a caller-supplied `--ttl` of a few seconds and waits # for it in real time. No clock is injected anywhere: an injected clock would # prove the arithmetic the unit suite already proves, and not the sweeper, the # driver call it makes, or the button it has to lift. # # `sessions.pointer.leaseTtl` is set on the machine anyway, and the acquire # subtest *prints* it beside the TTL the broker reports. They disagree, and # that is the point: the module renders the option into the generated TOML and # `hhstreamd/policy.py` reads neither it nor any flag for it. Printed rather # than asserted, because the broker is not this slice's file to change. # # ─── TWO THINGS THIS CHECK MEASURED, BOTH WORTH READING BEFORE EDITING IT ──── # # 1. A WARP TO WHERE THE CURSOR ALREADY IS REPORTS NOTHING, and correctly so: # nothing moved. It is only a trap for a check -- a second `acquire` that # restores a bookmark the cursor never left delivers no `wl_pointer.motion`, # so "the bookmark was restored" has no client-side evidence. The restore is # therefore asserted on the broker's reply, where the bookmark lives, and # *delivery* is asserted with a warp to somewhere the cursor is not. # # 2. `input:follow_mouse = 0` SENDS POINTER EVENTS TO THE FOCUSED WINDOW ONLY, # and when the window under the cursor is not the focused one, to nobody at # all. `nix/hyprland-conf.nix` USED TO ship it, justified by "No pointer # will ever exist; do not let focus depend on one" -- a belief this build # made false. **That is fixed: the conf file now sets `1`**, so the # `extraConfig` override below is belt and braces rather than the only # thing making this check pass. The measurement is kept because it is the # reason the conf changed, and because a revert would make it current again. # # What `1` does NOT fix, measured later by `tests/keyboard_probe.py`: one # warp moves the cursor and not KEYBOARD focus, because Hyprland zeroes # `m_mousePosDelta` when the previous movement was over 0.5s ago. So # `pointer acquire` sends two warps a real pixel apart, and the conf sets # `input:follow_mouse_threshold = 0` explicitly because that is what the # second one depends on. `checks/vm-keyboard.nix` is where that is asserted; # this check asserts pointer delivery and says nothing about keys. # # MEASURED, against the shipped config, with two sessions and the second # one holding focus because its window opened last: # # aimed at target-le22h7: it reports [] <- the session the warp named # focused is target-s76taj: it reports [] <- the session with focus # cursor now at {'x': 2048, 'y': 288} <- EXACTLY where it was aimed # # The compositor moved the cursor to the right pixel, inside the right # window, on the right output -- and told no client. The same warp and the # same click are delivered perfectly in the subtests above, where the # aimed-at session is also the focused one, which is why nothing before # this check noticed. # # That defeats what containers and the lease exist for: an agent can only # drive whichever session the compositor last focused. So this machine # overrides the one line through the module's `extraConfig`, and the # subtest "the cursor reaches a session that does not hold focus" is the # assertion that goes red if the shipped default comes back. # # That subtest now has to ARRANGE its own situation rather than inherit it. # It used to be free -- the second session's window took focus when it # opened and `acquire` left it there -- but `pointer acquire` now takes the # keyboard as well as the cursor, so the acquiring session ends up focused. # The subtest moves focus back with one `hyprctl dispatch`, as setup. Worth # knowing because the two bugs hid each other: the helper derivation that # this check's victim comes from was not building at all (see # checks/lib/session-tools.nix), so nothing ran here to notice the premise # had gone stale. # `nix/hyprland-conf.nix` is not this slice's file; the fix belongs there, # and whether it should be `1` (Hyprland's own default, keyboard focus # follows the cursor too) or a looser setting that leaves keyboard focus # alone is a decision for the keyboard work in PLAN §6.7. # ───────────────────────────────────────────────────────────────────────────── { testers, hhstream, hhsModule, testTools, hyprland, foot, jq, grim, procps, coreutils, dejavu_fonts, width ? 1280, height ? 720, sessionUser ? "hermes", # Short enough that the expiry subtest is seconds and not minutes, long # enough that a `systemd-run` round trip inside the guest (several seconds) # fits comfortably inside one lease. leaseTtl ? 20, leaseMax ? 120, }: testers.runNixOSTest ( { pkgs, ... }: let tools = pkgs.callPackage ./lib/session-tools.nix { inherit hhstream; }; guest = import ./lib/session-machine.nix { inherit hhsModule hhstream hyprland testTools foot jq procps grim coreutils dejavu_fonts ; sessionTools = tools; }; prelude = import ./lib/session-prelude.nix { inherit hhstream coreutils sessionUser; }; target = pkgs.writeShellScript "hhs-target-wrapper" '' exec ${tools}/bin/hhs-pointer-target --app-id "$HHSTREAM_APP_ID" "$@" ''; in { name = "hhstream-vm-pointer"; globalTimeout = 1800; nodes.machine = guest { inherit width height sessionUser leaseTtl leaseMax ; pointer = true; apps.target = { exec = "${target}"; argsAllow = [ ]; }; # Point 2 of the block at the top of this file. One line, overriding one # line of nix/hyprland-conf.nix, because that file is not this slice's # to edit -- not because there is any doubt about it. extraConfig = "input:follow_mouse = 1"; }; testScript = prelude + '' import re LEASE_TTL = ${toString leaseTtl} POINTER_SOCKET = "/run/hhstream/pointer.sock" #: wl_pointer surface coordinates are logical pixels. The budget covers #: two things and nothing else: the protocol's integer extent (the #: driver scales a normalised coordinate by 0xFFFF, so under a pixel on #: a 1280-wide output) and Hyprland's default 2px border, which sits #: between the window box `clients -j` reports and the surface the #: client is given coordinates in. A pointer bound without an output #: speaks *global* coordinates and would be out by hundreds, so this #: tolerance does not blunt the assertion it guards. TOLERANCE = 6.0 def pointer_log(session_id): """Every line the victim has printed so far.""" return machine.succeed(cli(f"logs {session_id} --lines 400"), timeout=120) def positions(session_id): """(x, y) from every `enter`/`motion` line the client printed.""" found = [] for line in pointer_log(session_id).splitlines(): if line.startswith(("pointer enter", "pointer motion")): pair = re.findall(r"[xy]=([-\d.]+)", line) if len(pair) == 2: found.append((float(pair[0]), float(pair[1]))) return found def buttons(session_id): """(code, state, x, y) from every `button` line the client printed.""" found = [] for line in pointer_log(session_id).splitlines(): match = re.match( r"pointer button code=(\d+) state=(\w+) x=([-\d.]+) y=([-\d.]+)", line, ) if match: found.append( ( int(match.group(1)), match.group(2), float(match.group(3)), float(match.group(4)), ) ) return found def aimed_at(nx, ny): """Where a warp to (nx, ny) of the output should land *in the surface*. Computed from the compositor's own geometry rather than assumed to be a fraction of the window: Hyprland's default layout leaves 20px outer gaps, so the window is not the output and the centre of one is not the centre of the other. Asking `monitors` and `clients` for both boxes is what makes this an assertion about aiming rather than about the layout. """ monitor = monitor_named(output) client = [c for c in compositor("clients") if c.get("initialClass") == output][0] at = client["at"] return ( monitor["x"] + nx * monitor["width"] - at[0], monitor["y"] + ny * monitor["height"] - at[1], ) def close_enough(got, want): return abs(got[0] - want[0]) <= TOLERANCE and abs(got[1] - want[1]) <= TOLERANCE start_all() bring_up("the compositor and broker") with subtest("the driver unit comes up and binds its socket"): # Same reasoning as the broker's: `Type=simple` means wait_for_unit # passes against a crash loop, so the socket and a restart count of # zero are the honest test. The driver refuses to start at all if # the compositor offers only a version-1 virtual-pointer manager -- # that refusal is deliberate (coordinates would be global and every # warp would aim at the wrong output) and shows here as a restart # loop with its own words in the journal. try: machine.wait_for_unit("hhstream-pointer.service", timeout=180) machine.wait_for_file(POINTER_SOCKET, timeout=120) machine.succeed("systemctl is-active hhstream-pointer.service") restarts = machine.succeed( "systemctl show -p NRestarts --value hhstream-pointer.service" ).strip() assert restarts == "0", ( f"the driver has restarted {restarts} time(s); read its journal" ) print( machine.succeed( "journalctl --no-pager --boot --unit hhstream-pointer.service" ) ) except Exception: dump("the pointer driver did not come up") raise with subtest("the broker reports the driver and a free cursor"): try: state = cli_json("pointer state --json") print(json.dumps(state, indent=2, sort_keys=True)) assert state["holder"] is None, state assert state["buttons"] == [], state assert state["driver"] == POINTER_SOCKET, state except Exception: dump("pointer state is not what a fresh broker should report") raise with subtest("a session's window is in its container, under the cursor"): try: session_id = machine.succeed(cli("start target"), timeout=180).strip() output = f"hh-{session_id}" print(f"session {session_id} -> {output}") machine.wait_until_succeeds( f"{HYPRCTL} clients | jq -e --arg m {output}" " 'any(.initialClass == $m)' >/dev/null", timeout=120, ) client = [ c for c in compositor("clients") if c.get("initialClass") == output ][0] print(json.dumps(client, indent=2, sort_keys=True)) print(json.dumps(monitor_named(output), indent=2, sort_keys=True)) except Exception: dump("the victim never got a window in its container", locals().get("session_id")) raise with subtest("acquire takes the cursor and the seat grows a pointer"): # The seat of a headless session has *no* pointer capability until # something creates a virtual one: there is no input device here. # So the client cannot have bound `wl_pointer` before this point, # and "target: pointer bound" appearing after the first warp is the # proof that the driver's `zwlr_virtual_pointer_v1` reached the # seat -- not merely that the broker thinks it sent something. try: reply = cli_json(f"pointer acquire --json {session_id}", timeout=120) print(json.dumps(reply, indent=2, sort_keys=True)) bookmark = reply["bookmark"] assert bookmark["output"] == output, bookmark assert (bookmark["x"], bookmark["y"]) == (0.5, 0.5), ( f"with no bookmark the cursor must go to the centre: {bookmark}" ) # A GAP, printed rather than asserted: the module's # `sessions.pointer.leaseTtl` is rendered into the generated # TOML and the broker reads neither the TOML nor any flag for # it, so the lease runs on the broker's own default. The number # below is the evidence. print( f"module leaseTtl={LEASE_TTL}s, broker reports " f"expires_in_s={reply['expires_in_s']}" ) wait_for( lambda: "target: pointer bound" in pointer_log(session_id), timeout=60, what="the client to bind wl_pointer", ) print(pointer_log(session_id)) except Exception: dump("acquire did not reach the compositor", session_id) raise with subtest("a warp lands where it was aimed, as the application saw it"): # Aimed off-centre so a wrong answer cannot coincide with the # centre the acquire already warped to. try: aim = (0.25, 0.75) before = len(positions(session_id)) moved = cli_json( f"pointer move --json {session_id} --to {aim[0]},{aim[1]}", timeout=120 ) print(json.dumps(moved, indent=2, sort_keys=True)) assert (moved["bookmark"]["x"], moved["bookmark"]["y"]) == aim, moved seen = wait_for( lambda: positions(session_id)[before:], timeout=60, what="the client to report the warp", ) want = aimed_at(*aim) print(f"the client reports {seen}, aimed at {want}") assert close_enough(seen[-1], want), ( f"the cursor arrived at {seen[-1]} and was aimed at {want}. " "An offset of hundreds of pixels means the virtual pointer " "speaks global coordinates, i.e. it was created without an " "output." ) except Exception: dump("the warp did not land where it was aimed", session_id) raise with subtest("a click is delivered there, pressed and released"): try: before = len(buttons(session_id)) clicked = cli_json(f"pointer click --json {session_id}", timeout=120) print(json.dumps(clicked, indent=2, sort_keys=True)) events = wait_for( lambda: ( buttons(session_id)[before:] if len(buttons(session_id)) >= before + 2 else None ), timeout=60, what="the client to report a press and a release", ) print(f"the client reports: {events}") assert {code for code, _, _, _ in events} == {0x110}, ( f"the client was sent {events}, not BTN_LEFT (0x110)" ) assert [state for _, state, _, _ in events] == ["pressed", "released"], ( f"a click delivered {events}; it must be exactly one press " "and one release, or something is left held down" ) want = aimed_at(0.25, 0.75) for _, state, x, y in events: assert close_enough((x, y), want), ( f"the {state} arrived at ({x}, {y}), aimed at {want}" ) except Exception: dump("the click did not reach the application", session_id) raise with subtest("a second acquire is refused with BUSY, naming the holder"): # The lock is broker-wide because the cursor is one (PLAN §6.2). try: other = machine.succeed(cli("start target"), timeout=180).strip() print(f"second session: {other}") code, out = machine.execute( cli(f"pointer acquire {other}") + " 2>&1", timeout=120 ) print(f"exit {code}: {out}") assert code == 8, f"a contended acquire exited {code}, not 8 (BUSY)" assert session_id in out, ( f"the refusal does not name the holder {session_id}: {out!r}" ) except Exception: dump("a contended acquire was not refused", locals().get("other")) raise with subtest("a session that never acquired cannot move the cursor"): # Exit 9 and not 8: an agent that sees 9 must acquire, one that # sees 8 must wait, and conflating them is how a retry loop spins. try: code, out = machine.execute( cli(f"pointer move {other} --to 0.5,0.5") + " 2>&1", timeout=120 ) print(f"exit {code}: {out}") assert code == 9, f"a gesture with no lease exited {code}, not 9" except Exception: dump("a gesture without a lease was not refused", other) raise with subtest("release frees the lock and leaves the bookmark behind"): try: released = cli_json(f"pointer release --json {session_id}", timeout=120) print(json.dumps(released, indent=2, sort_keys=True)) assert released["buttons_lifted"] == [], released assert (released["bookmark"]["x"], released["bookmark"]["y"]) == ( 0.25, 0.75, ), released state = cli_json("pointer state --json") assert state["holder"] is None, state except Exception: dump("release did not give the cursor back", session_id) raise with subtest("the cursor reaches a session that does not hold focus"): # Two assertions in one, because they need the same situation: the # lease is held by one session while a DIFFERENT session's window # holds keyboard focus. # # 1. `acquire` restores the bookmark the previous lease left -- # the point of a bookmark is that a gesture is resumable, and # it is checked on the client's side as well as the broker's. # 2. A warp is delivered to the session it was AIMED at, not to # whichever window the compositor last focused -- and the # focused one is told nothing. The lease and the containers # are worth nothing if a click aimed at one session arrives at # another, and `input:follow_mouse` is where that would go # wrong (see the block at the top of this file). # # HOW THE SITUATION IS SET UP, AND WHY IT CHANGED. It used to be # free: the second session's window took focus when it opened, and # `acquire` left it there, because one warp moves the cursor and # not keyboard focus. `pointer acquire` now takes the keyboard too # -- two warps a real pixel apart, see `_warp_taking_focus` -- so # after the acquire below the focused window is the acquiring # session's, and this subtest's premise no longer arranges itself. # # So focus is moved back explicitly. `hyprctl dispatch` is SETUP # here and not the thing under test: what is measured is which # client the compositor hands the warp to, and that is unaffected # by how focus came to be where it is. (The keyboard check is where # "acquire takes focus" is asserted; asserting it here as well # would make this subtest about the acquire and not about routing.) try: before = len(positions(session_id)) reply = cli_json(f"pointer acquire --json {session_id}", timeout=120) print(json.dumps(reply, indent=2, sort_keys=True)) assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.25, 0.75), ( f"acquire restored to {reply['bookmark']}, not where the " "previous lease left the cursor" ) other_window = [ c for c in compositor("clients") if c.get("initialClass") == f"hh-{other}" ] assert other_window, f"the other session {other} has no window" address = other_window[0]["address"] machine.succeed( f"{HYPRCTL} dispatch focuswindow address:{address}", timeout=120 ) focused = [ c.get("initialClass") for c in compositor("clients") if c.get("focusHistoryID") == 0 ] print(f"the compositor's focused window belongs to: {focused}") assert focused and focused[0] != output, ( f"this subtest needs the OTHER session focused; {focused} is. " "The `dispatch focuswindow` above was supposed to arrange " "that and did not." ) # Somewhere the cursor is not, so there is a motion to deliver # (see the note at the top of this file). elsewhere = (0.6, 0.4) before_other = len(positions(other)) machine.succeed( cli(f"pointer move {session_id} --to {elsewhere[0]},{elsewhere[1]}"), timeout=120, ) # Waits for EITHER client to report something, so a warp that # went to the wrong one is a message naming where it went # rather than a timeout naming nothing. wait_for( lambda: positions(session_id)[before:] or positions(other)[before_other:], timeout=60, what=f"either {session_id} or {other} to report the warp", ) mine = positions(session_id)[before:] theirs = positions(other)[before_other:] print(f"aimed at {session_id}: it reports {mine}") print(f"focused is {other}: it reports {theirs}") print(f"cursor now at {compositor('cursorpos')}") assert not theirs, ( f"the warp was aimed into {output} and {other}'s window got " f"it: {theirs}. The compositor is routing pointer events by " "keyboard focus, not by what is under the cursor -- read " "input:follow_mouse in nix/hyprland-conf.nix." ) want = aimed_at(*elsewhere) print(f"the client reports {mine}, aimed at {want}") assert close_enough(mine[-1], want), (mine[-1], want) machine.succeed(cli(f"pointer release {session_id}"), timeout=120) except Exception: dump("the warp did not reach the session it was aimed at", session_id) raise with subtest("an expired lease is released and its button is lifted"): # Real time, a caller-supplied TTL, and nothing touching the lease. # The sweeper is what makes the TTL a promise: without it expiry # would only be noticed by the next verb, so an agent that pressed # a button and died would hold the cursor -- with the button down # -- until somebody else happened to try. try: short = 8 cli_json( f"pointer acquire --json --ttl {short}s {session_id}", timeout=120 ) before = len(buttons(session_id)) machine.succeed(cli(f"pointer down {session_id}"), timeout=120) held = cli_json("pointer state --json") print(json.dumps(held, indent=2, sort_keys=True)) assert held["holder"] == session_id, held assert held["buttons"] == ["left"], ( f"the button is not recorded as down: {held}" ) # One bounded wait for the deadline to arrive, not a retry of # the assertion: the lease expires on its own or it does not. machine.wait_until_succeeds( cli("pointer state --json") + " | jq -e '.holder == null' >/dev/null", timeout=short * 6 + 120, ) state = cli_json("pointer state --json") print(json.dumps(state, indent=2, sort_keys=True)) assert state["buttons"] == [], ( f"the lease expired with a button still down: {state}" ) events = wait_for( lambda: ( buttons(session_id)[before:] if len(buttons(session_id)) >= before + 2 else None ), timeout=60, what="the client to be told the button came back up", ) print(f"the client reports: {events}") assert [s for _, s, _, _ in events] == ["pressed", "released"], ( "the application was told the button went down and never " f"that it came up: {events}. A compositor left holding a " "button is a drag nobody started." ) except Exception: dump("the lease did not expire cleanly", session_id) raise with subtest("a broker restart leaves the lock free and the bookmark intact"): # Leases are stale by definition across a restart (PLAN §6.2); the # bookmark is not, because it lives in the session record on disk. try: cli_json(f"pointer acquire --json {session_id}", timeout=120) machine.succeed(cli(f"pointer move {session_id} --to 0.8,0.2"), timeout=120) machine.succeed("systemctl restart hhstream-sessions.service", timeout=180) machine.wait_for_unit("hhstream-sessions.service", timeout=180) machine.wait_until_succeeds(cli("list") + " >/dev/null", timeout=120) state = cli_json("pointer state --json") print(json.dumps(state, indent=2, sort_keys=True)) assert state["holder"] is None, ( f"the restarted broker believes {state['holder']} still holds " "a lease that died with the process that granted it" ) record = cli_json(f"status --json {session_id}")["session"] bookmark = (record.get("pointer") or {}).get("bookmark") print(json.dumps(bookmark, indent=2, sort_keys=True)) assert bookmark is not None, record assert (bookmark["x"], bookmark["y"]) == (0.8, 0.2), ( f"the bookmark did not survive the restart: {bookmark}" ) assert bookmark["output"] == output, bookmark except Exception: dump("the restart lost the lock or the bookmark", session_id) raise with subtest("the driver is still reachable after the broker restarted"): # The socket the two speak over lives in the broker's runtime # directory. Without `RuntimeDirectoryPreserve` on that unit, # restarting the broker deletes /run/hhstream and takes # pointer.sock with it -- leaving the driver listening on an # unlinked inode and every pointer verb answering exit 10 while # `systemctl status hhstream-pointer` still says "active". try: machine.succeed(f"test -S {POINTER_SOCKET}") machine.succeed("systemctl is-active hhstream-pointer.service") reply = cli_json(f"pointer acquire --json {session_id}", timeout=120) print(json.dumps(reply, indent=2, sort_keys=True)) assert reply["bookmark"]["x"] == 0.8, reply machine.succeed(cli(f"pointer release {session_id}"), timeout=120) except Exception: dump("the driver was unreachable after the broker restarted", session_id) raise ''; } )