dsh-plugin-linux-computer-use 0.3.0 → 0.6.1
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 +76 -0
- package/README.md +16 -3
- package/docs/DETAIL.md +4 -3
- package/index.js +6 -0
- package/package.json +1 -1
- package/server/cu_a11y.py +117 -21
- package/server/cu_display.py +55 -0
- package/server/cu_unlock.py +33 -8
- package/server/linux_desktop_mcp.py +579 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,81 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.1 - 2026-11-28
|
|
4
|
+
|
|
5
|
+
- `desktop_status` no longer fails when the login keyring is locked: the secret
|
|
6
|
+
lookup gets a 6 second deadline and a locked keyring is reported as
|
|
7
|
+
`password_stored: null` with an `error` line instead of a 20 second hang.
|
|
8
|
+
- Same guard on `unlock_screen`: it now says the keyring is locked instead of
|
|
9
|
+
blocking the whole tool call.
|
|
10
|
+
- **Wayland apps publish no screen rectangles.** GTK 4 and Chromium report empty
|
|
11
|
+
AT-SPI extents, so `marks: true` can draw no numbered boxes and `click_ref`
|
|
12
|
+
cannot compute a centre point. `marks: true` now answers with a `clickable`
|
|
13
|
+
list of `{ref, role, name}` instead of pretending nothing is on screen, and
|
|
14
|
+
`click_ref` drives elements through their accessibility action first (which
|
|
15
|
+
works without coordinates), falling back to a pointer click only when a
|
|
16
|
+
rectangle exists. `actionable()` also scans 25 applications instead of 6, so
|
|
17
|
+
the list is no longer empty when the interesting window is late in the list.
|
|
18
|
+
- server 1.5.1.
|
|
19
|
+
|
|
20
|
+
## 0.6.0 - 2026-11-28
|
|
21
|
+
|
|
22
|
+
- **One call can run a whole flow.** `sequence {steps: [{op, args}, ...]}` runs up
|
|
23
|
+
to 25 tools in order and answers with a compact per-step report
|
|
24
|
+
(`{step, op, ok, ms, error?}`), the run's `elapsed_ms`, and the **last** step's
|
|
25
|
+
output — images included, so a "raise the window, click, type, screenshot" flow
|
|
26
|
+
costs one round trip instead of four. `stop_on_error: false` keeps going and
|
|
27
|
+
reports every failure; `allow_active_input: true` applies the idle-guard escape
|
|
28
|
+
hatch to every injecting step at once instead of repeating it in each step.
|
|
29
|
+
A sequence cannot nest another sequence (the cap is 25 steps, override with
|
|
30
|
+
`DSH_LINUX_CU_SEQUENCE_MAX_STEPS`).
|
|
31
|
+
- `ok` is true only when *every* step succeeded; `stopped_at` names the step that
|
|
32
|
+
halted the run.
|
|
33
|
+
- Server 1.5.0.
|
|
34
|
+
|
|
35
|
+
## 0.5.0 - 2026-11-27
|
|
36
|
+
|
|
37
|
+
- **Screenshots can label what is clickable.** `screenshot {marks: true}` draws a
|
|
38
|
+
numbered box around every button, entry, link, tab and menu item it can see in
|
|
39
|
+
the captured area (pycairo, already on the machine through GTK), and returns
|
|
40
|
+
the same numbers as `marks: [{id, ref, role, name, x, y, width, height}]` in
|
|
41
|
+
*screenshot* pixels — so a model can point at "box 4" instead of guessing
|
|
42
|
+
coordinates. `marks_limit` caps how many boxes are drawn (default 40).
|
|
43
|
+
- `screenshot {ref: "<ref>"}` crops straight to one element's rectangle, which
|
|
44
|
+
makes "look closely at this button" a single call.
|
|
45
|
+
- `click_ref {ref: "<ref>"}` clicks an element by its accessibility reference
|
|
46
|
+
(the `ref` that `ui_tree`, `ui_find` and the new `marks` hand out), and
|
|
47
|
+
`click {text: "Save"}` clicks the first element whose name or text matches —
|
|
48
|
+
no coordinates at all. Both run through the same lock and idle guards as
|
|
49
|
+
`click`, and both accept `allow_active_input`.
|
|
50
|
+
- An empty `marks` list is explained in the note (a locked session hides most of
|
|
51
|
+
the tree) instead of looking like a silent failure.
|
|
52
|
+
- Server 1.4.0.
|
|
53
|
+
|
|
54
|
+
## 0.4.0 - 2026-11-27
|
|
55
|
+
|
|
56
|
+
- **The server now refreshes itself.** The bundle copied `server/*.py` into
|
|
57
|
+
`~/.local/share/dsh-linux-computer-use` when the *doctor* plugin loaded, but
|
|
58
|
+
the MCP server is started by a separate patch entry: toggling only that entry
|
|
59
|
+
(the normal thing to do in Settings → Plugins) or upgrading the npm package
|
|
60
|
+
left a stale copy running, with no visible sign. The sync now also drops a
|
|
61
|
+
`.source` breadcrumb, and the server compares itself against that package
|
|
62
|
+
before doing anything, copies the newer files and re-executes — so a restart
|
|
63
|
+
is enough, and a stale code path can no longer survive one.
|
|
64
|
+
- `linux_mcp_doctor` grew two preflight checks: `keybindings` (which of
|
|
65
|
+
Alt+Tab / Super+Tab are actually bound, because the keyboard fallback of
|
|
66
|
+
`window_activate` depends on it) and `server-copy` (whether the running copy
|
|
67
|
+
is in step with the installed package). Both also run from
|
|
68
|
+
`linux_desktop_mcp.py --selftest`.
|
|
69
|
+
- `ui_tree` can now be pruned: pass `roles` (e.g. `["push button", "entry"]`)
|
|
70
|
+
to keep only the kinds of node you care about — ancestors collapse into a
|
|
71
|
+
bare `ref`/`role`/`name` path — and `compact` to drop rectangles, states and
|
|
72
|
+
text previews. Measured on this machine: 140 nodes / 10.2 KB → 20 nodes /
|
|
73
|
+
0.85 KB for the same screen, and filtered trees on a real application save
|
|
74
|
+
far more. The reply now reports `nodes_returned` next to `nodes_used`.
|
|
75
|
+
- Defunct applications are no longer walked (they still answer AT-SPI and
|
|
76
|
+
quietly ate the node budget).
|
|
77
|
+
- MCP server version 1.3.0.
|
|
78
|
+
|
|
3
79
|
## 0.3.0 - 2026-11-27
|
|
4
80
|
|
|
5
81
|
- New `window_activate`: raise a window by title substring (or app name). Three
|
package/README.md
CHANGED
|
@@ -27,7 +27,7 @@ English summary at the bottom.
|
|
|
27
27
|
| 窗口操作 | `window_list` 列出标题与是否 `active`;`window_activate` 按标题子串把窗口抬到前台——XWayland 走 `xdotool`,原生 Wayland 用 Alt+Tab / Super+Tab 循环并以无障碍树校验(GNOME 下 Alt+Tab 只切本应用窗口,Super+Tab 才切应用),返回里会说明这次用的是哪条路 |
|
|
28
28
|
| 等待条件 | `wait_until` 轮询直到满足条件:窗口出现/消失、某个窗口变成前台、某个 UI 节点出现、或用户空闲满多少毫秒;超时返回 `satisfied: false` 与最后一轮观察到的状态,不抛错 |
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
33 个工具,分组见 [docs/DETAIL.md](docs/DETAIL.md)。模型调用方式:`mcp__linux__screenshot`、`mcp__linux__click`、`mcp__linux__ui_find` ……
|
|
31
31
|
|
|
32
32
|
## 安装
|
|
33
33
|
|
|
@@ -59,6 +59,19 @@ sudo ./linux-computer-use-prep.sh --verify # 不需要 sudo
|
|
|
59
59
|
|
|
60
60
|
开着插件但没开 Computer Use 时也可以先跑 `linux_mcp_doctor`(不需要 MCP 在线),它会逐项告诉你缺什么、怎么补。
|
|
61
61
|
|
|
62
|
+
## 第三招:一次调用跑一整段流程
|
|
63
|
+
|
|
64
|
+
`sequence` 把多个工具合成一次调用:`{"steps": [{"op": "window_activate", "args": {"title": "嘉立创"}}, {"op": "click", "args": {"text": "保存"}}, {"op": "screenshot", "args": {"region": {...}, "scale": 1}}]}`。
|
|
65
|
+
|
|
66
|
+
回复是每步的 `{step, op, ok, ms, error?}` 加**最后一步**的输出(含图片),所以上面这段从 4 次模型往返变成 1 次。注入类步骤不必逐个写 `allow_active_input`,在最外层给 `true` 即可;某步允许失败就设 `stop_on_error: false`。
|
|
67
|
+
|
|
68
|
+
## 省钱与提速的两招
|
|
69
|
+
|
|
70
|
+
- **`ui_tree` 先过滤再读**:`roles: ["push button", "entry"]` 只保留你要的节点类型,祖先会折叠成 `ref`/`role`/`name` 的路径;再加 `compact: true` 去掉 rect/states/text。实测同一屏 140 节点/10.2 KB → 20 节点/0.85 KB。
|
|
71
|
+
- **`screenshot` 用 `region` + `scale: 1.0`**:先在 4480×1440 原图上裁剪再缩放,小字才清楚,token 也只有整屏的三分之一。
|
|
72
|
+
- **看不清哪个能点就用 `marks: true`**:截图会围上带编号的框,同时返回 `marks: [{id, ref, role, name, x, y, width, height}]`(坐标已经是截图像素)。之后 `click_ref {"ref": "e42"}` 直接点,不需要自己算坐标。
|
|
73
|
+
- **注意(GNOME Wayland 实测)**:GTK 4 与 Chromium 的窗口**不向 AT-SPI 报告屏幕矩形**,这时画不出框,`marks` 会是空数组,改为返回 `clickable: [{ref, role, name}]`。对这些元素 `click_ref` 走的是无障碍的「点击」动作(不需要坐标);没有动作的控件只能靠 `screenshot` + 坐标点击。Chrome 更是只暴露 `application` 与 `frame`,网页里的元素请优先用 `browser_*`(DOM)。
|
|
74
|
+
|
|
62
75
|
## 已知限制(重要,别踩坑)
|
|
63
76
|
|
|
64
77
|
- **Chromium / Electron / Qt 应用(Chrome、VS Code、微信、WPS、Bitwarden)暴露的 UI 树是空的**——这是平台事实,不是 bug。它们只能靠"截屏 + 坐标点击",窗口一动就得重新截图。原生 GTK 应用用 `ui_find` + `ui_action` 很稳。
|
|
@@ -125,7 +138,7 @@ honouring its motion: keyboard and scroll still work, clicks do nothing.
|
|
|
125
138
|
python3 -u ~/.local/share/dsh-linux-computer-use/linux_desktop_mcp.py --selftest
|
|
126
139
|
```
|
|
127
140
|
|
|
128
|
-
或在对话里让模型调用 `linux_mcp_doctor`。逐项报告:会话类型、Python/GI/Atspi/Gst、`/dev/uinput`、启动器、wl-clipboard、portal 版本、pipewiresrc、截屏授权、显示器、AT-SPI
|
|
141
|
+
或在对话里让模型调用 `linux_mcp_doctor`。逐项报告:会话类型、Python/GI/Atspi/Gst、`/dev/uinput`、启动器、wl-clipboard、portal 版本、pipewiresrc、截屏授权、显示器、AT-SPI 应用数、**GNOME 窗口切换键位绑定**(Alt+Tab / Super+Tab 哪个有效),以及**正在运行的 server 副本是否与安装的包一致**。
|
|
129
142
|
|
|
130
143
|
## 兼容性
|
|
131
144
|
|
|
@@ -141,7 +154,7 @@ MIT
|
|
|
141
154
|
|
|
142
155
|
### English
|
|
143
156
|
|
|
144
|
-
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.
|
|
157
|
+
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.
|
|
145
158
|
|
|
146
159
|
Install: `dsh plugin --profile web add dsh-plugin-linux-computer-use`, run `sudo ./linux-computer-use-prep.sh`, restart `dsh`, then flip the switch.
|
|
147
160
|
|
package/docs/DETAIL.md
CHANGED
|
@@ -45,15 +45,16 @@ reload the page. `linux_mcp_doctor` works either way.
|
|
|
45
45
|
|
|
46
46
|
| Group | Tools |
|
|
47
47
|
| --- | --- |
|
|
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
|
|
48
|
+
| Vision | `screenshot` — PNG + size + path; `region` crops before scaling (sharp text), `scale` sets pixels per logical pixel, `ref` crops to one element, `marks` draws numbered boxes around clickable elements and returns them in screenshot pixels; the first call asks for permission once |
|
|
49
|
+
| Tree | `ui_apps`, `ui_tree` (prune with `roles` + `compact`), `ui_find`, `ui_describe`, `ui_text` |
|
|
50
50
|
| Act on elements | `ui_action` (invoke/press/toggle), `ui_focus`, `ui_set_text` |
|
|
51
|
-
| Pointer | `click
|
|
51
|
+
| Pointer | `click` (coordinates, or `text` to hit an element by name), `click_ref` (by accessibility ref), `move`, `drag`, `scroll`, `pointer_button` (hold/release) |
|
|
52
52
|
| Keyboard | `key` (`ctrl+shift+t`), `type_text` (Unicode via clipboard paste) |
|
|
53
53
|
| Clipboard | `clipboard_get`, `clipboard_set` |
|
|
54
54
|
| System | `process_list`, `process_kill`, `launch_app`, `settings_get`, `settings_set`, `settings_list_keys`, `notify`, `display_info`, `desktop_status` |
|
|
55
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
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 |
|
|
57
|
+
| Batching | `sequence` — run up to 25 tools in one call, in order; the reply is a per-step report (`{step, op, ok, ms, error?}`) plus the **last** step's output (images included), so a fixed flow costs one round trip instead of one per step. `stop_on_error: false` keeps going, `allow_active_input: true` covers every injecting step at once, and the step cap can be raised with `DSH_LINUX_CU_SEQUENCE_MAX_STEPS` |
|
|
57
58
|
| Unlocking (opt-in) | `unlock_screen` — only listed while the unlock policy is on; see below |
|
|
58
59
|
|
|
59
60
|
Coordinates are **logical desktop pixels**. Pass `space: "screenshot"` to give
|
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.
|
|
3
|
+
"version": "0.6.1",
|
|
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
|
|
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
|
-
|
|
281
|
-
|
|
282
|
-
|
|
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
|
-
|
|
304
|
-
|
|
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
|
|
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 ------------------------------------------------------------ #
|
|
@@ -377,6 +404,75 @@ class A11y:
|
|
|
377
404
|
continue
|
|
378
405
|
return matches
|
|
379
406
|
|
|
407
|
+
|
|
408
|
+
# -- set of marks ------------------------------------------------------ #
|
|
409
|
+
ACTIONABLE_ROLES = (
|
|
410
|
+
"push button", "button", "toggle button", "check box", "radio button",
|
|
411
|
+
"menu item", "check menu item", "radio menu item", "entry", "text",
|
|
412
|
+
"link", "tab", "page tab", "combo box", "slider", "spin button",
|
|
413
|
+
"switch", "tree item", "list item",
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
def actionable(self, apps: int = 25, limit: int = 60, timeout_s: float = 6.0) -> list[dict]:
|
|
417
|
+
"""Collect clickable elements in reading order.
|
|
418
|
+
|
|
419
|
+
A node qualifies when its role is interactive or it exposes an action.
|
|
420
|
+
On Wayland most toolkits publish no screen rectangle, so the rectangle is
|
|
421
|
+
optional: when it is missing the node is still reported, and callers are
|
|
422
|
+
expected to drive it through its accessibility action instead of a
|
|
423
|
+
synthetic pointer click.
|
|
424
|
+
"""
|
|
425
|
+
self.start()
|
|
426
|
+
deadline = time.monotonic() + timeout_s
|
|
427
|
+
queue: list = []
|
|
428
|
+
for item in self.apps()[:apps]:
|
|
429
|
+
target = self._apps.get(item["name"])
|
|
430
|
+
if target is not None:
|
|
431
|
+
queue.append(target)
|
|
432
|
+
found: list[dict] = []
|
|
433
|
+
seen: set[tuple] = set()
|
|
434
|
+
visited = 0
|
|
435
|
+
while queue and len(found) < limit and time.monotonic() < deadline and visited < 4000:
|
|
436
|
+
acc = queue.pop(0)
|
|
437
|
+
visited += 1
|
|
438
|
+
try:
|
|
439
|
+
role_name = (acc.get_role_name() or "").lower()
|
|
440
|
+
name = acc.get_name() or ""
|
|
441
|
+
states = set(_state_names(acc))
|
|
442
|
+
except Exception: # noqa: BLE001
|
|
443
|
+
continue
|
|
444
|
+
if "defunct" in states:
|
|
445
|
+
continue
|
|
446
|
+
acts = _actions(acc)
|
|
447
|
+
worth = role_name in self.ACTIONABLE_ROLES or any(
|
|
448
|
+
word in act for act in acts for word in ("press", "click", "activate"))
|
|
449
|
+
rect = _extents(acc)
|
|
450
|
+
if rect is not None and (rect["width"] < 8 or rect["height"] < 8):
|
|
451
|
+
rect = None
|
|
452
|
+
if worth:
|
|
453
|
+
key = ("box", rect["x"], rect["y"], rect["width"], rect["height"]) if rect else (
|
|
454
|
+
"node", role_name, name[:80])
|
|
455
|
+
if key not in seen:
|
|
456
|
+
seen.add(key)
|
|
457
|
+
entry = {"ref": self._ref(acc), "role": role_name}
|
|
458
|
+
if name:
|
|
459
|
+
entry["name"] = name[:80]
|
|
460
|
+
if rect:
|
|
461
|
+
entry["rect"] = rect
|
|
462
|
+
if acts:
|
|
463
|
+
entry["actions"] = acts[:4]
|
|
464
|
+
found.append(entry)
|
|
465
|
+
try:
|
|
466
|
+
for index in range(min(acc.get_child_count(), 200)):
|
|
467
|
+
child = acc.get_child_at_index(index)
|
|
468
|
+
if child is not None:
|
|
469
|
+
queue.append(child)
|
|
470
|
+
except Exception: # noqa: BLE001
|
|
471
|
+
continue
|
|
472
|
+
found.sort(key=lambda item: (
|
|
473
|
+
(0, item["rect"]["y"], item["rect"]["x"]) if item.get("rect") else (1, 0, 0)))
|
|
474
|
+
return found
|
|
475
|
+
|
|
380
476
|
def describe_object(self, acc, name: str | None = None, role_name: str | None = None) -> dict:
|
|
381
477
|
try:
|
|
382
478
|
name = name if name is not None else (acc.get_name() or "")
|
package/server/cu_display.py
CHANGED
|
@@ -523,6 +523,61 @@ def downscale(path: str, max_width: int) -> tuple[int, int]:
|
|
|
523
523
|
return (width, height)
|
|
524
524
|
|
|
525
525
|
|
|
526
|
+
# --------------------------------------------------------------------------- #
|
|
527
|
+
# set-of-marks overlay
|
|
528
|
+
# --------------------------------------------------------------------------- #
|
|
529
|
+
|
|
530
|
+
_MARK_COLOURS = (
|
|
531
|
+
(0.98, 0.26, 0.26),
|
|
532
|
+
(0.16, 0.42, 0.98),
|
|
533
|
+
(0.10, 0.62, 0.36),
|
|
534
|
+
(0.85, 0.45, 0.05),
|
|
535
|
+
(0.55, 0.25, 0.75),
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def annotate(path: str, marks: list[dict]) -> tuple[int, int]:
|
|
540
|
+
"""Draw numbered boxes on a PNG so the model can refer to them by id.
|
|
541
|
+
|
|
542
|
+
Each mark carries x/y/width/height already expressed in image pixels, plus
|
|
543
|
+
an ``id``. The image is edited in place and its size is returned.
|
|
544
|
+
"""
|
|
545
|
+
if not marks:
|
|
546
|
+
return png_size(path)
|
|
547
|
+
try:
|
|
548
|
+
import cairo # noqa: PLC0415 (optional at import time)
|
|
549
|
+
except Exception: # noqa: BLE001
|
|
550
|
+
return png_size(path)
|
|
551
|
+
surface = cairo.ImageSurface.create_from_png(path)
|
|
552
|
+
ctx = cairo.Context(surface)
|
|
553
|
+
ctx.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
|
|
554
|
+
ctx.set_font_size(13.0)
|
|
555
|
+
for mark in marks:
|
|
556
|
+
x = float(mark["x"])
|
|
557
|
+
y = float(mark["y"])
|
|
558
|
+
w = float(mark["width"])
|
|
559
|
+
h = float(mark["height"])
|
|
560
|
+
colour = _MARK_COLOURS[int(mark.get("colour", 0)) % len(_MARK_COLOURS)]
|
|
561
|
+
ctx.set_line_width(2.0)
|
|
562
|
+
ctx.set_source_rgba(colour[0], colour[1], colour[2], 0.95)
|
|
563
|
+
ctx.rectangle(x + 1.0, y + 1.0, max(1.0, w - 2.0), max(1.0, h - 2.0))
|
|
564
|
+
ctx.stroke()
|
|
565
|
+
label = str(mark["id"])
|
|
566
|
+
extents = ctx.text_extents(label)
|
|
567
|
+
pad = 3.0
|
|
568
|
+
box_w = extents.width + pad * 2
|
|
569
|
+
box_h = extents.height + pad * 2
|
|
570
|
+
left = min(max(0.0, x), max(0.0, surface.get_width() - box_w))
|
|
571
|
+
top = y - box_h if y - box_h >= 0 else y
|
|
572
|
+
ctx.rectangle(left, top, box_w, box_h)
|
|
573
|
+
ctx.fill()
|
|
574
|
+
ctx.set_source_rgba(1.0, 1.0, 1.0, 1.0)
|
|
575
|
+
ctx.move_to(left + pad, top + box_h - pad - extents.y_bearing * 0 - 2.0)
|
|
576
|
+
ctx.show_text(label)
|
|
577
|
+
surface.write_to_png(path)
|
|
578
|
+
return surface.get_width(), surface.get_height()
|
|
579
|
+
|
|
580
|
+
|
|
526
581
|
def crop_and_scale(path: str, box: tuple[int, int, int, int], out_width: int) -> tuple[int, int]:
|
|
527
582
|
"""Crop ``box`` (physical pixels) out of a PNG, then scale it to ``out_width``.
|
|
528
583
|
|
package/server/cu_unlock.py
CHANGED
|
@@ -43,6 +43,10 @@ class UnlockError(RuntimeError):
|
|
|
43
43
|
pass
|
|
44
44
|
|
|
45
45
|
|
|
46
|
+
class KeyringLocked(UnlockError):
|
|
47
|
+
"""The secret service accepted the call but never answered it."""
|
|
48
|
+
|
|
49
|
+
|
|
46
50
|
# --------------------------------------------------------------------------- #
|
|
47
51
|
# settings
|
|
48
52
|
# --------------------------------------------------------------------------- #
|
|
@@ -173,12 +177,20 @@ def fetch_password() -> str | None:
|
|
|
173
177
|
binary = shutil.which("secret-tool")
|
|
174
178
|
if not binary:
|
|
175
179
|
return None
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
180
|
+
try:
|
|
181
|
+
proc = subprocess.run(
|
|
182
|
+
[binary, "lookup", "service", SERVICE, "account", _account()],
|
|
183
|
+
text=True,
|
|
184
|
+
capture_output=True,
|
|
185
|
+
timeout=6,
|
|
186
|
+
)
|
|
187
|
+
except (subprocess.TimeoutExpired, OSError) as error:
|
|
188
|
+
# A locked login keyring pops up a prompt and blocks the helper; the
|
|
189
|
+
# caller needs a clear answer rather than a hang.
|
|
190
|
+
raise KeyringLocked(
|
|
191
|
+
"the login keyring did not answer: it is probably locked, so the "
|
|
192
|
+
"stored unlock password cannot be read in this session"
|
|
193
|
+
) from error
|
|
182
194
|
if proc.returncode != 0:
|
|
183
195
|
return None
|
|
184
196
|
value = proc.stdout.rstrip("\n")
|
|
@@ -206,7 +218,10 @@ def clear_password() -> bool:
|
|
|
206
218
|
|
|
207
219
|
|
|
208
220
|
def has_password() -> bool:
|
|
209
|
-
|
|
221
|
+
try:
|
|
222
|
+
return fetch_password() is not None
|
|
223
|
+
except Exception:
|
|
224
|
+
return False
|
|
210
225
|
|
|
211
226
|
|
|
212
227
|
# --------------------------------------------------------------------------- #
|
|
@@ -216,12 +231,22 @@ def has_password() -> bool:
|
|
|
216
231
|
|
|
217
232
|
def status() -> dict[str, Any]:
|
|
218
233
|
policy_name = policy()
|
|
219
|
-
stored
|
|
234
|
+
stored: bool | None = None
|
|
235
|
+
note: str | None = None
|
|
236
|
+
if policy_name == "keyring":
|
|
237
|
+
try:
|
|
238
|
+
stored = fetch_password() is not None
|
|
239
|
+
except KeyringLocked as error:
|
|
240
|
+
stored = None
|
|
241
|
+
note = str(error)
|
|
242
|
+
except Exception:
|
|
243
|
+
stored = None
|
|
220
244
|
return {
|
|
221
245
|
"unlock_policy": policy_name,
|
|
222
246
|
"password_stored": stored,
|
|
223
247
|
"settings_path": SETTINGS_PATH,
|
|
224
248
|
"available_policies": list(POLICIES),
|
|
249
|
+
**({"error": note} if note else {}),
|
|
225
250
|
}
|
|
226
251
|
|
|
227
252
|
|
|
@@ -32,6 +32,7 @@ from __future__ import annotations
|
|
|
32
32
|
import base64
|
|
33
33
|
import json
|
|
34
34
|
import os
|
|
35
|
+
import shutil
|
|
35
36
|
import subprocess
|
|
36
37
|
import sys
|
|
37
38
|
import time
|
|
@@ -46,7 +47,7 @@ import cu_sys # noqa: E402
|
|
|
46
47
|
import cu_unlock # noqa: E402
|
|
47
48
|
|
|
48
49
|
SERVER_NAME = "linux-desktop-mcp"
|
|
49
|
-
SERVER_VERSION = "1.
|
|
50
|
+
SERVER_VERSION = "1.5.1"
|
|
50
51
|
PROTOCOL_VERSION = "2025-06-18"
|
|
51
52
|
SUPPORTED_PROTOCOLS = {"2024-11-05", "2025-03-26", "2025-06-18"}
|
|
52
53
|
LOG_PATH = os.path.join(cu_display.CACHE_DIR, "server.log")
|
|
@@ -290,6 +291,46 @@ def capture_shot(
|
|
|
290
291
|
# --------------------------------------------------------------------------- #
|
|
291
292
|
# tool implementations
|
|
292
293
|
# --------------------------------------------------------------------------- #
|
|
294
|
+
def _draw_marks(info: dict, limit: int) -> list[dict]:
|
|
295
|
+
"""Collect clickable nodes, express them in screenshot pixels, and draw them."""
|
|
296
|
+
origin_x = float(info.get("origin_x", 0.0))
|
|
297
|
+
origin_y = float(info.get("origin_y", 0.0))
|
|
298
|
+
ratio = float(LAST_SHOT.get("ratio") or 1.0) or 1.0
|
|
299
|
+
try:
|
|
300
|
+
nodes = A11Y.actionable(limit=max(1, limit))
|
|
301
|
+
except cu_a11y.A11yError:
|
|
302
|
+
return []
|
|
303
|
+
marks: list[dict] = []
|
|
304
|
+
for node in nodes:
|
|
305
|
+
rect = node.get("rect")
|
|
306
|
+
if not rect:
|
|
307
|
+
continue
|
|
308
|
+
left = (rect["x"] - origin_x) / ratio
|
|
309
|
+
top = (rect["y"] - origin_y) / ratio
|
|
310
|
+
width = rect["width"] / ratio
|
|
311
|
+
height = rect["height"] / ratio
|
|
312
|
+
if left + width < 0 or top + height < 0:
|
|
313
|
+
continue
|
|
314
|
+
if left > info["width"] or top > info["height"]:
|
|
315
|
+
continue
|
|
316
|
+
if width < 6 or height < 6:
|
|
317
|
+
continue
|
|
318
|
+
marks.append({
|
|
319
|
+
"id": len(marks) + 1,
|
|
320
|
+
"ref": node["ref"],
|
|
321
|
+
"role": node["role"],
|
|
322
|
+
"name": node.get("name", ""),
|
|
323
|
+
"x": round(left),
|
|
324
|
+
"y": round(top),
|
|
325
|
+
"width": round(width),
|
|
326
|
+
"height": round(height),
|
|
327
|
+
"colour": len(marks),
|
|
328
|
+
})
|
|
329
|
+
if marks:
|
|
330
|
+
cu_display.annotate(info["path"], marks)
|
|
331
|
+
return [{key: value for key, value in mark.items() if key != "colour"} for mark in marks]
|
|
332
|
+
|
|
333
|
+
|
|
293
334
|
def tool_screenshot(args: dict) -> dict:
|
|
294
335
|
max_width = int(args.get("max_width", SHOT_MAX_WIDTH))
|
|
295
336
|
region = _parse_region(args.get("region"))
|
|
@@ -297,6 +338,17 @@ def tool_screenshot(args: dict) -> dict:
|
|
|
297
338
|
scale = float(scale) if scale else None
|
|
298
339
|
if scale is not None and scale <= 0:
|
|
299
340
|
raise ToolError("scale must be positive (1.0 = one screenshot pixel per logical pixel)")
|
|
341
|
+
ref = args.get("ref")
|
|
342
|
+
if ref:
|
|
343
|
+
if region is not None:
|
|
344
|
+
raise ToolError("pass either region or ref, not both")
|
|
345
|
+
node = A11Y.describe(str(ref))
|
|
346
|
+
rect = node.get("rect")
|
|
347
|
+
if not rect:
|
|
348
|
+
raise ToolError(f"element {ref} has no on-screen rectangle to crop to")
|
|
349
|
+
region = (rect["x"], rect["y"], rect["width"], rect["height"])
|
|
350
|
+
if scale is None:
|
|
351
|
+
scale = 1.0
|
|
300
352
|
info = capture_shot(max_width, region=region, scale=scale)
|
|
301
353
|
try:
|
|
302
354
|
with open(info["path"], "rb") as handle:
|
|
@@ -314,6 +366,12 @@ def tool_screenshot(args: dict) -> dict:
|
|
|
314
366
|
logical_width = (info.get("region") or {}).get("width") or info["logical_width"]
|
|
315
367
|
info["coordinate_scale"] = round(logical_width / width, 6) if width else 1.0
|
|
316
368
|
LAST_SHOT.update({"width": width, "height": height, "ratio": info["coordinate_scale"]})
|
|
369
|
+
marks: list[dict] = []
|
|
370
|
+
wanted_marks = bool(args.get("marks"))
|
|
371
|
+
if wanted_marks:
|
|
372
|
+
marks = _draw_marks(info, int(args.get("marks_limit", 40)))
|
|
373
|
+
with open(info["path"], "rb") as handle:
|
|
374
|
+
payload = handle.read()
|
|
317
375
|
encoded = base64.b64encode(payload).decode("ascii")
|
|
318
376
|
if info.get("region"):
|
|
319
377
|
note = (
|
|
@@ -332,6 +390,36 @@ def tool_screenshot(args: dict) -> dict:
|
|
|
332
390
|
f"To click at a pixel of this image pass space='screenshot'; "
|
|
333
391
|
f"otherwise multiply by {info['coordinate_scale']}."
|
|
334
392
|
)
|
|
393
|
+
if wanted_marks:
|
|
394
|
+
info["marks"] = marks
|
|
395
|
+
info["mark_count"] = len(marks)
|
|
396
|
+
if marks:
|
|
397
|
+
note += (
|
|
398
|
+
f" {len(marks)} numbered boxes mark clickable elements; click one with "
|
|
399
|
+
"click_ref({ref}) or by the coordinates listed in \"marks\" (screenshot space)."
|
|
400
|
+
)
|
|
401
|
+
else:
|
|
402
|
+
# Wayland apps often publish no screen rectangles, so nothing can be
|
|
403
|
+
# boxed; a list of refs is still useful because click_ref can act on them.
|
|
404
|
+
try:
|
|
405
|
+
clickable = [
|
|
406
|
+
{k: node[k] for k in ("ref", "role", "name", "actions") if k in node}
|
|
407
|
+
for node in A11Y.actionable(limit=max(1, min(int(args.get("marks_limit", 40)), 40)))
|
|
408
|
+
]
|
|
409
|
+
except cu_a11y.A11yError:
|
|
410
|
+
clickable = []
|
|
411
|
+
info["clickable"] = clickable
|
|
412
|
+
if clickable:
|
|
413
|
+
note += (
|
|
414
|
+
f" No boxes were drawn because these windows publish no screen rectangles on"
|
|
415
|
+
f" Wayland, but {len(clickable)} clickable elements were found: pick a ref from"
|
|
416
|
+
" \"clickable\" and pass it to click_ref."
|
|
417
|
+
)
|
|
418
|
+
else:
|
|
419
|
+
note += (
|
|
420
|
+
" No clickable element was found in this area"
|
|
421
|
+
" (a locked session hides most of the tree), so no boxes were drawn."
|
|
422
|
+
)
|
|
335
423
|
return {
|
|
336
424
|
"content": [
|
|
337
425
|
{"type": "image", "data": encoded, "mimeType": "image/png"},
|
|
@@ -349,7 +437,15 @@ def tool_ui_tree(args: dict) -> dict:
|
|
|
349
437
|
app = args.get("app")
|
|
350
438
|
depth = max(1, min(int(args.get("max_depth", 3)), 8))
|
|
351
439
|
nodes = max(10, min(int(args.get("max_nodes", 220)), 1200))
|
|
352
|
-
|
|
440
|
+
roles = args.get("roles")
|
|
441
|
+
if isinstance(roles, str):
|
|
442
|
+
roles = [roles]
|
|
443
|
+
if roles is not None and not isinstance(roles, list):
|
|
444
|
+
raise ToolError("roles must be a list of role name fragments, e.g. [\"push button\", \"entry\"]")
|
|
445
|
+
compact = bool(args.get("compact", False))
|
|
446
|
+
snapshot = A11Y.snapshot(app=app, max_depth=depth, max_nodes=nodes,
|
|
447
|
+
roles=[str(item) for item in roles] if roles else None,
|
|
448
|
+
compact=compact)
|
|
353
449
|
if snapshot["nodes_used"] <= 3 and snapshot["applications"]:
|
|
354
450
|
snapshot["hint"] = (
|
|
355
451
|
"the application exposes (almost) no accessibility nodes: Chromium, "
|
|
@@ -403,6 +499,37 @@ def tool_ui_set_text(args: dict) -> dict:
|
|
|
403
499
|
|
|
404
500
|
def tool_click(args: dict) -> dict:
|
|
405
501
|
_guard_input("click", args)
|
|
502
|
+
text = args.get("text")
|
|
503
|
+
if text and args.get("x") is None and args.get("y") is None:
|
|
504
|
+
hits = [
|
|
505
|
+
hit for hit in A11Y.find(
|
|
506
|
+
query=str(text),
|
|
507
|
+
role=args.get("role"),
|
|
508
|
+
app=args.get("app"),
|
|
509
|
+
limit=5,
|
|
510
|
+
)
|
|
511
|
+
if hit.get("center")
|
|
512
|
+
]
|
|
513
|
+
if not hits:
|
|
514
|
+
raise ToolError(
|
|
515
|
+
f"no element whose name or text matches {text!r}; "
|
|
516
|
+
"try ui_find to see what is there, or click by coordinates"
|
|
517
|
+
)
|
|
518
|
+
best = hits[0]
|
|
519
|
+
button = _button_name(args.get("button", 1))
|
|
520
|
+
count = max(1, min(int(args.get("count", 1)), 3))
|
|
521
|
+
controller().click(best["center"][0], best["center"][1], button=button, count=count)
|
|
522
|
+
return {
|
|
523
|
+
"clicked": {
|
|
524
|
+
"x": best["center"][0],
|
|
525
|
+
"y": best["center"][1],
|
|
526
|
+
"button": button,
|
|
527
|
+
"count": count,
|
|
528
|
+
"matched": best.get("name") or best.get("text", "")[:60],
|
|
529
|
+
"role": best.get("role"),
|
|
530
|
+
"ref": best.get("ref"),
|
|
531
|
+
}
|
|
532
|
+
}
|
|
406
533
|
x, y = _point(args)
|
|
407
534
|
x, y = _to_logical(x, y, str(args.get("space", "logical")))
|
|
408
535
|
button = _button_name(args.get("button", 1))
|
|
@@ -411,6 +538,67 @@ def tool_click(args: dict) -> dict:
|
|
|
411
538
|
return {"clicked": {"x": round(x), "y": round(y), "button": button, "count": count}}
|
|
412
539
|
|
|
413
540
|
|
|
541
|
+
def tool_click_ref(args: dict) -> dict:
|
|
542
|
+
"""Click an accessibility node.
|
|
543
|
+
|
|
544
|
+
Wayland apps rarely publish global screen rectangles, so a pointer click is not
|
|
545
|
+
always possible: try the widget's own click action first and fall back to the
|
|
546
|
+
pointer when the node does have a rectangle.
|
|
547
|
+
"""
|
|
548
|
+
_guard_input("click", args)
|
|
549
|
+
ref = str(_require(args, "ref"))
|
|
550
|
+
node = A11Y.describe(ref)
|
|
551
|
+
center = node.get("center")
|
|
552
|
+
rect = node.get("rect")
|
|
553
|
+
if not center and rect:
|
|
554
|
+
center = [rect["x"] + rect["width"] // 2, rect["y"] + rect["height"] // 2]
|
|
555
|
+
button = _button_name(args.get("button", 1))
|
|
556
|
+
count = max(1, min(int(args.get("count", 1)), 3))
|
|
557
|
+
prefer = args.get("via", "auto")
|
|
558
|
+
failures: list[str] = []
|
|
559
|
+
|
|
560
|
+
if prefer in ("auto", "action"):
|
|
561
|
+
try:
|
|
562
|
+
done = A11Y.action(ref, "click")
|
|
563
|
+
except cu_a11y.A11yError:
|
|
564
|
+
try:
|
|
565
|
+
done = A11Y.action(ref, None)
|
|
566
|
+
except cu_a11y.A11yError as error:
|
|
567
|
+
done = None
|
|
568
|
+
failures.append(str(error))
|
|
569
|
+
if done is not None:
|
|
570
|
+
return {
|
|
571
|
+
"clicked": {
|
|
572
|
+
"ref": ref,
|
|
573
|
+
"role": node.get("role"),
|
|
574
|
+
"name": node.get("name", ""),
|
|
575
|
+
"via": "accessibility-action",
|
|
576
|
+
"action": done.get("action"),
|
|
577
|
+
"button": button,
|
|
578
|
+
"count": count,
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
if not center:
|
|
583
|
+
detail = f"element {ref} has no on-screen rectangle"
|
|
584
|
+
if failures:
|
|
585
|
+
detail = f"{detail} and no clickable action ({'; '.join(failures)})"
|
|
586
|
+
raise ToolError(f"{detail}, so it cannot be clicked")
|
|
587
|
+
controller().click(center[0], center[1], button=button, count=count)
|
|
588
|
+
return {
|
|
589
|
+
"clicked": {
|
|
590
|
+
"x": round(center[0]),
|
|
591
|
+
"y": round(center[1]),
|
|
592
|
+
"button": button,
|
|
593
|
+
"count": count,
|
|
594
|
+
"ref": ref,
|
|
595
|
+
"role": node.get("role"),
|
|
596
|
+
"name": node.get("name", ""),
|
|
597
|
+
"via": "pointer",
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
|
|
414
602
|
def tool_move(args: dict) -> dict:
|
|
415
603
|
_guard_input("move the pointer", args)
|
|
416
604
|
x, y = _point(args)
|
|
@@ -905,6 +1093,14 @@ def tool_display_info(args: dict) -> dict:
|
|
|
905
1093
|
return info
|
|
906
1094
|
|
|
907
1095
|
|
|
1096
|
+
def _unlock_status() -> dict:
|
|
1097
|
+
"""Never let a locked keyring take the whole status call down."""
|
|
1098
|
+
try:
|
|
1099
|
+
return cu_unlock.status()
|
|
1100
|
+
except Exception as error: # noqa: BLE001 - diagnostics must not raise
|
|
1101
|
+
return {"unlock_policy": cu_unlock.policy(), "password_stored": None, "error": str(error)}
|
|
1102
|
+
|
|
1103
|
+
|
|
908
1104
|
def tool_desktop_status(args: dict) -> dict:
|
|
909
1105
|
status: dict = {"server": {"name": SERVER_NAME, "version": SERVER_VERSION, "log": LOG_PATH}}
|
|
910
1106
|
status["session"] = {
|
|
@@ -913,7 +1109,7 @@ def tool_desktop_status(args: dict) -> dict:
|
|
|
913
1109
|
"locked": cu_sys.screen_locked(),
|
|
914
1110
|
"idle_ms": cu_sys.idle_ms(),
|
|
915
1111
|
"input_guard_ms": IDLE_GUARD_MS,
|
|
916
|
-
"unlock":
|
|
1112
|
+
"unlock": _unlock_status(),
|
|
917
1113
|
}
|
|
918
1114
|
try:
|
|
919
1115
|
current = layout()
|
|
@@ -1000,6 +1196,7 @@ ALLOW_ACTIVE_PROP = {
|
|
|
1000
1196
|
# Tools that inject input all accept the same escape hatch; adding it here keeps
|
|
1001
1197
|
# the schema in one place instead of ten copies.
|
|
1002
1198
|
_INJECTING_TOOLS = {
|
|
1199
|
+
"click_ref",
|
|
1003
1200
|
"click",
|
|
1004
1201
|
"move",
|
|
1005
1202
|
"drag",
|
|
@@ -1028,6 +1225,85 @@ def tool_unlock_screen(args: dict) -> dict:
|
|
|
1028
1225
|
return result
|
|
1029
1226
|
|
|
1030
1227
|
|
|
1228
|
+
SEQUENCE_MAX_STEPS = int(os.environ.get("DSH_LINUX_CU_SEQUENCE_MAX_STEPS", "25"))
|
|
1229
|
+
SEQUENCE_TEXT_LIMIT = 1200
|
|
1230
|
+
|
|
1231
|
+
|
|
1232
|
+
def _sequence_step_report(position: int, op: str, ok: bool, elapsed_ms: float, error: str | None = None) -> dict:
|
|
1233
|
+
entry = {"step": position, "op": op, "ok": ok, "ms": int(elapsed_ms)}
|
|
1234
|
+
if error:
|
|
1235
|
+
entry["error"] = error
|
|
1236
|
+
return entry
|
|
1237
|
+
|
|
1238
|
+
|
|
1239
|
+
def tool_sequence(args: dict) -> dict:
|
|
1240
|
+
steps = args.get("steps")
|
|
1241
|
+
if not isinstance(steps, list) or not steps:
|
|
1242
|
+
raise ToolError('steps must be a non-empty list of {"op": "...", "args": {...}} objects')
|
|
1243
|
+
if len(steps) > SEQUENCE_MAX_STEPS:
|
|
1244
|
+
raise ToolError(f"too many steps ({len(steps)}); the limit is {SEQUENCE_MAX_STEPS} per call")
|
|
1245
|
+
stop_on_error = bool(args.get("stop_on_error", True))
|
|
1246
|
+
inject_default = bool(args.get("allow_active_input", False))
|
|
1247
|
+
index = tool_index()
|
|
1248
|
+
report: list[dict] = []
|
|
1249
|
+
last_content: list[dict] | None = None
|
|
1250
|
+
stopped_at: int | None = None
|
|
1251
|
+
started = time.monotonic()
|
|
1252
|
+
for position, step in enumerate(steps, start=1):
|
|
1253
|
+
if not isinstance(step, dict):
|
|
1254
|
+
raise ToolError(f'step {position} must be an object like {{"op": "click", "args": {{...}}}}')
|
|
1255
|
+
op = step.get("op")
|
|
1256
|
+
if not isinstance(op, str) or not op.strip():
|
|
1257
|
+
raise ToolError(f'step {position} needs an "op" name')
|
|
1258
|
+
op = op.strip()
|
|
1259
|
+
if op == "sequence":
|
|
1260
|
+
raise ToolError("a sequence cannot contain another sequence")
|
|
1261
|
+
step_args = step.get("args") or {}
|
|
1262
|
+
if not isinstance(step_args, dict):
|
|
1263
|
+
raise ToolError(f"step {position} args must be an object")
|
|
1264
|
+
step_args = dict(step_args)
|
|
1265
|
+
if op not in index:
|
|
1266
|
+
report.append(_sequence_step_report(position, op, False, 0.0, f"unknown tool; available: {sorted(index)}"))
|
|
1267
|
+
if stop_on_error:
|
|
1268
|
+
stopped_at = position
|
|
1269
|
+
break
|
|
1270
|
+
continue
|
|
1271
|
+
if inject_default and op in _INJECTING_TOOLS:
|
|
1272
|
+
step_args.setdefault("allow_active_input", True)
|
|
1273
|
+
began = time.monotonic()
|
|
1274
|
+
payload = call_tool(op, step_args)
|
|
1275
|
+
took = (time.monotonic() - began) * 1000
|
|
1276
|
+
content = payload.get("content") or []
|
|
1277
|
+
if payload.get("isError"):
|
|
1278
|
+
message = " ".join(
|
|
1279
|
+
str(block.get("text", "")) for block in content if isinstance(block, dict)
|
|
1280
|
+
).strip()
|
|
1281
|
+
report.append(_sequence_step_report(position, op, False, took, message or "failed"))
|
|
1282
|
+
if stop_on_error:
|
|
1283
|
+
stopped_at = position
|
|
1284
|
+
break
|
|
1285
|
+
continue
|
|
1286
|
+
report.append(_sequence_step_report(position, op, True, took))
|
|
1287
|
+
last_content = content
|
|
1288
|
+
elapsed = int((time.monotonic() - started) * 1000)
|
|
1289
|
+
ok = stopped_at is None and all(entry["ok"] for entry in report)
|
|
1290
|
+
summary = {
|
|
1291
|
+
"ok": ok,
|
|
1292
|
+
"steps_total": len(steps),
|
|
1293
|
+
"steps_run": len(report),
|
|
1294
|
+
"stopped_at": stopped_at,
|
|
1295
|
+
"elapsed_ms": elapsed,
|
|
1296
|
+
"steps": report,
|
|
1297
|
+
}
|
|
1298
|
+
boxes = [block for block in (last_content or []) if isinstance(block, dict)]
|
|
1299
|
+
text_tail = " ".join(str(block.get("text", "")) for block in boxes if block.get("type") == "text").strip()
|
|
1300
|
+
if text_tail:
|
|
1301
|
+
summary["last_text"] = text_tail[:SEQUENCE_TEXT_LIMIT]
|
|
1302
|
+
content_out: list[dict] = [{"type": "text", "text": json.dumps(summary, ensure_ascii=False, default=str)}]
|
|
1303
|
+
content_out.extend(block for block in boxes if block.get("type") == "image")
|
|
1304
|
+
return {"content": content_out, "isError": not ok}
|
|
1305
|
+
|
|
1306
|
+
|
|
1031
1307
|
TOOLS: list[dict] = [
|
|
1032
1308
|
{
|
|
1033
1309
|
"name": "screenshot",
|
|
@@ -1067,6 +1343,29 @@ TOOLS: list[dict] = [
|
|
|
1067
1343
|
"Takes precedence over max_width."
|
|
1068
1344
|
),
|
|
1069
1345
|
},
|
|
1346
|
+
"ref": {
|
|
1347
|
+
"type": "string",
|
|
1348
|
+
"description": (
|
|
1349
|
+
"Crop to one accessibility node (a ref from ui_find/ui_tree) instead of a "
|
|
1350
|
+
"region. Great for reading a single widget without guessing its rectangle."
|
|
1351
|
+
),
|
|
1352
|
+
},
|
|
1353
|
+
"marks": {
|
|
1354
|
+
"type": "boolean",
|
|
1355
|
+
"default": False,
|
|
1356
|
+
"description": (
|
|
1357
|
+
"Draw numbered boxes over the clickable elements in the capture and return "
|
|
1358
|
+
"them as \"marks\": [{id, ref, role, name, x, y, width, height}] in screenshot "
|
|
1359
|
+
"pixels. Click one with click_ref or by its coordinates, so no guessing."
|
|
1360
|
+
),
|
|
1361
|
+
},
|
|
1362
|
+
"marks_limit": {
|
|
1363
|
+
"type": "integer",
|
|
1364
|
+
"default": 40,
|
|
1365
|
+
"minimum": 1,
|
|
1366
|
+
"maximum": 120,
|
|
1367
|
+
"description": "How many clickable elements to label at most.",
|
|
1368
|
+
},
|
|
1070
1369
|
},
|
|
1071
1370
|
},
|
|
1072
1371
|
"handler": tool_screenshot,
|
|
@@ -1084,8 +1383,10 @@ TOOLS: list[dict] = [
|
|
|
1084
1383
|
"name": "ui_tree",
|
|
1085
1384
|
"description": (
|
|
1086
1385
|
"Read the accessibility tree of one application (or a few) as nested role/name/rect/"
|
|
1087
|
-
"action nodes. Bounded by max_depth and max_nodes.
|
|
1088
|
-
"
|
|
1386
|
+
"action nodes. Bounded by max_depth and max_nodes. Pass roles to keep only interesting "
|
|
1387
|
+
"kinds of node (ancestors collapse to a bare ref/role/name path), and compact to drop "
|
|
1388
|
+
"rect/states/text: a filtered compact tree is often 10x cheaper than the full one. "
|
|
1389
|
+
"Chromium/Electron/Qt apps usually expose almost nothing; use screenshot for those."
|
|
1089
1390
|
),
|
|
1090
1391
|
"inputSchema": {
|
|
1091
1392
|
"type": "object",
|
|
@@ -1093,6 +1394,19 @@ TOOLS: list[dict] = [
|
|
|
1093
1394
|
"app": {"type": "string", "description": "Application name as shown by ui_apps (substring match)."},
|
|
1094
1395
|
"max_depth": {"type": "integer", "default": 3, "minimum": 1, "maximum": 8},
|
|
1095
1396
|
"max_nodes": {"type": "integer", "default": 220, "minimum": 10, "maximum": 1200},
|
|
1397
|
+
"roles": {
|
|
1398
|
+
"type": "array",
|
|
1399
|
+
"items": {"type": "string"},
|
|
1400
|
+
"description": (
|
|
1401
|
+
"Keep only nodes whose role contains one of these fragments, e.g. "
|
|
1402
|
+
"[\"push button\", \"entry\", \"menu item\"]. Case-insensitive."
|
|
1403
|
+
),
|
|
1404
|
+
},
|
|
1405
|
+
"compact": {
|
|
1406
|
+
"type": "boolean",
|
|
1407
|
+
"default": False,
|
|
1408
|
+
"description": "Drop rect, states and text previews; keep ref, role, name and actions.",
|
|
1409
|
+
},
|
|
1096
1410
|
},
|
|
1097
1411
|
},
|
|
1098
1412
|
"handler": tool_ui_tree,
|
|
@@ -1172,20 +1486,48 @@ TOOLS: list[dict] = [
|
|
|
1172
1486
|
},
|
|
1173
1487
|
{
|
|
1174
1488
|
"name": "click",
|
|
1175
|
-
"description":
|
|
1489
|
+
"description": (
|
|
1490
|
+
"Click at (x, y), or pass text instead of coordinates to click the element whose name "
|
|
1491
|
+
"or text matches. Supports button 1-3 and up to triple clicks."
|
|
1492
|
+
),
|
|
1176
1493
|
"inputSchema": {
|
|
1177
1494
|
"type": "object",
|
|
1178
1495
|
"properties": {
|
|
1179
1496
|
"x": {"type": "number"},
|
|
1180
1497
|
"y": {"type": "number"},
|
|
1498
|
+
"text": {
|
|
1499
|
+
"type": "string",
|
|
1500
|
+
"description": (
|
|
1501
|
+
"Click the first element whose accessible name or text contains this string "
|
|
1502
|
+
"instead of using coordinates. Ignored when x and y are given."
|
|
1503
|
+
),
|
|
1504
|
+
},
|
|
1505
|
+
"role": {"type": "string", "description": "With text: restrict to this role fragment."},
|
|
1506
|
+
"app": {"type": "string", "description": "With text: restrict to this application."},
|
|
1181
1507
|
"button": {"type": "integer", "default": 1, "description": "1 left, 2 middle, 3 right."},
|
|
1182
1508
|
"count": {"type": "integer", "default": 1, "minimum": 1, "maximum": 3},
|
|
1183
1509
|
"space": SPACE_PROP,
|
|
1184
1510
|
},
|
|
1185
|
-
"required": ["x", "y"],
|
|
1186
1511
|
},
|
|
1187
1512
|
"handler": tool_click,
|
|
1188
1513
|
},
|
|
1514
|
+
{
|
|
1515
|
+
"name": "click_ref",
|
|
1516
|
+
"description": (
|
|
1517
|
+
"Click the centre of one accessibility element by ref (from ui_find, ui_tree, or the "
|
|
1518
|
+
"marks list of an annotated screenshot). The reliable way to click: no coordinates."
|
|
1519
|
+
),
|
|
1520
|
+
"inputSchema": {
|
|
1521
|
+
"type": "object",
|
|
1522
|
+
"properties": {
|
|
1523
|
+
"ref": {"type": "string", "description": "Element ref, e.g. \"e42\"."},
|
|
1524
|
+
"button": {"type": "integer", "default": 1, "description": "1 left, 2 middle, 3 right."},
|
|
1525
|
+
"count": {"type": "integer", "default": 1, "minimum": 1, "maximum": 3},
|
|
1526
|
+
},
|
|
1527
|
+
"required": ["ref"],
|
|
1528
|
+
},
|
|
1529
|
+
"handler": tool_click_ref,
|
|
1530
|
+
},
|
|
1189
1531
|
{
|
|
1190
1532
|
"name": "move",
|
|
1191
1533
|
"description": "Move the pointer without clicking (useful to hover for menus and tooltips).",
|
|
@@ -1445,6 +1787,53 @@ TOOLS: list[dict] = [
|
|
|
1445
1787
|
},
|
|
1446
1788
|
"handler": tool_desktop_status,
|
|
1447
1789
|
},
|
|
1790
|
+
{
|
|
1791
|
+
"name": "sequence",
|
|
1792
|
+
"description": (
|
|
1793
|
+
"Run several tools in one call and get a compact per-step report plus the last step's "
|
|
1794
|
+
"output. Use it for a fixed multi-step flow (raise a window, click, type, screenshot): it "
|
|
1795
|
+
"saves one model round trip per step, and images from the final step are passed through. "
|
|
1796
|
+
"Steps run in order and a failing step stops the run unless stop_on_error is false."
|
|
1797
|
+
),
|
|
1798
|
+
"inputSchema": {
|
|
1799
|
+
"type": "object",
|
|
1800
|
+
"properties": {
|
|
1801
|
+
"steps": {
|
|
1802
|
+
"type": "array",
|
|
1803
|
+
"description": (
|
|
1804
|
+
'Ordered steps, e.g. [{"op": "click", "args": {"x": 40, "y": 30}}, '
|
|
1805
|
+
'{"op": "type_text", "args": {"text": "hello"}}]'
|
|
1806
|
+
),
|
|
1807
|
+
"items": {
|
|
1808
|
+
"type": "object",
|
|
1809
|
+
"properties": {
|
|
1810
|
+
"op": {"type": "string", "description": "Tool name, e.g. click, type_text, screenshot"},
|
|
1811
|
+
"args": {"type": "object", "description": "Arguments for that tool"},
|
|
1812
|
+
},
|
|
1813
|
+
"required": ["op"],
|
|
1814
|
+
},
|
|
1815
|
+
},
|
|
1816
|
+
"stop_on_error": {
|
|
1817
|
+
"type": "boolean",
|
|
1818
|
+
"default": True,
|
|
1819
|
+
"description": (
|
|
1820
|
+
"Stop at the first failing step (default). Set false to keep going and report "
|
|
1821
|
+
"every failure, which is useful when a step may legitimately fail."
|
|
1822
|
+
),
|
|
1823
|
+
},
|
|
1824
|
+
"allow_active_input": {
|
|
1825
|
+
"type": "boolean",
|
|
1826
|
+
"default": False,
|
|
1827
|
+
"description": (
|
|
1828
|
+
"Apply allow_active_input=true to every injecting step of the run, instead of "
|
|
1829
|
+
"repeating it in each step's args."
|
|
1830
|
+
),
|
|
1831
|
+
},
|
|
1832
|
+
},
|
|
1833
|
+
"required": ["steps"],
|
|
1834
|
+
},
|
|
1835
|
+
"handler": tool_sequence,
|
|
1836
|
+
},
|
|
1448
1837
|
]
|
|
1449
1838
|
|
|
1450
1839
|
# Every input-injecting tool advertises the idle-guard escape hatch.
|
|
@@ -1624,6 +2013,129 @@ def _portal_screencast_version() -> int | None:
|
|
|
1624
2013
|
return None
|
|
1625
2014
|
|
|
1626
2015
|
|
|
2016
|
+
def _gsettings_list(schema: str, key: str) -> list[str] | None:
|
|
2017
|
+
"""Read a list-valued gsettings key ("['<Super>Tab', '<Alt>Tab']")."""
|
|
2018
|
+
try:
|
|
2019
|
+
result = subprocess.run(
|
|
2020
|
+
["gsettings", "get", schema, key],
|
|
2021
|
+
capture_output=True, text=True, timeout=4.0, check=False,
|
|
2022
|
+
)
|
|
2023
|
+
except (OSError, subprocess.SubprocessError):
|
|
2024
|
+
return None
|
|
2025
|
+
if result.returncode != 0:
|
|
2026
|
+
return None
|
|
2027
|
+
raw = result.stdout.strip()
|
|
2028
|
+
if not raw.startswith("[") or not raw.endswith("]"):
|
|
2029
|
+
return None
|
|
2030
|
+
inner = raw[1:-1].strip()
|
|
2031
|
+
if not inner:
|
|
2032
|
+
return []
|
|
2033
|
+
return [part.strip().strip("'\"") for part in inner.split(",")]
|
|
2034
|
+
|
|
2035
|
+
|
|
2036
|
+
def _keybinding_checks(checks: list) -> None:
|
|
2037
|
+
"""Explain which window-switch shortcut window_activate can actually use."""
|
|
2038
|
+
schema = "org.gnome.desktop.wm.keybindings"
|
|
2039
|
+
windows = _gsettings_list(schema, "switch-windows")
|
|
2040
|
+
apps = _gsettings_list(schema, "switch-applications")
|
|
2041
|
+
if windows is None and apps is None:
|
|
2042
|
+
_check(
|
|
2043
|
+
checks,
|
|
2044
|
+
"keybindings",
|
|
2045
|
+
"warn",
|
|
2046
|
+
"window-switch keybindings are unreadable",
|
|
2047
|
+
"gsettings did not answer; window_activate can still raise XWayland windows",
|
|
2048
|
+
"install libglib2.0-bin (gsettings) to make the keyboard fallback verifiable",
|
|
2049
|
+
)
|
|
2050
|
+
return
|
|
2051
|
+
windows = windows or []
|
|
2052
|
+
apps = apps or []
|
|
2053
|
+
has_alt = any("Alt" in item and "Tab" in item for item in windows)
|
|
2054
|
+
has_super = any("Super" in item and "Tab" in item for item in apps)
|
|
2055
|
+
if has_alt and has_super:
|
|
2056
|
+
_check(
|
|
2057
|
+
checks,
|
|
2058
|
+
"keybindings",
|
|
2059
|
+
"ok",
|
|
2060
|
+
"both window-switch shortcuts are bound",
|
|
2061
|
+
"Alt+Tab switches windows of one application, Super+Tab switches applications",
|
|
2062
|
+
)
|
|
2063
|
+
elif has_super:
|
|
2064
|
+
_check(
|
|
2065
|
+
checks,
|
|
2066
|
+
"keybindings",
|
|
2067
|
+
"ok",
|
|
2068
|
+
"Super+Tab is bound to switch applications",
|
|
2069
|
+
"Alt+Tab is not bound, so window_activate goes straight to Super+Tab",
|
|
2070
|
+
)
|
|
2071
|
+
elif has_alt:
|
|
2072
|
+
_check(
|
|
2073
|
+
checks,
|
|
2074
|
+
"keybindings",
|
|
2075
|
+
"warn",
|
|
2076
|
+
"only Alt+Tab is bound",
|
|
2077
|
+
"Alt+Tab switches windows inside the current application, so raising another application's window may fail",
|
|
2078
|
+
"add a Super+Tab binding to switch-applications, or drag the window forward by hand",
|
|
2079
|
+
)
|
|
2080
|
+
else:
|
|
2081
|
+
_check(
|
|
2082
|
+
checks,
|
|
2083
|
+
"keybindings",
|
|
2084
|
+
"warn",
|
|
2085
|
+
"no window-switch shortcut is bound",
|
|
2086
|
+
"window_activate can only rely on xdotool and the accessibility default action",
|
|
2087
|
+
"bind switch-windows to <Alt>Tab in Settings -> Keyboard -> View and Customise Shortcuts",
|
|
2088
|
+
)
|
|
2089
|
+
|
|
2090
|
+
|
|
2091
|
+
def _sync_check(checks: list) -> None:
|
|
2092
|
+
"""Report whether this running copy is in step with the installed package."""
|
|
2093
|
+
if not os.path.exists(SOURCE_POINTER):
|
|
2094
|
+
_check(
|
|
2095
|
+
checks,
|
|
2096
|
+
"server-copy",
|
|
2097
|
+
"warn",
|
|
2098
|
+
"cannot tell which package this server copy came from",
|
|
2099
|
+
f"{SOURCE_POINTER} is missing; the copy never refreshes itself",
|
|
2100
|
+
"reinstall the bundle, or reload it from Settings -> Plugins",
|
|
2101
|
+
)
|
|
2102
|
+
return
|
|
2103
|
+
try:
|
|
2104
|
+
with open(SOURCE_POINTER, encoding="utf-8") as handle:
|
|
2105
|
+
source = handle.read().strip()
|
|
2106
|
+
except OSError as error: # noqa: BLE001
|
|
2107
|
+
_check(checks, "server-copy", "warn", "cannot read the package pointer", str(error))
|
|
2108
|
+
return
|
|
2109
|
+
fresh = os.path.join(source, "linux_desktop_mcp.py")
|
|
2110
|
+
if not os.path.exists(fresh):
|
|
2111
|
+
_check(
|
|
2112
|
+
checks,
|
|
2113
|
+
"server-copy",
|
|
2114
|
+
"warn",
|
|
2115
|
+
"the package this copy came from is gone",
|
|
2116
|
+
source,
|
|
2117
|
+
"reinstall the bundle; the copy now updates itself from the package on start",
|
|
2118
|
+
)
|
|
2119
|
+
return
|
|
2120
|
+
ours = os.path.abspath(__file__)
|
|
2121
|
+
try:
|
|
2122
|
+
same = open(fresh, "rb").read() == open(ours, "rb").read()
|
|
2123
|
+
except OSError as error: # noqa: BLE001
|
|
2124
|
+
_check(checks, "server-copy", "warn", "cannot compare server copies", str(error))
|
|
2125
|
+
return
|
|
2126
|
+
if same:
|
|
2127
|
+
_check(checks, "server-copy", "ok", "this copy matches the installed package", source)
|
|
2128
|
+
else:
|
|
2129
|
+
_check(
|
|
2130
|
+
checks,
|
|
2131
|
+
"server-copy",
|
|
2132
|
+
"warn",
|
|
2133
|
+
"this copy differs from the installed package",
|
|
2134
|
+
f"package: {fresh}",
|
|
2135
|
+
"restart the MCP entry (or reload the bundle): the server refreshes itself on start",
|
|
2136
|
+
)
|
|
2137
|
+
|
|
2138
|
+
|
|
1627
2139
|
def selftest() -> dict:
|
|
1628
2140
|
"""Collect everything the doctor tool needs, without asking for permissions."""
|
|
1629
2141
|
checks: list[dict] = []
|
|
@@ -1831,6 +2343,9 @@ def selftest() -> dict:
|
|
|
1831
2343
|
except Exception as error: # noqa: BLE001
|
|
1832
2344
|
_check(checks, "a11y", "warn", "AT-SPI is unavailable", str(error), "check that org.a11y.Bus is running")
|
|
1833
2345
|
|
|
2346
|
+
_keybinding_checks(checks)
|
|
2347
|
+
_sync_check(checks)
|
|
2348
|
+
|
|
1834
2349
|
ok = not any(check["status"] == "fail" for check in checks)
|
|
1835
2350
|
return {
|
|
1836
2351
|
"ok": ok,
|
|
@@ -1871,7 +2386,64 @@ def _cli_unlock(args: list[str]) -> int | None:
|
|
|
1871
2386
|
return None
|
|
1872
2387
|
|
|
1873
2388
|
|
|
2389
|
+
INSTALL_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
2390
|
+
SOURCE_POINTER = os.path.join(INSTALL_DIR, ".source")
|
|
2391
|
+
SELF_UPDATE_FLAG = "DSH_LINUX_CU_SELF_UPDATED"
|
|
2392
|
+
|
|
2393
|
+
|
|
2394
|
+
def _self_update() -> None:
|
|
2395
|
+
"""Refresh this copy of the server from the installed package, then re-exec.
|
|
2396
|
+
|
|
2397
|
+
The bundle syncs server/*.py into a stable directory when the *doctor*
|
|
2398
|
+
plugin loads, but the MCP server is started by a different patch entry, so
|
|
2399
|
+
toggling only that entry (or upgrading the npm package) leaves a stale copy
|
|
2400
|
+
behind. A pointer file records where the package lives; comparing against
|
|
2401
|
+
it here makes the server heal itself before it serves a single request.
|
|
2402
|
+
"""
|
|
2403
|
+
if os.environ.get(SELF_UPDATE_FLAG) == "1":
|
|
2404
|
+
return
|
|
2405
|
+
try:
|
|
2406
|
+
with open(SOURCE_POINTER, encoding="utf-8") as handle:
|
|
2407
|
+
source = handle.read().strip()
|
|
2408
|
+
except OSError:
|
|
2409
|
+
return
|
|
2410
|
+
if not source or not os.path.isdir(source):
|
|
2411
|
+
return
|
|
2412
|
+
if os.path.realpath(source) == os.path.realpath(INSTALL_DIR):
|
|
2413
|
+
return
|
|
2414
|
+
if not os.path.exists(os.path.join(source, "linux_desktop_mcp.py")):
|
|
2415
|
+
return
|
|
2416
|
+
changed: list[str] = []
|
|
2417
|
+
for name in sorted(os.listdir(source)):
|
|
2418
|
+
if not name.endswith(".py"):
|
|
2419
|
+
continue
|
|
2420
|
+
fresh = os.path.join(source, name)
|
|
2421
|
+
stale = os.path.join(INSTALL_DIR, name)
|
|
2422
|
+
try:
|
|
2423
|
+
with open(fresh, "rb") as mine, open(stale, "rb") as theirs:
|
|
2424
|
+
if mine.read() == theirs.read():
|
|
2425
|
+
continue
|
|
2426
|
+
except OSError:
|
|
2427
|
+
pass
|
|
2428
|
+
try:
|
|
2429
|
+
shutil.copyfile(fresh, stale)
|
|
2430
|
+
changed.append(name)
|
|
2431
|
+
except OSError as error: # noqa: BLE001
|
|
2432
|
+
log(f"self-refresh could not copy {name}: {error}")
|
|
2433
|
+
if not changed:
|
|
2434
|
+
return
|
|
2435
|
+
log(f"refreshed {len(changed)} server file(s) from {source}: {', '.join(changed)}")
|
|
2436
|
+
env = dict(os.environ)
|
|
2437
|
+
env[SELF_UPDATE_FLAG] = "1"
|
|
2438
|
+
try:
|
|
2439
|
+
os.execve(sys.executable, [sys.executable, os.path.abspath(__file__), *sys.argv[1:]], env)
|
|
2440
|
+
except OSError as error: # noqa: BLE001
|
|
2441
|
+
log(f"self-refresh re-exec failed: {error}")
|
|
2442
|
+
|
|
2443
|
+
|
|
1874
2444
|
def main() -> int:
|
|
2445
|
+
# Serve (and diagnose) with the freshest copy of the code we can find.
|
|
2446
|
+
_self_update()
|
|
1875
2447
|
unlock_exit = _cli_unlock(sys.argv[1:])
|
|
1876
2448
|
if unlock_exit is not None:
|
|
1877
2449
|
return unlock_exit
|