Files
hyprland-headless-stream-pl…/src/hhstreamd/containers.py
T
HermenixandClaude Opus 5 129430bffd wire the broker to the compositor, containers and pointer
The four slices existed and nothing called them. Now the broker builds a
spatial container per session, reads back what the compositor actually did,
and aims the cursor into one container under a broker-wide lease.

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017mUq7QvQ9EZb2Wi35xj4cs
2026-10-02 19:47:33 +00:00

305 lines
13 KiB
Python

"""Spatial containers: one headless output and one workspace per session.
A session used to be a process group and nothing more, so every application
landed on whichever workspace the compositor happened to be showing. Two
sessions then shared a screen: a capture of one caught the other's windows, and
a pointer aimed at one could land in the other. A container fixes that by
giving the session a place of its own — a dedicated headless output, a numbered
workspace bound to that output as its default and marked persistent so it
survives the window closing, and a window rule that pins anything the session
spawns there.
**This module computes command lines and nothing else.** It does not run them,
does not talk to a socket, does not read a file, does not look at a clock and
does not import :mod:`hhstreamd.ipc`. That separation is deliberate: the
compositor is the part that cannot be tested without a compositor, so every
decision that *can* be made in a pure function is made here, where a unit test
can assert the exact argv list. The broker executes what comes back.
Three properties the callers depend on:
**Byte-identical output for identical arguments.** The ``create`` list is
emitted in a fixed order — create the output, bind the workspace, pin the
window, then set the mode — that does not depend on the inputs, and no set or
dict is ever iterated to build a command. The only thing a caller can vary is
what it passes in, in the order the signature names: nothing else here is a
source of order. So ``container_plan`` is safe to call twice and diff, which is
how ``container.reconcile`` decides whether a live container matches its plan.
**Argv lists, never strings.** These values reach a compositor that will act on
them, so there is no shell, no quoting and no interpolation of a caller's string
into a command *word*. The one place caller data lands inside a word is a rule
body (``workspace 1000, monitor:hh-x``), where a comma or a newline would end
one field and begin another — which is why the validation below is a control and
not a style preference.
**Validation raises, and names the value.** A session id that is not
``[a-z0-9-]``, a non-positive size, an empty app id: all :class:`ValueError`.
The broker mints its own ids and sizes, so a rejection here means a bug upstream
of us, and a message that quotes the offending value is what makes that bug
findable.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
#: Every output this broker creates carries it. A start-up scan uses the prefix
#: to tell its own orphans — outputs left behind by a crash — from the outputs a
#: human or another tool made, which it must not remove.
OUTPUT_PREFIX = "hh-"
#: Session ids as the broker mints them. Deliberately narrower than "a safe
#: command word": lowercase, digits and the dash, so the name is also a legal
#: Hyprland output name and a regex literal with nothing to escape.
SESSION_ID_RE = re.compile(r"\A[a-z0-9-]+\Z")
#: An application's window class, which we do not mint — it is whatever the
#: toolkit reports, so it has to allow the shapes real classes take
#: (``org.gnome.Nautilus``, ``Alacritty``, ``firefox-esr``). It still excludes
#: every character that could end a field in a rule body or a line in the
#: request: comma, space, quote, newline, ``$``, ``^``.
APP_ID_RE = re.compile(r"\A[A-Za-z0-9._+-]+\Z")
class NoSlots(Exception):
"""The workspace band is full. The caller refuses the session; it never reuses."""
@dataclass(frozen=True, slots=True)
class ContainerPlan:
"""What a session's container is, and the two command lists that realise it.
``create`` and ``teardown`` are complete argv lists in the order they must
run. ``teardown`` is not the reverse of ``create``: removing the output is
enough, because the workspace and window rules are keywords that die with
the compositor's configuration and name an output that no longer exists.
"""
output: str
workspace: int
mode: tuple[int, int]
create: list[list[str]]
teardown: list[list[str]]
def output_name(session_id: str) -> str:
"""``hh-<session-id>`` — the name of the session's headless output."""
return OUTPUT_PREFIX + _checked_session_id(session_id)
def contains_output(name: str) -> bool:
"""True only for an output name this broker could have created.
Used by the start-up scan, which removes what it recognises. So it is
strict in the direction that matters: a bare ``hh-``, a trailing newline or
an upper-case suffix is *not* one of ours, and a scan that answered True
would delete someone else's output.
"""
if not name.startswith(OUTPUT_PREFIX):
return False
return SESSION_ID_RE.match(name[len(OUTPUT_PREFIX) :]) is not None
def app_id_for(session_id: str) -> str:
"""The bare ``hh-<session-id>`` the launcher sets as the app's class.
Same string as the output name, and that is the point: the launcher stamps
it on the application (``--class``, ``app_id``) and
:func:`container_plan` anchors it into the window rule, so the window finds
its own workspace with no lookup and no race against the window appearing.
"""
return OUTPUT_PREFIX + _checked_session_id(session_id)
def container_plan(
session_id: str,
workspace: int,
width: int,
height: int,
app_id: str,
) -> ContainerPlan:
"""The commands that create and tear down one session's container.
``app_id`` is passed in rather than derived from ``session_id`` because the
rule has to match whatever class the application actually reports: it is
:func:`app_id_for` for a well-behaved app the launcher could stamp, and the
app's own class for one that ignores the stamp.
"""
name = output_name(session_id)
slot = _checked_int(workspace, "workspace", minimum=1)
w = _checked_int(width, "width", minimum=1)
h = _checked_int(height, "height", minimum=1)
match = _checked_app_id(app_id)
return ContainerPlan(
output=name,
workspace=slot,
mode=(w, h),
create=[
# The output first: the workspace rule below names it, and a rule
# for an output that does not exist yet binds to nothing.
["hyprctl", "output", "create", "headless", name],
# `default:true` makes this the workspace the output shows, and
# `persistent:true` keeps it alive when the last window closes — a
# container that evaporated between two applications would send the
# next window back to the shared screen.
[
"hyprctl",
"keyword",
"workspace",
f"{slot}, monitor:{name}, default:true, persistent:true",
],
# Anchored (`^...$`) so a class that merely contains the app id
# cannot claim another session's workspace. `initial_class` rather
# than the live class: applications rename their window, and the
# placement has to be decided when it is mapped.
[
"hyprctl",
"keyword",
"windowrule",
f"match:initial_class ^{match}$, workspace {slot}, monitor {name}",
],
# Last, because the mode applies to an output that now exists and
# already has its workspace; setting it earlier would resize a
# screen that is about to be replaced.
["hyprctl", "keyword", "monitor", f"{name},{w}x{h},auto,1"],
],
teardown=[["hyprctl", "output", "remove", name]],
)
def quarantine_argv(quarantine_workspace: str) -> list[list[str]] | None:
"""The backstop rule: a window that matched no container goes here.
Without it, a window with an unexpected class — a dialog spawned by a
helper process, a toolkit that rewrites its class — lands on whatever
workspace is in front, which is the leak containers exist to prevent.
**Install it before any per-session rule.** Hyprland evaluates window
rules in the order the keywords were issued and this one matches every
class, so a quarantine rule issued *after* a session's anchored rule
overrides it and every window in the system ends up in the special
workspace — containers included. The ordering cannot be enforced from
here, because this module never runs anything; the broker installs it once
at start-up, before the first ``container_plan`` is executed, and
:mod:`hhstreamd.container_host` says so at the call site.
``quarantine_workspace`` is a workspace *name* (``special:quarantine``),
not a slot out of the allocator's band — which is why this returns bare
argv and not a :class:`ContainerPlan` (CONTRACT-sessions.md v2 §3.2): a
quarantine rule has no output, no numbered workspace and no mode, and
``container_plan`` refuses the zero size one would have to invent. An
empty or blank name is how "disabled" is spelled, and the answer is
``None`` rather than an empty list — a caller that gets commands should
always have something to run.
"""
target = quarantine_workspace.strip()
if not target:
return None
_checked_rule_value(target, "quarantine_workspace")
return [
[
"hyprctl",
"keyword",
"windowrule",
f"match:initial_class .*, workspace {target}",
]
]
class WorkspaceAllocator:
"""Hands out workspace slots from a fixed band, lowest free first.
Lowest-free rather than monotonic so a long-lived broker's numbers stay
small and readable (``hyprctl workspaces`` is something a human reads), and
so the band is a real bound: ``count`` slots means at most ``count``
containers, with exhaustion surfacing as :class:`NoSlots` at allocation
rather than as a collision later.
"""
def __init__(self, base: int, count: int) -> None:
self._base = _checked_int(base, "base", minimum=1)
self._count = _checked_int(count, "count", minimum=1)
self._used: set[int] = set()
def allocate(self) -> int:
"""The lowest free slot in ``[base, base + count)``. Raises :class:`NoSlots`."""
for slot in range(self._base, self._base + self._count):
if slot not in self._used:
self._used.add(slot)
return slot
raise NoSlots(
f"workspace band {self._base}..{self._base + self._count - 1} is full "
f"({self._count} in use)"
)
def release(self, workspace: int) -> None:
"""Give a slot back. A slot we never handed out raises :class:`KeyError`.
Loudly, because the two ways to get here are a double release and a
caller releasing someone else's slot, and both mean the registry and
this allocator have drifted. Swallowing it would hand the same
workspace to two sessions a few minutes later, which is the leak that is
hard to trace back.
"""
if workspace not in self._used:
raise KeyError(
f"workspace {workspace} was not allocated by this allocator "
f"(in use: {sorted(self._used)})"
)
self._used.discard(workspace)
def in_use(self) -> list[int]:
"""Allocated slots, ascending. Sorted because callers log and diff it."""
return sorted(self._used)
def _checked_session_id(session_id: str) -> str:
if not isinstance(session_id, str) or not SESSION_ID_RE.match(session_id):
raise ValueError(
f"session id {session_id!r} is not [a-z0-9-]+; it names an output and "
"goes into a compositor command"
)
return session_id
def _checked_app_id(app_id: str) -> str:
if not isinstance(app_id, str) or not app_id:
raise ValueError(f"app id {app_id!r} is empty; a window rule needs a class to match")
if not APP_ID_RE.match(app_id):
raise ValueError(
f"app id {app_id!r} is not [A-Za-z0-9._+-]+; a window rule body is "
"comma-separated, so anything else could forge a rule field"
)
return app_id
def _checked_rule_value(value: str, label: str) -> str:
# Same reasoning as an app id, one rule field over: this ends up inside a
# `workspace <value>` field, where a comma starts the next field. The colon
# is allowed because `special:quarantine` needs it.
if not re.match(r"\A[A-Za-z0-9._:+-]+\Z", value):
raise ValueError(
f"{label} {value!r} is not [A-Za-z0-9._:+-]+; it is interpolated into "
"a comma-separated rule body"
)
return value
def _checked_int(value: int, label: str, *, minimum: int) -> int:
# bool is an int in Python, and `True` would silently become workspace 1.
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(f"{label} {value!r} is not an int")
if value < minimum:
raise ValueError(f"{label} {value!r} is not >= {minimum}")
return value