Files
hyprland-headless-stream-pl…/tests/sessions/integration/test_containers.py
T
HermenixandClaude Opus 5 7890315cf6 checks(unit): xkbcommon in the suite's env, and the two-warp acquire
Two gaps found by running more than the gate command.

`checks/unit.nix` builds its own `python3.withPackages` and had only
pytest and pywayland in it, so `nix build .#checks.unit` would have
collected tests/pointer/test_keymap.py and failed on the import. The
dev shell has xkbcommon through nix/package.nix and the gate command
therefore never noticed. It is not an optional dependency: that file
compiles a real `us` keymap and a real `de` one, because only xkbcommon
can say `é` is unmappable on `us` and that `@` on `de` needs a
level-three mask.

And two integration tests asserted acquire's single warp, which is now
two. They are the whole-gesture trace and the bookmark-survives-a-
restart case, and both now assert the pair -- with the restored
position as the SECOND warp, since the bookmark is where the cursor is
left and the reverse order would restore every session a few pixels
off.

  nix develop -c python -m pytest tests -q
  905 passed in 65.91s

  nix build --no-link .#checks.x86_64-linux.unit
  903 passed, 2 skipped in 73.24s
  unit suite: 905 collected, 903 executed, 0 failed, 0 errored, 2 skipped

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

652 lines
25 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):
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")
rig.daemon.call("kill", id=first, grace_s=0)
assert rig.driver.dispatcher._pressed == {}
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_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"]