diff --git a/src/hhstreamd/container_host.py b/src/hhstreamd/container_host.py index 74b4d35..c41acdd 100644 --- a/src/hhstreamd/container_host.py +++ b/src/hhstreamd/container_host.py @@ -236,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.""" diff --git a/src/hhstreamd/ipc.py b/src/hhstreamd/ipc.py index ba39d48..ce9a14b 100644 --- a/src/hhstreamd/ipc.py +++ b/src/hhstreamd/ipc.py @@ -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 @@ -392,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 ``/hypr``, or a refusal.""" + @classmethod + def _sole_instance(cls, hypr: Path) -> str: + """The live instance under ``/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: @@ -407,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 ------------------------------------------------ diff --git a/src/hhstreamd/manager.py b/src/hhstreamd/manager.py index 134a906..e869ff0 100644 --- a/src/hhstreamd/manager.py +++ b/src/hhstreamd/manager.py @@ -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 @@ -541,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 @@ -563,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.** @@ -1491,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, diff --git a/tests/ipc/test_discovery.py b/tests/ipc/test_discovery.py index 7be09b3..2380ac0 100644 --- a/tests/ipc/test_discovery.py +++ b/tests/ipc/test_discovery.py @@ -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" diff --git a/tests/sessions/fakes.py b/tests/sessions/fakes.py index cdf2b0d..fcbea53 100644 --- a/tests/sessions/fakes.py +++ b/tests/sessions/fakes.py @@ -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: + """``,address:`` -- 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 `` -- 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": diff --git a/tests/sessions/integration/test_containers.py b/tests/sessions/integration/test_containers.py index 733f436..4ebd79f 100644 --- a/tests/sessions/integration/test_containers.py +++ b/tests/sessions/integration/test_containers.py @@ -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 # ===========================================================================