autoglm-gui 0.4.9__tar.gz → 0.4.12__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/.gitignore +16 -0
  2. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/__init__.py +8 -0
  3. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/__main__.py +64 -21
  4. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/adb_plus/__init__.py +8 -0
  5. autoglm_gui-0.4.12/AutoGLM_GUI/adb_plus/device.py +50 -0
  6. autoglm_gui-0.4.12/AutoGLM_GUI/adb_plus/ip.py +78 -0
  7. autoglm_gui-0.4.12/AutoGLM_GUI/adb_plus/keyboard_installer.py +380 -0
  8. autoglm_gui-0.4.12/AutoGLM_GUI/adb_plus/serial.py +35 -0
  9. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/api/__init__.py +8 -0
  10. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/api/agents.py +132 -1
  11. autoglm_gui-0.4.12/AutoGLM_GUI/api/devices.py +119 -0
  12. autoglm_gui-0.4.12/AutoGLM_GUI/api/media.py +49 -0
  13. autoglm_gui-0.4.12/AutoGLM_GUI/config_manager.py +565 -0
  14. autoglm_gui-0.4.12/AutoGLM_GUI/exceptions.py +7 -0
  15. autoglm_gui-0.4.12/AutoGLM_GUI/logger.py +85 -0
  16. autoglm_gui-0.4.12/AutoGLM_GUI/platform_utils.py +62 -0
  17. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/schemas.py +50 -0
  18. autoglm_gui-0.4.12/AutoGLM_GUI/scrcpy_protocol.py +46 -0
  19. autoglm_gui-0.4.12/AutoGLM_GUI/scrcpy_stream.py +459 -0
  20. autoglm_gui-0.4.12/AutoGLM_GUI/server.py +10 -0
  21. autoglm_gui-0.4.12/AutoGLM_GUI/socketio_server.py +125 -0
  22. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/state.py +2 -1
  23. autoglm_gui-0.4.9/AutoGLM_GUI/static/assets/about-BI6OV6gm.js → autoglm_gui-0.4.12/AutoGLM_GUI/static/assets/about-kgOkkOWe.js +1 -1
  24. autoglm_gui-0.4.12/AutoGLM_GUI/static/assets/chat-CZV3RByK.js +149 -0
  25. autoglm_gui-0.4.9/AutoGLM_GUI/static/assets/index-Do7ha9Kf.js → autoglm_gui-0.4.12/AutoGLM_GUI/static/assets/index-BPYHsweG.js +1 -1
  26. autoglm_gui-0.4.12/AutoGLM_GUI/static/assets/index-Beu9cbSy.css +1 -0
  27. autoglm_gui-0.4.12/AutoGLM_GUI/static/assets/index-DfI_Z1Cx.js +10 -0
  28. autoglm_gui-0.4.12/AutoGLM_GUI/static/assets/worker-D6BRitjy.js +1 -0
  29. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/static/index.html +2 -2
  30. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/PKG-INFO +15 -2
  31. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/README.md +11 -1
  32. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/pyproject.toml +5 -1
  33. autoglm_gui-0.4.9/AutoGLM_GUI/api/devices.py +0 -29
  34. autoglm_gui-0.4.9/AutoGLM_GUI/api/media.py +0 -279
  35. autoglm_gui-0.4.9/AutoGLM_GUI/platform_utils.py +0 -37
  36. autoglm_gui-0.4.9/AutoGLM_GUI/scrcpy_stream.py +0 -578
  37. autoglm_gui-0.4.9/AutoGLM_GUI/server.py +0 -5
  38. autoglm_gui-0.4.9/AutoGLM_GUI/static/assets/chat-C_2Cot0q.js +0 -25
  39. autoglm_gui-0.4.9/AutoGLM_GUI/static/assets/index-DCrxTz-A.css +0 -1
  40. autoglm_gui-0.4.9/AutoGLM_GUI/static/assets/index-Dn3vR6uV.js +0 -10
  41. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/adb_plus/screenshot.py +0 -0
  42. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/adb_plus/touch.py +0 -0
  43. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/api/control.py +0 -0
  44. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/config.py +0 -0
  45. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/AutoGLM_GUI/version.py +0 -0
  46. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/LICENSE +0 -0
  47. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/__init__.py +0 -0
  48. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/actions/__init__.py +0 -0
  49. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/actions/handler.py +0 -0
  50. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/adb/__init__.py +0 -0
  51. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/adb/connection.py +0 -0
  52. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/adb/device.py +0 -0
  53. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/adb/input.py +0 -0
  54. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/adb/screenshot.py +0 -0
  55. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/agent.py +0 -0
  56. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/config/__init__.py +0 -0
  57. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/config/apps.py +0 -0
  58. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/config/i18n.py +0 -0
  59. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/config/prompts.py +0 -0
  60. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/config/prompts_en.py +0 -0
  61. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/config/prompts_zh.py +0 -0
  62. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/model/__init__.py +0 -0
  63. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/phone_agent/model/client.py +0 -0
  64. {autoglm_gui-0.4.9 → autoglm_gui-0.4.12}/scrcpy-server-v3.3.3 +0 -0
