Files
HermenixandClaude Opus 5 561e0c28f5 Stage 2 fixes: the two tests the review named, and the docs drift
From docs/reviews/2026-10-04-stage2-3-review.md (Stage 3 done; Stage 2
done-with-fixes). Its findings 1, 2, 3 and 5, which it called the only
things standing before merge.

(A) REPLAY, THROUGH THE SINK. What existed was
    `test_every_keyboard_verb_is_cached_for_the_same_reason`, which
    asserts the two verbs are in MUTATING_VERBS -- and the verification
    doc had already named that as the false pass: "asserting
    `deduplicated` and not the sink. A handler that types and then sets
    the flag stays green." Two integration tests now, modelled on
    `test_a_retried_click_with_the_same_request_id_clicks_once`:

      test_a_retried_type_with_the_same_request_id_types_once
        `keyboard.type` of "ab" twice with request_id="retry-me".
        Asserts `deduplicated`, chars == 2 on both, and that the sink
        still has exactly 4 key events -- two characters, a down and an
        up each -- so a replay that typed again is caught by the count
        and not by the flag.

      test_a_retried_unmappable_type_stays_refused_and_types_nothing
        `café` twice with one id. Both refusals are `invalid_argument`,
        the second carries `deduplicated` (a recorded failure is
        replayed as the failure it was), and the sink is empty after
        both -- there is no partial type on either call.

    Mutation-checked rather than assumed: removing `keyboard.key` and
    `keyboard.type` from MUTATING_VERBS fails both.

(B) KILL, THROUGH kill(). `test_killing_the_holder_lifts_its_keys` calls
    `_drop_lease_for` directly, so it proves that helper lifts keys and
    says nothing about whether `kill` still calls it. The integration
    kill test now holds `Shift_L` before the kill and asserts the SINK
    saw `("key", 42, 0)` and `("modifiers", 0, 0, 0, 0)` -- the lease
    forgetting a key is not the compositor being told it came up, and
    only the second matters to the application. Code 42 because `type`
    never emits it, so the release cannot be a leftover.

    Mutation-checked: stubbing out the `_drop_lease_for` call in
    `kill()` fails it. Before this it stayed green.

(C) DOCS. The plan's stage table and risk paragraph still said acquire
    is one warp and that `focuswindow` was unbuilt Stage 4 work. The
    contract (v3 §4) describes what shipped; the plan did not. Rewritten
    so they agree, and the plan now says outright that the contract wins
    where they differ:

      * risk 1 marked RESOLVED, describing the two warps, the pinned
        `follow_mouse_threshold`, and `focuswindow` as the
        nudge-failure fallback selecting on `address:` (not
        `stable_id`, which is not a Hyprland selector)
      * Stage 3 marked Done; Stage 4 struck as not existing -- the
        answer to Stage 0 was the second warp, not a focus dispatch
      * the top banner, the §5 VM assertion list and open question 2
        no longer say "one warp"
      * verification §B3 subtest 1 amended: it is a live assertion
        rather than an expected red, and the check additionally requires
        `focus == "warp"` so the fallback is not accepted as success

    Also amended one sentence the review did not list, because leaving
    it would contradict the edit above inside the same document:
    verification §"Warp does not guarantee wl_keyboard.enter" predicted
    `focuswindow` was "likely mandatory". It was not; the second warp
    was.

    Written down rather than smoothed over: the `focuswindow` branch
    itself has no test, and if both mechanisms fail acquire still
    returns ok with `focus="none"` -- a lease whose first key may go to
    the previously focused window.

(D) The tap docstring claimed the `up` is sent even if the `down` was
    refused after sending. The next lines return early on `not ok`, and
    that early return is right: a refusal means the key was never
    pressed, so an `up` would ask the compositor to release something it
    never had. Sentence replaced with why the early return is correct
    and what actually covers a lost reply (the broker's `release_all`,
    not the CLI, which cannot know whether the request arrived).

Not done, and not claimed: findings 4, 6 and 7 (the broker chord test
checking first/last mask rather than the key; the at-cap test not
looking at the sink; the module-defaults test being a substring match).
The review rates all three as not holes in the claim, and the driver
tests are the locks for the first two.

  nix develop -c python -m pytest tests -q
    907 passed in 67.71s
  nix develop -c python -m pytest tests/pointer tests/sessions/unit -q
    605 passed in 27.16s

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GhNPM6rGcuzxocM1nATnuM
2026-10-05 04:43:56 +00:00

