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

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,61 @@
1
+ ## 0.6.2 - 2026-11-28
2
+
3
+ - **A sequence no longer trips its own idle guard.** Injected events reset Mutter's idle timer, so the second step of a `sequence` used to be refused as "the user is at the keyboard (last input 0.0s ago)". Input we injected ourselves is now recognised for 2.5 s.
4
+ - **`click {text}` works on Wayland.** It used to require a screen rectangle, which GTK 4 and Chromium never publish, so every text click answered "no element whose name or text matches". It now falls back to the widget's own click action and reports `via: "accessibility-action"`.
5
+
1
6
  # Changelog
2
7
 
8
+ ## 0.6.1 - 2026-11-28
9
+
10
+ - `desktop_status` no longer fails when the login keyring is locked: the secret
11
+ lookup gets a 6 second deadline and a locked keyring is reported as
12
+ `password_stored: null` with an `error` line instead of a 20 second hang.
13
+ - Same guard on `unlock_screen`: it now says the keyring is locked instead of
14
+ blocking the whole tool call.
15
+ - **Wayland apps publish no screen rectangles.** GTK 4 and Chromium report empty
16
+ AT-SPI extents, so `marks: true` can draw no numbered boxes and `click_ref`
17
+ cannot compute a centre point. `marks: true` now answers with a `clickable`
18
+ list of `{ref, role, name}` instead of pretending nothing is on screen, and
19
+ `click_ref` drives elements through their accessibility action first (which
20
+ works without coordinates), falling back to a pointer click only when a
21
+ rectangle exists. `actionable()` also scans 25 applications instead of 6, so
22
+ the list is no longer empty when the interesting window is late in the list.
23
+ - server 1.5.1.
24
+
25
+ ## 0.6.0 - 2026-11-28
26
+
27
+ - **One call can run a whole flow.** `sequence {steps: [{op, args}, ...]}` runs up
28
+ to 25 tools in order and answers with a compact per-step report
29
+ (`{step, op, ok, ms, error?}`), the run's `elapsed_ms`, and the **last** step's
30
+ output — images included, so a "raise the window, click, type, screenshot" flow
31
+ costs one round trip instead of four. `stop_on_error: false` keeps going and
32
+ reports every failure; `allow_active_input: true` applies the idle-guard escape
33
+ hatch to every injecting step at once instead of repeating it in each step.
34
+ A sequence cannot nest another sequence (the cap is 25 steps, override with
35
+ `DSH_LINUX_CU_SEQUENCE_MAX_STEPS`).
36
+ - `ok` is true only when *every* step succeeded; `stopped_at` names the step that
37
+ halted the run.
38
+ - Server 1.5.0.
39
+
40
+ ## 0.5.0 - 2026-11-27
41
+
42
+ - **Screenshots can label what is clickable.** `screenshot {marks: true}` draws a
43
+ numbered box around every button, entry, link, tab and menu item it can see in
44
+ the captured area (pycairo, already on the machine through GTK), and returns
45
+ the same numbers as `marks: [{id, ref, role, name, x, y, width, height}]` in
46
+ *screenshot* pixels — so a model can point at "box 4" instead of guessing
47
+ coordinates. `marks_limit` caps how many boxes are drawn (default 40).
48
+ - `screenshot {ref: "<ref>"}` crops straight to one element's rectangle, which
49
+ makes "look closely at this button" a single call.
50
+ - `click_ref {ref: "<ref>"}` clicks an element by its accessibility reference
51
+ (the `ref` that `ui_tree`, `ui_find` and the new `marks` hand out), and
52
+ `click {text: "Save"}` clicks the first element whose name or text matches —
53
+ no coordinates at all. Both run through the same lock and idle guards as
54
+ `click`, and both accept `allow_active_input`.
55
+ - An empty `marks` list is explained in the note (a locked session hides most of
56
+ the tree) instead of looking like a silent failure.
57
+ - Server 1.4.0.
58
+
3
59
  ## 0.4.0 - 2026-11-27
4
60
 
5
61
  - **The server now refreshes itself.** The bundle copied `server/*.py` into
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 个工具,分组见 [docs/DETAIL.md](docs/DETAIL.md)。模型调用方式:`mcp__linux__screenshot`、`mcp__linux__click`、`mcp__linux__ui_find` ……
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,10 +59,18 @@ 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
+
62
68
  ## 省钱与提速的两招
