"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
fix(recorder): window-anchored click_relative, fix space/ctrl bugs
haorui-harry242445f9c0fc
diff --git a/macrocli/agent-harness/cli_anything/macrocli/core/recorder.py b/macrocli/agent-harness/cli_anything/macrocli/core/recorder.pyindex 40afe6f8c..0c5deacc1 100644--- a/macrocli/agent-harness/cli_anything/macrocli/core/recorder.py+++ b/macrocli/agent-harness/cli_anything/macrocli/core/recorder.py@@ -50,7 +50,10 @@ class RecordedStep:y: int = 0button: str = "left"double: bool = False- template_path: str = "" # relative path to saved template png+ template_path: str = "" # relative path to saved template png (may be empty)+ window_title: str = "" # title of window under click+ x_pct: float = 0.5 # click x as fraction of window width+ y_pct: float = 0.5 # click y as fraction of window height# type fieldstext: str = ""# hotkey fields@@ -62,24 +65,68 @@ class RecordedStep:timestamp: float = field(default_factory=time.time)def to_step_dict(self) -> dict:- """Convert to a macro YAML step dict."""+ """Convert to a macro YAML step dict.++ Strategy for clicks:+ 1. If we have a window title → use click_relative (most robust)+ 2. If we have a good template → use click_image+ 3. Fallback → click_relative using screen percentages+ """if self.kind == "click":- params: dict = {- "template": self.template_path,- "confidence": 0.85,- "timeout_ms": 5000,- }- if self.button != "left":- params["button"] = self.button- if self.double:- params["double"] = True- return {- "id": f"step_{self.index:03d}_click",- "backend": "visual_anchor",- "action": "click_image",- "params": params,- "on_failure": "fail",- }+ if self.window_title:+ # Best case: window-relative fractional coordinates+ params: dict = {+ "window_title": self.window_title,+ "x_pct": self.x_pct,+ "y_pct": self.y_pct,+ }+ if self.button != "left":+ params["button"] = self.button+ if self.double:+ params["double"] = True+ step = {+ "id": f"step_{self.index:03d}_click",+ "backend": "visual_anchor",+ "action": "click_relative",+ "params": params,+ "on_failure": "fail",+ }+ # Attach template as a comment if available (for debugging)+ if self.template_path:+ step["_template"] = self.template_path+ return step++ elif self.template_path:+ # Has a usable template image+ params = {+ "template": self.template_path,+ "confidence": 0.85,+ "timeout_ms": 5000,+ }+ if self.button != "left":+ params["button"] = self.button+ if self.double:+ params["double"] = True+ return {+ "id": f"step_{self.index:03d}_click",+ "backend": "visual_anchor",+ "action": "click_image",+ "params": params,+ "on_failure": "fail",+ }++ else:+ # Fallback: screen-relative fractional coordinates+ return {+ "id": f"step_{self.index:03d}_click",+ "backend": "visual_anchor",+ "action": "click_relative",+ "params": {+ "x_pct": self.x_pct,+ "y_pct": self.y_pct,+ },+ "on_failure": "fail",+ }elif self.kind == "type":return {"id": f"step_{self.index:03d}_type",@@ -111,16 +158,84 @@ class RecordedStep:return {}+# ── Window detection ──────────────────────────────────────────────────────────++def _get_active_window_at(x: int, y: int) -> tuple[str, Optional[dict]]:+ """Return (title, bounds) of the topmost window containing point (x, y).++ Uses wmctrl -lG to list all windows with geometry.+ Returns ("", None) if not found or wmctrl unavailable.+ """+ import shutil+ import subprocess+ import os++ env = os.environ.copy()+ if "DISPLAY" not in env:+ env["DISPLAY"] = ":0"++ if not shutil.which("wmctrl"):+ return "", None++ try:+ r = subprocess.run(+ ["wmctrl", "-lG"], capture_output=True, text=True, env=env, timeout=2+ )+ except Exception:+ return "", None++ # wmctrl -lG format: wid desktop x y w h host title+ candidates = []+ for line in r.stdout.splitlines():+ parts = line.split(None, 7) # wid desktop x y w h host title(rest)+ if len(parts) < 8:+ continue+ try:+ wx, wy = int(parts[2]), int(parts[3])+ ww, wh = int(parts[4]), int(parts[5])+ title = parts[7] # everything after hostname+ if title in ("", "Desktop"):+ continue+ if wx <= x <= wx + ww and wy <= y <= wy + wh:+ candidates.append((wx, wy, ww, wh, title))+ except ValueError:+ continue++ if not candidates:+ return "", None++ # Take the last match (topmost in stacking order from wmctrl output)+ wx, wy, ww, wh, title = candidates[-1]+ # wmctrl -lG title format: "<hostname> <actual title>"+ # Strip just the hostname (first word)+ parts = title.split(" ", 1)+ title = parts[1] if len(parts) > 1 else title++ # Use a partial match-friendly fragment: last segment after " - "+ # e.g. "macrocli_final.txt (/tmp) - gedit" → "gedit"+ if " - " in title:+ app_name = title.split(" - ")[-1].strip()+ else:+ app_name = title.strip()++ return app_name, {"x": wx, "y": wy, "width": ww, "height": wh}++# ── Template capture ──────────────────────────────────────────────────────────-_TEMPLATE_PADDING = 30 # pixels around click point to capture+_TEMPLATE_PADDING = 60 # pixels around click point to capturedef _capture_template(x: int, y: int, output_path: str) -> bool:- """Capture a small region around (x, y) and save as PNG template."""+ """Capture a small region around (x, y) and save as PNG template.++ Returns False if the region has too little variance (blank/featureless)+ to be useful as a template.+ """try:import mssfrom PIL import Image+ import numpy as nppad = _TEMPLATE_PADDINGregion = {@@ -133,6 +248,12 @@ def _capture_template(x: int, y: int, output_path: str) -> bool:with mss.mss() as sct:raw = sct.grab(region)img = Image.frombytes("RGB", raw.size, raw.bgra, "raw", "BGRX")++ # Check variance — featureless templates are useless+ arr = np.array(img, dtype=np.float32)+ if arr.std() < 8.0:+ return False # blank region, skip+img.save(output_path)return Trueexcept Exception as e:@@ -241,7 +362,21 @@ class MacroRecorder:self._last_click_pos = (x, y)self._last_click_time = now- # Save template+ # Try to find the window under the click point+ window_title, window_bounds = _get_active_window_at(x, y)++ # Compute relative coords within window (fallback to screen pct)+ if window_bounds:+ wx, wy = window_bounds["x"], window_bounds["y"]+ ww, wh = window_bounds["width"], window_bounds["height"]+ x_pct = round((x - wx) / ww, 4) if ww > 0 else 0.5+ y_pct = round((y - wy) / wh, 4) if wh > 0 else 0.5+ else:+ window_title = ""+ x_pct = round(x / 1920, 4)+ y_pct = round(y / 1080, 4)++ # Also try to capture a template (useful when region has features)idx = self._next_index()template_file = str(self.templates_dir / f"step_{idx:03d}_click.png"@@ -255,9 +390,16 @@ class MacroRecorder:y=y,button=btn_str,template_path=template_file if captured else "",+ window_title=window_title,+ x_pct=x_pct,+ y_pct=y_pct,)self._steps.append(step)- print(f"[recorder] click #{idx} at ({x},{y}) btn={btn_str}", flush=True)+ print(+ f"[recorder] click #{idx} at ({x},{y}) "+ f"window='{window_title}' rel=({x_pct},{y_pct})",+ flush=True+ )def on_scroll(self, x: int, y: int, dx: int, dy: int):with self._lock:@@ -296,8 +438,12 @@ class MacroRecorder:return# If modifiers are pressed, it's a hotkey combination+ # But only if the key itself is NOT a modifier+ normalized_key = _KEY_NAME_MAP.get(key_str, key_str)+ is_modifier = normalized_key in {"ctrl", "shift", "alt", "cmd", "super"}active_mods = {_KEY_NAME_MAP.get(m, m) for m in self._pressed_modifiers}- if active_mods:++ if active_mods and not is_modifier:with self._lock:self._flush_pending_chars()combo = "+".join(sorted(active_mods) + [key_str])@@ -305,11 +451,14 @@ class MacroRecorder:step = RecordedStep(index=idx, kind="hotkey", keys=combo)self._steps.append(step)print(f"[recorder] hotkey #{idx}: {combo}", flush=True)- else:- # Regular character — accumulate- if len(key_str) == 1:+ elif not is_modifier:+ # Regular character or special key+ # space key comes as Key.space (len > 1), treat as printable+ is_space = (key_str == "space")+ if len(key_str) == 1 or is_space:+ char = " " if is_space else key_strwith self._lock:- self._pending_chars.append(key_str)+ self._pending_chars.append(char)else:# Special key alone (enter, tab, backspace, etc.)with self._lock: