Skip to content

The agent that grows with you

feat(desktop): read the window below through Hyprland's IPC (#82226)

brooklyn!c8318460e489
diff --git a/apps/desktop/electron/hyprland.test.ts b/apps/desktop/electron/hyprland.test.ts
new file mode 100644
index 00000000000..8b58340fb86
--- /dev/null
+++ b/apps/desktop/electron/hyprland.test.ts
@@ -0,0 +1,119 @@
+/**
+ * Unit tests for the Hyprland window provider. The socket itself needs a live
+ * compositor, so what is covered here is everything that decides whether the
+ * answer is right once the bytes arrive: which instance we talk to, and the two
+ * corrections that turn `j/clients` into a front-to-back list of the windows
+ * actually on screen.
+ */
+
+import { describe, expect, it } from 'vitest'
+
+import { hyprlandSocketPath, parseHyprlandClients } from './hyprland'
+
+const SELF_PID = 42
+
+const client = (over: Record<string, unknown> = {}) => ({
+ address: '0x55d1',
+ at: [0, 0],
+ class: 'app',
+ focusHistoryID: 0,
+ pid: 1,
+ size: [800, 600],
+ title: 'a window',
+ workspace: { id: 1 },
+ ...over
+})
+
+const payload = (...clients: Array<Record<string, unknown>>) => JSON.stringify(clients)
+
+describe('hyprlandSocketPath', () => {
+ it('is null when Hyprland is not the compositor', () => {
+ expect(hyprlandSocketPath({}, 1000)).toBeNull()
+ expect(hyprlandSocketPath({ XDG_RUNTIME_DIR: '/run/user/1000' }, 1000)).toBeNull()
+ })
+
+ it('addresses the running instance, not just the user', () => {
+ const path = hyprlandSocketPath({ HYPRLAND_INSTANCE_SIGNATURE: 'abc123', XDG_RUNTIME_DIR: '/run/user/1000' }, 1000)
+
+ expect(path).toBe('/run/user/1000/hypr/abc123/.socket.sock')
+ })
+
+ it('falls back to the uid runtime dir when XDG_RUNTIME_DIR is unset', () => {
+ const path = hyprlandSocketPath({ HYPRLAND_INSTANCE_SIGNATURE: 'abc123' }, 1000)
+
+ expect(path).toBe('/run/user/1000/hypr/abc123/.socket.sock')
+ })
+})
+
+describe('parseHyprlandClients', () => {
+ it('orders by focus history, so the window the user came from is first', () => {
+ const parsed = parseHyprlandClients(
+ payload(
+ client({ class: 'kitty', focusHistoryID: 3, pid: 3 }),
+ client({ class: 'firefox', focusHistoryID: 1, pid: 2 }),
+ client({ class: 'spotify', focusHistoryID: 2, pid: 4 })
+ ),
+ SELF_PID
+ )
+
+ expect(parsed.map(w => w.app)).toEqual(['firefox', 'spotify', 'kitty'])
+ })
+
+ // The HUD floats always-on-top while the user works underneath it, so it sits
+ // well down a focus-ordered list. Keeping it in would make the caller skip
+ // past the focused app — the very window it is trying to report.
+ it('leaves our own windows out, even when the HUD itself is focused', () => {
+ const parsed = parseHyprlandClients(
+ payload(
+ client({ class: 'hermes', focusHistoryID: 0, pid: SELF_PID }),
+ client({ class: 'firefox', focusHistoryID: 1, pid: 2 })
+ ),
+ SELF_PID
+ )
+
+ expect(parsed.map(w => w.app)).toEqual(['firefox'])
+ })
+
+ // Windows on a hidden workspace share coordinates with the visible ones, so
+ // left in they win the overlap test and the tool reports a window the user
+ // cannot see.
+ it('drops windows on workspaces other than ours', () => {
+ const parsed = parseHyprlandClients(
+ payload(
+ client({ class: 'hermes', pid: SELF_PID, workspace: { id: 2 } }),
+ client({ class: 'visible', focusHistoryID: 1, pid: 2, workspace: { id: 2 } }),
+ client({ class: 'elsewhere', focusHistoryID: 1, pid: 3, workspace: { id: 7 } })
+ ),
+ SELF_PID
+ )
+
+ expect(parsed.map(w => w.app)).toEqual(['visible'])
+ })
+
+ it('keeps everything when it cannot find our own window', () => {
+ const parsed = parseHyprlandClients(
+ payload(client({ class: 'a', pid: 2, workspace: { id: 1 } }), client({ class: 'b', pid: 3, workspace: { id: 7 } })),
+ SELF_PID
+ )
+
+ expect(parsed.map(w => w.app)).toEqual(['a', 'b'])
+ })
+
+ it('maps position and size into bounds', () => {
+ const [window] = parseHyprlandClients(payload(client({ at: [120, 80], pid: 2, size: [640, 320] })), SELF_PID)
+
+ expect(window.bounds).toEqual({ x: 120, y: 80, width: 640, height: 320 })
+ })
+
+ it('skips zero-sized windows', () => {
+ const parsed = parseHyprlandClients(payload(client({ pid: 2, size: [0, 0] })), SELF_PID)
+
+ expect(parsed).toEqual([])
+ })
+
+ it('survives a payload that is not the client list', () => {
+ for (const bad of ['', 'not json', '{}', 'null']) {
+ expect(parseHyprlandClients(bad, SELF_PID)).toEqual([])
+ }
+ })
+})
diff --git a/apps/desktop/electron/hyprland.ts b/apps/desktop/electron/hyprland.ts
new file mode 100644
index 00000000000..6aa50881e96
--- /dev/null
+++ b/apps/desktop/electron/hyprland.ts
@@ -0,0 +1,177 @@
+// hyprland.ts — window enumeration for Hyprland, via the compositor's own IPC.
+//
+// `read_window_below` normally enumerates through `get-windows`, which on Linux
+// shells out to `xprop` and reads `_NET_CLIENT_LIST_STACKING`. That is an X11
+// protocol, and Wayland deliberately refuses to tell one application about
+// another's windows — so on a Wayland session the tool has nothing to work
+// with. Under XWayland it is arguably worse than nothing: it enumerates the few
+// legacy X11 clients and silently misses every native Wayland window, which on
+// a Hyprland desktop is most of them.
+//
+// Hyprland answers the question directly. `j/clients` returns every window with
+// its class, title, position, size, pid and focus history, which is richer than
+// anything the X11 path provides. This module is the provider for that; the
+// picking logic stays in window-below.ts, unchanged and shared.
+//
+// Sway and the other wlroots compositors expose the same information through
+// `swaymsg -t get_tree`. That is a different shape (a tree, not a list) and is
+// deliberately not attempted here rather than shipped untested.
+
+import net from 'node:net'
+
+import type { EnumeratedWindow } from './window-below'
+
+// Hyprland evaluates this socket synchronously and freezes for a five-second
+// timeout on an unclosed connection, so every path below destroys the socket.
+// One request per tool call, never polled.
+const REQUEST_TIMEOUT_MS = 1000
+
+/**
+ * Path to the running instance's command socket, or null when Hyprland is not
+ * the compositor.
+ *
+ * The instance signature is what makes this per-instance — two Hyprlands on one
+ * machine have two sockets. The `/run/user/<uid>` fallback mirrors Hyprland's
+ * own client code for sessions that don't export `XDG_RUNTIME_DIR`.
+ */
+export function hyprlandSocketPath(env: NodeJS.ProcessEnv, uid: number): null | string {
+ const signature = env.HYPRLAND_INSTANCE_SIGNATURE
+
+ if (!signature) {
+ return null
+ }
+
+ const runtime = env.XDG_RUNTIME_DIR ? `${env.XDG_RUNTIME_DIR}/hypr` : `/run/user/${uid}/hypr`
+
+ return `${runtime}/${signature}/.socket.sock`
+}
+
+interface HyprlandClient {
+ address?: string
+ at?: [number, number]
+ class?: string
+ pid?: number
+ size?: [number, number]
+ title?: string
+ workspace?: { id?: number }
+}
+
+/**
+ * `j/clients` payload → the windows that could be underneath us, most recently
+ * used first.
+ *
+ * Three corrections turn Hyprland's answer into the one `pickWindowBelow`
+ * wants:
+ *
+ * - Order. The list arrives in the compositor's internal order, not z-order.
+ * `focusHistoryID` is 0 for the focused window, 1 for the one before it, and
+ * so on, which is the ordering the caller actually means by "underneath":
+ * the app the user was last working in.
+ * - Ourselves. Dropped, and this is load-bearing rather than tidiness. On X11
+ * the list is true stacking order, so walking past our own window and
+ * taking the next one is what "below" means. Focus history is not stacking
+ * order: the HUD floats always-on-top while the user works in the app
+ * beneath it, so the app we want to report is the focused one and WE are
+ * further down the list. Slicing after ourselves would skip straight past
+ * the answer and name something the user last touched ten minutes ago.
+ * Leaving ourselves out puts `pickWindowBelow` on its overlap-only path,
+ * which reads a focus-ordered list correctly.
+ * - Workspace. `clients` spans every workspace, and windows on a workspace
+ * you cannot see occupy the same coordinates as the ones you can. Left in,
+ * they win the overlap test against our bounds and the tool confidently
+ * reports a window on another desktop. Our own window pins which workspace
+ * is the visible one — the one use we have for it before dropping it; if we
+ * can't find ourselves we keep everything, which is no worse than the X11
+ * path.
+ */
+export function parseHyprlandClients(payload: string, selfPid: number): EnumeratedWindow[] {
+ let raw: unknown
+
+ try {
+ raw = JSON.parse(payload)
+ } catch {
+ return []
+ }
+
+ if (!Array.isArray(raw)) {
+ return []
+ }
+
+ const clients = raw as Array<HyprlandClient & { focusHistoryID?: number }>
+ const ours = clients.find(c => c.pid === selfPid)
+ const workspace = ours?.workspace?.id
+ const visible = workspace === undefined ? clients : clients.filter(c => c.workspace?.id === workspace)
+
+ return visible
+ .filter(c => c.pid !== selfPid && (c.size?.[0] ?? 0) > 0 && (c.size?.[1] ?? 0) > 0)
+ .sort((a, b) => (a.focusHistoryID ?? Number.MAX_SAFE_INTEGER) - (b.focusHistoryID ?? Number.MAX_SAFE_INTEGER))
+ .map(c => ({
+ app: c.class ?? '',
+ bounds: {
+ x: c.at?.[0] ?? 0,
+ y: c.at?.[1] ?? 0,
+ width: c.size?.[0] ?? 0,
+ height: c.size?.[1] ?? 0
+ },
+ // Addresses are pointers rendered as hex; they only travel back to the
+ // model as an opaque handle, so a failed parse costs nothing.
+ id: Number.parseInt(c.address ?? '', 16) || 0,
+ pid: c.pid ?? 0,
+ title: c.title ?? ''
+ }))
+}
+
+/** One request on the command socket, always closed, never left hanging. */
+function request(socketPath: string, command: string): Promise<null | string> {
+ return new Promise(resolve => {
+ let body = ''
+ let settled = false
+
+ const socket = net.createConnection(socketPath)
+
+ const finish = (result: null | string) => {
+ if (settled) {
+ return
+ }
+
+ settled = true
+ socket.destroy()
+ resolve(result)
+ }
+
+ socket.setTimeout(REQUEST_TIMEOUT_MS, () => finish(null))
+ socket.on('error', () => finish(null))
+ socket.on('connect', () => socket.write(command))
+ socket.on('data', chunk => {
+ body += chunk.toString('utf8')
+ })
+ socket.on('end', () => finish(body))
+ })
+}
+
+/**
+ * Every window Hyprland can see, front-to-back, or null when this isn't a
+ * Hyprland session or the compositor didn't answer — which is the caller's cue
+ * to fall back to the X11 enumerator.
+ */
+export async function readHyprlandWindows(
+ selfPid: number,
+ env: NodeJS.ProcessEnv = process.env,
+ uid: number = process.getuid?.() ?? 0
+): Promise<EnumeratedWindow[] | null> {
+ const socketPath = hyprlandSocketPath(env, uid)
+
+ if (!socketPath) {
+ return null
+ }
+
+ const payload = await request(socketPath, 'j/clients')
+
+ if (!payload) {
+ return null
+ }
+
+ const windows = parseHyprlandClients(payload, selfPid)
+
+ return windows.length > 0 ? windows : null
+}
diff --git a/apps/desktop/electron/window-below.test.ts b/apps/desktop/electron/window-below.test.ts
index 4719940a423..6a34384518a 100644
--- a/apps/desktop/electron/window-below.test.ts
+++ b/apps/desktop/electron/window-below.test.ts
@@ -92,6 +92,15 @@ describe('enumerationFailureNote', () => {
}
})
+ // Hyprland is asked over its own IPC, so the X11 tooling advice would be a
+ // wrong turn — reaching here means the compositor didn't answer.
+ it('points a Hyprland user at their compositor, not at xprop', () => {
+ const note = enumerationFailureNote('linux', { HYPRLAND_INSTANCE_SIGNATURE: 'abc', XDG_SESSION_TYPE: 'wayland' })
+
+ expect(note).toMatch(/Hyprland/)
+ expect(note).not.toMatch(/xprop|X11\/Xorg/)
+ })
+
it('tells an X11 user which commands are missing', () => {
const note = enumerationFailureNote('linux', { XDG_SESSION_TYPE: 'x11', DISPLAY: ':0' })
diff --git a/apps/desktop/electron/window-below.ts b/apps/desktop/electron/window-below.ts
index 5b9dff48ab3..82581addedd 100644
--- a/apps/desktop/electron/window-below.ts
+++ b/apps/desktop/electron/window-below.ts
@@ -12,6 +12,8 @@
// permission; we pass titles through only when that permission is ALREADY
// granted and never trigger the prompt for it.
+import { readHyprlandWindows } from './hyprland'
+
export interface EnumeratedWindow {
app: string
bounds: { x: number; y: number; width: number; height: number }
@@ -55,6 +57,17 @@ export function enumerationFailureNote(platform: string, env: NodeJS.ProcessEnv)
return 'Could not enumerate windows on this system.'
}
+ // Hyprland is asked over its own IPC, so reaching here means the socket
+ // didn't answer — telling a Hyprland user to go and install xprop, or to
+ // abandon Wayland, would send them in exactly the wrong direction.
+ if (env.HYPRLAND_INSTANCE_SIGNATURE) {
+ return (
+ 'Could not enumerate windows: Hyprland did not answer on its IPC socket. ' +
+ 'Check that `hyprctl clients` works from the same session Hermes is ' +
+ 'running in.'
+ )
+ }
+
const wayland = env.XDG_SESSION_TYPE === 'wayland' || (Boolean(env.WAYLAND_DISPLAY) && !env.DISPLAY)
if (wayland) {
@@ -126,16 +139,7 @@ const loadGetWindows = (): Promise<GetWindowsModule> => {
* rather than nothing, so the agent can tell the user what to fix instead of
* reporting a blank failure.
*/
-export async function readWindowBelow(
- selfPid: number,
- selfBounds: EnumeratedWindow['bounds'],
- titlesAvailable: boolean
-): Promise<WindowBelowResult | WindowBelowUnavailable> {
- const unavailable = (): WindowBelowUnavailable => ({
- error: enumerationFailureNote(process.platform, process.env),
- platform: process.platform
- })
-
+async function enumerateViaGetWindows(titlesAvailable: boolean): Promise<EnumeratedWindow[] | null> {
let raw
try {
@@ -146,11 +150,11 @@ export async function readWindowBelow(
: undefined
)
} catch {
- return unavailable()
+ return null
}
if (!Array.isArray(raw)) {
- return unavailable()
+ return null
}
// get-windows documents openWindows() as front-to-back, and macOS/Windows
@@ -160,7 +164,7 @@ export async function readWindowBelow(
// must be reversed to match. (Verified against get-windows 9.3.0.)
const ordered = process.platform === 'linux' ? [...raw].reverse() : raw
- const windows: EnumeratedWindow[] = ordered.map(w => ({
+ return ordered.map(w => ({
app: w.owner?.name ?? '',
bounds: {
x: w.bounds?.x ?? 0,
@@ -172,6 +176,24 @@ export async function readWindowBelow(
pid: w.owner?.processId ?? 0,
title: w.title ?? ''
}))
+}
+
+export async function readWindowBelow(
+ selfPid: number,
+ selfBounds: EnumeratedWindow['bounds'],
+ titlesAvailable: boolean
+): Promise<WindowBelowResult | WindowBelowUnavailable> {
+ // Hyprland first, and only ever on Hyprland — its own IPC sees native Wayland
+ // windows, which the X11 enumerator below cannot, and it answers null
+ // everywhere else so the established path stays the default.
+ const windows = (await readHyprlandWindows(selfPid)) ?? (await enumerateViaGetWindows(titlesAvailable))
+
+ if (!windows) {
+ return {
+ error: enumerationFailureNote(process.platform, process.env),
+ platform: process.platform
+ }
+ }
const { below, frontmost } = pickWindowBelow(windows, selfPid, selfBounds)