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
This commit is contained in:
1 parent
b1f2744cf0
commit
e6f4c3bb3f
24 files changed
+2474
-105
No files matched your search
@@ -16,6 +16,9 @@ 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
|
||||
@@ -139,6 +142,222 @@ def test_a_usable_layout_gets_as_far_as_the_compositor(no_compositor):
|
||||
|
||||
|
||||
def test_the_exit_codes_match_the_brokers_table():
|
||||
# Mirrored, not imported: the driver is a separate package on purpose
|
||||
# (see the module docstring in __main__).
|
||||
assert (entry.EXIT_OK, entry.EXIT_USAGE, entry.EXIT_COMPOSITOR) == (0, 2, 10)
|
||||
"""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
|
||||
Reference in new issue
Block a user