@@ -16,4 +16,20 @@ AutoGLM_GUI/static/
16
16
  # Frontend
17
17
  frontend/node_modules/
18
18
  frontend/dist/
19
+
20
+ # Electron
21
+ electron/node_modules/
22
+ electron/dist/
23
+
24
+ # Build resources
25
+ resources/
26
+
27
+ # Logs
28
+ *.log
29
+ logs/
30
+
31
+ # MCP
19
32
  .mcp.json
33
+
34
+ # macOS
35
+ .DS_Store
@@ -5,6 +5,14 @@ import sys
5
5
  from functools import wraps
6
6
  from importlib import metadata
7
7
 
8
+ # 修复 Windows 编码问题 - 必须在所有其他导入之前
9
+ if sys.platform == "win32":
10
+ import codecs
11
+
12
+ sys.stdout = codecs.getwriter("utf-8")(sys.stdout.buffer, "strict")
13
+ sys.stderr = codecs.getwriter("utf-8")(sys.stderr.buffer, "strict")
14
+
15
+
8
16
  # ============================================================================
9
17
  # Fix Windows encoding issue: Force UTF-8 for all subprocess calls
10
18
  # ============================================================================
@@ -1,9 +1,8 @@
1
1
  """CLI entry point for AutoGLM-GUI."""
2
2
 
3
3
  import argparse
4
- import os
5
- import socket
6
4
  import sys
5
+ import socket
7
6
  import threading
8
7
  import time
9
8
  import webbrowser
@@ -76,13 +75,13 @@ def main() -> None:
76
75
  )
77
76
  parser.add_argument(
78
77
  "--base-url",
79
- required=True,
80
- help="Base URL of the model API (required, e.g., http://localhost:8080/v1)",
78
+ required=False,
79
+ help="Base URL of the model API (e.g., http://localhost:8080/v1)",
81
80
  )
82
81
  parser.add_argument(
83
82
  "--model",
84
- default=DEFAULT_MODEL_NAME,
85
- help=f"Model name to use (default: {DEFAULT_MODEL_NAME})",
83
+ default=None,
84
+ help=f"Model name to use (default: {DEFAULT_MODEL_NAME}, or from config file)",
86
85
  )
87
86
  parser.add_argument(
88
87
  "--apikey",
@@ -110,11 +109,22 @@ def main() -> None:
110
109
  action="store_true",
111
110
  help="Do not open browser automatically",
112
111
  )
113
-
114
- # If no arguments provided, print help and exit
115
- if len(sys.argv) == 1:
116
- parser.print_help()
117
- sys.exit(1)
112
+ parser.add_argument(
113
+ "--log-level",
114
+ choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
115
+ default="INFO",
116
+ help="Console log level (default: INFO)",
117
+ )
118
+ parser.add_argument(
119
+ "--log-file",
120
+ default="logs/autoglm_{time:YYYY-MM-DD}.log",
121
+ help="Log file path (default: logs/autoglm_{time:YYYY-MM-DD}.log)",
122
+ )
123
+ parser.add_argument(
124
+ "--no-log-file",
125
+ action="store_true",
126
+ help="Disable file logging",
127
+ )
118
128
 
