Compare commits

..
Author SHA1 Message Date
Hermenix e80757106f docs(plan): stop the desktop reading as headless Linux — approach and open questions 2026-10-03 23:55:44 +00:00
Hermenix 4b5cb5197a docs+examples: log the cursor marker as open, and film each desk on its own
The marker is now written up as the *open* item rather than a research note: it
is not implemented, the video went out without it, and everything else about the
pointer is exact and readable.

proof-video.py is rewritten for desks, one command, no arguments. It films the
session's own output with `record --output` instead of the published socket --
with desks, the socket carries every output stitched together, so a viewer would
watch two thirds wallpaper. The scrolling beats are real pointer axis events,
down twice and back up once, so the movement cannot be mistaken for a page that
merely loaded a different part of itself.
2026-10-03 19:54:08 +00:00
Hermenix cbf58f6443 docs: two TODO items closed, and the cursor question answered
Closed: containers-do-not-bind and pointer-needs-a-container-or-a-screen. Both
were the same defect seen from two sides, and both are fixed by assigning
windows by pid -- two sessions now hold two outputs with a real browser on each,
and the pointer aims at a desk that has something in it.

The cursor item is rewritten with the answer rather than the speculation: the
compositor draws no cursor image for a virtual pointer, so no capture setting
can make one appear. The evidence is in the file, including the three wrong
answers that came before it and the boring measurement that settled it.

New item: killing a session left two browsers alive, found by counting windows
rather than sessions.
2026-10-03 19:45:42 +00:00
Hermenix acdfb2801e the default capture command now asks for the cursor
grim's `-c` ("include cursors in the screenshot") exists because the screencopy
protocol takes the decision from the client: Hyprland's capture_output carries
an overlayCursor argument and the frame is only composited with the cursor when
it is set. Without it a frame shows that *something* changed and never where it
was clicked -- and a click on the wrong element looks exactly like a click on
the right one, which is the whole reason the pointer work is verifiable at all.

Found by reading Hyprland's Screencopy.cpp rather than guessing at a compositor
setting: `no_hardware_cursors` was already on, and the cursor was invisible
because nobody had asked for it.
2026-10-03 19:42:13 +00:00
Hermenix 352cfdcb24 claim windows by pid, and find the compositor after a restart
Two things stood between "containers enabled" and an application actually
sitting on its own output, and neither was where I said it was.

ipc: discovery refused whenever two instance directories existed, which every
compositor restart leaves behind (a log file where a live compositor used to
be). After two rebuilds the broker could not reach any compositor at all, so no
container could be created and the pointer had nothing to aim at. It now asks
each candidate for its version and uses the one that answers, preferring the
newest only when two answer, and still refusing when none do.

container_host.claim: windows are assigned by the pid the compositor already
reports, not by the class stamp the per-session rule matches -- foot, GTK, Qt
and the chromium wrapper all ignore that stamp, so the desk was created and
left empty while the window sat in special:quarantine. The claim moves the
window to its desk's workspace, makes that workspace the one the desk is
showing, and reads back: the record says where the window is, never where it
was sent. Called from both places a window can appear -- the read-back at start
and container.reconcile -- and skipped in the steady state, because a move is a
real change on screen and should not be dispatched for its own sake.
2026-10-03 19:39:33 +00:00
Hermenix 336474793f docs: the pointer is unusable while containers are off
Found live while trying to demonstrate the scroll verb that was just deployed:
every cursor verb resolves its target through _pointer_output, which requires a
container output, and no session has one -- because containers are off. So the
verb exists and cannot be used, and the acceptance video's missing cursor was
never a capture artefact: nothing could have moved it.

Recorded with the routes out (aim at the shared output when a session owns no
container; or fix the binding first and leave this alone), the cost of the
quick one, and the misleading hint that blames the compositor for a switched-off
feature.
2026-10-03 19:19:24 +00:00
Hermenix 7e0544ed70 docs: point the known-gaps list at the TODO folder, and un-stale its first item
Item 1 said the broker reads none of the container or pointer configuration.
That was true and is not: the settings are parsed beside Policy and a switched-off
container host reports itself unavailable with the key named. The item now
records what actually matters about it -- that containers are off on the
deployment machine because no window can be put in one -- and the section links
docs/TODO/, where each open problem has its impact written down.

The TODO folder itself landed in the previous commit by accident (a `git add -A
docs` swept it in with the scroll work); this commit only makes it findable.
2026-10-03 19:06:17 +00:00
HermenixandClaude Opus 5 6b395305e0 scroll: one verb, two axes, and the sign carries the direction
A session could move a cursor and press it, but not scroll. The protocol
already had the request -- zwlr_virtual_pointer_v1.axis(time, axis, value) --
it had simply never been implemented, in the driver or the broker.

  hhstream session pointer scroll <id> --axis vertical --amount 3

Positive is down (vertical) or right (horizontal): the protocol's direction,
not a choice of ours, which is why direction travels in the sign and there is
deliberately no up/down vocabulary layered over it. The output is whatever the
last warp aimed at, exactly like a button, so scrolling somewhere else is a
warp first -- and the lease is what keeps the whole gesture atomic. Bounded at
100 wheel clicks per request on both sides, because a decimal-point slip should
be a refusal rather than a session scrolled somewhere unrecoverable.

The resume point is re-stamped, not moved: the cursor did not go anywhere, so
the coordinates are re-affirmed and only the stamp advances. Recorded in the
contract as an amendment to the frozen op set, because adding an op to a frozen
interface should be visible rather than implied.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-10-03 19:05:39 +00:00
HermenixandClaude Opus 5 d0efba0877 examples: the acceptance proof video, as a script
Driving the session's browser over CDP, then a terminal with cowsay, was a
scratch script twice and got pruned from scratch once -- which produced an
80-second video of an idle browser and no error. It is asked for repeatedly, so it
belongs with the rest of the agent-eyes tooling, takes a session id, and says in
its docstring that the URLs are real (the search uses key= singular, the bug that
once silently cost every Gunpost search its filtering).

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-10-03 12:14:57 +00:00
Hermenix 8f3f000783 read the config the module writes: containers can be turned off
The module rendered containers_enabled, workspace_base, container_mode,
max_containers and the pointer lease keys into the TOML, and policy.py read only
[defaults] and [apps] -- so the settings were inert. The defaults coincided,
which made it look honoured, until a deployment tried to turn containers off and
found it could not.

Settings now come from the same file: parsed beside Policy (read by __main__, so
the manager keeps taking a plain ManagerConfig its tests build directly) and
carried into ContainerHost, which reports itself unavailable when switched off.
That is the whole mechanism -- the manager already treats an unavailable host as
'sessions without containers', which is what turning them off means -- and the
reason names the key, so a disabled machine cannot be mistaken for one whose
compositor is down.

This is what made the rollback on the host possible; the machine had containers
built, tested, and impossible to disable.
2026-10-03 12:10:19 +00:00
Hermenix c1dc60af00 hyprland-conf: follow the pointer, because one now exists
vm-pointer measured what this setting actually does: with follow_mouse=0 Hyprland
delivers pointer events only to the keyboard-focused window, so a click aimed at
0.25,0.75 of a session's container put the cursor at x=299 y=519 -- inside that
window -- and both clients reported nothing. The click was aimed correctly and
delivered nowhere.

The comment here said 'no pointer will ever exist; do not let focus depend on
one', which was true when written and is false now that the broker injects a
virtual pointer. The cursor lease already serialises input, so focus following
the pointer cannot make two sessions fight over the keyboard.
2026-10-03 11:50:52 +00:00
Hermenix 1c886eec3f merge surface/cli-module-checks into main
The surface the plan described, and the first composer of real compositor
evidence: seven checks green one at a time, including three new ones. They proved
`hyprctl output create headless` works (PLAN experiment 3, until now
unverified), that a click lands where it was aimed read from the application
itself, and that an unmatched window is quarantined.

They also found three defects no fake could: Hyprland's IPC directory is mode
0700 so the broker could not reach either socket and degraded silently, a broker
restart deleted the driver's socket out from under it, and input:follow_mouse=0
sends pointer events only to the keyboard-focused window, so an aimed click
reaches a client that reports nothing.
2026-10-03 11:50:37 +00:00
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
49 changed files with 5916 additions and 117 deletions

No files matched your search