63
69
 
64
70
  - **`ui_tree` 先过滤再读**:`roles: ["push button", "entry"]` 只保留你要的节点类型,祖先会折叠成 `ref`/`role`/`name` 的路径;再加 `compact: true` 去掉 rect/states/text。实测同一屏 140 节点/10.2 KB → 20 节点/0.85 KB。
65
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)。
66
74
 
67
75
  ## 已知限制(重要,别踩坑)
68
76
 
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 |
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
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`, `move`, `drag`, `scroll`, `pointer_button` (hold/release) |
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-linux-computer-use",
3
- "version": "0.4.0",
3
+ "version": "0.6.2",
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
@@ -404,6 +404,75 @@ class A11y:
404
404
  continue
405
405
  return matches
406
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
+
407
476
  def describe_object(self, acc, name: str | None = None, role_name: str | None = None) -> dict:
408
477
  try:
409
478
  name = name if name is not None else (acc.get_name() or "")
@@ -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
 
@@ -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
- proc = subprocess.run(
177
- [binary, "lookup", "service", SERVICE, "account", _account()],
178
- text=True,
179
- capture_output=True,
180
- timeout=20,
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
- return fetch_password() is not None
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 = has_password() if policy_name == "keyring" else None
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
 
@@ -47,7 +47,7 @@ import cu_sys # noqa: E402
47
47
  import cu_unlock # noqa: E402
48
48
 
49
49
  SERVER_NAME = "linux-desktop-mcp"
50
- SERVER_VERSION = "1.3.0"
50
+ SERVER_VERSION = "1.5.1"
51
51
  PROTOCOL_VERSION = "2025-06-18"
52
52
  SUPPORTED_PROTOCOLS = {"2024-11-05", "2025-03-26", "2025-06-18"}
53
53
  LOG_PATH = os.path.join(cu_display.CACHE_DIR, "server.log")
@@ -109,6 +109,16 @@ def controller(reload_layout: bool = False) -> cu_input.InputController:
109
109
  return INPUT
110
110
 
111
111
 
112
+ # Injected events reset Mutter's idle timer, so a sequence would trip the very
113
+ # guard its own first step triggered. Anything inside this window is our echo.
114
+ SELF_ECHO_S = 2.5
115
+ _LAST_INJECT = {"at": 0.0}
116
+
117
+
118
+ def _stamp_injection() -> None:
119
+ _LAST_INJECT["at"] = time.monotonic()
120
+
121
+
112
122
  def _guard_input(what: str, args: dict | None = None) -> None:
113
123
  """Refuse to inject input while the session is locked or the user is active.
114
124
 
@@ -140,11 +150,17 @@ def _guard_input(what: str, args: dict | None = None) -> None:
140
150
  )
141
151
 
142
152
  if os.environ.get("DSH_LINUX_CU_ALLOW_ACTIVE_INPUT") == "1":
153
+ _stamp_injection()
143
154
  return
144
155
  if args and args.get("allow_active_input"):
156
+ _stamp_injection()
145
157
  return
146
158
  idle = cu_sys.idle_ms()
147
159
  if idle is None or idle >= IDLE_GUARD_MS:
160
+ _stamp_injection()
161
+ return
162
+ if (time.monotonic() - _LAST_INJECT["at"]) < SELF_ECHO_S:
163
+ _stamp_injection()
148
164
  return
149
165
  raise ToolError(
150
166
  f"refusing to {what}: the user is at the keyboard (last input {idle / 1000:.1f}s ago), "
@@ -291,6 +307,46 @@ def capture_shot(
291
307
  # --------------------------------------------------------------------------- #
292
308
  # tool implementations
293
309
  # --------------------------------------------------------------------------- #
310
+ def _draw_marks(info: dict, limit: int) -> list[dict]:
311
+ """Collect clickable nodes, express them in screenshot pixels, and draw them."""
312
+ origin_x = float(info.get("origin_x", 0.0))
313
+ origin_y = float(info.get("origin_y", 0.0))
314
+ ratio = float(LAST_SHOT.get("ratio") or 1.0) or 1.0
315
+ try:
316
+ nodes = A11Y.actionable(limit=max(1, limit))
317
+ except cu_a11y.A11yError:
318
+ return []
319
+ marks: list[dict] = []
320
+ for node in nodes:
321
+ rect = node.get("rect")
322
+ if not rect:
323
+ continue
324
+ left = (rect["x"] - origin_x) / ratio
325
+ top = (rect["y"] - origin_y) / ratio
326
+ width = rect["width"] / ratio
327
+ height = rect["height"] / ratio
328
+ if left + width < 0 or top + height < 0:
329
+ continue
330
+ if left > info["width"] or top > info["height"]:
331
+ continue
332
+ if width < 6 or height < 6:
333
+ continue
334
+ marks.append({
335
+ "id": len(marks) + 1,
336
+ "ref": node["ref"],
337
+ "role": node["role"],
338
+ "name": node.get("name", ""),
339
+ "x": round(left),
340
+ "y": round(top),
341
+ "width": round(width),
342
+ "height": round(height),
343
+ "colour": len(marks),
344
+ })
345
+ if marks:
346
+ cu_display.annotate(info["path"], marks)
347
+ return [{key: value for key, value in mark.items() if key != "colour"} for mark in marks]
348
+
349
+
294
350
  def tool_screenshot(args: dict) -> dict:
295
351
  max_width = int(args.get("max_width", SHOT_MAX_WIDTH))
296
352
  region = _parse_region(args.get("region"))
@@ -298,6 +354,17 @@ def tool_screenshot(args: dict) -> dict:
298
354
  scale = float(scale) if scale else None
299
355
  if scale is not None and scale <= 0:
300
356
  raise ToolError("scale must be positive (1.0 = one screenshot pixel per logical pixel)")
357
+ ref = args.get("ref")
358
+ if ref:
359
+ if region is not None:
360
+ raise ToolError("pass either region or ref, not both")
361
+ node = A11Y.describe(str(ref))
362
+ rect = node.get("rect")
363
+ if not rect:
364
+ raise ToolError(f"element {ref} has no on-screen rectangle to crop to")
365
+ region = (rect["x"], rect["y"], rect["width"], rect["height"])
366
+ if scale is None:
367
+ scale = 1.0
301
368
  info = capture_shot(max_width, region=region, scale=scale)
302
369
  try:
303
370
  with open(info["path"], "rb") as handle:
@@ -315,6 +382,12 @@ def tool_screenshot(args: dict) -> dict:
315
382
  logical_width = (info.get("region") or {}).get("width") or info["logical_width"]
316
383
  info["coordinate_scale"] = round(logical_width / width, 6) if width else 1.0
317
384
  LAST_SHOT.update({"width": width, "height": height, "ratio": info["coordinate_scale"]})
385
+ marks: list[dict] = []
386
+ wanted_marks = bool(args.get("marks"))
387
+ if wanted_marks:
388
+ marks = _draw_marks(info, int(args.get("marks_limit", 40)))
389
+ with open(info["path"], "rb") as handle:
390
+ payload = handle.read()
318
391
  encoded = base64.b64encode(payload).decode("ascii")
319
392
  if info.get("region"):
320
393
  note = (
@@ -333,6 +406,36 @@ def tool_screenshot(args: dict) -> dict:
333
406
  f"To click at a pixel of this image pass space='screenshot'; "
334
407
  f"otherwise multiply by {info['coordinate_scale']}."
335
408
  )
409
+ if wanted_marks:
410
+ info["marks"] = marks
411
+ info["mark_count"] = len(marks)
412
+ if marks:
413
+ note += (
414
+ f" {len(marks)} numbered boxes mark clickable elements; click one with "
415
+ "click_ref({ref}) or by the coordinates listed in \"marks\" (screenshot space)."
416
+ )
417
+ else:
418
+ # Wayland apps often publish no screen rectangles, so nothing can be
419
+ # boxed; a list of refs is still useful because click_ref can act on them.
420
+ try:
421
+ clickable = [
422
+ {k: node[k] for k in ("ref", "role", "name", "actions") if k in node}
423
+ for node in A11Y.actionable(limit=max(1, min(int(args.get("marks_limit", 40)), 40)))
424
+ ]
425
+ except cu_a11y.A11yError:
426
+ clickable = []
427
+ info["clickable"] = clickable
428
+ if clickable:
429
+ note += (
430
+ f" No boxes were drawn because these windows publish no screen rectangles on"
431
+ f" Wayland, but {len(clickable)} clickable elements were found: pick a ref from"
432
+ " \"clickable\" and pass it to click_ref."
433
+ )
434
+ else:
435
+ note += (
436
+ " No clickable element was found in this area"
437
+ " (a locked session hides most of the tree), so no boxes were drawn."
438
+ )
336
439
  return {
337
440
  "content": [
338
441
  {"type": "image", "data": encoded, "mimeType": "image/png"},
@@ -412,6 +515,61 @@ def tool_ui_set_text(args: dict) -> dict:
412
515
 
413
516
  def tool_click(args: dict) -> dict:
414
517
  _guard_input("click", args)
518
+ text = args.get("text")
519
+ if text and args.get("x") is None and args.get("y") is None:
520
+ hits = A11Y.find(
521
+ query=str(text),
522
+ role=args.get("role"),
523
+ app=args.get("app"),
524
+ limit=5,
525
+ )
526
+ if not hits:
527
+ raise ToolError(
528
+ f"no element whose name or text matches {text!r}; "
529
+ "try ui_find to see what is there, or click by coordinates"
530
+ )
531
+ best = hits[0]
532
+ if not best.get("center") and not best.get("rect"):
533
+ # Wayland toolkits publish no screen rectangle, so the widget's own
534
+ # action is the only way in.
535
+ try:
536
+ done = A11Y.action(best["ref"], "click")
537
+ except cu_a11y.A11yError:
538
+ try:
539
+ done = A11Y.action(best["ref"], None)
540
+ except cu_a11y.A11yError as error:
541
+ raise ToolError(
542
+ f"{text!r} matched {best.get('role')} {best['ref']}, but it has no "
543
+ f"on-screen rectangle and no clickable action ({error})"
544
+ ) from error
545
+ return {
546
+ "clicked": {
547
+ "ref": best["ref"],
548
+ "role": best.get("role"),
549
+ "matched": best.get("name") or str(text)[:60],
550
+ "via": "accessibility-action",
551
+ "action": (done or {}).get("action"),
552
+ }
553
+ }
554
+ if not best.get("center"):
555
+ raise ToolError(
556
+ f"{text!r} matched {best.get('role')} {best['ref']}, which has neither a "
557
+ "clickable action nor a usable rectangle"
558
+ )
559
+ button = _button_name(args.get("button", 1))
560
+ count = max(1, min(int(args.get("count", 1)), 3))
561
+ controller().click(best["center"][0], best["center"][1], button=button, count=count)
562
+ return {
563
+ "clicked": {
564
+ "x": best["center"][0],
565
+ "y": best["center"][1],
566
+ "button": button,
567
+ "count": count,
568
+ "matched": best.get("name") or best.get("text", "")[:60],
569
+ "role": best.get("role"),
570
+ "ref": best.get("ref"),
571
+ }
572
+ }
415
573
  x, y = _point(args)
416
574
  x, y = _to_logical(x, y, str(args.get("space", "logical")))
417
575
  button = _button_name(args.get("button", 1))
@@ -420,6 +578,67 @@ def tool_click(args: dict) -> dict:
420
578
  return {"clicked": {"x": round(x), "y": round(y), "button": button, "count": count}}
421
579
 
422
580
 
581
+ def tool_click_ref(args: dict) -> dict:
582
+ """Click an accessibility node.
583
+
584
+ Wayland apps rarely publish global screen rectangles, so a pointer click is not
585
+ always possible: try the widget's own click action first and fall back to the
586
+ pointer when the node does have a rectangle.
587
+ """
588
+ _guard_input("click", args)
589
+ ref = str(_require(args, "ref"))
590
+ node = A11Y.describe(ref)
591
+ center = node.get("center")
592
+ rect = node.get("rect")
593
+ if not center and rect:
594
+ center = [rect["x"] + rect["width"] // 2, rect["y"] + rect["height"] // 2]
595
+ button = _button_name(args.get("button", 1))
596
+ count = max(1, min(int(args.get("count", 1)), 3))
597
+ prefer = args.get("via", "auto")
598
+ failures: list[str] = []
599
+
600
+ if prefer in ("auto", "action"):
601
+ try:
602
+ done = A11Y.action(ref, "click")
603
+ except cu_a11y.A11yError:
604
+ try:
605
+ done = A11Y.action(ref, None)
606
+ except cu_a11y.A11yError as error:
607
+ done = None
608
+ failures.append(str(error))
609
+ if done is not None:
610
+ return {
611
+ "clicked": {
612
+ "ref": ref,
613
+ "role": node.get("role"),
614
+ "name": node.get("name", ""),
615
+ "via": "accessibility-action",
616
+ "action": done.get("action"),
617
+ "button": button,
618
+ "count": count,
619
+ }
620
+ }
621
+
622
+ if not center:
623
+ detail = f"element {ref} has no on-screen rectangle"
624
+ if failures:
625
+ detail = f"{detail} and no clickable action ({'; '.join(failures)})"
626
+ raise ToolError(f"{detail}, so it cannot be clicked")
627
+ controller().click(center[0], center[1], button=button, count=count)
628
+ return {
629
+ "clicked": {
630
+ "x": round(center[0]),
631
+ "y": round(center[1]),
632
+ "button": button,
633
+ "count": count,
634
+ "ref": ref,
635
+ "role": node.get("role"),
636
+ "name": node.get("name", ""),
637
+ "via": "pointer",
638
+ }
639
+ }
640
+
641
+
423
642
  def tool_move(args: dict) -> dict:
424
643
  _guard_input("move the pointer", args)
425
644
  x, y = _point(args)
@@ -914,6 +1133,14 @@ def tool_display_info(args: dict) -> dict:
914
1133
  return info
915
1134
 
916
1135
 
1136
+ def _unlock_status() -> dict:
1137
+ """Never let a locked keyring take the whole status call down."""
1138
+ try:
1139
+ return cu_unlock.status()
1140
+ except Exception as error: # noqa: BLE001 - diagnostics must not raise
1141
+ return {"unlock_policy": cu_unlock.policy(), "password_stored": None, "error": str(error)}
1142
+
1143
+
917
1144
  def tool_desktop_status(args: dict) -> dict:
918
1145
  status: dict = {"server": {"name": SERVER_NAME, "version": SERVER_VERSION, "log": LOG_PATH}}
919
1146
  status["session"] = {
@@ -922,7 +1149,7 @@ def tool_desktop_status(args: dict) -> dict:
922
1149
  "locked": cu_sys.screen_locked(),
923
1150
  "idle_ms": cu_sys.idle_ms(),
924
1151
  "input_guard_ms": IDLE_GUARD_MS,
925
- "unlock": cu_unlock.status(),
1152
+ "unlock": _unlock_status(),
926
1153
  }
927
1154
  try:
928
1155
  current = layout()
@@ -1009,6 +1236,7 @@ ALLOW_ACTIVE_PROP = {
1009
1236
  # Tools that inject input all accept the same escape hatch; adding it here keeps
1010
1237
  # the schema in one place instead of ten copies.
1011
1238
  _INJECTING_TOOLS = {
1239
+ "click_ref",
1012
1240
  "click",
1013
1241
  "move",
1014
1242
  "drag",
@@ -1037,6 +1265,85 @@ def tool_unlock_screen(args: dict) -> dict:
1037
1265
  return result
1038
1266
 
1039
1267
 
1268
+ SEQUENCE_MAX_STEPS = int(os.environ.get("DSH_LINUX_CU_SEQUENCE_MAX_STEPS", "25"))
1269
+ SEQUENCE_TEXT_LIMIT = 1200
1270
+
1271
+
1272
+ def _sequence_step_report(position: int, op: str, ok: bool, elapsed_ms: float, error: str | None = None) -> dict:
1273
+ entry = {"step": position, "op": op, "ok": ok, "ms": int(elapsed_ms)}
1274
+ if error:
1275
+ entry["error"] = error
1276
+ return entry
1277
+
1278
+
1279
+ def tool_sequence(args: dict) -> dict:
1280
+ steps = args.get("steps")
1281
+ if not isinstance(steps, list) or not steps:
1282
+ raise ToolError('steps must be a non-empty list of {"op": "...", "args": {...}} objects')
1283
+ if len(steps) > SEQUENCE_MAX_STEPS:
1284
+ raise ToolError(f"too many steps ({len(steps)}); the limit is {SEQUENCE_MAX_STEPS} per call")
1285
+ stop_on_error = bool(args.get("stop_on_error", True))
1286
+ inject_default = bool(args.get("allow_active_input", False))
1287
+ index = tool_index()
1288
+ report: list[dict] = []
1289
+ last_content: list[dict] | None = None
1290
+ stopped_at: int | None = None
1291
+ started = time.monotonic()
1292
+ for position, step in enumerate(steps, start=1):
1293
+ if not isinstance(step, dict):
1294
+ raise ToolError(f'step {position} must be an object like {{"op": "click", "args": {{...}}}}')
1295
+ op = step.get("op")
1296
+ if not isinstance(op, str) or not op.strip():
1297
+ raise ToolError(f'step {position} needs an "op" name')
1298
+ op = op.strip()
1299
+ if op == "sequence":
1300
+ raise ToolError("a sequence cannot contain another sequence")
1301
+ step_args = step.get("args") or {}
1302
+ if not isinstance(step_args, dict):
1303
+ raise ToolError(f"step {position} args must be an object")
1304
+ step_args = dict(step_args)
1305
+ if op not in index:
1306
+ report.append(_sequence_step_report(position, op, False, 0.0, f"unknown tool; available: {sorted(index)}"))
1307
+ if stop_on_error:
1308
+ stopped_at = position
1309
+ break
1310
+ continue
1311
+ if inject_default and op in _INJECTING_TOOLS:
1312
+ step_args.setdefault("allow_active_input", True)
1313
+ began = time.monotonic()
1314
+ payload = call_tool(op, step_args)
1315
+ took = (time.monotonic() - began) * 1000
1316
+ content = payload.get("content") or []
1317
+ if payload.get("isError"):
1318
+ message = " ".join(
1319
+ str(block.get("text", "")) for block in content if isinstance(block, dict)
1320
+ ).strip()
1321
+ report.append(_sequence_step_report(position, op, False, took, message or "failed"))
1322
+ if stop_on_error:
1323
+ stopped_at = position
1324
+ break
1325
+ continue
1326
+ report.append(_sequence_step_report(position, op, True, took))
1327
+ last_content = content
1328
+ elapsed = int((time.monotonic() - started) * 1000)
1329
+ ok = stopped_at is None and all(entry["ok"] for entry in report)
1330
+ summary = {
1331
+ "ok": ok,
1332
+ "steps_total": len(steps),
1333
+ "steps_run": len(report),
1334
+ "stopped_at": stopped_at,
1335
+ "elapsed_ms": elapsed,
1336
+ "steps": report,
1337
+ }
1338
+ boxes = [block for block in (last_content or []) if isinstance(block, dict)]
1339
+ text_tail = " ".join(str(block.get("text", "")) for block in boxes if block.get("type") == "text").strip()
1340
+ if text_tail:
1341
+ summary["last_text"] = text_tail[:SEQUENCE_TEXT_LIMIT]
1342
+ content_out: list[dict] = [{"type": "text", "text": json.dumps(summary, ensure_ascii=False, default=str)}]
1343
+ content_out.extend(block for block in boxes if block.get("type") == "image")
1344
+ return {"content": content_out, "isError": not ok}
1345
+
1346
+
1040
1347
  TOOLS: list[dict] = [
1041
1348
  {
1042
1349
  "name": "screenshot",
@@ -1076,6 +1383,29 @@ TOOLS: list[dict] = [
1076
1383
  "Takes precedence over max_width."
1077
1384
  ),
1078
1385
  },
1386
+ "ref": {
1387
+ "type": "string",
1388
+ "description": (
1389
+ "Crop to one accessibility node (a ref from ui_find/ui_tree) instead of a "
1390
+ "region. Great for reading a single widget without guessing its rectangle."
1391
+ ),
1392
+ },
1393
+ "marks": {
1394
+ "type": "boolean",
1395
+ "default": False,
1396
+ "description": (
1397
+ "Draw numbered boxes over the clickable elements in the capture and return "
1398
+ "them as \"marks\": [{id, ref, role, name, x, y, width, height}] in screenshot "
1399
+ "pixels. Click one with click_ref or by its coordinates, so no guessing."
1400
+ ),
1401
+ },
1402
+ "marks_limit": {
1403
+ "type": "integer",
1404
+ "default": 40,
1405
+ "minimum": 1,
1406
+ "maximum": 120,
1407
+ "description": "How many clickable elements to label at most.",
1408
+ },
1079
1409
  },
1080
1410
  },
1081
1411
  "handler": tool_screenshot,
@@ -1196,20 +1526,48 @@ TOOLS: list[dict] = [
1196
1526
  },
1197
1527
  {
1198
1528
  "name": "click",
1199
- "description": "Move the pointer to (x, y) and click. Supports button 1-3 and up to triple clicks.",
1529
+ "description": (
1530
+ "Click at (x, y), or pass text instead of coordinates to click the element whose name "
1531
+ "or text matches. Supports button 1-3 and up to triple clicks."
1532
+ ),
1200
1533
  "inputSchema": {
1201
1534
  "type": "object",
1202
1535
  "properties": {
1203
1536
  "x": {"type": "number"},
1204
1537
  "y": {"type": "number"},
1538
+ "text": {
1539
+ "type": "string",
1540
+ "description": (
1541
+ "Click the first element whose accessible name or text contains this string "
1542
+ "instead of using coordinates. Ignored when x and y are given."
1543
+ ),
1544
+ },
1545
+ "role": {"type": "string", "description": "With text: restrict to this role fragment."},
1546
+ "app": {"type": "string", "description": "With text: restrict to this application."},
1205
1547
  "button": {"type": "integer", "default": 1, "description": "1 left, 2 middle, 3 right."},
1206
1548
  "count": {"type": "integer", "default": 1, "minimum": 1, "maximum": 3},
1207
1549
  "space": SPACE_PROP,
1208
1550
  },
1209
- "required": ["x", "y"],
1210
1551
  },
1211
1552
  "handler": tool_click,
1212
1553
  },
1554
+ {
1555
+ "name": "click_ref",
1556
+ "description": (
1557
+ "Click the centre of one accessibility element by ref (from ui_find, ui_tree, or the "
1558
+ "marks list of an annotated screenshot). The reliable way to click: no coordinates."
1559
+ ),
1560
+ "inputSchema": {
1561
+ "type": "object",
1562
+ "properties": {
1563
+ "ref": {"type": "string", "description": "Element ref, e.g. \"e42\"."},
1564
+ "button": {"type": "integer", "default": 1, "description": "1 left, 2 middle, 3 right."},
1565
+ "count": {"type": "integer", "default": 1, "minimum": 1, "maximum": 3},
1566
+ },
1567
+ "required": ["ref"],
1568
+ },
1569
+ "handler": tool_click_ref,
1570
+ },
1213
1571
  {
1214
1572
  "name": "move",
1215
1573
  "description": "Move the pointer without clicking (useful to hover for menus and tooltips).",
@@ -1469,6 +1827,53 @@ TOOLS: list[dict] = [
1469
1827
  },
1470
1828
  "handler": tool_desktop_status,
1471
1829
  },
1830
+ {
1831
+ "name": "sequence",
1832
+ "description": (
1833
+ "Run several tools in one call and get a compact per-step report plus the last step's "
1834
+ "output. Use it for a fixed multi-step flow (raise a window, click, type, screenshot): it "
1835
+ "saves one model round trip per step, and images from the final step are passed through. "
1836
+ "Steps run in order and a failing step stops the run unless stop_on_error is false."
1837
+ ),
1838
+ "inputSchema": {
1839
+ "type": "object",
1840
+ "properties": {
1841
+ "steps": {
1842
+ "type": "array",
1843
+ "description": (
1844
+ 'Ordered steps, e.g. [{"op": "click", "args": {"x": 40, "y": 30}}, '
1845
+ '{"op": "type_text", "args": {"text": "hello"}}]'
1846
+ ),
1847
+ "items": {
1848
+ "type": "object",
1849
+ "properties": {
1850
+ "op": {"type": "string", "description": "Tool name, e.g. click, type_text, screenshot"},
1851
+ "args": {"type": "object", "description": "Arguments for that tool"},
1852
+ },
1853
+ "required": ["op"],
1854
+ },
1855
+ },
1856
+ "stop_on_error": {
1857
+ "type": "boolean",
1858
+ "default": True,
1859
+ "description": (
1860
+ "Stop at the first failing step (default). Set false to keep going and report "
1861
+ "every failure, which is useful when a step may legitimately fail."
1862
+ ),
1863
+ },
1864
+ "allow_active_input": {
1865
+ "type": "boolean",
1866
+ "default": False,
1867
+ "description": (
1868
+ "Apply allow_active_input=true to every injecting step of the run, instead of "
1869
+ "repeating it in each step's args."
1870
+ ),
1871
+ },
1872
+ },
1873
+ "required": ["steps"],
1874
+ },
1875
+ "handler": tool_sequence,
1876
+ },
1472
1877
  ]
1473
1878
 
1474
1879
  # Every input-injecting tool advertises the idle-guard escape hatch.