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>(emptyMap()) + val status = mutableStatus.asStateFlow() + private val mutableError = MutableStateFlow(null) + val error = mutableError.asStateFlow() + private var loadFailed = false + private var controller: FrpcController? = null + private var mcpPort: Int? = null + + @Synchronized fun initialize(appContext: Context) { + if (::context.isInitialized) return + context = appContext.applicationContext + store = TunnelStore(SecretStore(context)) + runCatching { store.load() }.onSuccess { mutableConfig.value = it }.onFailure { + loadFailed = true + mutableError.value = "隧道配置无法解密或读取,已停止加载;原配置保留" + } + } + + @Synchronized fun saveTunnel(tunnel: TunnelConfig) { + check(mutableConfig.value.tunnels.none { it.id == tunnel.id && it.enabled }) { "请先关闭此隧道再编辑" } + val old = mutableConfig.value + old.resolve(tunnel).requireBasicTcp() + require(tunnel.serverId.isEmpty() || tunnel.serverId == old.server?.id) { "请使用当前服务器" } + val next = old.copy(tunnels = old.tunnels.filterNot { it.id == tunnel.id } + tunnel.copy(enabled = false)).migrateServers() + require(next.tunnels.first { it.id == tunnel.id }.serverId == next.server?.id) { "请使用当前服务器" } + persist(next) + } + + @Synchronized fun removeTunnel(id: String) { + persist(mutableConfig.value.copy(tunnels = mutableConfig.value.tunnels.filterNot { it.id == id })) + mutableStatus.update { it - id } + refresh() + } + + @Synchronized fun saveServer(server: TunnelServer) { persist(mutableConfig.value.saveServer(server)) } + + @Synchronized fun removeServer(id: String) { persist(mutableConfig.value.removeServer(id)) } + + private fun persist(next: RemoteConfig) { + check(!loadFailed) { "原配置读取失败,不能覆盖;请重新启动应用后重试" } + store.save(next) + mutableConfig.value = next + } + + @Synchronized fun enableTunnel(id: String, enabled: Boolean) { + check(!loadFailed) { "隧道配置不可用" } + val old = mutableConfig.value + check(old.tunnels.any { it.id == id }) { "隧道不存在" } + if (enabled) { + val tunnel = old.tunnels.first { it.id == id } + require(tunnel.serverId == old.server?.id) { "此隧道使用旧服务器,请先编辑并保存隧道" } + old.resolve(tunnel).requireBasicTcp() + } + val next = old.copy(tunnels = old.tunnels.map { if (it.id == id) it.copy(enabled = enabled) else it }) + next.validate() + mutableConfig.value = next + try { + if (enabled) context.startForegroundService(Intent(context, TunnelService::class.java)) + refresh() + } catch (_: Exception) { + mutableConfig.value = old + throw IllegalStateException("无法启动隧道服务,请回到应用后重试") + } + } + + @Synchronized fun retry(id: String) { controller?.retry(id); refresh() } + + @Synchronized fun gatewayChanged(port: Int?) { mcpPort = port; refresh() } + + @Synchronized fun serviceStarted() { + if (controller == null) { + val directory = File(context.noBackupFilesDir, "frpc-runtime") + // Only this service owns this fixed private directory. Remove credentials left by process death. + directory.deleteRecursively() + controller = FrpcController(File(context.applicationInfo.nativeLibraryDir, "libfrpc.so"), directory, { id, state -> + mutableStatus.update { states -> states + (id to state) } + }) + } + refresh() + } + + @Synchronized fun serviceStopped() { + // A deliberately stopped service may be destroyed after a new UI start request. + // In that case its controller was already detached; do not clear the new request. + if (controller == null) return + controller?.close(); controller = null + mutableConfig.update { it.copy(tunnels = it.tunnels.map { tunnel -> tunnel.copy(enabled = false) }) } + mutableStatus.value = mutableConfig.value.tunnels.associate { it.id to TunnelStatus() } + } + + @Synchronized fun stopAll() { + mutableConfig.update { it.copy(tunnels = it.tunnels.map { tunnel -> tunnel.copy(enabled = false) }) } + mutableStatus.value = mutableConfig.value.tunnels.associate { it.id to TunnelStatus() } + controller?.close(); controller = null + context.stopService(Intent(context, TunnelService::class.java)) + } + + private fun refresh() { + controller?.reconcile(mutableConfig.value.tunnels.map(mutableConfig.value::resolve), mcpPort) + if (mutableConfig.value.tunnels.none { it.enabled } && controller != null) { + controller?.close(); controller = null + context.stopService(Intent(context, TunnelService::class.java)) + } + } +} diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/SecretStore.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/SecretStore.kt new file mode 100644 index 0000000..87319ec --- /dev/null +++ b/app/src/main/kotlin/com/powercess/mbrain/remote/SecretStore.kt @@ -0,0 +1,47 @@ +package com.powercess.mbrain.remote + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import java.security.KeyStore +import java.security.SecureRandom +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** App-private, backup-excluded encrypted preferences. Fail closed on unreadable keys. */ +class SecretStore(context: Context) { + private val prefs = context.getSharedPreferences("remote_secrets", Context.MODE_PRIVATE) + private val alias = "mbrain.remote.v1" + private fun key(): SecretKey { + val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (store.getKey(alias, null) as? SecretKey)?.let { return it } + return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply { + init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build()) + }.generateKey() + } + @Synchronized fun read(name: String): String? { + val encoded = prefs.getString(name, null) ?: return null + val parts = encoded.split(':') + require(parts.size == 2) { "凭据无法读取" } + return Cipher.getInstance("AES/GCM/NoPadding").run { + init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, Base64.decode(parts[0], Base64.NO_WRAP))) + updateAAD(name.toByteArray()) + doFinal(Base64.decode(parts[1], Base64.NO_WRAP)).toString(Charsets.UTF_8) + } + } + @Synchronized fun write(name: String, value: String) { + val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { + init(Cipher.ENCRYPT_MODE, key()); updateAAD(name.toByteArray()) + } + val encrypted = cipher.doFinal(value.toByteArray()) + check(prefs.edit().putString(name, Base64.encodeToString(cipher.iv, Base64.NO_WRAP) + ":" + Base64.encodeToString(encrypted, Base64.NO_WRAP)).commit()) { "凭据保存失败" } + } + @Synchronized fun gatewayToken(): String = read("gateway_token") ?: newToken().also { write("gateway_token", it) } + companion object { + fun newToken(): String = Base64.encodeToString(ByteArray(32).also { SecureRandom().nextBytes(it) }, Base64.NO_WRAP or Base64.URL_SAFE or Base64.NO_PADDING) + } +} diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelConfig.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelConfig.kt new file mode 100644 index 0000000..b0e809b --- /dev/null +++ b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelConfig.kt @@ -0,0 +1,130 @@ +package com.powercess.mbrain.remote + +import kotlinx.serialization.Serializable +import kotlinx.serialization.Transient +import kotlinx.serialization.json.* +import java.net.URI +import java.util.UUID + +internal fun newId(): String = UUID.randomUUID().toString().replace("-", "") +internal fun validId(value: String) = value.matches(Regex("[a-f0-9]{32}")) +internal fun validHost(value: String): Boolean = value.isNotBlank() && value.length <= 253 && + value.none { it.isWhitespace() || it.isISOControl() || it in "/\\?#@\"{}[]" } && + runCatching { URI("tcp://${if (':' in value) "[$value]" else value}:1").host != null }.getOrDefault(false) + +@Serializable enum class ProxyType { TCP, HTTPS } +@Serializable enum class TunnelPlugin(val label: String, val wireName: String) { + NONE("不使用插件", ""), HTTPS2HTTP("HTTPS → HTTP", "https2http"), TLS2RAW("TLS → TCP", "tls2raw") +} +@Serializable enum class TunnelTarget { MCP, CUSTOM } + +@Serializable +data class TunnelConfig( + val id: String = newId(), + val name: String = "", + val serverId: String = "", + val server: String = "", + val serverPort: Int = 7000, + val token: String = "", + val type: ProxyType = ProxyType.TCP, + val plugin: TunnelPlugin = TunnelPlugin.NONE, + val target: TunnelTarget = TunnelTarget.MCP, + val localHost: String = "127.0.0.1", + val localPort: Int = 8765, + val remotePort: Int = 0, + val domains: List = emptyList(), + val publicUrl: String = "", + val certificateId: String = "", + val hostHeaderRewrite: String = "", + val tlsServerName: String = "", + val tlsCaId: String = "", + val tlsClientCertificateId: String = "", + // Starting tunnels is an explicit action after app process death, never a restore side effect. + @Transient val enabled: Boolean = false, +) { + val proxyName: String get() = "mbrain-$id" + val accessUrl: String get() = publicUrl.ifBlank { + if (target == TunnelTarget.MCP && validHost(server) && remotePort in 1..65535) + URI("http", null, server, remotePort, "/mcp", null, null).toASCIIString() + else "" + } + fun endpoint(mcpPort: Int?): Pair? = if (target == TunnelTarget.MCP) + mcpPort?.let { "127.0.0.1" to it } else localHost to localPort + + fun validate(others: List = emptyList()) { + require(validId(id)) { "隧道 ID 无效" } + require(name.isNotBlank() && name.length <= 80) { "请填写隧道名称(最多 80 字)" } + require(validHost(server)) { "服务器地址应为域名或 IP,不包含协议与端口" } + require(serverPort in 1..65535) { "服务器端口应为 1–65535" } + require(token.length <= 4096 && token.none { it.isISOControl() } && "{{" !in token) { "服务器 Token 格式无效" } + require(validHost(localHost) && localPort in 1..65535) { "请填写有效的本地地址和端口" } + require(type != ProxyType.HTTPS || plugin != TunnelPlugin.TLS2RAW) { "TLS → TCP 插件需要 TCP 代理" } + require(target != TunnelTarget.MCP || type != ProxyType.HTTPS || plugin == TunnelPlugin.HTTPS2HTTP) { "MBrain 使用 HTTP,请选择 HTTPS → HTTP 插件" } + if (type == ProxyType.TCP) require(remotePort in 1..65535) { "公网访问端口应为 1–65535" } + else require(domains.isNotEmpty() && domains.size <= 20 && domains.distinctBy { it.lowercase() }.size == domains.size && + domains.all { validHost(it) && ':' !in it && it.contains('.') }) { "请填写有效且不重复的域名(不含协议或端口)" } + require(plugin == TunnelPlugin.NONE || validId(certificateId)) { "请选择包含私钥的服务证书" } + require(listOf(tlsCaId, tlsClientCertificateId).all { it.isEmpty() || validId(it) }) { "证书引用无效" } + require(tlsServerName.isEmpty() || validHost(tlsServerName)) { "TLS 服务器名称无效" } + require(hostHeaderRewrite.length <= 253 && hostHeaderRewrite.none { it.isISOControl() } && "{{" !in hostHeaderRewrite) { "Host 请求头无效" } + if (publicUrl.isNotBlank()) { + val uri = runCatching { URI(publicUrl) }.getOrNull() + require(uri != null && uri.scheme in listOf("http", "https") && !uri.host.isNullOrBlank() && uri.userInfo == null && + uri.fragment == null && uri.rawQuery == null && (uri.port == -1 || uri.port in 1..65535)) { "请填写完整的 HTTP / HTTPS 访问地址" } + require(target != TunnelTarget.MCP || uri!!.path == "/mcp") { "MBrain 公网地址路径应为 /mcp" } + } + require(others.none { other -> other.id != id && other.server.equals(server, true) && other.type == type && + (if (type == ProxyType.TCP) other.remotePort == remotePort else other.serverPort == serverPort && + other.domains.any { domain -> domains.any { it.equals(domain, true) } }) }) { "此服务器的公网访问端口或域名已被其他隧道使用" } + } + + // Legacy fields above remain readable so old configurations can be edited safely. + fun supportsBasicTcp(): Boolean = type == ProxyType.TCP && plugin == TunnelPlugin.NONE && + tlsCaId.isEmpty() && tlsClientCertificateId.isEmpty() && tlsServerName.isEmpty() + + fun requireBasicTcp() { + require(supportsBasicTcp()) { "此配置使用已停用的 HTTPS / TLS 功能,请重新编辑为 TCP 配置" } + require(publicUrl.isBlank() || URI(publicUrl).scheme == "http") { "当前仅支持 HTTP 公网地址" } + } + + fun asBasicTcp() = copy(type = ProxyType.TCP, plugin = TunnelPlugin.NONE, domains = emptyList(), + certificateId = "", hostHeaderRewrite = "", tlsServerName = "", tlsCaId = "", tlsClientCertificateId = "", + publicUrl = publicUrl.takeIf { it.isBlank() || runCatching { URI(it).scheme == "http" }.getOrDefault(false) }.orEmpty()) + + fun frpcConfig(endpoint: Pair): String { + validate() + requireBasicTcp() + require(validHost(endpoint.first) && endpoint.second in 1..65535) + return buildJsonObject { + put("serverAddr", server); put("serverPort", serverPort); put("loginFailExit", false) + putJsonObject("auth") { put("method", "token"); put("token", token) } + // Transport encryption is independent of the TCP proxy and requires no HTTPS configuration. + putJsonObject("transport") { putJsonObject("tls") { put("enable", true) } } + putJsonObject("log") { put("to", "console"); put("level", "info"); put("disablePrintColor", true) } + putJsonArray("proxies") { addJsonObject { + put("name", proxyName); put("type", "tcp"); put("remotePort", remotePort) + put("localIP", endpoint.first); put("localPort", endpoint.second) + } } + }.toString() + } + +} + +enum class TunnelPhase(val label: String) { + OFF("已关闭"), WAITING("等待 MCP 网关"), CONNECTING("连接中"), CONNECTED("隧道已注册"), RETRYING("重连中"), ERROR("连接失败") +} +enum class LocalHealth(val label: String) { UNKNOWN("尚未检测"), REACHABLE("端口可连接"), UNREACHABLE("端口不可连接") } +data class TunnelStatus( + val phase: TunnelPhase = TunnelPhase.OFF, val error: String? = null, val events: List = emptyList(), + val serverConnected: Boolean = false, val localHealth: LocalHealth = LocalHealth.UNKNOWN, +) + +internal fun classifyFrpcLine(line: String): Pair? = when { + "start proxy success" in line -> TunnelPhase.CONNECTED to null + "token" in line && listOf("mismatch", "invalid", "not match", "doesn't match").any { it in line } -> TunnelPhase.ERROR to "服务器认证失败" + "port already used" in line || "port already in use" in line -> TunnelPhase.ERROR to "服务器公网访问端口被占用" + "start error" in line || "start proxy error" in line -> TunnelPhase.ERROR to "隧道注册失败,请检查端口、域名和服务器配置" + "login to server failed" in line || "connect to server error" in line -> TunnelPhase.RETRYING to "无法连接服务器,正在重试" + listOf("try to connect to server", "reconnect", "heartbeat timeout", "control writer is closing", "read from control").any { it in line } -> TunnelPhase.RETRYING to null + else -> null +} diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelServer.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelServer.kt new file mode 100644 index 0000000..5e995f9 --- /dev/null +++ b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelServer.kt @@ -0,0 +1,35 @@ +package com.powercess.mbrain.remote + +import kotlinx.serialization.Serializable + +@Serializable +data class TunnelServer( + val id: String = newId(), + val name: String = "", + val host: String = "", + val port: Int = 7000, + val token: String = "", + val tlsServerName: String = "", + val tlsCaId: String = "", + val tlsClientCertificateId: String = "", +) { + fun applyTo(tunnel: TunnelConfig) = tunnel.copy(server = host, serverPort = port, token = token, + tlsServerName = tlsServerName, tlsCaId = tlsCaId, tlsClientCertificateId = tlsClientCertificateId) + + fun validate() { + require(validId(id)) { "服务器 ID 无效" } + require(name.isNotBlank() && name.length <= 80) { "请填写服务器名称(最多 80 字)" } + applyTo(TunnelConfig(name = name, remotePort = 1)).validate() + } + + + companion object { + fun from(tunnel: TunnelConfig) = TunnelServer(id = tunnel.id, name = tunnel.server.take(80), host = tunnel.server, + port = tunnel.serverPort, token = tunnel.token, tlsServerName = tunnel.tlsServerName, + tlsCaId = tunnel.tlsCaId, tlsClientCertificateId = tunnel.tlsClientCertificateId) + } +} + +/** Inline fields are retained only to read old files and feed the existing frpc controller. */ +fun TunnelConfig.referenceServer(id: String) = copy(serverId = id, server = "", serverPort = 7000, + token = "", tlsServerName = "", tlsCaId = "", tlsClientCertificateId = "") diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelService.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelService.kt new file mode 100644 index 0000000..0db1f62 --- /dev/null +++ b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelService.kt @@ -0,0 +1,32 @@ +package com.powercess.mbrain.remote + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Intent +import android.os.IBinder +import androidx.core.app.NotificationCompat +import com.powercess.mbrain.MainActivity +import com.powercess.mbrain.R + +class TunnelService : Service() { + override fun onCreate() { + super.onCreate() + RemoteRuntime.initialize(applicationContext) + getSystemService(NotificationManager::class.java).createNotificationChannel( + NotificationChannel(CHANNEL, "内网穿透", NotificationManager.IMPORTANCE_LOW)) + val open = PendingIntent.getActivity(this, 10, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE) + val stop = PendingIntent.getService(this, 11, Intent(this, TunnelService::class.java).setAction(STOP), PendingIntent.FLAG_IMMUTABLE) + startForeground(2410, NotificationCompat.Builder(this, CHANNEL).setSmallIcon(R.drawable.ic_mbrain) + .setContentTitle("MBrain 内网穿透").setContentText("隧道服务已启动,点按管理连接") + .setContentIntent(open).addAction(android.R.drawable.ic_media_pause, "停止全部隧道", stop).setOngoing(true).build()) + } + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent?.action == STOP) RemoteRuntime.stopAll() else RemoteRuntime.serviceStarted() + return START_NOT_STICKY + } + override fun onDestroy() { RemoteRuntime.serviceStopped(); super.onDestroy() } + override fun onBind(intent: Intent?): IBinder? = null + companion object { private const val CHANNEL = "mbrain_tunnels"; private const val STOP = "com.powercess.mbrain.STOP_TUNNELS" } +} diff --git a/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelStore.kt b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelStore.kt new file mode 100644 index 0000000..d81b10a --- /dev/null +++ b/app/src/main/kotlin/com/powercess/mbrain/remote/TunnelStore.kt @@ -0,0 +1,63 @@ +package com.powercess.mbrain.remote + +import kotlinx.serialization.Serializable +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json + +@Serializable +data class RemoteConfig(val tunnels: List = emptyList(), val certificates: List = emptyList(), + val servers: List = emptyList()) { + // The list is retained only for reading older multi-server configurations. + val server: TunnelServer? get() = servers.firstOrNull() + + fun resolve(tunnel: TunnelConfig): TunnelConfig = if (tunnel.serverId.isEmpty()) tunnel else + requireNotNull(servers.find { it.id == tunnel.serverId }) { "请选择已配置的服务器" }.applyTo(tunnel) + + fun migrateServers(): RemoteConfig { + val migrated = servers.toMutableList() + val next = tunnels.map { tunnel -> + if (tunnel.serverId.isNotEmpty()) tunnel else { + val legacy = TunnelServer.from(tunnel) + val candidate = if (migrated.any { it.id == legacy.id }) legacy.copy(id = newId()) else legacy + val server = migrated.find { it.copy(id = candidate.id, name = candidate.name) == candidate } + ?: run { + var name = candidate.name + var suffix = 2 + while (migrated.any { it.name == name }) { name = "${candidate.name.take(70)} (${suffix++})" } + candidate.copy(name = name).also { migrated.add(it) } + } + tunnel.referenceServer(server.id) + } + } + return copy(tunnels = next, servers = migrated) + } + + fun saveServer(server: TunnelServer): RemoteConfig { + require(this.server == null || this.server?.id == server.id) { "当前只支持配置一台服务器" } + server.applyTo(TunnelConfig(name = server.name, remotePort = 1)).requireBasicTcp() + require(tunnels.none { it.serverId == server.id && it.enabled }) { "请先关闭使用此服务器的隧道再编辑" } + return copy(servers = if (this.server == null) listOf(server) else servers.map { if (it.id == server.id) server else it }).also { it.validate() } + } + + fun removeServer(id: String): RemoteConfig { + require(tunnels.none { it.serverId == id }) { "此服务器仍被隧道使用,请先修改或删除相关隧道" } + return copy(servers = servers.filterNot { it.id == id }) + } + + fun validate() { + require(servers.map { it.id }.distinct().size == servers.size) { "服务器 ID 重复" } + servers.forEach { it.validate() } + require(tunnels.map { it.id }.distinct().size == tunnels.size && certificates.map { it.id }.distinct().size == certificates.size) + val resolved = tunnels.map(::resolve) + resolved.forEach { it.validate(resolved) } + } +} + +class TunnelStore(private val secrets: SecretStore) { + private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true } + fun load(): RemoteConfig = (secrets.read("remote_config_v2")?.let { json.decodeFromString(it) } + ?: secrets.read("tunnels")?.let { RemoteConfig(tunnels = json.decodeFromString>(it)) } + ?: RemoteConfig()).also { it.validate() } + .migrateServers().also { it.validate() } + fun save(config: RemoteConfig) { config.validate(); secrets.write("remote_config_v2", json.encodeToString(config)) } +} diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/ConnectionScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/ConnectionScreens.kt index 57d1c07..89df27a 100644 --- a/app/src/main/kotlin/com/powercess/mbrain/ui/ConnectionScreens.kt +++ b/app/src/main/kotlin/com/powercess/mbrain/ui/ConnectionScreens.kt @@ -16,45 +16,41 @@ import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp -import androidx.compose.ui.window.Dialog -import androidx.compose.ui.window.DialogProperties import com.powercess.mbrain.data.* import com.powercess.mbrain.gateway.* import kotlinx.coroutines.launch @Composable internal fun ConnectionsScreen(status: GatewayStatus, config: GatewayConfig, open: (String) -> Unit, add: () -> Unit, home: () -> Unit) { - ScreenList { - item { SectionLabel("我的服务", "${config.connections.size} 个配置 · ${status.connections.values.count { it.state == "已连接" }} 个已连接") } + ScreenList(groupedRows = true) { + item { ListSection("外部 MCP 服务", firstSection = true) } if (!status.running) item { Group { ActionRow("网关尚未启动", "前往首页启动后连接服务", Icons.Outlined.PowerSettingsNew, home) } } - if (config.connections.isEmpty()) item { EmptyState(Icons.Outlined.Hub, "接入你的第一个服务", "连接本机 HTTP 服务,或由 MBrain 托管 MCP 进程。", "添加服务", add) } - items(config.connections, key = { it.id }) { connection -> + if (config.connections.isEmpty()) item { EmptyState("暂无服务", action = "添加服务", onAction = add) } + groupedItems(config.connections, key = { it.id }) { connection -> val state = status.connections[connection.id] ?: ConnectionStatus() - Group { ActionRow(connection.name, "${if (connection.type == ConnectionType.HTTP) "HTTP" else "托管进程"} · ${state.state}" + if (state.count > 0) " · ${state.count} 个工具" else "", + ActionRow(connection.name, "${if (connection.type == ConnectionType.HTTP) "HTTP" else "托管进程"} · ${state.state}" + if (state.count > 0) " · ${state.count} 个工具" else "", if (connection.type == ConnectionType.HTTP) Icons.Outlined.Link else Icons.Outlined.Terminal, { open("connection:${connection.id}") }, trailing = { if (state.state == "连接中") CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) - else Icon(if (state.error != null) Icons.Outlined.ErrorOutline else Icons.Outlined.ChevronRight, null, + else Icon(if (state.error != null) Icons.Outlined.ErrorOutline else Icons.Outlined.ChevronRight, null, Modifier.size(20.dp), tint = if (state.error != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant) - }) } + }) } - if (config.connections.isNotEmpty()) item { OutlinedButton(onClick = add, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { - Icon(Icons.Outlined.Add, null); Spacer(Modifier.width(8.dp)); Text("添加服务") - } } + if (config.connections.isNotEmpty()) item { SecondaryAction("添加服务", Icons.Outlined.Add, onClick = add) } } } @Composable internal fun ConnectionScreen(connection: McpConnectionConfig?, status: GatewayStatus, open: (String) -> Unit, edit: (String) -> Unit, remove: (String) -> Unit) { - if (connection == null) { EmptyState(Icons.Outlined.Hub, "服务已移除", "返回服务列表以添加或选择其他服务。"); return } + if (connection == null) { EmptyState("服务已移除"); return } val state = status.connections[connection.id] ?: ConnectionStatus() val active = state.state in listOf("已连接", "连接中") ScreenList { item { Group(card = true) { - Column(Modifier.fillMaxWidth().padding(20.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) { + Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { - IconTile(if (connection.type == ConnectionType.HTTP) Icons.Outlined.Link else Icons.Outlined.Terminal, true) + Icon(if (connection.type == ConnectionType.HTTP) Icons.Outlined.Link else Icons.Outlined.Terminal, null, Modifier.size(24.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant) Column(Modifier.weight(1f)) { Text(if (connection.type == ConnectionType.HTTP) "本机 HTTP 服务" else "MBrain 托管进程", style = MaterialTheme.typography.titleMedium) Text(if (connection.type == ConnectionType.HTTP) connection.endpoint else connection.command.firstOrNull().orEmpty(), @@ -76,7 +72,7 @@ internal fun ConnectionScreen(connection: McpConnectionConfig?, status: GatewayS state.error?.let { item { SectionLabel("连接失败") }; item { Note(it, error = true) } } item { SectionLabel("服务管理") } item { Group { - ActionRow("工具目录", "${state.count} 个工具", Icons.Outlined.Build, { open("tools:@${connection.id}") }) + ActionRow("查看工具", "共 ${state.count} 个工具", Icons.Outlined.Build, { open("tools:@${connection.id}") }) GroupDivider() ActionRow("编辑配置", if (active) "断开连接后可修改" else "地址、认证与执行方式", Icons.Outlined.Edit, if (active) null else ({ edit(connection.id) })) @@ -105,16 +101,16 @@ internal fun ConnectionEditor(initial: McpConnectionConfig, existing: Boolean, d val dirty = name != initial.name || endpoint != initial.endpoint || token != initial.token || executable != initial.command.firstOrNull().orEmpty() || arguments != initial.command.drop(1) || mode != initial.mode val close = { if (dirty) discard = true else dismiss() } - Dialog(onDismissRequest = close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) { + // Use the activity window so the editor shares its system-bar and IME insets. + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { BackHandler { close() } - Scaffold(modifier = Modifier.fillMaxSize().imePadding(), containerColor = MaterialTheme.colorScheme.background, + Scaffold(modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding(), + contentWindowInsets = WindowInsets(0, 0, 0, 0), containerColor = MaterialTheme.colorScheme.background, topBar = { TopAppBar(title = { Text(if (existing) "编辑服务" else "添加服务") }, navigationIcon = { IconButton(onClick = close) { Icon(Icons.Outlined.Close, "关闭编辑") } - }) }, + }, colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.background), windowInsets = WindowInsets(0, 0, 0, 0)) }, bottomBar = { - Surface(color = MaterialTheme.colorScheme.surface) { - Box(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 20.dp, vertical = 12.dp), contentAlignment = Alignment.Center) { - Button(onClick = { + EditorSaveBar("保存服务") { try { val next = initial.copy(name = name.trim(), endpoint = endpoint.trim(), token = token.trim(), command = if (initial.type == ConnectionType.STDIO) listOf(executable.trim()) + arguments else emptyList(), mode = mode) @@ -123,11 +119,9 @@ internal fun ConnectionEditor(initial: McpConnectionConfig, existing: Boolean, d error = e.message ?: "请检查配置" scope.launch { formList.animateScrollToItem(0) } } - }, modifier = Modifier.widthIn(max = 680.dp).fillMaxWidth().heightIn(min = 50.dp)) { Text("保存服务") } - } } }) { padding -> - Box(Modifier.padding(padding)) { + Box(Modifier.padding(padding).consumeWindowInsets(padding)) { ScreenList(state = formList) { item(key = "type") { Group { ActionRow(if (initial.type == ConnectionType.HTTP) "HTTP MCP" else "托管 MCP 进程", if (initial.type == ConnectionType.HTTP) "连接这台设备上已有的服务" else "由 MBrain 管理进程的启动与停止", @@ -154,7 +148,7 @@ internal fun ConnectionEditor(initial: McpConnectionConfig, existing: Boolean, d IconButton(onClick = { arguments = arguments.filterIndexed { i, _ -> i != index } }) { Icon(Icons.Outlined.RemoveCircleOutline, "移除参数 ${index + 1}") } } } - item(key = "add-argument") { OutlinedButton(onClick = { arguments = arguments + "" }) { Icon(Icons.Outlined.Add, null); Text("添加参数") } } + item(key = "add-argument") { SecondaryAction("添加参数", Icons.Outlined.Add, onClick = { arguments = arguments + "" }) } item(key = "mode-title") { SectionLabel("执行身份") } item(key = "mode") { SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) { ExecutionMode.entries.forEachIndexed { index, value -> diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/DesignSystem.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/DesignSystem.kt index dcbe6af..39f5f9d 100644 --- a/app/src/main/kotlin/com/powercess/mbrain/ui/DesignSystem.kt +++ b/app/src/main/kotlin/com/powercess/mbrain/ui/DesignSystem.kt @@ -8,6 +8,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons @@ -78,42 +79,82 @@ internal fun MBrainTheme(dark: Boolean, content: @Composable () -> Unit) { } @Composable -internal fun ScreenList(state: LazyListState = rememberLazyListState(), content: LazyListScope.() -> Unit) { +internal fun ScreenList(state: LazyListState = rememberLazyListState(), groupedRows: Boolean = false, content: LazyListScope.() -> Unit) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) { LazyColumn(Modifier.widthIn(max = 720.dp).fillMaxSize(), state = state, contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 28.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), content = content) + verticalArrangement = Arrangement.spacedBy(if (groupedRows) 2.dp else 8.dp), content = content) + } +} + +/** Use with ScreenList(groupedRows = true). Rows stay lazy and retain stable item keys. */ +internal fun LazyListScope.groupedItems(values: List, key: (T) -> Any, row: @Composable (T) -> Unit) { + itemsIndexed(values, key = { _, value -> key(value) }) { index, value -> + val top = if (index == 0) 20.dp else 4.dp + val bottom = if (index == values.lastIndex) 20.dp else 4.dp + Surface(Modifier.fillMaxWidth(), shape = RoundedCornerShape(topStart = top, topEnd = top, + bottomStart = bottom, bottomEnd = bottom), color = MaterialTheme.colorScheme.surfaceContainerLow) { + row(value) + } + } +} + +@Composable +internal fun EditorSaveBar(label: String, enabled: Boolean = true, save: () -> Unit) { + Surface(color = MaterialTheme.colorScheme.surface) { + Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + Box(Modifier.widthIn(max = 720.dp).fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) { + Button(onClick = save, enabled = enabled, modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp)) { + Text(label) + } + } + } + } +} + +@Composable +internal fun SecondaryAction(label: String, icon: ImageVector? = null, enabled: Boolean = true, onClick: () -> Unit) { + OutlinedButton(onClick = onClick, enabled = enabled, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { + icon?.let { Icon(it, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)) } + Text(label) } } @Composable -internal fun SectionLabel(title: String, subtitle: String? = null) { - Column(Modifier.fillMaxWidth().padding(start = 4.dp, end = 4.dp, top = 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { +internal fun ContentCard(text: String, monospace: Boolean = false) { + Group(card = true) { + androidx.compose.foundation.text.selection.SelectionContainer { + Text(text, Modifier.fillMaxWidth().padding(16.dp), style = MaterialTheme.typography.bodyMedium, + fontFamily = if (monospace) androidx.compose.ui.text.font.FontFamily.Monospace else null) + } + } +} + +@Composable +internal fun SectionLabel(title: String, subtitle: String? = null, firstSection: Boolean = false) { + Column(Modifier.fillMaxWidth().padding(start = 4.dp, end = 4.dp, top = if (firstSection) 4.dp else 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.primary) subtitle?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } } } +/** Keep the section-to-row gap at 8dp in a list whose row gap is 2dp. */ +@Composable +internal fun ListSection(title: String, subtitle: String? = null, firstSection: Boolean = false) { + Column(Modifier.padding(bottom = 6.dp)) { SectionLabel(title, subtitle, firstSection) } +} + @Composable internal fun Group(card: Boolean = false, content: @Composable ColumnScope.() -> Unit) { Surface(modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp), - color = if (card) MaterialTheme.colorScheme.surfaceContainerLow else MaterialTheme.colorScheme.background) { + color = if (card) MaterialTheme.colorScheme.surfaceContainerLow else Color.Transparent) { Column(Modifier.fillMaxWidth(), content = content) } } @Composable -internal fun GroupDivider() = Spacer(Modifier.fillMaxWidth().height(2.dp).background(MaterialTheme.colorScheme.background)) - -@Composable -internal fun IconTile(icon: ImageVector, prominent: Boolean = false) { - Surface(shape = RoundedCornerShape(14.dp), color = if (prominent) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceContainerLow) { - Box(Modifier.size(42.dp), contentAlignment = Alignment.Center) { - Icon(icon, null, Modifier.size(22.dp), tint = if (prominent) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant) - } - } -} +internal fun GroupDivider() = Spacer(Modifier.fillMaxWidth().height(2.dp)) @Composable internal fun ActionRow(title: String, subtitle: String? = null, icon: ImageVector, @@ -148,13 +189,14 @@ internal fun StatusPill(text: String, good: Boolean = false, error: Boolean = fa } @Composable -internal fun EmptyState(icon: ImageVector, title: String, description: String, action: String? = null, onAction: () -> Unit = {}) { +internal fun EmptyState(title: String, description: String? = null, action: String? = null, onAction: () -> Unit = {}) { Column(Modifier.fillMaxWidth().padding(vertical = 36.dp, horizontal = 20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp)) { - IconTile(icon, prominent = true) Text(title, style = MaterialTheme.typography.titleMedium) - Text(description, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = androidx.compose.ui.text.style.TextAlign.Center) + description?.let { + Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = androidx.compose.ui.text.style.TextAlign.Center) + } if (action != null) FilledTonalButton(onClick = onAction) { Text(action) } } } diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/DetailScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/DetailScreens.kt index d7be5df..a2fe863 100644 --- a/app/src/main/kotlin/com/powercess/mbrain/ui/DetailScreens.kt +++ b/app/src/main/kotlin/com/powercess/mbrain/ui/DetailScreens.kt @@ -31,6 +31,17 @@ internal fun ToolsScreen(status: GatewayStatus, source: String, open: (String) - (query.isBlank() || listOf(tool.name, tool.description, tool.source, toolTitle(tool.name)).any { it.contains(query, true) }) } } + if (!status.running) { + ScreenList { + item { + Box(Modifier.fillMaxWidth().padding(vertical = 32.dp), contentAlignment = Alignment.Center) { + Text("启动网关后查看工具", style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } + return + } Column(Modifier.fillMaxSize()) { Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { OutlinedTextField(query, { query = it }, Modifier.widthIn(max = 720.dp).fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), @@ -38,14 +49,13 @@ internal fun ToolsScreen(status: GatewayStatus, source: String, open: (String) - trailingIcon = { if (query.isNotEmpty()) IconButton(onClick = { query = "" }) { Icon(Icons.Outlined.Close, "清空搜索") } }, singleLine = true, shape = MaterialTheme.shapes.large) } - ScreenList { - if (!status.running) item { EmptyState(Icons.Outlined.PowerSettingsNew, "网关尚未启动", "返回首页启动网关后,查看当前可用工具。") } - else if (matches.isEmpty()) item { EmptyState(Icons.Outlined.SearchOff, "没有找到工具", if (query.isNotBlank()) "试试其他关键词。" else "启用能力或连接服务后,工具会出现在这里。") } + ScreenList(groupedRows = true) { + if (matches.isEmpty()) item { EmptyState(if (query.isNotBlank()) "没有匹配的工具" else "暂无工具") } else { - item { SectionLabel("${matches.size} 个工具", "选择工具查看完整说明") } - items(matches, key = { it.name }) { tool -> Group { + item { ListSection("共 ${matches.size} 个工具", firstSection = true) } + groupedItems(matches, key = { it.name }) { tool -> ActionRow(toolTitle(tool.name), tool.source, Icons.Outlined.Build, { open("tool:${tool.name}") }) - } } + } } } } @@ -54,30 +64,40 @@ internal fun ToolsScreen(status: GatewayStatus, source: String, open: (String) - @Composable internal fun ToolScreen(tool: ToolInfo?, copy: (String, String) -> Unit) { ScreenList { - if (tool == null) item { EmptyState(Icons.Outlined.Build, "工具当前不可用", "对应服务可能已停止,请返回目录刷新查看。") } + if (tool == null) item { EmptyState("工具当前不可用", "返回列表刷新查看") } else { item { Group { ActionRow(toolTitle(tool.name), tool.source, Icons.Outlined.Build) } } item { SectionLabel("功能说明") } - item { SelectionContainer { Note(tool.description.ifBlank { "服务未提供工具说明。" }) } } + item { ContentCard(tool.description.ifBlank { "暂无说明" }) } item { SectionLabel("调用名称") } - item { Group { ActionRow(tool.name, "点击复制", Icons.Outlined.Code, { copy("工具名称", tool.name) }, trailing = { Icon(Icons.Outlined.ContentCopy, null) }) } } + item { Group(card = true) { + SelectionContainer { Text(tool.name, Modifier.fillMaxWidth().padding(16.dp), style = MaterialTheme.typography.bodyMedium, fontFamily = FontFamily.Monospace) } + GroupDivider() + ActionRow("复制调用名称", icon = Icons.Outlined.ContentCopy, onClick = { copy("工具名称", tool.name) }, trailing = {}) + } } } } } @Composable -internal fun CredentialsScreen(status: GatewayStatus, copy: (String, String) -> Unit) { +internal fun CredentialsScreen(status: GatewayStatus, copy: (String, String) -> Unit, + tunnels: List, open: (String) -> Unit) { var reveal by rememberSaveable { mutableStateOf(false) } + var reset by rememberSaveable { mutableStateOf(false) } LaunchedEffect(status.token) { reveal = false } ScreenList { - item { SectionLabel("连接地址") } - item { Group { ActionRow("本机 MCP", GatewayRuntime.ENDPOINT, Icons.Outlined.Link, - { copy("连接地址", GatewayRuntime.ENDPOINT) }, trailing = { Icon(Icons.Outlined.ContentCopy, null) }) } } + item { SectionLabel("连接地址", firstSection = true) } + item { Group { ActionRow("本机 MCP", status.endpoint ?: "启动网关后获取", Icons.Outlined.Link, + status.endpoint?.let { { copy("连接地址", it) } }, trailing = { if (status.endpoint != null) Icon(Icons.Outlined.ContentCopy, null) }) } } + tunnels.filter { it.publicUrl.isNotBlank() }.forEach { tunnel -> + item(key = tunnel.id) { Group { ActionRow(tunnel.name, tunnel.publicUrl, Icons.Outlined.Public, + { open("tunnel:${tunnel.id}") }) } } + } item { SectionLabel("访问凭据") } - if (status.token == null) item { EmptyState(Icons.Outlined.Key, "启动后生成 Token", "每次重启网关,都会生成新的访问凭据。") } + if (status.token == null) item { EmptyState("启动网关后查看 Token") } else { item { Group(card = true) { - Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { Text("Bearer Token", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) SelectionContainer { Text(if (reveal) status.token else "•••• •••• •••• ••••", fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodyMedium) } Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { @@ -86,7 +106,12 @@ internal fun CredentialsScreen(status: GatewayStatus, copy: (String, String) -> } } } } - item { Note("将 Token 填入客户端的 Bearer 认证。持有凭据的客户端可以调用已启用的全部工具。") } + item { Note("Token 固定保存在本机,重启不会更换;仅主动重置后改变。将它填入客户端的 Bearer 认证,即可调用已启用的全部工具。") } + item { TextButton(onClick = { reset = true }, modifier = Modifier.fillMaxWidth()) { Text("重置访问凭据", color = MaterialTheme.colorScheme.error) } } } } + if (reset) AlertDialog(onDismissRequest = { reset = false }, title = { Text("重置访问凭据?") }, + text = { Text("所有客户端需要更新 Token。") }, + confirmButton = { TextButton(onClick = { GatewayRuntime.rotateAccessToken(); reset = false }) { Text("重置") } }, + dismissButton = { TextButton(onClick = { reset = false }) { Text("取消") } }) } diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/MBrainApp.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/MBrainApp.kt index 1a9bf0f..cb67ca8 100644 --- a/app/src/main/kotlin/com/powercess/mbrain/ui/MBrainApp.kt +++ b/app/src/main/kotlin/com/powercess/mbrain/ui/MBrainApp.kt @@ -19,6 +19,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.powercess.mbrain.data.* import com.powercess.mbrain.gateway.* +import com.powercess.mbrain.remote.* import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @@ -26,6 +27,8 @@ import kotlinx.coroutines.launch fun MBrainApp(start: () -> Unit, stop: () -> Unit) { val status by GatewayRuntime.status.collectAsState() val config by GatewayRuntime.config.collectAsState() + val remote by RemoteRuntime.config.collectAsState() + val tunnelStates by RemoteRuntime.status.collectAsState() val context = LocalContext.current val prefs = remember { context.getSharedPreferences("appearance", Context.MODE_PRIVATE) } var appearance by rememberSaveable { mutableStateOf(prefs.getString("theme", "system") ?: "system") } @@ -39,6 +42,9 @@ fun MBrainApp(start: () -> Unit, stop: () -> Unit) { var adding by rememberSaveable { mutableStateOf(false) } var themePicker by rememberSaveable { mutableStateOf(false) } var removal by rememberSaveable { mutableStateOf(null) } + var tunnelEditor by rememberSaveable { mutableStateOf(null) } + var serverEditor by rememberSaveable { mutableStateOf(null) } + var remoteRemoval by rememberSaveable { mutableStateOf(null) } val snackbar = remember { SnackbarHostState() } val scope = rememberCoroutineScope() val notify: (String) -> Unit = { scope.launch { snackbar.showSnackbar(it) } } @@ -52,18 +58,21 @@ fun MBrainApp(start: () -> Unit, stop: () -> Unit) { route == "main" -> if (tab == 0) "MBrain" else pages[tab] route.startsWith("cap:") -> capabilityName(route.substringAfter(':')) route.startsWith("connection:") -> config.connections.find { it.id == route.substringAfter(':') }?.name ?: "服务详情" - route.startsWith("tools:") -> "工具目录" + route == "tools:" -> "全部工具" + route.startsWith("tools:") -> "工具列表" route.startsWith("tool:") -> "工具详情" route == "credentials" -> "连接到 MBrain" route == "activity" -> "运行记录" route == "about" -> "关于 MBrain" + route == "remote" -> "内网穿透" + route.startsWith("tunnel:") -> remote.tunnels.find { it.id == route.substringAfter(':') }?.name ?: "隧道详情" else -> "使用说明" } - BackHandler(stack.size > 1) { back() } + BackHandler(stack.size > 1 && editor == null && tunnelEditor == null && serverEditor == null) { back() } LaunchedEffect(status.error) { status.error?.let { snackbar.showSnackbar(it) } } val holder = rememberSaveableStateHolder() MBrainTheme(dark) { - Scaffold( + if (editor == null) Scaffold( snackbarHost = { SnackbarHost(snackbar) }, topBar = { TopAppBar(title = { Text(title, maxLines = 1) }, navigationIcon = { if (route != "main") IconButton(onClick = back) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, "返回") } @@ -88,23 +97,35 @@ fun MBrainApp(start: () -> Unit, stop: () -> Unit) { key == "tab:0" -> HomeScreen(status, config, start, stop, open, { tab = it }) key == "tab:1" -> CapabilitiesScreen(status, config, open) key == "tab:2" -> ConnectionsScreen(status, config, open, { adding = true }, { tab = 0 }) - key == "tab:3" -> SettingsScreen(appearance, open, { themePicker = true }) + key == "tab:3" -> SettingsScreen(appearance, open, { themePicker = true }, remote.tunnels.size, tunnelStates.values.count { it.phase == TunnelPhase.CONNECTED }) key.startsWith("cap:") -> CapabilityScreen(key.substringAfter(':'), status, config, open, notify) key.startsWith("tools:") -> ToolsScreen(status, key.substringAfter(':'), open) key.startsWith("tool:") -> ToolScreen(status.tools.find { it.name == key.substringAfter(':') }, copy) key.startsWith("connection:") -> ConnectionScreen(config.connections.find { it.id == key.substringAfter(':') }, status, open, { editor = it }, { removal = it }) - key == "credentials" -> CredentialsScreen(status, copy) + key == "credentials" -> CredentialsScreen(status, copy, remote.tunnels, open) key == "activity" -> ActivityScreen(status) key == "about" -> AboutScreen() - key == "help" -> HelpScreen(copy) + key == "help" -> HelpScreen(status, copy) + key == "remote" -> RemoteScreen(remote, tunnelStates, { destination -> + if (destination == "servers") serverEditor = remote.server?.id ?: "new" else open(destination) + }, { + if (remote.server == null) serverEditor = "new" else tunnelEditor = "new" + }, notify) + key.startsWith("tunnel:") -> { + val id = key.substringAfter(':') + TunnelScreen(remote.tunnels.find { it.id == id }?.let(remote::resolve), tunnelStates[id] ?: TunnelStatus(), status, { destination -> + if (destination == "servers") serverEditor = remote.server?.id ?: "new" else open(destination) + }, + { tunnelEditor = it }, { remoteRemoval = "tunnel:$it" }, copy, notify) + } } } } } } if (adding) ModalBottomSheet(onDismissRequest = { adding = false }) { - Column(Modifier.padding(horizontal = 20.dp).padding(bottom = 24.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { + Column(Modifier.padding(horizontal = 16.dp).padding(bottom = 24.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { Text("添加 MCP 服务", style = MaterialTheme.typography.headlineSmall) Group { ActionRow("HTTP 服务", "连接已有的本机 MCP", Icons.Outlined.Link, { adding = false; editor = "new:http" }) @@ -131,12 +152,38 @@ fun MBrainApp(start: () -> Unit, stop: () -> Unit) { } } + tunnelEditor?.let { editorKey -> key("tunnel-editor:$editorKey") { + val initial = remember(editorKey) { if (editorKey == "new") TunnelConfig(serverId = remote.server?.id.orEmpty()) else remote.tunnels.find { it.id == editorKey } } + if (initial != null) TunnelEditor(initial, editorKey != "new", remote, { tunnelEditor = null }) { next -> + RemoteRuntime.saveTunnel(next); tunnelEditor = null + if (editorKey == "new") open("tunnel:${next.id}") + notify("已保存隧道") + } + } } + serverEditor?.let { editorKey -> key("server-editor:$editorKey") { + val initial = remember(editorKey) { if (editorKey == "new") TunnelServer() else remote.servers.find { it.id == editorKey } } + if (initial != null) ServerEditor(initial, editorKey != "new", remote, { serverEditor = null }, { remoteRemoval = "server:${initial.id}" }) { next -> + RemoteRuntime.saveServer(next); serverEditor = null; notify("已保存服务器") + } + } } + remoteRemoval?.let { target -> + AlertDialog(onDismissRequest = { remoteRemoval = null }, title = { Text(if (target.startsWith("tunnel:")) "删除此隧道?" else "删除此服务器?") }, + text = { Text(if (target.startsWith("tunnel:")) "此隧道会停止并移除配置。" else "删除已保存的服务器配置,之后可重新添加。") }, + confirmButton = { TextButton(onClick = { + runCatching { + if (target.startsWith("tunnel:")) { RemoteRuntime.removeTunnel(target.substringAfter(':')); back() } + else { RemoteRuntime.removeServer(target.substringAfter(':')); serverEditor = null } + }.onFailure { notify(it.message ?: "删除失败") } + remoteRemoval = null + }) { Text("删除") } }, dismissButton = { TextButton(onClick = { remoteRemoval = null }) { Text("取消") } }) + } if (themePicker) ModalBottomSheet(onDismissRequest = { themePicker = false }) { - Column(Modifier.padding(horizontal = 20.dp).padding(bottom = 24.dp)) { + Column(Modifier.padding(horizontal = 16.dp).padding(bottom = 24.dp)) { Text("外观", style = MaterialTheme.typography.headlineSmall) Spacer(Modifier.height(16.dp)) Group { - listOf("system" to "跟随系统", "light" to "浅色", "dark" to "深色").forEach { (value, label) -> + listOf("system" to "跟随系统", "light" to "浅色", "dark" to "深色").forEachIndexed { index, (value, label) -> + if (index > 0) GroupDivider() ActionRow(label, icon = if (value == "dark") Icons.Outlined.DarkMode else Icons.Outlined.LightMode, onClick = { appearance = value; prefs.edit().putString("theme", value).apply(); themePicker = false }, trailing = { if (appearance == value) Icon(Icons.Outlined.Check, "已选择", tint = MaterialTheme.colorScheme.primary) }) diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/OverviewScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/OverviewScreens.kt index 4637805..8b822e4 100644 --- a/app/src/main/kotlin/com/powercess/mbrain/ui/OverviewScreens.kt +++ b/app/src/main/kotlin/com/powercess/mbrain/ui/OverviewScreens.kt @@ -11,14 +11,11 @@ import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.res.vectorResource import com.powercess.mbrain.R import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.disabled import androidx.compose.ui.unit.dp import com.powercess.mbrain.data.* import com.powercess.mbrain.gateway.* @@ -29,35 +26,41 @@ internal fun HomeScreen(status: GatewayStatus, config: GatewayConfig, start: () var busy by remember { mutableStateOf(false) } LaunchedEffect(status.running, status.error) { busy = false } LaunchedEffect(busy) { if (busy) { kotlinx.coroutines.delay(5000); busy = false } } - Box(Modifier.fillMaxSize()) { - ScreenList { - item { - Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { - SummaryTile("可用工具", if (status.running) status.tools.size.toString() else "—", Icons.Outlined.Build, - Modifier.weight(1f)) { open("tools:") } - SummaryTile("MCP 服务", "${status.connections.values.count { it.state == "已连接" }} / ${config.connections.size}", - Icons.Outlined.Hub, Modifier.weight(1f), green = true) { tab(2) } - } - } - item { - Group { ActionRow("连接地址与凭据", icon = Icons.Outlined.Link, onClick = { open("credentials") }) } + ScreenList { + item { SectionLabel("能力概览", firstSection = true) } + item { + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + SummaryTile("可用工具", if (status.running) status.tools.size.toString() else "—", Icons.Outlined.Build, + Modifier.weight(1f)) { open("tools:") } + SummaryTile("MCP 服务", "${status.connections.values.count { it.state == "已连接" }} / ${config.connections.size}", + Icons.Outlined.Hub, Modifier.weight(1f), green = true) { tab(2) } } - status.error?.let { error -> item { Note(error, error = true) } } - // Leave room to scroll the final item clear of the floating action. - item { Spacer(Modifier.height(88.dp)) } } - FloatingActionButton( - onClick = { if (!busy) { busy = true; if (status.running) stop() else start() } }, - modifier = Modifier.align(Alignment.BottomEnd).padding(16.dp).size(64.dp).semantics { - contentDescription = if (busy) "正在处理网关" else if (status.running) "停止网关" else "启动网关" - if (busy) disabled() - }, - shape = RoundedCornerShape(20.dp), - containerColor = if (status.running) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.tertiaryContainer, - contentColor = if (status.running) MaterialTheme.colorScheme.onTertiary else MaterialTheme.colorScheme.onTertiaryContainer, - ) { - if (busy) CircularProgressIndicator(Modifier.size(26.dp), color = LocalContentColor.current, strokeWidth = 2.dp) - else Icon(if (status.running) Icons.Outlined.Stop else Icons.Outlined.PlayArrow, null, Modifier.size(32.dp)) + item { + Group(card = true) { + Row(Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text("服务网关", style = MaterialTheme.typography.titleMedium) + StatusPill(if (status.running) "已开启" else "已关闭", status.running) + } + FilledIconButton( + onClick = { busy = true; if (status.running) stop() else start() }, + enabled = !busy, + modifier = Modifier.size(64.dp).semantics { + contentDescription = if (busy) "正在处理网关" else if (status.running) "关闭网关" else "开启网关" + }, + shape = RoundedCornerShape(20.dp), + colors = IconButtonDefaults.filledIconButtonColors( + containerColor = if (status.running) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.tertiaryContainer, + contentColor = if (status.running) MaterialTheme.colorScheme.onTertiary else MaterialTheme.colorScheme.onTertiaryContainer, + ), + ) { + if (busy) CircularProgressIndicator(Modifier.size(26.dp), color = LocalContentColor.current, strokeWidth = 2.dp) + else Icon(if (status.running) Icons.Outlined.Stop else Icons.Outlined.PlayArrow, null, Modifier.size(32.dp)) + } + } + } } } } @@ -84,7 +87,7 @@ internal fun capabilityState(ready: Boolean, enabled: Boolean, activation: Activ @Composable internal fun CapabilitiesScreen(status: GatewayStatus, config: GatewayConfig, open: (String) -> Unit) { ScreenList { - item { SectionLabel("执行通道", "打开开关即可申请权限并启用") } + item { SectionLabel("手机能力", firstSection = true) } item { Group { ActionRow("Root", "超级用户执行权限", Icons.Outlined.AdminPanelSettings, { open("cap:root") }, @@ -94,16 +97,17 @@ internal fun CapabilitiesScreen(status: GatewayStatus, config: GatewayConfig, op trailing = { StatusPill(capabilityState(status.shizukuReady, config.shizukuEnabled, status.shizukuActivation), status.shizukuReady && config.shizukuEnabled) }) } } - item { SectionLabel("基础能力") } + item { SectionLabel("插件") } item { Group { - ActionRow("应用管理", "查看应用、详情与启动", Icons.Outlined.Apps, { open("cap:apps") }) + ActionRow("应用管理", if (config.appsEnabled) "已启用" else "未启用", + Icons.Outlined.Widgets, { open("cap:apps") }) GroupDivider() - ActionRow("设备信息", "电量、存储与网络", Icons.Outlined.PhoneAndroid, { open("cap:device") }) + ActionRow("设备信息", "已启用", Icons.Outlined.PhoneAndroid, { open("cap:device") }) } } item { SectionLabel("工具") } - item { Group { ActionRow("浏览工具目录", if (status.running) "${status.tools.size} 个工具可供调用" else "启动网关后查看", Icons.Outlined.Search, { open("tools:") }) } } + item { Group { ActionRow("全部工具", if (status.running) "共 ${status.tools.size} 个工具" else "启动网关后查看", Icons.Outlined.Search, { open("tools:") }) } } } } @@ -138,12 +142,14 @@ internal fun CapabilityScreen(id: String, status: GatewayStatus, config: Gateway } @Composable -internal fun SettingsScreen(appearance: String, open: (String) -> Unit, theme: () -> Unit) { +internal fun SettingsScreen(appearance: String, open: (String) -> Unit, theme: () -> Unit, tunnelCount: Int, connectedCount: Int) { ScreenList { - item { SectionLabel("连接") } + item { SectionLabel("连接", firstSection = true) } item { Group { ActionRow("地址与凭据", "供 Agent 连接本机网关", Icons.Outlined.Key, { open("credentials") }) GroupDivider() + ActionRow("内网穿透", "服务器与 TCP 隧道", Icons.Outlined.Public, { open("remote") }) + GroupDivider() ActionRow("使用说明", "电脑连接、运行方式与限制", Icons.Outlined.HelpOutline, { open("help") }) } } item { SectionLabel("偏好") } @@ -159,13 +165,13 @@ internal fun SettingsScreen(appearance: String, open: (String) -> Unit, theme: ( @Composable internal fun ActivityScreen(status: GatewayStatus) { - ScreenList { - if (status.events.isEmpty()) item { EmptyState(Icons.Outlined.History, "还没有运行记录", "启动网关或连接服务后,活动会显示在这里。") } + ScreenList(groupedRows = true) { + if (status.events.isEmpty()) item { EmptyState("暂无运行记录") } else { - item { SectionLabel("最近 ${status.events.size} 条", "最新在前 · 仅保留本次进程内的记录") } - itemsIndexed(status.events) { _, event -> Group { + item { ListSection("最近 ${status.events.size} 条", "仅本次运行", firstSection = true) } + groupedItems(status.events.withIndex().toList(), key = { it.index }) { (_, event) -> ActionRow(event, icon = if (event.contains("失败")) Icons.Outlined.ErrorOutline else Icons.Outlined.CheckCircle) - } } + } } } } @@ -194,11 +200,12 @@ internal fun AboutScreen() { } @Composable -internal fun HelpScreen(copy: (String, String) -> Unit) { +internal fun HelpScreen(status: GatewayStatus, copy: (String, String) -> Unit) { + val command = status.port?.let { "adb forward tcp:$it tcp:$it" } ScreenList { item { SectionLabel("从电脑连接") } - item { Group { ActionRow("转发网关端口", "adb forward tcp:8765 tcp:8765", Icons.Outlined.Computer, - { copy("ADB 命令", "adb forward tcp:8765 tcp:8765") }, trailing = { Icon(Icons.Outlined.ContentCopy, null) }) } } + item { Group { ActionRow("转发网关端口", command ?: "启动网关后获取", Icons.Outlined.Computer, + command?.let { { copy("ADB 命令", it) } }, trailing = { if (command != null) Icon(Icons.Outlined.ContentCopy, null) }) } } item { Note("完成端口转发后,使用连接页中的地址和 Bearer Token 配置客户端。") } item { SectionLabel("运行方式") } item { Note("网关仅监听本机地址。停止网关会断开 MCP 并关闭直接托管的进程;应用不会在开机后自动启动。") } diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/RemoteScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/RemoteScreens.kt new file mode 100644 index 0000000..20a0f04 --- /dev/null +++ b/app/src/main/kotlin/com/powercess/mbrain/ui/RemoteScreens.kt @@ -0,0 +1,189 @@ +package com.powercess.mbrain.ui + +import android.Manifest +import android.os.Build +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.input.* +import androidx.compose.ui.unit.dp +import com.powercess.mbrain.gateway.GatewayStatus +import com.powercess.mbrain.gateway.GatewayRuntime +import com.powercess.mbrain.remote.* +import kotlinx.coroutines.launch +import kotlinx.serialization.json.* + +@Composable +internal fun RemoteScreen(config: RemoteConfig, states: Map, open: (String) -> Unit, add: () -> Unit, notify: (String) -> Unit) { + val failure by RemoteRuntime.error.collectAsState() + ScreenList(groupedRows = true) { + failure?.let { item { Note(it, error = true) } } + item { Group { ActionRow("配置服务器", config.server?.let { "${it.name} · ${it.host}:${it.port}" } ?: "未配置", Icons.Outlined.Dns, { open("servers") }) } } + if (config.tunnels.isEmpty()) item { EmptyState("暂无隧道", + description = if (config.servers.isEmpty()) "先配置服务器,再添加需要转发的服务" else null, + action = if (config.servers.isEmpty()) "配置服务器" else "添加隧道", + onAction = if (config.servers.isEmpty()) ({ open("servers") }) else add) } + else { + item { ListSection("我的隧道", "${states.values.count { it.phase == TunnelPhase.CONNECTED }} / ${config.tunnels.size} 已注册") } + groupedItems(config.tunnels, key = { it.id }) { tunnel -> + ActionRow(tunnel.name, "${tunnel.type} · ${(states[tunnel.id] ?: TunnelStatus()).phase.label}", Icons.Outlined.Public, + { open("tunnel:${tunnel.id}") }, trailing = { TunnelSwitch(tunnel, notify) }) + } + item { SecondaryAction("添加隧道", Icons.Outlined.Add, onClick = add) } + } + } +} + +@Composable +private fun TunnelSwitch(tunnel: TunnelConfig, notify: (String) -> Unit) { + val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { } + Switch(tunnel.enabled, onCheckedChange = { enabled -> + if (enabled && Build.VERSION.SDK_INT >= 33) permission.launch(Manifest.permission.POST_NOTIFICATIONS) + runCatching { RemoteRuntime.enableTunnel(tunnel.id, enabled) }.onFailure { notify(it.message ?: "启动失败") } + }, modifier = Modifier.semantics { contentDescription = "启用${tunnel.name}" }) +} + +@Composable +internal fun TunnelScreen(tunnel: TunnelConfig?, state: TunnelStatus, gateway: GatewayStatus, open: (String) -> Unit, + edit: (String) -> Unit, remove: (String) -> Unit, copy: (String, String) -> Unit, notify: (String) -> Unit) { + if (tunnel == null) return + var more by remember { mutableStateOf(false) } + var diagnostics by rememberSaveable(tunnel.id) { mutableStateOf(false) } + val target = if (tunnel.target == TunnelTarget.MCP) "MCP 网关 · 127.0.0.1:${gateway.port ?: GatewayRuntime.PORT}" else "${tunnel.localHost}:${tunnel.localPort}" + ScreenList { + item { Group { ActionRow("启用隧道", state.phase.label, Icons.Outlined.Public, + trailing = { TunnelSwitch(tunnel, notify) }) } } + state.error?.let { item { Note(it, error = true) } } + if (tunnel.accessUrl.isNotBlank()) item { Group { + ActionRow("访问地址", tunnel.accessUrl, Icons.Outlined.Link, { copy("访问地址", tunnel.accessUrl) }) + if (tunnel.target == TunnelTarget.MCP && gateway.running && gateway.token != null) { + GroupDivider() + ActionRow("复制客户端配置", icon = Icons.Outlined.ContentCopy, onClick = { + val payload = buildJsonObject { putJsonObject("mcpServers") { putJsonObject(tunnel.name) { + put("url", tunnel.accessUrl) + putJsonObject("headers") { put("Authorization", "Bearer ${gateway.token}") } + } } } + copy("客户端配置", payload.toString()) + }) + } + } } + item { Group { ActionRow("编辑隧道", if (tunnel.enabled) "关闭后可编辑" else "$target · 公网访问端口 ${tunnel.remotePort}", + Icons.Outlined.Edit, if (!tunnel.enabled) ({ edit(tunnel.id) }) else null) } } + item { Box { + TextButton(onClick = { more = true }) { Text("更多"); Icon(Icons.Outlined.ExpandMore, null) } + DropdownMenu(expanded = more, onDismissRequest = { more = false }) { + DropdownMenuItem(text = { Text(if (diagnostics) "收起连接详情" else "连接详情") }, + onClick = { diagnostics = !diagnostics; more = false }) + if (tunnel.target == TunnelTarget.MCP) DropdownMenuItem(text = { Text("访问凭据") }, + onClick = { more = false; open("credentials") }) + if (tunnel.enabled && state.phase != TunnelPhase.WAITING) DropdownMenuItem(text = { Text("重新连接") }, + onClick = { more = false; RemoteRuntime.retry(tunnel.id) }) + DropdownMenuItem(text = { Text("删除隧道", color = MaterialTheme.colorScheme.error) }, + onClick = { more = false; remove(tunnel.id) }) + } + } } + if (diagnostics) { + item { Group { + ActionRow("服务器", "${tunnel.server}:${tunnel.serverPort}", Icons.Outlined.Dns) + GroupDivider(); ActionRow("服务器连接", if (state.serverConnected) "已连接" else "未连接", Icons.Outlined.Link) + GroupDivider(); ActionRow("本地服务", state.localHealth.label, Icons.Outlined.PhoneAndroid) + } } + if (state.events.isNotEmpty()) { + item { SectionLabel("最近运行记录") } + item { Group { state.events.forEachIndexed { index, event -> + if (index > 0) GroupDivider() + ActionRow(event, icon = Icons.Outlined.History) + } } } + } + } + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun TunnelEditor(initial: TunnelConfig, existing: Boolean, config: RemoteConfig, dismiss: () -> Unit, save: (TunnelConfig) -> Unit) { + val json = remember { Json { encodeDefaults = true } } + var draft by rememberSaveable { mutableStateOf(json.encodeToString(TunnelConfig.serializer(), initial)) } + val value = remember(draft) { json.decodeFromString(TunnelConfig.serializer(), draft) } + fun update(next: TunnelConfig) { draft = json.encodeToString(TunnelConfig.serializer(), next) } + var localPort by rememberSaveable { mutableStateOf(initial.localPort.toString()) } + var remotePort by rememberSaveable { mutableStateOf(initial.remotePort.takeIf { it > 0 }?.toString().orEmpty()) } + var error by rememberSaveable { mutableStateOf(null) } + var discard by rememberSaveable { mutableStateOf(false) } + val dirty = value != initial.copy(enabled = false) || localPort != initial.localPort.toString() || + remotePort != initial.remotePort.takeIf { it > 0 }?.toString().orEmpty() + val close = { if (dirty) discard = true else dismiss() } + val list = rememberLazyListState() + val scope = rememberCoroutineScope() + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + BackHandler { close() } + Scaffold(modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding(), contentWindowInsets = WindowInsets(0, 0, 0, 0), + containerColor = MaterialTheme.colorScheme.background, + topBar = { TopAppBar(title = { Text(if (existing) "编辑隧道" else "添加隧道") }, + navigationIcon = { IconButton(onClick = close) { Icon(Icons.Outlined.Close, "关闭编辑") } }, colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.background), windowInsets = WindowInsets(0, 0, 0, 0)) }, + bottomBar = { EditorSaveBar("保存隧道") { + try { + val next = value.asBasicTcp().referenceServer(config.server?.id.orEmpty()).copy(name = value.name.trim(), + localHost = if (value.target == TunnelTarget.MCP) "127.0.0.1" else value.localHost.trim(), + localPort = if (value.target == TunnelTarget.MCP) GatewayRuntime.PORT else localPort.toIntOrNull() ?: 0, remotePort = remotePort.toIntOrNull() ?: 0, + publicUrl = value.publicUrl.trim()) + require(next.serverId.isNotEmpty()) { "请先配置服务器" } + config.copy(tunnels = config.tunnels.filterNot { it.id == next.id } + next).validate() + save(next.referenceServer(next.serverId)) + } catch (e: Exception) { error = e.message ?: "保存失败"; scope.launch { list.animateScrollToItem(0) } } + } }) { padding -> + Box(Modifier.padding(padding).consumeWindowInsets(padding)) { + ScreenList(state = list) { + error?.let { item(key = "error") { Note(it, error = true) } } + if (!initial.supportsBasicTcp() || (initial.serverId.isNotEmpty() && initial.serverId != config.server?.id)) + item(key = "legacy") { Note("保存后将使用当前服务器和基础 TCP 转发,请确认公网访问端口。") } + item(key = "name") { TunnelField("名称", value.name, { update(value.copy(name = it)); error = null }) } + item(key = "target-label") { SectionLabel("本地目标") } + item(key = "target") { ChoiceRow(TunnelTarget.entries, value.target, { if (it == TunnelTarget.MCP) "本应用 MCP" else "自定义服务" }) { + update(value.copy(target = it)) + } } + if (value.target == TunnelTarget.MCP) { + item(key = "mcp-endpoint") { Note("转发本机 MCP 网关:127.0.0.1:${GatewayRuntime.PORT}") } + } + if (value.target == TunnelTarget.CUSTOM) { + item(key = "local-host") { TunnelField("本地服务地址", value.localHost, { update(value.copy(localHost = it)) }, KeyboardType.Uri) } + item(key = "local-port") { TunnelField("本地服务端口", localPort, { localPort = it }, KeyboardType.Number) } + } + item(key = "remote-port") { TunnelField("公网访问端口", remotePort, { remotePort = it }, KeyboardType.Number) } + item(key = "public-url") { TunnelField("自定义公网地址(可选)", value.publicUrl, { update(value.copy(publicUrl = it)) }, KeyboardType.Uri, + if (value.target == TunnelTarget.MCP) value.copy(server = config.server?.host.orEmpty(), remotePort = remotePort.toIntOrNull() ?: 0, publicUrl = "").accessUrl else "http://phone.example.com:18080") } + + } + } + } + if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text("放弃未保存的修改?") }, + confirmButton = { TextButton(onClick = dismiss) { Text("放弃修改") } }, dismissButton = { TextButton(onClick = { discard = false }) { Text("继续编辑") } }) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun ChoiceRow(values: List, selected: T, label: (T) -> String, change: (T) -> Unit) { + SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) { values.forEachIndexed { index, option -> + SegmentedButton(selected == option, { change(option) }, SegmentedButtonDefaults.itemShape(index, values.size)) { Text(label(option)) } + } } +} + +@Composable +internal fun TunnelField(label: String, value: String, change: (String) -> Unit, keyboard: KeyboardType = KeyboardType.Text, placeholder: String = "") { + OutlinedTextField(value, change, Modifier.fillMaxWidth(), label = { Text(label) }, singleLine = true, + shape = MaterialTheme.shapes.medium, keyboardOptions = KeyboardOptions(keyboardType = keyboard), placeholder = { Text(placeholder) }) +} diff --git a/app/src/main/kotlin/com/powercess/mbrain/ui/ServerScreens.kt b/app/src/main/kotlin/com/powercess/mbrain/ui/ServerScreens.kt new file mode 100644 index 0000000..6349306 --- /dev/null +++ b/app/src/main/kotlin/com/powercess/mbrain/ui/ServerScreens.kt @@ -0,0 +1,69 @@ +package com.powercess.mbrain.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.* +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.* +import com.powercess.mbrain.remote.* +import kotlinx.coroutines.launch +import kotlinx.serialization.json.Json + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun ServerEditor(initial: TunnelServer, existing: Boolean, config: RemoteConfig, dismiss: () -> Unit, remove: () -> Unit, save: (TunnelServer) -> Unit) { + val json = remember { Json { encodeDefaults = true } } + var draft by rememberSaveable { mutableStateOf(json.encodeToString(TunnelServer.serializer(), initial)) } + val value = remember(draft) { json.decodeFromString(TunnelServer.serializer(), draft) } + fun update(next: TunnelServer) { draft = json.encodeToString(TunnelServer.serializer(), next) } + var port by rememberSaveable { mutableStateOf(initial.port.toString()) } + var reveal by remember { mutableStateOf(false) } + var error by rememberSaveable { mutableStateOf(null) } + var discard by rememberSaveable { mutableStateOf(false) } + val close = { if (value != initial || port != initial.port.toString()) discard = true else dismiss() } + val list = rememberLazyListState() + val scope = rememberCoroutineScope() + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + BackHandler { close() } + Scaffold(modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding(), contentWindowInsets = WindowInsets(0, 0, 0, 0), + containerColor = MaterialTheme.colorScheme.background, + topBar = { TopAppBar(title = { Text("配置服务器") }, + navigationIcon = { IconButton(onClick = close) { Icon(Icons.Outlined.Close, "关闭编辑") } }, colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.background), windowInsets = WindowInsets(0, 0, 0, 0)) }, + bottomBar = { EditorSaveBar("保存服务器") { + try { + val next = value.copy(name = value.name.trim(), host = value.host.trim(), port = port.toIntOrNull() ?: 0, + tlsServerName = "", tlsCaId = "", tlsClientCertificateId = "") + config.saveServer(next); save(next) + } catch (e: Exception) { error = e.message ?: "保存失败"; scope.launch { list.animateScrollToItem(0) } } + } }) { padding -> + Box(Modifier.padding(padding).consumeWindowInsets(padding)) { + ScreenList(state = list) { + error?.let { item { Note(it, error = true) } } + item { TunnelField("服务器名称", value.name, { update(value.copy(name = it)) }) } + item { TunnelField("服务器地址", value.host, { update(value.copy(host = it)) }, KeyboardType.Uri, "frp.example.com") } + item { TunnelField("服务器端口", port, { port = it }, KeyboardType.Number) } + item { OutlinedTextField(value.token, { update(value.copy(token = it)) }, Modifier.fillMaxWidth(), label = { Text("服务器 Token(可选)") }, + singleLine = true, shape = MaterialTheme.shapes.medium, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), + visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(), + trailingIcon = { IconButton(onClick = { reveal = !reveal }) { Icon(if (reveal) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility, "显示或隐藏 Token") } }) } + if (existing) item { TextButton(onClick = { + runCatching { config.removeServer(initial.id); remove() }.onFailure { + error = it.message ?: "无法删除服务器"; scope.launch { list.animateScrollToItem(0) } + } + }, modifier = Modifier.fillMaxWidth()) { + Text("删除服务器", color = MaterialTheme.colorScheme.error) + } } + + } + } + } + if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text("放弃未保存的修改?") }, + confirmButton = { TextButton(onClick = dismiss) { Text("放弃修改") } }, dismissButton = { TextButton(onClick = { discard = false }) { Text("继续编辑") } }) + } +} diff --git a/app/src/test/kotlin/com/powercess/mbrain/mcp/McpPeerTest.kt b/app/src/test/kotlin/com/powercess/mbrain/mcp/McpPeerTest.kt index a48f49a..1f407d8 100644 --- a/app/src/test/kotlin/com/powercess/mbrain/mcp/McpPeerTest.kt +++ b/app/src/test/kotlin/com/powercess/mbrain/mcp/McpPeerTest.kt @@ -40,7 +40,7 @@ class McpPeerTest { @Test fun `HTTP configuration rejects external and self endpoints`() { listOf("http://example.com/mcp", "http://127.0.0.1:8765/mcp", "file:///tmp/a", "http://user@localhost:8787/mcp").forEach { - assertThrows(IllegalArgumentException::class.java) { McpConnectionConfig(name = "Test server", endpoint = it).validate() } + assertThrows(IllegalArgumentException::class.java) { McpConnectionConfig(name = "Test server", endpoint = it).validate(8765) } } McpConnectionConfig(name = "Test server", endpoint = "http://localhost:9000/mcp").validate() assertThrows(IllegalArgumentException::class.java) { McpConnectionConfig().validate() } diff --git a/app/src/test/kotlin/com/powercess/mbrain/remote/FrpcControllerTest.kt b/app/src/test/kotlin/com/powercess/mbrain/remote/FrpcControllerTest.kt new file mode 100644 index 0000000..241daa7 --- /dev/null +++ b/app/src/test/kotlin/com/powercess/mbrain/remote/FrpcControllerTest.kt @@ -0,0 +1,130 @@ +package com.powercess.mbrain.remote + +import org.junit.Assert.* +import org.junit.Test +import kotlinx.coroutines.runBlocking +import java.io.* +import java.nio.file.Files +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.ConcurrentHashMap + +class FrpcControllerTest { + private class FakeProcess : Process() { + private val output = PipedOutputStream() + private val input = PipedInputStream(output) + @Volatile private var alive = true + fun line(text: String) { output.write((text + "\n").toByteArray()); output.flush() } + override fun getInputStream(): InputStream = input + override fun getErrorStream(): InputStream = ByteArrayInputStream(byteArrayOf()) + override fun getOutputStream(): OutputStream = ByteArrayOutputStream() + override fun waitFor(): Int = 0 + override fun exitValue(): Int = if (alive) throw IllegalThreadStateException() else 0 + override fun isAlive() = alive + override fun destroy() { alive = false; output.close() } + override fun destroyForcibly(): Process { destroy(); return this } + } + private fun await(check: () -> Boolean) { + val deadline = System.nanoTime() + 5_000_000_000 + while (!check() && System.nanoTime() < deadline) Thread.sleep(10) + assertTrue("Condition timed out", check()) + } + + @Test fun `simultaneous tunnels stop independently and follow changed local port`() { + val directory = Files.createTempDirectory("frpc-test").toFile() + val binary = File(System.getProperty("java.home"), "bin/" + if (System.getProperty("os.name").startsWith("Windows")) "java.exe" else "java") + val processes = CopyOnWriteArrayList() + val configs = CopyOnWriteArrayList() + val states = ConcurrentHashMap() + val controller = FrpcController(binary, directory, { id, state -> states[id] = state }, { _, file -> + configs.add(file.readText()) + FakeProcess().also { processes.add(it) } + }) + val first = TunnelConfig(name = "one", server = "frp.example.com", remotePort = 18081, enabled = true) + val second = TunnelConfig(name = "two", server = "frp.example.com", remotePort = 18082, enabled = true) + try { + controller.reconcile(listOf(first, second), null) + assertTrue(processes.isEmpty()) + controller.reconcile(listOf(first, second), 41234) + await { processes.size == 2 } + processes.forEach { it.line("[proxy] start proxy success") } + await { states.values.count { it.phase == TunnelPhase.CONNECTED } == 2 } + controller.reconcile(listOf(first.copy(enabled = false), second), 41234) + await { processes.count { it.isAlive } == 1 } + assertEquals(TunnelPhase.OFF, states[first.id]!!.phase) + controller.reconcile(listOf(second), 41235) + await { processes.size == 3 } + assertTrue(configs.last().contains("\"localPort\":41235")) + assertFalse(processes[0].isAlive) + assertFalse(processes[1].isAlive) + processes.last().destroy() + await { processes.size == 4 } + assertTrue(processes.last().isAlive) + controller.reconcile(listOf(second), null) + await { processes.none { it.isAlive } && directory.listFiles().orEmpty().isEmpty() } + Thread.sleep(1100) + assertEquals(4, processes.size) + } finally { controller.close(); runBlocking { controller.awaitTermination() }; directory.deleteRecursively() } + } + + @Test fun `custom service survives MCP shutdown and endpoint edits restart only its process`() { + val directory = Files.createTempDirectory("frpc-independent-test").toFile() + val binary = File(System.getProperty("java.home"), "bin/" + if (System.getProperty("os.name").startsWith("Windows")) "java.exe" else "java") + val processes = CopyOnWriteArrayList() + val configs = CopyOnWriteArrayList() + val controller = FrpcController(binary, directory, { _, _ -> }, { _, file -> + configs.add(file.readText()); FakeProcess().also { processes.add(it) } + }) + val mcp = TunnelConfig(name = "mcp", server = "frp.example.com", remotePort = 18081, enabled = true) + val custom = TunnelConfig(name = "custom", server = "frp.example.com", remotePort = 18082, + target = TunnelTarget.CUSTOM, localPort = 8787, enabled = true) + try { + controller.reconcile(listOf(custom, mcp), null) + await { processes.size == 1 } + val customProcess = processes.single() + assertFalse(configs.single().contains("plugin")) + controller.reconcile(listOf(custom, mcp), 8765) + await { processes.size == 2 } + val mcpProcess = processes.last() + val replacement = custom.copy(localPort = 8788) + controller.reconcile(listOf(replacement, mcp), 8765) + await { processes.size == 3 } + assertFalse(customProcess.isAlive) + assertTrue(mcpProcess.isAlive) + val replacementProcess = processes.last() + controller.reconcile(listOf(replacement, mcp), null) + await { !mcpProcess.isAlive } + assertTrue(replacementProcess.isAlive) + controller.close() + await { processes.none { it.isAlive } && directory.listFiles().orEmpty().isEmpty() } + } finally { controller.close(); runBlocking { controller.awaitTermination() }; directory.deleteRecursively() } + } + @Test fun `repeated retries retain one error until connection recovers`() { + val directory = Files.createTempDirectory("frpc-retry-test").toFile() + val binary = File(System.getProperty("java.home"), "bin/" + if (System.getProperty("os.name").startsWith("Windows")) "java.exe" else "java") + val processes = CopyOnWriteArrayList() + val states = ConcurrentHashMap() + val controller = FrpcController(binary, directory, { id, state -> states[id] = state }, { _, _ -> + FakeProcess().also { processes.add(it) } + }) + val tunnel = TunnelConfig(name = "retry", server = "frp.example.com", remotePort = 18080, enabled = true) + try { + controller.reconcile(listOf(tunnel), 8765) + await { processes.size == 1 } + val process = processes.single() + repeat(5) { + process.line("try to connect to server") + process.line("connect to server error: EOF") + } + process.line("try to connect to server") + process.line("login to server success") + await { states[tunnel.id]?.serverConnected == true } + val failed = states.getValue(tunnel.id) + assertEquals("无法连接服务器,正在重试", failed.error) + assertEquals(1, failed.events.count { it == failed.error }) + process.line("start proxy success") + await { states[tunnel.id]?.phase == TunnelPhase.CONNECTED } + assertNull(states.getValue(tunnel.id).error) + } finally { controller.close(); runBlocking { controller.awaitTermination() }; directory.deleteRecursively() } + } + +} diff --git a/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelConfigTest.kt b/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelConfigTest.kt new file mode 100644 index 0000000..c1c9d7b --- /dev/null +++ b/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelConfigTest.kt @@ -0,0 +1,75 @@ +package com.powercess.mbrain.remote + +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.* +import org.junit.Assert.* +import org.junit.Test + +class TunnelConfigTest { + private val base = TunnelConfig(name = "phone", server = "frp.example.com", remotePort = 18080) + + @Test fun `MCP forwards gateway port and advertises public port independently of server port`() { + val tunnel = base.copy(serverPort = 5080, localHost = "old.example.com", localPort = 9999) + val endpoint = tunnel.endpoint(8765)!! + assertEquals("127.0.0.1" to 8765, endpoint) + val config = Json.parseToJsonElement(tunnel.frpcConfig(endpoint)).jsonObject + assertEquals(5080, config["serverPort"]!!.jsonPrimitive.int) + val proxy = config["proxies"]!!.jsonArray.single().jsonObject + assertEquals(8765, proxy["localPort"]!!.jsonPrimitive.int) + assertEquals(18080, proxy["remotePort"]!!.jsonPrimitive.int) + assertEquals("http://frp.example.com:18080/mcp", tunnel.accessUrl) + assertEquals("http://frp.example.com:19000/mcp", tunnel.copy(remotePort = 19000).accessUrl) + assertEquals("http://[::1]:18080/mcp", tunnel.copy(server = "::1").accessUrl) + assertEquals("http://external.example.com:80/mcp", tunnel.copy(publicUrl = "http://external.example.com:80/mcp").accessUrl) + assertNull(tunnel.endpoint(null)) + } + + @Test fun `TCP forwards the local endpoint with transport TLS and without HTTPS plugins`() { + val tunnel = base.copy(target = TunnelTarget.CUSTOM, localPort = 8080) + assertEquals("127.0.0.1" to 8080, tunnel.endpoint(null)) + assertNull(base.endpoint(null)) + val json = Json.parseToJsonElement(tunnel.frpcConfig("127.0.0.1" to 8787)).jsonObject + assertTrue(json["transport"]!!.jsonObject["tls"]!!.jsonObject["enable"]!!.jsonPrimitive.boolean) + val proxy = json["proxies"]!!.jsonArray.single().jsonObject + assertEquals("tcp", proxy["type"]!!.jsonPrimitive.content) + assertEquals(8787, proxy["localPort"]!!.jsonPrimitive.int) + assertEquals(18080, proxy["remotePort"]!!.jsonPrimitive.int) + assertFalse(proxy.containsKey("plugin")) + assertFalse(proxy.containsKey("customDomains")) + } + + @Test fun `legacy HTTPS plugins and TLS never silently become plain TCP`() { + val id = "c".repeat(32) + listOf(base.copy(type = ProxyType.HTTPS, target = TunnelTarget.CUSTOM, domains = listOf("phone.example.com")), + base.copy(plugin = TunnelPlugin.HTTPS2HTTP, certificateId = id), + base.copy(plugin = TunnelPlugin.TLS2RAW, certificateId = id), base.copy(tlsCaId = id), + base.copy(tlsClientCertificateId = id), base.copy(tlsServerName = "frps.example.com"), + base.copy(publicUrl = "https://phone.example.com/mcp")).forEach { legacy -> + assertThrows(IllegalArgumentException::class.java) { legacy.frpcConfig("127.0.0.1" to 8765) } + legacy.asBasicTcp().copy(remotePort = 18080).frpcConfig("127.0.0.1" to 8765) + } + } + + @Test fun `invalid and conflicting TCP configurations fail before launching`() { + listOf(base.copy(server = "https://frp.example.com"), base.copy(serverPort = 0), base.copy(localPort = 65536), + base.copy(remotePort = 0), base.copy(token = "{{ .Envs.SECRET }}"), + base.copy(publicUrl = "http://phone.example.com/wrong")).forEach { bad -> + assertThrows(IllegalArgumentException::class.java) { bad.frpcConfig("127.0.0.1" to 8765) } + } + assertThrows(IllegalArgumentException::class.java) { base.validate(listOf(base.copy(id = "b".repeat(32)))) } + } + + @Test fun `legacy and saved configurations never restart automatically`() { + val json = Json { ignoreUnknownKeys = true } + val legacy = """[{"id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","name":"legacy","server":"frp.example.com","remotePort":18080,"enabled":true}]""" + assertFalse(json.decodeFromString>(legacy).single().enabled) + val text = json.encodeToString(RemoteConfig(tunnels = listOf(base.copy(enabled = true)))) + assertFalse(json.decodeFromString(text).tunnels.single().enabled) + } + + @Test fun `untrusted log messages cannot leak into visible errors`() { + assertNull(classifyFrpcLine("arbitrary secret value")) + assertEquals("服务器认证失败", classifyFrpcLine("token [private] doesn't match")!!.second) + assertEquals(TunnelPhase.CONNECTED, classifyFrpcLine("start proxy success")!!.first) + } +} diff --git a/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelServerTest.kt b/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelServerTest.kt new file mode 100644 index 0000000..41a7bdb --- /dev/null +++ b/app/src/test/kotlin/com/powercess/mbrain/remote/TunnelServerTest.kt @@ -0,0 +1,107 @@ +package com.powercess.mbrain.remote + +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Assert.* +import org.junit.Test + +class TunnelServerTest { + private val first = TunnelConfig(name = "one", server = "frp.example.com", remotePort = 18080, token = "test-token") + private val second = first.copy(id = "b".repeat(32), name = "two", remotePort = 18081) + + @Test fun `migration shares identical connections and preserves frpc output`() { + val original = RemoteConfig(tunnels = listOf(first, second)) + val migrated = original.migrateServers() + migrated.validate() + assertEquals(1, migrated.servers.size) + assertEquals(migrated.tunnels[0].serverId, migrated.tunnels[1].serverId) + assertTrue(migrated.tunnels.all { it.token.isEmpty() && it.server.isEmpty() }) + original.tunnels.zip(migrated.tunnels).forEach { (before, after) -> + assertEquals(before.frpcConfig("127.0.0.1" to 8765), migrated.resolve(after).frpcConfig("127.0.0.1" to 8765)) + } + assertEquals(migrated, migrated.migrateServers()) + } + + @Test fun `migration does not merge different credentials ports or TLS settings`() { + listOf(second.copy(token = "other"), second.copy(serverPort = 7001), second.copy(tlsServerName = "tls.example.com"), + second.copy(tlsCaId = "c".repeat(32)), second.copy(tlsClientCertificateId = "d".repeat(32))).forEach { different -> + val migrated = RemoteConfig(tunnels = listOf(first, different)).migrateServers() + assertEquals(2, migrated.servers.size) + val restored = migrated.resolve(migrated.tunnels[1]) + assertEquals(different.server, restored.server) + assertEquals(different.token, restored.token) + assertEquals(different.tlsCaId, restored.tlsCaId) + assertEquals(different.tlsClientCertificateId, restored.tlsClientCertificateId) + + } + } + + @Test fun `legacy migration is stable and accepts long valid hostnames`() { + val legacy = """[{"id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","name":"legacy","server":"frp.example.com","remotePort":18080,"enabled":true}]""" + val json = Json { ignoreUnknownKeys = true } + val config = RemoteConfig(tunnels = json.decodeFromString>(legacy)) + assertEquals(config.migrateServers(), config.migrateServers()) + assertFalse(config.migrateServers().tunnels.single().enabled) + val longHost = "a".repeat(50) + "." + "b".repeat(50) + ".example.com" + RemoteConfig(tunnels = listOf(first.copy(server = longHost))).migrateServers().validate() + } + + @Test fun `single server rejects extra servers and retired TLS settings`() { + val server = TunnelServer(name = "server", host = "frp.example.com") + val config = RemoteConfig().saveServer(server) + assertThrows(IllegalArgumentException::class.java) { config.saveServer(server.copy(id = "c".repeat(32))) } + listOf(server.copy(host = "https://frp.example.com"), server.copy(port = 0), server.copy(token = "{{ .Envs.SECRET }}"), + server.copy(tlsCaId = "c".repeat(32))).forEach { bad -> + assertThrows(IllegalArgumentException::class.java) { config.saveServer(bad) } + } + } + + @Test fun `server edits affect every reference and serialized reload keeps tunnels off`() { + val migrated = RemoteConfig(tunnels = listOf(first, second)).migrateServers() + val updated = migrated.saveServer(migrated.servers.single().copy(host = "new.example.com", token = "new-token")) + updated.tunnels.forEach { tunnel -> + val json = Json.parseToJsonElement(updated.resolve(tunnel).frpcConfig("127.0.0.1" to 8765)).jsonObject + assertEquals("new.example.com", json["serverAddr"]!!.jsonPrimitive.content) + assertEquals("new-token", json["auth"]!!.jsonObject["token"]!!.jsonPrimitive.content) + } + val running = updated.copy(tunnels = updated.tunnels.map { it.copy(enabled = true) }) + val restored = Json.decodeFromString(Json.encodeToString(running)) + restored.validate() + assertEquals(updated, restored) + } + + @Test fun `referenced and active servers are protected`() { + val config = RemoteConfig(tunnels = listOf(first)).migrateServers() + val server = config.servers.single() + assertThrows(IllegalArgumentException::class.java) { config.removeServer(server.id) } + val running = config.copy(tunnels = config.tunnels.map { it.copy(enabled = true) }) + assertThrows(IllegalArgumentException::class.java) { running.saveServer(server.copy(host = "new.example.com")) } + assertTrue(config.copy(tunnels = emptyList()).removeServer(server.id).servers.isEmpty()) + } + + @Test fun `missing references retired TLS and conflicting mappings fail validation`() { + val config = RemoteConfig(tunnels = listOf(first, second)).migrateServers() + assertThrows(IllegalArgumentException::class.java) { config.copy(servers = emptyList()).validate() } + assertThrows(IllegalArgumentException::class.java) { config.saveServer(config.servers.single().copy(tlsCaId = "c".repeat(32))) } + assertThrows(IllegalArgumentException::class.java) { + config.copy(tunnels = config.tunnels.map { it.copy(remotePort = 18080) }).validate() + } + val separate = RemoteConfig(tunnels = listOf(first, second.copy(server = "other.example.com", remotePort = 18080))).migrateServers() + assertThrows(IllegalArgumentException::class.java) { separate.saveServer(separate.servers[1].copy(host = first.server)) } + } + + @Test fun `editing primary server preserves inactive legacy servers and certificate payloads`() { + val certificate = TunnelCertificate(name = "legacy", pem = "legacy-payload", keyPem = "legacy-key") + val migrated = RemoteConfig(tunnels = listOf(first, second.copy(server = "other.example.com")), + certificates = listOf(certificate)).migrateServers() + val primary = migrated.server!! + val edited = migrated.saveServer(primary.copy(name = "renamed")) + assertEquals(primary.id, edited.server!!.id) + assertEquals(migrated.servers[1], edited.servers[1]) + val restored = Json.decodeFromString(Json.encodeToString(edited)) + assertEquals(listOf(certificate), restored.certificates) + assertEquals(migrated.tunnels, restored.tunnels) + } +} diff --git a/docs/development.md b/docs/development.md index ba78827..75424a4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,11 +1,22 @@ # MBrain 开发与联调 +## 远程访问集成验证(2026-09-17) + +- Debug / Release APK 构建和 lint 通过(无错误,37 条警告);两个 APK 均通过四 ABI 库完整性检查。 +- 应用与核心传输共 77 项 JVM 测试通过;仓库脚本 14 项测试、工作流 actionlint 通过。 +- Android API 35、x86_64 测试设备:实际运行 APK 内置 frpc,使用 ADB 反向转发连接仅监听电脑回环地址的 frps;两条隧道分别通过未认证拒绝、初始化、工具目录和只读电池查询。 +- 主动占用手机 8765 后,网关自动绑定空闲端口,两条隧道均跟随实际端口;关闭一条隧道不影响另一条。进程强制停止后映射关闭,重新启动后加密配置和 MCP Token 保留。 +- UI:深浅色、空字段校验、保存、等待网关、独立开关、编辑放弃/继续、删除取消/确认、凭据重置通过;重置后旧 Token 返回 401,新 Token 正常调用。 +- 限制:尚未验证公网域名/HTTPS 反向代理、ARM 真机、长期后台运行和多 OEM 电池策略。本次测试不代表公网部署已经完成。 + ## 工程环境 Android Studio 打开仓库根目录,运行 `app`。当前配置为 Kotlin 2.1.20、AGP 8.13.2、Gradle 8.13、compile/target SDK 35、min SDK 28。 使用标准 JDK 17,并将 `JAVA_HOME` 指向 JDK 安装目录;CI 使用 Temurin 17,不依赖特定厂商的自动下载配置。 安装 Android SDK Platform 35 和 Build Tools 35.0.0。SDK 路径通过 `ANDROID_HOME` 或本机 `local.properties` 指定,不提交。设备上的 root、Shizuku、MT 服务无需运行在开发电脑上。 +内置 frpc 还需 Go 1.26.3、Python 3.9+ 和 Android NDK 28.2.13676358。Gradle 自动校验并编译固定的 frp 源码,为四种 ABI 生成可执行文件;可用 `MBRAIN_PYTHON` 指定 Python 路径。功能与设备集成测试见[内网穿透](remote-access.md)。 + ```powershell .\gradlew.bat :app:assembleDebug :app:testDebugUnitTest :droid-mcp-core:testDebugUnitTest :droid-mcp-shell-core:testDebugUnitTest :droid-mcp-root:testDebugUnitTest :app:lintDebug .\gradlew.bat :app:installDebug @@ -75,7 +86,7 @@ KernelSU 等管理器可能对未授权应用隐藏 `su`,需在管理器中单 ## HTTP MCP(例如 MT) MT 仅作为普通 HTTP MCP 服务的联调示例,应用没有 MT 专属入口或默认配置。在 MT 中开启 MCP 后,手动添加 HTTP 服务。此前联调地址为 `http://127.0.0.1:8787/mcp`,实际地址和 Token 以该服务的配置为准。 -只接受 localhost / 127.0.0.1 / ::1,不跟随 HTTP 重定向,不允许连接 MBrain 自身的 8765 端口。 +只接受 localhost / 127.0.0.1 / ::1,不跟随 HTTP 重定向,不允许连接 MBrain 当前实际监听端口。 支持初始化、工具列表分页、会话头、JSON 与 SSE POST 响应,以及工具调用。 完整 inputSchema/outputSchema、显式 null 参数、content、structuredContent、isError 均保留;MT 自身权限错误不会被吞掉。 上游请求失败不自动重试写操作。服务重启或会话失效后点击“断开/连接”重新初始化;工具变更也通过重新连接刷新。 @@ -116,7 +127,7 @@ powershell -ExecutionPolicy Bypass -File scripts/smoke-mcp.ps1 ``` 按提示输入 Token。脚本验证未认证请求被拒绝、初始化、核心工具列表、电池查询。 -多个设备时使用 `adb -s `。Token 在每次重启网关后改变,旧 Token 失效。 +多个设备时使用 `adb -s `。端口冲突时以应用显示的实际端口为准。Token 加密持久保存,重置后旧 Token 失效。 ## 代码结构 diff --git a/docs/releases/0.2.0.md b/docs/releases/0.2.0.md new file mode 100644 index 0000000..7601a08 --- /dev/null +++ b/docs/releases/0.2.0.md @@ -0,0 +1,20 @@ +# MBrain 0.2.0 + +## 内网穿透 + +- 新增独立服务器配置入口,所有隧道共用一台 frps 服务器。 +- 简化服务器和隧道配置,仅提供基础 TCP 转发,移除 HTTPS 插件和证书管理界面。 +- MCP 隧道转发本机网关 `127.0.0.1:8765`,公网访问端口独立配置;自动生成 MCP 访问地址并支持复制客户端配置。 +- 精简隧道详情页,将连接诊断和运行记录收纳到“更多”。 +- 修复要求 TLS 的 frps 登录失败,保留底层连接加密,并合并重复重连错误。 + +## 升级说明 + +- 旧服务器配置会自动整理;旧多服务器数据保留,当前仅支持使用第一台服务器。 +- 旧 HTTPS、插件和证书配置需重新编辑为 TCP 后才能启动。 +- 应用重启或升级后,需手动启动网关和隧道。 +- frps Token 用于服务器登录,MCP Token 用于公网 MCP 请求鉴权,两者独立。 + +## 验证 + +- 已在测试设备验证公网 MCP 鉴权、初始化、工具发现和设备、电量、网络、存储四项只读工具调用。 diff --git a/docs/remote-access.md b/docs/remote-access.md new file mode 100644 index 0000000..5d49e71 --- /dev/null +++ b/docs/remote-access.md @@ -0,0 +1,47 @@ +# 内网穿透 + +在 **设置 → 内网穿透 → 配置服务器** 填写已有 frps 的名称、地址、端口和 Token。当前只支持配置一台服务器;点击服务器入口直接编辑,所有隧道共用此配置。MBrain 内置 frpc,不需要 Root 或 Shizuku。 + +## 配置隧道 + +返回内网穿透页,点击“添加隧道”,填写名称、本地目标和公网访问端口: + +- **本应用 MCP**:转发本机 MCP 网关 `127.0.0.1:8765`,运行时跟随网关实际监听端口,无需填写本地端口。 +- **自定义服务**:填写本地地址和端口,默认地址为回环地址。 +- **公网访问端口**:frps 对外提供此隧道的 TCP 端口,与服务器连接端口、本机网关端口分别配置。 +- **自定义公网地址**:可选。留空时,MCP 自动使用 `http://服务器地址:公网访问端口/mcp`;存在额外端口映射或域名时可填写完整 HTTP 地址覆盖,用于显示和复制客户端配置。 + +当前仅提供基础 TCP 转发,不提供 HTTPS 路由、客户端插件或证书管理。frpc 到 frps 的底层连接默认使用 TLS,与隧道转发类型独立,无需额外界面设置;兼容要求 TLS 的 frps。服务器需允许对应映射端口。 + +## 运行与编辑 + +- 每条隧道独立启停。MCP 隧道在网关关闭时等待,网关启动后连接;自定义服务隧道独立运行。 +- 修改服务器前,先关闭关联隧道。删除服务器前,先删除关联隧道。 +- frpc 网络重连与进程退避重启保持启用;应用进程死亡或设备重启后,隧道保持关闭。 +- 服务器连接、隧道注册和本地端口状态分别显示。“隧道已注册”不代表公网应用访问已验证。 +- MCP 继续使用网关 Bearer Token;服务器 Token 与 MCP Token 是不同凭据。 + +旧配置中的服务器会自动整理。若旧版本曾配置多台服务器,当前仅使用第一台,其余配置保留在加密存储中,对应隧道需重新编辑保存以使用当前服务器。旧 HTTPS、TLS 和插件配置不会自动改为明文转发;需编辑服务器或隧道,确认基础 TCP 参数后保存。 + +配置与 Token 继续使用 Android Keystore 的 AES-GCM 加密保存,禁止备份;读取失败时保留原数据并禁止覆盖。运行期间的 frpc 配置仅保存在应用私有临时目录,停止后清理。 + +## 最小 frps 示例 + +```toml +bindPort = 7000 +auth.method = "token" +auth.token = "replace-with-your-token" +transport.tls.force = true +allowPorts = [{ start = 18080, end = 18090 }] +``` + +## 构建与验证 + +内核固定为 frp v0.71.0,使用 `scripts/build_frpc.py` 构建四种 Android ABI。许可证保存在 `assets/licenses/frp-LICENSE.txt`。 + +`scripts/smoke-frpc.py` 使用仅监听电脑回环地址的临时 frps,通过 ADB reverse 验证共享服务器的两条 TCP 隧道、MCP 鉴权、流式响应、独立启停及运行目录清理。使用独立 QA 包名,不覆盖日常应用。 + +```shell +./gradlew :app:assembleDebug :app:assembleDebugAndroidTest -I scripts/frpc-qa.init.gradle +python scripts/smoke-frpc.py --serial <设备序列号> --package com.powercess.mbrain.frpcqa +``` diff --git a/docs/ui-style-audit.md b/docs/ui-style-audit.md new file mode 100644 index 0000000..bc4e78e --- /dev/null +++ b/docs/ui-style-audit.md @@ -0,0 +1,34 @@ +# UI 样式核查(2026-09-23) + +依据根目录 `DESIGN.md` 和项目 `mbrain-style` skill,检查 `ui/` 下全部七个 Kotlin 文件,包括页面、编辑器、底部弹层、确认对话框及公共组件。 + +## 统一结果 + +| 范围 | 处理 | +| --- | --- | +| 首页、能力、设置 | 保留概览卡片与网关主操作;同类入口复用分组行,首组顶部间距保持一致 | +| 工具列表与搜索 | 使用懒加载连续分组,2dp 间隙,仅首尾使用大圆角;搜索结果单项时四角恢复大圆角 | +| 工具详情 | 说明使用 ContentCard,调用名称完整展示、可选择与复制;复制不显示导航箭头 | +| MCP 服务列表、详情 | 连续分组;移除详情装饰图标底框;统一行首图标与导航箭头尺寸 | +| 隧道列表、详情 | 连续分组;运行记录使用标准分组;修正 Token 重启后变化的过时说明 | +| 证书列表 | 分组外形由公共懒加载组件处理,保留每份证书的信息与删除操作 | +| 服务、隧道、证书编辑器 | 统一 EditorSaveBar 的宽度、内边距和按钮高度;标题栏使用页面背景色 | +| 添加、导入、重连操作 | 统一 SecondaryAction 的高度、可选图标尺寸与间距 | +| 下拉选择 | 统一操作行,只在右侧显示下拉箭头 | +| 空状态 | 去掉装饰图标,缩短文案,保留必要操作和错误说明 | +| 外观选择与添加类型弹层 | 统一水平内边距,补齐外观选择的 2dp 间隙;公共分组和间隙透出容器底色,修复弹层中的黑边,已复查明暗主题 | +| 访问凭据 | 保持隐藏 Token,收敛内容内边距,未启动时使用简短提示 | +| 运行记录 | 使用连续分组,保留失败与成功的图标区别 | +| 关于、使用说明、确认对话框 | 核查后保留现有品牌图、提示及原生 Material 操作,不强行改成列表按钮 | + +## 验证 + +- Debug rebuild 与 `:app:lintDebug` 通过;lint 报告为 43 项警告、0 项错误。 +- 真机检查工具列表、单项搜索结果、详情,以及浅色/深色和 1.5 倍字体下的工具页、详情页、服务编辑器;字体和主题已恢复。 +- 检查 HTTP 与托管进程编辑器、隧道编辑器、证书编辑器、MCP 空状态、外观选择、凭据隐藏、帮助、运行记录、关于页。 +- 使用两个临时本机 HTTP 服务检查有数据分组、服务详情、放弃修改与删除确认;临时服务已删除,没有连接外部服务。 +- 检查 Root、Shizuku、应用管理、设备信息四种详情,以及一个禁用的临时隧道的列表与详情;临时隧道已删除,未启动 frpc。 +- 工具调用名称的复制入口正常触发。最终手机停留在“全部工具”,网关运行中,字体恢复为 1.0,外观恢复为跟随系统。 +- 测试截图及构建日志保留在忽略目录 `.local-tools/`,未纳入应用资源。 + +本轮是样式与交互验证,未验证公网 frps、真实证书导入或每个网络错误状态。证书有数据分支进行了源码检查,未导入测试证书。设备报告输入法已展开,但截图没有可见键盘,因此不将键盘遮挡测试记作通过;保存栏的 IME 避让代码保留,键盘设置已恢复。没有修改 Root/Shizuku 授权开关,也没有重置访问凭据。 diff --git a/scripts/build_frpc.py b/scripts/build_frpc.py new file mode 100644 index 0000000..62ff105 --- /dev/null +++ b/scripts/build_frpc.py @@ -0,0 +1,62 @@ +"""Build the pinned upstream frpc for every supported Android ABI (Go + NDK).""" +import argparse +import hashlib +import os +from pathlib import Path +import platform +import subprocess +import urllib.request +import zipfile + +VERSION = "0.71.0" +SHA256 = "35a19bb92d3b6ce20d9bceb2057ca88b4dfd56b15adf521c2110ddcc8e53e4e8" +TARGETS = { + "arm64-v8a": ("arm64", "aarch64-linux-android"), + "armeabi-v7a": ("arm", "armv7a-linux-androideabi"), + "x86_64": ("amd64", "x86_64-linux-android"), + "x86": ("386", "i686-linux-android"), +} + + +def build(ndk, output, cache): + cache.mkdir(parents=True, exist_ok=True) + archive = cache / f"frp-{VERSION}.zip" + if not archive.exists(): + with urllib.request.urlopen(f"https://codeload.github.com/fatedier/frp/zip/refs/tags/v{VERSION}", timeout=120) as response: + archive.write_bytes(response.read()) + if hashlib.sha256(archive.read_bytes()).hexdigest() != SHA256: + raise ValueError("frp source checksum mismatch; remove the cached archive and retry") + source = cache / f"frp-{VERSION}" + if not source.exists(): + with zipfile.ZipFile(archive) as package: + for item in package.infolist(): + target = (cache / item.filename).resolve() + if not target.is_relative_to(cache.resolve()): + raise ValueError("Unsafe archive path") + package.extractall(cache) + # MBrain never enables frpc's web admin listener. Satisfy its embed directive + # without shipping an unused web dashboard or requiring a Node toolchain. + dashboard = source / "web" / "frpc" / "dist" + dashboard.mkdir(parents=True, exist_ok=True) + (dashboard / "index.html").write_text("Not enabled", encoding="utf-8") + host = {"Windows": "windows-x86_64", "Linux": "linux-x86_64", "Darwin": "darwin-x86_64"}[platform.system()] + toolchain = ndk / "toolchains" / "llvm" / "prebuilt" / host / "bin" + for abi, (arch, triple) in TARGETS.items(): + compiler = toolchain / (triple + "28-clang" + (".cmd" if os.name == "nt" else "")) + if not compiler.exists(): + raise FileNotFoundError(f"Install NDK 28.2.13676358: missing {compiler.name}") + target = output / abi / "libfrpc.so" + target.parent.mkdir(parents=True, exist_ok=True) + env = dict(os.environ, GOOS="android", GOARCH=arch, CGO_ENABLED="1", CC=str(compiler), GOARM="7") + subprocess.run(["go", "build", "-trimpath", "-buildvcs=false", "-ldflags=-s -w -checklinkname=0 -extldflags=-Wl,-z,max-page-size=16384", + "-tags=frpc", "-o", str(target.resolve()), "./cmd/frpc"], cwd=source, env=env, check=True) + print(f"Built frpc {VERSION}: {abi}", flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--ndk", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--cache", type=Path, required=True) + args = parser.parse_args() + build(args.ndk.resolve(), args.output.resolve(), args.cache.resolve()) diff --git a/scripts/ci_scope.py b/scripts/ci_scope.py new file mode 100644 index 0000000..72166e7 --- /dev/null +++ b/scripts/ci_scope.py @@ -0,0 +1,35 @@ +"""Skip Android builds only for documentation-only pull requests.""" +import os +from pathlib import PurePosixPath +import subprocess + + +def needs_android(event, paths): + if event != "pull_request" or not paths: + return True + for path in paths: + p = PurePosixPath(path) + documentation = ( + (len(p.parts) == 1 and p.suffix == ".md") + or path.startswith("docs/") + or path in {"vendor/droid-mcp/README.md", "vendor/droid-mcp/UPSTREAM.md"} + ) + if not documentation: + return True + return False + + +if __name__ == "__main__": + event = os.environ["GITHUB_EVENT_NAME"] + paths = [] + if event == "pull_request": + # Disable rename detection so moving code into docs still requires a build. + result = subprocess.check_output([ + "git", "diff", "--name-only", "--no-renames", "-z", + os.environ["PR_BASE_SHA"] + "..." + os.environ["PR_HEAD_SHA"], "--", + ]) + paths = [p.decode("utf-8", errors="surrogateescape") for p in result.split(b"\0") if p] + required = needs_android(event, paths) + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"android={str(required).lower()}\n") + print("Android build required" if required else "Documentation-only PR: lightweight checks only") diff --git a/scripts/frpc-qa.init.gradle b/scripts/frpc-qa.init.gradle new file mode 100644 index 0000000..3cc41c8 --- /dev/null +++ b/scripts/frpc-qa.init.gradle @@ -0,0 +1,8 @@ +// Isolate device integration tests from installed release and regular debug data. +gradle.beforeProject { project -> + project.pluginManager.withPlugin('com.android.application') { + project.extensions.getByName('androidComponents').finalizeDsl { android -> + android.buildTypes.getByName('debug').applicationIdSuffix = '.frpcqa' + } + } +} diff --git a/scripts/smoke-frpc.py b/scripts/smoke-frpc.py new file mode 100644 index 0000000..cd1fd91 --- /dev/null +++ b/scripts/smoke-frpc.py @@ -0,0 +1,95 @@ +"""Run real Android frpc integration tests using a loopback-only, ephemeral frps. + +Build/install app and androidTest APKs first. Use an isolated debug application ID; +the script refuses the regular user-facing package. Requires Go, adb, built frp source. +""" +import argparse +import json +import os +from pathlib import Path +import secrets +import socket +import subprocess +import tempfile +import time + + +def free_port(): + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + return listener.getsockname()[1] + + +def run(args): + root = Path(__file__).resolve().parents[1] + if args.package in {"com.powercess.mbrain", "com.powercess.mbrain.debug"}: + raise ValueError("Use an isolated QA package to protect existing application data") + adb = [args.adb, "-s", args.serial] + source = root / "build/frpc-source/frp-0.71.0" + dashboard = source / "web/frps/dist" + dashboard.mkdir(parents=True, exist_ok=True) + (dashboard / "index.html").write_text("Local test", encoding="utf-8") + binary = source / ("frps-test.exe" if os.name == "nt" else "frps-test") + subprocess.run(["go", "build", "-trimpath", "-buildvcs=false", "-tags=frps", "-o", str(binary), "./cmd/frps"], cwd=source, check=True) + ports = {} + while len(ports) < 3: + candidate = free_port() + if candidate not in ports.values(): + ports[["controlPort", "tcpPort", "mcpPort"][len(ports)]] = candidate + with tempfile.TemporaryDirectory(prefix="mbrain-frpc-test-") as temporary: + directory = Path(temporary) + token = secrets.token_urlsafe(24) + config = { + "bindAddr": "127.0.0.1", "bindPort": ports["controlPort"], "proxyBindAddr": "127.0.0.1", + "auth": {"method": "token", "token": token}, + "transport": {"tls": {"force": True}}, + "allowPorts": [{"single": ports["tcpPort"]}, {"single": ports["mcpPort"]}], + } + config_file = directory / "frps.json" + config_file.write_text(json.dumps(config), encoding="utf-8") + with (directory / "frps.log").open("w") as log: + process = subprocess.Popen([str(binary), "-c", str(config_file)], stdout=log, stderr=log) + mapped = [] + try: + deadline = time.monotonic() + 15 + while True: + if process.poll() is not None: + raise RuntimeError("Local frps failed to start") + try: + with socket.create_connection(("127.0.0.1", ports["controlPort"]), timeout=1): + break + except OSError: + if time.monotonic() >= deadline: + raise RuntimeError("Local frps did not become ready") + time.sleep(.2) + for port in ports.values(): + subprocess.run(adb + ["reverse", f"tcp:{port}", f"tcp:{port}"], check=True, stdout=subprocess.DEVNULL) + mapped.append(port) + subprocess.run(adb + ["shell", "am", "start", "-n", args.package + "/com.powercess.mbrain.MainActivity"], check=True, stdout=subprocess.DEVNULL) + time.sleep(1) + command = adb + ["shell", "am", "instrument", "-w", "-r", "-e", "class", "com.powercess.mbrain.remote.FrpcDeviceTest"] + parameters = dict(ports, frpToken=token) + for name, value in parameters.items(): + command += ["-e", name, str(value)] + command += [args.package + ".test/androidx.test.runner.AndroidJUnitRunner"] + result = subprocess.run(command, capture_output=True, text=True, timeout=240) + print(result.stdout) + if result.returncode or "OK (1 test)" not in result.stdout: + raise RuntimeError("Device frpc integration test failed (see instrumentation output)") + finally: + subprocess.run(adb + ["shell", "am", "force-stop", args.package], stdout=subprocess.DEVNULL) + for port in mapped: + subprocess.run(adb + ["reverse", "--remove", f"tcp:{port}"], stdout=subprocess.DEVNULL) + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill(); process.wait() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--serial", required=True) + parser.add_argument("--adb", default="adb") + parser.add_argument("--package", default="com.powercess.mbrain.frpcqa") + run(parser.parse_args()) diff --git a/scripts/test_ci_scope.py b/scripts/test_ci_scope.py new file mode 100644 index 0000000..455bbb9 --- /dev/null +++ b/scripts/test_ci_scope.py @@ -0,0 +1,20 @@ +import unittest +from ci_scope import needs_android + + +class CiScopeTest(unittest.TestCase): + def test_documentation_only(self): + self.assertFalse(needs_android("pull_request", ["README.md", "AGENTS.md", "docs/development.md", "vendor/droid-mcp/UPSTREAM.md"])) + + def test_code_and_unknown_paths_require_build(self): + for path in ["app/src/main/Main.kt", "app/src/main/assets/help.md", "build.gradle.kts", "gradle/libs.versions.toml", ".github/workflows/android.yml", "scripts/ci_scope.py", "unknown", "vendor/droid-mcp/core.kt"]: + with self.subTest(path=path): + self.assertTrue(needs_android("pull_request", ["README.md", path])) + + def test_code_deletion_or_rename_requires_build(self): + self.assertTrue(needs_android("pull_request", ["app/old.kt", "docs/old.kt"])) + + def test_non_pr_and_empty_diff_require_build(self): + for event in ["push", "workflow_dispatch"]: + self.assertTrue(needs_android(event, ["README.md"])) + self.assertTrue(needs_android("pull_request", [])) diff --git a/vendor/droid-mcp/UPSTREAM.md b/vendor/droid-mcp/UPSTREAM.md index bacf1d1..83de974 100644 --- a/vendor/droid-mcp/UPSTREAM.md +++ b/vendor/droid-mcp/UPSTREAM.md @@ -1,5 +1,7 @@ # droid-mcp source provenance +MBrain remote-access changes: HTTP transport optionally falls back to an OS-assigned port on bind conflict and exposes the resolved port. The host may replace its primary token after encrypted persistence. Defaults retain fixed-port behavior unless fallback is explicitly requested. + - Repository: https://github.com/stixez/droid-mcp - Revision: `aeaa5b9e8e96f56ef64a7ca23d0726585f7b1103` - Imported: 2026-09-17 diff --git a/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/DroidMcp.kt b/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/DroidMcp.kt index 06ab81e..9726af1 100644 --- a/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/DroidMcp.kt +++ b/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/DroidMcp.kt @@ -24,6 +24,7 @@ class DroidMcp private constructor( ) { /** The HTTP server's effective bearer token, or null if the server is disabled or open (no auth). */ val serverToken: String? get() = httpTransport?.effectiveToken + val serverPort: Int? get() = httpTransport?.boundPort /** The registered tools as live [McpTool] instances (in-process). */ fun listTools(): List = inProcessTransport.listTools() @@ -71,6 +72,7 @@ class DroidMcp private constructor( * disabled or running without auth. Re-issue the pairing QR after calling. */ fun rotateToken(): String? = httpTransport?.rotateToken() + fun setServerToken(token: String) { httpTransport?.setToken(token) } /** * Mint a revocable token for a named client. Re-pairing an existing label @@ -99,6 +101,7 @@ class DroidMcp private constructor( private val tools = mutableListOf() private var httpPort: Int? = null private var httpHost: String = "127.0.0.1" + private var fallbackToDynamicPort: Boolean = false private var authToken: String? = null private var requireAuth: Boolean = true private var readOnly: Boolean = false @@ -147,8 +150,10 @@ class DroidMcp private constructor( readOnly: Boolean = false, context: Context? = null, host: String = "127.0.0.1", + fallbackToDynamicPort: Boolean = false, ) = apply { - require(port in 1..65535) { "Port must be between 1 and 65535" } + require(port in 0..65535) { "Port must be between 0 and 65535" } + this.fallbackToDynamicPort = fallbackToDynamicPort require(host.isNotBlank()) { "Host must not be blank" } this.httpHost = host this.httpPort = port @@ -174,6 +179,7 @@ class DroidMcp private constructor( auditSink = auditSink, tls = tls, host = httpHost, + fallbackToDynamicPort = fallbackToDynamicPort, ) } return DroidMcp(registry, http, inProcess) diff --git a/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/transport/HttpTransport.kt b/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/transport/HttpTransport.kt index c6c78e5..d78589c 100644 --- a/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/transport/HttpTransport.kt +++ b/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/transport/HttpTransport.kt @@ -22,6 +22,8 @@ import io.ktor.server.sse.* import kotlinx.coroutines.flow.MutableSharedFlow import java.util.Collections import java.util.UUID +import java.net.BindException +import kotlinx.coroutines.runBlocking /** * Ktor/Netty MCP server for desktop clients. Exposes the JSON-RPC surface at `POST /mcp` @@ -52,6 +54,7 @@ class HttpTransport( auditSink: AuditSink? = null, private val tls: TlsConfig? = null, private val host: String = "127.0.0.1", + private val fallbackToDynamicPort: Boolean = false, ) { /** * Bearer-token authority. `null` when [requireAuth] is false (open server). @@ -72,7 +75,9 @@ class HttpTransport( val tlsFingerprint: String? get() = tls?.certFingerprintSha256 /** Port the server actually binds — the HTTPS port when TLS is on. */ - private val activePort: Int get() = tls?.httpsPort ?: port + private val activePort: Int get() = boundPort ?: tls?.httpsPort ?: port + @Volatile var boundPort: Int? = null + private set /** mDNS service name advertised on the network, derived from the device model (sanitised, ≤63 chars). */ val mdnsServiceName: String = run { @@ -95,15 +100,25 @@ class HttpTransport( /** Start the embedded server and register mDNS. No-op if already running; rethrows bind failures. */ fun start() { if (server != null) return + try { + bind(port) + } catch (e: Exception) { + if (!fallbackToDynamicPort || tls != null || generateSequence(e) { it.cause }.none { it is BindException }) throw e + bind(0) + } + } + + private fun bind(listenPort: Int) { val tlsConfig = tls + var candidate: EmbeddedServer<*, *>? = null try { - server = embeddedServer( + candidate = embeddedServer( factory = Netty, configure = { if (tlsConfig == null) { connector { host = this@HttpTransport.host - port = this@HttpTransport.port + port = listenPort } } else { sslConnector( @@ -118,10 +133,15 @@ class HttpTransport( } }, module = { installMcpModule() }, - ).start(wait = false) + ) + candidate.start(wait = false) + boundPort = runBlocking { candidate.engine.resolvedConnectors().first().port } + server = candidate registerNsd() } catch (e: Exception) { + runCatching { candidate?.stop(0, 1000) } server = null + boundPort = null throw e } } @@ -201,6 +221,7 @@ class HttpTransport( unregisterNsd() server?.stop(1000, 2000) server = null + boundPort = null } /** Whether the embedded server is currently running. */ @@ -212,6 +233,7 @@ class HttpTransport( * Surface the new value in a fresh pairing QR. */ fun rotateToken(): String? = tokenStore?.rotatePrimary() + fun setToken(token: String) { tokenStore?.replacePrimary(token) } /** * Mint a revocable token for a named client. Re-pairing an existing label diff --git a/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/transport/TokenStore.kt b/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/transport/TokenStore.kt index 66ccfe0..fb3de39 100644 --- a/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/transport/TokenStore.kt +++ b/vendor/droid-mcp/droid-mcp-core/src/main/kotlin/io/droidmcp/core/transport/TokenStore.kt @@ -64,6 +64,11 @@ class TokenStore(seedPrimary: String? = null) { return next } + fun replacePrimary(token: String) { + require(token.length >= 32 && token.none { it.isWhitespace() }) + primary = token + } + /** * Mint a token for a named client. Re-pairing an existing label replaces its * token (and invalidates the previous one). Returns the new token. diff --git a/vendor/droid-mcp/droid-mcp-core/src/test/kotlin/io/droidmcp/core/transport/LocalHttpTransportTest.kt b/vendor/droid-mcp/droid-mcp-core/src/test/kotlin/io/droidmcp/core/transport/LocalHttpTransportTest.kt index 7c85bd2..5363b35 100644 --- a/vendor/droid-mcp/droid-mcp-core/src/test/kotlin/io/droidmcp/core/transport/LocalHttpTransportTest.kt +++ b/vendor/droid-mcp/droid-mcp-core/src/test/kotlin/io/droidmcp/core/transport/LocalHttpTransportTest.kt @@ -37,10 +37,48 @@ class LocalHttpTransportTest { @Test fun `invalid listen configuration is rejected before starting`() { assertThrows(IllegalArgumentException::class.java) { - DroidMcp.builder().enableHttpServer(port = 0) + DroidMcp.builder().enableHttpServer(port = -1) } assertThrows(IllegalArgumentException::class.java) { DroidMcp.builder().enableHttpServer(host = " ") } } + + @Test + fun `occupied preferred port falls back and reports actual authenticated listener`() { + ServerSocket(0, 1, java.net.InetAddress.getByName("127.0.0.1")).use { occupied -> + val server = DroidMcp.builder().enableHttpServer(port = occupied.localPort, fallbackToDynamicPort = true).build() + try { + server.startServer() + val actual = server.serverPort!! + assertNotEquals(occupied.localPort, actual) + val connection = URL("http://127.0.0.1:$actual/health").openConnection() as HttpURLConnection + connection.setRequestProperty("Authorization", "Bearer ${server.serverToken}") + try { assertEquals(200, connection.responseCode) } finally { connection.disconnect() } + val oldToken = server.serverToken + val replacement = "replacement-" + "a".repeat(32) + server.setServerToken(replacement) + fun health(token: String?): Int { + val request = URL("http://127.0.0.1:$actual/health").openConnection() as HttpURLConnection + request.setRequestProperty("Authorization", "Bearer $token") + return try { request.responseCode } finally { request.disconnect() } + } + assertEquals(401, health(oldToken)) + assertEquals(200, health(replacement)) + } finally { server.stopServer() } + assertNull(server.serverPort) + } + } + + @Test + fun `explicit fixed port never silently falls back`() { + ServerSocket(0).use { occupied -> + val server = DroidMcp.builder().enableHttpServer(port = occupied.localPort).build() + try { + assertThrows(Exception::class.java) { server.startServer() } + assertFalse(server.isServerRunning()) + assertNull(server.serverPort) + } finally { server.stopServer() } + } + } }