+130 -42
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`
@@ -187,56 +211,120 @@ 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
The deep versions of these — the issue, more than one idea, and why each one
matters — live in [`docs/TODO/`](docs/TODO/README.md). Update the file there
when one closes, so this list stays a description of what is still true.
1. **The container host can be switched off, and the broker now honours it.**
*(This item previously read "the broker reads none of the container or
pointer configuration." That is fixed: `policy.py` parses those settings
beside `Policy`, read in `__main__`, and a host that is switched off reports
itself unavailable with the reason naming the key — so a disabled machine
cannot be mistaken for one whose compositor is down. The reason it matters is
what follows.)* Containers are consequently **off on the deployment machine**:
no window can be put in one yet, and enabling them quarantines every
allowlisted app. That join is the first item in `docs/TODO/`.
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.
+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
''
+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
'';
}
)
+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
'';
}
)
+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.
+13
View File
@@ -278,11 +278,24 @@ blocked driver must not stall the broker.
```json
{"op": "warp", "output": "hh-x", "x": 0.42, "y": 0.61} -> {"ok": true}
{"op": "button", "button": "left", "state": "down"} -> {"ok": true}
{"op": "axis", "axis": "vertical", "value": 3.0} -> {"ok": true}
{"op": "frame"} -> {"ok": true}
{"op": "pressed"} -> {"ok": true, "buttons": ["left"]}
{"op": "release_all"} -> {"ok": true, "lifted": ["left"]}
```
**Amended after the freeze — `axis`, for scrolling.** Added to the op set above
and to the broker's verbs as `pointer.scroll`. Positive vertical is *down* and
positive horizontal is *right*: the protocol's direction, not a choice of ours,
and the reason there is no `up`/`down` vocabulary layered over it. The output is
whatever the last `warp` aimed at, exactly like `button`, so scrolling somewhere
else is a warp first — which is what keeps the whole gesture atomic under the
lease. The magnitude is bounded at 100 wheel clicks per request, in both the
driver and the broker, because a decimal-point slip should be a refusal rather
than a session scrolled somewhere unrecoverable. Unit tests cover validation and
the lease; a real-compositor case is still missing — see
`docs/TODO/scroll-has-no-compositor-proof.md`.
`{"ok": false, "error": "<text>"}` for anything rejected. The driver holds **no
lease state** — the broker owns the lease; the driver is an executor that must
never be trusted to serialise anything.
+34
View File
@@ -0,0 +1,34 @@
# TODO
Known, unfixed problems — each one real, none of them guessed at.
Each file answers three questions and stops:
- **The issue** — what is actually wrong, with the evidence for it.
- **Ideas** — more than one, and which one is the recommended route.
- **Why it matters** — the impact, not the principle.
| item | severity | state |
| --- | --- | --- |
| [cursor-visibility-in-captures](cursor-visibility-in-captures.md) | high | answered: the compositor draws no cursor for a virtual pointer. Needs a decision on an overlay marker |
| [scroll-has-no-compositor-proof](scroll-has-no-compositor-proof.md) | medium | works live; unproven in a gate |
| [reconcile-while-containers-are-off](reconcile-while-containers-are-off.md) | medium | partly fixed: discovery now survives a restart; teardown still lives inside the feature |
| [kill-can-leave-the-app-alive](kill-can-leave-the-app-alive.md) | medium | found by counting windows, not sessions |
Closed since this folder was written:
- *"Containers do not bind"* — fixed. Windows are assigned by the pid the
compositor reports, moved onto their desk's workspace and read back. Two
sessions now hold two outputs with a real browser on each.
- *"The pointer is unusable while containers are off"* — fixed with it. The
pointer aims at the session's desk, and desks hold applications.
- *"Discovery refuses when two compositor instances exist"* — fixed. Each
candidate is asked for its version and the one that answers is used.
Severity here means "how much of the feature is actually delivered", not "how
loud the failure is". The highest is highest because a whole class of work is
blocked on it: the pointer is exact and invisible, so nothing can show *where*
anything happened.
When one of these is fixed, delete its file and the row — this folder is a list
of what is still true, not a history of what was thought.
@@ -0,0 +1,63 @@
# The compositor draws no cursor for a virtual pointer
## What is open
**The overlay marker is not implemented.** The acceptance video was recorded
without it, so the frames show the pointer's *effects* — a page that scrolled,
a tab that opened — and never the pointer itself. Implement it by stamping
`hyprctl cursorpos` into each frame, mapped into the stitched layout, and label
it as an overlay wherever the frame is published. Nothing else about the pointer
is blocked: position, clicks and scrolling are all exact and all readable.
## The issue — answered, and it is not a capture setting
The pointer moves exactly where it is told, and **nothing is drawn**. Every
plausible cause was eliminated by test rather than by argument:
| candidate | test | result |
| --- | --- | --- |
| `grim` not asking for the cursor | Hyprland's `Screencopy.cpp` takes an `overlayCursor` argument, so `-c` was added to the capture command | no change at the pointer |
| hardware cursor plane | `cursor:no_hardware_cursors` | already `true` |
| no cursor theme installed | installed `adwaita-icon-theme`, present at `/run/current-system/sw/share/icons/Adwaita` (63 cursor files) | no change |
| theme not reaching the cursor manager | `hyprctl setcursor Adwaita 24` at runtime | no change — and note `env = XCURSOR_THEME` in the compositor's own config sets variables for **launched programs**, not for the compositor, which is where my first attempt put it |
| hyprcursor rather than X11 themes | `cursor:enable_hyprcursor` | already `false`: the X11 path |
The decisive measurement: park the pointer at two points that both miss the
browser's toolbar, capture each, diff them — **zero differing pixels**. The only
differences that ever appear are in the URL bar, which is a blinking text caret.
The cause is the protocol. `zwlr_virtual_pointer_v1` has no request to set a
cursor image, and Hyprland renders a cursor only for a pointer that has an image
to draw. A virtual pointer warps the position and has no surface behind it, so
the compositor has nothing to composite: every capture is faithful, and the
cursor is simply not in it.
## Ideas
1. **Stamp the position into the frames, labelled as an overlay.** *(recommended)*
The frame server can ask `hyprctl cursorpos` — this machine answers it exactly
— map it into the stitched frame, and draw a marker there. It is not fiction:
it is the compositor's own answer, drawn where the compositor says the pointer
is, precisely because the compositor draws nothing. It has to be *named* as an
overlay in the code and in anything published from it.
2. **Leave the pixels alone and prove motion by readout.** `hyprctl cursorpos` is
exact: 0.8 across a 1280-wide desk came back as 3584 with the desk starting at
2560. Gates can assert position with no image at all — cheaper and stronger
than a pixel check.
3. **Ask upstream, or try a newer compositor.** Whatever makes a cursor appear
for a virtual pointer is the real fix. Not attempted.
4. **A synthetic pointer client.** Impossible for a plain client (it cannot draw
over another window); it would need a layer-shell surface, which is more
machinery than (1) for the same result.
## Why it matters
Everything about the pointer is verifiable except the part a person can see. That
a click landed *here* is provable by readout and by what changed, but a viewer
cannot tell **where** it happened — and a click on the wrong element and a click
on the right one both produce a screen that changed.
Worth recording: this took three wrong answers (`-c`, the theme, the compositor
setting) before the right one, and two of those came from reasoning rather than
measurement. What settled it was boring — capture the same screen twice with the
pointer in two places and diff them. That should have been the first move.
+42
View File
@@ -0,0 +1,42 @@
# Killing a session does not always kill the browser it started
## The issue
Three chromium processes outlived the sessions that had launched them, while the
broker reported those sessions as ended. Found by counting windows on the
compositor after a probe run: two windows left on the main screen whose sessions
no longer existed, with pids older than the session that had replaced them.
The kill path does signal the process group — the audit line says
`sent SIGTERM to process group 2966561` and that session's process *did* die —
so this is not "the kill does nothing". It is narrower: two of three killings
left a live browser behind, and the two that leaked were started while the
compositor was unreachable from the broker, so they had no container recorded at
all. That correlation is the only clue so far and it is not proof.
## Ideas
1. **Check whether the leak tracks the container record.** *(recommended first)*
Kill a session whose container is `owned` and one whose container is `null`,
several times, and count survivors. If the leak is limited to containerless
sessions, the fix is in the kill path's cleanup of a session that never got a
desk, not in the signal path.
2. **Re-read the survivors from the compositor after every kill.** The teardown
already has `container_survivors` for windows; the same shape applies to
processes, and `procmon` already knows how to identify them by
`(pid, starttime)`. A kill that leaves anything alive should say so in its
reply rather than returning a clean record.
3. **Make the idle reaper the backstop it already is.** A session that was
reaped instead of killed goes through the same teardown; if the leak is in
the exit path, the reaper may be leaking too — worth measuring once (1).
4. **A test that counts processes, not sessions.** Every existing assertion is
about the broker's view. One that counts the app's processes after a kill
would have caught this the first time it happened.
## Why it matters
Processes that outlive their sessions are exactly what the registry's whole
identity design (boot id, start time) exists to prevent, and the ones found were
still holding windows on the compositor — invisible to `session list`, visible
on screen. A machine that accumulates them slowly fills up with browsers nobody
owns, each holding a desk slot if the band is what limits sessions.
@@ -0,0 +1,48 @@
# Cleanup depends on the feature it is cleaning up after
## The issue
Start-up reconciliation for stray `hh-*` outputs lives inside the container
host, so it runs **only when containers are enabled**. Turning containers off
therefore also turned off the broker's ability to see what it had already left
on the compositor.
That is not theoretical: an output created while the feature was on survived the
rollback switch. With containers off, nothing reconciled it, and the frame
capture stayed **2560×720 instead of 1280×720** — the extra width being the
orphan sitting beside the real one. The symptom is a *capture* problem, which is
where it would be looked for, and it was fixed by restarting the compositor,
which drops every session.
## Ideas
1. **Reconcile always, not conditionally.** *(recommended)* On start-up, list the
compositor's outputs, find `hh-*` ones that no live session owns, and remove
them — regardless of whether containers are enabled. "Disabled" should mean
*create none*, not *leave the machine as it was found*.
2. **Never start a session onto an unowned output.** If a leftover is found that
cannot be removed, refuse to place a session on it rather than silently
sharing it — the ambiguity is what makes the capture width unexplainable.
3. **Record removals in the audit trail.** The `hyprctl output remove` calls are
already logged individually; a reconcile pass that removes three outputs
should say so once, with the names, so a later "why is my screen narrower"
has an answer.
4. **Make it a check.** A VM case that creates a container, disables the feature,
and asserts the output is gone — the rollback path deserves the same gate as
the forward path, because it is the one that runs when something is already
wrong.
## Why it matters
A feature that cannot be turned off safely is worse than one that was never
turned on, and this one fails asymmetrically: the *forward* path is tested
(containers are created and torn down in `vm-sessions` and `vm-containers`),
while the *rollback* path was never exercised before it was needed. That is
precisely when it is used.
It also cost a compositor restart — the bluntest tool available, and one that
kills every session — to clean up a state the broker itself had created and
could no longer see. The general rule worth keeping: **teardown code belongs
outside the thing being torn down**, or there will be exactly one configuration
where it does not run, and it will be the configuration you are in when you
need it.
@@ -0,0 +1,50 @@
# Scrolling works, but nothing proves it against a real compositor
## The issue
`hhstream session pointer scroll <id> --amount N` now exists end to end: CLI →
`pointer.scroll` → the lease check → driver `axis` op →
`zwlr_virtual_pointer_v1.axis(time, axis, value)` → `frame`. Validation is
covered by unit tests, and the lease behaviour matches the other gestures.
What is **not** covered is the half that matters: no test scrolls a real
application on a real compositor. The `vm-pointer` gate has no axis case, and
the fake compositor can only prove the wiring — that the broker said the right
thing to the driver, not that a window moved.
Also unproven, and worth knowing before trusting it: whether an app on a
**headless** output honours a bare `axis` event at all. GTK and Chromium
smooth-scrolling both look at `axis_source` and `axis_discrete`, which the
driver does not send today. If they are required, the symptom will be a scroll
that silently does nothing — indistinguishable from a page that would not move.
## Ideas
1. **An axis case in `vm-pointer` that reads the app's own state.** *(recommended)*
Scroll a real app and assert *its* state changed, not the pixels — the
contract already sets this bar for clicks ("verified by reading the app's own
state"). A `foot` running a script that appends a line on scroll, or a page
whose scroll offset the app can report, keeps the assertion honest.
2. **Send `axis_source` and `axis_discrete` alongside `axis`** if (1) shows the
event arriving and the app ignoring it. Small, confined to the driver's
`axis` op.
3. **Keep the direction convention in one place.** Positive vertical is down and
positive horizontal is right, per the protocol. It is documented in
`hhstream_pointer/buttons.py` and mirrored in the CLI's `AXES` — if a third
copy ever appears, that is the point to notice, because two vocabularies over
one sign is how a scroll ends up backwards.
4. **A live check on this machine, not only in a VM.** The video that prompted
this work is a real scroll on a real app; making that reproducible as a
command (like `examples/proof-video.py`) is worth as much as the VM case.
## Why it matters
An unimplemented feature is honest; a **plausible** one is not. A scroll that
does nothing, a scroll that goes the wrong way, and a scroll the app ignores all
present as "the page would not move", and all three would be found by a human
watching a video — which is not a test.
This is the same shape as the bug that made `foot` exit 230 with every test
green: the tests exercised what was built, and the built thing was fine, and the
app exited anyway. Anything whose acceptance proof runs through a real window
needs a real window in the test.
+126
View File
@@ -0,0 +1,126 @@
# Make the Hyprland session look like a normal Linux desktop
Plan only. Nothing here was edited, rebuilt, or measured live. The diagnostic shell (`hyprctl monitors`, `systemctl cat`, `/dev/dri`, portals, audio) was cancelled before it ran. Every live fact below is either from files that were read or from older Chromium logs already on disk. Anything not in those sources is marked unverified.
## What was read
- `/etc/nixos/hyprland-stream.nix` — outputs, capture, session allowlist, fonts, cursor theme, window rule
- `/etc/nixos/common.nix` — QEMU guest, `chromium` on `systemPackages`, `hermes` groups, no audio/portal/timezone block
- `nix/module.nix` — compositor environment, `WLR_*`, `SEATD_VTBOUND`, session broker, what apps inherit
- `nix/hyprland-conf.nix` — generated `hyprland.conf` (cursor, input, `disable_xdg_env_checks`)
- `src/hhstream/capture.py` — `grim` to stdout; capture does not name an output
- `src/hhstreamd/containers.py` — `hyprctl output create headless hh-<session-id>`
- `src/hhstreamd/launcher.py`, `src/hhstreamd/compositor.py` — app environment
- `examples/agent-eyes` — `run` only sets `XDG_RUNTIME_DIR`, `WAYLAND_DISPLAY`, `XDG_SESSION_TYPE`
- `docs/ARCHITECTURE.md` (full). `docs/CONTRACT.md` and `docs/CONTRACT-sessions.md` were searched, not read end to end. Container output name `hh-<session-id>` is frozen in the sessions contract.
- `/var/lib/hermes/.hermes/skills/devops/agent-eyes/SKILL.md` and `headless-wayland-compositor/references/browser-fetch-and-cdp.md`
The SwiftShader flags are **not** in that skill, the allowlist, or `examples/agent-eyes`. They appear in one recorded command (`~/.hermes/logs/process-results/proc_a2b2e2384799.json`): `agent-eyes run -- chromium … --use-gl=angle --use-angle=swiftshader --enable-unsafe-swiftshader … https://discord.com/register`. Older Chromium logs (`proc_53cbb1c64842.json`, `proc_ecc7dddf484a.json`, `proc_3edb9a456ba3.json`) show `virtio_gpu_drv_video.so` init failure, `WebGL1 blocklisted`, and UPower `DisplayDevice` `ServiceUnknown`. Those logs still mention `XDG_RUNTIME_DIR=/run/hyprland-headless-stream` (the old path). The runtime dir in the current module is `/run/hypr-stream`.
## 1. Signal inventory
A page cannot see Hyprland output names, kernel input names, or `XDG_*`. Those matter only when they change something the page *can* read (WebGL, `screen`, media devices, `Intl`).
| Signal | Evidence | What a page actually sees | Live check |
|---|---|---|---|
| SwiftShader forced on | Ad-hoc `agent-eyes run` argv above. Not in the Nix allowlist, so `hhstream session start chromium` would reject those args. `agent-eyes run` execs them as-is. | `WEBGL_debug_renderer_info` / WebGPU adapter info. Stock SwiftShader strings are `Google SwiftShader` and device id `0x0000C0DE`. **The exact string on this box was not read back.** | Unverified |
| WebGL context dies without those flags | Same logs: `ContextResult::kFatalFailure: WebGL1 blocklisted` and a failed GPU command buffer | `getContext('webgl')` is null. That is its own automation signal. | From old logs, not a new probe |
| Virtio GPU present, video init fails | `libva error: …/virtio_gpu_drv_video.so init failed`, `vaInitialize failed`. `hardware.graphics.enable = true`. This is a QEMU guest (`common.nix` imports `qemu-guest.nix`). | Hardware decode missing (`mediaCapabilities`). The GL renderer string without SwiftShader flags was **not** captured. Likely Mesa virgl or llvmpipe, not NVIDIA/AMD/Intel. | Renderer string unverified |
| `/dev/dri` missing | **Not supported.** Architecture says the compositor will not start without a render node, and the VAAPI path found a virtio-gpu driver. | Nothing, if the node exists. | `ls /dev/dri` was not run |
| `hermes` cannot open the render node | `hermes.extraGroups` is `wheel`, `systemd-journal`, and `hhstream`. The compositor user gets `video` and `render`. Chromium runs as `hermes`. | Browser falls back to software GL or a blocklisted WebGL context. This is the likely reason SwiftShader was added by hand. | Groups were not read from the running session |
| Main output name | Module does **not** create the main output. The monitor rule uses an empty name (wildcard). Comments say `Virtual-1` on virtio, `eDP-1` on a laptop. `WLR_BACKENDS=headless` is set and documented as ignored by current Hyprland (aquamarine). | Not visible on `window.screen`. `getScreenDetails().label` might echo the wl_output name, and only after a permission prompt. **Not verified in this Chromium.** | `hyprctl monitors` was not run. Do not assume the name is `HEADLESS-1`. |
| Per-session output | `containers.enable = true` (trial, dated 2026-10-03). `containers.py` runs `hyprctl output create headless hh-<id>`. Contract freezes that name. | Same as above, and only if the window is actually on that output. The Nix comment says Chromium ignores the app-id stamp, so the window may miss the container. | Unverified whether any `hh-*` output exists now |
| Screen 1280×720 @ 30 Hz, scale 1 | `outputs` in `hyprland-stream.nix`; container default `1280x720`. Window rule `size 1040 560`. Launch recipe `--window-size=1040,560`. | `screen.width/height`, `devicePixelRatio` 1. Refresh rate is not on `window.screen`. 720p is a weak signal, not a headless label. | Mode unverified live |
| No real input devices | `WLR_LIBINPUT_NO_DEVICES=1`. Pointer is `zwlr_virtual_pointer_v1` (`hhstream-pointer`). Generated config sets `cursor.invisible = true`. | A page does **not** see kernel or libinput names. Compositor-delivered clicks are real Wayland events; `isTrusted` was not measured. CDP input (`Input.insertText` in the skill) is a separate, stronger tell. No keyboard injector exists (`wtype` / `ydotool` are called out as not installed). | Device list unverified |
| `navigator.webdriver` / headless UA | Allowlist and the skill do **not** pass `--enable-automation` or `--headless`. They do pass `--remote-debugging-port` and `--remote-debugging-address=127.0.0.1`. | `navigator.webdriver` should be false and the UA should not contain `HeadlessChrome`. **Not evaluated in a page.** The open DevTools port is not visible to the origin. Attaching CDP and typing through it is. | Unverified |
| Runtime dir not owned by the app | Compositor `XDG_RUNTIME_DIR=/run/hypr-stream`, owned by `hhstream`. Broker and `agent-eyes run` point the app at that same directory. Old log: `XDG_RUNTIME_DIR (…) is not owned by us (uid 1000), but by uid 994`. | Not visible as a string. Chromium then skips Pulse, portals, and dconf. That shows up as empty media devices and failed permission UIs. | Old path only; current path not re-checked |
| Desktop env not set | App env from `CompositorSession.env()` is only `XDG_RUNTIME_DIR`, `WAYLAND_DISPLAY`, `XDG_SESSION_TYPE=wayland`. Compositor also sets `HYPRLAND_NO_SD_VARS=1`, so it does not publish a desktop session. `HOME` for the compositor unit is `/run/hypr-stream`; for broker apps it is the hermes home. | Pages do not read `XDG_*`. GTK/Qt and Chromium's own desktop integration do. | Unverified in `/proc/<pid>/environ` |
| No portal | `disable_xdg_env_checks = true` because "the XDG portal environment" is not there. Neither Nix file enables `xdg.portal`. | No direct JS API. Clipboard, file choosers, and screencast fail. Not the Discord signup check. | Service state unverified |
| No audio server | No PipeWire, Pulse, or WirePlumber in either Nix file. | `enumerateDevices()` has no `audioinput` / `audiooutput` (kinds can leak before permission). | Unverified |
| No UPower | Chromium log: `org.freedesktop.UPower` `ServiceUnknown`. No upower module in the files read. | `navigator.getBattery()` fails. A tower desktop also has no battery, so this is a weak "VM" tell and a bad thing to fake as a laptop. | From old logs |
| Fonts | `fonts.packages = [ pkgs.dejavu_fonts ]` only, added so `foot` has a monospace. | Canvas / `document.fonts` look like a minimal Linux install, not specifically headless. Emoji and metric-compatible faces are absent. | `fc-list` was not run |
| Locale and timezone | Neither file sets `i18n.defaultLocale` or `time.timeZone`. The session unit does not set `LANG` or `TZ`. | `Intl.DateTimeFormat().resolvedOptions().timeZone` and `navigator.languages`. A VM left on UTC is a datacenter tell if the operator is not in UTC. **The live zone was not read.** | Unverified |
| Fresh profile every launch | Skill and the Discord command use `--user-data-dir=/tmp/eyes-profile-$$` (or a one-off `/tmp` dir). | Empty cookies, storage, and history. Behavioral, not a renderer string. | n/a |
Not listed, because nothing read supports them: a kernel input device whose name contains "headless"; `navigator.webdriver === true`; a UA containing `HeadlessChrome`; a missing `/dev/dri`.
## 2. What we can change
**Stop forcing SwiftShader.** Do not add those three flags to `sessions.apps.chromium.argsAllow`. `agent-eyes run` bypasses the allowlist, so a wrapper has to be the binary both paths exec. Wrapper lives in the NixOS module (`sessions.apps.chromium.exec`) and the skill's launch recipe points at it. Flags to keep: `--ozone-platform=wayland`. Flags to refuse: `--use-angle=swiftshader`, `--enable-unsafe-swiftshader`, `--enable-automation`, `--headless`. Do not spoof `UNMASKED_RENDERER`. Overriding `getParameter` in the page is itself detectable.
**Let Chromium open the same render node the compositor uses.** Add `video` and `render` to `users.users.hermes.extraGroups` in `hyprland-stream.nix`, and restart `hhstream-sessions` so the broker picks up the groups. An already-open SSH session will not see them until a new login. `agent-eyes run` from that SSH session still needs a new login or `sg`. This is the best chance of a real Mesa renderer (virgl) instead of SwiftShader or a null WebGL context.
**Give apps a runtime dir they own.** `CompositorSession.env()` and `examples/agent-eyes` `cmd_run` should set `XDG_RUNTIME_DIR` to hermes' `/run/user/<uid>` (linger is already on) and put a symlink to the compositor's `wayland-N` socket there. Toolkits resolve `WAYLAND_DISPLAY` against `XDG_RUNTIME_DIR`, so the symlink is required. Also set `XDG_CURRENT_DESKTOP=Hyprland` and `XDG_SESSION_DESKTOP=Hyprland` on the app, not by clearing `HYPRLAND_NO_SD_VARS` on the compositor unit. The frame server and `grim` stay on `/run/hypr-stream`.
**Desktop services, after that runtime-dir fix.** In `hyprland-stream.nix` (session-specific, not the whole guest image):
- PipeWire + WirePlumber. No sound card was verified; a null sink is the honest stand-in.
- `xdg.portal` with the GTK portal. The Hyprland portal only after it can see this compositor's IPC, which is not the user session's.
- `upower` so the D-Bus name exists. Do not invent a charge percentage.
- Fonts next to DejaVu: a sans/serif metric set (Liberation or Noto), plus Noto Color Emoji.
**Timezone and locale** belong in `common.nix` (`time.timeZone`, `i18n.defaultLocale`), set to the operator's real zone. The files do not say what that zone is. Do not guess.
**Resolution, only if capture still fits.** 1920×1080@60, scale 1, in `outputs` and `sessions.containers.mode`. Keep the window smaller than the output (the wallpaper is intentional). JPEG q80 at 1280×720 was measured at ~46 ms in the Nix comments; 1080p is about 2.25× the pixels. If `grim` goes much past that, stay at 720p. Do not set `outputs[].name` to `DP-1` or `HDMI-A-1`: a monitor rule whose name matches nothing is silently ignored and the mode never applies.
**Do not rename `hh-*` outputs.** The sessions contract, `grim -o`, pointer binding, and reconcile all use that name. A page almost certainly never reads it.
**One durable Chromium profile** for the signup browser, under `/var/lib/hermes/hhstream-sessions/`, not `/tmp/eyes-profile-$$`. Keep per-run profiles only when two browsers must run at once (Chromium exits if the profile is locked).
**Leave the cursor config alone** in this work. `invisible = true` is in the generated conf and the extraConfig does not turn it off. That affects captures, not fingerprinting.
## 3. What cannot be faked
There is no physical GPU on this guest. The GL string will be Mesa on virtio-gpu, or llvmpipe if virgl does not come up. Both are software-ish VM strings. SwiftShader is worse because `0x0000C0DE` is a known headless-Chrome id. Claiming Intel, AMD, or NVIDIA from stock Chromium is not possible, and a patched Chromium or a JS lie is a louder signal than llvmpipe.
There is no monitor EDID and no physical seat. Renaming an output `DP-1` does not create one. Websites do not read EDID.
`navigator.getBattery()` failing is normal for a desktop tower. A fake laptop battery would disagree with the rest of the machine.
WebRTC can still expose the guest address `10.77.0.2` and the hostname `hermes` (`common.nix`). That is a VM tell, not a "headless Linux" string. Confirm with a page before adding a WebRTC policy flag; do not add it speculatively.
Typing still goes through CDP unless a keyboard injector is added later. Pointer events from `zwlr_virtual_pointer_v1` are the less detectable input. This plan does not add a keyboard.
Discord's phone wall was not reproduced here. The Google signup note (`web-account-signup/references/google-signup.md`) records the same class of wall on this desktop, and it does not say which signal Google used. Fixing the rows above removes the signals we can point at. It does not guarantee the wall goes away.
## 4. Staged plan
**Stage 0 — baseline, no changes.** Small. Run, and save the output:
```bash
sg hhstream -c 'XDG_RUNTIME_DIR=/run/hypr-stream HYPRLAND_INSTANCE_SIGNATURE=$(basename /run/hypr-stream/hypr/*) hyprctl -j monitors'
sg hhstream -c 'XDG_RUNTIME_DIR=/run/hypr-stream HYPRLAND_INSTANCE_SIGNATURE=$(basename /run/hypr-stream/hypr/*) hyprctl -j devices'
ls -l /dev/dri
id hermes
systemctl is-active hyprland-headless hyprland-headless-stream hhstream-sessions hhstream-pointer
```
Then one windowed Chromium **without** SwiftShader flags, and one CDP `Runtime.evaluate` of: WebGL vendor/renderer (or null context), `navigator.webdriver`, `navigator.userAgent`, `screen.width/height/devicePixelRatio`, `Intl.DateTimeFormat().resolvedOptions()`, `navigator.languages`, `enumerateDevices()` kinds, and `getBattery()`'s rejection. That sheet is the only acceptance test that matters.
**Stage 1 — wrapper, stop SwiftShader.** Small. Nix wrapper as `chromium`'s `exec`; skill recipe updated; allowlist does not grow those flags. Proof: `/proc/<pid>/cmdline` has no `swiftshader`; the Stage 0 WebGL expression no longer returns SwiftShader. If the context is null, Stage 1 is incomplete and Stage 2 is the fix, not turning SwiftShader back on.
**Stage 2 — `render`/`video` for `hermes`.** Small config, needs a new login and a broker restart. Proof: same WebGL expression returns a Mesa/virgl (or llvmpipe) string, and the log has no `WebGL1 blocklisted`.
**Stage 3 — user-owned `XDG_RUNTIME_DIR` plus desktop variables.** Medium. `compositor.py` and `agent-eyes` `cmd_run`. Proof: Chromium's stderr does not contain `not owned by us`; a launched `foot` prints `/run/user/<uid>`. Run `checks.vm-sessions` and `checks.vm-pointer` (one at a time; they are timing-sensitive). Failure mode to watch: `Failed to connect to Wayland display`.
**Stage 4 — PipeWire null sink, GTK portal, upower, fonts, real timezone.** Medium, NixOS only, after Stage 3. Proof: `wpctl status` shows a sink; `busctl status org.freedesktop.portal.Desktop` and `org.freedesktop.UPower` are active; `fc-match sans` and `fc-match emoji` hit the new faces; the page's `enumerateDevices()` includes `audiooutput`; Chromium's log no longer says UPower `ServiceUnknown`; `Intl` timezone matches `timedatectl`.
**Stage 5 — 1080p@60, gated.** Small, only if Stage 0's page probe and a `grim` timing say 720p@30 is worth the CPU. Proof: `hyprctl monitors` shows the new mode, and one timed `grim -c -t jpeg -q 80` stays near the old ~46 ms budget. If it does not, revert the mode and keep 720p.
**Stage 6 — durable profile.** Small, convention plus the wrapper's `--user-data-dir`. Proof: second launch reuses the same directory and still starts; cmdline has no `/tmp/eyes-profile`.
Land 0 → 1 → 2 → 3 → 4 → 6. Stage 5 is optional and independent. Do not combine Stage 3 with a resolution change; a dead Wayland socket and a slow `grim` would be one undifferentiated failure.
## 5. Risks
- **Wayland socket.** Stage 3 is the BUG-01 area. The frame server must keep `XDG_RUNTIME_DIR=/run/hypr-stream`. Moving the compositor's own runtime directory re-breaks the 25-character `sun_path` limit on the event socket.
- **`hh-*` names.** Renaming them breaks capture-by-output, the pointer's per-output device, and reconcile. Leave the contract alone.
- **Monitor-rule names.** A non-empty `outputs[].name` that is not the real connector is ignored. The session would come up at the connector's preferred mode and the 1280×720 assumption in capture, the window rule, and the tests would be wrong.
- **Containers trial.** `containers.enable = true` today can park Chromium on the quarantine workspace, so the published frame is an empty desktop. A fingerprint change that assumes the window is on the main output will be "verified" against the wrong screen.
- **CPU.** `debug:vfr = false` renders every output every frame, and each container is another output. 1080p plus two containers is the capture-budget failure.
- **Groups.** `extraGroups` does nothing for a broker that is already running, and nothing for an SSH session started before the rebuild.
- **Allowlist vs `agent-eyes run`.** Fixing only `argsAllow` does not stop the helper from passing SwiftShader. The wrapper has to be on both paths.
- **Cursor and `grim -c`.** Do not flip `cursor.invisible` in the same change. Capture tests do not own that behavior.
- **VM checks.** Run `vm-sessions`, `vm-pointer`, and `vm-hyprland` one at a time after Stages 3 and 5. Two guests at once on this machine flake.
The defensible outcome is a windowed Chromium on virtio-gpu Mesa, with a normal runtime dir, a sink, fonts, and the operator's timezone. It will still be a QEMU guest. It will not be SwiftShader, and it will not be named like a headless Chrome.
+31
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
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env python3
"""The acceptance video: an SKS search, real scrolling, tabs, and cowsay.
One command, no arguments, and it cleans up after itself. It starts a browser
session (which gets a desk of its own — its own output and workspace), films
*that desk alone*, drives the search over the browser's own HTTP endpoints, and
scrolls the results page with the real pointer -- `hhstream session pointer
scroll`, which sends wl_pointer axis events rather than pressing a key.
Then it kills the browser, starts a terminal session on its own desk, and films
cowsay saying what it says. The two films are joined into one mp4.
Why `--output` and not the published frame socket: with desks, the socket
carries every output stitched side by side, so a viewer would watch two thirds
wallpaper. `--output` runs grim per frame against the session's own desk and
costs more; the trade is a video of the thing being demonstrated.
The cursor is **not** in the frames, and that is not a capture setting: the
virtual pointer has no cursor image for the compositor to draw. See
docs/TODO/cursor-visibility-in-captures.md. The scrolling is visible by what
moves, which is why the page is scrolled rather than merely pointed at.
./proof-video.py [--profile DIR] [--out FILE]
"""
from __future__ import annotations
import argparse
import json
import pathlib
import subprocess
import sys
import time
import urllib.parse
import urllib.request
CDP_PORT = 9344
CDP = f"http://127.0.0.1:{CDP_PORT}"
SEARCH = "https://www.gunpost.ca/ads?key=SKS&sort=created&order=desc"
LISTINGS = [
"https://www.gunpost.ca/firearms/rifles/hamilton/sks-1951-russian-excellent-rifle-762x39-100000-obo",
"https://www.gunpost.ca/firearms/rifles/pembroke/1953-tula-russian-sks-762x39-crisp-markings-solid-hardwood-stock-box",
"https://www.gunpost.ca/firearms/rifles/markham-york-region/chinese-type-56-sks-hush-folding-stock-original-wood-stock",
]
MESSAGE = "hahaha I can see the world now"
#: Absolute, because the broker is a systemd unit and a unit's PATH has no system
#: profile in it: a bare `cowsay` fails inside foot with "No such file or directory".
COWSAY = "/nix/store/s4hlzmy3ll1bphdsy8vjdpcw447vbr93-cowsay-3.8.4/bin/cowsay"
#: How long each film runs. The beats below are timed to fit inside these.
BROWSER_SECONDS = 44
COW_SECONDS = 12
def call(path: str, method: str = "GET") -> dict:
req = urllib.request.Request(CDP + path, method=method)
with urllib.request.urlopen(req, timeout=15) as response:
body = response.read().decode()
return json.loads(body) if body.strip() else {}
def open_tab(url: str) -> str:
return call("/json/new?" + urllib.parse.quote(url, safe=""), method="PUT")["id"]
def activate(tab_id: str) -> None:
"""Bring a tab to the front. Cosmetic: never fail the recording over it."""
try:
call("/json/activate/" + tab_id)
except Exception as exc: # noqa: BLE001 - a failed activation is not fatal
print(f" (activate {tab_id[:8]} said: {exc})", flush=True)
def hhstream(*args: str, check: bool = False) -> str:
out = subprocess.run(["hhstream", *args], capture_output=True, text=True, timeout=300)
if out.returncode != 0:
print(f" (hhstream {' '.join(args[:3])} -> {out.returncode}: {out.stderr.strip()[:160]})")
if check:
raise SystemExit(f"hhstream {' '.join(args[:3])} failed")
return out.stdout.strip()
def desk_of(session: str) -> str:
"""The output name of a session's desk, as the broker recorded it."""
reply = json.loads(hhstream("session", "container", "--json") or "{}")
rows = reply.get("containers") or reply.get("sessions") or []
for row in rows:
if row.get("id") == session:
desk = row.get("output") or (row.get("container") or {}).get("output")
if desk:
return desk
raise SystemExit(f"{session} has no desk output: {json.dumps(rows)[:300]}")
def busy_work(session: str) -> None:
"""The pointer beats: scroll the results, then walk the listings.
Scrolling is the point of these beats. The pointer is aimed into this
session's own desk, so the scroll lands on its page and nowhere else -- and
because the cursor is not drawn, what a viewer sees is the page moving.
"""
lease = json.loads(hhstream("session", "pointer", "acquire", session, "--json") or "{}")
lease_id = lease.get("lease_id")
if not lease_id:
print(f" (no lease: {json.dumps(lease)[:200]})", flush=True)
return
# Down, down again, then back up: two directions, so it cannot be mistaken
# for a page that simply loaded a different part of itself.
hhstream("session", "pointer", "move", session, "--lease", lease_id, "--to", "0.5,0.55")
for amount, pause in ((6, 2.5), (6, 2.5), (-4, 2.0)):
print(f" scroll vertical {amount:+d}", flush=True)
hhstream(
"session", "pointer", "scroll", session,
"--lease", lease_id, "--axis", "vertical", "--amount", str(amount),
)
time.sleep(pause)
hhstream("session", "pointer", "release", session, "--lease", lease_id)
def film(session: str, seconds: int, out: pathlib.Path) -> None:
"""Record one desk until `seconds` have passed, then wait for the encoder."""
hhstream(
"record", "--output", desk_of(session), "--fps", "12",
"--seconds", str(seconds), "--out", str(out),
)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--profile", default="/var/lib/hermes/agent-eyes/gunpost-profile")
parser.add_argument("--out", default="/var/lib/hermes/agent-eyes/desks-proof.mp4")
parser.add_argument("--work-dir", default="/var/lib/hermes/agent-eyes/takes")
args = parser.parse_args()
out = pathlib.Path(args.out)
work = pathlib.Path(args.work_dir)
work.mkdir(parents=True, exist_ok=True)
pathlib.Path(args.profile).mkdir(parents=True, exist_ok=True)
a, b = work / "desk-a.mp4", work / "desk-b.mp4"
print("=== starting the browser on its own desk ===", flush=True)
browser = hhstream(
"session", "start", "chromium", "--",
"--ozone-platform=wayland", f"--user-data-dir={args.profile}",
"--no-first-run", "--no-default-browser-check", "--window-size=1280,720",
f"--remote-debugging-port={CDP_PORT}", "--remote-debugging-address=127.0.0.1",
"--new-window", "about:blank",
check=True,
)
print(f" {browser} on {desk_of(browser)}", flush=True)
time.sleep(4) # let the window map and the debugging port come up
print("=== film 1: the search, scrolling, and three listings ===", flush=True)
recording = subprocess.Popen(
["hhstream", "record", "--output", desk_of(browser), "--fps", "12",
"--seconds", str(BROWSER_SECONDS), "--out", str(a)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
time.sleep(2)
search_tab = open_tab(SEARCH)
activate(search_tab)
print(" the SKS search is loading (Cloudflare included)", flush=True)
time.sleep(13)
busy_work(browser)
for n, url in enumerate(LISTINGS, 1):
activate(open_tab(url))
print(f" listing {n} in its own tab", flush=True)
time.sleep(4)
activate(search_tab)
time.sleep(2)
recording.wait(timeout=300)
print(f" {a}: {a.stat().st_size} bytes", flush=True)
print("=== clearing the browser away ===", flush=True)
print(f" {hhstream('session', 'kill', browser)[:90]}", flush=True)
time.sleep(2)
print("=== film 2: a terminal on its own desk, running cowsay ===", flush=True)
terminal = hhstream(
"session", "start", "foot", "--",
"-H", "-f", "monospace:size=20", COWSAY, MESSAGE,
check=True,
)
print(f" {terminal} on {desk_of(terminal)}", flush=True)
time.sleep(2)
film(terminal, COW_SECONDS, b)
print(f" {b}: {b.stat().st_size} bytes", flush=True)
print(f" {hhstream('session', 'kill', terminal)[:90]}", flush=True)
print("=== joining the two films ===", flush=True)
listing = work / "concat.txt"
listing.write_text(f"file '{a}'\nfile '{b}'\n")
joined = subprocess.run(
["ffmpeg", "-v", "error", "-f", "concat", "-safe", "0", "-i", str(listing),
"-c", "copy", "-y", str(out)],
capture_output=True, text=True,
)
if joined.returncode != 0:
raise SystemExit(f"join failed: {joined.stderr.strip()[:300]}")
probe = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration,size",
"-of", "default=noprint_wrappers=1", str(out)],
capture_output=True, text=True,
)
print(f" {out}\n {probe.stdout.strip().replace(chr(10), ' ')}", flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())
+12 -2
View File
@@ -79,8 +79,18 @@ in ''
}
input {
# No pointer will ever exist; do not let focus depend on one.
follow_mouse = 0
# Focus follows the pointer. This was `0`, on the reasoning written here
# that no pointer would ever exist — true when it was written, and false
# now that the broker injects one.
#
# It is not a preference. With `0` Hyprland delivers pointer events only to
# the keyboard-focused window: measured in `vm-pointer`, a click aimed at
# 0.25,0.75 of a session's container placed the cursor at x=299 y=519,
# inside that window, and **both** clients reported nothing — the click was
# aimed correctly and delivered nowhere. The cursor lease already
# serialises input, so letting the pointer move keyboard focus cannot make
# two sessions fight over the keyboard.
follow_mouse = 1
}
# Frames cost capture bandwidth and CPU, and no one is watching the easing.
+335 -8
View File
@@ -37,6 +37,16 @@ let
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;
# Hyprland refuses `--socket` unless it is paired with `--wayland-fd` (that
@@ -78,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
@@ -102,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: ''
@@ -406,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";
@@ -459,6 +673,28 @@ in {
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 = ''
@@ -492,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) {
@@ -570,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}";
};
};
@@ -623,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";
@@ -647,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"
@@ -665,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
];
};
};
};
}
+109 -12
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
@@ -54,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 ─────────────────────────────────────────────────────────────────
@@ -157,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 ──────────────────────────────────────────────────────────────────
@@ -187,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)
@@ -220,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)
@@ -258,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 ─────────────────────────────────────────────────────────────────
@@ -297,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 --")
@@ -306,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
@@ -27,7 +27,7 @@ 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`.
DEFAULT_CAPTURE_COMMAND = ["grim", "-t", "png", "-"]
DEFAULT_CAPTURE_COMMAND = ["grim", "-c", "-t", "png", "-"]
_BACKLOG = 64
_WAIT_TICK = 0.2 # how often a blocked client thread re-checks for shutdown
+4
View File
@@ -193,6 +193,10 @@ class WaylandSink:
self._pointer(output).button(_now_ms(), code, state)
self._flush()
def axis(self, output: str, axis: int, value: float) -> None:
self._pointer(output).axis(_now_ms(), axis, value)
self._flush()
def frame(self, output: str) -> None:
self._pointer(output).frame()
self._flush()
+23
View File
@@ -27,7 +27,30 @@ CODES: dict[str, int] = {
#: ``wl_pointer.button_state``. Named on the wire so a log line reads.
STATES: dict[str, int] = {"up": 0, "down": 1}
#: ``wl_pointer_axis`` values. Named "vertical"/"horizontal" rather than
#: up/down/left/right, because the sign is what carries the direction: the
#: protocol's positive vertical scroll is *down*, and a caller asking for
#: "down" while a negative value means down is how a scroll ends up backwards.
AXES: dict[str, int] = {"vertical": 0, "horizontal": 1}
#: The largest scroll a single request may carry, in wheel clicks. Bounded so a
#: decimal-point slip (3 -> 30000) is a refusal rather than a session scrolled
#: into next week, where the only clue is that the page will not move back.
MAX_AXIS_VALUE = 100.0
NAMES = tuple(CODES)
AXIS_NAMES = tuple(AXES)
def axis_for(name: str) -> int:
"""The protocol axis for a name, or :class:`ValueError` naming the set."""
try:
return AXES[name]
except KeyError:
raise ValueError(
f"unknown axis {name!r} (known: {', '.join(AXIS_NAMES)})"
) from None
def code_for(name: str) -> int:
+39
View File
@@ -39,6 +39,13 @@ class PointerSink(Protocol):
def button(self, output: str, code: int, state: int) -> None:
"""An evdev button code and a ``wl_pointer.button_state``."""
def axis(self, output: str, axis: int, value: float) -> None:
"""Scroll by ``value`` wheel clicks along ``axis`` (a ``wl_pointer_axis``).
Positive vertical is *down* and positive horizontal is *right*, which is
the protocol's direction and not a choice of ours.
"""
def frame(self, output: str) -> None:
"""Commit the queued events. Nothing is delivered until this."""
@@ -107,6 +114,37 @@ class Dispatcher:
self._pressed.pop(name, None)
return {"ok": True}
def _op_axis(self, request: dict) -> dict[str, Any]:
"""Scroll the aimed output.
The output is implicit, like ``button``: there is one cursor, and a
scroll belongs to whatever it is currently over. A caller that wants to
scroll somewhere else warps first, which is also what makes the gesture
serialisable by the lease.
"""
name = request.get("axis", "vertical")
if not isinstance(name, str):
raise Rejected("'axis' must be a string")
try:
code = buttons.axis_for(name)
except ValueError as exc:
raise Rejected(str(exc)) from None
value = request.get("value", 1.0)
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise Rejected("'value' must be a number of wheel clicks")
value = float(value)
if value != value or value in (float("inf"), float("-inf")):
raise Rejected("'value' must be finite")
if abs(value) > buttons.MAX_AXIS_VALUE:
raise Rejected(
f"'value' {value} exceeds the {buttons.MAX_AXIS_VALUE:g} wheel-click limit"
)
self._sink.axis(self._aimed(), code, value)
return {"ok": True}
def _op_frame(self, request: dict) -> dict[str, Any]:
self._sink.frame(self._aimed())
return {"ok": True}
@@ -131,6 +169,7 @@ class Dispatcher:
_ops = {
"warp": _op_warp,
"button": _op_button,
"axis": _op_axis,
"frame": _op_frame,
"pressed": _op_pressed,
"release_all": _op_release_all,
+589 -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,250 @@ 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")
#: Axis names the driver knows (``hhstream_pointer.buttons.AXES``), mirrored for
#: the same reason and with the same caveat: the driver remains the authority.
#: Direction is the sign of the amount, so there is deliberately no "down" or
#: "up" here -- the protocol fixes positive as down (vertical) and right
#: (horizontal), and a second vocabulary over it is how a scroll ends up
#: backwards.
AXES = ("vertical", "horizontal")
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()
)
scroll = with_lease(add_gesture(
"scroll",
_cmd_pointer_scroll,
help="scroll the session's screen where the cursor is",
description=(
"Scroll the session's screen. --amount is signed wheel clicks: "
"positive scrolls down (vertical) or right (horizontal), which is "
"the protocol's direction rather than a choice of ours. The cursor "
"does not move, so the resume point keeps its coordinates -- but it "
"is re-stamped, because a scroll is the session acting and a later "
"resume should know when it last did."
),
))
scroll.add_argument("id", help="session id")
scroll.add_argument(
"--axis", default="vertical", choices=AXES, metavar="A",
help="vertical (default) or horizontal",
)
scroll.add_argument(
"--amount", type=float, default=3.0, metavar="N",
help="wheel clicks, signed; positive is down/right (default: 3)",
)
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 +566,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 +636,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 +692,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 +770,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 +830,233 @@ 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_scroll(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.scroll",
id=args.id,
lease_id=lease_id,
axis=args.axis,
amount=args.amount,
)
def render(r: dict[str, Any]) -> str:
return (
f"{r.get('id')}: scrolled {r.get('axis')} by {r.get('amount')} "
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)
+12 -1
View File
@@ -23,7 +23,7 @@ from .clock import Clock, parse_duration
from .compositor import CompositorError, CompositorTarget
from .launcher import Launcher
from .manager import DEFAULT_SETTLE_S, ManagerConfig, SessionManager
from .policy import Policy, PolicyError, load_policy
from .policy import Policy, PolicyError, load_policy, load_settings
from .registry import Registry
from .server import ControlServer
@@ -166,12 +166,23 @@ async def serve(
# against whatever directory the app happens to be started in.
state_dir = Path(args.state_dir).resolve()
runtime_dir = Path(args.runtime_dir).resolve()
# The same file the allowlist comes from. Read here rather than in the
# manager so the manager keeps taking a plain ManagerConfig, which is what
# its tests build directly.
settings = load_settings(args.config)
config = ManagerConfig(
state_dir=state_dir,
runtime_dir=runtime_dir,
policy=policy,
settle_s=args.settle,
compositor=compositor,
containers_enabled=settings.containers_enabled,
container_base=settings.container_base,
container_slots=settings.container_slots,
container_mode=settings.container_mode,
quarantine_workspace=settings.quarantine_workspace,
pointer_ttl_s=settings.pointer_ttl_s,
pointer_max_s=settings.pointer_max_s,
)
manager = SessionManager(
config,
+64
View File
@@ -86,9 +86,15 @@ class ContainerHost:
mode: tuple[int, int] = DEFAULT_MODE,
quarantine_workspace: str = DEFAULT_QUARANTINE_WORKSPACE,
ipc: HyprlandIPC | None = None,
enabled: bool = True,
) -> None:
self.runtime_dir = None if runtime_dir is None else Path(runtime_dir)
self.allocator = allocator
#: Whether this broker gives sessions containers at all. Off is a
#: configuration, not a failure: `available()` reports it, and the manager
#: already knows what to do with an unavailable host (sessions without
#: containers), so nothing else has to branch on it.
self.enabled = enabled
self.mode = mode
self.quarantine_workspace = quarantine_workspace
self._wanted_signature = signature
@@ -138,8 +144,19 @@ class ContainerHost:
``version`` is the cheapest round trip that proves the socket is a live
compositor and not a leftover inode.
A host switched off by configuration is unavailable on purpose, and the
reason says which key turned it off -- otherwise a machine with
containers disabled looks identical to one whose compositor is down, and
the operator goes hunting for a broken compositor that is fine.
"""
if not self.enabled:
self._last_error = (
"containers are disabled in the config "
"([compositor] containers_enabled = false)"
)
return False
try:
self.ipc().version()
except CompositorUnavailable as exc:
@@ -219,6 +236,53 @@ class ContainerHost:
raise
return plan
def claim(
self, app_id: str, pid: int | None, workspace: int, output: str | None
) -> ContainerFacts | None:
"""Put this session's window on its desk's workspace, and show it.
Assignment is by **pid**, not by class. The compositor reports every
client's pid and the broker knows each session's, so this needs nothing
from the application -- which is the point: the per-session window rule
matches a class stamp that foot, GTK, Qt and the chromium wrapper all
ignore, so a rule-bound desk is empty while the window it was made for
sits in the quarantine backstop.
Two dispatches, in this order: move the window, then make its workspace
the one its own output is showing. Moving alone leaves the window on a
workspace nobody is looking at -- ``foreground`` false, and a frame
capture of wallpaper.
Everything is read back. What the caller records is where the window
*is* afterwards, never where it was sent.
"""
facts = self.read_back(app_id, pid)
if facts is None:
return None
window = facts.window or {}
address = window.get("address")
if facts.workspace != workspace and address:
self.dispatch(
[
"hyprctl",
"dispatch",
"movetoworkspacesilent",
f"{workspace},address:{address}",
]
)
if output is not None and not self.is_showing(workspace, output):
self.dispatch(["hyprctl", "dispatch", "workspace", str(workspace)])
return self.read_back(app_id, pid) or facts
def is_showing(self, workspace: int, output: str) -> bool:
"""Is ``output`` the one displaying ``workspace`` right now?"""
for monitor in self.ipc().monitors():
if monitor.name == output:
return monitor.active_workspace_id == workspace
return False
def remove(self, output: str) -> None:
"""Remove one output of ours. Refuses a name we could not have made."""
+11
View File
@@ -83,6 +83,17 @@ class PointerDriver:
def button(self, button: str, state: str) -> None:
self.request({"op": "button", "button": button, "state": state})
def axis(self, axis_name: str, value: float) -> None:
"""Scroll the aimed output by ``value`` wheel clicks along ``axis_name``.
Positive vertical is down, positive horizontal is right (the protocol's
direction). The output is whatever the last ``warp`` aimed at, so a
scroll into another session is a warp first -- which is also what the
lease serialises.
"""
self.request({"op": "axis", "axis": axis_name, "value": float(value)})
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."""
+88 -6
View File
@@ -33,6 +33,7 @@ watching an idle desktop.
from __future__ import annotations
import json
import logging
import os
import socket
import stat
@@ -49,6 +50,8 @@ INSTANCE_SUBDIR = "hypr"
REQUEST_SOCKET_NAME = ".socket.sock"
EVENT_SOCKET_NAME = ".socket2.sock"
log = logging.getLogger("hhstreamd.ipc")
#: 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
@@ -95,6 +98,7 @@ class CompositorUnavailable(Exception):
@dataclass(frozen=True)
class Monitor:
id: int
name: str
x: int
y: int
@@ -237,6 +241,13 @@ def _monitor(raw: dict) -> Monitor:
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),
@@ -384,9 +395,23 @@ class HyprlandIPC:
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."""
@classmethod
def _sole_instance(cls, hypr: Path) -> str:
"""The live instance under ``<runtime_dir>/hypr``, or a refusal.
A restart leaves its directory behind — the compositor's log outlives
it — so after two restarts this directory holds two names and neither is
obviously the real one. Refusing outright (which this used to do) is
safe but wrong after every rebuild: the broker cannot reach any
compositor, so no container can be created and the pointer has nothing to
aim at, all for want of a corpse being cleared.
So each candidate is *asked*, on its own request socket, for its version,
and one that answers is the compositor. Nothing is inferred from
timestamps unless more than one answers — a dead instance's log file can
easily be newer than a live instance's socket, so age is the weakest
signal available and is used only to break a tie.
"""
try:
with os.scandir(hypr) as entries:
@@ -399,12 +424,69 @@ class HyprlandIPC:
raise CompositorUnavailable(
f"compositor instance dir {hypr} holds no instance; is the compositor running?"
)
if len(names) > 1:
if len(names) == 1:
return names[0]
answered = [name for name in names if cls._answers(hypr / name)]
if len(answered) == 1:
log.info(
"compositor instance dir %s holds %d instances (%s); %s answered, "
"using it and ignoring the rest",
hypr,
len(names),
", ".join(names),
answered[0],
)
return answered[0]
if not answered:
raise CompositorUnavailable(
f"compositor instance dir {hypr} holds {len(names)} instances "
f"({', '.join(names)}); set {SIGNATURE_ENV} or pass a signature"
f"({', '.join(names)}) and none of them answered; set "
f"{SIGNATURE_ENV} or pass a signature"
)
return names[0]
newest = max(answered, key=lambda name: cls._socket_age(hypr / name))
log.warning(
"compositor instance dir %s holds %d answering instances (%s); using the "
"most recently modified, %s — pass %s to be certain",
hypr,
len(answered),
", ".join(answered),
newest,
SIGNATURE_ENV,
)
return newest
@classmethod
def _answers(cls, directory: Path) -> bool:
"""Does this instance dir hold a request socket that replies?
The probe is the real protocol, not a file check: a socket that exists
but belongs to a compositor that is gone looks identical on disk, and
the only way to tell them apart is to ask a question with a known
answer.
"""
request = directory / REQUEST_SOCKET_NAME
try:
mode = request.stat().st_mode
except OSError:
return False
if not stat.S_ISSOCK(mode):
return False
try:
cls(request, directory / EVENT_SOCKET_NAME).query("version")
except (CompositorUnavailable, OSError):
return False
return True
@staticmethod
def _socket_age(directory: Path) -> float:
"""Modification time of the request socket, for tie-breaking only."""
try:
return (directory / REQUEST_SOCKET_NAME).stat().st_mtime
except OSError:
return 0.0
# -- the request socket ------------------------------------------------
+136 -1
View File
@@ -50,7 +50,12 @@ from . import containers, procmon
from .audit import AuditLog
from .clock import Clock, iso
from .compositor import CompositorTarget
from .container_host import DEFAULT_MODE, DEFAULT_QUARANTINE_WORKSPACE, ContainerHost
from .container_host import (
DEFAULT_MODE,
DEFAULT_QUARANTINE_WORKSPACE,
ContainerFacts,
ContainerHost,
)
from .driver import DriverRejected, DriverUnavailable, PointerDriver
from .ipc import CompositorUnavailable
from .launcher import Launcher
@@ -116,6 +121,12 @@ DEFAULT_CONTAINER_SLOTS = 4
#: and "click 10000 times" is not a gesture.
MAX_CLICK_COUNT = 3
#: The largest scroll one request may carry, in wheel clicks. The driver
#: enforces the same ceiling with its own copy (they are separate processes and
#: neither imports the other); this one exists so the broker refuses early with a
#: message naming the caller's value rather than relaying the driver's.
MAX_SCROLL_AMOUNT = 100.0
SIGNALS_BY_NAME = {
"TERM": signal.SIGTERM,
"SIGTERM": signal.SIGTERM,
@@ -161,6 +172,11 @@ class ManagerConfig:
signature: str | None = None
container_base: int = DEFAULT_CONTAINER_BASE
container_slots: int = DEFAULT_CONTAINER_SLOTS
#: Whether sessions get their own output and workspace. False means "process
#: groups on the shared output", which is what the machine ran before
#: containers existed, and what a deployment that cannot match windows to
#: containers yet should be configured with.
containers_enabled: bool = True
container_mode: tuple[int, int] = DEFAULT_MODE
quarantine_workspace: str = DEFAULT_QUARANTINE_WORKSPACE
readback_s: float = DEFAULT_READBACK_S
@@ -213,6 +229,7 @@ class SessionManager:
signature=config.signature,
mode=config.container_mode,
quarantine_workspace=config.quarantine_workspace,
enabled=config.containers_enabled,
)
# The lease runs on CLOCK_BOOTTIME like every other deadline here, so a
# host suspended mid-gesture does not come back believing the lease is
@@ -529,6 +546,10 @@ class SessionManager:
# `container.reconcile` picks it up later. Nothing is invented.
log.info("%s: no window in clients -j yet; workspace and window stay null", session.id)
return
scene = session.container or {}
workspace, output = scene.get("workspace"), scene.get("output")
if workspace is not None and output is not None:
facts = await self._claim(session, app_id, facts, workspace, output)
session.workspace = facts.workspace
session.window = facts.window
session.foreground = facts.foreground
@@ -551,6 +572,44 @@ class SessionManager:
)
self.registry.persist(session, force=True)
async def _claim(
self,
session: Session,
app_id: str,
facts: ContainerFacts,
workspace: int,
output: str,
) -> ContainerFacts:
"""Move the session's window onto its desk, if it is not already there.
Skipped when the window is already home *and* the desk is showing it,
so the steady state costs nothing. Otherwise the compositor is asked to
move it and then read back, and what gets recorded is where the window
ended up -- an audit event is written only when something actually
changed, so the trail stays a record of moves rather than of polls.
"""
if facts.workspace == workspace and facts.foreground:
return facts
try:
claimed = self.host.claim(app_id, session.pid, workspace, output)
except CompositorUnavailable as exc:
log.error("%s: claiming its window failed: %s", session.id, exc)
self.containers_available = False
return facts
if claimed is None:
return facts
if claimed.workspace != facts.workspace or claimed.foreground != facts.foreground:
self.audit.emit(
"container_claimed",
session=session.id,
from_workspace=facts.workspace,
workspace=claimed.workspace,
foreground=claimed.foreground,
address=(claimed.window or {}).get("address"),
)
return claimed
async def shutdown(self) -> None:
"""Stop watching, flush the mirror. **Sessions are left running.**
@@ -1479,6 +1538,15 @@ class SessionManager:
except CompositorUnavailable as exc:
self.containers_available = False
return [{"id": session.id, "field": "compositor", "error": str(exc)}]
scene = session.container or {}
workspace, output = scene.get("workspace"), scene.get("output")
if facts is not None and workspace is not None and output is not None:
# Reconcile is the second place a window can be found: the first is
# the read-back at start, and an application slow to map one -- or
# one that reopened -- turns up only here. Claiming it is a repair,
# so it happens before the diff is taken: what gets reported is the
# difference between the old record and where the window now is.
facts = await self._claim(session, app_id, facts, workspace, output)
observed = {
"workspace": None if facts is None else facts.workspace,
"window": None if facts is None else facts.window,
@@ -1652,6 +1720,44 @@ class SessionManager:
"bookmark": self._restore_point(session, output),
}
async def pointer_scroll(
self, session_id: str, lease_id: str, axis: Any = "vertical", amount: Any = 3
) -> dict[str, Any]:
"""Scroll the session's screen.
Same shape as a click -- the lease is checked first, then the driver is
told, then the resume point is re-stamped -- with one difference that is
worth being precise about: **the cursor does not move**. The
coordinates are therefore re-affirmed rather than changed. The stamp
advances, because a scroll is the session acting and a later resume
should know when it last did -- but not one pixel of the position
changes, and a bookmark that claimed otherwise would be fiction.
"""
session, output = await self._refresh(session_id, lease_id)
name = _axis_name(axis if axis is not None else "vertical")
clicks = _checked_amount(amount)
await self._drive("axis", name, clicks)
await self._drive("frame")
# A bookmark from a container this session no longer has is not a
# position in this one, so a missing or stale one falls back to the
# centre that the acquire would have aimed at.
known = self._restore_point(session, output) or {}
mark = self._mark(
session,
lease_id,
output,
float(known.get("x", 0.5)),
float(known.get("y", 0.5)),
)
self.audit.emit("pointer_scroll", session=session.id, axis=name, amount=clicks)
return {
"id": session.id,
"axis": name,
"amount": clicks,
"bookmark": mark,
}
async def pointer_release(self, session_id: str, lease_id: str) -> dict[str, Any]:
"""Give the cursor back, leaving nothing pressed and a bookmark behind."""
@@ -2073,6 +2179,35 @@ def _button_name(value: Any) -> str:
return value
def _axis_name(value: Any) -> str:
if not isinstance(value, str) or not value:
raise ManagerError("invalid_argument", f"axis must be a name, got {value!r}")
return value
def _checked_amount(value: Any) -> float:
"""A scroll amount in wheel clicks, signed.
Signed rather than split into `--up`/`--down`: the protocol carries direction
in the sign (positive vertical is down), and a second vocabulary on top of it
is how a scroll ends up backwards. Zero is refused because it is never
intended -- it is a caller that forgot to pass an amount.
"""
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ManagerError(
"invalid_argument", f"amount must be a number of wheel clicks, got {value!r}"
)
amount = float(value)
if amount == 0 or abs(amount) > MAX_SCROLL_AMOUNT:
raise ManagerError(
"invalid_argument",
f"amount must be non-zero and at most {MAX_SCROLL_AMOUNT:g} wheel clicks, "
f"got {amount}",
)
return amount
def _checked_count(value: Any) -> int:
if isinstance(value, bool) or not isinstance(value, int):
raise ManagerError("invalid_argument", f"count must be an integer, got {value!r}")
+88
View File
@@ -169,6 +169,94 @@ def check_argv(argv: Any) -> None:
# --------------------------------------------------------------------------
@dataclass(frozen=True, slots=True)
class Settings:
"""What the config file says that is not the allowlist.
Kept beside :class:`Policy` because both come out of the same TOML file, and
read by ``__main__`` rather than by the manager, so the manager keeps taking a
plain :class:`~hhstreamd.manager.ManagerConfig` that a test can build
directly. Before this existed the module rendered these keys into the file
and the broker read none of them: a deployment could turn containers off, or
move a lease deadline, and be silently ignored while the defaults happened to
make it look honoured.
The defaults mirror the manager's own; the module always renders every key,
so they matter only for a config written by hand.
"""
containers_enabled: bool = True
container_base: int = 1000
container_slots: int = 4
container_mode: tuple[int, int] = (1280, 720)
quarantine_workspace: str = "special:quarantine"
pointer_ttl_s: float = 30.0
pointer_max_s: float = 300.0
def _mode(value: Any, key: str) -> tuple[int, int]:
"""Parse ``"1280x720"`` into ``(1280, 720)``; refuse anything else.
Refusing matters more than being permissive here: a container created at the
wrong size is a session whose window does not fit its own screen, which looks
like an application bug rather than a typo in a config file.
"""
if isinstance(value, str) and "x" in value:
width, _, height = value.partition("x")
try:
return int(width), int(height)
except ValueError:
pass
if isinstance(value, (list, tuple)) and len(value) == 2:
return int(value[0]), int(value[1])
raise PolicyError(
"invalid_argument",
f"[compositor] {key} must look like \"1280x720\", got {value!r}",
)
def settings_from_dict(data: dict[str, Any]) -> Settings:
defaults = data.get("defaults", {})
if not isinstance(defaults, dict):
raise PolicyError("invalid_argument", "[defaults] must be a table")
compositor = data.get("compositor", {})
if not isinstance(compositor, dict):
raise PolicyError("invalid_argument", "[compositor] must be a table")
pointer = data.get("pointer", {})
if not isinstance(pointer, dict):
raise PolicyError("invalid_argument", "[pointer] must be a table")
return Settings(
containers_enabled=bool(compositor.get("containers_enabled", True)),
container_base=int(compositor.get("workspace_base", 1000)),
container_slots=int(defaults.get("max_containers", 4)),
container_mode=_mode(compositor.get("container_mode", "1280x720"), "container_mode"),
quarantine_workspace=str(
compositor.get("quarantine_workspace", "special:quarantine")
),
pointer_ttl_s=float(pointer.get("lease_ttl_s", 30.0)),
pointer_max_s=float(pointer.get("lease_max_s", 300.0)),
)
def load_settings(path: Path | str | None) -> Settings:
"""Read the non-allowlist settings from the file :func:`load_policy` reads.
A missing file is the defaults, for the same reason a missing allowlist is an
empty one: a misconfigured deployment should behave conservatively, not fail
to start.
"""
if path is None:
return Settings()
path = Path(path)
if not path.exists():
return Settings()
with open(path, "rb") as fh:
return settings_from_dict(tomllib.load(fh))
def load_policy(path: Path | str | None) -> Policy:
"""Read the allowlist from a TOML file.
+2
View File
@@ -148,6 +148,7 @@ VERBS = (
"pointer.move",
"pointer.button",
"pointer.click",
"pointer.scroll",
"pointer.release",
"pointer.state",
)
@@ -171,6 +172,7 @@ MUTATING_VERBS = frozenset(
"pointer.move",
"pointer.button",
"pointer.click",
"pointer.scroll",
"pointer.release",
}
)
+13
View File
@@ -70,6 +70,7 @@ class ControlServer:
"pointer.move": self._op_pointer_move,
"pointer.button": self._op_pointer_button,
"pointer.click": self._op_pointer_click,
"pointer.scroll": self._op_pointer_scroll,
"pointer.release": self._op_pointer_release,
"pointer.state": self._op_pointer_state,
}
@@ -356,6 +357,18 @@ class ControlServer:
)
)
async def _op_pointer_scroll(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
return protocol.ok(
**await self.manager.pointer_scroll(
request.get("id"),
request.get("lease_id"),
request.get("axis", "vertical"),
request.get("amount", 3),
)
)
async def _op_pointer_release(
self, request: dict[str, Any], caller: dict[str, Any]
) -> dict[str, Any]:
+81 -5
View File
@@ -1,17 +1,25 @@
"""Finding the instance, and refusing to pick one when there is a choice.
"""Finding the instance: one answer beats a name that merely exists.
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.
Two instance dirs and no signature used to be a hard refusal. It still is when
neither answers — a broker that guessed would aim its queries, and later its
pointer, at someone else's desktop. But a *dead* instance directory is left
behind by every compositor restart, so refusing on two names made the broker
blind after every rebuild. The compositor that answers a version request is the
one that exists; the corpse beside it is a log file.
"""
from __future__ import annotations
import os
import socket
import threading
import pytest
from hhstreamd.ipc import SIGNATURE_ENV, CompositorUnavailable, HyprlandIPC
BANNER = b"Hyprland 0.56.2 built from branch v0.56.2-b\nTag: v0.56.2\n"
def bind(path):
"""A bound, listening socket at ``path``, so discovery sees a real one."""
@@ -22,6 +30,33 @@ def bind(path):
return sock
def answering(path):
"""A socket with a compositor behind it: it replies to a version request."""
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(str(path))
sock.listen(4)
def serve() -> None:
while True:
try:
conn, _ = sock.accept()
except OSError:
return
with conn:
# The client half-closes after writing, so the request ends at
# EOF -- the same shape the real compositor sees.
while conn.recv(4096):
pass
try:
conn.sendall(BANNER)
except OSError:
pass
threading.Thread(target=serve, daemon=True).start()
return sock
def test_single_instance_is_discovered(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
sock = bind(instance / ".socket.sock")
@@ -47,19 +82,60 @@ def test_zero_instances_under_hypr(runtime_dir, monkeypatch):
HyprlandIPC.discover(runtime_dir)
def test_two_instances_without_a_signature_refuses(runtime_dir, instance, monkeypatch):
def test_two_instances_and_one_answers_uses_the_one_that_answers(
runtime_dir, instance, monkeypatch
):
"""The corpse beside the live compositor must not make the broker blind."""
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
corpse = runtime_dir / "hypr" / "deadbee_1700000001"
corpse.mkdir()
(corpse / "hyprland.log").write_text("this compositor is gone; only its log is here\n")
sock = answering(instance / ".socket.sock")
try:
ipc = HyprlandIPC.discover(runtime_dir)
finally:
sock.close()
assert ipc.request_socket == instance / ".socket.sock"
def test_two_instances_and_neither_answers_refuses(runtime_dir, instance, monkeypatch):
"""Nothing answering is still the dangerous case, and still refused."""
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
other = runtime_dir / "hypr" / "deadbee_1700000001"
other.mkdir()
bind(instance / ".socket.sock").close()
(other / "hyprland.log").write_text("dead\n")
(instance / ".socket.sock").write_text("not a socket")
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 "none of them answered" in message
assert SIGNATURE_ENV in message
def test_two_answering_instances_pick_the_most_recent(runtime_dir, instance, monkeypatch):
"""Two live compositors is a real ambiguity: take the newest, and say so."""
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
older = runtime_dir / "hypr" / "aaaaaaa_1700000001"
older.mkdir()
older_sock = answering(older / ".socket.sock")
newer = runtime_dir / "hypr" / "bbbbbbb_1700000002"
newer.mkdir()
newer_sock = answering(newer / ".socket.sock")
try:
os.utime(older / ".socket.sock", (1_700_000_001, 1_700_000_001))
os.utime(newer / ".socket.sock", (1_700_000_002, 1_700_000_002))
ipc = HyprlandIPC.discover(runtime_dir)
finally:
older_sock.close()
newer_sock.close()
assert ipc.request_socket == newer / ".socket.sock"
def test_two_instances_with_an_explicit_signature(runtime_dir, instance, monkeypatch):
monkeypatch.delenv(SIGNATURE_ENV, raising=False)
other = runtime_dir / "hypr" / "deadbee_1700000001"
+21
View File
@@ -37,6 +37,9 @@ 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
@@ -47,6 +50,24 @@ def test_monitors(servers, good_handler, ipc):
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()
+73 -2
View File
@@ -34,6 +34,9 @@ class RecordingSink:
def button(self, output, code, state):
self.calls.append(("button", output, code, state))
def axis(self, output, axis, value):
self.calls.append(("axis", output, axis, value))
def frame(self, output):
self.calls.append(("frame", output))
@@ -105,6 +108,51 @@ def test_buttons_follow_the_last_warp_not_the_first(driver, sink):
assert sink.calls[-1] == ("button", "hh-beta", LEFT, DOWN)
# -- axis (scrolling) -------------------------------------------------------
def test_axis_scrolls_the_aimed_output_and_sends_no_implicit_frame(driver, sink):
warp(driver)
sink.calls.clear()
assert driver.handle({"op": "axis", "axis": "vertical", "value": 3}) == {"ok": True}
assert sink.calls == [("axis", "hh-alpha", buttons.AXES["vertical"], 3.0)]
def test_axis_defaults_to_one_vertical_click(driver, sink):
warp(driver)
sink.calls.clear()
assert driver.handle({"op": "axis"}) == {"ok": True}
assert sink.calls == [("axis", "hh-alpha", buttons.AXES["vertical"], 1.0)]
def test_a_horizontal_scroll_is_the_other_axis_and_keeps_the_sign(driver, sink):
warp(driver)
sink.calls.clear()
assert driver.handle({"op": "axis", "axis": "horizontal", "value": -2}) == {"ok": True}
assert sink.calls == [("axis", "hh-alpha", buttons.AXES["horizontal"], -2.0)]
# Two names, two axes -- and positive is down/right, per the protocol rather
# than per us, which is why direction travels in the sign and not the name.
assert buttons.AXES["vertical"] != buttons.AXES["horizontal"]
def test_a_scroll_goes_to_the_pointer_the_last_warp_aimed(driver, sink):
warp(driver, output="hh-alpha")
warp(driver, output="hh-beta")
sink.calls.clear()
driver.handle({"op": "axis", "value": 5})
assert sink.calls == [("axis", "hh-beta", buttons.AXES["vertical"], 5.0)]
def test_scroll_before_any_warp_is_refused(driver, sink):
assert driver.handle({"op": "axis", "value": 3})["ok"] is False
assert sink.calls == [], "a scroll with nothing aimed must emit nothing"
# -- pressed / release_all --------------------------------------------------
@@ -220,6 +268,13 @@ def test_a_failed_warp_does_not_change_the_aim():
({"op": "button", "button": "left"}, "'state' must be"),
({"op": "button", "button": "pinky", "state": "down"}, "unknown button 'pinky'"),
({"op": "button", "button": "left", "state": "sideways"}, "unknown button state"),
({"op": "axis", "axis": "diagonal"}, "unknown axis 'diagonal'"),
({"op": "axis", "axis": 0}, "'axis' must be a string"),
({"op": "axis", "value": "a lot"}, "'value' must be a number"),
({"op": "axis", "value": True}, "'value' must be a number"),
({"op": "axis", "value": float("nan")}, "'value' must be finite"),
({"op": "axis", "value": 101}, "wheel-click limit"),
({"op": "axis", "value": -1e9}, "wheel-click limit"),
],
)
def test_malformed_requests_are_answered_not_fatal(sink, request_, fragment):
@@ -240,5 +295,21 @@ def test_a_non_object_request_is_refused(driver, request_):
assert "must be a JSON object" in driver.handle(request_)["error"]
def test_the_contracts_five_ops_are_exactly_what_is_implemented():
assert set(Dispatcher._ops) == {"warp", "button", "frame", "pressed", "release_all"}
def test_the_contracts_ops_are_exactly_what_is_implemented() -> None:
"""The op set cannot drift quietly.
An op that exists here and nowhere in the contract -- or the reverse --
fails this test rather than surprising whoever reads the contract next.
``axis`` is the one addition since the freeze, made deliberately so that a
session can scroll; the set is edited by hand, which is the reminder to
write it down.
"""
assert set(Dispatcher._ops) == {
"warp",
"button",
"axis",
"frame",
"pressed",
"release_all",
}
+57
View File
@@ -213,10 +213,63 @@ class FakeCompositor:
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[:2] == ["dispatch", "movetoworkspacesilent"] and len(words) == 3:
return self._move_to_workspace(words[2])
if words[:2] == ["dispatch", "workspace"] and len(words) == 3:
return self._show_workspace(words[2])
if words[:1] == ["keyword"]:
return self._keyword(command[len("keyword") :].strip())
return f"unknown request {command!r}"
# -- dispatches -------------------------------------------------------
def _move_to_workspace(self, spec: str) -> str:
"""``<workspace>,address:<addr>`` -- what the broker claims with.
Moving a window is the one thing that puts a real application on its
desk, because no allowlisted app carries the class the rule matches.
"""
workspace_text, _, address = spec.partition(",address:")
if not workspace_text.isdigit() or not address:
return f"malformed move {spec!r}"
client = next((c for c in self._clients if c["address"] == address), None)
if client is None:
return f"no such window {address}"
workspace = int(workspace_text)
monitor = next(
(m["name"] for m in self._monitors if m["id"] == client["monitor"]), None
)
if not any(w["id"] == workspace for w in self._workspaces):
self._workspaces.append(
{"id": workspace, "name": str(workspace), "monitor": monitor, "windows": 0}
)
for entry in self._workspaces:
if entry["id"] == client["workspace"]["id"]:
entry["windows"] = max(0, entry["windows"] - 1)
if entry["id"] == workspace:
entry["windows"] += 1
client["workspace"] = {"id": workspace, "name": str(workspace)}
return "ok"
def _show_workspace(self, workspace_text: str) -> str:
"""``workspace <n>`` -- makes that workspace the visible one.
Only meaningful on the output that holds it, which is how Hyprland
behaves: the workspace's own monitor switches to it.
"""
if not workspace_text.lstrip("-").isdigit():
return f"malformed workspace {workspace_text!r}"
workspace = int(workspace_text)
holder = next((w["monitor"] for w in self._workspaces if w["id"] == workspace), None)
if holder is None:
return f"no such workspace {workspace}"
for monitor in self._monitors:
if monitor["name"] == holder:
monitor["activeWorkspace"] = {"id": workspace, "name": str(workspace)}
return "ok"
def _keyword(self, rest: str) -> str:
name, _, body = rest.partition(" ")
if name == "workspace":
@@ -353,6 +406,10 @@ class RecordingSink:
self._check()
self.calls.append(("button", output, code, state))
def axis(self, output: str, axis: int, value: float) -> None:
self._check()
self.calls.append(("axis", output, axis, value))
def frame(self, output: str) -> None:
self._check()
self.calls.append(("frame", output))
@@ -276,6 +276,47 @@ def test_container_reconcile_reports_the_difference_it_repaired(rig: Rig):
assert rig.daemon.session(session_id)["window"] is None
def test_a_window_that_lands_outside_its_desk_is_moved_onto_it(rig: Rig):
"""The case the class-matching rule could never handle.
Every allowlisted application keeps its own class, so the per-session rule
matches nothing and the window is swept to the quarantine backstop — a desk
created and left empty. The compositor reports each client's pid, so the
window can still be claimed: moved onto its own desk's workspace, with that
workspace made the visible one, and read back afterwards to say so.
"""
rig.compositor.auto_window = False
session_id = start(rig.daemon, "sleeper")
# It turns up on the main screen instead — where a quarantined window goes.
rig.compositor.add_window(f"hh-{session_id}", 1, "HEADLESS-1", pid=WINDOW_PID)
rig.daemon.call("container.reconcile", id=session_id)
record = rig.daemon.session(session_id)
desk = record["container"]
assert record["workspace"] == desk["workspace"], "the read-back says where it is"
assert record["foreground"] is True, "its desk is showing it"
assert desk["state"] != "degraded"
commands = rig.plan_commands()
assert (
f"dispatch movetoworkspacesilent {desk['workspace']},"
f"address:{record['window']['address']}" in commands
), commands
assert f"dispatch workspace {desk['workspace']}" in commands, commands
def test_a_window_already_on_its_desk_is_not_moved(rig: Rig):
"""The steady state costs nothing: a move is a real change on screen."""
session_id = start(rig.daemon, "sleeper")
rig.daemon.call("container.reconcile", id=session_id)
assert rig.daemon.session(session_id)["workspace"] == 1000
assert not [c for c in rig.plan_commands() if c.startswith("dispatch")]
# ===========================================================================
# the start-up scan
# ===========================================================================
+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]
@@ -28,6 +28,26 @@ def compositor(short_tmpdir: Path):
fake.stop()
def test_a_disabled_host_is_unavailable_and_says_why() -> None:
"""Turning containers off must be configuration, not a false compositor.
``available()`` is the whole mechanism: the manager already treats an
unavailable host as "sessions without containers", which is exactly what
turning them off means, so nothing else has to branch on it. It must also
not ask a compositor this deployment never intended to talk to -- and its
reason has to name the key, or a machine with containers disabled looks
identical to one whose compositor is down and the operator goes hunting for a
fault that is not there.
"""
host = ContainerHost(
None, allocator=containers.WorkspaceAllocator(1000, 4), enabled=False
)
assert host.available() is False
assert "containers_enabled" in (host.last_error or "")
def make_host(fake: FakeCompositor, *, slots: int = 4) -> ContainerHost:
return ContainerHost(
fake.runtime_dir,
+104
View File
@@ -24,6 +24,10 @@ from hhstreamd.registry import ContainerState, Session, State, container_record
LEFT = 0x110
DOWN, UP = 1, 0
#: ``wl_pointer_axis``, mirrored from the driver for the same reason the button
#: codes above are: these tests assert the events, so they name the wire values.
VERTICAL, HORIZONTAL = 0, 1
def make_session(session_id: str = "foot-aaaaaa", *, container: bool = True) -> Session:
return Session(
@@ -590,3 +594,103 @@ def test_the_sweeper_expires_a_lease_nobody_came_back_for(short_tmpdir: Path):
if manager.driver is not None:
manager.driver.close()
fake.stop()
# ---------------------------------------------------------------------------
# scrolling
# ---------------------------------------------------------------------------
def test_scroll_drives_axis_then_frame_on_the_sessions_own_output(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_scroll("foot-aaaaaa", lease, "vertical", 3))
assert (reply["axis"], reply["amount"]) == ("vertical", 3.0)
assert harness.fake.sink.calls == [
("axis", "hh-foot-aaaaaa", VERTICAL, 3.0),
("frame", "hh-foot-aaaaaa"),
]
def test_scrolling_up_is_the_sign_and_not_a_different_verb(harness):
"""One verb, one axis name, and the protocol's sign carries the direction."""
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", -3))
assert harness.fake.sink.calls == [
("axis", "hh-foot-aaaaaa", VERTICAL, -3.0),
("frame", "hh-foot-aaaaaa"),
]
def test_a_horizontal_scroll_uses_the_other_axis(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "horizontal", 2))
assert harness.fake.sink.calls == [
("axis", "hh-foot-aaaaaa", HORIZONTAL, 2.0),
("frame", "hh-foot-aaaaaa"),
]
def test_a_scroll_restamps_the_resume_point_without_moving_it(harness):
"""The cursor stays put -- and the record must not pretend otherwise."""
session = harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
before = dict(session.pointer["bookmark"])
harness.clock.advance(7.0)
reply = harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "vertical", 3))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (before["x"], before["y"])
assert reply["bookmark"]["output"] == before["output"]
assert reply["bookmark"]["at"] != before["at"], "the session acted, so the stamp moved"
assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa"
@pytest.mark.parametrize("bad", [0, 0.0, 101, -101, "three", True, None])
def test_a_scroll_amount_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_scroll("foot-aaaaaa", lease, "vertical", bad))
assert exc.value.error == "invalid_argument"
def test_an_unknown_axis_is_refused_by_the_driver_not_invented(harness):
harness.add()
lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"]
harness.fake.sink.calls.clear()
with pytest.raises(ManagerError) as exc:
harness.run(harness.manager.pointer_scroll("foot-aaaaaa", lease, "diagonal", 3))
assert exc.value.error == "driver_refused"
assert harness.fake.sink.calls == [], "a refused scroll must emit nothing"
def test_a_scroll_without_the_lease_is_refused(harness):
session = harness.add()
harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))
harness.fake.sink.calls.clear()
with pytest.raises(ManagerError):
harness.run(
harness.manager.pointer_scroll("foot-aaaaaa", "not-this-lease", "vertical", 3)
)
assert harness.fake.sink.calls == []
assert session.pointer.get("bookmark") is not None, "a refused scroll changes nothing"
+78
View File
@@ -0,0 +1,78 @@
"""The config file's non-allowlist half.
These keys are rendered by the NixOS module and, until this existed, read by
nothing: a deployment could turn containers off or move a lease deadline and be
silently ignored, while the defaults happened to make it look honoured. The
values here are therefore the ones the module actually writes -- if the module's
shape changes, these tests are where that shows up.
"""
from __future__ import annotations
from pathlib import Path
import tomllib
import pytest
from hhstreamd.policy import PolicyError, load_settings, settings_from_dict
#: Exactly what `nix/module.nix` renders today, through
#: `services.hyprland-headless-stream`, with containers turned off.
MODULE_SHAPE = """
[defaults]
max_sessions = 4
idle_timeout_s = 10800
max_containers = 2
[compositor]
runtime_dir = "/run/hypr-stream"
containers_enabled = false
workspace_base = 1000
container_mode = "1280x720"
[pointer]
enabled = true
lease_ttl_s = 30
lease_max_s = 300
[apps.chromium]
exec = "/nix/store/x/bin/chromium"
args_allow = ["--ozone-platform=wayland"]
"""
def test_the_module_shape_is_read() -> None:
settings = settings_from_dict(tomllib.loads(MODULE_SHAPE))
assert settings.containers_enabled is False
# max_containers lives in [defaults] while the rest live in [compositor];
# that split is the module's, and reading only one of them is how a budget
# silently stops applying.
assert settings.container_slots == 2
assert settings.container_base == 1000
assert settings.container_mode == (1280, 720)
assert (settings.pointer_ttl_s, settings.pointer_max_s) == (30.0, 300.0)
def test_containers_default_to_on_when_the_key_is_absent() -> None:
"""A config written before this setting existed keeps working."""
assert settings_from_dict({"apps": {}}).containers_enabled is True
def test_a_bad_mode_is_refused_by_name() -> None:
"""A typo must be loud: a container at the wrong size looks like an app bug."""
with pytest.raises(PolicyError) as exc:
settings_from_dict({"compositor": {"container_mode": "wide"}})
assert "container_mode" in str(exc.value)
def test_an_absent_file_is_the_defaults(tmp_path: Path) -> None:
"""Missing config behaves conservatively rather than refusing to start."""
settings = load_settings(tmp_path / "absent.toml")
assert settings.containers_enabled is True
assert settings.container_mode == (1280, 720)
+1 -1
View File
@@ -56,7 +56,7 @@ def test_server_defaults_match_the_contract():
args = server.build_parser().parse_args([])
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", "-"]
assert server.DEFAULT_CAPTURE_COMMAND == ["grim", "-c", "-t", "png", "-"]
def test_capture_command_is_one_argv_token_per_flag():