diff --git a/.agents/skills/mbrain-style/SKILL.md b/.agents/skills/mbrain-style/SKILL.md
new file mode 100644
index 0000000..d8ec0a6
--- /dev/null
+++ b/.agents/skills/mbrain-style/SKILL.md
@@ -0,0 +1,57 @@
+---
+name: mbrain-style
+description: 在 MBrain Android 项目新增、修改或审查 Compose 页面、操作行、图标、间距、主题和界面文案时使用,约束公共组件复用并防止样式漂移。不用于其他项目或纯后端修改。
+---
+
+# MBrain UI 样式约束
+
+## 先确定依据
+
+- 以本 skill 所在仓库为作用域;从 `.agents/skills/mbrain-style/` 向上三级定位仓库根目录,不使用个人电脑绝对路径。
+- 修改前读取根目录 [DESIGN.md](../../../DESIGN.md),以及 `app/src/main/kotlin/com/powercess/mbrain/ui/DesignSystem.kt` 和目标页面。
+- DESIGN.md 是视觉参数的唯一规范来源;DesignSystem.kt 是公共实现。二者不一致时指出具体差异,结合用户最新要求修正本次涉及的部分,不把偶然出现的页面样式当成新规范。
+- 用户明确提出的新设计优先于现有约定;无需为普通样式修复再次索要批准。将已采用的公共规范变化同步到 DESIGN.md。
+
+## 同类操作行只用同一实现
+
+设置项、能力与插件入口、服务列表入口、工具入口,以及带状态或开关的设置行,默认复用 `Group`、`ActionRow`、`GroupDivider`。
+
+- 组内使用 GroupDivider;禁止通过 Spacer、Arrangement.spacedBy 或额外 padding 自行模拟组内间隙。
+- 首尾外圆角由 Group 裁切,中间小圆角由 ActionRow 提供;只有一个条目时仍包在 Group 中。不要给每一行另加大圆角卡片。
+- 页面只提供内容、行为和语义明确的 trailing(状态、开关、进度);不为单页覆盖圆角、行高、图标尺寸、背景和文字层级。
+- 导航行使用默认箭头,状态行使用 StatusPill,开关行复用现有 Switch 模式。不要把整行点击与子开关变成重复触发的操作。
+- 行首图标使用现有单色线性图标风格,不使用彩色底框、emoji 或新绘制的装饰图标代替常规行图标。
+- 公共组件不足时,先在 DesignSystem.kt 增加最小必要的语义能力,再让同类入口复用;不要复制出页面私有版本,不为假设中的用途增加任意样式参数。
+- 静态分组显式放置 GroupDivider;动态列表使用 ScreenList(groupedRows = true)、ListSection 和 groupedItems,传入稳定 key,自动处理首尾圆角和行距。不要逐项再套 Group,也不要把长工具列表放入单个非懒加载 Column。
+
+示例:
+
+```kotlin
+Group {
+ ActionRow("应用管理", "已启用", Icons.Outlined.Widgets, { open("cap:apps") })
+ GroupDivider()
+ ActionRow("设备信息", "已启用", Icons.Outlined.PhoneAndroid, { open("cap:device") })
+}
+```
+
+## 页面、主题与文案
+
+- 列表页面复用 ScreenList,分组标题复用 SectionLabel;四个主页面首组使用 `firstSection = true`,不要用负偏移或逐页补偿顶部留白。
+- 颜色读取 MaterialTheme.colorScheme,字体使用 MaterialTheme.typography;不要在业务页硬编码主题色。不要靠固定高度裁剪大字体内容。
+- 编辑页复用 EditorSaveBar,标题栏与页面背景一致;全宽次级操作复用 SecondaryAction;完整详情说明使用 ContentCard,提示和错误使用 Note。完整调用名称使用可选择的等宽文本,不截断;复制操作不显示导航箭头。
+- 空状态统一使用无图标的 EmptyState,只提供必要信息和有效操作:MCP 无配置时用“暂无服务”与“添加服务”;工具页网关未启动时只提示“启动网关后查看工具”,不显示无效搜索框或装饰图标。
+- 汇总入口称“全部工具”,数量写“共 N 个工具”;分来源列表不称“全部”。避免重复标题、营销式欢迎语和不影响操作的技术说明;保留凭据重置、删除等必要后果提示。
+- 保留原生水波纹、焦点、禁用状态和可访问性语义;可操作区域不小于规范要求。
+
+## 合理保留不同控件
+
+首页统计卡片、网关启停、保存/添加/删除按钮、输入框、对话框和底部导航各有用途,不强行改成分组操作行。沿用其现有公共组件或 Material 控件。单次任务只迁移授权范围内的同类入口;全项目统一需逐一审查,不能机械替换所有 Surface 或 Button。
+
+## 完成前检查
+
+- 检查 diff 是否新增了业务页私有操作行、重复尺寸常量、硬编码颜色或多余嵌套 padding;如有,优先收敛到现有公共实现。
+- 每完成一轮应用功能或 UI 修改,按用户要求 rebuild;使用已连接的测试设备覆盖安装并验证,不卸载或清除数据。构建命令与环境见 `docs/development.md`;通过 adb devices 读取当前连接,不把设备地址写入源码或 skill。
+- 普通文案修改做构建与相关页面检查。公共布局、主题或组件修改另做相关 lint,检查受影响页面的浅色/深色、大字体、单项/多项分组和点击行为;四页共享布局修改需逐页核对。只报告实际完成的验证,说明环境限制。
+- 截图和构建日志放在忽略的 `.local-tools/`;截图前隐藏 Token 等凭据。覆盖安装可能停止网关,检查并说明实际状态。
+- 仅修改 skill/设计文档时验证文档、引用及 skill 格式,不为文档重新构建 APK。
+- 完成后汇报改动和验证结果;当前项目协作约定是等待用户明确要求再创建 PR。
diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
index 46e3ade..82ef579 100644
--- a/.github/workflows/android.yml
+++ b/.github/workflows/android.yml
@@ -32,27 +32,45 @@ jobs:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
+ fetch-depth: 0
+ - name: Select validation scope
+ id: scope
+ env:
+ PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: python3 scripts/ci_scope.py
- name: Inspect committed source
run: |
python3 -m unittest discover -s scripts -p 'test_*.py'
python3 scripts/check-source.py
- - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
+ - if: steps.scope.outputs.android == 'true'
+ uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
with:
distribution: temurin
java-version: '17'
- - uses: gradle/actions/setup-gradle@4c125117fe7c5aed11272ec4213f602f012f89f2 # v5
+ - if: steps.scope.outputs.android == 'true'
+ uses: gradle/actions/setup-gradle@4c125117fe7c5aed11272ec4213f602f012f89f2 # v5
with:
cache-disabled: true
- name: Install Android SDK packages
+ if: steps.scope.outputs.android == 'true'
uses: android-actions/setup-android@9fc6c4e9069bf8d3d10b2204b1fb8f6ef7065407 # v3
with:
packages: platform-tools
log-accepted-android-sdk-licenses: false
- name: Install required SDK versions
- run: sdkmanager "platforms;android-35" "build-tools;35.0.0"
+ if: steps.scope.outputs.android == 'true'
+ run: sdkmanager "platforms;android-35" "build-tools;35.0.0" "ndk;28.2.13676358"
+ - if: steps.scope.outputs.android == 'true'
+ uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
+ with:
+ go-version: '1.26.3'
+ cache: false
- name: Build, unit tests and lint
- run: ./gradlew :app:assembleDebug :app:assembleRelease testDebugUnitTest :app:lintDebug :app:lintRelease --no-daemon --no-build-cache --max-workers=2 --stacktrace
+ if: steps.scope.outputs.android == 'true'
+ run: ./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:assembleRelease testDebugUnitTest :app:lintDebug :app:lintRelease --no-daemon --no-build-cache --max-workers=2 --stacktrace
- name: Verify supported ABIs and prepare APK
+ if: steps.scope.outputs.android == 'true'
run: |
python3 scripts/check-apk.py app/build/outputs/apk/debug/app-debug.apk
python3 scripts/check-apk.py app/build/outputs/apk/release/app-release-unsigned.apk
@@ -61,6 +79,7 @@ jobs:
cd dist
sha256sum *.apk > SHA256SUMS.txt
- name: Upload universal debug APK
+ if: steps.scope.outputs.android == 'true'
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: mbrain-debug-universal-${{ github.run_number }}-${{ github.run_attempt }}
@@ -69,7 +88,7 @@ jobs:
retention-days: 14
compression-level: 0
- name: Upload test and lint reports
- if: ${{ !cancelled() }}
+ if: ${{ !cancelled() && steps.scope.outputs.android == 'true' }}
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: android-reports-${{ github.run_number }}-${{ github.run_attempt }}
@@ -80,6 +99,7 @@ jobs:
if-no-files-found: ignore
retention-days: 14
- name: Build summary
+ if: steps.scope.outputs.android == 'true'
run: |
cat >> "$GITHUB_STEP_SUMMARY" <<'EOF'
## MBrain testing build
@@ -91,3 +111,7 @@ jobs:
- Ephemeral CI signing keys may differ between runs; updating an existing installation may fail with a signature mismatch. Uninstalling clears app data.
- ABI packaging checks do not replace testing on each architecture.
EOF
+
+ - name: Documentation check summary
+ if: steps.scope.outputs.android == 'false'
+ run: echo 'Documentation-only PR; source checks passed. Android build skipped.' >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 007a895..19a945a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -48,7 +48,11 @@ jobs:
packages: platform-tools
log-accepted-android-sdk-licenses: false
- name: Install SDK
- run: sdkmanager "platforms;android-35" "build-tools;35.0.0"
+ run: sdkmanager "platforms;android-35" "build-tools;35.0.0" "ndk;28.2.13676358"
+ - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
+ with:
+ go-version: '1.26.3'
+ cache: false
- name: Build and test release
run: ./gradlew :app:assembleRelease testReleaseUnitTest :app:lintRelease --no-daemon --no-build-cache --max-workers=2 --stacktrace
- name: Verify and stage unsigned release
diff --git a/AGENTS.md b/AGENTS.md
index aa2113b..008afe8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,3 +7,25 @@
- Do not bypass branch protections, force-push protected branches, or merge before required checks pass.
- Keep `dev` as the default branch and retain it after merging into `main`.
- Create release tags only on `main` commits and only when a release is explicitly authorized.
+
+# Validation scope
+
+- Choose local checks according to the changed behavior; do not run a full Android build for every PR by default.
+- Documentation and repository-instruction changes need lightweight checks only. Workflow changes need workflow validation and tests of any changed CI logic.
+- Run relevant builds, tests and lint for application, dependency and build-configuration changes. Repeat checks only after relevant changes or failures.
+- CI keeps required checks reporting on every PR, but skips Android setup and builds for documentation-only PRs. Pushes to `dev`/`main`, manual runs and releases retain full validation.
+
+# Commit and pull request titles
+
+- Every commit title and pull request title must use `type: description` or `type(scope): description`.
+- The scope is optional. Use a colon followed by a space, and a concise, non-empty description.
+- Titles may be written in Chinese or English.
+- Examples: `fix: 修复保存按钮遮挡`, `fix(ui): keep the save button visible`, `docs: 更新开发规范`.
+- Apply the same format to merge and squash commit titles when creating or editing them.
+
+# UI style skill
+
+- For MBrain UI changes or reviews, read and apply [.agents/skills/mbrain-style/SKILL.md](.agents/skills/mbrain-style/SKILL.md) before editing.
+- Keep visual values in DESIGN.md and shared implementations in DesignSystem.kt; do not create per-page variants of grouped action rows.
+- After each application/UI change, rebuild and verify on the connected test device. Skill/documentation-only changes require lightweight validation.
+- Do not create a pull request until the user explicitly requests it.
diff --git a/DESIGN.md b/DESIGN.md
index 059847c..bc622a7 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -21,17 +21,46 @@ Android 原生工具面板,面向管理手机能力与 MCP 服务的用户。
- 首页取消连接示意图和装饰图标;网关启停使用青绿色,工具与服务概览分别使用浅蓝和浅绿表面,深色模式使用对应暗色表面。
- 页面切换使用短淡入淡出;原生组件保留按压、水波纹、禁用与焦点反馈。
+## 分组操作行的统一实现
+
+设置项、能力与插件入口、服务及工具入口默认复用 `Group / ActionRow / GroupDivider`。单项使用同样的分组外壳;整组裁切首尾外圆角,内部行保留小圆角。业务页面不单独覆盖这些样式。静态分组显式放置 `GroupDivider`;动态列表使用 `ScreenList(groupedRows = true)`、`ListSection` 和 `groupedItems`,自动处理首尾圆角与 2dp 行间隙,并保留逐行懒加载和稳定 key。不要在动态列表中为每行再套独立 Group。
+
+| 参数 | 统一值 |
+| --- | --- |
+| 外圆角 / 内圆角 / 组内间隙 | 20dp / 4dp / 2dp |
+| 行内水平 / 垂直边距 | 16dp / 12dp |
+| 图标与文字间距 / 标题与说明间距 | 16dp / 2dp |
+| 行首图标 / 导航箭头 | 24dp / 20dp |
+| 单行 / 双行最小高度 | 56dp / 72dp,内容可撑高 |
+| 列表顶部 padding | 8dp |
+| 四个主页面首组标题顶部 padding | 4dp(`firstSection = true`),合计留白 12dp |
+| 其他分组标题顶部 padding | 16dp |
+
+分组的行间隙保持透明,透出当前容器底色;不要绘制页面背景色分隔线,以免在弹层或卡片内形成黑边。普通 Group 底色透明,内容卡片保留表面色。
+
+这些数值由 `DesignSystem.kt` 实现。新增同类入口直接复用;统一调整时同时更新这里和公共实现。首页概览卡片、网关启停、表单操作按钮等保留各自用途对应的样式,不混用操作行规范。
+
+- 编辑页复用 `EditorSaveBar`:内容最大宽度 720dp,左右 16dp、上下 12dp 内边距,保存按钮最小高度 50dp;保留安全区与键盘避让。编辑页标题栏使用页面背景色。
+- 添加、导入、重连等全宽次级操作复用 `SecondaryAction`,最小高度 48dp,可选图标 18dp、文字间距 8dp;选择行右侧使用下拉箭头,导航行使用右箭头。
+- 完整说明使用 `ContentCard`(20dp 外圆角、16dp 内边距、正文 bodyMedium),不要当作提示消息使用 Note。调用名称完整显示、可选择,使用等宽字体;复制操作不显示导航箭头。
+- 空状态统一复用无图标的 `EmptyState`,只保留简短标题和必要操作;错误及危险操作仍须说明后果。Note 保留给帮助、提醒和错误,不用作普通详情容器。
+
+UI 修改流程见 [.agents/skills/mbrain-style/SKILL.md](.agents/skills/mbrain-style/SKILL.md)。Skill 约束复用与验证,不另存一套视觉参数。
+
## 交互规则
- 底部导航只用于四个主页面;详情页带返回按钮,系统返回与页面返回一致。
-- 首页仅保留连接凭据入口和工具/服务概览;网关启停使用右下角 64dp 悬浮按钮,位于底部导航上方 16dp,播放/停止图标对应状态,处理中显示进度并防止重复点击。列表末尾预留空间避免遮挡。能力管理通过底栏进入,运行记录放在设置中。
+- 首页仅展示顶部能力概览(工具/服务)和服务网关状态;网关卡片内使用 64dp 开关按钮,播放/停止图标对应状态,处理中显示进度并禁用按钮。首页不显示连接组件、说明文字或重复的顶栏状态;连接凭据和运行记录通过设置进入,错误通过 Snackbar 反馈。能力管理通过底栏进入。
+- 手机能力与外部 MCP 服务分区只显示标题,不附加解释。基础能力按已接入的 droid 模块展示为分组设置行,包含图标、名称与启用状态;复用 Group、ActionRow 和 GroupDivider,与手机能力及设置页保持相同的圆角、间距和行高,点击进入现有详情。
- Root / Shizuku 详情只保留一个启用开关和工具入口。打开时自动检查并申请权限,授权成功才启用;拒绝、超时或服务未启动保持关闭并显示原因。权限流程不依赖 Activity 生命周期;已启用 Root 在进程启动时自动恢复检查,工具仅在权限可用时发布。不提供独立授权入口或手动身份验证。
- MCP 列表进入服务详情;添加先选择类型,再进入全屏表单。托管进程参数逐项填写,不要求 JSON。
+- MCP 无配置时仅展示“暂无服务”和“添加服务”按钮,不展示装饰图标或技术说明;复用 EmptyState 的无图标模式。
- 添加类型仅包含 HTTP 服务与托管进程;名称和地址留空由用户填写,不内置 MT 或其他特定服务商入口。已保存连接按用户配置展示。
- 编辑页底部固定保存;未保存离开提示放弃修改。移除服务确认;连接失败显示在对应服务详情并提供重试。
- 工具列表只显示名称与来源;完整说明进入工具详情。搜索同时匹配中文名称、原始名称和描述。
- Token 默认隐藏,复制有反馈。运行记录在独立页,最多 40 条。
- 各主页面和详情保存滚动位置;编辑草稿与导航在 Activity 重建时恢复。
+- 设置中的内网穿透只配置一台服务器,点击服务器行直接进入完整编辑页,不展示服务器列表、单独的编辑按钮或顶部说明。服务器仅填写名称、地址、端口和 Token;隧道共用服务器,只配置本地目标、TCP 映射端口与可选 HTTP 公网地址。没有 HTTPS、TLS、插件和证书入口。
## 实现入口
@@ -40,3 +69,5 @@ Android 原生工具面板,面向管理手机能力与 MCP 服务的用户。
- OverviewScreens.kt:首页、能力、设置、记录。
- ConnectionScreens.kt:MCP 列表、详情、完整编辑页。
- DetailScreens.kt:工具、凭据。
+
+- 隧道详情默认只显示启用状态、已填写的访问地址和编辑入口;编辑入口合并本地目标与映射端口摘要。连接诊断、访问凭据、重连和删除放入“更多”,诊断与运行记录默认收起;错误直接显示。
diff --git a/README.md b/README.md
index 91535db..01385af 100644
--- a/README.md
+++ b/README.md
@@ -48,6 +48,7 @@ MBrain 是运行在 Android 上的 MCP 网关。它把手机自身的能力和
| **执行命令与操作文件** | 通过 Root 或 Shizuku 执行命令,浏览、读取、写入、复制和移动文件 |
| **接入其他 MCP 服务** | 添加手机本机的 HTTP MCP 服务,或由 MBrain 启动和管理 stdio MCP 进程 |
| **统一管理与连接** | 一个 MCP 地址提供工具目录,支持搜索工具、查看说明、复制连接信息和查看近期运行记录 |
+| **内网穿透** | 内置 frpc,统一配置一台服务器,多条基础 TCP 隧道转发 MBrain 或手机其他服务 |
- **按需启用**:Root 和 Shizuku 各用一个开关,打开时自动检查并申请权限。
- **随时停止**:首页右下角一键启停,也可从前台通知停止网关。
@@ -102,7 +103,9 @@ Authorization: Bearer <从 MBrain 复制的 Token>
adb forward tcp:8765 tcp:8765
```
-然后在电脑客户端中使用相同的 MCP 地址。每次重新启动网关,Token 都会变化,需要同步更新客户端配置。
+默认端口被占用时,网关会自动使用空闲端口。请以“连接地址与凭据”中的实际地址及“使用说明”中的 ADB 命令为准。Token 加密保存在设备上,重启后保持不变;可在凭据页重置。
+
+**远程客户端**可在“设置 → 内网穿透”配置一台自建 frps,再添加 TCP 隧道。每条隧道独立启停与重试;MCP 隧道跟随网关,自定义服务隧道独立运行。具体见[内网穿透指南](docs/remote-access.md)。
连接后可以先让 Agent 执行一个简单的只读请求:
@@ -112,6 +115,8 @@ adb forward tcp:8765 tcp:8765
## 接入 MCP 服务
+需要从公网连接时,可进入 **设置 → 内网穿透 → 配置服务器** 填写 frps 地址、端口和 Token。当前仅支持基础 TCP 转发,所有隧道共用一台服务器。配置示例与运行规则见[内网穿透指南](docs/remote-access.md)。
+
进入 **MCP → 添加服务**,选择连接方式:
| 方式 | 适用情况 | 需要填写 |
@@ -135,7 +140,7 @@ HTTP 服务目前只支持回环地址。托管进程所需的程序和运行环
为什么客户端连接不上?
-先确认首页显示“运行中”,并使用本次启动生成的 Token。电脑连接时还需确认 ADB 端口转发成功。网关仅监听手机的回环地址,不能直接用手机的局域网 IP 或公网地址访问。
+先确认首页显示“运行中”,并使用凭据页中的 Token。电脑连接时还需确认实际端口的 ADB 转发成功。网关仅监听手机回环地址;远程访问通过已配置的 TCP 隧道连接。
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 8675def..c8bd12e 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -5,14 +5,16 @@ plugins {
alias(libs.plugins.kotlin.serialization)
}
android {
+ ndkVersion = "28.2.13676358"
namespace = "com.powercess.mbrain"
compileSdk = libs.versions.compileSdk.get().toInt()
defaultConfig {
applicationId = "com.powercess.mbrain"
minSdk = libs.versions.minSdk.get().toInt()
targetSdk = libs.versions.targetSdk.get().toInt()
- versionCode = 3
- versionName = "0.1.0"
+ versionCode = 4
+ versionName = "0.2.0"
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildFeatures { compose = true; buildConfig = true }
buildTypes {
@@ -27,7 +29,21 @@ android {
}
kotlinOptions { jvmTarget = "11" }
packaging.resources.excludes += setOf("META-INF/INDEX.LIST", "META-INF/io.netty.versions.properties")
+ packaging.jniLibs.useLegacyPackaging = true
+ packaging.jniLibs.keepDebugSymbols += "**/libfrpc.so"
+ sourceSets.getByName("main").jniLibs.srcDir(layout.buildDirectory.dir("generated/frpc/jniLibs"))
}
+val buildFrpc by tasks.registering(Exec::class) {
+ val output = layout.buildDirectory.dir("generated/frpc/jniLibs")
+ inputs.file(rootProject.file("scripts/build_frpc.py"))
+ outputs.dir(output)
+ val python = providers.environmentVariable("MBRAIN_PYTHON").orElse(if (System.getProperty("os.name").startsWith("Windows")) "python" else "python3")
+ commandLine(python.get(), rootProject.file("scripts/build_frpc.py").absolutePath,
+ "--ndk", android.sdkDirectory.resolve("ndk/${android.ndkVersion}").absolutePath,
+ "--output", output.get().asFile.absolutePath,
+ "--cache", rootProject.layout.buildDirectory.dir("frpc-source").get().asFile.absolutePath)
+}
+tasks.named("preBuild").configure { dependsOn(buildFrpc) }
dependencies {
implementation(project(":droid-mcp-core"))
implementation(project(":droid-mcp-device"))
@@ -44,4 +60,6 @@ dependencies {
implementation("androidx.compose.material:material-icons-extended")
testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
+ androidTestImplementation("androidx.test:runner:1.6.2")
+ androidTestImplementation("androidx.test.ext:junit:1.2.1")
}
diff --git a/app/src/androidTest/kotlin/com/powercess/mbrain/remote/FrpcDeviceTest.kt b/app/src/androidTest/kotlin/com/powercess/mbrain/remote/FrpcDeviceTest.kt
new file mode 100644
index 0000000..8c5191c
--- /dev/null
+++ b/app/src/androidTest/kotlin/com/powercess/mbrain/remote/FrpcDeviceTest.kt
@@ -0,0 +1,122 @@
+package com.powercess.mbrain.remote
+
+import android.content.Intent
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import com.powercess.mbrain.gateway.GatewayRuntime
+import com.powercess.mbrain.gateway.MBrainService
+import org.junit.Assert.*
+import org.junit.Assume.assumeTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import java.net.InetAddress
+import java.net.ServerSocket
+import java.net.Socket
+import kotlin.concurrent.thread
+
+/** Run with scripts/smoke-frpc.py: a real frps is reached through adb reverse. */
+@RunWith(AndroidJUnit4::class)
+class FrpcDeviceTest {
+ @Test fun realTcpFrpcSupportsSharedServerAndIndependentLifecycles() {
+ val instrumentation = InstrumentationRegistry.getInstrumentation()
+ val args = InstrumentationRegistry.getArguments()
+ assumeTrue("Use scripts/smoke-frpc.py to provide the local frps fixture", args.containsKey("controlPort"))
+ val context = instrumentation.targetContext
+ val backend = ServerSocket(0, 16, InetAddress.getByName("127.0.0.1"))
+ serve(backend)
+ val tcpPort = args.getString("tcpPort")!!.toInt()
+ val mcpPort = args.getString("mcpPort")!!.toInt()
+ val server = TunnelServer(name = "integration", host = "127.0.0.1",
+ port = args.getString("controlPort")!!.toInt(), token = args.getString("frpToken")!!)
+ val base = TunnelConfig(name = "integration tcp", serverId = server.id,
+ target = TunnelTarget.CUSTOM, localPort = backend.localPort, remotePort = tcpPort)
+ val mcp = base.copy(id = newId(), name = "integration MCP", target = TunnelTarget.MCP, remotePort = mcpPort)
+ val tunnels = listOf(base, mcp)
+ fun main(block: () -> Unit) = instrumentation.runOnMainSync(block)
+ try {
+ main {
+ GatewayRuntime.initialize(context)
+ RemoteRuntime.initialize(context)
+ RemoteRuntime.saveServer(server)
+ tunnels.forEach(RemoteRuntime::saveTunnel)
+ tunnels.forEach { RemoteRuntime.enableTunnel(it.id, true) }
+ }
+ await { RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.WAITING }
+ await { RemoteRuntime.status.value[base.id]?.phase == TunnelPhase.CONNECTED }
+ assertTrue(request(tcpPort).contains("frpc-device-ok"))
+ main { context.startForegroundService(Intent(context, MBrainService::class.java)) }
+ await { GatewayRuntime.status.value.running && RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.CONNECTED }
+ assertTrue(request(mcpPort, "/mcp", "invalid-test-token").contains("401"))
+ val initialized = request(mcpPort, "/mcp", GatewayRuntime.status.value.token)
+ assertTrue(initialized.contains("200") && initialized.contains("protocolVersion"))
+ main { context.stopService(Intent(context, MBrainService::class.java)) }
+ await { RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.WAITING }
+ assertTrue(request(tcpPort).contains("frpc-device-ok"))
+ assertStreaming(tcpPort)
+ main {
+ RemoteRuntime.enableTunnel(mcp.id, false)
+ RemoteRuntime.saveTunnel(mcp.copy(target = TunnelTarget.CUSTOM, localPort = backend.localPort))
+ RemoteRuntime.enableTunnel(mcp.id, true)
+ }
+ await { RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.CONNECTED }
+ main { RemoteRuntime.enableTunnel(base.id, false) }
+ assertTrue(request(mcpPort).contains("frpc-device-ok"))
+ main { RemoteRuntime.stopAll() }
+ await { RemoteRuntime.status.value.values.all { it.phase == TunnelPhase.OFF } }
+ await { java.io.File(context.noBackupFilesDir, "frpc-runtime").listFiles().orEmpty().isEmpty() }
+ } finally {
+ main {
+ RemoteRuntime.stopAll(); context.stopService(Intent(context, MBrainService::class.java))
+ tunnels.forEach { RemoteRuntime.removeTunnel(it.id) }
+ RemoteRuntime.removeServer(server.id)
+ }
+ backend.close()
+ }
+ }
+
+ private fun serve(server: ServerSocket) = thread(isDaemon = true) {
+ while (!server.isClosed) {
+ val socket = runCatching { server.accept() }.getOrNull() ?: break
+ thread(isDaemon = true) { runCatching { socket.use {
+ it.soTimeout = 3000
+ val request = it.inputStream.bufferedReader().readLine()
+ if (request != null) {
+ if ("/events" in request) {
+ it.outputStream.write("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\ndata: first\n\n".toByteArray())
+ it.outputStream.flush()
+ Thread.sleep(3500)
+ it.outputStream.write("data: last\n\n".toByteArray())
+ } else it.outputStream.write("HTTP/1.1 200 OK\r\nContent-Length: 14\r\nConnection: close\r\n\r\nfrpc-device-ok".toByteArray())
+ }
+ } } }
+ }
+ }
+
+ private fun assertStreaming(port: Int) {
+ Socket("127.0.0.1", port).use { socket ->
+ socket.soTimeout = 2500
+ socket.outputStream.write("GET /events HTTP/1.1\r\nHost: phone.example.test\r\nAccept: text/event-stream\r\nConnection: close\r\n\r\n".toByteArray())
+ val reader = socket.inputStream.bufferedReader()
+ var line = reader.readLine()
+ while (line != null && line != "data: first") line = reader.readLine()
+ // The backend delays its final event by 3.5 seconds. A buffered response times out.
+ assertEquals("data: first", line)
+ }
+ }
+
+ private fun request(port: Int, path: String = "/", token: String? = null): String {
+ return Socket("127.0.0.1", port).apply { soTimeout = 10000 }.use {
+ val body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-03-26\",\"capabilities\":{},\"clientInfo\":{\"name\":\"frpc-test\",\"version\":\"1\"}}}"
+ val headers = if (token == null) "GET $path HTTP/1.1\r\n" else
+ "POST $path HTTP/1.1\r\nAuthorization: Bearer $token\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\nContent-Length: ${body.toByteArray().size}\r\n"
+ it.outputStream.write((headers + "Host: localhost\r\nConnection: close\r\n\r\n" + if (token == null) "" else body).toByteArray())
+ it.inputStream.bufferedReader().readText()
+ }
+ }
+
+ private fun await(check: () -> Boolean) {
+ val deadline = System.nanoTime() + 30_000_000_000
+ while (!check() && System.nanoTime() < deadline) Thread.sleep(100)
+ assertTrue("Condition timed out", check())
+ }
+}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 4791351..3b74617 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -7,7 +7,7 @@
android:authorities="${applicationId}.shizuku" android:multiprocess="false"
android:enabled="true" android:exported="true"
android:permission="android.permission.INTERACT_ACROSS_USERS_FULL" />
-
+
@@ -18,5 +18,9 @@
+
+
+
diff --git a/app/src/main/assets/licenses/frp-LICENSE.txt b/app/src/main/assets/licenses/frp-LICENSE.txt
new file mode 100644
index 0000000..8dada3e
--- /dev/null
+++ b/app/src/main/assets/licenses/frp-LICENSE.txt
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/app/src/main/kotlin/com/powercess/mbrain/MainActivity.kt b/app/src/main/kotlin/com/powercess/mbrain/MainActivity.kt
index b75ef70..a6a8741 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/MainActivity.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/MainActivity.kt
@@ -11,6 +11,7 @@ import androidx.activity.result.contract.ActivityResultContracts
import com.powercess.mbrain.gateway.GatewayRuntime
import com.powercess.mbrain.gateway.MBrainService
import com.powercess.mbrain.ui.MBrainApp
+import com.powercess.mbrain.remote.RemoteRuntime
class MainActivity : ComponentActivity() {
private val notificationPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { }
@@ -19,6 +20,7 @@ class MainActivity : ComponentActivity() {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
GatewayRuntime.initialize(applicationContext)
+ RemoteRuntime.initialize(applicationContext)
setContent {
MBrainApp(
start = {
diff --git a/app/src/main/kotlin/com/powercess/mbrain/data/GatewayConfig.kt b/app/src/main/kotlin/com/powercess/mbrain/data/GatewayConfig.kt
index f411f5c..d6619ba 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/data/GatewayConfig.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/data/GatewayConfig.kt
@@ -23,7 +23,7 @@ data class McpConnectionConfig(
val mode: ExecutionMode = ExecutionMode.APP,
val enabled: Boolean = false,
) {
- fun validate() {
+ fun validate(gatewayPort: Int? = null) {
require(name.isNotBlank()) { "请填写服务名称" }
require(id.matches(Regex("[a-f0-9]{32}"))) { "连接 ID 无效" }
if (type == ConnectionType.HTTP) {
@@ -32,7 +32,8 @@ data class McpConnectionConfig(
require(uri.scheme in listOf("http", "https")) { "仅支持 HTTP / HTTPS MCP" }
require(uri.host in listOf("127.0.0.1", "localhost", "[::1]", "::1")) { "当前仅支持本机回环地址" }
require(uri.userInfo == null && uri.fragment == null) { "地址不能包含用户名或 fragment" }
- require(uri.port != 8765) { "不能连接 MBrain 自身端口" }
+ val effectivePort = if (uri.port >= 0) uri.port else if (uri.scheme == "https") 443 else 80
+ require(gatewayPort == null || effectivePort != gatewayPort) { "不能连接 MBrain 自身端口" }
require(!token.contains('\r') && !token.contains('\n')) { "Token 不能包含换行" }
} else {
require(command.isNotEmpty() && command.first().startsWith('/')) { "命令首项必须是可执行文件绝对路径" }
diff --git a/app/src/main/kotlin/com/powercess/mbrain/gateway/GatewayRuntime.kt b/app/src/main/kotlin/com/powercess/mbrain/gateway/GatewayRuntime.kt
index 4a23588..7a6a48f 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/gateway/GatewayRuntime.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/gateway/GatewayRuntime.kt
@@ -4,6 +4,7 @@ import android.content.Context
import com.powercess.mbrain.data.*
import com.powercess.mbrain.mcp.*
import com.powercess.mbrain.shell.*
+import com.powercess.mbrain.remote.SecretStore
import io.droidmcp.apps.AppsTools
import io.droidmcp.core.*
import io.droidmcp.device.DeviceTools
@@ -23,18 +24,21 @@ data class ToolInfo(val name: String, val description: String, val source: Strin
data class ConnectionStatus(val state: String = "未连接", val count: Int = 0, val error: String? = null)
data class GatewayStatus(
val running: Boolean = false, val token: String? = null,
+ val port: Int? = null,
val tools: List = emptyList(), val error: String? = null,
val rootReady: Boolean = false, val shizukuReady: Boolean = false,
val rootActivation: ActivationState = ActivationState(), val shizukuActivation: ActivationState = ActivationState(),
val connections: Map = emptyMap(),
val events: List = emptyList(),
-)
+) {
+ val endpoint: String? get() = port?.let { "http://127.0.0.1:$it/mcp" }
+}
object GatewayRuntime {
const val PORT = 8765
- const val ENDPOINT = "http://127.0.0.1:8765/mcp"
private lateinit var context: Context
private lateinit var store: ConfigStore
+ private lateinit var secrets: SecretStore
private val mutableConfig = MutableStateFlow(GatewayConfig())
val config = mutableConfig.asStateFlow()
private val mutableStatus = MutableStateFlow(GatewayStatus())
@@ -98,6 +102,7 @@ object GatewayRuntime {
context = appContext.applicationContext
store = ConfigStore(context)
mutableConfig.value = store.load()
+ secrets = SecretStore(context)
Shizuku.addBinderReceivedListenerSticky(binderReceived)
Shizuku.addBinderDeadListener(binderDead)
Shizuku.addRequestPermissionResultListener(permissionResult)
@@ -172,11 +177,22 @@ object GatewayRuntime {
}
}
fun saveConnection(connection: McpConnectionConfig) {
- connection.validate()
+ connection.validate(status.value.port)
updateConfig { it.copy(connections = it.connections.filterNot { c -> c.id == connection.id } + connection) }
}
fun removeConnection(id: String) = updateConfig { it.copy(connections = it.connections.filterNot { c -> c.id == id }) }
+ fun rotateAccessToken() {
+ try {
+ // Persist first so a storage failure does not silently invalidate clients.
+ val next = SecretStore.newToken()
+ secrets.write("gateway_token", next)
+ server?.setServerToken(next)
+ mutableStatus.update { it.copy(token = next.takeIf { _ -> it.running }) }
+ event("访问凭据已重置")
+ } catch (_: Exception) { failed(IllegalStateException("访问凭据重置失败")) }
+ }
+
fun createServer(appContext: Context): DroidMcp {
initialize(appContext)
processes = ProcessSupervisor()
@@ -187,7 +203,8 @@ object GatewayRuntime {
event("${event.toolName} · ${if (event.success) "成功" else "失败"} · ${event.durationMs}ms")
}
})
- .enableHttpServer(port = PORT, host = "127.0.0.1", requireAuth = true, readOnly = false).build()
+ .enableHttpServer(port = PORT, host = "127.0.0.1", token = secrets.gatewayToken(), requireAuth = true,
+ readOnly = false, fallbackToDynamicPort = true).build()
}
private fun localTools(): List = buildList {
addAll(DeviceTools.all(context))
@@ -220,7 +237,8 @@ object GatewayRuntime {
}
fun started(instance: DroidMcp) {
server = instance
- mutableStatus.update { it.copy(running = true, token = instance.serverToken, error = null) }
+ val port = checkNotNull(instance.serverPort)
+ mutableStatus.update { it.copy(running = true, token = instance.serverToken, port = port, error = null) }
refreshTools()
event("本机 MCP 服务已启动")
config.value.connections.filter { it.enabled }.forEach { connect(it.id) }
@@ -236,7 +254,7 @@ object GatewayRuntime {
connectionState(id, ConnectionStatus("连接中"))
var peer: McpPeer? = null
try {
- item.validate()
+ item.validate(status.value.port)
val rpc = when (item.type) {
ConnectionType.HTTP -> HttpRpcConnection(item)
ConnectionType.STDIO -> {
@@ -281,7 +299,7 @@ object GatewayRuntime {
}
fun stopped() {
shutdown()
- mutableStatus.update { it.copy(running = false, token = null, tools = emptyList(), connections = emptyMap()) }
+ mutableStatus.update { it.copy(running = false, token = null, port = null, tools = emptyList(), connections = emptyMap()) }
event("网关及托管子进程已停止")
}
}
diff --git a/app/src/main/kotlin/com/powercess/mbrain/gateway/MBrainService.kt b/app/src/main/kotlin/com/powercess/mbrain/gateway/MBrainService.kt
index 2a8d44e..a6d6865 100644
--- a/app/src/main/kotlin/com/powercess/mbrain/gateway/MBrainService.kt
+++ b/app/src/main/kotlin/com/powercess/mbrain/gateway/MBrainService.kt
@@ -8,14 +8,20 @@ import com.powercess.mbrain.MainActivity
import com.powercess.mbrain.R
import io.droidmcp.core.DroidMcp
import io.droidmcp.server.DroidMcpServerService
+import com.powercess.mbrain.remote.RemoteRuntime
class MBrainService : DroidMcpServerService() {
override fun createServer(): DroidMcp = GatewayRuntime.createServer(this)
- override fun onServerStarted(server: DroidMcp) = GatewayRuntime.started(server)
+ override fun onServerStarted(server: DroidMcp) {
+ GatewayRuntime.started(server)
+ getSystemService(android.app.NotificationManager::class.java).notify(DroidMcpServerService.NOTIFICATION_ID, buildNotification())
+ RemoteRuntime.gatewayChanged(GatewayRuntime.status.value.port)
+ }
override fun onServerStartFailed(error: Exception) = GatewayRuntime.failed(error)
- override fun onServerStopped() = GatewayRuntime.stopped()
+ override fun onServerStopped() { RemoteRuntime.gatewayChanged(null); GatewayRuntime.stopped() }
override fun onDestroy() {
+ RemoteRuntime.gatewayChanged(null)
GatewayRuntime.shutdown()
super.onDestroy()
}
@@ -26,7 +32,7 @@ class MBrainService : DroidMcpServerService() {
return START_NOT_STICKY
}
super.onStartCommand(intent, flags, startId)
- // Require an explicit user start after process death; tokens are session-scoped.
+ // Require an explicit user start after process death.
return START_NOT_STICKY
}
@@ -37,7 +43,7 @@ class MBrainService : DroidMcpServerService() {
return NotificationCompat.Builder(this, DroidMcpServerService.CHANNEL_ID)
.setSmallIcon(R.drawable.ic_mbrain)
.setContentTitle("MBrain 正在运行")
- .setContentText("本机 MCP 能力网关 · 端口 ${GatewayRuntime.PORT}")
+ .setContentText(GatewayRuntime.status.value.port?.let { "MCP 网关 · 端口 $it" } ?: "正在启动 MCP 网关")
.setContentIntent(open)
.addAction(android.R.drawable.ic_media_pause, "停止服务", stop)
.setOngoing(true)
diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/Certificates.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/Certificates.kt
new file mode 100644
index 0000000..b34277f
--- /dev/null
+++ b/app/src/main/kotlin/com/powercess/mbrain/remote/Certificates.kt
@@ -0,0 +1,7 @@
+package com.powercess.mbrain.remote
+
+import kotlinx.serialization.Serializable
+
+/** Read-only legacy payload. Retained during saves; certificates are no longer imported or used. */
+@Serializable
+data class TunnelCertificate(val id: String = newId(), val name: String = "", val pem: String = "", val keyPem: String = "")
diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/FrpcController.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/FrpcController.kt
new file mode 100644
index 0000000..78cbc76
--- /dev/null
+++ b/app/src/main/kotlin/com/powercess/mbrain/remote/FrpcController.kt
@@ -0,0 +1,155 @@
+package com.powercess.mbrain.remote
+
+import kotlinx.coroutines.*
+import java.io.File
+import java.io.Reader
+import java.net.InetSocketAddress
+import java.net.Socket
+
+/** One supervised process per tunnel: credentials, failures and retries are independent. */
+class FrpcController(
+ private val executable: File,
+ private val directory: File,
+ private val changed: (String, TunnelStatus) -> Unit,
+ private val launchProcess: (File, File) -> Process = { binary, config ->
+ ProcessBuilder(binary.absolutePath, "-c", config.absolutePath).redirectErrorStream(true).start()
+ },
+) : AutoCloseable {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private class Entry(val config: TunnelConfig, val endpoint: Pair) {
+ var process: Process? = null
+ lateinit var job: Job
+ var status = TunnelStatus(TunnelPhase.CONNECTING)
+ }
+ private val entries = mutableMapOf()
+ private var closed = false
+
+ @Synchronized fun reconcile(configs: List, port: Int?) {
+ if (closed) return
+ val desired = configs.filter { it.enabled && it.endpoint(port) != null }.associateBy { it.id }
+ entries.keys.toList().forEach { id ->
+ val entry = entries.getValue(id)
+ if (desired[id] != entry.config || desired[id]?.endpoint(port) != entry.endpoint) stop(id)
+ }
+ configs.forEach { config ->
+ val endpoint = config.endpoint(port)
+ if (!config.enabled || endpoint == null) changed(config.id, TunnelStatus(if (config.enabled) TunnelPhase.WAITING else TunnelPhase.OFF))
+ else if (config.id !in entries) {
+ val entry = Entry(config, endpoint)
+ entry.job = scope.launch(start = CoroutineStart.LAZY) { supervise(entry) }
+ entries[config.id] = entry
+ changed(config.id, entry.status)
+ entry.job.start()
+ }
+ }
+ }
+
+ @Synchronized fun retry(id: String) { stop(id) }
+
+ private fun stop(id: String) {
+ val entry = entries.remove(id) ?: return
+ // Destroy first to unblock pipe reads; no process can be published after removal.
+ entry.process?.destroy()
+ entry.process?.let { process -> if (process.isAlive) process.destroyForcibly() }
+ entry.job.cancel()
+ }
+
+ @Synchronized private fun publish(entry: Entry, phase: TunnelPhase, error: String? = null) {
+ if (entries[entry.config.id] !== entry) return
+ // A new connection attempt does not resolve the preceding failure. Keep its reason
+ // until the state changes, rather than alternating error/retry rows on every attempt.
+ if (phase == TunnelPhase.RETRYING && entry.status.phase == TunnelPhase.RETRYING && error == null) return
+ if (entry.status.phase == phase && entry.status.error == error) return
+ entry.status = entry.status.copy(phase = phase, error = error, events = (listOf(error ?: phase.label) + entry.status.events).take(40),
+ serverConnected = when (phase) { TunnelPhase.CONNECTED -> true; TunnelPhase.ERROR -> entry.status.serverConnected; else -> false })
+ changed(entry.config.id, entry.status)
+ }
+
+ @Synchronized private fun updateHealth(entry: Entry, health: LocalHealth? = null, connected: Boolean? = null) {
+ if (entries[entry.config.id] !== entry) return
+ entry.status = entry.status.copy(localHealth = health ?: entry.status.localHealth, serverConnected = connected ?: entry.status.serverConnected)
+ changed(entry.config.id, entry.status)
+ }
+
+ private suspend fun supervise(entry: Entry) {
+ var pause = 1000L
+ while (currentCoroutineContext().isActive) {
+ var process: Process? = null
+ // A unique file per attempt prevents an old job deleting its replacement's config.
+ var attemptDirectory: File? = null
+ var healthJob: Job? = null
+ try {
+ check(executable.isFile && executable.canExecute()) { "此设备的 frpc 不可用" }
+ directory.mkdirs()
+ attemptDirectory = java.nio.file.Files.createTempDirectory(directory.toPath(), "frpc-").toFile()
+ val configFile = privateFile(attemptDirectory, "frpc.json", entry.config.frpcConfig(entry.endpoint))
+ currentCoroutineContext().ensureActive()
+ synchronized(this) {
+ if (entries[entry.config.id] !== entry) throw CancellationException()
+ process = launchProcess(executable, configFile)
+ entry.process = process
+ }
+ publish(entry, TunnelPhase.CONNECTING)
+ healthJob = scope.launch {
+ while (isActive) {
+ val healthy = runCatching {
+ Socket().use { it.connect(InetSocketAddress(entry.endpoint.first, entry.endpoint.second), 2000) }
+ }.isSuccess
+ updateHealth(entry, if (healthy) LocalHealth.REACHABLE else LocalHealth.UNREACHABLE)
+ delay(15_000)
+ }
+ }
+ process!!.inputStream.reader().use { reader ->
+ while (currentCoroutineContext().isActive) {
+ val line = reader.boundedLine() ?: break
+ if ("login to server success" in line) updateHealth(entry, connected = true)
+ classifyFrpcLine(line)?.let { (phase, error) ->
+ if (phase == TunnelPhase.CONNECTED) pause = 1000L
+ publish(entry, phase, error)
+ }
+ }
+ }
+ currentCoroutineContext().ensureActive()
+ publish(entry, TunnelPhase.RETRYING, "隧道进程已退出,正在重试")
+ } catch (e: CancellationException) { throw e
+ } catch (_: Exception) {
+ publish(entry, TunnelPhase.ERROR, if (!executable.canExecute()) "此设备的 frpc 不可用" else "隧道启动失败,正在重试")
+ } finally {
+ healthJob?.cancel()
+ process?.destroy()
+ process?.let { if (it.isAlive) it.destroyForcibly() }
+ process?.let { runCatching { it.inputStream.close() }; runCatching { it.outputStream.close() }; runCatching { it.errorStream.close() } }
+ attemptDirectory?.deleteRecursively()
+ synchronized(this) { if (entry.process === process) entry.process = null }
+ }
+ delay(pause)
+ pause = (pause * 2).coerceAtMost(30_000)
+ }
+ }
+
+ @Synchronized override fun close() {
+ closed = true
+ entries.keys.toList().forEach(::stop)
+ scope.cancel()
+ }
+
+ // Await asynchronous process/config cleanup before deleting the owner's directory.
+ internal suspend fun awaitTermination() { scope.coroutineContext.job.join() }
+}
+
+private fun privateFile(directory: File, name: String, text: String): File = File(directory, name).apply {
+ createNewFile()
+ setReadable(false, false); setReadable(true, true)
+ setWritable(false, false); setWritable(true, true)
+ writeText(text)
+}
+
+internal fun Reader.boundedLine(): String? {
+ val line = StringBuilder()
+ while (true) {
+ val char = read()
+ if (char < 0) return line.toString().takeIf { it.isNotEmpty() }
+ if (char == 10) return line.toString()
+ if (line.length < 4096) line.append(char.toChar())
+ }
+}
diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/RemoteRuntime.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/RemoteRuntime.kt
new file mode 100644
index 0000000..e320b80
--- /dev/null
+++ b/app/src/main/kotlin/com/powercess/mbrain/remote/RemoteRuntime.kt
@@ -0,0 +1,120 @@
+package com.powercess.mbrain.remote
+
+import android.content.Context
+import android.content.Intent
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import java.io.File
+
+/** Configuration outlives the service; enabled flags belong only to this application session. */
+object RemoteRuntime {
+ private lateinit var context: Context
+ private lateinit var store: TunnelStore
+ private val mutableConfig = MutableStateFlow(RemoteConfig())
+ val config = mutableConfig.asStateFlow()
+ private val mutableStatus = MutableStateFlow