Files
hyprland-headless-stream-pl…/src/hhstreamd/ipc.py
T
HermenixandClaude Opus 5 9b77c77ee8 ipc: a client that asks the compositor instead of guessing
The broker reported `workspace: null` and `window: null` for every session
because nothing in it could talk to Hyprland.  This is that voice, and the
only place that knows the compositor's wire format: one connection per
request on `.socket.sock` (leading `/` so an argument containing a slash is
never read as output flags, `j/` where JSON is wanted), and a held, blocking
stream on `.socket2.sock`.

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

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MLiQAZCmJf66CEcLx8siYF
2026-10-02 00:12:44 +00:00

590 lines
22 KiB
Python

"""Asking the compositor what it actually has, instead of guessing.
The broker launches applications and then reports on them. Until now it had no
way to see the other side: every session's ``workspace`` and ``window`` were
``null`` because nothing in the daemon could talk to Hyprland. This module is
that voice. It is deliberately the *only* place that knows the compositor's
wire format, so a Hyprland upgrade is one file to re-read.
Three decisions shape everything here.
**Degrade, never guess.** Every failure — no instance directory, two instance
directories and no signature, a socket that is gone, a connection refused, a
reply that is not the JSON it claims to be — is :class:`CompositorUnavailable`.
Nothing returns an empty list, a ``None`` or a plausible-looking default to
stand in for "I could not ask", because a caller that cannot tell those apart
will write a guess into a session record and the operator will believe it.
**Parse defensively, inside the defined shape.** Hyprland's JSON has gained,
renamed and re-typed keys across releases, so a missing key is a *defined*
value (``None``, ``0``, ``-1``) and never a ``KeyError`` reaching the caller.
The exception is a key whose absence makes the record meaningless — a client
with no ``address`` — which is a malformed reply, not a degraded one.
**One connection per request, a held connection for events.** That is what
``hyprctl`` does and what Hyprland expects: it reads a request, writes the
reply and closes. The event socket is the opposite — a stream that must stay
open, blocking, for as long as the caller reads it. When it ends, it raises:
an event stream that stops is a failure the caller must see, because a broker
that quietly stops being told about closed windows looks identical to a broker
watching an idle desktop.
"""
from __future__ import annotations
import json
import os
import socket
import stat
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
#: Hyprland names its per-instance directory after this variable, and every
#: process it starts inherits it. It is the strongest hint available.
SIGNATURE_ENV = "HYPRLAND_INSTANCE_SIGNATURE"
#: ``<runtime dir>/hypr/<signature>/`` holds both sockets (CONTRACT §5).
INSTANCE_SUBDIR = "hypr"
REQUEST_SOCKET_NAME = ".socket.sock"
EVENT_SOCKET_NAME = ".socket2.sock"
#: Requests are local, synchronous and tiny. The compositor answers at once or
#: it is wedged; this only bounds the pathological case where it accepts the
#: connection and then stops. It is a class attribute so a test can shorten it
#: without widening ``__init__``, whose signature is frozen by the contract.
REQUEST_TIMEOUT_S = 2.0
#: Field names for the events a session broker joins on, in payload order. The
#: payload is positional and comma-separated, and the *last* named field keeps
#: any remaining commas — window titles contain them, which is precisely why a
#: naive ``split(",")`` loses the end of a title.
_EVENT_FIELDS: dict[str, tuple[str, ...]] = {
"openwindow": ("address", "workspace", "class", "title"),
"closewindow": ("address",),
"movewindow": ("address", "workspace"),
"movewindowv2": ("address", "workspace_id", "workspace"),
"windowtitle": ("address",),
"windowtitlev2": ("address", "title"),
"activewindow": ("class", "title"),
"activewindowv2": ("address",),
"changefloatingmode": ("address", "floating"),
"urgent": ("address",),
"pin": ("address", "pinned"),
"fullscreen": ("state",),
"workspace": ("name",),
"workspacev2": ("id", "name"),
"createworkspace": ("name",),
"createworkspacev2": ("id", "name"),
"destroyworkspace": ("name",),
"destroyworkspacev2": ("id", "name"),
"moveworkspace": ("name", "monitor"),
"moveworkspacev2": ("id", "name", "monitor"),
"renameworkspace": ("id", "name"),
"activespecial": ("name", "monitor"),
"focusedmon": ("monitor", "workspace"),
"monitoradded": ("name",),
"monitoraddedv2": ("id", "name", "description"),
"monitorremoved": ("name",),
}
class CompositorUnavailable(Exception):
"""No request socket, or the compositor refused. Callers degrade, never guess."""
@dataclass(frozen=True)
class Monitor:
name: str
x: int
y: int
width: int
height: int
scale: float
active_workspace_id: int | None
@dataclass(frozen=True)
class Workspace:
id: int
name: str
monitor: str | None
windows: int
is_special: bool
@dataclass(frozen=True)
class Client:
address: str
pid: int
workspace_id: int | None
monitor: str | None
class_: str
initial_class: str
title: str
stable_id: str
visible: bool
@dataclass(frozen=True)
class CursorPos:
x: int
y: int
@dataclass(frozen=True)
class Event:
name: str
data: dict
def _as_int(value: object, default: int) -> int:
"""An int, or ``default`` for anything that is not plainly one.
Hyprland has shipped ids as numbers and as numeric strings; ``bool`` is
excluded because ``True`` is not a workspace id.
"""
if isinstance(value, bool):
return default
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, str):
try:
return int(value.strip())
except ValueError:
return default
return default
def _as_float(value: object, default: float) -> float:
if isinstance(value, bool):
return default
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
try:
return float(value.strip())
except ValueError:
return default
return default
def _as_str(value: object) -> str:
"""A string, or "" — never ``None`` leaking into a field typed ``str``."""
if isinstance(value, str):
return value
if value is None:
return ""
return str(value)
def _optional_name(value: object) -> str | None:
"""A monitor name, or ``None`` when the reply did not carry one.
``clients -j`` reports ``monitor`` as a numeric *index* while
``workspaces -j`` reports it as a *name*; both are coerced to text so the
field means "what the compositor said" and ``None`` keeps its single
meaning of "the compositor said nothing".
"""
if value is None or value == "":
return None
if isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return str(int(value))
if isinstance(value, str):
return value
return None
def _nested_id(value: object) -> int | None:
"""``{"id": 3, "name": "3"}`` -> ``3``; anything else -> ``None``."""
if isinstance(value, dict):
raw = value.get("id")
if isinstance(raw, bool):
return None
if isinstance(raw, int):
return raw
if isinstance(raw, (float, str)):
parsed = _as_int(raw, -(2**62))
return None if parsed == -(2**62) else parsed
return None
def _entries(payload: object, what: str) -> list[dict]:
"""The list of objects a ``-j`` listing must be, or a malformed reply."""
if not isinstance(payload, list):
raise CompositorUnavailable(f"{what}: expected a JSON list, got {type(payload).__name__}")
out = []
for item in payload:
if not isinstance(item, dict):
raise CompositorUnavailable(
f"{what}: expected objects in the list, got {type(item).__name__}"
)
out.append(item)
return out
def _monitor(raw: dict) -> Monitor:
name = raw.get("name")
if not isinstance(name, str) or not name:
raise CompositorUnavailable("monitors: an entry has no name")
return Monitor(
name=name,
x=_as_int(raw.get("x"), 0),
y=_as_int(raw.get("y"), 0),
width=_as_int(raw.get("width"), 0),
height=_as_int(raw.get("height"), 0),
scale=_as_float(raw.get("scale"), 1.0),
# Older replies nest the active workspace; a monitor with none (an
# output just created and not yet populated) legitimately has no id.
active_workspace_id=_nested_id(raw.get("activeWorkspace")),
)
def _workspace(raw: dict) -> Workspace:
if "id" not in raw:
raise CompositorUnavailable("workspaces: an entry has no id")
ident = _as_int(raw.get("id"), -(2**62))
if ident == -(2**62):
raise CompositorUnavailable(f"workspaces: entry id is not a number ({raw.get('id')!r})")
name = _as_str(raw.get("name"))
special = raw.get("special")
return Workspace(
id=ident,
name=name,
monitor=_optional_name(raw.get("monitor")),
windows=_as_int(raw.get("windows"), 0),
# Hyprland did not always report ``special``. Where it does not, the
# two things that have always been true of a special workspace are
# its negative id and its ``special:`` name prefix.
is_special=(
bool(special)
if isinstance(special, bool)
else (ident < 0 or name.startswith("special"))
),
)
def _client(raw: dict) -> Client:
address = raw.get("address")
if not isinstance(address, str) or not address:
raise CompositorUnavailable("clients: an entry has no address")
initial_class = _as_str(raw.get("initialClass"))
pid = _as_int(raw.get("pid"), -1)
mapped = raw.get("mapped")
hidden = raw.get("hidden")
return Client(
address=address,
# -1, not 0: no process has it, so an unknown pid cannot be mistaken
# for a real one by code that only checks for falsiness.
pid=pid,
workspace_id=_nested_id(raw.get("workspace")),
monitor=_optional_name(raw.get("monitor")),
class_=_as_str(raw.get("class")),
initial_class=initial_class,
title=_as_str(raw.get("title")),
# The contract names a stable id but Hyprland publishes none. The
# initial class plus the pid is the closest honest thing: the launcher
# sets the class per session, the pid is the session's process, and
# unlike ``address`` the pair survives a window being remapped. It
# falls back to the address rather than ever being empty.
stable_id=f"{initial_class}:{pid}" if initial_class and pid > 0 else address,
# "Visible" is mapped-and-not-hidden; a missing key must not make a
# live window look gone, so absence reads as mapped.
visible=(True if mapped is None else bool(mapped)) and not bool(hidden),
)
def parse_event(line: str) -> Event:
"""``"name>>a,b,c"`` -> :class:`Event`.
The payload is positional, so :data:`_EVENT_FIELDS` names the fields for
the events the broker joins on and the last named field absorbs any
remaining commas (titles contain them). ``raw`` and ``args`` are always
present, so an event this module does not know is still usable rather than
discarded, and nothing is hidden behind the naming.
A line with no ``>>`` is a malformed reply, not an event with an odd name:
:class:`CompositorUnavailable`.
"""
text = line.rstrip("\r\n")
name, separator, payload = text.partition(">>")
if not separator or not name:
raise CompositorUnavailable(f"event line has no name>>payload separator: {text!r}")
data: dict = {"raw": payload}
if payload == "":
# An empty payload carried nothing; naming fields here would invent
# values ("" is not a window address) for an event like
# ``configreloaded>>`` that has no arguments at all.
data["args"] = []
return Event(name=name, data=data)
fields = _EVENT_FIELDS.get(name)
if fields:
parts = payload.split(",", len(fields) - 1)
data["args"] = list(parts)
data.update(zip(fields, parts))
else:
data["args"] = payload.split(",")
return Event(name=name, data=data)
class HyprlandIPC:
"""A client for one compositor instance's request and event sockets."""
#: Overridable per instance; ``__init__``'s signature is frozen, so this is
#: how a caller (or a test) bounds a wedged compositor differently.
request_timeout_s: float = REQUEST_TIMEOUT_S
def __init__(self, request_socket: Path, event_socket: Path | None = None) -> None:
self.request_socket = Path(request_socket)
self.event_socket = Path(event_socket) if event_socket is not None else None
self._event_sock: socket.socket | None = None
@classmethod
def discover(cls, runtime_dir: Path, signature: str | None = None) -> "HyprlandIPC":
"""Locate the instance under ``runtime_dir`` and return a client for it.
The signature comes from the argument, else the environment, else the
*single* directory under ``<runtime_dir>/hypr/``. Two instances and no
signature raises: picking one would silently aim the broker's queries,
and later its pointer, at the wrong desktop.
"""
hypr = Path(runtime_dir) / INSTANCE_SUBDIR
chosen = signature or os.environ.get(SIGNATURE_ENV) or None
if chosen is not None:
chosen = chosen.strip() or None
if chosen is not None and ("/" in chosen or chosen in (".", "..")):
raise CompositorUnavailable(
f"instance signature is not a directory name: {chosen!r}"
)
if chosen is None:
chosen = cls._sole_instance(hypr)
directory = hypr / chosen
request = directory / REQUEST_SOCKET_NAME
try:
mode = request.stat().st_mode
except OSError as exc:
raise CompositorUnavailable(
f"compositor request socket {request}: {exc.strerror or exc}"
) from exc
if not stat.S_ISSOCK(mode):
raise CompositorUnavailable(f"compositor request socket {request} is not a socket")
return cls(request, directory / EVENT_SOCKET_NAME)
@staticmethod
def _sole_instance(hypr: Path) -> str:
"""The one directory under ``<runtime_dir>/hypr``, or a refusal."""
try:
with os.scandir(hypr) as entries:
names = sorted(e.name for e in entries if e.is_dir())
except OSError as exc:
raise CompositorUnavailable(
f"compositor instance dir {hypr}: {exc.strerror or exc}; is the compositor running?"
) from exc
if not names:
raise CompositorUnavailable(
f"compositor instance dir {hypr} holds no instance; is the compositor running?"
)
if len(names) > 1:
raise CompositorUnavailable(
f"compositor instance dir {hypr} holds {len(names)} instances "
f"({', '.join(names)}); set {SIGNATURE_ENV} or pass a signature"
)
return names[0]
# -- the request socket ------------------------------------------------
def _wire(self, command: str) -> str:
"""The bytes Hyprland expects for ``command``.
Hyprland reads everything before the *first* ``/`` as output flags, so
a command is sent with a leading ``/`` — otherwise ``dispatch exec
/usr/bin/foo`` would be read as the flags ``dispatch exec `` followed
by a request of ``usr/bin/foo``. A command whose first word already
carries a prefix (``j/clients``) is passed through untouched, which is
what makes :meth:`query` able to reach anything this module does not
wrap.
"""
text = command.strip()
if not text:
raise CompositorUnavailable("empty request")
first = text.split(None, 1)[0]
return text if "/" in first else "/" + text
def _request(self, command: str) -> str:
"""Send one request, read the whole reply, close. Raises on any failure."""
wire = self._wire(command)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(self.request_timeout_s)
try:
sock.connect(str(self.request_socket))
except OSError as exc:
raise CompositorUnavailable(
f"compositor request socket {self.request_socket}: {exc.strerror or exc}"
) from exc
try:
sock.sendall(wire.encode())
# Half-close: the reply ends at EOF, and a compositor that
# waits for more input would otherwise deadlock against a
# client waiting for more output.
sock.shutdown(socket.SHUT_WR)
chunks = []
while True:
chunk = sock.recv(65536)
if not chunk:
break
chunks.append(chunk)
except socket.timeout as exc:
raise CompositorUnavailable(
f"compositor did not answer {command!r} within {self.request_timeout_s}s"
) from exc
except OSError as exc:
raise CompositorUnavailable(
f"compositor connection lost during {command!r}: {exc.strerror or exc}"
) from exc
finally:
sock.close()
# errors="replace" because a window title is arbitrary user data and a
# decoding accident must not masquerade as the compositor being down.
return b"".join(chunks).decode("utf-8", errors="replace")
def _json(self, command: str, what: str) -> object:
text = self._request(command)
if not text.strip():
raise CompositorUnavailable(f"{what}: empty reply")
try:
return json.loads(text)
except ValueError as exc:
# Hyprland answers an unknown or rejected request in plain text, so
# this is also where "that command does not exist here" lands.
raise CompositorUnavailable(
f"{what}: reply is not JSON ({exc}): {text[:120]!r}"
) from exc
def query(self, command: str) -> str:
"""The raw request socket, for anything this module does not wrap."""
return self._request(command)
def version(self) -> str:
"""The compositor's own version banner, verbatim.
Text, not ``version -j``: the banner is what every Hyprland has
answered, and parsing it into parts here would be this module guessing
at a shape that has changed.
"""
text = self._request("version").strip()
if not text:
raise CompositorUnavailable("version: empty reply")
return text
def monitors(self) -> list[Monitor]:
entries = _entries(self._json("j/monitors", "monitors"), "monitors")
return [_monitor(raw) for raw in entries]
def workspaces(self) -> list[Workspace]:
entries = _entries(self._json("j/workspaces", "workspaces"), "workspaces")
return [_workspace(raw) for raw in entries]
def clients(self) -> list[Client]:
return [_client(raw) for raw in _entries(self._json("j/clients", "clients"), "clients")]
def cursorpos(self) -> CursorPos:
payload = self._json("j/cursorpos", "cursorpos")
if not isinstance(payload, dict) or "x" not in payload or "y" not in payload:
raise CompositorUnavailable(
f"cursorpos: expected an object with x and y, got {payload!r}"
)
sentinel = -(2**62)
x = _as_int(payload.get("x"), sentinel)
y = _as_int(payload.get("y"), sentinel)
if x == sentinel or y == sentinel:
raise CompositorUnavailable(f"cursorpos: x and y are not numbers: {payload!r}")
return CursorPos(x=x, y=y)
# -- the event socket --------------------------------------------------
def events(self) -> Iterator[Event]:
"""Blocking iteration over the event stream.
The connection is made here rather than on the first ``next()``, so a
missing event socket is reported to the caller that asked for the
stream instead of to whatever later happens to iterate it. The
iterator never ends quietly: EOF raises :class:`CompositorUnavailable`,
because a compositor that stopped talking and a desktop where nothing
happens must not look the same.
"""
if self.event_socket is None:
raise CompositorUnavailable("no event socket was configured for this instance")
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(self.request_timeout_s)
sock.connect(str(self.event_socket))
except OSError as exc:
sock.close()
raise CompositorUnavailable(
f"compositor event socket {self.event_socket}: {exc.strerror or exc}"
) from exc
# Blocking from here on: an idle desktop sends nothing for hours and a
# read timeout would turn that into a false failure.
sock.settimeout(None)
self._close_event_sock()
self._event_sock = sock
return self._iter_events(sock)
def _iter_events(self, sock: socket.socket) -> Iterator[Event]:
buffer = b""
while True:
try:
chunk = sock.recv(65536)
except OSError as exc:
raise CompositorUnavailable(
f"compositor event socket {self.event_socket}: {exc.strerror or exc}"
) from exc
if not chunk:
# A trailing fragment is a truncated event, never an event.
raise CompositorUnavailable(
f"compositor event stream ended ({self.event_socket})"
+ (f"; {len(buffer)} bytes left unterminated" if buffer else "")
)
buffer += chunk
while b"\n" in buffer:
line, buffer = buffer.split(b"\n", 1)
yield parse_event(line.decode("utf-8", errors="replace"))
def _close_event_sock(self) -> None:
sock, self._event_sock = self._event_sock, None
if sock is None:
return
try:
# shutdown first: closing alone does not wake a thread already
# blocked in recv, and unblocking it is the point of close().
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
sock.close()
def close(self) -> None:
"""Drop the event stream. Idempotent; request sockets are per-call."""
self._close_event_sock()