Compare commits

..
Author SHA1 Message Date
HermenixandClaude Opus 5 de408e4b7f the surface: CLI verbs, the module's options, and three checks the compositor votes in
Everything below the CLI was merged and green against fakes; none of it was
reachable and none of it had ever met a compositor. This wires it up and then
puts the compositor in a position to disagree.

CLI (src/hhstream/cli.py, src/hhstream_session/**)

  session container [ID], session reconcile [ID], and the seven pointer verbs
  from PLAN §9. `start` still prints the bare session id and nothing else.
  `list` gains WS / OUTPUT / POINTER, with the gap marker where a value is
  genuinely unknown rather than a blank that reads as zero -- the POINTER
  column needs a second, read-only `pointer.state` call because the `list`
  reply carries no lease state.

  The lease id is cached in `hhstream_session.lease` (under
  $XDG_RUNTIME_DIR), because PLAN §9's gesture verbs take no --lease and the
  wire requires a lease_id on every one of them; --lease and $HHSTREAM_LEASE
  override it, and a `no_lease` refusal drops the stale entry.

  Exit codes are the contract's: a gesture with no lease is 9 and never
  reaches the broker, and a compositor failure is 10 with a message that says
  the session is still running. `kill` now warns about
  `session.container_survivors` -- windows the compositor still shows -- and
  distinguishes `null` ("could not ask") from `[]`.

  `shot`/`record --output NAME` capture one container through `grim -o`; the
  frame socket publishes the main output only, so it cannot do it.

Module (nix/module.nix)

  sessions.containers.{enable,max,mode,workspaceBase},
  sessions.pointer.{enable,leaseTtl,leaseMax}, rendered into the generated
  TOML with §10's key names. hhstream-pointer.service: the operator's account,
  supplementary group hhstream, After=/BindsTo= the compositor,
  Restart=on-failure, KillMode=process, and the command line §3.4 freezes.
  tmpfiles for /run/hhstream plus RuntimeDirectoryPreserve on the broker,
  without which restarting the broker deletes the driver's socket out from
  under it. The runtime-directory length assertion is untouched.

  And ExecStartPost on the compositor, opening its IPC directory to its own
  group: Hyprland creates <runtime>/hypr with S_IRWXU, so the broker -- a
  different account by design -- could not reach the request or event socket
  at all, and degraded silently exactly as it is built to.

Checks (checks/**)

  vm-ipc: both sockets at their frozen names, measured against sun_path's 108
  bytes, and a socket2 subscriber that receives an openwindow for a window the
  test creates. The subscriber is the shipped HyprlandIPC, not a second
  implementation: this check exists to prove that this client hears this
  compositor.

  vm-containers: one hh-* output per session at the container mode, the window
  on it, a second window of the same application beside it, an unmatched
  window quarantined, grim -o isolating one container, teardown removing the
  output and freeing the slot. PLAN experiment 3 is answered: `hyprctl output
  create headless` works.

  vm-pointer: a version-2 virtual pointer, a warp and a click whose
  coordinates the *application* reports, BUSY naming the holder, 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.

  checks/lib gains the guest the three share, their test-script helpers (no
  assertions live there), an event-socket subscriber and a Wayland client that
  says where it was clicked -- nothing in nixpkgs both honours
  $HHSTREAM_APP_ID and reports pointer events.

Reported, not worked around: the broker reads none of the container or
pointer config (policy.py takes [defaults] and [apps] only), `start` has no
no_container field so --no-container is refused rather than silently ignored,
and nix/hyprland-conf.nix sets input:follow_mouse = 0, which sends pointer
events to the focused window only -- measured, with the cursor at the aimed
pixel and no client told. README.dev.md has the evidence for each.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WQy29x9AfHWyzNd1f7XPGK
2026-10-03 06:58:44 +00:00
Hermenix 57fdd4f636 ipc: Monitor gains the id that CONTRACT-sessions v2 promised
The contract bump added Monitor.id and nobody implemented it: slice B predates
v2, so the integration slice had to join a client to its output through
Workspace.monitor instead. Field added, parsed from `monitors -j`, and -1 when a
reply omits it -- a missing id must not default to 0, which would silently bind
every such client to the first output.

Two tests: the id is parsed, and omitting it yields -1.
2026-10-03 04:51:07 +00:00
Hermenix 39f0180d2d merge integration/broker-wiring into main
The four modules built against the frozen contract finally have a caller. Record
schema 3 with migration, container lifecycle (create on start, teardown on kill,
reap, gc and unprompted exit, reconcile at start-up), the pointer verbs over the
lease with a 1s expiry sweep, quarantine_argv, and the new wire verbs and error
codes.

Its own report is explicit that the fake compositor proves the broker's half
only; whether Hyprland accepts these commands is the VM checks' question.
2026-10-03 04:48:26 +00:00
HermenixandClaude Opus 5 129430bffd wire the broker to the compositor, containers and pointer
The four slices existed and nothing called them. Now the broker builds a
spatial container per session, reads back what the compositor actually did,
and aims the cursor into one container under a broker-wide lease.

Record schema 3 (registry.py): `container` {output, workspace, mode,
created_by, state}, `pointer` {bookmark, last_released_at, released_by} and
the compositor's `signature`. A v2 record is migrated on load, not refused —
its application is still running. Every field that could not be verified is
null; `container: null` means "no container", never "probably something".

Containers (new container_host.py, manager.py, launcher.py): `start`
allocates a slot from `WorkspaceAllocator`, runs `container_plan()`'s argv,
launches the app with the container stamp in its environment, then reads the
workspace, output and window back out of `clients -j`. Teardown removes the
output, releases the slot and reports survivors rather than claiming success
— and runs for an unprompted exit and for `gc` too, so no container is ever
left unattended. Broker start-up reconciles: adopt `hh-*` outputs a live
session claims, remove the rest, `contains_output()` being the only filter.
No IPC means `container: degraded` and lifecycle verbs unchanged.

The plans' argv are dispatched over the compositor's request socket rather
than by executing `hyprctl`, which is what hyprctl does with the same words;
the reply is checked, so a refused command is not recorded as a container.

Pointer (new driver.py, manager.py): a client for the driver's private
socket, and `pointer.acquire|move|button|click|release|state` on top of
`PointerLease`. The broker owns the lease, the driver executes. The bookmark
is marked on every move and before release and stored in the record, so it
survives a restart. On expiry `pressed()` is read before `expire()` and
`release_all` goes to the driver, because the lease cannot lift a button
itself; a sweep runs unprompted so the TTL is a promise.

containers.py to v2: `quarantine_plan()` -> `quarantine_argv()`, with the
before-any-per-session-rule ordering stated where the caller could get it
wrong. protocol.py: 9 NO_LEASE, 10 COMPOSITOR, the verb table, and the
`request_id` cache moved out of the server so the CLI agrees with it.

Tests: real AF_UNIX everywhere — a stateful fake compositor and the shipped
pointer driver behind a recording sink. No mocked sockets, no compositor, no
VM. 551 -> 693.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017mUq7QvQ9EZb2Wi35xj4cs
2026-10-02 19:47:33 +00:00
Hermenix 20b2aee109 unit check: run the whole tests/ tree, not just tests/unit
The check took ../tests/unit alone, so the broker's, the pointer driver's and the
sessions suites were collected by no check at all -- 432 of 551 tests ran only
when someone happened to enter the dev shell. It now takes ../tests, which
surfaced two real defects in the harness rather than in the code:

- tests/sessions/integration/test_lifecycle.py locates the repository by looking
  upward for a pyproject.toml, which a build has no reason to contain; it raised
  at import and took the whole run down as a collection error. The check now
  copies the marker in, which is what the test documents it needs.

- That file also REPLACED PYTHONPATH for the daemon it spawns instead of
  prepending to it. In a checkout src/ is the package, so it worked; under a
  build it discarded the package under test, and 'python -m hhstreamd' died at
  startup with an ImportError -- reported as a daemon failure on every test in
  the file. Prepending is the fix, and the right behaviour anywhere.

pywayland joins the test environment because the pointer driver imports it.

unit: 551 collected, 550 passed, 1 skipped (a deliberate skip).
2026-10-02 18:14:48 +00:00
Hermenix e8b3855a05 move every live default to /run/hypr-stream, and resolve the slices' contract gaps
Slice A renamed the runtime directory in the module, but the old path was still
live in the code and checks it does not own, so the VM gates pointed at a
directory the module no longer creates. This moves the 21 remaining live
occurrences (client/server defaults, the unit tests that pin them, all three VM
checks, the diagnostics script, both READMEs) and deliberately leaves the three
mentions that are history rather than configuration: the plan's problem
statement, module.nix's note about the previous name, and cli.py's explanation
for spelling its default out.

Also here: docs/CONTRACT-sessions.md is now v2 with every gap the four slices
reported resolved as a decision (Monitor.id, stable_id, pid -1, Event.data,
mark(), the quarantine argv type, the corrected wlr XML path, and the state
dir/frame socket rows), and docs/CONTRACT.md is v2 because its documented socket
default moved -- wire format unchanged.

Two comments that stated the old, wrong diagnosis (a 'misnamed' IPC socket) now
state the measured one: the event socket did not fit in sun_path.
2026-10-02 18:11:46 +00:00
Hermenix d45219994e tests: make the test basenames unique so the whole tree collects
The union of main and the four slices cannot be collected by pytest: an
import-file-mismatch on test_protocol.py (the frame wire's, the broker's) and
test_server.py (the frame server's, the pointer driver's). Per-directory runs
never hit it, so this is what the union run is for.

The tempting fix is --import-mode=importlib, and it is wrong: importlib does not
put a test file's directory on sys.path, which the slices' tests rely on for
sibling imports (from conftest import HANG, from test_ops import RecordingSink).
That trades a collection error for an ImportError. Renaming the two colliding
modules keeps the import behaviour and fixes the actual problem:

  tests/pointer/test_server.py       -> test_pointer_server.py
  tests/sessions/unit/test_protocol.py -> test_broker_protocol.py

tests: 551 passed.
2026-10-02 18:07:48 +00:00
Hermenix 8c180ec938 merge slice/pointer into main
Built in an independent worktree against docs/CONTRACT-sessions.md. Reports its
own slice's verification in its final message; the parent re-runs the union.
2026-10-02 18:05:48 +00:00
Hermenix 28b4b4b2cd merge slice/containers into main
Built in an independent worktree against docs/CONTRACT-sessions.md. Reports its
own slice's verification in its final message; the parent re-runs the union.
2026-10-02 18:05:48 +00:00
Hermenix 798ca1a4c1 merge slice/ipc-client into main
Built in an independent worktree against docs/CONTRACT-sessions.md. Reports its
own slice's verification in its final message; the parent re-runs the union.
2026-10-02 18:05:48 +00:00
Hermenix eb2aec99e7 merge slice/stage0-rename into main
Built in an independent worktree against docs/CONTRACT-sessions.md. Reports its
own slice's verification in its final message; the parent re-runs the union.
2026-10-02 18:05:48 +00:00
HermenixandClaude Opus 5 9b77c77ee8 ipc: a client that asks the compositor instead of guessing
The broker reported `workspace: null` and `window: null` for every session
because nothing in it could talk to Hyprland.  This is that voice, and the
only place that knows the compositor's wire format: one connection per
request on `.socket.sock` (leading `/` so an argument containing a slash is
never read as output flags, `j/` where JSON is wanted), and a held, blocking
stream on `.socket2.sock`.

Every failure is CompositorUnavailable -- no instance directory, two of them
and no signature, a socket that is gone, a peer that refuses or closes
mid-reply, a reply that is not the JSON it promised, an event stream that
ends.  Nothing returns an empty list or a None to stand in for "I could not
ask", because a caller that cannot tell those apart writes a guess into a
session record.  Inside the defined shape the parse is forgiving instead:
Hyprland's JSON has changed keys across releases, so a missing key is a
defined value and never a KeyError reaching the broker.

Tests bind real AF_UNIX sockets in a temporary directory laid out the way
Hyprland lays one out and serve canned bytes, so they drive the actual
connect, half-close, read-to-EOF and timeout paths rather than a mock that
would pass while the sockets broke.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLiQAZCmJf66CEcLx8siYF
2026-10-02 00:12:44 +00:00
HermenixandClaude Opus 5 06041030b0 rename the compositor runtime directory to /run/hypr-stream
`/run/hyprland-headless-stream` is 29 characters, and the compositor's IPC
sockets live under it at `hypr/<instance signature>/.socket2.sock`. With a
~30-character signature the *event* socket does not fit in `sun_path` and the
compositor refuses to bind it:

  ERR ]: Socket2 path is too long. (2) IPC will not work.

The *request* socket kept answering `hyprctl` (both ends agree on a residual
truncated path), which is why this looked healthy while every observation
feature that needs events had nothing to read.

`/run/hypr-stream` is 16 characters. The rename reaches both units'
`RuntimeDirectory`, `WorkingDirectory`, `XDG_RUNTIME_DIR` and `HOME`, the
broker's `--compositor-runtime-dir`, the `socketPath` option default, the
`hhstream` CLI's frame-socket default and the `agent-eyes` helper.

An assertion now holds the name at <= 25 characters, the ceiling frozen in
docs/CONTRACT-sessions.md §5, so this cannot regress silently -- the failure
mode is a working request socket and a dead event stream, which looks like
nothing is wrong. Its message says what breaks and why the limit exists.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018YqpJb5aZvZQKb49QDnV7P
2026-10-02 00:05:48 +00:00
HermenixandClaude Opus 5 01460016e7 containers: a headless output and a persistent workspace per session
A session was a process group, so every application landed on whichever
workspace the compositor happened to show: one session's capture caught
another's windows, and a pointer aimed at one could land in the other.

This is the pure half of the fix. containers.py computes the argv lists
that create a session's container (headless output, numbered workspace
bound to it as default and persistent, an anchored window rule pinning
the session's class there, then the mode) and the one that tears it down,
plus the lowest-free allocator for the 1000+slot band and the
quarantine backstop for windows that match no container. It runs
nothing: no subprocess, no socket, no file, no clock, and no import of
ipc.py, so every decision that can be tested without a compositor is
asserted in a unit test.

Validation is a control, not style: these strings reach a compositor
that acts on them, and a rule body is comma-separated, so a session id
outside [a-z0-9-], a class outside [A-Za-z0-9._+-], a non-positive or
fractional size and a blank quarantine name all raise ValueError naming
the value. Releasing a workspace the allocator never handed out raises
rather than no-opping, because the quiet version hands the same
workspace to two sessions minutes later.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QS2JvrgmvXmimKFcqqDVoa
2026-10-02 00:02:40 +00:00
62 changed files with 11344 additions and 195 deletions

No files matched your search

+132 -43
View File
@@ -7,7 +7,7 @@ decides, and if the document is wrong it gets a version bump, not an edit.
## Prerequisites
- Nix with flakes enabled.
- `/dev/kvm` readable, for the two VM checks. They are `nixosTest`s; without
- `/dev/kvm` readable, for the six VM checks. They are `nixosTest`s; without
KVM they still run, just slowly enough that the timeouts below get tight.
- No GPU. Nothing in the test suite needs one — the compositor runs on
Hyprland's headless backend over software rendering.
@@ -28,21 +28,26 @@ rather than an installed copy.
## Build
```bash
nix build .#hhstream # the package (server + client)
ls result/bin # hhstream-server, hhstream-client
nix build .#hhstream # the package
ls result/bin # hhstream-server, hhstream-client, hhstream,
# hhstreamd, hhstream-pointer
```
Both entry points currently exit with `NotImplementedError` — see "Known gaps"
at the bottom. The package builds; it does not yet run.
Five entry points: the frame server and a reference reader for it, the `hhstream`
front-door CLI (frames, `run`, and the `session` namespace), the session broker,
and the pointer driver.
## The checks
| Check | What it proves | Needs a VM |
|---|---|---|
| `unit` | the framing, the capture backend, the server's client handling, the client — in-process, against the `nix/package.nix` build | no |
| `unit` | the framing, the capture backend, the server's client handling, the broker, the CLI, the containers, the lease and the pointer driver — in-process, against the `nix/package.nix` build | no |
| `vm-basic` | the NixOS module brings up both units and publishes a contract-conformant socket, with a **fake** capture backend | yes |
| `vm-hyprland` | the same, capturing the **real** headless compositor through `grim` | yes |
| `vm-sessions` | the **session broker**: a real GUI application launched into the compositor as a tracked session, seen by the compositor's own IPC, killed as a tree, reaped on its idle deadline (and *not* reaped when touched), and adopted back after the broker restarts | yes |
| `vm-ipc` | the **compositor's IPC**: both sockets exist at the names `docs/CONTRACT-sessions.md` §5 freezes and fit inside `sun_path`, `hyprctl` answers, the broker's own `HyprlandIPC` reaches it, and a subscriber on the **event** socket receives an `openwindow` for a window the test creates | yes |
| `vm-containers` | one `hh-*` output per session at the container mode, the application's window on it, a second window of the same application beside it, an unmatched window **quarantined**, `grim -o` capturing that container alone, and teardown removing the output and freeing its workspace slot | yes |
| `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 |
All of them at once:
@@ -51,17 +56,36 @@ nix flake check -L
```
`nix flake check` stops at the first failing check, which makes it a poor way to
see the whole picture while the tree is still red. Prefer running them
individually — they are independent:
see the whole picture while the tree is still red. **Run the VM checks one at a
time** anyway — each boots a guest with a software-rendered compositor, and two
at once on a two-core machine make the timing-sensitive assertions flake. A
flaky green is worth less than a slow one.
```bash
nix build -L .#checks.x86_64-linux.unit
nix build -L .#checks.x86_64-linux.vm-basic
nix build -L .#checks.x86_64-linux.vm-hyprland
nix build -L .#checks.x86_64-linux.vm-sessions
nix build -L .#checks.x86_64-linux.vm-ipc
nix build -L .#checks.x86_64-linux.vm-containers
nix build -L .#checks.x86_64-linux.vm-pointer
```
`-L` is not optional in practice: without it, Nix hides the build log, and the
build log *is* the test report.
build log *is* the test report. Do **not** pipe a check into `tail` or `grep`:
the pipeline's exit status is the last command's, so a build that cannot fail
is not a test. Redirect to a file instead.
Each VM check's test script is type-checked before the guest boots, which is
much cheaper than finding a typo after a five-minute boot:
```bash
nix build -L .#checks.x86_64-linux.vm-pointer.driver --no-link
```
Watch for names the driver already defines — `log` is an `AbstractLogger` in
that namespace, and assigning a string to it is a type error, not a shadowing
warning.
### `unit`
@@ -152,7 +176,7 @@ What the dump contains, and where it comes from in the guest:
|---|---|
| `units` | `systemctl list-units --all 'hyprland*'` |
| per-unit `status` / `journalctl` | `hyprland-headless.service` and `hyprland-headless-stream.service`, 200 lines each |
| `socket and runtime directories` | `/run/hyprland-headless-stream`, `/run/user/*` |
| `socket and runtime directories` | `/run/hypr-stream`, `/run/user/*` |
| `hyprland logs` | every `hyprland*.log` found under `/run`, `/var/log`, `/tmp`, `/home` |
| `hyprctl monitors` | run once per instance found, with the right `XDG_RUNTIME_DIR` and `HYPRLAND_INSTANCE_SIGNATURE` |
| `processes` | `ps aux` filtered to `hypr`, `hhstream`, `grim` |
@@ -187,56 +211,121 @@ a line at a time. `machine.succeed("hhs-hyprland-diagnostics")` works there too.
```
checks/
default.nix wiring only: the three checks the flake exposes
default.nix wiring only: the checks the flake exposes
unit.nix pytest in the sandbox, against the nix/package.nix build
vm-basic.nix nixosTest, fake capture backend
vm-hyprland.nix nixosTest, real compositor + grim
vm-sessions.nix nixosTest, the broker's lifecycle against the compositor
vm-ipc.nix nixosTest, the compositor's request and event sockets
vm-containers.nix nixosTest, one output and one workspace per session
vm-pointer.nix nixosTest, the lease, the driver and a click that lands
lib/test-tools.nix packages the tests/ helpers for the guest
lib/session-tools.nix packages the two guest programs below
lib/session-machine.nix the guest the three session checks share
lib/session-prelude.nix their test-script helpers (no assertions live here)
lib/gpu-session.nix the hardware a bare test machine does not have
lib/check_report.py JUnit report -> build verdict (and the empty-suite guard)
lib/ipc_watch.py subscribes to the event socket: hhs-ipc-watch
lib/pointer_target.py a Wayland window that reports pointer events it receives:
hhs-pointer-target
tests/
fake_capture.py writes one fixed PNG to stdout: hhs-fake-capture
assert_stream.py independent contract reader/asserter: hhs-assert-stream
hyprland_diagnostics.sh the failure dump: hhs-hyprland-diagnostics
unit/ the pytest suite
unit/ ipc/ containers/ pointer/ sessions/ the pytest suite
```
`checks/lib/test-tools.nix` self-tests the two Python helpers at build time
(the fake emits a PNG of the size it was asked for; the asserter starts), because
a broken helper otherwise surfaces as a baffling failure three layers away.
`checks/lib/test-tools.nix` and `checks/lib/session-tools.nix` self-test their
programs at build time (the fake emits a PNG of the size it was asked for; the
asserter starts; the event subscriber can import the broker's IPC client; the
pointer target refuses to start without an app id), because a broken helper
otherwise surfaces as a baffling failure three layers away.
Adding a unit test: drop a `test_*.py` in `tests/unit/`. Nothing needs
registering. Adding a check: one file in `checks/`, one line in
`checks/default.nix`.
`hhs-ipc-watch` deliberately runs the **shipped** `hhstreamd.ipc.HyprlandIPC`
rather than a second implementation — the opposite choice from
`tests/assert_stream.py`. The difference is what each proves: `assert_stream`
asserts a wire format two programs must agree on, so a shared bug must still
fail it; `vm-ipc` asserts that *this* client receives events from *this*
compositor, which a reimplementation could not say anything about.
`hhs-pointer-target` exists because no application in nixpkgs does both of the
things the session checks need: set its `xdg_toplevel` app id from
`$HHSTREAM_APP_ID` (so its window matches its session's container rule) and
print the pointer events it receives with the coordinates it was given.
`foot` and `wev` do neither and ignore the environment entirely, which makes
them good *unmatched* windows and useless as matched ones.
Adding a unit test: drop a `test_*.py` under `tests/`. Nothing needs
registering, but the basename must be unique across the tree. Adding a check:
one file in `checks/`, one line in `checks/default.nix`.
## Known gaps in the interface (as of this branch)
These are defects in code this branch does not own; they are recorded here
because the tests are written against the contract and therefore trip over them.
Every item the previous revision of this section listed is closed: the module
has a `config` side, `package` has a default, `src/hhstream/*.py` is written,
and the frame server's command line is the one the module passes. What is open
is below. These are defects in code this branch does not own; they are recorded
here because the checks are written against the contract and therefore trip
over them.
1. **`nix/module.nix` has no `config` side yet.** Neither
`hyprland-headless.service` nor `hyprland-headless-stream.service` exists, so
both VM checks fail at their first wait with
`Unit hyprland-headless.service could not be found.` Nothing in `checks/`
works around this.
2. **`services.hyprland-headless-stream.package` is declared with no default.**
`docs/CONTRACT.md` says the default is "the flake's own build", but the option
has no `default`, so reading it fails with
1. **The broker reads none of the container or pointer configuration.**
`nix/module.nix` renders `sessions.containers.{max,mode,workspaceBase}` and
`sessions.pointer.{leaseTtl,leaseMax}` into the generated TOML as PLAN §10
names them, and `hhstreamd/policy.py:policy_from_dict` reads only
`[defaults]` and `[apps]`. `hhstreamd/__main__.py:serve` builds its
`ManagerConfig` from command-line flags that have no counterpart for any of
those numbers either, so the broker runs on its own defaults (band 1000,
4 slots, 1280x720, lease 30 s / 300 s).
Those defaults agree with the module's, so a deployment that leaves the
options alone behaves as documented; one that changes them is ignored.
`vm-pointer` prints the module's `leaseTtl` beside the TTL the broker
reports, so the discrepancy is visible in the build log rather than
inferred. The fix is in `policy.py` and `__main__.py`, not here.
2. **`session start --no-container` is refused, not honoured.** PLAN §9 lists
the flag; `docs/CONTRACT-sessions.md` §4 leaves `start` unchanged, and
`SessionManager.start` takes no such argument. A request carrying a
`no_container` field would be accepted and ignored, and the session would
get a container anyway — so the CLI exits 2 and names the disagreement
instead of lying about what it did.
3. **`nix/hyprland-conf.nix` sets `input:follow_mouse = 0`, and that stops
pointer input reaching anything but the focused window.** The comment
justifying it — "No pointer will ever exist; do not let focus depend on
one" — was true before this build and is false now.
Measured by `vm-pointer`, with two sessions and the second holding focus
because its window opened last:
```
error: The option `services.hyprland-headless-stream.package' was accessed but
has no value defined. Try setting the option.
aimed at target-le22h7: it reports [] <- the session the warp named
focused is target-s76taj: it reports [] <- the session with focus
cursor now at {'x': 2048, 'y': 288} <- exactly where it was aimed
```
Today that only bites code that reads `cfg.package`, which the unwritten
`config` side does not yet do; it will bite every consumer that sets only
`enable = true` the moment it does. Both VM checks set `package` explicitly.
3. **`src/hhstream/*.py` is stubs.** Every function raises
`NotImplementedError`, so 66 of the 70 unit tests fail. The 4 that pass are
`tests/unit/test_package.py`, which only reads constants — they are the
canary for the `unit` check's own wiring.
4. **The frame server's command line is unspecified.** `docs/CONTRACT.md` fixes
the module's option surface and the wire format but never says how the module
invokes `hhstream-server`. `tests/unit/test_server.py::test_build_parser_exposes_the_options_the_module_needs`
currently assumes `--socket PATH --fps N --format png -- <captureCommand...>`.
That is a guess; if the module ends up passing something else, that one test
is the thing to change, not the server.
The compositor moved the cursor to the right pixel, inside the right
window, on the right output, and told no client at all. Every warp and
click in the subtests before that one is delivered perfectly, because there
the aimed-at session is also the focused one — which is why nothing noticed
until a check put two sessions on the screen at once.
It defeats the point of containers and the lease: an agent could only drive
whichever session the compositor last focused. `vm-pointer` overrides the
single line through the module's `extraConfig` and asserts the property
that fails without it, so the check is green and the defect is still
visible. The fix is one line in `nix/hyprland-conf.nix`; whether it should
be `1` (Hyprland's own default, keyboard focus follows the cursor too) or a
looser setting that leaves keyboard focus alone is a decision for the
keyboard work in PLAN §6.7.
4. **A container's window rule only binds for an application that reads the
environment.** The broker's only lever on an application's class is
`$HHSTREAM_APP_ID` and the three toolkit variables beside it
(`hhstreamd/launcher.py`), so a GTK or Qt application — and `foot`, and
`wev` — keeps its own class, matches no per-session rule, and is swept into
the quarantine workspace. That is reported by the read-back rather than
papered over, and it is why `vm-containers` and `vm-pointer` use a
cooperating client (`hhs-pointer-target`) for the matched case and `foot`
for the unmatched one. Closing it needs a per-app `--app-id` in the
allowlist, which is a policy change.
+1 -1
View File
@@ -29,7 +29,7 @@ Two parts:
Then any consumer:
```bash
hhstream-client --socket /run/hyprland-headless-stream/stream.sock --count 1 --out frame.png
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
+28 -5
View File
@@ -1,11 +1,22 @@
# The flake's `checks` output. One file per check; this is only the wiring.
#
# unit -- pytest over tests/unit/, against the nix/package.nix build
# 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
# unit -- pytest over tests/, against the nix/package.nix build
# 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
# vm-ipc -- the compositor's IPC sockets, and an event that arrives
# vm-containers -- one output and one workspace per session
# vm-pointer -- the lease, the driver, and a click the application saw
#
# Everything the guests need lives in checks/lib/test-tools.nix.
# What the guests need lives in checks/lib: `test-tools.nix` for the fake
# capture and the contract asserter, `session-tools.nix` for the event
# subscriber and the pointer target, `session-machine.nix` for the guest the
# three session checks share, and `session-prelude.nix` for their test-script
# helpers.
#
# Run them ONE AT A TIME. Each boots a VM with a software-rendered compositor;
# two at once on a two-core machine make the timing-sensitive assertions flake,
# and a flaky green is worth less than a slow one.
{
pkgs,
self,
@@ -15,6 +26,12 @@ let
hhstream = self.packages.${system}.hhstream;
hhsModule = self.nixosModules.default;
testTools = pkgs.callPackage ./lib/test-tools.nix { };
# The three session checks take the same five arguments; naming them once
# keeps a new check from being wired up with a different compositor or a
# different package than its neighbours.
sessionArgs = {
inherit hhstream hhsModule testTools;
};
in
{
unit = pkgs.callPackage ./unit.nix { inherit hhstream; };
@@ -30,4 +47,10 @@ in
vm-sessions = pkgs.callPackage ./vm-sessions.nix {
inherit hhstream hhsModule testTools;
};
vm-ipc = pkgs.callPackage ./vm-ipc.nix sessionArgs;
vm-containers = pkgs.callPackage ./vm-containers.nix sessionArgs;
vm-pointer = pkgs.callPackage ./vm-pointer.nix sessionArgs;
}
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Subscribe to the compositor's event socket and write what arrives.
This is ``vm-ipc``'s witness, and it runs the **shipped** client
(:class:`hhstreamd.ipc.HyprlandIPC`) rather than a second implementation of
the same parsing. That is the opposite choice from ``tests/assert_stream.py``,
which is deliberately independent of ``hhstream.client`` so a shared framing
bug still fails -- and the reason for the difference is what each check is
for. ``vm-basic`` asserts a wire format two programs must agree on; this one
asserts that *this* client, against *this* compositor, receives events at all.
That is the defect it is pointed at. The compositor's event socket is
``<runtime dir>/hypr/<signature>/.socket2.sock``, and at the old 29-character
runtime directory the path did not fit in ``sun_path``:
ERR ]: Socket2 path is too long. (2) IPC will not work.
The *request* socket kept answering ``hyprctl`` -- both ends agreed on the
same truncated path -- so everything looked healthy while no event ever
arrived. Only a subscriber that waits for a named event can tell the
difference, which is why this program exists and why it reports what it saw
rather than just its exit status.
Every line it writes is flushed, so a caller can tail the file while the
compositor is still running.
"""
from __future__ import annotations
import argparse
import sys
import threading
import time
from pathlib import Path
from hhstreamd.ipc import CompositorUnavailable, HyprlandIPC
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="hhs-ipc-watch",
description="Record Hyprland events from the real event socket.",
)
parser.add_argument(
"--runtime-dir",
type=Path,
default=Path("/run/hypr-stream"),
help="the compositor's runtime directory (default: %(default)s)",
)
parser.add_argument(
"--out", type=Path, required=True, help="append every event here, one per line"
)
parser.add_argument(
"--await-event",
action="append",
default=[],
metavar="NAME",
help="exit 0 once this event has been seen; repeatable, all must arrive",
)
parser.add_argument(
"--timeout",
type=float,
default=120.0,
help="give up after this long and exit 1 (default: %(default)ss)",
)
args = parser.parse_args(argv)
try:
ipc = HyprlandIPC.discover(args.runtime_dir)
except CompositorUnavailable as exc:
print(f"hhs-ipc-watch: {exc}", file=sys.stderr)
return 1
out = args.out.open("a", encoding="utf-8", buffering=1)
print(f"watching {args.runtime_dir} for {args.await_event or 'everything'}", file=out)
wanted = set(args.await_event)
seen: set[str] = set()
deadline = time.monotonic() + args.timeout
# `events()` blocks in `recv`, so the deadline cannot be enforced from the
# same thread. Closing the socket from a timer is what unblocks it, and it
# is also what a real caller would have to do -- the contract's `events()`
# is explicitly a blocking iterator.
timer = threading.Timer(args.timeout, ipc.close)
timer.daemon = True
timer.start()
try:
for event in ipc.events():
print(f"{event.name}\t{event.data.get('raw', '')}", file=out)
if event.name in wanted:
seen.add(event.name)
if seen >= wanted:
print(f"saw {sorted(seen)}", file=out)
return 0
if time.monotonic() > deadline:
break
except CompositorUnavailable as exc:
print(f"event stream ended: {exc}", file=out)
finally:
timer.cancel()
ipc.close()
out.flush()
missing = sorted(wanted - seen)
print(f"TIMED OUT after {args.timeout}s; never saw {missing}", file=out)
print(f"hhs-ipc-watch: never saw {missing}", file=sys.stderr)
out.close()
return 1
if __name__ == "__main__":
sys.exit(main())
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env python3
"""A Wayland client that says where it was clicked, in its own words.
The VM checks need two things no application in nixpkgs gives them together:
* **a window that lands in its container.** The broker stamps a session's
identity into the environment only (``$HHSTREAM_APP_ID``, see
``hhstreamd/launcher.py``), because the alternative -- a per-app
``--app-id`` flag -- would have to come out of the allowlist. ``foot`` and
``wev`` ignore the environment and keep their own class, so their windows
match no per-session rule and are swept into quarantine. This client reads
the variable and sets ``xdg_toplevel.set_app_id`` to it, which is what the
rule ``match:initial_class ^hh-<id>$`` is written against.
* **a report of pointer events from the application's side.** PLAN §14 is
explicit that "a click lands where aimed" must be verified by reading back
*the application's* state and not by comparing pixels: a pixel comparison
proves the compositor drew a cursor, not that the client was told about a
button. Every event below is printed as the client received it, with the
surface-local coordinates the compositor sent, and flushed -- the broker
captures stdout into the session log, so ``hhstream session logs`` is the
read-back.
It is deliberately minimal and deliberately loud: it prints what it bound,
what size it was configured at, and every pointer event, so a check that fails
says whether the window was never mapped, never entered, or entered somewhere
other than where the warp aimed.
"""
from __future__ import annotations
import argparse
import mmap
import os
import signal
import struct
import sys
from pywayland.client import Display
from pywayland.protocol.wayland import WlCompositor, WlPointer, WlSeat, WlShm
from pywayland.protocol.xdg_shell import XdgWmBase
#: Opaque 32-bit colour. Something has to be in the buffer for the compositor
#: to map the surface at all, and a flat fill is the least that will do.
FILL = 0xFF3050A0
#: Fallback size for a compositor that configures 0x0 (meaning "you choose").
DEFAULT_SIZE = (640, 360)
def say(line: str) -> None:
"""One line, flushed. Unbuffered because the reader is a log tail."""
print(line, flush=True)
class Target:
def __init__(self, app_id: str, title: str, windows: int) -> None:
self.app_id = app_id
self.title = title
self.windows = windows
self.display: Display | None = None
self.compositor = None
self.shm = None
self.wm_base = None
self.seat = None
self.surfaces: list[_Window] = []
#: Last position the compositor reported, per surface, so a button
#: event can be printed with the place it happened. The protocol does
#: not put coordinates on `button`; `enter` and `motion` carry them.
self.pointer = None
# -- setup ---------------------------------------------------------
def run(self) -> int:
self.display = Display()
self.display.connect()
registry = self.display.get_registry()
registry.dispatcher["global"] = self._on_global
self.display.roundtrip()
missing = [
name
for name, value in (
("wl_compositor", self.compositor),
("wl_shm", self.shm),
("xdg_wm_base", self.wm_base),
("wl_seat", self.seat),
)
if value is None
]
if missing:
say(f"target: FATAL missing globals: {', '.join(missing)}")
return 1
self.wm_base.dispatcher["ping"] = lambda base, serial: base.pong(serial)
self.seat.dispatcher["capabilities"] = self._on_capabilities
for index in range(self.windows):
self.surfaces.append(_Window(self, index))
self.display.roundtrip()
say(f"target: app_id={self.app_id} windows={self.windows} pid={os.getpid()}")
while True:
# Blocking dispatch: this process exists to report events, so there
# is nothing to do between them and nothing to poll for.
if self.display.dispatch(block=True) < 0:
say("target: display disconnected")
return 1
def _on_global(self, registry, global_id: int, interface: str, version: int) -> None:
if interface == WlCompositor.name:
self.compositor = registry.bind(global_id, WlCompositor, min(version, 4))
elif interface == WlShm.name:
self.shm = registry.bind(global_id, WlShm, 1)
elif interface == XdgWmBase.name:
self.wm_base = registry.bind(global_id, XdgWmBase, min(version, 2))
elif interface == WlSeat.name and self.seat is None:
self.seat = registry.bind(global_id, WlSeat, min(version, 5))
def _on_capabilities(self, seat, capabilities: int) -> None:
if not capabilities & WlSeat.capability.pointer.value:
# Said out loud: a seat with no pointer capability is the headless
# case where nothing has ever created a virtual pointer, and it is
# indistinguishable from "the warp did not arrive" unless reported.
say("target: seat has no pointer capability yet")
return
if self.pointer is not None:
return
self.pointer = seat.get_pointer()
self.pointer.dispatcher["enter"] = self._on_enter
self.pointer.dispatcher["leave"] = self._on_leave
self.pointer.dispatcher["motion"] = self._on_motion
self.pointer.dispatcher["button"] = self._on_button
say("target: pointer bound")
# -- pointer -------------------------------------------------------
def _window_of(self, surface) -> "_Window | None":
for window in self.surfaces:
if window.surface == surface:
return window
return None
def _on_enter(self, pointer, serial, surface, x, y) -> None:
window = self._window_of(surface)
if window is not None:
window.at = (x, y)
say(f"pointer enter window={_name(window)} x={x:.2f} y={y:.2f}")
def _on_leave(self, pointer, serial, surface) -> None:
say(f"pointer leave window={_name(self._window_of(surface))}")
def _on_motion(self, pointer, time, x, y) -> None:
for window in self.surfaces:
# Motion carries no surface; the focused one is whichever was
# entered last, and with one window per container that is the only
# one. Recording it on all of them keeps the button line honest
# without inventing a focus model this client does not need.
window.at = (x, y)
say(f"pointer motion x={x:.2f} y={y:.2f}")
def _on_button(self, pointer, serial, time, button, state) -> None:
where = self.surfaces[0].at if self.surfaces else None
position = "x=? y=?" if where is None else f"x={where[0]:.2f} y={where[1]:.2f}"
say(
f"pointer button code={button} state="
f"{'pressed' if state else 'released'} {position}"
)
def _name(window: "_Window | None") -> str:
return "?" if window is None else str(window.index)
class _Window:
"""One toplevel: a surface, its xdg wrapper, and an shm buffer."""
def __init__(self, target: Target, index: int) -> None:
self.target = target
self.index = index
self.at: tuple[float, float] | None = None
self.size = DEFAULT_SIZE
self.buffer = None
self._pool = None
self._map: mmap.mmap | None = None
self.surface = target.compositor.create_surface()
self.xdg_surface = target.wm_base.get_xdg_surface(self.surface)
self.xdg_surface.dispatcher["configure"] = self._on_configure
self.toplevel = self.xdg_surface.get_toplevel()
# The whole reason this program exists rather than `wev`.
self.toplevel.set_app_id(target.app_id)
self.toplevel.set_title(f"{target.title}-{index}")
self.toplevel.dispatcher["configure"] = self._on_toplevel_configure
self.toplevel.dispatcher["close"] = lambda *_: sys.exit(0)
self.surface.commit()
def _on_toplevel_configure(self, toplevel, width, height, states) -> None:
if width and height:
self.size = (width, height)
def _on_configure(self, xdg_surface, serial) -> None:
xdg_surface.ack_configure(serial)
self._paint()
say(f"target: window {self.index} configured {self.size[0]}x{self.size[1]}")
def _paint(self) -> None:
width, height = self.size
stride = width * 4
size = stride * height
if self._map is None or self._map.size() < size:
self._allocate(size)
# A flat fill, written once per resize: the pixels are not the subject
# of any assertion, they only make the surface mappable.
self._map.seek(0)
self._map.write(struct.pack("<I", FILL) * (size // 4))
self.buffer = self._pool.create_buffer(
0, width, height, stride, WlShm.format.xrgb8888.value
)
self.surface.attach(self.buffer, 0, 0)
self.surface.damage(0, 0, width, height)
self.surface.commit()
def _allocate(self, size: int) -> None:
fd = os.memfd_create(f"hhs-target-{self.index}", 0)
os.ftruncate(fd, size)
self._map = mmap.mmap(fd, size)
self._pool = self.target.shm.create_pool(fd, size)
os.close(fd)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="hhs-pointer-target",
description="A Wayland window that reports the pointer events it receives.",
)
parser.add_argument(
"--app-id",
default=None,
help="xdg_toplevel app id; the default is $HHSTREAM_APP_ID, which is how "
"a session's window rule finds its container",
)
parser.add_argument("--title", default="hhs-target")
parser.add_argument(
"--windows",
type=int,
default=1,
help="how many toplevels to open, all with the same app id",
)
args = parser.parse_args(argv)
app_id = args.app_id or os.environ.get("HHSTREAM_APP_ID")
if not app_id:
print(
"hhs-pointer-target: no --app-id and no $HHSTREAM_APP_ID; refusing to "
"guess, because the app id is the whole point of this program",
file=sys.stderr,
)
return 2
# The broker kills the process group; exit on the first signal rather than
# leaving the compositor to notice a dead client.
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
signal.signal(signal.SIGINT, lambda *_: sys.exit(0))
return Target(app_id, args.title, max(1, args.windows)).run()
if __name__ == "__main__":
sys.exit(main())
+125
View File
@@ -0,0 +1,125 @@
# The guest the three session checks share: compositor, broker, one account.
#
# A function rather than a copy in each check, because what the three differ in
# is the *assertions*, not the machine, and three drifting copies of a machine
# definition is how a check quietly stops testing what its neighbour tests.
# Everything that varies is an argument; nothing here relaxes an assertion.
#
# It is a machine, not a test. `gpu-session.nix` supplies the two pieces of
# hardware a bare NixOS test machine lacks (see that file); this adds the
# module under test, the account applications run as, and the tools the guest
# needs to interrogate the compositor.
{
hhsModule,
hhstream,
hyprland,
testTools,
sessionTools,
foot,
jq,
procps,
grim,
coreutils,
dejavu_fonts,
}:
{
# The allowlist, as `sessions.apps` takes it.
apps,
pointer ? false,
# Only read when `pointer` is true; the module's own defaults otherwise.
leaseTtl ? 30,
leaseMax ? 300,
width ? 1280,
height ? 720,
fps ? 30,
sessionUser ? "hermes",
# Long enough that nothing is reaped by surprise mid-check, short enough that
# the number is visibly the test's and not the module's 3 h default.
idleTimeout ? 600,
# The group that owns the compositor's runtime directory. The module's
# default, named here because this fragment is a plain attribute set (the
# test driver's `nodes.<name>` does not take a function) and so cannot read
# it back out of `config`.
sessionGroup ? "hhstream",
# Appended to the generated hyprland.conf. Only `vm-pointer` uses it, and
# only for one line it has to override; see that file for the measurement.
extraConfig ? "",
}:
{
imports = [
hhsModule
./gpu-session.nix
];
services.hyprland-headless-stream = {
enable = true;
package = hhstream;
hyprlandPackage = hyprland;
inherit extraConfig;
# No `name`: the wildcard rule applies to whatever connector the virtio GPU
# gives this guest (see vm-hyprland.nix for why a check must not know it).
outputs = [
{
inherit width height;
refresh = fps;
}
];
sessions = {
enable = true;
user = sessionUser;
inherit apps idleTimeout;
pointer = {
enable = pointer;
inherit leaseTtl leaseMax;
};
};
};
# The module deliberately does not create this user: launched applications
# run as it, so it is normally a real person's account. `video` and `render`
# are what any client of this session needs to reach the GPU; the broker's
# unit adds the compositor's own group on top.
users.users.${sessionUser} = {
isNormalUser = true;
extraGroups = [
"video"
"render"
# The compositor's own group, on the *account*.
#
# The broker does not need this -- its unit has the group as a
# supplementary one, which is how the applications it launches reach the
# Wayland socket. This is for the other half of the CLI: `hhstream shot
# --output hh-<id>` runs grim as whoever typed it, and the frame socket
# and runtime directory are 0750/0660 owned by this group. The operator
# account on a real machine is in it for exactly that reason -- it is
# what `hhstream`'s `sg` re-exec exists to recover when a login predates
# the membership.
sessionGroup
];
};
# foot resolves "monospace" through fontconfig and refuses to start without a
# usable font; a NixOS test machine has `fonts.enableDefaultPackages = false`.
# One font, not the default set.
fonts.packages = [ dejavu_fonts ];
environment.systemPackages = [
testTools # hhs-hyprland-diagnostics
sessionTools # hhs-ipc-watch, hhs-pointer-target
hhstream # the CLI under test
hyprland # hyprctl: the compositor is the source of truth here
foot
grim # per-container capture, which is what an output *is* for
jq # the in-guest predicates the bounded waits poll
procps
coreutils
];
virtualisation = {
memorySize = 2048;
cores = 2;
diskSize = 4096;
graphics = false;
};
}
+219
View File
@@ -0,0 +1,219 @@
# The test-script helpers the three session checks share: how to run something
# as the session account, how to call the CLI, how to ask the compositor, and
# what to dump when an assertion fails.
#
# Helpers only. There is not one assertion in this file, deliberately: a shared
# prelude that asserted things would make each check's own script an incomplete
# account of what it proves, and the whole point of these scripts is that they
# can be read top to bottom when one of them goes red.
{
hhstream,
coreutils,
sessionUser,
compositorRuntime ? "/run/hypr-stream",
controlSocket ? "/run/hhstream/control.sock",
}:
''
import json
import time
USER = "${sessionUser}"
CONTROL = "${controlSocket}"
CONTROL_DIR = "/run/hhstream"
COMPOSITOR_RUNTIME = "${compositorRuntime}"
HHSTREAM = "${hhstream}/bin/hhstream"
TRUE = "${coreutils}/bin/true"
FALSE = "${coreutils}/bin/false"
# The module pins the compositor's XDG_RUNTIME_DIR; the instance signature
# under it is the only part not known ahead of time. Root may connect to the
# IPC socket even though it belongs to `hhstream`. Same shape as
# vm-hyprland.nix, which asks this for monitors.
HYPRCTL = (
"set -eu; "
f"sig=$(ls -1 {COMPOSITOR_RUNTIME}/hypr | head -n1); "
f"XDG_RUNTIME_DIR={COMPOSITOR_RUNTIME}"
" HYPRLAND_INSTANCE_SIGNATURE=$sig hyprctl -j"
)
#: A transient `systemd-run` unit inherits systemd's own minimal PATH, not
#: the guest's. That is an artefact of how these checks invoke things, not a
#: property of the system under test: a person's login has the system profile
#: on PATH, and `hhstream shot --output` looks `grim` up there. Measured, by
#: a check that failed with the CLI's own "grim is not on PATH, and --output
#: needs it" -- which is the right message and the wrong environment.
SYSTEM_PATH = "/run/current-system/sw/bin"
def as_user(command, env=""):
"""`command` (absolute path plus argv, never a shell) run as USER.
A transient unit rather than `su`, because it gives a clean argv with no
login shell in the middle, and `--pipe --wait` propagates the command's
own exit status -- which each check proves before anything depends on it.
"""
return (
"systemd-run --quiet --collect --pipe --wait"
f" --uid={USER} --setenv=HOME=/home/{USER}"
f" --setenv=PATH={SYSTEM_PATH} {env} -- {command}"
)
def background(unit, command, env="", user=None):
"""A transient unit that keeps running after the call returns.
For the programs a check must have running *before* the thing they
witness happens: the event subscriber, and a window that is not a
session.
No `--collect`: the unit has to stay loaded after it exits, because its
exit status is part of what is asserted, and a collected unit is
unloaded the moment it stops.
`user=None` means root, which is how the driver already reaches the
compositor's IPC socket (see HYPRCTL); pass USER for something that
should be subject to the same permissions an operator has.
"""
who = "" if user is None else f" --uid={user} --setenv=HOME=/home/{user}"
return (
f"systemd-run --quiet --unit={unit}{who}"
f" --setenv=PATH={SYSTEM_PATH} {env} -- {command}"
)
def compositor_env():
"""`--setenv` flags that point a Wayland client at this session.
The socket name is discovered, never assumed: the compositor binds the
first free `wayland-N`, and a crashed one leaves `wayland-0` behind.
"""
display = machine.succeed(
f"cd {COMPOSITOR_RUNTIME} && ls -1 wayland-* | grep -v '[.]lock$' | head -n1"
).strip()
assert display, f"no wayland socket in {COMPOSITOR_RUNTIME}"
return (
f"--setenv=XDG_RUNTIME_DIR={COMPOSITOR_RUNTIME}"
f" --setenv=WAYLAND_DISPLAY={display}"
)
def cli(args):
"""`hhstream session …` as USER, against the control socket."""
return as_user(f"{HHSTREAM} session --socket {CONTROL} {args}")
def cli_json(args, timeout=120):
"""Run a `--json` verb and parse what it printed. Fails loudly if it did not."""
out = machine.succeed(cli(args), timeout=timeout)
try:
return json.loads(out)
except json.JSONDecodeError:
raise AssertionError(f"not JSON from `session {args}`: {out!r}")
def compositor(resource):
"""`hyprctl -j <resource>`, parsed. The compositor is the authority here."""
return json.loads(machine.succeed(f"{HYPRCTL} {resource}", timeout=120))
def monitor_named(name):
for entry in compositor("monitors"):
if entry.get("name") == name:
return entry
return None
def wait_for(predicate, timeout, what, interval=1.0):
"""Poll a *Python* predicate to a deadline, and return its value.
`machine.wait_until_succeeds` can only wait on a shell command, which
forces anything with structure into jq. This is for the waits whose
condition is a parsed value -- "the client has reported a third button
event" -- where a shell pipeline would be both unreadable and quietly
wrong when `grep -c` prints 0 and exits 1.
It waits for an *event that must happen*, never for an assertion to come
good: every caller below asserts after it returns, not inside it.
"""
deadline = time.monotonic() + timeout
while True:
value = predicate()
if value:
return value
if time.monotonic() > deadline:
raise AssertionError(f"timed out after {timeout}s waiting for {what}")
time.sleep(interval)
def dump(label, session_id=None):
print(f"########## diagnostics: {label} ##########")
status, out = machine.execute("hhs-hyprland-diagnostics", timeout=300)
print(out)
print(f"----- hhs-hyprland-diagnostics exit {status} -----")
commands = [
"systemctl --no-pager --full status hhstream-sessions.service",
"journalctl --no-pager --boot --lines=200 --unit hhstream-sessions.service",
"systemctl --no-pager --full status hhstream-pointer.service",
"journalctl --no-pager --boot --lines=200 --unit hhstream-pointer.service",
f"ls -la {CONTROL_DIR} /var/lib/hhstream/sessions",
"ps -eo pid,ppid,pgid,sid,user,stat,comm,args --sort=pid",
cli("list --all"),
cli("container"),
cli("pointer state"),
]
if session_id:
commands += [
cli(f"status {session_id}"),
# Every session's captured output, not just the named one: when
# a pointer event goes to the wrong window, the wrong window's
# log is the evidence and the named session's is empty.
cli("list"),
# The application's own captured output: the only place a failed
# launch, or a pointer event that never arrived, explains itself.
cli(f"logs {session_id} --lines 200"),
]
for command in commands:
status, out = machine.execute(f"{command} 2>&1", timeout=180)
print(f"----- {command} (exit {status}) -----")
print(out)
for resource in ("monitors", "workspaces", "clients", "cursorpos"):
status, out = machine.execute(f"{HYPRCTL} {resource} 2>&1", timeout=180)
print(f"----- hyprctl {resource} (exit {status}) -----")
print(out)
print("########## end diagnostics ##########")
def bring_up(label="the session stack"):
"""Compositor, then broker, then the socket each exists to serve.
`wait_for_unit` alone is not enough for the broker and that is measured,
not assumed: the unit is `Type=simple` with no readiness protocol, so
systemd calls it active the instant it has forked. A daemon that exits
two milliseconds later and is restarted every second passes it. The
honest test of "it came up" is the socket plus a restart count of zero.
"""
try:
machine.wait_for_unit("hyprland-headless.service", timeout=300)
machine.wait_for_file(f"{COMPOSITOR_RUNTIME}/hypr", timeout=120)
machine.wait_for_unit("hhstream-sessions.service", timeout=180)
machine.wait_for_file(CONTROL, timeout=120)
machine.succeed("systemctl is-active hhstream-sessions.service")
restarts = machine.succeed(
"systemctl show -p NRestarts --value hhstream-sessions.service"
).strip()
assert restarts == "0", (
f"the broker has restarted {restarts} time(s) already: it is "
"crash-looping, not running"
)
except Exception:
dump(f"{label} did not come up")
raise
''
+55
View File
@@ -0,0 +1,55 @@
# The guest programs the session checks need, packaged with the interpreters
# they actually require.
#
# Separate from `test-tools.nix` because these two need things that one does
# not: `hhs-ipc-watch` imports the shipped `hhstreamd.ipc` (so it needs the
# package on PYTHONPATH -- it is the client under test, not a reimplementation
# of it), and `hhs-pointer-target` is a Wayland client (so it needs pywayland).
#
# Both are self-tested at build time, for the same reason test-tools.nix does
# it: a broken helper otherwise surfaces as a baffling VM failure three layers
# away, long after the thing that would have explained it scrolled past.
{
runCommandLocal,
python3,
hhstream,
}:
let
# pywayland for the Wayland client; nothing else, so an import error in the
# guest is a real missing dependency and not this file being generous.
waylandPython = python3.withPackages (ps: [ ps.pywayland ]);
in
runCommandLocal "hhstream-session-tools"
{
nativeBuildInputs = [ python3 ];
meta.description = "Event-socket witness and pointer target for the hhstream session checks";
} ''
mkdir -p $out/bin
# The event-socket subscriber runs the broker's own IPC client, so it is
# pointed at what nix/package.nix installed rather than at a copy.
cat > $out/bin/hhs-ipc-watch <<EOF
#!${python3}/bin/python3
import sys
sys.path.insert(0, "${hhstream}/${python3.sitePackages}")
sys.argv[0] = "hhs-ipc-watch"
exec(compile(open("${./ipc_watch.py}").read(), "${./ipc_watch.py}", "exec"))
EOF
install -Dm755 ${./pointer_target.py} $out/bin/hhs-pointer-target
chmod +x $out/bin/hhs-ipc-watch
sed -i '1s|.*|#!${waylandPython}/bin/python3|' $out/bin/hhs-pointer-target
# Proof that both start, that `hhstreamd.ipc` is importable through the path
# above, and that pywayland's xdg_shell bindings are present -- the three
# ways these could be broken without the guest ever saying so.
$out/bin/hhs-ipc-watch --help > /dev/null
$out/bin/hhs-pointer-target --help > /dev/null
${waylandPython}/bin/python3 -c 'from pywayland.protocol.xdg_shell import XdgWmBase'
# The target refuses to guess an app id, and the checks depend on that
# refusal being exit 2 rather than a window with somebody else's class.
if $out/bin/hhs-pointer-target; then
echo "hhs-pointer-target started with no app id; it must refuse" >&2
exit 1
fi
''
+21 -4
View File
@@ -1,6 +1,14 @@
# checks.<system>.unit -- the Python unit suite from tests/unit/, run against the
# checks.<system>.unit -- the Python unit suite from tests/, run against the
# package built by nix/package.nix, inside the build sandbox.
#
# The whole tree, not one directory: it used to take tests/unit alone, which
# meant the broker's and the pointer driver's suites (and the sessions one) were
# never collected by any check -- a gate that could not see 432 of 551 tests.
#
# pywayland is in the test environment because the pointer driver imports it;
# without it those tests fail as an import error rather than as the thing they
# test.
#
# nix/package.nix sets doCheck = false deliberately, so this is the only place
# the suite runs in a build.
{
@@ -10,13 +18,13 @@
hhstream,
}:
let
pytestEnv = python3.withPackages (ps: [ ps.pytest ]);
pytestEnv = python3.withPackages (ps: [ ps.pytest ps.pywayland ]);
# Only the suite itself, so an editor's droppings or a local .pytest_cache
# cannot change the derivation's hash.
testSrc = lib.cleanSourceWith {
name = "hhstream-unit-tests";
src = ../tests/unit;
name = "hhstream-tests";
src = ../tests;
filter =
path: type:
let
@@ -35,6 +43,14 @@ runCommand "hhstream-unit"
cp -r ${testSrc} suite
chmod -R u+w suite
# `tests/sessions/integration/test_lifecycle.py` locates the repository by
# looking upward for a `pyproject.toml` (it needs the root for `src/` on
# PYTHONPATH and as a cwd for the subprocesses it spawns). In a build there is
# no repository above the copied suite, so it raises at import time and takes
# the whole run down as a collection error. Giving it the marker it documents
# is the fix; the test itself is hermetic -- no compositor, no network.
cp ${../pyproject.toml} suite/pyproject.toml
# The package is an application, so its library is not on the default path:
# point PYTHONPATH at what nix/package.nix installed. Importing it here rather
# than letting pytest do it makes a packaging problem distinguishable from a
@@ -43,6 +59,7 @@ runCommand "hhstream-unit"
export PYTHONDONTWRITEBYTECODE=1
export HOME=$PWD
python3 -c 'import hhstream; print("testing hhstream", hhstream.__version__, "from", hhstream.__file__)'
python3 -c 'import hhstreamd.ipc, hhstream_pointer; print("broker ipc client + pointer driver import")'
set +e
pytest suite \
+1 -1
View File
@@ -13,7 +13,7 @@
width ? 1280,
height ? 720,
fps ? 30,
socketPath ? "/run/hyprland-headless-stream/stream.sock",
socketPath ? "/run/hypr-stream/stream.sock",
}:
testers.runNixOSTest {
name = "hhstream-vm-basic";
+355
View File
@@ -0,0 +1,355 @@
# checks.<system>.vm-containers -- one output and one workspace per session,
# proved against the compositor that has to create them.
#
# Everything under this has so far been proved against fakes. `hyprctl output
# create headless` is marked **[UNVERIFIED -- experiment 3]** in PLAN §5.1: it
# is *implied* by Hyprland requesting the headless backend as
# AQ_BACKEND_REQUEST_MANDATORY, and nobody had run it. If it does not work,
# this is where that is found out, and the right outcome is a red check that
# quotes the compositor rather than a softer assertion.
#
# ─── THE VICTIM, AND WHY IT IS NOT `foot` ────────────────────────────────────
# A session's window rule is `match:initial_class ^hh-<id>$`, and the broker's
# only lever on an application's class is the environment (`$HHSTREAM_APP_ID`,
# see `hhstreamd/launcher.py`): a per-app `--app-id` flag would have to come
# out of the allowlist. `foot` and `wev` ignore the environment and keep their
# own class, so their windows match no per-session rule -- which makes them
# excellent *unmatched* windows and useless as matched ones.
#
# So this check uses both, for the two different jobs:
#
# * `target`, a wrapper around `hhs-pointer-target` (checks/lib), reads
# $HHSTREAM_APP_ID and calls `xdg_toplevel.set_app_id` with it. Its windows
# are the ones that must land in their container.
# * `foot`, launched *outside* any session, is the window that matches
# nothing and must end up quarantined.
#
# The launcher's own docstring says a GTK or Qt application ignores all four
# variables and its rule will not bind. That is a real limitation of the
# design, and this check is deliberately written so it is visible: the matched
# case needs a cooperating client, and nothing here pretends otherwise.
# ─────────────────────────────────────────────────────────────────────────────
{
testers,
hhstream,
hhsModule,
testTools,
hyprland,
foot,
jq,
grim,
procps,
coreutils,
dejavu_fonts,
width ? 1280,
height ? 720,
sessionUser ? "hermes",
}:
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 wrapper the launcher's docstring describes: "HHSTREAM_APP_ID for a
# wrapper script that knows what to do with it". `exec`, so the session's
# pid is the client's and the broker's kill handle stays correct -- the
# cmdline change that causes is explicitly tolerated (procmon, BUG-02).
target = pkgs.writeShellScript "hhs-target-wrapper" ''
exec ${tools}/bin/hhs-pointer-target --app-id "$HHSTREAM_APP_ID" "$@"
'';
in
{
name = "hhstream-vm-containers";
globalTimeout = 1800;
nodes.machine = guest {
inherit width height sessionUser;
apps = {
target = {
exec = "${target}";
# One caller-supplied argument, so the two-window subtest can ask for
# a second toplevel without a second allowlist entry.
argsAllow = [ "--windows=*" ];
};
};
};
testScript =
prelude
+ ''
MODE = (${toString width}, ${toString height})
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("a fresh machine has one output and no containers"):
# The baseline every assertion below is a difference from. An
# `hh-*` output here would mean the compositor kept one from a
# previous boot, which it cannot -- so this also proves the
# start-up scan found nothing to clean up.
try:
before = [m["name"] for m in compositor("monitors")]
print(f"outputs before: {before}")
assert not [n for n in before if n.startswith("hh-")], before
listing = cli_json("container --json")
assert listing["containers"] == [], listing
assert listing["orphans"] == [], listing
except Exception:
dump("the machine did not start clean")
raise
with subtest("starting a session creates one output named hh-<id>"):
# PLAN §5.1 experiment 3: does `hyprctl output create headless`
# actually work on this instance? Everything else depends on it.
try:
session_id = machine.succeed(cli("start target"), timeout=180).strip()
print(f"session: {session_id}")
expected = f"hh-{session_id}"
record = cli_json(f"status --json {session_id}")["session"]
print(json.dumps(record["container"], indent=2, sort_keys=True))
container = record["container"]
assert container["state"] == "owned", (
f"the broker did not create a container: {container}. "
"If `state` is 'degraded' the compositor refused `output "
"create headless` -- read the journal above for its words."
)
assert container["output"] == expected, container
monitor = monitor_named(expected)
assert monitor is not None, (
f"the broker recorded {expected} but the compositor has "
f"{[m['name'] for m in compositor('monitors')]}"
)
print(json.dumps(monitor, indent=2, sort_keys=True))
assert (monitor["width"], monitor["height"]) == MODE, (
f"{expected} is {monitor['width']}x{monitor['height']}, not "
f"the container mode {MODE[0]}x{MODE[1]}"
)
workspace = container["workspace"]
assert workspace >= 1000, (
f"workspace {workspace} is outside the reserved band (1000+)"
)
except Exception:
dump("no container output was created", locals().get("session_id"))
raise
with subtest("the application's window is on that output, not elsewhere"):
# The compositor is the authority: the record saying `owned` only
# means the broker asked for an output, not that the window rule
# bound and the window went there.
try:
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e --arg m {expected}"
" 'any(.initialClass == $m)' >/dev/null",
timeout=120,
)
ours = [
c for c in compositor("clients") if c.get("initialClass") == expected
]
print(json.dumps(ours, indent=2, sort_keys=True))
assert len(ours) == 1, f"expected one window of ours, got {len(ours)}"
client = ours[0]
assert client["workspace"]["id"] == workspace, (
f"the window is on workspace {client['workspace']} and the "
f"container is {workspace}"
)
except Exception:
dump("the window did not land in its container", session_id)
raise
with subtest("a second window of the same application lands in the same one"):
# Same session, same app id, second toplevel. The rule matches on
# `initial_class`, so this is the case the rule is written for --
# and the one that would silently break if the rule were per-window
# rather than per-class.
try:
second = machine.succeed(
cli("start target -- --windows=2"), timeout=180
).strip()
second_expected = f"hh-{second}"
second_ws = cli_json(f"status --json {second}")["session"]["container"][
"workspace"
]
print(f"second session {second} on workspace {second_ws}")
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e --arg m {second_expected}"
" '[.[] | select(.initialClass == $m)] | length == 2' >/dev/null",
timeout=120,
)
windows = [
c
for c in compositor("clients")
if c.get("initialClass") == second_expected
]
print(json.dumps(windows, indent=2, sort_keys=True))
assert len(windows) == 2, windows
on = {w["workspace"]["id"] for w in windows}
assert on == {second_ws}, (
f"the two windows of one application are on workspaces {on}, "
f"not both on the container's {second_ws}"
)
# And they are in a different container from the first session:
# one output per session is the other half of the claim.
assert second_ws != workspace, (second_ws, workspace)
except Exception:
dump("the second window did not join its container", locals().get("second"))
raise
with subtest("a window matching no container is quarantined"):
# `foot` is launched outside any session, so it carries its own
# class and matches no per-session rule. Without the backstop it
# would appear on whatever output happened to be focused -- which
# is one of the two sessions' containers, i.e. in someone's screen
# capture. PLAN §5.2.
try:
machine.succeed(
background(
"stray",
"${foot}/bin/foot",
env=compositor_env(),
user=USER,
),
timeout=120,
)
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e 'any(.initialClass == \"foot\")' >/dev/null",
timeout=120,
)
stray = [c for c in compositor("clients") if c.get("initialClass") == "foot"]
print(json.dumps(stray, indent=2, sort_keys=True))
assert len(stray) == 1, stray
landed = stray[0]["workspace"]["name"]
assert landed == "special:quarantine", (
f"an unmatched window landed on workspace {landed!r}; the "
"quarantine backstop did not catch it, so it is sitting on "
"whatever output was focused"
)
except Exception:
dump("an unmatched window was not quarantined")
raise
with subtest("grim -o captures that container and only that container"):
# The reason a container is an *output* and not just a workspace
# (PLAN §5.4). Two captures of two different containers must differ
# -- and both must differ from a capture of the main output, which
# has the stray window on it.
try:
shots = {}
for name in (expected, second_expected):
path = f"/tmp/{name}.png"
# No compositor environment passed in: the CLI discovers
# the session itself, which is the part under test. It runs
# as the operator account, through grim, like a person.
machine.succeed(
as_user(f"{HHSTREAM} shot --output {name} --out {path}"),
timeout=180,
)
# PNG IHDR: width and height are two big-endian uint32 at
# byte 16. Read with od so no interpreter is involved.
geometry = machine.succeed(
f"od -An -tu4 -j16 -N8 --endian=big {path}"
).split()
shots[name] = (
geometry,
machine.succeed(f"sha256sum {path}").split()[0],
)
print(f"{name}: {geometry} sha {shots[name][1]}")
for name, (geometry, _) in shots.items():
assert geometry == [str(MODE[0]), str(MODE[1])], (
f"{name} captured at {geometry}, not the container mode "
f"{MODE[0]}x{MODE[1]}"
)
assert shots[expected][1] != shots[second_expected][1], (
"two different containers captured byte-identical images; "
"grim -o is not selecting an output"
)
except Exception:
dump("per-container capture did not isolate the containers")
raise
with subtest("an output that does not exist is refused, not invented"):
try:
code, out = machine.execute(
as_user(f"{HHSTREAM} shot --output hh-nothing --out /tmp/no.png")
+ " 2>&1",
timeout=120,
)
print(f"exit {code}: {out}")
assert code != 0, "capturing a non-existent output succeeded"
# grim's own words, passed through rather than replaced by a
# guess at what went wrong.
assert "hh-nothing" in out, out
machine.fail("test -e /tmp/no.png")
except Exception:
dump("a bad output name did not fail")
raise
with subtest("teardown removes the output and the compositor agrees"):
try:
reply = cli_json(f"kill --json {session_id}", timeout=180)
print(json.dumps(reply["session"]["container"], indent=2, sort_keys=True))
assert reply["ok"] is True, reply
assert reply["session"]["container_removed"] is True, reply["session"]
assert reply["session"]["container_survivors"] == [], (
"the compositor still shows windows for a session whose "
f"output was removed: {reply['session']['container_survivors']}"
)
machine.wait_until_succeeds(
f"{HYPRCTL} monitors | jq -e --arg m {expected}"
" 'all(.name != $m)' >/dev/null",
timeout=60,
)
assert monitor_named(expected) is None, (
f"{expected} is still an output after teardown"
)
except Exception:
dump("the container outlived its session", session_id)
raise
with subtest("the workspace slot comes back and a new session reuses the band"):
# Releasing the slot is what stops the band leaking: without it the
# fourth session on a 4-slot band would be refused for no reason.
try:
listing = cli_json("container --json")
print(json.dumps(listing, indent=2, sort_keys=True))
assert workspace not in listing["workspaces_in_use"], listing
assert listing["orphans"] == [], (
f"teardown left an orphan output behind: {listing['orphans']}"
)
third = machine.succeed(cli("start target"), timeout=180).strip()
third_ws = cli_json(f"status --json {third}")["session"]["container"][
"workspace"
]
print(f"third session {third} took workspace {third_ws}")
assert third_ws == workspace, (
f"the freed slot {workspace} was not reused; got {third_ws}"
)
except Exception:
dump("the workspace slot was not released", locals().get("third"))
raise
'';
}
)
+5 -5
View File
@@ -20,7 +20,7 @@
width ? 1280,
height ? 720,
fps ? 30,
socketPath ? "/run/hyprland-headless-stream/stream.sock",
socketPath ? "/run/hypr-stream/stream.sock",
}:
testers.runNixOSTest {
name = "hhstream-vm-hyprland";
@@ -111,8 +111,8 @@ testers.runNixOSTest {
# compositor's IPC socket even though it belongs to `hhstream`.
HYPRCTL_MONITORS = (
"set -eu; "
"sig=$(ls -1 /run/hyprland-headless-stream/hypr | head -n1); "
"XDG_RUNTIME_DIR=/run/hyprland-headless-stream"
"sig=$(ls -1 /run/hypr-stream/hypr | head -n1); "
"XDG_RUNTIME_DIR=/run/hypr-stream"
" HYPRLAND_INSTANCE_SIGNATURE=$sig hyprctl -j monitors"
)
@@ -177,8 +177,8 @@ testers.runNixOSTest {
# minimal PATH, not the guest's environment.systemPackages.
status, out = machine.execute(
"systemd-run --pipe --wait --uid=hhstream"
" --setenv=XDG_RUNTIME_DIR=/run/hyprland-headless-stream"
" --setenv=WAYLAND_DISPLAY=$(cd /run/hyprland-headless-stream"
" --setenv=XDG_RUNTIME_DIR=/run/hypr-stream"
" --setenv=WAYLAND_DISPLAY=$(cd /run/hypr-stream"
" && ls -1 wayland-* | grep -v '\.lock$' | head -n1)"
" sh -c '${grim}/bin/grim -t png - > /tmp/direct.png' 2>&1",
timeout=120,
+241
View File
@@ -0,0 +1,241 @@
# checks.<system>.vm-ipc -- the compositor's own IPC, against the real thing.
#
# This is the check that would have caught the `sun_path` defect, and that is
# its reason for existing. Hyprland's event socket lives at
#
# <runtime dir>/hypr/<HYPRLAND_INSTANCE_SIGNATURE>/.socket2.sock
#
# and at the old 29-character runtime directory that path did not fit in the
# 108 bytes a Unix socket address has:
#
# ERR ]: Socket2 path is too long. (2) IPC will not work.
#
# The *request* socket is shorter by one character and kept working, so
# `hyprctl` answered, every reconciliation that only ever asked `clients -j`
# looked healthy, and the event stream was simply dead. Nothing short of a
# subscriber that waits for a named event can tell those two apart -- so that
# is what the last subtest is, and the subscriber is the shipped
# `hhstreamd.ipc.HyprlandIPC`, not a reimplementation of it.
#
# Both socket paths are asserted by name and measured against the 108-byte
# limit with the numbers printed, because "it fits today" is a fact about this
# instance signature and the next compositor may choose a longer one.
#
# Habits copied from vm-hyprland and vm-sessions: every wait is bounded, each
# assertion is made 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",
}:
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;
};
in
{
name = "hhstream-vm-ipc";
globalTimeout = 1800;
nodes.machine = guest {
inherit width height sessionUser;
apps.foot = {
exec = "${foot}/bin/foot";
# The daemon refuses unlisted arguments and this check passes none:
# `foot` with no argv opens a window, which is all the witness needs.
argsAllow = [ ];
};
};
testScript =
prelude
+ ''
import re
EVENTS = "/tmp/hypr-events.log"
#: linux/un.h: sun_path is 108 bytes including the terminating NUL.
SUN_PATH_MAX = 107
start_all()
bring_up("the compositor and broker")
with subtest("the as-user wrapper propagates exit status"):
# Every assertion below reads machine.succeed/fail through it, so a
# wrapper that swallowed the status would make them all vacuous.
machine.succeed(as_user(TRUE), timeout=120)
machine.fail(as_user(FALSE), timeout=120)
with subtest("both IPC sockets exist, at the names the contract freezes"):
# By name, not by glob. CONTRACT-sessions.md §5 fixes
# <runtime dir>/hypr/<signature>/.socket{,2}.sock, and the defect
# this check exists for was precisely the second of those two being
# absent while the first was there.
try:
signature = machine.succeed(
f"ls -1 {COMPOSITOR_RUNTIME}/hypr | head -n1"
).strip()
assert signature, "no instance directory under the runtime dir"
print(f"instance signature: {signature!r} ({len(signature)} chars)")
base = f"{COMPOSITOR_RUNTIME}/hypr/{signature}"
for name in (".socket.sock", ".socket2.sock"):
path = f"{base}/{name}"
kind = machine.succeed(f"stat -c %F {path}").strip()
assert kind == "socket", f"{path} is a {kind}, not a socket"
print(f"{path} ({len(path)} bytes of {SUN_PATH_MAX})")
assert len(path) <= SUN_PATH_MAX, (
f"{path} is {len(path)} bytes; sun_path holds "
f"{SUN_PATH_MAX}. The compositor cannot have bound this."
)
except Exception:
dump("an IPC socket is missing or does not fit in sun_path")
raise
with subtest("hyprctl answers over the request socket"):
try:
version = machine.succeed(f"{HYPRCTL} version", timeout=120)
print(version)
assert json.loads(version).get("tag"), "version carries no tag"
monitors = compositor("monitors")
assert monitors, "hyprctl reported no monitors at all"
print(
"monitors: "
+ ", ".join(f"{m['name']} {m['width']}x{m['height']}" for m in monitors)
)
except Exception:
dump("the request socket did not answer")
raise
with subtest("the broker's own IPC client reads the same facts"):
# The client under test, not hyprctl: `container` goes through
# ContainerHost -> HyprlandIPC -> the request socket, so a reply
# here is this repository's parser against this compositor.
try:
reply = cli_json("container --json")
print(json.dumps(reply, indent=2, sort_keys=True))
assert reply["compositor"] == "ok", (
f"the broker cannot reach the compositor: {reply.get('error')!r}"
)
assert reply["orphans"] == [], (
f"a fresh machine already has orphan outputs: {reply['orphans']}"
)
except Exception:
dump("the broker's IPC client could not reach the compositor")
raise
with subtest("a socket2 subscriber receives openwindow for a window we create"):
# THE assertion. The subscriber is started first and left blocking
# on the event socket; the window is created after it is listening,
# so an `openwindow` in its log can only have come down the stream.
#
# If the event socket were the truncated one, everything above this
# point would still pass and this would time out -- which is the
# whole shape of the defect.
try:
machine.succeed(f"rm -f {EVENTS}")
machine.succeed(
background(
"ipc-watch",
"/run/current-system/sw/bin/hhs-ipc-watch"
f" --runtime-dir {COMPOSITOR_RUNTIME} --out {EVENTS}"
" --await-event openwindow --timeout 180",
),
timeout=120,
)
# Wait for the subscriber to be connected, not merely spawned:
# it writes its first line after `discover()` has returned and
# before it blocks, so the file appearing is the handshake.
machine.wait_for_file(EVENTS, timeout=60)
print(machine.succeed(f"cat {EVENTS}"))
session_id = machine.succeed(cli("start foot"), timeout=180).strip()
print(f"session: {session_id}")
# One bounded wait, for the unit to exit 0 -- which it does only
# when it has seen the event it was told to await.
machine.wait_until_fails(
"systemctl is-active ipc-watch.service", timeout=120
)
received = machine.succeed(f"cat {EVENTS}")
print(received)
result = machine.succeed(
"systemctl show -p Result --value ipc-watch.service"
).strip()
assert result == "success", (
f"the subscriber exited {result!r}: it never saw an openwindow "
"event. The request socket answers (above) and the event "
"socket does not -- which is exactly the sun_path defect."
)
assert "openwindow" in received, received
except Exception:
dump("no openwindow reached the event subscriber", locals().get("session_id"))
raise
with subtest("the event named the window the compositor also reports"):
# The event is not taken on trust: `openwindow>>address,workspace,
# class,title` carries an address, and the compositor's own client
# list has to agree that such a window exists.
try:
line = [
row
for row in machine.succeed(f"cat {EVENTS}").splitlines()
if row.startswith("openwindow\t")
][0]
payload = line.split("\t", 1)[1]
address = payload.split(",")[0]
print(f"openwindow payload: {payload!r} -> address {address!r}")
assert re.fullmatch(r"[0-9a-f]+", address), (
f"openwindow's first field is not an address: {address!r}"
)
addresses = [c["address"] for c in compositor("clients")]
print(f"compositor clients: {addresses}")
assert any(a.endswith(address) for a in addresses), (
f"the event announced {address} and `clients -j` has {addresses}"
)
except Exception:
dump("the openwindow event and the client list disagree")
raise
with subtest("teardown leaves the compositor with no client of ours"):
try:
reply = cli_json(f"kill --json {session_id}", timeout=180)
assert reply["ok"] is True, reply
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e 'length == 0' >/dev/null", timeout=60
)
except Exception:
dump("a client outlived its session", session_id)
raise
'';
}
)
+591
View File
@@ -0,0 +1,591 @@
# checks.<system>.vm-pointer -- the lease, the driver, and a click that lands.
#
# The lease's arithmetic is already proved by the unit suite with an injected
# clock. What no fake can prove is the half this check is for: that a warp
# through `zwlr_virtual_pointer_v1` reaches a real compositor, that the
# coordinates are the *output's* and not the desktop's, and that the button
# the broker sent arrives at the application underneath it.
#
# ─── "A CLICK LANDS WHERE IT WAS AIMED", AND WHY NOT PIXELS ──────────────────
# PLAN §14 says this must be verified by reading back the application's own
# state. A pixel comparison would prove the compositor drew a cursor
# somewhere; it would not prove any client was told about a button, and a
# cursor drawn at the right place with no `wl_pointer.button` delivered is
# precisely the failure a virtual pointer bound to the wrong output produces.
#
# So the victim is `hhs-pointer-target` (checks/lib/pointer_target.py), a
# Wayland client that prints every pointer event it receives with the
# surface-local coordinates the compositor sent it. The broker captures its
# stdout into the session log, so `hhstream session logs` is the read-back,
# and the assertion is on numbers the *client* reported.
#
# It also reads `$HHSTREAM_APP_ID` and sets its own `xdg_toplevel` app id from
# it, which is what gets its window into the container the pointer aims at.
# `foot` and `wev` cannot: they ignore the environment, so their windows are
# quarantined and there would be nothing under the cursor. See vm-containers.
# ─────────────────────────────────────────────────────────────────────────────
#
# The expiry subtest uses a caller-supplied `--ttl` of a few seconds and waits
# for it in real time. No clock is injected anywhere: an injected clock would
# prove the arithmetic the unit suite already proves, and not the sweeper, the
# driver call it makes, or the button it has to lift.
#
# `sessions.pointer.leaseTtl` is set on the machine anyway, and the acquire
# subtest *prints* it beside the TTL the broker reports. They disagree, and
# that is the point: the module renders the option into the generated TOML and
# `hhstreamd/policy.py` reads neither it nor any flag for it. Printed rather
# than asserted, because the broker is not this slice's file to change.
#
# ─── TWO THINGS THIS CHECK MEASURED, BOTH WORTH READING BEFORE EDITING IT ────
#
# 1. A WARP TO WHERE THE CURSOR ALREADY IS REPORTS NOTHING, and correctly so:
# nothing moved. It is only a trap for a check -- a second `acquire` that
# restores a bookmark the cursor never left delivers no `wl_pointer.motion`,
# so "the bookmark was restored" has no client-side evidence. The restore is
# therefore asserted on the broker's reply, where the bookmark lives, and
# *delivery* is asserted with a warp to somewhere the cursor is not.
#
# 2. `input:follow_mouse = 0` SENDS POINTER EVENTS TO THE FOCUSED WINDOW ONLY,
# and when the window under the cursor is not the focused one, to nobody at
# all. `nix/hyprland-conf.nix` ships it, justified by "No pointer will ever
# exist; do not let focus depend on one" -- a belief this build makes false.
#
# MEASURED, against the shipped config, with two sessions and the second
# one holding focus because its window opened last:
#
# aimed at target-le22h7: it reports [] <- the session the warp named
# focused is target-s76taj: it reports [] <- the session with focus
# cursor now at {'x': 2048, 'y': 288} <- EXACTLY where it was aimed
#
# The compositor moved the cursor to the right pixel, inside the right
# window, on the right output -- and told no client. The same warp and the
# same click are delivered perfectly in the subtests above, where the
# aimed-at session is also the focused one, which is why nothing before
# this check noticed.
#
# That defeats what containers and the lease exist for: an agent can only
# drive whichever session the compositor last focused. So this machine
# overrides the one line through the module's `extraConfig`, and the
# subtest "the cursor reaches a session that does not hold focus" is the
# assertion that goes red if the shipped default comes back.
# `nix/hyprland-conf.nix` is not this slice's file; the fix belongs there,
# and whether it should be `1` (Hyprland's own default, keyboard focus
# follows the cursor too) or a looser setting that leaves keyboard focus
# alone is a decision for the keyboard work in PLAN §6.7.
# ─────────────────────────────────────────────────────────────────────────────
{
testers,
hhstream,
hhsModule,
testTools,
hyprland,
foot,
jq,
grim,
procps,
coreutils,
dejavu_fonts,
width ? 1280,
height ? 720,
sessionUser ? "hermes",
# Short enough that the expiry subtest is seconds and not minutes, long
# enough that a `systemd-run` round trip inside the guest (several seconds)
# fits comfortably inside one lease.
leaseTtl ? 20,
leaseMax ? 120,
}:
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;
};
target = pkgs.writeShellScript "hhs-target-wrapper" ''
exec ${tools}/bin/hhs-pointer-target --app-id "$HHSTREAM_APP_ID" "$@"
'';
in
{
name = "hhstream-vm-pointer";
globalTimeout = 1800;
nodes.machine = guest {
inherit
width
height
sessionUser
leaseTtl
leaseMax
;
pointer = true;
apps.target = {
exec = "${target}";
argsAllow = [ ];
};
# Point 2 of the block at the top of this file. One line, overriding one
# line of nix/hyprland-conf.nix, because that file is not this slice's
# to edit -- not because there is any doubt about it.
extraConfig = "input:follow_mouse = 1";
};
testScript =
prelude
+ ''
import re
LEASE_TTL = ${toString leaseTtl}
POINTER_SOCKET = "/run/hhstream/pointer.sock"
#: wl_pointer surface coordinates are logical pixels. The budget covers
#: two things and nothing else: the protocol's integer extent (the
#: driver scales a normalised coordinate by 0xFFFF, so under a pixel on
#: a 1280-wide output) and Hyprland's default 2px border, which sits
#: between the window box `clients -j` reports and the surface the
#: client is given coordinates in. A pointer bound without an output
#: speaks *global* coordinates and would be out by hundreds, so this
#: tolerance does not blunt the assertion it guards.
TOLERANCE = 6.0
def pointer_log(session_id):
"""Every line the victim has printed so far."""
return machine.succeed(cli(f"logs {session_id} --lines 400"), timeout=120)
def positions(session_id):
"""(x, y) from every `enter`/`motion` line the client printed."""
found = []
for line in pointer_log(session_id).splitlines():
if line.startswith(("pointer enter", "pointer motion")):
pair = re.findall(r"[xy]=([-\d.]+)", line)
if len(pair) == 2:
found.append((float(pair[0]), float(pair[1])))
return found
def buttons(session_id):
"""(code, state, x, y) from every `button` line the client printed."""
found = []
for line in pointer_log(session_id).splitlines():
match = re.match(
r"pointer button code=(\d+) state=(\w+) x=([-\d.]+) y=([-\d.]+)",
line,
)
if match:
found.append(
(
int(match.group(1)),
match.group(2),
float(match.group(3)),
float(match.group(4)),
)
)
return found
def aimed_at(nx, ny):
"""Where a warp to (nx, ny) of the output should land *in the surface*.
Computed from the compositor's own geometry rather than assumed to
be a fraction of the window: Hyprland's default layout leaves 20px
outer gaps, so the window is not the output and the centre of one
is not the centre of the other. Asking `monitors` and `clients`
for both boxes is what makes this an assertion about aiming rather
than about the layout.
"""
monitor = monitor_named(output)
client = [c for c in compositor("clients") if c.get("initialClass") == output][0]
at = client["at"]
return (
monitor["x"] + nx * monitor["width"] - at[0],
monitor["y"] + ny * monitor["height"] - at[1],
)
def close_enough(got, want):
return abs(got[0] - want[0]) <= TOLERANCE and abs(got[1] - want[1]) <= TOLERANCE
start_all()
bring_up("the compositor and broker")
with subtest("the driver unit comes up and binds its socket"):
# Same reasoning as the broker's: `Type=simple` means wait_for_unit
# passes against a crash loop, so the socket and a restart count of
# zero are the honest test. The driver refuses to start at all if
# the compositor offers only a version-1 virtual-pointer manager --
# that refusal is deliberate (coordinates would be global and every
# warp would aim at the wrong output) and shows here as a restart
# loop with its own words in the journal.
try:
machine.wait_for_unit("hhstream-pointer.service", timeout=180)
machine.wait_for_file(POINTER_SOCKET, timeout=120)
machine.succeed("systemctl is-active hhstream-pointer.service")
restarts = machine.succeed(
"systemctl show -p NRestarts --value hhstream-pointer.service"
).strip()
assert restarts == "0", (
f"the driver has restarted {restarts} time(s); read its journal"
)
print(
machine.succeed(
"journalctl --no-pager --boot --unit hhstream-pointer.service"
)
)
except Exception:
dump("the pointer driver did not come up")
raise
with subtest("the broker reports the driver and a free cursor"):
try:
state = cli_json("pointer state --json")
print(json.dumps(state, indent=2, sort_keys=True))
assert state["holder"] is None, state
assert state["buttons"] == [], state
assert state["driver"] == POINTER_SOCKET, state
except Exception:
dump("pointer state is not what a fresh broker should report")
raise
with subtest("a session's window is in its container, under the cursor"):
try:
session_id = machine.succeed(cli("start target"), timeout=180).strip()
output = f"hh-{session_id}"
print(f"session {session_id} -> {output}")
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e --arg m {output}"
" 'any(.initialClass == $m)' >/dev/null",
timeout=120,
)
client = [
c for c in compositor("clients") if c.get("initialClass") == output
][0]
print(json.dumps(client, indent=2, sort_keys=True))
print(json.dumps(monitor_named(output), indent=2, sort_keys=True))
except Exception:
dump("the victim never got a window in its container", locals().get("session_id"))
raise
with subtest("acquire takes the cursor and the seat grows a pointer"):
# The seat of a headless session has *no* pointer capability until
# something creates a virtual one: there is no input device here.
# So the client cannot have bound `wl_pointer` before this point,
# and "target: pointer bound" appearing after the first warp is the
# proof that the driver's `zwlr_virtual_pointer_v1` reached the
# seat -- not merely that the broker thinks it sent something.
try:
reply = cli_json(f"pointer acquire --json {session_id}", timeout=120)
print(json.dumps(reply, indent=2, sort_keys=True))
bookmark = reply["bookmark"]
assert bookmark["output"] == output, bookmark
assert (bookmark["x"], bookmark["y"]) == (0.5, 0.5), (
f"with no bookmark the cursor must go to the centre: {bookmark}"
)
# A GAP, printed rather than asserted: the module's
# `sessions.pointer.leaseTtl` is rendered into the generated
# TOML and the broker reads neither the TOML nor any flag for
# it, so the lease runs on the broker's own default. The number
# below is the evidence.
print(
f"module leaseTtl={LEASE_TTL}s, broker reports "
f"expires_in_s={reply['expires_in_s']}"
)
wait_for(
lambda: "target: pointer bound" in pointer_log(session_id),
timeout=60,
what="the client to bind wl_pointer",
)
print(pointer_log(session_id))
except Exception:
dump("acquire did not reach the compositor", session_id)
raise
with subtest("a warp lands where it was aimed, as the application saw it"):
# Aimed off-centre so a wrong answer cannot coincide with the
# centre the acquire already warped to.
try:
aim = (0.25, 0.75)
before = len(positions(session_id))
moved = cli_json(
f"pointer move --json {session_id} --to {aim[0]},{aim[1]}", timeout=120
)
print(json.dumps(moved, indent=2, sort_keys=True))
assert (moved["bookmark"]["x"], moved["bookmark"]["y"]) == aim, moved
seen = wait_for(
lambda: positions(session_id)[before:],
timeout=60,
what="the client to report the warp",
)
want = aimed_at(*aim)
print(f"the client reports {seen}, aimed at {want}")
assert close_enough(seen[-1], want), (
f"the cursor arrived at {seen[-1]} and was aimed at {want}. "
"An offset of hundreds of pixels means the virtual pointer "
"speaks global coordinates, i.e. it was created without an "
"output."
)
except Exception:
dump("the warp did not land where it was aimed", session_id)
raise
with subtest("a click is delivered there, pressed and released"):
try:
before = len(buttons(session_id))
clicked = cli_json(f"pointer click --json {session_id}", timeout=120)
print(json.dumps(clicked, indent=2, sort_keys=True))
events = wait_for(
lambda: (
buttons(session_id)[before:]
if len(buttons(session_id)) >= before + 2
else None
),
timeout=60,
what="the client to report a press and a release",
)
print(f"the client reports: {events}")
assert {code for code, _, _, _ in events} == {0x110}, (
f"the client was sent {events}, not BTN_LEFT (0x110)"
)
assert [state for _, state, _, _ in events] == ["pressed", "released"], (
f"a click delivered {events}; it must be exactly one press "
"and one release, or something is left held down"
)
want = aimed_at(0.25, 0.75)
for _, state, x, y in events:
assert close_enough((x, y), want), (
f"the {state} arrived at ({x}, {y}), aimed at {want}"
)
except Exception:
dump("the click did not reach the application", session_id)
raise
with subtest("a second acquire is refused with BUSY, naming the holder"):
# The lock is broker-wide because the cursor is one (PLAN §6.2).
try:
other = machine.succeed(cli("start target"), timeout=180).strip()
print(f"second session: {other}")
code, out = machine.execute(
cli(f"pointer acquire {other}") + " 2>&1", timeout=120
)
print(f"exit {code}: {out}")
assert code == 8, f"a contended acquire exited {code}, not 8 (BUSY)"
assert session_id in out, (
f"the refusal does not name the holder {session_id}: {out!r}"
)
except Exception:
dump("a contended acquire was not refused", locals().get("other"))
raise
with subtest("a session that never acquired cannot move the cursor"):
# Exit 9 and not 8: an agent that sees 9 must acquire, one that
# sees 8 must wait, and conflating them is how a retry loop spins.
try:
code, out = machine.execute(
cli(f"pointer move {other} --to 0.5,0.5") + " 2>&1", timeout=120
)
print(f"exit {code}: {out}")
assert code == 9, f"a gesture with no lease exited {code}, not 9"
except Exception:
dump("a gesture without a lease was not refused", other)
raise
with subtest("release frees the lock and leaves the bookmark behind"):
try:
released = cli_json(f"pointer release --json {session_id}", timeout=120)
print(json.dumps(released, indent=2, sort_keys=True))
assert released["buttons_lifted"] == [], released
assert (released["bookmark"]["x"], released["bookmark"]["y"]) == (
0.25,
0.75,
), released
state = cli_json("pointer state --json")
assert state["holder"] is None, state
except Exception:
dump("release did not give the cursor back", session_id)
raise
with subtest("the cursor reaches a session that does not hold focus"):
# Two assertions in one, because they need the same situation: a
# second session exists and its window took focus when it opened
# (the BUSY subtest above started it).
#
# 1. `acquire` restores the bookmark the previous lease left --
# the point of a bookmark is that a gesture is resumable, and
# it is checked on the client's side as well as the broker's.
# 2. A warp is delivered to the session it was AIMED at, not to
# whichever window the compositor last focused -- and the
# focused one is told nothing. The lease and the containers
# are worth nothing if a click aimed at one session arrives at
# another, and `input:follow_mouse` is where that would go
# wrong (see the block at the top of this file).
try:
before = len(positions(session_id))
reply = cli_json(f"pointer acquire --json {session_id}", timeout=120)
print(json.dumps(reply, indent=2, sort_keys=True))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.25, 0.75), (
f"acquire restored to {reply['bookmark']}, not where the "
"previous lease left the cursor"
)
focused = [
c.get("initialClass")
for c in compositor("clients")
if c.get("focusHistoryID") == 0
]
print(f"the compositor's focused window belongs to: {focused}")
assert focused and focused[0] != output, (
f"this subtest needs the OTHER session focused; {focused} is"
)
# Somewhere the cursor is not, so there is a motion to deliver
# (see the note at the top of this file).
elsewhere = (0.6, 0.4)
before_other = len(positions(other))
machine.succeed(
cli(f"pointer move {session_id} --to {elsewhere[0]},{elsewhere[1]}"),
timeout=120,
)
# Waits for EITHER client to report something, so a warp that
# went to the wrong one is a message naming where it went
# rather than a timeout naming nothing.
wait_for(
lambda: positions(session_id)[before:] or positions(other)[before_other:],
timeout=60,
what=f"either {session_id} or {other} to report the warp",
)
mine = positions(session_id)[before:]
theirs = positions(other)[before_other:]
print(f"aimed at {session_id}: it reports {mine}")
print(f"focused is {other}: it reports {theirs}")
print(f"cursor now at {compositor('cursorpos')}")
assert not theirs, (
f"the warp was aimed into {output} and {other}'s window got "
f"it: {theirs}. The compositor is routing pointer events by "
"keyboard focus, not by what is under the cursor -- read "
"input:follow_mouse in nix/hyprland-conf.nix."
)
want = aimed_at(*elsewhere)
print(f"the client reports {mine}, aimed at {want}")
assert close_enough(mine[-1], want), (mine[-1], want)
machine.succeed(cli(f"pointer release {session_id}"), timeout=120)
except Exception:
dump("the warp did not reach the session it was aimed at", session_id)
raise
with subtest("an expired lease is released and its button is lifted"):
# Real time, a caller-supplied TTL, and nothing touching the lease.
# The sweeper is what makes the TTL a promise: without it expiry
# would only be noticed by the next verb, so an agent that pressed
# a button and died would hold the cursor -- with the button down
# -- until somebody else happened to try.
try:
short = 8
cli_json(
f"pointer acquire --json --ttl {short}s {session_id}", timeout=120
)
before = len(buttons(session_id))
machine.succeed(cli(f"pointer down {session_id}"), timeout=120)
held = cli_json("pointer state --json")
print(json.dumps(held, indent=2, sort_keys=True))
assert held["holder"] == session_id, held
assert held["buttons"] == ["left"], (
f"the button is not recorded as down: {held}"
)
# One bounded wait for the deadline to arrive, not a retry of
# the assertion: the lease expires on its own or it does not.
machine.wait_until_succeeds(
cli("pointer state --json") + " | jq -e '.holder == null' >/dev/null",
timeout=short * 6 + 120,
)
state = cli_json("pointer state --json")
print(json.dumps(state, indent=2, sort_keys=True))
assert state["buttons"] == [], (
f"the lease expired with a button still down: {state}"
)
events = wait_for(
lambda: (
buttons(session_id)[before:]
if len(buttons(session_id)) >= before + 2
else None
),
timeout=60,
what="the client to be told the button came back up",
)
print(f"the client reports: {events}")
assert [s for _, s, _, _ in events] == ["pressed", "released"], (
"the application was told the button went down and never "
f"that it came up: {events}. A compositor left holding a "
"button is a drag nobody started."
)
except Exception:
dump("the lease did not expire cleanly", session_id)
raise
with subtest("a broker restart leaves the lock free and the bookmark intact"):
# Leases are stale by definition across a restart (PLAN §6.2); the
# bookmark is not, because it lives in the session record on disk.
try:
cli_json(f"pointer acquire --json {session_id}", timeout=120)
machine.succeed(cli(f"pointer move {session_id} --to 0.8,0.2"), timeout=120)
machine.succeed("systemctl restart hhstream-sessions.service", timeout=180)
machine.wait_for_unit("hhstream-sessions.service", timeout=180)
machine.wait_until_succeeds(cli("list") + " >/dev/null", timeout=120)
state = cli_json("pointer state --json")
print(json.dumps(state, indent=2, sort_keys=True))
assert state["holder"] is None, (
f"the restarted broker believes {state['holder']} still holds "
"a lease that died with the process that granted it"
)
record = cli_json(f"status --json {session_id}")["session"]
bookmark = (record.get("pointer") or {}).get("bookmark")
print(json.dumps(bookmark, indent=2, sort_keys=True))
assert bookmark is not None, record
assert (bookmark["x"], bookmark["y"]) == (0.8, 0.2), (
f"the bookmark did not survive the restart: {bookmark}"
)
assert bookmark["output"] == output, bookmark
except Exception:
dump("the restart lost the lock or the bookmark", session_id)
raise
with subtest("the driver is still reachable after the broker restarted"):
# The socket the two speak over lives in the broker's runtime
# directory. Without `RuntimeDirectoryPreserve` on that unit,
# restarting the broker deletes /run/hhstream and takes
# pointer.sock with it -- leaving the driver listening on an
# unlinked inode and every pointer verb answering exit 10 while
# `systemctl status hhstream-pointer` still says "active".
try:
machine.succeed(f"test -S {POINTER_SOCKET}")
machine.succeed("systemctl is-active hhstream-pointer.service")
reply = cli_json(f"pointer acquire --json {session_id}", timeout=120)
print(json.dumps(reply, indent=2, sort_keys=True))
assert reply["bookmark"]["x"] == 0.8, reply
machine.succeed(cli(f"pointer release {session_id}"), timeout=120)
except Exception:
dump("the driver was unreachable after the broker restarted", session_id)
raise
'';
}
)
+1 -1
View File
@@ -214,7 +214,7 @@ testers.runNixOSTest {
CONTROL = "${controlSocket}"
CONTROL_DIR = "/run/hhstream"
IDLE_TIMEOUT = ${toString idleTimeout}.0
COMPOSITOR_RUNTIME = "/run/hyprland-headless-stream"
COMPOSITOR_RUNTIME = "/run/hypr-stream"
# The module pins the compositor's XDG_RUNTIME_DIR; the instance signature
# under it is the only part not known ahead of time. Root may connect to
+70 -14
View File
@@ -6,21 +6,35 @@
│ Hyprland 0.56.2, no physical monitor │
│ private XDG_RUNTIME_DIR, as `user` │
│ outputs come from `outputs[]` │
└───────────────┬──────────────────────────┘
│ Wayland session
▼
┌──────────────────────────────────────────┐
│ hyprland-headless-stream.service │
│ hhstream-server │
│ capture ──▶ one "latest frame" slot │
│ accept ──▶ a thread per client │
└───────────────┬──────────────────────────┘
│ AF_UNIX, mode 0660
▼
many clients ── hhstream-client / any socket reader
│ + one headless output per session │
└───┬───────────┬───────────────┬──────────┘
│ │ │
IPC: request / │ │ Wayland │ Wayland
event sockets │ │ session │ (virtual pointer)
│ ▼ │
│ ┌────────────────────────┴─────────┐
│ │ hyprland-headless-stream.service │
│ │ hhstream-server │
│ │ capture ──▶ one frame slot │
│ │ accept ──▶ thread per client│
│ └───────────────┬──────────────────┘
│ │ AF_UNIX, mode 0660
│ ▼
│ many clients ── hhstream-client / any reader
│
┌────────────┴──────────────┐ ┌──────────────────────────┐
│ 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
│ AF_UNIX control.sock, mode 0660
▼
hhstream session ... (the CLI an agent drives)
```
Three pieces, deliberately separate:
Five pieces, deliberately separate:
1. **The compositor** (`Hyprland`, unchanged upstream) renders into virtual
outputs. It knows nothing about frames on a socket.
@@ -29,6 +43,35 @@ Three pieces, deliberately separate:
3. **The client** is any process that can open a Unix socket and read the
contract's byte format. The shipped `hhstream-client` is a convenience, not a
requirement.
4. **The session broker** (`hhstreamd`) starts allowlisted applications as
tracked sessions, gives each one its own headless output and workspace (a
*container*), reads the compositor back over its own IPC, and owns the
pointer lease. It is the only part that keeps state across a restart.
5. **The pointer driver** (`hhstream-pointer`) is a Wayland client of the same
session that creates one `zwlr_virtual_pointer_v1` per output. It holds no
lease and no session state: the broker decides, the driver executes. It is
a separate process because a Wayland client needs its own connection and a
driver blocked on the compositor must not stall session lifecycle.
## Why containers are outputs
A session's container is a headless **output**, not just a workspace, and the
two consequences are the reason:
- `grim -o hh-<id>` captures exactly one session, so one agent's screenshot
cannot contain another's window;
- `zwlr_virtual_pointer_manager_v1` version 2 creates a pointer *bound to an
output*, so a warp to (0.5, 0.5) is the middle of that session's screen and
not the middle of the desktop. Version 1 is refused rather than used,
because its coordinates are global and every click would land somewhere
plausible and wrong.
The cursor itself is singular — there is one seat — so pointer access is
serialised by a broker-wide **lease**: one holder, a TTL the broker enforces
with its own sweeper, and buttons lifted on release or expiry. The lease
disciplines these sessions; it does not enforce against a hostile client,
which can create its own virtual pointer (that is what sandboxing, not the
lease, would fix).
## Why one frame, not a queue
@@ -71,7 +114,20 @@ So the requirements are:
| `checks.vm-basic` | the module actually starts both units, the socket appears with the right owner/mode, the Hello parses and two frames arrive — with a fake capture program |
| `checks.vm-hyprland` | the real thing: headless Hyprland comes up in the VM and `grim` captures a frame of the configured size |
| `checks.vm-sessions` | the session broker side: a real application runs as a tracked session on the compositor, the compositor's IPC sees its window, the idle reaper fires for real (and does not fire when the session is touched), and a broker restart adopts its sessions back |
| `checks.vm-ipc` | both IPC sockets exist at the names the contract freezes and fit in `sun_path`; `hyprctl` answers; and a subscriber on the **event** socket receives an `openwindow` for a window the test creates — the one assertion that can tell a working event socket from a silently truncated one |
| `checks.vm-containers` | one `hh-*` output per session at the container mode, the application's window on it, a second window of the same application beside the first, an unmatched window quarantined instead of landing on whoever had focus, `grim -o` isolating one container, and teardown removing the output and releasing its workspace slot |
| `checks.vm-pointer` | the driver binds a version-2 virtual pointer; acquire warps into the container and restores from the bookmark; a click arrives at the application, which reports the coordinates it was delivered at; a second acquire is BUSY naming the holder; an expired lease is swept and its held button lifted; a broker restart leaves the lock free, the bookmark intact and the driver reachable |
The three session checks share one guest (`checks/lib/session-machine.nix`) and
one set of test-script helpers (`checks/lib/session-prelude.nix`); the helpers
contain no assertions, so each check's script is still a complete account of
what it proves.
`vm-hyprland` is the only check that can fail for reasons outside this repo, so
it is kept separate from `vm-basic` on purpose: when it fails, the compositor's
log is the answer and the other two layers are already known good.
log is the answer and the other two layers are already known good.
**Run the VM checks one at a time.** Each boots a guest with a
software-rendered compositor; two at once on a two-core machine make the
timing-sensitive assertions flake, and a flaky green is worth less than a slow
one.
+66 -10
View File
@@ -9,7 +9,20 @@ else. If something here is wrong or missing, **stop and report it in your final
message** — the parent edits this file, not you. Do not widen your slice to work
around a gap.
Version: sessions-v1 (2026-10-01).
Version: sessions-v2 (2026-10-02). v1 was the freeze the four slices built against;
v2 records the decisions their reports asked for. Every v2 change is either a
clarification or an addition — **no v1 signature changed meaning** — so v1 code
stays valid except where noted. Changes:
| § | Change | Why |
| --- | --- | --- |
| §3.1 | `Monitor` gains `id: int` | `clients -j` reports a client's monitor as a numeric **index**, `Workspace.monitor` as a **name**, so without an id there is no way to join a client to its output. Slice D's aiming is output-local. |
| §3.1 | `Client.stable_id` defined as `"<initial_class>:<pid>"` (fallback `address`); absent `pid` becomes `-1`; `Event.data` is a per-event field table plus always-present `raw`/`args`; `request_timeout_s` is an overridable class attribute (2 s); `version()` returns the compositor's banner verbatim | What slice B had to decide, now written down instead of re-derived. |
| §3.2 | `quarantine_argv()` replaces `quarantine_plan()`, returning `list[list[str]] \| None` | A quarantine rule is not a container: no output, no numbered workspace, no mode, and `container_plan` refuses a zero size. **Integration updates `containers.py` and its tests to this shape.** |
| §3.3 | `mark()` added; `expire()` precedence documented | §3.3 gave no way to record a position, so `LeaseOutcome.bookmark` could only ever be `None` and `pointer.acquire … restore?` had nothing to restore. |
| §3.4 | Vendored protocol is permitted, and the XML path is corrected | The v1 path was wrong (`share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml`). |
| §5 | The broker state dir is stated as an *option default* with this machine's override; the frame socket is named | §5's value was the deployed one, not the default, and the frame socket was missing while `docs/CONTRACT.md` still documents the old one. |
---
@@ -57,7 +70,7 @@ class CompositorUnavailable(Exception):
@dataclass(frozen=True)
class Monitor:
name: str; x: int; y: int; width: int; height: int; scale: float
id: int; name: str; x: int; y: int; width: int; height: int; scale: float
active_workspace_id: int | None
@dataclass(frozen=True)
@@ -103,6 +116,24 @@ Rules: every method raises `CompositorUnavailable` rather than returning a
guess. `clients()` parses `clients -j`; `monitors()` parses `monitors -j`;
`workspaces()` parses `workspaces -j`. Stdlib only.
Decisions, so they are not re-derived per caller:
- **A client's monitor is an index, an output's name is a name.** `Client.monitor`
is the numeric index rendered as text (or `None` when the reply said nothing);
join it to a `Monitor` through `Monitor.id`. `Workspace.monitor` is a name.
- **`Client.stable_id`** is `"<initial_class>:<pid>"`, falling back to
`address`. Hyprland publishes no such key; this is the identity that survives a
remap, and the launcher sets the class per session.
- **An absent `pid` becomes `-1`**, not `0` — no process has pid `-1`.
- **Events are positional on the wire** (`name>>a,b,c`). `Event.data` is built
from a per-event field table, with the last named field absorbing the remaining
commas (titles contain them); `raw` and `args` are always present so an unknown
event is still usable. An event that carries fewer fields than the table names
only what arrived — never invented empties.
- **`request_timeout_s`** is a class attribute (2 s) on `HyprlandIPC` because
`__init__` is frozen.
- **`version()` returns the compositor's banner verbatim**, not a parsed number.
### 3.2 `hhstreamd/containers.py` (C)
**Pure logic. No I/O, no subprocess, no socket, no import of `ipc.py`.** It
@@ -139,9 +170,18 @@ def app_id_for(session_id: str) -> str: ...
# the bare "hh-<session-id>" the launcher sets on the app; "^hh-<session-id>$"
# is built in container_plan.
def quarantine_plan(quarantine_workspace: str) -> ContainerPlan | None: ...
def quarantine_argv(quarantine_workspace: str) -> list[list[str]] | None: ...
# the backstop: every window matching no container goes to
# special:quarantine. Returns the keyword argv, or None if disabled.
# special:quarantine. Returns the keyword argv, or None when the target is
# blank/whitespace (which is how "disabled" is spelled).
#
# Deliberately NOT a ContainerPlan: a quarantine rule has no output, no
# numbered workspace and no mode. The argv shape mirrors the per-session
# rule, with a catch-all class:
# ["hyprctl","keyword","windowrule",
# f"match:initial_class .*, workspace {target}"]
# It must be installed BEFORE any per-session rule, or the catch-all wins.
# That ordering is the caller's, and this module cannot enforce it.
class WorkspaceAllocator:
def __init__(self, base: int, count: int) -> None: ...
@@ -183,6 +223,11 @@ class PointerLease:
def acquire(self, session_id: str) -> str: ... # -> lease_id; raises LeaseBusy
def refresh(self, session_id: str, lease_id: str) -> None: ... # raises LeaseInvalid
def release(self, session_id: str, lease_id: str, reason: str) -> LeaseOutcome: ...
def mark(self, session_id: str, lease_id: str, bookmark: Bookmark) -> None: ...
# records where the cursor was left, called on every move and before
# release. Added in v2: without it LeaseOutcome.bookmark could only ever
# be None, so `pointer.acquire --restore` had nothing to restore.
# raises LeaseInvalid for a non-holder.
def state(self) -> dict: ... # {"holder": str|None, "since": float|None,
# "lease_id": str|None, "expires_at": float|None}
def expire(self) -> LeaseInfo | None: ...
@@ -192,6 +237,13 @@ class PointerLease:
def unpress(self, session_id: str, button: str) -> list[str]: ...
def pressed(self) -> list[str]: ...
**`expire()` carries no bookmark and no lifted buttons** — it returns the lease
that was released, nothing more. The broker therefore has two duties on expiry:
read `pressed()` *before* calling `expire()` if it wants the lease's view of what
was down, and lift those buttons on the driver (`release_all`), because the lease
cannot lift them itself. The bookmark is not `expire()`'s to keep: the broker
already stores it with the session (§1), which is where it belongs.
def window_to_absolute(point: tuple[int, int], window: tuple[int, int, int, int],
monitor: tuple[int, int, int, int]) -> tuple[float, float]:
# point is window-local pixels; window is (x, y, w, h) global; monitor is
@@ -209,11 +261,14 @@ blocked driver must not stall the broker.
- Command line the module will pass, exactly:
`hhstream-pointer --socket /run/hhstream/pointer.sock --compositor-runtime-dir /run/hypr-stream`
- Uses **pywayland** (packaged as `python3Packages.pywayland`) and the **wlr
virtual pointer XML** from `pkgs.wlr-protocols`
(`share/wayland-protocols/wlr-unstable/zwlr-virtual-pointer-unstable-v1.xml`).
Compile the protocol at build time or vendor the generated module under your
directory — your choice, stated in your report. `pyproject.toml` and
`nix/package.nix` are yours precisely so this is possible.
virtual pointer XML** from `pkgs.wlr-protocols`, which lives at
`share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml` (the v1
contract had this path wrong: different middle directory, and no `z` prefix on
the filename). **Vendoring the generated module is explicitly permitted** (v2):
generating at build time puts a code generator between a checkout and a runnable
driver, and the dev shell has neither the XML nor a scanner. State which you
did. `pyproject.toml` and `nix/package.nix` are yours precisely so this is
possible.
- Binds `zwlr_virtual_pointer_manager_v1` **version 2** and uses
`create_virtual_pointer_with_output(seat, output, id)` so coordinates are
output-local. If only version 1 is offered, **report it — never silently fall
@@ -269,9 +324,10 @@ reset the idle clock.
| Compositor runtime dir | `/run/hypr-stream` — **must be ≤ 25 chars** (socket paths must stay under `sun_path`'s 108-byte limit) |
| Compositor request socket | `<runtime dir>/hypr/<signature>/.socket.sock` |
| Compositor event socket | `<runtime dir>/hypr/<signature>/.socket2.sock` |
| Frame socket (published) | `<runtime dir>/stream.sock` — default `/run/hypr-stream/stream.sock`. Also frozen in `docs/CONTRACT.md`, which v1 of this file left disagreeing with it. |
| Broker control socket | `/run/hhstream/control.sock` |
| Broker↔driver socket | `/run/hhstream/pointer.sock` |
| Broker state dir | `/var/lib/hermes/hhstream-sessions` |
| Broker state dir | **option default** `/var/lib/hhstream`; this machine sets `/var/lib/hermes/hhstream-sessions` (`sessions.stateDir`). v1 listed the deployed value, which read as a contradiction of the module. |
| Session runtime dir | `/run/hhstream/sessions/<session-id>` |
| Container output name | `hh-<session-id>` |
| Container workspace band | `1000 + slot`, allocated from the registry's free list |
+10 -3
View File
@@ -1,4 +1,11 @@
# Wire contract (v1)
# Wire contract (v2)
**v2 changes nothing on the wire.** The published socket's documented *default*
moved from `/run/hyprland-headless-stream/stream.sock` to
`/run/hypr-stream/stream.sock`: the old runtime directory pushed the compositor's
own IPC *event* socket past `sun_path`'s 108-byte limit, so it never bound (see
`docs/CONTRACT-sessions.md` §5). Message sequence, framing and failure semantics
are unchanged, so a v1 reader is still a correct reader.
This file is the interface. Code on either side may change freely; **this
document may not**, without bumping the version.
@@ -7,7 +14,7 @@ document may not**, without bumping the version.
- Transport: `AF_UNIX`, `SOCK_STREAM`.
- Path: whatever `services.hyprland-headless-stream.socketPath` says.
Default `/run/hyprland-headless-stream/stream.sock`.
Default `/run/hypr-stream/stream.sock`.
- Ownership: the service user (`user` option, default `hhstream`), mode `0660`.
- The server accepts **any number of concurrent clients**. Each client gets its
own copy of the header and of every subsequent frame. A client disconnecting
@@ -78,7 +85,7 @@ Namespace: `services.hyprland-headless-stream`
| Option | Type | Default | Meaning |
|---|---|---|---|
| `enable` | bool | `false` | turn everything on |
| `socketPath` | str | `/run/hyprland-headless-stream/stream.sock` | published socket |
| `socketPath` | str | `/run/hypr-stream/stream.sock` | published socket |
| `user` / `group` | str | `hhstream` | owner of the session and the socket |
| `frameRate` | int | `30` | capture target, becomes `fps` in Hello |
| `format` | enum `png`/`jpeg` | `png` | frame encoding |
+39 -4
View File
@@ -27,6 +27,37 @@ examples/agent-eyes record --seconds 10 --out clip.mp4
Both `shot` and `record` want nothing but `hhstream-client`, `python3` and
`ffmpeg`, which are all on the system PATH; only `chromium` needs `nix develop`.
## The session verbs these helpers do not wrap
`agent-eyes` is the *frame* side of the session: look at the screen, put an app
on it, film it. Everything that tracks an application, gives it its own screen
or drives a cursor at it lives on the `hhstream session` namespace and is not
wrapped here, because it needs the broker and `agent-eyes` deliberately does
not:
```bash
hhstream session start chromium -- https://example.com # prints the bare id
hhstream session list # WS, OUTPUT, POINTER
hhstream session container <id> # its output and workspace
hhstream shot --output hh-<id> --out /tmp/just-that.png # one container alone
hhstream session pointer acquire <id> # prints the lease id
hhstream session pointer move <id> --to 0.5,0.5 # 0..1, within ITS output
hhstream session pointer click <id>
hhstream session pointer release <id>
```
Two things worth knowing before using them:
- **Coordinates are output-normalised, 0..1**, inside that session's own
container — never window-local pixels. The broker's IPC client carries no
window geometry, so there is nothing honest to convert from.
- **No pointer verb counts as activity.** A session being driven is still a
session nobody has said they want kept; only `touch` resets the idle clock.
The lease id is cached under `$XDG_RUNTIME_DIR/hhstream`, which is why the
gesture verbs need no flag; `--lease` and `$HHSTREAM_LEASE` override it.
## `agent-eyes-demo.py`
Puts a real browser on the headless screen, drives it, and films the result by
@@ -93,10 +124,14 @@ Two notes for anyone editing that file:
Hyprland draws the error *across the screen*, which lands in the recording.
Always check an edit with `Hyprland --verify-config --config <file>` — it does
not need a display, so it costs seconds instead of a rebuild.
- `hyprctl` **cannot connect** to this session: the compositor names its IPC
socket `.socket.so`/`.socket.s` instead of `.socket.sock`, so nothing using the
documented path works. Do not plan on `hyprctl` for window control — measure
what you need from the frames instead.
- `hyprctl` **works** against this session; an older note here claimed the
compositor misnames its IPC socket, which was wrong. The real defect was path
length: `$XDG_RUNTIME_DIR` was `/run/hyprland-headless-stream` (29 chars) and
the event socket `hypr/<signature>/.socket2.sock` did not fit in `sun_path`, so
the compositor logged `ERR ]: Socket2 path is too long. (2) IPC will not work.`
while the request socket kept answering — which is why the wrong diagnosis
survived. The runtime directory is now `/run/hypr-stream`, and `nix/module.nix`
asserts it stays ≤ 25 characters.
### Posting the result to a chat
+1 -1
View File
@@ -16,7 +16,7 @@
# predates the group membership.
set -euo pipefail
SOCKET=${AGENT_EYES_SOCKET:-/run/hyprland-headless-stream/stream.sock}
SOCKET=${AGENT_EYES_SOCKET:-/run/hypr-stream/stream.sock}
RUNDIR=$(dirname "$SOCKET")
GROUP=${AGENT_EYES_GROUP:-hhstream}
CLIENT=${AGENT_EYES_CLIENT:-hhstream-client}
+2 -2
View File
@@ -50,8 +50,8 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "src"))
from hhstream import protocol # noqa: E402 (path set above)
DEFAULT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
DEFAULT_RUNTIME_DIR = "/run/hyprland-headless-stream"
DEFAULT_SOCKET = "/run/hypr-stream/stream.sock"
DEFAULT_RUNTIME_DIR = "/run/hypr-stream"
def log(message: str) -> None:
+382 -10
View File
@@ -14,8 +14,38 @@ let
# socket of the session and, by default, the published frame socket too.
# `RuntimeDirectoryPreserve` keeps it (and the Wayland socket) alive across a
# restart of either unit.
runtimeDirName = "hyprland-headless-stream";
#
# The name is short on purpose, and the assertion below is what keeps it that
# way. A Unix socket address carries its path inside `sun_path`, which is 108
# bytes including the terminating NUL (linux/un.h), and the compositor puts
# its IPC sockets under this directory:
#
# <runtimeDir>/hypr/<HYPRLAND_INSTANCE_SIGNATURE>/.socket.sock requests
# <runtimeDir>/hypr/<HYPRLAND_INSTANCE_SIGNATURE>/.socket2.sock events
#
# Of that budget, 20 characters are fixed and the instance signature (~30) is
# Hyprland's to choose; this directory's name is the only part we control. At
# the previous name -- `/run/hyprland-headless-stream`, 29 characters -- the
# event socket did not fit and the compositor refused to bind it:
#
# ERR ]: Socket2 path is too long. (2) IPC will not work.
#
# The *request* socket kept answering `hyprctl` anyway (both ends agreed on a
# residual truncated path), which is why the broken event socket went
# unnoticed. docs/CONTRACT-sessions.md §5 freezes the ceiling at 25.
runtimeDirName = "hypr-stream";
runtimeDir = "/run/${runtimeDirName}";
runtimeDirMaxLength = 25;
# The broker's own runtime directory: its control socket and, when the
# pointer driver is enabled, the private socket the two speak over. Both
# paths are frozen in docs/CONTRACT-sessions.md §5, and the driver's command
# line is frozen with them, so this is a name for a constant rather than
# something a consumer may move.
brokerRuntimeDirName = "hhstream";
brokerRuntimeDir = "/run/${brokerRuntimeDirName}";
controlSocket = "${brokerRuntimeDir}/control.sock";
pointerSocket = "${brokerRuntimeDir}/pointer.sock";
socketDir = builtins.dirOf cfg.socketPath;
@@ -58,6 +88,64 @@ let
exit 1
'';
# Open the compositor's IPC directory to its own group.
#
# MEASURED, in checks/vm-ipc.nix, which is the check that exists to find
# exactly this:
#
# drwxr-x--- hhstream hhstream /run/hypr-stream
# drwx------ hhstream hhstream /run/hypr-stream/hypr <-- 0700
# srw-rw---- hhstream hhstream /run/hypr-stream/stream.sock
# srwxrwx--- hhstream hhstream /run/hypr-stream/wayland-1
#
# The unit's `UMask=0007` reaches everything the compositor creates with a
# permissive mode -- the Wayland socket is group-accessible, which is how a
# launched application connects at all -- but Hyprland creates its *instance*
# directory with `S_IRWXU`, i.e. 0700 with no umask left to subtract. So the
# request and event sockets underneath it are reachable by `hhstream` and by
# nobody else.
#
# The broker runs as the operator's account with `hhstream` as a supplementary
# group, deliberately (it starts processes that must be the operator's). It
# therefore could not open the IPC directory at all, and the symptom was not
# an error: `HyprlandIPC.discover` raised `CompositorUnavailable`, the broker
# degraded exactly as it is designed to, and every session got
# `container: degraded` while `container.list` said `compositor: absent`. A
# whole capability silently absent, on a machine where nothing looked wrong.
#
# Group access, not world: the directory stays 0750 and the sockets 0660, so
# this grants the compositor's own group what it already has on the Wayland
# socket beside it, and nothing more.
#
# Run only when the broker is enabled (nothing else needs the IPC sockets),
# and allowed to fail the unit: a compositor whose IPC the broker cannot
# reach is a session with no containers and no pointer, and discovering that
# from a half-working desktop is how this went unnoticed in the first place.
openIpcDirectory = pkgs.writeShellScript "hhstream-open-ipc-directory" ''
set -eu
hypr="$XDG_RUNTIME_DIR/hypr"
for _ in $(${lib.getExe' pkgs.coreutils "seq"} 1 300); do
if [ -n "$(${lib.getExe' pkgs.coreutils "ls"} -1 "$hypr" 2>/dev/null)" ]; then
break
fi
${lib.getExe' pkgs.coreutils "sleep"} 0.1
done
if [ ! -d "$hypr" ]; then
echo "no $hypr after 30s: the compositor bound no IPC socket" >&2
exit 1
fi
${lib.getExe' pkgs.coreutils "chmod"} 0750 "$hypr"
for instance in "$hypr"/*; do
[ -d "$instance" ] || continue
${lib.getExe' pkgs.coreutils "chmod"} 0750 "$instance"
for sock in "$instance"/.socket.sock "$instance"/.socket2.sock; do
[ -S "$sock" ] || continue
${lib.getExe' pkgs.coreutils "chmod"} 0660 "$sock"
done
${lib.getExe' pkgs.coreutils "ls"} -la "$instance"
done
'';
# The server needs WAYLAND_DISPLAY pointing at the socket the compositor
# actually bound. This cannot be an `Environment=` line, because the name is
# only known once the compositor is up — systemd's ExecStartPre cannot export
@@ -82,14 +170,49 @@ let
# defence for compositor builds that do not sd_notify, and it is why this is
# not a plain `After=` ordering.
# The session broker's app allowlist, in the daemon's own config format. The
# daemon treats a missing file as an empty allowlist and refuses every `start`
# with the path it looked for, so generating this is what makes
# `sessions.enable = true` useful rather than decorative.
# The session broker's config, in the daemon's own format (PLAN §10). It
# carries the app allowlist, which is what makes `sessions.enable = true`
# useful rather than decorative: the daemon treats a missing file as an empty
# allowlist and refuses every `start` with the path it looked for.
#
# ─── A GAP, STATED HERE RATHER THAN HIDDEN ───────────────────────────────
# `hhstreamd/policy.py:policy_from_dict` reads `[defaults]` and `[apps]` and
# nothing else, and `hhstreamd/__main__.py:serve` builds its `ManagerConfig`
# from command-line flags that have no counterpart for any of these numbers.
# So the `[compositor]` and `[pointer]` tables below, and `max_containers`,
# are written and *not read*: the broker falls back to its own defaults
# (container band 1000, 4 slots, 1280x720; lease 30 s / 300 s), which happen
# to agree with the defaults here, so a deployment that leaves these options
# alone behaves exactly as this file says. One that changes them is ignored.
#
# They are rendered anyway, and with §10's own key names, because that is the
# interface the broker is specified to read and writing it is what makes the
# omission a one-file fix rather than a redesign. `sessions.pointer.enable`
# is the one option here with teeth today: it decides whether the driver unit
# exists, which is what the broker's `pointer_socket` finds or does not find.
#
# Two key names differ from §10 on purpose. §10 puts `max_sessions` and
# `max_containers` under `[broker]`, but the broker reads `max_sessions` from
# `[defaults]` — so `max_containers` is written beside it, where the code
# that will read it already looks. And §10 has no key for
# `containers.enable`, so `containers_enabled` is named here.
# ──────────────────────────────────────────────────────────────────────────
sessionsConfig = pkgs.writeText "hhstream-sessions.toml" ''
[defaults]
max_sessions = ${toString cfg.sessions.maxSessions}
idle_timeout_s = ${toString cfg.sessions.idleTimeout}
max_containers = ${toString cfg.sessions.containers.max}
[compositor]
runtime_dir = ${builtins.toJSON runtimeDir}
containers_enabled = ${lib.boolToString cfg.sessions.containers.enable}
workspace_base = ${toString cfg.sessions.containers.workspaceBase}
container_mode = ${builtins.toJSON cfg.sessions.containers.mode}
[pointer]
enabled = ${lib.boolToString cfg.sessions.pointer.enable}
lease_ttl_s = ${toString cfg.sessions.pointer.leaseTtl}
lease_max_s = ${toString cfg.sessions.pointer.leaseMax}
${lib.concatStringsSep "\n" (
lib.mapAttrsToList (name: app: ''
@@ -160,7 +283,7 @@ in {
socketPath = lib.mkOption {
type = lib.types.str;
default = "/run/hyprland-headless-stream/stream.sock";
default = "/run/hypr-stream/stream.sock";
description = "Where the frame server publishes frames.";
};
@@ -386,6 +509,117 @@ in {
'';
};
containers = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Give each session its own headless output and workspace — a
*container* (PLAN §5). The broker creates `hh-<session-id>` on
`start`, binds a window rule to it so the application's window
lands there and nowhere else, and removes the output on teardown,
which takes the container with it.
Without it every application shares the main output, so two
sessions see each other's windows and `grim -o` has nothing to
aim at. It is on by default because every other part of this
option tree assumes it; turn it off to run a single application
on the main screen, as the pre-container module did.
'';
};
max = lib.mkOption {
type = lib.types.ints.positive;
default = 2;
description = ''
How many containers may exist at once.
Each one is a real render target: at `vfr = false` the compositor
renders every output every frame, so this is a CPU budget and not
a preference. The default of 2 is the plan's conservative starting
point for a two-core machine and is explicitly waiting on a
measurement (PLAN §5.5, experiment 2) — raise it from a number you
measured, not from one you hoped for.
Distinct from {option}`sessions.maxSessions`: a session may run
without a container (degraded, if the compositor was unreachable),
so the two caps bound different things. Exhausting this one refuses
the `start` with exit 6 rather than quietly sharing a screen.
'';
};
mode = lib.mkOption {
type = lib.types.strMatching "[0-9]+x[0-9]+";
default = "1280x720";
description = ''
The size each container's output is set to, `WIDTHxHEIGHT`
(docs/CONTRACT-sessions.md §5 freezes the default at 1280x720).
This is the resolution an application sees and the resolution
`grim -o hh-<id>` captures, so it is also the cost per container.
'';
};
workspaceBase = lib.mkOption {
type = lib.types.ints.positive;
default = 1000;
description = ''
First workspace number of the reserved band containers are
allocated from; a container gets `workspaceBase + slot`.
The band exists so a container never collides with a workspace the
operator uses by hand. Numbers this high are not reachable by the
default keybindings, which is the point.
'';
};
};
pointer = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Run `hhstream-pointer`, the driver that moves this session's one
cursor on the broker's instruction (`hhstream session pointer …`).
Off by default, and the default is the honest one: input injection
is a capability distinct from running applications, the cursor is
singular so it has to be leased, and nothing in the compositor
stops a *hostile* client from creating its own virtual pointer
(PLAN §6.6) — the lease disciplines our sessions, it does not
enforce against theirs.
With it off, every pointer verb answers `driver_unavailable`
(exit 10) rather than pretending: the broker looks for the driver's
socket and does not find one.
'';
};
leaseTtl = lib.mkOption {
type = lib.types.ints.positive;
default = 30;
description = ''
Seconds a pointer lease may go without a pointer verb before the
broker force-releases it and lifts anything still pressed.
This is what makes the lease a promise rather than a hope: an agent
that acquired the cursor, pressed a button and died holds neither
for longer than this. Every gesture verb refreshes it.
'';
};
leaseMax = lib.mkOption {
type = lib.types.ints.positive;
default = 300;
description = ''
Hard ceiling on a single lease, in seconds, refreshed or not.
{option}`sessions.pointer.leaseTtl` can be extended indefinitely by
a caller that keeps sending verbs; this one cannot, so one session
can never own the cursor forever.
'';
};
};
stateDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/hhstream";
@@ -414,6 +648,53 @@ in {
assertion = lib.hasPrefix "/" cfg.socketPath;
message = "services.hyprland-headless-stream.socketPath must be an absolute path.";
}
# Structural, not cosmetic: see the `runtimeDirName` comment above. The
# ceiling exists so the compositor's *event* socket still fits in
# `sun_path`, and the symptom of breaking it is silent -- the request
# socket keeps answering, so `hyprctl` looks fine while every event-driven
# feature is dead.
{
assertion = builtins.stringLength runtimeDir <= runtimeDirMaxLength;
message = ''
The compositor runtime directory "${runtimeDir}" is ${
toString (builtins.stringLength runtimeDir)
} characters; it must be at most ${toString runtimeDirMaxLength}.
Hyprland's event socket is <runtime dir>/hypr/<instance signature>/.socket2.sock.
A longer directory pushes that path past the 108 bytes a Unix socket address
has for `sun_path`, and the compositor then refuses to bind it:
ERR ]: Socket2 path is too long. (2) IPC will not work.
Nothing appears broken when that happens -- the shorter request socket still
answers `hyprctl` -- but the event stream never arrives, so every feature that
watches the compositor (window and workspace tracking, session containers)
stops working. docs/CONTRACT-sessions.md §5 freezes this limit; shorten the
directory rather than raising it.
'';
}
{
assertion = cfg.sessions.pointer.leaseTtl <= cfg.sessions.pointer.leaseMax;
message = ''
services.hyprland-headless-stream.sessions.pointer.leaseTtl
(${toString cfg.sessions.pointer.leaseTtl}s) is longer than leaseMax
(${toString cfg.sessions.pointer.leaseMax}s), so the hard ceiling would fire
before the idle timeout could and the idle timeout would never be reached.
leaseMax is the cap a caller cannot refresh past; leaseTtl is the one it can.
'';
}
{
# A driver with no broker is a process holding a Wayland connection and
# a socket nobody will ever connect to: the broker owns the lease, and
# the driver is deliberately stateless (CONTRACT-sessions.md §3.4).
assertion = !cfg.sessions.pointer.enable || cfg.sessions.enable;
message = ''
services.hyprland-headless-stream.sessions.pointer.enable needs
sessions.enable = true. The pointer driver takes its instructions from the
session broker -- it holds no lease of its own and has no other client --
so without the broker it would bind a socket nothing connects to.
'';
}
{
assertion = !cfg.sessions.enable || lib.hasAttr cfg.sessions.user config.users.users;
message = ''
@@ -447,6 +728,24 @@ in {
mode = "0700";
};
})
# The broker's runtime directory, which is also the pointer driver's: the
# control socket and the private broker-driver socket both live in it
# (CONTRACT-sessions.md §5), and it is declared here because *two* units
# now need it to exist.
#
# `RuntimeDirectory=` on the broker alone is not enough. systemd removes
# a unit's RuntimeDirectory when that unit stops, so a `systemctl restart
# hhstream-sessions` would delete /run/hhstream and take the driver's
# pointer.sock with it -- leaving the driver listening on an unlinked
# inode and the broker unable to reach a driver that is running. Hence
# this entry, and `RuntimeDirectoryPreserve` on the broker below.
(lib.mkIf cfg.sessions.pointer.enable {
"10-hhstream-pointer".${brokerRuntimeDir}.d = {
user = cfg.sessions.user;
group = cfg.sessions.group;
mode = "0750";
};
})
# Only needed when the socket was moved out of the runtime directory that
# `RuntimeDirectory=` already creates for us.
(lib.mkIf (socketDir != runtimeDir) {
@@ -525,6 +824,9 @@ in {
"--config"
"${hyprlandConf}"
];
# See `openIpcDirectory` above for what this fixes and why it is
# allowed to fail the unit.
ExecStartPost = lib.mkIf cfg.sessions.enable "${openIpcDirectory}";
};
};
@@ -578,9 +880,14 @@ in {
# dies with "Failed to connect to Wayland display".
SupplementaryGroups = [cfg.sessions.group];
RuntimeDirectory = "hhstream";
RuntimeDirectory = brokerRuntimeDirName;
RuntimeDirectoryMode = "0750";
WorkingDirectory = "/run/hhstream";
# Kept across a restart of this unit, because it is no longer only this
# unit's: the pointer driver's socket lives in it too, and systemd's
# default is to delete the directory when the unit stops. See the
# tmpfiles entry above for the failure that causes.
RuntimeDirectoryPreserve = "yes";
WorkingDirectory = brokerRuntimeDir;
UMask = "0007";
Restart = "on-failure";
@@ -602,9 +909,9 @@ in {
ExecStart = lib.escapeShellArgs [
(lib.getExe' cfg.package "hhstreamd")
"--socket"
"/run/hhstream/control.sock"
controlSocket
"--runtime-dir"
"/run/hhstream"
brokerRuntimeDir
"--state-dir"
cfg.sessions.stateDir
"--config"
@@ -620,5 +927,70 @@ in {
];
};
};
# ── the pointer driver ─────────────────────────────────────────────
#
# A third unit, and a third capability: this one injects input. It is a
# separate process from the broker because a Wayland client needs its own
# connection and a driver blocked on the compositor must not stall session
# lifecycle (PLAN §6.5). It holds no lease -- the broker owns that -- so it
# is an executor that can be restarted at any moment.
systemd.services.hhstream-pointer = lib.mkIf (cfg.sessions.enable && cfg.sessions.pointer.enable) {
description = "Pointer input driver for the headless Hyprland desktop";
wantedBy = ["multi-user.target"];
after = ["hyprland-headless.service"];
# `BindsTo` and not merely `After`: the driver's whole state is a Wayland
# connection to that compositor, so when the compositor goes the driver
# has nothing left to drive. The broker force-releases the lease when the
# driver's socket stops answering, which is how the cursor comes back.
bindsTo = ["hyprland-headless.service"];
environment = {
PYTHONUNBUFFERED = "1";
};
serviceConfig = {
Type = "simple";
User = cfg.sessions.user;
# The compositor's runtime directory is 0750 and owned by this group,
# and the driver is a Wayland client of it: without the group it cannot
# open wayland-N at all. Same reason the broker has it, one step
# further -- the broker only needs to *find* the socket for the
# applications it launches, the driver has to connect to it itself.
SupplementaryGroups = [cfg.sessions.group];
# No `RuntimeDirectory`: /run/hhstream belongs to the broker's unit and
# to the tmpfiles entry above, and a second RuntimeDirectory= on the
# same path would delete the broker's control socket when this unit
# stopped.
WorkingDirectory = brokerRuntimeDir;
UMask = "0007";
Restart = "on-failure";
RestartSec = 1;
NoNewPrivileges = true;
# The same reasoning as the broker's, for the same reason: a driver
# restart must not take sessions down. The applications the broker
# launched are in the broker's cgroup, not this one, so `control-group`
# would not reach them today -- but this unit is `After=` the
# compositor and shares the broker's account, and KillMode=process says
# plainly that stopping the driver stops the driver and nothing else.
KillMode = "process";
# Frozen in docs/CONTRACT-sessions.md §3.4, word for word. The driver
# defaults to both of these paths anyway; they are passed explicitly
# because the contract specifies the command line, and a unit that
# relied on the defaults would stop matching it the moment either
# default moved.
ExecStart = lib.escapeShellArgs [
(lib.getExe' cfg.package "hhstream-pointer")
"--socket"
pointerSocket
"--compositor-runtime-dir"
runtimeDir
];
};
};
};
}
+1 -1
View File
@@ -26,4 +26,4 @@ hhstreamd = "hhstreamd.__main__:main"
hhstream-pointer = "hhstream_pointer.__main__:main"
[tool.setuptools.packages.find]
where = ["src"]
where = ["src"]
+116 -14
View File
@@ -4,10 +4,16 @@ Four verbs that work whether or not the session daemon is running, and one
namespace that needs it:
hhstream status is the session up, and can I reach it?
hhstream shot one frame of the screen
hhstream shot one frame of the screen, or of one output
hhstream run -- CMD... launch a GUI app into the session (unmanaged)
hhstream record film the screen for N seconds
hhstream session ... managed application sessions (start/list/touch/kill)
hhstream session ... managed sessions: start/list/kill, their
containers, and the pointer lease
``shot`` and ``record`` read the published *main* output off the frame socket.
``--output NAME`` instead captures one output in isolation through ``grim -o``,
which is how a single session's container is looked at (PLAN §5.4); the frame
socket cannot do it, because the publisher serves one output and one frame slot.
``run`` and ``session start`` both put an application on the screen; they are
deliberately different. ``run`` is the primitive: it execs and forgets, nothing
@@ -37,8 +43,13 @@ from typing import Iterator
from . import client as frames
from . import protocol
#: The frame socket the compositor's publisher serves.
DEFAULT_FRAME_SOCKET = frames.DEFAULT_SOCKET
#: The frame socket the compositor's publisher serves, under the compositor's
#: runtime directory `/run/hypr-stream` (short because the compositor's event
#: socket has to fit in `sun_path` -- see the assertion in `nix/module.nix`).
#: Spelled out rather than taken from `frames.DEFAULT_SOCKET`, which still names
#: the old `/run/hyprland-headless-stream` and is not this slice's file to
#: change; the module's `socketPath` default is the authority and it says this.
DEFAULT_FRAME_SOCKET = "/run/hypr-stream/stream.sock"
ENV_FRAME_SOCKET = "HHSTREAM_FRAME_SOCKET"
#: The group that owns the session's runtime directory.
DEFAULT_GROUP = "hhstream"
@@ -49,6 +60,12 @@ DEFAULT_UNITS = ("hyprland-headless.service", "hyprland-headless-stream.service"
ENV_UNITS = "HHSTREAM_UNITS"
FFMPEG = "ffmpeg"
#: The screenshot tool used for `--output NAME`. The frame socket publishes the
#: *main* output and nothing else (docs/CONTRACT.md), so a per-container frame
#: cannot come from it; `grim -o <name>` is the one thing that can capture a
#: single output in isolation (PLAN §5.4), and it is already the module's
#: default capture backend, so this adds no dependency.
GRIM = "grim"
# ── access ─────────────────────────────────────────────────────────────────
@@ -152,6 +169,31 @@ def env_for_session(runtime_dir: str) -> dict[str, str]:
}
def capture_output(runtime_dir: str, output: str, destination: pathlib.Path) -> None:
"""One frame of a single output, through ``grim -o``.
Raises :class:`SystemExit` with the tool's own words. ``grim`` says
``unknown output`` for a container that no longer exists, which is the
message a caller needs — far better than this wrapper's guess at what went
wrong, and the reason stderr is passed through verbatim.
"""
if shutil.which(GRIM) is None:
sys.exit(f"hhstream: {GRIM} is not on PATH, and --output needs it")
env = dict(os.environ)
env.update(env_for_session(runtime_dir))
destination.parent.mkdir(parents=True, exist_ok=True)
done = subprocess.run(
[GRIM, "-o", output, str(destination)], env=env, capture_output=True, text=True
)
if done.returncode != 0:
detail = (done.stderr or done.stdout or "").strip()
sys.exit(
f"hhstream: could not capture output {output!r}: "
f"{detail or f'{GRIM} exited {done.returncode}'}"
)
# ── verbs ──────────────────────────────────────────────────────────────────
@@ -182,6 +224,14 @@ def cmd_status(args: argparse.Namespace) -> int:
def cmd_shot(args: argparse.Namespace) -> int:
runtime_dir = str(pathlib.Path(args.frame_socket).parent)
if args.output:
# A named output does not come off the frame socket: the publisher
# serves the main output, one frame slot, no selection (PLAN §5.4).
out = pathlib.Path(args.out or f"hhstream-{args.output}.png")
capture_output(runtime_dir, args.output, out)
print(out)
return 0
hello, payloads = read_frames(args.frame_socket, count=1, timeout=args.timeout)
if not payloads:
print("hhstream: the publisher sent no frame", file=sys.stderr)
@@ -215,17 +265,21 @@ def cmd_record(args: argparse.Namespace) -> int:
) / f"hhstream-rec-{os.getpid()}"
work.mkdir(parents=True, exist_ok=True)
hello, first = read_frames(args.frame_socket, count=1, timeout=args.timeout)
ext = frame_extension(hello)
if first:
(work / f"frame-{1:05d}.{ext}").write_bytes(first[0])
if args.output:
ext = "png"
count, elapsed = record_output(args, work, ext)
else:
hello, first = read_frames(args.frame_socket, count=1, timeout=args.timeout)
ext = frame_extension(hello)
if first:
(work / f"frame-{1:05d}.{ext}").write_bytes(first[0])
count = len(first)
started = time.monotonic()
for payload in stream_frames(args.frame_socket, max(0.0, args.seconds - 0.05)):
count += 1
(work / f"frame-{count:05d}.{ext}").write_bytes(payload)
elapsed = max(time.monotonic() - started, 0.001)
count = len(first)
started = time.monotonic()
for payload in stream_frames(args.frame_socket, max(0.0, args.seconds - 0.05)):
count += 1
(work / f"frame-{count:05d}.{ext}").write_bytes(payload)
elapsed = max(time.monotonic() - started, 0.001)
if count == 0:
print(f"hhstream: read no frames in {args.seconds}s", file=sys.stderr)
@@ -253,6 +307,31 @@ def cmd_record(args: argparse.Namespace) -> int:
return 0
def record_output(args: argparse.Namespace, work: pathlib.Path, ext: str) -> tuple[int, float]:
"""Frames of one named output, one ``grim`` run per frame.
Honest about being the slow path. There is no streaming capture of a single
output here: the frame server publishes the main one, and a per-output
screencopy client is a program this repository does not have. One ``grim``
per frame costs a process spawn and a full screencopy round trip, so the
achieved rate is well under ``--seconds * fps`` — which is exactly why the
encoder below uses the *measured* rate and the caller is told both numbers.
"""
runtime_dir = str(pathlib.Path(args.frame_socket).parent)
interval = 1.0 / max(args.fps, 1)
count = 0
started = time.monotonic()
while time.monotonic() - started < args.seconds:
due = time.monotonic() + interval
count += 1
capture_output(runtime_dir, args.output, work / f"frame-{count:05d}.{ext}")
# Never a negative sleep, and never a busy loop: a grim run slower than
# the interval simply sets the rate.
time.sleep(max(0.0, due - time.monotonic()))
return count, max(time.monotonic() - started, 0.001)
# ── parser ─────────────────────────────────────────────────────────────────
@@ -292,6 +371,14 @@ def build_parser() -> argparse.ArgumentParser:
shot = verbs.add_parser("shot", help="write one frame of the screen")
shot.add_argument("--out", metavar="FILE", help="where to write it (default: ./hhstream-frame.*)")
shot.add_argument(
"--output",
metavar="NAME",
help="capture this output alone (e.g. a session's container, "
"hh-<session-id>) through grim, instead of reading the published main "
"output off the frame socket. 'hhstream session container' lists the "
"names.",
)
run = verbs.add_parser("run", help="launch a GUI app into the session (unmanaged)")
run.add_argument("argv", nargs="*", metavar="-- CMD...", help="the command, after a literal --")
@@ -301,6 +388,21 @@ def build_parser() -> argparse.ArgumentParser:
record.add_argument("--out", metavar="FILE", help="output mp4 (default: ./hhstream-recording.mp4)")
record.add_argument("--work-dir", metavar="DIR", help="where frames go (default: a temp dir)")
record.add_argument("--keep", action="store_true", help="keep the frames after encoding")
record.add_argument(
"--output",
metavar="NAME",
help="film this output alone (e.g. hh-<session-id>) by running grim per "
"frame, instead of reading the published main output off the frame "
"socket. Markedly slower; the encoded rate is the measured one.",
)
record.add_argument(
"--fps",
type=float,
default=10.0,
metavar="N",
help="target frames per second for --output (default: %(default)s); "
"ignored without it, where the publisher sets the rate",
)
# The managed namespace. It brings its own --socket (the *control* socket,
# which is a different socket from the frame one) and its own exit codes.
+1 -1
View File
@@ -11,7 +11,7 @@ from typing import Iterable
from . import protocol
DEFAULT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
DEFAULT_SOCKET = "/run/hypr-stream/stream.sock"
def fetch(socket_path: str, count: int = 1, timeout: float = 10.0) -> list[bytes]:
+1 -1
View File
@@ -23,7 +23,7 @@ from typing import Iterable
from . import protocol
from .capture import CaptureBackend, CommandCapture
DEFAULT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
DEFAULT_SOCKET = "/run/hypr-stream/stream.sock"
#: Contract: the published socket is mode 0660 (ownership is the unit's job).
SOCKET_MODE = 0o660
#: Contract default for `services.hyprland-headless-stream.captureCommand`.
+535 -4
View File
@@ -21,9 +21,24 @@ standard library, so a host CLI pays no startup cost and gains no new failure
mode by registering it.
**The one thing to read before using this:** ``touch`` is the only mark of
activity that exists. ``list``, ``status``, ``logs`` and ``gc`` deliberately do
not reset a session's idle clock, so an agent watching a long-running app must
call ``touch`` or the session will be reaped on schedule.
activity that exists. ``list``, ``status``, ``logs``, ``gc``, ``container``,
``reconcile`` and every ``pointer`` verb deliberately do not reset a session's
idle clock, so an agent watching or driving a long-running app must call
``touch`` or the session will be reaped on schedule. Being driven is not the
same as being wanted.
The verb tree, beyond the original eight:
session container [ID] the output and workspace a session was given
session reconcile [ID] re-read them from the compositor, report drift
session pointer acquire ID take the one cursor, aimed into ID's container
session pointer move ID ... warp, --to X,Y or --by DX,DY (0..1, per output)
session pointer click/down/up/release ID
session pointer state who holds the cursor and what is pressed
The pointer verbs share one precondition — the lease — and the lease id lives
in :mod:`hhstream_session.lease` between invocations, because the wire requires
it on every gesture and the CLI is one process per verb.
"""
from __future__ import annotations
@@ -37,6 +52,7 @@ from hhstreamd.clock import format_duration, parse_duration
from hhstreamd.protocol import ExitCode
from . import format as fmt
from . import lease
from .client import DEFAULT_SOCKET, ENV_SOCKET, ClientError, call, reply_exit_code
__all__ = ["register", "build_parser", "dispatch", "main", "ExitCode"]
@@ -164,6 +180,12 @@ def _build_namespace(parser: argparse.ArgumentParser) -> None:
help="deduplication token: retrying a start with the same id returns the "
"original reply instead of launching a second application",
)
start.add_argument(
"--no-container",
action="store_true",
help="start without a container (NOT IMPLEMENTED: the broker's 'start' "
"verb carries no such field — see the message it refuses with)",
)
# ---- list --------------------------------------------------------
lst = add("list", _cmd_list, help="list sessions (does NOT count as activity)")
@@ -232,6 +254,219 @@ def _build_namespace(parser: argparse.ArgumentParser) -> None:
"--follow", "-f", action="store_true", help="keep printing new output until interrupted"
)
# ---- container ---------------------------------------------------
container = add(
"container",
_cmd_container,
help="the output and workspace a session was given "
"(does NOT count as activity)",
description=(
"Show one session's container -- the output, workspace and mode the "
"broker created for it -- or, with no id, every container plus the "
"'hh-*' outputs no live session claims (orphans)."
),
)
container.add_argument(
"id",
nargs="?",
help="session id; omit for every container and the orphan list",
)
# ---- reconcile ---------------------------------------------------
reconcile = add(
"reconcile",
_cmd_reconcile,
help="re-read containers from the compositor and report the drift "
"(does NOT count as activity)",
description=(
"Ask the compositor where a session's window actually is and bring "
"the record up to that answer; the compositor is the authority and "
"the record is a cache of it. With no id, every live session is "
"reconciled and the start-up scan is re-run: the quarantine rule is "
"re-installed, adopted containers re-take their workspace slots, and "
"'hh-*' outputs with no live session are removed."
),
)
reconcile.add_argument("id", nargs="?", help="session id; omit for all of them")
reconcile.add_argument("--request-id", metavar="ID", help="deduplication token")
# ---- pointer -----------------------------------------------------
_build_pointer(verbs, common)
#: Button names the driver knows (``hhstream_pointer.buttons.CODES``), mirrored
#: here rather than imported: this module's whole integration promise is that it
#: imports ``hhstreamd.protocol`` and the standard library and nothing else, so
#: registering it cannot drag in the driver's Wayland dependencies. The driver
#: is still the authority -- it answers an unknown name with the set it knows --
#: and this list only buys a typo an exit 2 instead of an exit 10.
BUTTONS = ("left", "right", "middle", "side", "extra", "forward", "back", "task")
def _build_pointer(verbs: Any, common: argparse.ArgumentParser) -> None:
"""``session pointer <verb>`` — the one cursor, under a lease (PLAN §6).
A nested namespace rather than seven top-level verbs because they share one
precondition that nothing else here has: the lease. Grouping them is what
makes ``pointer --help`` able to say that once.
"""
namespace = verbs.add_parser(
"pointer",
parents=[common],
help="aim and click the one cursor at a session, under a lease",
description=(
"The cursor is singular, so it is leased. 'acquire' takes it and "
"prints the lease id on stdout; the gesture verbs reuse that lease "
"and refuse (exit 9) without it; 'release' gives it back, lifting "
"anything still pressed. A lease left idle past its TTL is "
"force-released by the broker, which also lifts its buttons.\n\n"
"Coordinates are OUTPUT-NORMALISED, 0..1, within the session's own "
"container: (0,0) is its top-left corner and (1,1) its "
"bottom-right. Window-local pixel aiming is deliberately absent -- "
"the broker's IPC client carries no window geometry, so there is "
"nothing honest to convert from.\n\n"
"No pointer verb counts as activity: a session being driven is "
"still a session nobody has said they want kept. Call 'touch'."
),
epilog=ACTIVITY_NOTE,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
gestures = namespace.add_subparsers(dest="pointer_verb", metavar="VERB")
namespace.set_defaults(
func=_cmd_pointer_state, hhstream_session_handler=_cmd_pointer_state, json=False
)
def add_gesture(name: str, handler, **kwargs: Any):
sub = gestures.add_parser(name, parents=[common], **kwargs)
sub.set_defaults(func=handler, hhstream_session_handler=handler)
sub.add_argument("--json", action="store_true", help="emit the protocol object on stdout")
return sub
def with_lease(sub: argparse.ArgumentParser) -> argparse.ArgumentParser:
sub.add_argument(
"--lease",
metavar="ID",
help="the lease id from 'pointer acquire'. Omitted, the one that "
f"acquire cached is used (${lease.ENV_LEASE} overrides that).",
)
return sub
acquire = add_gesture(
"acquire",
_cmd_pointer_acquire,
help="take the cursor for a session and aim it into its container",
description=(
"Take the one cursor and warp it into this session's own output. "
"Prints the bare lease id on stdout, so $(hhstream session pointer "
"acquire ID) is the lease and nothing else, and caches it so the "
"gesture verbs below need no flag. A second acquire while someone "
"else holds it exits 8 (BUSY) naming the holder."
),
)
acquire.add_argument("id", help="session id")
acquire.add_argument(
"--ttl",
type=_duration,
metavar="DURATION",
help="idle lifetime for this lease before the broker force-releases it "
"(default: the broker's; capped by its hard maximum)",
)
acquire.add_argument(
"--no-restore",
action="store_true",
help="start at the centre of the container instead of the position this "
"session's cursor was last left at",
)
move = with_lease(add_gesture(
"move",
_cmd_pointer_move,
help="warp within the session's own output (normalised 0..1)",
description=(
"Warp the cursor inside this session's container. --to is absolute "
"and refused outside 0..1, because a caller that computed 1.4 has a "
"bug and clamping would hide it; --by is relative and IS clamped, "
"because running into the edge of the screen is what a mouse does."
),
))
move.add_argument("id", help="session id")
target = move.add_mutually_exclusive_group(required=True)
target.add_argument(
"--to", type=_point, metavar="X,Y", help="absolute, output-normalised 0..1"
)
target.add_argument(
"--by", type=_point, metavar="DX,DY", help="relative to the current bookmark"
)
click = with_lease(add_gesture(
"click",
_cmd_pointer_click,
help="press and release a button where the cursor is",
))
click.add_argument("id", help="session id")
click.add_argument(
"--button", default="left", choices=BUTTONS, metavar="B", help=_button_help()
)
for name, state in (("down", "down"), ("up", "up")):
sub = with_lease(add_gesture(
name,
_cmd_pointer_button,
help=f"hold a button {state} without releasing it"
if state == "down"
else "release a button that was held down",
description=(
"Half a click. Together with 'move' this is a drag, and the "
"lease is what makes the three calls atomic -- no other "
"session's events are interleaved. The broker lifts whatever "
"is still down on release or on a lease timeout, so a crashed "
"agent cannot leave a button pressed."
),
))
sub.set_defaults(button_state=state)
sub.add_argument("id", help="session id")
sub.add_argument(
"--button", default="left", choices=BUTTONS, metavar="B", help=_button_help()
)
release = with_lease(add_gesture(
"release",
_cmd_pointer_release,
help="give the cursor back, lifting anything still pressed",
))
release.add_argument("id", help="session id")
add_gesture(
"state",
_cmd_pointer_state,
help="who holds the cursor, and what is pressed (does NOT count as activity)",
)
def _button_help() -> str:
return f"one of: {', '.join(BUTTONS)} (default: left)"
def _point(text: str) -> tuple[float, float]:
"""``X,Y`` as two floats.
Parsed here so a malformed pair is a usage error from argparse (exit 2)
before anything reaches the broker, and so the error names the form.
"""
parts = text.split(",")
if len(parts) != 2:
raise argparse.ArgumentTypeError(
f"expected two numbers separated by a comma, e.g. 0.5,0.5 — got {text!r}"
)
try:
return (float(parts[0]), float(parts[1]))
except ValueError:
raise argparse.ArgumentTypeError(
f"{text!r} is not a pair of numbers (coordinates are output-normalised, 0..1)"
) from None
def _duration(text: str) -> float:
try:
@@ -300,6 +535,27 @@ def _cmd_start(args: argparse.Namespace) -> int:
# argparse has already removed the separating `--`, so what is left is the
# application's own argv, as a list. It is never joined into a string.
argv = list(args.argv or [])
if args.no_container:
# Refused rather than sent. The flag is in PLAN §9's surface, but the
# wire's `start` (CONTRACT-sessions.md §4: "existing verbs are
# unchanged") carries no `no_container` field and `SessionManager.start`
# takes no such argument, so a request carrying it would be silently
# ignored and the session would get a container anyway. A flag that
# lies about what it did is worse than one that says it cannot.
return _finish(
args,
{
"ok": False,
"error": "invalid_argument",
"reason": "--no-container is not implemented by this broker: the "
"'start' verb has no no_container field, so the request would be "
"accepted and a container created anyway",
"hint": "start without it and tear the container down with "
"'session kill', or report the gap against "
"docs/CONTRACT-sessions.md §4",
},
lambda r: "",
)
reply = _request(
args,
"start",
@@ -349,7 +605,40 @@ def _fmt_timeout(seconds: Any) -> str:
@_guard
def _cmd_list(args: argparse.Namespace) -> int:
reply = _request(args, "list", all=bool(getattr(args, "all", False)) or None)
return _finish(args, reply, lambda r: fmt.render_list(r.get("sessions") or []))
if getattr(args, "json", False) or not reply.get("ok"):
# `--json` is the protocol's own object, unmodified: splicing the lease
# holder into it would invent a field no other caller can rely on.
return _finish(args, reply, lambda r: "")
holder, known = _pointer_holder(args)
return _finish(
args,
reply,
lambda r: fmt.render_list(
r.get("sessions") or [], pointer_holder=holder, pointer_known=known
),
)
def _pointer_holder(args: argparse.Namespace) -> tuple[Any, bool]:
"""Who holds the one cursor, for the ``POINTER`` column.
A second request, because the ``list`` reply carries no lease state and the
broker is not this slice's file to change. It is read-only and does not
count as activity (CONTRACT-sessions.md §4), so the only cost is a round
trip on a human listing — ``--json`` never makes it.
Returns ``(holder, known)``. ``known=False`` is not a failure worth exiting
over: the sessions have been listed, and the honest thing is to print the
gap marker in that one column rather than lose the whole table.
"""
try:
reply = _request(args, "pointer.state")
except ClientError:
return None, False
if not reply.get("ok") or "holder" not in reply:
return None, False
return reply.get("holder"), True
@_guard
@@ -372,6 +661,43 @@ def _cmd_touch(args: argparse.Namespace) -> int:
return _finish(args, reply, render)
def _container_teardown(session: dict[str, Any]) -> list[str]:
"""What the compositor side of a teardown left behind.
``survivors`` (processes) was already reported and ``container_survivors``
(windows the compositor still shows) was not, so a teardown that removed
the output and left a window on the screen read as a clean kill. They are
two independent sources and PLAN §4.5 requires both to agree before a
teardown is called a success.
``None`` is its own case and is *not* folded into "none": it means the
compositor could not be asked, so "no windows survived" is a claim nobody
is in a position to make.
"""
bits = []
if session.get("container_removed"):
bits.append("container removed")
if session.get("container_error"):
bits.append(f"container error: {session['container_error']}")
survivors = session.get("container_survivors")
if survivors is None:
bits.append(
"WARNING: the compositor could not be asked whether any window "
"survived the teardown"
)
elif survivors:
named = ", ".join(
f"{w.get('class') or w.get('initial_class')}@{w.get('address')} (pid {w.get('pid')})"
for w in survivors
)
bits.append(
f"WARNING: the compositor still shows {len(survivors)} window(s) "
f"after the output was removed ({named})"
)
return bits
@_guard
def _cmd_kill(args: argparse.Namespace) -> int:
reply = _request(
@@ -413,6 +739,7 @@ def _cmd_kill(args: argparse.Namespace) -> int:
f"WARNING: {len(survivors)} process(es) SURVIVED "
f"({', '.join(str(p) for p in survivors)})"
)
bits.extend(_container_teardown(session))
return "; ".join(bits)
return _finish(args, reply, render)
@@ -472,6 +799,210 @@ def _cmd_logs(args: argparse.Namespace) -> int:
return int(ExitCode.OK)
# --------------------------------------------------------------------------
# containers
# --------------------------------------------------------------------------
@_guard
def _cmd_container(args: argparse.Namespace) -> int:
"""One session's container, or the whole picture including orphans.
With an id this is ``container.reconcile`` and not ``container.list``, and
that is deliberate: asking "what container does this session have" is
almost always asking "where is this window *now*", and the list verb can
only report what the record remembers.
"""
if args.id is None:
reply = _request(args, "container.list")
return _finish(args, reply, fmt.render_containers)
reply = _request(args, "container.reconcile", id=args.id)
return _finish(args, reply, fmt.render_container)
@_guard
def _cmd_reconcile(args: argparse.Namespace) -> int:
reply = _request(
args, "container.reconcile", id=args.id, request_id=args.request_id
)
return _finish(args, reply, fmt.render_reconcile)
# --------------------------------------------------------------------------
# the pointer lease
# --------------------------------------------------------------------------
def _lease_of(args: argparse.Namespace, session_id: str) -> str | None:
"""The lease id for this verb: the flag, the environment, then the cache."""
explicit = getattr(args, "lease", None)
if explicit:
return explicit
return lease.recall(session_id, socket=_socket_of(args))
def _no_lease(args: argparse.Namespace, session_id: str) -> int:
"""Refuse a gesture with no lease, without troubling the broker.
Exit 9 and not 2: the caller's command line is fine, what is missing is the
lease — and 9 is precisely the code that says "acquire one and try again"
(CONTRACT-sessions.md §4). The broker would answer the same way; refusing
here means the message can name the cache, which the broker knows nothing
about.
"""
reply = {
"ok": False,
"error": "no_lease",
"reason": f"no pointer lease for {session_id} on this socket",
"hint": f"run 'pointer acquire {session_id}' first, or pass --lease "
"with the id it printed",
}
return _finish(args, reply, lambda r: "")
def _finish_gesture(
args: argparse.Namespace, reply: dict[str, Any], render, session_id: str
) -> int:
"""Print a gesture's reply, dropping a lease the broker has just disowned.
A cached lease that is refused is stale by definition — expired, released
by the sweeper, or taken over — and keeping it would make every subsequent
verb fail the same way while the fix (``acquire``) looks unnecessary.
"""
if reply.get("error") in ("no_lease", "no_such_session"):
lease.forget(session_id)
return _finish(args, reply, render)
@_guard
def _cmd_pointer_acquire(args: argparse.Namespace) -> int:
reply = _request(
args,
"pointer.acquire",
id=args.id,
ttl_s=args.ttl,
# `False` and not `None`: the wire default is to restore, so the only
# way to ask for the centre is to say so explicitly.
restore=False if args.no_restore else None,
)
if not reply.get("ok"):
return _finish(args, reply, lambda r: "")
lease_id = reply.get("lease_id") or ""
lease.remember(args.id, lease_id, socket=_socket_of(args))
if args.json:
fmt.dump_json(reply)
return int(ExitCode.OK)
# Same shape as `start`: stdout is the one token a caller needs to pass
# back, detail goes to stderr.
print(lease_id)
bookmark = reply.get("bookmark") or {}
print(
f"acquired the cursor for {reply.get('id')} on {bookmark.get('output')} "
f"at {fmt.render_bookmark(bookmark)}",
file=sys.stderr,
)
print(
f"expires in {_fmt_timeout(reply.get('expires_in_s'))} with no further "
f"pointer verb; release it with: hhstream session pointer release {args.id}",
file=sys.stderr,
)
return int(ExitCode.OK)
@_guard
def _cmd_pointer_move(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
absolute = getattr(args, "to", None)
relative = getattr(args, "by", None)
coordinates = (
{"x": absolute[0], "y": absolute[1]}
if absolute is not None
else {"dx": relative[0], "dy": relative[1]}
)
reply = _request(args, "pointer.move", id=args.id, lease_id=lease_id, **coordinates)
def render(r: dict[str, Any]) -> str:
return f"{r.get('id')}: cursor at {fmt.render_bookmark(r.get('bookmark'))}"
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_pointer_click(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(
args, "pointer.click", id=args.id, lease_id=lease_id, button=args.button
)
def render(r: dict[str, Any]) -> str:
return (
f"{r.get('id')}: clicked {r.get('button')} "
f"at {fmt.render_bookmark(r.get('bookmark'))}"
)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_pointer_button(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(
args,
"pointer.button",
id=args.id,
lease_id=lease_id,
button=args.button,
state=args.button_state,
)
def render(r: dict[str, Any]) -> str:
down = r.get("buttons") or []
return (
f"{r.get('id')}: {args.button} {args.button_state}; "
f"held: {', '.join(down) if down else 'nothing'}"
)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_pointer_release(args: argparse.Namespace) -> int:
lease_id = _lease_of(args, args.id)
if not lease_id:
return _no_lease(args, args.id)
reply = _request(args, "pointer.release", id=args.id, lease_id=lease_id)
if reply.get("ok"):
lease.forget(args.id)
def render(r: dict[str, Any]) -> str:
lifted = r.get("buttons_lifted") or []
bits = [
f"{r.get('id')}: cursor released by {r.get('released_by')}",
f"bookmark {fmt.render_bookmark(r.get('bookmark'))}",
]
if lifted:
bits.append(f"lifted {', '.join(lifted)}")
return "; ".join(bits)
return _finish_gesture(args, reply, render, args.id)
@_guard
def _cmd_pointer_state(args: argparse.Namespace) -> int:
reply = _request(args, "pointer.state")
return _finish(args, reply, fmt.render_pointer_state)
# --------------------------------------------------------------------------
# standalone use
# --------------------------------------------------------------------------
+263 -10
View File
@@ -13,6 +13,11 @@ from typing import Any
from hhstreamd.clock import format_duration
#: The honest gap. Printed wherever a value is genuinely unknown, because the
#: alternative — a blank cell — reads as zero or as "no", and the three columns
#: added in this milestone (``WS``, ``OUTPUT``, ``POINTER``) are unknown exactly
#: when the compositor could not be asked. That is the case a reader most needs
#: to be able to see.
DASH = "—"
@@ -35,19 +40,48 @@ def render_table(rows: list[list[str]], headers: list[str]) -> str:
return "\n".join(out)
def render_list(sessions: list[dict[str, Any]]) -> str:
def pointer_cell(session_id: str, holder: Any, *, known: bool) -> str:
"""The ``POINTER`` column for one row (PLAN §9).
Three facts, told apart on purpose: this session holds the one cursor
(``held``), somebody else does and the row says who (``held:<id>``), or
nobody does (``free``). ``known=False`` is the fourth case and prints the
gap marker — the broker could not be asked who holds it, which is not the
same as nobody holding it.
"""
if not known:
return DASH
if holder is None:
return "free"
return "held" if holder == session_id else f"held:{holder}"
def render_list(
sessions: list[dict[str, Any]],
*,
pointer_holder: Any = None,
pointer_known: bool = False,
) -> str:
"""The default view.
``EXPIRES IN`` is on it rather than behind a flag because it is the number
an agent actually needs.
There is **no ``FG`` column** (DESIGN.md §1.4, amended): foreground-ness
needs compositor IPC, which this milestone does not have, so the column was
``?`` on every row of every listing — a header and six columns of width
paying for no information, and a reader who has to learn that ``?`` means
*unknown* rather than *no*. ``foreground`` stays in the record and in
``status``, where it is one line among many and can become real without
changing the shape of this table.
``WS`` / ``OUTPUT`` / ``POINTER`` are the columns PLAN §9 asks for, and they
are *after* ``PID`` rather than before it: the position of the existing
columns is something callers already read (and a VM check asserts on), so
the new ones are appended where nothing has to shift.
There is still **no ``FG`` column** (DESIGN.md §1.4, amended): it would be
a sixth narrow column carrying a tri-state almost nobody branches on, and
``status`` reports foreground in a line of its own. ``WS`` and ``OUTPUT``
earn their width differently — they are how a caller finds the container to
point ``grim -o`` or a pointer verb at.
``pointer_known`` exists because the ``list`` reply carries no lease state:
the holder comes from a second, read-only ``pointer.state`` call, and when
that call fails the column must say *unknown* rather than *free*.
"""
if not sessions:
@@ -64,17 +98,193 @@ def render_list(sessions: list[dict[str, Any]]) -> str:
idle = DASH
left = s.get("tombstone_expires_in_s")
expires = f"(tombstone, {format_duration(left)} left)" if left is not None else DASH
container = s.get("container") or {}
rows.append(
[
_cell(s.get("id")),
_cell(s.get("app")),
_cell(s.get("state")),
_cell(s.get("pid")) if live else DASH,
_cell(s.get("workspace")),
_cell(container.get("output")),
pointer_cell(str(s.get("id")), pointer_holder, known=pointer_known)
if live
else DASH,
idle,
expires,
]
)
return render_table(rows, ["ID", "APP", "STATE", "PID", "IDLE", "EXPIRES IN"])
return render_table(
rows,
["ID", "APP", "STATE", "PID", "WS", "OUTPUT", "POINTER", "IDLE", "EXPIRES IN"],
)
def render_containers(reply: dict[str, Any]) -> str:
"""``session container`` with no id: every container, and every orphan.
The orphan list is the reason this view exists at all. ``hh-*`` outputs with
no live session are the thing a start-up scan removes, and until they are
printed somewhere an operator has no way to see that the compositor is
carrying render targets nobody owns.
"""
rows = []
for row in reply.get("containers") or []:
rows.append(
[
_cell(row.get("id")),
_cell(row.get("app")),
_cell(row.get("output")),
_cell(row.get("workspace")),
render_mode(row.get("mode")),
_cell(row.get("state")),
_cell(row.get("window")),
]
)
lines = [
render_table(rows, ["ID", "APP", "OUTPUT", "WS", "MODE", "STATE", "WINDOW"])
if rows
else "no containers"
]
lines.append(f"compositor: {_cell(reply.get('compositor'))}")
if reply.get("error"):
lines.append(f" {reply['error']}")
in_use = reply.get("workspaces_in_use")
lines.append(
"workspaces: " + (", ".join(str(w) for w in in_use) if in_use else "none in use")
)
orphans = reply.get("orphans")
if orphans is None:
# Not `[]`: "could not look" and "looked, found none" are different
# claims and only one of them is reassuring.
lines.append(f"orphans: {DASH} (the compositor could not be asked)")
elif orphans:
lines.append(
f"orphans: {len(orphans)} hh-* output(s) no live session claims: "
+ ", ".join(orphans)
)
else:
lines.append("orphans: none")
return "\n".join(lines)
def render_container(reply: dict[str, Any]) -> str:
"""``session container ID``: one session's container, and its drift."""
container = reply.get("container")
lines = [f"{_cell(reply.get('id'))}"]
if not container:
lines.append(f" container {DASH} (this session has none)")
else:
lines.append(
f" output {_cell(container.get('output'))}"
f" workspace {_cell(container.get('workspace'))}"
f" mode {render_mode(container.get('mode'))}"
)
lines.append(
f" state {_cell(container.get('state'))}"
f" created by {_cell(container.get('created_by'))}"
)
lines.extend(render_diff(reply.get("diff") or []))
return "\n".join(lines)
def render_diff(diff: list[dict[str, Any]]) -> list[str]:
"""Where the record and the compositor disagreed, with both values.
An empty diff is printed, not omitted: "the record matches the compositor"
is the useful answer to ``reconcile``, and silence would be read as a verb
that did nothing.
"""
if not diff:
return [" drift none (the record matches the compositor)"]
lines = [" drift"]
for item in diff:
if item.get("error"):
lines.append(f" {item.get('id')}: {item['field']} — {item['error']}")
continue
lines.append(
f" {item.get('id')}: {item.get('field')} "
f"recorded {item.get('recorded')!r}, compositor says {item.get('observed')!r}"
)
return lines
def render_reconcile(reply: dict[str, Any]) -> str:
"""``session reconcile``, with or without an id."""
if reply.get("id"):
return render_container(reply)
scan = reply.get("scan") or {}
lines = [
f"compositor: {'reachable' if scan.get('available') else 'unreachable'}"
+ (f" (signature {scan['signature']})" if scan.get("signature") else ""),
]
if scan.get("error"):
lines.append(f" {scan['error']}")
lines.append(f"quarantine: {_cell(scan.get('quarantine'))}")
# The scan's four lists carry different shapes -- `removed` is a list of
# output names, the others are records -- so each is rendered rather than
# printed, and `failed` is last and loudest because it is the only one that
# means the compositor and the registry are still out of step.
for item in scan.get("adopted") or []:
lines.append(f" adopted {_scan_item(item)}")
for output in scan.get("removed") or []:
lines.append(f" removed {output} (no live session claimed it)")
for item in scan.get("orphaned") or []:
lines.append(f" orphan {_scan_item(item)}")
for item in scan.get("failed") or []:
lines.append(f" FAILED {_scan_item(item)}")
lines.extend(render_diff(reply.get("diff") or []))
return "\n".join(lines)
def _scan_item(item: Any) -> str:
"""One entry of a reconcile scan list, whatever shape it has."""
if not isinstance(item, dict):
return str(item)
return " ".join(f"{key} {value}" for key, value in item.items())
def render_mode(mode: dict[str, Any] | None) -> str:
"""``WIDTHxHEIGHT``, or the gap marker for a container that has no mode.
A degraded container records ``None`` here rather than a size it never set,
so this has to be able to say so.
"""
if not mode:
return DASH
return f"{mode.get('width')}x{mode.get('height')}"
def render_bookmark(bookmark: dict[str, Any] | None) -> str:
"""Where the cursor is, in the words the wire uses (PLAN §6.3)."""
if not isinstance(bookmark, dict):
return DASH
x, y = bookmark.get("x"), bookmark.get("y")
if not isinstance(x, (int, float)) or not isinstance(y, (int, float)):
return DASH
return f"{x:.4f},{y:.4f} on {bookmark.get('output')} at {bookmark.get('at')}"
def render_pointer_state(reply: dict[str, Any]) -> str:
holder = reply.get("holder")
buttons = reply.get("buttons") or []
lines = [
f"holder {holder if holder else 'free'}",
f"lease {_cell(reply.get('lease_id'))}",
# Loud, because a button left down is the one pointer failure that keeps
# hurting after the lease is gone.
f"buttons {', '.join(buttons) if buttons else 'none down'}",
f"bookmark {render_bookmark(reply.get('bookmark'))}",
f"driver {_cell(reply.get('driver'))}",
]
return "\n".join(lines)
def render_status(session: dict[str, Any]) -> str:
@@ -148,8 +358,51 @@ def render_gc(result: dict[str, Any]) -> str:
return "\n".join(lines)
#: Error names whose failure is on the *compositor* side (exit 10), annotated
#: with what that means for the session. CONTRACT-sessions.md §4 makes the
#: distinction load-bearing — "the session is not lost, it keeps running in
#: degraded mode" — and a message that only said "error" would leave a caller
#: deciding whether to restart an application that is perfectly alive.
COMPOSITOR_ERRORS = {
"compositor": "the compositor or the output operation failed",
"compositor_unavailable": "the compositor's IPC socket could not be reached",
"no_container": "this session has no container output to aim at",
"driver_unavailable": "the pointer driver is not reachable",
"driver_refused": "the pointer driver refused the operation",
}
def render_error(reply: dict[str, Any]) -> str:
parts = [f"error: {reply.get('reason') or reply.get('error')}"]
"""The human error, saying which side of the system failed.
Three classes get a named prefix because an agent (and a person) acts
differently on each: a compositor failure leaves the application running, a
missing lease is fixed by acquiring one, and anything else is about the
session itself.
"""
error = reply.get("error") or ""
reason = reply.get("reason") or error
if error in COMPOSITOR_ERRORS:
parts = [
f"compositor error: {reason}",
f" {COMPOSITOR_ERRORS[error]}; the session itself is unaffected "
"and keeps running (exit 10, not a session failure)",
]
elif error == "no_lease":
parts = [
f"no pointer lease: {reason}",
" this session does not hold the one cursor (exit 9); acquire it "
"first with 'pointer acquire'",
]
elif error == "pointer_busy":
parts = [
f"pointer busy: {reason}",
" another session holds the one cursor (exit 8); wait for it to "
"release or for its lease to time out",
]
else:
parts = [f"error: {reason}"]
if reply.get("hint"):
parts.append(f"hint: {reply['hint']}")
return "\n".join(parts)
+129
View File
@@ -0,0 +1,129 @@
"""Where the CLI keeps the lease id between two invocations.
The contract's pointer surface (PLAN §9) is flagless::
hhstream session pointer acquire ID
hhstream session pointer move ID --to 0.5,0.5
hhstream session pointer release ID
but the wire (CONTRACT-sessions.md §4) requires a ``lease_id`` on every gesture
verb, and the CLI is one process per verb: by the time ``move`` runs, the
``acquire`` that was handed the lease id has exited. Something has to remember
it, and the three candidates are a flag on every verb (which the frozen surface
does not have), the broker (which deliberately refuses to infer a holder — that
is what makes a stale lease detectable), or here.
So: ``acquire`` writes the lease id, the gesture verbs read it, ``release`` and
every ``no_lease`` refusal delete it. ``--lease`` and ``$HHSTREAM_LEASE``
override it, because an agent that holds the id already should not have to care
that this file exists.
It is a **cache, not state**: every entry is re-checked by the broker on the
next verb, and a stale one costs one refusal (exit 9) and is then dropped. It
lives under ``$XDG_RUNTIME_DIR``, so a reboot takes it with the leases it
describes.
"""
from __future__ import annotations
import json
import os
import tempfile
from pathlib import Path
from typing import Any
#: Overrides the directory below. Exists for tests and for an operator running
#: two brokers on one machine; the socket path is part of each entry anyway, so
#: the usual reason to move it is isolation, not correctness.
ENV_LEASE_DIR = "HHSTREAM_LEASE_DIR"
#: One lease id, for a caller that would rather pass it than let us cache it.
ENV_LEASE = "HHSTREAM_LEASE"
FILENAME = "pointer-leases.json"
def lease_dir() -> Path:
"""The directory the cache lives in — per user, and not world-readable.
``$XDG_RUNTIME_DIR`` is the right home: it is already per-user, already
private, and already emptied on logout. The fallbacks exist because an
agent reached over ``ssh`` or from a cron job often has neither it nor
``/run/user/<uid>``, and a lease it cannot cache would make the flagless
surface unusable exactly where it is most needed.
"""
override = os.environ.get(ENV_LEASE_DIR)
if override:
return Path(override)
runtime = os.environ.get("XDG_RUNTIME_DIR")
if runtime and os.path.isdir(runtime):
return Path(runtime) / "hhstream"
uid_runtime = Path(f"/run/user/{os.getuid()}")
if uid_runtime.is_dir():
return uid_runtime / "hhstream"
return Path(tempfile.gettempdir()) / f"hhstream-{os.getuid()}"
def _path() -> Path:
return lease_dir() / FILENAME
def _load() -> dict[str, Any]:
try:
with open(_path(), encoding="utf-8") as fh:
data = json.load(fh)
except (OSError, ValueError):
# Unreadable or corrupt is the same as empty: the broker is the
# authority on who holds the lease, and losing the cache costs one
# extra `acquire`.
return {}
return data if isinstance(data, dict) else {}
def _store(entries: dict[str, Any]) -> None:
path = _path()
try:
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
# Written through a temporary file in the same directory so a crash
# mid-write leaves the previous cache rather than a truncated one.
handle, temporary = tempfile.mkstemp(dir=path.parent, prefix=".leases-")
with os.fdopen(handle, "w", encoding="utf-8") as fh:
json.dump(entries, fh)
os.chmod(temporary, 0o600)
os.replace(temporary, path)
except OSError:
# A cache that cannot be written is not an error worth failing a warp
# over; the caller is told the lease id on stdout either way.
pass
def remember(session_id: str, lease_id: str, *, socket: str | None) -> None:
entries = _load()
entries[session_id] = {"lease_id": lease_id, "socket": socket}
_store(entries)
def recall(session_id: str, *, socket: str | None) -> str | None:
"""The cached lease for this session on this socket, or ``None``.
The socket is part of the match: a lease id from another broker is not a
lease here, and offering it would turn a clear "acquire first" into a
confusing "that is not your lease".
"""
explicit = os.environ.get(ENV_LEASE)
if explicit:
return explicit
entry = _load().get(session_id)
if not isinstance(entry, dict):
return None
if entry.get("socket") != socket:
return None
lease_id = entry.get("lease_id")
return lease_id if isinstance(lease_id, str) and lease_id else None
def forget(session_id: str) -> None:
entries = _load()
if entries.pop(session_id, None) is not None:
_store(entries)
+395
View File
@@ -0,0 +1,395 @@
"""The impure half of containers: running the plans and reading the result back.
:mod:`hhstreamd.containers` decides *what* a container is — argv lists, a
workspace slot, an output name — and deliberately cannot run any of it. This
module is the other side of that line: it owns the compositor connection, turns
a :class:`~hhstreamd.containers.ContainerPlan` into real outputs and rules, and
then asks the compositor what actually happened. Keeping the two apart is what
lets every placement decision be unit-tested without a compositor, and confines
everything that *needs* one to a single file.
Three decisions worth finding here.
**Commands go over the request socket, not through ``hyprctl``.** The plans are
``["hyprctl", "keyword", ...]`` argv lists, and running them literally would
mean a subprocess per command, ``hyprctl`` on the broker's ``PATH``, and
``HYPRLAND_INSTANCE_SIGNATURE``/``XDG_RUNTIME_DIR`` set correctly in its
environment — three ways to fail that have nothing to do with the compositor.
``hyprctl`` itself does exactly one thing with those arguments: it joins them
with spaces and writes them to ``<runtime>/hypr/<sig>/.socket.sock``, which is
the socket this broker already holds open for queries. So :meth:`dispatch`
sends the argv's *content* down the socket ``hyprctl`` would have used. The
plan is still the authority on what runs and in what order; only the transport
is ours.
**Read back, never assume.** Every mutation is followed by a query (PLAN §4.2).
``create`` returns what the compositor says the window's workspace and output
are, not what the rule asked for — a rule that did not bind is the failure mode
this exists to catch, and a record that repeated our intention back to us would
hide it.
**Degrade, never guess.** No compositor means :meth:`available` is false and
every lifecycle verb carries on without one: a container of ``state:
"degraded"``, with every field it could not verify left ``None``. Nothing here
ever invents an output name, a workspace number or a window.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from . import containers
from .ipc import Client, CompositorUnavailable, HyprlandIPC
log = logging.getLogger("hhstreamd.container_host")
#: Where a window that matched no container lands (PLAN §5.2). A special
#: workspace, so it is hidden rather than shown on whatever output is in front.
DEFAULT_QUARANTINE_WORKSPACE = "special:quarantine"
#: The container's size (CONTRACT-sessions.md §5).
DEFAULT_MODE = (1280, 720)
#: Hyprland answers a successful ``keyword``/``output`` with this, and anything
#: else with prose. Matched case-insensitively and with whitespace stripped.
OK_REPLY = "ok"
@dataclass(frozen=True)
class ContainerFacts:
"""What the compositor says about a session's window, after the fact.
Every field is ``None`` when the compositor did not say: there is no window
yet, or no workspace carries a monitor name. ``output`` is the monitor the
*window* is on, which is not necessarily the output we created — and when
the two differ, the rule did not bind and the caller must say so.
"""
workspace: int | None
output: str | None
window: dict[str, Any] | None
foreground: bool | None
class ContainerHost:
"""One compositor instance, and the containers this broker owns in it."""
def __init__(
self,
runtime_dir: Path | str | None,
*,
allocator: containers.WorkspaceAllocator,
signature: str | None = None,
mode: tuple[int, int] = DEFAULT_MODE,
quarantine_workspace: str = DEFAULT_QUARANTINE_WORKSPACE,
ipc: HyprlandIPC | None = None,
) -> None:
self.runtime_dir = None if runtime_dir is None else Path(runtime_dir)
self.allocator = allocator
self.mode = mode
self.quarantine_workspace = quarantine_workspace
self._wanted_signature = signature
self._ipc = ipc
self._signature: str | None = signature
self._last_error: str | None = None
if ipc is not None:
self._signature = signature or _signature_of(ipc)
# -- the connection ---------------------------------------------------
def ipc(self) -> HyprlandIPC:
"""The client for this instance, discovering it if we have none.
Rediscovery is a ``stat`` and is attempted on every call that needs the
compositor, so a compositor that comes back is picked up without a
broker restart. The signature, once known, is reused: a second
instance appearing must not silently move the broker's containers to a
different desktop.
"""
if self._ipc is not None:
return self._ipc
if self.runtime_dir is None:
raise CompositorUnavailable(
"no compositor runtime directory is configured; containers are disabled"
)
client = HyprlandIPC.discover(self.runtime_dir, self._wanted_signature or self._signature)
self._ipc = client
self._signature = _signature_of(client)
self._last_error = None
log.info("compositor instance %s at %s", self._signature, client.request_socket)
return client
@property
def signature(self) -> str | None:
"""The instance signature, or ``None`` if we never reached one."""
return self._signature
@property
def last_error(self) -> str | None:
return self._last_error
def available(self) -> bool:
"""True if the compositor answered just now. Never cached as true.
``version`` is the cheapest round trip that proves the socket is a live
compositor and not a leftover inode.
"""
try:
self.ipc().version()
except CompositorUnavailable as exc:
self._degrade(exc)
return False
return True
def _degrade(self, exc: CompositorUnavailable) -> None:
self._last_error = str(exc)
# Drop the client: its socket path may be stale, and the next call
# should rediscover rather than keep failing against a dead instance.
self._ipc = None
# -- running plans ----------------------------------------------------
def dispatch(self, argv: list[str]) -> str:
"""Run one ``["hyprctl", ...]`` argv over the request socket.
The reply is checked: Hyprland answers ``ok`` to a command it carried
out and prose to one it refused, and an unchecked dispatch is how a
container ends up recorded as created when the compositor declined.
"""
if not argv or argv[0] != "hyprctl":
raise ValueError(f"not a hyprctl plan entry: {argv!r}")
command = " ".join(argv[1:])
reply = self.ipc().query(command).strip()
if reply.lower() != OK_REPLY and reply != "":
raise CompositorUnavailable(f"compositor refused {command!r}: {reply[:200]!r}")
return reply
def run_plan(self, plan: list[list[str]]) -> None:
"""Run argv lists in the order given. Stops at the first refusal."""
for argv in plan:
self.dispatch(argv)
def install_quarantine(self) -> bool:
"""Install the catch-all backstop. Returns False when it is disabled.
**Called once at broker start-up, before any session's container
exists.** Hyprland applies window rules in the order they were
declared and this one matches every class, so installing it after a
per-session rule would override that rule and sweep the session's own
window into the special workspace. The ordering cannot live in
:mod:`hhstreamd.containers`, which runs nothing; it lives here, in the
one caller that could get it wrong.
"""
argv = containers.quarantine_argv(self.quarantine_workspace)
if argv is None:
log.info("the quarantine backstop is disabled; unmatched windows stay where they land")
return False
self.run_plan(argv)
return True
# -- containers -------------------------------------------------------
def create(self, session_id: str, app_id: str) -> containers.ContainerPlan:
"""Allocate a slot and build the session's container.
The slot is released again if the compositor refuses part way through,
because a half-built container must not also leak a workspace number.
Whatever *was* created is left for :meth:`remove` and for the start-up
scan: deleting an output while the compositor is misbehaving is how one
failure becomes two.
"""
workspace = self.allocator.allocate()
plan = containers.container_plan(
session_id, workspace, self.mode[0], self.mode[1], app_id
)
try:
self.run_plan(plan.create)
except (CompositorUnavailable, ValueError):
self.allocator.release(workspace)
raise
return plan
def remove(self, output: str) -> None:
"""Remove one output of ours. Refuses a name we could not have made."""
if not containers.contains_output(output):
raise ValueError(
f"refusing to remove output {output!r}: not one this broker creates"
)
self.dispatch(["hyprctl", "output", "remove", output])
def release(self, workspace: int | None) -> None:
"""Give a workspace slot back, tolerating one we never held.
Unlike the allocator's own ``release``, this is called from teardown
paths that also run for sessions started before the broker restarted,
or in degraded mode, where there is no slot to return. Losing a slot
is a leak; raising here would abort a teardown that has already killed
the application.
"""
if workspace is None:
return
try:
self.allocator.release(workspace)
except KeyError:
log.debug("workspace %s was not held by this allocator", workspace)
def reserve(self, workspaces: list[int]) -> list[int]:
"""Re-take slots a previous broker handed out. Returns what was taken.
The allocator's frozen interface (CONTRACT-sessions.md §3.2) has
``allocate``, ``release`` and ``in_use`` and no way to say "this one is
already mine", which adoption needs: the records restored at start-up
name workspaces that must not be handed to a new session. Allocating
from the bottom until each wanted slot has come up, then giving back
the ones we did not want, reserves them through the interface that
exists. The band is a few entries wide, so the cost is nothing; the
alternative is a second free list beside the allocator's, which is the
drift the allocator exists to prevent.
"""
wanted = {w for w in workspaces if isinstance(w, int) and not isinstance(w, bool)}
if not wanted:
return []
# Slots this allocator already holds are already reserved. Without
# this, a second reconcile walks the band looking for a number it has
# itself taken, exhausts it, and reports the band full.
taken: list[int] = sorted(wanted & set(self.allocator.in_use()))
wanted -= set(taken)
if not wanted:
return taken
spare: list[int] = []
while wanted - set(taken):
try:
slot = self.allocator.allocate()
except containers.NoSlots:
missing = sorted(wanted - set(taken))
log.error(
"cannot reserve adopted workspaces %s: the band is full; a new "
"session could be given one of them",
missing,
)
break
(taken if slot in wanted else spare).append(slot)
for slot in spare:
self.allocator.release(slot)
return sorted(taken)
# -- reading back -----------------------------------------------------
def read_back(self, app_id: str, pid: int | None = None) -> ContainerFacts | None:
"""What the compositor says about this session's window, or ``None``.
``None`` means no window has appeared yet, which is not a failure: an
application takes time to map one, and the caller polls. A window is
matched by its ``initial_class`` — the stamp the rule also matches —
and failing that by pid, so a session whose toolkit ignored the stamp
is still *observed*, even though its rule will not have bound.
"""
client = self._find(app_id, pid)
if client is None:
return None
workspace_monitor = {w.id: w.monitor for w in self.ipc().workspaces()}
output = workspace_monitor.get(client.workspace_id) if client.workspace_id else None
foreground: bool | None = None
if output is not None:
for monitor in self.ipc().monitors():
if monitor.name == output:
# "Foreground" is the monitor-active-workspace join, not
# the client's own `visible` flag: it answers "is anything
# — a human, the frame server — actually looking at this",
# which a mapped window on a hidden workspace is not.
foreground = monitor.active_workspace_id == client.workspace_id
break
return ContainerFacts(
workspace=client.workspace_id,
output=output,
window={
"stable_id": client.stable_id,
"address": client.address,
"class": client.class_,
"initial_class": client.initial_class,
"title": client.title,
"pid": client.pid,
},
foreground=foreground,
)
def _find(self, app_id: str, pid: int | None) -> Client | None:
by_pid: Client | None = None
for client in self.ipc().clients():
if client.initial_class == app_id:
return client
if pid is not None and pid > 0 and client.pid == pid:
by_pid = client
return by_pid
def survivors(self, app_id: str, output: str | None) -> list[dict[str, Any]]:
"""Windows of ours the compositor still has after a teardown.
Either identity counts: a window still carrying the session's class, or
any window still sitting on the output we were about to remove. Both
mean the teardown did not finish, and the caller reports them instead
of claiming success (PLAN §4.5).
"""
on_output: set[int] = set()
if output is not None:
on_output = {
workspace.id
for workspace in self.ipc().workspaces()
if workspace.monitor == output
}
found = []
for client in self.ipc().clients():
if client.initial_class == app_id or (
client.workspace_id is not None and client.workspace_id in on_output
):
found.append(
{
"address": client.address,
"pid": client.pid,
"class": client.class_,
"initial_class": client.initial_class,
"workspace": client.workspace_id,
}
)
return found
def our_outputs(self) -> list[str]:
"""Live outputs whose names this broker could have created.
:func:`hhstreamd.containers.contains_output` is the whole filter, and
it is the only thing standing between the start-up scan and somebody
else's monitor. A name it rejects is never returned, so it can never
be removed.
"""
return sorted(m.name for m in self.ipc().monitors() if containers.contains_output(m.name))
def _signature_of(client: HyprlandIPC) -> str | None:
"""The instance signature, read back off the socket path we connected to.
``HyprlandIPC.discover`` resolves the signature (from the argument, the
environment, or the single instance directory) but does not report which
one it chose, and the record has to carry it so a restarted broker
re-attaches to the same instance. The socket lives at
``<runtime>/hypr/<signature>/.socket.sock``, so its parent directory is the
answer.
"""
parent = client.request_socket.parent
return parent.name or None
+304
View File
@@ -0,0 +1,304 @@
"""Spatial containers: one headless output and one workspace per session.
A session used to be a process group and nothing more, so every application
landed on whichever workspace the compositor happened to be showing. Two
sessions then shared a screen: a capture of one caught the other's windows, and
a pointer aimed at one could land in the other. A container fixes that by
giving the session a place of its own — a dedicated headless output, a numbered
workspace bound to that output as its default and marked persistent so it
survives the window closing, and a window rule that pins anything the session
spawns there.
**This module computes command lines and nothing else.** It does not run them,
does not talk to a socket, does not read a file, does not look at a clock and
does not import :mod:`hhstreamd.ipc`. That separation is deliberate: the
compositor is the part that cannot be tested without a compositor, so every
decision that *can* be made in a pure function is made here, where a unit test
can assert the exact argv list. The broker executes what comes back.
Three properties the callers depend on:
**Byte-identical output for identical arguments.** The ``create`` list is
emitted in a fixed order — create the output, bind the workspace, pin the
window, then set the mode — that does not depend on the inputs, and no set or
dict is ever iterated to build a command. The only thing a caller can vary is
what it passes in, in the order the signature names: nothing else here is a
source of order. So ``container_plan`` is safe to call twice and diff, which is
how ``container.reconcile`` decides whether a live container matches its plan.
**Argv lists, never strings.** These values reach a compositor that will act on
them, so there is no shell, no quoting and no interpolation of a caller's string
into a command *word*. The one place caller data lands inside a word is a rule
body (``workspace 1000, monitor:hh-x``), where a comma or a newline would end
one field and begin another — which is why the validation below is a control and
not a style preference.
**Validation raises, and names the value.** A session id that is not
``[a-z0-9-]``, a non-positive size, an empty app id: all :class:`ValueError`.
The broker mints its own ids and sizes, so a rejection here means a bug upstream
of us, and a message that quotes the offending value is what makes that bug
findable.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
#: Every output this broker creates carries it. A start-up scan uses the prefix
#: to tell its own orphans — outputs left behind by a crash — from the outputs a
#: human or another tool made, which it must not remove.
OUTPUT_PREFIX = "hh-"
#: Session ids as the broker mints them. Deliberately narrower than "a safe
#: command word": lowercase, digits and the dash, so the name is also a legal
#: Hyprland output name and a regex literal with nothing to escape.
SESSION_ID_RE = re.compile(r"\A[a-z0-9-]+\Z")
#: An application's window class, which we do not mint — it is whatever the
#: toolkit reports, so it has to allow the shapes real classes take
#: (``org.gnome.Nautilus``, ``Alacritty``, ``firefox-esr``). It still excludes
#: every character that could end a field in a rule body or a line in the
#: request: comma, space, quote, newline, ``$``, ``^``.
APP_ID_RE = re.compile(r"\A[A-Za-z0-9._+-]+\Z")
class NoSlots(Exception):
"""The workspace band is full. The caller refuses the session; it never reuses."""
@dataclass(frozen=True, slots=True)
class ContainerPlan:
"""What a session's container is, and the two command lists that realise it.
``create`` and ``teardown`` are complete argv lists in the order they must
run. ``teardown`` is not the reverse of ``create``: removing the output is
enough, because the workspace and window rules are keywords that die with
the compositor's configuration and name an output that no longer exists.
"""
output: str
workspace: int
mode: tuple[int, int]
create: list[list[str]]
teardown: list[list[str]]
def output_name(session_id: str) -> str:
"""``hh-<session-id>`` — the name of the session's headless output."""
return OUTPUT_PREFIX + _checked_session_id(session_id)
def contains_output(name: str) -> bool:
"""True only for an output name this broker could have created.
Used by the start-up scan, which removes what it recognises. So it is
strict in the direction that matters: a bare ``hh-``, a trailing newline or
an upper-case suffix is *not* one of ours, and a scan that answered True
would delete someone else's output.
"""
if not name.startswith(OUTPUT_PREFIX):
return False
return SESSION_ID_RE.match(name[len(OUTPUT_PREFIX) :]) is not None
def app_id_for(session_id: str) -> str:
"""The bare ``hh-<session-id>`` the launcher sets as the app's class.
Same string as the output name, and that is the point: the launcher stamps
it on the application (``--class``, ``app_id``) and
:func:`container_plan` anchors it into the window rule, so the window finds
its own workspace with no lookup and no race against the window appearing.
"""
return OUTPUT_PREFIX + _checked_session_id(session_id)
def container_plan(
session_id: str,
workspace: int,
width: int,
height: int,
app_id: str,
) -> ContainerPlan:
"""The commands that create and tear down one session's container.
``app_id`` is passed in rather than derived from ``session_id`` because the
rule has to match whatever class the application actually reports: it is
:func:`app_id_for` for a well-behaved app the launcher could stamp, and the
app's own class for one that ignores the stamp.
"""
name = output_name(session_id)
slot = _checked_int(workspace, "workspace", minimum=1)
w = _checked_int(width, "width", minimum=1)
h = _checked_int(height, "height", minimum=1)
match = _checked_app_id(app_id)
return ContainerPlan(
output=name,
workspace=slot,
mode=(w, h),
create=[
# The output first: the workspace rule below names it, and a rule
# for an output that does not exist yet binds to nothing.
["hyprctl", "output", "create", "headless", name],
# `default:true` makes this the workspace the output shows, and
# `persistent:true` keeps it alive when the last window closes — a
# container that evaporated between two applications would send the
# next window back to the shared screen.
[
"hyprctl",
"keyword",
"workspace",
f"{slot}, monitor:{name}, default:true, persistent:true",
],
# Anchored (`^...$`) so a class that merely contains the app id
# cannot claim another session's workspace. `initial_class` rather
# than the live class: applications rename their window, and the
# placement has to be decided when it is mapped.
[
"hyprctl",
"keyword",
"windowrule",
f"match:initial_class ^{match}$, workspace {slot}, monitor {name}",
],
# Last, because the mode applies to an output that now exists and
# already has its workspace; setting it earlier would resize a
# screen that is about to be replaced.
["hyprctl", "keyword", "monitor", f"{name},{w}x{h},auto,1"],
],
teardown=[["hyprctl", "output", "remove", name]],
)
def quarantine_argv(quarantine_workspace: str) -> list[list[str]] | None:
"""The backstop rule: a window that matched no container goes here.
Without it, a window with an unexpected class — a dialog spawned by a
helper process, a toolkit that rewrites its class — lands on whatever
workspace is in front, which is the leak containers exist to prevent.
**Install it before any per-session rule.** Hyprland evaluates window
rules in the order the keywords were issued and this one matches every
class, so a quarantine rule issued *after* a session's anchored rule
overrides it and every window in the system ends up in the special
workspace — containers included. The ordering cannot be enforced from
here, because this module never runs anything; the broker installs it once
at start-up, before the first ``container_plan`` is executed, and
:mod:`hhstreamd.container_host` says so at the call site.
``quarantine_workspace`` is a workspace *name* (``special:quarantine``),
not a slot out of the allocator's band — which is why this returns bare
argv and not a :class:`ContainerPlan` (CONTRACT-sessions.md v2 §3.2): a
quarantine rule has no output, no numbered workspace and no mode, and
``container_plan`` refuses the zero size one would have to invent. An
empty or blank name is how "disabled" is spelled, and the answer is
``None`` rather than an empty list — a caller that gets commands should
always have something to run.
"""
target = quarantine_workspace.strip()
if not target:
return None
_checked_rule_value(target, "quarantine_workspace")
return [
[
"hyprctl",
"keyword",
"windowrule",
f"match:initial_class .*, workspace {target}",
]
]
class WorkspaceAllocator:
"""Hands out workspace slots from a fixed band, lowest free first.
Lowest-free rather than monotonic so a long-lived broker's numbers stay
small and readable (``hyprctl workspaces`` is something a human reads), and
so the band is a real bound: ``count`` slots means at most ``count``
containers, with exhaustion surfacing as :class:`NoSlots` at allocation
rather than as a collision later.
"""
def __init__(self, base: int, count: int) -> None:
self._base = _checked_int(base, "base", minimum=1)
self._count = _checked_int(count, "count", minimum=1)
self._used: set[int] = set()
def allocate(self) -> int:
"""The lowest free slot in ``[base, base + count)``. Raises :class:`NoSlots`."""
for slot in range(self._base, self._base + self._count):
if slot not in self._used:
self._used.add(slot)
return slot
raise NoSlots(
f"workspace band {self._base}..{self._base + self._count - 1} is full "
f"({self._count} in use)"
)
def release(self, workspace: int) -> None:
"""Give a slot back. A slot we never handed out raises :class:`KeyError`.
Loudly, because the two ways to get here are a double release and a
caller releasing someone else's slot, and both mean the registry and
this allocator have drifted. Swallowing it would hand the same
workspace to two sessions a few minutes later, which is the leak that is
hard to trace back.
"""
if workspace not in self._used:
raise KeyError(
f"workspace {workspace} was not allocated by this allocator "
f"(in use: {sorted(self._used)})"
)
self._used.discard(workspace)
def in_use(self) -> list[int]:
"""Allocated slots, ascending. Sorted because callers log and diff it."""
return sorted(self._used)
def _checked_session_id(session_id: str) -> str:
if not isinstance(session_id, str) or not SESSION_ID_RE.match(session_id):
raise ValueError(
f"session id {session_id!r} is not [a-z0-9-]+; it names an output and "
"goes into a compositor command"
)
return session_id
def _checked_app_id(app_id: str) -> str:
if not isinstance(app_id, str) or not app_id:
raise ValueError(f"app id {app_id!r} is empty; a window rule needs a class to match")
if not APP_ID_RE.match(app_id):
raise ValueError(
f"app id {app_id!r} is not [A-Za-z0-9._+-]+; a window rule body is "
"comma-separated, so anything else could forge a rule field"
)
return app_id
def _checked_rule_value(value: str, label: str) -> str:
# Same reasoning as an app id, one rule field over: this ends up inside a
# `workspace <value>` field, where a comma starts the next field. The colon
# is allowed because `special:quarantine` needs it.
if not re.match(r"\A[A-Za-z0-9._:+-]+\Z", value):
raise ValueError(
f"{label} {value!r} is not [A-Za-z0-9._:+-]+; it is interpolated into "
"a comma-separated rule body"
)
return value
def _checked_int(value: int, label: str, *, minimum: int) -> int:
# bool is an int in Python, and `True` would silently become workspace 1.
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(f"{label} {value!r} is not an int")
if value < minimum:
raise ValueError(f"{label} {value!r} is not >= {minimum}")
return value
+210
View File
@@ -0,0 +1,210 @@
"""The broker's end of the private driver socket (CONTRACT-sessions.md §3.4).
The pointer driver is a separate process because a Wayland client needs its own
connection; this module is the five-verb client that talks to it. It is the
only place in the broker that knows the driver's wire format, so the driver and
the broker can be read against each other in two files.
**It holds no lease state and asks for none.** The driver is an executor: it
will warp anywhere it is told, and the only thing that stops two sessions
fighting over the one cursor is the lease in :mod:`hhstreamd.manager`. Putting
even a session id in a request here would suggest otherwise, so none of these
methods takes one.
**Blocking, with a short timeout, and deliberately synchronous.** The driver
is local, the requests are one small line each, and the broker is the only
peer. An async client would buy nothing but a way to interleave two warps.
The caller runs it off the event loop (``asyncio.to_thread``) so a wedged
driver cannot stall session lifecycle — which is the whole reason the driver is
a separate process — and the lock below makes that safe: one request on the
wire at a time, whatever thread asks.
**One connection, checked before every use, never retried after one.** The
driver's server handles one connection at a time and reads lines from it until
EOF, so a connection per request would work but would churn the accept loop.
A held connection can die under us when the driver restarts, so it is tested
for EOF before each write and silently replaced — but a request that *was*
written and then went unanswered is never sent again, because a repeated
``button down`` is a click the agent did not ask for. Every failure is
:class:`DriverUnavailable` — never a guess, and never a silent no-op, because a
dropped ``release_all`` leaves a mouse button down.
"""
from __future__ import annotations
import json
import logging
import select
import socket
import threading
from pathlib import Path
from typing import Any
log = logging.getLogger("hhstreamd.driver")
#: The driver answers from memory; it does not render, wait for a frame
#: callback or ask the compositor anything. This only bounds a driver that has
#: stopped answering at all.
DEFAULT_TIMEOUT_S = 2.0
#: Matches the driver's own ceiling (``hhstream_pointer.server``).
MAX_LINE_BYTES = 1 << 20
class DriverUnavailable(Exception):
"""The driver could not be reached, or did not answer intelligibly.
Distinct from :class:`DriverRejected`: this one means the cursor's state is
now unknown, so the broker drops the lease rather than carrying on.
"""
class DriverRejected(Exception):
"""The driver understood the request and refused it (``ok: false``)."""
class PointerDriver:
"""A client for one driver socket. Thread-safe; one request at a time."""
def __init__(self, socket_path: Path | str, *, timeout_s: float = DEFAULT_TIMEOUT_S) -> None:
self.socket_path = Path(socket_path)
self.timeout_s = float(timeout_s)
self._lock = threading.Lock()
self._sock: socket.socket | None = None
self._stream = None
# -- the five verbs ---------------------------------------------------
def warp(self, output: str, x: float, y: float) -> None:
"""Aim at ``x``/``y``, each 0..1 in ``output``'s own frame."""
self.request({"op": "warp", "output": output, "x": float(x), "y": float(y)})
def button(self, button: str, state: str) -> None:
self.request({"op": "button", "button": button, "state": state})
def frame(self) -> None:
"""Commit what was queued. Nothing the driver was sent is delivered
to the compositor until this, so every gesture ends with one."""
self.request({"op": "frame"})
def pressed(self) -> list[str]:
"""What the *driver* believes is down.
The lease keeps its own set, and this is the one that matters when the
two disagree: the driver's is the one the compositor saw.
"""
reply = self.request({"op": "pressed"})
return _string_list(reply.get("buttons"), "pressed")
def release_all(self) -> list[str]:
"""Lift everything, returning what came up. Called on expiry."""
reply = self.request({"op": "release_all"})
return _string_list(reply.get("lifted"), "release_all")
# -- plumbing ---------------------------------------------------------
def request(self, message: dict[str, Any]) -> dict[str, Any]:
"""One request, one reply. Raises rather than returning a guess."""
with self._lock:
try:
return self._exchange(message)
except (OSError, ValueError) as exc:
# The connection is now of unknown state — a half-written
# request, a partial reply — so it is dropped rather than
# reused for the next verb.
self._disconnect()
raise DriverUnavailable(
f"pointer driver {self.socket_path}: {exc}"
) from exc
def close(self) -> None:
with self._lock:
self._disconnect()
def _exchange(self, message: dict[str, Any]) -> dict[str, Any]:
stream = self._connect()
line = json.dumps(message, separators=(",", ":")).encode("ascii") + b"\n"
stream.write(line)
stream.flush()
reply_line = stream.readline(MAX_LINE_BYTES + 1)
if not reply_line:
# The driver went away between the write and the reply, so whether
# it carried the request out is unknowable. **Not retried**: a
# repeated ``button down`` is a second press the agent never asked
# for, and the broker's answer to an unknown cursor is to drop the
# lease, not to guess again.
raise OSError("the driver closed the connection without answering")
if len(reply_line) > MAX_LINE_BYTES:
raise ValueError("reply exceeds the frame limit")
reply = json.loads(reply_line)
if not isinstance(reply, dict):
raise ValueError(f"reply is not an object: {type(reply).__name__}")
if not reply.get("ok"):
raise DriverRejected(str(reply.get("error") or "the driver refused the request"))
return reply
def _connect(self):
if self._stream is not None and not self._stale():
return self._stream
self._disconnect()
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(self.timeout_s)
sock.connect(str(self.socket_path))
except OSError:
sock.close()
raise
self._sock = sock
self._stream = sock.makefile("rwb")
log.debug("connected to the pointer driver at %s", self.socket_path)
return self._stream
def _stale(self) -> bool:
"""True if the held connection has died since the last verb.
The driver never speaks unsolicited, so a readable socket can only be
at EOF — the driver restarted, or was stopped. Checking costs one
non-blocking ``select`` and is what makes reconnecting safe: the
request is written only to a connection that was alive when it was
written, so there is never a question of whether a retry would repeat
a click.
"""
sock = self._sock
if sock is None:
return True
try:
readable, _, _ = select.select([sock], [], [], 0)
except (OSError, ValueError):
return True
return bool(readable)
def _disconnect(self) -> None:
stream, self._stream = self._stream, None
sock, self._sock = self._sock, None
for closeable in (stream, sock):
if closeable is None:
continue
try:
closeable.close()
except OSError:
pass
def _string_list(value: Any, what: str) -> list[str]:
"""A list of button names, or a malformed reply — never a silent ``[]``.
An empty list is a real answer ("nothing was down"); anything that is not a
list of strings means the broker and the driver disagree about the
protocol, and treating that as "nothing was down" is how a button stays
pressed forever.
"""
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
raise DriverUnavailable(f"{what}: expected a list of button names, got {value!r}")
return list(value)
+597
View File
@@ -0,0 +1,597 @@
"""Asking the compositor what it actually has, instead of guessing.
The broker launches applications and then reports on them. Until now it had no
way to see the other side: every session's ``workspace`` and ``window`` were
``null`` because nothing in the daemon could talk to Hyprland. This module is
that voice. It is deliberately the *only* place that knows the compositor's
wire format, so a Hyprland upgrade is one file to re-read.
Three decisions shape everything here.
**Degrade, never guess.** Every failure — no instance directory, two instance
directories and no signature, a socket that is gone, a connection refused, a
reply that is not the JSON it claims to be — is :class:`CompositorUnavailable`.
Nothing returns an empty list, a ``None`` or a plausible-looking default to
stand in for "I could not ask", because a caller that cannot tell those apart
will write a guess into a session record and the operator will believe it.
**Parse defensively, inside the defined shape.** Hyprland's JSON has gained,
renamed and re-typed keys across releases, so a missing key is a *defined*
value (``None``, ``0``, ``-1``) and never a ``KeyError`` reaching the caller.
The exception is a key whose absence makes the record meaningless — a client
with no ``address`` — which is a malformed reply, not a degraded one.
**One connection per request, a held connection for events.** That is what
``hyprctl`` does and what Hyprland expects: it reads a request, writes the
reply and closes. The event socket is the opposite — a stream that must stay
open, blocking, for as long as the caller reads it. When it ends, it raises:
an event stream that stops is a failure the caller must see, because a broker
that quietly stops being told about closed windows looks identical to a broker
watching an idle desktop.
"""
from __future__ import annotations
import json
import os
import socket
import stat
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
#: Hyprland names its per-instance directory after this variable, and every
#: process it starts inherits it. It is the strongest hint available.
SIGNATURE_ENV = "HYPRLAND_INSTANCE_SIGNATURE"
#: ``<runtime dir>/hypr/<signature>/`` holds both sockets (CONTRACT §5).
INSTANCE_SUBDIR = "hypr"
REQUEST_SOCKET_NAME = ".socket.sock"
EVENT_SOCKET_NAME = ".socket2.sock"
#: Requests are local, synchronous and tiny. The compositor answers at once or
#: it is wedged; this only bounds the pathological case where it accepts the
#: connection and then stops. It is a class attribute so a test can shorten it
#: without widening ``__init__``, whose signature is frozen by the contract.
REQUEST_TIMEOUT_S = 2.0
#: Field names for the events a session broker joins on, in payload order. The
#: payload is positional and comma-separated, and the *last* named field keeps
#: any remaining commas — window titles contain them, which is precisely why a
#: naive ``split(",")`` loses the end of a title.
_EVENT_FIELDS: dict[str, tuple[str, ...]] = {
"openwindow": ("address", "workspace", "class", "title"),
"closewindow": ("address",),
"movewindow": ("address", "workspace"),
"movewindowv2": ("address", "workspace_id", "workspace"),
"windowtitle": ("address",),
"windowtitlev2": ("address", "title"),
"activewindow": ("class", "title"),
"activewindowv2": ("address",),
"changefloatingmode": ("address", "floating"),
"urgent": ("address",),
"pin": ("address", "pinned"),
"fullscreen": ("state",),
"workspace": ("name",),
"workspacev2": ("id", "name"),
"createworkspace": ("name",),
"createworkspacev2": ("id", "name"),
"destroyworkspace": ("name",),
"destroyworkspacev2": ("id", "name"),
"moveworkspace": ("name", "monitor"),
"moveworkspacev2": ("id", "name", "monitor"),
"renameworkspace": ("id", "name"),
"activespecial": ("name", "monitor"),
"focusedmon": ("monitor", "workspace"),
"monitoradded": ("name",),
"monitoraddedv2": ("id", "name", "description"),
"monitorremoved": ("name",),
}
class CompositorUnavailable(Exception):
"""No request socket, or the compositor refused. Callers degrade, never guess."""
@dataclass(frozen=True)
class Monitor:
id: int
name: str
x: int
y: int
width: int
height: int
scale: float
active_workspace_id: int | None
@dataclass(frozen=True)
class Workspace:
id: int
name: str
monitor: str | None
windows: int
is_special: bool
@dataclass(frozen=True)
class Client:
address: str
pid: int
workspace_id: int | None
monitor: str | None
class_: str
initial_class: str
title: str
stable_id: str
visible: bool
@dataclass(frozen=True)
class CursorPos:
x: int
y: int
@dataclass(frozen=True)
class Event:
name: str
data: dict
def _as_int(value: object, default: int) -> int:
"""An int, or ``default`` for anything that is not plainly one.
Hyprland has shipped ids as numbers and as numeric strings; ``bool`` is
excluded because ``True`` is not a workspace id.
"""
if isinstance(value, bool):
return default
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, str):
try:
return int(value.strip())
except ValueError:
return default
return default
def _as_float(value: object, default: float) -> float:
if isinstance(value, bool):
return default
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
try:
return float(value.strip())
except ValueError:
return default
return default
def _as_str(value: object) -> str:
"""A string, or "" — never ``None`` leaking into a field typed ``str``."""
if isinstance(value, str):
return value
if value is None:
return ""
return str(value)
def _optional_name(value: object) -> str | None:
"""A monitor name, or ``None`` when the reply did not carry one.
``clients -j`` reports ``monitor`` as a numeric *index* while
``workspaces -j`` reports it as a *name*; both are coerced to text so the
field means "what the compositor said" and ``None`` keeps its single
meaning of "the compositor said nothing".
"""
if value is None or value == "":
return None
if isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return str(int(value))
if isinstance(value, str):
return value
return None
def _nested_id(value: object) -> int | None:
"""``{"id": 3, "name": "3"}`` -> ``3``; anything else -> ``None``."""
if isinstance(value, dict):
raw = value.get("id")
if isinstance(raw, bool):
return None
if isinstance(raw, int):
return raw
if isinstance(raw, (float, str)):
parsed = _as_int(raw, -(2**62))
return None if parsed == -(2**62) else parsed
return None
def _entries(payload: object, what: str) -> list[dict]:
"""The list of objects a ``-j`` listing must be, or a malformed reply."""
if not isinstance(payload, list):
raise CompositorUnavailable(f"{what}: expected a JSON list, got {type(payload).__name__}")
out = []
for item in payload:
if not isinstance(item, dict):
raise CompositorUnavailable(
f"{what}: expected objects in the list, got {type(item).__name__}"
)
out.append(item)
return out
def _monitor(raw: dict) -> Monitor:
name = raw.get("name")
if not isinstance(name, str) or not name:
raise CompositorUnavailable("monitors: an entry has no name")
return Monitor(
# `monitors -j` reports the id that `clients -j` refers to as a client's
# `monitor`. Joining through it is how a client is tied to the output it
# is on -- `Client.monitor` is that same number rendered as text, while
# `Workspace.monitor` is a name. CONTRACT-sessions v2 added this field;
# `-1` is the honest value when a reply omits it, because no compositor
# numbers a monitor negative.
id=_as_int(raw.get("id"), -1),
name=name,
x=_as_int(raw.get("x"), 0),
y=_as_int(raw.get("y"), 0),
width=_as_int(raw.get("width"), 0),
height=_as_int(raw.get("height"), 0),
scale=_as_float(raw.get("scale"), 1.0),
# Older replies nest the active workspace; a monitor with none (an
# output just created and not yet populated) legitimately has no id.
active_workspace_id=_nested_id(raw.get("activeWorkspace")),
)
def _workspace(raw: dict) -> Workspace:
if "id" not in raw:
raise CompositorUnavailable("workspaces: an entry has no id")
ident = _as_int(raw.get("id"), -(2**62))
if ident == -(2**62):
raise CompositorUnavailable(f"workspaces: entry id is not a number ({raw.get('id')!r})")
name = _as_str(raw.get("name"))
special = raw.get("special")
return Workspace(
id=ident,
name=name,
monitor=_optional_name(raw.get("monitor")),
windows=_as_int(raw.get("windows"), 0),
# Hyprland did not always report ``special``. Where it does not, the
# two things that have always been true of a special workspace are
# its negative id and its ``special:`` name prefix.
is_special=(
bool(special)
if isinstance(special, bool)
else (ident < 0 or name.startswith("special"))
),
)
def _client(raw: dict) -> Client:
address = raw.get("address")
if not isinstance(address, str) or not address:
raise CompositorUnavailable("clients: an entry has no address")
initial_class = _as_str(raw.get("initialClass"))
pid = _as_int(raw.get("pid"), -1)
mapped = raw.get("mapped")
hidden = raw.get("hidden")
return Client(
address=address,
# -1, not 0: no process has it, so an unknown pid cannot be mistaken
# for a real one by code that only checks for falsiness.
pid=pid,
workspace_id=_nested_id(raw.get("workspace")),
monitor=_optional_name(raw.get("monitor")),
class_=_as_str(raw.get("class")),
initial_class=initial_class,
title=_as_str(raw.get("title")),
# The contract names a stable id but Hyprland publishes none. The
# initial class plus the pid is the closest honest thing: the launcher
# sets the class per session, the pid is the session's process, and
# unlike ``address`` the pair survives a window being remapped. It
# falls back to the address rather than ever being empty.
stable_id=f"{initial_class}:{pid}" if initial_class and pid > 0 else address,
# "Visible" is mapped-and-not-hidden; a missing key must not make a
# live window look gone, so absence reads as mapped.
visible=(True if mapped is None else bool(mapped)) and not bool(hidden),
)
def parse_event(line: str) -> Event:
"""``"name>>a,b,c"`` -> :class:`Event`.
The payload is positional, so :data:`_EVENT_FIELDS` names the fields for
the events the broker joins on and the last named field absorbs any
remaining commas (titles contain them). ``raw`` and ``args`` are always
present, so an event this module does not know is still usable rather than
discarded, and nothing is hidden behind the naming.
A line with no ``>>`` is a malformed reply, not an event with an odd name:
:class:`CompositorUnavailable`.
"""
text = line.rstrip("\r\n")
name, separator, payload = text.partition(">>")
if not separator or not name:
raise CompositorUnavailable(f"event line has no name>>payload separator: {text!r}")
data: dict = {"raw": payload}
if payload == "":
# An empty payload carried nothing; naming fields here would invent
# values ("" is not a window address) for an event like
# ``configreloaded>>`` that has no arguments at all.
data["args"] = []
return Event(name=name, data=data)
fields = _EVENT_FIELDS.get(name)
if fields:
parts = payload.split(",", len(fields) - 1)
data["args"] = list(parts)
data.update(zip(fields, parts))
else:
data["args"] = payload.split(",")
return Event(name=name, data=data)
class HyprlandIPC:
"""A client for one compositor instance's request and event sockets."""
#: Overridable per instance; ``__init__``'s signature is frozen, so this is
#: how a caller (or a test) bounds a wedged compositor differently.
request_timeout_s: float = REQUEST_TIMEOUT_S
def __init__(self, request_socket: Path, event_socket: Path | None = None) -> None:
self.request_socket = Path(request_socket)
self.event_socket = Path(event_socket) if event_socket is not None else None
self._event_sock: socket.socket | None = None
@classmethod
def discover(cls, runtime_dir: Path, signature: str | None = None) -> "HyprlandIPC":
"""Locate the instance under ``runtime_dir`` and return a client for it.
The signature comes from the argument, else the environment, else the
*single* directory under ``<runtime_dir>/hypr/``. Two instances and no
signature raises: picking one would silently aim the broker's queries,
and later its pointer, at the wrong desktop.
"""
hypr = Path(runtime_dir) / INSTANCE_SUBDIR
chosen = signature or os.environ.get(SIGNATURE_ENV) or None
if chosen is not None:
chosen = chosen.strip() or None
if chosen is not None and ("/" in chosen or chosen in (".", "..")):
raise CompositorUnavailable(
f"instance signature is not a directory name: {chosen!r}"
)
if chosen is None:
chosen = cls._sole_instance(hypr)
directory = hypr / chosen
request = directory / REQUEST_SOCKET_NAME
try:
mode = request.stat().st_mode
except OSError as exc:
raise CompositorUnavailable(
f"compositor request socket {request}: {exc.strerror or exc}"
) from exc
if not stat.S_ISSOCK(mode):
raise CompositorUnavailable(f"compositor request socket {request} is not a socket")
return cls(request, directory / EVENT_SOCKET_NAME)
@staticmethod
def _sole_instance(hypr: Path) -> str:
"""The one directory under ``<runtime_dir>/hypr``, or a refusal."""
try:
with os.scandir(hypr) as entries:
names = sorted(e.name for e in entries if e.is_dir())
except OSError as exc:
raise CompositorUnavailable(
f"compositor instance dir {hypr}: {exc.strerror or exc}; is the compositor running?"
) from exc
if not names:
raise CompositorUnavailable(
f"compositor instance dir {hypr} holds no instance; is the compositor running?"
)
if len(names) > 1:
raise CompositorUnavailable(
f"compositor instance dir {hypr} holds {len(names)} instances "
f"({', '.join(names)}); set {SIGNATURE_ENV} or pass a signature"
)
return names[0]
# -- the request socket ------------------------------------------------
def _wire(self, command: str) -> str:
"""The bytes Hyprland expects for ``command``.
Hyprland reads everything before the *first* ``/`` as output flags, so
a command is sent with a leading ``/`` — otherwise ``dispatch exec
/usr/bin/foo`` would be read as the flags ``dispatch exec `` followed
by a request of ``usr/bin/foo``. A command whose first word already
carries a prefix (``j/clients``) is passed through untouched, which is
what makes :meth:`query` able to reach anything this module does not
wrap.
"""
text = command.strip()
if not text:
raise CompositorUnavailable("empty request")
first = text.split(None, 1)[0]
return text if "/" in first else "/" + text
def _request(self, command: str) -> str:
"""Send one request, read the whole reply, close. Raises on any failure."""
wire = self._wire(command)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(self.request_timeout_s)
try:
sock.connect(str(self.request_socket))
except OSError as exc:
raise CompositorUnavailable(
f"compositor request socket {self.request_socket}: {exc.strerror or exc}"
) from exc
try:
sock.sendall(wire.encode())
# Half-close: the reply ends at EOF, and a compositor that
# waits for more input would otherwise deadlock against a
# client waiting for more output.
sock.shutdown(socket.SHUT_WR)
chunks = []
while True:
chunk = sock.recv(65536)
if not chunk:
break
chunks.append(chunk)
except socket.timeout as exc:
raise CompositorUnavailable(
f"compositor did not answer {command!r} within {self.request_timeout_s}s"
) from exc
except OSError as exc:
raise CompositorUnavailable(
f"compositor connection lost during {command!r}: {exc.strerror or exc}"
) from exc
finally:
sock.close()
# errors="replace" because a window title is arbitrary user data and a
# decoding accident must not masquerade as the compositor being down.
return b"".join(chunks).decode("utf-8", errors="replace")
def _json(self, command: str, what: str) -> object:
text = self._request(command)
if not text.strip():
raise CompositorUnavailable(f"{what}: empty reply")
try:
return json.loads(text)
except ValueError as exc:
# Hyprland answers an unknown or rejected request in plain text, so
# this is also where "that command does not exist here" lands.
raise CompositorUnavailable(
f"{what}: reply is not JSON ({exc}): {text[:120]!r}"
) from exc
def query(self, command: str) -> str:
"""The raw request socket, for anything this module does not wrap."""
return self._request(command)
def version(self) -> str:
"""The compositor's own version banner, verbatim.
Text, not ``version -j``: the banner is what every Hyprland has
answered, and parsing it into parts here would be this module guessing
at a shape that has changed.
"""
text = self._request("version").strip()
if not text:
raise CompositorUnavailable("version: empty reply")
return text
def monitors(self) -> list[Monitor]:
entries = _entries(self._json("j/monitors", "monitors"), "monitors")
return [_monitor(raw) for raw in entries]
def workspaces(self) -> list[Workspace]:
entries = _entries(self._json("j/workspaces", "workspaces"), "workspaces")
return [_workspace(raw) for raw in entries]
def clients(self) -> list[Client]:
return [_client(raw) for raw in _entries(self._json("j/clients", "clients"), "clients")]
def cursorpos(self) -> CursorPos:
payload = self._json("j/cursorpos", "cursorpos")
if not isinstance(payload, dict) or "x" not in payload or "y" not in payload:
raise CompositorUnavailable(
f"cursorpos: expected an object with x and y, got {payload!r}"
)
sentinel = -(2**62)
x = _as_int(payload.get("x"), sentinel)
y = _as_int(payload.get("y"), sentinel)
if x == sentinel or y == sentinel:
raise CompositorUnavailable(f"cursorpos: x and y are not numbers: {payload!r}")
return CursorPos(x=x, y=y)
# -- the event socket --------------------------------------------------
def events(self) -> Iterator[Event]:
"""Blocking iteration over the event stream.
The connection is made here rather than on the first ``next()``, so a
missing event socket is reported to the caller that asked for the
stream instead of to whatever later happens to iterate it. The
iterator never ends quietly: EOF raises :class:`CompositorUnavailable`,
because a compositor that stopped talking and a desktop where nothing
happens must not look the same.
"""
if self.event_socket is None:
raise CompositorUnavailable("no event socket was configured for this instance")
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(self.request_timeout_s)
sock.connect(str(self.event_socket))
except OSError as exc:
sock.close()
raise CompositorUnavailable(
f"compositor event socket {self.event_socket}: {exc.strerror or exc}"
) from exc
# Blocking from here on: an idle desktop sends nothing for hours and a
# read timeout would turn that into a false failure.
sock.settimeout(None)
self._close_event_sock()
self._event_sock = sock
return self._iter_events(sock)
def _iter_events(self, sock: socket.socket) -> Iterator[Event]:
buffer = b""
while True:
try:
chunk = sock.recv(65536)
except OSError as exc:
raise CompositorUnavailable(
f"compositor event socket {self.event_socket}: {exc.strerror or exc}"
) from exc
if not chunk:
# A trailing fragment is a truncated event, never an event.
raise CompositorUnavailable(
f"compositor event stream ended ({self.event_socket})"
+ (f"; {len(buffer)} bytes left unterminated" if buffer else "")
)
buffer += chunk
while b"\n" in buffer:
line, buffer = buffer.split(b"\n", 1)
yield parse_event(line.decode("utf-8", errors="replace"))
def _close_event_sock(self) -> None:
sock, self._event_sock = self._event_sock, None
if sock is None:
return
try:
# shutdown first: closing alone does not wake a thread already
# blocked in recv, and unblocking it is the point of close().
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
sock.close()
def close(self) -> None:
"""Drop the event stream. Idempotent; request sockets are per-call."""
self._close_event_sock()
+38 -3
View File
@@ -32,6 +32,18 @@ environment at spawn. Without that option the old inherited-environment
behaviour stands, and the daemon warns at startup that applications may not
reach a compositor.
**The container stamp.** A session's window rule matches ``initial_class
^hh-<id>$``, so the application has to report that class or the rule binds to
nothing and the window lands outside its container. The only lever this module
has is the environment (:data:`APP_ID_ENV`), because the alternative — a
per-app ``--app-id``/``--class`` flag — would have to come from the allowlist,
and the allowlist is not this slice's file. The variables below are the ones
that are actually read by something: SDL's two, X11's ``RESOURCE_NAME`` (which
XWayland clients surface as ``WM_CLASS``), and ``HHSTREAM_APP_ID`` for a
wrapper script that knows what to do with it. **A GTK or Qt application
ignores all of them**, which is a real limit and is reported as one: the
read-back after launch is what tells the broker the rule did not bind.
The app runs as **the same unprivileged user as the daemon** and inherits the
real home directory. M0 invents no service account and forces no throwaway
``HOME``; ``--home`` pins a different one and ``--ephemeral-home`` opts in to a
@@ -52,6 +64,19 @@ from .registry import Session
log = logging.getLogger("hhstreamd.launcher")
#: The variables that carry the container stamp, each read by something real:
#: SDL sets the surface's app id from its two, Xlib's ``XSetClassHint`` falls
#: back to ``RESOURCE_NAME`` for an XWayland client's ``WM_CLASS``, and
#: ``HHSTREAM_APP_ID`` is the broker's own name for it. A toolkit that reads
#: none of them (GTK, Qt) keeps its own class and its window rule will not
#: bind; that is visible in the read-back, not papered over here.
APP_ID_ENV = (
"HHSTREAM_APP_ID",
"SDL_VIDEO_WAYLAND_WMCLASS",
"SDL_VIDEO_X11_WMCLASS",
"RESOURCE_NAME",
)
#: Environment variables the daemon's own plumbing must not leak into an app.
_STRIPPED = (
"HHSTREAM_SOCKET",
@@ -104,7 +129,7 @@ class Launcher:
# ---- environment -------------------------------------------------
def build_env(self, session_id: str, home: Path) -> dict[str, str]:
def build_env(self, session_id: str, home: Path, app_id: str | None = None) -> dict[str, str]:
"""The app's environment.
It inherits the daemon's, minus the daemon's own configuration, plus a
@@ -133,6 +158,9 @@ class Launcher:
env["HHSTREAM_SESSION_ID"] = session_id
if self.compositor is not None:
env.update(self.compositor.env())
if app_id:
for name in APP_ID_ENV:
env[name] = app_id
return env
def resolve_home(self, session_id: str, home: str | None, ephemeral: bool) -> tuple[Path, bool]:
@@ -184,8 +212,15 @@ class Launcher:
*,
home: str | None = None,
ephemeral_home: bool = False,
app_id: str | None = None,
) -> Spawned:
"""Start the application. Raises ``OSError`` if it cannot be executed."""
"""Start the application. Raises ``OSError`` if it cannot be executed.
``app_id`` is the container stamp: the class the session's window rule
matches on. It reaches the application through the environment only
(see :data:`APP_ID_ENV` and the module docstring), so passing it is a
request, not a guarantee.
"""
if not argv:
raise ValueError("argv is empty")
@@ -196,7 +231,7 @@ class Launcher:
raise ValueError(f"argv[0] must be an absolute path, got {argv[0]!r}")
home_path, is_ephemeral = self.resolve_home(session_id, home, ephemeral_home)
env = self.build_env(session_id, home_path)
env = self.build_env(session_id, home_path, app_id)
log_file = self.log_path(session_id)
log_file.parent.mkdir(parents=True, exist_ok=True, mode=0o750)
+1105 -22
View File
File diff suppressed because it is too large. Load diff
+114
View File
@@ -9,6 +9,7 @@ rest of ``hhstreamd``.
from __future__ import annotations
import collections
import enum
import json
from typing import Any
@@ -48,6 +49,14 @@ class ExitCode(enum.IntEnum):
POLICY = 6
TIMEOUT = 7
BUSY = 8
#: The verb needs the pointer lease and this session does not hold it.
#: Distinct from BUSY, which is "someone else holds it": an agent that
#: sees 9 must acquire, one that sees 8 must wait.
NO_LEASE = 9
#: An IPC or output operation failed. **The session is not lost** — it
#: keeps running in degraded mode — so this must never be confused with a
#: session failure, which is what a shared code would do.
COMPOSITOR = 10
#: Machine-readable error names, grouped by the exit code they map to. Every
@@ -80,6 +89,9 @@ EXIT_CODE_FOR_ERROR: dict[str, ExitCode] = {
"not_allowlisted": ExitCode.POLICY,
"argument_refused": ExitCode.POLICY,
"session_cap_reached": ExitCode.POLICY,
# The workspace band is full. A policy refusal and not a compositor
# failure: the compositor is fine, the broker is at its budget.
"container_budget": ExitCode.POLICY,
"refused": ExitCode.POLICY,
# 7 — timed out
"timeout": ExitCode.TIMEOUT,
@@ -87,6 +99,15 @@ EXIT_CODE_FOR_ERROR: dict[str, ExitCode] = {
# 8 — busy
"busy": ExitCode.BUSY,
"already_managed": ExitCode.BUSY,
"pointer_busy": ExitCode.BUSY,
# 9 — the lease is required and not held
"no_lease": ExitCode.NO_LEASE,
# 10 — the compositor side failed; the session itself is fine
"compositor": ExitCode.COMPOSITOR,
"compositor_unavailable": ExitCode.COMPOSITOR,
"no_container": ExitCode.COMPOSITOR,
"driver_unavailable": ExitCode.COMPOSITOR,
"driver_refused": ExitCode.COMPOSITOR,
}
@@ -103,6 +124,99 @@ def exit_code_for(error: str | None) -> ExitCode:
return EXIT_CODE_FOR_ERROR.get(error, ExitCode.BAD_STATE)
# --------------------------------------------------------------------------
# Verbs and `request_id` idempotency (PLAN §8)
# --------------------------------------------------------------------------
#: Every verb the daemon answers. The container and pointer verbs are dotted
#: and the original eight are not, because the original eight are frozen
#: (CONTRACT-sessions.md §4: "existing verbs are unchanged") and renaming them
#: would break every agent for a cosmetic gain.
VERBS = (
"ping",
"start",
"list",
"status",
"touch",
"kill",
"gc",
"adopt",
"logs",
"container.list",
"container.reconcile",
"pointer.acquire",
"pointer.move",
"pointer.button",
"pointer.click",
"pointer.release",
"pointer.state",
)
#: Verbs whose reply is remembered by ``request_id``, so a caller that died
#: before reading the reply can retry without the mutation happening twice.
#:
#: The read verbs are absent deliberately: they are idempotent already, so a
#: retry costs nothing, and a cached ``list`` would be a stale one. Every
#: ``pointer.*`` verb that moves something is here, because a retried click is
#: a second click — the one failure an agent cannot undo.
MUTATING_VERBS = frozenset(
{
"start",
"touch",
"kill",
"adopt",
"gc",
"container.reconcile",
"pointer.acquire",
"pointer.move",
"pointer.button",
"pointer.click",
"pointer.release",
}
)
#: How many completed replies are kept. Bounded because a client chooses the
#: ids: an unbounded cache is memory a peer controls.
DEDUP_ENTRIES = 64
class IdempotencyCache:
"""The last N mutating replies, by ``request_id``.
A retry returns *the recorded answer*, including a recorded failure: an
agent that retries a ``start`` which was refused by policy must see the
refusal again, not a second attempt that might succeed and leave it with
an application it has no id for. Replies are returned with
``deduplicated: true`` so the caller can tell a replay from a fresh answer
rather than having to infer it.
"""
def __init__(self, capacity: int = DEDUP_ENTRIES) -> None:
self.capacity = capacity
self._entries: collections.OrderedDict[str, dict[str, Any]] = collections.OrderedDict()
def lookup(self, op: str, request_id: Any) -> dict[str, Any] | None:
"""The recorded reply for this id, or ``None`` to go ahead and do it."""
if not isinstance(request_id, str) or op not in MUTATING_VERBS:
return None
recorded = self._entries.get(request_id)
if recorded is None:
return None
return {**recorded, "deduplicated": True}
def remember(self, op: str, request_id: Any, response: dict[str, Any]) -> None:
if not isinstance(request_id, str) or op not in MUTATING_VERBS:
return
self._entries[request_id] = dict(response)
self._entries.move_to_end(request_id)
while len(self._entries) > self.capacity:
self._entries.popitem(last=False)
def __len__(self) -> int:
return len(self._entries)
# --------------------------------------------------------------------------
# Message construction
# --------------------------------------------------------------------------
+124 -1
View File
@@ -22,7 +22,12 @@ from .clock import Clock, iso
log = logging.getLogger("hhstreamd.registry")
SCHEMA = 2
#: 3 adds the container, the pointer bookmark and the compositor signature
#: (PLAN §7). The number is read, never written by anyone but this module: a
#: record carrying an older one is **migrated on load** (:func:`migrate`), not
#: refused, because the processes it describes are still running and refusing
#: the record would strand them.
SCHEMA = 3
#: Tombstones survive this long so a ``status`` after an unexplained failure
#: still answers the question. ``gc`` prunes them.
@@ -34,6 +39,28 @@ DEFAULT_TOMBSTONE_TTL_S = 3600.0
ACTIVITY_FLUSH_INTERVAL_S = 15.0
class ContainerState:
"""What the broker knows about a session's spatial container.
These are the only four answers. ``container: null`` is a fifth and
different thing — "this session has no container at all" — and nothing here
means "probably something": a field the compositor did not confirm stays
``None`` (PLAN §7).
"""
#: Created by us, and the compositor still shows the output.
OWNED = "owned"
#: No IPC, so nothing was created and nothing can be verified. The session
#: still starts, stops and is reaped by process identity (PLAN §4.4).
DEGRADED = "degraded"
#: Torn down on purpose: the output was removed and the slot released.
REMOVED = "removed"
#: The record and the compositor disagree — the output we recorded is not
#: there, or an output of ours has no live session. Never deleted on a
#: guess; reconciliation decides.
ORPHAN = "orphan"
class State:
STARTING = "starting"
READY = "ready"
@@ -102,6 +129,19 @@ class Session:
workspace: int | None = None
window: Any = None
foreground: bool | None = None
#: ``{output, workspace, mode, created_by, state}`` or ``None`` for "no
#: container". A dict rather than a nested dataclass because
#: :meth:`to_dict` is ``asdict`` and :meth:`from_dict` is ``cls(**data)``:
#: a dataclass would serialise and come back as a dict anyway, and the
#: asymmetry is where a half-migrated record would hide.
container: dict[str, Any] | None = None
#: ``{bookmark, last_released_at, released_by}``. Absent (``None``) means
#: the pointer was never aimed here — not that its position is unknown.
pointer: dict[str, Any] | None = None
#: ``HYPRLAND_INSTANCE_SIGNATURE`` of the compositor this session's
#: container lives in, so a restarted broker re-attaches to the same
#: instance instead of picking whichever one is there now.
signature: str | None = None
command_count: int = 0
exit_code: int | None = None
exit_detected_by: str | None = None
@@ -147,6 +187,7 @@ class Session:
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "Session":
data = migrate(data)
known = {f for f in cls.__dataclass_fields__}
unknown = set(data) - known
if unknown:
@@ -168,6 +209,88 @@ class Session:
return data
def container_record(
*,
output: str | None,
workspace: int | None,
mode: tuple[int, int] | None,
created_by: str,
state: str,
) -> dict[str, Any]:
"""One ``container`` sub-record (PLAN §7).
Every argument is explicit and may be ``None`` because the degraded case is
the common one: there is a container *state* to report long before there is
an output to name, and the alternative — leaving the key out — would read
as "no container" when what we mean is "a container we could not verify".
"""
return {
"output": output,
"workspace": workspace,
"mode": None if mode is None else {"width": mode[0], "height": mode[1]},
"created_by": created_by,
"state": state,
}
def pointer_record(
*,
bookmark: dict[str, Any] | None,
last_released_at: str | None,
released_by: str | None,
) -> dict[str, Any]:
"""One ``pointer`` sub-record: where the cursor was left, and by what.
Written on every move and on release. A session that has one has been
aimed at; a session that has none never was.
"""
return {
"bookmark": bookmark,
"last_released_at": last_released_at,
"released_by": released_by,
}
def migrate(data: dict[str, Any]) -> dict[str, Any]:
"""Bring a record read from disk up to :data:`SCHEMA`.
A schema-2 record is **adopted, not rejected**: its application is very
likely still running, and the daemon that wrote it knew nothing of
containers, so the honest value for every field schema 3 added is ``None``
— "no container", "the pointer was never used here", "we do not know which
compositor instance this was". Each of those is a defined value, which is
the whole reason the migration can be this short.
A record from a *newer* schema is left alone and loudly logged: the fields
this daemon does not know are dropped by :meth:`Session.from_dict`, and
guessing at what a future version meant would be worse than running with
the subset we understand.
"""
schema = data.get("schema")
if schema == SCHEMA:
return data
if isinstance(schema, int) and schema > SCHEMA:
log.error(
"record %s is schema %s, newer than this daemon's %s; reading the fields "
"this version knows and leaving the rest",
data.get("id"),
schema,
SCHEMA,
)
return data
upgraded = dict(data)
# Only ever *adds* keys. A v2 record that somehow carries a container must
# keep it: the field is new to the schema, not new to the session.
for key in ("container", "pointer", "signature"):
upgraded.setdefault(key, None)
upgraded["schema"] = SCHEMA
log.info("migrated record %s from schema %s to %s", data.get("id"), schema, SCHEMA)
return upgraded
def mint_id(app: str, taken: set[str], *, rng: Any = secrets) -> str:
"""``<app-slug>-<6 base32 chars>`` (DESIGN.md §2.2).
+90 -22
View File
@@ -13,7 +13,6 @@ This module is framing and dispatch only. Every decision lives in
from __future__ import annotations
import asyncio
import collections
import contextlib
import logging
import os
@@ -35,14 +34,9 @@ DEFAULT_REQUEST_TIMEOUT_S = 5.0
#: A `kill` may legitimately take `grace` seconds, so it gets its own budget.
KILL_TIMEOUT_MARGIN_S = 5.0
#: Replies to mutating verbs are remembered so a CLI that died before reading
#: the reply can retry without launching a second application.
DEDUP_ENTRIES = 64
#: Verbs whose replies are cached by `request_id`. The read verbs are absent
#: deliberately: they are idempotent, so a retry costs nothing and a cached
#: `list` would be a stale one.
MUTATING_VERBS = frozenset({"start", "touch", "kill", "adopt", "gc"})
#: `request_id` idempotency lives in `protocol` (which verbs mutate, how many
#: replies are kept, what a replay looks like) because the CLI has to agree
#: with it and the CLI imports that module and not this one.
class ControlServer:
@@ -59,7 +53,7 @@ class ControlServer:
self.request_timeout_s = request_timeout_s
self.socket_mode = socket_mode
self._server: asyncio.AbstractServer | None = None
self._dedup: collections.OrderedDict[str, dict[str, Any]] = collections.OrderedDict()
self._dedup = protocol.IdempotencyCache()
self._ops: dict[str, Callable[[dict[str, Any], dict[str, Any]], Awaitable[dict[str, Any]]]] = {
"ping": self._op_ping,
"start": self._op_start,
@@ -70,6 +64,14 @@ class ControlServer:
"gc": self._op_gc,
"adopt": self._op_adopt,
"logs": self._op_logs,
"container.list": self._op_container_list,
"container.reconcile": self._op_container_reconcile,
"pointer.acquire": self._op_pointer_acquire,
"pointer.move": self._op_pointer_move,
"pointer.button": self._op_pointer_button,
"pointer.click": self._op_pointer_click,
"pointer.release": self._op_pointer_release,
"pointer.state": self._op_pointer_state,
}
# ------------------------------------------------------------------
@@ -188,9 +190,8 @@ class ControlServer:
"unknown_op", f"unknown op {op!r}", hint=f"known: {', '.join(sorted(self._ops))}"
)
if isinstance(request_id, str) and op in MUTATING_VERBS and request_id in self._dedup:
cached = dict(self._dedup[request_id])
cached["deduplicated"] = True
cached = self._dedup.lookup(op, request_id)
if cached is not None:
return cached
timeout = self.request_timeout_s
@@ -224,8 +225,7 @@ class ControlServer:
response.setdefault("elapsed_ms", elapsed_ms)
if isinstance(request_id, str):
response["request_id"] = request_id
if op in MUTATING_VERBS:
self._remember(request_id, response)
self._dedup.remember(op, request_id, response)
self.manager.audit.emit(
"request",
@@ -239,12 +239,6 @@ class ControlServer:
)
return response
def _remember(self, request_id: str, response: dict[str, Any]) -> None:
self._dedup[request_id] = dict(response)
self._dedup.move_to_end(request_id)
while len(self._dedup) > DEDUP_ENTRIES:
self._dedup.popitem(last=False)
# ------------------------------------------------------------------
# ops
# ------------------------------------------------------------------
@@ -290,7 +284,7 @@ class ControlServer:
return protocol.ok(id=record["id"], state=record["state"], session=record)
async def _op_gc(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
return protocol.ok(**self.manager.gc())
return protocol.ok(**await self.manager.gc())
async def _op_adopt(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
record = await self.manager.adopt(
@@ -300,6 +294,80 @@ class ControlServer:
)
return protocol.ok(id=record["id"], state=record["state"], session=record)
async def _op_container_list(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(**self.manager.container_list())
async def _op_container_reconcile(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(**await self.manager.container_reconcile(request.get("id")))
async def _op_pointer_acquire(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_acquire(
request.get("id"),
ttl_s=request.get("ttl_s"),
# Restoring is the default: the bookmark exists so a gesture
# can be picked up where it was left, and a caller that wants
# the centre of the output says so.
restore=bool(request.get("restore", True)),
)
)
async def _op_pointer_move(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_move(
request.get("id"),
request.get("lease_id"),
x=request.get("x"),
y=request.get("y"),
dx=request.get("dx"),
dy=request.get("dy"),
)
)
async def _op_pointer_button(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_button(
request.get("id"),
request.get("lease_id"),
request.get("button"),
request.get("state"),
)
)
async def _op_pointer_click(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_click(
request.get("id"),
request.get("lease_id"),
request.get("button", "left"),
request.get("count", 1),
)
)
async def _op_pointer_release(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_release(request.get("id"), request.get("lease_id"))
)
async def _op_pointer_state(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(**self.manager.pointer_state())
async def _op_logs(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]:
return protocol.ok(
**self.manager.logs(
+106
View File
@@ -0,0 +1,106 @@
"""The workspace allocator: lowest free, reuse after release, and loud bugs."""
from __future__ import annotations
import pytest
from hhstreamd.containers import NoSlots, WorkspaceAllocator
def test_allocates_the_band_from_its_base_upwards() -> None:
alloc = WorkspaceAllocator(1000, 4)
assert [alloc.allocate() for _ in range(4)] == [1000, 1001, 1002, 1003]
assert alloc.in_use() == [1000, 1001, 1002, 1003]
def test_a_released_slot_is_reused_before_a_higher_free_one() -> None:
alloc = WorkspaceAllocator(1000, 4)
for _ in range(3):
alloc.allocate()
alloc.release(1001)
assert alloc.in_use() == [1000, 1002]
assert alloc.allocate() == 1001
assert alloc.allocate() == 1003
assert alloc.in_use() == [1000, 1001, 1002, 1003]
def test_a_full_band_raises_no_slots_and_stays_unchanged() -> None:
alloc = WorkspaceAllocator(1000, 2)
alloc.allocate()
alloc.allocate()
with pytest.raises(NoSlots) as exc:
alloc.allocate()
assert "1000..1001" in str(exc.value)
assert alloc.in_use() == [1000, 1001]
# Exhaustion is not terminal: a release makes the slot available again.
alloc.release(1000)
assert alloc.allocate() == 1000
def test_releasing_a_slot_we_never_handed_out_is_a_key_error() -> None:
alloc = WorkspaceAllocator(1000, 2)
alloc.allocate()
# Inside the band but free, and outside the band: both are caller bugs, and
# a silent no-op would let two sessions share a workspace later.
with pytest.raises(KeyError) as free_slot:
alloc.release(1001)
assert "1001" in str(free_slot.value)
with pytest.raises(KeyError):
alloc.release(7)
assert alloc.in_use() == [1000]
def test_a_double_release_raises() -> None:
alloc = WorkspaceAllocator(1000, 2)
slot = alloc.allocate()
alloc.release(slot)
with pytest.raises(KeyError):
alloc.release(slot)
assert alloc.in_use() == []
def test_in_use_is_ascending_whatever_the_allocation_order() -> None:
alloc = WorkspaceAllocator(1000, 3)
a, b, c = alloc.allocate(), alloc.allocate(), alloc.allocate()
alloc.release(b)
alloc.release(a)
alloc.allocate()
alloc.allocate()
assert alloc.in_use() == [1000, 1001, 1002]
assert c == 1002
def test_a_band_must_be_a_real_band() -> None:
with pytest.raises(ValueError) as count:
WorkspaceAllocator(1000, 0)
assert "count" in str(count.value)
with pytest.raises(ValueError) as base:
WorkspaceAllocator(0, 4)
assert "base" in str(base.value)
with pytest.raises(ValueError) as kind:
WorkspaceAllocator(1000, 2.5) # type: ignore[arg-type]
assert "count" in str(kind.value)
assert "is not an int" in str(kind.value)
def test_two_allocators_do_not_share_state() -> None:
# The set is per-instance; a class attribute here would hand the same
# workspace to two brokers' containers.
first = WorkspaceAllocator(1000, 2)
second = WorkspaceAllocator(1000, 2)
assert first.allocate() == 1000
assert second.allocate() == 1000
assert first.in_use() == second.in_use() == [1000]
+238
View File
@@ -0,0 +1,238 @@
"""Container plans: the exact argv lists, and the validation that guards them.
The argv lists are asserted whole rather than probed for substrings. These
commands are the only thing this module produces, nobody here runs them, and a
test that accepted "contains the output name" would pass on a command that
silently changed shape under a refactor.
"""
from __future__ import annotations
import pytest
from hhstreamd.containers import (
ContainerPlan,
app_id_for,
contains_output,
container_plan,
output_name,
quarantine_argv,
)
def test_create_is_the_four_commands_in_order() -> None:
plan = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa")
assert plan.create == [
["hyprctl", "output", "create", "headless", "hh-foot-aaaaaa"],
[
"hyprctl",
"keyword",
"workspace",
"1000, monitor:hh-foot-aaaaaa, default:true, persistent:true",
],
[
"hyprctl",
"keyword",
"windowrule",
"match:initial_class ^hh-foot-aaaaaa$, workspace 1000, monitor hh-foot-aaaaaa",
],
["hyprctl", "keyword", "monitor", "hh-foot-aaaaaa,1280x720,auto,1"],
]
def test_teardown_removes_the_output_and_nothing_else() -> None:
plan = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa")
assert plan.teardown == [["hyprctl", "output", "remove", "hh-foot-aaaaaa"]]
def test_plan_describes_what_it_built() -> None:
plan = container_plan("x1", 1007, 1920, 1080, "org.gnome.Nautilus")
assert isinstance(plan, ContainerPlan)
assert (plan.output, plan.workspace, plan.mode) == ("hh-x1", 1007, (1920, 1080))
def test_a_foreign_class_is_matched_as_given() -> None:
# The rule has to match what the toolkit reports, which is not always the
# id the launcher stamped.
plan = container_plan("x1", 1001, 800, 600, "org.gnome.Nautilus")
assert plan.create[2] == [
"hyprctl",
"keyword",
"windowrule",
"match:initial_class ^org.gnome.Nautilus$, workspace 1001, monitor hh-x1",
]
def test_identical_arguments_give_byte_identical_commands() -> None:
first = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa")
second = container_plan("foot-aaaaaa", 1000, 1280, 720, "hh-foot-aaaaaa")
assert first == second
assert first.create == second.create
assert first.teardown == second.teardown
def test_output_name_and_app_id_are_the_same_string() -> None:
assert output_name("foot-aaaaaa") == "hh-foot-aaaaaa"
assert app_id_for("foot-aaaaaa") == "hh-foot-aaaaaa"
@pytest.mark.parametrize(
"name",
[
"hh-foot-aaaaaa",
"hh-x",
"hh-1000",
],
)
def test_contains_output_claims_our_own_names(name: str) -> None:
assert contains_output(name) is True
@pytest.mark.parametrize(
"name",
[
"HEADLESS-1", # the compositor's own
"eDP-1",
"hh",
"hh-", # no session id: not something the broker ever created
"hh-Foot", # upper case is outside the minted alphabet
"hh-foot\n", # a trailing newline is not a name, it is two lines
"hh-foot aaaa",
" hh-foot",
"xhh-foot",
"",
],
)
def test_contains_output_refuses_everything_else(name: str) -> None:
# A scan removes what this says is ours, so a false positive deletes an
# output the broker did not create.
assert contains_output(name) is False
@pytest.mark.parametrize(
"bad",
["", "Foot", "foot_aaaa", "foot aaaa", "hh-foot;rm", "foot\n", "../x", "é"],
)
def test_a_session_id_outside_the_alphabet_is_refused(bad: str) -> None:
with pytest.raises(ValueError) as exc:
output_name(bad)
assert repr(bad) in str(exc.value)
assert "[a-z0-9-]" in str(exc.value)
with pytest.raises(ValueError) as app_exc:
app_id_for(bad)
assert repr(bad) in str(app_exc.value)
with pytest.raises(ValueError) as plan_exc:
container_plan(bad, 1000, 1280, 720, "hh-x")
assert repr(bad) in str(plan_exc.value)
@pytest.mark.parametrize("width,height", [(0, 720), (1280, 0), (-1, 720), (1280, -720)])
def test_a_non_positive_mode_is_refused(width: int, height: int) -> None:
with pytest.raises(ValueError) as exc:
container_plan("x1", 1000, width, height, "hh-x1")
message = str(exc.value)
offender = width if width < 1 else height
assert repr(offender) in message
assert ("width" in message) or ("height" in message)
assert ">= 1" in message
def test_a_fractional_mode_is_refused() -> None:
# 1280.5 would reach the compositor as "1280.5x720"; a mode is pixels.
with pytest.raises(ValueError) as exc:
container_plan("x1", 1000, 1280.5, 720, "hh-x1") # type: ignore[arg-type]
assert "width" in str(exc.value)
assert "is not an int" in str(exc.value)
def test_a_boolean_workspace_is_refused() -> None:
# True is an int in Python and would quietly become workspace 1.
with pytest.raises(ValueError) as exc:
container_plan("x1", True, 1280, 720, "hh-x1") # type: ignore[arg-type]
assert "workspace" in str(exc.value)
assert "is not an int" in str(exc.value)
@pytest.mark.parametrize("workspace", [0, -1])
def test_a_non_positive_workspace_is_refused(workspace: int) -> None:
with pytest.raises(ValueError) as exc:
container_plan("x1", workspace, 1280, 720, "hh-x1")
assert "workspace" in str(exc.value)
assert repr(workspace) in str(exc.value)
def test_an_empty_app_id_is_refused() -> None:
with pytest.raises(ValueError) as exc:
container_plan("x1", 1000, 1280, 720, "")
assert "app id" in str(exc.value)
assert "''" in str(exc.value)
@pytest.mark.parametrize(
"bad",
[
"hh-x1, workspace 1001", # a forged second rule field
"hh-x1$, monitor eDP-1",
"hh x1",
"hh-x1\nkeyword monitor eDP-1,disable",
"^hh-x1$",
"hh-x1'",
],
)
def test_an_app_id_that_could_forge_a_rule_field_is_refused(bad: str) -> None:
with pytest.raises(ValueError) as exc:
container_plan("x1", 1000, 1280, 720, bad)
assert repr(bad) in str(exc.value)
assert "[A-Za-z0-9._+-]" in str(exc.value)
def test_quarantine_argv_is_the_catch_all_keyword() -> None:
argv = quarantine_argv("special:quarantine")
# Bare argv lists, not a ContainerPlan: a quarantine rule has no output,
# no numbered workspace and no mode to put in one (CONTRACT v2 §3.2).
assert argv == [
[
"hyprctl",
"keyword",
"windowrule",
"match:initial_class .*, workspace special:quarantine",
]
]
def test_the_quarantine_rule_matches_what_a_container_rule_does_not() -> None:
"""The backstop and a container rule must not be able to collide.
The catch-all is what every unplaced window hits, so it has to be the same
shape as a per-session rule with a wider match — otherwise the two are
evaluated differently and the ordering the caller gets right stops
mattering.
"""
(backstop,) = quarantine_argv("special:quarantine")
container = container_plan("x1", 1000, 1280, 720, "hh-x1").create[2]
assert backstop[:3] == container[:3] == ["hyprctl", "keyword", "windowrule"]
assert backstop[3].startswith("match:initial_class .*,")
assert container[3].startswith("match:initial_class ^hh-x1$,")
@pytest.mark.parametrize("disabled", ["", " ", "\n"])
def test_quarantine_argv_is_none_when_disabled(disabled: str) -> None:
assert quarantine_argv(disabled) is None
@pytest.mark.parametrize("bad", ["special:quarantine, monitor eDP-1", "a b", "q\n1", "q'"])
def test_a_quarantine_workspace_that_could_forge_a_field_is_refused(bad: str) -> None:
with pytest.raises(ValueError) as exc:
quarantine_argv(bad)
assert "quarantine_workspace" in str(exc.value)
assert repr(bad.strip()) in str(exc.value)
+2 -2
View File
@@ -42,7 +42,7 @@ ls -l /dev/dri 2>&1 || echo "[no /dev/dri: this machine has no DRM device at all
run cat /proc/fb
say "socket and runtime directories"
ls -la /run/hyprland-headless-stream 2>&1 || echo "[no /run/hyprland-headless-stream]"
ls -la /run/hypr-stream 2>&1 || echo "[no /run/hypr-stream]"
ls -la /run/user 2>&1 || echo "[no /run/user]"
for d in /run/user/*; do
[ -d "$d" ] && ls -la "$d" 2>&1
@@ -56,7 +56,7 @@ say "wayland socket vs WAYLAND_DISPLAY"
systemctl show -p Environment --value "$SERVICE_UNIT" 2>&1 \
| tr ' ' '\n' | grep -E '^(WAYLAND_DISPLAY|XDG_RUNTIME_DIR)=' \
|| echo "[no WAYLAND_DISPLAY/XDG_RUNTIME_DIR in the unit environment]"
for d in /run/hyprland-headless-stream /run/user/*; do
for d in /run/hypr-stream /run/user/*; do
[ -d "$d" ] || continue
found_sock=$(find "$d" -xdev -maxdepth 1 -name 'wayland-*' ! -name '*.lock' 2>/dev/null)
if [ -n "$found_sock" ]; then
+264
View File
@@ -0,0 +1,264 @@
"""A real compositor-shaped socket, because the sockets are what break.
Nothing here mocks :mod:`socket`. Each helper binds an actual ``AF_UNIX``
listener in a temporary directory laid out the way Hyprland lays one out
(``<runtime>/hypr/<signature>/.socket.sock``) and answers canned bytes, so the
tests drive the client's real connect, half-close, read-to-EOF and timeout
paths. A mocked socket would pass while the thing that actually fails in
production — a path that is gone, a peer that closes early, a reply that is
plain text where JSON was promised — went untested.
``AF_UNIX`` caps a path at 108 bytes, so the sockets live in a shallow
``mkdtemp`` rather than under ``tmp_path``, whose name encodes the test's.
"""
from __future__ import annotations
import shutil
import socket
import tempfile
import threading
from pathlib import Path
import pytest
#: Linux's sun_path is 108 bytes including the NUL.
SUN_PATH_MAX = 107
#: Returned by a handler that should keep the connection open and say nothing,
#: which is how a wedged compositor behaves and the only way to reach the
#: client's read timeout.
HANG = object()
#: Shapes taken from Hyprland's own ``-j`` output. Trimmed to the keys the
#: client reads, plus a few it must ignore.
MONITORS_JSON = """
[{"id": 0, "name": "HEADLESS-2", "description": "headless", "make": "", "model": "",
"x": 0, "y": 0, "width": 1280, "height": 720, "refreshRate": 60.0, "scale": 1.0,
"transform": 0, "focused": true, "activeWorkspace": {"id": 1000, "name": "1000"},
"specialWorkspace": {"id": 0, "name": ""}, "dpmsStatus": true},
{"id": 1, "name": "HEADLESS-3", "x": 1280, "y": 0, "width": 800, "height": 600,
"scale": 1.5, "focused": false}]
"""
WORKSPACES_JSON = """
[{"id": 1000, "name": "1000", "monitor": "HEADLESS-2", "monitorID": 0, "windows": 1,
"hasfullscreen": false, "lastwindow": "0x5d3d1c0", "lastwindowtitle": "foot"},
{"id": -99, "name": "special:quarantine", "monitor": "HEADLESS-2", "windows": 0}]
"""
CLIENTS_JSON = """
[{"address": "0x5d3d1c0", "mapped": true, "hidden": false, "at": [0, 0],
"size": [1280, 720], "workspace": {"id": 1000, "name": "1000"}, "floating": false,
"monitor": 0, "class": "foot", "initialClass": "hh-foot-v7r4li",
"title": "hermes: ~, build, and notes", "initialTitle": "foot", "pid": 4242,
"xwayland": false, "pinned": false, "fullscreen": 0},
{"address": "0x5d4aa10", "mapped": false, "hidden": true, "class": "chromium",
"initialClass": "", "title": "", "pid": 0, "monitor": null}]
"""
CURSORPOS_JSON = '{"x": 640, "y": 360}'
VERSION_TEXT = (
"Hyprland 0.41.2 built from branch at commit 0000000 (). Date: 2026-01-01\n"
"Tag: v0.41.2, commits: 5000\n\nflags: (if any)\ndebug\n"
)
#: What a well-behaved compositor answers, keyed by the bare command.
GOOD_REPLIES = {
"monitors": MONITORS_JSON,
"workspaces": WORKSPACES_JSON,
"clients": CLIENTS_JSON,
"cursorpos": CURSORPOS_JSON,
"version": VERSION_TEXT,
}
def check_path(path: Path) -> None:
if len(str(path).encode()) > SUN_PATH_MAX:
pytest.skip(f"socket path too long for AF_UNIX ({len(str(path))} bytes): {path}")
class RequestServer:
"""One listening request socket, answering through a handler.
The handler is called with ``(flags, command)`` split the way Hyprland
splits them — everything before the first ``/`` is flags — and returns the
reply, ``None`` to close without answering, or :data:`HANG`.
"""
def __init__(self, path: Path, handler) -> None:
check_path(path)
self.path = path
self.handler = handler
self.requests: list[tuple[str, str]] = []
self._stop = threading.Event()
self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._sock.bind(str(path))
self._sock.listen(8)
self._sock.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():
conn = self._accept()
if conn is None:
continue
try:
self._handle(conn)
finally:
conn.close()
def _accept(self):
"""``None`` on a poll timeout, so :meth:`stop` is not waited out.
Closing a listening socket does not reliably wake a thread blocked in
``accept``, which would make every test pay the join timeout.
"""
try:
conn, _ = self._sock.accept()
except (TimeoutError, socket.timeout):
return None
except OSError:
self._stop.set()
return None
return conn
def _handle(self, conn: socket.socket) -> None:
# The client half-closes after writing, so the request ends at EOF.
conn.settimeout(5.0)
received = b""
while True:
try:
chunk = conn.recv(4096)
except OSError:
return
if not chunk:
break
received += chunk
text = received.decode("utf-8", errors="replace")
flags, separator, command = text.partition("/")
if not separator:
flags, command = "", text
self.requests.append((flags, command))
reply = self.handler(flags, command)
if reply is HANG:
self._stop.wait(5.0)
return
if reply is None:
return
data = reply.encode() if isinstance(reply, str) else reply
try:
conn.sendall(data)
except OSError:
pass
def stop(self) -> None:
self._stop.set()
self._sock.close()
self._thread.join(timeout=5.0)
class EventServer:
"""One listening event socket that writes chunks, then closes or holds.
Chunks are written as given — not line by line — so a test can split an
event across two writes and prove the client reassembles it.
"""
def __init__(self, path: Path, chunks, close_after: bool = True) -> None:
check_path(path)
self.path = path
self.chunks = [c.encode() if isinstance(c, str) else c for c in chunks]
self.close_after = close_after
self.connections = 0
self._stop = threading.Event()
self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._sock.bind(str(path))
self._sock.listen(8)
self._sock.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._sock.accept()
except (TimeoutError, socket.timeout):
continue
except OSError:
return
self.connections += 1
try:
for chunk in self.chunks:
conn.sendall(chunk)
# Let the client see this write on its own, so a chunk
# boundary inside a line is a real boundary.
self._stop.wait(0.01)
if not self.close_after:
self._stop.wait(5.0)
except OSError:
pass
finally:
conn.close()
def stop(self) -> None:
self._stop.set()
self._sock.close()
self._thread.join(timeout=5.0)
@pytest.fixture
def runtime_dir():
"""A shallow temporary directory standing in for ``/run/hypr-stream``."""
path = Path(tempfile.mkdtemp(prefix="hhipc"))
try:
yield path
finally:
shutil.rmtree(path, ignore_errors=True)
@pytest.fixture
def instance(runtime_dir):
"""``<runtime_dir>/hypr/<signature>`` for one instance, created."""
directory = runtime_dir / "hypr" / "a1b2c3_1700000000"
directory.mkdir(parents=True)
return directory
@pytest.fixture
def servers(instance):
"""Factory for request/event servers on one instance, stopped at teardown."""
started: list = []
def start(handler=None, event_chunks=None, close_after=True):
request = None
events = None
if handler is not None:
request = RequestServer(instance / ".socket.sock", handler)
started.append(request)
if event_chunks is not None:
events = EventServer(instance / ".socket2.sock", event_chunks, close_after)
started.append(events)
return request, events
try:
yield start
finally:
for server in started:
server.stop()
@pytest.fixture
def good_handler():
"""Answers every wrapped command the way a live compositor does."""
def handler(flags, command):
return GOOD_REPLIES.get(command.strip(), "unknown request")
return handler
+131
View File
@@ -0,0 +1,131 @@
"""Finding the instance, and refusing to pick one when there is a choice.
Two instances and no signature is the dangerous case: a broker that guessed
would aim its queries — and later its pointer — at someone else's desktop.
"""
from __future__ import annotations
import socket
import pytest
from hhstreamd.ipc import SIGNATURE_ENV, CompositorUnavailable, HyprlandIPC
def bind(path):
"""A bound, listening socket at ``path``, so discovery sees a real one."""
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(str(path))
sock.listen(1)
return sock
def test_single_instance_is_discovered(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
sock = bind(instance / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir)
finally:
sock.close()
assert ipc.request_socket == instance / ".socket.sock"
assert ipc.event_socket == instance / ".socket2.sock"
def test_no_instance_directory_at_all(runtime_dir, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
with pytest.raises(CompositorUnavailable) as caught:
HyprlandIPC.discover(runtime_dir)
assert str(runtime_dir / "hypr") in str(caught.value)
def test_zero_instances_under_hypr(runtime_dir, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
(runtime_dir / "hypr").mkdir()
with pytest.raises(CompositorUnavailable, match="no instance"):
HyprlandIPC.discover(runtime_dir)
def test_two_instances_without_a_signature_refuses(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
other = runtime_dir / "hypr" / "deadbee_1700000001"
other.mkdir()
bind(instance / ".socket.sock").close()
with pytest.raises(CompositorUnavailable) as caught:
HyprlandIPC.discover(runtime_dir)
message = str(caught.value)
assert "2 instances" in message
assert instance.name in message and other.name in message
assert SIGNATURE_ENV in message
def test_two_instances_with_an_explicit_signature(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
other = runtime_dir / "hypr" / "deadbee_1700000001"
other.mkdir()
sock = bind(other / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir, signature=other.name)
finally:
sock.close()
assert ipc.request_socket == other / ".socket.sock"
def test_signature_from_the_environment(runtime_dir, instance, monkeypatch):
other = runtime_dir / "hypr" / "deadbee_1700000001"
other.mkdir()
monkeypatch.setenv(SIGNATURE_ENV, other.name)
sock = bind(other / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir)
finally:
sock.close()
assert ipc.request_socket == other / ".socket.sock"
def test_explicit_signature_beats_the_environment(runtime_dir, instance, monkeypatch):
monkeypatch.setenv(SIGNATURE_ENV, "not_this_one")
sock = bind(instance / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir, signature=instance.name)
finally:
sock.close()
assert ipc.request_socket == instance / ".socket.sock"
def test_signature_naming_a_missing_instance(runtime_dir, instance, monkeypatch):
monkeypatch.setenv(SIGNATURE_ENV, "gone_1700000002")
with pytest.raises(CompositorUnavailable, match="request socket"):
HyprlandIPC.discover(runtime_dir)
def test_instance_without_a_request_socket(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
with pytest.raises(CompositorUnavailable) as caught:
HyprlandIPC.discover(runtime_dir)
assert ".socket.sock" in str(caught.value)
def test_a_regular_file_is_not_a_socket(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
(instance / ".socket.sock").write_text("not a socket")
with pytest.raises(CompositorUnavailable, match="is not a socket"):
HyprlandIPC.discover(runtime_dir)
def test_a_signature_cannot_be_a_path(runtime_dir, instance):
with pytest.raises(CompositorUnavailable, match="not a directory name"):
HyprlandIPC.discover(runtime_dir, signature="../../elsewhere")
def test_an_empty_environment_signature_falls_through(runtime_dir, instance, monkeypatch):
"""An exported-but-empty variable is no signature, not a signature of ""."""
monkeypatch.setenv(SIGNATURE_ENV, "")
sock = bind(instance / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir)
finally:
sock.close()
assert ipc.request_socket == instance / ".socket.sock"
+197
View File
@@ -0,0 +1,197 @@
"""Event parsing, and a stream that must fail loudly when it stops.
The payload cases here are the ones that bite: a title full of commas (the
whole reason the last field absorbs the rest of the line), an event with no
payload at all, an event this module has never heard of, and a line delivered
in two pieces by the kernel.
"""
from __future__ import annotations
import threading
import time
import pytest
from hhstreamd.ipc import CompositorUnavailable, HyprlandIPC, parse_event
def test_openwindow_names_its_fields():
event = parse_event("openwindow>>0x5d3d1c0,1000,foot,hermes: ~")
assert event.name == "openwindow"
assert event.data["address"] == "0x5d3d1c0"
assert event.data["workspace"] == "1000"
assert event.data["class"] == "foot"
assert event.data["title"] == "hermes: ~"
assert event.data["args"] == ["0x5d3d1c0", "1000", "foot", "hermes: ~"]
assert event.data["raw"] == "0x5d3d1c0,1000,foot,hermes: ~"
def test_a_title_keeps_its_commas():
"""A naive split(",") loses the end of the title; this is that regression."""
event = parse_event("openwindow>>0x1,1000,foot,hermes: ~, build, and notes")
assert event.data["title"] == "hermes: ~, build, and notes"
assert len(event.data["args"]) == 4
def test_windowtitle_v2_absorbs_commas_too():
event = parse_event("windowtitlev2>>0x1,a,b,c")
assert event.data == {
"raw": "0x1,a,b,c",
"args": ["0x1", "a,b,c"],
"address": "0x1",
"title": "a,b,c",
}
def test_an_empty_payload_names_nothing():
"""``configreloaded>>`` carried no values; "" is not a value."""
event = parse_event("configreloaded>>")
assert event.name == "configreloaded"
assert event.data == {"raw": "", "args": []}
def test_a_single_field_event():
event = parse_event("monitorremoved>>HEADLESS-3")
assert event.data["name"] == "HEADLESS-3"
assert event.data["args"] == ["HEADLESS-3"]
def test_a_short_payload_names_only_what_arrived():
"""An older Hyprland sending fewer fields must not invent the rest."""
event = parse_event("openwindow>>0x1,1000")
assert event.data["address"] == "0x1"
assert event.data["workspace"] == "1000"
assert "class" not in event.data
assert "title" not in event.data
def test_an_unknown_event_is_still_usable():
event = parse_event("somethingnew>>a,b,c")
assert event.name == "somethingnew"
assert event.data == {"raw": "a,b,c", "args": ["a", "b", "c"]}
def test_trailing_newline_is_not_part_of_the_payload():
assert parse_event("workspace>>1000\n").data["name"] == "1000"
assert parse_event("workspace>>1000\r\n").data["name"] == "1000"
@pytest.mark.parametrize("line", ["workspace", "", " ", ">>1000", "workspace>1000"])
def test_a_line_with_no_separator_is_malformed(line):
with pytest.raises(CompositorUnavailable, match="name>>payload"):
parse_event(line)
@pytest.fixture
def ipc(instance):
client = HyprlandIPC(instance / ".socket.sock", instance / ".socket2.sock")
yield client
client.close()
def test_the_stream_yields_events_then_raises_at_eof(servers, ipc):
chunks = [
"openwindow>>0x1,1000,foot,hermes: ~, build\n",
# One line split across two writes: the client must reassemble it
# rather than parse half of it.
"closewin",
"dow>>0x1\nworkspacev2>>1000,1000\n",
]
servers(event_chunks=chunks)
stream = ipc.events()
first = next(stream)
assert first.name == "openwindow"
assert first.data["title"] == "hermes: ~, build"
assert next(stream).name == "closewindow"
third = next(stream)
assert (third.data["id"], third.data["name"]) == ("1000", "1000")
# The compositor closed. An iterator that merely stopped would be
# indistinguishable from an idle desktop.
with pytest.raises(CompositorUnavailable, match="event stream ended"):
next(stream)
def test_an_unterminated_tail_is_reported(servers, ipc):
servers(event_chunks=["openwindow>>0x1,1000,foot,t\nhalf-an-ev"])
stream = ipc.events()
assert next(stream).name == "openwindow"
with pytest.raises(CompositorUnavailable, match="unterminated"):
next(stream)
def test_a_malformed_line_in_the_stream(servers, ipc):
servers(event_chunks=["this is not an event\n"])
stream = ipc.events()
with pytest.raises(CompositorUnavailable, match="name>>payload"):
next(stream)
def test_a_missing_event_socket(instance, ipc):
with pytest.raises(CompositorUnavailable) as caught:
ipc.events()
assert ".socket2.sock" in str(caught.value)
def test_no_event_socket_configured(instance):
ipc = HyprlandIPC(instance / ".socket.sock")
with pytest.raises(CompositorUnavailable, match="no event socket"):
ipc.events()
def test_the_connection_is_made_by_events_not_by_the_first_next(servers, ipc):
"""So the caller that asked for the stream is the one told it failed."""
_, events = servers(event_chunks=["workspace>>1000\n"], close_after=False)
stream = ipc.events()
# ``connect`` returns as soon as the listen backlog takes it, so the
# server's own accept lags by a scheduling quantum; the claim is that the
# connection exists before anything iterates, not that it is instantaneous.
deadline = time.monotonic() + 5.0
while events.connections == 0 and time.monotonic() < deadline:
time.sleep(0.01)
assert events.connections == 1
assert next(stream).name == "workspace"
def test_close_unblocks_a_waiting_reader(servers, ipc):
"""A blocked reader must end when the broker shuts the client down.
``close()`` shuts the socket down rather than only closing it, because a
bare close does not wake a thread already sitting in ``recv``.
"""
servers(event_chunks=["workspace>>1000\n"], close_after=False)
stream = ipc.events()
assert next(stream).name == "workspace"
outcome = []
def read_until_it_fails():
try:
next(stream)
except BaseException as exc: # noqa: BLE001 - recorded, then asserted
outcome.append(exc)
reader = threading.Thread(target=read_until_it_fails, daemon=True)
reader.start()
# The reader is blocked in recv on an open, silent socket.
reader.join(timeout=0.2)
assert reader.is_alive()
ipc.close()
reader.join(timeout=5.0)
assert not reader.is_alive()
assert isinstance(outcome[0], CompositorUnavailable)
def test_close_is_idempotent(servers, ipc):
servers(event_chunks=["workspace>>1000\n"], close_after=False)
ipc.events()
ipc.close()
ipc.close()
+261
View File
@@ -0,0 +1,261 @@
"""The request socket, against a real listener.
Every test here connects over ``AF_UNIX`` to a socket the fixture bound, so the
failures that matter — a path that is gone, a peer that refuses, a peer that
closes mid-reply, a peer that never answers — are produced rather than
simulated.
"""
from __future__ import annotations
import socket
import pytest
from hhstreamd.ipc import CompositorUnavailable, CursorPos, HyprlandIPC
from conftest import HANG
@pytest.fixture
def ipc(instance):
client = HyprlandIPC(instance / ".socket.sock", instance / ".socket2.sock")
yield client
client.close()
def test_version_is_the_banner_verbatim(servers, good_handler, ipc):
request, _ = servers(good_handler)
assert ipc.version().startswith("Hyprland 0.41.2 built from branch")
assert "Tag: v0.41.2" in ipc.version()
# Text, not JSON, and the command carries a leading "/" so an argument
# containing a slash could never be read as output flags.
assert request.requests[0] == ("", "version")
def test_monitors(servers, good_handler, ipc):
request, _ = servers(good_handler)
monitors = ipc.monitors()
assert [m.name for m in monitors] == ["HEADLESS-2", "HEADLESS-3"]
# The id is what ties a client to the output it is on: `clients -j` reports
# a client's monitor as this same number, while workspaces report a name.
assert [m.id for m in monitors] == [0, 1]
first = monitors[0]
assert (first.x, first.y, first.width, first.height) == (0, 0, 1280, 720)
assert first.scale == 1.0
assert first.active_workspace_id == 1000
# The second monitor carries no activeWorkspace at all: a defined None.
assert monitors[1].active_workspace_id is None
assert monitors[1].scale == 1.5
assert request.requests == [("j", "monitors")]
def test_monitors_without_an_id_is_minus_one(servers, ipc):
"""A reply that omits the id must not join to a real output.
`Monitor.id` is the join key for a client's output, so a missing id has to be
a value no compositor can use -- `-1` -- rather than a plausible-looking `0`
that would silently bind every such client to the first output.
"""
def handler(flags, command):
return ('[{"name": "HEADLESS-9", "x": 0, "y": 0, "width": 100, '
'"height": 50, "scale": 1.0}]')
servers(handler)
monitors = ipc.monitors()
assert [m.id for m in monitors] == [-1]
assert monitors[0].name == "HEADLESS-9"
def test_workspaces(servers, good_handler, ipc):
servers(good_handler)
workspaces = ipc.workspaces()
assert [w.id for w in workspaces] == [1000, -99]
assert workspaces[0].monitor == "HEADLESS-2"
assert workspaces[0].windows == 1
assert workspaces[0].is_special is False
# No "special" key in this reply: the negative id and the name prefix are
# what every Hyprland has agreed on.
assert workspaces[1].is_special is True
def test_clients(servers, good_handler, ipc):
request, _ = servers(good_handler)
clients = ipc.clients()
assert len(clients) == 2
foot, chromium = clients
assert foot.address == "0x5d3d1c0"
assert foot.pid == 4242
assert foot.workspace_id == 1000
assert foot.class_ == "foot"
assert foot.initial_class == "hh-foot-v7r4li"
# A title with commas in it survives whole; the broker shows this to a user.
assert foot.title == "hermes: ~, build, and notes"
assert foot.stable_id == "hh-foot-v7r4li:4242"
assert foot.visible is True
# clients -j reports the monitor as an index, not a name; the field is text
# so that None keeps its one meaning of "the reply said nothing".
assert foot.monitor == "0"
assert chromium.visible is False
assert chromium.monitor is None
assert chromium.workspace_id is None
assert chromium.stable_id == "0x5d4aa10"
assert request.requests == [("j", "clients")]
def test_cursorpos(servers, good_handler, ipc):
servers(good_handler)
assert ipc.cursorpos() == CursorPos(x=640, y=360)
def test_query_passes_a_command_through_untouched(servers, ipc):
seen = []
def handler(flags, command):
seen.append((flags, command))
return "ok"
servers(handler)
assert ipc.query("dispatch exec /usr/bin/true") == "ok"
# The slash in the argument must not be read as a flag separator.
assert seen == [("", "dispatch exec /usr/bin/true")]
def test_query_keeps_an_explicit_flag_prefix(servers, ipc):
seen = []
def handler(flags, command):
seen.append((flags, command))
return "[]"
servers(handler)
assert ipc.query("j/devices") == "[]"
assert seen == [("j", "devices")]
def test_an_empty_request_is_refused_before_connecting(ipc):
with pytest.raises(CompositorUnavailable, match="empty request"):
ipc.query(" ")
@pytest.mark.parametrize("method", ["monitors", "workspaces", "clients", "cursorpos"])
def test_plain_text_where_json_was_promised(servers, ipc, method):
"""What Hyprland answers for a command it does not know."""
servers(lambda flags, command: "unknown request")
with pytest.raises(CompositorUnavailable, match="not JSON"):
getattr(ipc, method)()
def test_a_json_object_where_a_list_belongs(servers, ipc):
servers(lambda flags, command: '{"monitors": []}')
with pytest.raises(CompositorUnavailable, match="expected a JSON list"):
ipc.monitors()
def test_a_list_of_scalars(servers, ipc):
servers(lambda flags, command: '["HEADLESS-2"]')
with pytest.raises(CompositorUnavailable, match="expected objects"):
ipc.monitors()
def test_a_client_without_an_address_is_malformed(servers, ipc):
"""The one key whose absence makes the record meaningless."""
servers(lambda flags, command: '[{"class": "foot", "pid": 1}]')
with pytest.raises(CompositorUnavailable, match="no address"):
ipc.clients()
def test_a_monitor_without_a_name_is_malformed(servers, ipc):
servers(lambda flags, command: '[{"width": 1280}]')
with pytest.raises(CompositorUnavailable, match="no name"):
ipc.monitors()
def test_a_workspace_without_an_id_is_malformed(servers, ipc):
servers(lambda flags, command: '[{"name": "1000"}]')
with pytest.raises(CompositorUnavailable, match="no id"):
ipc.workspaces()
def test_missing_keys_degrade_rather_than_raise_keyerror(servers, ipc):
"""A reply from a Hyprland that reports less than this one expects."""
servers(lambda flags, command: '[{"address": "0x1"}]')
(client,) = ipc.clients()
assert client.pid == -1
assert client.workspace_id is None
assert client.monitor is None
assert (client.class_, client.initial_class, client.title) == ("", "", "")
assert client.stable_id == "0x1"
# Nothing said it was unmapped, so it is not reported as gone.
assert client.visible is True
def test_cursorpos_without_coordinates(servers, ipc):
servers(lambda flags, command: '{"ok": true}')
with pytest.raises(CompositorUnavailable, match="x and y"):
ipc.cursorpos()
def test_cursorpos_with_non_numeric_coordinates(servers, ipc):
servers(lambda flags, command: '{"x": "left", "y": null}')
with pytest.raises(CompositorUnavailable, match="not numbers"):
ipc.cursorpos()
def test_connection_closed_mid_reply(servers, ipc):
"""The compositor dies while writing: a truncated reply, never a guess."""
servers(lambda flags, command: '[{"address": "0x5d3d1c0", "pid": 4242, "cla')
with pytest.raises(CompositorUnavailable, match="not JSON"):
ipc.clients()
def test_connection_closed_with_no_reply_at_all(servers, ipc):
servers(lambda flags, command: None)
with pytest.raises(CompositorUnavailable, match="empty reply"):
ipc.workspaces()
with pytest.raises(CompositorUnavailable, match="empty reply"):
ipc.version()
def test_missing_socket(instance):
ipc = HyprlandIPC(instance / ".socket.sock")
with pytest.raises(CompositorUnavailable) as caught:
ipc.clients()
assert str(instance / ".socket.sock") in str(caught.value)
def test_nothing_listening(instance, ipc):
"""A socket left behind by a compositor that is gone: ECONNREFUSED."""
stale = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
stale.bind(str(instance / ".socket.sock"))
try:
with pytest.raises(CompositorUnavailable, match="request socket"):
ipc.monitors()
finally:
stale.close()
def test_a_compositor_that_never_answers(servers, ipc):
"""Accepted, then silence: the read timeout, exercised for real."""
servers(lambda flags, command: HANG)
ipc.request_timeout_s = 0.3
with pytest.raises(CompositorUnavailable, match="did not answer"):
ipc.clients()
def test_each_request_is_its_own_connection(servers, good_handler, ipc):
"""What hyprctl does, and what the compositor expects: no session state."""
request, _ = servers(good_handler)
ipc.monitors()
ipc.clients()
ipc.clients()
assert request.requests == [("j", "monitors"), ("j", "clients"), ("j", "clients")]
File renamed without changes.
+3
View File
@@ -23,7 +23,10 @@ from pathlib import Path
import pytest
# `tests/` for the shared helpers, and this directory for `fakes`, which the
# unit tests and the integration tests both import.
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(Path(__file__).resolve().parent))
#: Linux's sun_path is 108 bytes including the NUL.
SUN_PATH_MAX = 107
+432
View File
@@ -0,0 +1,432 @@
"""A compositor and a pointer driver that are real sockets and nothing else.
Both fakes bind an actual ``AF_UNIX`` listener and speak the real wire format.
Nothing here patches :mod:`socket`, :mod:`subprocess` or any method on the code
under test: a mock would pass while the things that actually break — a half-
closed request, a reply that is prose where JSON was promised, a driver that
went away mid-gesture — went untested. This is the same choice ``tests/ipc``
made, for the same reason.
What they prove and what they do not:
* :class:`FakeCompositor` proves the **wiring** — that the broker sends the
plan's commands in the plan's order, parses what comes back and writes the
compositor's answer rather than its own intention into the record. It does
not prove that Hyprland agrees: it answers ``ok`` because it was asked
politely, and the real compositor's behaviour for ``output create headless``
is marked unverified in the plan. Every test here is a test of this broker.
* :class:`FakeDriver` runs the **real dispatcher** from
:mod:`hhstream_pointer.ops`, behind the **real handler wrapper** from
:mod:`hhstream_pointer.__main__` and the **real server** from
:mod:`hhstream_pointer.server`, with only the Wayland sink replaced by a
recorder. So the protocol, the framing, the driver's own button bookkeeping
and — importantly — which backend failures become ``ok: false`` and which
kill the connection are the shipped ones; only the compositor is absent.
"""
from __future__ import annotations
import json
import socket
import threading
from pathlib import Path
from typing import Any
import pytest
from hhstream_pointer.__main__ import _handler
from hhstream_pointer.ops import Dispatcher
from hhstream_pointer.server import PointerServer
#: Linux's sun_path is 108 bytes including the NUL.
SUN_PATH_MAX = 107
#: The pid the fake gives a window it conjures for a window rule. Fixed, and
#: not the session's: the compositor is the authority on what is on screen, and
#: a fake that echoed the broker's own pid back could not catch a broker that
#: wrote its intention into the record instead of the read-back.
WINDOW_PID = 424242
def check_path(path: Path) -> None:
if len(str(path).encode()) > SUN_PATH_MAX:
pytest.skip(f"socket path too long for AF_UNIX ({len(str(path))} bytes): {path}")
class FakeCompositor:
"""A Hyprland request socket with state: outputs, workspaces and windows.
Laid out the way Hyprland lays one out — ``<runtime>/hypr/<signature>/
.socket.sock`` — so the broker's own discovery finds it, and answering
``j/monitors``, ``j/workspaces``, ``j/clients`` with JSON of the shape
``-j`` produces.
It is stateful because the interesting assertions are about state: an
``output create`` has to show up in the next ``monitors``, an ``output
remove`` has to make it and its windows disappear, and an orphan scan is
only meaningful against a compositor that still has the orphan.
"""
def __init__(self, runtime_dir: Path, signature: str = "fake_1700000000") -> None:
self.runtime_dir = Path(runtime_dir)
self.signature = signature
self.directory = self.runtime_dir / "hypr" / signature
self.directory.mkdir(parents=True, exist_ok=True)
self.socket_path = self.directory / ".socket.sock"
check_path(self.socket_path)
#: Commands received, in order, exactly as they arrived on the wire.
self.commands: list[str] = []
#: ``initial_class`` -> ``(workspace, monitor)`` from the window rules.
self.rules: dict[str, tuple[int, str]] = {}
#: Commands to answer with prose instead of ``ok`` (a refusal).
self.refuse: set[str] = set()
#: When true, installing an anchored window rule also conjures the
#: window it describes — which is what a compositor with a cooperating
#: application does, and what the read-back path needs to have happen.
self.auto_window = True
self._lock = threading.Lock()
self._monitors: list[dict[str, Any]] = [
{
"id": 0,
"name": "HEADLESS-1",
"x": 0,
"y": 0,
"width": 1920,
"height": 1080,
"scale": 1.0,
"activeWorkspace": {"id": 1, "name": "1"},
}
]
self._workspaces: list[dict[str, Any]] = [
{"id": 1, "name": "1", "monitor": "HEADLESS-1", "windows": 0}
]
self._clients: list[dict[str, Any]] = []
self._next_address = 0x1000
self._stop = threading.Event()
self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._sock.bind(str(self.socket_path))
self._sock.listen(8)
self._sock.settimeout(0.05)
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
# -- inspection, for the tests ---------------------------------------
def outputs(self) -> list[str]:
with self._lock:
return [m["name"] for m in self._monitors]
def workspaces_on(self, output: str) -> list[int]:
with self._lock:
return [w["id"] for w in self._workspaces if w["monitor"] == output]
def windows(self) -> list[str]:
with self._lock:
return [c["initialClass"] for c in self._clients]
def add_output(self, name: str) -> None:
"""Create an output behind the broker's back — an orphan from a crash."""
with self._lock:
self._create_output(name)
def add_window(
self, initial_class: str, workspace: int, monitor: str, *, pid: int = WINDOW_PID
) -> str:
with self._lock:
return self._create_window(initial_class, workspace, monitor, pid)
def focus(self, output: str, workspace: int) -> None:
"""Make ``workspace`` the active one on ``output`` (the foreground join)."""
with self._lock:
for monitor in self._monitors:
if monitor["name"] == output:
monitor["activeWorkspace"] = {"id": workspace, "name": str(workspace)}
def stop(self) -> None:
self._stop.set()
self._sock.close()
self._thread.join(timeout=5.0)
# -- the socket -------------------------------------------------------
def _serve(self) -> None:
while not self._stop.is_set():
try:
conn, _ = self._sock.accept()
except (TimeoutError, socket.timeout):
continue
except OSError:
return
try:
self._handle(conn)
finally:
conn.close()
def _handle(self, conn: socket.socket) -> None:
# The client half-closes after writing, so the request ends at EOF.
conn.settimeout(5.0)
received = b""
while True:
try:
chunk = conn.recv(4096)
except OSError:
return
if not chunk:
break
received += chunk
text = received.decode("utf-8", errors="replace")
flags, separator, command = text.partition("/")
if not separator:
flags, command = "", text
command = command.strip()
with self._lock:
self.commands.append(command)
reply = self._reply(command)
try:
conn.sendall(reply.encode())
except OSError:
pass
# -- the command set --------------------------------------------------
def _reply(self, command: str) -> str:
if command in self.refuse:
return "Invalid command"
if command == "version":
return "Hyprland 0.56.2 built from branch at commit 0000000\nTag: v0.56.2\n"
if command == "monitors":
return json.dumps(self._monitors)
if command == "workspaces":
return json.dumps(self._workspaces)
if command == "clients":
return json.dumps(self._clients)
if command == "cursorpos":
return json.dumps({"x": 0, "y": 0})
words = command.split()
if words[:3] == ["output", "create", "headless"] and len(words) == 4:
self._create_output(words[3])
return "ok"
if words[:2] == ["output", "remove"] and len(words) == 3:
return "ok" if self._remove_output(words[2]) else f"no such output {words[2]}"
if words[:1] == ["keyword"]:
return self._keyword(command[len("keyword") :].strip())
return f"unknown request {command!r}"
def _keyword(self, rest: str) -> str:
name, _, body = rest.partition(" ")
if name == "workspace":
return self._keyword_workspace(body)
if name == "windowrule":
return self._keyword_windowrule(body)
if name == "monitor":
return self._keyword_monitor(body)
return f"unknown keyword {name!r}"
def _keyword_workspace(self, body: str) -> str:
# `<n>, monitor:<name>, default:true, persistent:true`
parts = [p.strip() for p in body.split(",")]
slot = int(parts[0])
monitor = next((p.split(":", 1)[1] for p in parts if p.startswith("monitor:")), None)
if monitor is None:
return "workspace rule has no monitor"
if not any(w["id"] == slot for w in self._workspaces):
self._workspaces.append(
{"id": slot, "name": str(slot), "monitor": monitor, "windows": 0}
)
return "ok"
def _keyword_windowrule(self, body: str) -> str:
# `match:initial_class ^hh-x$, workspace 1000, monitor hh-x`
parts = [p.strip() for p in body.split(",")]
match = parts[0]
if not match.startswith("match:initial_class "):
return "unsupported rule"
pattern = match[len("match:initial_class ") :]
workspace = next((p[len("workspace ") :] for p in parts if p.startswith("workspace ")), None)
monitor = next((p[len("monitor ") :] for p in parts if p.startswith("monitor ")), None)
if pattern == ".*" or monitor is None or workspace is None:
# The quarantine backstop: recorded so a test can assert it was
# installed, and first, but it conjures nothing.
self.rules[pattern] = (0, workspace or "")
return "ok"
initial_class = pattern.strip("^$")
self.rules[initial_class] = (int(workspace), monitor)
if self.auto_window:
self._create_window(initial_class, int(workspace), monitor, WINDOW_PID)
return "ok"
def _keyword_monitor(self, body: str) -> str:
# `<name>,<w>x<h>,auto,1`
parts = body.split(",")
name = parts[0]
width, _, height = parts[1].partition("x")
for monitor in self._monitors:
if monitor["name"] == name:
monitor["width"] = int(width)
monitor["height"] = int(height)
return "ok"
return f"no such monitor {name}"
# -- state ------------------------------------------------------------
def _create_output(self, name: str) -> None:
if any(m["name"] == name for m in self._monitors):
return
self._monitors.append(
{
"id": len(self._monitors),
"name": name,
"x": 1920 * len(self._monitors),
"y": 0,
"width": 1280,
"height": 720,
"scale": 1.0,
"activeWorkspace": None,
}
)
def _remove_output(self, name: str) -> bool:
before = len(self._monitors)
self._monitors = [m for m in self._monitors if m["name"] != name]
if len(self._monitors) == before:
return False
gone = {w["id"] for w in self._workspaces if w["monitor"] == name}
self._workspaces = [w for w in self._workspaces if w["monitor"] != name]
# Hyprland destroys a window with its surface; the fake destroys the
# ones that were on the output's workspaces, which is the behaviour the
# teardown cross-check is written against.
self._clients = [c for c in self._clients if c["workspace"]["id"] not in gone]
return True
def _create_window(self, initial_class: str, workspace: int, monitor: str, pid: int) -> str:
self._next_address += 0x10
address = hex(self._next_address)
self._clients.append(
{
"address": address,
"mapped": True,
"hidden": False,
"at": [0, 0],
"size": [1280, 720],
"workspace": {"id": workspace, "name": str(workspace)},
"monitor": next(
(m["id"] for m in self._monitors if m["name"] == monitor), 0
),
"class": initial_class,
"initialClass": initial_class,
"title": "a window, with a comma in its title",
"pid": pid,
}
)
for entry in self._workspaces:
if entry["id"] == workspace:
entry["windows"] += 1
# A window that maps makes its workspace the active one on its output,
# which is what the `foreground` join reads.
for entry in self._monitors:
if entry["name"] == monitor:
entry["activeWorkspace"] = {"id": workspace, "name": str(workspace)}
return address
class RecordingSink:
"""A :class:`hhstream_pointer.ops.PointerSink` that writes nothing anywhere."""
def __init__(self) -> None:
self.calls: list[tuple] = []
#: An exception to raise from the next call. The shipped driver
#: answers an ``OutputUnknown`` on the wire and lets anything else
#: take the connection down, so which one is raised here decides which
#: of the broker's two failure paths is being tested.
self.fail: Exception | None = None
def motion_absolute(self, output: str, x: float, y: float) -> None:
self._check()
self.calls.append(("warp", output, round(x, 6), round(y, 6)))
def button(self, output: str, code: int, state: int) -> None:
self._check()
self.calls.append(("button", output, code, state))
def frame(self, output: str) -> None:
self._check()
self.calls.append(("frame", output))
def _check(self) -> None:
if self.fail is not None:
raise self.fail
def of(self, kind: str) -> list[tuple]:
return [c for c in self.calls if c[0] == kind]
class FakeDriver:
"""The shipped driver with its Wayland sink replaced by a recorder.
The dispatcher, the handler wrapper and the per-connection protocol loop
are the shipped ones. The **accept loop** is not: ``serve_forever`` blocks
in ``accept()`` for ever 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. Four lines with a poll interval replace it;
everything a test is actually asserting about still runs the real code.
"""
def __init__(self, socket_path: Path) -> None:
check_path(Path(socket_path))
self.socket_path = Path(socket_path)
self.sink = RecordingSink()
self.dispatcher = Dispatcher(self.sink)
self.server = PointerServer(self.socket_path, _handler(self.dispatcher))
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
conn.settimeout(None)
self.connections.append(conn)
try:
self.server._serve_connection(conn)
except Exception:
# The shipped `main` lets a backend failure out of the serve
# loop and exits with code 10 — a driver talking to a dead
# display has nothing useful left to say. The fake ends its
# thread for the same reason, so the broker sees the same
# thing: a connection that closed without answering.
return
finally:
conn.close()
def stop(self) -> None:
"""Stop the way a killed process stops: listener *and* connections.
The shipped driver never has to do this — the kernel closes its fds
when it exits — but a fake that left the broker's held connection open
would not look like a driver that restarted, which is one of the
things the client has to get right.
"""
self._stop.set()
for conn in self.connections:
try:
conn.shutdown(socket.SHUT_RDWR)
except OSError:
pass
conn.close()
self._thread.join(timeout=5.0)
self.server.close()
@@ -0,0 +1,600 @@
"""Integration: a real daemon, a real control socket, a container and a cursor.
Everything the broker talks to is a real socket in this test. The daemon is
``python -m hhstreamd`` in a subprocess; the compositor is an ``AF_UNIX``
listener laid out the way Hyprland lays one out, answering the commands
Hyprland answers; the pointer driver is the shipped driver with its Wayland
sink replaced by a recorder. No compositor, no VM, no GUI application, no
network.
**What this proves, and what it cannot.** It proves the broker's half: that
the plan's commands go out in the plan's order, that the record is built from
what came back rather than from what was asked for, that a container is taken
down with its session and an unattended one is taken down at start-up, and
that the cursor is leased, bookmarked and never left with a button down. It
proves nothing about whether Hyprland agrees — ``output create headless`` is
marked unverified in the plan, and this fake says ``ok`` because it was asked
politely. The slice report lists what still needs a real compositor.
"""
from __future__ import annotations
import json
import os
import signal
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from conftest import socket_path, wait_until
from fakes import WINDOW_PID, FakeCompositor, FakeDriver
from hhstreamd.protocol import ExitCode
# The lifecycle test owns the daemon harness; reusing it is what keeps the two
# files describing the *same* daemon rather than two subtly different ones.
from test_lifecycle import Daemon, compositor_dir, start
class Rig:
"""A daemon with a compositor and a driver behind it."""
def __init__(self, root: Path, *, with_compositor: bool = True, with_driver: bool = True):
self.root = root
# The daemon refuses to start without a Wayland socket to hand its
# children, so the compositor's runtime directory holds both: the
# `wayland-N` an application connects to and the `hypr/<sig>/` the
# broker queries. That is the real layout of /run/hypr-stream.
self.comp_dir, self._wayland = compositor_dir(root)
self.compositor = FakeCompositor(self.comp_dir) if with_compositor else None
runtime = root / "run"
runtime.mkdir(parents=True, exist_ok=True)
socket_path(runtime, "pointer.sock")
self.driver = FakeDriver(runtime / "pointer.sock") if with_driver else None
self.daemon = Daemon(root, "--compositor-runtime-dir", str(self.comp_dir))
if self.compositor is not None:
# As a deployment does: the instance is named, not guessed at.
self.daemon.env["HYPRLAND_INSTANCE_SIGNATURE"] = self.compositor.signature
def start(self) -> None:
self.daemon.start()
def stop(self) -> None:
self.daemon.stop()
if self.driver is not None:
self.driver.stop()
if self.compositor is not None:
self.compositor.stop()
self._wayland.close()
# -- convenience ------------------------------------------------------
def plan_commands(self) -> list[str]:
"""What the compositor was told to do, queries filtered out."""
assert self.compositor is not None
return [
c
for c in self.compositor.commands
if not c.startswith(("version", "clients", "monitors", "workspaces", "cursorpos"))
]
def make_rig(root: Path, **kwargs) -> Rig:
rig = Rig(root, **kwargs)
rig.start()
return rig
@pytest.fixture
def rig(short_tmpdir: Path):
r = make_rig(short_tmpdir)
try:
yield r
finally:
_kill_everything(r.daemon)
r.stop()
def _kill_everything(daemon: Daemon) -> None:
try:
for session in daemon.call("list", all=True).get("sessions", []):
if session.get("live"):
try:
daemon.call("kill", id=session["id"], grace_s=0)
except Exception:
pass
except Exception:
pass
# ===========================================================================
# the container, start to finish
# ===========================================================================
def test_a_started_session_gets_an_output_a_workspace_and_a_window(rig: Rig):
session_id = start(rig.daemon, "sleeper")
record = rig.daemon.session(session_id)
container = record["container"]
assert container["output"] == f"hh-{session_id}"
assert container["workspace"] == 1000
assert container["mode"] == {"width": 1280, "height": 720}
assert container["created_by"] == "broker"
assert container["state"] == "owned"
# The signature, so a restarted broker re-attaches to this instance.
assert record["signature"] == rig.compositor.signature
# And the compositor really has it.
assert f"hh-{session_id}" in rig.compositor.outputs()
assert rig.compositor.workspaces_on(f"hh-{session_id}") == [1000]
def test_the_spatial_fields_come_from_the_compositor_not_from_our_intention(rig: Rig):
"""The read-back is the point: a record that echoed the plan back would
look identical whether or not the window rule ever bound."""
session_id = start(rig.daemon, "sleeper")
record = rig.daemon.session(session_id)
assert record["workspace"] == 1000
# The fake gives every window it conjures a pid of its own, which is not
# the session's — so a record carrying it can only have come from
# `clients -j`.
assert record["window"]["stable_id"] == f"hh-{session_id}:{WINDOW_PID}"
assert record["window"]["initial_class"] == f"hh-{session_id}"
assert record["pid"] != WINDOW_PID
assert record["foreground"] is True
# And `status` says where all of that came from.
assert record["compositor"]["ipc"] == "ok"
assert record["compositor"]["signature"] == rig.compositor.signature
assert record["compositor"]["error"] is None
def test_the_plan_runs_in_order_with_the_quarantine_backstop_first(rig: Rig):
session_id = start(rig.daemon, "sleeper")
assert rig.plan_commands() == [
# Installed at start-up, before any container exists: it matches every
# class, and a catch-all declared after an anchored rule overrides it.
"keyword windowrule match:initial_class .*, workspace special:quarantine",
f"output create headless hh-{session_id}",
f"keyword workspace 1000, monitor:hh-{session_id}, default:true, persistent:true",
f"keyword windowrule match:initial_class ^hh-{session_id}$, workspace 1000, "
f"monitor hh-{session_id}",
f"keyword monitor hh-{session_id},1280x720,auto,1",
]
def test_the_application_is_launched_with_the_container_stamp(rig: Rig):
"""The class the window rule matches reaches the app in its environment.
The environment is the only lever the launcher has: a per-app
``--app-id``/``--class`` flag would have to come from the allowlist, and
the allowlist is not this slice's file. A toolkit that reads none of
these keeps its own class — which the read-back is there to catch.
"""
session_id = start(rig.daemon, "idump")
lines = wait_until(
lambda: rig.daemon.call("logs", id=session_id).get("lines"),
timeout=10.0,
what="the app to report its environment",
)
assert json.loads(lines[0]) == {
"HHSTREAM_APP_ID": f"hh-{session_id}",
"SDL_VIDEO_WAYLAND_WMCLASS": f"hh-{session_id}",
"RESOURCE_NAME": f"hh-{session_id}",
}
# And the rule the compositor was given matches exactly that class.
assert rig.compositor.rules[f"hh-{session_id}"] == (1000, f"hh-{session_id}")
def test_killing_a_session_removes_its_output_and_reports_no_survivors(rig: Rig):
session_id = start(rig.daemon, "sleeper")
assert f"hh-{session_id}" in rig.compositor.outputs()
reply = rig.daemon.call("kill", id=session_id, grace_s=0)
assert reply["ok"], reply
# Teardown facts ride with the record, where `survivors` already does and
# where the CLI reads them from.
record = reply["session"]
assert record["container_removed"] is True
assert record["container_survivors"] == []
assert record["container"]["state"] == "removed"
assert f"hh-{session_id}" not in rig.compositor.outputs()
assert f"output remove hh-{session_id}" in rig.plan_commands()
def test_a_window_that_outlives_the_teardown_is_reported_not_hidden(rig: Rig):
"""Two sources have to agree before a teardown is called a success."""
session_id = start(rig.daemon, "sleeper")
# A second window of ours that landed outside the container, so removing
# the output does not take it with it.
rig.compositor.add_window(f"hh-{session_id}", 1, "HEADLESS-1", pid=999)
reply = rig.daemon.call("kill", id=session_id, grace_s=0)
assert [s["pid"] for s in reply["session"]["container_survivors"]] == [999]
def test_the_workspace_slot_comes_back_when_the_session_does_not(rig: Rig):
first = start(rig.daemon, "sleeper")
assert rig.daemon.session(first)["container"]["workspace"] == 1000
rig.daemon.call("kill", id=first, grace_s=0)
second = start(rig.daemon, "sleeper")
assert rig.daemon.session(second)["container"]["workspace"] == 1000, "the slot was reused"
def test_two_sessions_get_different_outputs_and_different_workspaces(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
a = rig.daemon.session(first)["container"]
b = rig.daemon.session(second)["container"]
assert a["output"] != b["output"]
assert {a["workspace"], b["workspace"]} == {1000, 1001}
assert sorted(rig.compositor.outputs()) == sorted(
["HEADLESS-1", a["output"], b["output"]]
)
def test_container_list_reports_the_containers_and_the_orphans(rig: Rig):
session_id = start(rig.daemon, "sleeper")
rig.compositor.add_output("hh-ghost-aaaaaa")
reply = rig.daemon.call("container.list")
assert reply["ok"], reply
assert [row["id"] for row in reply["containers"]] == [session_id]
assert reply["orphans"] == ["hh-ghost-aaaaaa"]
assert reply["workspaces_in_use"] == [1000]
# Listing is not acting.
assert "hh-ghost-aaaaaa" in rig.compositor.outputs()
def test_container_reconcile_reports_the_difference_it_repaired(rig: Rig):
session_id = start(rig.daemon, "sleeper")
# The window goes away under the broker, as a crashed application's would.
rig.compositor._clients.clear()
reply = rig.daemon.call("container.reconcile", id=session_id)
assert reply["ok"], reply
fields = {d["field"]: d for d in reply["diff"]}
assert fields["window"]["observed"] is None
assert fields["window"]["recorded"]["initial_class"] == f"hh-{session_id}"
assert rig.daemon.session(session_id)["window"] is None
# ===========================================================================
# the start-up scan
# ===========================================================================
def test_an_unattended_output_is_removed_when_the_broker_starts(short_tmpdir: Path):
"""A container must never be left running with nobody to own it."""
rig = make_rig(short_tmpdir)
try:
rig.daemon.stop()
rig.compositor.add_output("hh-leftover-aaaaaa")
rig.compositor.add_output("DP-9") # not ours, and must survive
rig.daemon.start()
assert "hh-leftover-aaaaaa" not in rig.compositor.outputs()
assert "DP-9" in rig.compositor.outputs()
assert "output remove hh-leftover-aaaaaa" in rig.plan_commands()
assert "output remove DP-9" not in rig.plan_commands()
finally:
_kill_everything(rig.daemon)
rig.stop()
def test_a_session_adopted_across_a_restart_keeps_its_container(short_tmpdir: Path):
rig = make_rig(short_tmpdir)
try:
session_id = start(rig.daemon, "sleeper")
output = rig.daemon.session(session_id)["container"]["output"]
rig.daemon.stop()
rig.daemon.start()
record = rig.daemon.session(session_id)
assert record["adopted"] is True
assert record["container"]["state"] == "owned"
assert output in rig.compositor.outputs(), "an adopted container is not an orphan"
# Its slot is not handed to the next session.
assert rig.daemon.session(start(rig.daemon, "sleeper"))["container"]["workspace"] == 1001
finally:
_kill_everything(rig.daemon)
rig.stop()
# ===========================================================================
# degraded mode — PLAN §4.4
# ===========================================================================
def test_with_no_compositor_ipc_sessions_still_live_and_die_normally(short_tmpdir: Path):
"""Lifecycle verbs never depend on the compositor.
The daemon has a Wayland socket to hand its children (so it starts) and no
Hyprland instance to query, which is exactly what a compositor that is up
but not answering IPC looks like from here.
"""
rig = make_rig(short_tmpdir, with_compositor=False)
try:
session_id = start(rig.daemon, "sleeper")
record = rig.daemon.session(session_id)
assert record["state"] == "ready"
assert record["container"] == {
"output": None,
"workspace": None,
"mode": None,
"created_by": "broker",
"state": "degraded",
}
# Nothing is guessed: no workspace, no window, no instance.
assert (record["workspace"], record["window"], record["signature"]) == (None, None, None)
assert record["compositor"]["ipc"] == "absent"
rig.daemon.call("touch", id=session_id)
reply = rig.daemon.call("kill", id=session_id, grace_s=0)
assert reply["ok"], reply
assert reply["session"]["state"] == "killed"
assert reply["session"]["survivors"] == []
assert reply["session"]["container_survivors"] == []
finally:
_kill_everything(rig.daemon)
rig.stop()
def test_a_degraded_session_cannot_be_aimed_at_and_says_why(short_tmpdir: Path):
rig = make_rig(short_tmpdir, with_compositor=False)
try:
session_id = start(rig.daemon, "sleeper")
reply = rig.daemon.call("pointer.acquire", id=session_id)
assert reply["ok"] is False
assert reply["error"] == "no_container"
assert ExitCode(10) == ExitCode.COMPOSITOR
finally:
_kill_everything(rig.daemon)
rig.stop()
# ===========================================================================
# the pointer, over the real control socket
# ===========================================================================
def test_a_whole_gesture_runs_through_the_broker_and_the_driver(rig: Rig):
session_id = start(rig.daemon, "sleeper")
output = f"hh-{session_id}"
acquired = rig.daemon.call("pointer.acquire", id=session_id)
assert acquired["ok"], acquired
lease = acquired["lease_id"]
assert acquired["bookmark"] == {
"x": 0.5,
"y": 0.5,
"output": output,
"at": acquired["bookmark"]["at"],
}
moved = rig.daemon.call("pointer.move", id=session_id, lease_id=lease, x=0.25, y=0.75)
assert moved["ok"], moved
assert (moved["bookmark"]["x"], moved["bookmark"]["y"]) == (0.25, 0.75)
clicked = rig.daemon.call("pointer.click", id=session_id, lease_id=lease, button="left")
assert clicked["ok"], clicked
released = rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
assert released["ok"], released
assert released["released_by"] == "lease"
assert released["buttons_lifted"] == []
assert rig.driver.sink.calls == [
("warp", output, 0.5, 0.5),
("frame", output),
("warp", output, 0.25, 0.75),
("frame", output),
("button", output, 0x110, 1),
("frame", output),
("button", output, 0x110, 0),
("frame", output),
]
# The bookmark is in the record, which is what survives a broker restart.
record = rig.daemon.session(session_id)
assert record["pointer"]["bookmark"]["x"] == 0.25
assert record["pointer"]["released_by"] == "lease"
assert record["pointer"]["last_released_at"] == released["released_at"]
def test_the_cursor_is_leased_broker_wide_and_the_holder_is_named(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
refused = rig.daemon.call("pointer.acquire", id=second)
assert refused["ok"] is False
assert refused["error"] == "pointer_busy"
assert refused["holder"] == first
# And the other session cannot move it with someone else's lease either.
denied = rig.daemon.call("pointer.move", id=second, lease_id=lease, x=0.1, y=0.1)
assert denied["error"] == "no_lease"
state = rig.daemon.call("pointer.state")
assert state["holder"] == first
assert state["lease_id"] == lease
def test_a_released_lease_frees_the_cursor_for_the_next_session(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
rig.daemon.call("pointer.release", id=first, lease_id=lease)
taken = rig.daemon.call("pointer.acquire", id=second)
assert taken["ok"], taken
assert taken["bookmark"]["output"] == f"hh-{second}"
def test_a_button_left_down_is_lifted_when_the_lease_is_released(rig: Rig):
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
down = rig.daemon.call("pointer.button", id=session_id, lease_id=lease, button="left", state="down")
assert down["buttons"] == ["left"]
released = rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
assert released["buttons_lifted"] == ["left"]
assert rig.driver.dispatcher._pressed == {}, "nothing may be left down on the driver"
def test_killing_a_session_that_holds_the_cursor_gives_it_back(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
rig.daemon.call("pointer.button", id=first, lease_id=lease, button="right", state="down")
rig.daemon.call("kill", id=first, grace_s=0)
assert rig.driver.dispatcher._pressed == {}
assert rig.daemon.call("pointer.state")["holder"] is None
assert rig.daemon.call("pointer.acquire", id=second)["ok"]
def test_pointer_verbs_do_not_reset_the_idle_clock(rig: Rig):
"""A session being clicked in is still one nobody has asked to keep."""
session_id = start(rig.daemon, "sleeper")
before = rig.daemon.session(session_id)["command_count"]
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.daemon.call("pointer.move", id=session_id, lease_id=lease, x=0.3, y=0.3)
rig.daemon.call("pointer.click", id=session_id, lease_id=lease)
rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
assert rig.daemon.session(session_id)["command_count"] == before
def test_a_retried_click_with_the_same_request_id_clicks_once(rig: Rig):
"""A click is the one mutation an agent cannot undo."""
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.driver.sink.calls.clear()
first = rig.daemon.call(
"pointer.click", id=session_id, lease_id=lease, request_id="retry-me"
)
second = rig.daemon.call(
"pointer.click", id=session_id, lease_id=lease, request_id="retry-me"
)
assert first["ok"] and second["ok"]
assert second.get("deduplicated") is True
assert len(rig.driver.sink.of("button")) == 2, "one press and one release, not two"
def test_a_restored_bookmark_survives_a_daemon_restart(short_tmpdir: Path):
"""That is what putting it in the record, and not only in the lease, is for."""
rig = make_rig(short_tmpdir)
try:
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.daemon.call("pointer.move", id=session_id, lease_id=lease, x=0.8, y=0.2)
rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
rig.daemon.stop()
rig.daemon.start()
rig.driver.sink.calls.clear()
acquired = rig.daemon.call("pointer.acquire", id=session_id)
assert (acquired["bookmark"]["x"], acquired["bookmark"]["y"]) == (0.8, 0.2)
assert rig.driver.sink.of("warp") == [("warp", f"hh-{session_id}", 0.8, 0.2)]
finally:
_kill_everything(rig.daemon)
rig.stop()
def test_with_no_driver_the_pointer_verbs_say_so_and_the_lease_is_not_held(
short_tmpdir: Path,
):
rig = make_rig(short_tmpdir, with_driver=False)
try:
session_id = start(rig.daemon, "sleeper")
reply = rig.daemon.call("pointer.acquire", id=session_id)
assert reply["ok"] is False
assert reply["error"] == "driver_unavailable"
assert rig.daemon.call("pointer.state")["holder"] is None
finally:
_kill_everything(rig.daemon)
rig.stop()
# ===========================================================================
# an exit nobody asked for
# ===========================================================================
def test_an_application_that_dies_takes_its_container_with_it(rig: Rig):
session_id = start(rig.daemon, "sleeper")
output = f"hh-{session_id}"
pid = rig.daemon.session(session_id)["pid"]
os.kill(pid, signal.SIGKILL)
wait_until(
lambda: not rig.daemon.session(session_id)["live"],
timeout=10.0,
what="the daemon to notice the exit",
)
wait_until(
lambda: output not in rig.compositor.outputs(),
timeout=10.0,
what="the container to be taken down with it",
)
assert rig.daemon.session(session_id)["container"]["state"] == "removed"
# And its slot is free again.
assert rig.daemon.session(start(rig.daemon, "sleeper"))["container"]["workspace"] == 1000
def test_a_session_that_dies_holding_the_cursor_gives_it_back(rig: Rig):
"""Never leave a button down, even when nobody asked for the teardown."""
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
rig.daemon.call("pointer.button", id=first, lease_id=lease, button="left", state="down")
os.kill(rig.daemon.session(first)["pid"], signal.SIGKILL)
wait_until(
lambda: rig.daemon.call("pointer.state")["holder"] is None,
timeout=10.0,
what="the lease to come back",
)
assert rig.driver.dispatcher._pressed == {}
assert rig.daemon.call("pointer.acquire", id=second)["ok"]
+28 -2
View File
@@ -52,7 +52,17 @@ def _repo_root() -> Path:
REPO_ROOT = _repo_root()
#: The package lives under `src/` here. Keep the root too, so a flat checkout works.
IMPORT_PATH = os.pathsep.join([str(REPO_ROOT / "src"), str(REPO_ROOT)])
#:
#: These are PREPENDED to whatever PYTHONPATH we inherited rather than replacing
#: it. Clobbering it works in a checkout, where `src/` is the package, but under
#: a build (checks/unit.nix) the package under test is what the inherited path
#: points at -- so replacing it made `python -m hhstreamd` die at startup with an
#: ImportError, and every test in this file error out in its setup, which reads
#: as a daemon bug rather than a harness one.
_CHECKOUT_PATH = os.pathsep.join([str(REPO_ROOT / "src"), str(REPO_ROOT)])
IMPORT_PATH = os.pathsep.join(
p for p in (_CHECKOUT_PATH, os.environ.get("PYTHONPATH", "")) if p
)
# The brief's dummy app, verbatim.
SLEEP_600 = "import time; time.sleep(600)"
@@ -108,6 +118,17 @@ ENV_DUMP = (
"time.sleep(600)"
)
# The container stamp as the application actually receives it. A separate app
# from `envdump` because that one asserts on an exact three-key dict, and the
# question here is a different one: did the class the window rule matches
# reach the process.
APP_ID_DUMP = (
"import json, os, time; "
"print(json.dumps({k: os.environ.get(k) for k in "
"('HHSTREAM_APP_ID', 'SDL_VIDEO_WAYLAND_WMCLASS', 'RESOURCE_NAME')}), flush=True); "
"time.sleep(600)"
)
#: How the daemon may report having noticed an exit: a pidfd, or the documented
#: /proc fallback where pidfd is unavailable.
EXIT_MECHANISMS = {"pidfd", "proc_poll", "proc_check"}
@@ -136,6 +157,7 @@ def config_text(wrapper: Path | None = None) -> str:
+ app("echoer", "import time; print('hello', flush=True); time.sleep(600)")
+ app("chatty", "import time\nfor i in range(3):\n print(f'line {i}', flush=True)\n time.sleep(0.2)")
+ app("envdump", ENV_DUMP)
+ app("idump", APP_ID_DUMP)
)
@@ -144,6 +166,10 @@ class Daemon:
def __init__(self, root: Path, *extra_args: str):
self.extra_args = list(extra_args)
#: Extra environment for the daemon process, laid over the inherited
#: one. The container tests use it to pin the compositor instance
#: signature the way a real deployment's unit does.
self.env: dict[str, str] = {}
self.root = root
self.socket = socket_path(root)
self.state_dir = root / "state"
@@ -184,7 +210,7 @@ class Daemon:
stdout=open(self.log, "ab"),
stderr=subprocess.STDOUT,
cwd=str(REPO_ROOT),
env={**os.environ, "PYTHONPATH": IMPORT_PATH},
env={**os.environ, "PYTHONPATH": IMPORT_PATH, **self.env},
)
wait_until(
lambda: socket_is_live(self.socket) or self.process.poll() is not None,
@@ -108,3 +108,89 @@ def test_error_replies_carry_both_a_machine_field_and_a_human_field():
def test_ok_replies_are_flagged():
assert protocol.ok(id="a")["ok"] is True
# ---------------------------------------------------------------------------
# `request_id` idempotency (PLAN §8)
# ---------------------------------------------------------------------------
def test_a_repeated_mutating_request_returns_the_recorded_answer():
cache = protocol.IdempotencyCache()
cache.remember("start", "r1", {"ok": True, "id": "foot-aaaaaa"})
replay = cache.lookup("start", "r1")
assert replay == {"ok": True, "id": "foot-aaaaaa", "deduplicated": True}
def test_a_recorded_failure_is_replayed_as_the_failure_it_was():
"""A retried `start` that policy refused must not get a second attempt."""
cache = protocol.IdempotencyCache()
cache.remember("start", "r1", {"ok": False, "error": "not_allowlisted"})
assert cache.lookup("start", "r1")["error"] == "not_allowlisted"
def test_read_verbs_are_never_cached_because_a_stale_list_is_worse():
cache = protocol.IdempotencyCache()
cache.remember("list", "r1", {"ok": True, "sessions": []})
assert cache.lookup("list", "r1") is None
def test_a_request_with_no_id_is_never_matched_against_another():
cache = protocol.IdempotencyCache()
cache.remember("start", None, {"ok": True})
assert len(cache) == 0
assert cache.lookup("start", None) is None
def test_the_cache_is_bounded_because_the_peer_chooses_the_keys():
cache = protocol.IdempotencyCache(capacity=4)
for n in range(10):
cache.remember("touch", f"r{n}", {"ok": True, "n": n})
assert len(cache) == 4
assert cache.lookup("touch", "r0") is None
assert cache.lookup("touch", "r9")["n"] == 9
def test_every_pointer_verb_that_moves_something_is_cached():
"""A retried click is a second click — the one mutation an agent cannot undo."""
assert {
"pointer.acquire",
"pointer.move",
"pointer.button",
"pointer.click",
"pointer.release",
} <= protocol.MUTATING_VERBS
assert "pointer.state" not in protocol.MUTATING_VERBS
assert "container.list" not in protocol.MUTATING_VERBS
def test_every_verb_the_protocol_names_is_one_the_daemon_answers():
"""One list, so a verb cannot be added to the dispatcher alone.
The CLI imports `protocol`, not `server`; a verb in one and not the other
is a client that asks for something nothing answers.
"""
from pathlib import Path
from hhstreamd.clock import ManualClock
from hhstreamd.manager import ManagerConfig, SessionManager
from hhstreamd.policy import Policy
from hhstreamd.server import ControlServer
manager = SessionManager(
ManagerConfig(state_dir=Path("/nonexistent"), runtime_dir=Path("/nonexistent"), policy=Policy()),
clock=ManualClock(),
)
server = ControlServer(manager, "/nonexistent/control.sock")
assert set(server._ops) == set(protocol.VERBS)
assert protocol.MUTATING_VERBS <= set(protocol.VERBS)
+11 -3
View File
@@ -112,8 +112,15 @@ def test_session_with_no_verb_lists(host_cli, sent):
def test_the_socket_may_be_given_before_or_after_the_verb(host_cli, sent):
run(host_cli, ["session", "--socket", "/a.sock", "list"])
run(host_cli, ["session", "list", "--socket", "/b.sock"])
assert sent[0]["socket_path"] == "/a.sock"
assert sent[1]["socket_path"] == "/b.sock"
# Selected by op rather than by position: a human `list` also asks
# `pointer.state` for its POINTER column, so the requests interleave.
assert [c["socket_path"] for c in sent if c["op"] == "list"] == ["/a.sock", "/b.sock"]
# The second request of each run inherits the same socket, which is the
# thing that would break if it were resolved twice.
assert [c["socket_path"] for c in sent if c["op"] == "pointer.state"] == [
"/a.sock",
"/b.sock",
]
def test_the_socket_falls_back_to_the_environment(host_cli, sent, monkeypatch):
@@ -182,7 +189,8 @@ def test_list_all_is_only_sent_when_asked(host_cli, sent):
run(host_cli, ["session", "list"])
assert "all" not in sent[0]
run(host_cli, ["session", "list", "--all"])
assert sent[1]["all"] is True
lists = [c for c in sent if c["op"] == "list"]
assert lists[1]["all"] is True
def test_request_ids_are_forwarded_on_mutating_verbs(host_cli, sent):
+695
View File
@@ -0,0 +1,695 @@
"""The CLI surface added in this milestone: containers, and the pointer lease.
Same shape as ``test_cli_registration.py`` — a host parser the test builds
itself and a stubbed transport — because the point is the same: what the
handlers put on the wire, what they print, and what they exit with. Nothing
here needs a daemon, so nothing here starts one.
The lease cache is pointed at a temporary directory for every test. It is real
(the same code the CLI runs), because "acquire remembers the lease so move
needs no flag" is the whole reason it exists and a stub would prove nothing.
"""
from __future__ import annotations
import argparse
import io
import json
from contextlib import redirect_stderr, redirect_stdout
import pytest
import hhstream_session
from hhstream_session import format as fmt
from hhstream_session import lease, register
from hhstream_session.client import ClientError
from hhstreamd.protocol import ExitCode
@pytest.fixture(autouse=True)
def lease_cache(tmp_path, monkeypatch):
"""Every test gets its own cache, and none of them touch the real one."""
monkeypatch.setenv(lease.ENV_LEASE_DIR, str(tmp_path / "leases"))
monkeypatch.delenv(lease.ENV_LEASE, raising=False)
return tmp_path / "leases"
@pytest.fixture
def host_cli():
parser = argparse.ArgumentParser(prog="hhstream")
sub = parser.add_subparsers(dest="command")
register(sub)
return parser
@pytest.fixture
def sent(monkeypatch):
"""Captured requests, plus per-op canned replies.
Keyed by op rather than by call order, because a human ``list`` now makes
two requests and a test that counted positions would be asserting about
the order of calls rather than about the verb.
"""
class Transport(list):
replies: dict[str, dict] = {}
def of(self, op: str) -> list[dict]:
return [call for call in self if call["op"] == op]
calls = Transport()
calls.replies = {}
def fake_call(op, *, socket_path=None, timeout=None, **fields):
wire = {k: v for k, v in fields.items() if v is not None}
calls.append({"op": op, "socket_path": socket_path, **wire})
reply = calls.replies.get(op)
if isinstance(reply, ClientError):
raise reply
return reply if reply is not None else {"ok": True}
monkeypatch.setattr(hhstream_session, "call", fake_call)
return calls
def run(parser: argparse.ArgumentParser, argv: list[str]) -> tuple[int, str, str]:
args = parser.parse_args(argv)
out, err = io.StringIO(), io.StringIO()
with redirect_stdout(out), redirect_stderr(err):
code = hhstream_session.dispatch(args)
return code, out.getvalue(), err.getvalue()
# ---------------------------------------------------------------------------
# registration
# ---------------------------------------------------------------------------
def test_every_verb_the_contract_names_is_registered(host_cli):
"""PLAN §9's surface, verb by verb, as a caller would type it."""
surface = [
["session", "container", "foo-aaaaaa"],
["session", "container"],
["session", "reconcile"],
["session", "reconcile", "foo-aaaaaa"],
["session", "pointer", "acquire", "foo-aaaaaa"],
["session", "pointer", "acquire", "foo-aaaaaa", "--ttl", "10s", "--no-restore"],
["session", "pointer", "move", "foo-aaaaaa", "--to", "0.5,0.5"],
["session", "pointer", "move", "foo-aaaaaa", "--by", "-0.1,0.2"],
["session", "pointer", "click", "foo-aaaaaa"],
["session", "pointer", "click", "foo-aaaaaa", "--button", "right"],
["session", "pointer", "down", "foo-aaaaaa", "--button", "middle"],
["session", "pointer", "up", "foo-aaaaaa"],
["session", "pointer", "release", "foo-aaaaaa"],
["session", "pointer", "state"],
["session", "pointer", "state", "--json"],
]
for argv in surface:
args = host_cli.parse_args(argv)
assert callable(args.func), argv
def test_a_move_needs_exactly_one_target(host_cli):
with pytest.raises(SystemExit):
host_cli.parse_args(["session", "pointer", "move", "x"])
with pytest.raises(SystemExit):
host_cli.parse_args(
["session", "pointer", "move", "x", "--to", "0,0", "--by", "0,0"]
)
@pytest.mark.parametrize("bad", ["0.5", "0.5,", "a,b", "0.5,0.5,0.5", ""])
def test_a_malformed_coordinate_pair_is_a_usage_error(host_cli, bad):
"""Rejected by argparse, so nothing reaches the broker and exit 2 is exit 2."""
with pytest.raises(SystemExit):
host_cli.parse_args(["session", "pointer", "move", "x", "--to", bad])
def test_an_unknown_button_is_refused_before_the_wire(host_cli):
with pytest.raises(SystemExit):
host_cli.parse_args(["session", "pointer", "click", "x", "--button", "pinky"])
# ---------------------------------------------------------------------------
# containers
# ---------------------------------------------------------------------------
def test_container_with_no_id_lists_every_container_and_the_orphans(host_cli, sent):
sent.replies["container.list"] = {
"ok": True,
"containers": [
{
"id": "foot-aaaaaa",
"app": "foot",
"output": "hh-foot-aaaaaa",
"workspace": 1000,
"mode": {"width": 1280, "height": 720},
"state": "owned",
"window": "0x55f",
}
],
"orphans": ["hh-gone-bbbbbb"],
"compositor": "ok",
"error": None,
"workspaces_in_use": [1000],
}
code, out, _ = run(host_cli, ["session", "container"])
assert code == ExitCode.OK
assert sent.of("container.list") and not sent.of("container.reconcile")
assert "hh-foot-aaaaaa" in out and "1280x720" in out
assert "hh-gone-bbbbbb" in out and "orphans" in out
def test_orphans_that_could_not_be_read_are_not_reported_as_none(host_cli, sent):
"""`null` orphans is "I could not look", which is not "nothing is there"."""
sent.replies["container.list"] = {
"ok": True,
"containers": [],
"orphans": None,
"compositor": "absent",
"error": "no compositor IPC",
"workspaces_in_use": [],
}
code, out, _ = run(host_cli, ["session", "container"])
assert code == ExitCode.OK
assert "could not be asked" in out
assert "none" not in out.split("orphans:")[1]
assert "no compositor IPC" in out
def test_container_with_an_id_reconciles_so_the_answer_is_current(host_cli, sent):
sent.replies["container.reconcile"] = {
"ok": True,
"id": "foot-aaaaaa",
"container": {
"output": "hh-foot-aaaaaa",
"workspace": 1000,
"mode": {"width": 1280, "height": 720},
"created_by": "broker",
"state": "owned",
},
"diff": [
{
"id": "foot-aaaaaa",
"field": "workspace",
"recorded": None,
"observed": 1000,
}
],
}
code, out, _ = run(host_cli, ["session", "container", "foot-aaaaaa"])
assert code == ExitCode.OK
assert sent.of("container.reconcile")[0]["id"] == "foot-aaaaaa"
assert "hh-foot-aaaaaa" in out
# Both values, so a reader can see which way the record moved.
assert "recorded None" in out and "compositor says 1000" in out
def test_reconcile_with_no_drift_says_so_rather_than_printing_nothing(host_cli, sent):
sent.replies["container.reconcile"] = {
"ok": True,
"container": None,
"diff": [],
"scan": {
"available": True,
"signature": "abc123",
"quarantine": "special:quarantine",
"adopted": [],
"removed": ["hh-stale-cccccc"],
"orphaned": [],
"failed": [],
},
}
code, out, _ = run(host_cli, ["session", "reconcile"])
assert code == ExitCode.OK
assert "id" not in sent.of("container.reconcile")[0]
assert "matches the compositor" in out
assert "hh-stale-cccccc" in out and "removed" in out
assert "abc123" in out
# ---------------------------------------------------------------------------
# the lease, across two invocations
# ---------------------------------------------------------------------------
def _acquired(lease_id: str = "lease-1") -> dict:
return {
"ok": True,
"id": "foot-aaaaaa",
"lease_id": lease_id,
"bookmark": {
"x": 0.5,
"y": 0.5,
"output": "hh-foot-aaaaaa",
"at": "2026-10-03T00:00:00Z",
},
"expires_in_s": 30.0,
}
def test_acquire_prints_the_bare_lease_id_on_stdout_and_detail_on_stderr(host_cli, sent):
"""Same contract as `start`: stdout is the one token a caller passes back."""
sent.replies["pointer.acquire"] = _acquired()
code, out, err = run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
assert code == ExitCode.OK
assert out == "lease-1\n"
assert "hh-foot-aaaaaa" in err
assert "release foot-aaaaaa" in err
def test_acquire_sends_ttl_and_restore_only_when_asked(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
first = sent.of("pointer.acquire")[0]
assert "ttl_s" not in first and "restore" not in first
run(
host_cli,
["session", "pointer", "acquire", "foot-aaaaaa", "--ttl", "2m", "--no-restore"],
)
second = sent.of("pointer.acquire")[1]
assert second["ttl_s"] == 120.0
assert second["restore"] is False
def test_a_gesture_reuses_the_lease_acquire_cached(host_cli, sent):
"""The contract's surface has no --lease, so something has to remember it."""
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.move"] = {
"ok": True,
"id": "foot-aaaaaa",
"bookmark": {
"x": 0.25,
"y": 0.75,
"output": "hh-foot-aaaaaa",
"at": "2026-10-03T00:00:01Z",
},
}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
code, out, _ = run(
host_cli, ["session", "pointer", "move", "foot-aaaaaa", "--to", "0.25,0.75"]
)
assert code == ExitCode.OK
move = sent.of("pointer.move")[0]
assert move["lease_id"] == "lease-1"
assert (move["x"], move["y"]) == (0.25, 0.75)
assert "0.2500,0.7500" in out
def test_a_relative_move_sends_dx_dy_and_never_x_y(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
run(host_cli, ["session", "pointer", "move", "foot-aaaaaa", "--by", "-0.1,0.2"])
move = sent.of("pointer.move")[0]
assert (move["dx"], move["dy"]) == (-0.1, 0.2)
assert "x" not in move and "y" not in move
def test_an_explicit_lease_beats_the_cache(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
run(
host_cli,
["session", "pointer", "click", "foot-aaaaaa", "--lease", "from-the-caller"],
)
assert sent.of("pointer.click")[0]["lease_id"] == "from-the-caller"
def test_the_environment_beats_the_cache_too(host_cli, sent, monkeypatch):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
monkeypatch.setenv(lease.ENV_LEASE, "from-the-environment")
run(host_cli, ["session", "pointer", "click", "foot-aaaaaa"])
assert sent.of("pointer.click")[0]["lease_id"] == "from-the-environment"
def test_a_lease_cached_for_another_broker_is_not_a_lease_here(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
run(host_cli, ["session", "--socket", "/a.sock", "pointer", "acquire", "foot-aaaaaa"])
code, _, err = run(
host_cli, ["session", "--socket", "/b.sock", "pointer", "click", "foot-aaaaaa"]
)
assert code == ExitCode.NO_LEASE
assert not sent.of("pointer.click")
assert "no pointer lease" in err
def test_a_gesture_with_no_lease_is_nine_and_never_reaches_the_broker(host_cli, sent):
"""Exit 9, not 2: the command line is fine, the lease is what is missing."""
for argv in (
["session", "pointer", "move", "foot-aaaaaa", "--to", "0.5,0.5"],
["session", "pointer", "click", "foot-aaaaaa"],
["session", "pointer", "down", "foot-aaaaaa"],
["session", "pointer", "up", "foot-aaaaaa"],
["session", "pointer", "release", "foot-aaaaaa"],
):
code, out, err = run(host_cli, argv)
assert code == ExitCode.NO_LEASE, argv
assert "acquire" in err
assert sent == []
def test_a_no_lease_refusal_drops_the_stale_cache_entry(host_cli, sent):
"""Otherwise every later verb fails the same way and `acquire` looks pointless."""
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.move"] = {
"ok": False,
"error": "no_lease",
"reason": "foot-aaaaaa does not hold the pointer: lease expired",
"holder": None,
}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
code, _, err = run(
host_cli, ["session", "pointer", "move", "foot-aaaaaa", "--to", "0.5,0.5"]
)
assert code == ExitCode.NO_LEASE
assert "exit 9" in err
assert lease.recall("foot-aaaaaa", socket=None) is None
def test_release_gives_the_lease_back_and_forgets_it(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.release"] = {
"ok": True,
"id": "foot-aaaaaa",
"bookmark": {
"x": 0.5,
"y": 0.5,
"output": "hh-foot-aaaaaa",
"at": "2026-10-03T00:00:02Z",
},
"released_by": "lease",
"released_at": "2026-10-03T00:00:02Z",
"buttons_lifted": ["left"],
}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
code, out, _ = run(host_cli, ["session", "pointer", "release", "foot-aaaaaa"])
assert code == ExitCode.OK
# The loud part: a button that was down came back up.
assert "lifted left" in out
assert lease.recall("foot-aaaaaa", socket=None) is None
def test_a_held_button_is_reported_with_everything_still_down(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.button"] = {
"ok": True,
"id": "foot-aaaaaa",
"buttons": ["left"],
}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
code, out, _ = run(host_cli, ["session", "pointer", "down", "foot-aaaaaa"])
assert code == ExitCode.OK
request = sent.of("pointer.button")[0]
assert request["button"] == "left" and request["state"] == "down"
assert "held: left" in out
def test_up_sends_the_other_state_through_the_same_verb(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
sent.replies["pointer.button"] = {"ok": True, "id": "foot-aaaaaa", "buttons": []}
run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
run(host_cli, ["session", "pointer", "up", "foot-aaaaaa", "--button", "right"])
request = sent.of("pointer.button")[0]
assert (request["button"], request["state"]) == ("right", "up")
def test_pointer_state_needs_no_lease_and_no_session(host_cli, sent):
sent.replies["pointer.state"] = {
"ok": True,
"holder": "foot-aaaaaa",
"since": 123.0,
"lease_id": "lease-1",
"expires_at": 153.0,
"buttons": ["left"],
"bookmark": None,
"driver": "/run/hhstream/pointer.sock",
}
code, out, _ = run(host_cli, ["session", "pointer", "state"])
assert code == ExitCode.OK
assert "foot-aaaaaa" in out and "left" in out
def test_a_busy_pointer_exits_eight_naming_the_holder(host_cli, sent):
sent.replies["pointer.acquire"] = {
"ok": False,
"error": "pointer_busy",
"reason": "the pointer is held by chromium-bbbbbb",
"holder": "chromium-bbbbbb",
}
code, out, err = run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
assert code == ExitCode.BUSY
assert out == ""
assert "chromium-bbbbbb" in err
# Nothing was cached: there is no lease to remember.
assert lease.recall("foot-aaaaaa", socket=None) is None
def test_a_compositor_failure_says_the_session_is_still_running(host_cli, sent):
"""Exit 10 is not exit 4, and the message has to carry that difference."""
sent.replies["pointer.acquire"] = {
"ok": False,
"error": "no_container",
"reason": "session foot-aaaaaa has no container output to aim at",
"hint": "the compositor was unreachable when this session started",
}
code, _, err = run(host_cli, ["session", "pointer", "acquire", "foot-aaaaaa"])
assert code == ExitCode.COMPOSITOR
assert "compositor error" in err
assert "the session itself is unaffected" in err
def test_json_mode_puts_the_protocol_object_on_stdout(host_cli, sent):
sent.replies["pointer.acquire"] = _acquired()
code, out, err = run(
host_cli, ["session", "pointer", "acquire", "--json", "foot-aaaaaa"]
)
assert code == ExitCode.OK
assert json.loads(out)["lease_id"] == "lease-1"
assert err == ""
# Still cached: --json changes the rendering, not the behaviour.
assert lease.recall("foot-aaaaaa", socket=None) == "lease-1"
# ---------------------------------------------------------------------------
# list: the three new columns
# ---------------------------------------------------------------------------
def _listed(**overrides) -> dict:
session = {
"id": "foot-aaaaaa",
"app": "foot",
"state": "ready",
"pid": 4242,
"live": True,
"idle_s": 12.0,
"expires_in_s": 600.0,
"workspace": 1000,
"container": {"output": "hh-foot-aaaaaa", "workspace": 1000, "state": "owned"},
}
session.update(overrides)
return {"ok": True, "sessions": [session]}
def test_list_gains_the_workspace_output_and_pointer_columns(host_cli, sent):
sent.replies["list"] = _listed()
sent.replies["pointer.state"] = {"ok": True, "holder": None}
code, out, _ = run(host_cli, ["session", "list"])
assert code == ExitCode.OK
header = out.splitlines()[0].split()
assert header[:9] == [
"ID",
"APP",
"STATE",
"PID",
"WS",
"OUTPUT",
"POINTER",
"IDLE",
"EXPIRES",
]
row = out.splitlines()[1].split()
# PID stays in column four: callers (and vm-sessions) already read it there.
assert row[3] == "4242"
assert row[4] == "1000" and row[5] == "hh-foot-aaaaaa" and row[6] == "free"
def test_the_row_that_holds_the_cursor_says_held_and_the_others_say_who(host_cli, sent):
sent.replies["list"] = {
"ok": True,
"sessions": _listed()["sessions"]
+ [
{
"id": "chromium-bbbbbb",
"app": "chromium",
"state": "ready",
"pid": 4343,
"live": True,
"idle_s": 3.0,
"expires_in_s": 600.0,
"workspace": 1001,
"container": {"output": "hh-chromium-bbbbbb"},
}
],
}
sent.replies["pointer.state"] = {"ok": True, "holder": "foot-aaaaaa"}
code, out, _ = run(host_cli, ["session", "list"])
assert code == ExitCode.OK
rows = {line.split()[0]: line.split() for line in out.splitlines()[1:]}
assert rows["foot-aaaaaa"][6] == "held"
assert rows["chromium-bbbbbb"][6] == "held:foot-aaaaaa"
def test_a_degraded_session_shows_the_gap_marker_not_a_blank(host_cli, sent):
"""A blank reads as zero, or as "no". Neither is what `null` means."""
sent.replies["list"] = _listed(
workspace=None,
container={"output": None, "workspace": None, "state": "degraded"},
)
sent.replies["pointer.state"] = {"ok": True, "holder": None}
code, out, _ = run(host_cli, ["session", "list"])
row = out.splitlines()[1].split()
assert row[4] == fmt.DASH and row[5] == fmt.DASH
def test_an_unreachable_pointer_state_leaves_the_column_unknown_not_free(host_cli, sent):
"""The sessions were listed; only the lease could not be read."""
sent.replies["list"] = _listed()
sent.replies["pointer.state"] = ClientError("daemon_unreachable", "socket went away")
code, out, _ = run(host_cli, ["session", "list"])
assert code == ExitCode.OK
assert out.splitlines()[1].split()[6] == fmt.DASH
def test_json_list_makes_no_second_request_and_is_the_protocol_object(host_cli, sent):
sent.replies["list"] = _listed()
code, out, _ = run(host_cli, ["session", "list", "--json"])
assert code == ExitCode.OK
assert not sent.of("pointer.state")
assert json.loads(out)["sessions"][0]["id"] == "foot-aaaaaa"
def test_a_failed_list_does_not_go_on_to_ask_about_the_pointer(host_cli, sent):
sent.replies["list"] = {"ok": False, "error": "bad_request", "reason": "nope"}
code, _, err = run(host_cli, ["session", "list"])
assert code == ExitCode.USAGE
assert not sent.of("pointer.state")
assert "nope" in err
# ---------------------------------------------------------------------------
# teardown: the survivors the CLI used to be silent about
# ---------------------------------------------------------------------------
def test_kill_warns_about_windows_that_survived_the_teardown(host_cli, sent):
sent.replies["kill"] = {
"ok": True,
"id": "foot-aaaaaa",
"session": {
"id": "foot-aaaaaa",
"state": "killed",
"signal_sent": "TERM",
"pgid": 4242,
"survivors": [],
"container_removed": True,
"container_survivors": [
{
"address": "0x55f",
"pid": 4243,
"class": "hh-foot-aaaaaa",
"initial_class": "hh-foot-aaaaaa",
"workspace": 1000,
}
],
},
}
code, out, _ = run(host_cli, ["session", "kill", "foot-aaaaaa"])
assert code == ExitCode.OK
assert "WARNING" in out
assert "still shows 1 window" in out
assert "0x55f" in out
def test_kill_says_when_the_compositor_could_not_be_asked_about_survivors(host_cli, sent):
"""`null` is "I could not check", which must not print as "nothing survived"."""
sent.replies["kill"] = {
"ok": True,
"session": {
"id": "foot-aaaaaa",
"state": "killed",
"survivors": [],
"container_removed": False,
"container_survivors": None,
"container_error": "no compositor IPC",
},
}
code, out, _ = run(host_cli, ["session", "kill", "foot-aaaaaa"])
assert code == ExitCode.OK
assert "could not be asked" in out
assert "no compositor IPC" in out
def test_a_clean_teardown_says_the_container_went_away(host_cli, sent):
sent.replies["kill"] = {
"ok": True,
"session": {
"id": "foot-aaaaaa",
"state": "killed",
"survivors": [],
"container_removed": True,
"container_survivors": [],
},
}
code, out, _ = run(host_cli, ["session", "kill", "foot-aaaaaa"])
assert code == ExitCode.OK
assert "container removed" in out
assert "WARNING" not in out
# ---------------------------------------------------------------------------
# the gap this slice could not close
# ---------------------------------------------------------------------------
def test_no_container_is_refused_rather_than_sent_and_ignored(host_cli, sent):
"""The broker's `start` has no such field, so sending it would be a lie.
PLAN §9 lists the flag; CONTRACT-sessions.md §4 leaves `start` unchanged and
`SessionManager.start` takes no `no_container`. A request carrying it would
be accepted, ignored, and the session would get a container anyway — so the
CLI refuses and says which document disagrees with which.
"""
code, out, err = run(host_cli, ["session", "start", "foot", "--no-container"])
assert code == ExitCode.USAGE
assert sent == []
assert "not implemented" in err
assert out == ""
def test_start_without_the_flag_is_untouched(host_cli, sent):
sent.replies["start"] = {
"ok": True,
"id": "foot-aaaaaa",
"session": {"id": "foot-aaaaaa", "app": "foot", "pid": 1, "state": "ready"},
}
code, out, _ = run(host_cli, ["session", "start", "foot"])
assert code == ExitCode.OK
assert out == "foot-aaaaaa\n"
assert "no_container" not in sent.of("start")[0]
+288
View File
@@ -0,0 +1,288 @@
"""Running container plans against a compositor-shaped socket.
The compositor here is a real ``AF_UNIX`` listener laid out the way Hyprland
lays one out, answering the commands Hyprland answers. That proves the wiring
— the right commands, in the right order, and a record built from the reply
rather than from the request. It does **not** prove Hyprland agrees: see the
slice report for what is unverified.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from fakes import WINDOW_PID, FakeCompositor
from hhstreamd import containers
from hhstreamd.container_host import ContainerHost
from hhstreamd.ipc import CompositorUnavailable
@pytest.fixture
def compositor(short_tmpdir: Path):
fake = FakeCompositor(short_tmpdir)
try:
yield fake
finally:
fake.stop()
def make_host(fake: FakeCompositor, *, slots: int = 4) -> ContainerHost:
return ContainerHost(
fake.runtime_dir,
allocator=containers.WorkspaceAllocator(1000, slots),
signature=fake.signature,
)
def test_a_live_compositor_is_available_and_names_its_instance(compositor):
host = make_host(compositor)
assert host.available() is True
# The signature goes in the record so a restarted broker re-attaches to
# this instance rather than whichever one is there later.
assert host.signature == compositor.signature
def test_no_compositor_is_unavailable_and_says_why(short_tmpdir: Path):
host = ContainerHost(
short_tmpdir / "nothing-here",
allocator=containers.WorkspaceAllocator(1000, 2),
)
assert host.available() is False
assert host.last_error and "nothing-here" in host.last_error
def test_no_runtime_directory_at_all_is_unavailable_rather_than_an_error(short_tmpdir):
"""A broker with no `--compositor-runtime-dir` still has to start."""
host = ContainerHost(None, allocator=containers.WorkspaceAllocator(1000, 2))
assert host.available() is False
assert "no compositor runtime directory" in (host.last_error or "")
def test_create_runs_the_plan_in_order_and_the_output_appears(compositor):
host = make_host(compositor)
host.available()
plan = host.create("foot-aaaaaa", "hh-foot-aaaaaa")
assert plan.output == "hh-foot-aaaaaa"
assert plan.workspace == 1000
# The plan's own order, which is load-bearing: the output has to exist
# before a rule can name it, and the mode is set on an output that is
# already there.
queries = ("version", "clients", "monitors", "workspaces")
assert [c for c in compositor.commands if not c.startswith(queries)] == [
"output create headless hh-foot-aaaaaa",
"keyword workspace 1000, monitor:hh-foot-aaaaaa, default:true, persistent:true",
"keyword windowrule match:initial_class ^hh-foot-aaaaaa$, workspace 1000, "
"monitor hh-foot-aaaaaa",
"keyword monitor hh-foot-aaaaaa,1280x720,auto,1",
]
assert "hh-foot-aaaaaa" in compositor.outputs()
assert compositor.workspaces_on("hh-foot-aaaaaa") == [1000]
def test_the_quarantine_backstop_goes_in_before_any_container_rule(compositor):
"""Rules are applied in declaration order, so the catch-all must be first.
Installed after a session's anchored rule, the catch-all would override it
and sweep that session's own window into the special workspace — the exact
leak containers exist to prevent.
"""
host = make_host(compositor)
host.available()
assert host.install_quarantine() is True
host.create("foot-aaaaaa", "hh-foot-aaaaaa")
rules = [c for c in compositor.commands if c.startswith("keyword windowrule")]
assert rules[0] == "keyword windowrule match:initial_class .*, workspace special:quarantine"
assert rules[1].startswith("keyword windowrule match:initial_class ^hh-foot-aaaaaa$")
def test_a_blank_quarantine_workspace_installs_nothing(compositor):
host = ContainerHost(
compositor.runtime_dir,
allocator=containers.WorkspaceAllocator(1000, 2),
quarantine_workspace=" ",
)
host.available()
assert host.install_quarantine() is False
assert not [c for c in compositor.commands if c.startswith("keyword")]
def test_a_refused_command_is_reported_and_the_slot_is_given_back(compositor):
"""A half-built container must not also leak a workspace number."""
host = make_host(compositor)
host.available()
compositor.refuse.add("keyword monitor hh-foot-aaaaaa,1280x720,auto,1")
with pytest.raises(CompositorUnavailable) as exc:
host.create("foot-aaaaaa", "hh-foot-aaaaaa")
assert "refused" in str(exc.value)
assert host.allocator.in_use() == []
def test_read_back_reports_the_compositor_s_answer_not_ours(compositor):
host = make_host(compositor)
host.available()
host.create("foot-aaaaaa", "hh-foot-aaaaaa")
facts = host.read_back("hh-foot-aaaaaa")
assert facts is not None
assert facts.workspace == 1000
# The output is joined through the *workspace's* monitor name, because a
# client reports its monitor as a numeric index and `ipc.Monitor` carries
# no id to join that against (see the slice report).
assert facts.output == "hh-foot-aaaaaa"
assert facts.window["initial_class"] == "hh-foot-aaaaaa"
assert facts.window["stable_id"] == f"hh-foot-aaaaaa:{WINDOW_PID}"
# Titles contain commas; the client must not have lost the end of one.
assert facts.window["title"] == "a window, with a comma in its title"
def test_foreground_is_the_monitor_active_workspace_join(compositor):
"""Not the client's `visible` flag: "is anyone actually looking at this"."""
host = make_host(compositor)
host.available()
host.create("foot-aaaaaa", "hh-foot-aaaaaa")
assert host.read_back("hh-foot-aaaaaa").foreground is True
compositor.focus("hh-foot-aaaaaa", 9999)
assert host.read_back("hh-foot-aaaaaa").foreground is False
def test_no_window_yet_is_none_and_not_an_invented_one(compositor):
host = make_host(compositor)
host.available()
compositor.auto_window = False
host.create("foot-aaaaaa", "hh-foot-aaaaaa")
assert host.read_back("hh-foot-aaaaaa") is None
def test_a_window_that_kept_its_own_class_is_still_found_by_pid(compositor):
"""An application that ignored the stamp is observed, not pretended away."""
host = make_host(compositor)
host.available()
compositor.auto_window = False
host.create("foot-aaaaaa", "hh-foot-aaaaaa")
compositor.add_window("firefox", 1, "HEADLESS-1", pid=777)
facts = host.read_back("hh-foot-aaaaaa", pid=777)
assert facts is not None
assert facts.window["initial_class"] == "firefox"
# On the shared output, not the container's: the rule did not bind, and
# the caller is the one that has to say so.
assert facts.output == "HEADLESS-1"
def test_remove_takes_the_output_and_its_windows_with_it(compositor):
host = make_host(compositor)
host.available()
plan = host.create("foot-aaaaaa", "hh-foot-aaaaaa")
host.remove(plan.output)
assert "hh-foot-aaaaaa" not in compositor.outputs()
assert compositor.windows() == []
assert host.survivors("hh-foot-aaaaaa", plan.output) == []
def test_a_window_that_outlives_the_output_is_reported_as_a_survivor(compositor):
"""Teardown reports what is left rather than declaring success."""
host = make_host(compositor)
host.available()
host.create("foot-aaaaaa", "hh-foot-aaaaaa")
# A second window of ours that landed somewhere else entirely.
compositor.add_window("hh-foot-aaaaaa", 1, "HEADLESS-1", pid=999)
host.remove("hh-foot-aaaaaa")
survivors = host.survivors("hh-foot-aaaaaa", "hh-foot-aaaaaa")
assert [s["pid"] for s in survivors] == [999]
@pytest.mark.parametrize("name", ["HEADLESS-1", "hh-", "HH-x", "eDP-1", "hh-Foo"])
def test_remove_refuses_any_name_the_filter_rejects(compositor, name):
"""`contains_output` is the only thing between the scan and someone
else's monitor, so the removal path asks it too."""
host = make_host(compositor)
host.available()
with pytest.raises(ValueError) as exc:
host.remove(name)
assert "not one this broker creates" in str(exc.value)
def test_our_outputs_lists_only_names_this_broker_could_have_made(compositor):
host = make_host(compositor)
host.available()
host.create("foot-aaaaaa", "hh-foot-aaaaaa")
compositor.add_output("DP-1")
compositor.add_output("hh-orphan-zzzzzz")
assert host.our_outputs() == ["hh-foot-aaaaaa", "hh-orphan-zzzzzz"]
def test_reserve_re_takes_an_adopted_slot_so_it_is_not_handed_out_twice(compositor):
"""After a restart the records name workspaces that are still in use."""
host = make_host(compositor)
assert host.reserve([1002]) == [1002]
assert host.allocator.in_use() == [1002]
# The slots walked past on the way there were given back, so the next
# session still gets the lowest free one.
assert host.allocator.allocate() == 1000
def test_reserving_a_slot_this_allocator_already_holds_is_not_a_second_hunt(compositor):
"""Reconcile runs more than once; the second pass must be a no-op."""
host = make_host(compositor, slots=2)
assert host.reserve([1001]) == [1001]
assert host.reserve([1001]) == [1001]
assert host.allocator.in_use() == [1001]
assert host.allocator.allocate() == 1000
def test_reserve_is_a_no_op_for_a_session_that_never_had_a_slot(compositor):
host = make_host(compositor)
assert host.reserve([None, None]) == []
assert host.allocator.in_use() == []
def test_release_tolerates_a_slot_this_allocator_never_held(compositor):
"""Teardown runs for sessions started before the broker restarted too."""
host = make_host(compositor)
host.release(1003) # must not raise: the application is already dead
host.release(None)
assert host.allocator.in_use() == []
def test_a_plan_entry_that_is_not_hyprctl_is_a_bug_and_says_so(compositor):
host = make_host(compositor)
host.available()
with pytest.raises(ValueError) as exc:
host.dispatch(["sh", "-c", "rm -rf /"])
assert "not a hyprctl plan entry" in str(exc.value)
@@ -0,0 +1,296 @@
"""Start-up reconciliation: adopt what is ours, remove what is unattended.
A container is a render target that costs CPU and a place windows can land, so
one with no live session must never be left behind — and a broker that lost its
registry recovers by exactly this scan. The danger is the other direction: the
scan deletes outputs, so everything here is also a test that it deletes only
what :func:`hhstreamd.containers.contains_output` claims.
"""
from __future__ import annotations
import asyncio
import os
from pathlib import Path
import pytest
from fakes import FakeCompositor
from hhstreamd import procmon
from hhstreamd.clock import ManualClock
from hhstreamd.manager import ManagerConfig, SessionManager
from hhstreamd.policy import Policy
from hhstreamd.registry import ContainerState, Session, State, container_record
def make_session(session_id: str, *, output: str | None, workspace: int | None, **kwargs) -> Session:
return Session(
id=session_id,
app="foot",
argv=["/usr/bin/foot"],
pid=4242,
pgid=4242,
sid=4242,
pid_starttime=1,
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=output,
workspace=workspace,
mode=(1280, 720),
created_by="broker",
state=ContainerState.OWNED,
),
**kwargs,
)
@pytest.fixture
def compositor(short_tmpdir: Path):
fake = FakeCompositor(short_tmpdir)
try:
yield fake
finally:
fake.stop()
@pytest.fixture
def manager(short_tmpdir: Path, compositor: FakeCompositor) -> SessionManager:
return SessionManager(
ManagerConfig(
state_dir=short_tmpdir / "state",
runtime_dir=short_tmpdir / "run",
policy=Policy(),
compositor_runtime_dir=compositor.runtime_dir,
signature=compositor.signature,
),
clock=ManualClock(boottime=1000.0),
)
def test_an_unattended_output_is_removed_at_start_up(manager, compositor):
compositor.add_output("hh-ghost-aaaaaa")
summary = manager.reconcile_containers()
assert summary["removed"] == ["hh-ghost-aaaaaa"]
assert "hh-ghost-aaaaaa" not in compositor.outputs()
@pytest.mark.parametrize("name", ["HEADLESS-1", "DP-1", "hh-", "hh-Upper", "hhother"])
def test_an_output_the_filter_rejects_is_never_touched(manager, compositor, name):
"""The one thing between this scan and somebody else's monitor."""
compositor.add_output(name)
summary = manager.reconcile_containers()
assert summary["removed"] == []
assert name in compositor.outputs()
def test_a_container_with_a_live_session_is_adopted_not_removed(manager, compositor):
compositor.add_output("hh-foot-aaaaaa")
manager.registry.add(
make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1002,
signature=compositor.signature)
)
summary = manager.reconcile_containers()
assert summary["adopted"] == [{"id": "foot-aaaaaa", "output": "hh-foot-aaaaaa"}]
assert summary["removed"] == []
assert "hh-foot-aaaaaa" in compositor.outputs()
def test_an_adopted_workspace_is_not_handed_to_the_next_session(manager, compositor):
"""After a restart the records name slots that are still in use."""
compositor.add_output("hh-foot-aaaaaa")
manager.registry.add(
make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000,
signature=compositor.signature)
)
manager.reconcile_containers()
assert manager.host.allocator.in_use() == [1000]
assert manager.host.create("foot-bbbbbb", "hh-foot-bbbbbb").workspace == 1001
def test_a_record_naming_an_output_that_is_gone_is_marked_orphan(manager, compositor):
"""The application may still be running, so nothing is killed for this."""
session = manager.registry.add(
make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000,
signature=compositor.signature)
)
summary = manager.reconcile_containers()
assert session.container["state"] == ContainerState.ORPHAN
assert summary["orphaned"] == [{"id": "foot-aaaaaa", "output": "hh-foot-aaaaaa"}]
assert session.live, "losing a container is not losing the session"
def test_a_container_from_a_previous_compositor_instance_is_not_claimed(manager, compositor):
"""This is what the recorded signature is for.
The output name would match, and adopting it would hand this broker a
container that died with its compositor — and reserve a workspace slot in
an instance that never allocated one.
"""
compositor.add_output("hh-foot-aaaaaa")
session = manager.registry.add(
make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000,
signature="an-older-instance")
)
summary = manager.reconcile_containers()
assert session.container["state"] == ContainerState.ORPHAN
assert summary["orphaned"] == [{"id": "foot-aaaaaa", "why": "signature_changed"}]
# Unclaimed, so the scan takes it down like any other unattended output.
assert summary["removed"] == ["hh-foot-aaaaaa"]
assert manager.host.allocator.in_use() == []
def test_the_quarantine_backstop_is_installed_before_anything_else(manager, compositor):
manager.reconcile_containers()
keywords = [c for c in compositor.commands if c.startswith("keyword")]
assert keywords[0].startswith("keyword windowrule match:initial_class .*,")
def test_no_compositor_leaves_the_broker_degraded_rather_than_refusing(short_tmpdir: Path):
manager = SessionManager(
ManagerConfig(
state_dir=short_tmpdir / "state",
runtime_dir=short_tmpdir / "run",
policy=Policy(),
compositor_runtime_dir=short_tmpdir / "no-compositor",
),
clock=ManualClock(boottime=1000.0),
)
summary = manager.reconcile_containers()
assert summary["available"] is False
assert summary["removed"] == []
assert manager.containers_available is False
assert "no-compositor" in summary["error"]
def test_container_list_will_not_claim_there_are_no_orphans_without_looking(short_tmpdir):
"""`[]` would read as "nothing is out there", which we cannot know."""
manager = SessionManager(
ManagerConfig(
state_dir=short_tmpdir / "state",
runtime_dir=short_tmpdir / "run",
policy=Policy(),
compositor_runtime_dir=short_tmpdir / "no-compositor",
),
clock=ManualClock(boottime=1000.0),
)
manager.reconcile_containers()
listing = manager.container_list()
assert listing["orphans"] is None
assert listing["compositor"] == "absent"
def test_container_list_names_the_orphans_it_can_see(manager, compositor):
compositor.add_output("hh-ghost-aaaaaa")
manager.containers_available = True
manager.registry.add(
make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000,
signature=compositor.signature)
)
compositor.add_output("hh-foot-aaaaaa")
listing = manager.container_list()
assert listing["orphans"] == ["hh-ghost-aaaaaa"]
assert [row["id"] for row in listing["containers"]] == ["foot-aaaaaa"]
# Listing is not acting: the orphan is still there afterwards.
assert "hh-ghost-aaaaaa" in compositor.outputs()
def test_gc_takes_down_the_container_of_a_session_it_tombstones(manager, compositor):
"""`gc` is the last thing that will ever look at that session.
It tombstones a record whose process vanished without the watcher
noticing; if it did not also take the output down, nothing else would,
until the next broker start-up found it unattended.
"""
compositor.add_output("hh-foot-aaaaaa")
session = manager.registry.add(
make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000,
signature=compositor.signature)
)
manager.reconcile_containers() # adopts it, and reserves its slot
# A pid that is not a process: what `gc` is for.
session.pid = session.pgid = session.sid = 4_194_303
result = asyncio.run(manager.gc())
entry = {row["id"]: row for row in result["reconciled"]}["foot-aaaaaa"]
assert entry["container_removed"] is True
assert entry["container_survivors"] == []
assert "hh-foot-aaaaaa" not in compositor.outputs()
assert session.container["state"] == ContainerState.REMOVED
assert manager.host.allocator.in_use() == [], "the slot came back"
def test_gc_leaves_a_healthy_session_s_container_alone(manager, compositor):
compositor.add_output("hh-foot-aaaaaa")
session = manager.registry.add(
make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000,
signature=compositor.signature)
)
manager.reconcile_containers()
# This process: alive, and its own identity.
identity = procmon.identity(os.getpid())
session.pid, session.pgid, session.sid = os.getpid(), identity.pgid, identity.sid
session.pid_starttime = identity.starttime
session.cmdline_sha256 = identity.cmdline_sha256
asyncio.run(manager.gc())
assert "hh-foot-aaaaaa" in compositor.outputs()
assert session.container["state"] == ContainerState.OWNED
def test_reconciling_everything_rescans_the_outputs_and_every_session(manager, compositor):
"""`container.reconcile` with no id is the start-up scan, on demand."""
compositor.add_output("hh-foot-aaaaaa")
session = manager.registry.add(
make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000,
signature=compositor.signature)
)
manager.reconcile_containers()
compositor.add_output("hh-ghost-aaaaaa")
compositor.add_window("hh-foot-aaaaaa", 1000, "hh-foot-aaaaaa")
result = asyncio.run(manager.container_reconcile(None))
assert result["scan"]["removed"] == ["hh-ghost-aaaaaa"]
assert result["scan"]["adopted"] == [{"id": "foot-aaaaaa", "output": "hh-foot-aaaaaa"}]
# The window that appeared while nobody was looking is now in the record.
assert session.window["initial_class"] == "hh-foot-aaaaaa"
assert {d["field"] for d in result["diff"]} == {"workspace", "window"}
# The slot stays reserved across a second scan rather than being hunted
# for again in a band it is itself occupying.
assert manager.host.allocator.in_use() == [1000]
+222
View File
@@ -0,0 +1,222 @@
"""The broker's end of the driver socket, against a real driver socket.
Every test here goes over an actual ``AF_UNIX`` connection to the shipped
:class:`hhstream_pointer.server.PointerServer` running the shipped
:class:`hhstream_pointer.ops.Dispatcher`. Only the Wayland sink is a
recorder. Mocking the socket would have tested that this module can call
``json.dumps``; what it has to be right about is the half of the protocol it
does not own.
"""
from __future__ import annotations
import socket
import threading
from pathlib import Path
import pytest
from fakes import FakeDriver
from hhstream_pointer.backend import CompositorUnavailable as DriverDied
from hhstream_pointer.backend import OutputUnknown
from hhstreamd.driver import DriverRejected, DriverUnavailable, PointerDriver
@pytest.fixture
def driver(short_tmpdir: Path):
fake = FakeDriver(short_tmpdir / "p.sock")
client = PointerDriver(fake.socket_path, timeout_s=5.0)
try:
yield client, fake
finally:
client.close()
fake.stop()
def test_a_warp_reaches_the_sink_as_output_local_coordinates(driver):
client, fake = driver
client.warp("hh-a", 0.25, 0.75)
assert fake.sink.calls == [("warp", "hh-a", 0.25, 0.75)]
def test_a_gesture_arrives_in_order_and_is_committed_by_a_frame(driver):
"""Nothing the driver is sent reaches the compositor until a frame."""
client, fake = driver
client.warp("hh-a", 0.5, 0.5)
client.button("left", "down")
client.button("left", "up")
client.frame()
assert fake.sink.calls == [
("warp", "hh-a", 0.5, 0.5),
("button", "hh-a", 0x110, 1),
("button", "hh-a", 0x110, 0),
("frame", "hh-a"),
]
def test_pressed_reports_what_the_driver_believes_is_down(driver):
client, _ = driver
client.warp("hh-a", 0.5, 0.5)
assert client.pressed() == []
client.button("right", "down")
client.button("middle", "down")
assert client.pressed() == ["right", "middle"]
client.button("right", "up")
assert client.pressed() == ["middle"]
def test_release_all_lifts_everything_and_says_what_it_lifted(driver):
client, fake = driver
client.warp("hh-a", 0.5, 0.5)
client.button("left", "down")
client.button("right", "down")
assert client.release_all() == ["left", "right"]
assert client.pressed() == []
# Lifted through the pointer each went down on, then one frame for it.
assert fake.sink.calls[-3:] == [
("button", "hh-a", 0x110, 0),
("button", "hh-a", 0x111, 0),
("frame", "hh-a"),
]
def test_release_all_on_an_idle_driver_is_an_empty_list_not_an_error(driver):
"""The expiry path calls this unconditionally; it must be safe."""
client, _ = driver
assert client.release_all() == []
def test_a_refusal_is_carried_back_and_is_not_a_lost_connection(driver):
"""``ok: false`` is the driver working, so the client must stay usable."""
client, fake = driver
with pytest.raises(DriverRejected) as exc:
client.warp("hh-a", 1.5, 0.5)
assert "0..1" in str(exc.value)
client.warp("hh-a", 0.5, 0.5)
assert fake.sink.calls == [("warp", "hh-a", 0.5, 0.5)]
def test_a_button_before_any_warp_is_refused_rather_than_aimed_at_nothing(driver):
client, _ = driver
with pytest.raises(DriverRejected) as exc:
client.button("left", "down")
assert "warp" in str(exc.value)
def test_an_unknown_output_is_a_refusal_and_leaves_the_driver_usable(driver):
"""Routine: the broker can be racing a container it just tore down."""
client, fake = driver
fake.sink.fail = OutputUnknown("no output hh-gone")
with pytest.raises(DriverRejected) as exc:
client.warp("hh-gone", 0.5, 0.5)
assert "hh-gone" in str(exc.value)
fake.sink.fail = None
client.warp("hh-a", 0.5, 0.5)
assert fake.sink.of("warp") == [("warp", "hh-a", 0.5, 0.5)]
def test_a_driver_that_dies_mid_gesture_is_unavailable_not_a_refusal(driver):
"""A lost compositor takes the driver's connection with it (by design).
The broker has to be able to tell this from a refusal, because the cursor
is now in an unknown state and the lease has to go rather than carry on.
"""
client, fake = driver
fake.sink.fail = DriverDied("the compositor hung up")
with pytest.raises(DriverUnavailable):
client.warp("hh-a", 0.5, 0.5)
def test_no_driver_at_all_is_unavailable_and_never_a_silent_no_op(short_tmpdir: Path):
client = PointerDriver(short_tmpdir / "absent.sock", timeout_s=0.5)
with pytest.raises(DriverUnavailable) as exc:
client.release_all()
assert "absent.sock" in str(exc.value)
def test_a_driver_that_restarts_is_reconnected_to_rather_than_lost(short_tmpdir: Path):
"""The held connection dies with the driver; the next verb must not."""
path = short_tmpdir / "p.sock"
first = FakeDriver(path)
client = PointerDriver(path, timeout_s=5.0)
client.warp("hh-a", 0.1, 0.1)
first.stop()
second = FakeDriver(path)
try:
client.warp("hh-a", 0.2, 0.2)
assert second.sink.calls == [("warp", "hh-a", 0.2, 0.2)]
finally:
client.close()
second.stop()
def test_a_driver_that_answers_nothing_is_unavailable_within_the_timeout(short_tmpdir: Path):
"""A wedged driver must time out, not hang the verb that called it."""
path = short_tmpdir / "mute.sock"
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
listener.bind(str(path))
listener.listen(1)
accepted: list[socket.socket] = []
def accept_and_say_nothing() -> None:
conn, _ = listener.accept()
accepted.append(conn)
thread = threading.Thread(target=accept_and_say_nothing, daemon=True)
thread.start()
client = PointerDriver(path, timeout_s=0.3)
try:
with pytest.raises(DriverUnavailable):
client.pressed()
finally:
client.close()
thread.join(timeout=5.0)
for conn in accepted:
conn.close()
listener.close()
def test_a_reply_that_is_not_the_protocol_is_unavailable_not_an_empty_answer(
short_tmpdir: Path,
):
""""I could not read the answer" must never render as "nothing was down"."""
path = short_tmpdir / "liar.sock"
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
listener.bind(str(path))
listener.listen(1)
def answer_nonsense() -> None:
conn, _ = listener.accept()
with conn:
conn.recv(4096)
conn.sendall(b'{"ok":true,"buttons":"left"}\n')
thread = threading.Thread(target=answer_nonsense, daemon=True)
thread.start()
client = PointerDriver(path, timeout_s=2.0)
try:
with pytest.raises(DriverUnavailable) as exc:
client.pressed()
assert "list of button names" in str(exc.value)
finally:
client.close()
thread.join(timeout=5.0)
listener.close()
+36 -1
View File
@@ -21,6 +21,8 @@ def test_the_frozen_numbers():
assert ExitCode.POLICY == 6
assert ExitCode.TIMEOUT == 7
assert ExitCode.BUSY == 8
assert ExitCode.NO_LEASE == 9
assert ExitCode.COMPOSITOR == 10
# 1 is deliberately absent: it is the shell's "something went wrong", and
# reusing it would make an unhandled crash indistinguishable from a
# documented outcome.
@@ -61,6 +63,17 @@ def test_the_frozen_numbers():
# 8 — busy
("busy", 8),
("already_managed", 8),
("pointer_busy", 8),
# 9 — the verb needs the lease and this session does not hold it
("no_lease", 9),
# 10 — the compositor side failed; the session itself survives
("compositor", 10),
("compositor_unavailable", 10),
("no_container", 10),
("driver_unavailable", 10),
("driver_refused", 10),
# 6 — the container band is full: a budget, not a compositor failure
("container_budget", 6),
],
)
def test_every_error_name_maps_to_its_documented_code(error, code):
@@ -77,7 +90,9 @@ def test_the_table_has_no_entries_this_test_does_not_know_about():
"bad_state", "pid_reuse_detected", "identity_unknown",
"daemon_unreachable", "not_allowlisted",
"argument_refused", "session_cap_reached", "refused", "timeout",
"readiness_timeout", "busy", "already_managed",
"readiness_timeout", "busy", "already_managed", "pointer_busy",
"container_budget", "no_lease", "compositor", "compositor_unavailable",
"no_container", "driver_unavailable", "driver_refused",
}
assert set(EXIT_CODE_FOR_ERROR) == documented
@@ -87,6 +102,26 @@ def test_success_is_zero():
assert exit_code_for("") == 0
def test_losing_the_compositor_is_not_the_same_as_losing_the_session():
"""Code 10 exists precisely so these two cannot be confused (PLAN §8.2).
A session whose container could not be built is still running; one that
exited is not. An agent that saw the same code for both would kill a
healthy application to recover from a compositor hiccup.
"""
assert exit_code_for("compositor") == ExitCode.COMPOSITOR
assert exit_code_for("session_exited") == ExitCode.BAD_STATE
assert ExitCode.COMPOSITOR != ExitCode.BAD_STATE
def test_a_missing_lease_and_a_held_one_are_different_codes():
"""8 means "wait", 9 means "acquire". One code could not say both."""
assert exit_code_for("pointer_busy") == ExitCode.BUSY
assert exit_code_for("no_lease") == ExitCode.NO_LEASE
def test_an_unknown_error_degrades_to_not_usable_rather_than_to_success():
"""A caller that does not recognise the failure must still not see a 0."""
+592
View File
@@ -0,0 +1,592 @@
"""The pointer verbs: the lease, the bookmark, and never leaving a button down.
The broker end is real (the manager, the lease, the driver client) and so is
the driver end (the shipped dispatcher and server over a real ``AF_UNIX``
socket). Only the Wayland sink and the clock are substituted — the clock
because expiry has to be testable without sleeping for thirty seconds, and the
sink because this machine has no compositor.
"""
from __future__ import annotations
import asyncio
from pathlib import Path
import pytest
from fakes import FakeDriver
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
LEFT = 0x110
DOWN, UP = 1, 0
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 Harness:
def __init__(self, manager: SessionManager, fake: FakeDriver, clock: ManualClock) -> None:
self.manager = manager
self.fake = fake
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):
fake = FakeDriver(short_tmpdir / "p.sock")
clock = ManualClock(boottime=1000.0)
manager = SessionManager(
ManagerConfig(
state_dir=short_tmpdir / "state",
runtime_dir=short_tmpdir / "run",
policy=Policy(),
pointer_socket=fake.socket_path,
pointer_ttl_s=30.0,
pointer_max_s=300.0,
),
clock=clock,
)
try:
yield Harness(manager, fake, clock)
finally:
if manager.driver is not None:
manager.driver.close()
fake.stop()
# ---------------------------------------------------------------------------
# acquiring
# ---------------------------------------------------------------------------
def test_acquire_with_no_bookmark_aims_at_the_centre_of_the_container(harness):
harness.add()
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert reply["lease_id"]
assert reply["bookmark"] == {
"x": 0.5,
"y": 0.5,
"output": "hh-foot-aaaaaa",
"at": reply["bookmark"]["at"],
}
assert harness.fake.sink.calls == [
("warp", "hh-foot-aaaaaa", 0.5, 0.5),
("frame", "hh-foot-aaaaaa"),
]
def test_acquire_restores_the_position_the_session_was_left_at(harness):
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.25, y=0.75))
harness.run(harness.manager.pointer_release("foot-aaaaaa", lease))
harness.fake.sink.calls.clear()
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.25, 0.75)
assert harness.fake.sink.of("warp") == [("warp", "hh-foot-aaaaaa", 0.25, 0.75)]
assert session.pointer["bookmark"]["x"] == 0.25
def test_restore_false_goes_to_the_centre_even_with_a_bookmark(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.1, y=0.1))
harness.run(harness.manager.pointer_release("foot-aaaaaa", lease))
harness.fake.sink.calls.clear()
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa", restore=False))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.5, 0.5)
def test_a_bookmark_from_another_output_is_not_a_position_in_this_one(harness):
"""A container is rebuilt with a new name; the old fraction is not a place."""
session = harness.add()
session.pointer = {
"bookmark": {"x": 0.9, "y": 0.9, "output": "hh-gone", "at": "2026-01-01T00:00:00Z"},
"last_released_at": None,
"released_by": None,
}
reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.5, 0.5)
def test_a_second_session_is_told_who_holds_the_cursor(harness):
"""There is one cursor, so the answer is "wait", with a name attached."""
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("foot-bbbbbb"))
assert exc.value.error == "pointer_busy"
assert exit_code_for(exc.value.error) == ExitCode.BUSY
assert exc.value.fields["holder"] == "foot-aaaaaa"
def test_a_session_with_no_container_has_nowhere_to_aim(harness):
"""Aiming at "wherever the cursor is" is how a click lands next door."""
harness.add("foot-aaaaaa", container=False)
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert exc.value.error == "no_container"
assert exit_code_for(exc.value.error) == ExitCode.COMPOSITOR
def test_a_lease_that_could_not_be_aimed_is_not_left_held(harness):
harness.add()
harness.fake.stop()
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert exc.value.error == "driver_unavailable"
assert exit_code_for(exc.value.error) == ExitCode.COMPOSITOR
assert harness.manager.pointer.state()["holder"] is None
# ---------------------------------------------------------------------------
# moving
# ---------------------------------------------------------------------------
def test_every_move_writes_the_bookmark_to_the_record(harness):
"""So a broker that dies mid-gesture still leaves the last real position."""
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
for x in (0.1, 0.2, 0.3):
reply = harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=x, y=0.5))
assert reply["bookmark"]["x"] == x
assert session.pointer["bookmark"]["x"] == x
# And in the lease, which is what `release` reports.
outcome = harness.manager.pointer.release("foot-aaaaaa", lease, "test")
assert outcome.bookmark.x == 0.3
def test_a_relative_move_is_applied_to_the_bookmark_and_clamped(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
reply = harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, dx=0.25, dy=-0.25))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.75, 0.25)
# Running into the edge of the screen is what a mouse does.
reply = harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, dx=5.0, dy=-5.0))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (1.0, 0.0)
@pytest.mark.parametrize("bad", [1.4, -0.1, "0.5", True, None])
def test_an_absolute_coordinate_outside_the_frame_is_a_usage_error(harness, bad):
"""A caller that computed 1.4 has a bug; clamping it would hide it."""
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=bad, y=0.5))
assert exc.value.error == "invalid_argument"
def test_moving_without_the_lease_is_nine_and_not_eight(harness):
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_move("foot-bbbbbb", lease, x=0.5, y=0.5))
assert exc.value.error == "no_lease"
assert exit_code_for(exc.value.error) == ExitCode.NO_LEASE
def test_a_stale_lease_id_is_refused_even_for_the_holder(harness):
harness.add()
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_move("foot-aaaaaa", "not-the-lease", x=0.5, y=0.5))
assert exc.value.error == "no_lease"
# ---------------------------------------------------------------------------
# buttons
# ---------------------------------------------------------------------------
def test_a_button_goes_down_and_up_through_the_driver(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
assert harness.run(
harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down")
)["buttons"] == ["left"]
assert harness.run(
harness.manager.pointer_button("foot-aaaaaa", lease, "left", "up")
)["buttons"] == []
assert harness.fake.sink.calls == [
("button", "hh-foot-aaaaaa", LEFT, DOWN),
("frame", "hh-foot-aaaaaa"),
("button", "hh-foot-aaaaaa", LEFT, UP),
("frame", "hh-foot-aaaaaa"),
]
def test_a_click_is_a_press_and_a_release_each_committed(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
reply = harness.run(harness.manager.pointer_click("foot-aaaaaa", lease, "left", 2))
assert reply["count"] == 2
assert harness.fake.sink.calls == [
("button", "hh-foot-aaaaaa", LEFT, DOWN),
("frame", "hh-foot-aaaaaa"),
("button", "hh-foot-aaaaaa", LEFT, UP),
("frame", "hh-foot-aaaaaa"),
] * 2
assert harness.manager.pointer.pressed() == []
@pytest.mark.parametrize("bad", [0, 99, "two", True, 1.5])
def test_a_click_count_off_the_wire_is_bounded(harness, bad):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_click("foot-aaaaaa", lease, "left", bad))
assert exc.value.error == "invalid_argument"
def test_an_unknown_button_is_refused_by_the_driver_not_invented(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "pinky", "down"))
assert exc.value.error == "driver_refused"
assert harness.manager.pointer.pressed() == [], "a refused press must not be mirrored"
# ---------------------------------------------------------------------------
# releasing and expiry
# ---------------------------------------------------------------------------
def test_release_lifts_what_was_down_and_stamps_the_record(harness):
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.4, y=0.6))
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
reply = harness.run(harness.manager.pointer_release("foot-aaaaaa", lease))
assert reply["buttons_lifted"] == ["left"]
assert reply["released_by"] == "lease"
assert reply["bookmark"]["x"] == 0.4
assert session.pointer["released_by"] == "lease"
assert session.pointer["last_released_at"] == reply["released_at"]
assert harness.manager.pointer.state()["holder"] is None
def test_an_idle_lease_expires_and_the_button_it_left_down_is_lifted(harness):
"""The order is the contract's: `pressed()` is read before `expire()`,
because `expire()` drops the lease's button set with the lease."""
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
harness.clock.advance(31.0)
expired = harness.run(harness.manager._expire_pointer())
assert expired == {
"session": "foot-aaaaaa",
"lease_id": lease,
"buttons_lifted": ["left"],
}
assert harness.manager.pointer.state()["holder"] is None
assert harness.fake.sink.calls[-2:] == [
("button", "hh-foot-aaaaaa", LEFT, UP),
("frame", "hh-foot-aaaaaa"),
]
assert session.pointer["released_by"] == "timeout"
def test_an_expired_lease_is_noticed_by_the_next_verb_as_well(harness):
"""So the cursor is free for someone else even with no sweep in between."""
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
harness.clock.advance(31.0)
reply = harness.run(harness.manager.pointer_acquire("foot-bbbbbb"))
assert reply["id"] == "foot-bbbbbb"
assert harness.manager.pointer.state()["holder"] == "foot-bbbbbb"
def test_a_refresh_loop_still_loses_the_cursor_at_the_hard_cap(harness):
"""A stuck agent must not be able to hold the mouse forever."""
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
for _ in range(12):
harness.clock.advance(25.0)
try:
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.5, y=0.5))
except ManagerError as exc:
assert exc.error == "no_lease"
break
else: # pragma: no cover - the cap did not fire
pytest.fail("the hard cap never expired the lease")
assert harness.manager.pointer.state()["holder"] is None
def test_a_caller_supplied_ttl_applies_to_this_lease_and_then_goes_away(harness):
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
harness.run(harness.manager.pointer_acquire("foot-aaaaaa", ttl_s=5.0))
harness.clock.advance(6.0)
assert harness.run(harness.manager._expire_pointer()) is not None
assert harness.manager.pointer.ttl_s == 30.0, "the default must come back"
harness.run(harness.manager.pointer_acquire("foot-bbbbbb"))
harness.clock.advance(6.0)
assert harness.run(harness.manager._expire_pointer()) is None
def test_a_ttl_beyond_the_hard_cap_is_refused(harness):
harness.add()
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("foot-aaaaaa", ttl_s=10_000))
assert exc.value.error == "invalid_argument"
assert harness.manager.pointer.state()["holder"] is None
def test_expiry_with_no_driver_is_loud_rather_than_silent(harness, caplog):
"""A button we could not lift is the one thing that must never be quiet."""
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
harness.fake.stop()
harness.clock.advance(31.0)
with caplog.at_level("ERROR"):
harness.run(harness.manager._expire_pointer())
assert "a button may still be down" in caplog.text
assert harness.manager.pointer.state()["holder"] is None
# ---------------------------------------------------------------------------
# the rest of the contract
# ---------------------------------------------------------------------------
def test_no_pointer_verb_counts_as_activity(harness):
"""A session being clicked in is still one nobody has asked to keep."""
session = harness.add()
before = (session.last_activity_boottime, session.command_count)
harness.clock.advance(100.0)
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.5, y=0.5))
harness.run(harness.manager.pointer_click("foot-aaaaaa", lease))
harness.manager.pointer_state()
harness.run(harness.manager.pointer_release("foot-aaaaaa", lease))
assert (session.last_activity_boottime, session.command_count) == before
def test_pointer_state_names_the_holder_and_what_is_down(harness):
harness.add()
assert harness.manager.pointer_state()["holder"] is None
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "right", "down"))
state = harness.manager.pointer_state()
assert state["holder"] == "foot-aaaaaa"
assert state["lease_id"] == lease
assert state["buttons"] == ["right"]
assert state["bookmark"]["output"] == "hh-foot-aaaaaa"
def test_a_dead_session_cannot_be_aimed_at(harness):
session = harness.add()
harness.manager.registry.terminate(session, State.EXITED)
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
assert exc.value.error == "session_exited"
def test_an_unknown_session_is_three_not_a_lease_error(harness):
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_acquire("nope-zzzzzz"))
assert exit_code_for(exc.value.error) == ExitCode.NO_SUCH_SESSION
def test_no_driver_configured_at_all_is_reported_as_unavailable(short_tmpdir: Path):
manager = SessionManager(
ManagerConfig(
state_dir=short_tmpdir / "state",
runtime_dir=short_tmpdir / "run",
policy=Policy(),
# Explicitly nothing, rather than the derived default.
pointer_socket=short_tmpdir / "no-driver-here.sock",
),
clock=ManualClock(boottime=1000.0),
)
manager.registry.add(make_session())
with pytest.raises(ManagerError) as exc:
asyncio.run(manager.pointer_acquire("foot-aaaaaa"))
assert exc.value.error == "driver_unavailable"
def test_releasing_with_someone_elses_lease_lifts_nothing(harness):
"""The refusal has to come before anything reaches the driver.
Otherwise ``pointer.release`` is a way for any session to drop the
holder's buttons mid-drag on its way to being told no.
"""
harness.add("foot-aaaaaa")
harness.add("foot-bbbbbb")
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down"))
harness.fake.sink.calls.clear()
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_release("foot-bbbbbb", lease))
assert exc.value.error == "no_lease"
assert harness.fake.sink.calls == []
assert harness.manager.pointer.pressed() == ["left"]
assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa"
def test_a_stale_lease_id_cannot_release_the_current_one(harness):
harness.add()
first = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.run(harness.manager.pointer_release("foot-aaaaaa", first))
second = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_release("foot-aaaaaa", first))
assert exc.value.error == "no_lease"
assert harness.manager.pointer.state()["lease_id"] == second
def test_the_sweeper_expires_a_lease_nobody_came_back_for(short_tmpdir: Path):
"""The TTL is only a promise if something checks it unprompted.
An agent that acquired, pressed a button and died would otherwise hold the
cursor — with the button down — until some other session happened to try.
"""
fake = FakeDriver(short_tmpdir / "p.sock")
clock = ManualClock(boottime=1000.0)
manager = SessionManager(
ManagerConfig(
state_dir=short_tmpdir / "state",
runtime_dir=short_tmpdir / "run",
policy=Policy(),
pointer_socket=fake.socket_path,
pointer_ttl_s=30.0,
# Short, so the test waits on the sweep and not on the TTL; the
# TTL itself is the injected clock's business.
pointer_sweep_s=0.01,
),
clock=clock,
)
session = manager.registry.add(make_session())
async def scenario():
lease = (await manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
await manager.pointer_button("foot-aaaaaa", lease, "left", "down")
sweeper = asyncio.create_task(manager._sweep_pointer())
clock.advance(31.0)
for _ in range(500):
await asyncio.sleep(0.01)
if manager.pointer.state()["holder"] is None:
break
sweeper.cancel()
with pytest.raises(asyncio.CancelledError):
await sweeper
try:
asyncio.run(scenario())
assert manager.pointer.state()["holder"] is None
assert fake.dispatcher._pressed == {}, "the sweep lifted it on the driver"
assert session.pointer["released_by"] == "timeout"
finally:
if manager.driver is not None:
manager.driver.close()
fake.stop()
+104 -1
View File
@@ -11,11 +11,15 @@ import pytest
from hhstreamd.clock import ManualClock
from hhstreamd.registry import (
ContainerState,
Registry,
Session,
State,
atomic_write_json,
container_record,
migrate,
mint_id,
pointer_record,
)
@@ -267,4 +271,103 @@ 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"] == 2
assert public["schema"] == 3
# ---------------------------------------------------------------------------
# schema 3: the container, the pointer and the instance signature (PLAN §7)
# ---------------------------------------------------------------------------
def test_a_record_with_no_container_says_so_and_does_not_hint(registry: Registry):
"""`null` is "no spatial container", never "unknown but probably something"."""
session = registry.add(make_session())
public = session.public(now=1000.0)
assert public["container"] is None
assert public["pointer"] is None, "absent means the pointer was never used here"
assert public["signature"] is None
def test_the_container_sub_record_keeps_every_unverified_field_null():
"""Degraded has a *state* long before it has an output to name."""
degraded = container_record(
output=None, workspace=None, mode=None, created_by="broker", state=ContainerState.DEGRADED
)
assert degraded == {
"output": None,
"workspace": None,
"mode": None,
"created_by": "broker",
"state": "degraded",
}
def test_a_container_record_round_trips_through_the_mirror(tmp_path: Path):
registry = Registry(tmp_path, ManualClock(boottime=1000.0))
registry.ensure_dirs()
session = make_session(
container=container_record(
output="hh-foot-aaaaaa",
workspace=1003,
mode=(1280, 720),
created_by="broker",
state=ContainerState.OWNED,
),
pointer=pointer_record(
bookmark={"x": 0.42, "y": 0.61, "output": "hh-foot-aaaaaa", "at": "2026-10-01T09:14:02Z"},
last_released_at="2026-10-01T09:20:00Z",
released_by="lease",
),
signature="efb5deadbeef",
)
registry.add(session)
(restored,), quarantined = Registry(tmp_path, ManualClock()).load_records()
assert quarantined == []
assert restored.container["output"] == "hh-foot-aaaaaa"
assert restored.container["mode"] == {"width": 1280, "height": 720}
assert restored.pointer["bookmark"]["x"] == 0.42
assert restored.signature == "efb5deadbeef"
def test_a_schema_two_record_is_adopted_and_not_rejected(tmp_path: Path):
"""Its application is still running; refusing the record would strand it."""
registry = Registry(tmp_path, ManualClock(boottime=1000.0))
registry.ensure_dirs()
old = make_session().to_dict()
for gone in ("container", "pointer", "signature"):
del old[gone]
old["schema"] = 2
atomic_write_json(registry.record_path("foot-aaaaaa"), old)
(restored,), quarantined = registry.load_records()
assert quarantined == []
assert restored.id == "foot-aaaaaa"
assert restored.schema == 3
# 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)
def test_migrating_never_overwrites_a_field_that_was_already_there():
"""Only ever additive: the field is new to the schema, not to the session."""
migrated = migrate({"schema": 2, "id": "a", "container": {"state": "owned"}})
assert migrated["container"] == {"state": "owned"}
assert migrated["schema"] == 3
def test_a_record_from_a_newer_schema_is_read_not_guessed_at(caplog):
with caplog.at_level("ERROR"):
migrated = migrate({"schema": 99, "id": "a"})
assert migrated["schema"] == 99, "its number is not ours to rewrite"
assert "newer than this daemon" in caplog.text
+1 -1
View File
@@ -31,7 +31,7 @@ for _path in (str(_HERE), str(_SRC)):
from hhstream.server import FrameServer # noqa: E402 (needs sys.path above)
#: The path named in docs/CONTRACT.md and in the module's option default.
CONTRACT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
CONTRACT_SOCKET = "/run/hypr-stream/stream.sock"
# AF_UNIX addresses are capped near 108 bytes; a long tmp_path would fail with a
# confusing OSError instead of the assertion the test is about.
+1 -1
View File
@@ -54,7 +54,7 @@ def wait_for_socket(path: str, proc: subprocess.Popen, timeout: float = 10.0) ->
def test_server_defaults_match_the_contract():
args = server.build_parser().parse_args([])
assert args.socket == "/run/hyprland-headless-stream/stream.sock"
assert args.socket == "/run/hypr-stream/stream.sock"
assert (args.fps, args.format, args.capture_command) == (30, "png", None)
assert server.DEFAULT_CAPTURE_COMMAND == ["grim", "-t", "png", "-"]
+1 -1
View File
@@ -134,7 +134,7 @@ def test_main_rejects_a_negative_count(sock_path, capsys):
def test_default_socket_matches_the_contract():
assert client.DEFAULT_SOCKET == "/run/hyprland-headless-stream/stream.sock"
assert client.DEFAULT_SOCKET == "/run/hypr-stream/stream.sock"
assert client.build_parser().parse_args([]).socket == client.DEFAULT_SOCKET