dsh-plugin-linux-computer-use 0.1.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,73 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0 - 2026-11-27
4
+
5
+ - **The server now refreshes itself.** The bundle copied `server/*.py` into
6
+ `~/.local/share/dsh-linux-computer-use` when the *doctor* plugin loaded, but
7
+ the MCP server is started by a separate patch entry: toggling only that entry
8
+ (the normal thing to do in Settings → Plugins) or upgrading the npm package
9
+ left a stale copy running, with no visible sign. The sync now also drops a
10
+ `.source` breadcrumb, and the server compares itself against that package
11
+ before doing anything, copies the newer files and re-executes — so a restart
12
+ is enough, and a stale code path can no longer survive one.
13
+ - `linux_mcp_doctor` grew two preflight checks: `keybindings` (which of
14
+ Alt+Tab / Super+Tab are actually bound, because the keyboard fallback of
15
+ `window_activate` depends on it) and `server-copy` (whether the running copy
16
+ is in step with the installed package). Both also run from
17
+ `linux_desktop_mcp.py --selftest`.
18
+ - `ui_tree` can now be pruned: pass `roles` (e.g. `["push button", "entry"]`)
19
+ to keep only the kinds of node you care about — ancestors collapse into a
20
+ bare `ref`/`role`/`name` path — and `compact` to drop rectangles, states and
21
+ text previews. Measured on this machine: 140 nodes / 10.2 KB → 20 nodes /
22
+ 0.85 KB for the same screen, and filtered trees on a real application save
23
+ far more. The reply now reports `nodes_returned` next to `nodes_used`.
24
+ - Defunct applications are no longer walked (they still answer AT-SPI and
25
+ quietly ate the node budget).
26
+ - MCP server version 1.3.0.
27
+
28
+ ## 0.3.0 - 2026-11-27
29
+
30
+ - New `window_activate`: raise a window by title substring (or app name). Three
31
+ strategies are tried in order and the reply says which one worked: `xdotool
32
+ windowactivate` for XWayland surfaces, the AT-SPI default action for toolkits
33
+ that honour it, and Alt+Tab cycling verified against the accessibility tree
34
+ for native Wayland windows, which neither X11 nor AT-SPI can raise. Both
35
+ Alt+Tab (windows of the current application) and Super+Tab (applications)
36
+ are cycled, because GNOME binds them differently. A combination whose first
37
+ press moves no window is abandoned straight away, so raising a window of
38
+ another application takes one Super+Tab instead of thirteen Alt+Tabs.
39
+ - New `wait_until`: poll until a condition holds instead of sleeping a fixed
40
+ time. Conditions are a window appearing or disappearing
41
+ (`{"window": {"title": "...", "exists": false}}`), a window becoming active
42
+ (`{"window_active": "Chrome"}`), an accessibility node showing up
43
+ (`{"ui": {"app": "...", "name": "...", "role": "..."}}`), or the user being
44
+ idle for a while (`{"idle_at_least": 60000}`). On timeout it returns
45
+ `satisfied: false` with the last observed state instead of throwing.
46
+ - `window_list` now reports `active` from the AT-SPI `ACTIVE` state, which is
47
+ the flag most toolkits set on the toplevel frame (`FOCUSED` alone missed
48
+ them, so every window used to look inactive).
49
+ - MCP server version 1.2.0.
50
+
51
+ ## 0.2.0 - 2026-11-27
52
+
53
+ - `screenshot` gained `region` and `scale`. Cropping before downscaling is the
54
+ fix for HiDPI desktops: 11 px UI text on a 4480x1440 desktop used to turn to
55
+ mush once the capture was scaled to 1400 px wide, and re-reading a whole
56
+ screen to make out one label burned most of the tokens in a session. A
57
+ cropped capture keeps native sharpness and costs a fraction of the tokens.
58
+ `space: "screenshot"` adds the crop offset back, so coordinates stay correct.
59
+ - New idle guard: synthetic input is refused while the user has touched the
60
+ keyboard or pointer in the last 60 seconds (`org.gnome.Mutter.IdleMonitor`),
61
+ so automation cannot fight the person at the machine. Pass
62
+ `allow_active_input: true` on any input tool — the model does so when the
63
+ user explicitly asked it to drive — or set
64
+ `DSH_LINUX_CU_ALLOW_ACTIVE_INPUT=1`; tune the window with
65
+ `DSH_LINUX_CU_IDLE_GUARD_MS`. Screenshots, UI reads and clipboard reads stay
66
+ available, and `desktop_status` reports `session.idle_ms`.
67
+ - `capture_shot` now converts logical coordinates to the physical pixels the
68
+ portal returns, so `region` is correct on fractional HiDPI scaling.
69
+ - MCP server version 1.1.0.
70
+
3
71
  ## 0.1.1 - 2026-11-25
