feat: 初始化跨平台远程编译服务与 Android Studio 插件

This commit is contained in:
tongtong committed 2026-11-24 14:46:34 +08:00
commit 9eba4556db
44 files changed
+2802

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
# Windows 服务部署
本目录脚本以管理员权限运行,使用 [WinSW 2.12.0](https://github.com/winsw/winsw/releases/tag/v2.12.0) 官方 x64 包装器将 Go 程序注册为 Windows 服务。配置遵循 [WinSW 2.x 文档](https://winsw.github.io/v2/doc/xmlConfigFile/)。
将以下文件放入同一目录:
- `remotecompile-windows-amd64.exe`
- `WinSW-x64-v2.12.0.exe`(从官方固定版本下载)
- `install.ps1`
- `verify.ps1`
管理员 PowerShell:
```powershell
.\install.ps1 -JavaHome 'C:\工具链\jdk-17' -AndroidHome 'D:\AndroidSdk\Windows'
.\verify.ps1
```
默认根目录 `C:\ProgramData\VibeCodingRemoteCompilation`:
| 位置 | 内容 |
| --- | --- |
| `bin\remotecompile.exe` | Go 服务 |
| `bin\RemoteCompileService.exe` | WinSW(与 Go 程序不同名称,避免 Windows 大小写碰撞) |
| `bin\RemoteCompileService.xml` | 配置、工具链路径与随机 Token |
| `data\` | 工作区和产物 |
| `home\` | 独立 Gradle 缓存和调试签名 |
| `logs\` | 包装器与应用日志 |
服务名 `RemoteCompile`,自动延迟启动,以 `NT AUTHORITY\LocalService` 运行。配置及程序目录只向管理员、SYSTEM 和 LocalService 授权;LocalService 仅可写数据、日志、home 和 temp。LocalService 是系统内置共享低权限账户,不是不可信构建沙箱。
仅监听 `127.0.0.1:8765`。通过 SSH 隧道访问,不新开防火墙入站规则。Token 副本导出到部署用户的 `.remotecompile-service-token.txt`,并限制 ACL;不会保存 SSH 登录密码。
`verify.ps1` 验证 JDK 启动、android-35 平台读取、35.0.0 aapt2 执行、同步、模拟构建及产物摘要。它生成的测试文件不是有效 Android APK。
管理:
```powershell
Get-Service RemoteCompile
Restart-Service RemoteCompile
Get-Content 'C:\ProgramData\VibeCodingRemoteCompilation\logs\*.log' -Tail 30
```
调整 JDK/SDK 时编辑 XML 对应 env 后重启。服务不修改机器全局 Java 或 Android 环境变量,不自动安装缺失的 SDK 组件。真实构建需要选择与项目 Gradle/AGP 兼容的 JDK。
+64
View File
@@ -0,0 +1,64 @@
param(
[string]$Root = 'C:\ProgramData\VibeCodingRemoteCompilation',
[string]$OutputPath = (Join-Path $env:TEMP ('RemoteCompile-diagnostics-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.txt'))
)
$ErrorActionPreference = 'Stop'
$lines = New-Object 'System.Collections.Generic.List[string]'
$token = ''
$configPath = Join-Path $Root 'bin\RemoteCompileService.xml'
if (Test-Path -LiteralPath $configPath) {
[xml]$config = Get-Content -LiteralPath $configPath -Raw
$token = [string](($config.service.env | Where-Object name -eq 'REMOTE_BUILD_TOKEN').value)
}
function Add-Section([string]$name, [scriptblock]$collect) {
$lines.Add("`r`n## $name")
try {
$value = (& $collect 2>&1 | Out-String -Width 220)
if ($token) { $value = $value.Replace($token, '[REDACTED]') }
$value = $value -replace '(?i)Bearer\s+[A-Za-z0-9._~+/-]+', 'Bearer [REDACTED]'
$value = $value -replace '(?i)((?:password|passwd|secret|access_token)\s*[=:]\s*)[^\s,;]+', '$1[REDACTED]'
$lines.Add($value)
} catch { $lines.Add('Collection failed: ' + $_.Exception.Message) }
}
Add-Section 'System and service' {
Get-Date -Format o
Get-CimInstance Win32_OperatingSystem | Select-Object Caption,Version,LastBootUpTime
Get-CimInstance Win32_Service -Filter "Name='RemoteCompile' OR Name='sshd'" | Select-Object Name,State,StartMode,StartName,ProcessId
}
Add-Section 'Listening ports' {
Get-NetTCPConnection -State Listen | Where-Object LocalPort -in @(22,8765) | Select-Object LocalAddress,LocalPort,OwningProcess
}
Add-Section 'Toolchain configuration (token omitted)' {
if ($config) { $config.service.env | Where-Object name -in @('JAVA_HOME','ANDROID_HOME','ANDROID_SDK_ROOT','GRADLE_USER_HOME','HOME','USERPROFILE') | Select-Object name,value }
}
Add-Section 'Authenticated local health check' {
if (-not $token) { throw 'Service config/token unavailable; run as administrator.' }
Invoke-RestMethod -Uri 'http://127.0.0.1:8765/api/v1/health' -Headers @{Authorization="Bearer $token"} -TimeoutSec 5 | ConvertTo-Json -Compress
}
Add-Section 'Service wrapper and application logs' {
Get-ChildItem -LiteralPath (Join-Path $Root 'logs') -File | Where-Object Extension -eq '.log' | ForEach-Object {
'FILE: ' + $_.Name
Get-Content -LiteralPath $_.FullName -Tail 120
}
}
Add-Section 'Recent build results' {
Get-ChildItem -LiteralPath (Join-Path $Root 'data\artifacts') -Filter build.json -Recurse -File -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending | Select-Object -First 5 | ForEach-Object {
$build = Get-Content -LiteralPath $_.FullName -Raw | ConvertFrom-Json
$build | Select-Object id,project,revision,task,status | ConvertTo-Json -Compress
$build.logs | Select-Object -Last 120
}
}
Add-Section 'Active build markers' {
Get-ChildItem -LiteralPath (Join-Path $Root 'data\projects') -Filter active-build -Recurse -File -ErrorAction SilentlyContinue | ForEach-Object {
$_.FullName
Get-Content -LiteralPath $_.FullName
}
}
Add-Section 'Related service control events (48 hours)' {
Get-WinEvent -FilterHashtable @{LogName='System';ProviderName='Service Control Manager';StartTime=(Get-Date).AddDays(-2)} -MaxEvents 300 |
Where-Object Message -match 'RemoteCompile|VibeCoding|sshd|OpenSSH' | Select-Object TimeCreated,Id,LevelDisplayName,Message | Format-List
}
[IO.File]::WriteAllText($OutputPath,($lines -join "`r`n"),(New-Object Text.UTF8Encoding($false)))
Write-Output "Diagnostics saved: $OutputPath"
Write-Output 'The service token is redacted. Review build output for project-specific secrets before sharing.'
+24
View File
@@ -0,0 +1,24 @@
$ErrorActionPreference='Stop'
$candidates=New-Object 'System.Collections.Generic.List[string]'
foreach($base in @('C:\Program Files','D:\Program Files','D:\ProgramFiles')) {
foreach($folder in @(Get-ChildItem -LiteralPath $base -Directory -ErrorAction SilentlyContinue | Where-Object {$_.Name -match 'Java|JDK|Android|Studio|JetBrains|Microsoft|Eclipse|BellSoft'})) {
$candidates.Add($folder.FullName)
$candidates.Add((Join-Path $folder.FullName 'jbr'))
foreach($child in @(Get-ChildItem -LiteralPath $folder.FullName -Directory -ErrorAction SilentlyContinue)) {
$candidates.Add($child.FullName)
$candidates.Add((Join-Path $child.FullName 'jbr'))
}
}
}
$selected=$null
foreach($candidate in $candidates) {
$release=Join-Path $candidate 'release'
if((Test-Path -LiteralPath "$candidate\bin\java.exe") -and (Test-Path -LiteralPath $release)) {
$version=Get-Content -LiteralPath $release | Where-Object {$_ -match '^JAVA_VERSION="(17|21)\.'}
if($version){$selected=$candidate;break}
}
}
if(-not $selected){$selected='C:\Program Files\Java\jdk-25.0.3';Write-Output 'Only JDK25 detected; older Gradle projects require configuring a compatible JDK.'}
Write-Output "Selected JAVA_HOME=$selected"
& "$PSScriptRoot\install.ps1" -JavaHome $selected
& "$PSScriptRoot\verify.ps1"
+89
View File
@@ -0,0 +1,89 @@
param(
[string]$Root = 'C:\ProgramData\VibeCodingRemoteCompilation',
[Parameter(Mandatory=$true)][string]$JavaHome,
[string]$AndroidHome = 'D:\AndroidSdk\Windows'
)
$ErrorActionPreference = 'Stop'
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Administrator required' }
if (-not (Test-Path -LiteralPath "$JavaHome\bin\java.exe")) { throw 'Invalid JavaHome' }
if (-not (Test-Path -LiteralPath "$AndroidHome\platforms")) { throw 'Invalid AndroidHome' }
foreach ($name in @('remotecompile-windows-amd64.exe','WinSW-x64-v2.12.0.exe')) {
if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot $name))) { throw "Missing $name" }
}
if (Get-Service RemoteCompile -ErrorAction SilentlyContinue) {
Stop-Service RemoteCompile
(Get-Service RemoteCompile).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(45))
}
New-Item -ItemType Directory -Force -Path $Root | Out-Null
& icacls.exe $Root /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' '*S-1-5-19:(OI)(CI)RX' | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Root ACL failed' }
foreach ($dir in @('bin','logs','data','home','temp')) { New-Item -ItemType Directory -Force -Path (Join-Path $Root $dir) | Out-Null }
foreach ($dir in @('logs','data','home','temp')) {
& icacls.exe (Join-Path $Root $dir) /grant:r '*S-1-5-19:(OI)(CI)M' | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Data ACL failed' }
}
$config = Join-Path $Root 'bin\RemoteCompileService.xml'
if (Test-Path -LiteralPath $config) {
[xml]$old = Get-Content -LiteralPath $config -Raw
$token = ($old.service.env | Where-Object name -eq 'REMOTE_BUILD_TOKEN').value
} else {
$bytes = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
try { $rng.GetBytes($bytes) } finally { $rng.Dispose() }
$token = ([BitConverter]::ToString($bytes)).Replace('-','').ToLowerInvariant()
}
if ($token.Length -lt 24) { throw 'Invalid token' }
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'remotecompile-windows-amd64.exe') -Destination "$Root\bin\remotecompile.exe" -Force
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'WinSW-x64-v2.12.0.exe') -Destination "$Root\bin\RemoteCompileService.exe" -Force
function XmlEscape([string]$value) { [Security.SecurityElement]::Escape($value) }
$safeRoot = XmlEscape $Root
$safeJava = XmlEscape $JavaHome
$safeSdk = XmlEscape $AndroidHome
$xml = @"
<service>
<id>RemoteCompile</id>
<name>VibeCoding Remote Compilation</name>
<description>Android remote build service, loopback only.</description>
<executable>$safeRoot\bin\remotecompile.exe</executable>
<arguments>-listen 127.0.0.1:8765 -data &quot;$safeRoot\data&quot; -tasks :app:assembleDebug</arguments>
<workingdirectory>$safeRoot</workingdirectory>
<startmode>Automatic</startmode>
<delayedAutoStart>true</delayedAutoStart>
<stoptimeout>40 sec</stoptimeout>
<onfailure action="restart" delay="10 sec"/>
<logpath>$safeRoot\logs</logpath>
<log mode="roll-by-size"><sizeThreshold>10240</sizeThreshold><keepFiles>4</keepFiles></log>
<serviceaccount><domain>NT AUTHORITY</domain><user>LocalService</user></serviceaccount>
<env name="REMOTE_BUILD_TOKEN" value="$token"/>
<env name="JAVA_HOME" value="$safeJava"/>
<env name="ANDROID_HOME" value="$safeSdk"/>
<env name="ANDROID_SDK_ROOT" value="$safeSdk"/>
<env name="GRADLE_USER_HOME" value="$safeRoot\home\.gradle"/>
<env name="HOME" value="$safeRoot\home"/>
<env name="USERPROFILE" value="$safeRoot\home"/>
<env name="TEMP" value="$safeRoot\temp"/>
<env name="TMP" value="$safeRoot\temp"/>
</service>
"@
[IO.File]::WriteAllText($config,$xml,(New-Object Text.UTF8Encoding($false)))
if (-not (Get-Service RemoteCompile -ErrorAction SilentlyContinue)) {
& "$Root\bin\RemoteCompileService.exe" install
if ($LASTEXITCODE -ne 0) { throw 'Service installation failed' }
}
Start-Service RemoteCompile
$headers = @{Authorization="Bearer $token"}
$healthy = $false
for ($i=0;$i -lt 30;$i++) {
try {
$result = Invoke-RestMethod -Uri 'http://127.0.0.1:8765/api/v1/health' -Headers $headers -TimeoutSec 2
Write-Output ('Health: ' + ($result | ConvertTo-Json -Compress)); $healthy=$true; break
} catch { Start-Sleep -Seconds 1 }
}
if (-not $healthy) { throw "Service health failed. Check $Root\logs" }
$tokenPath = Join-Path $env:USERPROFILE '.remotecompile-service-token.txt'
[IO.File]::WriteAllText($tokenPath,$token,(New-Object Text.UTF8Encoding($false)))
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
& icacls.exe $tokenPath /inheritance:r /grant:r "*$($sid):R" '*S-1-5-18:F' '*S-1-5-32-544:F' | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Token ACL failed' }
Get-CimInstance Win32_Service -Filter "Name='RemoteCompile'" | Select-Object Name,State,StartMode,StartName
Write-Output 'Client token exported privately; contents hidden.'
+40
View File
@@ -0,0 +1,40 @@
param([string]$Root='C:\ProgramData\VibeCodingRemoteCompilation')
$ErrorActionPreference='Stop'
[xml]$config=Get-Content -LiteralPath "$Root\bin\RemoteCompileService.xml" -Raw
$token=($config.service.env | Where-Object name -eq 'REMOTE_BUILD_TOKEN').value
$headers=@{Authorization="Bearer $token"}
function Api([string]$method,[string]$path,$body=$null) {
$args=@{Method=$method;Uri="http://127.0.0.1:8765/api/v1$path";Headers=$headers;TimeoutSec=30}
if($null -ne $body){$args.ContentType='application/json';$args.Body=($body | ConvertTo-Json -Depth 12 -Compress)}
Invoke-RestMethod @args
}
$project=(Api POST '/projects').id
$wrapper=@'
@echo off
"%JAVA_HOME%\bin\java.exe" -version
if errorlevel 1 exit /b 1
if not exist "%ANDROID_HOME%\platforms\android-35\android.jar" exit /b 2
"%ANDROID_HOME%\build-tools\35.0.0\aapt2.exe" version
if errorlevel 1 exit /b 3
mkdir app\build\outputs\apk\debug 2>nul
echo windows-service-smoke>app\build\outputs\apk\debug\app-debug.apk
exit /b 0
'@
$content=[Text.Encoding]::ASCII.GetBytes($wrapper.Replace("`n","`r`n"))
$sha=[Security.Cryptography.SHA256]::Create()
try {$hash=([BitConverter]::ToString($sha.ComputeHash($content))).Replace('-','').ToLowerInvariant()}finally{$sha.Dispose()}
$files=@{'gradlew.bat'=@{hash=$hash;data=[Convert]::ToBase64String($content)}}
Api POST "/projects/$project/sync" @{revision='windows-deploy-smoke';files=$files} | Out-Null
$build=(Api POST "/projects/$project/builds" @{revision='windows-deploy-smoke';task=':app:assembleDebug'}).id
for($i=0;$i -lt 120;$i++) {
$result=Api GET "/builds/$build"
if($result.status -notin @('queued','running')){break}
Start-Sleep -Milliseconds 250
}
if($result.status -ne 'success'){throw ($result | ConvertTo-Json -Depth 6)}
$artifact=$result.artifacts[0]
$download=Join-Path $env:TEMP 'remotecompile-deploy-smoke.apk'
Invoke-WebRequest -UseBasicParsing -Uri "http://127.0.0.1:8765/api/v1/builds/$build/artifacts/$($artifact.name)" -Headers $headers -OutFile $download
if((Get-FileHash -LiteralPath $download -Algorithm SHA256).Hash.ToLowerInvariant() -ne $artifact.hash){throw 'Artifact hash mismatch'}
Remove-Item -LiteralPath $download
Write-Output "PASS: sync, LocalService JDK, SDK android-35 read, aapt2, build, download, SHA256. Build=$build. Simulated APK only."