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
364 lines
13 KiB
Python
364 lines
13 KiB
Python
"""The driver's XKB flags — the only path a layout has to the uploaded keymap.
|
|
|
|
This file exists where a `tests/sessions/unit/test_settings.py` case would have
|
|
gone, and that is the point. The broker's TOML is read by `hhstreamd` for its
|
|
lease numbers; `hhstream-pointer` is a different unit and never opens that
|
|
file. So a `[keyboard]` table there would be a setting an operator could change
|
|
with no effect at all, and a test asserting its default would be green while
|
|
every injected key stayed on `us`.
|
|
|
|
The layout therefore arrives as `--xkb-layout`, and these are the assertions
|
|
about that flag: what it defaults to, that a bad value is exit **2**, and that
|
|
a bad value is exit 2 **without the compositor being touched** — because a
|
|
layout xkbcommon will not compile is the operator's typo, and reporting it as
|
|
exit 10 sends them to the wrong unit.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from hhstream_pointer import __main__ as entry
|
|
|
|
|
|
class _Unreached(Exception):
|
|
"""Raised if the Wayland side is reached when it should not have been."""
|
|
|
|
|
|
class _RefusingSink:
|
|
"""A sink that fails the test if anything asks it to talk to a compositor.
|
|
|
|
The review asked for an injected connect that can be asserted *not* to have
|
|
been called; this is that, as a type rather than a flag, so a future code
|
|
path that connects earlier fails loudly instead of silently reordering
|
|
start-up.
|
|
"""
|
|
|
|
instances = 0
|
|
|
|
def __init__(self, runtime_dir, display_name=None) -> None:
|
|
type(self).instances += 1
|
|
|
|
def connect(self) -> None:
|
|
raise _Unreached("connect")
|
|
|
|
def upload_keymap(self, text: str) -> None:
|
|
raise _Unreached("upload_keymap")
|
|
|
|
def close(self) -> None:
|
|
pass
|
|
|
|
|
|
@pytest.fixture
|
|
def no_compositor(monkeypatch):
|
|
_RefusingSink.instances = 0
|
|
monkeypatch.setattr(entry, "WaylandSink", _RefusingSink)
|
|
return _RefusingSink
|
|
|
|
|
|
# -- defaults ---------------------------------------------------------------
|
|
|
|
|
|
def test_the_xkb_flags_default_to_the_frozen_values():
|
|
args = entry.build_parser().parse_args([])
|
|
assert args.xkb_layout == "us"
|
|
assert args.xkb_model == "pc105"
|
|
assert (args.xkb_variant, args.xkb_options) == ("", "")
|
|
|
|
|
|
def test_the_defaults_are_the_ones_the_module_option_defaults_to():
|
|
# Stated as constants so the NixOS option and the hand-run binary cannot
|
|
# drift into typing different characters.
|
|
assert (entry.DEFAULT_LAYOUT, entry.DEFAULT_MODEL) == ("us", "pc105")
|
|
|
|
|
|
def test_a_layout_is_taken_from_the_flag():
|
|
assert entry.build_parser().parse_args(["--xkb-layout", "de"]).xkb_layout == "de"
|
|
|
|
|
|
def test_the_contract_command_line_still_parses():
|
|
"""CONTRACT-sessions.md §3.4's exact line, plus the keymap flags."""
|
|
|
|
args = entry.build_parser().parse_args(
|
|
[
|
|
"--socket",
|
|
"/run/hhstream/pointer.sock",
|
|
"--compositor-runtime-dir",
|
|
"/run/hypr-stream",
|
|
"--xkb-layout",
|
|
"us",
|
|
"--xkb-model",
|
|
"pc105",
|
|
"--xkb-variant",
|
|
"",
|
|
"--xkb-options",
|
|
"",
|
|
]
|
|
)
|
|
assert str(args.socket) == "/run/hhstream/pointer.sock"
|
|
assert str(args.compositor_runtime_dir) == "/run/hypr-stream"
|
|
assert args.xkb_layout == "us"
|
|
|
|
|
|
# -- refusals, before any Wayland call --------------------------------------
|
|
|
|
|
|
def test_a_comma_separated_layout_exits_2_without_connecting(no_compositor, caplog):
|
|
"""v1 sends group 0 in every `modifiers`, so a second group is unreachable.
|
|
|
|
xkbcommon accepts `us,ru` and hands back a two-group keymap, so nothing
|
|
downstream would notice: a caller asking for Cyrillic would get Latin and
|
|
no error. Refused here, and the NixOS option's type refuses it too — this
|
|
one is for the binary run by hand, which that type cannot reach.
|
|
"""
|
|
|
|
code = entry.main(["--xkb-layout", "us,ru"])
|
|
|
|
assert code == entry.EXIT_USAGE
|
|
assert no_compositor.instances == 0, "the compositor must not be touched"
|
|
|
|
|
|
def test_a_layout_xkbcommon_rejects_exits_2_without_connecting(no_compositor):
|
|
code = entry.main(["--xkb-layout", "zzz-no-such-layout"])
|
|
|
|
assert code == entry.EXIT_USAGE
|
|
assert no_compositor.instances == 0
|
|
|
|
|
|
def test_a_usable_layout_gets_as_far_as_the_compositor(no_compositor):
|
|
"""The other half: exit 2 must not be how a *good* layout fails.
|
|
|
|
A test that only asserted the refusals would pass against a `main` that
|
|
returned 2 for everything, so this one proves the good path reaches the
|
|
Wayland side and fails there instead.
|
|
"""
|
|
|
|
with pytest.raises(_Unreached, match="connect"):
|
|
entry.main(["--xkb-layout", "us"])
|
|
assert no_compositor.instances == 1
|
|
|
|
|
|
def test_the_exit_codes_match_the_brokers_table():
|
|
"""Mirrored constants, compared against the table they mirror.
|
|
|
|
The driver keeps its own copies on purpose -- it is a separate package and
|
|
must not import the broker's internals -- so the two can drift, and
|
|
asserting the literals alone would not notice. This imports the broker's
|
|
enum to compare, which a test may do where the shipped driver may not.
|
|
"""
|
|
|
|
from hhstreamd.protocol import ExitCode
|
|
|
|
assert entry.EXIT_OK == ExitCode.OK
|
|
assert entry.EXIT_USAGE == ExitCode.USAGE
|
|
assert entry.EXIT_COMPOSITOR == ExitCode.COMPOSITOR
|
|
|
|
|
|
def test_the_module_passes_the_same_defaults_this_binary_has():
|
|
"""The drift this guards is silent: a unit and a hand-run binary that type
|
|
different characters, with nothing to compare them against but prose."""
|
|
|
|
module = Path(__file__).resolve().parents[2] / "nix/module.nix"
|
|
if not module.is_file():
|
|
pytest.skip("not running from a checkout")
|
|
text = module.read_text()
|
|
assert f'default = "{entry.DEFAULT_LAYOUT}";' in text
|
|
assert f'default = "{entry.DEFAULT_MODEL}";' in text
|
|
# And the unit really passes them, rather than relying on these defaults:
|
|
# a unit that relied on them would stop matching the contract's command
|
|
# line the moment either moved.
|
|
for flag in ("--xkb-layout", "--xkb-model", "--xkb-variant", "--xkb-options"):
|
|
assert f'"{flag}"' in text, f"{flag} is not on the unit's ExecStart"
|
|
|
|
|
|
# -- the keymap upload, which nothing else in the suite can see --------------
|
|
#
|
|
# The dispatcher tests record tuples from a sink, so they are blind to the
|
|
# Wayland `keymap` request: its format, its fd and its size never reach them.
|
|
# That is the review's finding 3 -- a `main` that connected and listened
|
|
# WITHOUT ever uploading passed every other test in this tree, and so did a
|
|
# backend that re-uploaded on every `type`.
|
|
|
|
|
|
#: One ordering log shared by the sink and the server stand-ins, because the
|
|
#: assertion is about the order of events *between* the two objects: an upload
|
|
#: after `listen` is a socket that promised a working device before it had one.
|
|
ORDER: list[str] = []
|
|
|
|
|
|
class _UploadingSink:
|
|
"""A sink whose connect succeeds, recording what it was asked to upload."""
|
|
|
|
def __init__(self, runtime_dir, display_name=None) -> None:
|
|
self.uploads: list[str] = []
|
|
self.connected = 0
|
|
_UploadingSink.last = self
|
|
|
|
def connect(self) -> None:
|
|
self.connected += 1
|
|
ORDER.append("connect")
|
|
|
|
def upload_keymap(self, text: str) -> None:
|
|
self.uploads.append(text)
|
|
ORDER.append("upload")
|
|
|
|
def has_keyboard(self) -> bool:
|
|
return True
|
|
|
|
def outputs(self) -> list[str]:
|
|
return []
|
|
|
|
def close(self) -> None:
|
|
pass
|
|
|
|
|
|
class _RecordingServer:
|
|
"""Stands in for `PointerServer`, so no socket is bound.
|
|
|
|
`serve_forever` raises, which is how the test gets control back at exactly
|
|
the point the real process would start answering requests -- and therefore
|
|
how it can assert the upload happened *before* that.
|
|
"""
|
|
|
|
class Served(Exception):
|
|
pass
|
|
|
|
def __init__(self, socket_path, handle, *, socket_mode=0o660) -> None:
|
|
self.events: list[str] = []
|
|
_RecordingServer.last = self
|
|
|
|
def listen(self) -> None:
|
|
self.events.append("listen")
|
|
ORDER.append("listen")
|
|
|
|
def serve_forever(self) -> None:
|
|
self.events.append("serve")
|
|
ORDER.append("serve")
|
|
raise _RecordingServer.Served
|
|
|
|
def close(self) -> None:
|
|
self.events.append("close")
|
|
|
|
|
|
@pytest.fixture
|
|
def uploading(monkeypatch):
|
|
ORDER.clear()
|
|
monkeypatch.setattr(entry, "WaylandSink", _UploadingSink)
|
|
monkeypatch.setattr(entry, "PointerServer", _RecordingServer)
|
|
return _UploadingSink
|
|
|
|
|
|
def test_the_keymap_is_uploaded_once_before_the_socket_listens(uploading):
|
|
"""The ordering rule, asserted rather than described.
|
|
|
|
`key` or `modifiers` before `keymap` is the protocol error `no_keymap`,
|
|
which kills the connection instead of returning something the broker could
|
|
report. So the upload has to happen between `connect` and `listen` -- a
|
|
listening socket is a promise that the device works.
|
|
"""
|
|
|
|
with pytest.raises(_RecordingServer.Served):
|
|
entry.main([])
|
|
|
|
sink = _UploadingSink.last
|
|
assert sink.connected == 1
|
|
assert len(sink.uploads) == 1, "uploaded once, not per request"
|
|
# The order across both objects, which is the whole assertion. A `main`
|
|
# that never uploaded, or uploaded after `listen`, fails here -- and before
|
|
# this test existed, both passed every other test in the tree.
|
|
assert ORDER == ["connect", "upload", "listen", "serve"]
|
|
|
|
|
|
def test_the_uploaded_text_is_the_keymap_for_the_flag(uploading):
|
|
with pytest.raises(_RecordingServer.Served):
|
|
entry.main(["--xkb-layout", "de"])
|
|
|
|
(text,) = _UploadingSink.last.uploads
|
|
assert text.lstrip().startswith("xkb_keymap {")
|
|
# The symbols name, which is what the VM check greps: a `de` layout that
|
|
# silently compiled as `us` would say `pc_us_inet(evdev)` here.
|
|
assert 'xkb_symbols "pc_de_inet(evdev)"' in text
|
|
|
|
|
|
def test_the_payload_is_nul_terminated_and_the_size_counts_the_nul():
|
|
"""The one value Hyprland reads off the end of the mapping if it is wrong.
|
|
|
|
It `mmap`s exactly `size` bytes and hands the pointer to
|
|
`xkb_keymap_new_from_string`, which wants a C string. A `size` of
|
|
`len(text)` therefore has no terminator inside the mapping. The symptom is
|
|
a keymap that will not compile, which from our side looks exactly like a
|
|
compositor that has no keyboard at all -- so this is asserted on the real
|
|
`WaylandSink.upload_keymap`, against a keyboard object that records the
|
|
request.
|
|
"""
|
|
|
|
pytest.importorskip("pywayland")
|
|
from hhstream_pointer import keymap as keymaps
|
|
from hhstream_pointer.backend import WaylandSink
|
|
|
|
class _Keyboard:
|
|
def __init__(self) -> None:
|
|
self.keymap_calls: list[tuple[int, bytes, int]] = []
|
|
self.modifier_calls: list[tuple] = []
|
|
|
|
def keymap(self, format_: int, fd: int, size: int) -> None:
|
|
# Read it back through the fd the compositor is handed, not through
|
|
# the string we started from: that is what the compositor sees.
|
|
with os.fdopen(os.dup(fd), "rb", closefd=True) as handle:
|
|
handle.seek(0)
|
|
self.keymap_calls.append((format_, handle.read(size), size))
|
|
|
|
def modifiers(self, *args) -> None:
|
|
self.modifier_calls.append(args)
|
|
|
|
class _Manager:
|
|
def __init__(self, keyboard) -> None:
|
|
self.keyboard = keyboard
|
|
|
|
def create_virtual_keyboard(self, seat):
|
|
return self.keyboard
|
|
|
|
keyboard = _Keyboard()
|
|
sink = WaylandSink(Path("/nonexistent"))
|
|
sink._keyboard_manager = _Manager(keyboard)
|
|
sink._display = _NullDisplay()
|
|
|
|
text = keymaps.build(layout="us").text()
|
|
sink.upload_keymap(text)
|
|
|
|
(format_, payload, size) = keyboard.keymap_calls[0]
|
|
assert format_ == keymaps.XKB_V1 == 1
|
|
assert payload.endswith(b"\0"), "no terminator inside the mapping"
|
|
assert payload.count(b"\0") == 1, "one terminator, not two"
|
|
assert size == len(text.encode("utf-8")) + 1
|
|
assert payload[:-1].decode("utf-8") == text
|
|
# And the mask is zeroed straight afterwards, because `destroy` of a
|
|
# previous driver's keyboard cleared no mask and a client keeps the last
|
|
# one it was sent.
|
|
assert keyboard.modifier_calls == [(0, 0, 0, 0)]
|
|
assert sink.has_keyboard() is True
|
|
|
|
|
|
def test_a_compositor_with_no_keyboard_manager_uploads_nothing_and_still_works():
|
|
pytest.importorskip("pywayland")
|
|
from hhstream_pointer.backend import WaylandSink
|
|
|
|
sink = WaylandSink(Path("/nonexistent"))
|
|
sink._display = _NullDisplay()
|
|
# No `_keyboard_manager`: the global was never advertised.
|
|
sink.upload_keymap("xkb_keymap {};")
|
|
assert sink.has_keyboard() is False
|
|
|
|
|
|
class _NullDisplay:
|
|
"""Enough of `pywayland.client.Display` for the two calls upload makes."""
|
|
|
|
def roundtrip(self) -> None:
|
|
pass
|
|
|
|
def flush(self) -> None:
|
|
pass
|