dsh-plugin-linux-computer-use 0.1.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +68 -0
- package/README.md +13 -3
- package/docs/DETAIL.md +19 -4
- package/index.js +6 -0
- package/package.json +1 -1
- package/server/cu_a11y.py +48 -21
- package/server/cu_display.py +33 -0
- package/server/cu_sys.py +34 -0
- package/server/linux_desktop_mcp.py +797 -55
|
@@ -32,6 +32,8 @@ from __future__ import annotations
|
|
|
32
32
|
import base64
|
|
33
33
|
import json
|
|
34
34
|
import os
|
|
35
|
+
import shutil
|
|
36
|
+
import subprocess
|
|
35
37
|
import sys
|
|
36
38
|
import time
|
|
37
39
|
import traceback
|
|
@@ -45,16 +47,17 @@ import cu_sys # noqa: E402
|
|
|
45
47
|
import cu_unlock # noqa: E402
|
|
46
48
|
|
|
47
49
|
SERVER_NAME = "linux-desktop-mcp"
|
|
48
|
-
SERVER_VERSION = "1.
|
|
50
|
+
SERVER_VERSION = "1.3.0"
|
|
49
51
|
PROTOCOL_VERSION = "2025-06-18"
|
|
50
52
|
SUPPORTED_PROTOCOLS = {"2024-11-05", "2025-03-26", "2025-06-18"}
|
|
51
53
|
LOG_PATH = os.path.join(cu_display.CACHE_DIR, "server.log")
|
|
52
54
|
MAX_IMAGE_BYTES = 3_500_000
|
|
53
55
|
SHOT_MAX_WIDTH = 1600
|
|
56
|
+
IDLE_GUARD_MS = int(os.environ.get("DSH_LINUX_CU_IDLE_GUARD_MS", "60000"))
|
|
54
57
|
|
|
55
58
|
A11Y = cu_a11y.A11y()
|
|
56
59
|
INPUT: cu_input.InputController | None = None
|
|
57
|
-
LAST_SHOT: dict = {"path": None, "width": 0, "height": 0, "logical": None, "at": 0.0}
|
|
60
|
+
LAST_SHOT: dict = {"path": None, "width": 0, "height": 0, "logical": None, "origin": (0, 0), "ratio": 1.0, "at": 0.0}
|
|
58
61
|
|
|
59
62
|
|
|
60
63
|
BUTTON_NAMES = {1: "left", 2: "middle", 3: "right"}
|
|
@@ -106,29 +109,50 @@ def controller(reload_layout: bool = False) -> cu_input.InputController:
|
|
|
106
109
|
return INPUT
|
|
107
110
|
|
|
108
111
|
|
|
109
|
-
def _guard_input(what: str) -> None:
|
|
110
|
-
"""Refuse to inject input while the session is locked.
|
|
112
|
+
def _guard_input(what: str, args: dict | None = None) -> None:
|
|
113
|
+
"""Refuse to inject input while the session is locked or the user is active.
|
|
111
114
|
|
|
112
115
|
A locked GNOME session keeps the password field focused, so a stray click
|
|
113
116
|
or keystroke lands inside it. Screenshots stay allowed; only input is
|
|
114
117
|
blocked. ``DSH_LINUX_CU_ALLOW_LOCKED_INPUT=1`` is the escape hatch for
|
|
115
118
|
someone who really knows what they are doing.
|
|
119
|
+
|
|
120
|
+
The second guard covers a subtler failure: driving the pointer while the
|
|
121
|
+
user is typing fights them for the keyboard and moves their cursor mid
|
|
122
|
+
gesture. When the compositor reports recent input, injection is refused
|
|
123
|
+
unless the caller says the user asked for it right now
|
|
124
|
+
(``allow_active_input=true``) or the machine-wide escape hatch
|
|
125
|
+
``DSH_LINUX_CU_ALLOW_ACTIVE_INPUT=1`` is set.
|
|
116
126
|
"""
|
|
117
|
-
if os.environ.get("DSH_LINUX_CU_ALLOW_LOCKED_INPUT")
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
127
|
+
if os.environ.get("DSH_LINUX_CU_ALLOW_LOCKED_INPUT") != "1":
|
|
128
|
+
if cu_sys.screen_locked() is True:
|
|
129
|
+
if cu_unlock.unlock_enabled():
|
|
130
|
+
hint = "unlock_screen is available because the user turned AI unlocking on."
|
|
131
|
+
else:
|
|
132
|
+
hint = (
|
|
133
|
+
"Unlock the desktop and retry; the user can also switch AI unlocking "
|
|
134
|
+
"on (unlock policy) to let this be handled here."
|
|
135
|
+
)
|
|
136
|
+
raise ToolError(
|
|
137
|
+
f"refusing to {what}: the session is locked. The lock screen's focused "
|
|
138
|
+
f"widget is the password field, so injected input would type into it. "
|
|
139
|
+
f"{hint} mcp__linux__screenshot still works."
|
|
126
140
|
)
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
141
|
+
|
|
142
|
+
if os.environ.get("DSH_LINUX_CU_ALLOW_ACTIVE_INPUT") == "1":
|
|
143
|
+
return
|
|
144
|
+
if args and args.get("allow_active_input"):
|
|
145
|
+
return
|
|
146
|
+
idle = cu_sys.idle_ms()
|
|
147
|
+
if idle is None or idle >= IDLE_GUARD_MS:
|
|
148
|
+
return
|
|
149
|
+
raise ToolError(
|
|
150
|
+
f"refusing to {what}: the user is at the keyboard (last input {idle / 1000:.1f}s ago), "
|
|
151
|
+
f"so synthetic input would fight them. Wait until they have been idle for "
|
|
152
|
+
f"{IDLE_GUARD_MS // 1000}s, or pass allow_active_input=true when they just asked you "
|
|
153
|
+
f"to drive the desktop. Screenshots and reads stay available."
|
|
154
|
+
)
|
|
155
|
+
|
|
132
156
|
|
|
133
157
|
|
|
134
158
|
def _to_logical(x: float, y: float, space: str) -> tuple[float, float]:
|
|
@@ -137,18 +161,50 @@ def _to_logical(x: float, y: float, space: str) -> tuple[float, float]:
|
|
|
137
161
|
logical = LAST_SHOT.get("logical") or None
|
|
138
162
|
if not shot_w or not logical:
|
|
139
163
|
raise ToolError("no screenshot yet: take one first, or pass space='logical'")
|
|
140
|
-
ratio = (logical[0] / shot_w) if shot_w else 1.0
|
|
141
|
-
|
|
164
|
+
ratio = LAST_SHOT.get("ratio") or ((logical[0] / shot_w) if shot_w else 1.0)
|
|
165
|
+
origin = LAST_SHOT.get("origin") or (0, 0)
|
|
166
|
+
return (origin[0] + x * ratio, origin[1] + y * ratio)
|
|
142
167
|
return (x, y)
|
|
143
168
|
|
|
144
169
|
|
|
145
|
-
def
|
|
170
|
+
def _parse_region(value) -> tuple[float, float, float, float] | None:
|
|
171
|
+
"""Accept ``{x, y, width, height}`` (logical pixels) or ``[x, y, w, h]``."""
|
|
172
|
+
if value is None:
|
|
173
|
+
return None
|
|
174
|
+
if isinstance(value, dict):
|
|
175
|
+
try:
|
|
176
|
+
x = float(value.get("x", 0))
|
|
177
|
+
y = float(value.get("y", 0))
|
|
178
|
+
w = float(value["width"] if "width" in value else value["w"])
|
|
179
|
+
h = float(value["height"] if "height" in value else value["h"])
|
|
180
|
+
except (KeyError, TypeError, ValueError) as error:
|
|
181
|
+
raise ToolError("region must be {x, y, width, height} in logical pixels") from error
|
|
182
|
+
elif isinstance(value, (list, tuple)) and len(value) == 4:
|
|
183
|
+
x, y, w, h = (float(v) for v in value)
|
|
184
|
+
else:
|
|
185
|
+
raise ToolError("region must be {x, y, width, height} in logical pixels")
|
|
186
|
+
if w <= 0 or h <= 0:
|
|
187
|
+
raise ToolError("region width and height must be positive")
|
|
188
|
+
return (x, y, w, h)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def capture_shot(
|
|
192
|
+
max_width: int = SHOT_MAX_WIDTH,
|
|
193
|
+
region: tuple[float, float, float, float] | None = None,
|
|
194
|
+
scale: float | None = None,
|
|
195
|
+
) -> dict:
|
|
146
196
|
"""Grab the desktop, preferring the screenshot portal over a pipewire stream.
|
|
147
197
|
|
|
148
198
|
The portal Screenshot interface is a single round trip (~0.5s) and needs no
|
|
149
199
|
long-lived session, so it is the default. The ScreenCast + GStreamer path
|
|
150
200
|
stays as a fallback because it is the only one that can stream frames when
|
|
151
201
|
capture permission exists but the screenshot interface is missing.
|
|
202
|
+
|
|
203
|
+
``region`` (logical pixels) crops before downscaling, which is what makes
|
|
204
|
+
small UI text readable: a 900 px wide slice of the desktop stays sharp at
|
|
205
|
+
1400 px of output, while the same output from a 4480 px desktop is mush.
|
|
206
|
+
``scale`` sets output pixels per logical pixel (1.0 = native size) and takes
|
|
207
|
+
precedence over ``max_width``.
|
|
152
208
|
"""
|
|
153
209
|
name = f"shot-{time.strftime('%Y%m%d-%H%M%S')}-{int(time.time() * 1000) % 1000:03d}.png"
|
|
154
210
|
path = os.path.join(cu_display.SHOT_DIR, name)
|
|
@@ -177,25 +233,59 @@ def capture_shot(max_width: int = SHOT_MAX_WIDTH) -> dict:
|
|
|
177
233
|
"run linux_mcp_doctor to see the current state."
|
|
178
234
|
) from error
|
|
179
235
|
|
|
180
|
-
width, height = cu_display.downscale(path, max_width)
|
|
181
236
|
current = layout()
|
|
237
|
+
raw_width, raw_height = cu_display.png_size(path)
|
|
238
|
+
# The portal hands back physical pixels; logical desktop size can be smaller
|
|
239
|
+
# on HiDPI, and region/scale are both expressed in logical pixels.
|
|
240
|
+
physical = (raw_width / current.width) if current.width and raw_width else 1.0
|
|
241
|
+
origin = (0.0, 0.0)
|
|
242
|
+
region_used = None
|
|
243
|
+
|
|
244
|
+
if region is not None:
|
|
245
|
+
x, y, w, h = region
|
|
246
|
+
box = (
|
|
247
|
+
round(x * physical),
|
|
248
|
+
round(y * physical),
|
|
249
|
+
max(1, round(w * physical)),
|
|
250
|
+
max(1, round(h * physical)),
|
|
251
|
+
)
|
|
252
|
+
target = round(w * scale) if scale else max_width
|
|
253
|
+
width, height = cu_display.crop_and_scale(path, box, max(1, int(target)))
|
|
254
|
+
origin = (x, y)
|
|
255
|
+
region_used = {"x": round(x), "y": round(y), "width": round(w), "height": round(h)}
|
|
256
|
+
ratio = (w / width) if width else 1.0
|
|
257
|
+
elif scale:
|
|
258
|
+
width, height = cu_display.crop_and_scale(
|
|
259
|
+
path, (0, 0, raw_width, raw_height), max(1, round(current.width * scale))
|
|
260
|
+
)
|
|
261
|
+
ratio = (current.width / width) if width else 1.0
|
|
262
|
+
else:
|
|
263
|
+
width, height = cu_display.downscale(path, max_width)
|
|
264
|
+
ratio = (current.width / width) if width else 1.0
|
|
265
|
+
|
|
182
266
|
LAST_SHOT.update({
|
|
183
267
|
"path": path,
|
|
184
268
|
"width": width,
|
|
185
269
|
"height": height,
|
|
186
270
|
"logical": (current.width, current.height),
|
|
271
|
+
"origin": origin,
|
|
272
|
+
"ratio": ratio,
|
|
187
273
|
"at": time.time(),
|
|
188
274
|
})
|
|
189
|
-
|
|
275
|
+
info = {
|
|
190
276
|
"path": path,
|
|
191
277
|
"width": width,
|
|
192
278
|
"height": height,
|
|
193
279
|
"logical_width": current.width,
|
|
194
280
|
"logical_height": current.height,
|
|
195
|
-
"coordinate_scale": round(
|
|
281
|
+
"coordinate_scale": round(ratio, 6),
|
|
196
282
|
"captured_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
|
197
283
|
"method": method,
|
|
198
284
|
}
|
|
285
|
+
if region_used:
|
|
286
|
+
info["region"] = region_used
|
|
287
|
+
info["origin_x"], info["origin_y"] = region_used["x"], region_used["y"]
|
|
288
|
+
return info
|
|
199
289
|
|
|
200
290
|
|
|
201
291
|
# --------------------------------------------------------------------------- #
|
|
@@ -203,7 +293,12 @@ def capture_shot(max_width: int = SHOT_MAX_WIDTH) -> dict:
|
|
|
203
293
|
# --------------------------------------------------------------------------- #
|
|
204
294
|
def tool_screenshot(args: dict) -> dict:
|
|
205
295
|
max_width = int(args.get("max_width", SHOT_MAX_WIDTH))
|
|
206
|
-
|
|
296
|
+
region = _parse_region(args.get("region"))
|
|
297
|
+
scale = args.get("scale")
|
|
298
|
+
scale = float(scale) if scale else None
|
|
299
|
+
if scale is not None and scale <= 0:
|
|
300
|
+
raise ToolError("scale must be positive (1.0 = one screenshot pixel per logical pixel)")
|
|
301
|
+
info = capture_shot(max_width, region=region, scale=scale)
|
|
207
302
|
try:
|
|
208
303
|
with open(info["path"], "rb") as handle:
|
|
209
304
|
payload = handle.read()
|
|
@@ -215,14 +310,29 @@ def tool_screenshot(args: dict) -> dict:
|
|
|
215
310
|
payload = handle.read()
|
|
216
311
|
width, height = cu_display.png_size(info["path"])
|
|
217
312
|
info["width"], info["height"] = width, height
|
|
218
|
-
|
|
313
|
+
# The ratio must follow the *visible* slice, not the whole desktop, so a
|
|
314
|
+
# cropped capture still maps screenshot pixels back to logical ones.
|
|
315
|
+
logical_width = (info.get("region") or {}).get("width") or info["logical_width"]
|
|
316
|
+
info["coordinate_scale"] = round(logical_width / width, 6) if width else 1.0
|
|
317
|
+
LAST_SHOT.update({"width": width, "height": height, "ratio": info["coordinate_scale"]})
|
|
219
318
|
encoded = base64.b64encode(payload).decode("ascii")
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
319
|
+
if info.get("region"):
|
|
320
|
+
note = (
|
|
321
|
+
f"screenshot {info['width']}x{info['height']} px saved at {info['path']}; it shows the "
|
|
322
|
+
f"logical region x={info['origin_x']} y={info['origin_y']} "
|
|
323
|
+
f"{info['region']['width']}x{info['region']['height']} of a "
|
|
324
|
+
f"{info['logical_width']}x{info['logical_height']} desktop. "
|
|
325
|
+
f"To click at a pixel of this image pass space='screenshot'; "
|
|
326
|
+
f"otherwise add ({info['origin_x']}, {info['origin_y']}) and multiply by "
|
|
327
|
+
f"{info['coordinate_scale']}."
|
|
328
|
+
)
|
|
329
|
+
else:
|
|
330
|
+
note = (
|
|
331
|
+
f"screenshot {info['width']}x{info['height']} px saved at {info['path']}; "
|
|
332
|
+
f"logical desktop is {info['logical_width']}x{info['logical_height']}. "
|
|
333
|
+
f"To click at a pixel of this image pass space='screenshot'; "
|
|
334
|
+
f"otherwise multiply by {info['coordinate_scale']}."
|
|
335
|
+
)
|
|
226
336
|
return {
|
|
227
337
|
"content": [
|
|
228
338
|
{"type": "image", "data": encoded, "mimeType": "image/png"},
|
|
@@ -240,7 +350,15 @@ def tool_ui_tree(args: dict) -> dict:
|
|
|
240
350
|
app = args.get("app")
|
|
241
351
|
depth = max(1, min(int(args.get("max_depth", 3)), 8))
|
|
242
352
|
nodes = max(10, min(int(args.get("max_nodes", 220)), 1200))
|
|
243
|
-
|
|
353
|
+
roles = args.get("roles")
|
|
354
|
+
if isinstance(roles, str):
|
|
355
|
+
roles = [roles]
|
|
356
|
+
if roles is not None and not isinstance(roles, list):
|
|
357
|
+
raise ToolError("roles must be a list of role name fragments, e.g. [\"push button\", \"entry\"]")
|
|
358
|
+
compact = bool(args.get("compact", False))
|
|
359
|
+
snapshot = A11Y.snapshot(app=app, max_depth=depth, max_nodes=nodes,
|
|
360
|
+
roles=[str(item) for item in roles] if roles else None,
|
|
361
|
+
compact=compact)
|
|
244
362
|
if snapshot["nodes_used"] <= 3 and snapshot["applications"]:
|
|
245
363
|
snapshot["hint"] = (
|
|
246
364
|
"the application exposes (almost) no accessibility nodes: Chromium, "
|
|
@@ -271,20 +389,20 @@ def tool_ui_text(args: dict) -> dict:
|
|
|
271
389
|
|
|
272
390
|
|
|
273
391
|
def tool_ui_action(args: dict) -> dict:
|
|
274
|
-
_guard_input("
|
|
392
|
+
_guard_input("act on an accessibility node", args)
|
|
275
393
|
ref = _require(args, "ref")
|
|
276
394
|
action = args.get("action")
|
|
277
395
|
return A11Y.action(ref, action)
|
|
278
396
|
|
|
279
397
|
|
|
280
398
|
def tool_ui_focus(args: dict) -> dict:
|
|
281
|
-
_guard_input("
|
|
399
|
+
_guard_input("move focus", args)
|
|
282
400
|
ref = _require(args, "ref")
|
|
283
401
|
return A11Y.focus(ref)
|
|
284
402
|
|
|
285
403
|
|
|
286
404
|
def tool_ui_set_text(args: dict) -> dict:
|
|
287
|
-
_guard_input("
|
|
405
|
+
_guard_input("set a widget value", args)
|
|
288
406
|
ref = _require(args, "ref")
|
|
289
407
|
text = args.get("text")
|
|
290
408
|
if not isinstance(text, str):
|
|
@@ -293,7 +411,7 @@ def tool_ui_set_text(args: dict) -> dict:
|
|
|
293
411
|
|
|
294
412
|
|
|
295
413
|
def tool_click(args: dict) -> dict:
|
|
296
|
-
_guard_input("click")
|
|
414
|
+
_guard_input("click", args)
|
|
297
415
|
x, y = _point(args)
|
|
298
416
|
x, y = _to_logical(x, y, str(args.get("space", "logical")))
|
|
299
417
|
button = _button_name(args.get("button", 1))
|
|
@@ -303,7 +421,7 @@ def tool_click(args: dict) -> dict:
|
|
|
303
421
|
|
|
304
422
|
|
|
305
423
|
def tool_move(args: dict) -> dict:
|
|
306
|
-
_guard_input("move the pointer")
|
|
424
|
+
_guard_input("move the pointer", args)
|
|
307
425
|
x, y = _point(args)
|
|
308
426
|
x, y = _to_logical(x, y, str(args.get("space", "logical")))
|
|
309
427
|
controller().move(x, y)
|
|
@@ -311,7 +429,7 @@ def tool_move(args: dict) -> dict:
|
|
|
311
429
|
|
|
312
430
|
|
|
313
431
|
def tool_drag(args: dict) -> dict:
|
|
314
|
-
_guard_input("drag")
|
|
432
|
+
_guard_input("drag", args)
|
|
315
433
|
start = (float(args.get("x1", 0)), float(args.get("y1", 0)))
|
|
316
434
|
end = (float(args.get("x2", 0)), float(args.get("y2", 0)))
|
|
317
435
|
space = str(args.get("space", "logical"))
|
|
@@ -323,7 +441,7 @@ def tool_drag(args: dict) -> dict:
|
|
|
323
441
|
|
|
324
442
|
|
|
325
443
|
def tool_scroll(args: dict) -> dict:
|
|
326
|
-
_guard_input("scroll")
|
|
444
|
+
_guard_input("scroll", args)
|
|
327
445
|
dx = int(args.get("dx", 0))
|
|
328
446
|
dy = int(args.get("dy", 0))
|
|
329
447
|
if not dx and not dy:
|
|
@@ -333,7 +451,7 @@ def tool_scroll(args: dict) -> dict:
|
|
|
333
451
|
|
|
334
452
|
|
|
335
453
|
def tool_pointer_button(args: dict) -> dict:
|
|
336
|
-
_guard_input("press a mouse button")
|
|
454
|
+
_guard_input("press a mouse button", args)
|
|
337
455
|
action = str(args.get("action", "press")).lower()
|
|
338
456
|
button = _button_name(args.get("button", 1))
|
|
339
457
|
if args.get("x") is not None and args.get("y") is not None:
|
|
@@ -349,14 +467,14 @@ def tool_pointer_button(args: dict) -> dict:
|
|
|
349
467
|
|
|
350
468
|
|
|
351
469
|
def tool_key(args: dict) -> dict:
|
|
352
|
-
_guard_input("press a key")
|
|
470
|
+
_guard_input("press a key", args)
|
|
353
471
|
combo = _require(args, "combo")
|
|
354
472
|
controller().key(str(combo))
|
|
355
473
|
return {"pressed": combo}
|
|
356
474
|
|
|
357
475
|
|
|
358
476
|
def tool_type_text(args: dict) -> dict:
|
|
359
|
-
_guard_input("type text")
|
|
477
|
+
_guard_input("type text", args)
|
|
360
478
|
text = _require(args, "text")
|
|
361
479
|
controller().type_text(str(text))
|
|
362
480
|
return {"typed": len(str(text))}
|
|
@@ -427,22 +545,219 @@ def tool_window_list(args: dict) -> dict:
|
|
|
427
545
|
node = A11Y.describe(app["ref"])
|
|
428
546
|
except cu_a11y.A11yError:
|
|
429
547
|
continue
|
|
430
|
-
|
|
431
|
-
if
|
|
548
|
+
frame = _first_frame_obj(A11Y.resolve(app["ref"]))
|
|
549
|
+
if frame is None:
|
|
432
550
|
windows.append({"app": app["name"], "title": "", "ref": app["ref"], "pid": app["pid"]})
|
|
433
551
|
continue
|
|
434
|
-
title
|
|
552
|
+
title = frame.get_name() or ""
|
|
435
553
|
windows.append({
|
|
436
554
|
"app": app["name"],
|
|
437
555
|
"title": title,
|
|
438
556
|
"ref": app["ref"],
|
|
439
557
|
"pid": app["pid"],
|
|
440
|
-
"active":
|
|
558
|
+
"active": _window_is_active(frame),
|
|
441
559
|
})
|
|
442
560
|
del node
|
|
443
561
|
return {"windows": windows, "count": len(windows)}
|
|
444
562
|
|
|
445
563
|
|
|
564
|
+
def tool_window_activate(args: dict) -> dict:
|
|
565
|
+
_guard_input("activate a window", args)
|
|
566
|
+
title = str(args.get("title") or "").strip()
|
|
567
|
+
app = str(args.get("app") or "").strip()
|
|
568
|
+
if not title and not app:
|
|
569
|
+
raise ToolError("window_activate needs either a title substring or an app name")
|
|
570
|
+
rows = _frame_rows()
|
|
571
|
+
match = _match_window(rows, title, app)
|
|
572
|
+
if match is None:
|
|
573
|
+
known = sorted({f"{row['app']}: {row['title']}" for row in rows if row["title"]})[:8]
|
|
574
|
+
raise ToolError(
|
|
575
|
+
"no window matches "
|
|
576
|
+
+ (f"title {title!r} " if title else "")
|
|
577
|
+
+ (f"app {app!r}" if app else "")
|
|
578
|
+
+ ("; known windows: " + "; ".join(known) if known else "")
|
|
579
|
+
)
|
|
580
|
+
window = {"app": match["app"], "title": match["title"]}
|
|
581
|
+
if match["active"]:
|
|
582
|
+
return {"activated": True, "method": "already-active", "window": window, "tried": []}
|
|
583
|
+
|
|
584
|
+
tried: list[dict] = []
|
|
585
|
+
needle = title or match["title"]
|
|
586
|
+
|
|
587
|
+
# XWayland windows answer to xdotool; native Wayland ones never show up here.
|
|
588
|
+
if needle:
|
|
589
|
+
if not os.environ.get("DISPLAY"):
|
|
590
|
+
tried.append({"method": "xdotool", "result": "no DISPLAY in this session"})
|
|
591
|
+
else:
|
|
592
|
+
code, out = _xdotool("search", "--name", needle)
|
|
593
|
+
ids = [line for line in out.splitlines() if line.strip().isdigit()] if code == 0 else []
|
|
594
|
+
if not ids:
|
|
595
|
+
tried.append({"method": "xdotool", "result": "no X11 match (native Wayland window)"})
|
|
596
|
+
for wid in ids[:4]:
|
|
597
|
+
_xdotool("windowactivate", wid)
|
|
598
|
+
if _wait_active(match["title"], 1.2):
|
|
599
|
+
return {"activated": True, "method": "xdotool", "window": window, "tried": tried}
|
|
600
|
+
else:
|
|
601
|
+
if ids:
|
|
602
|
+
tried.append({"method": "xdotool", "result": "activate did not raise it"})
|
|
603
|
+
|
|
604
|
+
try:
|
|
605
|
+
iface = match["acc"].get_action_iface()
|
|
606
|
+
if iface is not None and iface.get_n_actions() > 0:
|
|
607
|
+
iface.do_action(0)
|
|
608
|
+
if _wait_active(match["title"], 1.0):
|
|
609
|
+
return {"activated": True, "method": "atspi", "window": window, "tried": tried}
|
|
610
|
+
tried.append({"method": "atspi", "result": "default action did not raise it"})
|
|
611
|
+
else:
|
|
612
|
+
tried.append({"method": "atspi", "result": "frame exposes no actions"})
|
|
613
|
+
except Exception as error: # noqa: BLE001
|
|
614
|
+
tried.append({"method": "atspi", "result": str(error)})
|
|
615
|
+
|
|
616
|
+
cycles = max(1, min(int(args.get("max_cycles", WINDOW_ACTIVATE_MAX_CYCLES)), 30))
|
|
617
|
+
# GNOME binds Alt+Tab to switching windows *inside* the current application
|
|
618
|
+
# and Super+Tab to switching applications, so both are worth trying. A
|
|
619
|
+
# combination that changes nothing on its first press is not bound here (or
|
|
620
|
+
# the application has a single window), so move on instead of cycling.
|
|
621
|
+
for combo in ("alt+Tab", "super+Tab"):
|
|
622
|
+
try:
|
|
623
|
+
before = _active_titles()
|
|
624
|
+
for index in range(cycles):
|
|
625
|
+
controller().key(combo)
|
|
626
|
+
time.sleep(0.35)
|
|
627
|
+
if _is_active(match["title"]):
|
|
628
|
+
return {"activated": True, "method": combo.lower().replace("+", "-"), "window": window, "tried": tried}
|
|
629
|
+
now = _active_titles()
|
|
630
|
+
if now != before:
|
|
631
|
+
before = now
|
|
632
|
+
continue
|
|
633
|
+
if index == 0:
|
|
634
|
+
tried.append({"method": combo, "result": "no effect here (not bound, or the application has a single window)"})
|
|
635
|
+
break
|
|
636
|
+
else:
|
|
637
|
+
tried.append({"method": combo, "result": f"{cycles} cycles without reaching it"})
|
|
638
|
+
except cu_input.InputError as error:
|
|
639
|
+
tried.append({"method": combo, "result": str(error)})
|
|
640
|
+
break
|
|
641
|
+
except Exception as error: # noqa: BLE001
|
|
642
|
+
tried.append({"method": combo, "result": str(error)})
|
|
643
|
+
|
|
644
|
+
return {
|
|
645
|
+
"activated": False,
|
|
646
|
+
"method": "none",
|
|
647
|
+
"window": window,
|
|
648
|
+
"tried": tried,
|
|
649
|
+
"hint": (
|
|
650
|
+
"none of the three strategies raised it: X11 sees only XWayland surfaces, the "
|
|
651
|
+
"accessibility default action is a no-op for most toolkits, and the keyboard "
|
|
652
|
+
"fallback needs uinput plus a matching keybinding (Alt+Tab switches windows of "
|
|
653
|
+
"the current application, Super+Tab switches applications). Raise it by hand, or "
|
|
654
|
+
"pass a more distinctive title"
|
|
655
|
+
),
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
WAIT_CONDITIONS = ("window", "window_active", "ui", "idle_at_least")
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _check_condition(condition: dict) -> tuple[bool, dict]:
|
|
663
|
+
for key in WAIT_CONDITIONS:
|
|
664
|
+
if key not in condition:
|
|
665
|
+
continue
|
|
666
|
+
if key == "window":
|
|
667
|
+
spec = condition["window"]
|
|
668
|
+
if isinstance(spec, str):
|
|
669
|
+
spec = {"title": spec}
|
|
670
|
+
if not isinstance(spec, dict):
|
|
671
|
+
raise ToolError("condition.window must be a title string or an object")
|
|
672
|
+
want = bool(spec.get("exists", True))
|
|
673
|
+
rows = _frame_rows()
|
|
674
|
+
hit = _match_window(rows, str(spec.get("title") or ""), str(spec.get("app") or ""))
|
|
675
|
+
return (hit is not None) == want, {"windows": len(rows), "found": hit is not None}
|
|
676
|
+
if key == "window_active":
|
|
677
|
+
spec = condition["window_active"]
|
|
678
|
+
needle = str(spec.get("title") if isinstance(spec, dict) else spec or "").lower()
|
|
679
|
+
if not needle:
|
|
680
|
+
raise ToolError("condition.window_active needs a title substring")
|
|
681
|
+
active = [row["title"] for row in _frame_rows() if row["active"]]
|
|
682
|
+
hit = any(needle in (title or "").lower() for title in active)
|
|
683
|
+
return hit, {"active": active[:6]}
|
|
684
|
+
if key == "ui":
|
|
685
|
+
spec = condition["ui"]
|
|
686
|
+
if not isinstance(spec, dict):
|
|
687
|
+
raise ToolError("condition.ui must be an object such as {app, name, role}")
|
|
688
|
+
hits = A11Y.find(
|
|
689
|
+
query=spec.get("name"),
|
|
690
|
+
role=spec.get("role"),
|
|
691
|
+
app=spec.get("app"),
|
|
692
|
+
limit=3,
|
|
693
|
+
timeout_s=2.0,
|
|
694
|
+
)
|
|
695
|
+
return len(hits) > 0, {"matches": len(hits)}
|
|
696
|
+
idle = cu_sys.idle_ms()
|
|
697
|
+
want_idle = int(condition["idle_at_least"])
|
|
698
|
+
return (idle is not None and idle >= want_idle), {"idle_ms": idle}
|
|
699
|
+
raise ToolError(
|
|
700
|
+
"condition must contain one of: " + ", ".join(WAIT_CONDITIONS) + " (got " + repr(sorted(condition)) + ")"
|
|
701
|
+
)
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def tool_wait_until(args: dict) -> dict:
|
|
705
|
+
condition = args.get("condition")
|
|
706
|
+
if not isinstance(condition, dict) or not condition:
|
|
707
|
+
raise ToolError(
|
|
708
|
+
"wait_until needs a condition object, for example "
|
|
709
|
+
'{"window": {"title": "Build finished"}} or {"window_active": "Chrome"}'
|
|
710
|
+
)
|
|
711
|
+
timeout_ms = max(100, min(int(args.get("timeout_ms", 15000)), 120000))
|
|
712
|
+
interval_ms = max(80, min(int(args.get("interval_ms", 300)), 5000))
|
|
713
|
+
started = time.monotonic()
|
|
714
|
+
deadline = started + timeout_ms / 1000.0
|
|
715
|
+
polls = 0
|
|
716
|
+
detail: dict = {}
|
|
717
|
+
satisfied = False
|
|
718
|
+
while True:
|
|
719
|
+
polls += 1
|
|
720
|
+
try:
|
|
721
|
+
satisfied, detail = _check_condition(condition)
|
|
722
|
+
except ToolError:
|
|
723
|
+
raise
|
|
724
|
+
except Exception as error: # noqa: BLE001
|
|
725
|
+
detail = {"error": str(error)}
|
|
726
|
+
satisfied = False
|
|
727
|
+
if satisfied or time.monotonic() >= deadline:
|
|
728
|
+
break
|
|
729
|
+
time.sleep(interval_ms / 1000.0)
|
|
730
|
+
elapsed_ms = int((time.monotonic() - started) * 1000)
|
|
731
|
+
return {
|
|
732
|
+
"satisfied": satisfied,
|
|
733
|
+
"waited_ms": elapsed_ms,
|
|
734
|
+
"polls": polls,
|
|
735
|
+
"timeout_ms": timeout_ms,
|
|
736
|
+
"condition": condition,
|
|
737
|
+
"state": detail,
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def _first_frame_obj(app):
|
|
742
|
+
"""The first frame child of an application, or None."""
|
|
743
|
+
if app is None:
|
|
744
|
+
return None
|
|
745
|
+
try:
|
|
746
|
+
count = app.get_child_count()
|
|
747
|
+
except Exception: # noqa: BLE001
|
|
748
|
+
return None
|
|
749
|
+
for index in range(min(count, 4)):
|
|
750
|
+
try:
|
|
751
|
+
child = app.get_child_at_index(index)
|
|
752
|
+
if child is None:
|
|
753
|
+
continue
|
|
754
|
+
if (child.get_role_name() or "") == "frame":
|
|
755
|
+
return child
|
|
756
|
+
except Exception: # noqa: BLE001
|
|
757
|
+
continue
|
|
758
|
+
return None
|
|
759
|
+
|
|
760
|
+
|
|
446
761
|
def _first_frame(app):
|
|
447
762
|
try:
|
|
448
763
|
count = app.get_child_count()
|
|
@@ -460,6 +775,132 @@ def _first_frame(app):
|
|
|
460
775
|
return None
|
|
461
776
|
|
|
462
777
|
|
|
778
|
+
# --------------------------------------------------------------------------- #
|
|
779
|
+
# Windows: enumerate frames, raise one, wait for conditions
|
|
780
|
+
# --------------------------------------------------------------------------- #
|
|
781
|
+
|
|
782
|
+
WINDOW_ACTIVATE_MAX_CYCLES = int(os.environ.get("DSH_LINUX_CU_MAX_TAB_CYCLES", "12"))
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def _xdotool(*argv: str, timeout: float = 3.0) -> tuple[int, str]:
|
|
786
|
+
"""Run xdotool against the XWayland display; (127, "") when unavailable."""
|
|
787
|
+
if not os.environ.get("DISPLAY"):
|
|
788
|
+
return (127, "")
|
|
789
|
+
try:
|
|
790
|
+
done = subprocess.run(
|
|
791
|
+
["xdotool", *argv], capture_output=True, text=True, timeout=timeout
|
|
792
|
+
)
|
|
793
|
+
except (OSError, subprocess.SubprocessError):
|
|
794
|
+
return (127, "")
|
|
795
|
+
return (done.returncode, (done.stdout or "").strip())
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def _window_is_active(acc) -> bool:
|
|
799
|
+
"""True when the toolkit marks this window ACTIVE (raised/focused).
|
|
800
|
+
|
|
801
|
+
cu_a11y.STATE_FLAGS stops at FOCUSED, and most toolkits set ACTIVE on the
|
|
802
|
+
toplevel frame instead, so the flag is queried directly here.
|
|
803
|
+
"""
|
|
804
|
+
try:
|
|
805
|
+
state_set = acc.get_state_set()
|
|
806
|
+
except Exception: # noqa: BLE001
|
|
807
|
+
return False
|
|
808
|
+
for flag in ("ACTIVE", "FOCUSED"):
|
|
809
|
+
value = getattr(cu_a11y.Atspi.StateType, flag, None)
|
|
810
|
+
if value is None:
|
|
811
|
+
continue
|
|
812
|
+
try:
|
|
813
|
+
if state_set.contains(value):
|
|
814
|
+
return True
|
|
815
|
+
except Exception: # noqa: BLE001
|
|
816
|
+
return False
|
|
817
|
+
return False
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def _frame_rows() -> list[dict]:
|
|
821
|
+
"""Every top-level window frame the accessibility bus can see."""
|
|
822
|
+
rows: list[dict] = []
|
|
823
|
+
for app in A11Y.apps(max_age=1.5):
|
|
824
|
+
try:
|
|
825
|
+
target = A11Y.resolve(app["ref"])
|
|
826
|
+
if target is None:
|
|
827
|
+
continue
|
|
828
|
+
count = target.get_child_count()
|
|
829
|
+
except Exception: # noqa: BLE001
|
|
830
|
+
continue
|
|
831
|
+
for index in range(min(count, 4)):
|
|
832
|
+
try:
|
|
833
|
+
child = target.get_child_at_index(index)
|
|
834
|
+
if child is None or (child.get_role_name() or "") != "frame":
|
|
835
|
+
continue
|
|
836
|
+
except Exception: # noqa: BLE001
|
|
837
|
+
continue
|
|
838
|
+
active = _window_is_active(child)
|
|
839
|
+
rows.append(
|
|
840
|
+
{
|
|
841
|
+
"app": app.get("name") or "",
|
|
842
|
+
"title": child.get_name() or "",
|
|
843
|
+
"ref": app.get("ref"),
|
|
844
|
+
"pid": app.get("pid"),
|
|
845
|
+
"active": active,
|
|
846
|
+
"acc": child,
|
|
847
|
+
}
|
|
848
|
+
)
|
|
849
|
+
break
|
|
850
|
+
return rows
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def _match_window(rows: list[dict], title: str, app: str) -> dict | None:
|
|
854
|
+
"""Prefer an exact title, then a title substring, then the app name."""
|
|
855
|
+
needle = (title or "").strip().lower()
|
|
856
|
+
app_needle = (app or "").strip().lower()
|
|
857
|
+
if needle:
|
|
858
|
+
for row in rows:
|
|
859
|
+
if (row["title"] or "").lower() == needle:
|
|
860
|
+
return row
|
|
861
|
+
for row in rows:
|
|
862
|
+
if needle in (row["title"] or "").lower():
|
|
863
|
+
return row
|
|
864
|
+
for row in rows:
|
|
865
|
+
if needle in (row["app"] or "").lower():
|
|
866
|
+
return row
|
|
867
|
+
if app_needle:
|
|
868
|
+
for row in rows:
|
|
869
|
+
if (row["app"] or "").lower() == app_needle:
|
|
870
|
+
return row
|
|
871
|
+
for row in rows:
|
|
872
|
+
if app_needle in (row["app"] or "").lower():
|
|
873
|
+
return row
|
|
874
|
+
return None
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
def _active_titles() -> set:
|
|
878
|
+
"""Titles of the windows the accessibility tree currently reports as ACTIVE."""
|
|
879
|
+
return {row["title"] for row in _frame_rows() if row["active"]}
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def _is_active(title: str) -> bool:
|
|
883
|
+
needle = (title or "").strip().lower()
|
|
884
|
+
if not needle:
|
|
885
|
+
return False
|
|
886
|
+
for row in _frame_rows():
|
|
887
|
+
if not row["active"]:
|
|
888
|
+
continue
|
|
889
|
+
if (row["title"] or "").lower() == needle or needle in (row["title"] or "").lower():
|
|
890
|
+
return True
|
|
891
|
+
return False
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def _wait_active(title: str, timeout_s: float) -> bool:
|
|
895
|
+
deadline = time.monotonic() + timeout_s
|
|
896
|
+
while time.monotonic() < deadline:
|
|
897
|
+
if _is_active(title):
|
|
898
|
+
return True
|
|
899
|
+
time.sleep(0.12)
|
|
900
|
+
return _is_active(title)
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
|
|
463
904
|
def tool_display_info(args: dict) -> dict:
|
|
464
905
|
current = layout()
|
|
465
906
|
info = current.describe()
|
|
@@ -479,6 +920,8 @@ def tool_desktop_status(args: dict) -> dict:
|
|
|
479
920
|
"type": os.environ.get("XDG_SESSION_TYPE", ""),
|
|
480
921
|
"desktop": os.environ.get("XDG_CURRENT_DESKTOP", ""),
|
|
481
922
|
"locked": cu_sys.screen_locked(),
|
|
923
|
+
"idle_ms": cu_sys.idle_ms(),
|
|
924
|
+
"input_guard_ms": IDLE_GUARD_MS,
|
|
482
925
|
"unlock": cu_unlock.status(),
|
|
483
926
|
}
|
|
484
927
|
try:
|
|
@@ -554,6 +997,30 @@ SPACE_PROP = {
|
|
|
554
997
|
"description": "Coordinate space: 'logical' desktop pixels, or 'screenshot' pixels of the last screenshot.",
|
|
555
998
|
}
|
|
556
999
|
|
|
1000
|
+
ALLOW_ACTIVE_PROP = {
|
|
1001
|
+
"type": "boolean",
|
|
1002
|
+
"default": False,
|
|
1003
|
+
"description": (
|
|
1004
|
+
"Set true when the user just asked you to drive the desktop: it skips the idle guard, "
|
|
1005
|
+
"which otherwise refuses injected input while they are using the keyboard or pointer."
|
|
1006
|
+
),
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
# Tools that inject input all accept the same escape hatch; adding it here keeps
|
|
1010
|
+
# the schema in one place instead of ten copies.
|
|
1011
|
+
_INJECTING_TOOLS = {
|
|
1012
|
+
"click",
|
|
1013
|
+
"move",
|
|
1014
|
+
"drag",
|
|
1015
|
+
"scroll",
|
|
1016
|
+
"pointer_button",
|
|
1017
|
+
"key",
|
|
1018
|
+
"type_text",
|
|
1019
|
+
"ui_action",
|
|
1020
|
+
"ui_focus",
|
|
1021
|
+
"ui_set_text",
|
|
1022
|
+
}
|
|
1023
|
+
|
|
557
1024
|
def tool_unlock_screen(args: dict) -> dict:
|
|
558
1025
|
confirm = str(args.get("confirm") or "").strip().lower()
|
|
559
1026
|
if confirm != "unlock":
|
|
@@ -574,10 +1041,11 @@ TOOLS: list[dict] = [
|
|
|
574
1041
|
{
|
|
575
1042
|
"name": "screenshot",
|
|
576
1043
|
"description": (
|
|
577
|
-
"Capture the
|
|
578
|
-
"Use it to see the screen before deciding where to click.
|
|
579
|
-
"
|
|
580
|
-
"
|
|
1044
|
+
"Capture the desktop (or one region of it) and return a PNG image plus its size and path. "
|
|
1045
|
+
"Use it to see the screen before deciding where to click. Pass region {x, y, width, height} "
|
|
1046
|
+
"in logical pixels when you only need one window or one corner: a cropped capture stays "
|
|
1047
|
+
"sharp, while the whole 4K desktop scaled down does not. The desktop asks for a one-time "
|
|
1048
|
+
"screen-capture approval; after that every capture is silent and takes about half a second."
|
|
581
1049
|
),
|
|
582
1050
|
"inputSchema": {
|
|
583
1051
|
"type": "object",
|
|
@@ -585,8 +1053,29 @@ TOOLS: list[dict] = [
|
|
|
585
1053
|
"max_width": {
|
|
586
1054
|
"type": "integer",
|
|
587
1055
|
"default": SHOT_MAX_WIDTH,
|
|
588
|
-
"description": "Downscale the image to this pixel width (0 keeps native resolution).",
|
|
589
|
-
}
|
|
1056
|
+
"description": "Downscale the image to this pixel width (0 keeps native resolution). Ignored when scale is given.",
|
|
1057
|
+
},
|
|
1058
|
+
"region": {
|
|
1059
|
+
"type": "object",
|
|
1060
|
+
"description": (
|
|
1061
|
+
"Capture only this rectangle, in logical desktop pixels. Cropping before "
|
|
1062
|
+
"downscaling is what keeps small UI text readable."
|
|
1063
|
+
),
|
|
1064
|
+
"properties": {
|
|
1065
|
+
"x": {"type": "number"},
|
|
1066
|
+
"y": {"type": "number"},
|
|
1067
|
+
"width": {"type": "number"},
|
|
1068
|
+
"height": {"type": "number"},
|
|
1069
|
+
},
|
|
1070
|
+
"required": ["x", "y", "width", "height"],
|
|
1071
|
+
},
|
|
1072
|
+
"scale": {
|
|
1073
|
+
"type": "number",
|
|
1074
|
+
"description": (
|
|
1075
|
+
"Output pixels per logical pixel: 1.0 keeps native size, 2.0 doubles it. "
|
|
1076
|
+
"Takes precedence over max_width."
|
|
1077
|
+
),
|
|
1078
|
+
},
|
|
590
1079
|
},
|
|
591
1080
|
},
|
|
592
1081
|
"handler": tool_screenshot,
|
|
@@ -604,8 +1093,10 @@ TOOLS: list[dict] = [
|
|
|
604
1093
|
"name": "ui_tree",
|
|
605
1094
|
"description": (
|
|
606
1095
|
"Read the accessibility tree of one application (or a few) as nested role/name/rect/"
|
|
607
|
-
"action nodes. Bounded by max_depth and max_nodes.
|
|
608
|
-
"
|
|
1096
|
+
"action nodes. Bounded by max_depth and max_nodes. Pass roles to keep only interesting "
|
|
1097
|
+
"kinds of node (ancestors collapse to a bare ref/role/name path), and compact to drop "
|
|
1098
|
+
"rect/states/text: a filtered compact tree is often 10x cheaper than the full one. "
|
|
1099
|
+
"Chromium/Electron/Qt apps usually expose almost nothing; use screenshot for those."
|
|
609
1100
|
),
|
|
610
1101
|
"inputSchema": {
|
|
611
1102
|
"type": "object",
|
|
@@ -613,6 +1104,19 @@ TOOLS: list[dict] = [
|
|
|
613
1104
|
"app": {"type": "string", "description": "Application name as shown by ui_apps (substring match)."},
|
|
614
1105
|
"max_depth": {"type": "integer", "default": 3, "minimum": 1, "maximum": 8},
|
|
615
1106
|
"max_nodes": {"type": "integer", "default": 220, "minimum": 10, "maximum": 1200},
|
|
1107
|
+
"roles": {
|
|
1108
|
+
"type": "array",
|
|
1109
|
+
"items": {"type": "string"},
|
|
1110
|
+
"description": (
|
|
1111
|
+
"Keep only nodes whose role contains one of these fragments, e.g. "
|
|
1112
|
+
"[\"push button\", \"entry\", \"menu item\"]. Case-insensitive."
|
|
1113
|
+
),
|
|
1114
|
+
},
|
|
1115
|
+
"compact": {
|
|
1116
|
+
"type": "boolean",
|
|
1117
|
+
"default": False,
|
|
1118
|
+
"description": "Drop rect, states and text previews; keep ref, role, name and actions.",
|
|
1119
|
+
},
|
|
616
1120
|
},
|
|
617
1121
|
},
|
|
618
1122
|
"handler": tool_ui_tree,
|
|
@@ -886,6 +1390,55 @@ TOOLS: list[dict] = [
|
|
|
886
1390
|
"inputSchema": {"type": "object", "properties": {}},
|
|
887
1391
|
"handler": tool_window_list,
|
|
888
1392
|
},
|
|
1393
|
+
{
|
|
1394
|
+
"name": "window_activate",
|
|
1395
|
+
"description": (
|
|
1396
|
+
"Raise a window by title substring (or app name) and report which method worked: "
|
|
1397
|
+
"xdotool for XWayland surfaces, the AT-SPI default action, or Alt+Tab cycling for "
|
|
1398
|
+
"native Wayland windows."
|
|
1399
|
+
),
|
|
1400
|
+
"inputSchema": {
|
|
1401
|
+
"type": "object",
|
|
1402
|
+
"properties": {
|
|
1403
|
+
"title": {"type": "string", "description": "Case-insensitive substring of the window title."},
|
|
1404
|
+
"app": {"type": "string", "description": "Application name, used when the title is unknown."},
|
|
1405
|
+
"max_cycles": {
|
|
1406
|
+
"type": "integer",
|
|
1407
|
+
"minimum": 1,
|
|
1408
|
+
"maximum": 30,
|
|
1409
|
+
"default": 12,
|
|
1410
|
+
"description": "How many Alt+Tab presses to try before giving up.",
|
|
1411
|
+
},
|
|
1412
|
+
"allow_active_input": ALLOW_ACTIVE_PROP,
|
|
1413
|
+
},
|
|
1414
|
+
},
|
|
1415
|
+
"handler": tool_window_activate,
|
|
1416
|
+
},
|
|
1417
|
+
{
|
|
1418
|
+
"name": "wait_until",
|
|
1419
|
+
"description": (
|
|
1420
|
+
"Poll the desktop until a condition holds, instead of sleeping a fixed time: a window "
|
|
1421
|
+
"appears or disappears, a window becomes active, an accessibility node shows up, or the "
|
|
1422
|
+
"user has been idle long enough. Returns satisfied=false on timeout with the last state."
|
|
1423
|
+
),
|
|
1424
|
+
"inputSchema": {
|
|
1425
|
+
"type": "object",
|
|
1426
|
+
"properties": {
|
|
1427
|
+
"condition": {
|
|
1428
|
+
"type": "object",
|
|
1429
|
+
"description": (
|
|
1430
|
+
'One of: {"window": {"title": "...", "app": "...", "exists": true}}, '
|
|
1431
|
+
'{"window_active": "Chrome"}, {"ui": {"app": "...", "name": "...", "role": "..."}}, '
|
|
1432
|
+
'{"idle_at_least": 60000}.'
|
|
1433
|
+
),
|
|
1434
|
+
},
|
|
1435
|
+
"timeout_ms": {"type": "integer", "minimum": 100, "maximum": 120000, "default": 15000},
|
|
1436
|
+
"interval_ms": {"type": "integer", "minimum": 80, "maximum": 5000, "default": 300},
|
|
1437
|
+
},
|
|
1438
|
+
"required": ["condition"],
|
|
1439
|
+
},
|
|
1440
|
+
"handler": tool_wait_until,
|
|
1441
|
+
},
|
|
889
1442
|
{
|
|
890
1443
|
"name": "display_info",
|
|
891
1444
|
"description": (
|
|
@@ -918,6 +1471,12 @@ TOOLS: list[dict] = [
|
|
|
918
1471
|
},
|
|
919
1472
|
]
|
|
920
1473
|
|
|
1474
|
+
# Every input-injecting tool advertises the idle-guard escape hatch.
|
|
1475
|
+
for _spec in TOOLS:
|
|
1476
|
+
if _spec["name"] in _INJECTING_TOOLS:
|
|
1477
|
+
_spec["inputSchema"].setdefault("properties", {})["allow_active_input"] = ALLOW_ACTIVE_PROP
|
|
1478
|
+
|
|
1479
|
+
|
|
921
1480
|
UNLOCK_TOOL: dict = {
|
|
922
1481
|
"name": "unlock_screen",
|
|
923
1482
|
"description": (
|
|
@@ -1089,6 +1648,129 @@ def _portal_screencast_version() -> int | None:
|
|
|
1089
1648
|
return None
|
|
1090
1649
|
|
|
1091
1650
|
|
|
1651
|
+
def _gsettings_list(schema: str, key: str) -> list[str] | None:
|
|
1652
|
+
"""Read a list-valued gsettings key ("['<Super>Tab', '<Alt>Tab']")."""
|
|
1653
|
+
try:
|
|
1654
|
+
result = subprocess.run(
|
|
1655
|
+
["gsettings", "get", schema, key],
|
|
1656
|
+
capture_output=True, text=True, timeout=4.0, check=False,
|
|
1657
|
+
)
|
|
1658
|
+
except (OSError, subprocess.SubprocessError):
|
|
1659
|
+
return None
|
|
1660
|
+
if result.returncode != 0:
|
|
1661
|
+
return None
|
|
1662
|
+
raw = result.stdout.strip()
|
|
1663
|
+
if not raw.startswith("[") or not raw.endswith("]"):
|
|
1664
|
+
return None
|
|
1665
|
+
inner = raw[1:-1].strip()
|
|
1666
|
+
if not inner:
|
|
1667
|
+
return []
|
|
1668
|
+
return [part.strip().strip("'\"") for part in inner.split(",")]
|
|
1669
|
+
|
|
1670
|
+
|
|
1671
|
+
def _keybinding_checks(checks: list) -> None:
|
|
1672
|
+
"""Explain which window-switch shortcut window_activate can actually use."""
|
|
1673
|
+
schema = "org.gnome.desktop.wm.keybindings"
|
|
1674
|
+
windows = _gsettings_list(schema, "switch-windows")
|
|
1675
|
+
apps = _gsettings_list(schema, "switch-applications")
|
|
1676
|
+
if windows is None and apps is None:
|
|
1677
|
+
_check(
|
|
1678
|
+
checks,
|
|
1679
|
+
"keybindings",
|
|
1680
|
+
"warn",
|
|
1681
|
+
"window-switch keybindings are unreadable",
|
|
1682
|
+
"gsettings did not answer; window_activate can still raise XWayland windows",
|
|
1683
|
+
"install libglib2.0-bin (gsettings) to make the keyboard fallback verifiable",
|
|
1684
|
+
)
|
|
1685
|
+
return
|
|
1686
|
+
windows = windows or []
|
|
1687
|
+
apps = apps or []
|
|
1688
|
+
has_alt = any("Alt" in item and "Tab" in item for item in windows)
|
|
1689
|
+
has_super = any("Super" in item and "Tab" in item for item in apps)
|
|
1690
|
+
if has_alt and has_super:
|
|
1691
|
+
_check(
|
|
1692
|
+
checks,
|
|
1693
|
+
"keybindings",
|
|
1694
|
+
"ok",
|
|
1695
|
+
"both window-switch shortcuts are bound",
|
|
1696
|
+
"Alt+Tab switches windows of one application, Super+Tab switches applications",
|
|
1697
|
+
)
|
|
1698
|
+
elif has_super:
|
|
1699
|
+
_check(
|
|
1700
|
+
checks,
|
|
1701
|
+
"keybindings",
|
|
1702
|
+
"ok",
|
|
1703
|
+
"Super+Tab is bound to switch applications",
|
|
1704
|
+
"Alt+Tab is not bound, so window_activate goes straight to Super+Tab",
|
|
1705
|
+
)
|
|
1706
|
+
elif has_alt:
|
|
1707
|
+
_check(
|
|
1708
|
+
checks,
|
|
1709
|
+
"keybindings",
|
|
1710
|
+
"warn",
|
|
1711
|
+
"only Alt+Tab is bound",
|
|
1712
|
+
"Alt+Tab switches windows inside the current application, so raising another application's window may fail",
|
|
1713
|
+
"add a Super+Tab binding to switch-applications, or drag the window forward by hand",
|
|
1714
|
+
)
|
|
1715
|
+
else:
|
|
1716
|
+
_check(
|
|
1717
|
+
checks,
|
|
1718
|
+
"keybindings",
|
|
1719
|
+
"warn",
|
|
1720
|
+
"no window-switch shortcut is bound",
|
|
1721
|
+
"window_activate can only rely on xdotool and the accessibility default action",
|
|
1722
|
+
"bind switch-windows to <Alt>Tab in Settings -> Keyboard -> View and Customise Shortcuts",
|
|
1723
|
+
)
|
|
1724
|
+
|
|
1725
|
+
|
|
1726
|
+
def _sync_check(checks: list) -> None:
|
|
1727
|
+
"""Report whether this running copy is in step with the installed package."""
|
|
1728
|
+
if not os.path.exists(SOURCE_POINTER):
|
|
1729
|
+
_check(
|
|
1730
|
+
checks,
|
|
1731
|
+
"server-copy",
|
|
1732
|
+
"warn",
|
|
1733
|
+
"cannot tell which package this server copy came from",
|
|
1734
|
+
f"{SOURCE_POINTER} is missing; the copy never refreshes itself",
|
|
1735
|
+
"reinstall the bundle, or reload it from Settings -> Plugins",
|
|
1736
|
+
)
|
|
1737
|
+
return
|
|
1738
|
+
try:
|
|
1739
|
+
with open(SOURCE_POINTER, encoding="utf-8") as handle:
|
|
1740
|
+
source = handle.read().strip()
|
|
1741
|
+
except OSError as error: # noqa: BLE001
|
|
1742
|
+
_check(checks, "server-copy", "warn", "cannot read the package pointer", str(error))
|
|
1743
|
+
return
|
|
1744
|
+
fresh = os.path.join(source, "linux_desktop_mcp.py")
|
|
1745
|
+
if not os.path.exists(fresh):
|
|
1746
|
+
_check(
|
|
1747
|
+
checks,
|
|
1748
|
+
"server-copy",
|
|
1749
|
+
"warn",
|
|
1750
|
+
"the package this copy came from is gone",
|
|
1751
|
+
source,
|
|
1752
|
+
"reinstall the bundle; the copy now updates itself from the package on start",
|
|
1753
|
+
)
|
|
1754
|
+
return
|
|
1755
|
+
ours = os.path.abspath(__file__)
|
|
1756
|
+
try:
|
|
1757
|
+
same = open(fresh, "rb").read() == open(ours, "rb").read()
|
|
1758
|
+
except OSError as error: # noqa: BLE001
|
|
1759
|
+
_check(checks, "server-copy", "warn", "cannot compare server copies", str(error))
|
|
1760
|
+
return
|
|
1761
|
+
if same:
|
|
1762
|
+
_check(checks, "server-copy", "ok", "this copy matches the installed package", source)
|
|
1763
|
+
else:
|
|
1764
|
+
_check(
|
|
1765
|
+
checks,
|
|
1766
|
+
"server-copy",
|
|
1767
|
+
"warn",
|
|
1768
|
+
"this copy differs from the installed package",
|
|
1769
|
+
f"package: {fresh}",
|
|
1770
|
+
"restart the MCP entry (or reload the bundle): the server refreshes itself on start",
|
|
1771
|
+
)
|
|
1772
|
+
|
|
1773
|
+
|
|
1092
1774
|
def selftest() -> dict:
|
|
1093
1775
|
"""Collect everything the doctor tool needs, without asking for permissions."""
|
|
1094
1776
|
checks: list[dict] = []
|
|
@@ -1296,6 +1978,9 @@ def selftest() -> dict:
|
|
|
1296
1978
|
except Exception as error: # noqa: BLE001
|
|
1297
1979
|
_check(checks, "a11y", "warn", "AT-SPI is unavailable", str(error), "check that org.a11y.Bus is running")
|
|
1298
1980
|
|
|
1981
|
+
_keybinding_checks(checks)
|
|
1982
|
+
_sync_check(checks)
|
|
1983
|
+
|
|
1299
1984
|
ok = not any(check["status"] == "fail" for check in checks)
|
|
1300
1985
|
return {
|
|
1301
1986
|
"ok": ok,
|
|
@@ -1336,7 +2021,64 @@ def _cli_unlock(args: list[str]) -> int | None:
|
|
|
1336
2021
|
return None
|
|
1337
2022
|
|
|
1338
2023
|
|
|
2024
|
+
INSTALL_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
2025
|
+
SOURCE_POINTER = os.path.join(INSTALL_DIR, ".source")
|
|
2026
|
+
SELF_UPDATE_FLAG = "DSH_LINUX_CU_SELF_UPDATED"
|
|
2027
|
+
|
|
2028
|
+
|
|
2029
|
+
def _self_update() -> None:
|
|
2030
|
+
"""Refresh this copy of the server from the installed package, then re-exec.
|
|
2031
|
+
|
|
2032
|
+
The bundle syncs server/*.py into a stable directory when the *doctor*
|
|
2033
|
+
plugin loads, but the MCP server is started by a different patch entry, so
|
|
2034
|
+
toggling only that entry (or upgrading the npm package) leaves a stale copy
|
|
2035
|
+
behind. A pointer file records where the package lives; comparing against
|
|
2036
|
+
it here makes the server heal itself before it serves a single request.
|
|
2037
|
+
"""
|
|
2038
|
+
if os.environ.get(SELF_UPDATE_FLAG) == "1":
|
|
2039
|
+
return
|
|
2040
|
+
try:
|
|
2041
|
+
with open(SOURCE_POINTER, encoding="utf-8") as handle:
|
|
2042
|
+
source = handle.read().strip()
|
|
2043
|
+
except OSError:
|
|
2044
|
+
return
|
|
2045
|
+
if not source or not os.path.isdir(source):
|
|
2046
|
+
return
|
|
2047
|
+
if os.path.realpath(source) == os.path.realpath(INSTALL_DIR):
|
|
2048
|
+
return
|
|
2049
|
+
if not os.path.exists(os.path.join(source, "linux_desktop_mcp.py")):
|
|
2050
|
+
return
|
|
2051
|
+
changed: list[str] = []
|
|
2052
|
+
for name in sorted(os.listdir(source)):
|
|
2053
|
+
if not name.endswith(".py"):
|
|
2054
|
+
continue
|
|
2055
|
+
fresh = os.path.join(source, name)
|
|
2056
|
+
stale = os.path.join(INSTALL_DIR, name)
|
|
2057
|
+
try:
|
|
2058
|
+
with open(fresh, "rb") as mine, open(stale, "rb") as theirs:
|
|
2059
|
+
if mine.read() == theirs.read():
|
|
2060
|
+
continue
|
|
2061
|
+
except OSError:
|
|
2062
|
+
pass
|
|
2063
|
+
try:
|
|
2064
|
+
shutil.copyfile(fresh, stale)
|
|
2065
|
+
changed.append(name)
|
|
2066
|
+
except OSError as error: # noqa: BLE001
|
|
2067
|
+
log(f"self-refresh could not copy {name}: {error}")
|
|
2068
|
+
if not changed:
|
|
2069
|
+
return
|
|
2070
|
+
log(f"refreshed {len(changed)} server file(s) from {source}: {', '.join(changed)}")
|
|
2071
|
+
env = dict(os.environ)
|
|
2072
|
+
env[SELF_UPDATE_FLAG] = "1"
|
|
2073
|
+
try:
|
|
2074
|
+
os.execve(sys.executable, [sys.executable, os.path.abspath(__file__), *sys.argv[1:]], env)
|
|
2075
|
+
except OSError as error: # noqa: BLE001
|
|
2076
|
+
log(f"self-refresh re-exec failed: {error}")
|
|
2077
|
+
|
|
2078
|
+
|
|
1339
2079
|
def main() -> int:
|
|
2080
|
+
# Serve (and diagnose) with the freshest copy of the code we can find.
|
|
2081
|
+
_self_update()
|
|
1340
2082
|
unlock_exit = _cli_unlock(sys.argv[1:])
|
|
1341
2083
|
if unlock_exit is not None:
|
|
1342
2084
|
return unlock_exit
|