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

766 lines
27 KiB
Python

"""The CLI surface added in this milestone: containers, and the pointer lease.
Same shape as ``test_cli_registration.py`` — a host parser the test builds
itself and a stubbed transport — because the point is the same: what the
handlers put on the wire, what they print, and what they exit with. Nothing
here needs a daemon, so nothing here starts one.
The lease cache is pointed at a temporary directory for every test. It is real
(the same code the CLI runs), because "acquire remembers the lease so move
needs no flag" is the whole reason it exists and a stub would prove nothing.
"""
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 format as fmt
from hhstream_session import lease, register
from hhstream_session.client import ClientError
from hhstreamd.protocol import ExitCode
@pytest.fixture(autouse=True)
def lease_cache(tmp_path, monkeypatch):
"""Every test gets its own cache, and none of them touch the real one."""
monkeypatch.setenv(lease.ENV_LEASE_DIR, str(tmp_path / "leases"))
monkeypatch.delenv(lease.ENV_LEASE, raising=False)
return tmp_path / "leases"
@pytest.fixture
def host_cli():
parser = argparse.ArgumentParser(prog="hhstream")
sub = parser.add_subparsers(dest="command")
register(sub)
return parser
@pytest.fixture
def sent(monkeypatch):
"""Captured requests, plus per-op canned replies.
Keyed by op rather than by call order, because a human ``list`` now makes
two requests and a test that counted positions would be asserting about
the order of calls rather than about the verb.
"""
class Transport(list):
replies: dict[str, dict] = {}
def of(self, op: str) -> list[dict]:
return [call for call in self if call["op"] == op]
calls = Transport()
calls.replies = {}
def fake_call(op, *, socket_path=None, timeout=None, **fields):
wire = {k: v for k, v in fields.items() if v is not None}
calls.append({"op": op, "socket_path": socket_path, **wire})
reply = calls.replies.get(op)
if isinstance(reply, ClientError):
raise reply
return reply if reply is not None else {"ok": True}
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_every_verb_the_contract_names_is_registered(host_cli):
"""PLAN §9's surface, verb by verb, as a caller would type it."""
surface = [
["session", "container", "foo-aaaaaa"],
["session", "container"],
["session", "reconcile"],
["session", "reconcile", "foo-aaaaaa"],
["session", "pointer", "acquire", "foo-aaaaaa"],
["session", "pointer", "acquire", "foo-aaaaaa", "--ttl", "10s", "--no-restore"],
["session", "pointer", "move", "foo-aaaaaa", "--to", "0.5,0.5"],
["session", "pointer", "move", "foo-aaaaaa", "--by", "-0.1,0.2"],
["session", "pointer", "click", "foo-aaaaaa"],
["session", "pointer", "click", "foo-aaaaaa", "--button", "right"],
["session", "pointer", "down", "foo-aaaaaa", "--button", "middle"],
["session", "pointer", "up", "foo-aaaaaa"],
["session", "pointer", "release", "foo-aaaaaa"],
["session", "pointer", "state"],
["session", "pointer", "state", "--json"],
["session", "keyboard", "type", "foo-aaaaaa", "hello"],
["session", "keyboard", "type", "foo-aaaaaa", "hello", "--lease", "abc"],
["session", "keyboard", "key", "foo-aaaaaa", "Return"],
["session", "keyboard", "down", "foo-aaaaaa", "Control_L"],
["session", "keyboard", "up", "foo-aaaaaa", "Control_L"],
]
for argv in surface:
args = host_cli.parse_args(argv)
assert callable(args.func), argv
def test_the_keyboard_help_says_the_pointer_lease_is_required(host_cli, capsys):
"""Exit 9 until `pointer acquire` is the one fact an agent gets wrong here.
Asserted on the `keyboard` group's own help and on a leaf's, because
`--help` on a leaf is what an agent actually reads -- and the group help is
what a human skims.
"""
for argv in (["session", "keyboard", "--help"], ["session", "keyboard", "type", "--help"]):
with pytest.raises(SystemExit):
host_cli.parse_args(argv)
out = capsys.readouterr().out
assert "pointer acquire" in out
assert "9" in out, "the exit code an agent has to branch on"
def test_the_keyboard_help_warns_that_a_held_key_floods(host_cli, capsys):
"""Unconditionally, and not because a probe saw repeats on the wire.
It did not: the compositor sends one event and the application repeats, so
the flood is real and is not ours to rate-limit.
"""
with pytest.raises(SystemExit):
host_cli.parse_args(["session", "keyboard", "down", "--help"])
out = capsys.readouterr().out.lower()
assert "flood" in out
def test_the_pointer_help_does_not_grow_a_keyboard_tutorial(host_cli, capsys):
"""`pointer --help` stays about the cursor.
Narrow on purpose: `acquire`'s *stderr* had to start mentioning keyboard
verbs (they refresh the lease), so a test that grepped the whole binary's
help for the word would pass for the wrong reason. This reads the pointer
group's description only.
"""
with pytest.raises(SystemExit):
host_cli.parse_args(["session", "pointer", "--help"])
out = capsys.readouterr().out
assert "keysym" not in out
assert "keyboard type" not in out
def test_type_takes_its_text_as_one_argument_and_does_not_interpret_it(host_cli):
r"""A newline is a newline; a backslash-n is a backslash and an n.
Interpreting escapes here would make a literal backslash-n untypeable,
and the shell has already done the quoting.
"""
# A real newline survives as a real newline.
args = host_cli.parse_args(["session", "keyboard", "type", "foo-aaaaaa", "a\nb"])
assert args.text == "a\nb"
assert len(args.text) == 3
# And a backslash followed by an n stays two characters: interpreting it
# would make a literal backslash-n untypeable.
args = host_cli.parse_args(["session", "keyboard", "type", "foo-aaaaaa", r"a\nb"])
assert args.text == r"a\nb"
assert len(args.text) == 4
assert "\n" not in args.text
def test_a_move_needs_exactly_one_target(host_cli):
with pytest.raises(SystemExit):
host_cli.parse_args(["session", "pointer", "move", "x"])
with pytest.raises(SystemExit):
host_cli.parse_args(
["session", "pointer", "move", "x", "--to", "0,0", "--by", "0,0"]
)
@pytest.mark.parametrize("bad", ["0.5", "0.5,", "a,b", "0.5,0.5,0.5", ""])
def test_a_malformed_coordinate_pair_is_a_usage_error(host_cli, bad):
"""Rejected by argparse, so nothing reaches the broker and exit 2 is exit 2."""
with pytest.raises(SystemExit):
host_cli.parse_args(["session", "pointer", "move", "x", "--to", bad])
def test_an_unknown_button_is_refused_before_the_wire(host_cli):
with pytest.raises(SystemExit):
host_cli.parse_args(["session", "pointer", "click", "x", "--button", "pinky"])
# ---------------------------------------------------------------------------
# containers
# ---------------------------------------------------------------------------
def test_container_with_no_id_lists_every_container_and_the_orphans(host_cli, sent):
sent.replies["container.list"] = {
"ok": True,
"containers": [
{
"id": "foot-aaaaaa",
"app": "foot",
"output": "hh-foot-aaaaaa",
"workspace": 1000,
"mode": {"width": 1280, "height": 720},
"state": "owned",
"window": "0x55f",
}
],
"orphans": ["hh-gone-bbbbbb"],
"compositor": "ok",
"error": None,
"workspaces_in_use": [1000],
}
code, out, _ = run(host_cli, ["session", "container"])
assert code == ExitCode.OK
assert sent.of("container.list") and not sent.of("container.reconcile")
assert "hh-foot-aaaaaa" in out and "1280x720" in out
assert "hh-gone-bbbbbb" in out and "orphans" in out
def test_orphans_that_could_not_be_read_are_not_reported_as_none(host_cli, sent):
"""`null` orphans is "I could not look", which is not "nothing is there"."""
sent.replies["container.list"] = {
"ok": True,
"containers": [],
"orphans": None,
"compositor": "absent",
"error": "no compositor IPC",
"workspaces_in_use": [],
}
code, out, _ = run(host_cli, ["session", "container"])
assert code == ExitCode.OK
assert "could not be asked" in out
assert "none" not in out.split("orphans:")[1]
assert "no compositor IPC" in out
def test_container_with_an_id_reconciles_so_the_answer_is_current(host_cli, sent):
sent.replies["container.reconcile"] = {
"ok": True,
"id": "foot-aaaaaa",
"container": {
"output": "hh-foot-aaaaaa",
"workspace": 1000,
"mode": {"width": 1280, "height": 720},
"created_by": "broker",
"state": "owned",
},
"diff": [
{
"id": "foot-aaaaaa",
"field": "workspace",
"recorded": None,
"observed": 1000,
}
],
}
code, out, _ = run(host_cli, ["session", "container", "foot-aaaaaa"])
assert code == ExitCode.OK
assert sent.of("container.reconcile")[0]["id"] == "foot-aaaaaa"
assert "hh-foot-aaaaaa" in out
# Both values, so a reader can see which way the record moved.
assert "recorded None" in out and "compositor says 1000" in out
def test_reconcile_with_no_drift_says_so_rather_than_printing_nothing(host_cli, sent):
sent.replies["container.reconcile"] = {
"ok": True,
"container": None,
"diff": [],
"scan": {
"available": True,
"signature": "abc123",
"quarantine": "special:quarantine",
"adopted": [],
"removed": ["hh-stale-cccccc"],
"orphaned": [],
"failed": [],
},
}
code, out, _ = run(host_cli, ["session", "reconcile"])
assert code == ExitCode.OK
assert "id" not in sent.of("container.reconcile")[0]
assert "matches the compositor" in out
assert "hh-stale-cccccc" in out and "removed" in out
assert "abc123" in out
# ---------------------------------------------------------------------------
# the lease, across two invocations
# ---------------------------------------------------------------------------
def _acquired(lease_id: str = "lease-1") -> dict:
return {
"ok": True,
"id": "foot-aaaaaa",
"lease_id": lease_id,
"bookmark": {
"x": 0.5,
"y": 0.5,
"output": "hh-foot-aaaaaa",
"at": "2026-10-03T00:00:00Z",
},
"expires_in_s": 30.0,
}
def test_acquire_prints_the_bare_lease_id_on_stdout_and_detail_on_stderr(host_cli, sent):
"""Same contract as `start`: stdout is the one token a caller passes back."""
sent.replies["pointer.acquire"] = _acquired()
code, out, err = run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
assert code == ExitCode.OK
assert out == "lease-1\n"
assert "hh-foot-aaaaaa" in err
assert "release foot-aaaaaa" in err
def test_acquire_sends_ttl_and_restore_only_when_asked(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
first = sent.of("pointer.acquire")[0]
assert "ttl_s" not in first and "restore" not in first
run(
host_cli,
["session", "pointer", "acquire", "foot-aaaaaa", "--ttl", "2m", "--no-restore"],
)
second = sent.of("pointer.acquire")[1]
assert second["ttl_s"] == 120.0
assert second["restore"] is False
def test_a_gesture_reuses_the_lease_acquire_cached(host_cli, sent):
"""The contract's surface has no --lease, so something has to remember it."""
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.move"] = {
"ok": True,
"id": "foot-aaaaaa",
"bookmark": {
"x": 0.25,
"y": 0.75,
"output": "hh-foot-aaaaaa",
"at": "2026-10-03T00:00:01Z",
},
}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
code, out, _ = run(
host_cli, ["session", "pointer", "move", "foot-aaaaaa", "--to", "0.25,0.75"]
)
assert code == ExitCode.OK
move = sent.of("pointer.move")[0]
assert move["lease_id"] == "lease-1"
assert (move["x"], move["y"]) == (0.25, 0.75)
assert "0.2500,0.7500" in out
def test_a_relative_move_sends_dx_dy_and_never_x_y(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
run(host_cli, ["session", "pointer", "move", "foot-aaaaaa", "--by", "-0.1,0.2"])
move = sent.of("pointer.move")[0]
assert (move["dx"], move["dy"]) == (-0.1, 0.2)
assert "x" not in move and "y" not in move
def test_an_explicit_lease_beats_the_cache(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
run(
host_cli,
["session", "pointer", "click", "foot-aaaaaa", "--lease", "from-the-caller"],
)
assert sent.of("pointer.click")[0]["lease_id"] == "from-the-caller"
def test_the_environment_beats_the_cache_too(host_cli, sent, monkeypatch):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
monkeypatch.setenv(lease.ENV_LEASE, "from-the-environment")
run(host_cli, ["session", "pointer", "click", "foot-aaaaaa"])
assert sent.of("pointer.click")[0]["lease_id"] == "from-the-environment"
def test_a_lease_cached_for_another_broker_is_not_a_lease_here(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "--socket", "/a.sock", "pointer", "acquire", "foot-aaaaaa"])
code, _, err = run(
host_cli, ["session", "--socket", "/b.sock", "pointer", "click", "foot-aaaaaa"]
)
assert code == ExitCode.NO_LEASE
assert not sent.of("pointer.click")
assert "no pointer lease" in err
def test_a_gesture_with_no_lease_is_nine_and_never_reaches_the_broker(host_cli, sent):
"""Exit 9, not 2: the command line is fine, the lease is what is missing."""
for argv in (
["session", "pointer", "move", "foot-aaaaaa", "--to", "0.5,0.5"],
["session", "pointer", "click", "foot-aaaaaa"],
["session", "pointer", "down", "foot-aaaaaa"],
["session", "pointer", "up", "foot-aaaaaa"],
["session", "pointer", "release", "foot-aaaaaa"],
):
code, out, err = run(host_cli, argv)
assert code == ExitCode.NO_LEASE, argv
assert "acquire" in err
assert sent == []
def test_a_no_lease_refusal_drops_the_stale_cache_entry(host_cli, sent):
"""Otherwise every later verb fails the same way and `acquire` looks pointless."""
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.move"] = {
"ok": False,
"error": "no_lease",
"reason": "foot-aaaaaa does not hold the pointer: lease expired",
"holder": None,
}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
code, _, err = run(
host_cli, ["session", "pointer", "move", "foot-aaaaaa", "--to", "0.5,0.5"]
)
assert code == ExitCode.NO_LEASE
assert "exit 9" in err
assert lease.recall("foot-aaaaaa", socket=None) is None
def test_release_gives_the_lease_back_and_forgets_it(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.release"] = {
"ok": True,
"id": "foot-aaaaaa",
"bookmark": {
"x": 0.5,
"y": 0.5,
"output": "hh-foot-aaaaaa",
"at": "2026-10-03T00:00:02Z",
},
"released_by": "lease",
"released_at": "2026-10-03T00:00:02Z",
"buttons_lifted": ["left"],
}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
code, out, _ = run(host_cli, ["session", "pointer", "release", "foot-aaaaaa"])
assert code == ExitCode.OK
# The loud part: a button that was down came back up.
assert "lifted left" in out
assert lease.recall("foot-aaaaaa", socket=None) is None
def test_a_held_button_is_reported_with_everything_still_down(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.button"] = {
"ok": True,
"id": "foot-aaaaaa",
"buttons": ["left"],
}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
code, out, _ = run(host_cli, ["session", "pointer", "down", "foot-aaaaaa"])
assert code == ExitCode.OK
request = sent.of("pointer.button")[0]
assert request["button"] == "left" and request["state"] == "down"
assert "held: left" in out
def test_up_sends_the_other_state_through_the_same_verb(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.button"] = {"ok": True, "id": "foot-aaaaaa", "buttons": []}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
run(host_cli, ["session", "pointer", "up", "foot-aaaaaa", "--button", "right"])
request = sent.of("pointer.button")[0]
assert (request["button"], request["state"]) == ("right", "up")
def test_pointer_state_needs_no_lease_and_no_session(host_cli, sent):
sent.replies["pointer.state"] = {
"ok": True,
"holder": "foot-aaaaaa",
"since": 123.0,
"lease_id": "lease-1",
"expires_at": 153.0,
"buttons": ["left"],
"bookmark": None,
"driver": "/run/hhstream/pointer.sock",
}
code, out, _ = run(host_cli, ["session", "pointer", "state"])
assert code == ExitCode.OK
assert "foot-aaaaaa" in out and "left" in out
def test_a_busy_pointer_exits_eight_naming_the_holder(host_cli, sent):
sent.replies["pointer.acquire"] = {
"ok": False,
"error": "pointer_busy",
"reason": "the pointer is held by chromium-bbbbbb",
"holder": "chromium-bbbbbb",
}
code, out, err = run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
assert code == ExitCode.BUSY
assert out == ""
assert "chromium-bbbbbb" in err
# Nothing was cached: there is no lease to remember.
assert lease.recall("foot-aaaaaa", socket=None) is None
def test_a_compositor_failure_says_the_session_is_still_running(host_cli, sent):
"""Exit 10 is not exit 4, and the message has to carry that difference."""
sent.replies["pointer.acquire"] = {
"ok": False,
"error": "no_container",
"reason": "session foot-aaaaaa has no container output to aim at",
"hint": "the compositor was unreachable when this session started",
}
code, _, err = run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
assert code == ExitCode.COMPOSITOR
assert "compositor error" in err
assert "the session itself is unaffected" in err
def test_json_mode_puts_the_protocol_object_on_stdout(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
code, out, err = run(
host_cli, ["session", "pointer", "acquire", "--json", "foot-aaaaaa"]
)
assert code == ExitCode.OK
assert json.loads(out)["lease_id"] == "lease-1"
assert err == ""
# Still cached: --json changes the rendering, not the behaviour.
assert lease.recall("foot-aaaaaa", socket=None) == "lease-1"
# ---------------------------------------------------------------------------
# list: the three new columns
# ---------------------------------------------------------------------------
def _listed(**overrides) -> dict:
session = {
"id": "foot-aaaaaa",
"app": "foot",
"state": "ready",
"pid": 4242,
"live": True,
"idle_s": 12.0,
"expires_in_s": 600.0,
"workspace": 1000,
"container": {"output": "hh-foot-aaaaaa", "workspace": 1000, "state": "owned"},
}
session.update(overrides)
return {"ok": True, "sessions": [session]}
def test_list_gains_the_workspace_output_and_pointer_columns(host_cli, sent):
sent.replies["list"] = _listed()
sent.replies["pointer.state"] = {"ok": True, "holder": None}
code, out, _ = run(host_cli, ["session", "list"])
assert code == ExitCode.OK
header = out.splitlines()[0].split()
assert header[:9] == [
"ID",
"APP",
"STATE",
"PID",
"WS",
"OUTPUT",
"POINTER",
"IDLE",
"EXPIRES",
]
row = out.splitlines()[1].split()
# PID stays in column four: callers (and vm-sessions) already read it there.
assert row[3] == "4242"
assert row[4] == "1000" and row[5] == "hh-foot-aaaaaa" and row[6] == "free"
def test_the_row_that_holds_the_cursor_says_held_and_the_others_say_who(host_cli, sent):
sent.replies["list"] = {
"ok": True,
"sessions": _listed()["sessions"]
+ [
{
"id": "chromium-bbbbbb",
"app": "chromium",
"state": "ready",
"pid": 4343,
"live": True,
"idle_s": 3.0,
"expires_in_s": 600.0,
"workspace": 1001,
"container": {"output": "hh-chromium-bbbbbb"},
}
],
}
sent.replies["pointer.state"] = {"ok": True, "holder": "foot-aaaaaa"}
code, out, _ = run(host_cli, ["session", "list"])
assert code == ExitCode.OK
rows = {line.split()[0]: line.split() for line in out.splitlines()[1:]}
assert rows["foot-aaaaaa"][6] == "held"
assert rows["chromium-bbbbbb"][6] == "held:foot-aaaaaa"
def test_a_degraded_session_shows_the_gap_marker_not_a_blank(host_cli, sent):
"""A blank reads as zero, or as "no". Neither is what `null` means."""
sent.replies["list"] = _listed(
workspace=None,
container={"output": None, "workspace": None, "state": "degraded"},
)
sent.replies["pointer.state"] = {"ok": True, "holder": None}
code, out, _ = run(host_cli, ["session", "list"])
row = out.splitlines()[1].split()
assert row[4] == fmt.DASH and row[5] == fmt.DASH
def test_an_unreachable_pointer_state_leaves_the_column_unknown_not_free(host_cli, sent):
"""The sessions were listed; only the lease could not be read."""
sent.replies["list"] = _listed()
sent.replies["pointer.state"] = ClientError("daemon_unreachable", "socket went away")
code, out, _ = run(host_cli, ["session", "list"])
assert code == ExitCode.OK
assert out.splitlines()[1].split()[6] == fmt.DASH
def test_json_list_makes_no_second_request_and_is_the_protocol_object(host_cli, sent):
sent.replies["list"] = _listed()
code, out, _ = run(host_cli, ["session", "list", "--json"])
assert code == ExitCode.OK
assert not sent.of("pointer.state")
assert json.loads(out)["sessions"][0]["id"] == "foot-aaaaaa"
def test_a_failed_list_does_not_go_on_to_ask_about_the_pointer(host_cli, sent):
sent.replies["list"] = {"ok": False, "error": "bad_request", "reason": "nope"}
code, _, err = run(host_cli, ["session", "list"])
assert code == ExitCode.USAGE
assert not sent.of("pointer.state")
assert "nope" in err
# ---------------------------------------------------------------------------
# teardown: the survivors the CLI used to be silent about
# ---------------------------------------------------------------------------
def test_kill_warns_about_windows_that_survived_the_teardown(host_cli, sent):
sent.replies["kill"] = {
"ok": True,
"id": "foot-aaaaaa",
"session": {
"id": "foot-aaaaaa",
"state": "killed",
"signal_sent": "TERM",
"pgid": 4242,
"survivors": [],
"container_removed": True,
"container_survivors": [
{
"address": "0x55f",
"pid": 4243,
"class": "hh-foot-aaaaaa",
"initial_class": "hh-foot-aaaaaa",
"workspace": 1000,
}
],
},
}
code, out, _ = run(host_cli, ["session", "kill", "foot-aaaaaa"])
assert code == ExitCode.OK
assert "WARNING" in out
assert "still shows 1 window" in out
assert "0x55f" in out
def test_kill_says_when_the_compositor_could_not_be_asked_about_survivors(host_cli, sent):
"""`null` is "I could not check", which must not print as "nothing survived"."""
sent.replies["kill"] = {
"ok": True,
"session": {
"id": "foot-aaaaaa",
"state": "killed",
"survivors": [],
"container_removed": False,
"container_survivors": None,
"container_error": "no compositor IPC",
},
}
code, out, _ = run(host_cli, ["session", "kill", "foot-aaaaaa"])
assert code == ExitCode.OK
assert "could not be asked" in out
assert "no compositor IPC" in out
def test_a_clean_teardown_says_the_container_went_away(host_cli, sent):
sent.replies["kill"] = {
"ok": True,
"session": {
"id": "foot-aaaaaa",
"state": "killed",
"survivors": [],
"container_removed": True,
"container_survivors": [],
},
}
code, out, _ = run(host_cli, ["session", "kill", "foot-aaaaaa"])
assert code == ExitCode.OK
assert "container removed" in out
assert "WARNING" not in out
# ---------------------------------------------------------------------------
# the gap this slice could not close
# ---------------------------------------------------------------------------
def test_no_container_is_refused_rather_than_sent_and_ignored(host_cli, sent):
"""The broker's `start` has no such field, so sending it would be a lie.
PLAN §9 lists the flag; CONTRACT-sessions.md §4 leaves `start` unchanged and
`SessionManager.start` takes no `no_container`. A request carrying it would
be accepted, ignored, and the session would get a container anyway — so the
CLI refuses and says which document disagrees with which.
"""
code, out, err = run(host_cli, ["session", "start", "foot", "--no-container"])
assert code == ExitCode.USAGE
assert sent == []
assert "not implemented" in err
assert out == ""
def test_start_without_the_flag_is_untouched(host_cli, sent):
sent.replies["start"] = {
"ok": True,
"id": "foot-aaaaaa",
"session": {"id": "foot-aaaaaa", "app": "foot", "pid": 1, "state": "ready"},
}
code, out, _ = run(host_cli, ["session", "start", "foot"])
assert code == ExitCode.OK
assert out == "foot-aaaaaa\n"
assert "no_container" not in sent.of("start")[0]