Files
HermenixandClaude Opus 5 4af6f7072a server, client: implement the v1 frame protocol end to end
Fill in the bodies the skeleton left as NotImplementedError, to docs/CONTRACT.md:

- protocol: the `\n`-terminated JSON Hello and the `<ascii length>\n<payload>`
  frame, both directions. Malformed input raises (ValueError for a bad length
  prefix, EOFError for a truncated payload), never hangs on endless garbage and
  never silently truncates; a huge length prefix is not pre-allocated.
- capture: CommandCapture runs the configured command and reports a missing
  binary, a non-zero exit, a timeout and empty output as CaptureError, with the
  helper's stderr folded into the message so nothing leaks to the server's own
  stdio. The Hello's pixel size is read from the frame's PNG/JPEG header, so no
  compositor query is needed and an injected fake command behaves the same.
- server: one capture thread holding only the newest frame plus one thread per
  client, which is what drops frames for a slow client instead of queueing
  them. Survives a client dying mid-write, keeps the socket up across capture
  failures, withholds the Hello until a size is known, replaces a stale socket
  file (but never a non-socket one) and publishes it mode 0660.
- client: fetch()/read_stream() and the CLI, with --out suffixing per frame.

--capture-command folds its separated form into `--flag=value` before argparse
sees it, so the contract's default `grim -t png -` can actually be passed: its
tokens start with a dash.

Unit tests under tests/unit cover framing round-trips (including a payload
containing `\n` and a zero-length frame), truncated and garbage prefixes, a
stalled client not blocking a second one, a client dying mid-frame, frames being
dropped rather than queued, and every capture failure mode. A fake capture
command stands in for grim, so nothing needs a compositor or a GPU. They are
deliberately not wired into flake.nix: `checks` belongs to another workstream.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FYJ8ZQ5AZaDErYTwXZe7N9
2026-09-28 05:35:17 +00:00

117 lines
4.1 KiB
Python

"""The capture backend, driven by the fake capture command (no compositor)."""
from __future__ import annotations
import os
import sys
import pytest
from helpers import FAKE_CAPTURE, png_bytes
from hhstream.capture import CaptureError, CommandCapture, image_size
def fake(*flags: str) -> list[str]:
return [*FAKE_CAPTURE, *flags]
def test_grab_returns_the_frame_and_size_comes_from_its_header():
capture = CommandCapture(fake("--width", "1280", "--height", "720"))
frame = capture.grab()
assert frame.startswith(b"\x89PNG\r\n\x1a\n")
assert capture.size() == (1280, 720)
def test_size_grabs_once_when_nothing_has_been_captured_yet():
capture = CommandCapture(fake("--width", "64", "--height", "32"))
assert capture.size() == (64, 32)
def test_a_failing_command_raises_and_reports_its_stderr(capfd):
capture = CommandCapture(fake("--fail", "--message", "grim: no outputs"))
with pytest.raises(CaptureError) as excinfo:
capture.grab()
assert "exited 3" in str(excinfo.value)
assert "grim: no outputs" in str(excinfo.value)
out, err = capfd.readouterr()
assert (out, err) == ("", ""), "the helper must not write to our stdio"
def test_empty_output_is_a_failure_not_an_empty_frame(capfd):
with pytest.raises(CaptureError) as excinfo:
CommandCapture(fake("--empty")).grab()
assert "no output" in str(excinfo.value)
assert capfd.readouterr() == ("", "")
def test_a_hanging_command_times_out():
capture = CommandCapture(fake("--delay", "10"), timeout=0.5)
with pytest.raises(CaptureError) as excinfo:
capture.grab()
assert "timed out" in str(excinfo.value)
def test_a_missing_command_is_a_capture_error():
with pytest.raises(CaptureError) as excinfo:
CommandCapture(["hhstream-no-such-program"]).grab()
assert "could not be run" in str(excinfo.value)
def test_unmeasurable_output_cannot_produce_a_hello():
capture = CommandCapture(fake("--garbage"))
assert capture.grab() == b"fake_capture: not an image, sorry\n"
with pytest.raises(CaptureError) as excinfo:
capture.size()
assert "pixel size" in str(excinfo.value)
def test_a_failure_after_a_good_frame_keeps_the_known_size():
good = CommandCapture(fake("--width", "100", "--height", "50"))
assert good.size() == (100, 50)
good.argv = fake("--fail")
with pytest.raises(CaptureError):
good.grab()
assert good.size() == (100, 50)
def test_env_is_overlaid_on_our_own_environment():
argv = [sys.executable, "-c",
"import os,sys;sys.stdout.write(os.environ['WAYLAND_DISPLAY']+':'+"
"('PATH' in os.environ and 'haspath' or 'nopath'))"]
capture = CommandCapture(argv, env={"WAYLAND_DISPLAY": "wayland-9"})
assert capture.grab() == b"wayland-9:haspath"
assert "WAYLAND_DISPLAY" not in os.environ, "our own environment was mutated"
def test_empty_argv_and_bad_timeout_are_rejected_up_front():
with pytest.raises(ValueError):
CommandCapture([])
with pytest.raises(ValueError):
CommandCapture(["true"], timeout=0)
def test_the_helpers_stdin_is_closed_so_it_cannot_steal_ours():
code = ("import sys;"
"sys.stdout.buffer.write(b'EMPTY' if not sys.stdin.read() else b'DATA')")
assert CommandCapture([sys.executable, "-c", code]).grab() == b"EMPTY"
@pytest.mark.parametrize("width,height", [(1, 1), (16, 9), (3840, 2160)])
def test_image_size_reads_png_headers(width, height):
assert image_size(png_bytes(width, height)) == (width, height)
def test_image_size_reads_a_jpeg_sof_header():
jpeg = (b"\xff\xd8"
+ b"\xff\xe0" + (16).to_bytes(2, "big") + b"JFIF\x00" + b"\x00" * 9
+ b"\xff\xc0" + (17).to_bytes(2, "big") + b"\x08"
+ (720).to_bytes(2, "big") + (1280).to_bytes(2, "big")
+ b"\x03" + b"\x00" * 9)
assert image_size(jpeg) == (1280, 720)
@pytest.mark.parametrize("data", [b"", b"not an image", b"\x89PNG\r\n\x1a\n",
b"\xff\xd8", b"\xff\xd8\xff\xc0\x00\x11"])
def test_image_size_returns_none_when_it_cannot_tell(data):
assert image_size(data) is None