test(stream): both ends of live.sock, the broker's verbs, and a real viewer in a guest
Three layers, because the stream has three and each one can be wrong on its own. `tests/live/test_live_control.py` (20 tests) runs `Control` against a fake capture: the four ops, `attach` idempotent on the phrase, the same phrase aimed at another output refused, a malformed phrase refused *without the value in the message*, and `fps` defaulting to the daemon's when the broker sends none. `tests/sessions/unit/test_stream_verbs.py` (24 tests) runs the broker against a fake daemon, and its subjects are the decisions rather than the plumbing: no container output is a refusal and never a fallback to the main output; a re-`enable` returns the same phrase and a different one is exit 8; a down daemon turns `attached` false rather than failing a read; the sweep touches a watched session and leaves an unwatched one alone; teardown detaches before the container is destroyed. `tests/unit/test_mcp_*` grow the two tools, the two resources and the three `session_start` arguments, with the read-only half asserted *absent* as a tool by name -- re-adding one should be a failure, not a silent widening. `checks/vm-stream.nix` is the new guest check, and it exists for the two things none of the above can say: 1. **That `grim` captures a real compositor from inside a unit.** It reads actual JPEGs off `/<phrase>/stream.mjpg` with `checks/lib/mjpeg_read.py`, a hand-rolled multipart reader that shares no code with the server -- a parser that did could not tell you the boundary was wrong. It framed on SOI/EOI rather than `Content-Length` for the same reason. This is what caught the unit's missing `XDG_RUNTIME_DIR`: `frames: [25827, 25827, 25827]` now, ten capture failures and a stream that gave up before. 2. **That a connected viewer moves the idle clock.** That needs the broker's real sweep, on a real timer, with a client genuinely still there a minute later -- hence `--hold`, and hence a check that spends ~90 seconds twice. The negative control runs first, because if the sweep touched an unwatched stream the positive case would pass for the wrong reason. Measured in the guest: with nobody watching `580s -> 502s` remaining, with a viewer `499s -> 596s`. It also asserts the phrase is in neither the audit log nor a 404 body, that the old URL stops serving after `disable`, that `disable` then `enable` rotates it, that `kill` takes the stream down and leaves the daemon up, and that `start --stream` yields an id and a URL that serves frames. No clock is injected anywhere in this check. An injected one would prove the arithmetic, which the unit tests already do, and not the daemon. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
This commit is contained in:
1 parent
5f5726c02e
commit
b4abd085cc
10 files changed
+1626
-7
No files matched your search
@@ -0,0 +1,327 @@
|
||||
"""``live.sock``: the four ops, over a real socket, against the shipped client.
|
||||
|
||||
The server is `hhstream_live.control` and the client is
|
||||
`hhstreamd.live.LiveStreams` — both shipped, talking over a real ``AF_UNIX``
|
||||
socket, so this is the one place the two halves of CONTRACT-sessions.md §3.5
|
||||
are read against each other. Only the capture is substituted, because this
|
||||
machine has no compositor.
|
||||
|
||||
The opposite choice from `tests/assert_stream.py`, and for the stated reason:
|
||||
what is being asserted here is that *this* client reaches *this* daemon, which
|
||||
a second implementation could say nothing about. The *wire format* is held
|
||||
honest separately, by the raw-JSON tests at the bottom that bypass the client
|
||||
entirely.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fake_jpeg import jpeg_bytes
|
||||
|
||||
from hhstream_live import phrase as phrase_mod
|
||||
from hhstream_live.control import Control, ControlServer
|
||||
from hhstream_live.publisher import FPS_CAP, StreamRegistry
|
||||
from hhstreamd.live import Attachment, LiveRejected, LiveStreams, LiveUnavailable
|
||||
|
||||
PORT = 9988
|
||||
|
||||
|
||||
class FakeCapture:
|
||||
def grab(self) -> bytes:
|
||||
return jpeg_bytes()
|
||||
|
||||
|
||||
class Daemon:
|
||||
"""The shipped control server, with a poll-interval accept loop."""
|
||||
|
||||
def __init__(self, socket_path: Path) -> None:
|
||||
self.registry = StreamRegistry()
|
||||
self.control = Control(
|
||||
self.registry,
|
||||
capture_for=lambda output: FakeCapture(),
|
||||
url_for=lambda phrase: f"http://127.0.0.1:{PORT}/{phrase}/",
|
||||
)
|
||||
self.server = ControlServer(socket_path, self.control)
|
||||
self.server.listen()
|
||||
self.connections: list[socket.socket] = []
|
||||
self._stop = threading.Event()
|
||||
self._listener = self.server._sock
|
||||
self._listener.settimeout(0.05)
|
||||
self._thread = threading.Thread(target=self._serve, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def _serve(self) -> None:
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except (TimeoutError, socket.timeout):
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
self.connections.append(conn)
|
||||
with conn:
|
||||
self.server._serve_connection(conn)
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop.set()
|
||||
for conn in self.connections:
|
||||
with contextlib.suppress(OSError):
|
||||
conn.shutdown(socket.SHUT_RDWR)
|
||||
self._thread.join(timeout=2)
|
||||
self.registry.stop_all()
|
||||
self.server.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def short_tmpdir():
|
||||
"""A directory with a short path.
|
||||
|
||||
Its own fixture rather than `tmp_path`, and the reason is the same one
|
||||
`tests/sessions/conftest.py` has: an ``AF_UNIX`` address is capped near 108
|
||||
bytes and pytest's own paths are longer than that. Not imported from there
|
||||
-- these two suites have separate conftests, and a cross-import between
|
||||
them is how the collection collision in this tree started.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
path = tempfile.mkdtemp(prefix="hhs")
|
||||
try:
|
||||
yield Path(path)
|
||||
finally:
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def daemon(short_tmpdir: Path):
|
||||
daemon = Daemon(short_tmpdir / "live.sock")
|
||||
try:
|
||||
yield daemon
|
||||
finally:
|
||||
daemon.stop()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(daemon):
|
||||
client = LiveStreams(daemon.server.socket_path)
|
||||
try:
|
||||
yield client
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
# ── attach ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_attaching_publishes_an_output_and_returns_the_daemon_s_url(client, daemon):
|
||||
phrase = phrase_mod.generate()
|
||||
attachment = client.attach(
|
||||
phrase=phrase, output="hh-x", fps=5, session="x", label="chromium"
|
||||
)
|
||||
|
||||
assert isinstance(attachment, Attachment)
|
||||
assert (attachment.output, attachment.fps, attachment.session) == ("hh-x", 5, "x")
|
||||
assert attachment.viewers == 0
|
||||
# The URL is the DAEMON's: the broker never assembles one, because it does
|
||||
# not own the port.
|
||||
assert attachment.url == f"http://127.0.0.1:{PORT}/{phrase}/"
|
||||
assert daemon.registry.get(phrase) is not None
|
||||
|
||||
|
||||
def test_attaching_the_same_phrase_twice_starts_no_second_capture(client, daemon):
|
||||
phrase = phrase_mod.generate()
|
||||
first = client.attach(phrase=phrase, output="hh-x", fps=5, session="x")
|
||||
again = client.attach(phrase=phrase, output="hh-x", fps=5, session="x")
|
||||
|
||||
assert again.url == first.url
|
||||
assert len(daemon.registry.all()) == 1
|
||||
|
||||
|
||||
def test_the_same_phrase_aimed_somewhere_else_is_refused(client, daemon):
|
||||
"""A phrase is a credential for one view; re-pointing it silently would
|
||||
show somebody a desktop they were not given."""
|
||||
|
||||
phrase = phrase_mod.generate()
|
||||
client.attach(phrase=phrase, output="hh-x", fps=5)
|
||||
|
||||
with pytest.raises(LiveRejected) as caught:
|
||||
client.attach(phrase=phrase, output="hh-other", fps=5)
|
||||
assert caught.value.kind == "invalid_argument"
|
||||
assert daemon.registry.get(phrase).spec.output == "hh-x"
|
||||
|
||||
|
||||
def test_a_phrase_that_is_not_of_the_shape_is_refused_without_echoing_it(client):
|
||||
"""The refusal crosses a socket into the broker's log. It is a password."""
|
||||
|
||||
with pytest.raises(LiveRejected) as caught:
|
||||
client.attach(phrase="hunter2", output="hh-x", fps=5)
|
||||
|
||||
assert caught.value.kind == "invalid_argument"
|
||||
assert "hunter2" not in str(caught.value)
|
||||
|
||||
|
||||
def test_a_rate_over_the_cap_is_refused_by_the_process_that_must_keep_up(client):
|
||||
with pytest.raises(LiveRejected) as caught:
|
||||
client.attach(phrase=phrase_mod.generate(), output="hh-x", fps=FPS_CAP + 1)
|
||||
assert caught.value.kind == "invalid_argument"
|
||||
assert str(FPS_CAP) in str(caught.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fps", [0, -1])
|
||||
def test_a_nonsensical_rate_is_refused(client, fps):
|
||||
with pytest.raises(LiveRejected):
|
||||
client.attach(phrase=phrase_mod.generate(), output="hh-x", fps=fps)
|
||||
|
||||
|
||||
def test_an_empty_output_is_refused(client):
|
||||
with pytest.raises(LiveRejected) as caught:
|
||||
client.attach(phrase=phrase_mod.generate(), output=" ", fps=5)
|
||||
assert caught.value.kind == "invalid_argument"
|
||||
|
||||
|
||||
# ── detach, list, viewers ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_detaching_stops_the_capture_and_says_it_did(client, daemon):
|
||||
phrase = phrase_mod.generate()
|
||||
client.attach(phrase=phrase, output="hh-x", fps=5)
|
||||
|
||||
assert client.detach(phrase) is True
|
||||
assert daemon.registry.get(phrase) is None
|
||||
|
||||
|
||||
def test_detaching_something_unattached_is_false_and_not_an_error(client):
|
||||
"""`disable` after the daemon restarted is the ordinary case."""
|
||||
|
||||
assert client.detach(phrase_mod.generate()) is False
|
||||
|
||||
|
||||
def test_listing_returns_every_stream(client):
|
||||
phrases = [phrase_mod.generate() for _ in range(3)]
|
||||
for index, phrase in enumerate(phrases):
|
||||
client.attach(phrase=phrase, output=f"hh-{index}", fps=5, session=f"s-{index}")
|
||||
|
||||
listed = client.list()
|
||||
assert {a.output for a in listed} == {"hh-0", "hh-1", "hh-2"}
|
||||
assert all(isinstance(a, Attachment) for a in listed)
|
||||
|
||||
|
||||
def test_viewers_reports_a_count_per_phrase(client, daemon):
|
||||
phrase = phrase_mod.generate()
|
||||
client.attach(phrase=phrase, output="hh-x", fps=5)
|
||||
assert client.viewers() == {phrase: 0}
|
||||
|
||||
daemon.registry.get(phrase).add_viewer()
|
||||
daemon.registry.get(phrase).add_viewer()
|
||||
assert client.viewers() == {phrase: 2}
|
||||
|
||||
|
||||
def test_an_empty_daemon_lists_nothing_rather_than_failing(client):
|
||||
assert client.list() == []
|
||||
assert client.viewers() == {}
|
||||
|
||||
|
||||
# ── failure ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_a_socket_that_is_not_there_is_unavailable(short_tmpdir: Path):
|
||||
client = LiveStreams(short_tmpdir / "nothing-here.sock")
|
||||
with pytest.raises(LiveUnavailable):
|
||||
client.list()
|
||||
|
||||
|
||||
def test_a_daemon_that_went_away_is_unavailable_and_not_a_stale_answer(client, daemon):
|
||||
client.attach(phrase=phrase_mod.generate(), output="hh-x", fps=5)
|
||||
assert client.list() # the connection is now held
|
||||
daemon.stop()
|
||||
|
||||
with pytest.raises(LiveUnavailable):
|
||||
client.list()
|
||||
|
||||
|
||||
def test_the_client_reconnects_after_the_daemon_restarts(short_tmpdir: Path):
|
||||
"""The held connection is checked for EOF before each write, as the
|
||||
driver's is -- so a restart costs one reconnect and not a dead client."""
|
||||
|
||||
path = short_tmpdir / "live.sock"
|
||||
first = Daemon(path)
|
||||
client = LiveStreams(path)
|
||||
try:
|
||||
client.attach(phrase=phrase_mod.generate(), output="hh-x", fps=5)
|
||||
first.stop()
|
||||
second = Daemon(path)
|
||||
try:
|
||||
# The new daemon knows nothing, which is the point: the client
|
||||
# reached it at all.
|
||||
assert client.list() == []
|
||||
finally:
|
||||
second.stop()
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
# ── the wire format itself ─────────────────────────────────────────────────
|
||||
#
|
||||
# These bypass `LiveStreams` on purpose. The tests above prove the two shipped
|
||||
# halves agree with each other; these prove the *format* §3.5 freezes, which a
|
||||
# pair that agreed on something else would also pass.
|
||||
|
||||
|
||||
def raw(path: Path, message: dict) -> dict:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
|
||||
sock.settimeout(5)
|
||||
sock.connect(str(path))
|
||||
with sock.makefile("rwb") as stream:
|
||||
stream.write(json.dumps(message).encode() + b"\n")
|
||||
stream.flush()
|
||||
return json.loads(stream.readline())
|
||||
|
||||
|
||||
def test_the_frozen_op_names_and_reply_shape(daemon):
|
||||
path = daemon.server.socket_path
|
||||
phrase = phrase_mod.generate()
|
||||
|
||||
attached = raw(path, {"op": "attach", "phrase": phrase, "output": "hh-x", "fps": 5})
|
||||
assert attached["ok"] is True
|
||||
stream = attached["stream"]
|
||||
assert set(stream) >= {"phrase", "output", "fps", "session", "url", "viewers"}
|
||||
|
||||
assert raw(path, {"op": "list"})["streams"][0]["output"] == "hh-x"
|
||||
assert raw(path, {"op": "viewers"})["viewers"] == {phrase: 0}
|
||||
assert raw(path, {"op": "detach", "phrase": phrase}) == {"ok": True, "detached": True}
|
||||
|
||||
|
||||
def test_an_unknown_op_is_refused_with_a_kind(daemon):
|
||||
reply = raw(daemon.server.socket_path, {"op": "levitate"})
|
||||
assert reply["ok"] is False
|
||||
assert reply["kind"] == "invalid_argument"
|
||||
|
||||
|
||||
def test_malformed_json_is_refused_without_closing_the_connection(daemon):
|
||||
path = daemon.server.socket_path
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
|
||||
sock.settimeout(5)
|
||||
sock.connect(str(path))
|
||||
with sock.makefile("rwb") as stream:
|
||||
stream.write(b"{not json\n")
|
||||
stream.flush()
|
||||
first = json.loads(stream.readline())
|
||||
assert first["ok"] is False
|
||||
# Still answering: one bad line must not cost the broker its
|
||||
# connection, because the next op may be a `detach` in a teardown.
|
||||
stream.write(json.dumps({"op": "list"}).encode() + b"\n")
|
||||
stream.flush()
|
||||
assert json.loads(stream.readline())["ok"] is True
|
||||
|
||||
|
||||
def test_a_request_that_is_not_an_object_is_refused(daemon):
|
||||
reply = raw(daemon.server.socket_path, ["attach"]) # type: ignore[arg-type]
|
||||
assert reply["ok"] is False
|
||||
assert reply["kind"] == "invalid_argument"
|
||||
@@ -93,6 +93,8 @@ def test_the_table_has_no_entries_this_test_does_not_know_about():
|
||||
"readiness_timeout", "busy", "already_managed", "pointer_busy",
|
||||
"container_budget", "no_lease", "compositor", "compositor_unavailable",
|
||||
"no_container", "driver_unavailable", "driver_refused",
|
||||
# v4, the stream. No new exit *numbers*: 8, 6 and 10 respectively.
|
||||
"stream_busy", "stream_budget", "stream_unavailable",
|
||||
}
|
||||
assert set(EXIT_CODE_FOR_ERROR) == documented
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import pytest
|
||||
|
||||
from hhstreamd.clock import ManualClock
|
||||
from hhstreamd.registry import (
|
||||
SCHEMA,
|
||||
ContainerState,
|
||||
Registry,
|
||||
Session,
|
||||
@@ -271,7 +272,7 @@ def test_derived_fields_reported_to_callers(registry: Registry):
|
||||
assert public["idle_s"] == 600.0
|
||||
assert public["expires_in_s"] == 10800.0 - 600.0
|
||||
assert public["live"] is True
|
||||
assert public["schema"] == 3
|
||||
assert public["schema"] == SCHEMA
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -350,7 +351,7 @@ def test_a_schema_two_record_is_adopted_and_not_rejected(tmp_path: Path):
|
||||
|
||||
assert quarantined == []
|
||||
assert restored.id == "foot-aaaaaa"
|
||||
assert restored.schema == 3
|
||||
assert restored.schema == SCHEMA
|
||||
# The honest value for everything schema 3 added: the daemon that wrote
|
||||
# this record knew nothing of containers, so there is nothing to claim.
|
||||
assert (restored.container, restored.pointer, restored.signature) == (None, None, None)
|
||||
@@ -362,7 +363,7 @@ def test_migrating_never_overwrites_a_field_that_was_already_there():
|
||||
migrated = migrate({"schema": 2, "id": "a", "container": {"state": "owned"}})
|
||||
|
||||
assert migrated["container"] == {"state": "owned"}
|
||||
assert migrated["schema"] == 3
|
||||
assert migrated["schema"] == SCHEMA
|
||||
|
||||
|
||||
def test_a_record_from_a_newer_schema_is_read_not_guessed_at(caplog):
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
"""The stream verbs: the phrase, the record, the teardown order and the sweep.
|
||||
|
||||
Both ends are real. The broker end is the manager, its `LiveStreams` client
|
||||
and its registry; the daemon end is the shipped `Control` and `ControlServer`
|
||||
over a real ``AF_UNIX`` socket. Only two things are substituted: the clock,
|
||||
because the viewer sweep's effect on an idle deadline has to be testable
|
||||
without waiting a minute, and the *capture*, because this machine has no
|
||||
compositor — a `grim` here would fail for a reason none of these tests are
|
||||
about.
|
||||
|
||||
What that leaves real is everything the feature actually turns on: that a
|
||||
phrase minted by the broker is one the daemon accepts, that it survives a
|
||||
re-enable, that a stream is detached before its output is removed, and that a
|
||||
connected viewer moves the idle clock when nothing else does.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import socket
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fakes import check_path
|
||||
|
||||
from hhstream_live import phrase as phrase_mod
|
||||
from hhstream_live.control import Control, ControlServer
|
||||
from hhstream_live.publisher import StreamRegistry
|
||||
from hhstreamd.clock import ManualClock
|
||||
from hhstreamd.manager import ManagerConfig, ManagerError, SessionManager
|
||||
from hhstreamd.policy import Policy
|
||||
from hhstreamd.protocol import ExitCode, exit_code_for
|
||||
from hhstreamd.registry import ContainerState, Session, State, container_record
|
||||
|
||||
#: A JPEG the publisher will accept without a compositor. One pixel, enough
|
||||
#: for `Stream` to have captured something.
|
||||
ONE_PIXEL_JPEG = b"\xff\xd8\xff\xd9"
|
||||
|
||||
|
||||
def make_session(session_id: str = "foot-aaaaaa", *, container: bool = True) -> Session:
|
||||
return Session(
|
||||
id=session_id,
|
||||
app="foot",
|
||||
argv=["/usr/bin/foot"],
|
||||
pid=4242,
|
||||
pgid=4242,
|
||||
sid=4242,
|
||||
pid_starttime=918342,
|
||||
cmdline_sha256="9f2c",
|
||||
home="/home/someone",
|
||||
runtime_dir=f"/run/hhstream/sessions/{session_id}",
|
||||
created_at="2026-10-01T09:14:02Z",
|
||||
created_boottime=1000.0,
|
||||
last_activity_at="2026-10-01T09:14:02Z",
|
||||
last_activity_boottime=1000.0,
|
||||
idle_timeout_s=10800.0,
|
||||
state=State.READY,
|
||||
container=(
|
||||
container_record(
|
||||
output=f"hh-{session_id}",
|
||||
workspace=1000,
|
||||
mode=(1280, 720),
|
||||
created_by="broker",
|
||||
state=ContainerState.OWNED,
|
||||
)
|
||||
if container
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class FakeCapture:
|
||||
"""A capture with no compositor. Counts grabs so a test can see one."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.grabs = 0
|
||||
|
||||
def grab(self) -> bytes:
|
||||
self.grabs += 1
|
||||
return ONE_PIXEL_JPEG
|
||||
|
||||
|
||||
class FakeLiveDaemon:
|
||||
"""The shipped `Control` and protocol loop, with a poll-interval accept.
|
||||
|
||||
The accept loop is the one thing not shipped, for `FakeDriver`'s reason:
|
||||
``serve_forever`` blocks in ``accept()`` by design and closing a listening
|
||||
socket does not reliably wake a thread already inside it, so a fake that
|
||||
used it would cost every test the stop timeout.
|
||||
"""
|
||||
|
||||
PORT = 9988
|
||||
|
||||
def __init__(self, socket_path: Path) -> None:
|
||||
check_path(Path(socket_path))
|
||||
self.registry = StreamRegistry()
|
||||
self.captures: dict[str, FakeCapture] = {}
|
||||
self.control = Control(
|
||||
self.registry,
|
||||
capture_for=self._capture_for,
|
||||
url_for=lambda phrase: f"http://127.0.0.1:{self.PORT}/{phrase}/",
|
||||
)
|
||||
self.server = ControlServer(Path(socket_path), self.control)
|
||||
self.server.listen()
|
||||
self.socket_path = Path(socket_path)
|
||||
self.connections: list[socket.socket] = []
|
||||
self._stop = threading.Event()
|
||||
self._listener = self.server._sock
|
||||
self._listener.settimeout(0.05)
|
||||
self._thread = threading.Thread(target=self._serve, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def _capture_for(self, output: str) -> FakeCapture:
|
||||
capture = FakeCapture()
|
||||
self.captures[output] = capture
|
||||
return capture
|
||||
|
||||
def _serve(self) -> None:
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except (TimeoutError, socket.timeout):
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
self.connections.append(conn)
|
||||
with conn:
|
||||
self.server._serve_connection(conn)
|
||||
|
||||
def watch(self, phrase: str, viewers: int = 1) -> None:
|
||||
"""Pretend ``viewers`` browsers are connected to ``phrase``."""
|
||||
|
||||
stream = self.registry.get(phrase)
|
||||
assert stream is not None, "nothing is published under that phrase"
|
||||
for _ in range(viewers):
|
||||
stream.add_viewer()
|
||||
|
||||
def unwatch(self, phrase: str) -> None:
|
||||
stream = self.registry.get(phrase)
|
||||
assert stream is not None
|
||||
while stream.viewers:
|
||||
stream.remove_viewer()
|
||||
|
||||
def outputs(self) -> list[str]:
|
||||
return [s.spec.output for s in self.registry.all()]
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop answering, for real.
|
||||
|
||||
Shutting the *accepted* connections down matters and is easy to get
|
||||
wrong: the broker holds one open between ops, so a stop that only
|
||||
closed the listener would leave a thread still sitting in `readline`
|
||||
and still answering `list` -- and the "the daemon is down" tests would
|
||||
pass against a daemon that was up.
|
||||
"""
|
||||
|
||||
self._stop.set()
|
||||
for conn in self.connections:
|
||||
with contextlib.suppress(OSError):
|
||||
conn.shutdown(socket.SHUT_RDWR)
|
||||
self._thread.join(timeout=2)
|
||||
self.registry.stop_all()
|
||||
self.server.close()
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, manager: SessionManager, daemon: FakeLiveDaemon, clock: ManualClock):
|
||||
self.manager = manager
|
||||
self.daemon = daemon
|
||||
self.clock = clock
|
||||
|
||||
def add(self, session_id: str = "foot-aaaaaa", **kwargs) -> Session:
|
||||
return self.manager.registry.add(make_session(session_id, **kwargs))
|
||||
|
||||
def run(self, coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def harness(short_tmpdir: Path):
|
||||
daemon = FakeLiveDaemon(short_tmpdir / "live.sock")
|
||||
clock = ManualClock(boottime=1000.0)
|
||||
manager = SessionManager(
|
||||
ManagerConfig(
|
||||
state_dir=short_tmpdir / "state",
|
||||
runtime_dir=short_tmpdir / "run",
|
||||
policy=Policy(),
|
||||
live_socket=daemon.socket_path,
|
||||
),
|
||||
clock=clock,
|
||||
)
|
||||
try:
|
||||
yield Harness(manager, daemon, clock)
|
||||
finally:
|
||||
if manager.live is not None:
|
||||
manager.live.close()
|
||||
daemon.stop()
|
||||
|
||||
|
||||
# ── enable ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_enabling_mints_a_phrase_the_daemon_accepts_and_publishes(harness):
|
||||
harness.add()
|
||||
reply = harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
|
||||
stream = reply["stream"]
|
||||
assert stream["enabled"] is True
|
||||
assert stream["attached"] is True
|
||||
assert stream["output"] == "hh-foot-aaaaaa"
|
||||
# The phrase the broker minted is one the daemon's own validator took.
|
||||
assert phrase_mod.validate(stream["phrase"]) == stream["phrase"]
|
||||
assert stream["url"].endswith(f"/{stream['phrase']}/")
|
||||
# ...and the daemon really is publishing that output.
|
||||
assert harness.daemon.outputs() == ["hh-foot-aaaaaa"]
|
||||
|
||||
|
||||
def test_the_phrase_is_in_the_record_so_it_survives_a_restart(harness):
|
||||
harness.add()
|
||||
first = harness.run(harness.manager.stream_enable("foot-aaaaaa"))["stream"]
|
||||
|
||||
stored = harness.manager.registry.get("foot-aaaaaa").stream
|
||||
assert stored["phrase"] == first["phrase"]
|
||||
# And it is on disk, not just in memory: a URL somebody was read out to
|
||||
# must not change because the broker bounced.
|
||||
records, broken = harness.manager.registry.load_records()
|
||||
assert broken == []
|
||||
on_disk = {record.id: record for record in records}
|
||||
assert on_disk["foot-aaaaaa"].stream["phrase"] == first["phrase"]
|
||||
|
||||
|
||||
def test_re_enabling_returns_the_same_phrase_and_starts_no_second_capture(harness):
|
||||
harness.add()
|
||||
first = harness.run(harness.manager.stream_enable("foot-aaaaaa"))["stream"]
|
||||
again = harness.run(harness.manager.stream_enable("foot-aaaaaa"))["stream"]
|
||||
|
||||
assert again["phrase"] == first["phrase"]
|
||||
assert again["url"] == first["url"]
|
||||
# One stream on the daemon, not two: a re-enable after a restart must not
|
||||
# double the grim rate on one output.
|
||||
assert len(harness.daemon.registry.all()) == 1
|
||||
|
||||
|
||||
def test_a_phrase_that_is_not_this_session_s_is_refused_not_rotated(harness):
|
||||
harness.add()
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
mine = harness.manager.registry.get("foot-aaaaaa").stream["phrase"]
|
||||
|
||||
with pytest.raises(ManagerError) as caught:
|
||||
harness.run(
|
||||
harness.manager.stream_enable("foot-aaaaaa", phrase=phrase_mod.generate())
|
||||
)
|
||||
assert caught.value.error == "stream_busy"
|
||||
assert exit_code_for(caught.value.error) == ExitCode.BUSY
|
||||
# The stored one is untouched: somebody may be holding its URL.
|
||||
assert harness.manager.registry.get("foot-aaaaaa").stream["phrase"] == mine
|
||||
|
||||
|
||||
def test_disable_then_enable_rotates_the_phrase(harness):
|
||||
harness.add()
|
||||
first = harness.run(harness.manager.stream_enable("foot-aaaaaa"))["stream"]["phrase"]
|
||||
harness.run(harness.manager.stream_disable("foot-aaaaaa"))
|
||||
second = harness.run(harness.manager.stream_enable("foot-aaaaaa"))["stream"]["phrase"]
|
||||
|
||||
assert second != first
|
||||
assert harness.daemon.registry.get(first) is None
|
||||
|
||||
|
||||
def test_a_caller_s_own_phrase_is_held_to_the_generated_shape(harness):
|
||||
harness.add()
|
||||
with pytest.raises(ManagerError) as caught:
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa", phrase="a-b-c"))
|
||||
|
||||
assert caught.value.error == "invalid_argument"
|
||||
assert exit_code_for(caught.value.error) == ExitCode.USAGE
|
||||
# The refusal must not echo the phrase: this reason is logged.
|
||||
assert "a-b-c" not in caught.value.reason
|
||||
|
||||
|
||||
def test_a_session_with_no_container_is_refused_and_never_falls_back(harness):
|
||||
"""The main output carries every other session. This is the one that matters."""
|
||||
|
||||
harness.add(container=False)
|
||||
with pytest.raises(ManagerError) as caught:
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
|
||||
assert caught.value.error == "stream_unavailable"
|
||||
assert exit_code_for(caught.value.error) == ExitCode.COMPOSITOR
|
||||
assert harness.daemon.outputs() == []
|
||||
|
||||
|
||||
def test_a_bad_rate_is_a_usage_error_from_the_broker(harness):
|
||||
harness.add()
|
||||
for bad in (0, -1):
|
||||
with pytest.raises(ManagerError) as caught:
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa", fps=bad))
|
||||
assert caught.value.error == "invalid_argument"
|
||||
|
||||
|
||||
def test_a_rate_over_the_daemon_s_cap_is_refused_by_the_daemon(harness):
|
||||
"""The cap belongs to the process that has to keep up with it."""
|
||||
|
||||
harness.add()
|
||||
with pytest.raises(ManagerError) as caught:
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa", fps=1000))
|
||||
|
||||
# The daemon's `invalid_argument` kind, mapped to exit 2 by the broker.
|
||||
assert caught.value.error == "invalid_argument"
|
||||
assert harness.daemon.outputs() == []
|
||||
|
||||
|
||||
def test_no_daemon_configured_is_unavailable_and_not_a_dead_session(harness, short_tmpdir):
|
||||
manager = SessionManager(
|
||||
ManagerConfig(
|
||||
state_dir=short_tmpdir / "s2",
|
||||
runtime_dir=short_tmpdir / "r2",
|
||||
policy=Policy(),
|
||||
live_socket=short_tmpdir / "nothing-here.sock",
|
||||
),
|
||||
clock=ManualClock(boottime=1000.0),
|
||||
)
|
||||
manager.registry.add(make_session())
|
||||
|
||||
with pytest.raises(ManagerError) as caught:
|
||||
asyncio.run(manager.stream_enable("foot-aaaaaa"))
|
||||
assert caught.value.error == "stream_unavailable"
|
||||
# Exit 10, which the table defines as "the session is NOT lost".
|
||||
assert exit_code_for(caught.value.error) == ExitCode.COMPOSITOR
|
||||
assert manager.registry.get("foot-aaaaaa").live
|
||||
|
||||
|
||||
# ── disable ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_disabling_stops_the_capture_and_clears_the_record(harness):
|
||||
harness.add()
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
reply = harness.run(harness.manager.stream_disable("foot-aaaaaa"))
|
||||
|
||||
assert reply["detached"] is True
|
||||
assert reply["stream"] is None
|
||||
assert harness.manager.registry.get("foot-aaaaaa").stream is None
|
||||
assert harness.daemon.outputs() == []
|
||||
|
||||
|
||||
def test_disabling_a_stream_the_daemon_forgot_is_not_an_error(harness):
|
||||
"""The ordinary case after the daemon restarts; the record still clears."""
|
||||
|
||||
harness.add()
|
||||
stream = harness.run(harness.manager.stream_enable("foot-aaaaaa"))["stream"]
|
||||
harness.daemon.registry.remove(stream["phrase"]) # as a restart would
|
||||
|
||||
reply = harness.run(harness.manager.stream_disable("foot-aaaaaa"))
|
||||
assert reply["detached"] is False
|
||||
assert harness.manager.registry.get("foot-aaaaaa").stream is None
|
||||
|
||||
|
||||
def test_disabling_a_session_with_no_stream_says_so(harness):
|
||||
harness.add()
|
||||
with pytest.raises(ManagerError) as caught:
|
||||
harness.run(harness.manager.stream_disable("foot-aaaaaa"))
|
||||
assert caught.value.error == "stream_unavailable"
|
||||
|
||||
|
||||
# ── reading ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_the_listing_merges_the_daemon_s_view_into_the_records(harness):
|
||||
harness.add("foot-aaaaaa")
|
||||
harness.add("foot-bbbbbb")
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
phrase = harness.manager.registry.get("foot-aaaaaa").stream["phrase"]
|
||||
harness.daemon.watch(phrase, viewers=3)
|
||||
|
||||
reply = harness.manager.stream_list()
|
||||
assert reply["available"] is True
|
||||
assert [row["id"] for row in reply["streams"]] == ["foot-aaaaaa"]
|
||||
assert reply["streams"][0]["viewers"] == 3
|
||||
assert reply["streams"][0]["attached"] is True
|
||||
|
||||
|
||||
def test_a_down_daemon_turns_attached_false_rather_than_failing_the_read(harness):
|
||||
harness.add()
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
harness.daemon.stop()
|
||||
|
||||
reply = harness.manager.stream_list()
|
||||
assert reply["available"] is False
|
||||
row = reply["streams"][0]
|
||||
assert row["attached"] is False
|
||||
# No stale URL and no stale count: absent is the honest answer.
|
||||
assert "url" not in row
|
||||
assert "viewers" not in row
|
||||
# The phrase is still there, which is what makes a re-enable the same URL.
|
||||
assert row["phrase"]
|
||||
|
||||
|
||||
def test_status_of_a_session_with_no_stream_is_a_null_not_an_error(harness):
|
||||
harness.add()
|
||||
assert harness.manager.stream_status("foot-aaaaaa")["stream"] is None
|
||||
|
||||
|
||||
def test_status_with_no_id_is_the_listing(harness):
|
||||
harness.add()
|
||||
assert "streams" in harness.manager.stream_status(None)
|
||||
|
||||
|
||||
# ── the idle clock ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_enabling_and_reading_do_not_touch_the_idle_clock(harness):
|
||||
session = harness.add()
|
||||
before = session.last_activity_boottime
|
||||
harness.clock.advance(300.0)
|
||||
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
harness.manager.stream_list()
|
||||
harness.manager.stream_status("foot-aaaaaa")
|
||||
|
||||
assert harness.manager.registry.get("foot-aaaaaa").last_activity_boottime == before
|
||||
|
||||
|
||||
def test_a_connected_viewer_is_activity_and_moves_the_deadline(harness):
|
||||
"""The one exception to "`touch` is the only mark of activity"."""
|
||||
|
||||
session = harness.add()
|
||||
before = session.last_activity_boottime
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
phrase = harness.manager.registry.get("foot-aaaaaa").stream["phrase"]
|
||||
harness.daemon.watch(phrase)
|
||||
harness.clock.advance(600.0)
|
||||
|
||||
touched = harness.run(harness.manager._touch_watched())
|
||||
|
||||
assert touched == ["foot-aaaaaa"]
|
||||
after = harness.manager.registry.get("foot-aaaaaa").last_activity_boottime
|
||||
assert after == before + 600.0
|
||||
|
||||
|
||||
def test_an_enabled_stream_nobody_watches_keeps_nothing_alive(harness):
|
||||
"""Otherwise a forgotten `enable` would be an immortal session."""
|
||||
|
||||
session = harness.add()
|
||||
before = session.last_activity_boottime
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
harness.clock.advance(600.0)
|
||||
|
||||
assert harness.run(harness.manager._touch_watched()) == []
|
||||
assert harness.manager.registry.get("foot-aaaaaa").last_activity_boottime == before
|
||||
|
||||
|
||||
def test_the_sweep_touches_only_the_sessions_being_watched(harness):
|
||||
harness.add("foot-aaaaaa")
|
||||
harness.add("foot-bbbbbb")
|
||||
for session_id in ("foot-aaaaaa", "foot-bbbbbb"):
|
||||
harness.run(harness.manager.stream_enable(session_id))
|
||||
watched = harness.manager.registry.get("foot-bbbbbb").stream["phrase"]
|
||||
harness.daemon.watch(watched)
|
||||
|
||||
assert harness.run(harness.manager._touch_watched()) == ["foot-bbbbbb"]
|
||||
|
||||
|
||||
def test_the_sweep_survives_a_daemon_that_is_not_there(harness):
|
||||
harness.add()
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
harness.daemon.stop()
|
||||
|
||||
assert harness.run(harness.manager._touch_watched()) == []
|
||||
|
||||
|
||||
def test_the_viewer_audit_entry_never_carries_the_phrase(harness):
|
||||
"""The audit log is read by whoever can read logs, and this is a password."""
|
||||
|
||||
harness.add()
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
phrase = harness.manager.registry.get("foot-aaaaaa").stream["phrase"]
|
||||
harness.daemon.watch(phrase)
|
||||
harness.run(harness.manager._touch_watched())
|
||||
|
||||
written = (Path(harness.manager.config.state_dir) / "events.jsonl").read_text()
|
||||
assert "stream_viewer_activity" in written
|
||||
assert "stream_enable" in written
|
||||
assert phrase not in written
|
||||
|
||||
|
||||
# ── teardown order ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_a_kill_detaches_the_stream_before_removing_the_output(harness):
|
||||
"""Order is load-bearing: a capture aimed at a removed output fails every
|
||||
time, and the daemon's failure budget would close the viewers saying
|
||||
"unknown output" instead of the session simply ending."""
|
||||
|
||||
harness.add()
|
||||
harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
order: list[str] = []
|
||||
real_detach = harness.manager._detach_stream
|
||||
real_destroy = harness.manager._destroy_container
|
||||
|
||||
async def detach(session):
|
||||
order.append("detach")
|
||||
return await real_detach(session)
|
||||
|
||||
def destroy(session):
|
||||
order.append("output remove")
|
||||
return real_destroy(session)
|
||||
|
||||
harness.manager._detach_stream = detach
|
||||
harness.manager._destroy_container = destroy
|
||||
harness.run(
|
||||
harness.manager.teardown(
|
||||
harness.manager.registry.get("foot-aaaaaa"), reason="kill", grace_s=0.1
|
||||
)
|
||||
)
|
||||
|
||||
assert order == ["detach", "output remove"]
|
||||
assert harness.daemon.outputs() == []
|
||||
@@ -42,11 +42,13 @@ EXPECTED_FIXED = {
|
||||
"hhstream://sessions",
|
||||
"hhstream://pointer",
|
||||
"hhstream://containers",
|
||||
"hhstream://streams",
|
||||
"hhstream://screen",
|
||||
}
|
||||
EXPECTED_TEMPLATES = {
|
||||
"hhstream://sessions/{id}{?events}",
|
||||
"hhstream://sessions/{id}/logs{?lines}",
|
||||
"hhstream://sessions/{id}/stream",
|
||||
"hhstream://outputs/{name}",
|
||||
}
|
||||
|
||||
@@ -76,7 +78,8 @@ def test_a_template_is_exactly_an_entry_with_a_capture():
|
||||
def test_the_three_reads_the_activity_rule_names_say_so_themselves():
|
||||
"""The rule has to be where it is read, and these are read, not called."""
|
||||
|
||||
for name in ("sessions", "session", "session-logs", "pointer", "containers"):
|
||||
for name in ("sessions", "session", "session-logs", "pointer", "containers",
|
||||
"streams", "session-stream"):
|
||||
description = resources.BY_NAME[name].description
|
||||
assert "does NOT reset" in description, name
|
||||
assert "`session_touch`" in description, name
|
||||
@@ -109,6 +112,7 @@ def test_each_fixed_resource_runs_the_verb_it_names(read):
|
||||
"hhstream://sessions": ["session", "list", "--json"],
|
||||
"hhstream://pointer": ["session", "pointer", "state", "--json"],
|
||||
"hhstream://containers": ["session", "container", "--json"],
|
||||
"hhstream://streams": ["session", "stream", "list", "--json"],
|
||||
}
|
||||
for uri, argv in cases.items():
|
||||
_, calls = read(uri, stdout=mcp_fake.reply(ok=True))
|
||||
@@ -290,6 +294,48 @@ def test_a_refused_capture_carries_the_cli_s_own_words(read):
|
||||
assert "hh-gone" in str(caught.value)
|
||||
|
||||
|
||||
# ── the stream ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_one_session_s_stream_reads_through_its_own_route(read):
|
||||
_, calls = read("hhstream://sessions/foot-abc/stream", stdout=mcp_fake.reply(ok=True))
|
||||
assert calls == [["session", "stream", "status", "--json", "--", "foot-abc"]]
|
||||
|
||||
|
||||
def test_the_stream_routes_do_not_collide_with_the_logs_route():
|
||||
"""Three templates under `sessions/{id}`; each must resolve to its own."""
|
||||
|
||||
assert resources.resolve("hhstream://sessions/x")[0].name == "session"
|
||||
assert resources.resolve("hhstream://sessions/x/logs")[0].name == "session-logs"
|
||||
assert resources.resolve("hhstream://sessions/x/stream")[0].name == "session-stream"
|
||||
|
||||
|
||||
def test_reading_a_stream_never_enables_one(read):
|
||||
"""The read is `status`, not `enable` -- switching one on is a tool."""
|
||||
|
||||
_, calls = read("hhstream://sessions/x/stream", stdout=mcp_fake.reply(ok=True))
|
||||
assert "enable" not in calls[0]
|
||||
_, calls = read("hhstream://streams", stdout=mcp_fake.reply(ok=True))
|
||||
assert "enable" not in calls[0]
|
||||
|
||||
|
||||
def test_both_stream_reads_warn_that_the_url_carries_its_credential():
|
||||
"""The URL is in these bodies, so the warning has to be on them."""
|
||||
|
||||
for name in ("streams", "session-stream"):
|
||||
description = resources.BY_NAME[name].description
|
||||
assert "PHRASE" in description, name
|
||||
assert "only thing protecting" in resources.BY_NAME["streams"].description
|
||||
|
||||
|
||||
def test_the_streams_listing_says_a_viewer_is_the_activity_exception():
|
||||
"""The one exception to `session_touch`, where somebody will read it."""
|
||||
|
||||
description = resources.BY_NAME["streams"].description
|
||||
assert "does NOT reset" in description
|
||||
assert "connected viewer" in description
|
||||
|
||||
|
||||
# ── the one read that must not be a resource ───────────────────────────────
|
||||
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ def test_tools_list_returns_every_tool_with_a_title_and_a_description(session):
|
||||
|
||||
listed = run(go).tools
|
||||
assert {tool.name for tool in listed} == set(tools.BY_NAME)
|
||||
assert len(listed) == 21
|
||||
assert len(listed) == 23
|
||||
for tool in listed:
|
||||
assert tool.title, tool.name
|
||||
assert tool.description and len(tool.description) > 40, tool.name
|
||||
@@ -524,6 +524,53 @@ def test_a_tool_outside_the_selection_cannot_be_called_by_name(session):
|
||||
assert fake.calls == []
|
||||
|
||||
|
||||
def test_the_stream_url_round_trips_through_a_resource_read(session):
|
||||
"""The phrase reaching an agent is the point of the whole feature."""
|
||||
|
||||
reply = {
|
||||
"ok": True,
|
||||
"id": "s-1",
|
||||
"stream": {
|
||||
"enabled": True,
|
||||
"attached": True,
|
||||
"output": "hh-s-1",
|
||||
"fps": 5,
|
||||
"viewers": 1,
|
||||
"url": "http://127.0.0.1:9988/amber-otter-lantern-harbor-7k2qp/",
|
||||
},
|
||||
}
|
||||
fake, connected = session(stdout=json.dumps(reply, indent=2))
|
||||
|
||||
async def go():
|
||||
async with connected as client:
|
||||
await client.initialize()
|
||||
return await client.read_resource(AnyUrl("hhstream://sessions/s-1/stream"))
|
||||
|
||||
content = run(go).contents[0]
|
||||
assert json.loads(content.text)["stream"]["url"] == reply["stream"]["url"]
|
||||
assert fake.calls == [["session", "stream", "status", "--json", "--", "s-1"]]
|
||||
|
||||
|
||||
def test_enabling_a_stream_through_a_tool_call_returns_its_url(session):
|
||||
reply = {
|
||||
"ok": True,
|
||||
"id": "s-1",
|
||||
"stream": {"attached": True, "url": "http://127.0.0.1:9988/a-b-c-d-12345/"},
|
||||
}
|
||||
fake, connected = session(stdout=json.dumps(reply, indent=2))
|
||||
|
||||
async def go():
|
||||
async with connected as client:
|
||||
await client.initialize()
|
||||
return await client.call_tool("session_stream_enable", {"id": "s-1"})
|
||||
|
||||
result = run(go)
|
||||
assert not result.isError
|
||||
assert result.content[0].text.startswith(reply["stream"]["url"])
|
||||
assert result.structuredContent == reply
|
||||
assert fake.calls == [["session", "stream", "enable", "--json", "--", "s-1"]]
|
||||
|
||||
|
||||
def test_content_for_a_text_only_result_has_no_image_block():
|
||||
blocks = server.content_for(tools.Result(text="hello"))
|
||||
assert [block.type for block in blocks] == ["text"]
|
||||
|
||||
@@ -51,6 +51,7 @@ EXPECTED = {
|
||||
# lifecycle. The read-only verbs are resources; see MOVED_TO_RESOURCES.
|
||||
"session_start", "session_touch", "session_kill", "session_gc",
|
||||
"session_adopt", "session_container", "session_reconcile",
|
||||
"session_stream_enable", "session_stream_disable",
|
||||
# pointer
|
||||
"pointer_acquire", "pointer_move", "pointer_click", "pointer_scroll",
|
||||
"pointer_down", "pointer_up", "pointer_release",
|
||||
@@ -72,7 +73,7 @@ MOVED_TO_RESOURCES = {
|
||||
|
||||
def test_the_acting_verbs_are_tools_and_nothing_else_is():
|
||||
assert set(tools.BY_NAME) == EXPECTED
|
||||
assert len(tools.TOOLS) == 21
|
||||
assert len(tools.TOOLS) == 23
|
||||
|
||||
|
||||
def test_the_read_only_verbs_are_not_tools():
|
||||
@@ -108,7 +109,12 @@ def test_only_the_verbs_that_read_are_marked_read_only():
|
||||
# `record` writes a file, so it is not read-only either.
|
||||
assert not tools.BY_NAME["record"].read_only
|
||||
assert tools.BY_NAME["session_kill"].destructive
|
||||
assert [t.name for t in tools.TOOLS if t.destructive] == ["session_kill"]
|
||||
# `stream_disable` is destructive too, and for a reason worth naming: it
|
||||
# forgets the phrase, so anybody holding the URL loses it.
|
||||
assert [t.name for t in tools.TOOLS if t.destructive] == [
|
||||
"session_kill",
|
||||
"session_stream_disable",
|
||||
]
|
||||
|
||||
|
||||
# ── the two rules an agent gets wrong ──────────────────────────────────────
|
||||
@@ -448,6 +454,151 @@ def test_a_broker_that_is_down_is_reported_as_the_operator_s_problem(call):
|
||||
assert "frame tools" in result.text
|
||||
|
||||
|
||||
# ── the live stream ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_enabling_a_stream_puts_the_url_where_a_caller_will_look(call):
|
||||
reply = {
|
||||
"ok": True,
|
||||
"id": "s-1",
|
||||
"stream": {
|
||||
"enabled": True,
|
||||
"output": "hh-s-1",
|
||||
"fps": 5,
|
||||
"attached": True,
|
||||
"url": "http://127.0.0.1:9988/amber-otter-lantern-harbor-7k2qp/",
|
||||
"viewers": 0,
|
||||
},
|
||||
}
|
||||
result, calls = call(
|
||||
"session_stream_enable", {"id": "s-1"}, stdout=json.dumps(reply, indent=2)
|
||||
)
|
||||
|
||||
assert calls == [["session", "stream", "enable", "--json", "--", "s-1"]]
|
||||
# The URL on the first line: it is the whole point of the call.
|
||||
assert result.text.startswith(reply["stream"]["url"])
|
||||
assert result.data == reply
|
||||
# ...and the one thing a caller must know about it.
|
||||
assert "only thing protecting it" in result.text
|
||||
|
||||
|
||||
def test_enabling_a_stream_passes_a_phrase_and_a_rate_through(call):
|
||||
_, calls = call(
|
||||
"session_stream_enable",
|
||||
{"id": "s-1", "phrase": "amber-otter-lantern-harbor-7k2qp", "fps": 3},
|
||||
stdout=mcp_fake.reply(ok=True, id="s-1", stream={"url": "http://x/"}),
|
||||
)
|
||||
assert calls == [
|
||||
[
|
||||
"session", "stream", "enable", "--json",
|
||||
"--phrase=amber-otter-lantern-harbor-7k2qp",
|
||||
"--fps=3",
|
||||
"--", "s-1",
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
def test_an_enable_the_daemon_did_not_confirm_does_not_invent_a_url(call):
|
||||
"""A printed URL that serves nothing is worse than saying there is none."""
|
||||
|
||||
result, _ = call(
|
||||
"session_stream_enable",
|
||||
{"id": "s-1"},
|
||||
stdout=mcp_fake.reply(ok=True, id="s-1", stream={"attached": False}),
|
||||
)
|
||||
assert "did not confirm" in result.text
|
||||
assert "http" not in result.text.split("\n\n")[0]
|
||||
|
||||
|
||||
def test_a_stream_on_a_session_with_no_container_is_exit_ten(call):
|
||||
"""It must never fall back to the main output -- that one carries everyone."""
|
||||
|
||||
result, _ = call(
|
||||
"session_stream_enable",
|
||||
{"id": "s-1"},
|
||||
stderr=mcp_fake.reply(
|
||||
ok=False,
|
||||
error="stream_unavailable",
|
||||
reason="session s-1 has no container output to publish",
|
||||
),
|
||||
exit_code=int(ExitCode.COMPOSITOR),
|
||||
)
|
||||
assert result.is_error
|
||||
assert result.data["exit_code"] == int(ExitCode.COMPOSITOR)
|
||||
assert "not lost" in result.text # the exit-10 remedy: degraded, not dead
|
||||
|
||||
|
||||
def test_a_phrase_that_is_not_this_session_s_is_exit_eight(call):
|
||||
result, _ = call(
|
||||
"session_stream_enable",
|
||||
{"id": "s-1", "phrase": "other-words-go-here-99999"},
|
||||
stderr=mcp_fake.reply(ok=False, error="stream_busy", reason="already has a stream"),
|
||||
exit_code=int(ExitCode.BUSY),
|
||||
)
|
||||
assert result.is_error
|
||||
assert result.text.startswith("exit 8 (BUSY)")
|
||||
|
||||
|
||||
def test_disabling_a_stream_is_marked_destructive_and_forgets_the_phrase(call):
|
||||
_, calls = call(
|
||||
"session_stream_disable", {"id": "s-1"}, stdout=mcp_fake.reply(ok=True, detached=True)
|
||||
)
|
||||
assert calls == [["session", "stream", "disable", "--json", "--", "s-1"]]
|
||||
assert tools.BY_NAME["session_stream_disable"].destructive
|
||||
assert "forget" in tools.BY_NAME["session_stream_disable"].description
|
||||
|
||||
|
||||
def test_start_can_ask_for_a_stream_and_gets_its_url_back(call):
|
||||
"""One call, because a stream needs the container output that start makes."""
|
||||
|
||||
reply = {
|
||||
"ok": True,
|
||||
"id": "s-9",
|
||||
"stream": {"url": "http://127.0.0.1:9988/amber-otter-lantern-harbor-7k2qp/"},
|
||||
}
|
||||
result, calls = call(
|
||||
"session_start",
|
||||
{"app": "chromium", "stream": True, "stream_fps": 4},
|
||||
stdout=json.dumps(reply, indent=2),
|
||||
)
|
||||
assert calls == [
|
||||
["session", "start", "--json", "--stream", "--stream-fps=4", "--", "chromium"]
|
||||
]
|
||||
assert "session id: s-9" in result.text
|
||||
assert reply["stream"]["url"] in result.text
|
||||
|
||||
|
||||
def test_a_start_whose_stream_failed_says_so_although_it_succeeded(call):
|
||||
"""Exit 0 with a running session; a caller must not read that as a stream."""
|
||||
|
||||
result, _ = call(
|
||||
"session_start",
|
||||
{"app": "chromium", "stream": True},
|
||||
stdout=mcp_fake.reply(
|
||||
ok=True, id="s-9", stream_error="session s-9 has no container output to publish"
|
||||
),
|
||||
)
|
||||
assert not result.is_error
|
||||
assert "stream: NOT enabled" in result.text
|
||||
assert "session_stream_enable" in result.text
|
||||
|
||||
|
||||
def test_a_start_that_asked_for_no_stream_says_nothing_about_one(call):
|
||||
result, calls = call(
|
||||
"session_start", {"app": "foot"}, stdout=mcp_fake.reply(ok=True, id="s-1")
|
||||
)
|
||||
assert "--stream" not in calls[0]
|
||||
assert "stream" not in result.text.lower().split("\n\n")[0]
|
||||
|
||||
|
||||
def test_the_stream_note_carries_both_facts_it_exists_for():
|
||||
assert "CREDENTIAL" in tools.STREAM_NOTE
|
||||
assert "only protection" in tools.STREAM_NOTE
|
||||
# The exception to the activity rule has to be where the stream is.
|
||||
assert "A CONNECTED VIEWER DOES" in tools.STREAM_NOTE
|
||||
assert tools.STREAM_NOTE in tools.BY_NAME["session_stream_enable"].description
|
||||
|
||||
|
||||
# ── shot and record ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user