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:
HermenixandClaude Opus 5 committed 2026-10-04 04:11:24 +00:00
1 parent b1f2744cf0
commit e6f4c3bb3f
24 files changed
+2474 -105

No files matched your search

+253 -4
View File
@@ -35,10 +35,17 @@ The verb tree, beyond the original eight:
session pointer move ID ... warp, --to X,Y or --by DX,DY (0..1, per output)
session pointer click/down/up/release ID
session pointer state who holds the cursor and what is pressed
session keyboard type ID TEXT one argument, raw UTF-8, no escapes
session keyboard key ID NAME tap: down then up
session keyboard down/up ID NAME
The pointer verbs share one precondition — the lease — and the lease id lives
in :mod:`hhstream_session.lease` between invocations, because the wire requires
it on every gesture and the CLI is one process per verb.
The pointer *and keyboard* verbs share one precondition — the pointer lease —
and the lease id lives in :mod:`hhstream_session.lease` between invocations,
because the wire requires it on every gesture and the CLI is one process per
verb. There is no ``keyboard acquire``: one ``wl_seat`` means one keyboard
focus, and the shipped ``follow_mouse = 1`` means another session's warp
retargets the keys, so a second lease would let session B move the pointer
while session A believed it was typing into its own window.
"""
from __future__ import annotations
@@ -293,6 +300,9 @@ def _build_namespace(parser: argparse.ArgumentParser) -> None:
# ---- pointer -----------------------------------------------------
_build_pointer(verbs, common)
# ---- keyboard ----------------------------------------------------
_build_keyboard(verbs, common)
#: Button names the driver knows (``hhstream_pointer.buttons.CODES``), mirrored
#: here rather than imported: this module's whole integration promise is that it
@@ -475,6 +485,148 @@ def _build_pointer(verbs: Any, common: argparse.ArgumentParser) -> None:
)
#: Printed under `keyboard --help` and under every one of its verbs. It is the
#: single fact an agent gets wrong about this group, exactly as ACTIVITY_NOTE is
#: for the namespace: the keyboard has no lease of its own.
KEYBOARD_LEASE_NOTE = (
"LEASE: every keyboard verb needs the POINTER lease and refuses with exit 9 "
"until 'hhstream session pointer acquire <id>'. There is no 'keyboard "
"acquire': the compositor has one seat and one keyboard focus, and another "
"session's pointer warp would retarget the keys mid-string. 'pointer "
"release' lifts held keys as well as held buttons, and so does a lease "
"timeout."
)
def _build_keyboard(verbs: Any, common: argparse.ArgumentParser) -> None:
"""``session keyboard <verb>`` — typing into whatever the seat focuses.
A nested namespace for the same reason ``pointer`` is one: these four verbs
share a precondition nothing else here has. It is the *pointer* lease, and
saying that once in a group description is better than four times in four
help strings -- though the note is repeated per verb anyway, because
``--help`` on a leaf is what an agent actually reads.
"""
namespace = verbs.add_parser(
"keyboard",
parents=[common],
help="type into the session the seat is focused on, under the pointer lease",
description=(
"Keys go to whichever surface the compositor's one seat has focused "
"-- a virtual keyboard is seat-global and has no output argument, so "
"unlike the pointer there is nothing to aim. What aims it is the "
"pointer: 'pointer acquire' warps into the session's own container "
"and the lease is what stops another session moving focus while you "
"type.\n\n"
"NAME is an XKB keysym name, not a number: 'a', 'A', 'Return', "
"'BackSpace', 'Left', 'Control_L', 'Shift_L'. It is resolved against "
"the layout the driver uploaded (set by the operator; 'us' by "
"default), so a name that layout does not carry is exit 2.\n\n"
"TEXT is one argument of raw UTF-8 and backslash escapes are NOT "
"interpreted: a newline is a real newline in the argument and the "
"shell does the quoting. A character the layout cannot produce "
"fails the whole string and types nothing -- there is no partial "
"type.\n\n"
"No keyboard verb counts as activity, exactly as no pointer verb "
"does. Call 'touch'."
),
epilog=f"{KEYBOARD_LEASE_NOTE}\n\n{ACTIVITY_NOTE}",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
keys = namespace.add_subparsers(dest="keyboard_verb", metavar="VERB")
# With no verb, print this group's help rather than guessing: unlike
# `pointer`, there is no read-only verb here that could be the default --
# held keys are reported by `pointer state`, which is where buttons are.
namespace.set_defaults(
func=_cmd_keyboard_usage, hhstream_session_handler=_cmd_keyboard_usage, json=False
)
namespace.set_defaults(keyboard_parser=namespace)
def add_key_verb(name: str, handler, **kwargs: Any):
sub = keys.add_parser(
name,
parents=[common],
epilog=KEYBOARD_LEASE_NOTE,
formatter_class=argparse.RawDescriptionHelpFormatter,
**kwargs,
)
sub.set_defaults(func=handler, hhstream_session_handler=handler)
sub.add_argument("--json", action="store_true", help="emit the protocol object on stdout")
sub.add_argument(
"--lease",
metavar="ID",
help="the lease id from 'pointer acquire'. Omitted, the one that "
f"acquire cached is used (${lease.ENV_LEASE} overrides that).",
)
sub.add_argument("id", help="session id")
return sub
type_ = add_key_verb(
"type",
_cmd_keyboard_type,
help="type one string into the focused window",
description=(
"Type TEXT. One argument, raw UTF-8, no backslash escapes: '\n' is "
"a backslash and an n, and a newline is a newline. Capitals and "
"symbols are sent as a modifier MASK plus the letter's key, not as "
"a synthesized Shift keypress, because this compositor does not "
"derive the mask from an injected key.\n\n"
"Validation is complete before the first event: a character the "
"uploaded layout cannot produce fails the request and types "
"nothing, so there is never a half-typed prefix to clean up. On the "
"default 'us' layout that includes 'e' with an acute accent, and "
"every C0 control except newline and tab.\n\n"
"A modifier held with 'keyboard down' is a baseline: its mask is "
"ORed into every character and it is STILL HELD when this returns, "
"which is how a chord is spelled. A non-modifier key held is a "
"refusal, because the application still believes it is being held."
),
)
type_.add_argument(
"text",
help="the string to type, as ONE argument (quote it; a newline is a newline)",
)
tap = add_key_verb(
"key",
_cmd_keyboard_key,
help="tap one keysym: down then up",
description=(
"Press and release one key. This is the verb for 'Return', 'Tab', "
"'BackSpace' and the arrows -- anything 'type' cannot express "
"because it has no character."
),
)
tap.add_argument("name", help="XKB keysym name, e.g. Return, BackSpace, Left")
for verb, state in (("down", "down"), ("up", "up")):
sub = add_key_verb(
verb,
_cmd_keyboard_hold,
help=(
"hold a key down without releasing it"
if state == "down"
else "release a key that was held down"
),
description=(
"Half a tap. The justified use is a chord: 'down Control_L', "
"then 'type c', then 'up Control_L'.\n\n"
"HOLDING A NON-MODIFIER FLOODS THE WINDOW. The compositor sends "
"one key event and publishes a repeat rate; the APPLICATION "
"repeats, so a held 'a' inserts characters for as long as it is "
"down -- up to the whole lease TTL. This is not configurable "
"here: the repeats are not ours to rate-limit. Measured on this "
"build at 25/s after 600ms.\n\n"
"The broker lifts whatever is still down on 'pointer release' "
"or on a lease timeout, so a crashed agent cannot leave a key "
"held."
),
)
sub.set_defaults(key_state=state)
sub.add_argument("name", help="XKB keysym name, e.g. Control_L, Shift_L")
def _button_help() -> str:
return f"one of: {', '.join(BUTTONS)} (default: left)"
@@ -938,7 +1090,8 @@ def _cmd_pointer_acquire(args: argparse.Namespace) -> int:
)
print(
f"expires in {_fmt_timeout(reply.get('expires_in_s'))} with no further "
f"pointer verb; release it with: hhstream session pointer release {args.id}",
f"pointer OR keyboard verb; release it with: hhstream session pointer "
f"release {args.id}",
file=sys.stderr,
)
return int(ExitCode.OK)
@@ -1057,6 +1210,102 @@ def _cmd_pointer_state(args: argparse.Namespace) -> int:
return _finish(args, reply, fmt.render_pointer_state)
# --------------------------------------------------------------------------
# the keyboard, on the same lease
# --------------------------------------------------------------------------
def _cmd_keyboard_usage(args: argparse.Namespace) -> int:
"""`session keyboard` with no verb. Prints help, exits 2.
Not a default verb: the only read-only thing to say about the keyboard is
which keys are held, and that is `pointer state`, beside the buttons.
"""
parser = getattr(args, "keyboard_parser", None)
if parser is not None:
parser.print_help(sys.stderr)
return int(ExitCode.USAGE)
@_guard
def _cmd_keyboard_type(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
# `args.text` goes through untouched. No `.encode().decode('unicode_escape')`
# and no strip: the shell quoted it, and a CLI that interpreted backslashes
# would make a literal backslash-n untypeable.
reply = _request(args, "keyboard.type", id=args.id, lease_id=lease_id, text=args.text)
def render(r: dict[str, Any]) -> str:
held = r.get("keys") or []
# The COUNT, never the text: this line goes to a terminal that is
# often being logged, and the string is a password as often as not.
bits = [f"{r.get('id')}: typed {r.get('chars')} character(s)"]
if held:
bits.append(f"still held: {', '.join(held)}")
return "; ".join(bits)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_keyboard_key(args: argparse.Namespace) -> int:
"""A tap: down then up, as two wire calls.
Two calls and not a `count`-style loop in the broker, because a tap is the
only thing anyone wants and the pair is what `down`/`up` already are. The
`up` is sent even if the `down` was refused-after-sending, for the same
reason the broker lifts on expiry: a key left down is worse than stuck.
"""
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
down = _request(
args, "keyboard.key", id=args.id, lease_id=lease_id, key=args.name, state="down"
)
if not down.get("ok"):
return _finish_gesture(args, down, lambda r: "", args.id)
reply = _request(
args, "keyboard.key", id=args.id, lease_id=lease_id, key=args.name, state="up"
)
def render(r: dict[str, Any]) -> str:
held = r.get("keys") or []
return (
f"{r.get('id')}: tapped {args.name}; "
f"held: {', '.join(held) if held else 'nothing'}"
)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_keyboard_hold(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(
args,
"keyboard.key",
id=args.id,
lease_id=lease_id,
key=args.name,
state=args.key_state,
)
def render(r: dict[str, Any]) -> str:
held = r.get("keys") or []
return (
f"{r.get('id')}: {args.name} {args.key_state}; "
f"held: {', '.join(held) if held else 'nothing'}"
)
return _finish_gesture(args, reply, render, args.id)
# --------------------------------------------------------------------------
# standalone use
# --------------------------------------------------------------------------