755 lines
29 KiB
Python

"""Integration: a real daemon, a real control socket, a container and a cursor.
Everything the broker talks to is a real socket in this test. The daemon is
``python -m hhstreamd`` in a subprocess; the compositor is an ``AF_UNIX``
listener laid out the way Hyprland lays one out, answering the commands
Hyprland answers; the pointer driver is the shipped driver with its Wayland
sink replaced by a recorder. No compositor, no VM, no GUI application, no
network.
**What this proves, and what it cannot.** It proves the broker's half: that
the plan's commands go out in the plan's order, that the record is built from
what came back rather than from what was asked for, that a container is taken
down with its session and an unattended one is taken down at start-up, and
that the cursor is leased, bookmarked and never left with a button down. It
proves nothing about whether Hyprland agrees — ``output create headless`` is
marked unverified in the plan, and this fake says ``ok`` because it was asked
politely. The slice report lists what still needs a real compositor.
"""
from __future__ import annotations
import json
import os
import signal
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from conftest import socket_path, wait_until
from fakes import WINDOW_PID, FakeCompositor, FakeDriver
from hhstreamd.protocol import ExitCode
# The lifecycle test owns the daemon harness; reusing it is what keeps the two
# files describing the *same* daemon rather than two subtly different ones.
from test_lifecycle import Daemon, compositor_dir, start
class Rig:
"""A daemon with a compositor and a driver behind it."""
def __init__(self, root: Path, *, with_compositor: bool = True, with_driver: bool = True):
self.root = root
# The daemon refuses to start without a Wayland socket to hand its
# children, so the compositor's runtime directory holds both: the
# `wayland-N` an application connects to and the `hypr/<sig>/` the
# broker queries. That is the real layout of /run/hypr-stream.
self.comp_dir, self._wayland = compositor_dir(root)
self.compositor = FakeCompositor(self.comp_dir) if with_compositor else None
runtime = root / "run"
runtime.mkdir(parents=True, exist_ok=True)
socket_path(runtime, "pointer.sock")
self.driver = FakeDriver(runtime / "pointer.sock") if with_driver else None
self.daemon = Daemon(root, "--compositor-runtime-dir", str(self.comp_dir))
if self.compositor is not None:
# As a deployment does: the instance is named, not guessed at.
self.daemon.env["HYPRLAND_INSTANCE_SIGNATURE"] = self.compositor.signature
def start(self) -> None:
self.daemon.start()
def stop(self) -> None:
self.daemon.stop()
if self.driver is not None:
self.driver.stop()
if self.compositor is not None:
self.compositor.stop()
self._wayland.close()
# -- convenience ------------------------------------------------------
def plan_commands(self) -> list[str]:
"""What the compositor was told to do, queries filtered out."""
assert self.compositor is not None
return [
c
for c in self.compositor.commands
if not c.startswith(("version", "clients", "monitors", "workspaces", "cursorpos"))
]
def make_rig(root: Path, **kwargs) -> Rig:
rig = Rig(root, **kwargs)
rig.start()
return rig
@pytest.fixture
def rig(short_tmpdir: Path):
r = make_rig(short_tmpdir)
try:
yield r
finally:
_kill_everything(r.daemon)
r.stop()
def _kill_everything(daemon: Daemon) -> None:
try:
for session in daemon.call("list", all=True).get("sessions", []):
if session.get("live"):
try:
daemon.call("kill", id=session["id"], grace_s=0)
except Exception:
pass
except Exception:
pass
# ===========================================================================
# the container, start to finish
# ===========================================================================
def test_a_started_session_gets_an_output_a_workspace_and_a_window(rig: Rig):
session_id = start(rig.daemon, "sleeper")
record = rig.daemon.session(session_id)
container = record["container"]
assert container["output"] == f"hh-{session_id}"
assert container["workspace"] == 1000
assert container["mode"] == {"width": 1280, "height": 720}
assert container["created_by"] == "broker"
assert container["state"] == "owned"
# The signature, so a restarted broker re-attaches to this instance.
assert record["signature"] == rig.compositor.signature
# And the compositor really has it.
assert f"hh-{session_id}" in rig.compositor.outputs()
assert rig.compositor.workspaces_on(f"hh-{session_id}") == [1000]
def test_the_spatial_fields_come_from_the_compositor_not_from_our_intention(rig: Rig):
"""The read-back is the point: a record that echoed the plan back would
look identical whether or not the window rule ever bound."""
session_id = start(rig.daemon, "sleeper")
record = rig.daemon.session(session_id)
assert record["workspace"] == 1000
# The fake gives every window it conjures a pid of its own, which is not
# the session's — so a record carrying it can only have come from
# `clients -j`.
assert record["window"]["stable_id"] == f"hh-{session_id}:{WINDOW_PID}"
assert record["window"]["initial_class"] == f"hh-{session_id}"
assert record["pid"] != WINDOW_PID
assert record["foreground"] is True
# And `status` says where all of that came from.
assert record["compositor"]["ipc"] == "ok"
assert record["compositor"]["signature"] == rig.compositor.signature
assert record["compositor"]["error"] is None
def test_the_plan_runs_in_order_with_the_quarantine_backstop_first(rig: Rig):
session_id = start(rig.daemon, "sleeper")
assert rig.plan_commands() == [
# Installed at start-up, before any container exists: it matches every
# class, and a catch-all declared after an anchored rule overrides it.
"keyword windowrule match:initial_class .*, workspace special:quarantine",
f"output create headless hh-{session_id}",
f"keyword workspace 1000, monitor:hh-{session_id}, default:true, persistent:true",
f"keyword windowrule match:initial_class ^hh-{session_id}$, workspace 1000, "
f"monitor hh-{session_id}",
f"keyword monitor hh-{session_id},1280x720,auto,1",
]
def test_the_application_is_launched_with_the_container_stamp(rig: Rig):
"""The class the window rule matches reaches the app in its environment.
The environment is the only lever the launcher has: a per-app
``--app-id``/``--class`` flag would have to come from the allowlist, and
the allowlist is not this slice's file. A toolkit that reads none of
these keeps its own class — which the read-back is there to catch.
"""
session_id = start(rig.daemon, "idump")
lines = wait_until(
lambda: rig.daemon.call("logs", id=session_id).get("lines"),
timeout=10.0,
what="the app to report its environment",
)
assert json.loads(lines[0]) == {
"HHSTREAM_APP_ID": f"hh-{session_id}",
"SDL_VIDEO_WAYLAND_WMCLASS": f"hh-{session_id}",
"RESOURCE_NAME": f"hh-{session_id}",
}
# And the rule the compositor was given matches exactly that class.
assert rig.compositor.rules[f"hh-{session_id}"] == (1000, f"hh-{session_id}")
def test_killing_a_session_removes_its_output_and_reports_no_survivors(rig: Rig):
session_id = start(rig.daemon, "sleeper")
assert f"hh-{session_id}" in rig.compositor.outputs()
reply = rig.daemon.call("kill", id=session_id, grace_s=0)
assert reply["ok"], reply
# Teardown facts ride with the record, where `survivors` already does and
# where the CLI reads them from.
record = reply["session"]
assert record["container_removed"] is True
assert record["container_survivors"] == []
assert record["container"]["state"] == "removed"
assert f"hh-{session_id}" not in rig.compositor.outputs()
assert f"output remove hh-{session_id}" in rig.plan_commands()
def test_a_window_that_outlives_the_teardown_is_reported_not_hidden(rig: Rig):
"""Two sources have to agree before a teardown is called a success."""
session_id = start(rig.daemon, "sleeper")
# A second window of ours that landed outside the container, so removing
# the output does not take it with it.
rig.compositor.add_window(f"hh-{session_id}", 1, "HEADLESS-1", pid=999)
reply = rig.daemon.call("kill", id=session_id, grace_s=0)
assert [s["pid"] for s in reply["session"]["container_survivors"]] == [999]
def test_the_workspace_slot_comes_back_when_the_session_does_not(rig: Rig):
first = start(rig.daemon, "sleeper")
assert rig.daemon.session(first)["container"]["workspace"] == 1000
rig.daemon.call("kill", id=first, grace_s=0)
second = start(rig.daemon, "sleeper")
assert rig.daemon.session(second)["container"]["workspace"] == 1000, "the slot was reused"
def test_two_sessions_get_different_outputs_and_different_workspaces(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
a = rig.daemon.session(first)["container"]
b = rig.daemon.session(second)["container"]
assert a["output"] != b["output"]
assert {a["workspace"], b["workspace"]} == {1000, 1001}
assert sorted(rig.compositor.outputs()) == sorted(
["HEADLESS-1", a["output"], b["output"]]
)
def test_container_list_reports_the_containers_and_the_orphans(rig: Rig):
session_id = start(rig.daemon, "sleeper")
rig.compositor.add_output("hh-ghost-aaaaaa")
reply = rig.daemon.call("container.list")
assert reply["ok"], reply
assert [row["id"] for row in reply["containers"]] == [session_id]
assert reply["orphans"] == ["hh-ghost-aaaaaa"]
assert reply["workspaces_in_use"] == [1000]
# Listing is not acting.
assert "hh-ghost-aaaaaa" in rig.compositor.outputs()
def test_container_reconcile_reports_the_difference_it_repaired(rig: Rig):
session_id = start(rig.daemon, "sleeper")
# The window goes away under the broker, as a crashed application's would.
rig.compositor._clients.clear()
reply = rig.daemon.call("container.reconcile", id=session_id)
assert reply["ok"], reply
fields = {d["field"]: d for d in reply["diff"]}
assert fields["window"]["observed"] is None
assert fields["window"]["recorded"]["initial_class"] == f"hh-{session_id}"
assert rig.daemon.session(session_id)["window"] is None
def test_a_window_that_lands_outside_its_desk_is_moved_onto_it(rig: Rig):
"""The case the class-matching rule could never handle.
Every allowlisted application keeps its own class, so the per-session rule
matches nothing and the window is swept to the quarantine backstop — a desk
created and left empty. The compositor reports each client's pid, so the
window can still be claimed: moved onto its own desk's workspace, with that
workspace made the visible one, and read back afterwards to say so.
"""
rig.compositor.auto_window = False
session_id = start(rig.daemon, "sleeper")
# It turns up on the main screen instead — where a quarantined window goes.
rig.compositor.add_window(f"hh-{session_id}", 1, "HEADLESS-1", pid=WINDOW_PID)
rig.daemon.call("container.reconcile", id=session_id)
record = rig.daemon.session(session_id)
desk = record["container"]
assert record["workspace"] == desk["workspace"], "the read-back says where it is"
assert record["foreground"] is True, "its desk is showing it"
assert desk["state"] != "degraded"
commands = rig.plan_commands()
assert (
f"dispatch movetoworkspacesilent {desk['workspace']},"
f"address:{record['window']['address']}" in commands
), commands
assert f"dispatch workspace {desk['workspace']}" in commands, commands
def test_a_window_already_on_its_desk_is_not_moved(rig: Rig):
"""The steady state costs nothing: a move is a real change on screen."""
session_id = start(rig.daemon, "sleeper")
rig.daemon.call("container.reconcile", id=session_id)
assert rig.daemon.session(session_id)["workspace"] == 1000
assert not [c for c in rig.plan_commands() if c.startswith("dispatch")]
# ===========================================================================
# the start-up scan
# ===========================================================================
def test_an_unattended_output_is_removed_when_the_broker_starts(short_tmpdir: Path):
"""A container must never be left running with nobody to own it."""
rig = make_rig(short_tmpdir)
try:
rig.daemon.stop()
rig.compositor.add_output("hh-leftover-aaaaaa")
rig.compositor.add_output("DP-9") # not ours, and must survive
rig.daemon.start()
assert "hh-leftover-aaaaaa" not in rig.compositor.outputs()
assert "DP-9" in rig.compositor.outputs()
assert "output remove hh-leftover-aaaaaa" in rig.plan_commands()
assert "output remove DP-9" not in rig.plan_commands()
finally:
_kill_everything(rig.daemon)
rig.stop()
def test_a_session_adopted_across_a_restart_keeps_its_container(short_tmpdir: Path):
rig = make_rig(short_tmpdir)
try:
session_id = start(rig.daemon, "sleeper")
output = rig.daemon.session(session_id)["container"]["output"]
rig.daemon.stop()
rig.daemon.start()
record = rig.daemon.session(session_id)
assert record["adopted"] is True
assert record["container"]["state"] == "owned"
assert output in rig.compositor.outputs(), "an adopted container is not an orphan"
# Its slot is not handed to the next session.
assert rig.daemon.session(start(rig.daemon, "sleeper"))["container"]["workspace"] == 1001
finally:
_kill_everything(rig.daemon)
rig.stop()
# ===========================================================================
# degraded mode — PLAN §4.4
# ===========================================================================
def test_with_no_compositor_ipc_sessions_still_live_and_die_normally(short_tmpdir: Path):
"""Lifecycle verbs never depend on the compositor.
The daemon has a Wayland socket to hand its children (so it starts) and no
Hyprland instance to query, which is exactly what a compositor that is up
but not answering IPC looks like from here.
"""
rig = make_rig(short_tmpdir, with_compositor=False)
try:
session_id = start(rig.daemon, "sleeper")
record = rig.daemon.session(session_id)
assert record["state"] == "ready"
assert record["container"] == {
"output": None,
"workspace": None,
"mode": None,
"created_by": "broker",
"state": "degraded",
}
# Nothing is guessed: no workspace, no window, no instance.
assert (record["workspace"], record["window"], record["signature"]) == (None, None, None)
assert record["compositor"]["ipc"] == "absent"
rig.daemon.call("touch", id=session_id)
reply = rig.daemon.call("kill", id=session_id, grace_s=0)
assert reply["ok"], reply
assert reply["session"]["state"] == "killed"
assert reply["session"]["survivors"] == []
assert reply["session"]["container_survivors"] == []
finally:
_kill_everything(rig.daemon)
rig.stop()
def test_a_degraded_session_cannot_be_aimed_at_and_says_why(short_tmpdir: Path):
rig = make_rig(short_tmpdir, with_compositor=False)
try:
session_id = start(rig.daemon, "sleeper")
reply = rig.daemon.call("pointer.acquire", id=session_id)
assert reply["ok"] is False
assert reply["error"] == "no_container"
assert ExitCode(10) == ExitCode.COMPOSITOR
finally:
_kill_everything(rig.daemon)
rig.stop()
# ===========================================================================
# the pointer, over the real control socket
# ===========================================================================
def test_a_whole_gesture_runs_through_the_broker_and_the_driver(rig: Rig):
session_id = start(rig.daemon, "sleeper")
output = f"hh-{session_id}"
acquired = rig.daemon.call("pointer.acquire", id=session_id)
assert acquired["ok"], acquired
lease = acquired["lease_id"]
assert acquired["bookmark"] == {
"x": 0.5,
"y": 0.5,
"output": output,
"at": acquired["bookmark"]["at"],
}
moved = rig.daemon.call("pointer.move", id=session_id, lease_id=lease, x=0.25, y=0.75)
assert moved["ok"], moved
assert (moved["bookmark"]["x"], moved["bookmark"]["y"]) == (0.25, 0.75)
clicked = rig.daemon.call("pointer.click", id=session_id, lease_id=lease, button="left")
assert clicked["ok"], clicked
released = rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
assert released["ok"], released
assert released["released_by"] == "lease"
assert released["buttons_lifted"] == []
assert rig.driver.sink.calls == [
# Acquire is TWO warps: one warp onto an idle cursor moves the cursor
# and not keyboard focus, so acquire nudges to a neighbouring pixel and
# then lands on the target. The second one is the bookmark.
("warp", output, 0.5, 0.504),
("frame", output),
("warp", output, 0.5, 0.5),
("frame", output),
("warp", output, 0.25, 0.75),
("frame", output),
("button", output, 0x110, 1),
("frame", output),
("button", output, 0x110, 0),
("frame", output),
]
# The bookmark is in the record, which is what survives a broker restart.
record = rig.daemon.session(session_id)
assert record["pointer"]["bookmark"]["x"] == 0.25
assert record["pointer"]["released_by"] == "lease"
assert record["pointer"]["last_released_at"] == released["released_at"]
def test_the_cursor_is_leased_broker_wide_and_the_holder_is_named(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
refused = rig.daemon.call("pointer.acquire", id=second)
assert refused["ok"] is False
assert refused["error"] == "pointer_busy"
assert refused["holder"] == first
# And the other session cannot move it with someone else's lease either.
denied = rig.daemon.call("pointer.move", id=second, lease_id=lease, x=0.1, y=0.1)
assert denied["error"] == "no_lease"
state = rig.daemon.call("pointer.state")
assert state["holder"] == first
assert state["lease_id"] == lease
def test_a_released_lease_frees_the_cursor_for_the_next_session(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
rig.daemon.call("pointer.release", id=first, lease_id=lease)
taken = rig.daemon.call("pointer.acquire", id=second)
assert taken["ok"], taken
assert taken["bookmark"]["output"] == f"hh-{second}"
def test_a_button_left_down_is_lifted_when_the_lease_is_released(rig: Rig):
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
down = rig.daemon.call("pointer.button", id=session_id, lease_id=lease, button="left", state="down")
assert down["buttons"] == ["left"]
released = rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
assert released["buttons_lifted"] == ["left"]
assert rig.driver.dispatcher._pressed == {}, "nothing may be left down on the driver"
def test_killing_a_session_that_holds_the_cursor_gives_it_back(rig: Rig):
"""Through `kill`, with a button AND a key down.
The key half is here rather than in a unit test on purpose. The unit test
calls `_drop_lease_for` directly, so it proves that helper lifts keys and
says nothing about whether `kill` still calls it -- removing the call would
leave that test green. This goes through the verb, and it asserts on the
SINK rather than on `pointer.state`: the lease forgetting a key is not the
same as the compositor being told it came up, and only the second one
matters to the application.
"""
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
rig.daemon.call("pointer.button", id=first, lease_id=lease, button="right", state="down")
held = rig.daemon.call(
"keyboard.key", id=first, lease_id=lease, key="Shift_L", state="down"
)
assert held["keys"] == ["Shift_L"], held
rig.driver.sink.calls.clear()
rig.daemon.call("kill", id=first, grace_s=0)
# KEY_LEFTSHIFT, and `state=0`. Shift is the key to use because `type`
# never emits code 42, so a release of it cannot be a leftover from
# anything else this rig did.
assert ("key", 42, 0) in rig.driver.sink.calls, (
f"kill did not lift the held key: {rig.driver.sink.calls}. On this "
"compositor a code left in the seat's m_pressed makes the NEXT press "
"of it a no-op, so the key is dead rather than merely stuck."
)
# And the mask with it: a virtual key-up clears no modifier state, so
# without this the next holder inherits Shift.
assert ("modifiers", 0, 0, 0, 0) in rig.driver.sink.calls, rig.driver.sink.calls
assert rig.driver.dispatcher._pressed == {}
assert rig.driver.dispatcher._keys == {}
assert rig.daemon.call("pointer.state")["holder"] is None
assert rig.daemon.call("pointer.acquire", id=second)["ok"]
def test_pointer_verbs_do_not_reset_the_idle_clock(rig: Rig):
"""A session being clicked in is still one nobody has asked to keep."""
session_id = start(rig.daemon, "sleeper")
before = rig.daemon.session(session_id)["command_count"]
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.daemon.call("pointer.move", id=session_id, lease_id=lease, x=0.3, y=0.3)
rig.daemon.call("pointer.click", id=session_id, lease_id=lease)
rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
assert rig.daemon.session(session_id)["command_count"] == before
def test_a_retried_click_with_the_same_request_id_clicks_once(rig: Rig):
"""A click is the one mutation an agent cannot undo."""
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.driver.sink.calls.clear()
first = rig.daemon.call(
"pointer.click", id=session_id, lease_id=lease, request_id="retry-me"
)
second = rig.daemon.call(
"pointer.click", id=session_id, lease_id=lease, request_id="retry-me"
)
assert first["ok"] and second["ok"]
assert second.get("deduplicated") is True
assert len(rig.driver.sink.of("button")) == 2, "one press and one release, not two"
def test_a_retried_type_with_the_same_request_id_types_once(rig: Rig):
"""A retried `type` is the keyboard's version of a second click.
Asserted on the SINK and not on the `deduplicated` flag, because the flag
alone is the false pass the verification doc names: a handler that typed
the string and *then* set the flag would satisfy it. The thing that must
not happen twice is the key events, so those are what is counted.
The cache is not keyboard-specific -- `_dispatch` looks the `request_id` up
before the handler and remembers it after, keyed on the id alone -- so what
this locks is that `keyboard.type` is in the mutating set and therefore
reaches that path at all.
"""
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.driver.sink.calls.clear()
first = rig.daemon.call(
"keyboard.type", id=session_id, lease_id=lease, text="ab", request_id="retry-me"
)
second = rig.daemon.call(
"keyboard.type", id=session_id, lease_id=lease, text="ab", request_id="retry-me"
)
assert first["ok"] and second["ok"]
assert second.get("deduplicated") is True
assert first["chars"] == 2 and second["chars"] == 2
# Two characters, a down and an up each: four key events for one `type`,
# and the replay must not add a fifth.
assert len(rig.driver.sink.of("key")) == 4, (
f"a replayed type sent {rig.driver.sink.of('key')}; the recorded answer "
"must be returned without typing again"
)
def test_a_retried_unmappable_type_stays_refused_and_types_nothing(rig: Rig):
"""The recorded answer includes a recorded refusal.
An agent that retries a `type` which was refused must see the refusal
again, not a second attempt -- and the sink must still be untouched after
both calls, because validation happens before the first event either time.
"""
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.driver.sink.calls.clear()
first = rig.daemon.call(
"keyboard.type",
id=session_id,
lease_id=lease,
text="caf\u00e9",
request_id="refuse-me",
)
second = rig.daemon.call(
"keyboard.type",
id=session_id,
lease_id=lease,
text="caf\u00e9",
request_id="refuse-me",
)
assert first["ok"] is False and second["ok"] is False
assert first["error"] == "invalid_argument", first
assert second["error"] == "invalid_argument", second
assert second.get("deduplicated") is True, (
"a recorded failure must be replayed as the failure it was"
)
assert rig.driver.sink.of("key") == [], (
f"an unmappable string typed something: {rig.driver.sink.calls}. There is "
"no partial type, on the first call or the replay."
)
def test_a_restored_bookmark_survives_a_daemon_restart(short_tmpdir: Path):
"""That is what putting it in the record, and not only in the lease, is for."""
rig = make_rig(short_tmpdir)
try:
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.daemon.call("pointer.move", id=session_id, lease_id=lease, x=0.8, y=0.2)
rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
rig.daemon.stop()
rig.daemon.start()
rig.driver.sink.calls.clear()
acquired = rig.daemon.call("pointer.acquire", id=session_id)
assert (acquired["bookmark"]["x"], acquired["bookmark"]["y"]) == (0.8, 0.2)
# The nudge, then the restored position: the bookmark has to be the
# *second* warp, or every restore would be a few pixels off.
assert rig.driver.sink.of("warp") == [
("warp", f"hh-{session_id}", 0.8, 0.204),
("warp", f"hh-{session_id}", 0.8, 0.2),
]
finally:
_kill_everything(rig.daemon)
rig.stop()
def test_with_no_driver_the_pointer_verbs_say_so_and_the_lease_is_not_held(
short_tmpdir: Path,
):
rig = make_rig(short_tmpdir, with_driver=False)
try:
session_id = start(rig.daemon, "sleeper")
reply = rig.daemon.call("pointer.acquire", id=session_id)
assert reply["ok"] is False
assert reply["error"] == "driver_unavailable"
assert rig.daemon.call("pointer.state")["holder"] is None
finally:
_kill_everything(rig.daemon)
rig.stop()
# ===========================================================================
# an exit nobody asked for
# ===========================================================================
def test_an_application_that_dies_takes_its_container_with_it(rig: Rig):
session_id = start(rig.daemon, "sleeper")
output = f"hh-{session_id}"
pid = rig.daemon.session(session_id)["pid"]
os.kill(pid, signal.SIGKILL)
wait_until(
lambda: not rig.daemon.session(session_id)["live"],
timeout=10.0,
what="the daemon to notice the exit",
)
wait_until(
lambda: output not in rig.compositor.outputs(),
timeout=10.0,
what="the container to be taken down with it",
)
assert rig.daemon.session(session_id)["container"]["state"] == "removed"
# And its slot is free again.
assert rig.daemon.session(start(rig.daemon, "sleeper"))["container"]["workspace"] == 1000
def test_a_session_that_dies_holding_the_cursor_gives_it_back(rig: Rig):
"""Never leave a button down, even when nobody asked for the teardown."""
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
rig.daemon.call("pointer.button", id=first, lease_id=lease, button="left", state="down")
os.kill(rig.daemon.session(first)["pid"], signal.SIGKILL)
wait_until(
lambda: rig.daemon.call("pointer.state")["holder"] is None,
timeout=10.0,
what="the lease to come back",
)
assert rig.driver.dispatcher._pressed == {}
assert rig.daemon.call("pointer.acquire", id=second)["ok"]