Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

chore(desktop): Android platform-tools 二进制移出 Git LFS,改打包前按 pin 下载

Lizi3b551630b52f
diff --git a/.gitattributes b/.gitattributes
index b682047e95..2dbd733eed 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -14,9 +14,10 @@ apps/desktop/native/sqlite-vec/**/*.dll filter=lfs diff=lfs merge=lfs -text
apps/desktop/native/sqlite-vec/**/*.so filter=lfs diff=lfs merge=lfs -text
# claude / codex / ripgrep CLI 二进制不再进 git/LFS——按需从上游下载
# (见 scripts/ensure-agent-binaries.mjs;版本 pin 在 tools/<kind>/latest.json)。
-# Android platform-tools 二进制—— 走 Git LFS
-apps/android-platform-tools-bin/**/*.exe filter=lfs diff=lfs merge=lfs -text
-apps/android-platform-tools-bin/**/*.dll filter=lfs diff=lfs merge=lfs -text
+# Android platform-tools 二进制(adb.exe / AdbWin*.dll)不再进 git/LFS——Windows
+# 打包前按 source.properties 的 pin 版本从上游下载并校验 sha256
+# (见 apps/desktop/scripts/ensure-android-platform-tools.mjs);路径已在
+# .gitignore 中排除。同目录的 NOTICE.txt 与 source.properties 是文本、照常入仓。
# cindy-updater.exe 不再进 git/LFS——Windows 打包的 prePackage 每次都从
# apps/desktop/cindy-updater/ 现场 cargo build 并覆盖 resources/ 下的产物
# (见 forge.config.ts buildCindyUpdater);路径已在 .gitignore 中排除。
diff --git a/.gitignore b/.gitignore
index 8646a4acbc..ddd94e1c0c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,6 +47,14 @@ apps/desktop/resources/cindy-updater.exe
apps/claude-code-bin/
apps/codex-bin/
apps/ripgrep-bin/
+# Android platform-tools 的二进制同理:Windows 打包前按 source.properties 的 pin
+# 版本下载并校验 sha256(apps/desktop/scripts/ensure-android-platform-tools.mjs)。
+# 只忽略已知的三个二进制文件——同目录的 NOTICE.txt(许可清单要读)与
+# source.properties(版本事实源)是文本,必须继续入仓。不使用通配符,防止
+# 意外文件被隐藏后经 stageAndroidPlatformTools 混入安装包。
+apps/android-platform-tools-bin/win32-x64/adb.exe
+apps/android-platform-tools-bin/win32-x64/AdbWinApi.dll
+apps/android-platform-tools-bin/win32-x64/AdbWinUsbApi.dll
tools/claude/updates/
tools/codex/updates/
tools/ripgrep/updates/
diff --git a/README.md b/README.md
index cea30668e3..95dec39a61 100644
--- a/README.md
+++ b/README.md
@@ -62,7 +62,7 @@ Ready out of the box, never boxed in — start with
| `apps/desktop` | Electron desktop client |
| `apps/mobile` | Expo / React Native mobile client |
| `packages/*` | Shared client capabilities (auth, device-link, agent orchestration, model providers, …) |
-| `apps/*-bin` | Tool binaries shipped with the desktop app; only android-platform-tools is committed (via Git LFS) — claude-code, codex, and ripgrep are downloaded per platform by `pnpm install` and never checked in |
+| `apps/*-bin` | Tool binaries shipped with the desktop app; none are committed — claude-code, codex, and ripgrep are downloaded per platform by `pnpm install`, and the Android platform-tools binaries are fetched (pinned version, sha256-verified) before Windows packaging |
| `cindy-protocol/` | Wire protocol shared with the server (git submodule) |
**Not in this repo:** the backend service lives in a separate
diff --git a/README.zh-CN.md b/README.zh-CN.md
index e4233f22c2..65cb4999e5 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -61,7 +61,7 @@ monorepo 组织。
| `apps/desktop` | Electron 桌面客户端 |
| `apps/mobile` | Expo / React Native 手机客户端 |
| `packages/*` | 客户端共享能力(鉴权、device-link、agent 编排、模型供应商等) |
-| `apps/*-bin` | 桌面端附带的工具二进制;仓库内只含 android-platform-tools(Git LFS),claude-code / codex / ripgrep 由 `pnpm install` 按平台自动下载、不入库 |
+| `apps/*-bin` | 桌面端附带的工具二进制,均不入库;claude-code / codex / ripgrep 由 `pnpm install` 按平台自动下载,Android platform-tools 在 Windows 打包前按 pin 版本下载并校验 sha256 |
| `cindy-protocol/` | 与服务端共用的协议(git submodule) |
**服务端不在本仓库:** 服务端位于独立仓库,不属于本 monorepo。
diff --git a/apps/android-platform-tools-bin/win32-x64/AdbWinApi.dll b/apps/android-platform-tools-bin/win32-x64/AdbWinApi.dll
deleted file mode 100644
index 56b7cb6319..0000000000
--- a/apps/android-platform-tools-bin/win32-x64/AdbWinApi.dll
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:d60103a5e99bc9888f786ee916f5d6e45493c3247972cb053833803de7e95cf9
-size 97792
diff --git a/apps/android-platform-tools-bin/win32-x64/AdbWinUsbApi.dll b/apps/android-platform-tools-bin/win32-x64/AdbWinUsbApi.dll
deleted file mode 100644
index 3d627f75aa..0000000000
--- a/apps/android-platform-tools-bin/win32-x64/AdbWinUsbApi.dll
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:25207c506d29c4e8dceb61b4bd50e8669ba26012988a43fbf26a890b1e60fc97
-size 62976
diff --git a/apps/android-platform-tools-bin/win32-x64/adb.exe b/apps/android-platform-tools-bin/win32-x64/adb.exe
deleted file mode 100644
index 5c9126ec08..0000000000
--- a/apps/android-platform-tools-bin/win32-x64/adb.exe
+++ /dev/null
@@ -1,3 +0,0 @@
-version https://git-lfs.github.com/spec/v1
-oid sha256:e79dc8fc3c6385192bdccd7ff7eabe3d5c1ec292475a06b04d82759f07655982
-size 6303744
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index 2196adc10e..37bcb94c6b 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -788,11 +788,38 @@ function validateAndroidPlatformToolsSource(srcDir: string, targetPlatform: stri
assertRealAndroidPlatformTool(path.join(srcDir, 'adb'));
}
+/**
+ * Windows 打包前把 Android platform-tools 的三个二进制按 pin 版本就位。
+ *
+ * 它们(6.5MB)不入仓:公开仓每次 clone 与每次 CI checkout(ci.yml 的 lfs: true)都会
+ * 把 LFS 对象下一遍,免费带宽额度耗尽后 clone 与 CI 会一起硬失败。脚本幂等 ——
+ * 已就位且 sha256 匹配时直接跳过、不碰网络;无外网的打包机见脚本内的离线出路。
+ */
+function ensureAndroidPlatformToolsBinaries(key: string): void {
+ const script = path.join(__dirname, 'scripts', 'ensure-android-platform-tools.mjs');
+ const r = spawnSync(process.execPath, [script, `--platform-key=${key}`], { stdio: 'inherit' });
+ if (r.error) {
+ throw new Error(`[forge] failed to invoke ${script}: ${r.error.message}`);
+ }
+ if (r.status !== 0) {
+ throw new Error(
+ `[forge] Android platform-tools ${key} 未能就位(exit ${r.status})——见上方脚本输出的离线出路。`,
+ );
+ }
+}
+
function stageAndroidPlatformTools(targetPlatform: string, targetArch: string): void {
const key = targetPlatformKey(targetPlatform, targetArch);
const srcDir = path.join(__dirname, '..', 'android-platform-tools-bin', key);
const destDir = path.join(__dirname, 'resources', 'tools', 'android-platform-tools', key);
+ // win32 的二进制不入仓,先按 pin 版本下载/校验。注意不能靠 srcDir 是否存在来判断
+ // 二进制在不在 —— 同目录的 NOTICE.txt 与 source.properties 是有意入仓的文本
+ // (许可清单与版本 pin 都读它们),所以目录一直存在。
+ if (targetPlatform === 'win32') {
+ ensureAndroidPlatformToolsBinaries(key);
+ }
+
if (!fs.existsSync(srcDir)) {
fs.rmSync(destDir, { recursive: true, force: true });
if (targetPlatform !== 'win32') {
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 89b6cd58d4..7581400b03 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -18,6 +18,7 @@
"dev:inspect": "pnpm dev:winsetup && cross-env OPEN_DEVTOOLS=1 node scripts/dev-remote-env.mjs electron-forge start --inspect-electron --",
"package": "electron-forge package",
"release:package": "node scripts/package-desktop.mjs",
+ "install:android-platform-tools": "node scripts/ensure-android-platform-tools.mjs",
"build": "electron-forge make",
"db:check": "drizzle-kit check",
"db:generate": "drizzle-kit generate",
diff --git a/apps/desktop/scripts/ensure-android-platform-tools.mjs b/apps/desktop/scripts/ensure-android-platform-tools.mjs
new file mode 100644
index 0000000000..2533d22dc8
--- /dev/null
+++ b/apps/desktop/scripts/ensure-android-platform-tools.mjs
@@ -0,0 +1,372 @@
+#!/usr/bin/env node
+// =============================================================================
+// ensure-android-platform-tools — 打包前把 Android SDK Platform-Tools 的 Windows
+// 二进制(adb.exe + AdbWinApi.dll + AdbWinUsbApi.dll)按 pin 版本就位到
+// apps/android-platform-tools-bin/<platformKey>/。
+//
+// 为什么改成下载而不是入仓:这三个文件共 6.5MB,过去走 Git LFS。公开仓里每次
+// clone、以及每次 CI checkout(ci.yml 的 lfs: true)都要把它们下一遍,LFS 免费
+// 带宽额度耗尽后不是"变慢"而是 clone 与 CI checkout 一起硬失败,所有 PR 都会
+// 卡住。改成打包时下载后,安装包内容与过去逐字节一致 —— 下面 pin 的 sha256 正是
+// 原 Git LFS 对象的 oid(LFS oid 就是文件 sha256),对得上就说明字节没变。
+//
+// 版本事实源:同目录 source.properties 的 Pkg.Revision。
+// generate-third-party-notices.mjs 读的是同一个文件(readAndroidPlatformToolsVersion),
+// 所以许可清单里的版本号不会和实际打进包的二进制漂移。
+//
+// 升级版本时三处必须一起改:source.properties 的 Pkg.Revision、PINNED[key].version、
+// PINNED[key].files 的 sha256(把新版三个文件放好后用 `--print-hashes` 现算)。漏改任
+// 一处都会 fail-closed,不会静默打包错版本 —— 漏改 version 被 verifyInstalled 的版本
+// 绑定挡下(报 version mismatch),漏改 sha256 则在下载解压后的校验里失败。
+//
+// 非 Windows 平台不在本脚本职责内:forge 的 stageAndroidPlatformTools 对非 win32
+// 缺失即跳过,运行时由 src/main/mcp-integrations/android.ts 按需下载到 userData。
+//
+// 下载来源(按顺序尝试,任一成功即止):
+// 1) 上游 dl.google.com 的版本化 zip;
+// 2) 公司 OSS 兜底 —— 与 agent 二进制那条链路同一份 cdnBaseUrl 与 region 切换
+// (cn → hotfix.cindy.com.cn / global → hotfix.cindy.app),见 ossZipUrlFor 的
+// 路径约定。国内打包机可设 CINDY_ANDROID_PLATFORM_TOOLS_PREFER_OSS=1 让 OSS
+// 先行,免得每次先吃一轮 Google 的连接超时。
+// 无论来自哪个来源,校验都是本文件里硬 pin 的 sha256,不因来源放宽。
+//
+// 两个来源都不通时还有两条出路:
+// 1) CINDY_ANDROID_PLATFORM_TOOLS_ZIP=<本地 platform-tools-*.zip 路径> 走本地解压;
+// 2) 手工把三个文件放进 apps/android-platform-tools-bin/<platformKey>/,
+// sha256 匹配即视为就位(本脚本与 forge 都只校验哈希,不关心来源)。
+//
+// 用法:
+// node apps/desktop/scripts/ensure-android-platform-tools.mjs [--platform-key=win32-x64]
+// [--force] [--print-hashes]
+// =============================================================================
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import JSZip from 'jszip';
+
+import {
+ downloadToFileWithTimeout,
+ createDownloadProgressLogger,
+} from '../../../tools/shared/fetch-with-timeout.mjs';
+// 复用 agent 二进制 de-LFS 那条链路的 sha256 工具:同一套 fail-closed 语义与错误
+// 文案,不在这里重复实现哈希校验。
+import { sha256File, sha256Hex, assertSha256 } from '../../../tools/shared/verify-sha256.mjs';
+// OSS 兜底的基址与 agent 二进制那条链路同源:同一份 config/endpoint*.json 的
+// cdnBaseUrl,同一套 region 切换(cn → hotfix.cindy.com.cn,global → hotfix.cindy.app)。
+import { loadEndpointManifestBaseUrl } from '../../../scripts/shared/client-endpoint-build-env.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');
+const BIN_ROOT = path.join(REPO_ROOT, 'apps', 'android-platform-tools-bin');
+
+/** zip 内所有条目都在这个前缀下(Google 的包结构,历代未变)。 */
+const ZIP_ENTRY_PREFIX = 'platform-tools/';
+
+/**
+ * 每个平台需要落地的文件及其期望 sha256。
+ *
+ * 只有 win32 需要 —— 它的 adb 依赖两个 AdbWin*.dll,缺一个 adb.exe 起不来。
+ * 值取自 platform-tools r32.0.0,与被本次改动删除的 Git LFS 对象 oid 完全一致。
+ */
+const PINNED = {
+ 'win32-x64': {
+ version: '32.0.0',
+ zipOs: 'windows',
+ files: {
+ 'adb.exe': 'e79dc8fc3c6385192bdccd7ff7eabe3d5c1ec292475a06b04d82759f07655982',
+ 'AdbWinApi.dll': 'd60103a5e99bc9888f786ee916f5d6e45493c3247972cb053833803de7e95cf9',
+ 'AdbWinUsbApi.dll': '25207c506d29c4e8dceb61b4bd50e8669ba26012988a43fbf26a890b1e60fc97',
+ },
+ },
+};
+
+function log(msg) {
+ console.log(`[android-platform-tools] ${msg}`);
+}
+
+export function isSupportedPlatformKey(platformKey) {
+ return Object.hasOwn(PINNED, platformKey);
+}
+
+/** 该平台需要落地的 { 文件名: 期望 sha256 };未支持的平台返回 null。 */
+export function expectedHashesFor(platformKey) {
+ const spec = PINNED[platformKey];
+ return spec ? { ...spec.files } : null;
+}
+
+/** 当前宿主对应的 platformKey;不受支持时返回 null(调用方据此跳过)。 */
+export function currentPlatformKey() {
+ if (process.platform === 'win32' && process.arch === 'x64') return 'win32-x64';
+ return null;
+}
+
+/**
+ * 从 <BIN_ROOT>/<platformKey>/source.properties 解析 pin 版本。
+ *
+ * 这个文件随二进制一起来自上游 zip,是仓库内唯一的版本事实源;缺失即报错而不是
+ * 猜 latest —— 拉到比声明更新的版本会让许可清单里的版本号说谎。
+ */
+export function readPinnedVersion(platformKey, binRoot = BIN_ROOT) {
+ const propsPath = path.join(binRoot, platformKey, 'source.properties');
+ if (!fs.existsSync(propsPath)) {
+ throw new Error(
+ `missing ${path.relative(REPO_ROOT, propsPath)} — 无法确定 pin 版本。` +
+ `该文件与 NOTICE.txt 是有意入仓的文本(不占 LFS),不应被删除。`,
+ );
+ }
+ const revision = /^Pkg\.Revision=(.+)$/m.exec(fs.readFileSync(propsPath, 'utf8'))?.[1]?.trim();
+ if (!revision) {
+ throw new Error(`cannot parse Pkg.Revision from ${path.relative(REPO_ROOT, propsPath)}`);
+ }
+ return revision;
+}
+
+export function downloadUrlFor(platformKey, version) {
+ const spec = PINNED[platformKey];
+ if (!spec) throw new Error(`unsupported platform key: ${platformKey}`);
+ // 版本化 URL(非 -latest-):锁得住版本,才能用固定 sha256 校验。
+ return `https://dl.google.com/android/repository/platform-tools_r${version}-${spec.zipOs}.zip`;
+}
+
+/**
+ * OSS 兜底基址。每次调用都读 env,便于 region 切换与测试注入(语义对齐
+ * agent-binary-cdn-fallback 的 getCdnBase)。
+ */
+export function resolveOssBaseUrl() {
+ return (
+ process.env.XDT_CDN_BASE_URL?.trim().replace(/\/+$/, '') ||
+ loadEndpointManifestBaseUrl({ authRegion: process.env.CINDY_AUTH_REGION })
+ );
+}
+
+/**
+ * OSS 上的兜底 zip 地址。约定:上游 zip 原封不动上传,文件名保持上游那个 ——
+ * 上传方 curl 下来直接传即可,不用 gzip、不用改 manifest。
+ *
+ * <cdnBaseUrl>/android-platform-tools/<version>/platform-tools_r<version>-<os>.zip
+ *
+ * 例(cn): https://hotfix.cindy.com.cn/cindy/android-platform-tools/32.0.0/platform-tools_r32.0.0-windows.zip
+ * 例(global): https://hotfix.cindy.app/cindy/android-platform-tools/32.0.0/platform-tools_r32.0.0-windows.zip
+ *
+ * 不需要 manifest:期望 sha256 硬 pin 在本文件里,比 agent 二进制那套"manifest
+ * 版本对得上才校验"的 best-effort 更严 —— OSS 上的文件被换掉一样会被拦下。
+ */
+export function ossZipUrlFor(platformKey, version, baseUrl) {
+ const spec = PINNED[platformKey];
+ if (!spec) throw new Error(`unsupported platform key: ${platformKey}`);
+ if (!baseUrl) throw new Error('OSS base url unavailable');
+ return `${baseUrl}/android-platform-tools/${version}/platform-tools_r${version}-${spec.zipOs}.zip`;
+}
+
+/** 三个文件都在、sha256 都对、且版本匹配 → 视为就位。任一不符都当作缺失重新获取。 */
+export function verifyInstalled(platformKey, binRoot = BIN_ROOT) {
+ const spec = PINNED[platformKey];
+ if (!spec) return { ok: false, reason: `unsupported platform key: ${platformKey}` };
+ // 版本绑定:source.properties 声明的版本必须与 PINNED 中哈希对应的版本一致,
+ // 否则升级 source.properties 后旧二进制会被错误地视为就位。
+ try {
+ const declaredVersion = readPinnedVersion(platformKey, binRoot);
+ if (declaredVersion !== spec.version) {
+ return {
+ ok: false,
+ reason: `version mismatch: source.properties declares ${declaredVersion} but pinned hashes are for ${spec.version}`,
+ };
+ }
+ } catch {
+ return { ok: false, reason: 'cannot read source.properties for version check' };
+ }
+ for (const [name, expected] of Object.entries(spec.files)) {
+ const filePath = path.join(binRoot, platformKey, name);
+ if (!fs.existsSync(filePath)) return { ok: false, reason: `${name} missing` };
+ const actual = sha256File(filePath);
+ if (actual !== expected) {
+ return { ok: false, reason: `${name} sha256 mismatch (expected ${expected}, got ${actual})` };
+ }
+ }
+ return { ok: true };
+}
+
+/**
+ * 从 zip buffer 里抽出该平台需要的文件,逐个校验 sha256 后写入目标目录。
+ *
+ * 先校验再落盘:校验不过就整批不写,免得留下半套二进制让 forge 以为已就位。
+ */
+async function extractVerifiedFiles(zipBuffer, platformKey, destDir) {
+ const spec = PINNED[platformKey];
+ const zip = await JSZip.loadAsync(zipBuffer);
+ const staged = new Map();
+
+ for (const [name, expected] of Object.entries(spec.files)) {
+ const entry = zip.file(`${ZIP_ENTRY_PREFIX}${name}`);
+ if (!entry) throw new Error(`zip 内找不到 ${ZIP_ENTRY_PREFIX}${name}`);
+ const content = await entry.async('nodebuffer');
+ // fail-closed:哈希不符直接抛,不落盘。上游包被替换、或 source.properties 的
+ // 版本与 pin 的哈希对不上,都会走到这里。
+ assertSha256({
+ actualHex: sha256Hex(content),
+ expected,
+ label: `${name} (platform-tools ${platformKey})`,
+ });
+ staged.set(name, content);
+ }
+
+ fs.mkdirSync(destDir, { recursive: true });
+ for (const [name, content] of staged) {
+ fs.writeFileSync(path.join(destDir, name), content);
+ }
+ return [...staged.keys()];
+}
+
+/**
+ * 确保指定平台的 platform-tools 二进制就位。
+ *
+ * @returns {Promise<{ status: 'skipped'|'installed', version: string, files?: string[] }>}
+ */
+export async function ensureAndroidPlatformTools({
+ platformKey = currentPlatformKey(),
+ force = false,
+ binRoot = BIN_ROOT,
+} = {}) {
+ if (!platformKey || !isSupportedPlatformKey(platformKey)) {
+ throw new Error(
+ `unsupported platform key: ${platformKey ?? '(none)'} — ` +
+ `仅 ${Object.keys(PINNED).join(', ')} 需要预置,其他平台由运行时按需下载。`,
+ );
+ }
+
+ const version = readPinnedVersion(platformKey, binRoot);
+ const spec = PINNED[platformKey];
+ // Fail-fast: 如果 source.properties 声明的版本与 PINNED 中哈希对应的版本不一致,
+ // 下载回来的 zip 里文件哈希必然不匹配,不如立即报错省时间和带宽。
+ if (version !== spec.version) {
+ throw new Error(
+ `版本不一致:source.properties 声明 ${version},但 PINNED 哈希对应 ${spec.version}。` +
+ `升级时需同步更新 source.properties 与脚本中的 sha256(先手工放新版文件,再用 --print-hashes 现算)。`,
+ );
+ }
+ const destDir = path.join(binRoot, platformKey);
+
+ if (!force) {
+ const installed = verifyInstalled(platformKey, binRoot);
+ if (installed.ok) {
+ log(`${platformKey}: already present @ ${version} (sha256 verified), skip`);
+ return { status: 'skipped', version };
+ }
+ log(`${platformKey}: need fetch @ ${version} — ${installed.reason}`);
+ }
+
+ // 本地 zip 出路优先:无外网/无法访问 Google 的打包机靠它离线完成。
+ const localZip = process.env.CINDY_ANDROID_PLATFORM_TOOLS_ZIP?.trim();
+ if (localZip) {
+ if (!fs.existsSync(localZip)) {
+ throw new Error(`CINDY_ANDROID_PLATFORM_TOOLS_ZIP 指向的文件不存在:${localZip}`);
+ }
+ log(`${platformKey}: 使用本地 zip ${localZip}`);
+ const files = await extractVerifiedFiles(fs.readFileSync(localZip), platformKey, destDir);
+ log(`${platformKey}: installed @ ${version} from local zip (${files.join(', ')})`);
+ return { status: 'installed', version, files };
+ }
+
+ // 依次尝试各来源。默认 upstream 先、OSS 兜底(与 agent 二进制那条链路同序);
+ // 国内打包机可设 CINDY_ANDROID_PLATFORM_TOOLS_PREFER_OSS=1 直接走 OSS,免得每次
+ // 先吃一轮 dl.google.com 的连接超时。
+ const preferOss = /^(1|true|yes)$/i.test(
+ process.env.CINDY_ANDROID_PLATFORM_TOOLS_PREFER_OSS?.trim() ?? '',
+ );
+ const order = preferOss ? ['oss', 'upstream'] : ['upstream', 'oss'];
+
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-platform-tools-'));
+ const tmpZip = path.join(tmpDir, 'platform-tools.zip');
+ const attempts = [];
+ try {
+ for (let i = 0; i < order.length; i++) {
+ const source = order[i];
+ const isLastSource = i === order.length - 1;
+ let url;
+ try {
+ url =
+ source === 'upstream'
+ ? downloadUrlFor(platformKey, version)
+ : ossZipUrlFor(platformKey, version, resolveOssBaseUrl());
+ } catch (err) {
+ // OSS 基址解析不出来(端点清单缺失/region 非法)时只跳过这一路,不掩盖上游的错。
+ attempts.push(`${source}: ${err.message}`);
+ continue;
+ }
+ try {
+ log(`${platformKey}: downloading from ${source} — ${url}`);
+ const progress = createDownloadProgressLogger(`platform-tools ${platformKey} ${source}`);
+ try {
+ // 最后一个来源(无论名字是 oss 还是 upstream)没有退路:给宽松超时并
+ // 禁用吞吐下限,避免把"慢但能成"变成失败。非末位来源用默认值快速失败
+ // 以便尽快尝试下一个。
+ await downloadToFileWithTimeout(
+ url,
+ tmpZip,
+ {},
+ isLastSource
+ ? {
+ connectTimeoutMs: 15_000,
+ stallTimeoutMs: 20_000,
+ totalTimeoutMs: 1_800_000,
+ minThroughputBytesPerSec: 0,
+ onProgress: progress.onProgress,
+ }
+ : { onProgress: progress.onProgress },
+ );
+ } finally {
+ progress.finish();
+ }
+ // 校验对所有来源同一套硬 pin sha256:OSS 上的文件被换掉同样会被拦下,
+ // 所以多一个来源不等于多一份信任。
+ const files = await extractVerifiedFiles(fs.readFileSync(tmpZip), platformKey, destDir);
+ log(`${platformKey}: installed @ ${version} from ${source} (${files.join(', ')})`);
+ return { status: 'installed', version, files, source };
+ } catch (err) {
+ attempts.push(`${source} (${url}): ${err.message}`);
+ try { fs.rmSync(tmpZip, { force: true }); } catch { /* ignore */ }
+ }
+ }
+ throw new Error(
+ `无法就位 Android platform-tools ${platformKey}@${version}:所有来源均失败\n` +
+ attempts.map((a) => ` - ${a}`).join('\n') + '\n' +
+ ` 出路 1: 设 CINDY_ANDROID_PLATFORM_TOOLS_ZIP=<本地 zip 路径> 后重试;\n` +
+ ` 出路 2: 手工把 ${Object.keys(PINNED[platformKey].files).join(' / ')} 放进 ` +
+ `apps/android-platform-tools-bin/${platformKey}/(sha256 需匹配)。`,
+ );
+ } finally {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ }
+}
+
+function parseArgs(argv) {
+ const out = { platformKey: currentPlatformKey(), force: false, printHashes: false };
+ for (const arg of argv) {
+ if (arg === '--force') out.force = true;
+ else if (arg === '--print-hashes') out.printHashes = true;
+ else if (arg.startsWith('--platform-key=')) out.platformKey = arg.slice('--platform-key='.length);
+ else throw new Error(`unknown argument: ${arg}`);
+ }
+ return out;
+}
+
+// 直接执行时作为 CLI 跑;被 import 时(forge / package-desktop)只暴露函数。
+if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.printHashes) {
+ // 升级版本时用:先手工放好新版三个文件,再用它打印新 sha256 回填 PINNED。
+ const key = args.platformKey ?? 'win32-x64';
+ for (const name of Object.keys(PINNED[key]?.files ?? {})) {
+ const p = path.join(BIN_ROOT, key, name);
+ console.log(`${fs.existsSync(p) ? sha256File(p) : '(missing)'} ${name}`);
+ }
+ } else {
+ ensureAndroidPlatformTools(args).catch((err) => {
+ console.error(`ERROR: ${err.message}`);
+ process.exit(1);
+ });
+ }
+}
diff --git a/package.json b/package.json
index fdca2c4a76..3d77535deb 100644
--- a/package.json
+++ b/package.json
@@ -108,7 +108,7 @@
"licenses:generate": "node scripts/generate-third-party-notices.mjs",
"lint": "pnpm -r lint",
"format": "pnpm -r format",
- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/glossary-rules.test.mjs",
+ "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/glossary-rules.test.mjs",
"test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit",
"test:all": "pnpm test:runner && node scripts/test-workspaces.mjs --all",
"test:db": "pnpm test:runner && node scripts/test-workspaces.mjs --tier db",
diff --git a/scripts/__tests__/ensure-android-platform-tools.test.mjs b/scripts/__tests__/ensure-android-platform-tools.test.mjs
new file mode 100644
index 0000000000..c6850685de
--- /dev/null
+++ b/scripts/__tests__/ensure-android-platform-tools.test.mjs
@@ -0,0 +1,184 @@
+// ensure-android-platform-tools 纯辅助函数的单测。
+//
+// 这些 helper 是 adb de-LFS 改动的正确性核心:版本必须从 source.properties 读
+// (与许可清单同源,否则清单里的版本号会说谎),就位判定必须逐文件校验 sha256
+// (否则半套二进制或被替换的上游包会被当成"已就位"直接打进安装包)。
+// 用 node 内置 test runner,不碰网络、不依赖 vitest。
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import {
+ currentPlatformKey,
+ downloadUrlFor,
+ expectedHashesFor,
+ isSupportedPlatformKey,
+ ossZipUrlFor,
+ readPinnedVersion,
+ resolveOssBaseUrl,
+ verifyInstalled,
+} from '../../apps/desktop/scripts/ensure-android-platform-tools.mjs';
+// 哈希工具本身由 verify-sha256.test.mjs 覆盖,这里只借它做一致性比对。
+import { sha256File } from '../../tools/shared/verify-sha256.mjs';
+
+const REPO_ROOT = path.resolve(import.meta.dirname, '..', '..');
+const REAL_BIN_ROOT = path.join(REPO_ROOT, 'apps', 'android-platform-tools-bin');
+
+function tmpBinRoot(platformKey, files) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'android-pt-test-'));
+ const dir = path.join(root, platformKey);
+ fs.mkdirSync(dir, { recursive: true });
+ for (const [name, contents] of Object.entries(files)) {
+ fs.writeFileSync(path.join(dir, name), contents);
+ }
+ return root;
+}
+
+test('isSupportedPlatformKey: 只有 win32-x64 需要预置', () => {
+ assert.equal(isSupportedPlatformKey('win32-x64'), true);
+ // 其他平台由运行时按需下载到 userData,不该被本脚本认领。
+ assert.equal(isSupportedPlatformKey('darwin-arm64'), false);
+ assert.equal(isSupportedPlatformKey('linux-x64'), false);
+ assert.equal(isSupportedPlatformKey('nonsense'), false);
+});
+
+test('currentPlatformKey: 非 win32-x64 宿主返回 null', () => {
+ const key = currentPlatformKey();
+ if (process.platform === 'win32' && process.arch === 'x64') {
+ assert.equal(key, 'win32-x64');
+ } else {
+ assert.equal(key, null);
+ }
+});
+
+test('expectedHashesFor: win32-x64 三个文件都 pin 了合法 sha256', () => {
+ const hashes = expectedHashesFor('win32-x64');
+ assert.deepEqual(Object.keys(hashes).sort(), ['AdbWinApi.dll', 'AdbWinUsbApi.dll', 'adb.exe']);
+ for (const [name, hash] of Object.entries(hashes)) {
+ assert.match(hash, /^[0-9a-f]{64}$/, `${name} 的 pin 不是 64 位小写 hex sha256`);
+ }
+ assert.equal(expectedHashesFor('darwin-arm64'), null);
+});
+
+test('readPinnedVersion: 从 source.properties 的 Pkg.Revision 读版本', () => {
+ const root = tmpBinRoot('win32-x64', {
+ 'source.properties': 'Pkg.UserSrc=false\nPkg.Revision=32.0.0',
+ });
+ assert.equal(readPinnedVersion('win32-x64', root), '32.0.0');
+});
+
+test('readPinnedVersion: 文件缺失或没有 Pkg.Revision 时报错,不猜 latest', () => {
+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'android-pt-empty-'));
+ assert.throws(() => readPinnedVersion('win32-x64', empty), /source\.properties/);
+
+ const noRevision = tmpBinRoot('win32-x64', { 'source.properties': 'Pkg.UserSrc=false\n' });
+ assert.throws(() => readPinnedVersion('win32-x64', noRevision), /Pkg\.Revision/);
+});
+
+test('readPinnedVersion: 仓库内真实 source.properties 可解析(与许可清单同源)', () => {
+ const version = readPinnedVersion('win32-x64', REAL_BIN_ROOT);
+ assert.match(version, /^\d+\.\d+\.\d+$/);
+});
+
+test('downloadUrlFor: 用版本化 URL 而不是 -latest-(否则 sha256 pin 无意义)', () => {
+ assert.equal(
+ downloadUrlFor('win32-x64', '32.0.0'),
+ 'https://dl.google.com/android/repository/platform-tools_r32.0.0-windows.zip',
+ );
+ assert.throws(() => downloadUrlFor('darwin-arm64', '32.0.0'), /unsupported platform key/);
+});
+
+test('ossZipUrlFor: 上传约定为「原始 zip 原名放在 <base>/android-platform-tools/<version>/」', () => {
+ assert.equal(
+ ossZipUrlFor('win32-x64', '32.0.0', 'https://hotfix.cindy.com.cn/cindy'),
+ 'https://hotfix.cindy.com.cn/cindy/android-platform-tools/32.0.0/platform-tools_r32.0.0-windows.zip',
+ );
+ // 海外 region 只换 base,路径结构不变。
+ assert.equal(
+ ossZipUrlFor('win32-x64', '32.0.0', 'https://hotfix.cindy.app/cindy'),
+ 'https://hotfix.cindy.app/cindy/android-platform-tools/32.0.0/platform-tools_r32.0.0-windows.zip',
+ );
+ assert.throws(() => ossZipUrlFor('darwin-arm64', '32.0.0', 'https://x.test'), /unsupported platform key/);
+ assert.throws(() => ossZipUrlFor('win32-x64', '32.0.0', ''), /OSS base url unavailable/);
+});
+
+test('resolveOssBaseUrl: 优先 XDT_CDN_BASE_URL,否则回落端点清单的 cdnBaseUrl', (t) => {
+ const original = process.env.XDT_CDN_BASE_URL;
+ t.after(() => {
+ if (original === undefined) delete process.env.XDT_CDN_BASE_URL;
+ else process.env.XDT_CDN_BASE_URL = original;
+ });
+
+ process.env.XDT_CDN_BASE_URL = 'https://override.test/base/';
+ // 尾部斜杠要被去掉,否则拼出来会是双斜杠。
+ assert.equal(resolveOssBaseUrl(), 'https://override.test/base');
+
+ delete process.env.XDT_CDN_BASE_URL;
+ const fromManifest = resolveOssBaseUrl();
+ assert.match(fromManifest, /^https:\/\//);
+ assert.doesNotMatch(fromManifest, /\/$/);
+});
+
+test('verifyInstalled: 缺少 source.properties 时不算就位', () => {
+ const root = tmpBinRoot('win32-x64', { 'adb.exe': 'not the real adb' });
+ const r = verifyInstalled('win32-x64', root);
+ assert.equal(r.ok, false);
+ assert.match(r.reason, /source\.properties/);
+});
+
+test('verifyInstalled: source.properties 版本与 PINNED 不匹配时不算就位', () => {
+ const root = tmpBinRoot('win32-x64', {
+ 'source.properties': 'Pkg.Revision=99.0.0',
+ 'adb.exe': 'fake',
+ });
+ const r = verifyInstalled('win32-x64', root);
+ assert.equal(r.ok, false);
+ assert.match(r.reason, /version mismatch/);
+});
+
+test('verifyInstalled: 文件缺失时不算就位', () => {
+ const root = tmpBinRoot('win32-x64', {
+ 'source.properties': 'Pkg.Revision=32.0.0',
+ 'adb.exe': 'not the real adb',
+ });
+ const r = verifyInstalled('win32-x64', root);
+ assert.equal(r.ok, false);
+ assert.match(r.reason, /sha256 mismatch/);
+});
+
+test('verifyInstalled: 内容被换掉时报 sha256 不匹配', () => {
+ const hashes = expectedHashesFor('win32-x64');
+ // 三个文件都在,但内容是假的 —— 必须被逐个哈希拦下。
+ const files = Object.fromEntries(Object.keys(hashes).map((name) => [name, `fake ${name}`]));
+ files['source.properties'] = 'Pkg.Revision=32.0.0';
+ const root = tmpBinRoot('win32-x64', files);
+ const r = verifyInstalled('win32-x64', root);
+ assert.equal(r.ok, false);
+ assert.match(r.reason, /sha256 mismatch/);
+});
+
+test('verifyInstalled: 未支持的平台不被认为已就位', () => {
+ const root = tmpBinRoot('darwin-arm64', { adb: 'x' });
+ assert.equal(verifyInstalled('darwin-arm64', root).ok, false);
+});
+
+test('pin 的哈希与本机已就位文件一致(文件不在则跳过)', (t) => {
+ const hashes = expectedHashesFor('win32-x64');
+ const present = Object.keys(hashes).filter((name) =>
+ fs.existsSync(path.join(REAL_BIN_ROOT, 'win32-x64', name)),
+ );
+ if (present.length === 0) {
+ // CI / 干净 clone 上这些二进制尚未下载(已 gitignore),无从比对。
+ t.skip('platform-tools 二进制未就位,跳过一致性比对');
+ return;
+ }
+ for (const name of present) {
+ assert.equal(
+ sha256File(path.join(REAL_BIN_ROOT, 'win32-x64', name)),
+ hashes[name],
+ `${name} 的实际哈希与 pin 不一致 —— 要么本地文件被换过,要么 pin 该更新了`,
+ );
+ }
+});