The four slices existed and nothing called them. Now the broker builds a
spatial container per session, reads back what the compositor actually did,
and aims the cursor into one container under a broker-wide lease.
Record schema 3 (registry.py): `container` {output, workspace, mode,
created_by, state}, `pointer` {bookmark, last_released_at, released_by} and
the compositor's `signature`. A v2 record is migrated on load, not refused —
its application is still running. Every field that could not be verified is
null; `container: null` means "no container", never "probably something".
Containers (new container_host.py, manager.py, launcher.py): `start`
allocates a slot from `WorkspaceAllocator`, runs `container_plan()`'s argv,
launches the app with the container stamp in its environment, then reads the
workspace, output and window back out of `clients -j`. Teardown removes the
output, releases the slot and reports survivors rather than claiming success
— and runs for an unprompted exit and for `gc` too, so no container is ever
left unattended. Broker start-up reconciles: adopt `hh-*` outputs a live
session claims, remove the rest, `contains_output()` being the only filter.
No IPC means `container: degraded` and lifecycle verbs unchanged.
The plans' argv are dispatched over the compositor's request socket rather
than by executing `hyprctl`, which is what hyprctl does with the same words;
the reply is checked, so a refused command is not recorded as a container.
Pointer (new driver.py, manager.py): a client for the driver's private
socket, and `pointer.acquire|move|button|click|release|state` on top of
`PointerLease`. The broker owns the lease, the driver executes. The bookmark
is marked on every move and before release and stored in the record, so it
survives a restart. On expiry `pressed()` is read before `expire()` and
`release_all` goes to the driver, because the lease cannot lift a button
itself; a sweep runs unprompted so the TTL is a promise.
containers.py to v2: `quarantine_plan()` -> `quarantine_argv()`, with the
before-any-per-session-rule ordering stated where the caller could get it
wrong. protocol.py: 9 NO_LEASE, 10 COMPOSITOR, the verb table, and the
`request_id` cache moved out of the server so the CLI agrees with it.
Tests: real AF_UNIX everywhere — a stateful fake compositor and the shipped
pointer driver behind a recording sink. No mocked sockets, no compositor, no
VM. 551 -> 693.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017mUq7QvQ9EZb2Wi35xj4cs
197 lines
6.4 KiB
Python
197 lines
6.4 KiB
Python
"""Protocol framing tests (DESIGN.md §3.4)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import pytest
|
|
|
|
from hhstreamd import protocol
|
|
from hhstreamd.protocol import MAX_LINE_BYTES, PROTOCOL_VERSION, ProtocolError
|
|
|
|
|
|
def test_a_message_is_exactly_one_newline_terminated_line():
|
|
frame = protocol.encode({"ok": True, "id": "foot-aaaaaa"})
|
|
assert frame.endswith(b"\n")
|
|
assert frame.count(b"\n") == 1
|
|
assert json.loads(frame) == {"ok": True, "id": "foot-aaaaaa"}
|
|
|
|
|
|
def test_round_trip():
|
|
message = {"v": 1, "op": "start", "app": "foot", "argv": ["--a", "--b"]}
|
|
assert protocol.decode(protocol.encode(message)) == message
|
|
|
|
|
|
def test_embedded_newlines_cannot_break_the_framing():
|
|
"""A session id or an argv element must never be able to split a frame."""
|
|
|
|
message = {"ok": False, "reason": "line one\nline two\r\nline three"}
|
|
frame = protocol.encode(message)
|
|
assert frame.count(b"\n") == 1
|
|
assert protocol.decode(frame) == message
|
|
|
|
|
|
def test_non_ascii_is_escaped_so_the_frame_stays_ascii():
|
|
frame = protocol.encode({"reason": "café — ✓"})
|
|
frame.decode("ascii") # must not raise
|
|
assert protocol.decode(frame)["reason"] == "café — ✓"
|
|
|
|
|
|
def test_decode_tolerates_a_missing_trailing_newline():
|
|
assert protocol.decode(b'{"ok":true}') == {"ok": True}
|
|
|
|
|
|
@pytest.mark.parametrize("line", [b"", b"\n", b" \n"])
|
|
def test_an_empty_frame_is_a_bad_request(line):
|
|
with pytest.raises(ProtocolError) as exc:
|
|
protocol.decode(line)
|
|
assert exc.value.error == "bad_request"
|
|
|
|
|
|
def test_malformed_json_is_a_bad_request():
|
|
with pytest.raises(ProtocolError) as exc:
|
|
protocol.decode(b"{not json\n")
|
|
assert exc.value.error == "bad_request"
|
|
assert "malformed JSON" in exc.value.reason
|
|
|
|
|
|
@pytest.mark.parametrize("payload", [b"[1,2,3]", b'"a string"', b"42", b"null"])
|
|
def test_a_frame_that_is_not_an_object_is_rejected(payload):
|
|
with pytest.raises(ProtocolError) as exc:
|
|
protocol.decode(payload)
|
|
assert exc.value.error == "bad_request"
|
|
|
|
|
|
def test_an_oversized_frame_is_refused_on_both_sides():
|
|
with pytest.raises(ProtocolError) as exc:
|
|
protocol.decode(b"x" * (MAX_LINE_BYTES + 1))
|
|
assert exc.value.error == "message_too_large"
|
|
|
|
with pytest.raises(ProtocolError) as exc:
|
|
protocol.encode({"argv": ["x" * MAX_LINE_BYTES]})
|
|
assert exc.value.error == "message_too_large"
|
|
|
|
|
|
def test_decode_request_requires_an_op():
|
|
with pytest.raises(ProtocolError) as exc:
|
|
protocol.decode_request(b'{"v":1}')
|
|
assert exc.value.error == "bad_request"
|
|
assert "no 'op'" in exc.value.reason
|
|
|
|
|
|
def test_decode_request_rejects_an_unknown_protocol_version():
|
|
with pytest.raises(ProtocolError) as exc:
|
|
protocol.decode_request(b'{"v":99,"op":"list"}')
|
|
assert exc.value.error == "unsupported_version"
|
|
|
|
|
|
def test_a_request_without_a_version_is_assumed_to_be_current():
|
|
assert protocol.decode_request(b'{"op":"list"}')["op"] == "list"
|
|
|
|
|
|
def test_request_attaches_the_version_and_drops_unset_fields():
|
|
message = protocol.request("start", app="foot", argv=None, idle_timeout_s=30.0)
|
|
assert message == {"v": PROTOCOL_VERSION, "op": "start", "app": "foot", "idle_timeout_s": 30.0}
|
|
|
|
|
|
def test_error_replies_carry_both_a_machine_field_and_a_human_field():
|
|
reply = protocol.error(
|
|
"not_allowlisted", "app 'sh' is not in the allowlist", hint="see the config"
|
|
)
|
|
assert reply == {
|
|
"ok": False,
|
|
"error": "not_allowlisted",
|
|
"reason": "app 'sh' is not in the allowlist",
|
|
"hint": "see the config",
|
|
}
|
|
|
|
|
|
def test_ok_replies_are_flagged():
|
|
assert protocol.ok(id="a")["ok"] is True
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# `request_id` idempotency (PLAN §8)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_a_repeated_mutating_request_returns_the_recorded_answer():
|
|
cache = protocol.IdempotencyCache()
|
|
cache.remember("start", "r1", {"ok": True, "id": "foot-aaaaaa"})
|
|
|
|
replay = cache.lookup("start", "r1")
|
|
|
|
assert replay == {"ok": True, "id": "foot-aaaaaa", "deduplicated": True}
|
|
|
|
|
|
def test_a_recorded_failure_is_replayed_as_the_failure_it_was():
|
|
"""A retried `start` that policy refused must not get a second attempt."""
|
|
|
|
cache = protocol.IdempotencyCache()
|
|
cache.remember("start", "r1", {"ok": False, "error": "not_allowlisted"})
|
|
|
|
assert cache.lookup("start", "r1")["error"] == "not_allowlisted"
|
|
|
|
|
|
def test_read_verbs_are_never_cached_because_a_stale_list_is_worse():
|
|
cache = protocol.IdempotencyCache()
|
|
cache.remember("list", "r1", {"ok": True, "sessions": []})
|
|
|
|
assert cache.lookup("list", "r1") is None
|
|
|
|
|
|
def test_a_request_with_no_id_is_never_matched_against_another():
|
|
cache = protocol.IdempotencyCache()
|
|
cache.remember("start", None, {"ok": True})
|
|
|
|
assert len(cache) == 0
|
|
assert cache.lookup("start", None) is None
|
|
|
|
|
|
def test_the_cache_is_bounded_because_the_peer_chooses_the_keys():
|
|
cache = protocol.IdempotencyCache(capacity=4)
|
|
for n in range(10):
|
|
cache.remember("touch", f"r{n}", {"ok": True, "n": n})
|
|
|
|
assert len(cache) == 4
|
|
assert cache.lookup("touch", "r0") is None
|
|
assert cache.lookup("touch", "r9")["n"] == 9
|
|
|
|
|
|
def test_every_pointer_verb_that_moves_something_is_cached():
|
|
"""A retried click is a second click — the one mutation an agent cannot undo."""
|
|
|
|
assert {
|
|
"pointer.acquire",
|
|
"pointer.move",
|
|
"pointer.button",
|
|
"pointer.click",
|
|
"pointer.release",
|
|
} <= protocol.MUTATING_VERBS
|
|
assert "pointer.state" not in protocol.MUTATING_VERBS
|
|
assert "container.list" not in protocol.MUTATING_VERBS
|
|
|
|
|
|
def test_every_verb_the_protocol_names_is_one_the_daemon_answers():
|
|
"""One list, so a verb cannot be added to the dispatcher alone.
|
|
|
|
The CLI imports `protocol`, not `server`; a verb in one and not the other
|
|
is a client that asks for something nothing answers.
|
|
"""
|
|
|
|
from pathlib import Path
|
|
|
|
from hhstreamd.clock import ManualClock
|
|
from hhstreamd.manager import ManagerConfig, SessionManager
|
|
from hhstreamd.policy import Policy
|
|
from hhstreamd.server import ControlServer
|
|
|
|
manager = SessionManager(
|
|
ManagerConfig(state_dir=Path("/nonexistent"), runtime_dir=Path("/nonexistent"), policy=Policy()),
|
|
clock=ManualClock(),
|
|
)
|
|
server = ControlServer(manager, "/nonexistent/control.sock")
|
|
|
|
assert set(server._ops) == set(protocol.VERBS)
|
|
assert protocol.MUTATING_VERBS <= set(protocol.VERBS)
|