Skip to content

hyprland/ipc: reconnect event socket after it is closed - #1560

Open
vaknin wants to merge 1 commit into
quickshell-mirror:masterfrom
vaknin:hyprland-ipc-reconnect
Open

vaknin wants to merge 1 commit into
quickshell-mirror:masterfrom
vaknin:hyprland-ipc-reconnect

Conversation

@vaknin

@vaknin vaknin commented Nov 26, 2026

Copy link
Copy Markdown

Describe your changes

The Hyprland event socket was only connected once. When Hyprland closes it (seen after lock/unlock cycles in #989), no more events arrive and every Hyprland property stays frozen until the shell restarts.

The socket now reconnects (after 100ms, doubling up to 5s), and once connected again monitors, workspaces, toplevels and the active toplevel are requested again, since events sent while disconnected are lost.

Fixes #989

Details and descisions

The existing disconnect check never fired: a socket closed by the peer goes Connected -> Closing -> Unconnected, and valid was already false when it reached Unconnected. That is why the logs in #989 show PeerClosedError but never "Hyprland event socket disconnected." The disconnect is now noticed when leaving ConnectedState, and the retry starts once the socket is Unconnected.

refreshToplevels() never removed anything, so windows closed while disconnected would stay forever. It now removes toplevels missing from j/clients, but only those that already existed when the request was sent, so one created by an event while the request is pending is not dropped. It also takes a toplevel out of its old workspace's list when j/clients puts it on another workspace, like movewindowv2 does.

The active toplevel comes from j/activewindow, which is empty when nothing is focused.

Tested with a fake Hyprland (below) that closes the event socket 2s in, changes state while nobody is connected (workspace 1 fullscreen with window a1 -> workspace 2, a1 closed, b2 active), then sends workspacev2>>3,3 at 4.5s.

Before, on 2b4501a, state stays at the moment of the drop and the later event never arrives:

WARN: Hyprland event socket error: QLocalSocket::PeerClosedError
STATE t=2.0s ws=1 fullscreen=true toplevels=[a1] active=null
STATE t=6.5s ws=1 fullscreen=true toplevels=[a1] active=null

After:

WARN: Hyprland event socket error: QLocalSocket::PeerClosedError
WARN quickshell.hyprland.ipc: Hyprland event socket disconnected.
INFO quickshell.hyprland.ipc: Reconnecting to hyprland event socket in 100 ms.
INFO quickshell.hyprland.ipc: Hyprland event socket connected.
STATE t=2.0s ws=2 fullscreen=false toplevels=[b2] active=b2
STATE t=4.5s ws=3 fullscreen=false toplevels=[b2] active=b2

With the socket path missing for 3s after the drop it retries at 100/200/400/800/1600ms and recovers the same way once the path is back. clang-format is clean.

fake Hyprland and probe config
#!/usr/bin/env python3
"""Fake Hyprland IPC for reproducing quickshell issue 989.

Serves .socket.sock (requests) and .socket2.sock (events) under
$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE. Starts with workspace 1
focused and fullscreen (window a1). At DROP seconds it closes every event
socket client, as Hyprland does, and changes state while nobody listens:
window a1 closed, window b2 opened on workspace 2, workspace 2 focused, no
fullscreen. At EVENT seconds it moves focus to workspace 3 with a live event.
With DOWN, the event socket path is missing for DOWN seconds after the drop,
so reconnect attempts fail meanwhile.
"""
import json, os, socket, sys, threading, time

DROP, EVENT = float(sys.argv[1]), float(sys.argv[2])
DOWN = float(sys.argv[3]) if len(sys.argv) > 3 else 0
d = os.path.join(os.environ["XDG_RUNTIME_DIR"], "hypr", os.environ["HYPRLAND_INSTANCE_SIGNATURE"])
os.makedirs(d, exist_ok=True)

lock = threading.Lock()
state = {"ws": "1", "fullscreen": True, "clients": [("a1", "1")], "active": "a1"}
listeners = []


def log(*a):
    print(f"[fake {time.monotonic() - T0:5.2f}s]", *a, flush=True)


def ws_obj(name):
    return {"id": int(name), "name": name, "monitor": "eDP-1", "monitorID": 0, "windows": 0,
            "hasfullscreen": state["fullscreen"] and name == state["ws"]}


def answer(req):
    with lock:
        if req == "j/status":
            return {"configProvider": "hyprlang"}
        if req == "j/monitors":
            return [{"id": 0, "name": "eDP-1", "description": "fake", "x": 0, "y": 0, "width": 1920,
                     "height": 1080, "scale": 1.0, "focused": True,
                     "activeWorkspace": {"id": int(state["ws"]), "name": state["ws"]}}]
        if req == "j/workspaces":
            names = sorted({state["ws"]} | {w for _, w in state["clients"]})
            return [ws_obj(n) for n in names]
        if req == "j/clients":
            return [{"address": "0x" + a, "title": "win " + a, "focusHistoryID": 0,
                     "workspace": {"id": int(w), "name": w}} for a, w in state["clients"]]
        if req == "j/activewindow":
            return {"address": "0x" + state["active"]} if state["active"] else {}
    return None


def serve_requests(path):
    srv = socket.socket(socket.AF_UNIX)
    srv.bind(path)
    srv.listen(16)
    while True:
        c, _ = srv.accept()
        req = c.recv(4096).decode()
        resp = answer(req)
        log("request", req)
        c.sendall(b"unknown request" if resp is None else json.dumps(resp).encode())
        c.close()


def serve_events(path):
    srv = socket.socket(socket.AF_UNIX)
    srv.bind(path)
    srv.listen(16)
    while True:
        c, _ = srv.accept()
        with lock:
            listeners.append(c)
        log("event client connected, total", len(listeners))


def emit(*events):
    with lock:
        for c in listeners:
            for e in events:
                c.sendall((e + "\n").encode())
    log("emitted", events, "to", len(listeners), "clients")


T0 = time.monotonic()
for p in (".socket.sock", ".socket2.sock"):
    try:
        os.unlink(os.path.join(d, p))
    except FileNotFoundError:
        pass
threading.Thread(target=serve_requests, args=(os.path.join(d, ".socket.sock"),), daemon=True).start()
threading.Thread(target=serve_events, args=(os.path.join(d, ".socket2.sock"),), daemon=True).start()

time.sleep(DROP)
ev = os.path.join(d, ".socket2.sock")
with lock:
    for c in listeners:
        c.shutdown(socket.SHUT_RDWR)
        c.close()
    listeners.clear()
    state.update(ws="2", fullscreen=False, clients=[("b2", "2")], active="b2")
    if DOWN:
        os.rename(ev, ev + ".off")
log("dropped event clients; state now ws=2, no fullscreen, a1 closed, b2 active")

if DOWN:
    time.sleep(DOWN)
    os.rename(ev + ".off", ev)
    log("event socket path back after", DOWN, "s")

time.sleep(EVENT - DROP - DOWN)
with lock:
    state["ws"] = "3"
emit("workspace>>3", "workspacev2>>3,3")
time.sleep(60)
import QtQuick
import Quickshell
import Quickshell.Hyprland

ShellRoot {
	Timer {
		property int n: 0
		interval: 500
		running: true
		repeat: true

		onTriggered: {
			n++;
			const ws = Hyprland.focusedWorkspace;
			const at = Hyprland.activeToplevel;
			const tls = Hyprland.toplevels.values.map(t => t.address).join(",");
			console.log(`STATE t=${(n * 0.5).toFixed(1)}s ws=${ws ? ws.name : "null"} fullscreen=${ws ? ws.hasFullscreen : "-"} toplevels=[${tls}] active=${at ? at.address : "null"}`);
			if (n >= 14) Qt.quit();
		}
	}
}

Run with XDG_RUNTIME_DIR=$(mktemp -d) HYPRLAND_INSTANCE_SIGNATURE=fake QT_QPA_PLATFORM=offscreen QT_LOGGING_RULES=quickshell.hyprland.ipc.info=true, start fake_hyprland.py 2 4.5, then quickshell -p shell.qml.

Open concerns

Reconnecting only happens after a connection was established once; a failing first connect behaves as before.

Participation

Written with an AI agent; I accept the project may close it.

Hyprland can close the event socket of a live session, after which no
event arrived again and all Hyprland state stayed frozen. Reconnect with
backoff and refresh monitors, workspaces, toplevels and the active
toplevel once connected, as events sent in between are lost.

Toplevel refreshes now also drop toplevels missing from j/clients and
move toplevels between workspace lists.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hyprland event socket is never reconnected after it drops, silently freezing all Hyprland state

1 participant