diff --git a/app/src/main/java/cn/com/omnimind/bot/agent/runtime/AgentSystemPrompt.kt b/app/src/main/java/cn/com/omnimind/bot/agent/runtime/AgentSystemPrompt.kt index 12450a844..6cdc78443 100644 --- a/app/src/main/java/cn/com/omnimind/bot/agent/runtime/AgentSystemPrompt.kt +++ b/app/src/main/java/cn/com/omnimind/bot/agent/runtime/AgentSystemPrompt.kt @@ -165,7 +165,12 @@ object AgentSystemPrompt { 工具使用规则: - 需要应用包名或确认安装状态时,优先调用 `context_apps_query`。 - 需要当前日期、时间、星期或时区信息时,使用本轮自动注入的 `[time_context]`,不要再寻找当前时间查询工具。 - - 设备自动化使用 `vlm_task`。 + - 设备界面自动化(操作 App、操作手机屏幕)使用 `vlm_task`。它会把控制权交给一个独立的「computer use」端侧智能体,由它自己看屏幕并完成点击、滑动、输入、按键。 + - 委派 `vlm_task` 时,请用自然语言给出一个清晰、以结果为导向的目标(例如「打开微信,给妈妈发『我在路上了』」),而不是罗列底层步骤;不要逐步指定点击或坐标,端侧智能体会根据屏幕自行规划步骤。 + - 通过 `vlm_task` 启动 App 前,先用 `context_apps_query` 解析包名,并把 packageName 传入,确保打开正确的 App,而不是靠猜。 + - 每次 `vlm_task` 调用尽量只承载一个独立完整的任务;如果请求包含多个互相独立的目标,按顺序分多次执行,而不是塞进一个 prompt。 + - 端侧智能体会回报最终状态:返回 FINISHED 时,向用户总结结果;如果它暂停等待用户接管(如登录、验证码、支付确认),请准确转达用户需要做的操作,再让其恢复;不要在用户被要求接管时自行重试。 + - 如果 `vlm_task` 因临时/超时错误失败,可用同样清晰的目标重试一次;若持续失败,请说明情况而不是反复循环。 - 调用任意工具时都必须提供 4-12 个字、与用户相同的语言的 `tool_title`,。 - 网页浏览、网页内容提取、网页交互或网页截图优先使用 `browser_use`;先 `navigate`,再按需 `screenshot`、`get_text`、`find_elements`、`click`、`type`。 - 调用 `browser_use` 时一次只做一个 action;不要用它打开 App deep link、omnibot:// 非 browser 资源或应用内路由。 @@ -227,7 +232,12 @@ object AgentSystemPrompt { Tool usage rules: - When you need an app package name or need to confirm installation status, prefer `context_apps_query`. - When you need the current date, time, weekday, or timezone, use this turn's injected `[time_context]`; do not look for a current-time query tool. - - Use `vlm_task` for on-device automation. + - Use `vlm_task` for on-device UI automation (operating apps and the phone screen). It hands control to a separate on-device "computer use" agent that sees the screen and performs taps, scrolls, typing, and key presses on its own. + - When delegating to `vlm_task`, give ONE clear, outcome-focused goal in plain language (e.g. "Open WhatsApp and send 'on my way' to Mom"), not a list of low-level steps. Do not micromanage individual taps or coordinates — the computer-use agent figures out the steps from the screen. + - Before launching an app via `vlm_task`, resolve its package name with `context_apps_query` first, and pass the packageName so the agent opens the right app instead of guessing. + - Prefer one self-contained task per `vlm_task` call. If a request has several independent objectives, run them as separate sequential tasks rather than cramming everything into one prompt. + - The computer-use agent reports back a final status: when it returns FINISHED, summarize the outcome for the user; if it pauses waiting for the user to take over (e.g. login, captcha, payment confirmation), relay exactly what the user must do, then let them resume. Do not silently retry a task the user was asked to take over. + - If a `vlm_task` fails on a transient/timeout error, it is reasonable to retry once with the same clear goal; if it keeps failing, explain what happened instead of looping. - Every tool call must include a 4-12 word `tool_title` in the same language as the user. - Prefer `browser_use` for web browsing, extraction, interaction, and screenshots. Start with `navigate`, then use `screenshot`, `get_text`, `find_elements`, `click`, or `type` as needed. - Only perform one browser action per `browser_use` call. Do not use it for app deep links, non-browser `omnibot://` resources, or in-app routes. diff --git a/assists/src/main/java/cn/com/omnimind/assists/controller/http/HttpController.kt b/assists/src/main/java/cn/com/omnimind/assists/controller/http/HttpController.kt index 63bb2b401..dcdc41980 100644 --- a/assists/src/main/java/cn/com/omnimind/assists/controller/http/HttpController.kt +++ b/assists/src/main/java/cn/com/omnimind/assists/controller/http/HttpController.kt @@ -64,6 +64,7 @@ object HttpController { private const val ANTHROPIC_EPHEMERAL_CACHE_TYPE = "ephemeral" private const val ANTHROPIC_MAX_CACHE_BREAKPOINTS = 4 private const val LOCAL_BACKEND_MAX_COMPLETION_TOKENS = 4096 + private const val GEMINI_CU_MAX_ATTEMPTS = 3 /** * JSON text block that acknowledges a Computer Use safety_decision in a @@ -1005,22 +1006,73 @@ object HttpController { ) put("generation_config", JSONObject().put("thinking_level", "high")) } - val requestBody = payload.toString().toRequestBody("application/json".toMediaType()) val url = buildGeminiInteractionsUrl(resolved.apiBase) - val request = Request.Builder() - .url(url) - .addHeader("Content-Type", "application/json") - .addHeader("x-goog-api-key", apiKey) - .post(requestBody) - .build() - val response = openAIStreamClient(forceHttp1 = false).newCall(request).execute() - val responseBody = response.body?.string().orEmpty() - if (!response.isSuccessful) { - throw IllegalStateException("Gemini Computer Use request failed (${response.code}): ${extractAvailabilityMessage(responseBody)}") + + // Transient upstream failures (504 deadline-exceeded, 503, 429, 500, and + // network/timeout IOExceptions) are common with thinking_level:high on + // heavy screens. Retry a few times with backoff instead of aborting the + // whole task on a single hiccup. The payload is rebuilt each attempt + // because an OkHttp RequestBody can only be consumed once. + val maxAttempts = GEMINI_CU_MAX_ATTEMPTS + var lastError: Exception? = null + for (attempt in 1..maxAttempts) { + try { + val requestBody = payload.toString() + .toRequestBody("application/json".toMediaType()) + val request = Request.Builder() + .url(url) + .addHeader("Content-Type", "application/json") + .addHeader("x-goog-api-key", apiKey) + .post(requestBody) + .build() + val response = openAIStreamClient(forceHttp1 = false).newCall(request).execute() + val responseBody = response.body?.string().orEmpty() + if (!response.isSuccessful) { + val code = response.code + if (isRetryableGeminiCuStatus(code) && attempt < maxAttempts) { + OmniLog.w( + "HttpController", + "Gemini CU transient $code (attempt $attempt/$maxAttempts), retrying..." + ) + kotlinx.coroutines.delay(geminiCuBackoffMillis(attempt)) + continue + } + throw IllegalStateException( + "Gemini Computer Use request failed ($code): ${extractAvailabilityMessage(responseBody)}" + ) + } + return@withContext parseGeminiComputerUseInteraction( + responseBody, resolved.resolvedModel, normalizedEnvironment + ) + } catch (io: java.io.IOException) { + // network blip / read timeout — retry + lastError = io + if (attempt < maxAttempts) { + OmniLog.w( + "HttpController", + "Gemini CU IO error (attempt $attempt/$maxAttempts): ${io.message}, retrying..." + ) + kotlinx.coroutines.delay(geminiCuBackoffMillis(attempt)) + continue + } + throw IllegalStateException( + "Gemini Computer Use request failed (network): ${io.message}", io + ) + } } - parseGeminiComputerUseInteraction(responseBody, resolved.resolvedModel, normalizedEnvironment) + throw (lastError ?: IllegalStateException("Gemini Computer Use request failed")) } + private fun isRetryableGeminiCuStatus(code: Int): Boolean = + code == 408 || code == 429 || code == 500 || code == 502 || code == 503 || code == 504 + + private fun geminiCuBackoffMillis(attempt: Int): Long = + when (attempt) { + 1 -> 800L + 2 -> 2000L + else -> 4000L + } + private fun parseGeminiComputerUseInteraction( responseBody: String, model: String, diff --git a/assists/src/main/java/cn/com/omnimind/assists/task/vlmserver/AndroidDeviceOperator.kt b/assists/src/main/java/cn/com/omnimind/assists/task/vlmserver/AndroidDeviceOperator.kt index 9bd584117..4a3186bf0 100644 --- a/assists/src/main/java/cn/com/omnimind/assists/task/vlmserver/AndroidDeviceOperator.kt +++ b/assists/src/main/java/cn/com/omnimind/assists/task/vlmserver/AndroidDeviceOperator.kt @@ -9,6 +9,8 @@ import android.content.Intent import cn.com.omnimind.assists.controller.accessibility.AccessibilityController import cn.com.omnimind.assists.api.eventapi.ExecutionTaskEventApi import cn.com.omnimind.baselib.shizuku.ShizukuCapabilityManager +import cn.com.omnimind.baselib.shizuku.ShizukuControlState +import cn.com.omnimind.baselib.shizuku.ControlMethod import cn.com.omnimind.baselib.util.OmniLog import cn.com.omnimind.baselib.util.exception.PrivacyBlockedException import cn.com.omnimind.omniintelligence.models.ScrollDirection @@ -27,6 +29,112 @@ class AndroidDeviceOperator( private val Tag = "AndroidDeviceOperator" + /** + * Hybrid "Shizuku power mode": when the user enabled it AND Shizuku is + * granted, taps / long-press / text / keys are routed through Shizuku + * (shell-level `input`), which reaches surfaces accessibility gestures + * can't. Scrolling stays on accessibility for smoother flings. Every path + * falls back to accessibility on failure, and reports which technique + * actually ran so the floating window can show a live indicator. + */ + private fun powerMode(): Boolean { + val ctx = context ?: return false + return ShizukuControlState.isShizukuPowerModeActive(ctx) + } + + private suspend fun shizukuTap(x: Float, y: Float): Boolean { + val ctx = context ?: return false + return runCatching { + ShizukuCapabilityManager.get(ctx).tap(x.toInt(), y.toInt()).success + }.getOrDefault(false) + } + + private suspend fun shizukuLongPress(x: Float, y: Float, duration: Long): Boolean { + val ctx = context ?: return false + return runCatching { + ShizukuCapabilityManager.get(ctx) + .longPress(x.toInt(), y.toInt(), duration.toInt().coerceAtLeast(300)) + .success + }.getOrDefault(false) + } + + private suspend fun shizukuSwipe( + x1: Float, y1: Float, x2: Float, y2: Float, duration: Long + ): Boolean { + val ctx = context ?: return false + return runCatching { + ShizukuCapabilityManager.get(ctx) + .swipe(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt(), duration.toInt()) + .success + }.getOrDefault(false) + } + + private suspend fun shizukuKey(key: String): Boolean { + val ctx = context ?: return false + return runCatching { + ShizukuCapabilityManager.get(ctx).pressKeyEvent(key).success + }.getOrDefault(false) + } + + private fun reportMethod(method: ControlMethod) = ShizukuControlState.reportMethod(method) + + // ----- action runners: prefer Shizuku in power mode, fall back to accessibility ----- + + private suspend fun runTap(x: Float, y: Float) { + // Accessibility gesture-tap is the PRIMARY path even in power mode: it + // dispatches a proper down/up tap that reliably focuses text fields and + // raises the IME, so the CU model sees the field focus in the next + // screenshot and proceeds to type. A raw Shizuku `input tap` frequently + // does not register focus the same way, which makes the model re-tap the + // text box in a loop. Shizuku tap is only a fallback for surfaces the + // accessibility gesture can't reach (timeout/permission) in power mode. + try { + AccessibilityController.clickCoordinate(x, y) + reportMethod(ControlMethod.ACCESSIBILITY) + } catch (e: Exception) { + if (powerMode() && shizukuTap(x, y)) { + reportMethod(ControlMethod.SHIZUKU) + } else { + throw e + } + } + } + + private suspend fun runLongClick(x: Float, y: Float, duration: Long) { + // Same reasoning as runTap: accessibility-first for reliable focus/menus, + // Shizuku long-press only as a reach fallback in power mode. + try { + AccessibilityController.longClickCoordinate(x, y, duration) + reportMethod(ControlMethod.ACCESSIBILITY) + } catch (e: Exception) { + if (powerMode() && shizukuLongPress(x, y, duration)) { + reportMethod(ControlMethod.SHIZUKU) + } else { + throw e + } + } + } + + private suspend fun runScroll( + x: Float, y: Float, direction: ScrollDirection, distance: Float, duration: Long, + x2: Float, y2: Float + ) { + // Hybrid: accessibility first for smooth flings; Shizuku swipe as fallback. + val ok = runCatching { + AccessibilityController.scrollCoordinate(x, y, direction, distance, duration = duration) + true + }.getOrDefault(false) + if (ok) { + reportMethod(ControlMethod.ACCESSIBILITY); return + } + if (powerMode() && shizukuSwipe(x, y, x2, y2, duration.coerceAtLeast(1))) { + reportMethod(ControlMethod.SHIZUKU); return + } + // surface the accessibility failure path + AccessibilityController.scrollCoordinate(x, y, direction, distance, duration = duration) + reportMethod(ControlMethod.ACCESSIBILITY) + } + // 存储最后一次截图的尺寸(传给VLM的图片)以及设备实际尺寸 private var lastScreenshotWidth: Int = 1080 private var lastScreenshotHeight: Int = 1920 @@ -60,10 +168,10 @@ class AndroidDeviceOperator( return try { if (executionTaskEventApi != null) { executionTaskEventApi.clickCoordinate(x, y) { - AccessibilityController.clickCoordinate(x, y) + runTap(x, y) } } else { - AccessibilityController.clickCoordinate(x, y) + runTap(x, y) } OperationResult(true, "点击坐标 ($x, $y) 成功", null) } catch (e: Exception) { @@ -75,10 +183,10 @@ class AndroidDeviceOperator( return try { if (executionTaskEventApi != null) { executionTaskEventApi.longClickCoordinate(x, y) { - AccessibilityController.longClickCoordinate(x, y, duration) + runLongClick(x, y, duration) } } else { - AccessibilityController.longClickCoordinate(x, y, duration) + runLongClick(x, y, duration) } OperationResult(true, "长按坐标 ($x, $y) 成功", null) } catch (e: Exception) { @@ -87,6 +195,12 @@ class AndroidDeviceOperator( } override suspend fun inputText(text: String): OperationResult { + // Text entry ALWAYS prefers accessibility ACTION_SET_TEXT even in power mode: + // it sets the whole string atomically on the focused node and handles any + // unicode. Shizuku `input text` can't type non-ASCII, fires char-by-char + // keyevents that drop on stubborn fields, and reports success even when + // nothing lands in the box. So we only fall back to Shizuku if accessibility + // actually throws. (Power mode still uses Shizuku for taps/long-press/keys.) return try { if (executionTaskEventApi != null) { executionTaskEventApi.inputText() { @@ -95,10 +209,12 @@ class AndroidDeviceOperator( } else { AccessibilityController.inputTextToFocusedNode(text) } + reportMethod(ControlMethod.ACCESSIBILITY) OperationResult(true, "输入文本成功: $text", null) } catch (e: Exception) { val shizukuFallback = inputTextViaShizuku(text) if (shizukuFallback.success) { + reportMethod(ControlMethod.SHIZUKU) return shizukuFallback } val shellFallback = inputTextViaShell(text) @@ -111,13 +227,20 @@ class AndroidDeviceOperator( override suspend fun pressHotKey(key: String): OperationResult { val normalized = key.trim().uppercase() + // In power mode, prefer Shizuku keyevent (works on more surfaces). + if (powerMode() && shizukuKey(normalized)) { + reportMethod(ControlMethod.SHIZUKU) + return OperationResult(true, "通过 Shizuku 按下 $normalized 成功", null) + } return try { AccessibilityController.pressHotKey(normalized) + reportMethod(ControlMethod.ACCESSIBILITY) OperationResult(true, "按下热键 $normalized 成功", null) } catch (primaryError: Exception) { if (normalized == "ENTER") { val shizukuFallback = pressEnterViaShizuku() if (shizukuFallback.success) { + reportMethod(ControlMethod.SHIZUKU) return shizukuFallback } val fallback = pressEnterViaShell() @@ -305,22 +428,10 @@ class AndroidDeviceOperator( scrollDirection, distance.toInt() ) { - AccessibilityController.scrollCoordinate( - x1, - y1, - scrollDirection, - distance, - duration = duration - ) + runScroll(x1, y1, scrollDirection, distance, duration, x2, y2) } } else { - AccessibilityController.scrollCoordinate( - x1, - y1, - scrollDirection, - distance, - duration = duration - ) + runScroll(x1, y1, scrollDirection, distance, duration, x2, y2) } OperationResult(true, "滑动 ($x1, $y1) → ($x2, $y2) 成功", null) } catch (e: Exception) { @@ -330,14 +441,12 @@ class AndroidDeviceOperator( override suspend fun goHome(): OperationResult { return try { - - if (executionTaskEventApi != null) { executionTaskEventApi.goHome { - AccessibilityController.goHome() + runGoHome() } } else { - AccessibilityController.goHome() + runGoHome() } OperationResult(true, "返回桌面成功", null) @@ -346,14 +455,22 @@ class AndroidDeviceOperator( } } + private suspend fun runGoHome() { + if (powerMode() && shizukuKey("HOME")) { + reportMethod(ControlMethod.SHIZUKU); return + } + AccessibilityController.goHome() + reportMethod(ControlMethod.ACCESSIBILITY) + } + override suspend fun goBack(): OperationResult { return try { if (executionTaskEventApi != null) { executionTaskEventApi.goBack { - AccessibilityController.goBack() + runGoBack() } } else { - AccessibilityController.goBack() + runGoBack() } OperationResult(true, "返回上一级成功", null) } catch (e: Exception) { @@ -361,6 +478,14 @@ class AndroidDeviceOperator( } } + private suspend fun runGoBack() { + if (powerMode() && shizukuKey("BACK")) { + reportMethod(ControlMethod.SHIZUKU); return + } + AccessibilityController.goBack() + reportMethod(ControlMethod.ACCESSIBILITY) + } + /** * 启动应用 */ diff --git a/baselib/src/main/java/cn/com/omnimind/baselib/shizuku/ShizukuCapabilityManager.kt b/baselib/src/main/java/cn/com/omnimind/baselib/shizuku/ShizukuCapabilityManager.kt index 6bab1ce49..45507c98f 100644 --- a/baselib/src/main/java/cn/com/omnimind/baselib/shizuku/ShizukuCapabilityManager.kt +++ b/baselib/src/main/java/cn/com/omnimind/baselib/shizuku/ShizukuCapabilityManager.kt @@ -370,6 +370,35 @@ class ShizukuCapabilityManager private constructor( ) } + /** + * Tap at absolute display pixel coordinates via `input tap` (shell-level). + * Works on many surfaces accessibility gestures can't reach. + */ + suspend fun tap(x: Int, y: Int): PrivilegedResult { + return executeRawShell("input tap $x $y", confirmed = true) + } + + /** + * Swipe/scroll between absolute display pixels via `input swipe`. + * durationMs controls fling speed (smaller = faster fling). + */ + suspend fun swipe(x1: Int, y1: Int, x2: Int, y2: Int, durationMs: Int): PrivilegedResult { + return executeRawShell( + "input swipe $x1 $y1 $x2 $y2 ${durationMs.coerceAtLeast(1)}", + confirmed = true + ) + } + + /** + * Long-press at a point by issuing a zero-distance swipe held for durationMs. + */ + suspend fun longPress(x: Int, y: Int, durationMs: Int): PrivilegedResult { + return executeRawShell( + "input swipe $x $y $x $y ${durationMs.coerceAtLeast(1)}", + confirmed = true + ) + } + private suspend fun execute(request: PrivilegedRequest): PrivilegedResult { val status = getStatus() if (!status.isGranted()) { diff --git a/baselib/src/main/java/cn/com/omnimind/baselib/shizuku/ShizukuControlState.kt b/baselib/src/main/java/cn/com/omnimind/baselib/shizuku/ShizukuControlState.kt new file mode 100644 index 000000000..b0c6e3ea1 --- /dev/null +++ b/baselib/src/main/java/cn/com/omnimind/baselib/shizuku/ShizukuControlState.kt @@ -0,0 +1,92 @@ +package cn.com.omnimind.baselib.shizuku + +import android.content.Context +import cn.com.omnimind.baselib.util.OmniLog +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +/** + * Which low-level technique physically performed the most recent device action. + * This is the "hand" layer (how a tap/scroll/keystroke is delivered), NOT the + * "brain" layer (Computer Use vs legacy, which is decided by the model binding). + */ +enum class ControlMethod { + SHIZUKU, + ACCESSIBILITY +} + +/** + * Central state for the optional "Shizuku power mode". + * + * - Persists the user's "prefer Shizuku control" toggle (mirrored with the + * Flutter shared_preferences store so both the Dart UI and the native + * executor read the same value). + * - Tracks, at runtime, which technique (Shizuku vs Accessibility) last drove + * the phone, so the floating operation window can show a live indicator. + */ +object ShizukuControlState { + + private const val TAG = "[ShizukuControlState]" + + // Raw key. The Flutter shared_preferences plugin stores it as + // "flutter.prefer_shizuku_control" inside FlutterSharedPreferences. + const val PREF_KEY = "prefer_shizuku_control" + private const val NATIVE_PREFS = "OmnibotSettings" + private const val FLUTTER_PREFS = "FlutterSharedPreferences" + private const val FLUTTER_KEY = "flutter.$PREF_KEY" + + private val _activeMethod = MutableStateFlow(null) + + /** Last technique that actually executed a device action, or null when idle. */ + val activeMethod: StateFlow = _activeMethod + + /** Reported by the device executor after each action. */ + fun reportMethod(method: ControlMethod) { + _activeMethod.value = method + } + + /** Clear the live indicator (e.g. when a task ends). */ + fun clearMethod() { + _activeMethod.value = null + } + + /** Whether the user opted into routing taps/keys through Shizuku. Defaults to off. */ + fun isPreferShizuku(context: Context): Boolean { + return try { + val native = context.getSharedPreferences(NATIVE_PREFS, Context.MODE_PRIVATE) + if (native.contains(PREF_KEY)) return native.getBoolean(PREF_KEY, false) + context.getSharedPreferences(FLUTTER_PREFS, Context.MODE_PRIVATE) + .getBoolean(FLUTTER_KEY, false) + } catch (e: Exception) { + OmniLog.e(TAG, "read prefer-shizuku failed: ${e.message}") + false + } + } + + /** Persist the toggle natively (Flutter side persists via shared_preferences). */ + fun setPreferShizuku(context: Context, enabled: Boolean): Boolean { + return try { + context.getSharedPreferences(NATIVE_PREFS, Context.MODE_PRIVATE) + .edit() + .putBoolean(PREF_KEY, enabled) + .commit() + } catch (e: Exception) { + OmniLog.e(TAG, "write prefer-shizuku failed: ${e.message}") + false + } + } + + /** + * Power mode is active only when the user enabled it AND Shizuku is actually + * granted/connected. If Shizuku isn't ready we silently stay on accessibility. + */ + fun isShizukuPowerModeActive(context: Context): Boolean { + if (!isPreferShizuku(context)) return false + return try { + ShizukuCapabilityManager.get(context).isGranted() + } catch (e: Exception) { + OmniLog.e(TAG, "shizuku granted check failed: ${e.message}") + false + } + } +} diff --git a/ui/lib/features/home/pages/scene_model_setting/scene_model_setting_page.dart b/ui/lib/features/home/pages/scene_model_setting/scene_model_setting_page.dart index 98ef4bc6f..37f08ad25 100644 --- a/ui/lib/features/home/pages/scene_model_setting/scene_model_setting_page.dart +++ b/ui/lib/features/home/pages/scene_model_setting/scene_model_setting_page.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; import 'package:ui/services/assists_core_service.dart'; import 'package:ui/services/model_provider_config_service.dart'; import 'package:ui/services/scene_model_config_service.dart'; +import 'package:ui/services/special_permission.dart'; +import 'package:ui/services/storage_service.dart'; import 'package:ui/theme/app_colors.dart'; import 'package:ui/theme/theme_context.dart'; import 'package:ui/utils/popup_menu_anchor_position.dart'; @@ -79,6 +81,12 @@ class _SceneModelSettingPageState extends State { bool _isRefreshingModels = false; bool _isSavingVoiceConfig = false; + // Shizuku power-mode state + static const String _kPreferShizukuKey = 'prefer_shizuku_control'; + ShizukuStatusSnapshot? _shizukuStatus; + bool _preferShizuku = false; + bool _savingPreferShizuku = false; + List _catalog = const []; List _bindings = const []; List _profiles = const []; @@ -108,6 +116,7 @@ class _SceneModelSettingPageState extends State { _voiceIdController = TextEditingController(); _voiceCustomStyleController = TextEditingController(); _loadData(); + _loadShizukuState(); _configChangedSubscription = AssistsMessageService .agentAiConfigChangedStream .listen((event) { @@ -261,6 +270,216 @@ class _SceneModelSettingPageState extends State { ); } + // Bilingual helper: English for English users, Chinese otherwise. + String _t(String en, String zh) => LegacyTextLocalizer.isEnglish ? en : zh; + + Future _loadShizukuState() async { + final prefer = + StorageService.getBool(_kPreferShizukuKey, defaultValue: false) ?? false; + ShizukuStatusSnapshot status; + try { + status = await getShizukuStatus(); + } catch (_) { + status = ShizukuStatusSnapshot.fallback(); + } + if (!mounted) return; + setState(() { + _preferShizuku = prefer; + _shizukuStatus = status; + }); + } + + Future _setPreferShizuku(bool value) async { + setState(() { + _preferShizuku = value; + _savingPreferShizuku = true; + }); + try { + await StorageService.setBool(_kPreferShizukuKey, value); + // Refresh Shizuku status so the card reflects current grant state. + final status = await getShizukuStatus(); + if (!mounted) return; + setState(() => _shizukuStatus = status); + } catch (_) { + // keep optimistic value; status card will refresh on next open + } finally { + if (mounted) setState(() => _savingPreferShizuku = false); + } + } + + Future _requestShizukuFromCard() async { + try { + await requestShizukuPermission(); + } catch (_) {} + await _loadShizukuState(); + } + + Widget _buildShizukuControlCard() { + final status = _shizukuStatus; + final granted = status?.isGranted ?? false; + final accent = (_preferShizuku && granted) + ? const Color(0xFF18A957) + : context.omniPalette.accentPrimary; + final statusLabel = status?.localizedStatusLabel ?? + _t('Checking…', '检测中…'); + + final modeLabel = (_preferShizuku && granted) + ? _t('Hybrid (Shizuku + Accessibility)', '混合(Shizuku + 无障碍)') + : _t('Accessibility only', '仅无障碍'); + + return Container( + width: double.infinity, + margin: const EdgeInsets.only(bottom: 16), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: _cardColor, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: accent.withValues(alpha: 0.35), width: 1), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.shield_outlined, size: 20, color: accent), + const SizedBox(width: 8), + Expanded( + child: Text( + _t('Shizuku Control (Power Mode)', 'Shizuku 控制(增强模式)'), + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + color: + _isDarkTheme ? Colors.white : const Color(0xFF1A1A1A), + ), + ), + ), + Container( + padding: + const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: accent.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(20), + ), + child: Text( + modeLabel, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: accent, + ), + ), + ), + ], + ), + const SizedBox(height: 10), + Text( + _t( + 'When ON, key presses (Home/Back/Enter) are sent through Shizuku (shell-level, reaches tougher surfaces). Taps, long-press, scrolling and text input stay on Accessibility for reliable focus and smooth flings, with Shizuku used automatically as a fallback only when an Accessibility gesture can\'t reach. When OFF, everything uses Accessibility only.', + '开启后,按键(Home/Back/Enter)通过 Shizuku(shell 级,可触达更复杂界面)执行;点击、长按、滑动和文本输入仍走无障碍以保证可靠聚焦与顺滑滚动,仅当无障碍手势无法触达时才自动回退到 Shizuku。关闭时全部仅用无障碍。', + ), + style: TextStyle( + color: _secondaryTextColor, + fontSize: 12, + height: 1.5, + ), + ), + const SizedBox(height: 12), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: (_isDarkTheme ? Colors.white : Colors.black) + .withValues(alpha: 0.04), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + Icon( + granted ? Icons.check_circle : Icons.error_outline, + size: 16, + color: granted + ? const Color(0xFF18A957) + : context.omniPalette.accentPrimary, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + '${_t('Shizuku', 'Shizuku')}: $statusLabel', + style: TextStyle( + color: _secondaryTextColor, + fontSize: 12, + ), + ), + ), + ], + ), + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: Text( + _t('Prefer Shizuku control', '优先使用 Shizuku 控制'), + style: TextStyle( + color: _primaryTextColor, + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + if (_savingPreferShizuku) + const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ) + else + Switch( + value: _preferShizuku, + activeColor: const Color(0xFF18A957), + onChanged: (v) => _setPreferShizuku(v), + ), + ], + ), + if (_preferShizuku && !granted) ...[ + const SizedBox(height: 6), + Text( + _t( + 'Shizuku isn\'t granted yet, so control will stay on Accessibility until you grant it.', + 'Shizuku 尚未授权,授权前将继续使用无障碍控制。', + ), + style: TextStyle( + color: context.omniPalette.accentPrimary, + fontSize: 12, + height: 1.4, + ), + ), + const SizedBox(height: 8), + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: _requestShizukuFromCard, + child: Text(_t('Grant Shizuku permission', '授予 Shizuku 权限')), + ), + ), + ], + const SizedBox(height: 8), + Text( + _t( + 'Note: Shizuku must be re-started after each reboot. During a task, the operation window shows a live badge (🛡 Shizuku / 👆 Accessibility) telling you which one is driving each action.', + '注意:每次重启后需重新启动 Shizuku。任务执行时,操作窗口会显示实时标记(🛡 Shizuku / 👆 无障碍),告诉你每个动作由哪种方式执行。', + ), + style: TextStyle( + color: _tertiaryTextColor, + fontSize: 11, + height: 1.4, + ), + ), + ], + ), + ); + } + Widget _buildPhoneComputerUseCard() { final active = _isPhoneComputerUseActive; final saving = @@ -285,7 +504,7 @@ class _SceneModelSettingPageState extends State { const SizedBox(width: 8), Expanded( child: Text( - context.trLegacy('手机 Computer Use'), + _t('Phone Computer Use', '手机 Computer Use'), style: TextStyle( fontSize: 15, fontWeight: FontWeight.w600, @@ -303,7 +522,7 @@ class _SceneModelSettingPageState extends State { borderRadius: BorderRadius.circular(20), ), child: Text( - active ? context.trLegacy('已开启') : context.trLegacy('未开启'), + _t(active ? 'On' : 'Off', active ? '已开启' : '未开启'), style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, @@ -316,7 +535,8 @@ class _SceneModelSettingPageState extends State { ), const SizedBox(height: 10), Text( - context.trLegacy( + _t( + 'One tap makes phone & browser control use Gemini 3.5 Flash (native Computer Use + high reasoning) — the smartest, most reliable control mode. Enabling switches the Operation and Agent scenes to gemini-3.5-flash.', '一键让手机与浏览器控制使用 Gemini 3.5 Flash(原生 Computer Use + 高强度推理)——目前最聪明、最稳的操控模式。开启后会把 Operation 与 Agent 两个场景切换到 gemini-3.5-flash。', ), style: TextStyle( @@ -346,8 +566,8 @@ class _SceneModelSettingPageState extends State { ) : Text( active - ? context.trLegacy('重新应用最佳配置') - : context.trLegacy('一键开启手机 Computer Use'), + ? _t('Re-apply best config', '重新应用最佳配置') + : _t('Enable Phone Computer Use', '一键开启手机 Computer Use'), style: const TextStyle( color: Colors.white, fontWeight: FontWeight.w600, @@ -1220,6 +1440,7 @@ class _SceneModelSettingPageState extends State { padding: const EdgeInsets.fromLTRB(18, 12, 18, 24), children: [ _buildPhoneComputerUseCard(), + _buildShizukuControlCard(), SettingsSectionTitle( label: context.l10n.sceneModelMapping, subtitle: context.l10n.sceneModelMappingDesc, diff --git a/uikit/src/main/java/cn/com/omnimind/uikit/api/eventimpl/ExecutionUIImpl.kt b/uikit/src/main/java/cn/com/omnimind/uikit/api/eventimpl/ExecutionUIImpl.kt index d9517d08a..cfad8fbb3 100644 --- a/uikit/src/main/java/cn/com/omnimind/uikit/api/eventimpl/ExecutionUIImpl.kt +++ b/uikit/src/main/java/cn/com/omnimind/uikit/api/eventimpl/ExecutionUIImpl.kt @@ -4,6 +4,10 @@ import cn.com.omnimind.assists.api.enums.TaskFinishType import cn.com.omnimind.assists.api.eventapi.ExecutingTaskType import cn.com.omnimind.assists.api.eventapi.ExecutionTaskEventApi import cn.com.omnimind.assists.task.vlmserver.VLMOperationTask +import cn.com.omnimind.baselib.i18n.AppLocaleManager +import cn.com.omnimind.baselib.i18n.LocalizedText +import cn.com.omnimind.baselib.shizuku.ControlMethod +import cn.com.omnimind.baselib.shizuku.ShizukuControlState import cn.com.omnimind.baselib.util.OmniLog import cn.com.omnimind.omniintelligence.models.ScrollDirection import cn.com.omnimind.uikit.api.uievent.UIBaseEvent @@ -24,7 +28,7 @@ class ExecutionUIImpl( override suspend fun onReadyStartVLMTask(task: VLMOperationTask) { taskType = ExecutingTaskType.VLM vlmTask = task - uiTaskEvent.readyDoingTask("小万即将为您执行任务...") + uiTaskEvent.readyDoingTask(tr("小万即将为您执行任务...", "Omnibot is getting ready to run your task...")) // 可取消的延迟:每100ms检查一次取消状态,共检查20次(2秒) repeat(20) { @@ -41,7 +45,8 @@ class ExecutionUIImpl( } if (isCompanionRunning) { uiTaskEvent.startDoingAutoTask( - "小万已领取任务,即将开始执行", "智能执行中" + tr("小万已领取任务,即将开始执行", "Omnibot accepted the task, starting now"), + tr("智能执行中", "Running") ) } else { uiTaskEvent.startCompanionAndDoingTask() @@ -50,7 +55,7 @@ class ExecutionUIImpl( override suspend fun onVlmTaskPaused(vmlTask: VLMOperationTask) { uiBaseEvent.cancelLockScreenMask() - uiTaskEvent.pauseTask("用户已接管任务") + uiTaskEvent.pauseTask(tr("用户已接管任务", "You've taken over the task")) } override suspend fun onVLMTaskStop( @@ -59,15 +64,16 @@ class ExecutionUIImpl( if (finishType == TaskFinishType.WAITING_INPUT) { val isResume = uiTaskEvent.waitingUserAction(message) if (isResume) { - vlmTask?.provideUserInput("用户已完成操作,请继续执行") + vlmTask?.provideUserInput(tr("用户已完成操作,请继续执行", "I've finished, please continue")) } else { vlmTask?.finishTask() } } else if (finishType == TaskFinishType.USER_PAUSED) { - uiTaskEvent.pauseTask("用户已接管任务") + uiTaskEvent.pauseTask(tr("用户已接管任务", "You've taken over the task")) OmniLog.d("StateMachine", "VLM任务进入用户主动暂停状态") } else { vlmTask = null + ShizukuControlState.clearMethod() uiTaskEvent.finishDoingTask(message.ifEmpty { finishType.message }) if (!isCompanionRunning) { delay(500)//动画执行完毕再执行结束 @@ -77,7 +83,7 @@ class ExecutionUIImpl( } override suspend fun readyOpenThirdAPP(packageName: String) { - uiTaskEvent.setDoing("正在打开应用...", false); + uiTaskEvent.setDoing(tr("正在打开应用...", "Opening app..."), false); } //无障碍能力相关 @@ -176,8 +182,27 @@ class ExecutionUIImpl( return uiTaskEvent.waitingUserAction(message) } + // Localize fixed floating-window status strings to the app language. + private fun tr(zh: String, en: String): String = + LocalizedText(zhCN = zh, enUS = en).resolve(AppLocaleManager.currentPromptLocale()) + override suspend fun updateShowStepText(message: String) { - uiTaskEvent.setDoing(message, true) + uiTaskEvent.setDoing(withControlMethodBadge(message), true) + } + + /** + * Prefix the step text with a live badge showing which technique is + * currently driving the phone (Shizuku vs Accessibility), so the user can + * see in real time how each action is being delivered. Shows nothing until + * the first action has run. + */ + private fun withControlMethodBadge(message: String): String { + val badge = when (ShizukuControlState.activeMethod.value) { + ControlMethod.SHIZUKU -> "🛡 Shizuku" + ControlMethod.ACCESSIBILITY -> "👆 Accessibility" + null -> return message + } + return "[$badge] $message" } override suspend fun dismissScheduledNotification() { diff --git a/uikit/src/main/java/cn/com/omnimind/uikit/api/uieventimpl/UITaskEventImpl.kt b/uikit/src/main/java/cn/com/omnimind/uikit/api/uieventimpl/UITaskEventImpl.kt index 9d4f85149..df3587d7d 100644 --- a/uikit/src/main/java/cn/com/omnimind/uikit/api/uieventimpl/UITaskEventImpl.kt +++ b/uikit/src/main/java/cn/com/omnimind/uikit/api/uieventimpl/UITaskEventImpl.kt @@ -2,6 +2,8 @@ package cn.com.omnimind.uikit.api.uieventimpl import android.content.Context import cn.com.omnimind.assists.api.eventapi.ExecutingTaskType +import cn.com.omnimind.baselib.i18n.AppLocaleManager +import cn.com.omnimind.baselib.i18n.LocalizedText import cn.com.omnimind.baselib.util.VibrationUtil import cn.com.omnimind.uikit.UIKit import cn.com.omnimind.uikit.api.uievent.UITaskEvent @@ -18,6 +20,9 @@ import kotlinx.coroutines.withContext class UITaskEventImpl : UITaskEvent { private var taskUIJob: CoroutineScope? = null + + private fun tr(zh: String, en: String): String = + LocalizedText(zhCN = zh, enUS = en).resolve(AppLocaleManager.currentPromptLocale()) private var context: Context? = null override fun onUIInit(context: Context) { @@ -45,8 +50,8 @@ class UITaskEventImpl : UITaskEvent { DraggableBallInstance.loadBall() ScreenMaskLoader.loadLockScreenMask() DraggableBallInstance.doingTask( - "小万已领取任务,即将开始执行", - "执行中" + tr("小万已领取任务,即将开始执行", "Omnibot accepted the task, starting now"), + tr("执行中", "Running") ) } } @@ -60,12 +65,12 @@ class UITaskEventImpl : UITaskEvent { val isResume = DraggableBallInstance.userTakeover(message) if (isResume) { val subMessage = when (UIKit.executionTaskEventApi?.taskType) { - ExecutingTaskType.VLM -> "智能执行中" - ExecutingTaskType.EMPTY -> "智能执行中" - null -> "智能执行中" + ExecutingTaskType.VLM -> tr("智能执行中", "Running") + ExecutingTaskType.EMPTY -> tr("智能执行中", "Running") + null -> tr("智能执行中", "Running") } withContext(Dispatchers.Main) { - DraggableBallInstance.doingTask("用户操作已完成", subMessage) + DraggableBallInstance.doingTask(tr("用户操作已完成", "Your action is complete"), subMessage) } } return isResume