Everything below the CLI was merged and green against fakes; none of it was
reachable and none of it had ever met a compositor. This wires it up and then
puts the compositor in a position to disagree.
CLI (src/hhstream/cli.py, src/hhstream_session/**)
session container [ID], session reconcile [ID], and the seven pointer verbs
from PLAN §9. `start` still prints the bare session id and nothing else.
`list` gains WS / OUTPUT / POINTER, with the gap marker where a value is
genuinely unknown rather than a blank that reads as zero -- the POINTER
column needs a second, read-only `pointer.state` call because the `list`
reply carries no lease state.
The lease id is cached in `hhstream_session.lease` (under
$XDG_RUNTIME_DIR), because PLAN §9's gesture verbs take no --lease and the
wire requires a lease_id on every one of them; --lease and $HHSTREAM_LEASE
override it, and a `no_lease` refusal drops the stale entry.
Exit codes are the contract's: a gesture with no lease is 9 and never
reaches the broker, and a compositor failure is 10 with a message that says
the session is still running. `kill` now warns about
`session.container_survivors` -- windows the compositor still shows -- and
distinguishes `null` ("could not ask") from `[]`.
`shot`/`record --output NAME` capture one container through `grim -o`; the
frame socket publishes the main output only, so it cannot do it.
Module (nix/module.nix)
sessions.containers.{enable,max,mode,workspaceBase},
sessions.pointer.{enable,leaseTtl,leaseMax}, rendered into the generated
TOML with §10's key names. hhstream-pointer.service: the operator's account,
supplementary group hhstream, After=/BindsTo= the compositor,
Restart=on-failure, KillMode=process, and the command line §3.4 freezes.
tmpfiles for /run/hhstream plus RuntimeDirectoryPreserve on the broker,
without which restarting the broker deletes the driver's socket out from
under it. The runtime-directory length assertion is untouched.
And ExecStartPost on the compositor, opening its IPC directory to its own
group: Hyprland creates <runtime>/hypr with S_IRWXU, so the broker -- a
different account by design -- could not reach the request or event socket
at all, and degraded silently exactly as it is built to.
Checks (checks/**)
vm-ipc: both sockets at their frozen names, measured against sun_path's 108
bytes, and a socket2 subscriber that receives an openwindow for a window the
test creates. The subscriber is the shipped HyprlandIPC, not a second
implementation: this check exists to prove that this client hears this
compositor.
vm-containers: one hh-* output per session at the container mode, the window
on it, a second window of the same application beside it, an unmatched
window quarantined, grim -o isolating one container, teardown removing the
output and freeing the slot. PLAN experiment 3 is answered: `hyprctl output
create headless` works.
vm-pointer: a version-2 virtual pointer, a warp and a click whose
coordinates the *application* reports, BUSY naming the holder, an expired
lease swept with its held button lifted, and a broker restart that leaves
the lock free, the bookmark intact and the driver reachable.
checks/lib gains the guest the three share, their test-script helpers (no
assertions live there), an event-socket subscriber and a Wayland client that
says where it was clicked -- nothing in nixpkgs both honours
$HHSTREAM_APP_ID and reports pointer events.
Reported, not worked around: the broker reads none of the container or
pointer config (policy.py takes [defaults] and [apps] only), `start` has no
no_container field so --no-container is refused rather than silently ignored,
and nix/hyprland-conf.nix sets input:follow_mouse = 0, which sends pointer
events to the focused window only -- measured, with the cursor at the aimed
pixel and no client told. README.dev.md has the evidence for each.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WQy29x9AfHWyzNd1f7XPGK
315 lines
11 KiB
Python
315 lines
11 KiB
Python
"""The integration contract: ``register(subparsers)`` into someone else's CLI.
|
|
|
|
The registrant is assumed to know nothing about the daemon beyond the socket
|
|
path, so these tests drive the handlers through a host parser they build
|
|
themselves and stub out the transport.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import io
|
|
import json
|
|
from contextlib import redirect_stderr, redirect_stdout
|
|
|
|
import pytest
|
|
|
|
import hhstream_session
|
|
from hhstream_session import register
|
|
from hhstream_session.client import ClientError
|
|
from hhstreamd.protocol import ExitCode
|
|
|
|
|
|
@pytest.fixture
|
|
def host_cli():
|
|
"""A stand-in for the pre-existing ``hhstream`` CLI."""
|
|
|
|
parser = argparse.ArgumentParser(prog="hhstream")
|
|
sub = parser.add_subparsers(dest="command")
|
|
|
|
existing = sub.add_parser("frame", help="an existing subcommand")
|
|
existing.set_defaults(func=lambda args: 0)
|
|
|
|
register(sub)
|
|
return parser
|
|
|
|
|
|
@pytest.fixture
|
|
def sent(monkeypatch):
|
|
"""Capture what the handlers would send, and reply with what the test wants."""
|
|
|
|
class Transport(list):
|
|
"""The captured requests, plus the canned replies to hand back."""
|
|
|
|
replies = [
|
|
{
|
|
"ok": True,
|
|
"id": "stub-aaaaaa",
|
|
"session": {"id": "stub-aaaaaa", "state": "ready"},
|
|
"sessions": [],
|
|
"lines": [],
|
|
}
|
|
]
|
|
|
|
calls = Transport()
|
|
|
|
def fake_call(op, *, socket_path=None, timeout=None, **fields):
|
|
# Mirror protocol.request(): unset fields are not put on the wire, so
|
|
# the tests below can assert on what is actually sent.
|
|
wire = {k: v for k, v in fields.items() if v is not None}
|
|
calls.append({"op": op, "socket_path": socket_path, **wire})
|
|
return calls.replies[min(len(calls) - 1, len(calls.replies) - 1)]
|
|
|
|
monkeypatch.setattr(hhstream_session, "call", fake_call)
|
|
return calls
|
|
|
|
|
|
def run(parser: argparse.ArgumentParser, argv: list[str]) -> tuple[int, str, str]:
|
|
args = parser.parse_args(argv)
|
|
out, err = io.StringIO(), io.StringIO()
|
|
with redirect_stdout(out), redirect_stderr(err):
|
|
code = hhstream_session.dispatch(args)
|
|
return code, out.getvalue(), err.getvalue()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# registration
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_registration_adds_exactly_one_subcommand_and_leaves_the_host_alone(host_cli):
|
|
args = host_cli.parse_args(["frame"])
|
|
assert args.func(args) == 0 # the pre-existing subcommand still works
|
|
|
|
args = host_cli.parse_args(["session", "list"])
|
|
assert callable(args.func)
|
|
|
|
|
|
def test_the_handler_is_exposed_under_both_the_common_name_and_a_namespaced_one(host_cli):
|
|
args = host_cli.parse_args(["session", "status", "foo-aaaaaa"])
|
|
assert args.func is args.hhstream_session_handler
|
|
|
|
|
|
def test_every_v1_verb_is_registered(host_cli):
|
|
for verb in ["start", "list", "status", "touch", "kill", "gc", "adopt", "logs"]:
|
|
argv = ["session", verb]
|
|
if verb in ("status", "touch", "kill", "logs"):
|
|
argv.append("foo-aaaaaa")
|
|
if verb == "start":
|
|
argv.append("foot")
|
|
if verb == "adopt":
|
|
argv += ["--pid", "1234"]
|
|
args = host_cli.parse_args(argv)
|
|
assert callable(args.func), verb
|
|
|
|
|
|
def test_session_with_no_verb_lists(host_cli, sent):
|
|
code, _, _ = run(host_cli, ["session"])
|
|
assert code == ExitCode.OK
|
|
assert sent[0]["op"] == "list"
|
|
|
|
|
|
def test_the_socket_may_be_given_before_or_after_the_verb(host_cli, sent):
|
|
run(host_cli, ["session", "--socket", "/a.sock", "list"])
|
|
run(host_cli, ["session", "list", "--socket", "/b.sock"])
|
|
# Selected by op rather than by position: a human `list` also asks
|
|
# `pointer.state` for its POINTER column, so the requests interleave.
|
|
assert [c["socket_path"] for c in sent if c["op"] == "list"] == ["/a.sock", "/b.sock"]
|
|
# The second request of each run inherits the same socket, which is the
|
|
# thing that would break if it were resolved twice.
|
|
assert [c["socket_path"] for c in sent if c["op"] == "pointer.state"] == [
|
|
"/a.sock",
|
|
"/b.sock",
|
|
]
|
|
|
|
|
|
def test_the_socket_falls_back_to_the_environment(host_cli, sent, monkeypatch):
|
|
"""The registrant's only piece of daemon knowledge."""
|
|
|
|
monkeypatch.setenv("HHSTREAM_SOCKET", "/env.sock")
|
|
run(host_cli, ["session", "list"])
|
|
# The handler passes None through; the client resolves the default.
|
|
assert sent[0]["socket_path"] is None
|
|
from hhstream_session.client import default_socket_path
|
|
|
|
assert default_socket_path() == "/env.sock"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# request shapes
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_start_sends_the_app_and_an_argv_list_never_a_command_string(host_cli, sent):
|
|
run(host_cli, ["session", "start", "chromium", "--", "--new-window", "https://example.com"])
|
|
assert sent[0]["op"] == "start"
|
|
assert sent[0]["app"] == "chromium"
|
|
assert sent[0]["argv"] == ["--new-window", "https://example.com"]
|
|
|
|
|
|
def test_this_commands_own_flags_still_parse_after_the_app_name(host_cli, sent):
|
|
"""The separator divides the two argvs; it does not divide the parsers."""
|
|
|
|
run(host_cli, ["session", "start", "chromium", "--idle-timeout", "5m", "--", "--new-window"])
|
|
assert sent[0]["idle_timeout_s"] == 300.0
|
|
assert sent[0]["argv"] == ["--new-window"]
|
|
|
|
|
|
def test_an_application_flag_after_the_separator_is_never_read_as_ours(host_cli, sent):
|
|
run(host_cli, ["session", "start", "chromium", "--", "--idle-timeout", "5m"])
|
|
assert "idle_timeout_s" not in sent[0]
|
|
assert sent[0]["argv"] == ["--idle-timeout", "5m"]
|
|
|
|
|
|
def test_durations_are_parsed_on_the_way_in(host_cli, sent):
|
|
run(host_cli, ["session", "start", "foot", "--idle-timeout", "3h"])
|
|
assert sent[0]["idle_timeout_s"] == 10800.0
|
|
run(host_cli, ["session", "kill", "foo-aaaaaa", "--grace", "30s"])
|
|
assert sent[1]["grace_s"] == 30.0
|
|
|
|
|
|
def test_a_bad_duration_is_rejected_by_argparse(host_cli):
|
|
with pytest.raises(SystemExit):
|
|
host_cli.parse_args(["session", "start", "foot", "--idle-timeout", "soon"])
|
|
|
|
|
|
def test_home_and_ephemeral_home_are_mutually_exclusive(host_cli):
|
|
with pytest.raises(SystemExit):
|
|
host_cli.parse_args(["session", "start", "foot", "--home", "/x", "--ephemeral-home"])
|
|
|
|
|
|
def test_ephemeral_home_is_opt_in_and_absent_by_default(host_cli, sent):
|
|
run(host_cli, ["session", "start", "foot"])
|
|
assert "ephemeral_home" not in sent[0]
|
|
run(host_cli, ["session", "start", "foot", "--ephemeral-home"])
|
|
assert sent[1]["ephemeral_home"] is True
|
|
|
|
|
|
def test_list_all_is_only_sent_when_asked(host_cli, sent):
|
|
run(host_cli, ["session", "list"])
|
|
assert "all" not in sent[0]
|
|
run(host_cli, ["session", "list", "--all"])
|
|
lists = [c for c in sent if c["op"] == "list"]
|
|
assert lists[1]["all"] is True
|
|
|
|
|
|
def test_request_ids_are_forwarded_on_mutating_verbs(host_cli, sent):
|
|
run(host_cli, ["session", "start", "foot", "--request-id", "abc"])
|
|
assert sent[0]["request_id"] == "abc"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# output and exit codes
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_start_prints_the_bare_id_on_stdout_and_detail_on_stderr(host_cli, sent):
|
|
sent.replies[:] = [
|
|
{
|
|
"ok": True,
|
|
"id": "foot-k3f9qx",
|
|
"session": {
|
|
"id": "foot-k3f9qx",
|
|
"app": "foot",
|
|
"pid": 48812,
|
|
"pgid": 48812,
|
|
"sid": 48812,
|
|
"state": "ready",
|
|
"ready_signal": "spawned",
|
|
"idle_timeout_s": 10800,
|
|
},
|
|
}
|
|
]
|
|
code, out, err = run(host_cli, ["session", "start", "foot"])
|
|
assert code == ExitCode.OK
|
|
assert out == "foot-k3f9qx\n" # exactly the id, so $(...) works
|
|
assert "pid 48812" in err
|
|
assert "touch foot-k3f9qx" in err # the keepalive is named where it is needed
|
|
|
|
|
|
def test_start_json_puts_one_object_on_stdout_and_nothing_on_stderr(host_cli, sent):
|
|
sent.replies[:] = [{"ok": True, "id": "foot-k3f9qx", "session": {"id": "foot-k3f9qx"}}]
|
|
code, out, err = run(host_cli, ["session", "start", "--json", "foot"])
|
|
assert code == ExitCode.OK
|
|
assert json.loads(out) == {"id": "foot-k3f9qx"}
|
|
assert err == ""
|
|
|
|
|
|
def test_json_is_available_on_every_read_verb(host_cli, sent):
|
|
sent.replies[:] = [{"ok": True, "sessions": []}]
|
|
code, out, _ = run(host_cli, ["session", "list", "--json"])
|
|
assert json.loads(out)["ok"] is True
|
|
|
|
sent.replies[:] = [{"ok": True, "session": {"id": "a"}, "id": "a"}]
|
|
code, out, _ = run(host_cli, ["session", "status", "--json", "a"])
|
|
assert json.loads(out)["session"] == {"id": "a"}
|
|
|
|
sent.replies[:] = [{"ok": True, "lines": ["hello"], "offset": 6, "eof": True}]
|
|
code, out, _ = run(host_cli, ["session", "logs", "--json", "a"])
|
|
assert json.loads(out)["lines"] == ["hello"]
|
|
|
|
|
|
def test_errors_go_to_stderr_with_the_machine_field_in_json_mode(host_cli, sent):
|
|
sent.replies[:] = [
|
|
{"ok": False, "error": "not_allowlisted", "reason": "app 'sh' is not in the allowlist"}
|
|
]
|
|
code, out, err = run(host_cli, ["session", "start", "--json", "sh"])
|
|
assert code == ExitCode.POLICY
|
|
assert out == ""
|
|
assert json.loads(err)["error"] == "not_allowlisted"
|
|
|
|
|
|
def test_errors_are_human_readable_without_json(host_cli, sent):
|
|
sent.replies[:] = [
|
|
{"ok": False, "error": "no_such_session", "reason": "no session 'x'", "hint": "try list"}
|
|
]
|
|
code, out, err = run(host_cli, ["session", "status", "x"])
|
|
assert code == ExitCode.NO_SUCH_SESSION
|
|
assert "no session 'x'" in err and "try list" in err
|
|
|
|
|
|
def test_a_transport_failure_becomes_exit_five_not_a_traceback(host_cli, monkeypatch):
|
|
def boom(*args, **kwargs):
|
|
raise ClientError("daemon_unreachable", "nothing is listening", hint="start it")
|
|
|
|
monkeypatch.setattr(hhstream_session, "call", boom)
|
|
code, _, err = run(host_cli, ["session", "list"])
|
|
assert code == ExitCode.DAEMON_UNREACHABLE
|
|
assert "nothing is listening" in err and "start it" in err
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# the activity contract, as documented to the user
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_the_help_text_says_touch_is_the_only_mark_of_activity(host_cli):
|
|
out = io.StringIO()
|
|
with redirect_stdout(out):
|
|
with pytest.raises(SystemExit):
|
|
host_cli.parse_args(["session", "--help"])
|
|
text = out.getvalue()
|
|
assert "touch" in text
|
|
assert "ONLY" in text
|
|
for verb in ["list", "status", "logs", "gc"]:
|
|
assert verb in text
|
|
|
|
|
|
@pytest.mark.parametrize("verb", ["list", "status", "logs", "gc"])
|
|
def test_each_read_verbs_help_says_it_does_not_count(host_cli, verb):
|
|
out = io.StringIO()
|
|
with redirect_stdout(out):
|
|
with pytest.raises(SystemExit):
|
|
host_cli.parse_args(["session", "--help"])
|
|
line = [l for l in out.getvalue().splitlines() if l.strip().startswith(verb)]
|
|
assert line, verb
|
|
assert "does NOT count" in " ".join(out.getvalue().split())
|
|
|
|
|
|
def test_touchs_help_calls_itself_the_only_mark_of_activity(host_cli):
|
|
out = io.StringIO()
|
|
with redirect_stdout(out):
|
|
with pytest.raises(SystemExit):
|
|
host_cli.parse_args(["session", "touch", "--help"])
|
|
assert "only verb that counts as activity" in " ".join(out.getvalue().split())
|