Compare commits
7
Commits
ca5dbfb2ea
...
9708154eea
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9708154eea | ||
|
|
a61558a0ad | ||
|
|
0c06de4ea7 | ||
|
|
887ed17be2 | ||
|
|
9d33639c04 | ||
|
|
b4abd085cc | ||
|
|
5f5726c02e |
No files matched your search
+6
-2
@@ -52,7 +52,7 @@ import the SDK:
|
||||
```bash
|
||||
nix develop
|
||||
hhstream-mcp --list-tools # the 21 acting verbs
|
||||
hhstream-mcp --list-resources # the 8 read-only URIs
|
||||
hhstream-mcp --list-resources # the 10 read-only URIs
|
||||
```
|
||||
|
||||
## The checks
|
||||
@@ -68,8 +68,9 @@ hhstream-mcp --list-resources # the 8 read-only URIs
|
||||
| `vm-pointer` | the **lease and the driver**: a version-2 virtual pointer, a warp that lands where it was aimed *as the application reports it*, a click delivered as one press and one release, a contended acquire refused with BUSY, 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 | yes |
|
||||
| `vm-keyboard` | the **keymap, the focus and a decoded symbol**: the keymap the driver uploads reaching a real compositor, `pointer acquire` leaving the aimed window holding the *keyboard* and not merely the cursor, and `hhs-keyboard-target` decoding `hello` from the keymap it was **forwarded** — so a driver that stopped uploading one arrives as `sym=?` and goes red | yes |
|
||||
| `vm-keyboard-de` | the same file with `sessions.keyboard.layout = "de"`, because that option reaches the uploaded keymap through exactly one path — `--xkb-layout` on the driver unit — and a single-layout check cannot tell that path from a hardcoded `us`: keysym `y`'s evdev code swaps (21 against 44), the forwarded `symbols=` name with it, and `ü` goes from exit 2 to `udiaeresis` | yes |
|
||||
| `vm-stream` | the **live stream end to end**: `stream enable` on a live session mints a phrase the daemon accepts, a real HTTP viewer reads JPEGs off `/<phrase>/stream.mjpg` from *inside* the guest, `stream list` reports that viewer, the broker's idle-clock sweep stamps `touch` for it (and does not when nobody is watching), a wrong phrase 404s, and `kill` detaches the stream before the output is removed | yes |
|
||||
| `vm-stream-firewall` | the stream's **port**: the guest's own running firewall accepts the configured port and not the module's default, a peer outside the guest reaches it, and is refused on a port beside it that was never opened | yes |
|
||||
| `vm-mcp` | the **MCP server over stdio**: `mcp.enable` puts the binary on PATH and starts no unit, the `initialize` handshake completes over a real pipe, all 21 tools and 8 resources are listed with their annotations and their two rules, both a tool call and a resource read reach the live broker and return its own protocol object, two reads of a session do **not** move its idle deadline while `session_touch` does, a frame arrives as a blob at exactly its output's configured size, the pointer lease is granted/used/returned against the real driver, `--toolsets` narrows the tools and leaves the resources alone, and a refusal arrives as a tool error (or, for a read, a protocol error) carrying the frozen exit code | yes |
|
||||
| `vm-mcp` | the **MCP server over stdio**: `mcp.enable` puts the binary on PATH and starts no unit, the `initialize` handshake completes over a real pipe, all 23 tools and 10 resources are listed with their annotations and their two rules, both a tool call and a resource read reach the live broker and return its own protocol object, two reads of a session do **not** move its idle deadline while `session_touch` does, a frame arrives as a blob at exactly its output's configured size, the pointer lease is granted/used/returned against the real driver, `--toolsets` narrows the tools and leaves the resources alone, and a refusal arrives as a tool error (or, for a read, a protocol error) carrying the frozen exit code | yes |
|
||||
|
||||
All of them at once:
|
||||
|
||||
@@ -95,6 +96,7 @@ nix build -L .#checks.x86_64-linux.vm-keyboard
|
||||
nix build -L .#checks.x86_64-linux.vm-keyboard-de
|
||||
nix build -L .#checks.x86_64-linux.vm-stream-firewall
|
||||
nix build -L .#checks.x86_64-linux.vm-mcp
|
||||
nix build -L .#checks.x86_64-linux.vm-stream
|
||||
```
|
||||
|
||||
`-L` is not optional in practice: without it, Nix hides the build log, and the
|
||||
@@ -262,6 +264,8 @@ checks/
|
||||
vm-stream-firewall.nix nixosTest, the stream's port in the guest's firewall
|
||||
vm-mcp.nix nixosTest, hhstream-mcp driven over stdio by a raw
|
||||
JSON-RPC client against the live broker
|
||||
vm-stream.nix nixosTest, `session stream enable` and a real HTTP
|
||||
viewer reading MJPEG from inside the guest
|
||||
lib/mcp_client.py that client: hhs-mcp-call, stdlib only and deliberately
|
||||
NOT the MCP SDK's -- the SDK on both ends would agree
|
||||
with itself about a framing neither side had to get right
|
||||
|
||||
@@ -35,6 +35,52 @@ hhstream-client --socket /run/hypr-stream/stream.sock --count 1 --out frame.png
|
||||
The socket is a plain file descriptor: the server serves every client that
|
||||
connects, and keeps running when one disconnects.
|
||||
|
||||
## Watching a session: one port, a phrase per session
|
||||
|
||||
A session can publish its own screen on a web page, so a person can watch what
|
||||
an agent is doing from a phone. One port for the whole machine, and a path that
|
||||
is four words and a short tail:
|
||||
|
||||
```bash
|
||||
hhstream session stream enable chromium-k3f9d2
|
||||
# http://127.0.0.1:9988/amber-otter-lantern-harbor-7k2qp/
|
||||
```
|
||||
|
||||
That URL is the whole interface — a browser `<img>` is the entire client, over
|
||||
MJPEG — and the phrase in it is its **only** protection. No TLS, no second
|
||||
factor: anyone who can reach the port and guess four words can watch. It is
|
||||
never written to the audit log, and `stream list` does not print it.
|
||||
|
||||
Four things worth knowing before switching one on:
|
||||
|
||||
- **It is per session and off by default.** A session does not stream because
|
||||
it exists; it streams because somebody enabled it. What is published is that
|
||||
session's own container output, never the main one — the main output carries
|
||||
every other session, and putting it behind one session's phrase is the
|
||||
mistake this refuses to make.
|
||||
- **The phrase survives a restart.** It lives in the session's record, so
|
||||
somebody you read it out to keeps the URL you gave them. `disable` then
|
||||
`enable` rotates it.
|
||||
- **Capture runs only while somebody is connected.** An enabled stream nobody
|
||||
is watching costs no `grim` and no CPU.
|
||||
- **Watching counts as activity.** This is the one exception to "`touch` is the
|
||||
only mark of activity": about once a minute the broker notices a connected
|
||||
viewer and resets that session's idle clock, so a long job you are watching
|
||||
on a phone is not reaped at three hours. An enabled stream with nobody
|
||||
watching keeps nothing alive.
|
||||
|
||||
```nix
|
||||
services.hyprland-headless-stream.sessions.stream = {
|
||||
enable = true; # runs hhstream-live; turns no stream on
|
||||
# bind = "0.0.0.0"; # and openFirewall, to reach it from another device
|
||||
# openFirewall = true;
|
||||
};
|
||||
```
|
||||
|
||||
Loopback by default, where the path to a phone is `ssh -L 9988:127.0.0.1:9988`.
|
||||
`hhstream session start <app> --stream` starts an application and prints its
|
||||
URL in one go, which is the usual way an agent sets one up.
|
||||
|
||||
## Driving it from an agent: the MCP server
|
||||
|
||||
`hhstream-mcp` is the `hhstream` CLI behind a [Model Context
|
||||
@@ -45,14 +91,16 @@ application without writing command lines. The interface is frozen in
|
||||
|
||||
It is split the way the protocol splits things:
|
||||
|
||||
- **Resources are the state** — eight of them, read by URI, and reading one
|
||||
- **Resources are the state** — ten of them, read by URI, and reading one
|
||||
changes nothing. `hhstream://status` is whether the desktop is up,
|
||||
`hhstream://sessions` is what is running, `hhstream://sessions/<id>/logs` is
|
||||
an application's own output, `hhstream://pointer` is who holds the input
|
||||
lease, `hhstream://screen` is a frame of the screen.
|
||||
- **Tools are the acts** — twenty-one, one per CLI verb that does something.
|
||||
lease, `hhstream://screen` is a frame of the screen, `hhstream://streams` is
|
||||
what is being published and who is watching.
|
||||
- **Tools are the acts** — twenty-three, one per CLI verb that does something.
|
||||
`session_start` puts an application on the screen, `pointer_acquire` takes the
|
||||
input lease, `keyboard_type` types, `session_kill` ends a session.
|
||||
input lease, `keyboard_type` types, `session_stream_enable` publishes the
|
||||
screen for a person to watch, `session_kill` ends a session.
|
||||
|
||||
A host decides what state to put in front of its model; the model decides what
|
||||
to do. That is the whole of the split, and it is why `shot` is still a tool
|
||||
@@ -104,7 +152,7 @@ account in the group.
|
||||
`hhstream-mcp --list-tools` and `--list-resources` print the two tables and
|
||||
exit, which is the quickest way to check an install.
|
||||
|
||||
If twenty-one tools is more than a client has room for, `--toolsets` narrows
|
||||
If twenty-three tools is more than a client has room for, `--toolsets` narrows
|
||||
what is offered to whichever families are wanted — `frames`, `sessions`,
|
||||
`pointer`, `keyboard`:
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#
|
||||
# unit -- pytest over tests/, against the nix/package.nix build
|
||||
# vm-mcp -- the MCP server over stdio, against a live broker
|
||||
# vm-stream -- the per-session live stream, with a real HTTP viewer
|
||||
# vm-basic -- nixosTest with a fake capture backend: module + wire contract
|
||||
# vm-hyprland -- nixosTest with the real compositor and grim
|
||||
# vm-sessions -- nixosTest with the real compositor and the session broker
|
||||
@@ -80,4 +81,9 @@ in
|
||||
# JSON-RPC client the check writes itself. `sessionArgs` plus the one package
|
||||
# the others have no reason to carry.
|
||||
vm-mcp = pkgs.callPackage ./vm-mcp.nix (sessionArgs // { inherit hhstream-mcp; });
|
||||
|
||||
# The live stream: `stream enable`, a real HTTP viewer inside the guest, and
|
||||
# the one thing no in-process test can say -- that a connected viewer moves
|
||||
# the idle clock. Spends real time on purpose; see the file's header.
|
||||
vm-stream = pkgs.callPackage ./vm-stream.nix sessionArgs;
|
||||
}
|
||||
Executable
+148
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
"""``hhs-mjpeg-read`` -- read a real MJPEG stream, and optionally keep watching.
|
||||
|
||||
What `checks/vm-stream.nix` uses as the *person with a phone*. Two jobs, and the
|
||||
second is the one that matters:
|
||||
|
||||
1. Read N frames off ``multipart/x-mixed-replace`` and report their sizes, so
|
||||
"the stream works" is a statement about bytes a client actually received
|
||||
rather than about a 200.
|
||||
2. **Hold the connection open** for a while afterwards. The broker counts
|
||||
connected viewers and treats one as activity, so proving that needs a viewer
|
||||
that is still there a minute later -- a client that read three frames and
|
||||
exited would make the sweep correct and untested.
|
||||
|
||||
Standard library only, and a hand-rolled multipart reader rather than anything
|
||||
that understands HTTP for us: the framing is this repository's own
|
||||
(`hhstream_live.server`), and a parser that shared code with it could not tell
|
||||
you the boundary was wrong.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
SOI = b"\xff\xd8"
|
||||
EOI = b"\xff\xd9"
|
||||
|
||||
|
||||
def connect(url: str, timeout: float) -> socket.socket:
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
host = parsed.hostname or "127.0.0.1"
|
||||
port = parsed.port or 80
|
||||
path = parsed.path or "/"
|
||||
sock = socket.create_connection((host, port), timeout=timeout)
|
||||
request = (
|
||||
f"GET {path} HTTP/1.1\r\n"
|
||||
f"Host: {host}:{port}\r\n"
|
||||
"Accept: */*\r\n"
|
||||
"Connection: close\r\n\r\n"
|
||||
)
|
||||
sock.sendall(request.encode("ascii"))
|
||||
return sock
|
||||
|
||||
|
||||
def read_headers(sock: socket.socket) -> tuple[int, dict[str, str], bytes]:
|
||||
buffer = b""
|
||||
while b"\r\n\r\n" not in buffer:
|
||||
chunk = sock.recv(4096)
|
||||
if not chunk:
|
||||
raise SystemExit("the server closed the connection before any headers")
|
||||
buffer += chunk
|
||||
head, rest = buffer.split(b"\r\n\r\n", 1)
|
||||
lines = head.decode("latin-1").split("\r\n")
|
||||
status = int(lines[0].split()[1])
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
if ":" in line:
|
||||
name, _, value = line.partition(":")
|
||||
headers[name.strip().lower()] = value.strip()
|
||||
return status, headers, rest
|
||||
|
||||
|
||||
def frames(sock: socket.socket, rest: bytes, wanted: int, deadline: float) -> list[int]:
|
||||
"""Sizes of the JPEGs read off the multipart body, by SOI/EOI.
|
||||
|
||||
Framed on the markers rather than on ``Content-Length``: a stream that sent
|
||||
the right lengths and the wrong bytes would pass a length-based reader, and
|
||||
what the check is about is whether a browser would paint this.
|
||||
"""
|
||||
|
||||
sizes: list[int] = []
|
||||
buffer = rest
|
||||
while len(sizes) < wanted:
|
||||
if time.monotonic() > deadline:
|
||||
raise SystemExit(
|
||||
f"only {len(sizes)} of {wanted} frames arrived before the deadline"
|
||||
)
|
||||
start = buffer.find(SOI)
|
||||
end = buffer.find(EOI, start + 2) if start != -1 else -1
|
||||
if start != -1 and end != -1:
|
||||
sizes.append(end + 2 - start)
|
||||
buffer = buffer[end + 2 :]
|
||||
continue
|
||||
try:
|
||||
chunk = sock.recv(65536)
|
||||
except TimeoutError:
|
||||
raise SystemExit("the stream went quiet") from None
|
||||
if not chunk:
|
||||
raise SystemExit("the stream ended before enough frames arrived")
|
||||
buffer += chunk
|
||||
return sizes
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="hhs-mjpeg-read", description=__doc__)
|
||||
parser.add_argument("url", help="the stream.mjpg URL")
|
||||
parser.add_argument("--frames", type=int, default=2, help="how many to read")
|
||||
parser.add_argument(
|
||||
"--hold",
|
||||
type=float,
|
||||
default=0.0,
|
||||
metavar="SECONDS",
|
||||
help="keep the connection open this long after reading, so the broker "
|
||||
"counts a viewer for that whole time",
|
||||
)
|
||||
parser.add_argument("--timeout", type=float, default=30.0)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
sock = connect(args.url, args.timeout)
|
||||
sock.settimeout(args.timeout)
|
||||
try:
|
||||
status, headers, rest = read_headers(sock)
|
||||
content_type = headers.get("content-type", "")
|
||||
if status != 200:
|
||||
print(json.dumps({"status": status}), flush=True)
|
||||
raise SystemExit(f"the stream answered {status}, not 200")
|
||||
if "multipart/x-mixed-replace" not in content_type:
|
||||
raise SystemExit(f"content-type is {content_type!r}, not multipart")
|
||||
sizes = frames(sock, rest, args.frames, time.monotonic() + args.timeout)
|
||||
print(
|
||||
json.dumps(
|
||||
{"status": status, "content_type": content_type, "frames": sizes}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
if args.hold > 0:
|
||||
# Still connected, and still reading: a viewer that stopped reading
|
||||
# would have its socket buffer fill and the server would see it go.
|
||||
deadline = time.monotonic() + args.hold
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if not sock.recv(65536):
|
||||
break
|
||||
except TimeoutError:
|
||||
continue
|
||||
print(json.dumps({"held_for_s": args.hold}), flush=True)
|
||||
finally:
|
||||
sock.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+69
-4
@@ -11,7 +11,7 @@
|
||||
# WHAT THIS PROVES, AND WHAT IT DOES NOT.
|
||||
#
|
||||
# It proves the *surface*, both halves of it: the handshake completes over a
|
||||
# real pipe, all twenty-one tools and all eight resources are listed, a tool
|
||||
# real pipe, all twenty-three tools and all ten resources are listed, a tool
|
||||
# call reaches the broker and comes back with the broker's own protocol object,
|
||||
# a resource read reaches it the same way, an image arrives as a blob with the
|
||||
# geometry the module configured, `--toolsets` actually narrows what is
|
||||
@@ -119,6 +119,17 @@ testers.runNixOSTest (
|
||||
package = hhstream-mcp;
|
||||
};
|
||||
|
||||
# Enabled because two tools and two resources here are about streams,
|
||||
# and with no daemon they could only be shown to *refuse*. What a stream
|
||||
# actually serves is `vm-stream`'s subject -- it reads JPEGs off the
|
||||
# port; what this check owns is that the URL (with its phrase) comes back
|
||||
# through the MCP layer at all.
|
||||
services.hyprland-headless-stream.sessions.stream = {
|
||||
enable = true;
|
||||
bind = "127.0.0.1";
|
||||
port = 9988;
|
||||
};
|
||||
|
||||
environment.systemPackages = [ client ];
|
||||
};
|
||||
|
||||
@@ -227,10 +238,11 @@ testers.runNixOSTest (
|
||||
listed = mcp("--list")["tools"]
|
||||
names = sorted(tool["name"] for tool in listed)
|
||||
print(f"{len(names)} tools: {', '.join(names)}")
|
||||
assert len(names) == 21, names
|
||||
assert len(names) == 23, names
|
||||
for expected in (
|
||||
"shot", "record", "run",
|
||||
"session_start", "session_touch", "session_kill",
|
||||
"session_stream_enable", "session_stream_disable",
|
||||
"pointer_acquire", "pointer_click", "keyboard_type",
|
||||
):
|
||||
assert expected in names, f"{expected} is missing from the listing"
|
||||
@@ -257,10 +269,12 @@ testers.runNixOSTest (
|
||||
"hhstream://screen",
|
||||
"hhstream://sessions",
|
||||
"hhstream://status",
|
||||
"hhstream://streams",
|
||||
], uris
|
||||
assert templates == [
|
||||
"hhstream://outputs/{name}",
|
||||
"hhstream://sessions/{id}/logs{?lines}",
|
||||
"hhstream://sessions/{id}/stream",
|
||||
"hhstream://sessions/{id}{?events}",
|
||||
], templates
|
||||
by_uri = {r["uri"]: r for r in both["resources"]}
|
||||
@@ -505,8 +519,12 @@ testers.runNixOSTest (
|
||||
timeout=180,
|
||||
)
|
||||
)
|
||||
assert len(still_there["resources"]) == 5, still_there
|
||||
assert len(still_there["resourceTemplates"]) == 3, still_there
|
||||
# Every one of them, unnarrowed: `--toolsets` is a tool budget and
|
||||
# must not take the host's context away with it. Counted against
|
||||
# the full listing above rather than against a literal, so the next
|
||||
# resource added cannot make this pass by being forgotten.
|
||||
assert len(still_there["resources"]) == len(uris), still_there
|
||||
assert len(still_there["resourceTemplates"]) == len(templates), still_there
|
||||
|
||||
# And a tool outside the selection must be unreachable, not merely
|
||||
# unlisted, or the flag is cosmetic.
|
||||
@@ -532,6 +550,53 @@ testers.runNixOSTest (
|
||||
except Exception:
|
||||
dump("session_kill over mcp", session_id)
|
||||
raise
|
||||
|
||||
with subtest("a stream asked for at start comes back as a url, twice"):
|
||||
# The two places an agent can learn the phrase, and they have to
|
||||
# agree: the `session_start` reply, and the resource for that
|
||||
# session's stream. A URL is the daemon's to name and is never
|
||||
# stored, so a reply built from the broker's record alone would
|
||||
# carry a phrase and no URL -- which is how this went wrong once
|
||||
# (see `SessionManager.start`).
|
||||
streamed_id = None
|
||||
try:
|
||||
streamed = succeeded(
|
||||
"session_start", {"app": "foot", "stream": True}, timeout=300
|
||||
)
|
||||
streamed_id = streamed["structuredContent"]["id"]
|
||||
stream = streamed["structuredContent"]["stream"]
|
||||
print(f"{streamed_id} -> {stream['url']}")
|
||||
assert stream["url"].startswith("http://127.0.0.1:9988/"), stream
|
||||
# The phrase is IN the URL and is the whole of its protection,
|
||||
# so the text a model reads has to carry it too.
|
||||
assert stream["url"] in text_of(streamed)
|
||||
assert stream["phrase"] in stream["url"]
|
||||
assert streamed["structuredContent"]["stream_error"] is None
|
||||
|
||||
body = json.loads(
|
||||
read(f"hhstream://sessions/{streamed_id}/stream")[0]["text"]
|
||||
)
|
||||
assert body["stream"]["url"] == stream["url"], body
|
||||
assert body["stream"]["attached"] is True, body
|
||||
|
||||
# And the listing resource names it, with the daemon reachable.
|
||||
listed = json.loads(read("hhstream://streams")[0]["text"])
|
||||
assert listed["available"] is True, listed
|
||||
assert [row["id"] for row in listed["streams"]] == [streamed_id], listed
|
||||
except Exception:
|
||||
dump("session_start --stream over mcp", streamed_id)
|
||||
raise
|
||||
|
||||
with subtest("disabling over mcp takes the stream off both resources"):
|
||||
try:
|
||||
succeeded("session_stream_disable", {"id": streamed_id}, timeout=180)
|
||||
body = json.loads(
|
||||
read(f"hhstream://sessions/{streamed_id}/stream")[0]["text"]
|
||||
)
|
||||
assert body["stream"] is None, body
|
||||
assert json.loads(read("hhstream://streams")[0]["text"])["streams"] == []
|
||||
finally:
|
||||
succeeded("session_kill", {"id": streamed_id}, timeout=300)
|
||||
'';
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,372 @@
|
||||
# checks.<system>.vm-stream -- the per-session live stream, end to end, with a
|
||||
# real HTTP viewer inside the guest.
|
||||
#
|
||||
# The session machine plus `sessions.stream.enable = true`, which runs
|
||||
# `hhstream-live` and hands the broker `/run/hhstream/live.sock`. Then:
|
||||
# `hhstream session stream enable` on a live session, and a client that reads
|
||||
# actual JPEGs off `/<phrase>/stream.mjpg`.
|
||||
#
|
||||
# WHAT THIS PROVES THAT THE UNIT TESTS CANNOT.
|
||||
#
|
||||
# `tests/live/test_live_control.py` and `tests/sessions/unit/test_stream_verbs.py`
|
||||
# already run both ends of `live.sock` against each other with a fake capture.
|
||||
# What they cannot say is that `grim` captures a real compositor from inside a
|
||||
# *unit* -- which is the one failure this feature has already been bitten by
|
||||
# once elsewhere in this tree (`docs/TODO/capture-binary-and-the-unit-path.md`:
|
||||
# a unit's PATH has no `grim`, and the symptom is an empty frame area with no
|
||||
# error). So the capture command is passed explicitly by the module and this
|
||||
# check reads the bytes that come out of it.
|
||||
#
|
||||
# It also proves the one thing no in-process test can: that a *connected
|
||||
# viewer* moves the idle clock. That needs the broker's real sweep, on a real
|
||||
# timer, with a client that is genuinely still there a minute later -- which is
|
||||
# why `hhs-mjpeg-read --hold` exists and why this check spends real time.
|
||||
#
|
||||
# THE TWO REAL-TIME WAITS ARE THE POINT OF THEIR SUBTESTS. The sweep runs once
|
||||
# a minute (`hhstreamd.manager.STREAM_SWEEP_S`), and both the positive case and
|
||||
# its negative control have to outlast one pass. No clock is injected anywhere:
|
||||
# an injected one would prove the arithmetic, which the unit tests already do,
|
||||
# and not the daemon.
|
||||
#
|
||||
# Habits copied from the other session checks: every wait is bounded, each
|
||||
# subtest asserts once, and a failure dumps the compositor's diagnostics and
|
||||
# the broker's journal before it propagates.
|
||||
{
|
||||
testers,
|
||||
hhstream,
|
||||
hhsModule,
|
||||
testTools,
|
||||
hyprland,
|
||||
foot,
|
||||
jq,
|
||||
grim,
|
||||
procps,
|
||||
coreutils,
|
||||
dejavu_fonts,
|
||||
width ? 1280,
|
||||
height ? 720,
|
||||
sessionUser ? "hermes",
|
||||
port ? 9988,
|
||||
}:
|
||||
testers.runNixOSTest (
|
||||
{ pkgs, ... }:
|
||||
let
|
||||
tools = pkgs.callPackage ./lib/session-tools.nix { inherit hhstream; };
|
||||
guest = import ./lib/session-machine.nix {
|
||||
inherit
|
||||
hhsModule
|
||||
hhstream
|
||||
hyprland
|
||||
testTools
|
||||
foot
|
||||
jq
|
||||
procps
|
||||
grim
|
||||
coreutils
|
||||
dejavu_fonts
|
||||
;
|
||||
sessionTools = tools;
|
||||
};
|
||||
prelude = import ./lib/session-prelude.nix {
|
||||
inherit hhstream coreutils sessionUser;
|
||||
};
|
||||
|
||||
# The viewer. Plain python3 and a hand-rolled multipart reader, so the
|
||||
# framing this repository serves is read by something that does not share
|
||||
# code with it -- the same choice `tests/assert_stream.py` makes about the
|
||||
# frame socket, for the same reason.
|
||||
viewer = pkgs.runCommandLocal "hhs-mjpeg-read" { } ''
|
||||
install -Dm755 ${./lib/mjpeg_read.py} $out/bin/hhs-mjpeg-read
|
||||
sed -i '1s|.*|#!${pkgs.python3}/bin/python3|' $out/bin/hhs-mjpeg-read
|
||||
$out/bin/hhs-mjpeg-read --help > /dev/null
|
||||
'';
|
||||
in
|
||||
{
|
||||
name = "hhstream-vm-stream";
|
||||
|
||||
# Boot, plus two sweep windows of real waiting (~70 s each) and a session
|
||||
# launch. Capped so a hang is a failure rather than a wedged builder.
|
||||
globalTimeout = 2400;
|
||||
|
||||
nodes.machine = {
|
||||
imports = [
|
||||
(guest {
|
||||
inherit width height sessionUser;
|
||||
apps.foot = {
|
||||
exec = "${foot}/bin/foot";
|
||||
argsAllow = [ ];
|
||||
};
|
||||
})
|
||||
];
|
||||
|
||||
services.hyprland-headless-stream.sessions.stream = {
|
||||
enable = true;
|
||||
# Loopback: the viewer runs inside the guest. Reaching it from outside
|
||||
# is `vm-stream-firewall`'s subject, and opening a port here would make
|
||||
# two checks assert the same thing badly.
|
||||
bind = "127.0.0.1";
|
||||
inherit port;
|
||||
};
|
||||
|
||||
environment.systemPackages = [ viewer ];
|
||||
};
|
||||
|
||||
testScript =
|
||||
prelude
|
||||
+ ''
|
||||
# `machine.sleep` wants a `timedelta`: a bare number is deprecated as
|
||||
# `secs=` and refused outright by the driver's type check as
|
||||
# `duration=`. MEASURED, as `nix build` failing before the VM even
|
||||
# booted: "Expected `timedelta | None`, found `Literal[75]`".
|
||||
import datetime as dt
|
||||
|
||||
READ = "${viewer}/bin/hhs-mjpeg-read"
|
||||
PORT = ${toString port}
|
||||
LIVE_SOCKET = "/run/hhstream/live.sock"
|
||||
#: `hhstreamd.manager.STREAM_SWEEP_S`, plus room for one round trip.
|
||||
SWEEP_WINDOW_S = 75
|
||||
|
||||
|
||||
def expires_in(session_id):
|
||||
"""The session's own idle deadline, as the broker reports it."""
|
||||
|
||||
return cli_json(f"status {session_id} --json")["session"]["expires_in_s"]
|
||||
|
||||
|
||||
def stream_json(args=""):
|
||||
return cli_json(f"stream {args} --json".strip())
|
||||
|
||||
|
||||
start_all()
|
||||
bring_up("the compositor and broker")
|
||||
|
||||
with subtest("the as-user wrapper propagates exit status"):
|
||||
machine.succeed(as_user(TRUE), timeout=120)
|
||||
machine.fail(as_user(FALSE), timeout=120)
|
||||
|
||||
with subtest("the stream daemon came up and owns its socket, not the broker's"):
|
||||
try:
|
||||
machine.wait_for_unit("hhstream-live.service", timeout=180)
|
||||
machine.wait_for_file(LIVE_SOCKET, timeout=120)
|
||||
restarts = machine.succeed(
|
||||
"systemctl show -p NRestarts --value hhstream-live.service"
|
||||
).strip()
|
||||
assert restarts == "0", (
|
||||
f"hhstream-live has restarted {restarts} time(s): it is "
|
||||
"crash-looping, not running"
|
||||
)
|
||||
# The risk the plan names by name: a second RuntimeDirectory on
|
||||
# /run/hhstream would have deleted the broker's socket.
|
||||
machine.succeed(f"test -S {CONTROL}")
|
||||
machine.succeed(f"test -S {LIVE_SOCKET}")
|
||||
# And it is listening on the port it was given, with no stream
|
||||
# on it: running the daemon turns nothing on.
|
||||
machine.wait_until_succeeds(
|
||||
f"ss -ltn | grep -q 127.0.0.1:{PORT}", timeout=60
|
||||
)
|
||||
assert stream_json("list")["streams"] == []
|
||||
except Exception:
|
||||
dump("the stream daemon did not come up")
|
||||
raise
|
||||
|
||||
with subtest("a session with no stream reports none"):
|
||||
session_id = machine.succeed(cli("start foot"), timeout=300).strip()
|
||||
print(f"session {session_id}")
|
||||
assert stream_json(f"status {session_id}")["stream"] is None
|
||||
|
||||
with subtest("enabling mints a phrase and the daemon publishes the output"):
|
||||
try:
|
||||
url = machine.succeed(
|
||||
cli(f"stream enable {session_id}"), timeout=180
|
||||
).strip()
|
||||
print(f"stream url: {url}")
|
||||
assert url.startswith(f"http://127.0.0.1:{PORT}/"), url
|
||||
|
||||
status = stream_json(f"status {session_id}")["stream"]
|
||||
assert status["attached"] is True, status
|
||||
assert status["output"] == f"hh-{session_id}", status
|
||||
assert status["url"] == url, status
|
||||
# The phrase is in the URL and in the record, and nowhere else.
|
||||
assert status["phrase"] in url
|
||||
except Exception:
|
||||
dump("enabling the stream", session_id)
|
||||
raise
|
||||
|
||||
with subtest("the phrase is not in the audit log"):
|
||||
# It is the stream's only credential, and the log is read by
|
||||
# whoever can read logs (CONTRACT-sessions.md §3.5).
|
||||
phrase = stream_json(f"status {session_id}")["stream"]["phrase"]
|
||||
events = machine.succeed(
|
||||
"cat /var/lib/hhstream/events.jsonl || true", timeout=60
|
||||
)
|
||||
assert "stream_enable" in events, "the enable was not audited at all"
|
||||
assert phrase not in events, "the phrase reached the audit log"
|
||||
|
||||
with subtest("a real client reads JPEGs off the stream"):
|
||||
# The subtest the unit tests cannot write: `grim` capturing a real
|
||||
# compositor, from inside a unit, through the module's own capture
|
||||
# command.
|
||||
try:
|
||||
out = machine.succeed(
|
||||
as_user(f"{READ} {url}stream.mjpg --frames 3"), timeout=180
|
||||
)
|
||||
first = json.loads(out.strip().splitlines()[0])
|
||||
print(f"viewer read: {first}")
|
||||
assert first["status"] == 200, first
|
||||
assert "multipart/x-mixed-replace" in first["content_type"], first
|
||||
assert len(first["frames"]) == 3, first
|
||||
# Real frames of a real desktop, not a 1x1 placeholder.
|
||||
assert all(size > 1024 for size in first["frames"]), first["frames"]
|
||||
except Exception:
|
||||
dump("reading the stream", session_id)
|
||||
raise
|
||||
|
||||
with subtest("a wrong phrase is a 404 and is never echoed back"):
|
||||
wrong = "wrong-words-entirely-here-00000"
|
||||
status, body = machine.execute(
|
||||
as_user(f"{READ} http://127.0.0.1:{PORT}/{wrong}/stream.mjpg --frames 1"),
|
||||
timeout=120,
|
||||
)
|
||||
assert status != 0, f"a wrong phrase was served: {body}"
|
||||
assert wrong not in body, "the wrong phrase was echoed back"
|
||||
|
||||
with subtest("an enabled stream nobody watches keeps nothing alive"):
|
||||
# The negative control, and it has to come first: if the sweep
|
||||
# touched an unwatched stream, the positive case below would pass
|
||||
# for the wrong reason.
|
||||
try:
|
||||
assert stream_json("list")["streams"][0]["viewers"] == 0
|
||||
before = expires_in(session_id)
|
||||
machine.sleep(duration=dt.timedelta(seconds=SWEEP_WINDOW_S))
|
||||
after = expires_in(session_id)
|
||||
print(f"with no viewer: {before:.0f}s -> {after:.0f}s remaining")
|
||||
assert after < before, (
|
||||
"the idle deadline did not move closer over a whole sweep "
|
||||
"window with nobody watching, so something is touching this "
|
||||
"session"
|
||||
)
|
||||
except Exception:
|
||||
dump("the unwatched stream", session_id)
|
||||
raise
|
||||
|
||||
with subtest("a connected viewer is activity and moves the idle deadline"):
|
||||
# The one exception to "touch is the only mark of activity"
|
||||
# (CONTRACT-sessions.md §4). The viewer holds its connection open
|
||||
# across a sweep, because a client that read and left would make
|
||||
# the sweep correct and untested.
|
||||
try:
|
||||
before = expires_in(session_id)
|
||||
machine.succeed(
|
||||
background(
|
||||
"hhs-viewer",
|
||||
f"{READ} {url}stream.mjpg --frames 2 "
|
||||
f"--hold {SWEEP_WINDOW_S} --timeout {SWEEP_WINDOW_S + 60}",
|
||||
user=USER,
|
||||
),
|
||||
timeout=120,
|
||||
)
|
||||
watching = wait_for(
|
||||
lambda: stream_json("list")["streams"][0]["viewers"] > 0,
|
||||
timeout=60,
|
||||
what="the broker to see a connected viewer",
|
||||
)
|
||||
assert watching
|
||||
after = wait_for(
|
||||
lambda: expires_in(session_id) > before,
|
||||
timeout=SWEEP_WINDOW_S + 60,
|
||||
what="the viewer sweep to reset the idle clock",
|
||||
)
|
||||
print(f"with a viewer: {before:.0f}s -> {expires_in(session_id):.0f}s")
|
||||
|
||||
events = machine.succeed("cat /var/lib/hhstream/events.jsonl")
|
||||
assert "stream_viewer_activity" in events
|
||||
assert stream_json(f"status {session_id}")["stream"]["phrase"] not in events
|
||||
except Exception:
|
||||
dump("the watched stream", session_id)
|
||||
raise
|
||||
|
||||
with subtest("re-enabling returns the same url and starts no second capture"):
|
||||
again = machine.succeed(cli(f"stream enable {session_id}"), timeout=180).strip()
|
||||
assert again == url, f"the phrase rotated: {again} != {url}"
|
||||
assert len(stream_json("list")["streams"]) == 1
|
||||
|
||||
with subtest("a phrase that is not this session's is refused"):
|
||||
# Of the generated SHAPE and not this session's phrase -- the two
|
||||
# refusals are different exits, and a fixture that is merely
|
||||
# malformed would take the shape path (exit 2) and never reach the
|
||||
# broker. MEASURED: the first fixture here was
|
||||
# `other-words-go-here-99999`, which fails on `go` being two
|
||||
# letters -- the CLI refused it on shape and this subtest read
|
||||
# exit 2 where it wanted 8.
|
||||
status, out = machine.execute(
|
||||
cli(f"stream enable {session_id} --phrase other-words-going-here-99999"),
|
||||
timeout=120,
|
||||
)
|
||||
# Exit 8 (BUSY): rotating under somebody holding the old URL is the
|
||||
# one outcome neither answer can be mistaken for.
|
||||
assert status == 8, f"expected exit 8, got {status}: {out}"
|
||||
assert stream_json(f"status {session_id}")["stream"]["url"] == url
|
||||
|
||||
with subtest("a malformed phrase is refused without echoing it"):
|
||||
status, out = machine.execute(
|
||||
cli(f"stream enable {session_id} --phrase hunter2"), timeout=120
|
||||
)
|
||||
assert status == 2, f"expected exit 2, got {status}: {out}"
|
||||
assert "hunter2" not in out, "the refusal echoed the phrase back"
|
||||
|
||||
with subtest("disabling stops the capture and forgets the phrase"):
|
||||
machine.succeed(cli(f"stream disable {session_id}"), timeout=180)
|
||||
assert stream_json(f"status {session_id}")["stream"] is None
|
||||
assert stream_json("list")["streams"] == []
|
||||
status, _ = machine.execute(
|
||||
as_user(f"{READ} {url}stream.mjpg --frames 1"), timeout=120
|
||||
)
|
||||
assert status != 0, "the old URL still serves after disable"
|
||||
|
||||
with subtest("disable then enable rotates the phrase"):
|
||||
rotated = machine.succeed(cli(f"stream enable {session_id}"), timeout=180).strip()
|
||||
assert rotated != url, "the phrase did not rotate"
|
||||
url = rotated
|
||||
|
||||
with subtest("kill takes the stream down with the session"):
|
||||
# The teardown *order* is unit-tested (a capture aimed at a removed
|
||||
# output fails every time); what is asserted here is the outcome
|
||||
# both halves have to agree on.
|
||||
try:
|
||||
machine.succeed(cli(f"kill {session_id}"), timeout=300)
|
||||
assert stream_json("list")["streams"] == []
|
||||
status, _ = machine.execute(
|
||||
as_user(f"{READ} {url}stream.mjpg --frames 1"), timeout=120
|
||||
)
|
||||
assert status != 0, "the stream outlived its session"
|
||||
# And the daemon is still up: a session ending is not its
|
||||
# problem.
|
||||
machine.succeed("systemctl is-active hhstream-live.service")
|
||||
except Exception:
|
||||
dump("killing a streaming session", session_id)
|
||||
raise
|
||||
|
||||
with subtest("start --stream does it in one call"):
|
||||
# The usual way an agent sets one up, and the reason `start` takes
|
||||
# the flag at all: a stream needs the container output that
|
||||
# starting creates.
|
||||
try:
|
||||
out = machine.succeed(cli("start foot --stream"), timeout=300)
|
||||
lines = [line for line in out.strip().splitlines() if line]
|
||||
streamed_id, streamed_url = lines[0], lines[1]
|
||||
print(f"{streamed_id} -> {streamed_url}")
|
||||
assert streamed_url.startswith(f"http://127.0.0.1:{PORT}/")
|
||||
read = json.loads(
|
||||
machine.succeed(
|
||||
as_user(f"{READ} {streamed_url}stream.mjpg --frames 2"),
|
||||
timeout=180,
|
||||
).strip().splitlines()[0]
|
||||
)
|
||||
assert len(read["frames"]) == 2, read
|
||||
machine.succeed(cli(f"kill {streamed_id}"), timeout=300)
|
||||
except Exception:
|
||||
dump("start --stream")
|
||||
raise
|
||||
'';
|
||||
}
|
||||
)
|
||||
+27
-8
@@ -26,9 +26,17 @@
|
||||
│ hhstream-sessions.service │─────▶│ hhstream-pointer.service │
|
||||
│ hhstreamd │ │ one Wayland connection │
|
||||
│ registry, containers, │ JSON │ one virtual pointer │
|
||||
│ the pointer lease │ over │ per output │
|
||||
└────────────┬──────────────┘ a └──────────────────────────┘
|
||||
│ private socket
|
||||
│ the pointer lease, │ over │ per output │
|
||||
│ the stream phrases │ a └──────────────────────────┘
|
||||
└────────────┬────────┬─────┘ private socket
|
||||
│ │ ┌──────────────────────────┐
|
||||
│ └─────────────▶│ hhstream-live.service │
|
||||
│ live.sock │ one port (9988) │
|
||||
│ │ grim ─▶ MJPEG per │
|
||||
│ │ phrase, while watched │
|
||||
│ └───────────┬──────────────┘
|
||||
│ │ HTTP
|
||||
│ a browser ┘ /<phrase>/
|
||||
│ AF_UNIX control.sock, mode 0660
|
||||
▼
|
||||
hhstream session ... (the CLI an agent drives)
|
||||
@@ -37,12 +45,12 @@
|
||||
│
|
||||
┌────────────┴──────────────┐
|
||||
│ hhstream-mcp │ spawned per client, stdio only
|
||||
│ 21 tools (the acts) │◀─── an MCP client's JSON-RPC
|
||||
│ 8 resources (the state)│
|
||||
│ 23 tools (the acts) │◀─── an MCP client's JSON-RPC
|
||||
│ 10 resources (the state)│
|
||||
└───────────────────────────┘
|
||||
```
|
||||
|
||||
Five pieces, deliberately separate, and a sixth that is deliberately not a
|
||||
Six pieces, deliberately separate, and a seventh that is deliberately not a
|
||||
piece at all:
|
||||
|
||||
1. **The compositor** (`Hyprland`, unchanged upstream) renders into virtual
|
||||
@@ -62,9 +70,20 @@ piece at all:
|
||||
a separate process because a Wayland client needs its own connection and a
|
||||
driver blocked on the compositor must not stall session lifecycle.
|
||||
|
||||
And the sixth, which is a *shim* and not a layer:
|
||||
6. **The stream daemon** (`hhstream-live`) publishes one session's output as
|
||||
MJPEG on one port, behind a four-word phrase, while somebody is connected.
|
||||
A third executor on the pointer driver's pattern and for its reasons: `grim`
|
||||
blocks tens to hundreds of milliseconds so it must not run where `touch` and
|
||||
`kill` are answered, and a LAN-facing HTTP parser must not run in the frame
|
||||
server whose one-socket contract cannot grow one. The broker owns the
|
||||
*decision* (which session, under which phrase, in the record); the daemon
|
||||
owns the port, the capture and the URL. It knows nothing about sessions or
|
||||
idle clocks — it publishes what it is told to publish, and reports a viewer
|
||||
count the broker chooses to read as activity.
|
||||
|
||||
6. **The MCP server** (`hhstream-mcp`, `docs/CONTRACT-mcp.md`) is the CLI with a
|
||||
And the seventh, which is a *shim* and not a layer:
|
||||
|
||||
7. **The MCP server** (`hhstream-mcp`, `docs/CONTRACT-mcp.md`) is the CLI with a
|
||||
Model Context Protocol surface on it, so an agent reads state by URI and
|
||||
acts by calling tools instead of writing command lines. It is drawn above
|
||||
the CLI rather than beside the broker because that is where it sits: every
|
||||
|
||||
+59
-8
@@ -1,4 +1,4 @@
|
||||
# CONTRACT — the MCP server (mcp-v2)
|
||||
# CONTRACT — the MCP server (mcp-v3)
|
||||
|
||||
This file is the interface of `hhstream-mcp`: the resource URIs, the tool names,
|
||||
the arguments each takes, what comes back, and which of the CLI's exit codes
|
||||
@@ -10,7 +10,19 @@ containers and the input lease).
|
||||
these argument shapes is a consumer like any other, and renaming a tool breaks
|
||||
it exactly as renaming a wire verb would.
|
||||
|
||||
Version: mcp-v2 (2026-10-11). v1 was the first freeze and lasted one day.
|
||||
Version: mcp-v3 (2026-10-11). v1 was the first freeze and lasted one day; v2
|
||||
split state out into resources; v3 adds the live stream. v3 is **additive** —
|
||||
every v2 name still means what it meant.
|
||||
|
||||
v3 changes, all of them the per-session live stream
|
||||
(`docs/CONTRACT-sessions.md` §4, v4):
|
||||
|
||||
| § | Change | Why |
|
||||
| --- | --- | --- |
|
||||
| §3 | Tools `session_stream_enable` and `session_stream_disable`. 21 tools became 23. | Switching a stream on is an *act*, and a consequential one: it publishes a desktop on the LAN behind a phrase. Nothing about it is a read. |
|
||||
| §3 | `session_start` gains `stream`, `stream_phrase` and `stream_fps`, and its reply carries the URL. | A stream needs the container output that starting creates, so sequencing start-then-enable in the caller means every caller repeats the ordering and the half-done case. One call, one answer, and the phrase comes back with the session. |
|
||||
| §4 | Resources `hhstream://streams` and `hhstream://sessions/{id}/stream`. 8 resources became 10. | What is being published, and who is watching, is state — so it is read, not called. |
|
||||
| §6 | A connected viewer is the **one exception** to the idle-clock rule. | About once a minute the broker stamps `touch` on any session somebody is watching. It is not a verb and cannot be invoked; it is the broker noticing that a person is looking. |
|
||||
|
||||
**v2 is a breaking change, and the only one: the verbs that merely read are
|
||||
resources now, not tools.**
|
||||
@@ -120,7 +132,7 @@ to an argv list.
|
||||
| family | tools |
|
||||
| --- | --- |
|
||||
| `frames` | `shot`, `record`, `run` |
|
||||
| `sessions` | `session_start`, `session_touch`, `session_kill`, `session_gc`, `session_adopt`, `session_container`, `session_reconcile` |
|
||||
| `sessions` | `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` |
|
||||
| `keyboard` | `keyboard_type`, `keyboard_key`, `keyboard_down`, `keyboard_up` |
|
||||
|
||||
@@ -154,13 +166,15 @@ running.
|
||||
|
||||
| Tool | Arguments |
|
||||
| --- | --- |
|
||||
| `session_start` | `app`, `argv?`, `idle_timeout?`, `wait_ready?`, `home?`, `ephemeral_home?`, `request_id?` |
|
||||
| `session_start` | `app`, `argv?`, `idle_timeout?`, `wait_ready?`, `home?`, `ephemeral_home?`, `stream?`, `stream_phrase?`, `stream_fps?`, `request_id?` |
|
||||
| `session_touch` | `id` |
|
||||
| `session_kill` | `id`, `grace?`, `signal?`, `request_id?` |
|
||||
| `session_gc` | `request_id?` |
|
||||
| `session_adopt` | `pid`, `app?`, `idle_timeout?`, `request_id?` |
|
||||
| `session_container` | `id` |
|
||||
| `session_reconcile` | `id?`, `request_id?` |
|
||||
| `session_stream_enable` | `id`, `phrase?`, `fps?` |
|
||||
| `session_stream_disable` | `id` |
|
||||
|
||||
Every one of these runs with `--json`, so what comes back is the broker's own
|
||||
protocol object: in the text part verbatim, and in `structuredContent` parsed.
|
||||
@@ -170,6 +184,21 @@ second wire format.
|
||||
`home` and `ephemeral_home` are mutually exclusive, and the schema says so —
|
||||
the CLI's argparse group, moved forward to where the refusal is free.
|
||||
|
||||
`session_stream_enable` returns the **URL** on the first line of its text part,
|
||||
because that is the whole point of the call: it is what gets handed to a person.
|
||||
It publishes the session's own container output and never the main one — that
|
||||
output carries every other session, and putting it behind one session's phrase
|
||||
is the mistake the broker refuses to make (exit 10 with no container). Re-enabling
|
||||
returns the same URL; a different `phrase` is exit 8, not a silent rotation,
|
||||
because rotating under somebody holding the old URL is the one outcome neither
|
||||
answer can be mistaken for. `session_stream_disable` is marked **destructive**:
|
||||
it forgets the phrase, so anyone holding that URL loses it.
|
||||
|
||||
`session_start` with `stream: true` is one call rather than two, and a stream
|
||||
that cannot be opened **does not fail the start** — the application is on the
|
||||
screen, and killing it over a web page would be the wrong trade. The reply
|
||||
carries `stream_error` whenever `stream` was asked for, `null` when it worked.
|
||||
|
||||
`session_container` is **not** marked read-only, and that is not an oversight:
|
||||
with an `id` the CLI runs `container.reconcile`, which writes the record back.
|
||||
That is also why it is a tool rather than a resource. The no-id listing, which
|
||||
@@ -232,6 +261,13 @@ verb a tool would have, with `--json` where the verb has it.
|
||||
| `hhstream://sessions/{id}` | `application/json` — one session with its recent audit events | `?events=N` |
|
||||
| `hhstream://sessions/{id}/logs` | `application/json` — the application's own captured output | `?lines=N` |
|
||||
| `hhstream://outputs/{name}` | one output captured alone, as an image blob. Exactly that output's configured size, which is the coordinate space the pointer tools aim in. | — |
|
||||
| `hhstream://streams` | `application/json` — every session a stream was enabled on, with its URL, rate and connected viewer count, plus `available` (whether the stream daemon answered) | — |
|
||||
| `hhstream://sessions/{id}/stream` | `application/json` — one session's stream, or `null`. `attached` is separate from `enabled`, and the URL is absent rather than stale when it is false. | — |
|
||||
|
||||
**The URLs in those two bodies contain their phrases**, which are the only thing
|
||||
protecting those streams. Both descriptions say so, because a host that puts
|
||||
`hhstream://streams` into a model's context has put a credential there — and
|
||||
the one place it must never go is anywhere the streamed session can see.
|
||||
|
||||
Rules this surface keeps:
|
||||
|
||||
@@ -349,13 +385,22 @@ in terms of this surface. They are on the individual tools and resources and
|
||||
not only in the server instructions, because a client shows a thing's own
|
||||
description at the point of use:
|
||||
|
||||
1. **`session_touch` is the only thing that resets a session's idle clock.**
|
||||
Reading `hhstream://sessions`, `hhstream://sessions/{id}` or its logs does
|
||||
not, `session_gc` does not, and neither does any pointer or keyboard tool. A
|
||||
1. **`session_touch` is the only thing a *caller* can do that resets a
|
||||
session's idle clock.** Reading `hhstream://sessions`,
|
||||
`hhstream://sessions/{id}` or its logs does not, `session_gc` does not, the
|
||||
stream tools do not, and neither does any pointer or keyboard tool. A
|
||||
session being driven is still a session nobody has said they want kept. The
|
||||
three resources it applies to say so in their own descriptions, because a
|
||||
resources it applies to say so in their own descriptions, because a
|
||||
description is what a host shows beside the thing it describes.
|
||||
|
||||
**The one exception is a connected viewer** (`docs/CONTRACT-sessions.md` §4,
|
||||
v4): about once a minute the broker stamps `touch` on any session somebody
|
||||
is watching through its live stream. It is not a tool and cannot be
|
||||
invoked — it is the broker noticing that a person is looking, which is the
|
||||
one form of "still wanted" that does not come down the control socket. It
|
||||
cannot hold a session open by itself: an enabled stream with no viewer
|
||||
captures nothing and stamps nothing.
|
||||
|
||||
2. **Every keyboard tool needs the pointer lease, and holds only while it
|
||||
holds.** There is no keyboard lease: one compositor seat means one keyboard
|
||||
focus. A held non-modifier key floods the window until it is lifted or the
|
||||
@@ -376,6 +421,12 @@ socket, the CLI and the broker are stdlib-only by policy. `packages.hhstream`
|
||||
must not grow that dependency; the root `pyproject.toml` excludes
|
||||
`hhstream_mcp*` from its package discovery so it cannot acquire it by accident.
|
||||
|
||||
The stream tools and the two stream resources additionally need
|
||||
`services.hyprland-headless-stream.sessions.stream.enable`, which runs the
|
||||
`hhstream-live` unit and gives the broker the socket it switches streams on
|
||||
over. Without it they answer exit 10 (`stream_unavailable`) — the session is
|
||||
unaffected, which is what that code means.
|
||||
|
||||
`services.hyprland-headless-stream.mcp.enable` (default `false`) puts the
|
||||
binary on the system PATH. That is the whole of the option: there is no unit, no
|
||||
socket and no state directory, because the server is spawned per client over
|
||||
|
||||
+3
-1
@@ -14,9 +14,11 @@ Each file answers three questions and stops:
|
||||
| [scroll-has-no-compositor-proof](scroll-has-no-compositor-proof.md) | medium | works live; unproven in a gate |
|
||||
| [reconcile-while-containers-are-off](reconcile-while-containers-are-off.md) | medium | partly fixed: discovery now survives a restart; teardown still lives inside the feature |
|
||||
| [kill-can-leave-the-app-alive](kill-can-leave-the-app-alive.md) | medium | found by counting windows, not sessions |
|
||||
| [capture-binary-and-the-unit-path](capture-binary-and-the-unit-path.md) | medium | found the first time the app was run as a unit: a unit's `PATH` has no `grim` |
|
||||
| [capture-binary-and-the-unit-path](capture-binary-and-the-unit-path.md) | medium | partly fixed: the module passes grim's store path and a check reads real frames; the app still never checks its capture binary |
|
||||
| [mcp-in-process-has-no-call-deadline](mcp-in-process-has-no-call-deadline.md) | medium | two costs of running the CLI in process: no killable deadline, and no `sg` recovery |
|
||||
| [mcp-resources-cannot-be-subscribed-to](mcp-resources-cannot-be-subscribed-to.md) | medium | the SDK hardcodes `subscribe=False`, so a log resource can only be re-read |
|
||||
| [stream-does-not-reattach-after-a-broker-restart](stream-does-not-reattach-after-a-broker-restart.md) | low | the phrase survives and the sweep works; `attached` reports false until re-enabled |
|
||||
| [a-stream-that-gave-up-still-reports-attached](a-stream-that-gave-up-still-reports-attached.md) | low | the other direction: a capture that permanently gave up still reads `LIVE: YES` |
|
||||
|
||||
Closed since this folder was written:
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# A stream whose capture gave up still reports `attached: true`
|
||||
|
||||
## The issue
|
||||
|
||||
`hhstream_live.publisher` stops a stream after `FAILURE_LIMIT` (10) consecutive
|
||||
capture failures, and the stop is sticky on purpose — the case it guards is an
|
||||
output that was removed, and that does not come back. The stream object stays in
|
||||
`StreamRegistry` with `stopped = True`; the HTTP handler returns as soon as it
|
||||
notices, so viewers are dropped and new ones get a page that ends immediately.
|
||||
|
||||
Nothing on the broker side can see that. `Control._describe` returns
|
||||
`spec.public()` plus `url` and `viewers` — not `stopped`, `captured`,
|
||||
`failures` or `last_frame_age_s`, all of which `Stream.status()` already
|
||||
computes. So `LiveStreams.list()` reports the phrase, `_attachments()` finds it
|
||||
and `_stream_public` sets `attached = True`. `hhstream session stream status`
|
||||
says `LIVE: YES` for a capture that has permanently given up.
|
||||
|
||||
MEASURED, in checks/vm-stream.nix, by the bug that check found: the
|
||||
`hhstream-live` unit had the compositor's group but not its environment, so
|
||||
every `grim` exited 1 with
|
||||
|
||||
error: XDG_RUNTIME_DIR is invalid or not set in the environment.
|
||||
|
||||
The unit was `active (running)`, the broker's record was intact, `stream status`
|
||||
said `attached: true` with a URL, and the only place the truth appeared was a
|
||||
single `WARNING` in the daemon's journal. The environment bug is fixed
|
||||
(`execLive` in nix/module.nix); the reporting gap it exposed is not.
|
||||
|
||||
## Ideas
|
||||
|
||||
1. **Carry the publisher's health through `list`.** *(recommended)* Add
|
||||
`stopped` and `last_frame_age_s` to `Control._describe` — both already exist
|
||||
on `Stream.status()` — parse them in `hhstreamd.live.Attachment`, and have
|
||||
`_stream_public` report `attached: false` (or a third state) when the daemon
|
||||
says the capture is dead. The cost is one more field pair in
|
||||
CONTRACT-sessions.md §3.5 and a `render_stream` line; the gain is that
|
||||
`attached` means what it was added to mean.
|
||||
2. **Drop a stopped stream from the registry.** Then `list` stops naming it and
|
||||
`attached` goes false for free, with no new fields. Rejected as the first
|
||||
move because it destroys the evidence: `failures` and the phrase are what an
|
||||
operator needs in order to understand what happened, and a 404 on the URL
|
||||
reads as "wrong phrase".
|
||||
3. **Leave it.** What ships. `stream disable` then `stream enable` revives it
|
||||
(a fresh `Stream`, same phrase, same URL), which is what an operator reaches
|
||||
for anyway, and the daemon's journal does say what happened.
|
||||
|
||||
## Why it matters
|
||||
|
||||
Low severity because the capture only gives up for a reason that is itself a
|
||||
failure — a removed output, a compositor that went away, a misconfigured unit —
|
||||
and in two of those three the session is in trouble in ways `status` does show.
|
||||
|
||||
It matters because `attached` exists specifically to separate "the operator
|
||||
asked for this" from "a capture is running right now" (CONTRACT-sessions.md
|
||||
§3.5), and this is the second case where it answers the second question wrongly;
|
||||
see [stream-does-not-reattach-after-a-broker-restart](stream-does-not-reattach-after-a-broker-restart.md)
|
||||
for the first. A field that is right only when nothing is wrong is not worth
|
||||
reading.
|
||||
@@ -27,6 +27,19 @@ worst way. The unit starts, the port opens, the landing page answers, and
|
||||
`"failures": 10`. A viewer sees an empty frame area and nothing else says why.
|
||||
Only the unit's log names the reason, one line above the giving-up entry.
|
||||
|
||||
**Half of this is now fixed.** The module passes grim's absolute store path
|
||||
(idea 1), checks/vm-stream.nix starts the unit and reads real JPEGs off the
|
||||
stream — the check this file asked for — and that check immediately found the
|
||||
sibling fault: the unit had the compositor's *group* but not its *environment*,
|
||||
so grim exited 1 with "XDG_RUNTIME_DIR is invalid or not set", ten times, with
|
||||
the same silence. Fixed too (`execLive`). What is still open is idea 2: the app
|
||||
resolves its capture command by name and never checks it, so a standalone
|
||||
`hhstream-live serve` and any deployment shape that is not this module still
|
||||
discover a missing or unusable capture binary ten failures later. The quiet
|
||||
half — a stream that gave up while the broker still reports it attached — has
|
||||
its own file now:
|
||||
[a-stream-that-gave-up-still-reports-attached](a-stream-that-gave-up-still-reports-attached.md).
|
||||
|
||||
## Ideas
|
||||
|
||||
1. **An absolute binary, as the module already does elsewhere** *(recommended)*.
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# A broker restart leaves an enabled stream recorded but not attached
|
||||
|
||||
## The issue
|
||||
|
||||
`docs/plans/2026-10-04-session-stream-webapp.md` §6 says what a restart should
|
||||
do:
|
||||
|
||||
> If `hhstream-live` is still up, the broker asks it for the list and
|
||||
> re-attaches them to the session records, so `status` and teardown still see
|
||||
> them.
|
||||
|
||||
Stage 2 did not build that half. What happens today, measured in
|
||||
`tests/sessions/unit/test_stream_verbs.py`
|
||||
(`test_a_down_daemon_turns_attached_false_rather_than_failing_the_read`) and by
|
||||
reading `SessionManager.startup`:
|
||||
|
||||
* the record keeps its phrase, so nothing is lost and a later `enable` restores
|
||||
the *same* URL — which is the property §4 exists for, and it works;
|
||||
* but `startup` does not call `LiveStreams.list()`, so the broker does not
|
||||
learn about streams the daemon is still publishing;
|
||||
* so `stream list` and `stream status` report `attached: false` for a stream
|
||||
that is, in fact, up and serving. The viewer sweep then skips it, because it
|
||||
only touches sessions whose phrase the daemon reports a viewer for — and it
|
||||
asks `viewers`, which *would* name it. So the sweep actually still works;
|
||||
what is wrong is the reporting.
|
||||
|
||||
The symptom is therefore narrow and confusing rather than broad: after
|
||||
`systemctl restart hhstream-sessions`, somebody watching a stream keeps
|
||||
watching it, the session keeps being touched, and `hhstream session stream
|
||||
list` says `LIVE: NO`. An operator reading that would reasonably `enable`
|
||||
again — which is harmless (`attach` is idempotent on the phrase) but should not
|
||||
be necessary.
|
||||
|
||||
The other half of §6 *is* implemented: if the daemon restarted too, the records
|
||||
keep their phrases and the streams stay off until re-enabled, because an open
|
||||
port and a running capture are explicit acts.
|
||||
|
||||
## Ideas
|
||||
|
||||
1. **Ask the daemon in `startup` and merge.** *(recommended)* One
|
||||
`LiveStreams.list()` where `reconcile_containers()` already runs, matching
|
||||
attachments to records by phrase. Small and local: `_stream_public` already
|
||||
merges an attachment into a record, so this is about *having* the
|
||||
attachments at start-up rather than only at read time. The one thing to get
|
||||
right is a phrase the daemon is publishing that no live record claims —
|
||||
which is the stream equivalent of an orphan `hh-*` output, and should
|
||||
probably be detached rather than adopted.
|
||||
2. **Ask on every read instead.** `_attachments()` already does, which is why
|
||||
the *reads* are nearly right. The reason it is not enough: there is no
|
||||
record-side state to update, so a restart's first `stream list` is correct
|
||||
and `attached` is still computed per call — this is really just (1) done
|
||||
lazily, and it hides the orphan case entirely.
|
||||
3. **Leave it.** What ships. The phrase survives, re-enabling is idempotent and
|
||||
costs one record write, and the sweep keeps working. The cost is a status
|
||||
field that lies after a restart.
|
||||
|
||||
## Why it matters
|
||||
|
||||
Low severity because nothing breaks and nothing is lost: the stream keeps
|
||||
serving, the viewer keeps being counted, and the fix an operator will reach for
|
||||
by instinct (`enable` again) is exactly the right one and is idempotent.
|
||||
|
||||
It matters at all because `attached` was added specifically so that "the
|
||||
operator asked for this" and "a capture is running right now" could be told
|
||||
apart — and after a restart it reports the second one wrongly, which is the one
|
||||
job that field has.
|
||||
@@ -175,12 +175,54 @@ one at a time; no browser in a VM check.
|
||||
3. **Port 9988**, fixed and single, no range fallback.
|
||||
4. **Capture pauses at zero viewers** (v1's choice, kept).
|
||||
|
||||
**Stage 1 is built** (`src/hhstream_live/`, `tests/live/`, 51 unit tests): the
|
||||
router, the pages, the phrase and the publisher, runnable standalone via
|
||||
`hhstream-live serve --stream PHRASE=OUTPUT`. The broker verbs and
|
||||
`/run/hhstream/live.sock` are Stage 2.
|
||||
**Stage 1 is built** (`src/hhstream_live/`, `tests/live/`): the router, the
|
||||
pages, the phrase and the publisher, runnable standalone via `hhstream-live
|
||||
serve --stream PHRASE=OUTPUT`.
|
||||
|
||||
**Stage 3 has started, out of order and on purpose** (2026-10-11). A machine
|
||||
**Stage 2 is built** (2026-10-11), and §5's surface is what shipped:
|
||||
`stream.enable|disable|list|status` on the control socket, `hhstream session
|
||||
stream …` on the CLI, the record field at **registry schema 4**,
|
||||
`/run/hhstream/live.sock` with `hhstreamd/live.py` on the broker's end and
|
||||
`hhstream_live/control.py` on the daemon's, the teardown order, and the viewer
|
||||
heartbeat. `docs/CONTRACT-sessions.md` went to **sessions-v4** for it.
|
||||
|
||||
Two decisions §5 left open, settled in the building:
|
||||
|
||||
1. **`start` takes `--stream`.** A stream needs the container output that
|
||||
starting creates, so "start, then enable" made every caller repeat the
|
||||
ordering and the half-done case in between. One call, and the URL comes
|
||||
back with the session id. A stream that cannot be opened does **not** fail
|
||||
the start — the application is on the screen, and `stream_error` says what
|
||||
went wrong.
|
||||
2. **The default rate is the daemon's, not the broker's.** §5 did not say who
|
||||
owns it, and the first cut had the broker send its own default on every
|
||||
attach — which would have made `sessions.stream.fps` a setting that changed
|
||||
nothing, the exact failure `--xkb-layout` exists to avoid. `fps` is now
|
||||
omitted from `attach` unless a caller named one.
|
||||
|
||||
What Stage 2 did **not** do: `stream.enable` carries no `--port`, and §6's
|
||||
restart re-attachment is not implemented. A broker restart leaves the records'
|
||||
phrases intact and their streams off until re-enabled, which is §6's own
|
||||
fallback ("an open port and a running capture are explicit acts") — but it does
|
||||
*not* ask a surviving daemon for its list and re-attach, so `attached` reads
|
||||
false until somebody enables again. Recorded in `docs/TODO/`.
|
||||
|
||||
**Stage 3 is built** (2026-10-11), the unit included — `hhstream-live.service`
|
||||
runs the app with `--control-socket`, the module's own capture command (`grim`
|
||||
is not on a unit's PATH), and `sessions.stream.{enable,fps,port,bind,openFirewall}`.
|
||||
What follows is why the firewall half landed first.
|
||||
|
||||
The unit has to be handed two things, and both were found by
|
||||
`checks/vm-stream.nix` rather than reasoned about: the capture command with
|
||||
grim's store path, because a unit's `PATH` has no `grim`; and the compositor's
|
||||
session — `XDG_RUNTIME_DIR` plus the `wayland-N` the compositor actually bound,
|
||||
discovered at start by `execLive`. Without the second the unit was
|
||||
`active (running)`, the broker attached, `stream status` said `attached: true`,
|
||||
and every capture exited 1 with "XDG_RUNTIME_DIR is invalid or not set" until
|
||||
the publisher gave up. Both failures are silent in the same way, which is why
|
||||
the check reads JPEG bytes instead of asserting a 200.
|
||||
|
||||
**Stage 3 started out of order and on purpose.** A machine
|
||||
had to be able to *reach* a stream before the rest of the app is settled: the
|
||||
operator asked for the port to be open on the deployment machine, where the app
|
||||
runs by hand, and a hand-written firewall line in one machine's config is the
|
||||
@@ -189,7 +231,12 @@ openFirewall }` and the single rule it stands for are in `nix/module.nix`, with
|
||||
`checks/vm-stream-firewall.nix` asking the *running* firewall — and a peer
|
||||
outside the guest — whether the configured port is the one that opened.
|
||||
|
||||
What that does **not** do: no unit, no phrases, no `session stream
|
||||
enable|disable|list|status`, and nothing in the module turns a stream on. The
|
||||
app is still started by hand, and the option's whole job is to describe where a
|
||||
stream will be reachable from.
|
||||
At the time that did **not** include a unit, phrases or the verbs; those are
|
||||
above. What is still true of it is the last sentence: nothing in the module
|
||||
turns a stream *on*. `sessions.stream.enable` runs a listener serving one form,
|
||||
and a stream exists only for the sessions somebody enabled it on.
|
||||
|
||||
**Stage 4 — the host pass — has not been done.** Nothing here has had a real
|
||||
browser pointed at it; `checks/vm-stream.nix` reads the MJPEG with a
|
||||
hand-rolled client inside the guest, which proves the framing and the capture
|
||||
but not that a phone paints it.
|
||||
+3
-3
@@ -14,7 +14,7 @@
|
||||
# `buildPythonApplication` output is not.
|
||||
#
|
||||
# `grim` and `ffmpeg` do go on PATH, because the CLI itself spawns them --
|
||||
# `shot --output` and `record` are two of the twenty-one tools, and the server
|
||||
# `shot --output` and `record` are two of the twenty-three tools, and the server
|
||||
# is launched by an MCP client whose PATH is not ours to predict. `--prefix`
|
||||
# and not `--set`, so a deployment that wants its own ahead of these puts them
|
||||
# on PATH and wins.
|
||||
@@ -89,11 +89,11 @@ python3.pkgs.buildPythonApplication {
|
||||
echo "checking the wrapped entry point..."
|
||||
tools=$($out/bin/hhstream-mcp --list-tools)
|
||||
echo "$tools"
|
||||
test "$(echo "$tools" | wc -l)" -eq 21
|
||||
test "$(echo "$tools" | wc -l)" -eq 23
|
||||
|
||||
resources=$($out/bin/hhstream-mcp --list-resources)
|
||||
echo "$resources"
|
||||
test "$(echo "$resources" | wc -l)" -eq 8
|
||||
test "$(echo "$resources" | wc -l)" -eq 10
|
||||
|
||||
narrowed=$($out/bin/hhstream-mcp --list-tools --toolsets keyboard | wc -l)
|
||||
echo "--toolsets keyboard offers $narrowed tools"
|
||||
|
||||
+2
-2
@@ -989,8 +989,8 @@ in {
|
||||
# to declare.
|
||||
environment.systemPackages = lib.mkIf cfg.mcp.enable [ cfg.mcp.package ];
|
||||
|
||||
# A warning and not an assertion: eighteen of the twenty-one tools and six
|
||||
# of the eight resources need the broker, and an agent handed them against
|
||||
# A warning and not an assertion: twenty of the twenty-three tools and
|
||||
# seven of the ten resources need the broker, and an agent handed them against
|
||||
# a machine where it is off gets exit 5 from every one of them -- which is
|
||||
# a true answer, badly timed. The frame tools are genuinely useful on their
|
||||
# own, so this is a thing worth saying rather than a thing worth refusing.
|
||||
|
||||
@@ -359,6 +359,24 @@ ENTRIES: tuple[Entry, ...] = (
|
||||
media_type=JSON,
|
||||
read=_json_read(["session", "container"], "the container list"),
|
||||
),
|
||||
Entry(
|
||||
route=("streams",),
|
||||
name="streams",
|
||||
title="What is being published, and who is watching",
|
||||
description=(
|
||||
"Every session a live stream was enabled on, with its output, "
|
||||
"rate, URL and connected viewer count -- and `available`, which "
|
||||
"says whether the stream daemon could be asked at all, so 'no "
|
||||
"streams' is distinguishable from 'no daemon'.\n\n"
|
||||
"THE URLS HERE CONTAIN THEIR PHRASES, which are the only thing "
|
||||
"protecting those streams. Do not put this where a session's own "
|
||||
"screen can see it." + _NOT_ACTIVITY + " A connected viewer, "
|
||||
"however, does: that is the one exception, and it is why a "
|
||||
"session somebody is watching is not reaped."
|
||||
),
|
||||
media_type=JSON,
|
||||
read=_json_read(["session", "stream", "list"], "the stream list"),
|
||||
),
|
||||
Entry(
|
||||
route=("screen",),
|
||||
name="screen",
|
||||
@@ -405,6 +423,26 @@ ENTRIES: tuple[Entry, ...] = (
|
||||
read=_json_read(["session", "logs"], "that session's logs"),
|
||||
parameters=("lines",),
|
||||
),
|
||||
Entry(
|
||||
route=("sessions", "{id}", "stream"),
|
||||
name="session-stream",
|
||||
title="One session's live stream",
|
||||
description=(
|
||||
"Whether this session is being published, and if so the URL to "
|
||||
"watch it at, the output it shows, its frame rate and how many "
|
||||
"people are connected right now. `null` when no stream was "
|
||||
"enabled.\n\n"
|
||||
"`attached` is separate from `enabled` on purpose: a record can "
|
||||
"say the operator asked for a stream while the daemon is down, "
|
||||
"and those are two different facts. The URL is absent rather than "
|
||||
"stale when `attached` is false.\n\n"
|
||||
"THE URL CONTAINS THE PHRASE that protects it. Switch a stream on "
|
||||
"with the `session_stream_enable` tool -- reading this never "
|
||||
"enables one." + _NOT_ACTIVITY
|
||||
),
|
||||
media_type=JSON,
|
||||
read=_json_read(["session", "stream", "status"], "that session's stream"),
|
||||
),
|
||||
Entry(
|
||||
route=("outputs", "{name}"),
|
||||
name="output",
|
||||
|
||||
+160
-5
@@ -31,7 +31,7 @@ with an ``action`` enum. Three reasons, in order of weight:
|
||||
3. ``readOnlyHint`` is per tool and is still a real distinction among what is
|
||||
left: ``shot`` reads, ``session_kill`` destroys, ``record`` writes a file.
|
||||
|
||||
The cost is twenty-one tools in one listing, and :data:`TOOLSETS` is the lever
|
||||
The cost is twenty-three tools in one listing, and :data:`TOOLSETS` is the lever
|
||||
for a client that cannot afford them all. It is paid back by the names being
|
||||
the CLI's own: an agent that has read ``hhstream session --help``, or this
|
||||
repository's README, already knows what ``session_touch`` is, and a transcript
|
||||
@@ -104,6 +104,19 @@ HOLD_NOTE = (
|
||||
"`keyboard_up Control_L`."
|
||||
)
|
||||
|
||||
STREAM_NOTE = (
|
||||
"CREDENTIAL: the phrase in the stream's URL is its only protection -- no "
|
||||
"TLS, no second factor. Anyone who can reach the port and guess four "
|
||||
"words can watch this session's screen. Treat the URL as a password: do "
|
||||
"not put it anywhere the session's own output goes. It is never written "
|
||||
"to the broker's audit log.\n\n"
|
||||
"ACTIVITY: the stream tools do NOT reset the idle clock -- but A "
|
||||
"CONNECTED VIEWER DOES. About once a minute the broker stamps `touch` on "
|
||||
"any session somebody is watching, which is the one exception to "
|
||||
"`session_touch` being the only mark of activity. An enabled stream with "
|
||||
"nobody watching captures nothing and keeps nothing alive."
|
||||
)
|
||||
|
||||
COORDINATES_NOTE = (
|
||||
"Coordinates are OUTPUT-NORMALISED 0..1 inside the session's own "
|
||||
"container: (0,0) is its top-left corner and (1,1) its bottom-right. They "
|
||||
@@ -516,15 +529,58 @@ def _acquire_summary(outcome: Outcome, payload: dict[str, Any] | None) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _start_summary(outcome: Outcome, payload: dict[str, Any] | None) -> str:
|
||||
session_id = (payload or {}).get("id") or "(not reported)"
|
||||
def _stream_summary(outcome: Outcome, payload: dict[str, Any] | None) -> str:
|
||||
"""The URL on the first line: it is the whole point of the call."""
|
||||
|
||||
stream = (payload or {}).get("stream") or {}
|
||||
url = stream.get("url")
|
||||
if not url:
|
||||
return (
|
||||
"the broker recorded this stream but the daemon did not confirm "
|
||||
"it is attached, so there is no URL to hand out yet; read "
|
||||
"`hhstream://streams` and retry if it stays that way."
|
||||
f"\n\n{outcome.stdout.strip()}"
|
||||
)
|
||||
return (
|
||||
f"session id: {session_id}\n"
|
||||
f"Keep it alive with `session_touch` before its idle timeout expires.\n\n"
|
||||
f"{url}\n"
|
||||
"Hand that URL to whoever is watching. Its phrase is the only thing "
|
||||
"protecting it, so do not put it anywhere this session's own screen "
|
||||
"can see. Somebody watching counts as activity; `session_stream_"
|
||||
"disable` stops it.\n\n"
|
||||
f"{outcome.stdout.strip()}"
|
||||
)
|
||||
|
||||
|
||||
def _start_summary(outcome: Outcome, payload: dict[str, Any] | None) -> str:
|
||||
"""The id first, and the stream's URL beside it when one was asked for.
|
||||
|
||||
Both on the first lines, because both are what the next step needs: the id
|
||||
to drive the session, the URL to hand to a person.
|
||||
"""
|
||||
|
||||
session = payload or {}
|
||||
session_id = session.get("id") or "(not reported)"
|
||||
lines = [f"session id: {session_id}"]
|
||||
stream = session.get("stream") or {}
|
||||
if stream.get("url"):
|
||||
lines.append(f"stream url: {stream['url']}")
|
||||
lines.append(
|
||||
"That URL's phrase is its only protection -- treat it as a "
|
||||
"password. Somebody watching it counts as activity."
|
||||
)
|
||||
elif session.get("stream_error"):
|
||||
# Loudly, because the call succeeded: a caller that asked for a stream
|
||||
# must not read a session id as one.
|
||||
lines.append(
|
||||
f"stream: NOT enabled -- {session['stream_error']}. The session is "
|
||||
"running; retry with `session_stream_enable`."
|
||||
)
|
||||
lines.append(
|
||||
"Keep it alive with `session_touch` before its idle timeout expires."
|
||||
)
|
||||
return "\n".join(lines) + f"\n\n{outcome.stdout.strip()}"
|
||||
|
||||
|
||||
def build() -> tuple[Tool, ...]:
|
||||
"""The whole surface. A function, so the table is built once per process."""
|
||||
|
||||
@@ -712,6 +768,33 @@ def _session_tools() -> list[Tool]:
|
||||
"the session ends. Mutually exclusive with `home`."
|
||||
),
|
||||
},
|
||||
"stream": {
|
||||
"type": "boolean",
|
||||
"description": (
|
||||
"also enable a live stream for this session, and "
|
||||
"return its URL in the reply's `stream.url`. One "
|
||||
"call rather than start-then-enable, because a "
|
||||
"stream needs the container output that starting "
|
||||
"creates. A stream that cannot be opened does NOT "
|
||||
"fail the start -- the application is on the "
|
||||
"screen, and `stream_error` says what went wrong."
|
||||
),
|
||||
},
|
||||
"stream_phrase": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"use this phrase instead of a minted one: four "
|
||||
"words of at least three letters and a "
|
||||
"five-character tail, e.g. "
|
||||
"`amber-otter-lantern-harbor-7k2qp`. Held to "
|
||||
"exactly that shape, because it is a password."
|
||||
),
|
||||
},
|
||||
"stream_fps": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "frames per second for the stream (default: the broker's)",
|
||||
},
|
||||
"request_id": REQUEST_ID,
|
||||
},
|
||||
["app"],
|
||||
@@ -728,6 +811,9 @@ def _session_tools() -> list[Tool]:
|
||||
*_optional(a, "wait_ready", "wait-ready"),
|
||||
*_optional(a, "home"),
|
||||
*_switch(a, "ephemeral_home", "ephemeral-home"),
|
||||
*_switch(a, "stream"),
|
||||
*_optional(a, "stream_phrase", "stream-phrase"),
|
||||
*_optional(a, "stream_fps", "stream-fps"),
|
||||
*_optional(a, "request_id", "request-id"),
|
||||
],
|
||||
positionals=lambda a: [a["app"], *[str(x) for x in a.get("argv") or []]],
|
||||
@@ -872,6 +958,73 @@ def _session_tools() -> list[Tool]:
|
||||
positionals=lambda a: [a["id"]] if a.get("id") else [],
|
||||
),
|
||||
),
|
||||
Tool(
|
||||
name="session_stream_enable",
|
||||
title="Publish a session's screen",
|
||||
description=(
|
||||
"Switch on a live view of this session's screen, in a browser, "
|
||||
"at a URL whose path is a spoken phrase -- and return that "
|
||||
"URL. This is how a person watches what an agent is doing.\n\n"
|
||||
"It publishes the session's own container output, never the "
|
||||
"main one: that output carries every other session, and "
|
||||
"putting it behind one session's phrase is the mistake this "
|
||||
"refuses to make (exit 10 with no container).\n\n"
|
||||
"Re-enabling an already-enabled session returns the same URL. "
|
||||
"A `phrase` that differs from the stored one is exit 8 rather "
|
||||
"than a silent rotation, because rotating under somebody who "
|
||||
"is holding the old URL is the one outcome neither answer can "
|
||||
"be mistaken for. Disable then enable to rotate it.\n\n"
|
||||
"Capture runs only while somebody is connected, so an enabled "
|
||||
"stream nobody is watching costs nothing.\n\n"
|
||||
f"{STREAM_NOTE}"
|
||||
),
|
||||
schema=obj(
|
||||
{
|
||||
"id": SESSION_ID,
|
||||
"phrase": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"use this phrase instead of a minted one: four "
|
||||
"words of at least three letters and a "
|
||||
"five-character tail. Held to exactly that shape, "
|
||||
"because it is this stream's only credential."
|
||||
),
|
||||
},
|
||||
"fps": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"description": "frames per second (default: the broker's; the daemon caps it)",
|
||||
},
|
||||
},
|
||||
["id"],
|
||||
),
|
||||
invoke=json_verb(
|
||||
["session", "stream", "enable"],
|
||||
options=lambda a: [*_optional(a, "phrase"), *_optional(a, "fps")],
|
||||
positionals=lambda a: [a["id"]],
|
||||
summary=_stream_summary,
|
||||
),
|
||||
),
|
||||
Tool(
|
||||
name="session_stream_disable",
|
||||
title="Stop publishing a session's screen",
|
||||
description=(
|
||||
"Close the capture, drop the route, and forget the phrase. "
|
||||
"Anyone holding the old URL loses it, which is the point: "
|
||||
"this is also how a phrase is rotated, since the next enable "
|
||||
"mints a new one.\n\n"
|
||||
"Disabling a stream the daemon has already forgotten is not an "
|
||||
"error -- that is the ordinary case after the daemon restarts, "
|
||||
"and the record is cleared either way. `detached` says which "
|
||||
"happened.\n\n"
|
||||
f"{ACTIVITY_NOTE}"
|
||||
),
|
||||
schema=obj({"id": SESSION_ID}, ["id"]),
|
||||
invoke=json_verb(
|
||||
["session", "stream", "disable"], positionals=lambda a: [a["id"]]
|
||||
),
|
||||
destructive=True,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@@ -1214,6 +1367,8 @@ TOOLSETS: dict[str, tuple[str, ...]] = {
|
||||
"session_adopt",
|
||||
"session_container",
|
||||
"session_reconcile",
|
||||
"session_stream_enable",
|
||||
"session_stream_disable",
|
||||
),
|
||||
"pointer": (
|
||||
"pointer_acquire",
|
||||
|
||||
@@ -1018,6 +1018,9 @@ class SessionManager:
|
||||
if session.live:
|
||||
await self._read_back(session, app_id)
|
||||
stream_error: str | None = None
|
||||
#: The daemon's view of the stream, which is the only place a `url`
|
||||
#: exists. Locals and not attributes, for the reason below.
|
||||
stream_public: dict[str, Any] | None = None
|
||||
if stream and session.live:
|
||||
# After the read-back, because that is what settles the container's
|
||||
# output, and a stream has to have one to publish
|
||||
@@ -1032,9 +1035,10 @@ class SessionManager:
|
||||
# be the wrong trade; the refusal is reported on the session's
|
||||
# `stream_error` and the caller can retry `stream.enable`.
|
||||
try:
|
||||
await self.stream_enable(
|
||||
enabled = await self.stream_enable(
|
||||
session.id, phrase=stream_phrase, fps=stream_fps
|
||||
)
|
||||
stream_public = enabled.get("stream")
|
||||
except ManagerError as exc:
|
||||
log.warning("could not enable %s's stream: %s", session.id, exc.reason)
|
||||
session.last_error = session.last_error or exc.reason
|
||||
@@ -1049,6 +1053,19 @@ class SessionManager:
|
||||
# a key that appears only on failure is a key every caller has to
|
||||
# remember to look for.
|
||||
record["stream_error"] = stream_error
|
||||
if stream_public is not None:
|
||||
# The daemon's view, not the record's. `Session.public()`
|
||||
# reports what was stored, and a `url` is never stored --
|
||||
# naming one is the daemon's (§3.5), and a URL on disk is a URL
|
||||
# that lies after the listener moves. So a successful
|
||||
# `start --stream` that answered with `session.public()` alone
|
||||
# handed back a stream with no URL, which a caller cannot tell
|
||||
# from one that failed to open.
|
||||
#
|
||||
# MEASURED in checks/vm-stream.nix: the daemon attached, the
|
||||
# broker recorded it, and the CLI printed "the session is
|
||||
# running but its stream was not enabled".
|
||||
record["stream"] = stream_public
|
||||
if session.state == State.EXITED:
|
||||
# The app exited during the settle: surface it rather than handing
|
||||
# back a healthy-looking id (DESIGN.md §7 #3).
|
||||
|
||||
@@ -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,541 @@
|
||||
"""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_url_is_the_daemon_s_and_is_not_in_the_record(harness):
|
||||
"""So anything answering with the record alone must merge the reply in.
|
||||
|
||||
REGRESSION. `start --stream` built its answer from `Session.public()`,
|
||||
which reports what was *stored* -- and a `url` is never stored, because
|
||||
naming one is the daemon's (CONTRACT-sessions.md §3.5). The result was a
|
||||
successful start whose stream had no URL, which the CLI could not tell
|
||||
from a stream that failed to open: it printed "the session is running but
|
||||
its stream was not enabled" over a stream the daemon had just attached.
|
||||
Found by checks/vm-stream.nix, which is also where the `start --stream`
|
||||
path is proven end to end -- there is no launcher here.
|
||||
"""
|
||||
|
||||
harness.add()
|
||||
reply = harness.run(harness.manager.stream_enable("foot-aaaaaa"))
|
||||
|
||||
assert reply["stream"]["url"]
|
||||
stored = harness.manager.registry.get("foot-aaaaaa").public(harness.clock.boottime())
|
||||
assert stored["stream"]["phrase"] == reply["stream"]["phrase"]
|
||||
assert "url" not in stored["stream"]
|
||||
|
||||
|
||||
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