diff --git a/app/src/main/java/com/wangzan101/mika/MikaApp.kt b/app/src/main/java/com/wangzan101/mika/MikaApp.kt index 4c7c67b678..40225cd46f 100644 --- a/app/src/main/java/com/wangzan101/mika/MikaApp.kt +++ b/app/src/main/java/com/wangzan101/mika/MikaApp.kt @@ -577,6 +577,9 @@ class MikaApp : Application(), WebOwner, SandboxOwner, TaskEnvironment.Owner, Ph capsule.start() // 内置助手的真实现,并开始看着助手(Mika 进程起来后,还活着的助手会自己交接 Binder) phone.shellManager.start() + // 银行模式暂停着:进程重启后把暂停重设上,看门狗不再把助手起回来, + // 无障碍自动修复也不会把它打开。用户在设置 › 银行模式里恢复之前一直停着。 + if (com.wangzan101.mika.settings.BankingMode.isPaused(this)) phone.shellControl.pause() // 连接一可用就补上默认打开的几项能力 phone.recovery.start() // 告诉内置助手:Mika 被杀后要不要把它拉起来(胶囊一直显示或有任务在跑时才要;退出期间都不要) diff --git a/app/src/main/java/com/wangzan101/mika/cap/phone/setup/BuiltinShellRecovery.kt b/app/src/main/java/com/wangzan101/mika/cap/phone/setup/BuiltinShellRecovery.kt index 722c349aa5..f098269646 100644 --- a/app/src/main/java/com/wangzan101/mika/cap/phone/setup/BuiltinShellRecovery.kt +++ b/app/src/main/java/com/wangzan101/mika/cap/phone/setup/BuiltinShellRecovery.kt @@ -31,6 +31,7 @@ import com.wangzan101.mika.core.shell.RecoveryPolicy import com.wangzan101.mika.core.shell.RestoreOutcome import com.wangzan101.mika.core.shell.ShellCommandRunner import com.wangzan101.mika.core.shell.ShellTransport +import com.wangzan101.mika.settings.BankingMode import com.wangzan101.mika.settings.FeatureFlags import com.wangzan101.mika.settings.RecoverySettings import kotlinx.coroutines.CoroutineScope @@ -77,6 +78,7 @@ class BuiltinShellRecovery( consent = { settings.consent.value }, direct = ::canWriteSecure, allowed = { !FeatureFlags.get(app).quitRequested() }, + paused = { BankingMode.isPaused(app) || control.paused }, ) private fun canWriteSecure() = diff --git a/app/src/main/java/com/wangzan101/mika/cap/phone/setup/DeveloperSettings.kt b/app/src/main/java/com/wangzan101/mika/cap/phone/setup/DeveloperSettings.kt index 63d26f682f..3943975820 100644 --- a/app/src/main/java/com/wangzan101/mika/cap/phone/setup/DeveloperSettings.kt +++ b/app/src/main/java/com/wangzan101/mika/cap/phone/setup/DeveloperSettings.kt @@ -52,6 +52,14 @@ object DeveloperSettings { fun turnOnWirelessDebugging(cr: ContentResolver): Boolean = runCatching { Settings.Global.putInt(cr, ADB_WIFI_ENABLED, 1) }.getOrDefault(false) + /** + * 把无线调试开关写成关闭(要有修改系统设置的授权,和打开同一条路)。 + * 只关开关,不解除配对:配对钥匙、端口缓存和系统里的授权记录都留着, + * 再打开时直接用已配对的连接重连,不用重新配对。写入被拒返回 false。 + */ + fun turnOffWirelessDebugging(cr: ContentResolver): Boolean = + runCatching { Settings.Global.putInt(cr, ADB_WIFI_ENABLED, 0) }.getOrDefault(false) + fun usbDebugging(cr: ContentResolver): Boolean = Settings.Global.getInt(cr, Settings.Global.ADB_ENABLED, 0) == 1 /** 「关于手机」,版本号在这里(有的手机在它下面的「软件信息」里)。 */ diff --git a/app/src/main/java/com/wangzan101/mika/cap/phone/setup/PairingNotifier.kt b/app/src/main/java/com/wangzan101/mika/cap/phone/setup/PairingNotifier.kt index f440fa0764..18cd139557 100644 --- a/app/src/main/java/com/wangzan101/mika/cap/phone/setup/PairingNotifier.kt +++ b/app/src/main/java/com/wangzan101/mika/cap/phone/setup/PairingNotifier.kt @@ -44,6 +44,8 @@ sealed interface PairingNotice { return when (status) { BuiltinShellStatus.Running -> Done BuiltinShellStatus.Connecting -> Working + // 银行模式暂停着:用户亲手停的,不要弹配对码通知打扰他。 + BuiltinShellStatus.Paused -> null is BuiltinShellStatus.Failed -> when { status.reason.duringPairing -> EnterCode(port, PhoneSetupCopy.notifyRetry(status.reason)) status.fix == BuiltinShellFix.RePair && port != null -> EnterCode(port) diff --git a/app/src/main/java/com/wangzan101/mika/self/AndroidSelfPort.kt b/app/src/main/java/com/wangzan101/mika/self/AndroidSelfPort.kt index 39d0057f90..e800bd5e3a 100644 --- a/app/src/main/java/com/wangzan101/mika/self/AndroidSelfPort.kt +++ b/app/src/main/java/com/wangzan101/mika/self/AndroidSelfPort.kt @@ -330,6 +330,7 @@ class AndroidSelfPort( BuiltinShellStatus.Connecting -> "connecting" BuiltinShellStatus.NotPaired -> "not_paired" BuiltinShellStatus.WirelessDebuggingOff -> "wireless_debugging_off" + BuiltinShellStatus.Paused -> "paused" is BuiltinShellStatus.Failed -> "failed" } diff --git a/app/src/main/java/com/wangzan101/mika/settings/BankingMode.kt b/app/src/main/java/com/wangzan101/mika/settings/BankingMode.kt new file mode 100644 index 0000000000..79a4d36dbe --- /dev/null +++ b/app/src/main/java/com/wangzan101/mika/settings/BankingMode.kt @@ -0,0 +1,203 @@ +package com.wangzan101.mika.settings + +import android.content.ComponentName +import android.content.Context +import android.content.pm.PackageManager +import android.provider.Settings +import com.wangzan101.mika.MikaApp +import com.wangzan101.mika.a11y.MikaAccessibilityService +import com.wangzan101.mika.cap.phone.PhoneServices +import com.wangzan101.mika.cap.phone.a11y.ScreenAccessibility +import com.wangzan101.mika.cap.phone.setup.DeveloperSettings +import com.wangzan101.mika.core.shell.BuiltinShellControl +import com.wangzan101.mika.core.shell.BuiltinShellStatus +import com.wangzan101.mika.core.shell.PermissionCommands +import com.wangzan101.mika.task.TaskService + +/** + * 银行模式:亲手暂停 Mika,让银行 App 不再把它当成从非官方商店装的无障碍应用。 + * + * 用户在真机上验证过:无障碍服务关掉、无线调试关掉,HSBC 就能打开;其中任何一个 + * 开着,HSBC 就拦。暂停就是把这两样都关掉,再把内置助手停下。恢复时按已配对 + * 的连接重连,不用重新配对。 + * + * 有两件事 App 自己做不了,安卓不允许,恢复时必须用户亲手做,界面要说清楚: + * - 无障碍服务只能由用户在系统设置里重新打开(App 不能替自己打开它); + * - 无线调试的开关 App 能写(拿到了修改系统设置的授权时),写不进去就得用户 + * 自己去开发者选项里打开。 + * 配对钥匙、端口缓存和「已配对」标记暂停时一律不动:暂停不是解除配对, + * [BuiltinShellControl.unpair] 在这里绝不能调。 + */ +class BankingMode private constructor( + private val app: Context, + private val shell: BuiltinShellControl, + private val canWriteSecureSettings: () -> Boolean, +) { + companion object { + const val PREFS = "banking_mode" + const val KEY_PAUSED = "paused" + + /** 持久化的暂停开关:进程重启后 App 启动时按它把暂停重设上。 */ + fun isPaused(context: Context): Boolean = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY_PAUSED, false) + + fun create(context: Context): BankingMode { + val app = context.applicationContext + val phone = PhoneServices.of(context) + return BankingMode(app, phone.shellControl) { + app.checkSelfPermission(PermissionCommands.WRITE_SECURE_SETTINGS) == PackageManager.PERMISSION_GRANTED + } + } + } + + /** 持久化的暂停开关。 */ + fun isPaused(): Boolean = isPaused(app) + + private fun setPaused(value: Boolean) { + app.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_PAUSED, value).apply() + } + + /** 此刻的真实状态,直接读系统,不读缓存。 */ + fun snapshot(): BankingState { + val instanceRunning = ScreenAccessibility.instance.value != null + val enabled = Settings.Secure.getString(app.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES) + .orEmpty().split(':').mapNotNull { ComponentName.unflattenFromString(it.trim()) } + val me = ComponentName(app, MikaAccessibilityService::class.java) + val accessibility = when { + instanceRunning -> AccessibilityState.On + me in enabled -> AccessibilityState.EnabledNotRunning + else -> AccessibilityState.Off + } + return BankingState( + paused = isPaused(), + accessibility = accessibility, + accessibilityRunning = instanceRunning, + wirelessDebugging = DeveloperSettings.wirelessDebugging(app.contentResolver), + helper = shell.status.value, + helperPaired = shell.paired, + taskRunning = (app as? MikaApp)?.taskState?.busy?.value ?: false, + ) + } + + /** + * 暂停:先记下开关(中途出错也保持暂停),再停任务、停助手、关无障碍、关无线调试。 + * 必须在主线程调用([ScreenAccessibility.disableSelf] 是无障碍服务的方法)。 + */ + fun pause(): PauseResult { + setPaused(true) + val before = snapshot() + var tasksStopped = false + if (before.taskRunning) { + TaskService.cancel(app) + tasksStopped = true + } + // 先停助手:看门狗从这一刻起不再重起它;配对钥匙和端口缓存不动。 + shell.pause() + // 无障碍:服务在跑时能自己关掉自己;如果服务在列表里却没在跑, + // 只能由用户去系统设置里关,界面要说清楚。 + var a11yOff = before.accessibility == AccessibilityState.Off + var a11yNeedsManual = false + if (!a11yOff) { + val instance = ScreenAccessibility.instance.value + if (instance != null) { + runCatching { instance.disableSelf() } + a11yOff = true + } else { + // 服务在列表里却没在跑:关掉再打开才能彻底停,App 替它关不掉。 + a11yNeedsManual = true + } + } + // 无线调试:只关开关,不解除配对。写不进去(没有修改系统设置的授权)时, + // 界面提示用户去开发者选项里亲手关。 + var wirelessOff = !before.wirelessDebugging + var wirelessNeedsManual = false + if (!wirelessOff) { + wirelessOff = if (canWriteSecureSettings()) { + DeveloperSettings.turnOffWirelessDebugging(app.contentResolver) && + !DeveloperSettings.wirelessDebugging(app.contentResolver) + } else { + wirelessNeedsManual = true + false + } + } + return PauseResult( + tasksStopped = tasksStopped, + accessibilityOff = a11yOff, + accessibilityNeedsManual = a11yNeedsManual, + wirelessOff = wirelessOff, + wirelessNeedsManual = wirelessNeedsManual, + helperPaused = shell.paused, + ) + } + + /** + * 恢复:先清掉开关,再把无线调试打开(写得进去时),然后让助手按已配对的连接重连。 + * 无障碍服务 App 打不开,返回的步骤里一定有「去系统设置里打开」这一项, + * 除非它已经开着。配对丢了才需要重新配对,平时绝不走那一步。 + * 必须在主线程调用。 + */ + fun resume(): ResumeResult { + setPaused(false) + val before = snapshot() + if (!before.wirelessDebugging && canWriteSecureSettings()) { + DeveloperSettings.turnOnWirelessDebugging(app.contentResolver) + } + shell.resume() + // 再读一次系统:写开关可能被系统在不允许的 Wi-Fi 上撤回,以实测为准。 + val after = snapshot() + return ResumeResult( + wirelessOn = after.wirelessDebugging, + helperReconnecting = after.helper == BuiltinShellStatus.Connecting || + after.helper == BuiltinShellStatus.Running, + steps = planResumeSteps(after), + ) + } +} + +/** 银行模式此刻的真实状态。 */ +data class BankingState( + val paused: Boolean, + val accessibility: AccessibilityState, + val accessibilityRunning: Boolean, + val wirelessDebugging: Boolean, + val helper: BuiltinShellStatus, + val helperPaired: Boolean, + val taskRunning: Boolean, +) + +/** 暂停一次做完之后,哪些关掉了、哪些还要用户亲手做。 */ +data class PauseResult( + val tasksStopped: Boolean, + val accessibilityOff: Boolean, + val accessibilityNeedsManual: Boolean, + val wirelessOff: Boolean, + val wirelessNeedsManual: Boolean, + val helperPaused: Boolean, +) { + /** 银行 App 现在应该能打开:两样都关掉了,助手也停了。 */ + val readyForBanking: Boolean get() = accessibilityOff && wirelessOff && helperPaused +} + +/** 恢复一次做完之后,还有哪些步骤要用户亲手做。 */ +data class ResumeResult( + val wirelessOn: Boolean, + val helperReconnecting: Boolean, + val steps: List, +) + +/** 恢复时 App 自己做不了、必须用户亲手做的步骤。 */ +enum class ResumeStep { + /** 去系统设置里打开 Mika 的无障碍服务:App 不能替自己打开它。 */ + OpenAccessibilitySettings, + /** 去开发者选项里打开无线调试:App 写不进去开关时才需要。 */ + OpenWirelessDebuggingPage, + /** 配对已经丢了:重新走一遍配对流程。平时不出现。 */ + RePairHelper, +} + +/** 纯函数:按恢复后的真实状态,算出还有哪些步骤要用户亲手做。 */ +fun planResumeSteps(state: BankingState): List = buildList { + if (state.accessibility != AccessibilityState.On) add(ResumeStep.OpenAccessibilitySettings) + if (!state.wirelessDebugging) add(ResumeStep.OpenWirelessDebuggingPage) + if (!state.helperPaired) add(ResumeStep.RePairHelper) +} diff --git a/app/src/main/java/com/wangzan101/mika/ui/BankingScreen.kt b/app/src/main/java/com/wangzan101/mika/ui/BankingScreen.kt new file mode 100644 index 0000000000..139cbe261a --- /dev/null +++ b/app/src/main/java/com/wangzan101/mika/ui/BankingScreen.kt @@ -0,0 +1,190 @@ +package com.wangzan101.mika.ui + +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.height +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.wangzan101.mika.R +import com.wangzan101.mika.cap.phone.PhoneServices +import com.wangzan101.mika.cap.phone.a11y.ScreenAccessibility +import com.wangzan101.mika.core.shell.BuiltinShellStatus +import com.wangzan101.mika.settings.BankingMode +import com.wangzan101.mika.settings.ResumeStep +import com.wangzan101.mika.settings.planResumeSteps +import com.wangzan101.mika.ui.components.GroupCard +import com.wangzan101.mika.ui.components.GroupLabel +import com.wangzan101.mika.ui.components.ListRow +import com.wangzan101.mika.ui.components.PageScaffold +import com.wangzan101.mika.ui.components.RowValue +import com.wangzan101.mika.ui.components.StateCard +import com.wangzan101.mika.ui.components.TileTone +import com.wangzan101.mika.ui.components.ValueTone +import com.wangzan101.mika.ui.theme.MikaIcons +import com.wangzan101.mika.ui.theme.MikaTheme +import com.wangzan101.mika.ui.theme.MikaType + +/** + * Banking mode: pause Mika so a bank app opens, then resume it. + * + * Some banking apps refuse to open while either the accessibility service or + * wireless debugging is on. Pause turns both off and stops the phone helper; + * the wireless-debugging pairing stays saved, so resume reconnects with it and + * needs no new pairing code. Android does not let an app turn its own + * accessibility service back on, so resume lists that step for the user to tap + * in system settings. State is read fresh from the system every time the helper + * or the accessibility service changes, never assumed. + */ +@Composable +fun BankingScreen(onBack: () -> Unit, onFix: (Fix) -> Unit) { + val context = LocalContext.current + val mode = remember { BankingMode.create(context) } + val phone = remember { PhoneServices.of(context) } + // 助手状态或无障碍实例一变就重读系统状态:界面永远是实测,不是上次记的。 + val shellStatus by phone.shellControl.status.collectAsState() + val a11yInstance by ScreenAccessibility.instance.collectAsState() + var state by remember { mutableStateOf(mode.snapshot()) } + var notice by remember { mutableStateOf(null) } + LaunchedEffect(shellStatus, a11yInstance) { state = mode.snapshot() } + + val helperText = when (state.helper) { + BuiltinShellStatus.Running -> stringResource(R.string.banking_helper_running) + BuiltinShellStatus.Paused -> stringResource(R.string.banking_helper_paused) + BuiltinShellStatus.Connecting -> stringResource(R.string.banking_helper_connecting) + else -> stringResource(R.string.banking_helper_not_running) + } + val helperTone = when (state.helper) { + BuiltinShellStatus.Running -> ValueTone.Ok + BuiltinShellStatus.Paused -> ValueTone.Plain + else -> ValueTone.Bad + } + val wirelessText = stringResource(if (state.wirelessDebugging) R.string.state_on else R.string.state_off) + val (a11yText, a11yTone) = StatusCopy.accessibilityValue(state.accessibility) + // 没暂停时,按真实状态算出恢复后还剩哪些步骤要用户亲手做。 + val resumeSteps = if (state.paused) emptyList() else planResumeSteps(state) + + PageScaffold(stringResource(R.string.banking_title), onBack) { + StateCard( + MikaIcons.Shield, + stringResource(if (state.paused) R.string.banking_paused_title else R.string.banking_active_title), + stringResource(if (state.paused) R.string.banking_paused_body else R.string.banking_active_body), + if (state.paused) TileTone.Ok else TileTone.Warn, + ) + Spacer(Modifier.height(12.dp)) + Text( + stringResource(R.string.banking_explain), + style = MikaType.Caption, color = MikaTheme.colors.ink2, + ) + Spacer(Modifier.height(12.dp)) + + GroupLabel(stringResource(R.string.banking_title)) + GroupCard { + ListRow( + MikaIcons.Shield, stringResource(R.string.banking_a11y_label), null, first = true, + ) { RowValue(a11yText, a11yTone) } + ListRow( + MikaIcons.Wrench, stringResource(R.string.banking_wireless_label), null, + ) { RowValue(wirelessText, if (state.wirelessDebugging) ValueTone.Bad else ValueTone.Ok) } + ListRow( + MikaIcons.Phone, stringResource(R.string.banking_helper_label), null, + ) { RowValue(helperText, helperTone) } + } + Spacer(Modifier.height(12.dp)) + + GroupCard { + if (state.paused) { + ListRow( + MikaIcons.Power, stringResource(R.string.banking_resume), + stringResource(R.string.banking_resume_sub), first = true, + onClick = { + val result = mode.resume() + state = mode.snapshot() + notice = if (result.steps.isEmpty()) { + context.getString(R.string.banking_resumed) + } else { + null + } + }, + ) { } + } else { + ListRow( + MikaIcons.Power, stringResource(R.string.banking_pause), + stringResource(R.string.banking_pause_sub), first = true, + onClick = { + val result = mode.pause() + state = mode.snapshot() + notice = buildString { + if (result.tasksStopped) append(context.getString(R.string.banking_task_stopped)) + if (result.readyForBanking) { + if (isNotEmpty()) append(" ") + append(context.getString(R.string.banking_paused_body)) + } else { + if (result.accessibilityNeedsManual) { + if (isNotEmpty()) append(" ") + append(context.getString(R.string.banking_a11y_manual)) + } + if (result.wirelessNeedsManual) { + if (isNotEmpty()) append(" ") + append(context.getString(R.string.banking_wireless_manual)) + } + } + }.takeIf { it.isNotEmpty() } + }, + ) { } + } + } + + // 恢复后还剩的、App 自己做不了的步骤:每一步都是一个直达系统设置的按钮。 + if (!state.paused && resumeSteps.isNotEmpty()) { + Spacer(Modifier.height(12.dp)) + Text( + stringResource(R.string.banking_resume_note), + style = MikaType.Caption, color = MikaTheme.colors.ink2, + ) + Spacer(Modifier.height(12.dp)) + GroupCard { + resumeSteps.forEachIndexed { index, step -> + val (icon, label, fix) = when (step) { + ResumeStep.OpenAccessibilitySettings -> + Triple(MikaIcons.Shield, stringResource(R.string.banking_step_a11y), Fix.OpenAccessibility) + ResumeStep.OpenWirelessDebuggingPage -> + Triple(MikaIcons.Wrench, stringResource(R.string.banking_step_wireless), Fix.OpenWirelessDebugging) + ResumeStep.RePairHelper -> + Triple(MikaIcons.Phone, stringResource(R.string.banking_step_repair), Fix.OpenPhoneSetup) + } + ListRow( + icon, label, null, first = index == 0, + onClick = { onFix(fix) }, + ) { } + } + } + } + + // 助手已配对、却还没连上(例如刚恢复、正在等 Wi-Fi):手动再连一次。 + if (!state.paused && state.helperPaired && + state.helper != BuiltinShellStatus.Running && state.helper != BuiltinShellStatus.Connecting + ) { + Spacer(Modifier.height(12.dp)) + GroupCard { + ListRow( + MikaIcons.Refresh, stringResource(R.string.banking_reconnect), null, first = true, + onClick = { onFix(Fix.RetryPhoneHelper) }, + ) { } + } + } + + notice?.let { + Spacer(Modifier.height(12.dp)) + Text(it, style = MikaType.Caption, color = MikaTheme.colors.ink2) + } + } +} diff --git a/app/src/main/java/com/wangzan101/mika/ui/MainActivity.kt b/app/src/main/java/com/wangzan101/mika/ui/MainActivity.kt index 74a1341553..48ed86742e 100644 --- a/app/src/main/java/com/wangzan101/mika/ui/MainActivity.kt +++ b/app/src/main/java/com/wangzan101/mika/ui/MainActivity.kt @@ -304,7 +304,7 @@ class MainActivity : ComponentActivity() { Fix.OpenPairingChannel -> openChannelSettings(PairingNotifier.ensureChannel(this).id) Fix.AddModel -> Unit // 设置页自己处理 // 换页由 MikaRoot 处理 - Fix.OpenPhoneSetup, Fix.OpenPhoneOps, Fix.RepairPhoneHelper -> Unit + Fix.OpenPhoneSetup, Fix.OpenPhoneOps, Fix.RepairPhoneHelper, Fix.OpenBankingMode -> Unit Fix.RetryPhoneHelper -> phone.pairing.scope.launch { phone.sharedShell.reconnect() phone.shellControl.retry() @@ -433,6 +433,8 @@ private fun MikaRoot( openPhoneOps = true nav.push(Route.Settings) } + // 银行模式住在设置页里:打开设置首页,那一行就在最上面。 + Fix.OpenBankingMode -> nav.push(Route.Settings) else -> activityFix(fix) } } diff --git a/app/src/main/java/com/wangzan101/mika/ui/PhoneSetupCopy.kt b/app/src/main/java/com/wangzan101/mika/ui/PhoneSetupCopy.kt index 93aea3c25b..2ad7b10e42 100644 --- a/app/src/main/java/com/wangzan101/mika/ui/PhoneSetupCopy.kt +++ b/app/src/main/java/com/wangzan101/mika/ui/PhoneSetupCopy.kt @@ -261,6 +261,8 @@ object PhoneSetupCopy { BuiltinShellStatus.NotPaired -> tr(R.string.settings_not_set) to ValueTone.Bad BuiltinShellStatus.WirelessDebuggingOff -> tr(R.string.phone_wireless_off) to ValueTone.Bad BuiltinShellStatus.Connecting -> tr(R.string.phone_connecting) to ValueTone.Plain + // 银行模式暂停着:不是故障,用户亲手停的。 + BuiltinShellStatus.Paused -> tr(R.string.banking_helper_paused) to ValueTone.Plain is BuiltinShellStatus.Failed -> tr(R.string.phone_error) to ValueTone.Bad } @@ -287,6 +289,8 @@ object PhoneSetupCopy { rootStart -> ROOT_STARTING_LINE else -> tr(R.string.phone_connecting) } + // 银行模式暂停着:说清是用户亲手停的、银行 App 现在应该能打开。 + BuiltinShellStatus.Paused -> tr(R.string.banking_paused_body) is BuiltinShellStatus.Failed -> when (s.reason) { BuiltinShellFailure.NoWifi -> NO_WIFI_LINE BuiltinShellFailure.WifiNotAllowed -> tr(R.string.phone_line_joined, failure(s.reason).title, WIFI_NOT_ALLOWED_LINE) diff --git a/app/src/main/java/com/wangzan101/mika/ui/SettingsScreen.kt b/app/src/main/java/com/wangzan101/mika/ui/SettingsScreen.kt index fd5b1fd3c5..a1db91223b 100644 --- a/app/src/main/java/com/wangzan101/mika/ui/SettingsScreen.kt +++ b/app/src/main/java/com/wangzan101/mika/ui/SettingsScreen.kt @@ -61,6 +61,7 @@ import com.wangzan101.mika.ui.components.PageScaffold import com.wangzan101.mika.ui.components.PillTone import com.wangzan101.mika.ui.components.RowChevron import com.wangzan101.mika.ui.components.RowValue +import com.wangzan101.mika.ui.components.ValueTone import com.wangzan101.mika.ui.components.StateCard import com.wangzan101.mika.ui.components.StatusPill import com.wangzan101.mika.ui.components.TileTone @@ -75,7 +76,7 @@ import kotlinx.coroutines.withContext private const val SHIZUKU_SETUP_GUIDE_URL = "https://shizuku.rikka.app/guide/setup/" /** 设置里能进入的子页面;[Home] 是设置首页,[Advanced] 集中放置连接、维护和工程能力。 */ -private enum class SettingsPage { Home, Advanced, AppAccess, SmsLogin, PhoneOps, Calls, Wechat, DuringWork, AppPace, Capsule, Language, Notifications, Recommendations, Checklists, Workflows, Sandbox, Plugins, EnvVars, Recovery, SelfCheck, ComputerAccess, McpServers, Root, Developer, DeviceDirectories, RunStats, Proactive, Backup } +private enum class SettingsPage { Home, Advanced, AppAccess, SmsLogin, PhoneOps, Calls, Wechat, DuringWork, AppPace, Capsule, Language, Notifications, Recommendations, Checklists, Workflows, Sandbox, Plugins, EnvVars, Recovery, SelfCheck, ComputerAccess, McpServers, Root, Developer, DeviceDirectories, RunStats, Proactive, Backup, Banking } /** * 设置页:总状态卡 + 常用 / 我的数据 / 其他。高级与其他只增加一层,各子页返回来时的页面。 @@ -245,6 +246,8 @@ fun SettingsScreen( onOpenAutoArchive = { editingAutoArchive = true }, onOpenMemory = onOpenMemory, onOpenBackup = { page = SettingsPage.Backup }, + onOpenBanking = { page = SettingsPage.Banking }, + bankingPaused = com.wangzan101.mika.settings.BankingMode.isPaused(context), onOpenRecommendations = { page = SettingsPage.Recommendations }, onOpenPersonas = onOpenPersonas, onOpenAdvanced = { page = SettingsPage.Advanced }, @@ -346,6 +349,7 @@ fun SettingsScreen( SettingsPage.RunStats -> RunStatsScreen(remember { RunStore(context).metrics }, onBack = back) SettingsPage.Proactive -> com.wangzan101.mika.proactive.ProactiveScreen(onBack = back) SettingsPage.Backup -> BackupScreen(onBack = toHome) + SettingsPage.Banking -> BankingScreen(onBack = toHome, onFix = ::fix) } if (editingProxy) NetProxyDialog( @@ -457,6 +461,9 @@ fun SettingsContent( onOpenLanguage: () -> Unit = {}, onOpenMemory: (() -> Unit)? = null, onOpenBackup: (() -> Unit)? = null, + /** 银行模式(暂停 Mika 让银行 App 打开)的入口;暂停着时首页这一行写「已暂停」。 */ + onOpenBanking: (() -> Unit)? = null, + bankingPaused: Boolean = false, onOpenRecommendations: () -> Unit = {}, onOpenPersonas: (() -> Unit)? = null, onOpenAdvanced: () -> Unit = {}, @@ -491,6 +498,19 @@ fun SettingsContent( PhoneOpsPill(status) RowChevron() } + onOpenBanking?.let { + ListRow( + MikaIcons.Shield, stringResource(R.string.banking_title), + stringResource(if (bankingPaused) R.string.banking_paused_row_sub else R.string.banking_active_row_sub), + onClick = it, + ) { + RowValue( + stringResource(if (bankingPaused) R.string.banking_helper_paused else R.string.banking_active), + if (bankingPaused) ValueTone.Plain else ValueTone.Ok, + ) + RowChevron() + } + } ListRow(MikaIcons.Clock, stringResource(R.string.drawer_plans), onClick = onOpenPlans) { RowChevron() } ListRow(MikaIcons.Globe, stringResource(R.string.drawer_browser), onClick = onOpenBrowser) { RowChevron() } ListRow(MikaIcons.Paperclip, stringResource(R.string.file_library_title), onClick = onOpenFiles) { RowChevron() } diff --git a/app/src/main/java/com/wangzan101/mika/ui/StatusCopy.kt b/app/src/main/java/com/wangzan101/mika/ui/StatusCopy.kt index f3f9233106..d35ae29d48 100644 --- a/app/src/main/java/com/wangzan101/mika/ui/StatusCopy.kt +++ b/app/src/main/java/com/wangzan101/mika/ui/StatusCopy.kt @@ -28,6 +28,8 @@ enum class Fix { // 内置助手 OpenPhoneSetup, RepairPhoneHelper, RetryPhoneHelper, UnpairPhoneHelper, OpenPhoneOps, OpenAboutPhone, OpenDeveloperOptions, OpenUsbDebugging, OpenWirelessDebugging, OpenWifi, + /** 打开设置页(银行模式在设置首页就有入口):银行模式暂停时横幅点的就是它。 */ + OpenBankingMode, } /** 顶部横幅的一行字和右侧链接。 */ @@ -88,6 +90,8 @@ object StatusCopy { Problem.NoModel -> Fix.AddModel // 引导页把每一步都讲清楚了,不再弹说明 is Problem.PhoneHelper -> when { + // 银行模式暂停着:这不是故障,是用户亲手要的,直接去银行模式那页。 + p.status == BuiltinShellStatus.Paused -> Fix.OpenBankingMode PhoneSetupCopy.canReconnect(p.status) -> Fix.RetryPhoneHelper (p.status as? BuiltinShellStatus.Failed)?.reason == BuiltinShellFailure.ShizukuNotInstalled || (p.status as? BuiltinShellStatus.Failed)?.reason == BuiltinShellFailure.ShizukuPermissionNeeded -> Fix.OpenPhoneOps @@ -170,6 +174,12 @@ object StatusCopy { tr(R.string.banner_failed), PhoneSetupCopy.failure(st.reason).title, if (PhoneSetupCopy.canReconnect(st)) PhoneSetupCopy.RECONNECT else tr(R.string.fix_it), ) + // 银行模式暂停着:标题说在暂停,下面一句说银行 App 现在应该能打开。 + BuiltinShellStatus.Paused -> BannerCopy( + tr(R.string.banking_paused_title), + tr(R.string.banking_paused_body), + tr(R.string.view), + ) BuiltinShellStatus.Running -> error("not a problem") } is Problem.Accessibility -> when (p.state) { diff --git a/app/src/main/res/values/strings_banking.xml b/app/src/main/res/values/strings_banking.xml new file mode 100644 index 0000000000..e32e90be6b --- /dev/null +++ b/app/src/main/res/values/strings_banking.xml @@ -0,0 +1,34 @@ + + + + Banking mode + Pause Mika so your bank app opens + Banking apps block Mika while its accessibility service or wireless debugging is on. Banking mode turns both off and stops the phone helper. Nothing is uninstalled, nothing is deleted, and the wireless-debugging pairing stays saved. + Mika paused + Accessibility off, helper disconnected. Your bank app should now open. + Active + Mika active + Accessibility and the helper are running. Turn on Banking mode before opening your bank app. + Pause Mika + Turn off accessibility and wireless debugging, stop the helper + Resume Mika + Reconnect the helper using the saved pairing + Mika is back on. + Android does not let an app turn its own accessibility service back on. After resuming, open Accessibility settings and turn Mika back on yourself. No new pairing code is needed: the helper reconnects with the pairing that is already saved. + Accessibility service + Wireless debugging + Phone helper + Running + Paused + Not running + Connecting… + A running task was stopped first. + Could not turn the accessibility service off from here. Open Accessibility settings and turn Mika off. + Could not turn wireless debugging off from here. Open Developer options and turn it off. + Turn Mika back on in Accessibility settings + Turn wireless debugging back on in Developer options + Pair the phone helper again + Reconnect helper now + Paused - your bank app should open + Active - Mika is running + diff --git a/app/src/test/java/com/wangzan101/mika/settings/BankingModeTest.kt b/app/src/test/java/com/wangzan101/mika/settings/BankingModeTest.kt new file mode 100644 index 0000000000..d144a02834 --- /dev/null +++ b/app/src/test/java/com/wangzan101/mika/settings/BankingModeTest.kt @@ -0,0 +1,87 @@ +package com.wangzan101.mika.settings + +import com.wangzan101.mika.core.shell.BuiltinShellStatus +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * 银行模式恢复步骤的纯函数测试:按恢复后的真实状态,算出还有哪些步骤要用户亲手做。 + * 暂停/恢复本身要读系统(无障碍列表、无线调试开关、助手状态),不在 JVM 单测里跑, + * 由 [com.wangzan101.mika.core.shell.BuiltinShellEngineTest] 在 core 单测里覆盖状态机。 + */ +class BankingModeTest { + private fun state( + accessibility: AccessibilityState = AccessibilityState.On, + wirelessDebugging: Boolean = true, + helper: BuiltinShellStatus = BuiltinShellStatus.Running, + helperPaired: Boolean = true, + ) = BankingState( + paused = false, + accessibility = accessibility, + accessibilityRunning = accessibility == AccessibilityState.On, + wirelessDebugging = wirelessDebugging, + helper = helper, + helperPaired = helperPaired, + taskRunning = false, + ) + + @Test + fun everythingBackOnNeedsNoManualStep() { + assertTrue(planResumeSteps(state()).isEmpty()) + } + + @Test + fun accessibilityOffNeedsTheSettingsStep() { + assertEquals( + listOf(ResumeStep.OpenAccessibilitySettings), + planResumeSteps(state(accessibility = AccessibilityState.Off)), + ) + // 服务在列表里却没在跑也一样:用户得去系统设置里亲手打开。 + assertEquals( + listOf(ResumeStep.OpenAccessibilitySettings), + planResumeSteps(state(accessibility = AccessibilityState.EnabledNotRunning)), + ) + } + + @Test + fun wirelessOffNeedsTheDeveloperOptionsStep() { + assertEquals( + listOf(ResumeStep.OpenWirelessDebuggingPage), + planResumeSteps(state(wirelessDebugging = false)), + ) + } + + @Test + fun lostPairingNeedsRePairing() { + assertEquals( + listOf(ResumeStep.RePairHelper), + planResumeSteps(state(helper = BuiltinShellStatus.NotPaired, helperPaired = false)), + ) + } + + @Test + fun pausedHelperWithSavedPairingNeedsNoRePairing() { + // 银行模式暂停后恢复:助手是 Paused、配对还在,不用重新配对。 + assertTrue(planResumeSteps(state(helper = BuiltinShellStatus.Paused)).isEmpty()) + } + + @Test + fun allThreeGapsAreListedInOrder() { + assertEquals( + listOf( + ResumeStep.OpenAccessibilitySettings, + ResumeStep.OpenWirelessDebuggingPage, + ResumeStep.RePairHelper, + ), + planResumeSteps( + state( + accessibility = AccessibilityState.Off, + wirelessDebugging = false, + helper = BuiltinShellStatus.NotPaired, + helperPaired = false, + ), + ), + ) + } +} diff --git a/core/src/main/kotlin/com/wangzan101/mika/core/shell/AccessibilityRepair.kt b/core/src/main/kotlin/com/wangzan101/mika/core/shell/AccessibilityRepair.kt index 772d4bc791..cbca614142 100644 --- a/core/src/main/kotlin/com/wangzan101/mika/core/shell/AccessibilityRepair.kt +++ b/core/src/main/kotlin/com/wangzan101/mika/core/shell/AccessibilityRepair.kt @@ -55,6 +55,8 @@ class AccessibilityRepair( private val now: () -> Long = System::currentTimeMillis, /** 明确退出后为 false:不写回无障碍;下次手动打开时 [watch] 的 active 流会重新判断。 */ private val allowed: () -> Boolean = { true }, + /** 银行模式暂停时为 true:即使助手状态不是 Paused,也不自动打开无障碍。 */ + private val paused: () -> Boolean = { false }, ) { private val _last = MutableStateFlow(null) val last: StateFlow = _last.asStateFlow() @@ -103,7 +105,10 @@ class AccessibilityRepair( } private fun eligible(s: A11yObservation, h: BuiltinShellStatus, unlocked: Boolean) = - allowed() && s.stuck && unlocked && (direct() || h == BuiltinShellStatus.Running) && consent().wants(RecoveryCapability.Accessibility) + // 银行模式暂停时绝不自动把无障碍打开:用户亲手关掉它就是为了让银行 App 通过, + // 修好它等于把暂停取消了。恢复时用户自己在系统设置里打开。 + allowed() && !paused() && s.stuck && unlocked && h != BuiltinShellStatus.Paused && + (direct() || h == BuiltinShellStatus.Running) && consent().wants(RecoveryCapability.Accessibility) private suspend fun repair( service: StateFlow, diff --git a/core/src/main/kotlin/com/wangzan101/mika/core/shell/BuiltinShell.kt b/core/src/main/kotlin/com/wangzan101/mika/core/shell/BuiltinShell.kt index 743dcf24b5..a7fb773315 100644 --- a/core/src/main/kotlin/com/wangzan101/mika/core/shell/BuiltinShell.kt +++ b/core/src/main/kotlin/com/wangzan101/mika/core/shell/BuiltinShell.kt @@ -18,6 +18,13 @@ sealed interface BuiltinShellStatus { data object Running : BuiltinShellStatus + /** + * 银行模式:用户亲手暂停了 Mika,助手已停下,看门狗不会把它起回来。 + * 配对没有解除(钥匙、端口缓存都还在),恢复时直接用已配对的连接重连,不用重新配对。 + * [BuiltinShellControl.paired] 仍为 true,所以这不是 [NotPaired]。 + */ + data object Paused : BuiltinShellStatus + /** 出错了:[reason] 说明是哪一类,[fix] 是一键修复走哪条路。 */ data class Failed(val reason: BuiltinShellFailure, val fix: BuiltinShellFix = reason.defaultFix) : BuiltinShellStatus } @@ -145,6 +152,21 @@ interface BuiltinShellControl { /** 删除配对钥匙、停掉助手、撤销助手给 Mika 的授权;之后状态是 [BuiltinShellStatus.NotPaired]。 */ suspend fun unpair() + + /** 银行模式是否暂停着:暂停时看门狗不重起助手,[status] 是 [BuiltinShellStatus.Paused]。 */ + val paused: Boolean get() = false + + /** + * 暂停内置助手:停掉正在跑的助手,看门狗不再把它起回来。配对不解除,钥匙和端口缓存 + * 都留着,[resume] 直接用已配对的连接重连,不用重新配对。重复调用无害。 + */ + fun pause() {} + + /** + * 恢复内置助手:取消暂停,按已有配对重新连接并启动助手。没有配对过时什么都不做, + * 由界面按 [BuiltinShellStatus.NotPaired] 引导配对。 + */ + fun resume() {} } /** 配对码:6 位数字。用户可能带空格、横线或全角数字,一并规范掉;不是 6 位数字就返回 null。 */ diff --git a/core/src/main/kotlin/com/wangzan101/mika/core/shell/BuiltinShellEngine.kt b/core/src/main/kotlin/com/wangzan101/mika/core/shell/BuiltinShellEngine.kt index a7552ea56e..842020577d 100644 --- a/core/src/main/kotlin/com/wangzan101/mika/core/shell/BuiltinShellEngine.kt +++ b/core/src/main/kotlin/com/wangzan101/mika/core/shell/BuiltinShellEngine.kt @@ -125,6 +125,47 @@ class BuiltinShellEngine( private var pendingImmediate = false private var started = false + /** + * 银行模式:用户亲手暂停时为 true。暂停时看门狗不重起助手,[status] 是 + * [BuiltinShellStatus.Paused];配对、钥匙和端口缓存都不动,恢复时直接重连。 + * 只由 [pause]/[resume] 改,进程重启后由 App 层按持久化的银行模式开关重设。 + */ + @Volatile + private var _paused = false + override val paused: Boolean get() = _paused + + /** + * 暂停:取消排着的重试,停掉正在跑的助手,看门狗不再把它起回来。 + * 不调用 [platform.forget]:配对钥匙、端口缓存和「已配对」标记都留着, + * [resume] 直接用已配对的连接重连,不用重新配对。 + */ + override fun pause() { + synchronized(this) { + retryJob?.cancel() + retryJob = null + _paused = true + } + runCatching { platform.stopHelper() } + _status.value = BuiltinShellStatus.Paused + } + + /** + * 恢复:取消暂停,按已有配对重新连接并启动助手。没有配对过(也不能经 root 起) + * 时不强行起,状态回到没设置的样子,由界面引导配对。 + */ + override fun resume() { + synchronized(this) { + if (!_paused) return + _paused = false + failures = 0 + } + if (helper.value != null) { + _status.value = BuiltinShellStatus.Running + return + } + if (selfStart()) schedule(0) else _status.value = idleStatus() + } + override val paired: Boolean get() = platform.paired() override val transport: ShellTransport get() = platform.transport() @@ -151,6 +192,7 @@ class BuiltinShellEngine( } private fun initialStatus(): BuiltinShellStatus = when { + _paused -> BuiltinShellStatus.Paused helper.value != null -> BuiltinShellStatus.Running selfStart() -> BuiltinShellStatus.Connecting // 电脑起过的助手可能还活着,等它来交接 @@ -162,17 +204,19 @@ class BuiltinShellEngine( * Mika 自己起不来、手里也没有助手时的状态:Shizuku 模式下报 Shizuku 缺哪一步; * 自动模式下若未配对且已装 Shizuku 也如实提示;否则看 root、电脑启动或未配对。 */ - private fun idleStatus(): BuiltinShellStatus = when (platform.transport()) { - ShellTransport.Shizuku -> BuiltinShellStatus.Failed(platform.shizukuState().failure()) - ShellTransport.WirelessDebugging -> wirelessOrRootIdleStatus() - ShellTransport.Auto -> { - if (!platform.paired() && platform.rootStart() == RootStart.Off && !platform.usbStarted() && platform.shizukuState().installed) { - BuiltinShellStatus.Failed(platform.shizukuState().failure()) - } else { - wirelessOrRootIdleStatus() + private fun idleStatus(): BuiltinShellStatus = + if (_paused) BuiltinShellStatus.Paused + else when (platform.transport()) { + ShellTransport.Shizuku -> BuiltinShellStatus.Failed(platform.shizukuState().failure()) + ShellTransport.WirelessDebugging -> wirelessOrRootIdleStatus() + ShellTransport.Auto -> { + if (!platform.paired() && platform.rootStart() == RootStart.Off && !platform.usbStarted() && platform.shizukuState().installed) { + BuiltinShellStatus.Failed(platform.shizukuState().failure()) + } else { + wirelessOrRootIdleStatus() + } } } - } private fun wirelessOrRootIdleStatus(): BuiltinShellStatus { platform.rootStart().failure?.let { return BuiltinShellStatus.Failed(it) } @@ -187,6 +231,12 @@ class BuiltinShellEngine( var first = true scope.launch { helper.collect { h -> + // 银行模式暂停着:助手断开是用户要的,不重起,状态就停在 Paused。 + if (_paused) { + if (h != null) runCatching { platform.stopHelper() } + _status.value = BuiltinShellStatus.Paused + return@collect + } if (h != null) { synchronized(this@BuiltinShellEngine) { failures = 0; retryJob?.cancel(); pendingImmediate = false } lastError = null @@ -217,8 +267,9 @@ class BuiltinShellEngine( } } - /** 有人要用助手却没有:没在起、也没排着重试就马上起一次。 */ + /** 有人要用助手却没有:没在起、也没排着重试就马上起一次。银行模式暂停时不做:用户要的就是助手停着。 */ fun need() { + if (_paused) return if (helper.value != null || !selfStart()) return synchronized(this) { if (retryJob?.isActive == true) return } if (launchLock.isLocked) return @@ -230,6 +281,7 @@ class BuiltinShellEngine( * Mika 自己起不来了就照实改状态。 */ fun rootChanged() { + if (_paused) return if (platform.transport() == ShellTransport.Shizuku) return if (helper.value != null) return synchronized(this) { @@ -252,6 +304,10 @@ class BuiltinShellEngine( retryJob = null pendingImmediate = false } + if (_paused) { + _status.value = BuiltinShellStatus.Paused + return + } if (selfStart()) { _status.value = BuiltinShellStatus.Connecting schedule(0) @@ -262,6 +318,7 @@ class BuiltinShellEngine( /** Shizuku 状态或授权变了:仅无线调试模式不动;有助手就保持运行;否则按新状态马上试或照实改状态。 */ fun shizukuChanged() { + if (_paused) return if (platform.transport() == ShellTransport.WirelessDebugging) return synchronized(this) { failures = 0 @@ -278,6 +335,8 @@ class BuiltinShellEngine( * Mika 自己正在写这个开关时不跟着动:系统可能马上拨回去,由写的那一边判断。 */ fun wirelessDebuggingChanged() { + // 银行模式暂停时开关的变化是用户要的(暂停时关掉、恢复时打开),不跟着动。 + if (_paused) return // 经 su 或纯 Shizuku 起助手不看无线调试 if (helper.value != null || !platform.paired() || rootStart || platform.transport() == ShellTransport.Shizuku) return if (autoOn?.writing == true) return @@ -295,6 +354,7 @@ class BuiltinShellEngine( * 卡在无线调试关着(包括上一个网络不允许)也马上再试。换了网络,上一个网络上的拒绝不再算数。 */ fun wifiAvailable() { + if (_paused) return if (platform.transport() == ShellTransport.Shizuku) return autoOn?.reset() val s = _status.value @@ -342,6 +402,11 @@ class BuiltinShellEngine( private suspend fun launchOnce(): Unit = launchLock.withLock { synchronized(this) { pendingImmediate = false } + // 暂停和启动几乎同时发生时:已经排上的这一次也不起,状态停在 Paused。 + if (_paused) { + _status.value = BuiltinShellStatus.Paused + return@withLock + } if (helper.value != null) return@withLock when (platform.transport()) { ShellTransport.Shizuku -> { @@ -352,6 +417,11 @@ class BuiltinShellEngine( } _status.value = BuiltinShellStatus.Connecting val failure = attemptShizuku() + if (_paused) { + runCatching { platform.stopHelper() } + _status.value = BuiltinShellStatus.Paused + return@withLock + } if (failure == null) { lastError = null _status.value = BuiltinShellStatus.Running @@ -364,6 +434,11 @@ class BuiltinShellEngine( if (platform.shizukuState().ready) { _status.value = BuiltinShellStatus.Connecting val failure = attemptShizuku() + if (_paused) { + runCatching { platform.stopHelper() } + _status.value = BuiltinShellStatus.Paused + return@withLock + } if (failure == null) { lastError = null _status.value = BuiltinShellStatus.Running @@ -381,6 +456,11 @@ class BuiltinShellEngine( if (rootStart) { _status.value = BuiltinShellStatus.Connecting val failure = attemptRoot() + if (_paused) { + runCatching { platform.stopHelper() } + _status.value = BuiltinShellStatus.Paused + return@withLock + } if (failure == null) { lastError = null _status.value = BuiltinShellStatus.Running @@ -398,6 +478,11 @@ class BuiltinShellEngine( if (platform.wirelessDebugging() == false && !turnOnWirelessDebugging()) return@withLock _status.value = BuiltinShellStatus.Connecting val failure = attempt() + if (_paused) { + runCatching { platform.stopHelper() } + _status.value = BuiltinShellStatus.Paused + return@withLock + } if (failure == null) { lastError = null _status.value = BuiltinShellStatus.Running @@ -408,6 +493,10 @@ class BuiltinShellEngine( /** 报失败;看门狗自己再试有用的按 [backoff] 排下一次。 */ private fun failed(failure: BuiltinShellFailure) { + if (_paused) { + _status.value = BuiltinShellStatus.Paused + return + } _status.value = BuiltinShellStatus.Failed(failure) val next = synchronized(this) { ++failures } if (BuiltinShellFailures.retryable(failure)) backoff.delayAfter(next)?.let { d -> @@ -534,6 +623,8 @@ class BuiltinShellEngine( } override suspend fun retry() { + // 银行模式暂停时重试也不起助手:要恢复请调 resume()。 + if (_paused) return synchronized(this) { failures = 0 retryJob?.cancel() diff --git a/core/src/main/kotlin/com/wangzan101/mika/core/shell/FakeBuiltinShellControl.kt b/core/src/main/kotlin/com/wangzan101/mika/core/shell/FakeBuiltinShellControl.kt index 909194ae8a..7197d7f1a0 100644 --- a/core/src/main/kotlin/com/wangzan101/mika/core/shell/FakeBuiltinShellControl.kt +++ b/core/src/main/kotlin/com/wangzan101/mika/core/shell/FakeBuiltinShellControl.kt @@ -41,6 +41,18 @@ class FakeBuiltinShellControl( status.value = retryResult } + override val paused: Boolean get() = status.value == BuiltinShellStatus.Paused + + override fun pause() { + calls += "pause" + status.value = BuiltinShellStatus.Paused + } + + override fun resume() { + calls += "resume" + status.value = retryResult + } + override suspend fun unpair() { calls += "unpair" status.value = BuiltinShellStatus.NotPaired diff --git a/core/src/main/kotlin/com/wangzan101/mika/core/shell/PairingScreen.kt b/core/src/main/kotlin/com/wangzan101/mika/core/shell/PairingScreen.kt index aa81a36b5d..aab374441b 100644 --- a/core/src/main/kotlin/com/wangzan101/mika/core/shell/PairingScreen.kt +++ b/core/src/main/kotlin/com/wangzan101/mika/core/shell/PairingScreen.kt @@ -41,7 +41,8 @@ object PairingScreen { val waiting = when (status) { BuiltinShellStatus.NotPaired, BuiltinShellStatus.WirelessDebuggingOff -> true is BuiltinShellStatus.Failed -> status.reason.duringPairing || status.fix == BuiltinShellFix.RePair - BuiltinShellStatus.Connecting, BuiltinShellStatus.Running -> false + // 银行模式暂停着:用户亲手停的,不要拿屏上读到的码去配对。 + BuiltinShellStatus.Connecting, BuiltinShellStatus.Running, BuiltinShellStatus.Paused -> false } return if (waiting) PairingAttempt(code, reading.port) else null } diff --git a/core/src/main/kotlin/com/wangzan101/mika/core/shell/PhoneSetupFlow.kt b/core/src/main/kotlin/com/wangzan101/mika/core/shell/PhoneSetupFlow.kt index fdf186c126..5e797b0918 100644 --- a/core/src/main/kotlin/com/wangzan101/mika/core/shell/PhoneSetupFlow.kt +++ b/core/src/main/kotlin/com/wangzan101/mika/core/shell/PhoneSetupFlow.kt @@ -212,6 +212,8 @@ object PhoneSetupFlow { // 配对过、无线调试开着而状态还没跟上:实现马上会自动连,先显示「正在连接」 BuiltinShellStatus.WirelessDebuggingOff -> working(i) BuiltinShellStatus.NotPaired -> guide(SetupStep.PairingCode, i) + // 银行模式暂停着:用户亲手停的,不是没配好。停在「连接」这一步:恢复就是在这里重连。 + BuiltinShellStatus.Paused -> guide(SetupStep.Connect, i) is BuiltinShellStatus.Failed -> { val step = if (status.reason.duringPairing || status.fix == BuiltinShellFix.RePair) SetupStep.PairingCode else SetupStep.Connect SetupView( diff --git a/core/src/test/kotlin/com/wangzan101/mika/core/shell/AccessibilityRepairTest.kt b/core/src/test/kotlin/com/wangzan101/mika/core/shell/AccessibilityRepairTest.kt index ca59200944..96a58f556c 100644 --- a/core/src/test/kotlin/com/wangzan101/mika/core/shell/AccessibilityRepairTest.kt +++ b/core/src/test/kotlin/com/wangzan101/mika/core/shell/AccessibilityRepairTest.kt @@ -30,6 +30,7 @@ class AccessibilityRepairTest { var direct: Boolean = false, unlocked: Boolean = true, var allowed: Boolean = true, + var paused: Boolean = false, ) { val userUnlocked = MutableStateFlow(unlocked) val active = MutableStateFlow(allowed) @@ -50,6 +51,7 @@ class AccessibilityRepairTest { direct = { direct }, now = { scope.currentTime }, allowed = { allowed }, + paused = { paused }, ) fun start(s: TestScope) { @@ -274,6 +276,32 @@ class AccessibilityRepairTest { assertNull(wait.await()) } + /** + * 银行模式暂停时绝不自动把无障碍打开:即使 App 自己拿着修改系统设置的授权 + * (direct),助手状态是 Paused 也不能修。用户恢复时自己在系统设置里打开。 + */ + @Test + fun bankingModePausedNeverRepairs() = runTest { + val rig = Rig(helperStatus = BuiltinShellStatus.Paused, direct = true).also { it.start(this) } + advanceTimeBy(AccessibilityRepair.GRACE_MS + 20_000) + runCurrent() + assertTrue(rig.restarts.isEmpty()) + assertEquals(A11yObservation(enabled = true, connected = false), rig.service.value) + } + + @Test + fun pausedCallbackBlocksRepairEvenWhenHelperStatusIsNotPaused() = runTest { + val rig = Rig( + helperStatus = BuiltinShellStatus.Failed(BuiltinShellFailure.ShizukuNotRunning), + direct = true, + paused = true, + ).also { it.start(this) } + advanceTimeBy(AccessibilityRepair.GRACE_MS + 20_000) + runCurrent() + assertTrue(rig.restarts.isEmpty()) + assertEquals(A11yObservation(enabled = true, connected = false), rig.service.value) + } + @Test fun awaitWithTheRealRepairEndToEnd() = runTest { val rig = Rig(connectAfterMs = 3_000).also { it.start(this) } diff --git a/core/src/test/kotlin/com/wangzan101/mika/core/shell/BuiltinShellEngineBankingTest.kt b/core/src/test/kotlin/com/wangzan101/mika/core/shell/BuiltinShellEngineBankingTest.kt new file mode 100644 index 0000000000..4267fa78ec --- /dev/null +++ b/core/src/test/kotlin/com/wangzan101/mika/core/shell/BuiltinShellEngineBankingTest.kt @@ -0,0 +1,187 @@ +package com.wangzan101.mika.core.shell + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class BuiltinShellEngineBankingTest { + private class StubPlatform( + val helper: MutableStateFlow, + var pairedFlag: Boolean = false, + ) : BuiltinShellPlatform { + var usbFlag = false + var currentTransport: ShellTransport = ShellTransport.Auto + var shizuku: ShizukuPlatformState = ShizukuPlatformState.Unavailable + var launchGate: CompletableDeferred? = null + var autoAttachOnLaunch = true + val calls = mutableListOf() + + override fun paired(): Boolean = pairedFlag + override fun setPaired(paired: Boolean) { pairedFlag = paired } + override fun wirelessDebugging(): Boolean = true + override fun wifiConnected(): Boolean = true + override suspend fun findPairingPort(timeoutMs: Long): Int? = null + override fun pair(port: Int, code: String) { calls += "pair $code" } + override suspend fun launchHelper() { + calls += "launch" + launchGate?.await() + if (autoAttachOnLaunch) { + helper.value = "helper-${calls.size}" + } + } + override fun stopHelper() { + calls += "stop" + helper.value = null + } + override fun forget() { calls += "forget" } + override fun usbStarted(): Boolean = usbFlag + override fun setUsbStarted(on: Boolean) { usbFlag = on } + override fun transport(): ShellTransport = currentTransport + override fun setTransport(transport: ShellTransport) { currentTransport = transport } + override fun shizukuState(): ShizukuPlatformState = shizuku + } + + private fun TestScope.makeEngine(paired: Boolean = false, initialHelper: Any? = null): Pair { + val helper = MutableStateFlow(initialHelper) + val platform = StubPlatform(helper, pairedFlag = paired) + val dispatcher = StandardTestDispatcher(testScheduler) + val engine = BuiltinShellEngine( + platform = platform, + helper = helper, + scope = CoroutineScope(SupervisorJob() + dispatcher), + io = dispatcher, + graceMs = 0, + ) + return engine to platform + } + + @Test + fun pauseStopsHelperAndWatchdogWithoutForgetting() = runTest { + val (e, platform) = makeEngine(paired = true, initialHelper = "first") + e.start() + advanceUntilIdle() + assertEquals(BuiltinShellStatus.Running, e.status.value) + + e.pause() + assertEquals(BuiltinShellStatus.Paused, e.status.value) + assertTrue(e.paused) + assertTrue(e.paired) + assertEquals(listOf("stop"), platform.calls.filter { it == "stop" }) + assertFalse(platform.calls.any { it == "forget" }) + + advanceUntilIdle() + e.need() + e.retry() + e.wifiAvailable() + e.wirelessDebuggingChanged() + advanceUntilIdle() + assertEquals(0, platform.calls.count { it == "launch" }) + assertEquals(BuiltinShellStatus.Paused, e.status.value) + } + + @Test + fun resumeReconnectsWithSavedPairing() = runTest { + val (e, platform) = makeEngine(paired = true, initialHelper = "first") + e.start() + advanceUntilIdle() + assertEquals(BuiltinShellStatus.Running, e.status.value) + + e.pause() + assertEquals(BuiltinShellStatus.Paused, e.status.value) + e.resume() + assertFalse(e.paused) + advanceUntilIdle() + assertEquals(1, platform.calls.count { it == "launch" }) + assertEquals(BuiltinShellStatus.Running, e.status.value) + assertFalse(platform.calls.any { it.startsWith("pair ") }) + } + + @Test + fun pauseBeforeStartKeepsHelperStopped() = runTest { + val (e, platform) = makeEngine(paired = true) + e.pause() + e.start() + advanceUntilIdle() + assertEquals(BuiltinShellStatus.Paused, e.status.value) + assertEquals(0, platform.calls.count { it == "launch" }) + + e.resume() + advanceUntilIdle() + assertEquals(1, platform.calls.count { it == "launch" }) + assertEquals(BuiltinShellStatus.Running, e.status.value) + } + + @Test + fun resumeWithoutPairingDoesNotLaunch() = runTest { + val (e, platform) = makeEngine(paired = false) + e.pause() + e.resume() + advanceUntilIdle() + assertEquals(0, platform.calls.count { it == "launch" }) + assertEquals(BuiltinShellStatus.NotPaired, e.status.value) + } + + @Test + fun pauseDuringInFlightLaunchStopsLateAttachingHelper() = runTest { + val (e, platform) = makeEngine(paired = true) + val gate = CompletableDeferred() + platform.launchGate = gate + platform.autoAttachOnLaunch = false + + e.start() + runCurrent() + assertEquals(1, platform.calls.count { it == "launch" }) + + e.pause() + assertEquals(BuiltinShellStatus.Paused, e.status.value) + assertEquals(1, platform.calls.count { it == "stop" }) + + gate.complete(Unit) + runCurrent() + platform.helper.value = "late-helper" + advanceUntilIdle() + + assertTrue(platform.calls.count { it == "stop" } >= 2) + assertNull(platform.helper.value) + assertEquals(BuiltinShellStatus.Paused, e.status.value) + } + + @Test + fun shizukuChangedAndSelectTransportWhilePausedKeepPausedStatus() = runTest { + val (e, platform) = makeEngine(paired = false) + platform.currentTransport = ShellTransport.Auto + platform.shizuku = ShizukuPlatformState(installed = true, running = false, permissionGranted = false) + e.start() + advanceUntilIdle() + + e.pause() + assertEquals(BuiltinShellStatus.Paused, e.status.value) + + e.shizukuChanged() + advanceUntilIdle() + assertEquals(BuiltinShellStatus.Paused, e.status.value) + + e.selectTransport(ShellTransport.Shizuku) + advanceUntilIdle() + assertEquals(ShellTransport.Shizuku, platform.currentTransport) + assertEquals(BuiltinShellStatus.Paused, e.status.value) + + e.shizukuChanged() + advanceUntilIdle() + assertEquals(BuiltinShellStatus.Paused, e.status.value) + assertEquals(0, platform.calls.count { it == "launch" }) + } +} diff --git a/docs/banking-mode.md b/docs/banking-mode.md new file mode 100644 index 0000000000..ccab28ef8e --- /dev/null +++ b/docs/banking-mode.md @@ -0,0 +1,92 @@ +# Banking mode (Pause Mika) + +Pause Mika so a bank app opens, then resume it. No uninstall, no Play +listing, no re-signing, no data loss. + +## Why + +Some banking apps refuse to open while either of these is active: + +- the accessibility service (MikaAccessibilityService) +- wireless debugging (the shell helper's transport) + +Banking mode turns both off and stops the helper. Resume turns them back on. + +## Where the switch lives + +- **Settings > Banking mode** — the full screen, and a row on the Settings + home page (right under "Phone operations") showing Paused / Active. +- **Home screen banner** — while paused, the status banner says + "Mika paused — Accessibility off, helper disconnected. Your bank app should now + open." Tapping it opens Settings. +- The Settings status list still shows "Accessibility off" as a separate + problem while paused; that entry opens Accessibility settings, which is + where the user goes to resume anyway. + +## What Pause does + +1. Remembers `paused = true` (SharedPreferences `banking_mode`, survives + restarts). A restart re-applies the pause before the recovery watchers + start, so Mika does not come back on by itself. +2. Stops any running task first (and says so). +3. Stops the phone helper: `BuiltinShellControl.pause()` sets + `BuiltinShellStatus.Paused`. The watchdog does not restart it, the + accessibility auto-repair does not re-enable the service while paused + (`AccessibilityRepair` refuses when the helper is Paused), and no + pairing-code notification is shown. +4. Turns the accessibility service off with `AccessibilityService.disableSelf()`. + If the service is listed in system settings but not currently running, + the screen tells the user to turn it off in Accessibility settings instead + of claiming it worked. +5. Turns wireless debugging off by writing the system setting (only when + Mika holds the write-secure-settings permission). If the write is not + allowed, the screen tells the user to turn it off in Developer options. + +Pause does NOT unpair, does NOT delete the pairing key +(`noBackupFilesDir/adb/adbkey.bin`), does NOT delete the port cache, does +NOT uninstall anything, does NOT delete data. `BuiltinShellControl.unpair()` +is never called on this path. + +## What Resume does + +1. Clears the persisted `paused` flag. +2. Turns wireless debugging back on (same system-setting write, when + allowed). +3. Reconnects the helper with the **saved pairing** — `BuiltinShellControl.resume()` + relaunches from the stored identity and port cache. No new pairing code. + Only if the pairing is actually gone (helper status NotPaired) does the + screen offer the re-pair flow. +4. Lists the steps the app cannot do itself, each as a button that opens the + right system page: + - **Turn Mika back on in Accessibility settings** — Android forbids an + app from enabling its own accessibility service, so the user flicks it + on there. This step is always listed unless the service is already on. + - **Turn wireless debugging back on in Developer options** — only if + Mika could not write the switch itself. + - **Pair the phone helper again** — only if the pairing is gone. +5. Shows the live state afterwards (accessibility on/off, wireless + debugging on/off, helper running/paused/not running) — read fresh from + the system, never assumed. If the helper is paired but not connected yet, + a "Reconnect helper now" row retries it. + +## Edge cases + +- Pausing while a task is running stops the task first. +- Accessibility already off: pause still disconnects the helper, and vice versa. +- Helper not paired: pause still works; resume shows the re-pair step. +- Pause before the engine starts (e.g. right after a restart) keeps the + helper stopped until resume. +- `BuiltinShellStatus.Paused` is a new status. `paired` stays true while + paused (the pairing is intact), so the phone-setup screens and the + recovery policy treat it as "paired, not running" rather than "never set up". + +## Tests + +- `core/.../BuiltinShellEngineTest`: pause stops the helper and the + watchdog without forgetting; resume reconnects with the saved pairing; + pause before start keeps the helper stopped; resume without pairing does + not launch. +- `core/.../AccessibilityRepairTest`: repair never fires while the helper + is Paused, even when Mika holds the write-secure-settings permission. +- `app/.../BankingModeTest`: the resume-step planner (`planResumeSteps`) + lists exactly the manual steps the live state still needs.