4
72
 
5
73
  - fix: send the complete `input_absinfo` when creating the absolute pointer.
package/README.md CHANGED
@@ -24,8 +24,10 @@ English summary at the bottom.
24
24
  | "注册表"类比 | `gsettings` / dconf |
25
25
  | 通知 | `notify-send` |
26
26
  | 显示器信息 | Mutter `DisplayConfig`(坐标换算、多屏) |
27
+ | 窗口操作 | `window_list` 列出标题与是否 `active`;`window_activate` 按标题子串把窗口抬到前台——XWayland 走 `xdotool`,原生 Wayland 用 Alt+Tab / Super+Tab 循环并以无障碍树校验(GNOME 下 Alt+Tab 只切本应用窗口,Super+Tab 才切应用),返回里会说明这次用的是哪条路 |
28
+ | 等待条件 | `wait_until` 轮询直到满足条件:窗口出现/消失、某个窗口变成前台、某个 UI 节点出现、或用户空闲满多少毫秒;超时返回 `satisfied: false` 与最后一轮观察到的状态,不抛错 |
27
29
 
28
- 28 个工具,分组见 [docs/DETAIL.md](docs/DETAIL.md)。模型调用方式:`mcp__linux__screenshot`、`mcp__linux__click`、`mcp__linux__ui_find` ……
30
+ 30 个工具,分组见 [docs/DETAIL.md](docs/DETAIL.md)。模型调用方式:`mcp__linux__screenshot`、`mcp__linux__click`、`mcp__linux__ui_find` ……
29
31
 
30
32
  ## 安装
31
33
 
@@ -57,12 +59,20 @@ sudo ./linux-computer-use-prep.sh --verify # 不需要 sudo
57
59
 
58
60
  开着插件但没开 Computer Use 时也可以先跑 `linux_mcp_doctor`(不需要 MCP 在线),它会逐项告诉你缺什么、怎么补。
59
61
 
62
+ ## 省钱与提速的两招
63
+
64
+ - **`ui_tree` 先过滤再读**:`roles: ["push button", "entry"]` 只保留你要的节点类型,祖先会折叠成 `ref`/`role`/`name` 的路径;再加 `compact: true` 去掉 rect/states/text。实测同一屏 140 节点/10.2 KB → 20 节点/0.85 KB。
65
+ - **`screenshot` 用 `region` + `scale: 1.0`**:先在 4480×1440 原图上裁剪再缩放,小字才清楚,token 也只有整屏的三分之一。
66
+
60
67
  ## 已知限制(重要,别踩坑)
61
68
 
62
69
  - **Chromium / Electron / Qt 应用(Chrome、VS Code、微信、WPS、Bitwarden)暴露的 UI 树是空的**——这是平台事实,不是 bug。它们只能靠"截屏 + 坐标点击",窗口一动就得重新截图。原生 GTK 应用用 `ui_find` + `ui_action` 很稳。
63
70
  - AT-SPI 全量枚举约 3–4 秒(某个无响应应用会拖慢),所以应用列表有 5 秒缓存。
64
71
  - 截屏必须走 portal:第一次会弹一次系统授权框(GNOME 记住你的选择),之后每次截图静默、约 0.5 秒。ScreenCast 流式路径(`DSH_LINUX_CU_SCREENCAST=1` 可强制)在 GNOME 46 上画面静止时不产帧,只当兜底。
65
72
  - **锁屏时只截图、不注入**:服务器会向 `org.gnome.ScreenSaver.GetActive` 查询锁屏状态,处于锁屏时 `click` / `key` / `type_text` 等全部拒绝执行(锁屏焦点在密码框上,误打就会往密码里塞字符),`screenshot` 仍可用。`desktop_status` 的 `session.locked` 会告诉你当前状态。
