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

+47
View File
@@ -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."""
+80 -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
@@ -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 ``<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:
@@ -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 ------------------------------------------------
+57 -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
@@ -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,