RepoPeft-data / oracle_context_cache /CursorTouch__Windows-MCP.json
nanigock's picture
Upload folder using huggingface_hub
cd15502 verified
{"repo": "CursorTouch/Windows-MCP", "n_pairs": 73, "version": "v2_function_scoped", "contexts": {"tests/test_analytics.py::68": {"resolved_imports": ["src/windows_mcp/analytics.py"], "used_names": ["AsyncMock", "asyncio", "pytest", "with_analytics"], "enclosing_function": "test_error_still_tracks_duration", "extracted_code": "# Source: src/windows_mcp/analytics.py\ndef with_analytics(analytics_instance: Analytics | None, tool_name: str):\n \"\"\"\n Decorator to wrap tool functions with analytics tracking.\n \"\"\"\n\n def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:\n @wraps(func)\n async def wrapper(*args, **kwargs) -> T:\n start = time.time()\n\n # Capture client info from Context passed as argument\n client_data = {}\n try:\n ctx = next((arg for arg in args if isinstance(arg, Context)), None)\n if not ctx:\n ctx = next(\n (val for val in kwargs.values() if isinstance(val, Context)),\n None,\n )\n\n if (\n ctx\n and ctx.session\n and ctx.session.client_params\n and ctx.session.client_params.clientInfo\n ):\n info = ctx.session.client_params.clientInfo\n client_data[\"client_name\"] = info.name\n client_data[\"client_version\"] = info.version\n except Exception:\n pass\n\n try:\n if asyncio.iscoroutinefunction(func):\n result = await func(*args, **kwargs)\n else:\n # Run sync function in thread to avoid blocking loop\n result = await asyncio.to_thread(func, *args, **kwargs)\n\n duration_ms = int((time.time() - start) * 1000)\n\n if analytics_instance:\n await analytics_instance.track_tool(\n tool_name,\n {\"duration_ms\": duration_ms, \"success\": True, **client_data},\n )\n\n return result\n except Exception as error:\n duration_ms = int((time.time() - start) * 1000)\n if analytics_instance:\n await analytics_instance.track_error(\n error,\n {\n \"tool_name\": tool_name,\n \"duration_ms\": duration_ms,\n **client_data,\n },\n )\n raise error\n\n return wrapper\n\n return decorator", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2391}, "tests/test_auth_service.py::44": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthClient"], "enclosing_function": "test_repr_masks_key", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nclass AuthClient:\n \"\"\"\n Handles authentication between the MCP server (running on EC2)\n and the Windows-MCP Dashboard.\n\n Flow:\n 1. POST /api/user/auth with api_key + sandbox_id\n 2. Dashboard validates key, checks credits, resolves sandbox\n 3. Returns session_token for subsequent /api/mcp calls\n 4. ProxyClient uses Bearer <session_token> to connect\n \"\"\"\n\n def __init__(self, api_key: str, sandbox_id: str):\n self.dashboard_url = \"http://localhost:3000\"\n self.api_key = api_key\n self.sandbox_id = sandbox_id\n self._session_token: str | None = None\n\n @property\n def session_token(self) -> str | None:\n return self._session_token\n\n @property\n def proxy_url(self) -> str:\n \"\"\"The dashboard's MCP streamable-HTTP endpoint.\"\"\"\n return f\"{self.dashboard_url}/api/mcp\"\n\n @property\n def proxy_headers(self) -> dict[str, str]:\n \"\"\"Headers for ProxyClient with Bearer auth.\"\"\"\n if not self._session_token:\n raise AuthError(\"Not authenticated. Call authenticate() first.\")\n return {\"Authorization\": f\"Bearer {self._session_token}\"}\n\n def authenticate(self) -> None:\n \"\"\"\n Authenticate with the dashboard and obtain a session token.\n Retries up to MAX_RETRIES times on transient failures.\n\n Raises:\n AuthError: If authentication fails after all retries.\n \"\"\"\n url = f\"{self.dashboard_url}/api/user/auth\"\n payload = {\n \"api_key\": self.api_key,\n \"sandbox_id\": self.sandbox_id,\n }\n\n last_error: AuthError | None = None\n\n for attempt in range(1, MAX_RETRIES + 1):\n logger.info(\"Authenticating with dashboard at %s (attempt %d/%d)\", url, attempt, MAX_RETRIES)\n\n try:\n response = requests.post(url, json=payload, timeout=30)\n except requests.ConnectionError:\n last_error = AuthError(\n f\"Cannot reach dashboard at {self.dashboard_url}. \"\n \"Check DASHBOARD_URL and network connectivity.\"\n )\n self._backoff(attempt)\n continue\n except requests.Timeout:\n last_error = AuthError(\"Dashboard authentication request timed out.\")\n self._backoff(attempt)\n continue\n except requests.RequestException as e:\n last_error = AuthError(f\"Request failed: {e}\")\n self._backoff(attempt)\n continue\n\n try:\n data = response.json()\n except (ValueError, requests.JSONDecodeError):\n last_error = AuthError(\n f\"Dashboard returned non-JSON response (HTTP {response.status_code}).\"\n )\n self._backoff(attempt)\n continue\n\n if response.status_code != 200:\n detail = data.get(\"detail\", \"Unknown error\")\n logger.error(\"Authentication failed [%d]: %s\", response.status_code, detail)\n # Don't retry on client errors (4xx) — these won't resolve themselves\n if 400 <= response.status_code < 500:\n raise AuthError(detail, status_code=response.status_code)\n last_error = AuthError(detail, status_code=response.status_code)\n self._backoff(attempt)\n continue\n\n session_token = data.get(\"session_token\")\n if not session_token:\n raise AuthError(\n \"Dashboard returned success but no session_token. \"\n \"Ensure the dashboard is up to date.\"\n )\n\n self._session_token = session_token\n logger.info(\"Authenticated successfully. Session token obtained.\")\n return\n\n raise last_error\n\n @staticmethod\n def _backoff(attempt: int) -> None:\n \"\"\"Sleep with exponential backoff between retry attempts.\"\"\"\n if attempt < MAX_RETRIES:\n delay = RETRY_BACKOFF * (2 ** (attempt - 1))\n logger.warning(\"Retrying in %ds...\", delay)\n time.sleep(delay)\n\n def __repr__(self) -> str:\n masked_key = f\"{self.api_key[:12]}...{self.api_key[-4:]}\" if len(self.api_key) > 16 else \"***\"\n return (\n f\"AuthClient(dashboard={self.dashboard_url!r}, \"\n f\"sandbox={self.sandbox_id!r}, key={masked_key})\"\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 4532}, "tests/test_desktop_views.py::40": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": ["Size"], "enclosing_function": "test_to_string_zero", "extracted_code": "# Source: src/windows_mcp/desktop/views.py\nclass Size:\n width: int\n height: int\n\n def to_string(self):\n return f\"({self.width},{self.height})\"", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 158}, "tests/test_filesystem_views.py::9": {"resolved_imports": ["src/windows_mcp/filesystem/views.py"], "used_names": ["format_size"], "enclosing_function": "test_bytes", "extracted_code": "# Source: src/windows_mcp/filesystem/views.py\ndef format_size(size_bytes: int) -> str:\n \"\"\"Format bytes into a human-readable string.\"\"\"\n if size_bytes < 1024:\n return f'{size_bytes} B'\n elif size_bytes < 1024 ** 2:\n return f'{size_bytes / 1024:.1f} KB'\n elif size_bytes < 1024 ** 3:\n return f'{size_bytes / (1024 ** 2):.1f} MB'\n else:\n return f'{size_bytes / (1024 ** 3):.1f} GB'", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 423}, "tests/test_tree_views.py::145": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": [], "enclosing_function": "test_to_row_with_base_index", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tree_views.py::27": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox"], "enclosing_function": "test_get_center_negative_coords", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1086}, "tests/test_auth_service.py::18": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthError"], "enclosing_function": "test_with_status_code", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nclass AuthError(Exception):\n \"\"\"Raised when authentication with the dashboard fails.\"\"\"\n\n def __init__(self, message: str, status_code: int | None = None):\n self.message = message\n self.status_code = status_code\n super().__init__(self.message)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 312}, "tests/test_tree_views.py::14": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": [], "enclosing_function": "test_get_center_standard", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_analytics.py::21": {"resolved_imports": ["src/windows_mcp/analytics.py"], "used_names": ["AsyncMock", "with_analytics"], "enclosing_function": "test_success_path", "extracted_code": "# Source: src/windows_mcp/analytics.py\ndef with_analytics(analytics_instance: Analytics | None, tool_name: str):\n \"\"\"\n Decorator to wrap tool functions with analytics tracking.\n \"\"\"\n\n def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:\n @wraps(func)\n async def wrapper(*args, **kwargs) -> T:\n start = time.time()\n\n # Capture client info from Context passed as argument\n client_data = {}\n try:\n ctx = next((arg for arg in args if isinstance(arg, Context)), None)\n if not ctx:\n ctx = next(\n (val for val in kwargs.values() if isinstance(val, Context)),\n None,\n )\n\n if (\n ctx\n and ctx.session\n and ctx.session.client_params\n and ctx.session.client_params.clientInfo\n ):\n info = ctx.session.client_params.clientInfo\n client_data[\"client_name\"] = info.name\n client_data[\"client_version\"] = info.version\n except Exception:\n pass\n\n try:\n if asyncio.iscoroutinefunction(func):\n result = await func(*args, **kwargs)\n else:\n # Run sync function in thread to avoid blocking loop\n result = await asyncio.to_thread(func, *args, **kwargs)\n\n duration_ms = int((time.time() - start) * 1000)\n\n if analytics_instance:\n await analytics_instance.track_tool(\n tool_name,\n {\"duration_ms\": duration_ms, \"success\": True, **client_data},\n )\n\n return result\n except Exception as error:\n duration_ms = int((time.time() - start) * 1000)\n if analytics_instance:\n await analytics_instance.track_error(\n error,\n {\n \"tool_name\": tool_name,\n \"duration_ms\": duration_ms,\n **client_data,\n },\n )\n raise error\n\n return wrapper\n\n return decorator", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2391}, "tests/test_desktop_views.py::19": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": ["Browser"], "enclosing_function": "test_has_process_unknown", "extracted_code": "# Source: src/windows_mcp/desktop/views.py\nclass Browser(Enum):\n CHROME = \"chrome\"\n EDGE = \"msedge\"\n FIREFOX = \"firefox\"\n\n @classmethod\n def has_process(cls, process_name: str) -> bool:\n if not hasattr(cls, \"_process_names\"):\n cls._process_names = {f\"{b.value}.exe\" for b in cls}\n return process_name.lower() in cls._process_names", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 370}, "tests/test_tree_views.py::150": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": [], "enclosing_function": "test_to_row_with_base_index", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tree_service.py::58": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": ["SimpleNamespace"], "enclosing_function": "test_partial_overlap", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_desktop_views.py::28": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": ["Status"], "enclosing_function": "test_enum_values", "extracted_code": "# Source: src/windows_mcp/desktop/views.py\nclass Status(Enum):\n MAXIMIZED = \"Maximized\"\n MINIMIZED = \"Minimized\"\n NORMAL = \"Normal\"\n HIDDEN = \"Hidden\"", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 162}, "tests/test_desktop_views.py::29": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": ["Status"], "enclosing_function": "test_enum_values", "extracted_code": "# Source: src/windows_mcp/desktop/views.py\nclass Status(Enum):\n MAXIMIZED = \"Maximized\"\n MINIMIZED = \"Minimized\"\n NORMAL = \"Normal\"\n HIDDEN = \"Hidden\"", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 162}, "tests/test_tree_views.py::20": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox"], "enclosing_function": "test_get_center_zero_size", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1086}, "tests/test_analytics.py::18": {"resolved_imports": ["src/windows_mcp/analytics.py"], "used_names": ["AsyncMock", "with_analytics"], "enclosing_function": "test_success_path", "extracted_code": "# Source: src/windows_mcp/analytics.py\ndef with_analytics(analytics_instance: Analytics | None, tool_name: str):\n \"\"\"\n Decorator to wrap tool functions with analytics tracking.\n \"\"\"\n\n def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:\n @wraps(func)\n async def wrapper(*args, **kwargs) -> T:\n start = time.time()\n\n # Capture client info from Context passed as argument\n client_data = {}\n try:\n ctx = next((arg for arg in args if isinstance(arg, Context)), None)\n if not ctx:\n ctx = next(\n (val for val in kwargs.values() if isinstance(val, Context)),\n None,\n )\n\n if (\n ctx\n and ctx.session\n and ctx.session.client_params\n and ctx.session.client_params.clientInfo\n ):\n info = ctx.session.client_params.clientInfo\n client_data[\"client_name\"] = info.name\n client_data[\"client_version\"] = info.version\n except Exception:\n pass\n\n try:\n if asyncio.iscoroutinefunction(func):\n result = await func(*args, **kwargs)\n else:\n # Run sync function in thread to avoid blocking loop\n result = await asyncio.to_thread(func, *args, **kwargs)\n\n duration_ms = int((time.time() - start) * 1000)\n\n if analytics_instance:\n await analytics_instance.track_tool(\n tool_name,\n {\"duration_ms\": duration_ms, \"success\": True, **client_data},\n )\n\n return result\n except Exception as error:\n duration_ms = int((time.time() - start) * 1000)\n if analytics_instance:\n await analytics_instance.track_error(\n error,\n {\n \"tool_name\": tool_name,\n \"duration_ms\": duration_ms,\n **client_data,\n },\n )\n raise error\n\n return wrapper\n\n return decorator", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2391}, "tests/test_filesystem_service.py::68": {"resolved_imports": ["src/windows_mcp/filesystem/service.py"], "used_names": ["copy_path"], "enclosing_function": "test_copy_file", "extracted_code": "# Source: src/windows_mcp/filesystem/service.py\ndef copy_path(source: str, destination: str, overwrite: bool = False) -> str:\n \"\"\"Copy a file or directory to a new location.\"\"\"\n src = Path(source).resolve()\n dst = Path(destination).resolve()\n\n if not src.exists():\n return f'Error: Source not found: {src}'\n\n if dst.exists() and not overwrite:\n return f'Error: Destination already exists: {dst}. Set overwrite=True to replace.'\n\n try:\n if src.is_file():\n dst.parent.mkdir(parents=True, exist_ok=True)\n shutil.copy2(str(src), str(dst))\n return f'Copied file: {src} -> {dst}'\n elif src.is_dir():\n if dst.exists() and overwrite:\n shutil.rmtree(str(dst))\n shutil.copytree(str(src), str(dst))\n return f'Copied directory: {src} -> {dst}'\n else:\n return f'Error: Unsupported file type: {src}'\n except PermissionError:\n return f'Error: Permission denied.'\n except Exception as e:\n return f'Error copying: {e}'", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1066}, "tests/test_tree_views.py::134": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox", "Center", "TreeElementNode"], "enclosing_function": "test_update_from_node", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2\n\nclass Center:\n x: int\n y: int\n\n def to_string(self) -> str:\n return f\"({self.x},{self.y})\"\n\nclass TreeElementNode:\n bounding_box: BoundingBox\n center: Center\n name: str = \"\"\n control_type: str = \"\"\n window_name: str = \"\"\n value: str = \"\"\n shortcut: str = \"\"\n xpath: str = \"\"\n is_focused: bool = False\n\n def update_from_node(self, node: \"TreeElementNode\"):\n self.name = node.name\n self.control_type = node.control_type\n self.window_name = node.window_name\n self.value = node.value\n self.shortcut = node.shortcut\n self.bounding_box = node.bounding_box\n self.center = node.center\n self.xpath = node.xpath\n self.is_focused = node.is_focused\n\n # Legacy method kept for compatibility if needed, but not used in new format\n def to_row(self, index: int):\n return [\n index,\n self.window_name,\n self.control_type,\n self.name,\n self.value,\n self.shortcut,\n self.center.to_string(),\n self.is_focused,\n ]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 2196}, "tests/test_filesystem_views.py::8": {"resolved_imports": ["src/windows_mcp/filesystem/views.py"], "used_names": ["format_size"], "enclosing_function": "test_bytes", "extracted_code": "# Source: src/windows_mcp/filesystem/views.py\ndef format_size(size_bytes: int) -> str:\n \"\"\"Format bytes into a human-readable string.\"\"\"\n if size_bytes < 1024:\n return f'{size_bytes} B'\n elif size_bytes < 1024 ** 2:\n return f'{size_bytes / 1024:.1f} KB'\n elif size_bytes < 1024 ** 3:\n return f'{size_bytes / (1024 ** 2):.1f} MB'\n else:\n return f'{size_bytes / (1024 ** 3):.1f} GB'", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 423}, "tests/test_tree_service.py::56": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": ["SimpleNamespace"], "enclosing_function": "test_partial_overlap", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_tree_views.py::47": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox", "SimpleNamespace"], "enclosing_function": "test_from_bounding_rectangle", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1086}, "tests/test_desktop_views.py::80": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": ["DesktopState"], "enclosing_function": "test_windows_to_string_empty", "extracted_code": "# Source: src/windows_mcp/desktop/views.py\nclass DesktopState:\n active_desktop: dict\n all_desktops: list[dict]\n active_window: Window | None\n windows: list[Window]\n screenshot: Image | None = None\n tree_state: TreeState | None = None\n\n def active_desktop_to_string(self):\n desktop_name = self.active_desktop.get(\"name\")\n headers = [\"Name\"]\n return tabulate([[desktop_name]], headers=headers, tablefmt=\"simple\")\n\n def desktops_to_string(self):\n headers = [\"Name\"]\n rows = [[desktop.get(\"name\")] for desktop in self.all_desktops]\n return tabulate(rows, headers=headers, tablefmt=\"simple\")\n\n def active_window_to_string(self):\n if not self.active_window:\n return \"No active window found\"\n headers = [\"Name\", \"Depth\", \"Status\", \"Width\", \"Height\", \"Handle\"]\n return tabulate([self.active_window.to_row()], headers=headers, tablefmt=\"simple\")\n\n def windows_to_string(self):\n if not self.windows:\n return \"No windows found\"\n headers = [\"Name\", \"Depth\", \"Status\", \"Width\", \"Height\", \"Handle\"]\n rows = [window.to_row() for window in self.windows]\n return tabulate(rows, headers=headers, tablefmt=\"simple\")", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1239}, "tests/test_tree_service.py::74": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": ["SimpleNamespace"], "enclosing_function": "test_screen_clamping", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_analytics.py::45": {"resolved_imports": ["src/windows_mcp/analytics.py"], "used_names": ["with_analytics"], "enclosing_function": "test_no_analytics_instance", "extracted_code": "# Source: src/windows_mcp/analytics.py\ndef with_analytics(analytics_instance: Analytics | None, tool_name: str):\n \"\"\"\n Decorator to wrap tool functions with analytics tracking.\n \"\"\"\n\n def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:\n @wraps(func)\n async def wrapper(*args, **kwargs) -> T:\n start = time.time()\n\n # Capture client info from Context passed as argument\n client_data = {}\n try:\n ctx = next((arg for arg in args if isinstance(arg, Context)), None)\n if not ctx:\n ctx = next(\n (val for val in kwargs.values() if isinstance(val, Context)),\n None,\n )\n\n if (\n ctx\n and ctx.session\n and ctx.session.client_params\n and ctx.session.client_params.clientInfo\n ):\n info = ctx.session.client_params.clientInfo\n client_data[\"client_name\"] = info.name\n client_data[\"client_version\"] = info.version\n except Exception:\n pass\n\n try:\n if asyncio.iscoroutinefunction(func):\n result = await func(*args, **kwargs)\n else:\n # Run sync function in thread to avoid blocking loop\n result = await asyncio.to_thread(func, *args, **kwargs)\n\n duration_ms = int((time.time() - start) * 1000)\n\n if analytics_instance:\n await analytics_instance.track_tool(\n tool_name,\n {\"duration_ms\": duration_ms, \"success\": True, **client_data},\n )\n\n return result\n except Exception as error:\n duration_ms = int((time.time() - start) * 1000)\n if analytics_instance:\n await analytics_instance.track_error(\n error,\n {\n \"tool_name\": tool_name,\n \"duration_ms\": duration_ms,\n **client_data,\n },\n )\n raise error\n\n return wrapper\n\n return decorator", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2391}, "tests/test_tree_views.py::44": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox", "SimpleNamespace"], "enclosing_function": "test_from_bounding_rectangle", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1086}, "tests/test_system_info.py::50": {"resolved_imports": ["src/windows_mcp/desktop/service.py"], "used_names": ["MagicMock", "SimpleNamespace", "builtins", "patch"], "enclosing_function": "test_returns_all_sections", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tree_views.py::131": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox", "Center", "TreeElementNode"], "enclosing_function": "test_update_from_node", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2\n\nclass Center:\n x: int\n y: int\n\n def to_string(self) -> str:\n return f\"({self.x},{self.y})\"\n\nclass TreeElementNode:\n bounding_box: BoundingBox\n center: Center\n name: str = \"\"\n control_type: str = \"\"\n window_name: str = \"\"\n value: str = \"\"\n shortcut: str = \"\"\n xpath: str = \"\"\n is_focused: bool = False\n\n def update_from_node(self, node: \"TreeElementNode\"):\n self.name = node.name\n self.control_type = node.control_type\n self.window_name = node.window_name\n self.value = node.value\n self.shortcut = node.shortcut\n self.bounding_box = node.bounding_box\n self.center = node.center\n self.xpath = node.xpath\n self.is_focused = node.is_focused\n\n # Legacy method kept for compatibility if needed, but not used in new format\n def to_row(self, index: int):\n return [\n index,\n self.window_name,\n self.control_type,\n self.name,\n self.value,\n self.shortcut,\n self.center.to_string(),\n self.is_focused,\n ]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 2196}, "tests/test_desktop_views.py::36": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": ["Size"], "enclosing_function": "test_to_string_standard", "extracted_code": "# Source: src/windows_mcp/desktop/views.py\nclass Size:\n width: int\n height: int\n\n def to_string(self):\n return f\"({self.width},{self.height})\"", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 158}, "tests/test_desktop_views.py::52": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": [], "enclosing_function": "test_active_desktop_to_string", "extracted_code": "", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_filesystem_service.py::58": {"resolved_imports": ["src/windows_mcp/filesystem/service.py"], "used_names": ["write_file"], "enclosing_function": "test_creates_parent_dirs", "extracted_code": "# Source: src/windows_mcp/filesystem/service.py\ndef write_file(path: str, content: str, append: bool = False, encoding: str = 'utf-8', create_parents: bool = True) -> str:\n \"\"\"Write or append text content to a file.\"\"\"\n file_path = Path(path).resolve()\n\n try:\n if create_parents:\n file_path.parent.mkdir(parents=True, exist_ok=True)\n\n mode = 'a' if append else 'w'\n with open(file_path, mode, encoding=encoding) as f:\n f.write(content)\n\n action = 'Appended to' if append else 'Written to'\n size = file_path.stat().st_size\n return f'{action} {file_path} ({size:,} bytes)'\n except PermissionError:\n return f'Error: Permission denied: {file_path}'\n except Exception as e:\n return f'Error writing file: {e}'", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 796}, "tests/test_tree_views.py::151": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": [], "enclosing_function": "test_to_row_with_base_index", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_auth_service.py::14": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthError"], "enclosing_function": "test_message", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nclass AuthError(Exception):\n \"\"\"Raised when authentication with the dashboard fails.\"\"\"\n\n def __init__(self, message: str, status_code: int | None = None):\n self.message = message\n self.status_code = status_code\n super().__init__(self.message)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 312}, "tests/test_analytics.py::32": {"resolved_imports": ["src/windows_mcp/analytics.py"], "used_names": ["AsyncMock", "pytest", "with_analytics"], "enclosing_function": "test_error_path", "extracted_code": "# Source: src/windows_mcp/analytics.py\ndef with_analytics(analytics_instance: Analytics | None, tool_name: str):\n \"\"\"\n Decorator to wrap tool functions with analytics tracking.\n \"\"\"\n\n def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:\n @wraps(func)\n async def wrapper(*args, **kwargs) -> T:\n start = time.time()\n\n # Capture client info from Context passed as argument\n client_data = {}\n try:\n ctx = next((arg for arg in args if isinstance(arg, Context)), None)\n if not ctx:\n ctx = next(\n (val for val in kwargs.values() if isinstance(val, Context)),\n None,\n )\n\n if (\n ctx\n and ctx.session\n and ctx.session.client_params\n and ctx.session.client_params.clientInfo\n ):\n info = ctx.session.client_params.clientInfo\n client_data[\"client_name\"] = info.name\n client_data[\"client_version\"] = info.version\n except Exception:\n pass\n\n try:\n if asyncio.iscoroutinefunction(func):\n result = await func(*args, **kwargs)\n else:\n # Run sync function in thread to avoid blocking loop\n result = await asyncio.to_thread(func, *args, **kwargs)\n\n duration_ms = int((time.time() - start) * 1000)\n\n if analytics_instance:\n await analytics_instance.track_tool(\n tool_name,\n {\"duration_ms\": duration_ms, \"success\": True, **client_data},\n )\n\n return result\n except Exception as error:\n duration_ms = int((time.time() - start) * 1000)\n if analytics_instance:\n await analytics_instance.track_error(\n error,\n {\n \"tool_name\": tool_name,\n \"duration_ms\": duration_ms,\n **client_data,\n },\n )\n raise error\n\n return wrapper\n\n return decorator", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2391}, "tests/test_auth_service.py::177": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthClient", "AuthError", "MAX_RETRIES", "RETRY_BACKOFF", "patch", "pytest", "requests"], "enclosing_function": "test_backoff_timing", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nMAX_RETRIES = 3\n\nRETRY_BACKOFF = 2\n\nclass AuthError(Exception):\n \"\"\"Raised when authentication with the dashboard fails.\"\"\"\n\n def __init__(self, message: str, status_code: int | None = None):\n self.message = message\n self.status_code = status_code\n super().__init__(self.message)\n\nclass AuthClient:\n \"\"\"\n Handles authentication between the MCP server (running on EC2)\n and the Windows-MCP Dashboard.\n\n Flow:\n 1. POST /api/user/auth with api_key + sandbox_id\n 2. Dashboard validates key, checks credits, resolves sandbox\n 3. Returns session_token for subsequent /api/mcp calls\n 4. ProxyClient uses Bearer <session_token> to connect\n \"\"\"\n\n def __init__(self, api_key: str, sandbox_id: str):\n self.dashboard_url = \"http://localhost:3000\"\n self.api_key = api_key\n self.sandbox_id = sandbox_id\n self._session_token: str | None = None\n\n @property\n def session_token(self) -> str | None:\n return self._session_token\n\n @property\n def proxy_url(self) -> str:\n \"\"\"The dashboard's MCP streamable-HTTP endpoint.\"\"\"\n return f\"{self.dashboard_url}/api/mcp\"\n\n @property\n def proxy_headers(self) -> dict[str, str]:\n \"\"\"Headers for ProxyClient with Bearer auth.\"\"\"\n if not self._session_token:\n raise AuthError(\"Not authenticated. Call authenticate() first.\")\n return {\"Authorization\": f\"Bearer {self._session_token}\"}\n\n def authenticate(self) -> None:\n \"\"\"\n Authenticate with the dashboard and obtain a session token.\n Retries up to MAX_RETRIES times on transient failures.\n\n Raises:\n AuthError: If authentication fails after all retries.\n \"\"\"\n url = f\"{self.dashboard_url}/api/user/auth\"\n payload = {\n \"api_key\": self.api_key,\n \"sandbox_id\": self.sandbox_id,\n }\n\n last_error: AuthError | None = None\n\n for attempt in range(1, MAX_RETRIES + 1):\n logger.info(\"Authenticating with dashboard at %s (attempt %d/%d)\", url, attempt, MAX_RETRIES)\n\n try:\n response = requests.post(url, json=payload, timeout=30)\n except requests.ConnectionError:\n last_error = AuthError(\n f\"Cannot reach dashboard at {self.dashboard_url}. \"\n \"Check DASHBOARD_URL and network connectivity.\"\n )\n self._backoff(attempt)\n continue\n except requests.Timeout:\n last_error = AuthError(\"Dashboard authentication request timed out.\")\n self._backoff(attempt)\n continue\n except requests.RequestException as e:\n last_error = AuthError(f\"Request failed: {e}\")\n self._backoff(attempt)\n continue\n\n try:\n data = response.json()\n except (ValueError, requests.JSONDecodeError):\n last_error = AuthError(\n f\"Dashboard returned non-JSON response (HTTP {response.status_code}).\"\n )\n self._backoff(attempt)\n continue\n\n if response.status_code != 200:\n detail = data.get(\"detail\", \"Unknown error\")\n logger.error(\"Authentication failed [%d]: %s\", response.status_code, detail)\n # Don't retry on client errors (4xx) — these won't resolve themselves\n if 400 <= response.status_code < 500:\n raise AuthError(detail, status_code=response.status_code)\n last_error = AuthError(detail, status_code=response.status_code)\n self._backoff(attempt)\n continue\n\n session_token = data.get(\"session_token\")\n if not session_token:\n raise AuthError(\n \"Dashboard returned success but no session_token. \"\n \"Ensure the dashboard is up to date.\"\n )\n\n self._session_token = session_token\n logger.info(\"Authenticated successfully. Session token obtained.\")\n return\n\n raise last_error\n\n @staticmethod\n def _backoff(attempt: int) -> None:\n \"\"\"Sleep with exponential backoff between retry attempts.\"\"\"\n if attempt < MAX_RETRIES:\n delay = RETRY_BACKOFF * (2 ** (attempt - 1))\n logger.warning(\"Retrying in %ds...\", delay)\n time.sleep(delay)\n\n def __repr__(self) -> str:\n masked_key = f\"{self.api_key[:12]}...{self.api_key[-4:]}\" if len(self.api_key) > 16 else \"***\"\n return (\n f\"AuthClient(dashboard={self.dashboard_url!r}, \"\n f\"sandbox={self.sandbox_id!r}, key={masked_key})\"\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 4840}, "tests/test_tree_views.py::15": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": [], "enclosing_function": "test_get_center_standard", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_auth_service.py::172": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthClient", "AuthError", "MAX_RETRIES", "RETRY_BACKOFF", "patch", "pytest", "requests"], "enclosing_function": "test_backoff_timing", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nMAX_RETRIES = 3\n\nRETRY_BACKOFF = 2\n\nclass AuthError(Exception):\n \"\"\"Raised when authentication with the dashboard fails.\"\"\"\n\n def __init__(self, message: str, status_code: int | None = None):\n self.message = message\n self.status_code = status_code\n super().__init__(self.message)\n\nclass AuthClient:\n \"\"\"\n Handles authentication between the MCP server (running on EC2)\n and the Windows-MCP Dashboard.\n\n Flow:\n 1. POST /api/user/auth with api_key + sandbox_id\n 2. Dashboard validates key, checks credits, resolves sandbox\n 3. Returns session_token for subsequent /api/mcp calls\n 4. ProxyClient uses Bearer <session_token> to connect\n \"\"\"\n\n def __init__(self, api_key: str, sandbox_id: str):\n self.dashboard_url = \"http://localhost:3000\"\n self.api_key = api_key\n self.sandbox_id = sandbox_id\n self._session_token: str | None = None\n\n @property\n def session_token(self) -> str | None:\n return self._session_token\n\n @property\n def proxy_url(self) -> str:\n \"\"\"The dashboard's MCP streamable-HTTP endpoint.\"\"\"\n return f\"{self.dashboard_url}/api/mcp\"\n\n @property\n def proxy_headers(self) -> dict[str, str]:\n \"\"\"Headers for ProxyClient with Bearer auth.\"\"\"\n if not self._session_token:\n raise AuthError(\"Not authenticated. Call authenticate() first.\")\n return {\"Authorization\": f\"Bearer {self._session_token}\"}\n\n def authenticate(self) -> None:\n \"\"\"\n Authenticate with the dashboard and obtain a session token.\n Retries up to MAX_RETRIES times on transient failures.\n\n Raises:\n AuthError: If authentication fails after all retries.\n \"\"\"\n url = f\"{self.dashboard_url}/api/user/auth\"\n payload = {\n \"api_key\": self.api_key,\n \"sandbox_id\": self.sandbox_id,\n }\n\n last_error: AuthError | None = None\n\n for attempt in range(1, MAX_RETRIES + 1):\n logger.info(\"Authenticating with dashboard at %s (attempt %d/%d)\", url, attempt, MAX_RETRIES)\n\n try:\n response = requests.post(url, json=payload, timeout=30)\n except requests.ConnectionError:\n last_error = AuthError(\n f\"Cannot reach dashboard at {self.dashboard_url}. \"\n \"Check DASHBOARD_URL and network connectivity.\"\n )\n self._backoff(attempt)\n continue\n except requests.Timeout:\n last_error = AuthError(\"Dashboard authentication request timed out.\")\n self._backoff(attempt)\n continue\n except requests.RequestException as e:\n last_error = AuthError(f\"Request failed: {e}\")\n self._backoff(attempt)\n continue\n\n try:\n data = response.json()\n except (ValueError, requests.JSONDecodeError):\n last_error = AuthError(\n f\"Dashboard returned non-JSON response (HTTP {response.status_code}).\"\n )\n self._backoff(attempt)\n continue\n\n if response.status_code != 200:\n detail = data.get(\"detail\", \"Unknown error\")\n logger.error(\"Authentication failed [%d]: %s\", response.status_code, detail)\n # Don't retry on client errors (4xx) — these won't resolve themselves\n if 400 <= response.status_code < 500:\n raise AuthError(detail, status_code=response.status_code)\n last_error = AuthError(detail, status_code=response.status_code)\n self._backoff(attempt)\n continue\n\n session_token = data.get(\"session_token\")\n if not session_token:\n raise AuthError(\n \"Dashboard returned success but no session_token. \"\n \"Ensure the dashboard is up to date.\"\n )\n\n self._session_token = session_token\n logger.info(\"Authenticated successfully. Session token obtained.\")\n return\n\n raise last_error\n\n @staticmethod\n def _backoff(attempt: int) -> None:\n \"\"\"Sleep with exponential backoff between retry attempts.\"\"\"\n if attempt < MAX_RETRIES:\n delay = RETRY_BACKOFF * (2 ** (attempt - 1))\n logger.warning(\"Retrying in %ds...\", delay)\n time.sleep(delay)\n\n def __repr__(self) -> str:\n masked_key = f\"{self.api_key[:12]}...{self.api_key[-4:]}\" if len(self.api_key) > 16 else \"***\"\n return (\n f\"AuthClient(dashboard={self.dashboard_url!r}, \"\n f\"sandbox={self.sandbox_id!r}, key={masked_key})\"\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 4840}, "tests/test_auth_service.py::164": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthClient", "MagicMock", "patch", "requests"], "enclosing_function": "test_retry_then_success", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nclass AuthClient:\n \"\"\"\n Handles authentication between the MCP server (running on EC2)\n and the Windows-MCP Dashboard.\n\n Flow:\n 1. POST /api/user/auth with api_key + sandbox_id\n 2. Dashboard validates key, checks credits, resolves sandbox\n 3. Returns session_token for subsequent /api/mcp calls\n 4. ProxyClient uses Bearer <session_token> to connect\n \"\"\"\n\n def __init__(self, api_key: str, sandbox_id: str):\n self.dashboard_url = \"http://localhost:3000\"\n self.api_key = api_key\n self.sandbox_id = sandbox_id\n self._session_token: str | None = None\n\n @property\n def session_token(self) -> str | None:\n return self._session_token\n\n @property\n def proxy_url(self) -> str:\n \"\"\"The dashboard's MCP streamable-HTTP endpoint.\"\"\"\n return f\"{self.dashboard_url}/api/mcp\"\n\n @property\n def proxy_headers(self) -> dict[str, str]:\n \"\"\"Headers for ProxyClient with Bearer auth.\"\"\"\n if not self._session_token:\n raise AuthError(\"Not authenticated. Call authenticate() first.\")\n return {\"Authorization\": f\"Bearer {self._session_token}\"}\n\n def authenticate(self) -> None:\n \"\"\"\n Authenticate with the dashboard and obtain a session token.\n Retries up to MAX_RETRIES times on transient failures.\n\n Raises:\n AuthError: If authentication fails after all retries.\n \"\"\"\n url = f\"{self.dashboard_url}/api/user/auth\"\n payload = {\n \"api_key\": self.api_key,\n \"sandbox_id\": self.sandbox_id,\n }\n\n last_error: AuthError | None = None\n\n for attempt in range(1, MAX_RETRIES + 1):\n logger.info(\"Authenticating with dashboard at %s (attempt %d/%d)\", url, attempt, MAX_RETRIES)\n\n try:\n response = requests.post(url, json=payload, timeout=30)\n except requests.ConnectionError:\n last_error = AuthError(\n f\"Cannot reach dashboard at {self.dashboard_url}. \"\n \"Check DASHBOARD_URL and network connectivity.\"\n )\n self._backoff(attempt)\n continue\n except requests.Timeout:\n last_error = AuthError(\"Dashboard authentication request timed out.\")\n self._backoff(attempt)\n continue\n except requests.RequestException as e:\n last_error = AuthError(f\"Request failed: {e}\")\n self._backoff(attempt)\n continue\n\n try:\n data = response.json()\n except (ValueError, requests.JSONDecodeError):\n last_error = AuthError(\n f\"Dashboard returned non-JSON response (HTTP {response.status_code}).\"\n )\n self._backoff(attempt)\n continue\n\n if response.status_code != 200:\n detail = data.get(\"detail\", \"Unknown error\")\n logger.error(\"Authentication failed [%d]: %s\", response.status_code, detail)\n # Don't retry on client errors (4xx) — these won't resolve themselves\n if 400 <= response.status_code < 500:\n raise AuthError(detail, status_code=response.status_code)\n last_error = AuthError(detail, status_code=response.status_code)\n self._backoff(attempt)\n continue\n\n session_token = data.get(\"session_token\")\n if not session_token:\n raise AuthError(\n \"Dashboard returned success but no session_token. \"\n \"Ensure the dashboard is up to date.\"\n )\n\n self._session_token = session_token\n logger.info(\"Authenticated successfully. Session token obtained.\")\n return\n\n raise last_error\n\n @staticmethod\n def _backoff(attempt: int) -> None:\n \"\"\"Sleep with exponential backoff between retry attempts.\"\"\"\n if attempt < MAX_RETRIES:\n delay = RETRY_BACKOFF * (2 ** (attempt - 1))\n logger.warning(\"Retrying in %ds...\", delay)\n time.sleep(delay)\n\n def __repr__(self) -> str:\n masked_key = f\"{self.api_key[:12]}...{self.api_key[-4:]}\" if len(self.api_key) > 16 else \"***\"\n return (\n f\"AuthClient(dashboard={self.dashboard_url!r}, \"\n f\"sandbox={self.sandbox_id!r}, key={masked_key})\"\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 4532}, "tests/test_tree_views.py::137": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox", "Center", "TreeElementNode"], "enclosing_function": "test_update_from_node", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2\n\nclass Center:\n x: int\n y: int\n\n def to_string(self) -> str:\n return f\"({self.x},{self.y})\"\n\nclass TreeElementNode:\n bounding_box: BoundingBox\n center: Center\n name: str = \"\"\n control_type: str = \"\"\n window_name: str = \"\"\n value: str = \"\"\n shortcut: str = \"\"\n xpath: str = \"\"\n is_focused: bool = False\n\n def update_from_node(self, node: \"TreeElementNode\"):\n self.name = node.name\n self.control_type = node.control_type\n self.window_name = node.window_name\n self.value = node.value\n self.shortcut = node.shortcut\n self.bounding_box = node.bounding_box\n self.center = node.center\n self.xpath = node.xpath\n self.is_focused = node.is_focused\n\n # Legacy method kept for compatibility if needed, but not used in new format\n def to_row(self, index: int):\n return [\n index,\n self.window_name,\n self.control_type,\n self.name,\n self.value,\n self.shortcut,\n self.center.to_string(),\n self.is_focused,\n ]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 2196}, "tests/test_analytics.py::22": {"resolved_imports": ["src/windows_mcp/analytics.py"], "used_names": ["AsyncMock", "with_analytics"], "enclosing_function": "test_success_path", "extracted_code": "# Source: src/windows_mcp/analytics.py\ndef with_analytics(analytics_instance: Analytics | None, tool_name: str):\n \"\"\"\n Decorator to wrap tool functions with analytics tracking.\n \"\"\"\n\n def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:\n @wraps(func)\n async def wrapper(*args, **kwargs) -> T:\n start = time.time()\n\n # Capture client info from Context passed as argument\n client_data = {}\n try:\n ctx = next((arg for arg in args if isinstance(arg, Context)), None)\n if not ctx:\n ctx = next(\n (val for val in kwargs.values() if isinstance(val, Context)),\n None,\n )\n\n if (\n ctx\n and ctx.session\n and ctx.session.client_params\n and ctx.session.client_params.clientInfo\n ):\n info = ctx.session.client_params.clientInfo\n client_data[\"client_name\"] = info.name\n client_data[\"client_version\"] = info.version\n except Exception:\n pass\n\n try:\n if asyncio.iscoroutinefunction(func):\n result = await func(*args, **kwargs)\n else:\n # Run sync function in thread to avoid blocking loop\n result = await asyncio.to_thread(func, *args, **kwargs)\n\n duration_ms = int((time.time() - start) * 1000)\n\n if analytics_instance:\n await analytics_instance.track_tool(\n tool_name,\n {\"duration_ms\": duration_ms, \"success\": True, **client_data},\n )\n\n return result\n except Exception as error:\n duration_ms = int((time.time() - start) * 1000)\n if analytics_instance:\n await analytics_instance.track_error(\n error,\n {\n \"tool_name\": tool_name,\n \"duration_ms\": duration_ms,\n **client_data,\n },\n )\n raise error\n\n return wrapper\n\n return decorator", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2391}, "tests/test_filesystem_views.py::109": {"resolved_imports": ["src/windows_mcp/filesystem/views.py"], "used_names": ["Directory"], "enclosing_function": "test_relative_path_override", "extracted_code": "# Source: src/windows_mcp/filesystem/views.py\nclass Directory:\n name: str\n is_dir: bool\n size: int = 0\n\n def to_string(self, relative_path: str | None = None) -> str:\n entry_type = 'DIR ' if self.is_dir else 'FILE'\n size_str = format_size(self.size) if not self.is_dir else ''\n display = relative_path or self.name\n return f' [{entry_type}] {display} {size_str}'", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 404}, "tests/test_tree_views.py::26": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox"], "enclosing_function": "test_get_center_negative_coords", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1086}, "tests/test_tree_service.py::45": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": ["SimpleNamespace"], "enclosing_function": "test_full_overlap", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_analytics.py::58": {"resolved_imports": ["src/windows_mcp/analytics.py"], "used_names": ["AsyncMock", "asyncio", "with_analytics"], "enclosing_function": "test_duration_measurement", "extracted_code": "# Source: src/windows_mcp/analytics.py\ndef with_analytics(analytics_instance: Analytics | None, tool_name: str):\n \"\"\"\n Decorator to wrap tool functions with analytics tracking.\n \"\"\"\n\n def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:\n @wraps(func)\n async def wrapper(*args, **kwargs) -> T:\n start = time.time()\n\n # Capture client info from Context passed as argument\n client_data = {}\n try:\n ctx = next((arg for arg in args if isinstance(arg, Context)), None)\n if not ctx:\n ctx = next(\n (val for val in kwargs.values() if isinstance(val, Context)),\n None,\n )\n\n if (\n ctx\n and ctx.session\n and ctx.session.client_params\n and ctx.session.client_params.clientInfo\n ):\n info = ctx.session.client_params.clientInfo\n client_data[\"client_name\"] = info.name\n client_data[\"client_version\"] = info.version\n except Exception:\n pass\n\n try:\n if asyncio.iscoroutinefunction(func):\n result = await func(*args, **kwargs)\n else:\n # Run sync function in thread to avoid blocking loop\n result = await asyncio.to_thread(func, *args, **kwargs)\n\n duration_ms = int((time.time() - start) * 1000)\n\n if analytics_instance:\n await analytics_instance.track_tool(\n tool_name,\n {\"duration_ms\": duration_ms, \"success\": True, **client_data},\n )\n\n return result\n except Exception as error:\n duration_ms = int((time.time() - start) * 1000)\n if analytics_instance:\n await analytics_instance.track_error(\n error,\n {\n \"tool_name\": tool_name,\n \"duration_ms\": duration_ms,\n **client_data,\n },\n )\n raise error\n\n return wrapper\n\n return decorator", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2391}, "tests/test_desktop_views.py::6": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": ["Browser"], "enclosing_function": "test_has_process_chrome", "extracted_code": "# Source: src/windows_mcp/desktop/views.py\nclass Browser(Enum):\n CHROME = \"chrome\"\n EDGE = \"msedge\"\n FIREFOX = \"firefox\"\n\n @classmethod\n def has_process(cls, process_name: str) -> bool:\n if not hasattr(cls, \"_process_names\"):\n cls._process_names = {f\"{b.value}.exe\" for b in cls}\n return process_name.lower() in cls._process_names", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 370}, "tests/test_tree_service.py::22": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": [], "enclosing_function": "test_shell_traywnd", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_registry.py::55": {"resolved_imports": ["src/windows_mcp/desktop/service.py"], "used_names": [], "enclosing_function": "test_command_uses_ps_quote", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_filesystem_views.py::31": {"resolved_imports": ["src/windows_mcp/filesystem/views.py"], "used_names": ["MAX_RESULTS"], "enclosing_function": "test_max_results", "extracted_code": "# Source: src/windows_mcp/filesystem/views.py\nMAX_RESULTS = 500", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 63}, "tests/test_tree_service.py::43": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": ["SimpleNamespace"], "enclosing_function": "test_full_overlap", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_tree_views.py::135": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox", "Center", "TreeElementNode"], "enclosing_function": "test_update_from_node", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2\n\nclass Center:\n x: int\n y: int\n\n def to_string(self) -> str:\n return f\"({self.x},{self.y})\"\n\nclass TreeElementNode:\n bounding_box: BoundingBox\n center: Center\n name: str = \"\"\n control_type: str = \"\"\n window_name: str = \"\"\n value: str = \"\"\n shortcut: str = \"\"\n xpath: str = \"\"\n is_focused: bool = False\n\n def update_from_node(self, node: \"TreeElementNode\"):\n self.name = node.name\n self.control_type = node.control_type\n self.window_name = node.window_name\n self.value = node.value\n self.shortcut = node.shortcut\n self.bounding_box = node.bounding_box\n self.center = node.center\n self.xpath = node.xpath\n self.is_focused = node.is_focused\n\n # Legacy method kept for compatibility if needed, but not used in new format\n def to_row(self, index: int):\n return [\n index,\n self.window_name,\n self.control_type,\n self.name,\n self.value,\n self.shortcut,\n self.center.to_string(),\n self.is_focused,\n ]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 2196}, "tests/test_tree_service.py::77": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": ["SimpleNamespace"], "enclosing_function": "test_screen_clamping", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_filesystem_views.py::113": {"resolved_imports": ["src/windows_mcp/filesystem/views.py"], "used_names": ["Directory"], "enclosing_function": "test_default_size_zero", "extracted_code": "# Source: src/windows_mcp/filesystem/views.py\nclass Directory:\n name: str\n is_dir: bool\n size: int = 0\n\n def to_string(self, relative_path: str | None = None) -> str:\n entry_type = 'DIR ' if self.is_dir else 'FILE'\n size_str = format_size(self.size) if not self.is_dir else ''\n display = relative_path or self.name\n return f' [{entry_type}] {display} {size_str}'", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 404}, "tests/test_auth_service.py::12": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthError"], "enclosing_function": "test_message", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nclass AuthError(Exception):\n \"\"\"Raised when authentication with the dashboard fails.\"\"\"\n\n def __init__(self, message: str, status_code: int | None = None):\n self.message = message\n self.status_code = status_code\n super().__init__(self.message)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 312}, "tests/test_auth_service.py::133": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthClient", "AuthError", "MAX_RETRIES", "MagicMock", "patch", "pytest"], "enclosing_function": "test_5xx_retries", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nMAX_RETRIES = 3\n\nclass AuthError(Exception):\n \"\"\"Raised when authentication with the dashboard fails.\"\"\"\n\n def __init__(self, message: str, status_code: int | None = None):\n self.message = message\n self.status_code = status_code\n super().__init__(self.message)\n\nclass AuthClient:\n \"\"\"\n Handles authentication between the MCP server (running on EC2)\n and the Windows-MCP Dashboard.\n\n Flow:\n 1. POST /api/user/auth with api_key + sandbox_id\n 2. Dashboard validates key, checks credits, resolves sandbox\n 3. Returns session_token for subsequent /api/mcp calls\n 4. ProxyClient uses Bearer <session_token> to connect\n \"\"\"\n\n def __init__(self, api_key: str, sandbox_id: str):\n self.dashboard_url = \"http://localhost:3000\"\n self.api_key = api_key\n self.sandbox_id = sandbox_id\n self._session_token: str | None = None\n\n @property\n def session_token(self) -> str | None:\n return self._session_token\n\n @property\n def proxy_url(self) -> str:\n \"\"\"The dashboard's MCP streamable-HTTP endpoint.\"\"\"\n return f\"{self.dashboard_url}/api/mcp\"\n\n @property\n def proxy_headers(self) -> dict[str, str]:\n \"\"\"Headers for ProxyClient with Bearer auth.\"\"\"\n if not self._session_token:\n raise AuthError(\"Not authenticated. Call authenticate() first.\")\n return {\"Authorization\": f\"Bearer {self._session_token}\"}\n\n def authenticate(self) -> None:\n \"\"\"\n Authenticate with the dashboard and obtain a session token.\n Retries up to MAX_RETRIES times on transient failures.\n\n Raises:\n AuthError: If authentication fails after all retries.\n \"\"\"\n url = f\"{self.dashboard_url}/api/user/auth\"\n payload = {\n \"api_key\": self.api_key,\n \"sandbox_id\": self.sandbox_id,\n }\n\n last_error: AuthError | None = None\n\n for attempt in range(1, MAX_RETRIES + 1):\n logger.info(\"Authenticating with dashboard at %s (attempt %d/%d)\", url, attempt, MAX_RETRIES)\n\n try:\n response = requests.post(url, json=payload, timeout=30)\n except requests.ConnectionError:\n last_error = AuthError(\n f\"Cannot reach dashboard at {self.dashboard_url}. \"\n \"Check DASHBOARD_URL and network connectivity.\"\n )\n self._backoff(attempt)\n continue\n except requests.Timeout:\n last_error = AuthError(\"Dashboard authentication request timed out.\")\n self._backoff(attempt)\n continue\n except requests.RequestException as e:\n last_error = AuthError(f\"Request failed: {e}\")\n self._backoff(attempt)\n continue\n\n try:\n data = response.json()\n except (ValueError, requests.JSONDecodeError):\n last_error = AuthError(\n f\"Dashboard returned non-JSON response (HTTP {response.status_code}).\"\n )\n self._backoff(attempt)\n continue\n\n if response.status_code != 200:\n detail = data.get(\"detail\", \"Unknown error\")\n logger.error(\"Authentication failed [%d]: %s\", response.status_code, detail)\n # Don't retry on client errors (4xx) — these won't resolve themselves\n if 400 <= response.status_code < 500:\n raise AuthError(detail, status_code=response.status_code)\n last_error = AuthError(detail, status_code=response.status_code)\n self._backoff(attempt)\n continue\n\n session_token = data.get(\"session_token\")\n if not session_token:\n raise AuthError(\n \"Dashboard returned success but no session_token. \"\n \"Ensure the dashboard is up to date.\"\n )\n\n self._session_token = session_token\n logger.info(\"Authenticated successfully. Session token obtained.\")\n return\n\n raise last_error\n\n @staticmethod\n def _backoff(attempt: int) -> None:\n \"\"\"Sleep with exponential backoff between retry attempts.\"\"\"\n if attempt < MAX_RETRIES:\n delay = RETRY_BACKOFF * (2 ** (attempt - 1))\n logger.warning(\"Retrying in %ds...\", delay)\n time.sleep(delay)\n\n def __repr__(self) -> str:\n masked_key = f\"{self.api_key[:12]}...{self.api_key[-4:]}\" if len(self.api_key) > 16 else \"***\"\n return (\n f\"AuthClient(dashboard={self.dashboard_url!r}, \"\n f\"sandbox={self.sandbox_id!r}, key={masked_key})\"\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 4821}, "tests/test_auth_service.py::176": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthClient", "AuthError", "MAX_RETRIES", "RETRY_BACKOFF", "patch", "pytest", "requests"], "enclosing_function": "test_backoff_timing", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nMAX_RETRIES = 3\n\nRETRY_BACKOFF = 2\n\nclass AuthError(Exception):\n \"\"\"Raised when authentication with the dashboard fails.\"\"\"\n\n def __init__(self, message: str, status_code: int | None = None):\n self.message = message\n self.status_code = status_code\n super().__init__(self.message)\n\nclass AuthClient:\n \"\"\"\n Handles authentication between the MCP server (running on EC2)\n and the Windows-MCP Dashboard.\n\n Flow:\n 1. POST /api/user/auth with api_key + sandbox_id\n 2. Dashboard validates key, checks credits, resolves sandbox\n 3. Returns session_token for subsequent /api/mcp calls\n 4. ProxyClient uses Bearer <session_token> to connect\n \"\"\"\n\n def __init__(self, api_key: str, sandbox_id: str):\n self.dashboard_url = \"http://localhost:3000\"\n self.api_key = api_key\n self.sandbox_id = sandbox_id\n self._session_token: str | None = None\n\n @property\n def session_token(self) -> str | None:\n return self._session_token\n\n @property\n def proxy_url(self) -> str:\n \"\"\"The dashboard's MCP streamable-HTTP endpoint.\"\"\"\n return f\"{self.dashboard_url}/api/mcp\"\n\n @property\n def proxy_headers(self) -> dict[str, str]:\n \"\"\"Headers for ProxyClient with Bearer auth.\"\"\"\n if not self._session_token:\n raise AuthError(\"Not authenticated. Call authenticate() first.\")\n return {\"Authorization\": f\"Bearer {self._session_token}\"}\n\n def authenticate(self) -> None:\n \"\"\"\n Authenticate with the dashboard and obtain a session token.\n Retries up to MAX_RETRIES times on transient failures.\n\n Raises:\n AuthError: If authentication fails after all retries.\n \"\"\"\n url = f\"{self.dashboard_url}/api/user/auth\"\n payload = {\n \"api_key\": self.api_key,\n \"sandbox_id\": self.sandbox_id,\n }\n\n last_error: AuthError | None = None\n\n for attempt in range(1, MAX_RETRIES + 1):\n logger.info(\"Authenticating with dashboard at %s (attempt %d/%d)\", url, attempt, MAX_RETRIES)\n\n try:\n response = requests.post(url, json=payload, timeout=30)\n except requests.ConnectionError:\n last_error = AuthError(\n f\"Cannot reach dashboard at {self.dashboard_url}. \"\n \"Check DASHBOARD_URL and network connectivity.\"\n )\n self._backoff(attempt)\n continue\n except requests.Timeout:\n last_error = AuthError(\"Dashboard authentication request timed out.\")\n self._backoff(attempt)\n continue\n except requests.RequestException as e:\n last_error = AuthError(f\"Request failed: {e}\")\n self._backoff(attempt)\n continue\n\n try:\n data = response.json()\n except (ValueError, requests.JSONDecodeError):\n last_error = AuthError(\n f\"Dashboard returned non-JSON response (HTTP {response.status_code}).\"\n )\n self._backoff(attempt)\n continue\n\n if response.status_code != 200:\n detail = data.get(\"detail\", \"Unknown error\")\n logger.error(\"Authentication failed [%d]: %s\", response.status_code, detail)\n # Don't retry on client errors (4xx) — these won't resolve themselves\n if 400 <= response.status_code < 500:\n raise AuthError(detail, status_code=response.status_code)\n last_error = AuthError(detail, status_code=response.status_code)\n self._backoff(attempt)\n continue\n\n session_token = data.get(\"session_token\")\n if not session_token:\n raise AuthError(\n \"Dashboard returned success but no session_token. \"\n \"Ensure the dashboard is up to date.\"\n )\n\n self._session_token = session_token\n logger.info(\"Authenticated successfully. Session token obtained.\")\n return\n\n raise last_error\n\n @staticmethod\n def _backoff(attempt: int) -> None:\n \"\"\"Sleep with exponential backoff between retry attempts.\"\"\"\n if attempt < MAX_RETRIES:\n delay = RETRY_BACKOFF * (2 ** (attempt - 1))\n logger.warning(\"Retrying in %ds...\", delay)\n time.sleep(delay)\n\n def __repr__(self) -> str:\n masked_key = f\"{self.api_key[:12]}...{self.api_key[-4:]}\" if len(self.api_key) > 16 else \"***\"\n return (\n f\"AuthClient(dashboard={self.dashboard_url!r}, \"\n f\"sandbox={self.sandbox_id!r}, key={masked_key})\"\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 4840}, "tests/test_analytics.py::23": {"resolved_imports": ["src/windows_mcp/analytics.py"], "used_names": ["AsyncMock", "with_analytics"], "enclosing_function": "test_success_path", "extracted_code": "# Source: src/windows_mcp/analytics.py\ndef with_analytics(analytics_instance: Analytics | None, tool_name: str):\n \"\"\"\n Decorator to wrap tool functions with analytics tracking.\n \"\"\"\n\n def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:\n @wraps(func)\n async def wrapper(*args, **kwargs) -> T:\n start = time.time()\n\n # Capture client info from Context passed as argument\n client_data = {}\n try:\n ctx = next((arg for arg in args if isinstance(arg, Context)), None)\n if not ctx:\n ctx = next(\n (val for val in kwargs.values() if isinstance(val, Context)),\n None,\n )\n\n if (\n ctx\n and ctx.session\n and ctx.session.client_params\n and ctx.session.client_params.clientInfo\n ):\n info = ctx.session.client_params.clientInfo\n client_data[\"client_name\"] = info.name\n client_data[\"client_version\"] = info.version\n except Exception:\n pass\n\n try:\n if asyncio.iscoroutinefunction(func):\n result = await func(*args, **kwargs)\n else:\n # Run sync function in thread to avoid blocking loop\n result = await asyncio.to_thread(func, *args, **kwargs)\n\n duration_ms = int((time.time() - start) * 1000)\n\n if analytics_instance:\n await analytics_instance.track_tool(\n tool_name,\n {\"duration_ms\": duration_ms, \"success\": True, **client_data},\n )\n\n return result\n except Exception as error:\n duration_ms = int((time.time() - start) * 1000)\n if analytics_instance:\n await analytics_instance.track_error(\n error,\n {\n \"tool_name\": tool_name,\n \"duration_ms\": duration_ms,\n **client_data,\n },\n )\n raise error\n\n return wrapper\n\n return decorator", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2391}, "tests/test_auth_service.py::66": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthClient", "MagicMock", "patch"], "enclosing_function": "test_success", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nclass AuthClient:\n \"\"\"\n Handles authentication between the MCP server (running on EC2)\n and the Windows-MCP Dashboard.\n\n Flow:\n 1. POST /api/user/auth with api_key + sandbox_id\n 2. Dashboard validates key, checks credits, resolves sandbox\n 3. Returns session_token for subsequent /api/mcp calls\n 4. ProxyClient uses Bearer <session_token> to connect\n \"\"\"\n\n def __init__(self, api_key: str, sandbox_id: str):\n self.dashboard_url = \"http://localhost:3000\"\n self.api_key = api_key\n self.sandbox_id = sandbox_id\n self._session_token: str | None = None\n\n @property\n def session_token(self) -> str | None:\n return self._session_token\n\n @property\n def proxy_url(self) -> str:\n \"\"\"The dashboard's MCP streamable-HTTP endpoint.\"\"\"\n return f\"{self.dashboard_url}/api/mcp\"\n\n @property\n def proxy_headers(self) -> dict[str, str]:\n \"\"\"Headers for ProxyClient with Bearer auth.\"\"\"\n if not self._session_token:\n raise AuthError(\"Not authenticated. Call authenticate() first.\")\n return {\"Authorization\": f\"Bearer {self._session_token}\"}\n\n def authenticate(self) -> None:\n \"\"\"\n Authenticate with the dashboard and obtain a session token.\n Retries up to MAX_RETRIES times on transient failures.\n\n Raises:\n AuthError: If authentication fails after all retries.\n \"\"\"\n url = f\"{self.dashboard_url}/api/user/auth\"\n payload = {\n \"api_key\": self.api_key,\n \"sandbox_id\": self.sandbox_id,\n }\n\n last_error: AuthError | None = None\n\n for attempt in range(1, MAX_RETRIES + 1):\n logger.info(\"Authenticating with dashboard at %s (attempt %d/%d)\", url, attempt, MAX_RETRIES)\n\n try:\n response = requests.post(url, json=payload, timeout=30)\n except requests.ConnectionError:\n last_error = AuthError(\n f\"Cannot reach dashboard at {self.dashboard_url}. \"\n \"Check DASHBOARD_URL and network connectivity.\"\n )\n self._backoff(attempt)\n continue\n except requests.Timeout:\n last_error = AuthError(\"Dashboard authentication request timed out.\")\n self._backoff(attempt)\n continue\n except requests.RequestException as e:\n last_error = AuthError(f\"Request failed: {e}\")\n self._backoff(attempt)\n continue\n\n try:\n data = response.json()\n except (ValueError, requests.JSONDecodeError):\n last_error = AuthError(\n f\"Dashboard returned non-JSON response (HTTP {response.status_code}).\"\n )\n self._backoff(attempt)\n continue\n\n if response.status_code != 200:\n detail = data.get(\"detail\", \"Unknown error\")\n logger.error(\"Authentication failed [%d]: %s\", response.status_code, detail)\n # Don't retry on client errors (4xx) — these won't resolve themselves\n if 400 <= response.status_code < 500:\n raise AuthError(detail, status_code=response.status_code)\n last_error = AuthError(detail, status_code=response.status_code)\n self._backoff(attempt)\n continue\n\n session_token = data.get(\"session_token\")\n if not session_token:\n raise AuthError(\n \"Dashboard returned success but no session_token. \"\n \"Ensure the dashboard is up to date.\"\n )\n\n self._session_token = session_token\n logger.info(\"Authenticated successfully. Session token obtained.\")\n return\n\n raise last_error\n\n @staticmethod\n def _backoff(attempt: int) -> None:\n \"\"\"Sleep with exponential backoff between retry attempts.\"\"\"\n if attempt < MAX_RETRIES:\n delay = RETRY_BACKOFF * (2 ** (attempt - 1))\n logger.warning(\"Retrying in %ds...\", delay)\n time.sleep(delay)\n\n def __repr__(self) -> str:\n masked_key = f\"{self.api_key[:12]}...{self.api_key[-4:]}\" if len(self.api_key) > 16 else \"***\"\n return (\n f\"AuthClient(dashboard={self.dashboard_url!r}, \"\n f\"sandbox={self.sandbox_id!r}, key={masked_key})\"\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 4532}, "tests/test_auth_service.py::163": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthClient", "MagicMock", "patch", "requests"], "enclosing_function": "test_retry_then_success", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nclass AuthClient:\n \"\"\"\n Handles authentication between the MCP server (running on EC2)\n and the Windows-MCP Dashboard.\n\n Flow:\n 1. POST /api/user/auth with api_key + sandbox_id\n 2. Dashboard validates key, checks credits, resolves sandbox\n 3. Returns session_token for subsequent /api/mcp calls\n 4. ProxyClient uses Bearer <session_token> to connect\n \"\"\"\n\n def __init__(self, api_key: str, sandbox_id: str):\n self.dashboard_url = \"http://localhost:3000\"\n self.api_key = api_key\n self.sandbox_id = sandbox_id\n self._session_token: str | None = None\n\n @property\n def session_token(self) -> str | None:\n return self._session_token\n\n @property\n def proxy_url(self) -> str:\n \"\"\"The dashboard's MCP streamable-HTTP endpoint.\"\"\"\n return f\"{self.dashboard_url}/api/mcp\"\n\n @property\n def proxy_headers(self) -> dict[str, str]:\n \"\"\"Headers for ProxyClient with Bearer auth.\"\"\"\n if not self._session_token:\n raise AuthError(\"Not authenticated. Call authenticate() first.\")\n return {\"Authorization\": f\"Bearer {self._session_token}\"}\n\n def authenticate(self) -> None:\n \"\"\"\n Authenticate with the dashboard and obtain a session token.\n Retries up to MAX_RETRIES times on transient failures.\n\n Raises:\n AuthError: If authentication fails after all retries.\n \"\"\"\n url = f\"{self.dashboard_url}/api/user/auth\"\n payload = {\n \"api_key\": self.api_key,\n \"sandbox_id\": self.sandbox_id,\n }\n\n last_error: AuthError | None = None\n\n for attempt in range(1, MAX_RETRIES + 1):\n logger.info(\"Authenticating with dashboard at %s (attempt %d/%d)\", url, attempt, MAX_RETRIES)\n\n try:\n response = requests.post(url, json=payload, timeout=30)\n except requests.ConnectionError:\n last_error = AuthError(\n f\"Cannot reach dashboard at {self.dashboard_url}. \"\n \"Check DASHBOARD_URL and network connectivity.\"\n )\n self._backoff(attempt)\n continue\n except requests.Timeout:\n last_error = AuthError(\"Dashboard authentication request timed out.\")\n self._backoff(attempt)\n continue\n except requests.RequestException as e:\n last_error = AuthError(f\"Request failed: {e}\")\n self._backoff(attempt)\n continue\n\n try:\n data = response.json()\n except (ValueError, requests.JSONDecodeError):\n last_error = AuthError(\n f\"Dashboard returned non-JSON response (HTTP {response.status_code}).\"\n )\n self._backoff(attempt)\n continue\n\n if response.status_code != 200:\n detail = data.get(\"detail\", \"Unknown error\")\n logger.error(\"Authentication failed [%d]: %s\", response.status_code, detail)\n # Don't retry on client errors (4xx) — these won't resolve themselves\n if 400 <= response.status_code < 500:\n raise AuthError(detail, status_code=response.status_code)\n last_error = AuthError(detail, status_code=response.status_code)\n self._backoff(attempt)\n continue\n\n session_token = data.get(\"session_token\")\n if not session_token:\n raise AuthError(\n \"Dashboard returned success but no session_token. \"\n \"Ensure the dashboard is up to date.\"\n )\n\n self._session_token = session_token\n logger.info(\"Authenticated successfully. Session token obtained.\")\n return\n\n raise last_error\n\n @staticmethod\n def _backoff(attempt: int) -> None:\n \"\"\"Sleep with exponential backoff between retry attempts.\"\"\"\n if attempt < MAX_RETRIES:\n delay = RETRY_BACKOFF * (2 ** (attempt - 1))\n logger.warning(\"Retrying in %ds...\", delay)\n time.sleep(delay)\n\n def __repr__(self) -> str:\n masked_key = f\"{self.api_key[:12]}...{self.api_key[-4:]}\" if len(self.api_key) > 16 else \"***\"\n return (\n f\"AuthClient(dashboard={self.dashboard_url!r}, \"\n f\"sandbox={self.sandbox_id!r}, key={masked_key})\"\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 4532}, "tests/test_tree_service.py::19": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": [], "enclosing_function": "test_progman", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_tree_views.py::153": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": [], "enclosing_function": "test_to_row_with_base_index", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_registry.py::41": {"resolved_imports": ["src/windows_mcp/desktop/service.py"], "used_names": [], "enclosing_function": "test_success", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_desktop_views.py::30": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": ["Status"], "enclosing_function": "test_enum_values", "extracted_code": "# Source: src/windows_mcp/desktop/views.py\nclass Status(Enum):\n MAXIMIZED = \"Maximized\"\n MINIMIZED = \"Minimized\"\n NORMAL = \"Normal\"\n HIDDEN = \"Hidden\"", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 162}, "tests/test_filesystem_service.py::22": {"resolved_imports": ["src/windows_mcp/filesystem/service.py"], "used_names": ["read_file"], "enclosing_function": "test_read_entire_file", "extracted_code": "# Source: src/windows_mcp/filesystem/service.py\ndef read_file(path: str, offset: int | None = None, limit: int | None = None, encoding: str = 'utf-8') -> str:\n \"\"\"Read the contents of a text file.\"\"\"\n file_path = Path(path).resolve()\n\n if not file_path.exists():\n return f'Error: File not found: {file_path}'\n if not file_path.is_file():\n return f'Error: Path is not a file: {file_path}'\n if file_path.stat().st_size > MAX_READ_SIZE:\n return f'Error: File too large ({file_path.stat().st_size:,} bytes). Maximum is {MAX_READ_SIZE:,} bytes. Use offset/limit parameters or the Shell tool for large files.'\n\n try:\n with open(file_path, 'r', encoding=encoding, errors='replace') as f:\n if offset is not None or limit is not None:\n lines = f.readlines()\n start = (offset or 1) - 1 # Convert 1-based to 0-based\n start = max(0, start)\n end = start + limit if limit else len(lines)\n selected = lines[start:end]\n total = len(lines)\n content = ''.join(selected)\n return f'File: {file_path}\\nLines {start + 1}-{min(end, total)} of {total}:\\n{content}'\n else:\n content = f.read()\n return f'File: {file_path}\\n{content}'\n except UnicodeDecodeError:\n return f'Error: Unable to read file as text with encoding \"{encoding}\". File may be binary.'\n except PermissionError:\n return f'Error: Permission denied: {file_path}'\n except Exception as e:\n return f'Error reading file: {e}'", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1611}, "tests/test_tree_views.py::46": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox", "SimpleNamespace"], "enclosing_function": "test_from_bounding_rectangle", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1086}, "tests/test_tree_views.py::45": {"resolved_imports": ["src/windows_mcp/tree/views.py"], "used_names": ["BoundingBox", "SimpleNamespace"], "enclosing_function": "test_from_bounding_rectangle", "extracted_code": "# Source: src/windows_mcp/tree/views.py\nclass BoundingBox:\n left: int\n top: int\n right: int\n bottom: int\n width: int\n height: int\n\n @classmethod\n def from_bounding_rectangle(cls, bounding_rectangle: Any) -> \"BoundingBox\":\n return cls(\n left=bounding_rectangle.left,\n top=bounding_rectangle.top,\n right=bounding_rectangle.right,\n bottom=bounding_rectangle.bottom,\n width=bounding_rectangle.width(),\n height=bounding_rectangle.height(),\n )\n\n def get_center(self) -> \"Center\":\n return Center(x=self.left + self.width // 2, y=self.top + self.height // 2)\n\n def xywh_to_string(self):\n return f\"({self.left},{self.top},{self.width},{self.height})\"\n\n def xyxy_to_string(self):\n x1, y1, x2, y2 = self.convert_xywh_to_xyxy()\n return f\"({x1},{y1},{x2},{y2})\"\n\n def convert_xywh_to_xyxy(self) -> tuple[int, int, int, int]:\n x1, y1 = self.left, self.top\n x2, y2 = self.left + self.width, self.top + self.height\n return x1, y1, x2, y2", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1086}, "tests/test_filesystem_service.py::98": {"resolved_imports": ["src/windows_mcp/filesystem/service.py"], "used_names": ["copy_path"], "enclosing_function": "test_copy_destination_exists_overwrite", "extracted_code": "# Source: src/windows_mcp/filesystem/service.py\ndef copy_path(source: str, destination: str, overwrite: bool = False) -> str:\n \"\"\"Copy a file or directory to a new location.\"\"\"\n src = Path(source).resolve()\n dst = Path(destination).resolve()\n\n if not src.exists():\n return f'Error: Source not found: {src}'\n\n if dst.exists() and not overwrite:\n return f'Error: Destination already exists: {dst}. Set overwrite=True to replace.'\n\n try:\n if src.is_file():\n dst.parent.mkdir(parents=True, exist_ok=True)\n shutil.copy2(str(src), str(dst))\n return f'Copied file: {src} -> {dst}'\n elif src.is_dir():\n if dst.exists() and overwrite:\n shutil.rmtree(str(dst))\n shutil.copytree(str(src), str(dst))\n return f'Copied directory: {src} -> {dst}'\n else:\n return f'Error: Unsupported file type: {src}'\n except PermissionError:\n return f'Error: Permission denied.'\n except Exception as e:\n return f'Error copying: {e}'", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1066}, "tests/test_tree_service.py::65": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": ["SimpleNamespace"], "enclosing_function": "test_no_overlap", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_filesystem_views.py::51": {"resolved_imports": ["src/windows_mcp/filesystem/views.py"], "used_names": [], "enclosing_function": "test_to_string_basic", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tree_service.py::73": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": ["SimpleNamespace"], "enclosing_function": "test_screen_clamping", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_desktop_views.py::27": {"resolved_imports": ["src/windows_mcp/desktop/views.py"], "used_names": ["Status"], "enclosing_function": "test_enum_values", "extracted_code": "# Source: src/windows_mcp/desktop/views.py\nclass Status(Enum):\n MAXIMIZED = \"Maximized\"\n MINIMIZED = \"Minimized\"\n NORMAL = \"Normal\"\n HIDDEN = \"Hidden\"", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 162}, "tests/test_registry.py::30": {"resolved_imports": ["src/windows_mcp/desktop/service.py"], "used_names": ["Desktop"], "enclosing_function": "test_empty_string", "extracted_code": "# Source: src/windows_mcp/desktop/service.py\nclass Desktop:\n def __init__(self):\n self.encoding = getpreferredencoding()\n self.tree = Tree(self)\n self.desktop_state = None\n\n def get_state(\n self,\n use_annotation: bool | str = True,\n use_vision: bool | str = False,\n use_dom: bool | str = False,\n as_bytes: bool | str = False,\n scale: float = 1.0,\n ) -> DesktopState:\n use_annotation = use_annotation is True or (\n isinstance(use_annotation, str) and use_annotation.lower() == \"true\"\n )\n use_vision = use_vision is True or (\n isinstance(use_vision, str) and use_vision.lower() == \"true\"\n )\n use_dom = use_dom is True or (isinstance(use_dom, str) and use_dom.lower() == \"true\")\n as_bytes = as_bytes is True or (isinstance(as_bytes, str) and as_bytes.lower() == \"true\")\n\n start_time = time()\n\n controls_handles = self.get_controls_handles() # Taskbar,Program Manager,Apps, Dialogs\n windows, windows_handles = self.get_windows(controls_handles=controls_handles) # Apps\n active_window = self.get_active_window(windows=windows) # Active Window\n active_window_handle = active_window.handle if active_window else None\n\n try:\n active_desktop = get_current_desktop()\n all_desktops = get_all_desktops()\n except RuntimeError:\n active_desktop = {\n \"id\": \"00000000-0000-0000-0000-000000000000\",\n \"name\": \"Default Desktop\",\n }\n all_desktops = [active_desktop]\n\n if active_window is not None and active_window in windows:\n windows.remove(active_window)\n\n logger.debug(f\"Active window: {active_window or 'No Active Window Found'}\")\n logger.debug(f\"Windows: {windows}\")\n\n # Preparing handles for Tree\n other_windows_handles = list(controls_handles - windows_handles)\n\n tree_state = self.tree.get_state(\n active_window_handle, other_windows_handles, use_dom=use_dom\n )\n\n if use_vision:\n if use_annotation:\n nodes = tree_state.interactive_nodes\n screenshot = self.get_annotated_screenshot(nodes=nodes)\n else:\n screenshot = self.get_screenshot()\n\n if scale != 1.0:\n screenshot = screenshot.resize(\n (int(screenshot.width * scale), int(screenshot.height * scale)),\n Image.LANCZOS,\n )\n\n if as_bytes:\n buffered = io.BytesIO()\n screenshot.save(buffered, format=\"PNG\")\n screenshot = buffered.getvalue()\n buffered.close()\n else:\n screenshot = None\n\n self.desktop_state = DesktopState(\n active_window=active_window,\n windows=windows,\n active_desktop=active_desktop,\n all_desktops=all_desktops,\n screenshot=screenshot,\n tree_state=tree_state,\n )\n # Log the time taken to capture the state\n end_time = time()\n logger.info(f\"Desktop State capture took {end_time - start_time:.2f} seconds\")\n return self.desktop_state\n\n def get_window_status(self, control: uia.Control) -> Status:\n if uia.IsIconic(control.NativeWindowHandle):\n return Status.MINIMIZED\n elif uia.IsZoomed(control.NativeWindowHandle):\n return Status.MAXIMIZED\n elif uia.IsWindowVisible(control.NativeWindowHandle):\n return Status.NORMAL\n else:\n return Status.HIDDEN\n\n def get_cursor_location(self) -> tuple[int, int]:\n return uia.GetCursorPos()\n\n def get_element_under_cursor(self) -> uia.Control:\n return uia.ControlFromCursor()\n\n def get_apps_from_start_menu(self) -> dict[str, str]:\n \"\"\"Get installed apps. Tries Get-StartApps first, falls back to shortcut scanning.\"\"\"\n command = \"Get-StartApps | ConvertTo-Csv -NoTypeInformation\"\n apps_info, status = self.execute_command(command)\n\n if status == 0 and apps_info and apps_info.strip():\n try:\n reader = csv.DictReader(io.StringIO(apps_info.strip()))\n apps = {\n row.get(\"Name\", \"\").lower(): row.get(\"AppID\", \"\")\n for row in reader\n if row.get(\"Name\") and row.get(\"AppID\")\n }\n if apps:\n return apps\n except Exception as e:\n logger.warning(f\"Error parsing Get-StartApps output: {e}\")\n\n # Fallback: scan Start Menu shortcut folders (works on all Windows versions)\n logger.info(\"Get-StartApps unavailable, falling back to Start Menu folder scan\")\n return self._get_apps_from_shortcuts()\n\n def _get_apps_from_shortcuts(self) -> dict[str, str]:\n \"\"\"Scan Start Menu folders for .lnk shortcuts as a fallback for Get-StartApps.\"\"\"\n import glob\n\n apps = {}\n start_menu_paths = [\n os.path.join(\n os.environ.get(\"PROGRAMDATA\", r\"C:\\ProgramData\"),\n r\"Microsoft\\Windows\\Start Menu\\Programs\",\n ),\n os.path.join(\n os.environ.get(\"APPDATA\", \"\"),\n r\"Microsoft\\Windows\\Start Menu\\Programs\",\n ),\n ]\n for base_path in start_menu_paths:\n if not os.path.isdir(base_path):\n continue\n for lnk_path in glob.glob(os.path.join(base_path, \"**\", \"*.lnk\"), recursive=True):\n name = os.path.splitext(os.path.basename(lnk_path))[0].lower()\n if name and name not in apps:\n apps[name] = lnk_path\n return apps\n\n def execute_command(self, command: str, timeout: int = 10) -> tuple[str, int]:\n try:\n encoded = base64.b64encode(command.encode(\"utf-16le\")).decode(\"ascii\")\n result = subprocess.run(\n [\n \"powershell\",\n \"-NoProfile\",\n \"-OutputFormat\",\n \"Text\",\n \"-EncodedCommand\",\n encoded,\n ],\n capture_output=True, # No errors='ignore' - let subprocess return bytes\n timeout=timeout,\n cwd=os.path.expanduser(path=\"~\"),\n env=os.environ.copy(), # Inherit environment variables including PATH\n )\n # Handle both bytes and str output (subprocess behavior varies by environment)\n stdout = result.stdout\n stderr = result.stderr\n if isinstance(stdout, bytes):\n stdout = stdout.decode(self.encoding, errors=\"ignore\")\n if isinstance(stderr, bytes):\n stderr = stderr.decode(self.encoding, errors=\"ignore\")\n return (stdout or stderr, result.returncode)\n except subprocess.TimeoutExpired:\n return (\"Command execution timed out\", 1)\n except Exception as e:\n return (f\"Command execution failed: {type(e).__name__}: {e}\", 1)\n\n def is_window_browser(self, node: uia.Control):\n \"\"\"Give any node of the app and it will return True if the app is a browser, False otherwise.\"\"\"\n try:\n process = Process(node.ProcessId)\n return Browser.has_process(process.name())\n except Exception:\n return False\n\n def get_default_language(self) -> str:\n command = \"Get-Culture | Select-Object Name,DisplayName | ConvertTo-Csv -NoTypeInformation\"\n response, _ = self.execute_command(command)\n reader = csv.DictReader(io.StringIO(response))\n return \"\".join([row.get(\"DisplayName\") for row in reader])\n\n def resize_app(\n self, size: tuple[int, int] = None, loc: tuple[int, int] = None\n ) -> tuple[str, int]:\n active_window = self.desktop_state.active_window\n if active_window is None:\n return \"No active window found\", 1\n if active_window.status == Status.MINIMIZED:\n return f\"{active_window.name} is minimized\", 1\n elif active_window.status == Status.MAXIMIZED:\n return f\"{active_window.name} is maximized\", 1\n else:\n window_control = uia.ControlFromHandle(active_window.handle)\n if loc is None:\n x = window_control.BoundingRectangle.left\n y = window_control.BoundingRectangle.top\n loc = (x, y)\n if size is None:\n width = window_control.BoundingRectangle.width()\n height = window_control.BoundingRectangle.height()\n size = (width, height)\n x, y = loc\n width, height = size\n window_control.MoveWindow(x, y, width, height)\n return (f\"{active_window.name} resized to {width}x{height} at {x},{y}.\", 0)\n\n def is_app_running(self, name: str) -> bool:\n windows, _ = self.get_windows()\n windows_dict = {window.name: window for window in windows}\n return process.extractOne(name, list(windows_dict.keys()), score_cutoff=60) is not None\n\n def app(\n self,\n mode: Literal[\"launch\", \"switch\", \"resize\"],\n name: str | None = None,\n loc: tuple[int, int] | None = None,\n size: tuple[int, int] | None = None,\n ):\n match mode:\n case \"launch\":\n response, status, pid = self.launch_app(name)\n if status != 0:\n return response\n\n # Smart wait using UIA Exists (avoids manual Python loops)\n launched = False\n if pid > 0:\n if uia.WindowControl(ProcessId=pid).Exists(maxSearchSeconds=10):\n launched = True\n\n if not launched:\n # Fallback: Regex search for the window title\n safe_name = re.escape(name)\n if uia.WindowControl(RegexName=f\"(?i).*{safe_name}.*\").Exists(\n maxSearchSeconds=10\n ):\n launched = True\n\n if launched:\n return f\"{name.title()} launched.\"\n return f\"Launching {name.title()} sent, but window not detected yet.\"\n case \"resize\":\n response, status = self.resize_app(size=size, loc=loc)\n if status != 0:\n return response\n else:\n return response\n case \"switch\":\n response, status = self.switch_app(name)\n if status != 0:\n return response\n else:\n return response\n\n def launch_app(self, name: str) -> tuple[str, int, int]:\n apps_map = self.get_apps_from_start_menu()\n matched_app = process.extractOne(name, apps_map.keys(), score_cutoff=70)\n if matched_app is None:\n return (f\"{name.title()} not found in start menu.\", 1, 0)\n app_name, _ = matched_app\n appid = apps_map.get(app_name)\n if appid is None:\n return (f\"{name.title()} not found in start menu.\", 1, 0)\n\n pid = 0\n if os.path.exists(appid) or \"\\\\\" in appid:\n safe = ps_quote(appid)\n command = f\"Start-Process {safe} -PassThru | Select-Object -ExpandProperty Id\"\n response, status = self.execute_command(command)\n if status == 0 and response.strip().isdigit():\n pid = int(response.strip())\n else:\n if (\n not appid.replace(\"\\\\\", \"\")\n .replace(\"_\", \"\")\n .replace(\".\", \"\")\n .replace(\"-\", \"\")\n .isalnum()\n ):\n return (f\"Invalid app identifier: {appid}\", 1, 0)\n safe = ps_quote(f\"shell:AppsFolder\\\\{appid}\")\n command = f\"Start-Process {safe}\"\n response, status = self.execute_command(command)\n\n return response, status, pid\n\n def switch_app(self, name: str):\n try:\n # Refresh state if desktop_state is None or has no windows\n if self.desktop_state is None or not self.desktop_state.windows:\n self.get_state()\n if self.desktop_state is None:\n return (\"Failed to get desktop state. Please try again.\", 1)\n\n window_list = [\n w\n for w in [self.desktop_state.active_window] + self.desktop_state.windows\n if w is not None\n ]\n if not window_list:\n return (\"No windows found on the desktop.\", 1)\n\n windows = {window.name: window for window in window_list}\n matched_window: tuple[str, float] | None = process.extractOne(\n name, list(windows.keys()), score_cutoff=70\n )\n if matched_window is None:\n return (f\"Application {name.title()} not found.\", 1)\n window_name, _ = matched_window\n window = windows.get(window_name)\n target_handle = window.handle\n\n if uia.IsIconic(target_handle):\n uia.ShowWindow(target_handle, win32con.SW_RESTORE)\n content = f\"{window_name.title()} restored from Minimized state.\"\n else:\n self.bring_window_to_top(target_handle)\n content = f\"Switched to {window_name.title()} window.\"\n return content, 0\n except Exception as e:\n return (f\"Error switching app: {str(e)}\", 1)\n\n def bring_window_to_top(self, target_handle: int):\n if not win32gui.IsWindow(target_handle):\n raise ValueError(\"Invalid window handle\")\n\n try:\n if win32gui.IsIconic(target_handle):\n win32gui.ShowWindow(target_handle, win32con.SW_RESTORE)\n\n foreground_handle = win32gui.GetForegroundWindow()\n\n # Validate both handles before proceeding\n if not win32gui.IsWindow(foreground_handle):\n # No valid foreground window, just try to set target as foreground\n win32gui.SetForegroundWindow(target_handle)\n win32gui.BringWindowToTop(target_handle)\n return\n\n foreground_thread, _ = win32process.GetWindowThreadProcessId(foreground_handle)\n target_thread, _ = win32process.GetWindowThreadProcessId(target_handle)\n\n if not foreground_thread or not target_thread or foreground_thread == target_thread:\n win32gui.SetForegroundWindow(target_handle)\n win32gui.BringWindowToTop(target_handle)\n return\n\n ctypes.windll.user32.AllowSetForegroundWindow(-1)\n\n attached = False\n try:\n win32process.AttachThreadInput(foreground_thread, target_thread, True)\n attached = True\n\n win32gui.SetForegroundWindow(target_handle)\n win32gui.BringWindowToTop(target_handle)\n\n win32gui.SetWindowPos(\n target_handle,\n win32con.HWND_TOP,\n 0,\n 0,\n 0,\n 0,\n win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW,\n )\n\n finally:\n if attached:\n win32process.AttachThreadInput(foreground_thread, target_thread, False)\n\n except Exception as e:\n logger.exception(f\"Failed to bring window to top: {e}\")\n\n def get_element_handle_from_label(self, label: int) -> uia.Control:\n tree_state = self.desktop_state.tree_state\n element_node = tree_state.interactive_nodes[label]\n xpath = element_node.xpath\n element_handle = self.get_element_from_xpath(xpath)\n return element_handle\n\n def get_coordinates_from_label(self, label: int) -> tuple[int, int]:\n element_handle = self.get_element_handle_from_label(label)\n bounding_rectangle = element_handle.BoundingRectangle\n return bounding_rectangle.xcenter(), bounding_rectangle.ycenter()\n\n def click(self, loc: tuple[int, int], button: str = \"left\", clicks: int = 2):\n x, y = loc\n if clicks == 0:\n uia.SetCursorPos(x, y)\n return\n match button:\n case \"left\":\n if clicks >= 2:\n dbl_wait = uia.GetDoubleClickTime() / 2000.0\n for i in range(clicks):\n uia.Click(x, y, waitTime=dbl_wait if i < clicks - 1 else 0.5)\n else:\n uia.Click(x, y)\n case \"right\":\n for _ in range(clicks):\n uia.RightClick(x, y)\n case \"middle\":\n for _ in range(clicks):\n uia.MiddleClick(x, y)\n\n def type(\n self,\n loc: tuple[int, int],\n text: str,\n caret_position: Literal[\"start\", \"idle\", \"end\"] = \"idle\",\n clear: bool | str = False,\n press_enter: bool | str = False,\n ):\n x, y = loc\n uia.Click(x, y)\n if caret_position == \"start\":\n uia.SendKeys(\"{Home}\", waitTime=0.05)\n elif caret_position == \"end\":\n uia.SendKeys(\"{End}\", waitTime=0.05)\n if clear is True or (isinstance(clear, str) and clear.lower() == \"true\"):\n sleep(0.5)\n uia.SendKeys(\"{Ctrl}a\", waitTime=0.05)\n uia.SendKeys(\"{Back}\", waitTime=0.05)\n escaped_text = _escape_text_for_sendkeys(text)\n uia.SendKeys(escaped_text, interval=0.02, waitTime=0.05)\n if press_enter is True or (isinstance(press_enter, str) and press_enter.lower() == \"true\"):\n uia.SendKeys(\"{Enter}\", waitTime=0.05)\n\n def scroll(\n self,\n loc: tuple[int, int] = None,\n type: Literal[\"horizontal\", \"vertical\"] = \"vertical\",\n direction: Literal[\"up\", \"down\", \"left\", \"right\"] = \"down\",\n wheel_times: int = 1,\n ) -> str | None:\n if loc:\n self.move(loc)\n match type:\n case \"vertical\":\n match direction:\n case \"up\":\n uia.WheelUp(wheel_times)\n case \"down\":\n uia.WheelDown(wheel_times)\n case _:\n return 'Invalid direction. Use \"up\" or \"down\".'\n case \"horizontal\":\n match direction:\n case \"left\":\n uia.PressKey(uia.Keys.VK_SHIFT, waitTime=0.05)\n uia.WheelUp(wheel_times)\n sleep(0.05)\n uia.ReleaseKey(uia.Keys.VK_SHIFT, waitTime=0.05)\n case \"right\":\n uia.PressKey(uia.Keys.VK_SHIFT, waitTime=0.05)\n uia.WheelDown(wheel_times)\n sleep(0.05)\n uia.ReleaseKey(uia.Keys.VK_SHIFT, waitTime=0.05)\n case _:\n return 'Invalid direction. Use \"left\" or \"right\".'\n case _:\n return 'Invalid type. Use \"horizontal\" or \"vertical\".'\n return None\n\n def drag(self, loc: tuple[int, int]):\n x, y = loc\n sleep(0.5)\n cx, cy = uia.GetCursorPos()\n uia.DragDrop(cx, cy, x, y, moveSpeed=1)\n\n def move(self, loc: tuple[int, int]):\n x, y = loc\n uia.MoveTo(x, y, moveSpeed=10)\n\n def shortcut(self, shortcut: str):\n keys = shortcut.split(\"+\")\n sendkeys_str = \"\"\n for key in keys:\n key = key.strip()\n if len(key) == 1:\n sendkeys_str += key\n else:\n name = _KEY_ALIASES.get(key.lower(), key)\n sendkeys_str += \"{\" + name + \"}\"\n uia.SendKeys(sendkeys_str, interval=0.01)\n\n def multi_select(self, press_ctrl: bool | str = False, locs: list[tuple[int, int]] = []):\n press_ctrl = press_ctrl is True or (\n isinstance(press_ctrl, str) and press_ctrl.lower() == \"true\"\n )\n if press_ctrl:\n uia.PressKey(uia.Keys.VK_CONTROL, waitTime=0.05)\n for loc in locs:\n x, y = loc\n uia.Click(x, y, waitTime=0.2)\n sleep(0.5)\n uia.ReleaseKey(uia.Keys.VK_CONTROL, waitTime=0.05)\n\n def multi_edit(self, locs: list[tuple[int, int, str]]):\n for loc in locs:\n x, y, text = loc\n self.type((x, y), text=text, clear=True)\n\n def scrape(self, url: str) -> str:\n try:\n response = requests.get(url, timeout=10)\n response.raise_for_status()\n except requests.exceptions.HTTPError as e:\n raise ValueError(f\"HTTP error for {url}: {e}\") from e\n except requests.exceptions.ConnectionError as e:\n raise ConnectionError(f\"Failed to connect to {url}: {e}\") from e\n except requests.exceptions.Timeout as e:\n raise TimeoutError(f\"Request timed out for {url}: {e}\") from e\n html = response.text\n content = markdownify(html=html)\n return content\n\n def get_window_from_element(self, element: uia.Control) -> Window | None:\n if element is None:\n return None\n top_window = element.GetTopLevelControl()\n if top_window is None:\n return None\n handle = top_window.NativeWindowHandle\n windows, _ = self.get_windows()\n for window in windows:\n if window.handle == handle:\n return window\n return None\n\n def is_window_visible(self, window: uia.Control) -> bool:\n is_minimized = self.get_window_status(window) != Status.MINIMIZED\n size = window.BoundingRectangle\n area = size.width() * size.height()\n is_overlay = self.is_overlay_window(window)\n return not is_overlay and is_minimized and area > 10\n\n def is_overlay_window(self, element: uia.Control) -> bool:\n no_children = len(element.GetChildren()) == 0\n is_name = \"Overlay\" in element.Name.strip()\n return no_children or is_name\n\n def get_controls_handles(self, optimized: bool = False):\n handles = set()\n\n # For even more faster results (still under development)\n def callback(hwnd, _):\n try:\n # Validate handle before checking properties\n if (\n win32gui.IsWindow(hwnd)\n and win32gui.IsWindowVisible(hwnd)\n and is_window_on_current_desktop(hwnd)\n ):\n handles.add(hwnd)\n except Exception:\n # Skip invalid handles without logging (common during window enumeration)\n pass\n\n win32gui.EnumWindows(callback, None)\n\n if desktop_hwnd := win32gui.FindWindow(\"Progman\", None):\n handles.add(desktop_hwnd)\n if taskbar_hwnd := win32gui.FindWindow(\"Shell_TrayWnd\", None):\n handles.add(taskbar_hwnd)\n if secondary_taskbar_hwnd := win32gui.FindWindow(\"Shell_SecondaryTrayWnd\", None):\n handles.add(secondary_taskbar_hwnd)\n return handles\n\n def get_active_window(self, windows: list[Window] | None = None) -> Window | None:\n try:\n if windows is None:\n windows, _ = self.get_windows()\n active_window = self.get_foreground_window()\n if active_window.ClassName == \"Progman\":\n return None\n active_window_handle = active_window.NativeWindowHandle\n for window in windows:\n if window.handle != active_window_handle:\n continue\n return window\n # In case active window is not present in the windows list\n return Window(\n **{\n \"name\": active_window.Name,\n \"is_browser\": self.is_window_browser(active_window),\n \"depth\": 0,\n \"bounding_box\": BoundingBox(\n left=active_window.BoundingRectangle.left,\n top=active_window.BoundingRectangle.top,\n right=active_window.BoundingRectangle.right,\n bottom=active_window.BoundingRectangle.bottom,\n width=active_window.BoundingRectangle.width(),\n height=active_window.BoundingRectangle.height(),\n ),\n \"status\": self.get_window_status(active_window),\n \"handle\": active_window_handle,\n \"process_id\": active_window.ProcessId,\n }\n )\n except Exception as ex:\n logger.error(f\"Error in get_active_window: {ex}\")\n return None\n\n def get_foreground_window(self) -> uia.Control:\n handle = uia.GetForegroundWindow()\n active_window = self.get_window_from_element_handle(handle)\n return active_window\n\n def get_window_from_element_handle(self, element_handle: int) -> uia.Control:\n current = uia.ControlFromHandle(element_handle)\n root_handle = uia.GetRootControl().NativeWindowHandle\n\n while True:\n parent = current.GetParentControl()\n if parent is None or parent.NativeWindowHandle == root_handle:\n return current\n current = parent\n\n def get_windows(\n self, controls_handles: set[int] | None = None\n ) -> tuple[list[Window], set[int]]:\n try:\n windows = []\n window_handles = set()\n controls_handles = controls_handles or self.get_controls_handles()\n for depth, hwnd in enumerate(controls_handles):\n try:\n child = uia.ControlFromHandle(hwnd)\n except Exception:\n continue\n\n # Filter out Overlays (e.g. NVIDIA, Steam)\n if self.is_overlay_window(child):\n continue\n\n if isinstance(child, (uia.WindowControl, uia.PaneControl)):\n window_pattern = child.GetPattern(uia.PatternId.WindowPattern)\n if window_pattern is None:\n continue\n\n if window_pattern.CanMinimize and window_pattern.CanMaximize:\n status = self.get_window_status(child)\n\n bounding_rect = child.BoundingRectangle\n if bounding_rect.isempty() and status != Status.MINIMIZED:\n continue\n\n windows.append(\n Window(\n **{\n \"name\": child.Name,\n \"depth\": depth,\n \"status\": status,\n \"bounding_box\": BoundingBox(\n left=bounding_rect.left,\n top=bounding_rect.top,\n right=bounding_rect.right,\n bottom=bounding_rect.bottom,\n width=bounding_rect.width(),\n height=bounding_rect.height(),\n ),\n \"handle\": child.NativeWindowHandle,\n \"process_id\": child.ProcessId,\n \"is_browser\": self.is_window_browser(child),\n }\n )\n )\n window_handles.add(child.NativeWindowHandle)\n except Exception as ex:\n logger.error(f\"Error in get_windows: {ex}\")\n windows = []\n return windows, window_handles\n\n def get_xpath_from_element(self, element: uia.Control):\n current = element\n if current is None:\n return \"\"\n path_parts = []\n while current is not None:\n parent = current.GetParentControl()\n if parent is None:\n # we are at the root node\n path_parts.append(f\"{current.ControlTypeName}\")\n break\n children = parent.GetChildren()\n same_type_children = [\n \"-\".join(map(lambda x: str(x), child.GetRuntimeId()))\n for child in children\n if child.ControlType == current.ControlType\n ]\n index = same_type_children.index(\n \"-\".join(map(lambda x: str(x), current.GetRuntimeId()))\n )\n if same_type_children:\n path_parts.append(f\"{current.ControlTypeName}[{index + 1}]\")\n else:\n path_parts.append(f\"{current.ControlTypeName}\")\n current = parent\n path_parts.reverse()\n xpath = \"/\".join(path_parts)\n return xpath\n\n def get_element_from_xpath(self, xpath: str) -> uia.Control:\n pattern = re.compile(r\"(\\w+)(?:\\[(\\d+)\\])?\")\n parts = xpath.split(\"/\")\n root = uia.GetRootControl()\n element = root\n for part in parts[1:]:\n match = pattern.fullmatch(part)\n if match is None:\n continue\n control_type, index = match.groups()\n index = int(index) if index else None\n children = element.GetChildren()\n same_type_children = list(filter(lambda x: x.ControlTypeName == control_type, children))\n if index:\n element = same_type_children[index - 1]\n else:\n element = same_type_children[0]\n return element\n\n def get_windows_version(self) -> str:\n response, status = self.execute_command(\"(Get-CimInstance Win32_OperatingSystem).Caption\")\n if status == 0:\n return response.strip()\n return \"Windows\"\n\n def get_user_account_type(self) -> str:\n response, status = self.execute_command(\n \"(Get-LocalUser -Name $env:USERNAME).PrincipalSource\"\n )\n return (\n \"Local Account\"\n if response.strip() == \"Local\"\n else \"Microsoft Account\"\n if status == 0\n else \"Local Account\"\n )\n\n def get_dpi_scaling(self):\n try:\n user32 = ctypes.windll.user32\n dpi = user32.GetDpiForSystem()\n return dpi / 96.0 if dpi > 0 else 1.0\n except Exception:\n # Fallback to standard DPI if system call fails\n return 1.0\n\n def get_screen_size(self) -> Size:\n width, height = uia.GetVirtualScreenSize()\n return Size(width=width, height=height)\n\n def get_screenshot(self) -> Image.Image:\n try:\n return ImageGrab.grab(all_screens=True)\n except Exception:\n logger.warning(\"Failed to capture virtual screen, using primary screen\")\n return ImageGrab.grab()\n\n def get_annotated_screenshot(self, nodes: list[TreeElementNode]) -> Image.Image:\n screenshot = self.get_screenshot()\n # Add padding\n padding = 5\n width = int(screenshot.width + (1.5 * padding))\n height = int(screenshot.height + (1.5 * padding))\n padded_screenshot = Image.new(\"RGB\", (width, height), color=(255, 255, 255))\n padded_screenshot.paste(screenshot, (padding, padding))\n\n draw = ImageDraw.Draw(padded_screenshot)\n font_size = 12\n try:\n font = ImageFont.truetype(\"arial.ttf\", font_size)\n except IOError:\n font = ImageFont.load_default()\n\n def get_random_color():\n return \"#{:06x}\".format(random.randint(0, 0xFFFFFF))\n\n left_offset, top_offset, _, _ = uia.GetVirtualScreenRect()\n\n def draw_annotation(label, node: TreeElementNode):\n box = node.bounding_box\n color = get_random_color()\n\n # Scale and pad the bounding box also clip the bounding box\n # Adjust for virtual screen offset so coordinates map to the screenshot image\n adjusted_box = (\n int(box.left - left_offset) + padding,\n int(box.top - top_offset) + padding,\n int(box.right - left_offset) + padding,\n int(box.bottom - top_offset) + padding,\n )\n # Draw bounding box\n draw.rectangle(adjusted_box, outline=color, width=2)\n\n # Label dimensions\n label_width = draw.textlength(str(label), font=font)\n label_height = font_size\n left, top, right, bottom = adjusted_box\n\n # Label position above bounding box\n label_x1 = right - label_width\n label_y1 = top - label_height - 4\n label_x2 = label_x1 + label_width\n label_y2 = label_y1 + label_height + 4\n\n # Draw label background and text\n draw.rectangle([(label_x1, label_y1), (label_x2, label_y2)], fill=color)\n draw.text(\n (label_x1 + 2, label_y1 + 2),\n str(label),\n fill=(255, 255, 255),\n font=font,\n )\n\n # Draw annotations in parallel\n with ThreadPoolExecutor() as executor:\n executor.map(draw_annotation, range(len(nodes)), nodes)\n return padded_screenshot\n\n def send_notification(self, title: str, message: str) -> str:\n safe_title = ps_quote_for_xml(title)\n safe_message = ps_quote_for_xml(message)\n\n ps_script = (\n \"[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null\\n\"\n \"[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null\\n\"\n f\"$notifTitle = {safe_title}\\n\"\n f\"$notifMessage = {safe_message}\\n\"\n '$template = @\"\\n'\n \"<toast>\\n\"\n \" <visual>\\n\"\n ' <binding template=\"ToastGeneric\">\\n'\n \" <text>$notifTitle</text>\\n\"\n \" <text>$notifMessage</text>\\n\"\n \" </binding>\\n\"\n \" </visual>\\n\"\n \"</toast>\\n\"\n '\"@\\n'\n \"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument\\n\"\n \"$xml.LoadXml($template)\\n\"\n '$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(\"Windows MCP\")\\n'\n \"$toast = New-Object Windows.UI.Notifications.ToastNotification $xml\\n\"\n \"$notifier.Show($toast)\"\n )\n response, status = self.execute_command(ps_script)\n if status == 0:\n return f'Notification sent: \"{title}\" - {message}'\n else:\n return f'Notification may have been sent. PowerShell output: {response[:200]}'\n\n def list_processes(\n self,\n name: str | None = None,\n sort_by: Literal[\"memory\", \"cpu\", \"name\"] = \"memory\",\n limit: int = 20,\n ) -> str:\n import psutil\n from tabulate import tabulate\n\n procs = []\n for p in psutil.process_iter([\"pid\", \"name\", \"cpu_percent\", \"memory_info\"]):\n try:\n info = p.info\n mem_mb = info[\"memory_info\"].rss / (1024 * 1024) if info[\"memory_info\"] else 0\n procs.append(\n {\n \"pid\": info[\"pid\"],\n \"name\": info[\"name\"] or \"Unknown\",\n \"cpu\": info[\"cpu_percent\"] or 0,\n \"mem_mb\": round(mem_mb, 1),\n }\n )\n except (psutil.NoSuchProcess, psutil.AccessDenied):\n continue\n if name:\n from thefuzz import fuzz\n\n procs = [p for p in procs if fuzz.partial_ratio(name.lower(), p[\"name\"].lower()) > 60]\n sort_key = {\n \"memory\": lambda x: x[\"mem_mb\"],\n \"cpu\": lambda x: x[\"cpu\"],\n \"name\": lambda x: x[\"name\"].lower(),\n }\n procs.sort(key=sort_key.get(sort_by, sort_key[\"memory\"]), reverse=(sort_by != \"name\"))\n procs = procs[:limit]\n if not procs:\n return f\"No processes found{f' matching {name}' if name else ''}.\"\n table = tabulate(\n [[p[\"pid\"], p[\"name\"], f\"{p['cpu']:.1f}%\", f\"{p['mem_mb']:.1f} MB\"] for p in procs],\n headers=[\"PID\", \"Name\", \"CPU%\", \"Memory\"],\n tablefmt=\"simple\",\n )\n return f\"Processes ({len(procs)} shown):\\n{table}\"\n\n def kill_process(\n self, name: str | None = None, pid: int | None = None, force: bool = False\n ) -> str:\n import psutil\n\n if pid is None and name is None:\n return \"Error: Provide either pid or name parameter for kill mode.\"\n killed = []\n if pid is not None:\n try:\n p = psutil.Process(pid)\n pname = p.name()\n if force:\n p.kill()\n else:\n p.terminate()\n killed.append(f\"{pname} (PID {pid})\")\n except psutil.NoSuchProcess:\n return f\"No process with PID {pid} found.\"\n except psutil.AccessDenied:\n return f\"Access denied to kill PID {pid}. Try running as administrator.\"\n else:\n for p in psutil.process_iter([\"pid\", \"name\"]):\n try:\n if p.info[\"name\"] and p.info[\"name\"].lower() == name.lower():\n if force:\n p.kill()\n else:\n p.terminate()\n killed.append(f\"{p.info['name']} (PID {p.info['pid']})\")\n except (psutil.NoSuchProcess, psutil.AccessDenied):\n continue\n if not killed:\n return f'No process matching \"{name}\" found or access denied.'\n return f\"{'Force killed' if force else 'Terminated'}: {', '.join(killed)}\"\n\n def lock_screen(self) -> str:\n ctypes.windll.user32.LockWorkStation()\n return \"Screen locked.\"\n\n def get_system_info(self) -> str:\n import psutil\n import platform\n from datetime import datetime, timedelta\n\n cpu_pct = psutil.cpu_percent(interval=1)\n cpu_count = psutil.cpu_count()\n mem = psutil.virtual_memory()\n disk = psutil.disk_usage(\"C:\\\\\")\n boot = datetime.fromtimestamp(psutil.boot_time())\n uptime = datetime.now() - boot\n uptime_str = str(timedelta(seconds=int(uptime.total_seconds())))\n net = psutil.net_io_counters()\n from textwrap import dedent\n\n return dedent(f\"\"\"System Information:\n OS: {platform.system()} {platform.release()} ({platform.version()})\n Machine: {platform.machine()}\n\n CPU: {cpu_pct}% ({cpu_count} cores)\n Memory: {mem.percent}% used ({round(mem.used / 1024**3, 1)} / {round(mem.total / 1024**3, 1)} GB)\n Disk C: {disk.percent}% used ({round(disk.used / 1024**3, 1)} / {round(disk.total / 1024**3, 1)} GB)\n\n Network: ↑ {round(net.bytes_sent / 1024**2, 1)} MB sent, ↓ {round(net.bytes_recv / 1024**2, 1)} MB received\n Uptime: {uptime_str} (booted {boot.strftime(\"%Y-%m-%d %H:%M\")})\"\"\")\n\n def registry_get(self, path: str, name: str) -> str:\n q_path = ps_quote(path)\n q_name = ps_quote(name)\n command = f\"Get-ItemProperty -Path {q_path} -Name {q_name} | Select-Object -ExpandProperty {q_name}\"\n response, status = self.execute_command(command)\n if status != 0:\n return f'Error reading registry: {response.strip()}'\n return f'Registry value [{path}] \"{name}\" = {response.strip()}'\n\n def registry_set(self, path: str, name: str, value: str, reg_type: str = 'String') -> str:\n q_path = ps_quote(path)\n q_name = ps_quote(name)\n q_value = ps_quote(value)\n allowed_types = {\"String\", \"ExpandString\", \"Binary\", \"DWord\", \"MultiString\", \"QWord\"}\n if reg_type not in allowed_types:\n return f\"Error: invalid registry type '{reg_type}'. Allowed: {', '.join(sorted(allowed_types))}\"\n command = (\n f\"if (-not (Test-Path {q_path})) {{ New-Item -Path {q_path} -Force | Out-Null }}; \"\n f\"Set-ItemProperty -Path {q_path} -Name {q_name} -Value {q_value} -Type {reg_type} -Force\"\n )\n response, status = self.execute_command(command)\n if status != 0:\n return f'Error writing registry: {response.strip()}'\n return f'Registry value [{path}] \"{name}\" set to \"{value}\" (type: {reg_type}).'\n\n def registry_delete(self, path: str, name: str | None = None) -> str:\n q_path = ps_quote(path)\n if name:\n q_name = ps_quote(name)\n command = f\"Remove-ItemProperty -Path {q_path} -Name {q_name} -Force\"\n response, status = self.execute_command(command)\n if status != 0:\n return f'Error deleting registry value: {response.strip()}'\n return f'Registry value [{path}] \"{name}\" deleted.'\n else:\n command = f\"Remove-Item -Path {q_path} -Recurse -Force\"\n response, status = self.execute_command(command)\n if status != 0:\n return f'Error deleting registry key: {response.strip()}'\n return f'Registry key [{path}] deleted.'\n\n def registry_list(self, path: str) -> str:\n q_path = ps_quote(path)\n command = (\n f\"$values = (Get-ItemProperty -Path {q_path} -ErrorAction Stop | \"\n f\"Select-Object * -ExcludeProperty PS* | Format-List | Out-String).Trim(); \"\n f\"$subkeys = (Get-ChildItem -Path {q_path} -ErrorAction SilentlyContinue | \"\n f\"Select-Object -ExpandProperty PSChildName) -join \\\"`n\\\"; \"\n f\"if ($values) {{ Write-Output \\\"Values:`n$values\\\" }}; \"\n f\"if ($subkeys) {{ Write-Output \\\"`nSub-Keys:`n$subkeys\\\" }}; \"\n f\"if (-not $values -and -not $subkeys) {{ Write-Output 'No values or sub-keys found.' }}\"\n )\n response, status = self.execute_command(command)\n if status != 0:\n return f'Error listing registry: {response.strip()}'\n return f'Registry key [{path}]:\\n{response.strip()}'\n\n @contextmanager\n def auto_minimize(self):\n try:\n handle = uia.GetForegroundWindow()\n uia.ShowWindow(handle, win32con.SW_MINIMIZE)\n yield\n finally:\n uia.ShowWindow(handle, win32con.SW_RESTORE)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 42754}, "tests/test_auth_service.py::79": {"resolved_imports": ["src/windows_mcp/auth/service.py"], "used_names": ["AuthClient", "AuthError", "MAX_RETRIES", "patch", "pytest", "requests"], "enclosing_function": "test_connection_error_retries", "extracted_code": "# Source: src/windows_mcp/auth/service.py\nMAX_RETRIES = 3\n\nclass AuthError(Exception):\n \"\"\"Raised when authentication with the dashboard fails.\"\"\"\n\n def __init__(self, message: str, status_code: int | None = None):\n self.message = message\n self.status_code = status_code\n super().__init__(self.message)\n\nclass AuthClient:\n \"\"\"\n Handles authentication between the MCP server (running on EC2)\n and the Windows-MCP Dashboard.\n\n Flow:\n 1. POST /api/user/auth with api_key + sandbox_id\n 2. Dashboard validates key, checks credits, resolves sandbox\n 3. Returns session_token for subsequent /api/mcp calls\n 4. ProxyClient uses Bearer <session_token> to connect\n \"\"\"\n\n def __init__(self, api_key: str, sandbox_id: str):\n self.dashboard_url = \"http://localhost:3000\"\n self.api_key = api_key\n self.sandbox_id = sandbox_id\n self._session_token: str | None = None\n\n @property\n def session_token(self) -> str | None:\n return self._session_token\n\n @property\n def proxy_url(self) -> str:\n \"\"\"The dashboard's MCP streamable-HTTP endpoint.\"\"\"\n return f\"{self.dashboard_url}/api/mcp\"\n\n @property\n def proxy_headers(self) -> dict[str, str]:\n \"\"\"Headers for ProxyClient with Bearer auth.\"\"\"\n if not self._session_token:\n raise AuthError(\"Not authenticated. Call authenticate() first.\")\n return {\"Authorization\": f\"Bearer {self._session_token}\"}\n\n def authenticate(self) -> None:\n \"\"\"\n Authenticate with the dashboard and obtain a session token.\n Retries up to MAX_RETRIES times on transient failures.\n\n Raises:\n AuthError: If authentication fails after all retries.\n \"\"\"\n url = f\"{self.dashboard_url}/api/user/auth\"\n payload = {\n \"api_key\": self.api_key,\n \"sandbox_id\": self.sandbox_id,\n }\n\n last_error: AuthError | None = None\n\n for attempt in range(1, MAX_RETRIES + 1):\n logger.info(\"Authenticating with dashboard at %s (attempt %d/%d)\", url, attempt, MAX_RETRIES)\n\n try:\n response = requests.post(url, json=payload, timeout=30)\n except requests.ConnectionError:\n last_error = AuthError(\n f\"Cannot reach dashboard at {self.dashboard_url}. \"\n \"Check DASHBOARD_URL and network connectivity.\"\n )\n self._backoff(attempt)\n continue\n except requests.Timeout:\n last_error = AuthError(\"Dashboard authentication request timed out.\")\n self._backoff(attempt)\n continue\n except requests.RequestException as e:\n last_error = AuthError(f\"Request failed: {e}\")\n self._backoff(attempt)\n continue\n\n try:\n data = response.json()\n except (ValueError, requests.JSONDecodeError):\n last_error = AuthError(\n f\"Dashboard returned non-JSON response (HTTP {response.status_code}).\"\n )\n self._backoff(attempt)\n continue\n\n if response.status_code != 200:\n detail = data.get(\"detail\", \"Unknown error\")\n logger.error(\"Authentication failed [%d]: %s\", response.status_code, detail)\n # Don't retry on client errors (4xx) — these won't resolve themselves\n if 400 <= response.status_code < 500:\n raise AuthError(detail, status_code=response.status_code)\n last_error = AuthError(detail, status_code=response.status_code)\n self._backoff(attempt)\n continue\n\n session_token = data.get(\"session_token\")\n if not session_token:\n raise AuthError(\n \"Dashboard returned success but no session_token. \"\n \"Ensure the dashboard is up to date.\"\n )\n\n self._session_token = session_token\n logger.info(\"Authenticated successfully. Session token obtained.\")\n return\n\n raise last_error\n\n @staticmethod\n def _backoff(attempt: int) -> None:\n \"\"\"Sleep with exponential backoff between retry attempts.\"\"\"\n if attempt < MAX_RETRIES:\n delay = RETRY_BACKOFF * (2 ** (attempt - 1))\n logger.warning(\"Retrying in %ds...\", delay)\n time.sleep(delay)\n\n def __repr__(self) -> str:\n masked_key = f\"{self.api_key[:12]}...{self.api_key[-4:]}\" if len(self.api_key) > 16 else \"***\"\n return (\n f\"AuthClient(dashboard={self.dashboard_url!r}, \"\n f\"sandbox={self.sandbox_id!r}, key={masked_key})\"\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 4821}, "tests/test_tree_service.py::75": {"resolved_imports": ["src/windows_mcp/desktop/views.py", "src/windows_mcp/tree/service.py"], "used_names": ["SimpleNamespace"], "enclosing_function": "test_screen_clamping", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_analytics.py::81": {"resolved_imports": ["src/windows_mcp/analytics.py"], "used_names": ["AsyncMock", "with_analytics"], "enclosing_function": "test_return_value_preserved", "extracted_code": "# Source: src/windows_mcp/analytics.py\ndef with_analytics(analytics_instance: Analytics | None, tool_name: str):\n \"\"\"\n Decorator to wrap tool functions with analytics tracking.\n \"\"\"\n\n def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:\n @wraps(func)\n async def wrapper(*args, **kwargs) -> T:\n start = time.time()\n\n # Capture client info from Context passed as argument\n client_data = {}\n try:\n ctx = next((arg for arg in args if isinstance(arg, Context)), None)\n if not ctx:\n ctx = next(\n (val for val in kwargs.values() if isinstance(val, Context)),\n None,\n )\n\n if (\n ctx\n and ctx.session\n and ctx.session.client_params\n and ctx.session.client_params.clientInfo\n ):\n info = ctx.session.client_params.clientInfo\n client_data[\"client_name\"] = info.name\n client_data[\"client_version\"] = info.version\n except Exception:\n pass\n\n try:\n if asyncio.iscoroutinefunction(func):\n result = await func(*args, **kwargs)\n else:\n # Run sync function in thread to avoid blocking loop\n result = await asyncio.to_thread(func, *args, **kwargs)\n\n duration_ms = int((time.time() - start) * 1000)\n\n if analytics_instance:\n await analytics_instance.track_tool(\n tool_name,\n {\"duration_ms\": duration_ms, \"success\": True, **client_data},\n )\n\n return result\n except Exception as error:\n duration_ms = int((time.time() - start) * 1000)\n if analytics_instance:\n await analytics_instance.track_error(\n error,\n {\n \"tool_name\": tool_name,\n \"duration_ms\": duration_ms,\n **client_data,\n },\n )\n raise error\n\n return wrapper\n\n return decorator", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2391}}}