73
+ - **你在用电脑时也不注入**:服务器用 `org.gnome.Mutter.IdleMonitor.GetIdletime` 查空闲时间,最近 60 秒内有键鼠动作就拒绝点击/输入(否则自动化会和你抢光标)。这一条可以放行:工具参数带 `allow_active_input: true`(模型在你明确让它代操作时会带),或设环境变量 `DSH_LINUX_CU_ALLOW_ACTIVE_INPUT=1`;阈值用 `DSH_LINUX_CU_IDLE_GUARD_MS` 调(默认 `60000`)。截图、读 UI 树、读文件不受影响。`desktop_status` 的 `session.idle_ms` 就是当前空闲毫秒数。
74
+ - **原生 Wayland 窗口没法被 X11 抬起**:Chrome、GNOME 自家应用在 `xdotool search` 里完全不存在,`window_activate` 对它们会用 Alt+Tab(本应用内切窗口)与 Super+Tab(切应用)循环,需要 uinput 键盘可用。如果三条路都失败,返回 `activated: false` 与 `tried` 明细,而不是假装成功。
75
+ - **截图要看清小字就用 `region`**:整屏 4480×1440 缩到 1400 宽,11px 的小字会糊成一团;传 `{"region": {"x":120,"y":140,"width":900,"height":620}, "scale":1.0}` 只截那块、按原尺寸返回,既清楚又省 token。`space: "screenshot"` 会自动加回偏移,不用自己算。
66
76
  - 只能工作在**当前登录的图形会话**里;SSH / 无头环境下没有桌面可控制。
67
77
 
68
78
  ## 安全模型
@@ -120,7 +130,7 @@ honouring its motion: keyboard and scroll still work, clicks do nothing.
120
130
  python3 -u ~/.local/share/dsh-linux-computer-use/linux_desktop_mcp.py --selftest