119
129
  args = parser.parse_args()
120
130
 
@@ -131,16 +141,41 @@ def main() -> None:
131
141
 
132
142
  from AutoGLM_GUI import server
133
143
  from AutoGLM_GUI.config import config
144
+ from AutoGLM_GUI.config_manager import config_manager
145
+ from AutoGLM_GUI.logger import configure_logger
134
146
 
135
- # Set model configuration via environment variables (survives reload)
136
- os.environ["AUTOGLM_BASE_URL"] = args.base_url
137
- os.environ["AUTOGLM_MODEL_NAME"] = args.model
138
- if args.apikey is not None:
139
- os.environ["AUTOGLM_API_KEY"] = args.apikey
147
+ # Configure logging system
148
+ configure_logger(
149
+ console_level=args.log_level,
150
+ log_file=None if args.no_log_file else args.log_file,
151
+ )
152
+
153
+ # ==================== 配置系统初始化 ====================
154
+ # 使用统一配置管理器(四层优先级:CLI > ENV > FILE > DEFAULT)
155
+
156
+ # 1. 设置 CLI 参数配置(最高优先级)
157
+ config_manager.set_cli_config(
158
+ base_url=args.base_url, model_name=args.model, api_key=args.apikey
159
+ )
160
+
161
+ # 2. 加载环境变量配置
162
+ config_manager.load_env_config()
163
+
164
+ # 3. 加载配置文件
165
+ config_manager.load_file_config()
140
166
 
141
- # Refresh config from environment variables
167
+ # 4. 获取合并后的有效配置
168
+ effective_config = config_manager.get_effective_config()
169
+
170
+ # 5. 同步到环境变量(reload 模式需要)
171
+ config_manager.sync_to_env()
172
+
173
+ # 6. 刷新旧的 config 对象(保持现有代码兼容)
142
174
  config.refresh_from_env()
143
175
 
176
+ # 获取配置来源
177
+ config_source = config_manager.get_config_source()
178
+
144
179
  # Display startup banner
145
180
  print()
146
181
  print("=" * 50)
@@ -151,11 +186,19 @@ def main() -> None:
151
186
  print(f" Server: http://{args.host}:{args.port}")
152
187
  print()
153
188
  print(" Model Configuration:")
154
- print(f" Base URL: {args.base_url}")
155
- print(f" Model: {args.model}")
156
- if args.apikey is not None:
157
- print(" API Key: (provided via --apikey)")
189
+ print(f" Source: {config_source.value}")
190
+ print(f" Base URL: {effective_config.base_url or '(not set)'}")
191
+ print(f" Model: {effective_config.model_name}")
192
+ if effective_config.api_key != "EMPTY":
193
+ print(" API Key: (configured)")
158
194
  print()
195
+
196
+ # Warning if base_url is not configured
197
+ if not effective_config.base_url:
198
+ print(" [!] WARNING: base_url is not configured!")
199
+ print(" Please configure via frontend or use --base-url")
200
+ print()
201
+
159
202
  print("=" * 50)
160
203
  print(" Press Ctrl+C to stop")
161
204
  print("=" * 50)
@@ -1,12 +1,20 @@
1
1
  """Lightweight ADB helpers with a more robust screenshot implementation."""
2
2
 
3
+ from .keyboard_installer import ADBKeyboardInstaller
3
4
  from .screenshot import Screenshot, capture_screenshot
4
5
  from .touch import touch_down, touch_move, touch_up
6
+ from .ip import get_wifi_ip
7
+ from .serial import get_device_serial
8
+ from .device import check_device_available
5
9
 
