feat: 支持安装前后ADB命令与安装后启动应用

按工程保存前后置命令和自动启动选项,全程绑定选中设备,区分安装与后续动作失败。通过实际APK及目标设备解析Launcher入口,兼容activity-alias;增加模拟进程回归测试及0.8.0三套服务部署记录。
This commit is contained in:
tongtong committed 2026-11-27 16:26:03 +08:00
1 parent 6f9cc7e7ea
commit b46ebd1070
18 files changed
+472 -35

No files matched your search

+2
View File
@@ -113,3 +113,5 @@ Linux/macOS 在 `plugin/` 执行 `sh ./gradlew buildPlugin`。也可使用已安
0.7.0支持在侧边栏维护[服务端私有文件清单](docs/private-files.md):IDE编辑路径清单、显式保存、检查并在构建前复制未跟踪的签名脚本和密钥文件。
0.8.0支持[安装前后ADB命令与安装后打开应用](docs/install-actions.md),按工程配置并自动绑定选定设备。
+5
View File
@@ -149,3 +149,8 @@ Windows远端已替换0.4.9,备份原程序、XML和access.json。实际运行
## 2026-11-27 全量部署0.7.0
确认空闲、校验SHA-256并备份旧程序和配置后完成升级。服务账户、启动方式、授权目录与任务、工具链、签名映射、TLS/Token及历史APK保留。HTTPS版本0.7.0及privateFileList能力、私有文件清单GET与401认证、ADB设备接口验证通过;未创建业务清单、同步源码、触发构建或向设备安装应用。插件侧边栏需安装0.7.0后使用。
## 2026-11-27 全量部署0.8.0
空闲检查、程序摘要核验和配置备份后完成升级。服务账户及启动方式保留,原目录/任务授权、工具链、私有文件清单、签名映射、TLS/Token及历史APK未改动。HTTPS版本0.8.0/installActions能力、安装接口新字段校验、私有清单读取/认证、ADB列表和历史产物验证通过。使用无效设备和非法前置命令验证新参数,在任何ADB命令执行前拒绝;没有向真实设备执行配置命令、安装或启动。需安装0.8.0插件使用新选项。
+5
View File
@@ -149,3 +149,8 @@ Ubuntu已升级0.4.10并验证active;CLI自动定位、原两个工程根目
## 2026-11-27 全量部署0.7.0
确认空闲、校验SHA-256并备份旧程序和配置后完成升级。服务账户、启动方式、授权目录与任务、工具链、签名映射、TLS/Token及历史APK保留。HTTPS版本0.7.0及privateFileList能力、私有文件清单GET与401认证、ADB设备接口验证通过;未创建业务清单、同步源码、触发构建或向设备安装应用。插件侧边栏需安装0.7.0后使用。
## 2026-11-27 全量部署0.8.0
空闲检查、程序摘要核验和配置备份后完成升级。服务账户及启动方式保留,原目录/任务授权、工具链、私有文件清单、签名映射、TLS/Token及历史APK未改动。HTTPS版本0.8.0/installActions能力、安装接口新字段校验、私有清单读取/认证、ADB列表和历史产物验证通过。使用无效设备和非法前置命令验证新参数,在任何ADB命令执行前拒绝;没有向真实设备执行配置命令、安装或启动。需安装0.8.0插件使用新选项。
+5
View File
@@ -80,3 +80,8 @@ Get-Content 'C:\ProgramData\VibeCodingRemoteCompilation\logs\*.log' -Tail 50
## 2026-11-27 全量部署0.7.0
确认空闲、校验SHA-256并备份旧程序和配置后完成升级。服务账户、启动方式、授权目录与任务、工具链、签名映射、TLS/Token及历史APK保留。HTTPS版本0.7.0及privateFileList能力、私有文件清单GET与401认证、ADB设备接口验证通过;未创建业务清单、同步源码、触发构建或向设备安装应用。插件侧边栏需安装0.7.0后使用。
## 2026-11-27 全量部署0.8.0
空闲检查、程序摘要核验和配置备份后完成升级。服务账户及启动方式保留,原目录/任务授权、工具链、私有文件清单、签名映射、TLS/Token及历史APK未改动。HTTPS版本0.8.0/installActions能力、安装接口新字段校验、私有清单读取/认证、ADB列表和历史产物验证通过。使用无效设备和非法前置命令验证新参数,在任何ADB命令执行前拒绝;没有向真实设备执行配置命令、安装或启动。需安装0.8.0插件使用新选项。
+21
View File
@@ -0,0 +1,21 @@
# 安装前后命令与安装后打开应用(0.8.0)
在右侧连接设置中点击“编辑安装前 / 安装后 ADB 命令…”填写,关闭编辑窗口后点击保存配置。每个工程独立保存,不作为新工程的全局默认命令。另有“安装后打开应用”复选框,默认关闭。未启用安装时不会执行命令或启动旧应用;本机自动安装仍需勾选构建后安装,服务端模式沿用右列的服务端ADB安装选项。手动安装按钮同样使用当前工程的命令和启动设置。
```text
# 安装前:每行一条
adb shell settings delete system app_source_white_list
```
只支持ADB shell命令,可省略adb或使用adb.exe前缀。设备由程序追加-s <选中序列号>,不允许手写-s/-d/-e/-H等宿主ADB参数。当前参数须为不含空格的简单文本,只允许字母数字及_./:@%+=,-;不支持引号、管道、重定向、变量和多命令拼接。空行和#注释行忽略,每阶段最多10条、文本上限16KiB、每条命令30秒超时。通过命令参数直接启动ADB,不使用本机cmd/PowerShell/Bash执行命令行。
执行顺序:安装前命令 → 安装APK → 安装后命令 → 打开应用。所有操作固定为同一所选设备,不在离线时改装其他设备。本机同一adb/设备的安装互斥,服务端安装沿用服务安装锁。前置失败停止安装,安装失败停止后续动作;后置失败停止剩余动作和启动,并明确保留安装成功的结果。命令日志包含阶段、顺序、所选序列号、输出和退出状态;不会自动卸载应用。请勿把敏感值写入需要日志输出的命令。
打开应用时,用Android SDK build-tools中的aapt从实际APK读取applicationId,而非猜测项目namespace或主模块包名。再在已安装的目标设备上执行cmd package resolve-activity,解析MAIN+LAUNCHER,支持不同flavor/applicationIdSuffix及activity-alias,最后am start -W启动解析到的组件。没有可解析的Launcher、缺少aapt或启动失败仅提示后续操作失败,保留安装成功;仅有服务/接收器的APK不会凭空创建启动入口。需要目标设备支持cmd package resolve-activity。
服务端安装API增加beforeCommands/afterCommands字符串及launchAfter布尔字段。只有使用新动作时插件才发送这些字段并检查installActions能力,未开启时保持旧服务普通安装兼容。远程模式全部操作在服务器执行,不依赖先将APK下载到本机;本地模式使用本机SDK与ADB。
本轮只实现和打包,不自动部署、不对真实设备执行配置命令或安装启动;IDE交互及真实APK/设备验收需升级后进行。
2026-11-27部署更新:三套服务已升级0.8.0,通过能力及无副作用参数校验和原功能验收;未对真实设备执行安装动作。插件需用户安装0.8.0。
+16
View File
@@ -157,3 +157,19 @@ Windows192.168.5.222、Ubuntu192.168.5.224和本机服务均升级0.7.0。Window
仅插件变更,服务端0.7.0无需重部署;IDE实际点击保存及在用户当前IDE版本运行待安装后验收。
0.7.1离线test/buildPlugin成功(2m3s),共35项测试无失败;最终ZIP已复制到dist,未自动安装或重启IDE。
## 2026-11-27 安装动作与Launcher启动0.8.0
增加按工程保存的安装前/安装后ADB shell命令和默认关闭的安装后打开应用选项。命令仅接受简单ADB shell参数,自动追加选定序号;本机自动/手动安装及服务端安装复用一致设置。顺序为前置→安装→后置→启动;前置失败不安装,安装失败不后置,后置或启动失败保留安装成功并停止剩余动作。每条命令有30秒超时、10条/阶段限制,本机同设备互斥,远程操作沿用服务安装锁。
启动使用实际APK经SDK aapt得到applicationId,再由目标设备cmd package resolve-activity解析MAIN/LAUNCHER入口(兼容alias),不猜测源码包名或直接启动其他应用。无入口、缺aapt、启动失败单独报告。未开启新动作时仍兼容老服务普通安装,开启时要求installActions能力/服务端0.8.0。
模拟ADB/aapt的真实子进程测试验证多阶段执行顺序、全程-s选中序号、前置失败阻止安装、后置失败保留success、无Launcher不误报安装失败;服务端完整Windows回归通过120.770s,Unix权限测试按平台跳过。只使用模拟设备,不执行真实设备命令或启动。Windows/Linux服务端已构建,Linux仅交叉编译。插件当前IDE实机点击与实际APK启动需后续验收,本轮未自动部署/提交/推送。
最终插件test/buildPlugin通过1m57s,共37项测试无失败(新增安装命令解析边界);0.8.0 ZIP已复制dist,最终字节码确认包含本机设备安装互斥。未部署。
## 2026-11-27 三套服务部署0.8.0
Windows192.168.5.222、Ubuntu192.168.5.224、本机服务均升级0.8.0并正常运行,保留配置、权限策略、清单及历史APK。Windows保持Automatic/Running、LocalService;Ubuntuactive/remotecompile,备份/opt/remotecompile/upgrade-0.8.0-20261127-161249。三端HTTPS版本/installActions能力、安装新字段的执行前拒绝校验、原授权与任务拦截、私有清单接口/401认证、ADB设备查询及历史成功产物验证通过。不执行真实设备配置/安装/启动。插件仍需用户安装0.8.0。此前未部署记录由本轮更新。
+1 -1
View File
@@ -3,7 +3,7 @@ plugins {
id("org.jetbrains.intellij.platform") version "2.5.0"
}
group = "studio.tongtong"
version = "0.7.1"
version = "0.8.0"
repositories {
mavenCentral()
intellijPlatform { defaultRepositories() }
@@ -28,15 +28,19 @@ object AdbDevices {
fun resolve(source: Path, configured: String): String {
if (configured.isNotBlank() && configured != "adb") return configured
val roots = sdkRoots(source)
val executable = if (System.getProperty("os.name").startsWith("Windows")) "adb.exe" else "adb"
return roots.map { Path.of(it).resolve("platform-tools").resolve(executable) }.firstOrNull { Files.isRegularFile(it) }?.toString() ?: "adb"
}
fun sdkRoots(source: Path): List<String> {
val properties = Properties()
val local = source.resolve("local.properties")
if (Files.isRegularFile(local)) Files.newInputStream(local).use(properties::load)
val roots = listOfNotNull(properties.getProperty("sdk.dir"), System.getenv("ANDROID_HOME"), System.getenv("ANDROID_SDK_ROOT"),
return listOfNotNull(properties.getProperty("sdk.dir"), System.getenv("ANDROID_HOME"), System.getenv("ANDROID_SDK_ROOT"),
System.getenv("LOCALAPPDATA")?.let { "$it/Android/Sdk" },
System.getProperty("user.home")?.let { "$it/Library/Android/sdk" },
System.getProperty("user.home")?.let { "$it/Android/Sdk" })
val executable = if (System.getProperty("os.name").startsWith("Windows")) "adb.exe" else "adb"
return roots.map { Path.of(it).resolve("platform-tools").resolve(executable) }.firstOrNull { Files.isRegularFile(it) }?.toString() ?: "adb"
}
fun list(adb: String): List<AdbDevice> {
@@ -0,0 +1,79 @@
package studio.tongtong.remotecompile
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.TimeUnit
object InstallActions {
private val word = Regex("[A-Za-z0-9_./:@%+=,-]+")
fun commands(text: String): List<List<String>> {
require(text.toByteArray().size <= 16384) { "安装命令最多16KiB" }
return text.lineSequence().map(String::trim).filter { it.isNotEmpty() && !it.startsWith('#') }.map { line ->
val parts = line.split(Regex("\\s+")).let { if (it.first().lowercase() in setOf("adb", "adb.exe")) it.drop(1) else it }
require(parts.size >= 2 && parts.first() == "shell") { "仅支持adb shell命令;设备由插件自动指定,请勿填写-s/-d/-e" }
require(parts.all { word.matches(it) }) { "参数不支持引号、管道、重定向或命令拼接" }
parts
}.toList().also { require(it.size <= 10) { "每个安装阶段最多10条命令" } }
}
private fun process(args: List<String>, seconds: Long, log: (String) -> Unit): String {
val file = Files.createTempFile("remotecompile-adb-action-", ".log")
try {
val p = ProcessBuilder(args).redirectErrorStream(true).redirectOutput(file.toFile()).start()
try {
check(p.waitFor(seconds, TimeUnit.SECONDS)) { "命令超时(${seconds}秒),结果未确认" }
val output = Files.newInputStream(file).use { String(it.readNBytes(65536), Charsets.UTF_8) }
if (output.isNotBlank()) log(output)
log("退出码:${p.exitValue()}")
check(p.exitValue() == 0) { "命令失败,退出码${p.exitValue()}" }
return output
} finally { if (p.isAlive) { p.destroyForcibly(); p.waitFor(3, TimeUnit.SECONDS) } }
} finally { Files.deleteIfExists(file) }
}
private fun hooks(adb: String, serial: String, stage: String, entries: List<List<String>>, log: (String) -> Unit) {
entries.forEachIndexed { index, args ->
log("[$stage ${index + 1}/${entries.size}] adb -s $serial ${args.joinToString(" ")}")
process(listOf(adb, "-s", serial) + args, 30, log)
}
}
private fun applicationId(source: Path, adb: String, apk: Path): String {
val roots = AdbDevices.sdkRoots(source) + listOfNotNull(runCatching { Path.of(adb).takeIf { it.isAbsolute }?.parent?.parent?.toString() }.getOrNull())
val name = if (System.getProperty("os.name").startsWith("Windows")) "aapt.exe" else "aapt"
val candidates = roots.distinct().flatMap { root ->
val tools = Path.of(root).resolve("build-tools")
if (!Files.isDirectory(tools)) emptyList() else Files.list(tools).use { paths -> paths.sorted(Comparator.reverseOrder()).map { it.resolve(name) }.filter(Files::isRegularFile).toList() }
}
for (candidate in candidates) {
val output = runCatching { process(listOf(candidate.toString(), "dump", "badging", apk.toString()), 15) {} }.getOrNull() ?: continue
Regex("(?m)^package: name='([A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)+)'").find(output)?.let { return it.groupValues[1] }
}
error("无法读取APK包名,请检查项目SDK build-tools中的aapt")
}
private fun launch(source: Path, adb: String, serial: String, apk: Path, log: (String) -> Unit) {
val pkg = applicationId(source, adb, apk)
val prefix = listOf(adb, "-s", serial, "shell")
val resolved = process(prefix + listOf("cmd", "package", "resolve-activity", "--brief", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", pkg), 30, {})
val component = resolved.lineSequence().map(String::trim).lastOrNull {
it.startsWith("$pkg/") && Regex("[A-Za-z0-9_.]+/[A-Za-z0-9_.$]+").matches(it)
} ?: error("${pkg}没有可解析的默认Launcher入口")
log("[打开应用] adb -s $serial:$component")
val output = process(prefix + listOf("am", "start", "-W", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", "-n", "'$component'"), 30, log)
check(!output.contains("Error:") && !output.contains("Exception")) { "启动失败,请查看上方输出" }
}
private val installs = java.util.concurrent.ConcurrentHashMap<String, java.util.concurrent.locks.ReentrantLock>()
fun install(source: Path, cfg: Settings.Data, adb: String, serial: String, apk: Path, log: (String) -> Unit) {
val lock = installs.computeIfAbsent("$adb\n$serial") { java.util.concurrent.locks.ReentrantLock() }
check(lock.tryLock()) { "该本机设备正在安装,请稍后重试" }
try {
val before = commands(cfg.beforeInstall); val after = commands(cfg.afterInstall)
hooks(adb, serial, "安装前", before, log)
log("[安装APK] adb -s $serial install -r $apk")
val output = process(listOf(adb, "-s", serial, "install", "-r", apk.toString()), 120, log)
check(output.contains("Success")) { "ADB未确认安装成功" }
log("安装已成功")
try {
hooks(adb, serial, "安装后", after, log)
if (cfg.launchAfterInstall) launch(source, adb, serial, apk, log)
} catch (e: Exception) { log("安装已成功,后续操作未完成:${e.message}") }
} finally { lock.unlock() }
}
}
@@ -437,13 +437,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
}
settings.selectDevice(target.serial)
append("安装目标:$target")
val outputLog = Files.createTempFile("remotecompile-adb-", ".log")
try {
val process = ProcessBuilder(adb, "-s", target.serial, "install", "-r", output.toString())
.redirectErrorStream(true).redirectOutput(outputLog.toFile()).start()
if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("adb 安装超时") }
append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" }
} finally { Files.deleteIfExists(outputLog) }
InstallActions.install(source, cfg, adb, target.serial, output, ::append)
}
private fun setBuildId(id: String) = ApplicationManager.getApplication().invokeLater { if (!disposed) buildIdField.text = id }
private fun showProgress(message: String, percent: Int = -1) = ApplicationManager.getApplication().invokeLater {
@@ -597,12 +591,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
val target = AdbDevices.choose(AdbDevices.list(adb), explicit?.serial ?: cfg.device, explicit != null)
check(target != null) { "请选择在线且已授权的设备" }
append("安装构建 ${record.buildId} 到 $target")
val outputLog = Files.createTempFile("remote-install-", ".log")
try {
val process = ProcessBuilder(adb, "-s", target.serial, "install", "-r", output.toString()).redirectErrorStream(true).redirectOutput(outputLog.toFile()).start()
if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("安装超时") }
append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" }
} finally { Files.deleteIfExists(outputLog) }
InstallActions.install(source, cfg, adb, target.serial, output, ::append)
} catch (e: Exception) { append("安装失败:${e.message ?: e.javaClass.simpleName}") }
finally { busy = false; ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } }
}
@@ -14,13 +14,13 @@ object ServerAdb {
validateEndpoint(base)
val token = PasswordSafe.instance.getPassword(credentials(base)).orEmpty()
check(token.isNotBlank()) { "请先保存服务器 Token" }
val builder = HttpRequest.newBuilder(URI.create("$base/api/v1/adb/$route"))
val builder = HttpRequest.newBuilder(URI.create(base + if (route == "health") "/api/v1/health" else "/api/v1/adb/$route"))
.header("Authorization", "Bearer $token").header("Content-Type", "application/json")
.timeout(if (body == null) Duration.ofSeconds(25) else Duration.ofMinutes(4))
.timeout(if (body == null) Duration.ofSeconds(25) else Duration.ofMinutes(15))
val req = if (body == null) builder.GET().build() else builder.POST(HttpRequest.BodyPublishers.ofString(Gson().toJson(body))).build()
val response = ServerTls.client(cfg.serverCertificate).send(req, HttpResponse.BodyHandlers.ofString())
check(response.statusCode() in 200..299) {
if (response.statusCode() == 404) "服务端需升级至 0.6.0 才支持远程 ADB" else response.body().replace(token, "***")
if (response.statusCode() == 404) "服务端需升级以支持当前ADB功能" else response.body().replace(token, "***")
}
return Gson().fromJson(response.body(), JsonObject::class.java)
}
@@ -28,6 +28,13 @@ object ServerAdb {
val d = it.asJsonObject
AdbDevice(d.get("serial").asString, d.get("state").asString, d.get("model")?.asString.orEmpty())
}
fun install(cfg: Settings.Data, buildId: String, artifact: String, serial: String): String =
call(cfg, "install", mapOf("buildId" to buildId, "artifact" to artifact, "serial" to serial)).get("output").asString
fun install(cfg: Settings.Data, buildId: String, artifact: String, serial: String): String {
val before = InstallActions.commands(cfg.beforeInstall); val after = InstallActions.commands(cfg.afterInstall)
val body = mutableMapOf<String, Any>("buildId" to buildId, "artifact" to artifact, "serial" to serial)
if (before.isNotEmpty() || after.isNotEmpty() || cfg.launchAfterInstall) {
check(call(cfg, "health").get("installActions")?.asBoolean == true) { "服务端需升级至0.8.0,才支持安装前后命令和安装后打开应用" }
body["beforeCommands"] = cfg.beforeInstall; body["afterCommands"] = cfg.afterInstall; body["launchAfter"] = cfg.launchAfterInstall
}
return call(cfg, "install", body).get("output").asString
}
}
@@ -20,7 +20,7 @@ import javax.swing.event.DocumentListener
class ConnectionDefaults : PersistentStateComponent<Settings.Data> {
@Volatile private var data = Settings.Data()
@Synchronized override fun getState() = data.copy()
@Synchronized override fun loadState(state: Settings.Data) { data = state.copy(projectId = "", device = "", remoteAdb = false, remoteDevice = "", remoteFolder = "", remoteJavaHome = "", taskHistory = mutableListOf()) }
@Synchronized override fun loadState(state: Settings.Data) { data = state.copy(projectId = "", device = "", remoteAdb = false, remoteDevice = "", beforeInstall = "", afterInstall = "", launchAfterInstall = false, remoteFolder = "", remoteJavaHome = "", taskHistory = mutableListOf()) }
}
@State(name = "RemoteCompilation", storages = [Storage("remote-compilation.xml")])
@@ -39,6 +39,9 @@ class Settings : PersistentStateComponent<Settings.Data> {
var remoteAdb: Boolean = false,
var remoteDevice: String = "",
var install: Boolean = false,
var beforeInstall: String = "",
var afterInstall: String = "",
var launchAfterInstall: Boolean = false,
var serverCertificate: String = "",
var configured: Boolean = false
)
@@ -46,7 +49,7 @@ class Settings : PersistentStateComponent<Settings.Data> {
private fun defaults() = ApplicationManager.getApplication()?.getService(ConnectionDefaults::class.java)
@Synchronized fun snapshot(): Data {
val shared = if (!data.configured) defaults()?.getState() else null
return if (shared?.configured == true) shared.copy(remoteAdb = data.remoteAdb, remoteDevice = data.remoteDevice, projectId = data.projectId, device = data.device, remoteFolder = data.remoteFolder, remoteJavaHome = data.remoteJavaHome, taskHistory = data.taskHistory.toMutableList()) else data.copy()
return if (shared?.configured == true) shared.copy(beforeInstall = data.beforeInstall, afterInstall = data.afterInstall, launchAfterInstall = data.launchAfterInstall, remoteAdb = data.remoteAdb, remoteDevice = data.remoteDevice, projectId = data.projectId, device = data.device, remoteFolder = data.remoteFolder, remoteJavaHome = data.remoteJavaHome, taskHistory = data.taskHistory.toMutableList()) else data.copy()
}
@Synchronized override fun getState(): Data = data.copy()
@Synchronized override fun loadState(state: Data) {
@@ -102,6 +105,9 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL
private val adb = JTextField(original.adb)
private val certificate = JTextField(original.serverCertificate)
private val install = JCheckBox("构建成功后自动安装(无可用设备时仅下载 APK)", original.install)
private val beforeInstall = JTextArea(original.beforeInstall, 4, 24)
private val afterInstall = JTextArea(original.afterInstall, 4, 24)
private val launchAfter = JCheckBox("安装后打开应用(目标设备默认Launcher入口)", original.launchAfterInstall)
private val save = JButton("保存配置")
private val status = JLabel("Token 留空保留已保存值")
private val tokenStatus = JLabel("正在读取已保存 Token…")
@@ -143,7 +149,18 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL
val picker = JFileChooser().apply { fileFilter = javax.swing.filechooser.FileNameExtensionFilter("服务器证书", "crt", "pem", "cer") }
if (picker.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) certificate.text = picker.selectedFile.absolutePath
}
fields.add(choose); fields.add(install); fields.add(checkRemote); fields.add(save); fields.add(status)
val actionsButton = JButton("编辑安装前 / 安装后 ADB 命令…")
actionsButton.addActionListener {
val panel = JPanel(BorderLayout(0, 8)).apply {
add(JLabel("每行一条 adb shell 命令,自动绑定所选设备;不支持引号、管道或重定向。"), BorderLayout.NORTH)
add(JPanel(GridLayout(2, 1, 0, 8)).apply {
add(JPanel(BorderLayout()).apply { add(JLabel("安装前(失败停止安装)"), BorderLayout.NORTH); add(JScrollPane(beforeInstall)) })
add(JPanel(BorderLayout()).apply { add(JLabel("安装后(失败停止后续操作,保留安装成功)"), BorderLayout.NORTH); add(JScrollPane(afterInstall)) })
}, BorderLayout.CENTER)
}
JOptionPane.showMessageDialog(this, panel, "安装命令(编辑后点击保存配置)", JOptionPane.PLAIN_MESSAGE)
}
fields.add(choose); fields.add(install); fields.add(actionsButton); fields.add(launchAfter); fields.add(checkRemote); fields.add(save); fields.add(status)
checkRemote.addActionListener { checkRemoteProject() }
val content = object : JPanel(BorderLayout(0, 8)), Scrollable {
override fun getPreferredScrollableViewportSize() = preferredSize
@@ -176,12 +193,12 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL
restoreToken()
save.addActionListener {
val base = url.text.trim().trimEnd('/')
try { validateEndpoint(base); require(remoteFolder.text.isNotBlank()) { "请填写服务端已有工程文件夹" } }
try { InstallActions.commands(beforeInstall.text); InstallActions.commands(afterInstall.text); validateEndpoint(base); require(remoteFolder.text.isNotBlank()) { "请填写服务端已有工程文件夹" } }
catch (e: IllegalArgumentException) { status.text = e.message; return@addActionListener }
tokenRequest++ // Discard a pending restore before replacing/saving this credential.
val entered = String(token.password); token.text = ""
val previous = settings.snapshot()
val next = previous.copy(url = base, remoteFolder = remoteFolder.text.trim(), remoteJavaHome = (jdks.selectedItem as? JdkChoice)?.home.orEmpty(), ignoreLineEndings = ignoreLineEndings.isSelected, adb = adb.text.trim(), install = install.isSelected, serverCertificate = certificate.text.trim(),
val next = previous.copy(beforeInstall = beforeInstall.text, afterInstall = afterInstall.text, launchAfterInstall = launchAfter.isSelected, url = base, remoteFolder = remoteFolder.text.trim(), remoteJavaHome = (jdks.selectedItem as? JdkChoice)?.home.orEmpty(), ignoreLineEndings = ignoreLineEndings.isSelected, adb = adb.text.trim(), install = install.isSelected, serverCertificate = certificate.text.trim(),
projectId = if (previous.url == base && previous.remoteFolder == remoteFolder.text.trim()) previous.projectId else "")
save.isEnabled = false; status.text = "正在保存…"
ApplicationManager.getApplication().executeOnPooledThread {
@@ -0,0 +1,17 @@
package studio.tongtong.remotecompile
import org.junit.Assert.*
import org.junit.Test
class InstallActionsTest {
@Test fun acceptsOrderedCommandsWithoutDeviceSelectors() {
val commands = InstallActions.commands("# before\nadb shell settings delete system app_source_white_list\r\nshell am force-stop com.example.app")
assertEquals(2, commands.size)
assertEquals(listOf("shell", "settings", "delete", "system", "app_source_white_list"), commands[0])
}
@Test fun rejectsOtherTargetsAndShellComposition() {
for (input in listOf("adb -s other shell id", "adb -d shell id", "adb install test.apk", "adb shell id;reboot", "shell id | cat", "shell echo \$HOME", "shell sh -c 'id'", "shell id\n".repeat(11))) {
try { InstallActions.commands(input); fail("Accepted: $input") } catch (_: IllegalArgumentException) { }
}
}
}
+5
View File
@@ -122,3 +122,8 @@ health增加remoteADB=true,现有Bearer认证及HTTPS配置适用。
health增加privateFileList=true。GET /api/v1/private-files?workspacePath=<服务端来源目录>返回workspacePath/manifestPath/exists/content/hash/ready/message/entries(path,status,message)。PUT同一路径,请求workspacePath/content/baseHash;乐观并发冲突或同来源正在构建返回409,非法清单400,仍要求Bearer认证及工程根目录授权。保存允许文件暂时缺失,响应ready=false逐项说明;实际构建则拒绝。此接口只操作路径清单,不返回私有文件内容。
Project持久化privateFiles摘要用于区分普通源码与私有文件和安全清理;同步清单与私有路径冲突则拒绝。构建前在源工程内读取并复制,参见docs/private-files.md。
## 0.8.0 安装动作
health增加installActions=true;POST /adb/install新增可选beforeCommands/afterCommands多行文本及launchAfter布尔值。原字段保持。所有命令只允许ADB shell简单参数,服务端绑定请求serial;单条30秒、每阶段10条,总请求最多12分钟。前置失败400不安装;安装成功后后置或启动失败仍返回success=true、postActionsSuccess=false,output保留分阶段日志。启动使用服务器SDK的aapt解析真实APK包名,再向选中设备解析MAIN/LAUNCHER组件并启动。参见docs/install-actions.md。
+36 -7
View File
@@ -109,14 +109,27 @@ func (s *Server) serveADB(w http.ResponseWriter, r *http.Request) {
return
}
var req struct {
BuildID string `json:"buildId"`
Artifact string `json:"artifact"`
Serial string `json:"serial"`
BuildID string `json:"buildId"`
Artifact string `json:"artifact"`
Serial string `json:"serial"`
BeforeCommands string `json:"beforeCommands"`
AfterCommands string `json:"afterCommands"`
LaunchAfter bool `json:"launchAfter"`
}
if e := decode(w, r, &req); e != nil {
http.Error(w, e.Error(), 400)
return
}
before, err := parseInstallCommands(req.BeforeCommands)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
after, err := parseInstallCommands(req.AfterCommands)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
if req.Serial == "" || strings.HasPrefix(req.Serial, "-") || strings.ContainsAny(req.Serial, " \t\r\n\x00") {
http.Error(w, "请选择服务端在线且已授权的设备", 400)
return
@@ -143,7 +156,7 @@ func (s *Server) serveADB(w http.ResponseWriter, r *http.Request) {
return
}
defer adbInstallLock.Unlock()
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Minute)
defer cancel()
out, e := s.adbCommand(ctx, "devices", "-l")
if e != nil {
@@ -166,14 +179,30 @@ func (s *Server) serveADB(w http.ResponseWriter, r *http.Request) {
http.Error(w, "服务端APK缺失或摘要校验失败,请重新构建", 409)
return
}
out, e = s.adbCommand(ctx, "-s", req.Serial, "install", "-r", path)
var log strings.Builder
if e = s.runInstallCommands(ctx, req.Serial, "安装前", before, &log); e != nil {
http.Error(w, log.String()+"\n"+e.Error(), 400)
return
}
log.WriteString("[安装APK] adb -s " + req.Serial + " install -r\n")
installCtx, installCancel := context.WithTimeout(ctx, 2*time.Minute)
out, e = s.adbCommand(installCtx, "-s", req.Serial, "install", "-r", path)
installCancel()
log.WriteString(out)
if e != nil {
http.Error(w, e.Error(), 400)
http.Error(w, log.String()+"\n"+e.Error(), 400)
return
}
if !strings.Contains(out, "Success") {
http.Error(w, "ADB未确认安装成功:"+out, 400)
return
}
jsonOut(w, map[string]any{"success": true, "serial": req.Serial, "output": out})
postError := s.runInstallCommands(ctx, req.Serial, "安装后", after, &log)
if postError == nil && req.LaunchAfter {
postError = s.launchInstalledAPK(ctx, req.Serial, path, &log)
}
if postError != nil {
log.WriteString("\n安装已成功,后续操作未完成:" + postError.Error())
}
jsonOut(w, map[string]any{"success": true, "serial": req.Serial, "output": log.String(), "postActionsSuccess": postError == nil})
}
+127
View File
@@ -0,0 +1,127 @@
package main
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"time"
)
var shellWord = regexp.MustCompile(`^[A-Za-z0-9_./:@%+=,-]+$`)
var apkPackage = regexp.MustCompile(`(?m)^package: name='([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+)'`)
var launcherComponent = regexp.MustCompile(`^[A-Za-z0-9_.]+/[A-Za-z0-9_.$]+$`)
func parseInstallCommands(text string) ([][]string, error) {
if len(text) > 16<<10 {
return nil, fmt.Errorf("安装命令最多16KiB")
}
result := [][]string{}
for i, line := range strings.Split(text, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
words := strings.Fields(line)
if strings.EqualFold(words[0], "adb") || strings.EqualFold(words[0], "adb.exe") {
words = words[1:]
}
if len(words) < 2 || words[0] != "shell" {
return nil, fmt.Errorf("第%d行仅支持adb shell命令;设备由插件指定,请勿填写-s/-d/-e", i+1)
}
for _, word := range words {
if !shellWord.MatchString(word) {
return nil, fmt.Errorf("第%d行参数包含不支持的字符;请勿使用引号、管道、重定向或命令拼接", i+1)
}
}
result = append(result, words)
if len(result) > 10 {
return nil, fmt.Errorf("每个安装阶段最多10条命令")
}
}
return result, nil
}
func (s *Server) runInstallCommands(ctx context.Context, serial, stage string, commands [][]string, log *strings.Builder) error {
for i, args := range commands {
fmt.Fprintf(log, "[%s %d/%d] adb -s %s %s\n", stage, i+1, len(commands), serial, strings.Join(args, " "))
child, cancel := context.WithTimeout(ctx, 30*time.Second)
out, e := s.adbCommand(child, append([]string{"-s", serial}, args...)...)
cancel()
log.WriteString(out)
if e != nil {
return fmt.Errorf("%s命令失败,已停止该阶段:%w", stage, e)
}
log.WriteString("\n退出码:0\n")
}
return nil
}
func (s *Server) apkApplicationID(ctx context.Context, path string) (string, error) {
cfg, e := s.buildEnvironment()
if e != nil {
return "", e
}
exe := "aapt"
if runtime.GOOS == "windows" {
exe += ".exe"
}
candidates, _ := filepath.Glob(filepath.Join(cfg.AndroidHome, "build-tools", "*", exe))
sort.Sort(sort.Reverse(sort.StringSlice(candidates)))
if binary, e := exec.LookPath(exe); e == nil {
candidates = append(candidates, binary)
}
for _, binary := range candidates {
if st, e := os.Stat(binary); e != nil || st.IsDir() {
continue
}
child, cancel := context.WithTimeout(ctx, 15*time.Second)
cmd := exec.CommandContext(child, binary, "dump", "badging", path)
var out adbOutput
cmd.Stdout = &out
cmd.Stderr = &out
e := cmd.Run()
cancel()
if e == nil {
if match := apkPackage.FindStringSubmatch(out.String()); match != nil {
return match[1], nil
}
}
}
return "", fmt.Errorf("无法从APK读取包名,请检查服务端Android SDK build-tools中的aapt;应用已安装")
}
func (s *Server) launchInstalledAPK(ctx context.Context, serial, path string, log *strings.Builder) error {
pkg, e := s.apkApplicationID(ctx, path)
if e != nil {
return e
}
child, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
out, e := s.adbCommand(child, "-s", serial, "shell", "cmd", "package", "resolve-activity", "--brief", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", pkg)
if e != nil {
return e
}
component := ""
for _, line := range strings.Split(out, "\n") {
line = strings.TrimSpace(line)
if launcherComponent.MatchString(line) && strings.HasPrefix(line, pkg+"/") {
component = line
}
}
if component == "" {
return fmt.Errorf("%s没有可解析的默认Launcher入口;保持安装成功", pkg)
}
fmt.Fprintf(log, "[打开应用] adb -s %s:%s\n", serial, component)
out, e = s.adbCommand(child, "-s", serial, "shell", "am", "start", "-W", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", "-n", "'"+component+"'")
log.WriteString(out)
if e == nil && (strings.Contains(out, "Error:") || strings.Contains(out, "Exception")) {
e = fmt.Errorf("启动失败:%s", out)
}
return e
}
+109
View File
@@ -0,0 +1,109 @@
package main
import (
"bytes"
"encoding/json"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestInstallCommandValidation(t *testing.T) {
commands, e := parseInstallCommands("# comment\n adb shell settings delete system app_source_white_list\r\nshell am force-stop com.example.app\n")
if e != nil || len(commands) != 2 || commands[0][0] != "shell" {
t.Fatal(commands, e)
}
for _, command := range []string{"adb -s other shell settings delete x y", "adb -H host shell id", "adb install app.apk", "adb shell id;reboot", "adb shell echo $HOME", "adb shell id | cat", "adb shell sh -c 'id'", strings.Repeat("shell id\n", 11)} {
if _, e := parseInstallCommands(command); e == nil {
t.Fatalf("accepted %q", command)
}
}
}
func TestInstallActionsOrderingFailureAndLauncher(t *testing.T) {
root := t.TempDir()
exe := filepath.Join(root, "fake-adb")
name := "aapt"
if runtime.GOOS == "windows" {
exe += ".exe"
name += ".exe"
}
helper := filepath.Join(root, "helper.go")
writeFixture(t, helper, `package main
import("encoding/json";"os";"strings";"fmt")
func main(){a:=os.Args[1:];f,_:=os.OpenFile(os.Getenv("HOOK_LOG"),os.O_CREATE|os.O_APPEND|os.O_WRONLY,0600);json.NewEncoder(f).Encode(a);f.Close();text:=strings.Join(a," ");if strings.Contains(text,"fail"){fmt.Println("hook failed");os.Exit(7)};if a[0]=="devices"{fmt.Println("List of devices attached\nselected device model:Tablet");return};if a[0]=="dump"{fmt.Println("package: name='com.example.variant' versionCode='1'");return};if strings.Contains(text,"resolve-activity"){if os.Getenv("NO_LAUNCHER")=="1"{fmt.Println("No activity found")}else{fmt.Println("com.example.variant/.LauncherAlias")};return};fmt.Println("Success")}
`)
cmd := exec.Command("go", "build", "-o", exe, helper)
if out, e := cmd.CombinedOutput(); e != nil {
t.Fatalf("%v %s", e, out)
}
sdk := filepath.Join(root, "sdk")
aapt := filepath.Join(sdk, "build-tools", "35.0.0", name)
os.MkdirAll(filepath.Dir(aapt), 0700)
binary, e := os.ReadFile(exe)
if e != nil {
t.Fatal(e)
}
if e = os.WriteFile(aapt, binary, 0700); e != nil {
t.Fatal(e)
}
cfg, _ := json.Marshal(BuildEnvironment{Adb: exe, AndroidHome: sdk})
config := filepath.Join(root, "env.json")
writeFixture(t, config, string(cfg))
bid := strings.Repeat("c", 32)
apk := []byte("fake-apk")
artifact := Artifact{Name: "0.apk", Hash: digest(apk), Size: int64(len(apk))}
s := &Server{root: root, token: "test", environmentFile: config, builds: map[string]*Build{bid: {ID: bid, Status: "success", Artifacts: []Artifact{artifact}}}}
writeFixture(t, filepath.Join(root, "artifacts", bid, artifact.Name), string(apk))
log := filepath.Join(root, "calls.jsonl")
t.Setenv("HOOK_LOG", log)
run := func(before, after string, launch bool) *httptest.ResponseRecorder {
os.WriteFile(log, nil, 0600)
data, _ := json.Marshal(map[string]any{"buildId": bid, "artifact": artifact.Name, "serial": "selected", "beforeCommands": before, "afterCommands": after, "launchAfter": launch})
req := httptest.NewRequest("POST", "/api/v1/adb/install", bytes.NewReader(data))
req.Header.Set("Authorization", "Bearer test")
w := httptest.NewRecorder()
s.ServeHTTP(w, req)
return w
}
w := run("adb shell settings delete system app_source_white_list", "adb shell settings put system ready 1", true)
if w.Code != 200 {
t.Fatal(w.Code, w.Body.String())
}
raw, _ := os.ReadFile(log)
calls := string(raw)
last := -1
for _, part := range []string{`"delete"`, `"install"`, `"put"`, `"dump"`, `"resolve-activity"`, `"am","start"`} {
pos := strings.Index(calls, part)
if pos <= last {
t.Fatalf("order %s: %s", part, calls)
}
last = pos
}
for _, line := range strings.Split(strings.TrimSpace(calls), "\n") {
var args []string
json.Unmarshal([]byte(line), &args)
if args[0] != "dump" && args[0] != "devices" && (len(args) < 2 || args[0] != "-s" || args[1] != "selected") {
t.Fatal("wrong target", args)
}
}
w = run("shell fail", "shell id", true)
raw, _ = os.ReadFile(log)
if w.Code == 200 || strings.Contains(string(raw), `"install"`) {
t.Fatal("pre failure did not stop install", w.Code, string(raw))
}
w = run("", "shell fail", true)
raw, _ = os.ReadFile(log)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"postActionsSuccess":false`) || strings.Contains(string(raw), "resolve-activity") {
t.Fatal("post failure result", w.Code, w.Body.String())
}
t.Setenv("NO_LAUNCHER", "1")
w = run("", "", true)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"postActionsSuccess":false`) {
t.Fatal("missing launcher must keep installed", w.Body.String())
}
}
+1 -1
View File
@@ -182,7 +182,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
fail := func(e error) { http.Error(w, e.Error(), 400) }
if r.URL.Path == "/api/v1/health" {
jsonOut(w, map[string]any{"version": "0.7.0", "privateFileList": true, "remoteADB": true, "syncPreflight": true, "dedicatedGit": true, "adminCLI": true, "preflight": true, "textComparison": true, "jdkSelection": true, "workspaceSelection": true, "os": runtime.GOOS, "sync": "http-manifest", "recovery": true})
jsonOut(w, map[string]any{"version": "0.8.0", "installActions": true, "privateFileList": true, "remoteADB": true, "syncPreflight": true, "dedicatedGit": true, "adminCLI": true, "preflight": true, "textComparison": true, "jdkSelection": true, "workspaceSelection": true, "os": runtime.GOOS, "sync": "http-manifest", "recovery": true})
return
}
if r.URL.Path == "/api/v1/environment" && r.Method == "GET" {