Files
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

221 lines
7.3 KiB
Python

"""Protocol framing tests (DESIGN.md §3.4)."""
from __future__ import annotations
import json
import pytest
from hhstreamd import protocol
from hhstreamd.protocol import MAX_LINE_BYTES, PROTOCOL_VERSION, ProtocolError
def test_a_message_is_exactly_one_newline_terminated_line():
frame = protocol.encode({"ok": True, "id": "foot-aaaaaa"})
assert frame.endswith(b"\n")
assert frame.count(b"\n") == 1
assert json.loads(frame) == {"ok": True, "id": "foot-aaaaaa"}
def test_round_trip():
message = {"v": 1, "op": "start", "app": "foot", "argv": ["--a", "--b"]}
assert protocol.decode(protocol.encode(message)) == message
def test_embedded_newlines_cannot_break_the_framing():
"""A session id or an argv element must never be able to split a frame."""
message = {"ok": False, "reason": "line one\nline two\r\nline three"}
frame = protocol.encode(message)
assert frame.count(b"\n") == 1
assert protocol.decode(frame) == message
def test_non_ascii_is_escaped_so_the_frame_stays_ascii():
frame = protocol.encode({"reason": "café — ✓"})
frame.decode("ascii") # must not raise
assert protocol.decode(frame)["reason"] == "café — ✓"
def test_decode_tolerates_a_missing_trailing_newline():
assert protocol.decode(b'{"ok":true}') == {"ok": True}
@pytest.mark.parametrize("line", [b"", b"\n", b" \n"])
def test_an_empty_frame_is_a_bad_request(line):
with pytest.raises(ProtocolError) as exc:
protocol.decode(line)
assert exc.value.error == "bad_request"
def test_malformed_json_is_a_bad_request():
with pytest.raises(ProtocolError) as exc:
protocol.decode(b"{not json\n")
assert exc.value.error == "bad_request"
assert "malformed JSON" in exc.value.reason
@pytest.mark.parametrize("payload", [b"[1,2,3]", b'"a string"', b"42", b"null"])
def test_a_frame_that_is_not_an_object_is_rejected(payload):
with pytest.raises(ProtocolError) as exc:
protocol.decode(payload)
assert exc.value.error == "bad_request"
def test_an_oversized_frame_is_refused_on_both_sides():
with pytest.raises(ProtocolError) as exc:
protocol.decode(b"x" * (MAX_LINE_BYTES + 1))
assert exc.value.error == "message_too_large"
with pytest.raises(ProtocolError) as exc:
protocol.encode({"argv": ["x" * MAX_LINE_BYTES]})
assert exc.value.error == "message_too_large"
def test_decode_request_requires_an_op():
with pytest.raises(ProtocolError) as exc:
protocol.decode_request(b'{"v":1}')
assert exc.value.error == "bad_request"
assert "no 'op'" in exc.value.reason
def test_decode_request_rejects_an_unknown_protocol_version():
with pytest.raises(ProtocolError) as exc:
protocol.decode_request(b'{"v":99,"op":"list"}')
assert exc.value.error == "unsupported_version"
def test_a_request_without_a_version_is_assumed_to_be_current():
assert protocol.decode_request(b'{"op":"list"}')["op"] == "list"
def test_request_attaches_the_version_and_drops_unset_fields():
message = protocol.request("start", app="foot", argv=None, idle_timeout_s=30.0)
assert message == {"v": PROTOCOL_VERSION, "op": "start", "app": "foot", "idle_timeout_s": 30.0}
def test_error_replies_carry_both_a_machine_field_and_a_human_field():
reply = protocol.error(
"not_allowlisted", "app 'sh' is not in the allowlist", hint="see the config"
)
assert reply == {
"ok": False,
"error": "not_allowlisted",
"reason": "app 'sh' is not in the allowlist",
"hint": "see the config",
}
def test_ok_replies_are_flagged():
assert protocol.ok(id="a")["ok"] is True
# ---------------------------------------------------------------------------
# `request_id` idempotency (PLAN §8)
# ---------------------------------------------------------------------------
def test_a_repeated_mutating_request_returns_the_recorded_answer():
cache = protocol.IdempotencyCache()
cache.remember("start", "r1", {"ok": True, "id": "foot-aaaaaa"})
replay = cache.lookup("start", "r1")
assert replay == {"ok": True, "id": "foot-aaaaaa", "deduplicated": True}
def test_a_recorded_failure_is_replayed_as_the_failure_it_was():
"""A retried `start` that policy refused must not get a second attempt."""
cache = protocol.IdempotencyCache()
cache.remember("start", "r1", {"ok": False, "error": "not_allowlisted"})
assert cache.lookup("start", "r1")["error"] == "not_allowlisted"
def test_read_verbs_are_never_cached_because_a_stale_list_is_worse():
cache = protocol.IdempotencyCache()
cache.remember("list", "r1", {"ok": True, "sessions": []})
assert cache.lookup("list", "r1") is None
def test_a_request_with_no_id_is_never_matched_against_another():
cache = protocol.IdempotencyCache()
cache.remember("start", None, {"ok": True})
assert len(cache) == 0
assert cache.lookup("start", None) is None
def test_the_cache_is_bounded_because_the_peer_chooses_the_keys():
cache = protocol.IdempotencyCache(capacity=4)
for n in range(10):
cache.remember("touch", f"r{n}", {"ok": True, "n": n})
assert len(cache) == 4
assert cache.lookup("touch", "r0") is None
assert cache.lookup("touch", "r9")["n"] == 9
def test_every_pointer_verb_that_moves_something_is_cached():
"""A retried click is a second click — the one mutation an agent cannot undo."""
assert {
"pointer.acquire",
"pointer.move",
"pointer.button",
"pointer.click",
"pointer.release",
} <= protocol.MUTATING_VERBS
assert "pointer.state" not in protocol.MUTATING_VERBS
assert "container.list" not in protocol.MUTATING_VERBS
def test_every_keyboard_verb_is_cached_for_the_same_reason():
"""A retried `type` that typed twice is also unrecoverable.
And `pointer.state`, which now reports held keys, stays out of the set: it
mutates nothing, and a cached one would be a stale one.
"""
assert {"keyboard.key", "keyboard.type"} <= protocol.MUTATING_VERBS
assert {"keyboard.key", "keyboard.type"} <= set(protocol.VERBS)
assert "pointer.state" not in protocol.MUTATING_VERBS
def test_there_is_no_keyboard_acquire_verb():
"""One seat, one keyboard focus, one lease.
A `keyboard.acquire` would let session B warp the pointer while session A
believed it was typing into its own window, because `follow_mouse = 1`
means a warp retargets the keys.
"""
assert not any(verb.startswith("keyboard.acquire") for verb in protocol.VERBS)
assert "keyboard.release" not in protocol.VERBS
def test_every_verb_the_protocol_names_is_one_the_daemon_answers():
"""One list, so a verb cannot be added to the dispatcher alone.
The CLI imports `protocol`, not `server`; a verb in one and not the other
is a client that asks for something nothing answers.
"""
from pathlib import Path
from hhstreamd.clock import ManualClock
from hhstreamd.manager import ManagerConfig, SessionManager
from hhstreamd.policy import Policy
from hhstreamd.server import ControlServer
manager = SessionManager(
ManagerConfig(state_dir=Path("/nonexistent"), runtime_dir=Path("/nonexistent"), policy=Policy()),
clock=ManualClock(),
)
server = ControlServer(manager, "/nonexistent/control.sock")
assert set(server._ops) == set(protocol.VERBS)
assert protocol.MUTATING_VERBS <= set(protocol.VERBS)