121
131
  ```
122
132
 
123
- 或在对话里让模型调用 `linux_mcp_doctor`。逐项报告:会话类型、Python/GI/Atspi/Gst、`/dev/uinput`、启动器、wl-clipboard、portal 版本、pipewiresrc、截屏授权、显示器、AT-SPI 应用数。
133
+ 或在对话里让模型调用 `linux_mcp_doctor`。逐项报告:会话类型、Python/GI/Atspi/Gst、`/dev/uinput`、启动器、wl-clipboard、portal 版本、pipewiresrc、截屏授权、显示器、AT-SPI 应用数、**GNOME 窗口切换键位绑定**(Alt+Tab / Super+Tab 哪个有效),以及**正在运行的 server 副本是否与安装的包一致**。
124
134
 
125
135
  ## 兼容性
126
136
 
@@ -136,7 +146,7 @@ MIT
136
146
 
137
147
  ### English
138
148
 
139
- Linux desktop automation for DeepSeek Harness on Wayland. Screenshots go through the `xdg-desktop-portal` Screenshot interface (the only Wayland-legal path, ~0.5s per capture after one granted approval); pointer and keyboard input go straight to `/dev/uinput` so applications cannot tell them from a real user; the UI tree comes from AT-SPI2. 28 tools are published as `mcp__linux__*`, plus a `linux_mcp_doctor` host tool that diagnoses the environment even while the bridge is off. Ships disabled: enable it in Settings → Plugins.
149
+ Linux desktop automation for DeepSeek Harness on Wayland. Screenshots go through the `xdg-desktop-portal` Screenshot interface (the only Wayland-legal path, ~0.5s per capture after one granted approval); pointer and keyboard input go straight to `/dev/uinput` so applications cannot tell them from a real user; the UI tree comes from AT-SPI2. 30 tools are published as `mcp__linux__*`, plus a `linux_mcp_doctor` host tool that diagnoses the environment even while the bridge is off. Ships disabled: enable it in Settings → Plugins.
140
150
 
141
151
  Install: `dsh plugin --profile web add dsh-plugin-linux-computer-use`, run `sudo ./linux-computer-use-prep.sh`, restart `dsh`, then flip the switch.
142
152
 
package/docs/DETAIL.md CHANGED
@@ -15,6 +15,8 @@ Wayland neither exists, so each capability has its own path:
15
15
  | Clipboard | `wl-copy` / `wl-paste` | `xclip` does not work on Wayland |
16
16
  | Settings ("registry") | `gsettings` / dconf | closest analogue to the registry |
17
17
  | Lock state | `org.gnome.ScreenSaver.GetActive` over the session bus | input must stop while the lock screen holds the password field; screenshots stay allowed |
18
+ | Idle state | `org.gnome.Mutter.IdleMonitor.GetIdletime` over the session bus | synthetic input stops while the user is at the keyboard, so automation cannot fight them |
19
+ | Raising a window | `xdotool windowactivate` (XWayland), the AT-SPI default action, then Alt+Tab and Super+Tab with an accessibility check | native Wayland surfaces are invisible to X11, `_NET_ACTIVE_WINDOW` cannot be honoured by the compositor, and the AT-SPI default action is a no-op for most toolkits |
18
20
  | Processes | `ps` and `/proc` | portable |
19
21
 
20
22
  ## Requirements
@@ -43,18 +45,31 @@ reload the page. `linux_mcp_doctor` works either way.
43
45
 
44
46
  | Group | Tools |
45
47
  | --- | --- |
46
- | Vision | `screenshot` — PNG + size + path; the first call asks for permission once |
47
- | Tree | `ui_apps`, `ui_tree`, `ui_find`, `ui_describe`, `ui_text` |
48
+ | Vision | `screenshot` — PNG + size + path; `region` crops before scaling (sharp text), `scale` sets pixels per logical pixel; the first call asks for permission once |
49
+ | Tree | `ui_apps`, `ui_tree` (prune with `roles` + `compact`), `ui_find`, `ui_describe`, `ui_text` |
48
50
  | Act on elements | `ui_action` (invoke/press/toggle), `ui_focus`, `ui_set_text` |
49
51
  | Pointer | `click`, `move`, `drag`, `scroll`, `pointer_button` (hold/release) |
50
52
  | Keyboard | `key` (`ctrl+shift+t`), `type_text` (Unicode via clipboard paste) |
51
53
  | Clipboard | `clipboard_get`, `clipboard_set` |
52
- | System | `process_list`, `process_kill`, `launch_app`, `settings_get`, `settings_set`, `settings_list_keys`, `notify`, `window_list`, `display_info`, `desktop_status` |
54
+ | System | `process_list`, `process_kill`, `launch_app`, `settings_get`, `settings_set`, `settings_list_keys`, `notify`, `display_info`, `desktop_status` |
55
+ | Windows | `window_list` (titles + `active`), `window_activate` — raises a window by title substring; XWayland through `xdotool`, native Wayland by cycling Alt+Tab then Super+Tab and checking the accessibility tree (GNOME binds Alt+Tab to windows of the current app and Super+Tab to applications), and the reply names the strategy that worked |
56
+ | Waiting | `wait_until` — poll until `window` appears/disappears, `window_active` is raised, a `ui` node shows up, or `idle_at_least` ms pass; on timeout it returns `satisfied: false` with the last state instead of throwing |
53
57
  | Unlocking (opt-in) | `unlock_screen` — only listed while the unlock policy is on; see below |
54
58
 
55
59
  Coordinates are **logical desktop pixels**. Pass `space: "screenshot"` to give
56
60
  coordinates in the pixels of the most recent screenshot instead; on a HiDPI
57
- display those differ, and the tool converts for you.
61
+ display those differ, and the tool converts for you. A cropped screenshot keeps
62
+ the offset, so `space: "screenshot"` still lands on the right spot.
63
+
64
+ Reading one window is much cheaper than reading the whole desktop:
65
+
66
+ ```json
67
+ {"region": {"x": 120, "y": 140, "width": 900, "height": 620}, "scale": 1.0}
68
+ ```
69
+
70
+ The desktop is 4480x1440 on HiDPI; scaled to 1400 px wide the same capture
71
+ turns 11 px text into mush, while the crop above stays at native sharpness and
72
+ costs a third of the tokens.
58
73
 
59
74
  ## What works well and what does not
60
75
 
package/index.js CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  mkdirSync,
20
20
  readdirSync,
21
21
  readFileSync,
22
+ writeFileSync,
22
23
  } from 'node:fs'
23
24
  import { homedir } from 'node:os'
24
25
  import { dirname, join } from 'node:path'
@@ -58,6 +59,11 @@ function syncServerFiles() {
58
59
  copyFileSync(from, to)
59
60
  copied.push(name)
60
61
  }
62
+ // Leave a breadcrumb so the installed copy can refresh itself even when
63
+ // only the MCP entry is toggled (that entry never re-runs this function).
64
+ try {
65
+ writeFileSync(join(INSTALL_DIR, '.source'), `${source}\n`, { mode: 0o600 })
66
+ } catch {}
61
67
  return { ok: true, dir: INSTALL_DIR, copied }
62
68
  } catch (error) {
63
69
  return { ok: false, dir: INSTALL_DIR, detail: error?.message ?? String(error), copied }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-linux-computer-use",
3
- "version": "0.1.2",
3
+ "version": "0.4.0",
4
4
  "description": "Computer Use for a Wayland Linux desktop in DeepSeek Harness: screenshots, UI tree, pointer and keyboard input, clipboard, processes and settings, bridged as mcp__linux__* tools. · 让 DSH 接管 Ubuntu/GNOME 桌面:截屏、UI 树、鼠标键盘、剪贴板、进程与系统设置。",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/server/cu_a11y.py CHANGED
@@ -65,6 +65,11 @@ class A11yError(RuntimeError):
65
65
  """The accessibility tree could not be read or the element is gone."""
66
66
 
67
67
 
68
+ def _count_nodes(node: dict) -> int:
69
+ """How many nodes this subtree actually carries (after filtering)."""
70
+ return 1 + sum(_count_nodes(child) for child in node.get("children", []))
71
+
72
+
68
73
  def _state_names(acc) -> list[str]:
69
74
  try:
70
75
  state_set = acc.get_state_set()
@@ -262,7 +267,8 @@ class A11y:
262
267
  return None
263
268
 
264
269
  # -- snapshot ---------------------------------------------------------- #
265
- def node(self, acc, depth: int, budget: dict, deadline: float) -> dict | None:
270
+ def node(self, acc, depth: int, budget: dict, deadline: float,
271
+ wanted_roles: set | None = None, compact: bool = False) -> dict | None:
266
272
  if budget["nodes"] <= 0 or time.monotonic() > deadline:
267
273
  budget["truncated"] = True
268
274
  return None
@@ -272,40 +278,57 @@ class A11y:
272
278
  name = acc.get_name() or ""
273
279
  except Exception: # noqa: BLE001
274
280
  return None
275
- item: dict = {"ref": self._ref(acc), "role": role}
276
- if name:
277
- item["name"] = name[:120]
278
281
  states = _state_names(acc)
279
- if states:
280
- item["states"] = states
281
- rect = _extents(acc)
282
- if rect:
283
- item["rect"] = rect
284
- actions = _actions(acc)
285
- if actions:
286
- item["actions"] = actions
287
- text = _text_preview(acc)
288
- if text:
289
- item["text"] = text
282
+ if "defunct" in states:
283
+ # A dead application still answers AT-SPI; walking it wastes the budget.
284
+ return None
285
+ children: list[dict] = []
290
286
  if depth > 0:
291
- children = []
292
287
  try:
293
288
  count = acc.get_child_count()
294
289
  except Exception: # noqa: BLE001
295
290
  count = 0
296
291
  for index in range(count):
297
- child = self.node(acc.get_child_at_index(index), depth - 1, budget, deadline)
292
+ child = self.node(acc.get_child_at_index(index), depth - 1, budget, deadline,
293
+ wanted_roles, compact)
298
294
  if child is None:
299
295
  if budget["truncated"]:
300
296
  break
301
297
  continue
302
298
  children.append(child)
303
- if children:
304
- item["children"] = children
299
+ matched = True
300
+ if wanted_roles is not None:
301
+ lowered = role.lower()
302
+ matched = any(needle in lowered for needle in wanted_roles)
303
+ if not matched and not children:
304
+ # Nothing here and nothing below is interesting: drop the node.
305
+ return None
306
+ item: dict = {"ref": self._ref(acc), "role": role}
307
+ if name:
308
+ item["name"] = name[:120]
309
+ if matched and not compact:
310
+ if states:
311
+ item["states"] = states
312
+ rect = _extents(acc)
313
+ if rect:
314
+ item["rect"] = rect
315
+ actions = _actions(acc)
316
+ if actions:
317
+ item["actions"] = actions
318
+ text = _text_preview(acc)
319
+ if text:
320
+ item["text"] = text
321
+ elif matched and compact:
322
+ actions = _actions(acc)
323
+ if actions:
324
+ item["actions"] = actions
325
+ if children:
326
+ item["children"] = children
305
327
  return item
306
328
 
307
329
  def snapshot(self, app: str | None = None, max_depth: int = 3,
308
- max_nodes: int = 220, timeout_s: float = 20.0) -> dict:
330
+ max_nodes: int = 220, timeout_s: float = 20.0,
331
+ roles: list[str] | None = None, compact: bool = False) -> dict:
309
332
  self.start()
310
333
  deadline = time.monotonic() + timeout_s
311
334
  budget = {"nodes": max_nodes, "truncated": False}
@@ -321,17 +344,21 @@ class A11y:
321
344
  target = self._apps.get(item["name"])
322
345
  if target is not None:
323
346
  roots.append((target, item["name"]))
347
+ wanted_roles = {item.lower() for item in roles} if roles else None
324
348
  tree = []
325
349
  for root, label in roots:
326
- node = self.node(root, max_depth, budget, deadline)
350
+ node = self.node(root, max_depth, budget, deadline, wanted_roles, compact)
327
351
  if node is not None:
328
352
  node.setdefault("name", label)
329
353
  node["app"] = label
330
354
  tree.append(node)
355
+ emitted = sum(_count_nodes(item) for item in tree)
356
+
331
357
  return {
332
358
  "applications": tree,
333
359
  "truncated": bool(budget["truncated"]),
334
360
  "nodes_used": max_nodes - max(0, budget["nodes"]),
361
+ "nodes_returned": emitted,
335
362
  }
336
363
 
337
364
  # -- search ------------------------------------------------------------ #
@@ -521,3 +521,36 @@ def downscale(path: str, max_width: int) -> tuple[int, int]:
521
521
  return png_size(path)
522
522
  except Exception: # noqa: BLE001 - scaling is best effort
523
523
  return (width, height)
524
+
525
+
526
+ def crop_and_scale(path: str, box: tuple[int, int, int, int], out_width: int) -> tuple[int, int]:
527
+ """Crop ``box`` (physical pixels) out of a PNG, then scale it to ``out_width``.
528
+
529
+ Cropping before scaling is the whole point: a 4480x1440 desktop scaled to
530
+ 1400 px makes small UI text unreadable, while a 900x400 region of it stays
531
+ sharp at the same output size. The box is clipped to the image, and every
532
+ failure falls back to the untouched file so a capture is never lost.
533
+ """
534
+ width, height = png_size(path)
535
+ x, y, w, h = box
536
+ x = max(0, min(int(x), max(0, width - 1)))
537
+ y = max(0, min(int(y), max(0, height - 1)))
538
+ w = max(1, min(int(w), width - x))
539
+ h = max(1, min(int(h), height - y))
540
+ target_width = out_width if out_width > 0 else w
541
+ target_height = max(1, round(h * target_width / w)) if w else h
542
+ try:
543
+ gi.require_version("GdkPixbuf", "2.0")
544
+ from gi.repository import GdkPixbuf
545
+
546
+ pixbuf = GdkPixbuf.Pixbuf.new_from_file(path)
547
+ cropped = pixbuf.new_subpixbuf(x, y, w, h)
548
+ out = cropped
549
+ if (target_width, target_height) != (w, h):
550
+ scaled = cropped.scale_simple(target_width, target_height, GdkPixbuf.InterpType.BILINEAR)
551
+ if scaled is not None:
552
+ out = scaled
553
+ out.savev(path, "png", [], [])
554
+ return png_size(path)
555
+ except Exception: # noqa: BLE001 - cropping is best effort
556
+ return (width, height)
package/server/cu_sys.py CHANGED
@@ -86,6 +86,40 @@ def screen_locked() -> bool | None:
86
86
  return None
87
87
 
88
88
 
89
+ def idle_ms() -> int | None:
90
+ """Milliseconds since the last keyboard or pointer event, or ``None``.
91
+
92
+ Mutter's IdleMonitor is the compositor's own idea of idleness, so it sees
93
+ input delivered to any client (including the ones synthetic input misses).
94
+ ``None`` means the service is not there (not GNOME, or a very old release);
95
+ callers then fall back to behaving as before.
96
+ """
97
+ try:
98
+ import gi
99
+
100
+ gi.require_version("Gio", "2.0")
101
+ gi.require_version("GLib", "2.0")
102
+ from gi.repository import Gio, GLib
103
+ except (ImportError, ValueError):
104
+ return None
105
+ try:
106
+ connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
107
+ reply = connection.call_sync(
108
+ "org.gnome.Mutter.IdleMonitor",
109
+ "/org/gnome/Mutter/IdleMonitor/Core",
110
+ "org.gnome.Mutter.IdleMonitor",
111
+ "GetIdletime",
112
+ None,
113
+ GLib.VariantType.new("(t)"),
114
+ Gio.DBusCallFlags.NONE,
115
+ 2000,
116
+ None,
117
+ )
118
+ return int(reply.unpack()[0])
119
+ except Exception: # noqa: BLE001 - a missing service is not an error here
120
+ return None
121
+
122
+
89
123
  def have(binary: str) -> bool:
90
124
  return shutil.which(binary) is not None
91
125