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.
This commit is contained in:
Hermenix committed 2026-10-03 19:39:33 +00:00
1 parent 336474793f
commit 352cfdcb24
6 files changed
+359 -12

No files matched your search

+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"
+53
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":
@@ -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
# ===========================================================================