Compare commits

...
2 Commits
36 changed files with 3729 additions and 57 deletions

No files matched your search

+3 -1
View File
@@ -38,7 +38,7 @@
| `adb/` | 本地第三方 AOSP ADB 源码检出,用于参考与研究;已被 Git 忽略,不是 adb 可执行文件目录 | 主要为 C++,另含 Python、Shell、Android.bp |
| `scrcpy/` | 本地第三方 scrcpy 源码检出;已被 Git 忽略,不是可直接运行的发行包 | C(客户端)、Java(Android 服务端)、Meson、Gradle |
| `QtScrcpy/` | 本地第三方 QtScrcpy 源码检出,供参考与研究;已被 Git 忽略 | C++、Qt、CMake |
| `bin/` | 编译/分发产物和运行工具,如 ads 三端程序、桌面包、Linux 产物及 `tools/`;已被 Git 忽略 | 可执行文件、运行库及资源,无独立源码语言 |
| `bin/` | 编译/分发产物和运行工具,如 ads 三端程序、桌面包、Linux 产物、`apk/` Android 安装包及 `tools/`;已被 Git 忽略 | 可执行文件、运行库及资源,无独立源码语言 |
| `target/` | Cargo 生成的编译产物与缓存;已被 Git 忽略 | Rust 构建产物,无独立源码语言 |
| `work/` | 本地联调、测试输出、截图、日志、工具下载与临时脚本;已被 Git 忽略,不作为正式源码入口 | 混合格式,含 Python、PowerShell、日志及图片 |
| `__pycache__/` | Python 自动生成的字节码缓存;已被 Git 忽略 | Python 字节码,无手写源码 |
@@ -125,3 +125,5 @@ macOS 是正式交付的最大不确定性。不能把存在 API 或实验原型
每次新发布打包将版本号的补丁位增加 1(例如 0.2.0 → 0.2.1),同步 Cargo 工作区与锁文件、Avalonia、Flutter 和安装包版本。Windows 必须生成 Setup.exe,Linux 采用 deb 安装包;普通开发编译不增加版本。同一版本的 Windows/Linux 安装包只递增一次,另一平台使用复用版本选项。打包失败后重试复用已分配版本,避免重复递增。发布产物不包含私有凭据。
`scripts/release-version.py` 为共享版本分配脚本(Python)。Windows 使用 `scripts/build-installers.ps1` 自动递增并重建后端与桌面安装包;同一次发布的重试或第二平台使用 `-ReuseVersion`。Linux 使用 `bash scripts/build-linux-packages.sh` 自动递增,另一平台已分配版本时设置 `ADS_REUSE_VERSION=1`,须提供该版本重新构建的原生产物。
Android APK 交付目录固定为 `bin/apk/`(APK 格式,无业务源码,自动生成且 Git 忽略);`android_agent` 的 assembleRelease / assembleDebug 成功后自动复制到该目录。
Generated
+6 -6
View File
@@ -4,7 +4,7 @@ version = 4
[[package]]
name = "ads-agent"
version = "0.2.2"
version = "0.2.3"
dependencies = [
"ads-core",
"ads-management",
@@ -21,7 +21,7 @@ dependencies = [
[[package]]
name = "ads-client"
version = "0.2.2"
version = "0.2.3"
dependencies = [
"ads-core",
"anyhow",
@@ -32,7 +32,7 @@ dependencies = [
[[package]]
name = "ads-core"
version = "0.2.2"
version = "0.2.3"
dependencies = [
"anyhow",
"bytes",
@@ -51,7 +51,7 @@ dependencies = [
[[package]]
name = "ads-management"
version = "0.2.2"
version = "0.2.3"
dependencies = [
"ads-core",
"anyhow",
@@ -67,7 +67,7 @@ dependencies = [
[[package]]
name = "ads-usb"
version = "0.2.2"
version = "0.2.3"
dependencies = [
"anyhow",
"clap",
@@ -78,7 +78,7 @@ dependencies = [
[[package]]
name = "adsctl"
version = "0.2.2"
version = "0.2.3"
dependencies = [
"ads-core",
"ads-management",
+1 -1
View File
@@ -3,7 +3,7 @@ members = ["crates/ads-core", "agent", "client", "usb", "crates/ads-management",
resolver = "2"
[workspace.package]
version = "0.2.2"
version = "0.2.3"
edition = "2021"
license = "MIT"
+3 -1
View File
@@ -47,7 +47,7 @@ Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络
| `adb/` | 本地第三方 AOSP ADB 源码检出,用于参考与研究;已被 Git 忽略,不是 adb 可执行文件目录 | 主要为 C++,另含 Python、Shell、Android.bp |
| `scrcpy/` | 本地第三方 scrcpy 源码检出;已被 Git 忽略,不是可直接运行的发行包 | C(客户端)、Java(Android 服务端)、Meson、Gradle |
| `QtScrcpy/` | 本地第三方 QtScrcpy 源码检出,供参考与研究;已被 Git 忽略 | C++、Qt、CMake |
| `bin/` | 编译/分发产物和运行工具,如 ads 三端程序、桌面包、Linux 产物及 `tools/`;已被 Git 忽略 | 可执行文件、运行库及资源,无独立源码语言 |
| `bin/` | 编译/分发产物和运行工具,如 ads 三端程序、桌面包、Linux 产物、`apk/` Android 安装包及 `tools/`;已被 Git 忽略 | 可执行文件、运行库及资源,无独立源码语言 |
| `target/` | Cargo 生成的编译产物与缓存;已被 Git 忽略 | Rust 构建产物,无独立源码语言 |
| `work/` | 本地联调、测试输出、截图、日志、工具下载与临时脚本;已被 Git 忽略,不作为正式源码入口 | 混合格式,含 Python、PowerShell、日志及图片 |
| `__pycache__/` | Python 自动生成的字节码缓存;已被 Git 忽略 | Python 字节码,无手写源码 |
@@ -246,3 +246,5 @@ Flutter 管理中心已迁移 Cupertino UI,设备按电脑归属分组,支
Windows 发布精简:Avalonia 合并托管程序集、保留原生库;Flutter 源码插件静态链接 MSVC CRT。`scripts/check-windows-crt.py` 使用 Python 标准库检查 PE 直接及延迟导入,防止缺失运行库。安装升级清理应用根目录旧 DLL,保留配置和独立工具目录。
升级从 `Programs/TTSTD` 迁至 `Programs/TongTongStudio` 后,两个桌面客户端自动修复保存的工具路径,保留有效自定义路径及私有凭据。Flutter 在启动与连接前进行迁移和文件检查。
Android APK 交付目录固定为 `bin/apk/`(APK 格式,无业务源码,自动生成且 Git 忽略);`android_agent` 的 assembleRelease / assembleDebug 成功后自动复制到该目录。
+10
View File
@@ -0,0 +1,10 @@
.gradle/
**/build/
local.properties
native/target/
app/src/main/jniLibs/
*.jks
*.keystore
signing.local.properties
agent.local.properties
+95
View File
@@ -0,0 +1,95 @@
# Android 手机直接联网设备端
独立 Android Gradle 项目,Kotlin 传统 View(无 Compose)+ Rust JNI。手机无需连接现场电脑,通过本机 adbd 接入现有控制中心、P2P 与中继,远端继续使用 ads-client、ADB、scrcpy 和可选 ads-usb。
## 目录
| 目录 | 用途 | 语言/格式 |
|---|---|---|
| app/ | Android APK 模块 | Kotlin、XML、Gradle Kotlin DSL |
| app/src/main/java/com/ttstd/ads/ | Activity、前台服务、开机恢复、配置加密、日志和 JNI 声明 | Kotlin |
| app/src/main/jniLibs/ | 构建脚本生成的多 ABI JNI 运行库,Git 忽略 | SO,无业务源码 |
| native/ | 独立 Cargo 工作区,JNI、生命周期、状态及输入校验 | Rust、TOML、Cargo.lock |
| native/src/ | Rust 网关入口与单元测试 | Rust |
| scripts/ | Windows NDK 多 ABI 构建脚本 | PowerShell |
build/、.gradle/、native/target/ 为自动生成产物或缓存,不纳入源码。当前直接通过源码路径复用 ../agent/src/gateway.rs 和 ../crates/ads-core,所以本目录需要与整个仓库一起检出,不能只复制此目录构建。
## 当前实现
- 支持最低 Android 6 / API 23,compile/target API 35;API 26+ 通知渠道与 startForegroundService;API 34+ specialUse 类型;不使用受新版限时约束的 dataSync 类型冒充长期连接。
- Kotlin Activity 提供控制中心、设备 ID、内置 Agent 令牌、本机 adbd 端口、启动/停止和实时日志。
- Service 工作线程调用 JNI,Tokio 双线程执行网络;UI 不阻塞等待网络。控制连接断线时终止旧会话,按现有网关 1–30 秒退避重连。
- 原样复用现有网关 v1/v2:设备注册、独占租约、WebRTC P2P、独立中继回退、32 路并发限制、流控和超时。
- 当前测试包从 Git 忽略的 agent.local.properties 读取 agentToken 并编入 BuildConfig;界面无需输入,不回显、不传 Intent、不写入日志。内置令牌可从 APK 提取,此包仅用于受控测试,不应公开分发。
- Rust 日志有界队列 300 条;服务每秒转入 Logcat(ADS-Agent)及应用内 300 条环形日志。记录启动、ABI、adbd 探测、注册、连接失败、重试、转发失败和退出,不记录票据、SDP、ADB 内容。
- BOOT_COMPLETED 仅在用户已启用时尝试恢复;不支持解锁前启动。停止按钮关闭下次开机恢复,关闭界面不停止服务。
## 系统前置条件与边界
按需求不实现运行时权限申请、通知权限弹窗、忽略电池优化申请、Shizuku、root、setprop 或隐藏 API 提权。Manifest 中正常声明网络、开机及前台服务权限。
ROM 必须预先提供可被本应用访问的原始 adbd TCP 端点(固定连接 127.0.0.1,默认 5555),并配置必要的 SELinux、系统预授权和后台策略。此处连接的是手机 adbd,不是电脑 ADB server 的 5037,也不是 Android 无线调试的配对/TLS 端口。程序不会自动开启 adbd,不会关闭 ADB 认证。电脑首次调试密钥授权仍由 adbd/ROM 管理。
注册成功仅代表手机已连中继,不代表 adbd 可调试。ADBD_PROBE_OK 仅代表端口可连接;探测失败仍允许注册,实际数据通道会明确报无法连接 adbd。
当前是 APK 内的 Rust JNI 服务,不是 init 托管 native 守护。START_STICKY 和开机广播不能保证 OEM 强杀、强制停止、Doze、未解锁或系统禁止前台启动时仍永久在线;系统签名也不能替代 ROM 的策略配置。未实现独立 init 服务和 SELinux 策略,不能宣称已完成所有 ROM 常驻适配。
支持 ABI:arm64-v8a、armeabi-v7a、x86_64;不包含 x86。设置 16 KB ELF 对齐,仍需在真实 16 KB 系统验收。Android 6–15 是代码适配范围,不是实机兼容认证;更高版本需要按目标 ROM 验证。
## 只构建,不安装
准备 JDK 17、Android SDK 35、Gradle 8.11.1+(当前插件 8.9.2)、NDK r28+、Rust Android targets。仓库不包含平台签名私钥,不自动签系统应用,不执行安装、刷机或更改设备配置。
```powershell
# 仓库根目录;仅编译现有工具链,不安装任何目标或软件
.\android_agent\scripts\build-native.ps1 -Ndk F:\AndroidSDK\ndk\28.2.13676358
cd android_agent
# ANDROID_HOME 指向已安装 SDK;或在 Git 忽略的 local.properties 配置 sdk.dir
gradle :app:assembleDebug
```
APK 构建会检查三种 ABI 的 SO 是否存在,不允许静默输出缺少 native 核心的 APK。当前默认使用本机提供的 Crosshatch 证书签名;系统预装、权限白名单和 SELinux 集成仍由设备厂商 ROM 流程完成。
```powershell
cargo test --manifest-path android_agent/native/Cargo.toml --locked --lib
# 如需纯 Kotlin/Manifest 编译检查(不能将其产物视为可用 APK)
gradle :app:compileDebugKotlin -x verifyNative
```
日志查看(将来安装验证时):`adb logcat -s ADS-Agent`。启动失败按 CONFIG_INVALID、JNI_LOAD_FAILED、FGS_DENIED、ADBD_PROBE_FAILED、START_FAILED 排查。不要把令牌/配置 JSON 添加到诊断输出。
参考:[前台服务类型](https://developer.android.com/develop/background-work/services/fgs/service-types)、[启动前台服务](https://developer.android.com/develop/background-work/services/fgs/launch)。
## 本次验证
- Rust 主机侧 3 项测试通过;ARM64、ARMv7、x86_64 的 Release SO 均编译完成。
- Gradle Release 编译、Manifest/资源处理、Lint Vital 和 APK 打包通过;使用 SDK 35 本地 aapt2 解决离线工具依赖缺失。
- apksigner verify 通过,v1/v2 签名有效;证书 SHA-256 与指定 keystore 别名导出的证书一致:`c8a2e9bccf597c2fb6dc66bee293fc13f2fc47ec77bc6b2b0d52c11f51192ab8`。
- APK 包含三个 ABI 的 JNI 库与 classes.dex;minSdk 23、targetSdk 35。ARM64 ELF LOAD 对齐检查为 0x4000。
- 已签名 APK:`../bin/apk/ads-android-agent-0.1.0-crosshatch.apk`(12,846,591 字节)。
- 未安装、刷机或进行真机多版本、休眠保活及公网远程调试验收。
## 默认签名
app/build.gradle.kts 默认对 debug 和 release 使用 crosshatch 签名。当前机器的密钥位置、别名和口令存放在 Git 忽略的 signing.local.properties,不把口令写入可提交构建脚本。复制项目到其他机器时需提供该文件(storeFile、storePassword、keyAlias、keyPassword),或对应 ADS_SIGNING_STOREFILE、ADS_SIGNING_STOREPASSWORD、ADS_SIGNING_KEYALIAS、ADS_SIGNING_KEYPASSWORD 环境变量。
```powershell
gradle :app:assembleRelease
```
Gradle 中间输出为 app/build/outputs/apk/release/app-release.apk;成功后自动交付到 ../bin/apk/,debug 文件增加 -debug 后缀。签名不会自动获得系统应用身份、ROM 白名单或 SELinux 权限;需要与目标 ROM 平台证书及系统预装配置匹配。
本机打包时可使用现有 SDK 的 aapt2(PowerShell 参数需保留引号):
```powershell
gradle :app:assembleRelease '-Pandroid.aapt2FromMavenOverride=F:/AndroidSDK/build-tools/35.0.0/aapt2.exe'
```
## 固定 Agent 测试包(0.1.1)
按当前要求,构建时将现有 config/private/agent.env 中的 ADS_AGENT_TOKEN 写入 Git 忽略的 agent.local.properties,通过 BuildConfig.AGENT_TOKEN 固定在 APK 内。界面已移除令牌输入框,保存配置只保存服务器、设备 ID 和 adbd 端口;旧版加密令牌字段在保存时清理,运行时始终使用内置值。
重新构建仍需本机 agent.local.properties;该文件和签名配置都不得提交。没有新增自动启动或自动开启 adbd 行为,仍需用户点击保存并启动。产物为 ../bin/apk/ads-android-agent-0.1.1-crosshatch.apk,versionCode=2,默认 Crosshatch 签名。
后续 APK 统一交付到仓库 `bin/apk/`,该目录只保存自动生成的 APK,无业务源码且不纳入 Git。
+61
View File
@@ -0,0 +1,61 @@
import java.util.Properties
plugins { id("com.android.application"); id("org.jetbrains.kotlin.android") }
val signingFile = rootProject.file("signing.local.properties")
val crosshatchProperties = Properties().apply {
if (signingFile.isFile) signingFile.inputStream().use { load(it) }
}
fun signingValue(name: String): String = crosshatchProperties.getProperty(name)
?: providers.environmentVariable("ADS_SIGNING_${name.uppercase()}").orNull
?: error("Missing signing property $name. Configure signing.local.properties (Git ignored).")
val agentProperties = Properties().apply {
rootProject.file("agent.local.properties").inputStream().use { load(it) }
}
val agentToken = agentProperties.getProperty("agentToken") ?: error("Missing agentToken in agent.local.properties")
require(agentToken.length >= 32 && agentToken.all { it.code in 33..126 }) { "Invalid Agent token" }
android {
buildFeatures { buildConfig = true }
namespace = "com.ttstd.ads"
compileSdk = 35
defaultConfig {
buildConfigField("String", "AGENT_TOKEN", "\"" + agentToken.replace("\\", "\\\\").replace("\"", "\\\"") + "\"")
applicationId = "com.ttstd.ads"; minSdk = 23; targetSdk = 35; versionCode = 2; versionName = "0.1.1"; ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") } }
signingConfigs {
create("crosshatch") {
storeFile = file(signingValue("storeFile"))
storePassword = signingValue("storePassword")
keyAlias = signingValue("keyAlias")
keyPassword = signingValue("keyPassword")
}
}
buildTypes {
getByName("debug") { signingConfig = signingConfigs.getByName("crosshatch") }
getByName("release") { signingConfig = signingConfigs.getByName("crosshatch"); isMinifyEnabled = false }
}
compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 }
kotlinOptions { jvmTarget = "17" }
packaging { jniLibs.useLegacyPackaging = true }
}
tasks.register("verifyNative") {
doLast {
listOf("arm64-v8a", "armeabi-v7a", "x86_64").forEach {
check(file("src/main/jniLibs/$it/libads_android.so").isFile) { "Missing JNI library for $it. Run scripts/build-native.ps1 first." }
}
}
}
tasks.named("preBuild") { dependsOn("verifyNative") }
// Export deliverables after a successful assembly; bin/apk is Git ignored.
tasks.matching { it.name == "assembleRelease" || it.name == "assembleDebug" }.configureEach {
val variant = if (name == "assembleRelease") "release" else "debug"
doLast {
val source = layout.buildDirectory.file("outputs/apk/$variant/app-$variant.apk").get().asFile
check(source.isFile) { "APK missing: $source" }
copy {
from(source)
into(rootProject.file("../bin/apk"))
rename { "ads-android-agent-${android.defaultConfig.versionName}-crosshatch${if (variant == "debug") "-debug" else ""}.apk" }
}
}
}
@@ -0,0 +1,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
<application android:label="ADS 手机设备端" android:theme="@android:style/Theme.Material.Light.NoActionBar" android:allowBackup="false" android:usesCleartextTraffic="false" android:supportsRtl="true">
<activity android:name=".MainActivity" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
<service android:name=".AgentService" android:exported="false" android:stopWithTask="false" android:foregroundServiceType="specialUse"><property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="User-enabled remote ADB device relay for managed system devices"/></service>
<receiver android:name=".BootReceiver" android:exported="false"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/></intent-filter></receiver>
</application>
</manifest>
@@ -0,0 +1,23 @@
package com.ttstd.ads
import android.content.Context
import org.json.JSONObject
/** Agent credential comes from an ignored build-time file; never print it. */
object AgentConfig {
fun prefs(c: Context) = c.getSharedPreferences("agent", Context.MODE_PRIVATE)
fun save(c: Context, server: String, device: String, port: Int) {
require(device.matches(Regex("[A-Za-z0-9._-]{1,128}"))) { "Invalid device ID" }
require(port in 1..65535) { "Invalid adbd port" }
val uri = java.net.URI(server)
require(uri.scheme == "wss" && !uri.host.isNullOrEmpty() && uri.userInfo == null && uri.query == null && uri.fragment == null) { "Invalid WSS URL" }
check(prefs(c).edit().putString("server", server).putString("device", device).putInt("port", port)
.remove("token").remove("iv").commit()) { "Configuration write failed" }
}
fun json(c: Context): String {
val p = prefs(c)
return JSONObject().put("server", p.getString("server", "wss://ttstd.com/ads"))
.put("device", p.getString("device", "android-phone")).put("port", p.getInt("port", 5555))
.put("token", BuildConfig.AGENT_TOKEN).toString()
}
}
@@ -0,0 +1,19 @@
package com.ttstd.ads
import android.util.Log
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
object AgentLog {
private val lines = ArrayDeque<String>()
@Volatile var status = "未启动"
@Synchronized fun add(stage: String, text: String) {
// Call sites never supply config JSON, credentials, tickets, SDP, or ADB payloads.
val line = "${SimpleDateFormat("HH:mm:ss.SSS", Locale.ROOT).format(Date())} [$stage] ${text.take(1600)}"
Log.i("ADS-Agent", line)
lines.addLast(line)
while (lines.size > 300) lines.removeFirst()
}
@Synchronized fun text(): String = lines.joinToString("\n")
}
@@ -0,0 +1,75 @@
package com.ttstd.ads
import android.app.*
import android.content.*
import android.content.pm.ServiceInfo
import android.os.*
import org.json.JSONObject
class AgentService : Service() {
private lateinit var thread: HandlerThread
private lateinit var worker: Handler
private var started = false
private val poll = object : Runnable {
override fun run() {
if (!started) return
try {
val s = JSONObject(NativeBridge.snapshot())
AgentLog.status = when { !s.optBoolean("running") -> "原生核心已停止"; s.optBoolean("registered") -> "已注册 · 等待/处理远程连接"; else -> "连接中 · 自动重试" }
val logs = s.optJSONArray("logs")
if (logs != null) for (i in 0 until logs.length()) AgentLog.add("RUST", logs.getString(i).trim())
s.optString("error").takeIf { it.isNotEmpty() && it != "null" }?.let { AgentLog.status += " · $it" }
} catch (e: Exception) { AgentLog.add("POLL_FAILED", e.javaClass.simpleName) }
worker.postDelayed(this, 1000)
}
}
override fun onCreate() {
super.onCreate()
thread = HandlerThread("ads-agent-control").apply { start() }; worker = Handler(thread.looper)
AgentLog.add("SERVICE_CREATE", "Android API=${Build.VERSION.SDK_INT}; ABI=${Build.SUPPORTED_ABIS.joinToString()}; no permission requests")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (!AgentConfig.prefs(this).getBoolean("enabled", false)) { stopSelf(); return START_NOT_STICKY }
try { foreground() } catch (e: Exception) {
AgentLog.add("FGS_DENIED", "${e.javaClass.simpleName}: ROM must allow foreground service startup")
stopSelf(); return START_NOT_STICKY
}
worker.post {
if (!started) {
try {
check(NativeBridge.loadError == null) { NativeBridge.loadError!! }
val error = NativeBridge.start(AgentConfig.json(this))
check(error.isEmpty()) { error }
started = true; AgentLog.add("NATIVE_STARTED", "网关已启动;registered 不等于 adbd 已授权;未自动开启 TCP ADB")
worker.post(poll)
} catch (e: Exception) {
AgentLog.status = "启动失败"
AgentLog.add("START_FAILED", if (e is IllegalStateException) e.message ?: "配置或核心错误" else "${e.javaClass.simpleName}: 配置不可用,请重新保存")
stopSelf()
}
}
}
return START_STICKY
}
private fun foreground() {
val manager = getSystemService(NotificationManager::class.java)
if (Build.VERSION.SDK_INT >= 26) manager.createNotificationChannel(NotificationChannel("agent", "ADS 远程调试", NotificationManager.IMPORTANCE_LOW))
val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val builder = if (Build.VERSION.SDK_INT >= 26) Notification.Builder(this, "agent") else Notification.Builder(this)
val notification = builder.setSmallIcon(android.R.drawable.stat_sys_upload).setContentTitle("ADS 远程调试服务")
.setContentText("手机正连接远程调试网关,点此查看或停止").setContentIntent(open).setOngoing(true).build()
if (Build.VERSION.SDK_INT >= 34) startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) else startForeground(1, notification)
}
override fun onDestroy() {
worker.removeCallbacks(poll)
worker.post { if (started) { NativeBridge.stop(); started = false }; AgentLog.status = "已停止"; AgentLog.add("SERVICE_STOP", "数据会话与控制连接已释放"); thread.quitSafely() }
super.onDestroy()
}
override fun onBind(intent: Intent?) = null
companion object {
fun launch(c: Context) {
try { val i = Intent(c, AgentService::class.java); if (Build.VERSION.SDK_INT >= 26) c.startForegroundService(i) else c.startService(i) }
catch (e: Exception) { AgentLog.status = "系统拒绝启动"; AgentLog.add("LAUNCH_DENIED", "${e.javaClass.simpleName}: 检查系统预授权及后台启动策略") }
}
}
}
@@ -0,0 +1,11 @@
package com.ttstd.ads
import android.content.*
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
if (AgentConfig.prefs(context).getBoolean("enabled", false)) {
AgentLog.add("BOOT", "用户已启用远程调试,尝试恢复服务(解锁后启动)")
AgentService.launch(context)
}
}
}
@@ -0,0 +1,47 @@
package com.ttstd.ads
import android.app.Activity
import android.os.*
import android.content.Intent
import android.text.InputType
import android.widget.*
class MainActivity : Activity() {
private val handler = Handler(Looper.getMainLooper())
private lateinit var state: TextView
private lateinit var logs: TextView
private val refresh = object : Runnable {
override fun run() { state.text = AgentLog.status; logs.text = AgentLog.text(); handler.postDelayed(this, 1000) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val p = AgentConfig.prefs(this)
val box = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(24, 24, 24, 24) }
val scroll = ScrollView(this).apply { isFillViewport = true; addView(box) }; setContentView(scroll)
fun label(text: String) { box.addView(TextView(this).apply { this.text = text; textSize = 16f }) }
fun field(title: String, value: String, secret: Boolean = false): EditText {
label(title)
return EditText(this).apply { setSingleLine(true); setText(value); inputType = if (secret) InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_CLASS_TEXT; box.addView(this) }
}
label("ADS · 手机直接接入远程调试")
label("不需要 USB 线。ROM 必须预先允许本机 adbd 接入和后台运行。本应用不申请权限、不执行提权。")
val server = field("控制中心", p.getString("server", "wss://ttstd.com/ads")!!)
val device = field("设备 ID", p.getString("device", "android-phone")!!)
val port = field("本机 adbd 端口(仅连接 127.0.0.1)", p.getInt("port", 5555).toString())
port.inputType = InputType.TYPE_CLASS_NUMBER
label("Agent 令牌已内置,无需填写")
box.addView(Button(this).apply { text = "保存并启动(改配置前先停止)"; setOnClickListener {
try {
AgentConfig.save(this@MainActivity, server.text.toString().trim(), device.text.toString().trim(), port.text.toString().toInt())
p.edit().putBoolean("enabled", true).apply(); AgentService.launch(this@MainActivity)
} catch (e: Exception) { AgentLog.add("CONFIG_INVALID", if (e is IllegalArgumentException) "设备 ID / WSS / 令牌 / 端口格式错误" else "${e.javaClass.simpleName}: 无法保存配置") }
} })
box.addView(Button(this).apply { text = "停止并关闭开机恢复"; setOnClickListener {
p.edit().putBoolean("enabled", false).commit(); stopService(Intent(this@MainActivity, AgentService::class.java))
AgentLog.status = "停止中"; AgentLog.add("USER_STOP", "已关闭开机恢复")
} })
state = TextView(this).also { box.addView(it) }
logs = TextView(this).apply { typeface = android.graphics.Typeface.MONOSPACE; textSize = 12f; setTextIsSelectable(true); box.addView(this) }
}
override fun onStart() { super.onStart(); handler.post(refresh) }
override fun onStop() { handler.removeCallbacks(refresh); super.onStop() }
}
@@ -0,0 +1,9 @@
package com.ttstd.ads
/** JNI calls stay on the service worker; polling returns bounded, ticket-free native logs. */
object NativeBridge {
val loadError: String? = try { System.loadLibrary("ads_android"); null } catch (e: UnsatisfiedLinkError) { "JNI_LOAD_FAILED: ${e.javaClass.simpleName}; check APK ABI and native libraries" }
external fun start(config: String): String
external fun stop()
external fun snapshot(): String
}
+4
View File
@@ -0,0 +1,4 @@
plugins {
id("com.android.application") version "8.9.2" apply false
id("org.jetbrains.kotlin.android") version "2.1.20" apply false
}
+4
View File
@@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
org.gradle.workers.max=2
android.useAndroidX=false
kotlin.code.style=official
+2910
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -0,0 +1,16 @@
[workspace]
[package]
name = "ads-android"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
ads-core = { path = "../../crates/ads-core" }
anyhow = "1"
jni = "0.21"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["fmt"] }
+231
View File
@@ -0,0 +1,231 @@
use ads_core::{valid_device_id, validate_token, NetworkArgs};
use jni::{
objects::{JObject, JString},
sys::jstring,
JNIEnv,
};
use serde::Deserialize;
use std::{
collections::VecDeque,
io::Write,
sync::{Arc, Mutex, Once, OnceLock},
thread,
};
// Reuse the actual v1/v2 gateway (including P2P, relay fallback, bounded streams).
#[path = "../../../agent/src/gateway.rs"]
mod gateway;
#[derive(Deserialize)]
struct Config {
server: String,
token: String,
device: String,
port: u16,
}
impl Config {
fn validate(&self) -> anyhow::Result<()> {
anyhow::ensure!(
valid_device_id(&self.device),
"device ID must be 1-128 ASCII letters/digits/._-"
);
validate_token(&self.token)?;
anyhow::ensure!(self.port > 0, "adbd port must be nonzero");
self.network().url("/v1/agent", &[])?;
Ok(())
}
fn network(&self) -> NetworkArgs {
NetworkArgs {
server: self.server.clone(),
connect_address: None,
allow_insecure: false,
}
}
}
struct Worker {
stop: tokio::sync::oneshot::Sender<()>,
join: thread::JoinHandle<()>,
health: gateway::WorkerHealth,
}
static WORKER: Mutex<Option<Worker>> = Mutex::new(None);
static LOGS: OnceLock<Mutex<VecDeque<String>>> = OnceLock::new();
fn logs() -> &'static Mutex<VecDeque<String>> {
LOGS.get_or_init(|| Mutex::new(VecDeque::new()))
}
struct LogWriter;
impl Write for LogWriter {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
let mut q = logs().lock().unwrap_or_else(|e| e.into_inner());
q.push_back(String::from_utf8_lossy(b).into_owned());
while q.len() > 300 {
q.pop_front();
}
Ok(b.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn start(config: Config) -> anyhow::Result<()> {
config.validate()?;
let mut guard = WORKER.lock().unwrap_or_else(|e| e.into_inner());
anyhow::ensure!(
guard.is_none(),
"agent already running; stop before changing config"
);
static INIT: Once = Once::new();
INIT.call_once(|| {
let _ = tracing_subscriber::fmt()
.with_ansi(false)
.with_max_level(tracing::Level::INFO)
.with_writer(|| LogWriter)
.try_init();
});
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()?;
let health = Arc::new(Mutex::new(gateway::Health::default()));
let state = health.clone();
let (stop, rx) = tokio::sync::oneshot::channel();
let args = Arc::new(gateway::Gateway {
network: config.network(),
token: config.token,
device: config.device,
target: Some(format!("127.0.0.1:{}", config.port)),
adb_serial: None,
adb_server: String::new(),
device_port: config.port,
});
let join = thread::spawn(move || {
runtime.block_on(async move {
let work = async {
tracing::info!("ANDROID_START: phone-local adbd and relay worker starting");
match ads_core::tcp_connect(args.target.as_deref().unwrap()).await {
Ok(s) => { drop(s); tracing::info!("ADBD_PROBE_OK: loopback reachable; ADB authentication still required"); }
Err(_) => tracing::warn!("ADBD_PROBE_FAILED: check ROM adbd listener and SELinux; no permission requests or setprop performed"),
}
gateway::run(args, Some(state)).await;
};
tokio::select! { _ = work => {}, _ = rx => {} }
tracing::info!("ANDROID_STOP: control and data sessions cancelled");
});
runtime.shutdown_timeout(std::time::Duration::from_secs(2));
});
*guard = Some(Worker { stop, join, health });
Ok(())
}
fn stop() {
let mut guard = WORKER.lock().unwrap_or_else(|e| e.into_inner());
if let Some(w) = guard.take() {
let _ = w.stop.send(());
let _ = w.join.join();
}
}
fn snapshot() -> String {
let guard = WORKER.lock().unwrap_or_else(|e| e.into_inner());
let (running, registered, error) = match guard.as_ref() {
Some(w) => {
let s = w.health.lock().unwrap_or_else(|e| e.into_inner());
(!w.join.is_finished(), s.connected, s.last_error.clone())
}
None => (false, false, None),
};
let lines: Vec<_> = logs()
.lock()
.unwrap_or_else(|e| e.into_inner())
.drain(..)
.collect();
serde_json::json!({"running":running,"registered":registered,"error":error,"logs":lines})
.to_string()
}
fn java_string(env: &mut JNIEnv, value: String) -> jstring {
env.new_string(value)
.map(|v| v.into_raw())
.unwrap_or(std::ptr::null_mut())
}
#[no_mangle]
pub extern "system" fn Java_com_ttstd_ads_NativeBridge_start(
mut env: JNIEnv,
_this: JObject,
json: JString,
) -> jstring {
let result =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> anyhow::Result<()> {
let raw: String = env.get_string(&json)?.into();
let c = serde_json::from_str::<Config>(&raw)
.map_err(|_| anyhow::anyhow!("invalid configuration JSON"))?;
start(c)
}));
let message = match result {
Ok(Ok(())) => String::new(),
Ok(Err(e)) => format!("{e:#}"),
Err(_) => "native start failed".into(),
};
java_string(&mut env, message)
}
#[no_mangle]
pub extern "system" fn Java_com_ttstd_ads_NativeBridge_stop(_env: JNIEnv, _this: JObject) {
stop();
}
#[no_mangle]
pub extern "system" fn Java_com_ttstd_ads_NativeBridge_snapshot(
mut env: JNIEnv,
_this: JObject,
) -> jstring {
java_string(&mut env, snapshot())
}
#[cfg(test)]
mod tests {
use super::*;
fn config() -> Config {
Config {
server: "wss://ttstd.com/ads".into(),
token: "x".repeat(32),
device: "android-test".into(),
port: 5555,
}
}
#[test]
fn validates_prefix() {
let c = config();
c.validate().unwrap();
assert_eq!(
c.network().url("/v1/agent", &[]).unwrap().path(),
"/ads/v1/agent"
);
}
#[test]
fn rejects_invalid_inputs() {
let mut c = config();
c.port = 0;
assert!(c.validate().is_err());
c = config();
c.server = "ws://example.com".into();
assert!(c.validate().is_err());
c = config();
c.device = "bad/device".into();
assert!(c.validate().is_err());
c = config();
c.token = "short".into();
assert!(c.validate().is_err());
}
#[test]
fn worker_lifecycle_and_secret_free_status() {
stop();
let mut c = config();
c.server = "wss://127.0.0.1:1".into();
c.port = 1;
start(c).unwrap();
let s = snapshot();
assert!(s.contains("\"running\":true"));
assert!(!s.contains(&"x".repeat(32)));
assert!(
start(config()).is_err(),
"must not create duplicate workers"
);
let began = std::time::Instant::now();
stop();
assert!(began.elapsed() < std::time::Duration::from_secs(3));
assert!(snapshot().contains("\"running\":false"));
stop(); // idempotent
}
}
+26
View File
@@ -0,0 +1,26 @@
param([string]$Ndk = $env:ANDROID_NDK_HOME)
$ErrorActionPreference = 'Stop'
if (-not $Ndk -or -not (Test-Path $Ndk)) { throw 'Set ANDROID_NDK_HOME to an installed NDK (r28+ recommended for 16 KB pages).' }
$project = Split-Path $PSScriptRoot -Parent
$manifest = Join-Path $project 'native/Cargo.toml'
$targets = @(
@{Rust='aarch64-linux-android'; Abi='arm64-v8a'; Clang='aarch64-linux-android23-clang.cmd'},
@{Rust='armv7-linux-androideabi'; Abi='armeabi-v7a'; Clang='armv7a-linux-androideabi23-clang.cmd'},
@{Rust='x86_64-linux-android'; Abi='x86_64'; Clang='x86_64-linux-android23-clang.cmd'}
)
foreach ($t in $targets) {
$linker = Join-Path $Ndk "toolchains/llvm/prebuilt/windows-x86_64/bin/$($t.Clang)"
if (-not (Test-Path $linker)) { throw "Missing NDK clang: $linker" }
$key = 'CARGO_TARGET_' + $t.Rust.Replace('-', '_').ToUpper() + '_LINKER'
[Environment]::SetEnvironmentVariable($key, $linker, 'Process')
$ccKey = 'CC_' + $t.Rust.Replace('-', '_')
[Environment]::SetEnvironmentVariable($ccKey, $linker, 'Process')
$ar = Join-Path $Ndk 'toolchains/llvm/prebuilt/windows-x86_64/bin/llvm-ar.exe'
[Environment]::SetEnvironmentVariable(('AR_' + $t.Rust.Replace('-', '_')), $ar, 'Process')
[Environment]::SetEnvironmentVariable(($key.Replace('_LINKER', '_RUSTFLAGS')), '-C link-arg=-Wl,-z,max-page-size=16384', 'Process')
cargo build --manifest-path $manifest --release --target $t.Rust --locked
if ($LASTEXITCODE -ne 0) { throw "Rust build failed: $($t.Rust). Install rust target separately if missing." }
$out = Join-Path $project "app/src/main/jniLibs/$($t.Abi)"
New-Item -ItemType Directory -Force $out | Out-Null
Copy-Item -LiteralPath (Join-Path $project "native/target/$($t.Rust)/release/libads_android.so") -Destination (Join-Path $out 'libads_android.so')
}
+4
View File
@@ -0,0 +1,4 @@
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } }
rootProject.name = "AdsAndroidAgent"
include(":app")
+5
View File
@@ -0,0 +1,5 @@
# Copy to signing.local.properties (Git ignored); do not commit real passwords.
storeFile=D:/TongTongStudio/TTSTD/AospCrosshatch.keystore
storePassword=REPLACE_LOCALLY
keyAlias=AospCrosshatch
keyPassword=REPLACE_LOCALLY
+45 -1
View File
@@ -19,12 +19,24 @@ internal static class Program
Thread.Sleep(Timeout.Infinite);
return 0;
}
if (args.Contains("--encoding-child"))
{
var bytes=System.Text.Encoding.UTF8.GetBytes("连接已建立:中文日志 ✓ 📱\n");
Console.OpenStandardOutput().Write(bytes);Console.OpenStandardError().Write(bytes);
return 0;
}
if (args.Contains("--encoding-input"))
{
using var reader=new StreamReader(Console.OpenStandardInput(),System.Text.Encoding.UTF8);
var bytes=System.Text.Encoding.UTF8.GetBytes(reader.ReadToEnd());Console.OpenStandardOutput().Write(bytes);
return 0;
}
AppBuilder.Configure<App>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
using var finished = new CancellationTokenSource();
Exception? failure = null;
Dispatcher.UIThread.Post(async () =>
{
try { if (args.Contains("--agents")) await RunAgentsAsync(args.Contains("--local-agent")); else if (args.Contains("--multi")) await RunMultiAsync(args.Contains("--usb")); else await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
try { if(args.Contains("--theme-preview")) await PreviewThemeAsync(); else if (args.Contains("--agents")) await RunAgentsAsync(args.Contains("--local-agent")); else if (args.Contains("--multi")) await RunMultiAsync(args.Contains("--usb")); else await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
catch (Exception error) { failure = error; }
finally { finished.Cancel(); }
});
@@ -33,6 +45,38 @@ internal static class Program
return 0;
}
private static async Task PreviewThemeAsync()
{
var root=DesktopPaths.ProjectRoot()!;
using var vm=new MainViewModel(Path.Combine(root,"work","semi-preview"),backgroundMonitoring:false,loadLocalCredentials:false);
vm.AutoRefresh=false;vm.AgentManager.AutoRefresh=false;
vm.Devices.Add(new DeviceItem("home-phone",false,false,ComputerName:"家里的 Windows",AgentId:"home-pc"));
vm.Devices.Add(new DeviceItem("pixel-test",false,false,ComputerName:"Ubuntu 实验室",AgentId:"ubuntu-224"));
vm.Devices.Add(new DeviceItem("android-phone",true,false,ComputerName:"办公电脑",AgentId:"office-pc"));
vm.Logs.Add("13:20:10 已连接设备 · 中文日志正常显示 ✓ 📱");
vm.Logs.Add("13:20:11 设备离线,等待自动重连。拒绝访问,请检查权限。");
vm.AgentManager.RemoteLogText="[INFO] 设备发现完成:3 台手机。\n[INFO] 连接已建立:中文日志正常。";
var window=new MainWindow {DataContext=vm};window.Show();
try {
var tabs=window.FindControl<TabControl>("MainTabs")!;
foreach(var dark in new[]{false,true}) {
var theme=dark?"dark":"light";
window.FindControl<ToggleSwitch>("ThemeSwitch")!.IsChecked=dark;
Require(Application.Current!.RequestedThemeVariant==(dark?Avalonia.Styling.ThemeVariant.Dark:Avalonia.Styling.ThemeVariant.Light),"Theme switch did not update the application");
for(var page=0;page<4;page++) {
tabs.SelectedIndex=page;window.Width=1240;window.Height=880;
await Task.Delay(220);
using var frame=window.CaptureRenderedFrame();
Require(frame!=null,"Semi frame was not rendered");
frame!.Save(Path.Combine(root,"work",$"semi-{theme}-{page}.png"));
}
tabs.SelectedIndex=0;window.Width=980;window.Height=700;await Task.Delay(220);
using var compact=window.CaptureRenderedFrame();compact!.Save(Path.Combine(root,"work",$"semi-{theme}-compact.png"));
}
Console.WriteLine("PASS: Semi light/dark pages and 980x700 compact layout rendered");
} finally { await vm.ShutdownAsync();window.Close(); }
}
private static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
@@ -0,0 +1,36 @@
using System.Text;
using System.Diagnostics;
using Ads.Desktop;
using Xunit;
namespace Ads.Desktop.Tests;
public class ProcessEncodingTests {
const string Text="连接已建立:中文日志 ✓ 📱";
static ProcessStartInfo Child(string argument) {
var configuration=new DirectoryInfo(AppContext.BaseDirectory).Parent!.Name;
var file=Path.Combine(DesktopPaths.ProjectRoot()!,"desktop","Ads.Desktop.Smoke","bin",configuration,"net8.0","Ads.Desktop.Smoke.dll");
return ProcessTools.CreateStartInfo("dotnet",[file,argument]);
}
[Fact] public async Task CapturedUnicodeOutputAndErrorsAreUtf8() {
var info=Child("--encoding-child");
Assert.Equal(65001,info.StandardOutputEncoding!.CodePage);Assert.Equal(65001,info.StandardErrorEncoding!.CodePage);
var result=await ProcessTools.RunAsync(info);
Assert.Equal(0,result.ExitCode);Assert.Equal(Text,result.Output.Trim());Assert.Equal(Text,result.Error.Trim());
}
[Fact] public async Task StreamingUnicodeLogsAreUtf8() {
using var process=new Process {StartInfo=Child("--encoding-child")};
var output=new TaskCompletionSource<string>();var error=new TaskCompletionSource<string>();
process.OutputDataReceived+=(_,e)=>{if(e.Data!=null)output.TrySetResult(e.Data);};
process.ErrorDataReceived+=(_,e)=>{if(e.Data!=null)error.TrySetResult(e.Data);};
process.Start();process.BeginOutputReadLine();process.BeginErrorReadLine();
await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10));
Assert.Equal(Text,await output.Task.WaitAsync(TimeSpan.FromSeconds(3)));Assert.Equal(Text,await error.Task.WaitAsync(TimeSpan.FromSeconds(3)));
}
[Fact] public async Task AgentJsonInputRetainsChinese() {
var info=Child("--encoding-input");info.RedirectStandardInput=true;info.StandardInputEncoding=new UTF8Encoding(false);
using var process=Process.Start(info)!;
await process.StandardInput.WriteAsync("{\"name\":\"家里的电脑\"}");process.StandardInput.Close();
var output=process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10));
Assert.Equal("{\"name\":\"家里的电脑\"}",await output);
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><Version>0.2.2</Version><OutputType>WinExe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><PackageReference Include="Avalonia.Desktop" Version="11.3.8"/><PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.8"/><PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/></ItemGroup>
<PropertyGroup><Version>0.2.3</Version><OutputType>WinExe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><PackageReference Include="Avalonia.Desktop" Version="11.3.8"/><PackageReference Include="Semi.Avalonia" Version="11.3.7.3"/><PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/></ItemGroup>
<ItemGroup><AvaloniaResource Include="Assets/**"/></ItemGroup></Project>
+6 -11
View File
@@ -1,9 +1,4 @@
<UserControl xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="Ads.Desktop.AgentManagementView">
<UserControl.Styles>
<Style Selector="Border.agentCard"><Setter Property="Background" Value="#192230"/><Setter Property="CornerRadius" Value="10"/><Setter Property="Padding" Value="16"/></Style>
<Style Selector="Button"><Setter Property="Padding" Value="12,8"/><Setter Property="Margin" Value="0,0,8,6"/></Style>
<Style Selector="TextBox"><Setter Property="Margin" Value="0,4,0,10"/></Style>
</UserControl.Styles>
<Grid RowDefinitions="Auto,*,Auto" Margin="0,14,0,0">
<StackPanel>
<WrapPanel><CheckBox x:Name="LocalAgentMode" Content="管理本机 Agent" IsChecked="{Binding LocalMode}" IsEnabled="{Binding !IsBusy}" Margin="0,0,20,8"/><CheckBox Content="自动刷新" IsChecked="{Binding AutoRefresh}"/><Button x:Name="RefreshAgentsButton" Content="刷新 Agent" Command="{Binding RefreshAgentsCommand}" IsEnabled="{Binding !IsBusy}" Margin="20,0,0,10"/></WrapPanel>
@@ -11,9 +6,9 @@
<StackPanel IsVisible="{Binding LocalMode}"><TextBlock Text="本机配置路径"/><Grid ColumnDefinitions="*,Auto"><TextBox Text="{Binding ConfigPath}"/><Button Grid.Column="1" Content="选择" Click="ChooseConfigClick"/></Grid><WrapPanel><Button Content="启动后台 Agent" Command="{Binding StartLocalCommand}"/><Button Content="安装开机服务" Command="{Binding InstallServiceCommand}"/></WrapPanel></StackPanel>
</StackPanel>
<Grid Grid.Row="1" ColumnDefinitions="300,*">
<Border Classes="agentCard" Margin="0,0,14,0"><Grid RowDefinitions="Auto,*"><TextBlock Text="Agent / 被控电脑" FontSize="18" FontWeight="SemiBold"/><ListBox x:Name="AgentList" Grid.Row="1" ItemsSource="{Binding Agents}" SelectedItem="{Binding SelectedAgent}" Margin="0,10,0,0"><ListBox.ItemTemplate><DataTemplate><StackPanel Spacing="5" Margin="4,8"><TextBlock Text="{Binding Id}" FontSize="16"/><TextBlock Text="{Binding Description}" TextWrapping="Wrap" Foreground="#A8B7CC"/></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox></Grid></Border>
<Border Classes="agentCard" Margin="0,0,14,0"><Grid RowDefinitions="Auto,*"><TextBlock Text="Agent / 被控电脑" FontSize="18" FontWeight="SemiBold"/><ListBox x:Name="AgentList" Grid.Row="1" ItemsSource="{Binding Agents}" SelectedItem="{Binding SelectedAgent}" Margin="0,10,0,0"><ListBox.ItemTemplate><DataTemplate><StackPanel Spacing="5" Margin="4,8"><TextBlock Text="{Binding Id}" FontSize="16"/><TextBlock Text="{Binding Description}" TextWrapping="Wrap" Foreground="{DynamicResource SemiColorText2}"/></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox></Grid></Border>
<ScrollViewer Grid.Column="1"><StackPanel Spacing="14">
<Border Classes="agentCard"><StackPanel Spacing="10"><TextBlock Text="{Binding SelectedAgentDetails}" TextWrapping="Wrap" Foreground="#66D9C0"/><WrapPanel><Button x:Name="LoadAgentConfigButton" Content="读取配置" Command="{Binding LoadConfigCommand}"/><Button Content="重启 Agent" Command="{Binding RestartAgentCommand}"/></WrapPanel><TextBlock Text="重启由监督进程执行,设备连接会短暂中断。" FontSize="12" Foreground="#A8B7CC"/></StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="10"><TextBlock Text="{Binding SelectedAgentDetails}" TextWrapping="Wrap" Foreground="{DynamicResource SemiColorPrimary}"/><WrapPanel><Button x:Name="LoadAgentConfigButton" Content="读取配置" Command="{Binding LoadConfigCommand}"/><Button Content="重启 Agent" Command="{Binding RestartAgentCommand}"/></WrapPanel><TextBlock Text="重启由监督进程执行,设备连接会短暂中断。" FontSize="12" Foreground="{DynamicResource SemiColorText2}"/></StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8">
<Button Content="发现 ADB 设备" Command="{Binding DiscoverDevicesCommand}" HorizontalAlignment="Left"/>
<ListBox ItemsSource="{Binding DiscoveredDevices}" SelectedItem="{Binding SelectedDiscoveredDevice}" MaxHeight="160"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Description}" TextWrapping="Wrap"/></DataTemplate></ListBox.ItemTemplate></ListBox>
@@ -21,15 +16,15 @@
<ListBox x:Name="ManagedDevicesList" ItemsSource="{Binding AgentDevices}" SelectedItem="{Binding SelectedManagedDevice}" MinHeight="70" MaxHeight="180"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Description}" TextWrapping="Wrap" Margin="3,7"/></DataTemplate></ListBox.ItemTemplate></ListBox>
<WrapPanel><Button Content="启用" Command="{Binding EnableDeviceCommand}"/><Button Content="停用" Command="{Binding DisableDeviceCommand}"/><Button Content="移除配置" Command="{Binding RemoveDeviceCommand}"/></WrapPanel>
<Grid ColumnDefinitions="*,*"><StackPanel><TextBlock Text="设备 ID"/><TextBox Text="{Binding DeviceId}" Watermark="home-phone"/></StackPanel><StackPanel Grid.Column="1" Margin="12,0,0,0"><TextBlock Text="手机 adbd 地址"/><TextBox Text="{Binding Target}" Watermark="192.168.1.10:5555"/></StackPanel></Grid>
<Expander Header="通过已有 ADB server 接入"><StackPanel><TextBlock Text="ADB 序列号(与手机地址二选一)"/><TextBox Text="{Binding AdbSerial}"/><TextBlock Text="ADB server 地址(留空使用 Agent 默认值)"/><TextBox Text="{Binding AdbServer}" Watermark="127.0.0.1:5037"/><TextBlock Text="此模式仍要求手机启用 TCP adbd。" Foreground="#A8B7CC"/></StackPanel></Expander>
<Expander Header="通过已有 ADB server 接入"><StackPanel><TextBlock Text="ADB 序列号(与手机地址二选一)"/><TextBox Text="{Binding AdbSerial}"/><TextBlock Text="ADB server 地址(留空使用 Agent 默认值)"/><TextBox Text="{Binding AdbServer}" Watermark="127.0.0.1:5037"/><TextBlock Text="此模式仍要求手机启用 TCP adbd。" Foreground="{DynamicResource SemiColorText2}"/></StackPanel></Expander>
<Button x:Name="AddManagedDeviceButton" Content="添加手机" Command="{Binding AddDeviceCommand}" HorizontalAlignment="Left"/>
</StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8"><TextBlock Text="Agent 配置" FontSize="18" FontWeight="SemiBold"/><TextBlock Text="修改设备或地址会重建受影响的连接;Agent ID 保持固定。" Foreground="#A8B7CC" TextWrapping="Wrap"/><TextBox x:Name="AgentConfigBox" Text="{Binding ConfigJson}" AcceptsReturn="True" FontFamily="Cascadia Mono,Consolas" FontSize="12" MinHeight="200" MaxHeight="380" ScrollViewer.VerticalScrollBarVisibility="Auto"/><Button Content="保存并应用配置" Command="{Binding SaveConfigCommand}" HorizontalAlignment="Left"/>
<Border Classes="agentCard"><StackPanel Spacing="8"><TextBlock Text="Agent 配置" FontSize="18" FontWeight="SemiBold"/><TextBlock Text="修改设备或地址会重建受影响的连接;Agent ID 保持固定。" Foreground="{DynamicResource SemiColorText2}" TextWrapping="Wrap"/><TextBox x:Name="AgentConfigBox" Text="{Binding ConfigJson}" AcceptsReturn="True" FontFamily="Cascadia Mono,Consolas,Microsoft YaHei UI,Noto Sans CJK SC" FontSize="12" MinHeight="200" MaxHeight="380" ScrollViewer.VerticalScrollBarVisibility="Auto"/><Button Content="保存并应用配置" Command="{Binding SaveConfigCommand}" HorizontalAlignment="Left"/>
<StackPanel IsVisible="{Binding LocalMode}"><TextBlock Text="首次设置:填写上方配置及设备端凭据后初始化,再启动后台 Agent。" TextWrapping="Wrap"/><TextBlock Text="{Binding EnrollmentPath}" TextWrapping="Wrap"/><TextBox Text="{Binding EnrollmentToken}" PasswordChar="●" Watermark="ADS_AGENT_TOKEN"/><WrapPanel><Button Content="导入 agent.env" Click="ImportEnrollmentClick"/><Button Content="初始化本机配置" Command="{Binding InitializeLocalCommand}"/></WrapPanel></StackPanel>
</StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8"><WrapPanel><Button Content="读取日志" Command="{Binding ReadLogsCommand}"/><CheckBox Content="持续跟随日志" IsChecked="{Binding FollowLogs}"/></WrapPanel><TextBox x:Name="AgentLogsBox" Text="{Binding RemoteLogText}" IsReadOnly="True" AcceptsReturn="True" FontFamily="Cascadia Mono,Consolas" FontSize="12" Height="200" ScrollViewer.VerticalScrollBarVisibility="Auto"/></StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8"><WrapPanel><Button Content="读取日志" Command="{Binding ReadLogsCommand}"/><CheckBox Content="持续跟随日志" IsChecked="{Binding FollowLogs}"/></WrapPanel><TextBox x:Name="AgentLogsBox" Text="{Binding RemoteLogText}" IsReadOnly="True" AcceptsReturn="True" FontFamily="Cascadia Mono,Consolas,Microsoft YaHei UI,Noto Sans CJK SC" FontSize="12" Height="200" ScrollViewer.VerticalScrollBarVisibility="Auto"/></StackPanel></Border>
</StackPanel></ScrollViewer>
</Grid>
<TextBlock Grid.Row="2" x:Name="AgentNotice" Text="{Binding Notice}" TextWrapping="Wrap" Foreground="#A8B7CC" Margin="0,12,0,0"/>
<TextBlock Grid.Row="2" x:Name="AgentNotice" Text="{Binding Notice}" TextWrapping="Wrap" Foreground="{DynamicResource SemiColorText2}" Margin="0,12,0,0"/>
</Grid>
</UserControl>
@@ -136,7 +136,7 @@ public partial class AgentManagementViewModel : ObservableObject, IDisposable
private async Task<JsonElement> LocalRequestAsync(object request)
{
var executable=DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl");
var info=ProcessTools.CreateStartInfo(executable,["--json","--config",ConfigPath,"request"]);info.RedirectStandardInput=true;
var info=ProcessTools.CreateStartInfo(executable,["--json","--config",ConfigPath,"request"]);info.RedirectStandardInput=true;info.StandardInputEncoding=new System.Text.UTF8Encoding(false);
using var process=Process.Start(info) ?? throw new InvalidOperationException("adsctl 无法启动。");
var output=process.StandardOutput.ReadToEndAsync();var error=process.StandardError.ReadToEndAsync();
await process.StandardInput.WriteAsync(JsonSerializer.Serialize(request));process.StandardInput.Close();
@@ -219,7 +219,7 @@ public partial class AgentManagementViewModel : ObservableObject, IDisposable
if(!File.Exists(ConfigPath))throw new InvalidOperationException("请先导入 agent.env 并初始化本机配置,再启动 Agent。");
try { await LocalRequestAsync(new{op="status"});Notice="本机 Agent 已在运行。";return; } catch(InvalidOperationException){}
var info=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-agent"),"ads-agent"),["--quiet","--supervise","--config",ConfigPath]);
info.RedirectStandardOutput=false;info.RedirectStandardError=false;
info.RedirectStandardOutput=false;info.RedirectStandardError=false;info.StandardOutputEncoding=null;info.StandardErrorEncoding=null;
using var process=Process.Start(info) ?? throw new InvalidOperationException("Agent 启动失败。");
await Task.Delay(700,lifetime.Token);await RefreshCoreAsync();Notice="后台 Agent 已启动,退出托盘不会停止它。";
});
+5 -2
View File
@@ -1,3 +1,6 @@
<Application xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="Ads.Desktop.App" RequestedThemeVariant="Dark">
<Application.Styles><FluentTheme/></Application.Styles>
<Application xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:semi="https://irihi.tech/semi" x:Class="Ads.Desktop.App" RequestedThemeVariant="Light">
<Application.Styles>
<semi:SemiTheme Locale="zh-CN"/>
<StyleInclude Source="avares://Ads.Desktop/WorkbenchStyles.axaml"/>
</Application.Styles>
</Application>
+1 -1
View File
@@ -18,7 +18,7 @@ public partial class App : Application
Window window;
if(localAgentMode) {
vm.AgentManager.LocalMode=true;vm.AgentManager.StartMonitoring();
window=new Window {Title="ADS · 被控端 Agent 管理",Width=1100,Height=850,MinWidth=900,MinHeight=650,Background=Avalonia.Media.Brush.Parse("#10151F"),Content=new AgentManagementView{DataContext=vm.AgentManager,Margin=new Avalonia.Thickness(22)}};
window=new Window {Title="ADS · 被控端 Agent 管理",Width=1100,Height=850,MinWidth=900,MinHeight=650,Content=new AgentManagementView{DataContext=vm.AgentManager,Margin=new Avalonia.Thickness(22)}};
} else window = new MainWindow { DataContext = vm };
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
+20 -27
View File
@@ -1,36 +1,29 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Ads.Desktop"
x:Class="Ads.Desktop.MainWindow" Title="ADS · 公网设备工作台"
Width="1240" Height="880" MinWidth="980" MinHeight="700" Background="#10151F">
<Window.Styles>
<Style Selector="TextBox"><Setter Property="Margin" Value="0,5,0,12"/></Style>
<Style Selector="Button"><Setter Property="Padding" Value="15,10"/><Setter Property="Margin" Value="0,0,8,8"/></Style>
<Style Selector="TextBlock.label"><Setter Property="Foreground" Value="#9CAFC7"/></Style>
<Style Selector="TextBlock.section"><Setter Property="FontSize" Value="18"/><Setter Property="FontWeight" Value="SemiBold"/></Style>
<Style Selector="Border.card"><Setter Property="Background" Value="#192230"/><Setter Property="CornerRadius" Value="12"/><Setter Property="Padding" Value="20"/></Style>
</Window.Styles>
<Grid RowDefinitions="Auto,*,Auto" Margin="26">
Width="1240" Height="880" MinWidth="980" MinHeight="700" Background="{DynamicResource SemiColorBackground0}">
<Grid RowDefinitions="Auto,*,Auto" Margin="24">
<Grid ColumnDefinitions="*,Auto" Margin="0,0,0,20">
<StackPanel Spacing="5">
<TextBlock Text="ANDROID DEVICE STREAMING" Foreground="#66D9C0" FontSize="11" LetterSpacing="3"/>
<TextBlock Text="ANDROID DEVICE STREAMING" Foreground="{DynamicResource SemiColorPrimary}" FontSize="11" LetterSpacing="3"/>
<TextBlock Text="公网设备工作台" FontSize="29" FontWeight="Bold"/>
<TextBlock Text="连接远程手机,在本机调试与控制" Classes="label"/>
</StackPanel>
<StackPanel Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" Spacing="8">
<Border Height="3" HorizontalAlignment="Stretch"><ProgressBar IsIndeterminate="True" IsVisible="{Binding IsRefreshing}" Height="3"/></Border>
<TextBlock x:Name="RelayStatusText" Text="{Binding RelayStatus}" HorizontalAlignment="Right" Foreground="#66D9C0"/>
<StackPanel Orientation="Horizontal"><Button x:Name="RefreshButton" Content="刷新设备" Command="{Binding RefreshCommand}"/><Button Content="保存配置" Command="{Binding SaveCommand}"/></StackPanel>
<TextBlock x:Name="RelayStatusText" Text="{Binding RelayStatus}" HorizontalAlignment="Right" Foreground="{DynamicResource SemiColorPrimary}"/>
<StackPanel Orientation="Horizontal"><ToggleSwitch x:Name="ThemeSwitch" OnContent="深色" OffContent="浅色" IsChecked="False" IsCheckedChanged="ThemeChanged" Margin="0,0,16,8"/><Button x:Name="RefreshButton" Content="刷新设备" Command="{Binding RefreshCommand}"/><Button Content="保存配置" Command="{Binding SaveCommand}"/></StackPanel>
</StackPanel>
</Grid>
<TabControl x:Name="MainTabs" Grid.Row="1">
<TabControl x:Name="MainTabs" Classes="workbench" TabStripPlacement="Left" Grid.Row="1">
<TabItem Header="设备与连接">
<Grid ColumnDefinitions="320,*" Margin="0,16,0,0">
<Grid ColumnDefinitions="270,*" Margin="0,16,0,0">
<Border Classes="card" Margin="0,0,16,0">
<Grid RowDefinitions="Auto,*,Auto,Auto,Auto">
<TextBlock Text="在线设备" Classes="section"/>
<ListBox x:Name="DeviceList" Grid.Row="1" ItemsSource="{Binding Devices}" SelectedItem="{Binding SelectedDevice}" Margin="0,14,0,12" Background="Transparent">
<ListBox.ItemTemplate><DataTemplate><StackPanel Margin="5,10" Spacing="6"><TextBlock Text="{Binding Id}" FontSize="17" TextWrapping="Wrap"/><TextBlock Text="{Binding ComputerLabel}" Classes="label" TextWrapping="Wrap"/><TextBlock Text="{Binding Description}" Classes="label" TextWrapping="Wrap"/></StackPanel></DataTemplate></ListBox.ItemTemplate>
</ListBox>
<TextBlock Grid.Row="2" Text="{Binding ConnectionSummary}" Foreground="#66D9C0" Margin="0,0,0,8" TextWrapping="Wrap"/>
<TextBlock Grid.Row="2" Text="{Binding ConnectionSummary}" Foreground="{DynamicResource SemiColorPrimary}" Margin="0,0,0,8" TextWrapping="Wrap"/>
<TextBlock Grid.Row="3" Text="{Binding DeviceSummary}" Classes="label" TextWrapping="Wrap"/>
<CheckBox Grid.Row="4" Content="自动刷新设备列表" IsChecked="{Binding AutoRefresh}" Margin="0,12,0,0"/>
</Grid>
@@ -39,15 +32,15 @@
<StackPanel Spacing="14">
<Border Classes="card">
<StackPanel Spacing="12">
<Grid ColumnDefinitions="*,Auto"><TextBlock Text="多设备连接总览" Classes="section"/><TextBlock Grid.Column="1" Text="{Binding ConnectionSummary}" Foreground="#66D9C0" VerticalAlignment="Center"/></Grid>
<WrapPanel><Button x:Name="ConnectAllButton" Content="连接全部空闲设备" Command="{Binding ConnectAllCommand}"/><Button Content="投屏全部就绪设备" Command="{Binding StartAllScreensCommand}"/><Button x:Name="DisconnectAllButton" Content="断开全部" Command="{Binding DisconnectAllCommand}"/></WrapPanel>
<Grid ColumnDefinitions="*,Auto"><TextBlock Text="多设备连接总览" Classes="section"/><TextBlock Grid.Column="1" Text="{Binding ConnectionSummary}" Foreground="{DynamicResource SemiColorPrimary}" VerticalAlignment="Center"/></Grid>
<WrapPanel><Button Classes="Primary" Theme="{DynamicResource SolidButton}" x:Name="ConnectAllButton" Content="连接全部空闲设备" Command="{Binding ConnectAllCommand}"/><Button Content="投屏全部就绪设备" Command="{Binding StartAllScreensCommand}"/><Button Classes="Danger" x:Name="DisconnectAllButton" Content="断开全部" Command="{Binding DisconnectAllCommand}"/></WrapPanel>
<ScrollViewer MaxHeight="380">
<ItemsControl x:Name="ConnectionsList" ItemsSource="{Binding Connections}">
<ItemsControl.ItemTemplate><DataTemplate>
<Border Background="#101923" CornerRadius="8" Padding="12" Margin="0,0,0,8">
<Border Classes="inset" Margin="0,0,0,8">
<StackPanel Spacing="6">
<Grid ColumnDefinitions="*,Auto"><TextBlock Text="{Binding DeviceId}" FontSize="17" FontWeight="SemiBold"/><TextBlock Grid.Column="1" Text="{Binding Mode}" Foreground="#66D9C0"/></Grid>
<TextBlock Text="{Binding Status}" Foreground="#66D9C0"/>
<Grid ColumnDefinitions="*,Auto"><TextBlock Text="{Binding DeviceId}" FontSize="17" FontWeight="SemiBold"/><TextBlock Grid.Column="1" Text="{Binding Mode}" Foreground="{DynamicResource SemiColorPrimary}"/></Grid>
<TextBlock Text="{Binding Status}" Foreground="{DynamicResource SemiColorPrimary}"/>
<TextBlock Text="{Binding Endpoint}" Classes="label"/><TextBlock Text="{Binding PortSummary}" Classes="label" FontSize="12" TextWrapping="Wrap"/><TextBlock Text="{Binding TransportStatus}" Classes="label" TextWrapping="Wrap"/>
<WrapPanel>
<Button Content="查看" Command="{Binding $parent[Window].DataContext.SelectConnectionCommand}" CommandParameter="{Binding}" Padding="10,6"/>
@@ -67,10 +60,10 @@
<Border Classes="card">
<StackPanel Spacing="12">
<TextBlock Text="所选设备 · 连接管理" Classes="section"/>
<TextBlock x:Name="ConnectionStatusText" Text="{Binding Status}" Foreground="#66D9C0" FontSize="19" TextWrapping="Wrap"/>
<TextBlock x:Name="TransportStatusText" Text="{Binding TransportStatus}" Foreground="#A8B7CC" TextWrapping="Wrap"/>
<TextBlock x:Name="ConnectionStatusText" Text="{Binding Status}" Foreground="{DynamicResource SemiColorPrimary}" FontSize="19" TextWrapping="Wrap"/>
<TextBlock x:Name="TransportStatusText" Text="{Binding TransportStatus}" Foreground="{DynamicResource SemiColorText2}" TextWrapping="Wrap"/>
<TextBlock x:Name="EndpointText" Text="{Binding ActiveEndpoint}" Classes="label" TextWrapping="Wrap"/>
<WrapPanel><Button x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制设备标识" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
<WrapPanel><Button Classes="Primary" Theme="{DynamicResource SolidButton}" x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制设备标识" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
<TextBlock Text="断开连接只释放本机通道,远程手机守护程序会继续在线。" TextWrapping="Wrap" Classes="label" FontSize="12"/>
</StackPanel>
</Border>
@@ -93,7 +86,7 @@
<StackPanel Grid.Column="1"><TextBlock Text="最大帧率" Classes="label"/><NumericUpDown Value="{Binding MaxFps}" Minimum="1" Maximum="240" Increment="10" Margin="8,6,0,4"/></StackPanel>
</Grid>
<WrapPanel><CheckBox Content="传输音频" IsChecked="{Binding Audio}" Margin="0,0,24,0"/><CheckBox Content="只看画面" IsChecked="{Binding ViewOnly}"/></WrapPanel>
<WrapPanel><Button x:Name="StartScreenButton" Content="打开手机控制" Command="{Binding StartScrcpyCommand}"/><Button Content="停止投屏" Command="{Binding StopScrcpyCommand}"/></WrapPanel>
<WrapPanel><Button Classes="Primary" Theme="{DynamicResource SolidButton}" x:Name="StartScreenButton" Content="打开手机控制" Command="{Binding StartScrcpyCommand}"/><Button Content="停止投屏" Command="{Binding StopScrcpyCommand}"/></WrapPanel>
</StackPanel>
</Border>
</StackPanel>
@@ -106,7 +99,7 @@
<StackPanel Margin="4,18" MaxWidth="880" Spacing="16">
<Border Classes="card"><StackPanel>
<TextBlock Text="控制中心" Classes="section" Margin="0,0,0,12"/>
<ItemsControl ItemsSource="{Binding RelayNodes}" Margin="0,0,0,12"><ItemsControl.ItemTemplate><DataTemplate><TextBlock Text="{Binding Description}" Foreground="#66D9C0" Margin="0,3"/></DataTemplate></ItemsControl.ItemTemplate></ItemsControl>
<ItemsControl ItemsSource="{Binding RelayNodes}" Margin="0,0,0,12"><ItemsControl.ItemTemplate><DataTemplate><TextBlock Text="{Binding Description}" Foreground="{DynamicResource SemiColorPrimary}" Margin="0,3"/></DataTemplate></ItemsControl.ItemTemplate></ItemsControl>
<TextBlock Text="控制中心地址(WSS,可包含路径)"/><TextBox x:Name="ServerBox" Text="{Binding Server}" Watermark="wss://ttstd.com/ads"/>
<TextBlock Text="直连服务器(可选)"/><TextBox x:Name="OriginBox" Text="{Binding Origin}" Watermark="175.178.213.60:443"/>
<TextBlock Text="留空则按域名解析;指定公网 IP 时仍验证域名证书。当前部署使用此设置避开 Cloudflare 连接超时。" Classes="label" TextWrapping="Wrap"/>
@@ -148,10 +141,10 @@
<TabItem Header="运行日志">
<Grid RowDefinitions="Auto,*" Margin="0,16,0,0">
<StackPanel Orientation="Horizontal"><Button Content="打开日志文件夹" Command="{Binding OpenLogFolderCommand}"/><Button Content="清空日志" Command="{Binding ClearLogsCommand}"/><Button Content="导出日志" Command="{Binding ExportLogsCommand}"/></StackPanel>
<ListBox Grid.Row="1" ItemsSource="{Binding Logs}" Margin="0,8,0,0" FontFamily="Cascadia Mono,Consolas" FontSize="12"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding}" TextWrapping="Wrap"/></DataTemplate></ListBox.ItemTemplate></ListBox>
<ListBox x:Name="RuntimeLogs" Grid.Row="1" ItemsSource="{Binding Logs}" Margin="0,8,0,0" FontFamily="Cascadia Mono,Consolas,Microsoft YaHei UI,Noto Sans CJK SC" FontSize="12"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding}" TextWrapping="Wrap"/></DataTemplate></ListBox.ItemTemplate></ListBox>
</Grid>
</TabItem>
</TabControl>
<TextBlock Grid.Row="2" x:Name="NoticeText" Text="{Binding Notice}" Foreground="#A8B7CC" Margin="0,18,0,0" TextWrapping="Wrap" MaxHeight="70"/>
<TextBlock Grid.Row="2" x:Name="NoticeText" Text="{Binding Notice}" Foreground="{DynamicResource SemiColorText2}" Margin="0,18,0,0" TextWrapping="Wrap" MaxHeight="70"/>
</Grid>
</Window>
+6
View File
@@ -10,6 +10,12 @@ public partial class MainWindow : Window
Opened += async (_, _) => { if (DataContext is MainViewModel vm) await vm.InitializeAsync(); };
}
private void ThemeChanged(object? sender, RoutedEventArgs e)
{
if (sender is ToggleSwitch control && Avalonia.Application.Current is {} app)
app.RequestedThemeVariant = control.IsChecked == true ? Avalonia.Styling.ThemeVariant.Dark : Avalonia.Styling.ThemeVariant.Light;
}
private async void ImportCredentialsClick(object? sender, RoutedEventArgs e)
{
if (DataContext is not MainViewModel vm) return;
+3 -1
View File
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Text;
namespace Ads.Desktop;
@@ -11,7 +12,8 @@ public static class ProcessTools
var info = new ProcessStartInfo(executable)
{
UseShellExecute = false, CreateNoWindow = true,
RedirectStandardOutput = true, RedirectStandardError = true
RedirectStandardOutput = true, RedirectStandardError = true,
StandardOutputEncoding = new UTF8Encoding(false), StandardErrorEncoding = new UTF8Encoding(false)
};
foreach (var argument in arguments) info.ArgumentList.Add(argument);
foreach (var key in new[] { "ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT", "ADS_CLIENT_TOKEN", "ADS_AGENT_TOKEN", "ADS_ADMIN_TOKEN", "ADS_CONNECT_ADDRESS" })
+16
View File
@@ -0,0 +1,16 @@
<Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style Selector="Window">
<Setter Property="Background" Value="{DynamicResource SemiColorBackground0}"/>
<Setter Property="Foreground" Value="{DynamicResource SemiColorText0}"/>
<Setter Property="FontFamily" Value="Segoe UI,Microsoft YaHei UI,Noto Sans CJK SC"/>
<Setter Property="FontSize" Value="14"/>
</Style>
<Style Selector="Button"><Setter Property="Padding" Value="14,8"/><Setter Property="MinHeight" Value="36"/><Setter Property="Margin" Value="0,0,8,8"/><Setter Property="CornerRadius" Value="6"/></Style>
<Style Selector="TextBox"><Setter Property="Margin" Value="0,6,0,12"/><Setter Property="MinHeight" Value="36"/></Style>
<Style Selector="TextBlock.label"><Setter Property="Foreground" Value="{DynamicResource SemiColorText2}"/></Style>
<Style Selector="TextBlock.section"><Setter Property="FontSize" Value="18"/><Setter Property="FontWeight" Value="SemiBold"/></Style>
<Style Selector="Border.card, Border.agentCard"><Setter Property="Background" Value="{DynamicResource SemiColorBackground1}"/><Setter Property="BorderBrush" Value="{DynamicResource SemiColorBorder}"/><Setter Property="BorderThickness" Value="1"/><Setter Property="CornerRadius" Value="10"/><Setter Property="Padding" Value="18"/></Style>
<Style Selector="Border.inset"><Setter Property="Background" Value="{DynamicResource SemiColorFill0}"/><Setter Property="CornerRadius" Value="8"/><Setter Property="Padding" Value="14"/></Style>
<Style Selector="TabControl.workbench TabItem"><Setter Property="MinWidth" Value="144"/><Setter Property="Padding" Value="16,12"/><Setter Property="Margin" Value="0,0,14,6"/><Setter Property="HorizontalContentAlignment" Value="Left"/></Style>
<Style Selector="ListBox"><Setter Property="CornerRadius" Value="6"/></Style>
</Styles>
+4
View File
@@ -98,3 +98,7 @@ USB 会话后端已按操作系统选择:Windows 使用已签名 USBip 控制
Windows 自包含发布把托管程序集打包到主程序,保留原生图形 DLL 和独立 Rust/ADB/scrcpy 工具;不启用反射裁剪,不要求安装 .NET,也不将全部应用压为单文件。发布使用全新暂存目录。`Ads.Desktop.exe --package-check` 可在隔离配置、无设备连接和不占用正式客户端互斥锁的条件下创建窗口后退出,用于验证发布包。
升级安装目录后会修复保存的旧工具位置;有效自定义可执行文件保留。启动时将解析后的路径写回已有设置,避免仍使用已删除的 TTSTD 安装目录。
Avalonia 使用锁定的 Semi.Avalonia 11.3.7.3(兼容 Avalonia 11.3.8)。`Ads.Desktop/WorkbenchStyles.axaml`(AXAML)统一侧边导航、卡片、表单和文本样式,颜色引用 Semi 语义资源,支持浅色/深色切换;Agent 托盘窗口共享主题。`dotnet run --project Ads.Desktop.Smoke -- --theme-preview` 可离线渲染 4 个页面的明暗主题和最小窗口尺寸,结果写入根目录 work(PNG)。
子进程 stdout/stderr 显式按 UTF-8 解码,包含 Rust、ADB、scrcpy 及 USB 工具;Agent JSON stdin 也使用 UTF-8。已生成的历史乱码日志保留,不猜测或改写丢失的字符。测试覆盖中文和 emoji 的一次性输出、流式日志及中文配置输入。
+7
View File
@@ -77,3 +77,10 @@ Port cleanup follow-up:
- 现场 settings.json 中 client、adb、scrcpy 三项仍为 Programs/TTSTD/ADS-Flutter,且三文件已不存在;当前 TongTongStudio 安装目录中的工具存在,ads-client --version 与 adb version 可运行。已备份现场配置后修复三项路径,其他设置和凭据保持不变;已运行的旧 UI 需重启才能重新读取设置。
- Flutter 新增 ToolPaths:启动及连接前解析、持久化当前工具位置,优先当前安装包,保留有效自定义工具。缺失工具在分配端口和建立租约之前报出修复方法,避免底层 ProcessException。投屏也解析 scrcpy/ADB 及工作目录。
- Avalonia 同步旧路径回退、启动迁移及保存。Flutter 32 项测试、Dart 静态分析、Avalonia 24 项测试通过,实际发布包窗口启动检查 PACKAGE_CHECK_OK。并行编译压力下一次端口测试超时,完整复跑 24 项均通过。
### 0.2.3:Avalonia Semi 主题与 UTF-8 日志
- 现场日志出现“鍦ㄥ叾…”等 UTF-8 字节被按 Windows 本地编码解释后的乱码。ProcessTools 对 stdout/stderr 显式使用 UTF-8,覆盖同步命令与流式日志;本机 Agent 管理 JSON stdin 同步 UTF-8,非重定向后台启动清空输出编码选项。
- 锁定 Semi.Avalonia 11.3.7.3,与当前 Avalonia 11.3.8 兼容。设备、Agent 管理、设置、日志及 Agent 托盘统一使用 Semi 资源;新增 WorkbenchStyles.axaml,替换硬编码深色配色,使用左侧导航和明暗主题开关。
- 27 项 Avalonia 测试通过,包含中文及 emoji stdout/stderr、流式日志和中文 JSON 输入。离屏渲染四个页面的浅色/深色和 980×700 最小窗口共 10 张 PNG 并检查截图;实际 Windows 发布包 PACKAGE_CHECK_OK,PE 运行库检查通过。
- Windows 安装器为 0.2.3;Linux 发布同版本 Avalonia/Agent deb。历史乱码日志不改写;安装新版本并重启后,新日志按 UTF-8 正常显示。尚未在本轮执行干净虚拟机完整安装/卸载和 Linux GUI 实机回归。
+1 -1
View File
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 0.2.2+3
version: 0.2.3+4
environment:
sdk: ^3.14.0