6
10
  __all__ = [
11
+ "ADBKeyboardInstaller",
7
12
  "Screenshot",
8
13
  "capture_screenshot",
9
14
  "touch_down",
10
15
  "touch_move",
11
16
  "touch_up",
17
+ "get_wifi_ip",
18
+ "get_device_serial",
19
+ "check_device_available",
12
20
  ]
@@ -0,0 +1,50 @@
1
+ """Device availability checking utilities."""
2
+
3
+ import asyncio
4
+
5
+ from AutoGLM_GUI.exceptions import DeviceNotAvailableError
6
+ from AutoGLM_GUI.logger import logger
7
+ from AutoGLM_GUI.platform_utils import run_cmd_silently
8
+
9
+
10
+ async def check_device_available(device_id: str | None = None) -> None:
11
+ """Check if the device is available.
12
+
13
+ Args:
14
+ device_id: ADB device serial (None for default device)
15
+
16
+ Raises:
17
+ DeviceNotAvailableError: If device is not reachable
18
+ """
19
+ cmd = ["adb"]
20
+ if device_id:
21
+ cmd.extend(["-s", device_id])
22
+ cmd.append("get-state")
23
+
24
+ try:
25
+ result = await asyncio.wait_for(run_cmd_silently(cmd), timeout=5.0)
26
+
27
+ state = result.stdout.strip() if result.stdout else ""
28
+ error_output = result.stderr.strip() if result.stderr else ""
29
+
30
+ # Check for common error patterns
31
+ if "not found" in error_output.lower() or "offline" in error_output.lower():
32
+ raise DeviceNotAvailableError(
33
+ f"Device {device_id} is not available: {error_output}"
34
+ )
35
+
36
+ if state != "device":
37
+ raise DeviceNotAvailableError(
38
+ f"Device {device_id} is not available (state: {state or 'offline'})"
39
+ )
40
+
41
+ logger.debug(f"Device {device_id} is available (state: {state})")
42
+
43
+ except asyncio.TimeoutError:
44
+ raise DeviceNotAvailableError(f"Device {device_id} connection timed out")
45
+ except FileNotFoundError:
46
+ raise DeviceNotAvailableError("ADB executable not found")
47
+ except DeviceNotAvailableError:
48
+ raise
49
+ except Exception as e:
50
+ raise DeviceNotAvailableError(f"Failed to check device {device_id}: {e}")
@@ -0,0 +1,78 @@
1
+ """ADB IP helpers (prefer WiFi address, skip cellular interfaces)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import subprocess
7
+ from typing import Optional
8
+
9
+ __all__ = ["get_wifi_ip"]
10
+
11
+
12
+ def _run(adb_path: str, device_id: Optional[str], cmd: list[str]) -> str:
13
+ base_cmd = [adb_path]
14
+ if device_id:
15
+ base_cmd.extend(["-s", device_id])
16
+ result = subprocess.run(
17
+ base_cmd + ["shell", *cmd], capture_output=True, text=True, timeout=5
18
+ )
19
+ return (result.stdout or "") + (result.stderr or "")
20
+
21
+
22
+ def _extract_ip(text: str) -> Optional[str]:
23
+ m = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", text)
24
+ if not m:
25
+ return None
26
+ ip = m.group(0)
27
+ if ip == "0.0.0.0":
28
+ return None
29
+ return ip
30
+
31
+
32
+ def get_wifi_ip(
33
+ adb_path: str = "adb", device_id: Optional[str] = None
34
+ ) -> Optional[str]:
35
+ """
36
+ Prefer WiFi IP when multiple interfaces exist.
37
+
38
+ - First try `ip -4 route get 8.8.8.8`, skip typical cellular interfaces (ccmni/rmnet).
39
+ - Fallback to `ip -4 addr show wlan0`.
40
+ Returns None if no suitable IP is found or on error.
41
+ """
42
+ # 1) route
43
+ try:
44
+ route_out = _run(adb_path, device_id, ["ip", "-4", "route", "get", "8.8.8.8"])
45
+ for line in route_out.splitlines():
46
+ if "src" not in line:
47
+ continue
48
+ parts = line.split()
49
+ iface = None
50
+ ip = None
51
+ if "dev" in parts:
52
+ try:
53
+ iface = parts[parts.index("dev") + 1]
54
+ except Exception:
55
+ pass
56
+ if "src" in parts:
57
+ try:
58
+ ip = parts[parts.index("src") + 1]
59
+ except Exception:
60
+ pass
61
+ if not ip or ip == "0.0.0.0":
62
+ continue
63
+ if iface and (iface.startswith("ccmni") or iface.startswith("rmnet")):
64
+ continue
65
+ return ip
66
+ except Exception:
67
+ pass
68
+
69
+ # 2) wlan0 addr
70
+ try:
71
+ addr_out = _run(adb_path, device_id, ["ip", "-4", "addr", "show", "wlan0"])
72
+ ip = _extract_ip(addr_out)
73
+ if ip:
74
+ return ip
75
+ except Exception:
76
+ pass
77
+
78
+ return None
@@ -0,0 +1,380 @@
1
+ """ADB Keyboard Auto-Installation and Enablement Tool.
2
+
3
+ This module provides automatic installation, configuration, and enabling of ADB Keyboard,
4
+ without requiring users to manually download and install APK.
5
+ """
6
+
7
+ import asyncio
8
+ import urllib.request
9
+ from pathlib import Path
10
+ from typing import Optional, Tuple
11
+
12
+ from AutoGLM_GUI.logger import logger
13
+ from AutoGLM_GUI.platform_utils import run_cmd_silently
14
+
15
+ ADB_KEYBOARD_PACKAGE = "com.android.adbkeyboard"
16
+ ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
17
+ ADB_KEYBOARD_APK_URL = (
18
+ "https://github.com/senzhk/ADBKeyBoard/raw/master/ADBKeyboard.apk"
19
+ )
20
+ ADB_KEYBOARD_APK_FILENAME = "ADBKeyboard.apk"
21
+
22
+ # APK file in user cache directory (fallback)
23
+ USER_CACHE_APK_PATH = Path.home() / ".cache" / "autoglm" / ADB_KEYBOARD_APK_FILENAME
24
+
25
+
26
+ class ADBKeyboardInstaller:
27
+ """ADB Keyboard Auto-Installer."""
28
+
29
+ def __init__(self, device_id: Optional[str] = None):
30
+ """
31
+ Initialize the installer.
32
+
33
+ Args:
34
+ device_id: Optional ADB device ID for multi-device scenarios.
35
+ """
36
+ self.device_id = device_id
37
+ self.adb_prefix = ["adb"]
38
+ if device_id:
39
+ self.adb_prefix.extend(["-s", device_id])
40
+
41
+ logger.debug(
42
+ f"Initialized ADBKeyboardInstaller for device: {device_id or 'default'}"
43
+ )
44
+
45
+ def is_installed(self) -> bool:
46
+ """
47
+ Check if ADB Keyboard is installed (via package name).
48
+
49
+ Returns:
50
+ bool: True if installed, False otherwise.
51
+ """
52
+ try:
53
+ logger.debug(
54
+ f"Checking if ADB Keyboard is installed on device {self.device_id or 'default'}"
55
+ )
56
+ result = asyncio.run(
57
+ run_cmd_silently(self.adb_prefix + ["shell", "pm", "list", "packages"])
58
+ )
59
+ package_list = result.stdout.strip()
60
+ installed = ADB_KEYBOARD_PACKAGE in package_list
61
+ logger.debug(f"ADB Keyboard installed: {installed}")
62
+ return installed
63
+ except Exception as e:
64
+ logger.error(f"Error checking keyboard installation status: {e}")
65
+ return False
66
+
67
+ def is_enabled(self) -> bool:
68
+ """
69
+ Check if ADB Keyboard is enabled (usable).
70
+
71
+ Determined by checking the list of enabled input methods.
72
+
73
+ Returns:
74
+ bool: True if enabled, False otherwise.
75
+ """
76
+ try:
77
+ logger.debug(
78
+ f"Checking if ADB Keyboard is enabled on device {self.device_id or 'default'}"
79
+ )
80
+ # Use ime list -s to check only enabled input methods
81
+ result = asyncio.run(
82
+ run_cmd_silently(self.adb_prefix + ["shell", "ime", "list", "-s"])
83
+ )
84
+ ime_list_enabled = result.stdout.strip()
85
+ enabled = ADB_KEYBOARD_IME in ime_list_enabled
86
+ logger.debug(f"ADB Keyboard enabled: {enabled}")
87
+ return enabled
88
+ except Exception as e:
89
+ logger.error(f"Error checking keyboard enable status: {e}")
90
+ return False
91
+
92
+ def get_apk_path(self) -> Optional[Path]:
93
+ """
94
+ Get APK file path.
95
+
96
+ Prioritizes returning the APK file within the project (bundled in wheel),
97
+ falls back to user cache if not exists.
98
+
99
+ Returns:
100
+ Optional[Path]: APK file path, or None if neither exists.
101
+ """
102
+ # Priority 1: Try bundled resource (packaged in wheel)
103
+ try:
104
+ from importlib.resources import files
105
+
106
+ logger.debug("Searching for bundled APK in wheel package")
107
+ resource = files("AutoGLM_GUI").joinpath(
108
+ "resources/apks", ADB_KEYBOARD_APK_FILENAME
109
+ )
110
+ # Convert to Path
111
+ if hasattr(resource, "read_bytes"):
112
+ # For Python 3.9+, use as_file() context manager
113
+ from importlib.resources import as_file
114
+
115
+ with as_file(resource) as path:
116
+ if path.exists():
117
+ logger.info(f"Found bundled APK: {path}")
118
+ return path
119
+ elif hasattr(resource, "_path"):
120
+ # Fallback for older importlib.resources
121
+ path = Path(str(resource))
122
+ if path.exists():
123
+ logger.info(f"Found bundled APK: {path}")
124
+ return path
125
+ except Exception as e:
126
+ logger.debug(f"Bundled APK not found: {e}")
127
+
128
+ # Priority 2: Try user cache directory
129
+ if USER_CACHE_APK_PATH.exists():
130
+ logger.info(f"Found cached APK: {USER_CACHE_APK_PATH}")
131
+ return USER_CACHE_APK_PATH
132
+
133
+ logger.warning("APK file not found in bundled resources or cache")
134
+ return None
135
+
136
+ def download_apk(self, force: bool = False) -> bool:
137
+ """
138
+ Get or download ADB Keyboard APK.
139
+
140
+ Prioritizes using the APK file within the project, downloads from GitHub if not exists.
141
+
142
+ Args:
143
+ force: Whether to force re-download even if file already exists.
144
+
145
+ Returns:
146
+ bool: True if APK is successfully obtained, False otherwise.
147
+ """
148
+ # Check if APK already exists
149
+ existing_apk = self.get_apk_path()
150
+ if existing_apk and not force:
151
+ logger.debug(f"APK already exists at {existing_apk}, skipping download")
152
+ return True
153
+
154
+ # Download from GitHub
155
+ logger.info(f"Downloading ADB Keyboard APK from {ADB_KEYBOARD_APK_URL}")
156
+
157
+ # Ensure cache directory exists
158
+ USER_CACHE_APK_PATH.parent.mkdir(parents=True, exist_ok=True)
159
+
160
+ try:
161
+ urllib.request.urlretrieve(ADB_KEYBOARD_APK_URL, USER_CACHE_APK_PATH)
162
+
163
+ if USER_CACHE_APK_PATH.exists() and USER_CACHE_APK_PATH.stat().st_size > 0:
164
+ logger.info(f"APK downloaded successfully to {USER_CACHE_APK_PATH}")
165
+ return True
166
+ else:
167
+ logger.error("Downloaded APK is empty or invalid")
168
+ return False
169
+
170
+ except Exception as e:
171
+ logger.error(f"Failed to download APK: {e}")
172
+ # Clean up incomplete file
173
+ if USER_CACHE_APK_PATH.exists():
174
+ USER_CACHE_APK_PATH.unlink()
175
+ return False
176
+
177
+ def install(self) -> Tuple[bool, str]:
178
+ """
179
+ Install ADB Keyboard APK.
180
+
181
+ Returns:
182
+ Tuple[bool, str]: (success, message)
183
+ """
184
+ apk_path = self.get_apk_path()
185
+ if not apk_path or not apk_path.exists():
186
+ error_msg = "APK file not found. Please download first."
187
+ logger.error(error_msg)
188
+ return False, error_msg
189
+
190
+ try:
191
+ logger.info(f"Installing ADB Keyboard from {apk_path}")
192
+ result = asyncio.run(
193
+ run_cmd_silently(self.adb_prefix + ["install", "-r", str(apk_path)])
194
+ )
195
+
196
+ if "Success" in result.stdout or result.returncode == 0:
197
+ success_msg = "ADB Keyboard installed successfully"
198
+ logger.info(success_msg)
199
+ return True, success_msg
200
+ else:
201
+ error_msg = f"Installation failed: {result.stdout} {result.stderr}"
202
+ logger.error(error_msg)
203
+ return False, error_msg
204
+
205
+ except Exception as e:
206
+ error_msg = f"Installation error: {e}"
207
+ logger.exception("Unexpected error during installation")
208
+ return False, error_msg
209
+
210
+ def enable(self) -> Tuple[bool, str]:
211
+ """
212
+ Enable ADB Keyboard (enable only, do not modify default input method).
213
+
214
+ Note: This only enables ADB Keyboard, does not set it as default input method.
215
+ In actual usage, Phone Agent will temporarily switch via detect_and_set_adb_keyboard().
216
+
217
+ Returns:
218
+ Tuple[bool, str]: (success, message)
219
+ """
220
+ try:
221
+ logger.info("Enabling ADB Keyboard IME")
222
+ # Enable keyboard
223
+ result = asyncio.run(
224
+ run_cmd_silently(
225
+ self.adb_prefix + ["shell", "ime", "enable", ADB_KEYBOARD_IME]
226
+ )
227
+ )
228
+
229
+ if result.returncode == 0:
230
+ success_msg = "ADB Keyboard enabled successfully"
231
+ logger.info(success_msg)
232
+ return True, success_msg
233
+ else:
234
+ # Some devices return non-zero but still succeed, verify with is_enabled()
235
+ if self.is_enabled():
236
+ success_msg = "ADB Keyboard enabled (verified)"
237
+ logger.info(success_msg)
238
+ return True, success_msg
239
+ else:
240
+ error_msg = f"Enable failed: {result.stdout} {result.stderr}"
241
+ logger.warning(error_msg)
242
+ return False, error_msg
243
+
244
+ except Exception as e:
245
+ error_msg = f"Enable error: {e}"
246
+ logger.exception("Unexpected error during enable")
247
+ return False, error_msg
248
+
249
+ def auto_setup(self) -> Tuple[bool, str]:
250
+ """
251
+ Automatically complete installation and enablement process.
252
+
253
+ Intelligent handling:
254
+ 1. Installed and enabled - skip, return True
255
+ 2. Installed but not enabled - enable only, return result
256
+ 3. Not installed - install+enable, return result
257
+
258
+ Note: This method does not interact with users, all user prompts should be handled by the caller.
259
+
260
+ Returns:
261
+ Tuple[bool, str]: (success, message)
262
+ """
263
+ logger.debug("Starting auto-setup for ADB Keyboard")
264
+
265
+ # Check current status
266
+ installed = self.is_installed()
267
+ enabled = self.is_enabled()
268
+
269
+ # Status 1: Installed and enabled
270
+ if installed and enabled:
271
+ msg = "ADB Keyboard is ready (already installed and enabled)"
272
+ logger.info(msg)
273
+ return True, msg
274
+
275
+ # Status 2: Installed but not enabled
276
+ if installed and not enabled:
277
+ logger.info("ADB Keyboard is installed but not enabled, enabling now")
278
+ return self.enable()
279
+
280
+ # Status 3: Not installed
281
+ if not installed:
282
+ logger.info("ADB Keyboard is not installed, starting installation")
283
+
284
+ # Step 1: Download APK (if not already available)
285
+ if not self.download_apk():
286
+ error_msg = "Failed to download APK"
287
+ logger.error(error_msg)
288
+ return False, error_msg
289
+
290
+ # Step 2: Install
291
+ success, message = self.install()
292
+ if not success:
293
+ logger.error(f"Installation failed: {message}")
294
+ return False, message
295
+
296
+ # Step 3: Enable
297
+ success, message = self.enable()
298
+ if not success:
299
+ logger.error(f"Enable failed: {message}")
300
+ return False, message
301
+
302
+ # Verify final status
303
+ if self.is_installed() and self.is_enabled():
304
+ success_msg = "ADB Keyboard setup completed successfully"
305
+ logger.info(success_msg)
306
+ return True, success_msg
307
+ else:
308
+ error_msg = "Setup completed but verification failed"
309
+ logger.warning(error_msg)
310
+ return False, error_msg
311
+
312
+ # Default return failure
313
+ error_msg = "Unknown status, setup failed"
314
+ logger.error(error_msg)
315
+ return False, error_msg
316
+
317
+ def get_status(self) -> dict:
318
+ """
319
+ Get detailed status of ADB Keyboard.
320
+
321
+ Returns:
322
+ dict: Dictionary containing installation and enablement status.
323
+ """
324
+ apk_path = self.get_apk_path()
325
+ installed = self.is_installed()
326
+ enabled = self.is_enabled()
327
+
328
+ # Determine current status
329
+ if installed and enabled:
330
+ status = "ready" # Ready
331
+ elif installed and not enabled:
332
+ status = "installed_but_disabled" # Installed but not enabled
333
+ elif not installed:
334
+ status = "not_installed" # Not installed
335
+ else:
336
+ status = "unknown" # Unknown
337
+
338
+ return {
339
+ "installed": installed,
340
+ "enabled": enabled,
341
+ "status": status,
342
+ "status_text": {
343
+ "ready": "Installed and enabled",
344
+ "installed_but_disabled": "Installed but not enabled",
345
+ "not_installed": "Not installed",
346
+ "unknown": "Unknown status",
347
+ }.get(status, "Unknown"),
348
+ "apk_exists": apk_path is not None and apk_path.exists(),
349
+ "apk_path": str(apk_path) if apk_path else "N/A",
350
+ "cache_apk_exists": USER_CACHE_APK_PATH.exists(),
351
+ "cache_apk_path": str(USER_CACHE_APK_PATH),
352
+ }
353
+
354
+
355
+ def auto_setup_adb_keyboard(device_id: Optional[str] = None) -> Tuple[bool, str]:
356
+ """
357
+ Convenience function: One-click auto-install and enable ADB Keyboard.
358
+
359
+ Args:
360
+ device_id: Optional device ID.
361
+
362
+ Returns:
363
+ Tuple[bool, str]: (success, message)
364
+ """
365
+ installer = ADBKeyboardInstaller(device_id)
366
+ return installer.auto_setup()
367
+
368
+
369
+ def check_and_suggest_installation() -> bool:
370
+ """
371
+ Check if ADB Keyboard needs installation.
372
+
373
+ Note: This function does not interact with users, only returns boolean value.
374
+ All user prompts should be handled by the caller.
375
+
376
+ Returns:
377
+ bool: True if not installed, False otherwise.
378
+ """
379
+ installer = ADBKeyboardInstaller()
380
+ return not installer.is_installed()