豆包复刻:原生安卓(Compose + 内嵌 Termux)+ Web / Windows
一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、 不需要另外装 Termux。 安卓端 - 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的 - 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹 - 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端; pty 不可用的 ROM 上自动降级成命令控制台 - APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上 - 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板 - 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎 AI 能力 - 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义 - 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发), 认不出来的一律不发,避免给不支持的厂商发字段直接 400 - MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式 跨端 - 安卓走原生 Compose,Web / Windows 走 Lynx - Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本 自检脚本(都不需要真 Key) - verify-phone.mjs 设备端 24 项验收 - verify-speech.mjs 语音链路 31 项,两份内核各跑一遍 - parity-thinking.mjs 思考强度映射对拍 - probe-settings-wipe.mjs 设置防清空攻击测试 - mock-llm.mjs 假的 OpenAI + 火山语音服务 许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron) 的授权见 LICENSE。
This commit is contained in:
130
scripts/android-setup.mjs
Normal file
130
scripts/android-setup.mjs
Normal file
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* 下载并安装 Android 命令行工具链(不需要 Android Studio)。
|
||||
* 用法: node scripts/android-setup.mjs [sdkRoot]
|
||||
* 默认装到 C:\Android\Sdk —— 必须是纯 ASCII 路径。
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const positional = argv.filter((a) => !a.startsWith('--'));
|
||||
const SDK = positional[0] || 'C:\\Android\\Sdk';
|
||||
const CACHE = path.join(SDK, '.cache');
|
||||
|
||||
const CMDLINE_TOOLS = [
|
||||
'https://dl.google.com/android/repository/commandlinetools-win-11076708_latest.zip',
|
||||
'https://mirrors.cloud.tencent.com/AndroidSDK/commandlinetools-win-11076708_latest.zip',
|
||||
];
|
||||
const GRADLE_URLS = [
|
||||
'https://services.gradle.org/distributions/gradle-8.14-bin.zip',
|
||||
'https://mirrors.cloud.tencent.com/gradle/gradle-8.14-bin.zip',
|
||||
];
|
||||
const GRADLE_DIR = 'C:\\Android\\gradle-8.14';
|
||||
|
||||
function log(msg) {
|
||||
console.log(`[android] ${msg}`);
|
||||
}
|
||||
|
||||
/** 流式下载并打印进度,避免大文件全缓存在内存里看不出动静 */
|
||||
async function download(urls, dest) {
|
||||
if (fs.existsSync(dest) && fs.statSync(dest).size > 1024 * 1024) {
|
||||
log(`已有缓存 ${path.basename(dest)}:${(fs.statSync(dest).size / 1024 / 1024).toFixed(1)} MB`);
|
||||
return dest;
|
||||
}
|
||||
const list = Array.isArray(urls) ? urls : [urls];
|
||||
let lastError = null;
|
||||
for (const url of list) {
|
||||
try {
|
||||
log(`下载 ${url}`);
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(1800000) });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const total = Number(res.headers.get('content-length') || 0);
|
||||
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
||||
const out = fs.createWriteStream(dest);
|
||||
let got = 0;
|
||||
let lastLog = 0;
|
||||
for await (const chunk of res.body) {
|
||||
out.write(chunk);
|
||||
got += chunk.length;
|
||||
const now = Date.now();
|
||||
if (now - lastLog > 3000) {
|
||||
lastLog = now;
|
||||
const pct = total ? ` ${((got / total) * 100).toFixed(0)}%` : '';
|
||||
log(` ${(got / 1024 / 1024).toFixed(1)} MB${pct}`);
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => out.end(resolve));
|
||||
log(` 完成 ${(got / 1024 / 1024).toFixed(1)} MB`);
|
||||
return dest;
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
log(` 失败:${err.message},换下一个源`);
|
||||
fs.rmSync(dest, { force: true });
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
function run(cmd, args, opts = {}) {
|
||||
log(`$ ${cmd} ${args.join(' ')}`);
|
||||
// Windows 上 .bat/.cmd 必须走 shell —— Node 20+ 出于安全考虑不允许直接 spawn 批处理
|
||||
const needsShell = /\.(bat|cmd)$/i.test(cmd);
|
||||
const res = spawnSync(cmd, args, { stdio: 'inherit', shell: needsShell, ...opts });
|
||||
return res.status;
|
||||
}
|
||||
|
||||
fs.mkdirSync(SDK, { recursive: true });
|
||||
fs.mkdirSync(CACHE, { recursive: true });
|
||||
|
||||
/* ---------------- 1. cmdline-tools ---------------- */
|
||||
const toolsZip = path.join(CACHE, 'cmdline-tools.zip');
|
||||
await download(CMDLINE_TOOLS, toolsZip);
|
||||
|
||||
const toolsRoot = path.join(SDK, 'cmdline-tools');
|
||||
if (!fs.existsSync(path.join(toolsRoot, 'latest', 'bin', 'sdkmanager.bat'))) {
|
||||
log('解压 cmdline-tools…');
|
||||
fs.mkdirSync(toolsRoot, { recursive: true });
|
||||
const tmp = path.join(CACHE, 'cmdline-tools-extract');
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
fs.mkdirSync(tmp, { recursive: true });
|
||||
if (run('tar', ['-xf', toolsZip, '-C', tmp]) !== 0) throw new Error('解压 cmdline-tools 失败');
|
||||
fs.renameSync(path.join(tmp, 'cmdline-tools'), path.join(toolsRoot, 'latest'));
|
||||
}
|
||||
|
||||
const sdkmanager = path.join(toolsRoot, 'latest', 'bin', 'sdkmanager.bat');
|
||||
|
||||
/* ---------------- 2. 平台与构建工具 ---------------- */
|
||||
const packages = [
|
||||
'platform-tools',
|
||||
'platforms;android-35',
|
||||
'build-tools;35.0.0',
|
||||
];
|
||||
const skipSdk = argv.includes('--skip-sdk');
|
||||
|
||||
if (!skipSdk) {
|
||||
log('接受 SDK 许可…');
|
||||
// 用 stdin 连喂一堆 y;不要走 cmd /c "...",Node 会转义里面的引号导致命令找不到
|
||||
spawnSync(sdkmanager, [`--sdk_root=${SDK}`, '--licenses'], {
|
||||
input: 'y\n'.repeat(80),
|
||||
stdio: ['pipe', 'inherit', 'inherit'],
|
||||
});
|
||||
|
||||
log('安装 SDK 组件(第一次要下载几百 MB)…');
|
||||
const code = run(sdkmanager, [`--sdk_root=${SDK}`, ...packages]);
|
||||
if (code !== 0) throw new Error('sdkmanager 安装组件失败');
|
||||
} else {
|
||||
log('跳过 SDK 组件安装');
|
||||
}
|
||||
|
||||
/* ---------------- 3. Gradle ---------------- */
|
||||
if (!fs.existsSync(path.join(GRADLE_DIR, 'bin', 'gradle.bat'))) {
|
||||
const gradleZip = await download(GRADLE_URLS, path.join(CACHE, 'gradle.zip'));
|
||||
log('解压 Gradle…');
|
||||
fs.mkdirSync('C:\\Android', { recursive: true });
|
||||
if (run('tar', ['-xf', gradleZip, '-C', 'C:\\Android']) !== 0) throw new Error('解压 Gradle 失败');
|
||||
}
|
||||
|
||||
log('完成');
|
||||
console.log(` SDK : ${SDK}`);
|
||||
console.log(` Gradle : ${GRADLE_DIR}`);
|
||||
170
scripts/build-apk.mjs
Normal file
170
scripts/build-apk.mjs
Normal file
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* 打包 Android APK。
|
||||
*
|
||||
* 两个关键点:
|
||||
* 1. 构建在纯 ASCII 路径(C:\DoubaoAndroid)里做 —— 工作区目录是中文,Gradle/AGP 对它不一定友好
|
||||
* 2. Python 工具要拷进 Chaquopy 的源集目录,APK 里才有内置工具可播种
|
||||
*
|
||||
* 注意:安卓端已经**不用 Lynx 了**(界面重写成原生 Compose),
|
||||
* 所以这里不再构建/拷贝 main.lynx.bundle。
|
||||
*
|
||||
* 用法: node scripts/build-apk.mjs [--skip-build] [--release]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repo = path.resolve(here, '..');
|
||||
const STAGE = 'C:\\DoubaoAndroid';
|
||||
const SDK = 'C:\\Android\\Sdk';
|
||||
const GRADLE = 'C:\\Android\\gradle-8.14\\bin\\gradle.bat';
|
||||
const JAVA_HOME = process.env.JAVA_HOME || 'C:\\Program Files\\Microsoft\\jdk-17.0.19.10-hotspot';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const skipBuild = args.includes('--skip-build');
|
||||
const release = args.includes('--release');
|
||||
|
||||
function log(msg) {
|
||||
console.log(`[apk] ${msg}`);
|
||||
}
|
||||
|
||||
function run(cmd, argv, opts = {}) {
|
||||
// Windows 上 .bat/.cmd 必须走 shell:Node 20+ 不允许直接 spawn 批处理(会返回 status=null)
|
||||
const needsShell = /\.(bat|cmd)$/i.test(cmd) || opts.shell === true;
|
||||
const res = spawnSync(cmd, argv, {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, JAVA_HOME, ANDROID_HOME: SDK, ANDROID_SDK_ROOT: SDK },
|
||||
...opts,
|
||||
shell: needsShell,
|
||||
});
|
||||
if (res.status !== 0) throw new Error(`${cmd} ${argv.join(' ')} 退出码 ${res.status}`);
|
||||
}
|
||||
|
||||
// 安卓端不再用 Lynx,所以没有前端产物要构建/拷贝;
|
||||
// 界面是 android/app/src/main/java/.../ui 下的原生 Compose。
|
||||
if (!skipBuild) {
|
||||
log('界面是原生 Compose,无需构建前端产物');
|
||||
}
|
||||
|
||||
/* ---------------- 2. 同步工程到 ASCII 路径 ---------------- */
|
||||
/** 手写递归拷贝:fs.cpSync 带 filter 时在这套环境下会把 Node 直接搞崩(0xC0000409) */
|
||||
function copyTree(from, to, skipDirs) {
|
||||
const stat = fs.statSync(from);
|
||||
if (stat.isDirectory()) {
|
||||
if (skipDirs.has(path.basename(from))) return;
|
||||
fs.mkdirSync(to, { recursive: true });
|
||||
for (const entry of fs.readdirSync(from)) {
|
||||
copyTree(path.join(from, entry), path.join(to, entry), skipDirs);
|
||||
}
|
||||
return;
|
||||
}
|
||||
fs.copyFileSync(from, to);
|
||||
}
|
||||
|
||||
log(`同步工程到 ${STAGE}…`);
|
||||
// ★ 不要整个删掉 STAGE:
|
||||
// Chaquopy 每次构建都要去 PyPI 拉 requests/httpx,网络一抖就整个构建失败。
|
||||
// 保留 app/build(里面有 Chaquopy 的 python env 和下载缓存)+ .gradle,就能增量复用。
|
||||
// 需要彻底重建时加 --clean。
|
||||
const clean = args.includes('--clean');
|
||||
if (clean) {
|
||||
log('--clean:删除整个构建目录');
|
||||
fs.rmSync(STAGE, { recursive: true, force: true });
|
||||
}
|
||||
fs.mkdirSync(STAGE, { recursive: true });
|
||||
copyTree(path.join(repo, 'android'), STAGE, new Set(['build', '.gradle', '.idea', '__pycache__']));
|
||||
log('已复制工程文件');
|
||||
|
||||
/* ---------------- 3. 清掉上一版可能残留的 Lynx 产物 ---------------- */
|
||||
const assets = path.join(STAGE, 'app', 'src', 'main', 'assets');
|
||||
if (fs.existsSync(assets)) {
|
||||
for (const leftover of ['main.lynx.bundle', 'static', 'lynx_core.js']) {
|
||||
const target = path.join(assets, leftover);
|
||||
if (fs.existsSync(target)) {
|
||||
fs.rmSync(target, { recursive: true, force: true });
|
||||
log(`清掉旧的 Lynx 产物 ${leftover}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 3.5 把 Python 工具打进 APK 的 Python 源集 ---------------- */
|
||||
// 这些 *.py 会落到 Python 的 import 根目录,内核首次启动时把它们复制到
|
||||
// 手机上的可写工具目录(用户可以自己改/加),所以这里是"出厂内置版"。
|
||||
//
|
||||
// ★ 为什么要额外生成 bundled_tool_sources.py:
|
||||
// Chaquopy 把 .py 编译成 .pyc 放进 app.imy,运行期 **拿不到源码**
|
||||
// (importlib 的 loader.get_source() 对 .pyc-only 的包不可用),
|
||||
// 于是"把内置工具播种到可写目录"这一步会一个文件都写不出来。
|
||||
// 所以构建时把源码 base64 嵌进去,运行期解码即可。
|
||||
const pyRoot = path.join(STAGE, 'app', 'src', 'main', 'python');
|
||||
fs.mkdirSync(pyRoot, { recursive: true });
|
||||
const toolSources = {};
|
||||
let toolCount = 0;
|
||||
for (const file of fs.readdirSync(path.join(repo, 'tools'))) {
|
||||
if (!file.endsWith('.py')) continue;
|
||||
const source = fs.readFileSync(path.join(repo, 'tools', file));
|
||||
fs.writeFileSync(path.join(pyRoot, file), source);
|
||||
toolSources[file] = source.toString('base64');
|
||||
toolCount += 1;
|
||||
}
|
||||
const bundledPy = [
|
||||
'"""构建时自动生成,不要手改。',
|
||||
'',
|
||||
'内置 Python 工具的源码(base64)。安卓端 Chaquopy 只有 .pyc,',
|
||||
'所以由 scripts/build-apk.mjs 在打包时把源码嵌进来,',
|
||||
'由 doubao_entry 首次启动时解码写到手机上的可写工具目录。',
|
||||
'"""',
|
||||
'',
|
||||
'import base64',
|
||||
'',
|
||||
'_DATA = {',
|
||||
...Object.entries(toolSources).map(([name, b64]) => ` ${JSON.stringify(name)}: ${JSON.stringify(b64)},`),
|
||||
'}',
|
||||
'',
|
||||
'',
|
||||
'def sources():',
|
||||
' """返回 {文件名: 源码文本}"""',
|
||||
' return {name: base64.b64decode(data).decode("utf-8") for name, data in _DATA.items()}',
|
||||
'',
|
||||
].join('\n');
|
||||
fs.writeFileSync(path.join(pyRoot, 'bundled_tool_sources.py'), bundledPy, 'utf8');
|
||||
log(`已内置 ${toolCount} 个 Python 工具(含源码与 _protocol.py)`);
|
||||
|
||||
// 内核源码在 android/kernel,靠 chaquopy 的 srcDir("../kernel") 引入;
|
||||
// 这里检查一下它确实在
|
||||
if (!fs.existsSync(path.join(STAGE, 'kernel', 'main.py'))) {
|
||||
log('⚠️ 没找到 android/kernel/main.py,安卓端本地内核会起不来');
|
||||
}
|
||||
|
||||
fs.writeFileSync(path.join(STAGE, 'local.properties'), `sdk.dir=${SDK.replace(/\\/g, '\\\\')}\n`, 'utf8');
|
||||
fs.writeFileSync(
|
||||
path.join(STAGE, 'app', 'src', 'main', 'assets', '.gitignore'),
|
||||
'',
|
||||
'utf8',
|
||||
);
|
||||
|
||||
/* ---------------- 4. Gradle 构建 ---------------- */
|
||||
const task = release ? 'assembleRelease' : 'assembleDebug';
|
||||
log(`gradle ${task} …`);
|
||||
run(GRADLE, ['-p', STAGE, task, '--no-daemon', '--console=plain']);
|
||||
|
||||
/* ---------------- 5. 收尾 ---------------- */
|
||||
const variant = release ? 'release' : 'debug';
|
||||
const apkDir = path.join(STAGE, 'app', 'build', 'outputs', 'apk', variant);
|
||||
const apk = fs.readdirSync(apkDir).find((f) => f.endsWith('.apk'));
|
||||
if (!apk) throw new Error(`没找到 APK:${apkDir}`);
|
||||
|
||||
const outDir = path.join(repo, 'dist-android');
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
const outName = release ? 'doubao-release.apk' : 'doubao-debug.apk';
|
||||
fs.copyFileSync(path.join(apkDir, apk), path.join(outDir, outName));
|
||||
|
||||
log('完成 ✅');
|
||||
console.log('');
|
||||
console.log(` APK:${path.join(outDir, outName)}`);
|
||||
console.log(` 体积:${(fs.statSync(path.join(outDir, outName)).size / 1024 / 1024).toFixed(1)} MB`);
|
||||
console.log('');
|
||||
console.log(` 安装:adb install -r "${path.join(outDir, outName)}"`);
|
||||
console.log(' 模拟器连宿主机内核:adb reverse tcp:5199 tcp:5199');
|
||||
179
scripts/build-exe.mjs
Normal file
179
scripts/build-exe.mjs
Normal file
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* 打包 Windows 桌面版(Electron)。
|
||||
*
|
||||
* ⚠️ 一个必须知道的坑:Electron 的 exe 放在**非 ASCII 目录**下会在启动时崩溃(0xC0000005),
|
||||
* 所以输出目录固定用纯英文路径,工作区里的中文目录不能直接放 exe。
|
||||
* exe 的**文件名**可以是中文,这个没问题。
|
||||
*
|
||||
* 用法: node scripts/build-exe.mjs [--skip-build] [--out D:\some\ascii\dir]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repo = path.resolve(here, '..');
|
||||
const desktopDir = path.join(repo, 'desktop');
|
||||
const staging = path.join(desktopDir, 'dist-staging');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const skipBuild = args.includes('--skip-build');
|
||||
const outIndex = args.indexOf('--out');
|
||||
const OUT_DIR = outIndex >= 0 && args[outIndex + 1]
|
||||
? path.resolve(args[outIndex + 1])
|
||||
: 'C:\\Users\\Administrator\\Documents\\DoubaoClone';
|
||||
|
||||
const APP_NAME = 'Doubao'; // 必须 ASCII:决定输出文件夹名
|
||||
const EXE_NAME = '\u8c46\u5305.exe'; // 豆包.exe:文件名可以是中文
|
||||
const version = JSON.parse(fs.readFileSync(path.join(desktopDir, 'package.json'), 'utf8')).version;
|
||||
|
||||
function log(msg) {
|
||||
console.log(`[build-exe] ${msg}`);
|
||||
}
|
||||
|
||||
function run(cmd, argv, opts = {}) {
|
||||
const res = spawnSync(cmd, argv, { stdio: 'inherit', shell: true, ...opts });
|
||||
if (res.status !== 0) throw new Error(`${cmd} ${argv.join(' ')} 退出码 ${res.status}`);
|
||||
}
|
||||
|
||||
function rm(target) {
|
||||
fs.rmSync(target, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function copy(from, to, filter) {
|
||||
if (!fs.existsSync(from)) throw new Error(`缺少 ${from}`);
|
||||
fs.cpSync(from, to, { recursive: true, filter });
|
||||
}
|
||||
|
||||
/* ------------------------------ 1. 构建界面 ------------------------------ */
|
||||
if (!skipBuild) {
|
||||
log('构建 Lynx 界面产物…');
|
||||
run('npm', ['--prefix', 'app', 'run', 'build'], { cwd: repo });
|
||||
}
|
||||
|
||||
/* ------------------------------ 2. 准备暂存目录 ------------------------------ */
|
||||
log('准备暂存目录…');
|
||||
rm(staging);
|
||||
fs.mkdirSync(staging, { recursive: true });
|
||||
|
||||
// 2.1 Electron 主进程 + package.json
|
||||
fs.copyFileSync(path.join(desktopDir, 'main.cjs'), path.join(staging, 'main.cjs'));
|
||||
fs.mkdirSync(path.join(staging, 'build'), { recursive: true });
|
||||
for (const f of ['icon.ico', 'icon.png']) {
|
||||
const src = path.join(desktopDir, 'build', f);
|
||||
if (fs.existsSync(src)) fs.copyFileSync(src, path.join(staging, 'build', f));
|
||||
}
|
||||
fs.writeFileSync(
|
||||
path.join(staging, 'package.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'doubao-desktop',
|
||||
productName: APP_NAME, // 用 ASCII:%APPDATA% 下的数据目录也跟着是英文,稳妥
|
||||
version,
|
||||
description: '\u8c46\u5305 \u00b7 LynxJS \u590d\u523b\uff08\u684c\u9762\u7248\uff09',
|
||||
main: 'main.cjs',
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
// 2.2 AI 内核(源码 + 依赖)
|
||||
log('复制 AI 内核…');
|
||||
fs.mkdirSync(path.join(staging, 'server'), { recursive: true });
|
||||
copy(path.join(repo, 'server', 'src'), path.join(staging, 'server', 'src'));
|
||||
if (fs.existsSync(path.join(repo, 'server', 'config'))) {
|
||||
copy(path.join(repo, 'server', 'config'), path.join(staging, 'server', 'config'));
|
||||
}
|
||||
fs.copyFileSync(path.join(repo, 'server', 'package.json'), path.join(staging, 'server', 'package.json'));
|
||||
copy(path.join(repo, 'server', 'node_modules'), path.join(staging, 'server', 'node_modules'));
|
||||
|
||||
// 2.3 运行时资源:Lynx 产物 / 宿主页 / web-core / python 工具
|
||||
log('复制运行时资源…');
|
||||
const runtime = path.join(staging, 'runtime');
|
||||
fs.mkdirSync(runtime, { recursive: true });
|
||||
copy(path.join(repo, 'app', 'dist'), path.join(runtime, 'app', 'dist'));
|
||||
copy(path.join(repo, 'web'), path.join(runtime, 'web'));
|
||||
copy(
|
||||
path.join(repo, 'app', 'node_modules', '@lynx-js', 'web-core', 'dist', 'client_prod', 'static'),
|
||||
path.join(runtime, 'web-core'),
|
||||
);
|
||||
copy(path.join(repo, 'tools'), path.join(runtime, 'tools'), (src) => !src.includes('__pycache__'));
|
||||
|
||||
// 2.4 打包版 MCP 配置:文件系统服务的目录指向数据目录,用占位符避免写死路径
|
||||
const mcpPath = path.join(runtime, 'tools', 'mcp.servers.json');
|
||||
if (fs.existsSync(mcpPath)) {
|
||||
const conf = JSON.parse(fs.readFileSync(mcpPath, 'utf8'));
|
||||
conf.servers = (conf.servers || []).map((s) =>
|
||||
s.name === 'filesystem'
|
||||
? { ...s, enabled: true, args: ['-y', '@modelcontextprotocol/server-filesystem', '${DOUBAO_DATA}'] }
|
||||
: s);
|
||||
fs.writeFileSync(mcpPath, JSON.stringify(conf, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/* ------------------------------ 3. 调 electron-packager ------------------------------ */
|
||||
log(`打包到 ${OUT_DIR} …`);
|
||||
const packager = path.join(desktopDir, 'node_modules', '.bin', 'electron-packager.cmd');
|
||||
if (!fs.existsSync(packager)) throw new Error('没找到 electron-packager,先在 desktop/ 里 npm install');
|
||||
|
||||
fs.mkdirSync(OUT_DIR, { recursive: true });
|
||||
run(packager, [
|
||||
`"${staging}"`,
|
||||
APP_NAME,
|
||||
'--platform=win32',
|
||||
'--arch=x64',
|
||||
'--out', `"${OUT_DIR}"`,
|
||||
'--overwrite',
|
||||
// packager 默认会打成 app.asar,这里关掉:明文目录路径透明,出问题好排查
|
||||
'--asar=false',
|
||||
'--prune=true',
|
||||
'--icon', `"${path.join(desktopDir, 'build', 'icon.ico')}"`,
|
||||
`--app-version=${version}`,
|
||||
'--build-version', version,
|
||||
'--win32metadata.CompanyName=DoubaoClone',
|
||||
`--win32metadata.ProductName=${APP_NAME}`,
|
||||
'--win32metadata.FileDescription=Doubao for Windows',
|
||||
], {
|
||||
cwd: desktopDir,
|
||||
env: {
|
||||
...process.env,
|
||||
ELECTRON_MIRROR: process.env.ELECTRON_MIRROR || 'https://npmmirror.com/mirrors/electron/',
|
||||
ELECTRON_CUSTOM_DIR: process.env.ELECTRON_CUSTOM_DIR || '{{ version }}',
|
||||
},
|
||||
});
|
||||
|
||||
/* ------------------------------ 4. 收尾 ------------------------------ */
|
||||
const appDir = path.join(OUT_DIR, `${APP_NAME}-win32-x64`);
|
||||
const exePath = path.join(appDir, `${APP_NAME}.exe`);
|
||||
if (!fs.existsSync(exePath)) throw new Error(`打包产物里没找到 ${exePath}`);
|
||||
|
||||
const cnExe = path.join(appDir, EXE_NAME);
|
||||
if (cnExe !== exePath) {
|
||||
if (fs.existsSync(cnExe)) rm(cnExe);
|
||||
fs.renameSync(exePath, cnExe);
|
||||
}
|
||||
|
||||
rm(staging);
|
||||
|
||||
log('完成 ✅');
|
||||
const totalBytes = (() => {
|
||||
let sum = 0;
|
||||
const walk = (dir) => {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) walk(full);
|
||||
else sum += fs.statSync(full).size;
|
||||
}
|
||||
};
|
||||
walk(appDir);
|
||||
return sum;
|
||||
})();
|
||||
console.log('');
|
||||
console.log(` 目录:${appDir}`);
|
||||
console.log(` 程序:${EXE_NAME}`);
|
||||
console.log(` 体积:exe ${(fs.statSync(cnExe).size / 1024 / 1024).toFixed(0)} MB,整包 ${(totalBytes / 1024 / 1024).toFixed(0)} MB`);
|
||||
console.log('');
|
||||
console.log(' ⚠️ 整个路径必须是纯英文/数字:Electron 放在中文目录下会在启动时崩溃。');
|
||||
console.log(` 双击「${EXE_NAME}」即可,数据存在 %APPDATA%\\Doubao\\data。`);
|
||||
95
scripts/check-braces.mjs
Normal file
95
scripts/check-braces.mjs
Normal file
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* 找出 Kotlin 文件里第一个括号不配对的位置。
|
||||
* 会跳过 // 行注释、/* *\/ 块注释、字符串与字符字面量(含 ${} 模板里的配对)。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
|
||||
const file = process.argv[2];
|
||||
const src = fs.readFileSync(file, 'utf8');
|
||||
|
||||
let depth = 0;
|
||||
let paren = 0;
|
||||
let i = 0;
|
||||
let line = 1;
|
||||
const openStack = [];
|
||||
|
||||
function where() {
|
||||
return `line ${line}`;
|
||||
}
|
||||
|
||||
while (i < src.length) {
|
||||
const c = src[i];
|
||||
const next = src[i + 1];
|
||||
|
||||
if (c === '\n') {
|
||||
line += 1;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 行注释
|
||||
if (c === '/' && next === '/') {
|
||||
while (i < src.length && src[i] !== '\n') i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 块注释(Kotlin 支持嵌套)
|
||||
if (c === '/' && next === '*') {
|
||||
let nest = 1;
|
||||
i += 2;
|
||||
while (i < src.length && nest > 0) {
|
||||
if (src[i] === '\n') line += 1;
|
||||
if (src[i] === '/' && src[i + 1] === '*') { nest += 1; i += 2; continue; }
|
||||
if (src[i] === '*' && src[i + 1] === '/') { nest -= 1; i += 2; continue; }
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// 三引号字符串
|
||||
if (c === '"' && src.startsWith('"""', i)) {
|
||||
i += 3;
|
||||
while (i < src.length && !src.startsWith('"""', i)) {
|
||||
if (src[i] === '\n') line += 1;
|
||||
i += 1;
|
||||
}
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 普通字符串
|
||||
if (c === '"') {
|
||||
i += 1;
|
||||
let braces = 0;
|
||||
while (i < src.length && src[i] !== '"') {
|
||||
if (src[i] === '\\') { i += 2; continue; }
|
||||
if (src[i] === '$' && src[i + 1] === '{') { braces += 1; i += 2; continue; }
|
||||
if (src[i] === '}' && braces > 0) { braces -= 1; i += 1; continue; }
|
||||
if (src[i] === '\n') line += 1;
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c === '{') { depth += 1; openStack.push(where()); }
|
||||
if (c === '}') {
|
||||
depth -= 1;
|
||||
openStack.pop();
|
||||
if (depth < 0) {
|
||||
console.log(`❌ 多了一个 } 在 ${where()}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
if (c === '(') paren += 1;
|
||||
if (c === ')') paren -= 1;
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
console.log(`${file}`);
|
||||
console.log(` 末尾花括号深度 = ${depth}(应为 0)`);
|
||||
console.log(` 末尾圆括号深度 = ${paren}(应为 0)`);
|
||||
if (depth !== 0) {
|
||||
console.log(' 还开着的 {:', openStack.slice(-5).join(', '));
|
||||
}
|
||||
31
scripts/crop-bottom.ps1
Normal file
31
scripts/crop-bottom.ps1
Normal file
@@ -0,0 +1,31 @@
|
||||
# 把抽屉截图底部那一条裁掉(那里有用户昵称)。
|
||||
#
|
||||
# 为什么不"涂掉再画一个假头像":位置要对到像素级,字体还要依赖系统,
|
||||
# 试了一轮发现又慢又容易出错。直接把这一条裁掉最干净 ——
|
||||
# 抽屉少一行用户信息完全正常,也没人会怀疑那里藏了东西。
|
||||
#
|
||||
# 注意:Windows PowerShell 5.1 按 GBK 读 .ps1,脚本里别写中文。
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$src = $args[0]
|
||||
$dst = $args[1]
|
||||
$cutHeight = [int]$args[2]
|
||||
|
||||
if (-not $src -or -not $dst -or -not $cutHeight) {
|
||||
Write-Host "用法: crop-bottom.ps1 <源图> <输出> <要裁掉的高度>"
|
||||
exit 2
|
||||
}
|
||||
|
||||
$img = [System.Drawing.Image]::FromFile($src)
|
||||
$newH = $img.Height - $cutHeight
|
||||
Write-Host " $($img.Width)x$($img.Height) -> $($img.Width)x$newH"
|
||||
|
||||
$rect = New-Object System.Drawing.Rectangle 0, 0, $img.Width, $newH
|
||||
$bmp = New-Object System.Drawing.Bitmap $img.Width, $newH
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.DrawImage($img, 0, 0, $rect, [System.Drawing.GraphicsUnit]::Pixel)
|
||||
|
||||
$bmp.Save($dst, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$g.Dispose(); $bmp.Dispose(); $img.Dispose()
|
||||
Write-Host " 已写出 $dst"
|
||||
67
scripts/device-settings-attack.mjs
Normal file
67
scripts/device-settings-attack.mjs
Normal file
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* 在**设备**上验证设置守卫:按"旧版前端那种全量下发空值"的打法打一次 PUT,
|
||||
* 配置必须一个字都不能掉。
|
||||
*
|
||||
* 为什么要单独做设备版:手机跑的是 Python 内核(Chaquopy),
|
||||
* 电脑跑的是 Node 内核,两份实现是分别写的,只在电脑上验过不算数。
|
||||
*
|
||||
* 用法: node scripts/device-settings-attack.mjs [serial] [port]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const SERIAL = process.argv[2] || 'emulator-5556';
|
||||
const PORT = process.argv[3] || '5199';
|
||||
const ADB = 'C:\\Android\\Sdk\\platform-tools\\adb.exe';
|
||||
|
||||
function sh(cmd, timeout = 60000) {
|
||||
const res = spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout });
|
||||
return `${res.stdout || ''}${res.stderr || ''}`.trim();
|
||||
}
|
||||
|
||||
function getState() {
|
||||
const out = sh(`curl -s --max-time 20 http://127.0.0.1:${PORT}/api/state`);
|
||||
try {
|
||||
return JSON.parse(out);
|
||||
} catch {
|
||||
console.error('拿不到 state,原始返回:', out.slice(0, 300));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function put(patch) {
|
||||
const b64 = Buffer.from(JSON.stringify(patch), 'utf8').toString('base64');
|
||||
sh(`echo '${b64}' | base64 -d > /data/local/tmp/patch.json`);
|
||||
const out = sh(
|
||||
`curl -s --max-time 20 -X PUT -H 'Content-Type: application/json' -d @/data/local/tmp/patch.json http://127.0.0.1:${PORT}/api/settings`,
|
||||
);
|
||||
return out.slice(0, 80);
|
||||
}
|
||||
|
||||
const KEYS = ['provider', 'model', 'baseUrl', 'thinkingLevel', 'nickname'];
|
||||
|
||||
console.log(`=== 设备 ${SERIAL} 上的 Python 内核 ===`);
|
||||
const before = getState().settings;
|
||||
console.log(' 保存前:', KEYS.map((k) => `${k}=${JSON.stringify(before[k])}`).join(' '));
|
||||
console.log(` hasApiKey=${before.hasApiKey} systemPrompt=${(before.systemPrompt || '').length}字`);
|
||||
|
||||
console.log('\n--- 攻击:全量下发空值(就是"一保存就清空"那个 bug 的形状)---');
|
||||
console.log(' PUT →', put({ provider: '', baseUrl: '', model: '', apiKey: '', nickname: '', thinkingLevel: '', systemPrompt: '' }));
|
||||
|
||||
const after = getState().settings;
|
||||
console.log(' 保存后:', KEYS.map((k) => `${k}=${JSON.stringify(after[k])}`).join(' '));
|
||||
console.log(` hasApiKey=${after.hasApiKey} systemPrompt=${(after.systemPrompt || '').length}字`);
|
||||
|
||||
const hurt = [];
|
||||
for (const key of KEYS) {
|
||||
if (String(before[key] ?? '') !== String(after[key] ?? '')) {
|
||||
hurt.push(`${key}: ${JSON.stringify(before[key])} → ${JSON.stringify(after[key])}`);
|
||||
}
|
||||
}
|
||||
if (before.hasApiKey && !after.hasApiKey) hurt.push('API Key 被清掉了');
|
||||
|
||||
console.log('\n=== 结论 ===');
|
||||
if (hurt.length) {
|
||||
console.log(' ❌ 还是被改动:\n ' + hurt.join('\n '));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(' ✅ 空值被忽略,配置一个字都没掉');
|
||||
37
scripts/device-state-health.mjs
Normal file
37
scripts/device-state-health.mjs
Normal file
@@ -0,0 +1,37 @@
|
||||
/** 检查设备内核的 /api/state 是否健康(把关键字段打出来) */
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const SERIAL = process.argv[2] || 'emulator-5556';
|
||||
const ADB = 'C:\\Android\\Sdk\\platform-tools\\adb.exe';
|
||||
|
||||
const res = spawnSync(ADB, ['-s', SERIAL, 'shell', 'curl -s --max-time 15 http://127.0.0.1:5199/api/state'], {
|
||||
encoding: 'utf8',
|
||||
timeout: 60000,
|
||||
});
|
||||
const out = `${res.stdout || ''}`.trim();
|
||||
|
||||
let s;
|
||||
try {
|
||||
s = JSON.parse(out);
|
||||
} catch {
|
||||
console.log(' ❌ 不是合法 JSON:', out.slice(0, 200));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (s.error) {
|
||||
console.log(' ❌ 内核返回错误:', s.error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const st = s.settings || {};
|
||||
console.log(' ✅ /api/state 正常');
|
||||
console.log(' provider =', JSON.stringify(st.provider));
|
||||
console.log(' model =', JSON.stringify(st.model));
|
||||
console.log(' nickname =', JSON.stringify(st.nickname));
|
||||
console.log(' hasApiKey =', st.hasApiKey);
|
||||
console.log(' speech 是对象 =', st.speech && typeof st.speech === 'object' && !Array.isArray(st.speech));
|
||||
console.log(' speech.ttsEngine =', JSON.stringify(st.speech?.ttsEngine));
|
||||
console.log(' speech.autoRead =', st.speech?.autoRead);
|
||||
console.log(' 会话数 =', (s.conversations || []).length);
|
||||
console.log(' 智能体数 =', (s.agents || []).length);
|
||||
console.log(' 工具数 =', (s.toolNames || []).length);
|
||||
42
scripts/device-state.mjs
Normal file
42
scripts/device-state.mjs
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 看设备上内核当前的真实设置(判断"保存后被清空"是否真的发生)。
|
||||
* 用法: node scripts/device-state.mjs [serial] [port]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const SERIAL = process.argv[2] || 'YOUR_DEVICE_SERIAL';
|
||||
const PORT = process.argv[3] || '5199';
|
||||
const ADB = 'C:\\Android\\Sdk\\platform-tools\\adb.exe';
|
||||
|
||||
function sh(cmd, timeout = 60000) {
|
||||
const res = spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout });
|
||||
return `${res.stdout || ''}${res.stderr || ''}`.trim();
|
||||
}
|
||||
|
||||
const out = sh(`curl -s --max-time 20 http://127.0.0.1:${PORT}/api/state`);
|
||||
let state;
|
||||
try {
|
||||
state = JSON.parse(out);
|
||||
} catch {
|
||||
console.log('原始返回:', out.slice(0, 400));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const s = state.settings || {};
|
||||
console.log('=== 设备内核当前设置 ===');
|
||||
for (const key of ['provider', 'baseUrl', 'model', 'temperature', 'maxRounds', 'thinkingLevel', 'toolsDir', 'nickname', 'activeAgentId']) {
|
||||
console.log(` ${key.padEnd(14)} = ${JSON.stringify(s[key])}`);
|
||||
}
|
||||
console.log(` hasApiKey = ${s.hasApiKey}`);
|
||||
console.log(` systemPrompt = ${(s.systemPrompt || '').length} 字`);
|
||||
console.log(` tools = ${JSON.stringify(s.tools)}`);
|
||||
console.log(` security = ${JSON.stringify(s.security)}`);
|
||||
console.log(` agents = ${(state.agents || []).length} 个`);
|
||||
console.log(` conversations = ${(state.conversations || []).length} 个`);
|
||||
|
||||
const empty = [];
|
||||
if (!s.baseUrl) empty.push('baseUrl');
|
||||
if (!s.model) empty.push('model');
|
||||
if (!s.hasApiKey) empty.push('apiKey');
|
||||
if (!s.systemPrompt) empty.push('systemPrompt');
|
||||
console.log(empty.length ? `\n⚠️ 这些是空的:${empty.join(', ')}` : '\n✅ 关键字段都有值');
|
||||
37
scripts/device-tool.mjs
Normal file
37
scripts/device-tool.mjs
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* 在设备上跑任意内核工具(走 /api/tools/run)。
|
||||
* 用法: node scripts/device-tool.mjs <serial> <tool> <argsJson>
|
||||
* 例: node scripts/device-tool.mjs 3B1F... python_run "{\"code\":\"print(1+1)\"}"
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const [SERIAL, TOOL, ARGS = '{}'] = process.argv.slice(2);
|
||||
const PORT = process.env.PORT || '5199';
|
||||
const ADB = 'C:\\Android\\Sdk\\platform-tools\\adb.exe';
|
||||
|
||||
if (!SERIAL || !TOOL) {
|
||||
console.error('用法: node scripts/device-tool.mjs <serial> <tool> <argsJson|@file>');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
function sh(cmd, timeout = 90000) {
|
||||
const res = spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout });
|
||||
return `${res.stdout || ''}${res.stderr || ''}`.trim();
|
||||
}
|
||||
|
||||
// 参数可以用 @文件 传:PowerShell 会把命令行里的 JSON 引号搅坏,写文件最稳
|
||||
const argsText = ARGS.startsWith('@') ? fs.readFileSync(ARGS.slice(1), 'utf8') : ARGS;
|
||||
const payload = JSON.stringify({ name: TOOL, args: JSON.parse(argsText) });
|
||||
const b64 = Buffer.from(payload, 'utf8').toString('base64');
|
||||
sh(`echo '${b64}' | base64 -d > /data/local/tmp/p.json`);
|
||||
const out = sh(
|
||||
`curl -s --max-time 60 -X POST -H 'Content-Type: application/json' -d @/data/local/tmp/p.json http://127.0.0.1:${PORT}/api/tools/run`,
|
||||
);
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(out);
|
||||
console.log(JSON.stringify(parsed, null, 2));
|
||||
} catch {
|
||||
console.log('原始返回:', out.slice(0, 500));
|
||||
}
|
||||
55
scripts/dl.mjs
Normal file
55
scripts/dl.mjs
Normal file
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* 带重试的下载器(GitHub releases 在国内时通时不通,必须重试)。
|
||||
* 用法: node scripts/dl.mjs <url> <dest> [尝试次数]
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
|
||||
const [url, dest, triesArg] = process.argv.slice(2);
|
||||
const tries = Number(triesArg || 6);
|
||||
|
||||
if (!url || !dest) {
|
||||
console.error('用法: node scripts/dl.mjs <url> <dest> [tries]');
|
||||
process.exit(2);
|
||||
}
|
||||
if (fs.existsSync(dest) && fs.statSync(dest).size > 1024) {
|
||||
console.log('已存在:', dest, (fs.statSync(dest).size / 1024 / 1024).toFixed(1), 'MB');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
for (let i = 1; i <= tries; i += 1) {
|
||||
try {
|
||||
console.log(`尝试 ${i}/${tries} …`);
|
||||
// 不用 fetch:它改不了连接超时。用 node:https 自己控。
|
||||
const { get } = await import('node:https');
|
||||
const buf = await new Promise((resolve, reject) => {
|
||||
const req = get(url, { timeout: 60000, headers: { 'User-Agent': 'node' } }, (res) => {
|
||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
// 自己跟一次跳转(GitHub releases 会跳到 objects.githubusercontent.com)
|
||||
get(res.headers.location, { timeout: 60000, headers: { 'User-Agent': 'node' } }, (r2) => {
|
||||
if (r2.statusCode !== 200) return reject(new Error(`HTTP ${r2.statusCode}`));
|
||||
const chunks = [];
|
||||
r2.on('data', (c) => chunks.push(c));
|
||||
r2.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
r2.on('error', reject);
|
||||
}).on('timeout', function () { this.destroy(new Error('读取超时')); }).on('error', reject);
|
||||
return;
|
||||
}
|
||||
if (res.statusCode !== 200) return reject(new Error(`HTTP ${res.statusCode}`));
|
||||
const chunks = [];
|
||||
res.on('data', (c) => chunks.push(c));
|
||||
res.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
res.on('error', reject);
|
||||
});
|
||||
req.on('timeout', () => req.destroy(new Error('连接超时')));
|
||||
req.on('error', reject);
|
||||
});
|
||||
fs.writeFileSync(dest, buf);
|
||||
console.log('完成:', dest, (buf.length / 1024 / 1024).toFixed(1), 'MB');
|
||||
process.exit(0);
|
||||
} catch (err) {
|
||||
console.error(' 失败:', err.message);
|
||||
if (i < tries) await new Promise((r) => setTimeout(r, 3000 * i));
|
||||
}
|
||||
}
|
||||
console.error('全部尝试失败');
|
||||
process.exit(1);
|
||||
76
scripts/fetch-termux-terminal.mjs
Normal file
76
scripts/fetch-termux-terminal.mjs
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* 从 GitHub 拉 Termux 的 terminal-emulator / terminal-view 源码树(Apache-2.0)。
|
||||
* raw.githubusercontent 在本机不通,所以走 api.github.com 的 raw 模式。
|
||||
*
|
||||
* 用法: node scripts/fetch-termux-terminal.mjs
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const REF = 'v0.118.3';
|
||||
const REPO = 'termux/termux-app';
|
||||
|
||||
/** 目标:把这些模块的 src 全量拷到 app/src/main/ 下(java + res) */
|
||||
const MODULES = [
|
||||
{ name: 'terminal-emulator', destJava: 'app/src/main/java', wantRes: false },
|
||||
{ name: 'terminal-view', destJava: 'app/src/main/java', wantRes: true },
|
||||
];
|
||||
|
||||
async function api(url, raw = false) {
|
||||
for (let i = 1; i <= 4; i += 1) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
'User-Agent': 'node',
|
||||
Accept: raw ? 'application/vnd.github.raw' : 'application/vnd.github+json',
|
||||
},
|
||||
signal: AbortSignal.timeout(60000),
|
||||
});
|
||||
if (res.status === 404) return null;
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return raw ? await res.text() : await res.json();
|
||||
} catch (err) {
|
||||
console.log(` 重试 ${i}/4:${err.message}`);
|
||||
await new Promise((r) => setTimeout(r, 1500 * i));
|
||||
}
|
||||
}
|
||||
throw new Error(`拉取失败:${url}`);
|
||||
}
|
||||
|
||||
async function listDir(dirPath) {
|
||||
const url = `https://api.github.com/repos/${REPO}/contents/${dirPath}?ref=${REF}`;
|
||||
return (await api(url)) || [];
|
||||
}
|
||||
|
||||
async function fetchFile(filePath) {
|
||||
const url = `https://api.github.com/repos/${REPO}/contents/${filePath}?ref=${REF}`;
|
||||
return api(url, true);
|
||||
}
|
||||
|
||||
async function walk(srcDir, outDir, stats) {
|
||||
const entries = await listDir(srcDir);
|
||||
for (const entry of entries) {
|
||||
if (entry.type === 'dir') {
|
||||
await walk(entry.path, path.join(outDir, entry.name), stats);
|
||||
} else if (entry.type === 'file') {
|
||||
const text = await fetchFile(entry.path);
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(outDir, entry.name), text, 'utf8');
|
||||
stats.files += 1;
|
||||
stats.bytes += Buffer.byteLength(text);
|
||||
console.log(` + ${entry.path} (${(Buffer.byteLength(text) / 1024).toFixed(1)} KB)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const stats = { files: 0, bytes: 0 };
|
||||
for (const mod of MODULES) {
|
||||
console.log(`\n=== ${mod.name} ===`);
|
||||
await walk(`${mod.name}/src/main/java`, path.join(repo, 'android', mod.destJava), stats);
|
||||
if (mod.wantRes) {
|
||||
await walk(`${mod.name}/src/main/res`, path.join(repo, 'android', 'app/src/main/res-extra'), stats);
|
||||
}
|
||||
}
|
||||
console.log(`\n完成:${stats.files} 个文件,共 ${(stats.bytes / 1024).toFixed(0)} KB`);
|
||||
34
scripts/fetch-termux.mjs
Normal file
34
scripts/fetch-termux.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 下载 Termux APK 到本地缓存(用来在模拟器上验证 Termux 桥接)。
|
||||
* 用法: node scripts/fetch-termux.mjs [abi]
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const ABI = process.argv[2] || 'x86_64';
|
||||
const CACHE = 'C:\\Android\\cache';
|
||||
fs.mkdirSync(CACHE, { recursive: true });
|
||||
|
||||
const res = await fetch('https://api.github.com/repos/termux/termux-app/releases/latest', {
|
||||
headers: { 'User-Agent': 'node' },
|
||||
signal: AbortSignal.timeout(60000),
|
||||
});
|
||||
if (!res.ok) throw new Error(`GitHub API HTTP ${res.status}`);
|
||||
const release = await res.json();
|
||||
console.log('最新版本:', release.tag_name);
|
||||
console.log('产物:');
|
||||
for (const asset of release.assets) {
|
||||
console.log(' ', asset.name, (asset.size / 1024 / 1024).toFixed(1) + 'MB');
|
||||
}
|
||||
|
||||
const wanted = release.assets.find((a) => a.name.includes(ABI) && a.name.endsWith('.apk'))
|
||||
|| release.assets.find((a) => a.name.includes('universal') && a.name.endsWith('.apk'));
|
||||
if (!wanted) throw new Error(`没找到 ${ABI} 的 APK`);
|
||||
|
||||
const dest = path.join(CACHE, wanted.name);
|
||||
if (!fs.existsSync(dest)) {
|
||||
console.log('下载', wanted.name);
|
||||
const apk = await fetch(wanted.browser_download_url, { signal: AbortSignal.timeout(900000) });
|
||||
fs.writeFileSync(dest, Buffer.from(await apk.arrayBuffer()));
|
||||
}
|
||||
console.log('APK:', dest, (fs.statSync(dest).size / 1024 / 1024).toFixed(1), 'MB');
|
||||
34
scripts/fix-models-json.mjs
Normal file
34
scripts/fix-models-json.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
/** 修 Models.kt 里被正则吃掉的 JSON 字段名。跑完可删。 */
|
||||
import fs from 'node:fs';
|
||||
|
||||
const p = process.argv[2];
|
||||
let s = fs.readFileSync(p, 'utf8');
|
||||
|
||||
const fixes = [
|
||||
['attachments = optJSONArray().mapObj', 'attachments = optJSONArray("attachments").mapObj'],
|
||||
['models = optJSONArray().mapObj', 'models = optJSONArray("models").mapObj'],
|
||||
['allow = sec?.optJSONArray().mapObj', 'allow = sec?.optJSONArray("allow")?.strings() ?: emptyList()'],
|
||||
['tools = python?.optJSONArray().mapObj', 'tools = python?.optJSONArray("tools").mapObj'],
|
||||
['mcp = optJSONArray().mapObj', 'mcp = optJSONArray("mcp").mapObj'],
|
||||
['conversations = optJSONArray().mapObj', 'conversations = optJSONArray("conversations").mapObj'],
|
||||
['agents = optJSONArray().mapObj', 'agents = optJSONArray("agents").mapObj'],
|
||||
['toolNames = optJSONArray().mapObj', 'toolNames = optJSONArray("toolNames").strings()'],
|
||||
['suggestedAllow = optJSONArray().mapObj', 'suggestedAllow = optJSONArray("suggestedAllow").strings()'],
|
||||
];
|
||||
|
||||
for (const [from, to] of fixes) {
|
||||
if (s.includes(from)) s = s.replace(from, to);
|
||||
}
|
||||
|
||||
// 剩下的 { it.toString() } 形式统一换成 strings()
|
||||
s = s.replace(/optJSONArray\("([a-zA-Z]+)"\)\.mapObj \{ it\.toString\(\) \}/g, 'optJSONArray("$1").strings()');
|
||||
// allow 那行可能被上一步换成 strings(),去掉多余的三元
|
||||
s = s.replace(/allow = sec\?\.optJSONArray\("allow"\)\.strings\(\) \?: emptyList\(\)/,
|
||||
'allow = sec?.optJSONArray("allow")?.strings() ?: emptyList()');
|
||||
|
||||
fs.writeFileSync(p, s, 'utf8');
|
||||
console.log('已修复');
|
||||
|
||||
for (const line of s.split('\n')) {
|
||||
if (line.includes('optJSONArray')) console.log(' ' + line.trim());
|
||||
}
|
||||
58
scripts/fix-termux-vendor.mjs
Normal file
58
scripts/fix-termux-vendor.mjs
Normal file
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* 修 vendored 的 Termux 源码:它们 import 的是 com.termux.view.R,
|
||||
* 但代码并进我们工程后 R 类变成 com.doubao.lynxclone.R 了。
|
||||
* 顺手把 res-extra 里的资源并进 res/。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const appMain = path.join(repo, 'android', 'app', 'src', 'main');
|
||||
const javaRoot = path.join(appMain, 'java');
|
||||
const resRoot = path.join(appMain, 'res');
|
||||
const resExtra = path.join(appMain, 'res-extra');
|
||||
|
||||
let fixed = 0;
|
||||
function walk(dir) {
|
||||
for (const entry of fs.readdirSync(dir)) {
|
||||
const full = path.join(dir, entry);
|
||||
if (fs.statSync(full).isDirectory()) {
|
||||
walk(full);
|
||||
continue;
|
||||
}
|
||||
if (!full.endsWith('.java')) continue;
|
||||
const src = fs.readFileSync(full, 'utf8');
|
||||
if (src.includes('import com.termux.view.R;')) {
|
||||
fs.writeFileSync(full, src.replace('import com.termux.view.R;', 'import com.doubao.lynxclone.R;'), 'utf8');
|
||||
fixed += 1;
|
||||
console.log(' 改 R 引用:', path.relative(javaRoot, full));
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log('修正 R 类引用…');
|
||||
walk(path.join(javaRoot, 'com', 'termux'));
|
||||
|
||||
if (fs.existsSync(resExtra)) {
|
||||
console.log('合并 Termux 资源…');
|
||||
const copy = (from, to) => {
|
||||
if (fs.statSync(from).isDirectory()) {
|
||||
fs.mkdirSync(to, { recursive: true });
|
||||
for (const e of fs.readdirSync(from)) copy(path.join(from, e), path.join(to, e));
|
||||
} else {
|
||||
// ★ values/ 下的 strings.xml 必须改名,否则会把我们自己的 strings.xml 覆盖掉(踩过)
|
||||
let target = to;
|
||||
if (path.basename(from) === 'strings.xml') {
|
||||
target = path.join(path.dirname(to), 'termux_strings.xml');
|
||||
}
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.copyFileSync(from, target);
|
||||
console.log(' +', path.relative(resRoot, target));
|
||||
}
|
||||
};
|
||||
copy(resExtra, resRoot);
|
||||
fs.rmSync(resExtra, { recursive: true, force: true });
|
||||
console.log(' 已删除 res-extra');
|
||||
}
|
||||
|
||||
console.log(`完成:改了 ${fixed} 个文件的 R 引用`);
|
||||
101
scripts/gitea.mjs
Normal file
101
scripts/gitea.mjs
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Gitea 上的仓库操作(建仓 / 查仓 / 列出)。
|
||||
*
|
||||
* 凭据从环境变量读,不写进命令行参数也不落盘 —— 免得密码进 shell 历史或被提交。
|
||||
* GIT_USER / GIT_PASS / GIT_HOST
|
||||
*
|
||||
* 用法:
|
||||
* node scripts/gitea.mjs whoami
|
||||
* node scripts/gitea.mjs list
|
||||
* node scripts/gitea.mjs ensure <repoName> 建仓(已存在就复用)
|
||||
*/
|
||||
const HOST = process.env.GIT_HOST || 'https://git.xnhw.cc';
|
||||
const USER = process.env.GIT_USER || '';
|
||||
const PASS = process.env.GIT_PASS || '';
|
||||
|
||||
if (!USER || !PASS) {
|
||||
console.error('缺少 GIT_USER / GIT_PASS 环境变量');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const auth = `Basic ${Buffer.from(`${USER}:${PASS}`).toString('base64')}`;
|
||||
|
||||
async function api(path, init = {}) {
|
||||
const res = await fetch(`${HOST}/api/v1${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: auth,
|
||||
'Content-Type': 'application/json',
|
||||
...(init.headers || {}),
|
||||
},
|
||||
});
|
||||
const text = await res.text();
|
||||
let body;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
body = { __raw: text.slice(0, 300) };
|
||||
}
|
||||
return { status: res.status, body };
|
||||
}
|
||||
|
||||
const [cmd, arg] = process.argv.slice(2);
|
||||
|
||||
if (cmd === 'whoami') {
|
||||
const r = await api('/user');
|
||||
if (r.status !== 200) {
|
||||
console.log('❌ 认证失败:HTTP', r.status, JSON.stringify(r.body).slice(0, 200));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('✅ 认证通过');
|
||||
console.log(' 用户名 :', r.body.login);
|
||||
console.log(' 昵称 :', r.body.full_name || '(无)');
|
||||
console.log(' 邮箱 :', r.body.email || '(隐藏)');
|
||||
console.log(' 管理员 :', r.body.is_admin ? '是' : '否');
|
||||
} else if (cmd === 'list') {
|
||||
const r = await api(`/users/${encodeURIComponent(USER)}/repos?limit=50`);
|
||||
if (r.status !== 200) {
|
||||
console.log('❌ HTTP', r.status, JSON.stringify(r.body).slice(0, 200));
|
||||
process.exit(1);
|
||||
}
|
||||
if (!r.body.length) {
|
||||
console.log(` ${USER} 名下还没有仓库`);
|
||||
} else {
|
||||
console.log(` ${USER} 名下有 ${r.body.length} 个仓库:`);
|
||||
for (const repo of r.body) {
|
||||
console.log(` ${repo.full_name.padEnd(28)} ${repo.private ? '私有' : '公开'} ${repo.size ?? 0} KB ${repo.empty ? '(空)' : ''}`);
|
||||
}
|
||||
}
|
||||
} else if (cmd === 'ensure') {
|
||||
const name = arg;
|
||||
if (!name) {
|
||||
console.error('用法: ensure <repoName>');
|
||||
process.exit(2);
|
||||
}
|
||||
const exists = await api(`/repos/${encodeURIComponent(USER)}/${encodeURIComponent(name)}`);
|
||||
if (exists.status === 200) {
|
||||
console.log(`✅ 仓库已存在:${exists.body.full_name}(${exists.body.private ? '私有' : '公开'},${exists.body.empty ? '空仓' : '有内容'})`);
|
||||
console.log(` clone: ${exists.body.clone_url}`);
|
||||
} else {
|
||||
const created = await api('/user/repos', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
description: '豆包复刻 · 原生安卓(Compose + 内嵌 Termux)+ Web/Windows',
|
||||
private: true,
|
||||
auto_init: false,
|
||||
default_branch: 'main',
|
||||
}),
|
||||
});
|
||||
if (created.status === 201) {
|
||||
console.log(`✅ 已创建:${created.body.full_name}(私有)`);
|
||||
console.log(` clone: ${created.body.clone_url}`);
|
||||
} else {
|
||||
console.log('❌ 创建失败 HTTP', created.status, JSON.stringify(created.body).slice(0, 300));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error('用法: whoami | list | ensure <repoName>');
|
||||
process.exit(2);
|
||||
}
|
||||
49
scripts/install-python313.mjs
Normal file
49
scripts/install-python313.mjs
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 下载并静默安装 Python 3.13(Chaquopy 17 要求 buildPython 与内嵌版本主次号一致)。
|
||||
* 用法: node scripts/install-python313.mjs
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const VERSION = '3.13.9';
|
||||
const TARGET = 'C:\\Python313';
|
||||
const CACHE = 'C:\\Android\\cache';
|
||||
const installer = path.join(CACHE, `python-${VERSION}-amd64.exe`);
|
||||
const exe = path.join(TARGET, 'python.exe');
|
||||
|
||||
if (fs.existsSync(exe)) {
|
||||
const res = spawnSync(exe, ['-V'], { encoding: 'utf8' });
|
||||
console.log(`已安装:${(res.stdout || res.stderr).trim()} → ${TARGET}`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (!fs.existsSync(installer)) {
|
||||
const url = `https://www.python.org/ftp/python/${VERSION}/python-${VERSION}-amd64.exe`;
|
||||
console.log('下载', url);
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(900000) });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
fs.mkdirSync(CACHE, { recursive: true });
|
||||
fs.writeFileSync(installer, Buffer.from(await res.arrayBuffer()));
|
||||
console.log(' ', (fs.statSync(installer).size / 1024 / 1024).toFixed(1), 'MB');
|
||||
}
|
||||
|
||||
console.log('静默安装到', TARGET);
|
||||
const args = [
|
||||
'/quiet',
|
||||
'InstallAllUsers=0',
|
||||
`TargetDir=${TARGET}`,
|
||||
'Include_pip=1',
|
||||
'Include_test=0',
|
||||
'Include_launcher=0',
|
||||
'PrependPath=0',
|
||||
'Shortcuts=0',
|
||||
];
|
||||
const code = spawnSync(installer, args, { stdio: 'inherit' }).status;
|
||||
if (code !== 0) {
|
||||
// 安装器有时返回非 0 但实际装好了
|
||||
console.log('安装器退出码', code, ',检查是否装成功…');
|
||||
}
|
||||
if (!fs.existsSync(exe)) throw new Error('安装失败:没找到 ' + exe);
|
||||
const res = spawnSync(exe, ['-V'], { encoding: 'utf8' });
|
||||
console.log('完成:', (res.stdout || res.stderr).trim(), '→', TARGET);
|
||||
37
scripts/lynx-api-grep.mjs
Normal file
37
scripts/lynx-api-grep.mjs
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* 在已下载的 lynx AAR 里检索指定方法/字段签名。
|
||||
* 用法: node scripts/lynx-api-grep.mjs <正则> [类名...]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const WORK = 'C:\\Android\\probe';
|
||||
const classesJar = (() => {
|
||||
for (const dir of fs.readdirSync(WORK)) {
|
||||
const p = path.join(WORK, dir, 'classes.jar');
|
||||
if (fs.existsSync(p)) return p;
|
||||
}
|
||||
throw new Error('还没下载 AAR,先跑 lynx-api-probe.mjs');
|
||||
})();
|
||||
|
||||
const pattern = new RegExp(process.argv[2] || 'init', 'i');
|
||||
const classes = process.argv.slice(3).length
|
||||
? process.argv.slice(3)
|
||||
: [
|
||||
'com.lynx.tasm.LynxEnv',
|
||||
'com.lynx.tasm.LynxView',
|
||||
'com.lynx.tasm.LynxViewBuilder',
|
||||
'com.lynx.tasm.group.LynxBaseConfigurator',
|
||||
];
|
||||
|
||||
for (const cls of classes) {
|
||||
const res = spawnSync('javap', ['-classpath', classesJar, cls], { encoding: 'utf8' });
|
||||
if (res.status !== 0) {
|
||||
console.log(`-- ${cls}: 未找到`);
|
||||
continue;
|
||||
}
|
||||
const hits = res.stdout.split('\n').filter((l) => pattern.test(l));
|
||||
console.log(`\n== ${cls} 匹配 /${pattern.source}/ 共 ${hits.length} 条`);
|
||||
console.log(hits.slice(0, 40).join('\n'));
|
||||
}
|
||||
76
scripts/lynx-api-probe.mjs
Normal file
76
scripts/lynx-api-probe.mjs
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* 下载 Lynx Android SDK 产物,解出 classes.jar,用 javap 打印关键类的真实签名。
|
||||
* 用法: node scripts/lynx-api-probe.mjs [version]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const VERSION = process.argv[2] || '4.1.0';
|
||||
const WORK = 'C:\\Android\\probe';
|
||||
fs.mkdirSync(WORK, { recursive: true });
|
||||
|
||||
function run(cmd, args) {
|
||||
const res = spawnSync(cmd, args, { encoding: 'utf8' });
|
||||
return { code: res.status, out: res.stdout || '', err: res.stderr || '' };
|
||||
}
|
||||
|
||||
async function listDir(url) {
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(60000) });
|
||||
if (!res.ok) return { status: res.status, files: [] };
|
||||
const html = await res.text();
|
||||
const files = [...html.matchAll(/href="([^"]+)"/g)]
|
||||
.map((m) => m[1])
|
||||
.filter((x) => !x.startsWith('..') && !x.startsWith('http') && !x.endsWith('/'));
|
||||
return { status: res.status, files };
|
||||
}
|
||||
|
||||
const ROOT = 'https://repo1.maven.org/maven2/org/lynxsdk/lynx/lynx';
|
||||
const listing = await listDir(`${ROOT}/${VERSION}/`);
|
||||
console.log(`== ${ROOT}/${VERSION}/ → HTTP ${listing.status}`);
|
||||
console.log(listing.files.join(' '));
|
||||
|
||||
const artifact = listing.files.find((f) => f.endsWith('.aar')) || listing.files.find((f) => f.endsWith('.jar'));
|
||||
if (!artifact) {
|
||||
console.log('没找到 aar/jar,退出');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const filePath = path.join(WORK, artifact);
|
||||
if (!fs.existsSync(filePath)) {
|
||||
console.log('下载', artifact);
|
||||
const res = await fetch(`${ROOT}/${VERSION}/${artifact}`, { signal: AbortSignal.timeout(600000) });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
fs.writeFileSync(filePath, Buffer.from(await res.arrayBuffer()));
|
||||
}
|
||||
console.log('大小', (fs.statSync(filePath).size / 1024 / 1024).toFixed(1), 'MB');
|
||||
|
||||
const extractDir = path.join(WORK, `x-${VERSION}`);
|
||||
fs.rmSync(extractDir, { recursive: true, force: true });
|
||||
fs.mkdirSync(extractDir, { recursive: true });
|
||||
run('tar', ['-xf', filePath, '-C', extractDir]);
|
||||
console.log('内容:', fs.readdirSync(extractDir).join(', '));
|
||||
|
||||
const classesJar = fs.existsSync(path.join(extractDir, 'classes.jar'))
|
||||
? path.join(extractDir, 'classes.jar')
|
||||
: filePath;
|
||||
|
||||
const targets = [
|
||||
'com.lynx.tasm.provider.AbsTemplateProvider',
|
||||
'com.lynx.tasm.provider.AbsTemplateProvider$Callback',
|
||||
'com.lynx.tasm.provider.TemplateBundle',
|
||||
'com.lynx.tasm.LynxEnv',
|
||||
'com.lynx.tasm.LynxViewBuilder',
|
||||
'com.lynx.tasm.LynxView',
|
||||
];
|
||||
|
||||
for (const cls of targets) {
|
||||
console.log(`\n===== ${cls} =====`);
|
||||
const res = run('javap', ['-classpath', classesJar, cls]);
|
||||
if (res.code !== 0) {
|
||||
console.log(' (找不到)', res.err.split('\n')[0]);
|
||||
continue;
|
||||
}
|
||||
const lines = res.out.split('\n').filter((l) => /public|protected/.test(l));
|
||||
console.log(lines.slice(0, 55).join('\n'));
|
||||
}
|
||||
20
scripts/lynx-demo-deps.mjs
Normal file
20
scripts/lynx-demo-deps.mjs
Normal file
@@ -0,0 +1,20 @@
|
||||
/** 通过 GitHub API(raw.githubusercontent 被墙)读官方 demo 的构建文件。 */
|
||||
const REPO = 'lynx-family/integrating-lynx-demo-projects';
|
||||
const FILES = [
|
||||
'android/KotlinEmptyProject/app/build.gradle.kts',
|
||||
'android/KotlinEmptyProject/gradle/libs.versions.toml',
|
||||
'android/KotlinEmptyProject/build.gradle.kts',
|
||||
'android/KotlinEmptyProject/gradle.properties',
|
||||
];
|
||||
|
||||
for (const file of FILES) {
|
||||
const url = `https://api.github.com/repos/${REPO}/contents/${file}`;
|
||||
const res = await fetch(url, {
|
||||
headers: { 'User-Agent': 'node', Accept: 'application/vnd.github.raw' },
|
||||
signal: AbortSignal.timeout(60000),
|
||||
});
|
||||
console.log(`\n===== ${file} → ${res.status}`);
|
||||
if (!res.ok) continue;
|
||||
const text = await res.text();
|
||||
console.log(text.split('\n').filter((l) => l.trim() && !l.trim().startsWith('//')).slice(0, 45).join('\n'));
|
||||
}
|
||||
20
scripts/lynx-pom-deps.mjs
Normal file
20
scripts/lynx-pom-deps.mjs
Normal file
@@ -0,0 +1,20 @@
|
||||
/** 看 Lynx 各 artifact 的 POM 依赖声明,找 Fresco 相关坐标。 */
|
||||
const ARTIFACTS = ['lynx', 'lynx-service-image', 'lynx-service-http', 'lynx-service-log', 'xelement'];
|
||||
const VERSION = '4.1.0';
|
||||
|
||||
for (const artifact of ARTIFACTS) {
|
||||
const url = `https://repo1.maven.org/maven2/org/lynxsdk/lynx/${artifact}/${VERSION}/${artifact}-${VERSION}.pom`;
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(60000) });
|
||||
if (!res.ok) {
|
||||
console.log(`\n== ${artifact} → HTTP ${res.status}`);
|
||||
continue;
|
||||
}
|
||||
const xml = await res.text();
|
||||
const deps = [...xml.matchAll(/<dependency>([\s\S]*?)<\/dependency>/g)].map((m) => {
|
||||
const block = m[1];
|
||||
const get = (tag) => (block.match(new RegExp(`<${tag}>([^<]+)</${tag}>`)) || [])[1] || '';
|
||||
return `${get('groupId')}:${get('artifactId')}:${get('version')}${get('scope') ? ` (${get('scope')})` : ''}`;
|
||||
});
|
||||
console.log(`\n== ${artifact}`);
|
||||
console.log(deps.map((d) => ` ${d}`).join('\n') || ' (无依赖)');
|
||||
}
|
||||
79
scripts/mcp-python-test.mjs
Normal file
79
scripts/mcp-python-test.mjs
Normal file
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* 验证:把 Python 写的 MCP 服务接进内核(stdio 模式)。
|
||||
* 用法: node scripts/mcp-python-test.mjs [base] [pythonPath] [serverPy]
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const BASE = process.argv[2] || 'http://127.0.0.1:5199';
|
||||
const PYTHON = process.argv[3] || 'python';
|
||||
const SERVER_PY = process.argv[4] || path.join(repo, 'tools', '_mcp_python_example.py');
|
||||
|
||||
const config = {
|
||||
servers: [
|
||||
{
|
||||
name: 'py-demo',
|
||||
enabled: true,
|
||||
transport: 'stdio',
|
||||
command: PYTHON,
|
||||
args: [SERVER_PY],
|
||||
env: {},
|
||||
},
|
||||
{
|
||||
name: 'filesystem',
|
||||
enabled: false,
|
||||
transport: 'stdio',
|
||||
command: 'npx',
|
||||
args: ['-y', '@modelcontextprotocol/server-filesystem', '${DOUBAO_DATA}'],
|
||||
},
|
||||
{
|
||||
name: 'my-python-mcp-inproc',
|
||||
enabled: false,
|
||||
transport: 'inproc',
|
||||
path: '/sdcard/Android/data/com.doubao.lynxclone/files/tools/my_mcp_server.py',
|
||||
note: '安卓端用:内核直接 import 这个 py,不依赖独立 python 解释器',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
console.log('写入配置…');
|
||||
const save = await fetch(`${BASE}/api/mcp/config`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: JSON.stringify(config, null, 2) }),
|
||||
});
|
||||
const saved = await save.json();
|
||||
console.log('ok=', saved.ok, 'count=', saved.count, 'error=', saved.error || '无');
|
||||
for (const r of saved.results || []) console.log(' ', r.ok ? '✓' : '✗', r.name, r.error || '');
|
||||
|
||||
console.log('\n工具列表:');
|
||||
const state = await (await fetch(`${BASE}/api/state`)).json();
|
||||
const mcpTools = state.toolNames.filter((n) => n.startsWith('mcp__py-demo__'));
|
||||
console.log(' py-demo 暴露:', mcpTools.join(', ') || '(无)');
|
||||
|
||||
console.log('\n跑一下 word_count:');
|
||||
const run = await fetch(`${BASE}/api/tools/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'mcp__py-demo__word_count', args: { text: 'hello 世界 hello' } }),
|
||||
});
|
||||
console.log(' ', JSON.stringify(await run.json()));
|
||||
|
||||
console.log('\n跑一下 host_info:');
|
||||
const info = await fetch(`${BASE}/api/tools/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'mcp__py-demo__host_info', args: {} }),
|
||||
});
|
||||
console.log(' ', JSON.stringify(await info.json()).slice(0, 260));
|
||||
|
||||
console.log('\n跑一下 http_get(证明 MCP 里的 py 也能联网):');
|
||||
const net = await fetch(`${BASE}/api/tools/run`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'mcp__py-demo__http_get', args: { url: 'https://example.com' } }),
|
||||
});
|
||||
const netJson = await net.json();
|
||||
console.log(' ', JSON.stringify(netJson).slice(0, 200));
|
||||
45
scripts/mcp-smoke.mjs
Normal file
45
scripts/mcp-smoke.mjs
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 验证 MCP 配置读写链路:往内核里塞一份配置,看能不能连上。
|
||||
* 用法: node scripts/mcp-smoke.mjs <baseUrl> <输出用的json路径>
|
||||
*/
|
||||
const [, , base = 'http://127.0.0.1:5399', outPath] = process.argv;
|
||||
|
||||
const cfg = {
|
||||
servers: [
|
||||
{
|
||||
name: 'filesystem',
|
||||
enabled: true,
|
||||
transport: 'stdio',
|
||||
command: 'npx',
|
||||
args: ['-y', '@modelcontextprotocol/server-filesystem', '${DOUBAO_DATA}'],
|
||||
env: {},
|
||||
},
|
||||
{
|
||||
name: 'memory',
|
||||
enabled: true,
|
||||
transport: 'stdio',
|
||||
command: 'npx',
|
||||
args: ['-y', '@modelcontextprotocol/server-memory'],
|
||||
env: {},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const started = Date.now();
|
||||
const res = await fetch(`${base}/api/mcp/config`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: JSON.stringify(cfg, null, 2) }),
|
||||
});
|
||||
const json = await res.json();
|
||||
console.log(`耗时 ${Math.round((Date.now() - started) / 1000)}s status=${res.status}`);
|
||||
console.log('ok=', json.ok, 'count=', json.count, 'error=', json.error || '无');
|
||||
for (const r of json.results || []) console.log(' ', r.ok ? '✓' : '✗', r.name, r.error || '');
|
||||
for (const s of json.servers || []) {
|
||||
console.log(' ->', s.name, s.connected ? `已连接/${s.tools.length} 工具` : '未连接', s.error || '');
|
||||
if (s.tools.length) console.log(' 工具:', s.tools.map((t) => t.name).join(', '));
|
||||
}
|
||||
if (outPath) {
|
||||
const fs = await import('node:fs');
|
||||
fs.writeFileSync(outPath, await (await fetch(`${base}/api/mcp`)).text(), 'utf8');
|
||||
}
|
||||
194
scripts/mock-llm.mjs
Normal file
194
scripts/mock-llm.mjs
Normal file
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* 假的 OpenAI 兼容服务 + 假的火山语音服务,用来端到端验证内核(不消耗任何真实额度)。
|
||||
*
|
||||
* 对话:第一轮返回 tool_call(calc),第二轮根据工具结果流式回答。
|
||||
* 语音:/v1/audio/speech 回一段真 WAV;/v1/audio/transcriptions 回固定文字;
|
||||
* 还顺手把收到的请求形状打出来,用来核对"我们到底发了什么头/字段"。
|
||||
*/
|
||||
import http from 'node:http';
|
||||
|
||||
const PORT = Number(process.env.MOCK_PORT || 5299);
|
||||
|
||||
function sse(res, obj) {
|
||||
res.write(`data: ${JSON.stringify(obj)}\n\n`);
|
||||
}
|
||||
|
||||
/** 造一段 0.3 秒的正弦波 WAV(16000Hz 单声道 16bit),用来验证播放链路 */
|
||||
function makeWav(seconds = 0.3, freq = 440) {
|
||||
const rate = 16000;
|
||||
const n = Math.floor(rate * seconds);
|
||||
const data = Buffer.alloc(n * 2);
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
data.writeInt16LE(Math.round(Math.sin((2 * Math.PI * freq * i) / rate) * 8000), i * 2);
|
||||
}
|
||||
const header = Buffer.alloc(44);
|
||||
header.write('RIFF', 0);
|
||||
header.writeUInt32LE(36 + data.length, 4);
|
||||
header.write('WAVE', 8);
|
||||
header.write('fmt ', 12);
|
||||
header.writeUInt32LE(16, 16);
|
||||
header.writeUInt16LE(1, 20);
|
||||
header.writeUInt16LE(1, 22);
|
||||
header.writeUInt32LE(rate, 24);
|
||||
header.writeUInt32LE(rate * 2, 28);
|
||||
header.writeUInt16LE(2, 32);
|
||||
header.writeUInt16LE(16, 34);
|
||||
header.write('data', 36);
|
||||
header.writeUInt32LE(data.length, 40);
|
||||
return Buffer.concat([header, data]);
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = req.url || '';
|
||||
|
||||
/* ---------------- 语音合成(OpenAI 兼容 /audio/speech)---------------- */
|
||||
if (url.startsWith('/v1/audio/speech')) {
|
||||
const chunks = [];
|
||||
for await (const c of req) chunks.push(c);
|
||||
let body = {};
|
||||
try {
|
||||
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||||
} catch { /* 下面照常回音频 */ }
|
||||
console.log(
|
||||
`[mock][tts] auth=${req.headers.authorization ? '有' : '无'} model=${body.model} ` +
|
||||
`voice=${body.voice} speed=${body.speed} fmt=${body.response_format} ` +
|
||||
`文本=${JSON.stringify(String(body.input || '').slice(0, 30))}`,
|
||||
);
|
||||
const wav = makeWav(0.3, 520);
|
||||
res.writeHead(200, { 'Content-Type': 'audio/wav', 'Content-Length': wav.length }).end(wav);
|
||||
return;
|
||||
}
|
||||
|
||||
/* ---------------- 语音合成(火山 v1 /api/v1/tts)---------------- */
|
||||
if (url.startsWith('/api/v1/tts')) {
|
||||
const chunks = [];
|
||||
for await (const c of req) chunks.push(c);
|
||||
let body = {};
|
||||
try {
|
||||
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||||
} catch { /* 忽略 */ }
|
||||
const auth = req.headers.authorization || '';
|
||||
console.log(
|
||||
`[mock][volc-tts] Authorization=${JSON.stringify(auth)} ` +
|
||||
`app.appid=${body.app?.appid} app.token=${body.app?.token ? '有' : '无'} app.cluster=${body.app?.cluster} ` +
|
||||
`audio.voice_type=${body.audio?.voice_type} audio.encoding=${body.audio?.encoding} ` +
|
||||
`audio.speed_ratio=${body.audio?.speed_ratio} ` +
|
||||
`request.text_type=${body.request?.text_type} request.operation=${body.request?.operation} ` +
|
||||
`request.reqid=${body.request?.reqid ? '有' : '无'} text=${JSON.stringify(String(body.request?.text || '').slice(0, 20))}`,
|
||||
);
|
||||
// 校验鉴权头是不是文档要求的分号形式 —— 这正是最容易写错的地方
|
||||
const semicolonOk = auth.startsWith('Bearer;');
|
||||
if (!semicolonOk) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' }).end(
|
||||
JSON.stringify({ code: 3001, message: '鉴权头格式不对:必须是 Bearer;<token>(分号)' }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const wav = makeWav(0.3, 660);
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' }).end(
|
||||
JSON.stringify({ code: 3000, message: 'Success', reqid: body.request?.reqid, data: wav.toString('base64') }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
/* ---------------- 语音识别(OpenAI 兼容 /audio/transcriptions)---------------- */
|
||||
if (url.startsWith('/v1/audio/transcriptions')) {
|
||||
const chunks = [];
|
||||
for await (const c of req) chunks.push(c);
|
||||
const raw = Buffer.concat(chunks);
|
||||
const ctype = req.headers['content-type'] || '';
|
||||
const boundary = (ctype.match(/boundary=(.+)$/) || [])[1] || '';
|
||||
const text = raw.toString('latin1');
|
||||
const model = (text.match(/name="model"\r\n\r\n([^\r]*)/) || [])[1] || '?';
|
||||
const hasFile = text.includes('name="file"') && text.includes('filename=');
|
||||
console.log(
|
||||
`[mock][stt] auth=${req.headers.authorization ? '有' : '无'} boundary=${boundary ? '有' : '无'} ` +
|
||||
`model=${model} 带文件=${hasFile} 体积=${raw.length}`,
|
||||
);
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' }).end(
|
||||
JSON.stringify({ text: '这是语音识别的模拟结果' }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!url.startsWith('/v1/chat/completions')) {
|
||||
res.writeHead(404).end('nope');
|
||||
return;
|
||||
}
|
||||
const chunks = [];
|
||||
for await (const c of req) chunks.push(c);
|
||||
// 别让一条坏请求把整个 mock 打死:壳脚本/手敲 curl 很容易发出不合法 JSON,
|
||||
// 之前没防这一下,mock 直接退出,界面那边只看到 "Remote end closed connection"。
|
||||
let body;
|
||||
try {
|
||||
body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
||||
} catch (e) {
|
||||
console.log('[mock] 请求体不是合法 JSON,已忽略:', e.message);
|
||||
res.writeHead(400, { 'Content-Type': 'application/json' }).end('{"error":"bad json"}');
|
||||
return;
|
||||
}
|
||||
const messages = body.messages || [];
|
||||
const toolMsg = messages.findLast?.((m) => m.role === 'tool');
|
||||
const hasTools = Array.isArray(body.tools) && body.tools.length > 0;
|
||||
|
||||
console.log(
|
||||
`[mock] model=${body.model} tools=${body.tools?.length || 0} msgs=${messages.length} ` +
|
||||
`temperature=${body.temperature} thinking=${JSON.stringify(body.thinking)} ` +
|
||||
`reasoning_effort=${body.reasoning_effort}`,
|
||||
);
|
||||
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Cache-Control': 'no-cache, no-transform',
|
||||
Connection: 'keep-alive',
|
||||
});
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
if (!toolMsg && hasTools) {
|
||||
// 第一轮:要求调用 calc 工具
|
||||
const args = JSON.stringify({ expression: '(1+2)*3' });
|
||||
sse(res, {
|
||||
choices: [{
|
||||
delta: {
|
||||
tool_calls: [{
|
||||
index: 0,
|
||||
id: 'call_mock_1',
|
||||
type: 'function',
|
||||
function: { name: 'calc', arguments: args },
|
||||
}],
|
||||
},
|
||||
}],
|
||||
});
|
||||
await sleep(120);
|
||||
sse(res, { choices: [{ delta: {}, finish_reason: 'tool_calls' }] });
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
// 第二轮:先吐一段思维链(reasoning_content),再给最终回答
|
||||
const thinking = [
|
||||
'用户要算 (1+2)*3。',
|
||||
'我需要先调用计算工具,避免自己算错。',
|
||||
'工具返回的表达式是 (1+2)*3,结果是 9。',
|
||||
'把结果解释给用户,并说明这条链路是端到端跑通的。',
|
||||
].join('');
|
||||
for (const ch of thinking) {
|
||||
sse(res, { choices: [{ delta: { reasoning_content: ch } }] });
|
||||
await sleep(8);
|
||||
}
|
||||
|
||||
const toolText = toolMsg ? String(toolMsg.content) : '(没拿到工具结果)';
|
||||
const answer = `我用 calc 工具算了一下:${toolText}\n\n所以 (1+2)*3 = 9。这条回答是端到端跑通的:界面 → 内核 → 工具调用 → 流式返回。`;
|
||||
for (const ch of answer) {
|
||||
sse(res, { choices: [{ delta: { content: ch } }] });
|
||||
await sleep(12);
|
||||
}
|
||||
sse(res, { choices: [{ delta: {}, finish_reason: 'stop' }] });
|
||||
sse(res, { usage: { prompt_tokens: 100, completion_tokens: 60, total_tokens: 160 }, choices: [] });
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
});
|
||||
|
||||
server.listen(PORT, '127.0.0.1', () => console.log(`[mock] listening on http://127.0.0.1:${PORT}/v1`));
|
||||
129
scripts/parity-thinking.mjs
Normal file
129
scripts/parity-thinking.mjs
Normal file
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* 对拍:Node 内核和 Python 内核,给每个提供商 + 每个思考强度
|
||||
* 生成的请求体必须逐字段一致。
|
||||
*
|
||||
* 为什么值得专门对拍:这两份实现跑在不同端(电脑 / 手机),
|
||||
* 一旦分叉,就会出现"电脑上好好的,手机上 400"这种最难查的问题。
|
||||
*
|
||||
* 用法: node scripts/parity-thinking.mjs
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { normalizeBody, thinkingModeOf } from '../server/src/providers.mjs';
|
||||
import { PROVIDER_PRESETS } from '../server/src/config.mjs';
|
||||
|
||||
const PY = 'C:\\Python313\\python.exe';
|
||||
const LEVELS = ['auto', 'off', 'low', 'medium', 'high'];
|
||||
const MODELS = {
|
||||
ark: 'doubao-seed-2-1-pro-260628',
|
||||
openai: 'gpt-5-mini', // 故意用推理模型,把剥离 sampling 参数那条分支也带上
|
||||
deepseek: 'deepseek-reasoner',
|
||||
kimi: 'kimi-k2-0905-preview',
|
||||
zhipu: 'glm-4.6',
|
||||
dashscope: 'qwen-plus',
|
||||
siliconflow: 'deepseek-ai/DeepSeek-V3',
|
||||
openrouter: 'o3-mini',
|
||||
ollama: 'qwen2.5:7b',
|
||||
custom: 'my-model',
|
||||
};
|
||||
|
||||
/* ---------------- Node 侧:直接算 ---------------- */
|
||||
const nodeCases = [];
|
||||
for (const provider of Object.keys(PROVIDER_PRESETS)) {
|
||||
for (const level of LEVELS) {
|
||||
const body = normalizeBody({
|
||||
provider,
|
||||
model: MODELS[provider] || 'x',
|
||||
thinkingLevel: level,
|
||||
body: {
|
||||
model: MODELS[provider] || 'x',
|
||||
messages: [{ role: 'user', content: 'hi' }],
|
||||
stream: false,
|
||||
temperature: 0.7,
|
||||
},
|
||||
});
|
||||
nodeCases.push({ provider, level, body });
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- Python 侧:让内核自己算 ---------------- */
|
||||
const pyScript = `
|
||||
import json, sys
|
||||
sys.path.insert(0, 'android/kernel')
|
||||
import providers
|
||||
from defaults import PROVIDER_PRESETS
|
||||
|
||||
models = json.loads(sys.argv[1])
|
||||
levels = json.loads(sys.argv[2])
|
||||
out = []
|
||||
for provider in PROVIDER_PRESETS:
|
||||
for level in levels:
|
||||
body = providers.normalize_body(
|
||||
provider, models.get(provider, 'x'), level,
|
||||
{'model': models.get(provider, 'x'),
|
||||
'messages': [{'role': 'user', 'content': 'hi'}],
|
||||
'stream': False, 'temperature': 0.7},
|
||||
)
|
||||
out.append({'provider': provider, 'level': level, 'body': body,
|
||||
'mode': providers.thinking_mode_of(provider)})
|
||||
print(json.dumps(out, ensure_ascii=False))
|
||||
`;
|
||||
|
||||
const res = spawnSync(
|
||||
PY,
|
||||
['-c', pyScript, JSON.stringify(MODELS), JSON.stringify(LEVELS)],
|
||||
{ encoding: 'utf8', cwd: process.cwd(), timeout: 120000 },
|
||||
);
|
||||
|
||||
if (res.status !== 0) {
|
||||
console.error('Python 侧跑失败:');
|
||||
console.error(res.stderr || res.stdout);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const pyCases = JSON.parse(res.stdout.trim());
|
||||
|
||||
/* ---------------- 比对 ---------------- */
|
||||
if (pyCases.length !== nodeCases.length) {
|
||||
console.error(`❌ 用例数不一样:Node ${nodeCases.length} vs Python ${pyCases.length}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let pass = 0;
|
||||
const fails = [];
|
||||
for (const n of nodeCases) {
|
||||
const p = pyCases.find((x) => x.provider === n.provider && x.level === n.level);
|
||||
if (!p) {
|
||||
fails.push(`${n.provider}/${n.level}: Python 侧没有这个用例`);
|
||||
continue;
|
||||
}
|
||||
const a = JSON.stringify(n.body, Object.keys(n.body).sort());
|
||||
const b = JSON.stringify(p.body, Object.keys(p.body).sort());
|
||||
if (a === b) {
|
||||
pass += 1;
|
||||
} else {
|
||||
fails.push(`${n.provider}/${n.level}\n Node : ${a}\n Python: ${b}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('=== 思考强度映射对拍 ===');
|
||||
console.log(` 提供商 ${Object.keys(PROVIDER_PRESETS).length} 家 × 思考强度 ${LEVELS.length} 档 = ${nodeCases.length} 个用例`);
|
||||
console.log(` 结果:${pass} 通过 / ${fails.length} 失败`);
|
||||
|
||||
console.log('\n=== 每家实际发什么 ===');
|
||||
for (const provider of Object.keys(PROVIDER_PRESETS)) {
|
||||
const mode = thinkingModeOf(provider);
|
||||
const samples = [];
|
||||
for (const level of ['off', 'high']) {
|
||||
const c = nodeCases.find((x) => x.provider === provider && x.level === level);
|
||||
const keys = Object.keys(c.body).filter((k) => ['thinking', 'reasoning_effort', 'temperature'].includes(k));
|
||||
samples.push(`${level}: ${keys.length ? JSON.stringify(Object.fromEntries(keys.map((k) => [k, c.body[k]]))) : '(不加字段)'}`);
|
||||
}
|
||||
console.log(` ${provider.padEnd(12)} mode=${mode.padEnd(7)} ${samples.join(' ')}`);
|
||||
}
|
||||
|
||||
if (fails.length) {
|
||||
console.log('\n=== 不一致明细 ===');
|
||||
fails.forEach((f) => console.log(' ❌ ' + f));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('\n✅ 两边完全一致');
|
||||
23
scripts/prefix-agent-avatars.mjs
Normal file
23
scripts/prefix-agent-avatars.mjs
Normal file
@@ -0,0 +1,23 @@
|
||||
/** 头像 PNG 加 agent- 前缀,避免和图标同名(cloud.png 撞车导致 rspack 报冲突)。 */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const dir = path.join(repo, 'app', 'src', 'assets', 'avatars-png');
|
||||
|
||||
for (const file of fs.readdirSync(dir)) {
|
||||
if (!file.endsWith('.png') || file.startsWith('agent-')) continue;
|
||||
fs.renameSync(path.join(dir, file), path.join(dir, `agent-${file}`));
|
||||
}
|
||||
|
||||
const iconFile = path.join(repo, 'app', 'src', 'Icon.tsx');
|
||||
let src = fs.readFileSync(iconFile, 'utf8');
|
||||
src = src.replace(/\.\/assets\/avatars-png\/([a-z0-9-]+)\.png/g, './assets/avatars-png/agent-$1.png');
|
||||
fs.writeFileSync(iconFile, src, 'utf8');
|
||||
|
||||
console.log('头像文件:', fs.readdirSync(dir).join(', '));
|
||||
console.log('Icon.tsx 里的头像引用:');
|
||||
for (const line of src.split('\n')) {
|
||||
if (line.includes('avatars-png')) console.log(' ', line.trim());
|
||||
}
|
||||
31
scripts/probe-bootstrap-order.py
Normal file
31
scripts/probe-bootstrap-order.py
Normal file
@@ -0,0 +1,31 @@
|
||||
"""查 zip 里有没有把 bin 当成普通文件的条目,以及 bin/su 在列表中的位置。"""
|
||||
|
||||
import zipfile
|
||||
|
||||
z = zipfile.ZipFile(r"C:\Android\cache\_boot.zip")
|
||||
infos = z.infolist()
|
||||
names = [i.filename for i in infos]
|
||||
|
||||
print("总条目:", len(names))
|
||||
|
||||
for target in ("bin", "bin/", "usr", "etc", "lib", "tmp", "var"):
|
||||
hits = [i for i, n in enumerate(names) if n == target]
|
||||
print(f" 条目 {target!r}: {'存在,位置 ' + str(hits) if hits else '不存在'}")
|
||||
|
||||
idx = names.index("bin/su")
|
||||
print("\nbin/su 的位置:", idx)
|
||||
print("它前面 8 个条目:")
|
||||
for n in names[max(0, idx - 8):idx + 1]:
|
||||
info = z.getinfo(n)
|
||||
kind = "DIR" if n.endswith("/") else "FILE"
|
||||
print(f" {kind} {n!r} attr={oct(info.external_attr)}")
|
||||
|
||||
print("\n前 12 个条目:")
|
||||
for n in names[:12]:
|
||||
info = z.getinfo(n)
|
||||
print(f" {'DIR ' if n.endswith('/') else 'FILE'} {n!r} size={info.file_size}")
|
||||
|
||||
print("\n--- 关键:bin/su 之前 bin/ 下已经有多少条目 ---")
|
||||
bin_before = [n for n in names[:idx] if n.startswith("bin/")]
|
||||
print(" ", len(bin_before))
|
||||
print(" 前几个:", bin_before[:5])
|
||||
32
scripts/probe-bootstrap-zip.py
Normal file
32
scripts/probe-bootstrap-zip.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""看 Termux bootstrap zip 里 bin/su 这个条目到底长什么样,以及有没有非法名字。"""
|
||||
|
||||
import zipfile
|
||||
|
||||
ZIP = r"C:\Android\cache\_boot.zip"
|
||||
|
||||
z = zipfile.ZipFile(ZIP)
|
||||
names = [i.filename for i in z.infolist()]
|
||||
print("总条目:", len(names))
|
||||
|
||||
print("\n--- 名字里含 su 的 ---")
|
||||
for n in names:
|
||||
if "su" in n.split("/")[-1]:
|
||||
info = z.getinfo(n)
|
||||
print(f" {n!r} size={info.file_size} compress={info.compress_type} attr={oct(info.external_attr)}")
|
||||
|
||||
print("\n--- bin 下以 s 开头的 ---")
|
||||
print(" ", [n for n in names if n.startswith("bin/s")][:24])
|
||||
|
||||
print("\n--- 含控制字符的名字 ---")
|
||||
bad = [n for n in names if any(ord(c) < 32 or ord(c) == 127 for c in n)]
|
||||
print(" ", bad[:10] or "无")
|
||||
|
||||
print("\n--- 以 bin/ 开头的条目数 ---")
|
||||
print(" ", len([n for n in names if n.startswith("bin/")]))
|
||||
|
||||
print("\n--- bin 下的目录条目 ---")
|
||||
print(" ", [n for n in names if n.startswith("bin/") and n.endswith("/")][:10] or "无")
|
||||
|
||||
print("\n--- 前 5 个条目 ---")
|
||||
for n in names[:5]:
|
||||
print(" ", repr(n))
|
||||
35
scripts/probe-bootstrap.mjs
Normal file
35
scripts/probe-bootstrap.mjs
Normal file
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* 搞清楚 Termux 的 libtermux-bootstrap.so 到底是什么格式:
|
||||
* 它是 ELF 开头,但 tar/bsdtar 能当 zip 解出来 —— 说明 ZIP 数据在后面。
|
||||
* 我们需要知道 ZIP 的起始偏移,才能在 Android 上正确解压。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
|
||||
const files = [
|
||||
'C:/Android/cache/termux-arm64.apk',
|
||||
'C:/Users/Administrator/AppData/Local/Temp/termux-arm64/lib/arm64-v8a/libtermux-bootstrap.so',
|
||||
];
|
||||
|
||||
function analyze(buf, label) {
|
||||
const sig = Buffer.from([0x50, 0x4b, 0x03, 0x04]);
|
||||
const eocd = Buffer.from([0x50, 0x4b, 0x05, 0x06]);
|
||||
const firstLoc = buf.indexOf(sig);
|
||||
const firstEocd = buf.indexOf(eocd);
|
||||
console.log(`\n== ${label}`);
|
||||
console.log(' 大小:', buf.length);
|
||||
console.log(' 前 16 字节:', [...buf.slice(0, 16)].map((b) => b.toString(16).padStart(2, '0')).join(' '));
|
||||
console.log(' 首个 PK\\x03\\x04 偏移:', firstLoc);
|
||||
console.log(' 首个 PK\\x05\\x06(EOCD) 偏移:', firstEocd);
|
||||
// EOCD 在文件尾部,里面记录了中央目录偏移
|
||||
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65558); i--) {
|
||||
if (buf[i] === 0x50 && buf[i + 1] === 0x4b && buf[i + 2] === 0x05 && buf[i + 3] === 0x06) {
|
||||
const entries = buf.readUInt16LE(i + 10);
|
||||
const cdSize = buf.readUInt32LE(i + 12);
|
||||
const cdOffset = buf.readUInt32LE(i + 16);
|
||||
console.log(` EOCD@${i}: 条目数=${entries} 中央目录偏移=${cdOffset} 大小=${cdSize}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
analyze(fs.readFileSync(files[1]), 'libtermux-bootstrap.so (arm64)');
|
||||
51
scripts/probe-keepalive.mjs
Normal file
51
scripts/probe-keepalive.mjs
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 确定性排查:同一 keep-alive 连接上连发多个 POST,看响应会不会错位。
|
||||
* 用法: node scripts/probe-keepalive.mjs [base]
|
||||
*/
|
||||
import http from 'node:http';
|
||||
|
||||
const BASE = process.argv[2] || 'http://127.0.0.1:5399';
|
||||
const url = new URL(BASE);
|
||||
|
||||
function requestOnce(agent, index) {
|
||||
return new Promise((resolve) => {
|
||||
const payload = JSON.stringify({ name: 'shell', args: { command: `echo req-${index}` } });
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: url.hostname,
|
||||
port: url.port,
|
||||
path: '/api/tools/run',
|
||||
method: 'POST',
|
||||
agent,
|
||||
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) },
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (c) => (data += c));
|
||||
res.on('end', () =>
|
||||
resolve({ index, status: res.statusCode, keepAlive: res.headers.connection, body: data.slice(0, 160) }),
|
||||
);
|
||||
},
|
||||
);
|
||||
req.on('error', (e) => resolve({ index, status: 0, body: `ERR ${e.message}` }));
|
||||
req.end(payload);
|
||||
});
|
||||
}
|
||||
|
||||
const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
|
||||
|
||||
console.log('=== 同一连接串行 5 次 ===');
|
||||
for (let i = 1; i <= 5; i += 1) {
|
||||
const r = await requestOnce(agent, i);
|
||||
const matched = r.body.includes(`req-${i}`);
|
||||
console.log(`${matched ? '✅' : '❌'} #${i} status=${r.status} conn=${r.keepAlive} ${r.body.replace(/\s+/g, ' ')}`);
|
||||
}
|
||||
agent.destroy();
|
||||
|
||||
console.log('\n=== 每次新连接(Connection: close)===');
|
||||
const closeAgent = new http.Agent({ keepAlive: false });
|
||||
for (let i = 1; i <= 3; i += 1) {
|
||||
const r = await requestOnce(closeAgent, i);
|
||||
const matched = r.body.includes(`req-${i}`);
|
||||
console.log(`${matched ? '✅' : '❌'} #${i} status=${r.status} ${r.body.replace(/\s+/g, ' ')}`);
|
||||
}
|
||||
45
scripts/probe-misc.mjs
Normal file
45
scripts/probe-misc.mjs
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 列出 AAR 里的类名,并测一下下载源速度。
|
||||
* 用法: node scripts/probe-misc.mjs
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const WORK = 'C:\\Android\\probe';
|
||||
|
||||
// 1) xelement 里有哪些类
|
||||
const xeDir = path.join(WORK, 'x-xelement');
|
||||
console.log('x-xelement 内容:', fs.existsSync(xeDir) ? fs.readdirSync(xeDir).join(', ') : '(不存在)');
|
||||
const jar = path.join(xeDir, 'classes.jar');
|
||||
if (fs.existsSync(jar)) {
|
||||
const res = spawnSync('jar', ['tf', jar], { encoding: 'utf8' });
|
||||
const all = (res.stdout || '').split('\n').filter(Boolean);
|
||||
console.log('类总数:', all.length);
|
||||
console.log('含 Behaviors/XElement 的类:');
|
||||
console.log(all.filter((c) => /Behavior|XElement/i.test(c)).slice(0, 20).join('\n'));
|
||||
}
|
||||
|
||||
// 2) 测速:分别从谷歌和腾讯镜像拉前 8MB
|
||||
async function speed(label, url, bytes = 8 * 1024 * 1024) {
|
||||
const started = Date.now();
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
headers: { Range: `bytes=0-${bytes - 1}` },
|
||||
signal: AbortSignal.timeout(60000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.log(`${label}: HTTP ${res.status}`);
|
||||
return;
|
||||
}
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
const secs = (Date.now() - started) / 1000;
|
||||
console.log(`${label}: ${(buf.length / 1024 / 1024).toFixed(1)}MB / ${secs.toFixed(1)}s = ${(buf.length / 1024 / 1024 / secs).toFixed(2)} MB/s`);
|
||||
} catch (err) {
|
||||
console.log(`${label}: ERR ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
await speed('google ', 'https://dl.google.com/android/repository/commandlinetools-win-11076708_latest.zip');
|
||||
await speed('tencent ', 'https://mirrors.cloud.tencent.com/AndroidSDK/commandlinetools-win-11076708_latest.zip');
|
||||
await speed('aliyun ', 'https://mirrors.aliyun.com/android.googlesource.com/commandlinetools-win-11076708_latest.zip');
|
||||
38
scripts/probe-mix.mjs
Normal file
38
scripts/probe-mix.mjs
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* 区分"请求体是旧的"还是"响应是旧的":两次请求用不同的工具名。
|
||||
* 用法: node scripts/probe-mix.mjs [base]
|
||||
*/
|
||||
import http from 'node:http';
|
||||
|
||||
const BASE = process.argv[2] || 'http://127.0.0.1:5399';
|
||||
const url = new URL(BASE);
|
||||
const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
|
||||
|
||||
function call(payload) {
|
||||
return new Promise((resolve) => {
|
||||
const data = JSON.stringify(payload);
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: url.hostname,
|
||||
port: url.port,
|
||||
path: '/api/tools/run',
|
||||
method: 'POST',
|
||||
agent,
|
||||
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) },
|
||||
},
|
||||
(res) => {
|
||||
let out = '';
|
||||
res.on('data', (c) => (out += c));
|
||||
res.on('end', () => resolve(out.replace(/\s+/g, ' ').slice(0, 150)));
|
||||
},
|
||||
);
|
||||
req.end(data);
|
||||
});
|
||||
}
|
||||
|
||||
console.log('#1 shell echo A →', await call({ name: 'shell', args: { command: 'echo A' } }));
|
||||
console.log('#2 calc 1+1 →', await call({ name: 'calc', args: { expression: '1+1' } }));
|
||||
console.log('#3 shell echo C →', await call({ name: 'shell', args: { command: 'echo C' } }));
|
||||
console.log('#4 calc 9*9 →', await call({ name: 'calc', args: { expression: '9*9' } }));
|
||||
console.log('#5 now →', await call({ name: 'now', args: {} }));
|
||||
agent.destroy();
|
||||
79
scripts/probe-poll-cursor.mjs
Normal file
79
scripts/probe-poll-cursor.mjs
Normal file
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* 精确定位"轮询会不会重复投递事件"(不走 adb,直接 HTTP)。
|
||||
* 用法: node scripts/probe-poll-cursor.mjs [base]
|
||||
*/
|
||||
const BASE = process.argv[2] || 'http://127.0.0.1:5403';
|
||||
|
||||
const post = async (p, body) =>
|
||||
(await fetch(BASE + p, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})).json();
|
||||
|
||||
const get = async (p) => (await fetch(BASE + p)).json();
|
||||
|
||||
console.log('起任务…');
|
||||
const started = await post('/api/chat', {
|
||||
conversationId: 'c_main',
|
||||
message: '用一句话解释什么是流式输出',
|
||||
history: [],
|
||||
transport: 'poll',
|
||||
});
|
||||
console.log(' runId =', started.runId);
|
||||
|
||||
let cursor = 0;
|
||||
let text = '';
|
||||
let reasoning = '';
|
||||
let done = false;
|
||||
const perPoll = [];
|
||||
let seq = 0;
|
||||
|
||||
while (!done && seq < 300) {
|
||||
const r = await get(`/api/chat/poll?runId=${started.runId}&cursor=${cursor}`);
|
||||
if (!r.ok) {
|
||||
console.log('轮询失败', r);
|
||||
break;
|
||||
}
|
||||
let addedText = 0;
|
||||
let addedEvents = 0;
|
||||
for (const e of r.events || []) {
|
||||
addedEvents += 1;
|
||||
if (e.type === 'delta') {
|
||||
text += e.text;
|
||||
addedText += e.text.length;
|
||||
}
|
||||
if (e.type === 'reasoning') reasoning += e.text;
|
||||
}
|
||||
perPoll.push({ seq, from: cursor, to: r.cursor, events: addedEvents, addedText });
|
||||
// 关键:游标必须由服务端给的 cursor 推进,且不能回退
|
||||
if (r.cursor < cursor) {
|
||||
console.log('❌ 服务端 cursor 回退了!', cursor, '→', r.cursor);
|
||||
break;
|
||||
}
|
||||
cursor = r.cursor;
|
||||
done = Boolean(r.done);
|
||||
seq += 1;
|
||||
if (!done) await new Promise((x) => setTimeout(x, 120));
|
||||
}
|
||||
|
||||
console.log(`\n轮询 ${perPoll.length} 次,正文累计 ${text.length} 字,思维链 ${reasoning.length} 字`);
|
||||
console.log('每次拉到的增量:');
|
||||
for (const p of perPoll.slice(0, 20)) {
|
||||
console.log(` #${p.seq} cursor ${p.from}→${p.to} 事件 ${p.events} 正文 +${p.addedText}`);
|
||||
}
|
||||
|
||||
// 和落库内容对比:这才是"真值"
|
||||
const conv = await get('/api/conversations/c_main');
|
||||
const stored = (conv.conversation.messages || []).filter((m) => m.role === 'assistant').pop();
|
||||
const storedText = stored?.content || '';
|
||||
console.log(`\n落库正文 ${storedText.length} 字`);
|
||||
console.log(`轮询累计 ${text.length} 字`);
|
||||
console.log(storedText.length === text.length
|
||||
? '✅ 完全一致:轮询没有重复投递'
|
||||
: `❌ 对不上:差 ${text.length - storedText.length} 字`);
|
||||
|
||||
if (storedText.length !== text.length) {
|
||||
console.log('\n落库:', storedText.slice(0, 100));
|
||||
console.log('累计:', text.slice(0, 100));
|
||||
}
|
||||
106
scripts/probe-settings-wipe.mjs
Normal file
106
scripts/probe-settings-wipe.mjs
Normal file
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* 复现"保存设置后配置被清空"。
|
||||
* 直接按 SettingsScreen 发的那个 patch 形状打 PUT /api/settings,再看 GET /api/state。
|
||||
*
|
||||
* 用法: node scripts/probe-settings-wipe.mjs [base]
|
||||
*/
|
||||
const BASE = process.argv[2] || 'http://127.0.0.1:5199';
|
||||
|
||||
const get = async () => (await fetch(`${BASE}/api/state`)).json();
|
||||
|
||||
async function put(patch) {
|
||||
const res = await fetch(`${BASE}/api/settings`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
const text = await res.text();
|
||||
let json;
|
||||
try {
|
||||
json = JSON.parse(text);
|
||||
} catch {
|
||||
json = { __raw: text.slice(0, 200) };
|
||||
}
|
||||
return { status: res.status, json };
|
||||
}
|
||||
|
||||
const show = (label, s) => {
|
||||
console.log(` ${label}`);
|
||||
console.log(` provider=${JSON.stringify(s.provider)} model=${JSON.stringify(s.model)}`);
|
||||
console.log(` baseUrl=${JSON.stringify(s.baseUrl)} thinking=${JSON.stringify(s.thinkingLevel)}`);
|
||||
console.log(` nickname=${JSON.stringify(s.nickname)} toolsDir=${JSON.stringify(s.toolsDir)}`);
|
||||
console.log(` hasApiKey=${s.hasApiKey} python=${s.tools?.python} mcp=${s.tools?.mcp}`);
|
||||
console.log(` systemPrompt 长度=${(s.systemPrompt || '').length}`);
|
||||
};
|
||||
|
||||
console.log('=== 保存前 ===');
|
||||
const before = await get();
|
||||
show('当前', before.settings);
|
||||
|
||||
console.log('\n=== 模拟界面发的那份 patch ===');
|
||||
// 关键:SettingsScreen 用 json.put("tools", mapOf(...)),看内核怎么处理
|
||||
const patch = {
|
||||
provider: before.settings.provider,
|
||||
baseUrl: before.settings.baseUrl,
|
||||
model: before.settings.model,
|
||||
temperature: before.settings.temperature,
|
||||
maxRounds: before.settings.maxRounds,
|
||||
thinkingLevel: before.settings.thinkingLevel,
|
||||
toolsDir: before.settings.toolsDir,
|
||||
systemPrompt: before.settings.systemPrompt,
|
||||
tools: { python: true, mcp: true },
|
||||
nickname: before.settings.nickname || '我',
|
||||
};
|
||||
console.log(' ', JSON.stringify(patch).slice(0, 220));
|
||||
|
||||
const res = await put(patch);
|
||||
console.log('\n=== PUT 响应 ===');
|
||||
console.log(' HTTP', res.status, JSON.stringify(res.json).slice(0, 300));
|
||||
|
||||
console.log('\n=== 保存后 ===');
|
||||
const after = await get();
|
||||
show('当前', after.settings);
|
||||
|
||||
const lost = [];
|
||||
for (const key of ['provider', 'model', 'baseUrl', 'thinkingLevel', 'nickname', 'toolsDir']) {
|
||||
if (String(before.settings[key] ?? '') !== String(after.settings[key] ?? '')) {
|
||||
lost.push(`${key}: ${JSON.stringify(before.settings[key])} → ${JSON.stringify(after.settings[key])}`);
|
||||
}
|
||||
}
|
||||
if ((before.settings.systemPrompt || '').length !== (after.settings.systemPrompt || '').length) {
|
||||
lost.push(`systemPrompt 长度: ${(before.settings.systemPrompt || '').length} → ${(after.settings.systemPrompt || '').length}`);
|
||||
}
|
||||
if (before.settings.hasApiKey && !after.settings.hasApiKey) lost.push('API Key 丢了');
|
||||
|
||||
console.log('\n=== 结论 ===');
|
||||
console.log(lost.length ? '❌ 有字段被改动/清空:\n ' + lost.join('\n ') : '✅ 没有字段丢失');
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* 第二关:模拟"旧版前端那个 bug"——全量下发空值。
|
||||
* 内核现在必须把这些空值当"没填"丢掉,一个字段都不许被清掉。
|
||||
* ------------------------------------------------------------------ */
|
||||
console.log('\n=== 攻击测试:下发一堆空值 ===');
|
||||
const attack = {
|
||||
provider: '',
|
||||
baseUrl: '',
|
||||
model: '',
|
||||
apiKey: '',
|
||||
nickname: '',
|
||||
systemPrompt: '',
|
||||
thinkingLevel: '',
|
||||
};
|
||||
const attackRes = await put(attack);
|
||||
console.log(' HTTP', attackRes.status);
|
||||
const afterAttack = await get();
|
||||
const hurt = [];
|
||||
for (const key of ['provider', 'model', 'baseUrl', 'thinkingLevel', 'nickname']) {
|
||||
if (String(after.settings[key] ?? '') !== String(afterAttack.settings[key] ?? '')) {
|
||||
hurt.push(`${key}: ${JSON.stringify(after.settings[key])} → ${JSON.stringify(afterAttack.settings[key])}`);
|
||||
}
|
||||
}
|
||||
if (after.settings.hasApiKey && !afterAttack.settings.hasApiKey) hurt.push('API Key 被清');
|
||||
if ((after.settings.systemPrompt || '').length !== (afterAttack.settings.systemPrompt || '').length) {
|
||||
hurt.push(`systemPrompt: ${(after.settings.systemPrompt || '').length} → ${(afterAttack.settings.systemPrompt || '').length}`);
|
||||
}
|
||||
console.log(hurt.length ? ' ❌ 还是被清掉了:\n ' + hurt.join('\n ') : ' ✅ 空值被正确忽略,配置没被动');
|
||||
|
||||
131
scripts/rasterize-icons.mjs
Normal file
131
scripts/rasterize-icons.mjs
Normal file
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* 把 assets 里的 SVG 图标/头像栅格化成 PNG。
|
||||
*
|
||||
* 为什么需要:Lynx 在 Android 上走 Fresco 加载图片,而 Fresco 不认 SVG,
|
||||
* logcat 里会看到 `LynxImageManager: onFailed ... reason: unknown image format`,
|
||||
* 结果是所有 SVG 图标在真机/模拟器上都不显示(Web 端正常)。
|
||||
*
|
||||
* 做法:用无头 Edge 把这些 SVG 渲染成一张透明底的雪碧图,再按格子裁成单张 PNG。
|
||||
*
|
||||
* 用法: node scripts/rasterize-icons.mjs
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repo = path.resolve(here, '..');
|
||||
const ASSETS = path.join(repo, 'app', 'src', 'assets');
|
||||
|
||||
const CELL = 96; // 每个图标的栅格尺寸(原 viewBox 是 24,等于 4x)
|
||||
const AVATAR_CELL = 192;
|
||||
const COLS = 8;
|
||||
|
||||
/** 收集要处理的 svg */
|
||||
function collect(dir, prefix) {
|
||||
const full = path.join(ASSETS, dir);
|
||||
if (!fs.existsSync(full)) return [];
|
||||
return fs
|
||||
.readdirSync(full)
|
||||
.filter((f) => f.endsWith('.svg'))
|
||||
.map((f) => ({
|
||||
name: f.replace(/\.svg$/, ''),
|
||||
outDir: `${prefix}`,
|
||||
file: path.join(full, f),
|
||||
content: fs.readFileSync(path.join(full, f), 'utf8'),
|
||||
}));
|
||||
}
|
||||
|
||||
const icons = collect('icons', 'icons-png');
|
||||
const avatars = collect('avatars', 'avatars-png');
|
||||
const groups = [
|
||||
{ items: icons, cell: CELL, out: path.join(ASSETS, 'icons-png') },
|
||||
{ items: avatars, cell: AVATAR_CELL, out: path.join(ASSETS, 'avatars-png') },
|
||||
];
|
||||
|
||||
async function shoot(items, cell, outDir, tag) {
|
||||
const rows = Math.ceil(items.length / COLS);
|
||||
const width = COLS * cell;
|
||||
const height = rows * cell;
|
||||
const cells = items
|
||||
.map(
|
||||
(item) => `<div class="cell">${item.content
|
||||
.replace(/width="\d+"/, `width="${cell}"`)
|
||||
.replace(/height="\d+"/, `height="${cell}"`)}</div>`,
|
||||
)
|
||||
.join('\n');
|
||||
|
||||
const html = `<!doctype html><html><head><meta charset="utf-8"><style>
|
||||
html,body{margin:0;padding:0;background:transparent;}
|
||||
.grid{display:grid;grid-template-columns:repeat(${COLS}, ${cell}px);width:${width}px;}
|
||||
.cell{width:${cell}px;height:${cell}px;display:flex;align-items:center;justify-content:center;}
|
||||
.cell svg{display:block;}
|
||||
</style></head><body><div class="grid">${cells}</div></body></html>`;
|
||||
|
||||
const htmlPath = path.join(repo, `.rasterize-${tag}.html`);
|
||||
fs.writeFileSync(htmlPath, html, 'utf8');
|
||||
|
||||
const pngPath = path.join(repo, `.rasterize-${tag}.png`);
|
||||
fs.rmSync(pngPath, { force: true });
|
||||
const res = spawnSync(
|
||||
process.execPath,
|
||||
[path.join(here, 'screenshot.mjs'), `file:///${htmlPath.replace(/\\/g, '/')}`, pngPath, '2500'],
|
||||
{
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
...process.env,
|
||||
OMIT_BG: '1',
|
||||
// 关键:视口必须正好是网格尺寸,否则网格会折行、裁剪就全错位
|
||||
VIEWPORT: `${width}x${height}`,
|
||||
SCALE: '1',
|
||||
},
|
||||
},
|
||||
);
|
||||
if (res.status !== 0) throw new Error('截图失败');
|
||||
return { pngPath, htmlPath, width, height, rows };
|
||||
}
|
||||
|
||||
const { execFileSync } = await import('node:child_process');
|
||||
const PY = process.env.PYTHON || 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python312\\python.exe';
|
||||
|
||||
for (const group of groups) {
|
||||
if (group.items.length === 0) continue;
|
||||
console.log(`\n=== ${group.out} :${group.items.length} 个 ===`);
|
||||
const { pngPath, htmlPath } = await shoot(group.items, group.cell, group.out, path.basename(group.out));
|
||||
fs.mkdirSync(group.out, { recursive: true });
|
||||
|
||||
// 用 Pillow 按格子裁
|
||||
const cropScript = path.join(repo, `.rasterize-crop.py`);
|
||||
fs.writeFileSync(
|
||||
cropScript,
|
||||
[
|
||||
'import sys, json, os',
|
||||
'from PIL import Image',
|
||||
'src, out_dir, cell, cols, names = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]), json.loads(sys.argv[5])',
|
||||
'img = Image.open(src).convert("RGBA")',
|
||||
'os.makedirs(out_dir, exist_ok=True)',
|
||||
'for i, name in enumerate(names):',
|
||||
' r, c = divmod(i, cols)',
|
||||
' tile = img.crop((c * cell, r * cell, (c + 1) * cell, (r + 1) * cell))',
|
||||
' tile.save(os.path.join(out_dir, name + ".png"))',
|
||||
'print("cropped", len(names))',
|
||||
].join('\n'),
|
||||
'utf8',
|
||||
);
|
||||
const out = execFileSync(
|
||||
PY,
|
||||
[cropScript, pngPath, group.out, String(group.cell), String(COLS), JSON.stringify(group.items.map((i) => i.name))],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
console.log(out.trim());
|
||||
if (process.env.KEEP !== '1') {
|
||||
fs.rmSync(htmlPath, { force: true });
|
||||
fs.rmSync(pngPath, { force: true });
|
||||
fs.rmSync(cropScript, { force: true });
|
||||
} else {
|
||||
console.log('保留了雪碧图:', pngPath);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('\n完成,PNG 在 app/src/assets/icons-png 与 avatars-png');
|
||||
20
scripts/rewire-icons.mjs
Normal file
20
scripts/rewire-icons.mjs
Normal file
@@ -0,0 +1,20 @@
|
||||
/** 把 Icon.tsx 里的 svg 引用改成栅格化后的 png(原生端 Fresco 不认 SVG)。 */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const file = path.join(repo, 'app', 'src', 'Icon.tsx');
|
||||
let src = fs.readFileSync(file, 'utf8');
|
||||
|
||||
const before = src;
|
||||
src = src.replace(/\.\/assets\/icons\/([a-z0-9-]+)\.svg/g, './assets/icons-png/$1.png');
|
||||
src = src.replace(/\.\/assets\/avatars\/([a-z0-9-]+)\.svg/g, './assets/avatars-png/$1.png');
|
||||
|
||||
if (src === before) {
|
||||
console.log('没有变化,可能已经改过');
|
||||
} else {
|
||||
fs.writeFileSync(file, src, 'utf8');
|
||||
console.log('已改写 Icon.tsx');
|
||||
}
|
||||
console.log('剩余 .svg 引用:', (src.match(/\.svg/g) || []).length);
|
||||
56
scripts/scan-nested-comment.mjs
Normal file
56
scripts/scan-nested-comment.mjs
Normal file
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* 扫 Kotlin/Java 注释里有没有 "块注释嵌套" 的雷:
|
||||
* Kotlin 的 /* ... *\/ 是**可以嵌套**的,注释里只要出现一个 "斜杠星号"(比如写通配路径 lib/*.so),
|
||||
* 就会开一层新的块注释,导致后面的代码全被注释掉 ——
|
||||
* 报错却是莫名其妙的 "Unresolved reference" / "Unclosed comment",很难查。
|
||||
*
|
||||
* 用法: node scripts/scan-nested-comment.mjs <dir>
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const root = process.argv[2];
|
||||
if (!root) {
|
||||
console.error('用法: node scripts/scan-nested-comment.mjs <目录>');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const BAD = /\/\*[^*\s]/; // 注释内容里再出现 /*
|
||||
let hits = 0;
|
||||
|
||||
function walk(dir) {
|
||||
for (const entry of fs.readdirSync(dir)) {
|
||||
const full = path.join(dir, entry);
|
||||
const stat = fs.statSync(full);
|
||||
if (stat.isDirectory()) {
|
||||
walk(full);
|
||||
continue;
|
||||
}
|
||||
if (!/\.(kt|java)$/.test(entry)) continue;
|
||||
|
||||
const lines = fs.readFileSync(full, 'utf8').split('\n');
|
||||
let inComment = false;
|
||||
lines.forEach((line, index) => {
|
||||
const trimmed = line.trim();
|
||||
if (!inComment && (trimmed.startsWith('/*') || trimmed.startsWith('/**'))) {
|
||||
inComment = true;
|
||||
return;
|
||||
}
|
||||
if (inComment) {
|
||||
if (trimmed.includes('*/')) {
|
||||
inComment = false;
|
||||
return;
|
||||
}
|
||||
// 注释正文里出现了 /* 就危险
|
||||
if (line.includes('/*')) {
|
||||
hits += 1;
|
||||
console.log(` ⚠️ ${path.relative(root, full)}:${index + 1} ${trimmed}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`扫 ${root} …`);
|
||||
walk(root);
|
||||
console.log(hits === 0 ? '没有发现嵌套注释风险' : `发现 ${hits} 处风险`);
|
||||
34
scripts/scan-newlines.mjs
Normal file
34
scripts/scan-newlines.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
/** 扫源文件里有没有异常换行符(lone CR / U+2028 等),这类字符会让编译器行号和编辑器对不上。 */
|
||||
import fs from 'node:fs';
|
||||
|
||||
const files = process.argv.slice(2);
|
||||
for (const file of files) {
|
||||
const buf = fs.readFileSync(file);
|
||||
const text = buf.toString('utf8');
|
||||
|
||||
let cr = 0;
|
||||
let crlf = 0;
|
||||
let lf = 0;
|
||||
let u2028 = 0;
|
||||
let u2029 = 0;
|
||||
let nul = 0;
|
||||
let bad = 0;
|
||||
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
const c = text[i];
|
||||
if (c === '\r') {
|
||||
if (text[i + 1] === '\n') crlf += 1;
|
||||
else cr += 1;
|
||||
} else if (c === '\n') {
|
||||
lf += 1;
|
||||
} else if (c === '\u2028') u2028 += 1;
|
||||
else if (c === '\u2029') u2029 += 1;
|
||||
else if (c === '\u0000') nul += 1;
|
||||
else if (c === '\uFFFD') bad += 1;
|
||||
}
|
||||
|
||||
const lines = text.split(/\r\n|\r|\n/).length;
|
||||
console.log(`\n${file}`);
|
||||
console.log(` 字节 ${buf.length} | 逻辑行数 ${lines}`);
|
||||
console.log(` CRLF=${crlf} 裸CR=${cr} 裸LF=${lf} U+2028=${u2028} U+2029=${u2029} NUL=${nul} 替换字符=${bad}`);
|
||||
}
|
||||
230
scripts/screenshot.mjs
Normal file
230
scripts/screenshot.mjs
Normal file
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* 用 CDP 驱动浏览器:加载页面、收集控制台/异常、模拟点击、截图。
|
||||
*
|
||||
* 用法: node screenshot.mjs <url|- > <out.png> [waitMs] [stepsJson|@stepsFile]
|
||||
* stepsJson 形如 [{"click":[28,26]},{"wait":900},{"type":"你好"},{"key":"Enter"}]
|
||||
* 坐标是 CSS px(截图是 2x 的,别看错)
|
||||
*
|
||||
* 环境变量:
|
||||
* CDP_PORT=9555 连到「已经开着调试端口」的浏览器/Electron 窗口,不再自己起 Edge
|
||||
* EDGE_PATH=... 指定浏览器可执行文件
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const EDGE = process.env.EDGE_PATH
|
||||
|| 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
|
||||
/** 有 CDP_PORT 就附着到已运行的浏览器(Electron 桌面窗口就是这种用法) */
|
||||
const attachPort = process.env.CDP_PORT ? Number(process.env.CDP_PORT) : null;
|
||||
const PORT = attachPort || 9333 + Math.floor(Math.random() * 200);
|
||||
const [, , url, outFile, waitMsArg, stepsArg] = process.argv;
|
||||
const waitMs = Number(waitMsArg || 9000);
|
||||
// stepsArg 可以是 JSON 字面量,也可以是 @文件路径(PowerShell 5.1 传引号不可靠,推荐文件)
|
||||
const steps = stepsArg
|
||||
? JSON.parse(stepsArg.startsWith('@') ? fs.readFileSync(stepsArg.slice(1), 'utf8') : stepsArg)
|
||||
: [];
|
||||
// 浏览器 profile 放系统临时目录,别污染输出目录
|
||||
const profile = path.join(os.tmpdir(), `doubao-shot-${PORT}`);
|
||||
|
||||
const child = attachPort ? null : spawn(
|
||||
EDGE,
|
||||
[
|
||||
'--headless=new',
|
||||
'--no-sandbox',
|
||||
'--disable-gpu',
|
||||
'--disable-crash-reporter',
|
||||
'--no-first-run',
|
||||
'--disable-extensions',
|
||||
'--hide-scrollbars',
|
||||
`--remote-debugging-port=${PORT}`,
|
||||
`--user-data-dir=${profile}`,
|
||||
'--window-size=420,900',
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: 'ignore', windowsHide: true },
|
||||
);
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
async function findPage() {
|
||||
for (let i = 0; i < 60; i += 1) {
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${PORT}/json/list`);
|
||||
const list = await res.json();
|
||||
const page = list.find((t) => t.type === 'page');
|
||||
if (page?.webSocketDebuggerUrl) return page;
|
||||
} catch {
|
||||
/* 还没起来 */
|
||||
}
|
||||
await sleep(300);
|
||||
}
|
||||
throw new Error('连不上 CDP');
|
||||
}
|
||||
|
||||
function connect(wsUrl) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const listeners = [];
|
||||
ws.addEventListener('open', () =>
|
||||
resolve({
|
||||
send(method, params = {}) {
|
||||
const msgId = ++id;
|
||||
ws.send(JSON.stringify({ id: msgId, method, params }));
|
||||
return new Promise((res, rej) => pending.set(msgId, { res, rej }));
|
||||
},
|
||||
on(fn) {
|
||||
listeners.push(fn);
|
||||
},
|
||||
close: () => ws.close(),
|
||||
}));
|
||||
ws.addEventListener('error', reject);
|
||||
ws.addEventListener('message', (event) => {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { res, rej } = pending.get(msg.id);
|
||||
pending.delete(msg.id);
|
||||
if (msg.error) rej(new Error(JSON.stringify(msg.error)));
|
||||
else res(msg.result);
|
||||
} else if (msg.method) {
|
||||
for (const fn of listeners) fn(msg);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function describe(msg) {
|
||||
if (msg.method === 'Runtime.consoleAPICalled') {
|
||||
const text = (msg.params.args || [])
|
||||
.map((a) => a.value ?? a.description ?? a.unserializableValue ?? a.type)
|
||||
.join(' ');
|
||||
return `[console.${msg.params.type}] ${text}`;
|
||||
}
|
||||
if (msg.method === 'Runtime.exceptionThrown') {
|
||||
const d = msg.params.exceptionDetails;
|
||||
return `[exception] ${d.text} ${d.exception?.description || ''}`.slice(0, 1200);
|
||||
}
|
||||
if (msg.method === 'Log.entryAdded') {
|
||||
const e = msg.params.entry;
|
||||
return `[log.${e.level}] ${e.text}`.slice(0, 800);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const page = await findPage();
|
||||
const cdp = await connect(page.webSocketDebuggerUrl);
|
||||
const logs = [];
|
||||
cdp.on((msg) => {
|
||||
const line = describe(msg);
|
||||
if (line) logs.push(line);
|
||||
});
|
||||
|
||||
await cdp.send('Runtime.enable');
|
||||
await cdp.send('Log.enable');
|
||||
await cdp.send('Page.enable');
|
||||
if (!attachPort) {
|
||||
// 自己起的 Edge 需要模拟成手机尺寸;附着到 Electron 窗口时用窗口真实尺寸
|
||||
// VIEWPORT=宽x高 / SCALE=倍率 可以覆盖(栅格化图标时要用整页尺寸 + 1x)
|
||||
const [vw, vh] = (process.env.VIEWPORT || '420x900').split('x').map(Number);
|
||||
const scale = Number(process.env.SCALE || 2);
|
||||
await cdp.send('Emulation.setDeviceMetricsOverride', {
|
||||
width: vw,
|
||||
height: vh,
|
||||
deviceScaleFactor: scale,
|
||||
mobile: scale > 1,
|
||||
});
|
||||
}
|
||||
|
||||
if (url && url !== '-') {
|
||||
await cdp.send('Page.navigate', { url });
|
||||
}
|
||||
await sleep(waitMs);
|
||||
|
||||
for (const step of steps) {
|
||||
if (step.wait) {
|
||||
await sleep(step.wait);
|
||||
} else if (step.click) {
|
||||
const [x, y] = step.click;
|
||||
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y });
|
||||
await cdp.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 });
|
||||
await sleep(60);
|
||||
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 });
|
||||
await sleep(step.after || 600);
|
||||
} else if (step.type !== undefined) {
|
||||
for (const ch of step.type) {
|
||||
await cdp.send('Input.insertText', { text: ch });
|
||||
await sleep(25);
|
||||
}
|
||||
await sleep(step.after || 400);
|
||||
} else if (step.key) {
|
||||
await cdp.send('Input.dispatchKeyEvent', {
|
||||
type: 'keyDown',
|
||||
key: step.key,
|
||||
code: step.key === 'Enter' ? 'Enter' : step.key,
|
||||
windowsVirtualKeyCode: step.key === 'Enter' ? 13 : 0,
|
||||
});
|
||||
await cdp.send('Input.dispatchKeyEvent', {
|
||||
type: 'keyUp',
|
||||
key: step.key,
|
||||
code: step.key === 'Enter' ? 'Enter' : step.key,
|
||||
});
|
||||
await sleep(step.after || 600);
|
||||
} else if (step.wheel) {
|
||||
// [x, y, deltaY]
|
||||
const [x, y, deltaY] = step.wheel;
|
||||
await cdp.send('Input.dispatchMouseEvent', {
|
||||
type: 'mouseWheel',
|
||||
x,
|
||||
y,
|
||||
deltaX: 0,
|
||||
deltaY,
|
||||
});
|
||||
await sleep(step.after || 500);
|
||||
} else if (step.eval) {
|
||||
const res = await cdp.send('Runtime.evaluate', { expression: step.eval, awaitPromise: true, returnByValue: true });
|
||||
console.log('[step-eval]', JSON.stringify(res.result?.value ?? res.result?.description ?? null).slice(0, 1200));
|
||||
await sleep(step.after || 400);
|
||||
}
|
||||
}
|
||||
|
||||
const probe = await cdp.send('Runtime.evaluate', {
|
||||
expression: `(() => {
|
||||
const v = document.querySelector('lynx-view');
|
||||
const sr = v && v.shadowRoot;
|
||||
return JSON.stringify({
|
||||
hasView: !!v,
|
||||
viewRect: v ? [v.clientWidth, v.clientHeight] : null,
|
||||
shadowChildren: sr ? sr.children.length : -1,
|
||||
shadowHtmlLen: sr ? sr.innerHTML.length : -1,
|
||||
bodyText: (document.body.innerText || '').slice(0, 200),
|
||||
});
|
||||
})()`,
|
||||
returnByValue: true,
|
||||
});
|
||||
console.log('[probe]', probe.result?.value);
|
||||
|
||||
const shot = await cdp.send('Page.captureScreenshot', {
|
||||
format: 'png',
|
||||
captureBeyondViewport: false,
|
||||
// OMIT_BG=1 时输出透明背景,用来把 SVG 栅格化成带透明通道的 PNG
|
||||
omitBackground: process.env.OMIT_BG === '1',
|
||||
});
|
||||
fs.writeFileSync(outFile, Buffer.from(shot.data, 'base64'));
|
||||
console.log('[shot]', outFile, fs.statSync(outFile).size, 'bytes');
|
||||
|
||||
console.log('--- console ---');
|
||||
for (const line of logs.slice(0, 60)) console.log(line);
|
||||
|
||||
cdp.close();
|
||||
child?.kill();
|
||||
await sleep(500);
|
||||
process.exit(0);
|
||||
})().catch(async (err) => {
|
||||
console.error('[fatal]', err.message);
|
||||
child?.kill();
|
||||
process.exit(1);
|
||||
});
|
||||
38
scripts/test-shell-tool.mjs
Normal file
38
scripts/test-shell-tool.mjs
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* 在设备上跑一条 shell 命令,验证内置 Termux 的 bash 环境是否正常。
|
||||
* 用法: node scripts/test-shell-tool.mjs [serial] [port] [command]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const SERIAL = process.argv[2] || 'emulator-5554';
|
||||
const PORT = process.argv[3] || '5199';
|
||||
const COMMAND = process.argv[4] || 'echo BASH_OK; uname -a; whoami; echo "PREFIX=$PREFIX"; ls $PREFIX/bin | wc -l';
|
||||
const ADB = 'C:\\Android\\Sdk\\platform-tools\\adb.exe';
|
||||
|
||||
function sh(cmd, timeout = 90000) {
|
||||
const res = spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout });
|
||||
return `${res.stdout || ''}${res.stderr || ''}`.trim();
|
||||
}
|
||||
|
||||
const b64 = Buffer.from(JSON.stringify({ name: 'shell', args: { command: COMMAND } }), 'utf8').toString('base64');
|
||||
sh(`echo '${b64}' | base64 -d > /data/local/tmp/p.json`);
|
||||
const out = sh(`curl -s --max-time 60 -X POST -H 'Content-Type: application/json' -d @/data/local/tmp/p.json http://127.0.0.1:${PORT}/api/tools/run`);
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(out);
|
||||
} catch {
|
||||
console.log('原始返回:', out.slice(0, 400));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const r = parsed.result || {};
|
||||
console.log('命令:', COMMAND);
|
||||
console.log('ok :', parsed.ok);
|
||||
console.log('通道(via):', r.via);
|
||||
console.log('退出码 :', r.exit_code);
|
||||
console.log('--- stdout ---');
|
||||
console.log((r.stdout || '').trim() || '(空)');
|
||||
console.log('--- stderr ---');
|
||||
console.log((r.stderr || '').trim() || '(空)');
|
||||
if (parsed.error) console.log('error:', parsed.error);
|
||||
71
scripts/verify-mcp-stdio.mjs
Normal file
71
scripts/verify-mcp-stdio.mjs
Normal file
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 验证 MCP 的 stdio 传输两种模式结果一致:
|
||||
* 真子进程(电脑默认) vs 进程内仿真(安卓默认;电脑上用 DOUBAO_MCP_INPROC_STDIO=1 强制)
|
||||
*
|
||||
* 用法: node scripts/verify-mcp-stdio.mjs [base] [pythonPath] [serverPy]
|
||||
*/
|
||||
const BASE = process.argv[2] || 'http://127.0.0.1:5399';
|
||||
const PY = process.argv[3] || 'python';
|
||||
const SERVER = process.argv[4];
|
||||
|
||||
const config = {
|
||||
servers: [
|
||||
{
|
||||
name: 'py-stdio',
|
||||
enabled: true,
|
||||
transport: 'stdio',
|
||||
command: PY,
|
||||
args: [SERVER],
|
||||
env: {},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const put = async (p, body) => {
|
||||
const res = await fetch(BASE + p, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return res.json();
|
||||
};
|
||||
const post = async (p, body) => {
|
||||
const res = await fetch(BASE + p, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body ?? {}),
|
||||
});
|
||||
return res.json();
|
||||
};
|
||||
const get = async (p) => (await fetch(BASE + p)).json();
|
||||
|
||||
console.log(`目标 ${BASE}\n`);
|
||||
console.log('写入 stdio 配置…');
|
||||
const saved = await put('/api/mcp/config', { text: JSON.stringify(config, null, 2) });
|
||||
console.log(' ok =', saved.ok, '| 结果 =', JSON.stringify(saved.results));
|
||||
if (!saved.ok) process.exit(1);
|
||||
|
||||
const state = await get('/api/state');
|
||||
const tools = (state.toolNames || []).filter((n) => n.startsWith('mcp__py-stdio__'));
|
||||
console.log(' stdio 暴露的工具 =', tools.join(', ') || '(无)');
|
||||
|
||||
let pass = 0;
|
||||
let fail = 0;
|
||||
const check = (label, ok, detail) => {
|
||||
console.log(`${ok ? '✅' : '❌'} ${label}${detail ? ` → ${String(detail).slice(0, 200)}` : ''}`);
|
||||
ok ? (pass += 1) : (fail += 1);
|
||||
};
|
||||
|
||||
check('连接成功并列出 3 个工具', tools.length === 3, tools.join(', '));
|
||||
|
||||
const wc = await post('/api/tools/run', { name: 'mcp__py-stdio__word_count', args: { text: 'hello 世界 hello' } });
|
||||
check('tools/call: word_count', wc.ok === true && String(wc.result || '').includes('chars'), JSON.stringify(wc.result ?? wc.error));
|
||||
|
||||
const host = await post('/api/tools/run', { name: 'mcp__py-stdio__host_info', args: {} });
|
||||
check('tools/call: host_info', host.ok === true && String(host.result || '').includes('python'), JSON.stringify(host.result ?? host.error).slice(0, 200));
|
||||
|
||||
const net = await post('/api/tools/run', { name: 'mcp__py-stdio__http_get', args: { url: 'https://example.com' } });
|
||||
check('tools/call: http_get(服务内部联网)', net.ok === true && String(net.result || '').includes('Example'), JSON.stringify(net.result ?? net.error).slice(0, 200));
|
||||
|
||||
console.log(`\n结果:${pass} 通过 / ${fail} 失败`);
|
||||
process.exit(fail === 0 ? 0 : 1);
|
||||
98
scripts/verify-phone-stream.mjs
Normal file
98
scripts/verify-phone-stream.mjs
Normal file
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* 在真机上验证"准流式":起一个轮询任务,连续拉几次,看正文是不是**逐步变长**的。
|
||||
* 这是用户反馈"等很久然后一次性全出来"的直接回归测试。
|
||||
*
|
||||
* 用法: node scripts/verify-phone-stream.mjs [serial] [port]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const SERIAL = process.argv[2] || 'YOUR_DEVICE_SERIAL';
|
||||
const PORT = process.argv[3] || '5199';
|
||||
const ADB = 'C:\\Android\\Sdk\\platform-tools\\adb.exe';
|
||||
|
||||
function sh(cmd, timeout = 90000) {
|
||||
const res = spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout });
|
||||
return `${res.stdout || ''}${res.stderr || ''}`.trim();
|
||||
}
|
||||
|
||||
function postJson(path, payload) {
|
||||
const b64 = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');
|
||||
sh(`echo '${b64}' | base64 -d > /data/local/tmp/p.json`);
|
||||
const out = sh(`curl -s --max-time 40 -X POST -H 'Content-Type: application/json' -d @/data/local/tmp/p.json http://127.0.0.1:${PORT}${path}`);
|
||||
try {
|
||||
return JSON.parse(out);
|
||||
} catch {
|
||||
return { __raw: out.slice(0, 200) };
|
||||
}
|
||||
}
|
||||
|
||||
function getJson(path) {
|
||||
const out = sh(`curl -s --max-time 30 http://127.0.0.1:${PORT}${path}`);
|
||||
try {
|
||||
return JSON.parse(out);
|
||||
} catch {
|
||||
return { __raw: out.slice(0, 200) };
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`设备 ${SERIAL}\n`);
|
||||
|
||||
// 先确认上游配好了;没配就用手机上的设置原样跑
|
||||
const state = getJson('/api/state');
|
||||
console.log('模型:', state.settings?.model, '| 思考强度:', state.settings?.thinkingLevel);
|
||||
console.log('有没有 Key:', state.settings?.hasApiKey ? '有' : '没有(会走报错分支,也算验证提示)');
|
||||
|
||||
console.log('\n起一个轮询任务…');
|
||||
const started = postJson('/api/chat', {
|
||||
conversationId: 'c_main',
|
||||
message: '用一句话解释什么是流式输出',
|
||||
history: [],
|
||||
transport: 'poll',
|
||||
});
|
||||
if (!started.runId) {
|
||||
console.log('❌ 没拿到 runId:', JSON.stringify(started).slice(0, 200));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(' runId =', started.runId);
|
||||
|
||||
let cursor = 0;
|
||||
let text = '';
|
||||
let reasoning = '';
|
||||
let done = false;
|
||||
let errorMsg = '';
|
||||
const growth = [];
|
||||
|
||||
const t0 = Date.now();
|
||||
for (let i = 0; i < 200 && !done; i += 1) {
|
||||
const r = getJson(`/api/chat/poll?runId=${started.runId}&cursor=${cursor}`);
|
||||
if (!r.ok) {
|
||||
console.log('❌ 轮询失败:', JSON.stringify(r).slice(0, 200));
|
||||
break;
|
||||
}
|
||||
cursor = r.cursor;
|
||||
let added = 0;
|
||||
for (const e of r.events || []) {
|
||||
if (e.type === 'delta') {
|
||||
text += e.text;
|
||||
added += e.text.length;
|
||||
}
|
||||
if (e.type === 'reasoning') reasoning += e.text;
|
||||
if (e.type === 'error') errorMsg = `${e.message}${e.hint ? `|${e.hint}` : ''}`;
|
||||
}
|
||||
if (added > 0) growth.push({ t: Date.now() - t0, len: text.length });
|
||||
done = Boolean(r.done);
|
||||
if (!done) await new Promise((x) => setTimeout(x, 150));
|
||||
}
|
||||
|
||||
console.log(`\n耗时 ${Date.now() - t0}ms,正文 ${text.length} 字,思维链 ${reasoning.length} 字`);
|
||||
if (errorMsg) console.log('上游报错(提示语应当可见):', errorMsg);
|
||||
|
||||
console.log('\n正文增长过程(观察是不是逐步变长,而不是最后一次性出现):');
|
||||
for (const point of growth.slice(0, 14)) {
|
||||
console.log(` +${String(point.t).padStart(5)}ms → ${point.len} 字`);
|
||||
}
|
||||
if (growth.length > 14) console.log(` …共 ${growth.length} 次增长`);
|
||||
|
||||
const gradual = growth.length >= 3;
|
||||
console.log(`\n${gradual ? '✅' : '❌'} 准流式:${gradual ? `分 ${growth.length} 批到达` : '增长批次太少,可能还是一次性返回'}`);
|
||||
if (text) console.log('\n正文预览:', text.slice(0, 120).replace(/\s+/g, ' '));
|
||||
195
scripts/verify-phone.mjs
Normal file
195
scripts/verify-phone.mjs
Normal file
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* 在**真机/模拟器上**直接验证内置 Python 内核(不经过电脑)。
|
||||
*
|
||||
* 为什么要 base64:adb shell 的引号转义会把 JSON 里的双引号搞坏,
|
||||
* 直接 `-d '{"a":1}'` 到手机上必然变成"请求体不是合法 JSON"。
|
||||
*
|
||||
* 用法: node scripts/verify-phone.mjs [serial] [port]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const SERIAL = process.argv[2] || 'YOUR_DEVICE_SERIAL';
|
||||
const PORT = process.argv[3] || '5199';
|
||||
const ADB = 'C:\\Android\\Sdk\\platform-tools\\adb.exe';
|
||||
|
||||
function sh(cmd, timeout = 60000) {
|
||||
const res = spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout });
|
||||
return `${res.stdout || ''}${res.stderr || ''}`.trim();
|
||||
}
|
||||
|
||||
/** 把 JSON 塞进设备上的文件,再用 curl -d @file,绕开 shell 引号地狱 */
|
||||
function post(path, payload) {
|
||||
const b64 = Buffer.from(JSON.stringify(payload ?? {}), 'utf8').toString('base64');
|
||||
sh(`echo '${b64}' | base64 -d > /data/local/tmp/p.json`);
|
||||
const out = sh(`curl -s --max-time 40 -X POST -H 'Content-Type: application/json' -d @/data/local/tmp/p.json http://127.0.0.1:${PORT}${path}`);
|
||||
try {
|
||||
return JSON.parse(out);
|
||||
} catch {
|
||||
return { __raw: out.slice(0, 300) };
|
||||
}
|
||||
}
|
||||
|
||||
function get(path) {
|
||||
const out = sh(`curl -s --max-time 20 http://127.0.0.1:${PORT}${path}`);
|
||||
try {
|
||||
return JSON.parse(out);
|
||||
} catch {
|
||||
return { __raw: out.slice(0, 300) };
|
||||
}
|
||||
}
|
||||
|
||||
let pass = 0;
|
||||
let fail = 0;
|
||||
/** detail 一定要能安全字符串化:返回体缺字段时 JSON.stringify(undefined) 会炸 */
|
||||
const d = (value, max = 260) => {
|
||||
let text;
|
||||
try {
|
||||
text = typeof value === 'string' ? value : JSON.stringify(value);
|
||||
} catch {
|
||||
text = String(value);
|
||||
}
|
||||
return (text ?? 'undefined').slice(0, max);
|
||||
};
|
||||
const check = (label, ok, detail) => {
|
||||
console.log(`${ok ? '✅' : '❌'} ${label}${detail ? ` → ${d(detail)}` : ''}`);
|
||||
ok ? (pass += 1) : (fail += 1);
|
||||
};
|
||||
|
||||
console.log(`设备 ${SERIAL}\n`);
|
||||
|
||||
console.log('=== 0. 手机信息 ===');
|
||||
console.log(' ', sh('getprop ro.product.model'), '|', sh('getprop ro.build.version.release'), '|', sh('uname -m'));
|
||||
|
||||
console.log('\n=== 1. 本机内核在监听吗 ===');
|
||||
const health = get('/api/health');
|
||||
check('GET /api/health', health.ok === true, JSON.stringify(health));
|
||||
|
||||
console.log('\n=== 2. /api/state ===');
|
||||
const state = get('/api/state');
|
||||
check('智能体 4 个', state.agents?.length === 4, state.agents?.map((a) => a.name).join(', '));
|
||||
const toolNames = state.toolNames || [];
|
||||
check('工具列表(含 device)', toolNames.includes('device'), toolNames.join(', '));
|
||||
check('默认思考强度可读', typeof state.settings?.thinkingLevel === 'string', state.settings?.thinkingLevel);
|
||||
|
||||
console.log('\n=== 3. shell 工具(安卓 toybox)===');
|
||||
const shellRes = post('/api/tools/run', { name: 'shell', args: { command: 'getprop ro.product.model; uname -m; echo ok' } });
|
||||
check('执行系统命令', shellRes.ok === true, JSON.stringify(shellRes.result || shellRes.error));
|
||||
|
||||
console.log('\n=== 4. python_run(进程内 CPython)===');
|
||||
const pyRes = post('/api/tools/run', {
|
||||
name: 'python_run',
|
||||
args: { code: 'import sys, platform\nprint(sys.version.split()[0], platform.machine(), platform.system())' },
|
||||
});
|
||||
check('跑 Python 代码', pyRes.ok === true, JSON.stringify(pyRes.result || pyRes.error));
|
||||
|
||||
const libs = post('/api/tools/run', { name: 'python_run', args: { action: 'libs' } });
|
||||
check('libs(网络库)', libs.ok === true, `可用 ${libs.result?.available?.length ?? 0} 个:${(libs.result?.available || []).join(', ')}`);
|
||||
|
||||
console.log('\n=== 5. 网络能力 ===');
|
||||
const net = post('/api/tools/run', {
|
||||
name: 'python_run',
|
||||
args: { code: 'import urllib.request\nprint("HTTP", urllib.request.urlopen("https://example.com", timeout=25).status)' },
|
||||
});
|
||||
check('手机上能联网', net.ok === true && String(net.result?.stdout || '').includes('HTTP 200'), JSON.stringify(net.result?.stdout || net.error));
|
||||
|
||||
const req = post('/api/tools/run', {
|
||||
name: 'python_run',
|
||||
args: { code: 'import requests\nprint("requests", requests.get("https://example.com", timeout=25).status_code)' },
|
||||
});
|
||||
check('requests 库可用', req.ok === true && String(req.result?.stdout || '').includes('200'), d());
|
||||
|
||||
console.log('\n=== 6. device 工具(定位/传感器)===');
|
||||
const info = post('/api/tools/run', { name: 'device', args: { action: 'info' } });
|
||||
check('设备信息', info.ok === true && info.result?.model, d());
|
||||
|
||||
const sensors = post('/api/tools/run', { name: 'device', args: { action: 'sensors' } });
|
||||
const sensorList = sensors.result?.sensors || [];
|
||||
check('传感器列表', sensors.ok === true && sensorList.length > 0, `共 ${sensors.result?.count ?? 0} 个:${sensorList.slice(0, 6).map((s) => s.key).join(', ')}`);
|
||||
|
||||
const acc = post('/api/tools/run', { name: 'device', args: { action: 'sensor', sensor: 'accelerometer', duration: 1.5 } });
|
||||
check('加速度计采样', acc.ok === true && (acc.result?.sample_count ?? 0) > 0,
|
||||
`样本 ${acc.result?.sample_count} 个,last=${JSON.stringify(acc.result?.last)} ${acc.result?.unit || ''}`);
|
||||
|
||||
const gyro = post('/api/tools/run', { name: 'device', args: { action: 'sensor', sensor: 'gyroscope', duration: 1.2 } });
|
||||
check('陀螺仪采样', gyro.ok === true && (gyro.result?.sample_count ?? 0) > 0,
|
||||
`样本 ${gyro.result?.sample_count} 个,last=${JSON.stringify(gyro.result?.last)}`);
|
||||
|
||||
const loc = post('/api/tools/run', { name: 'device', args: { action: 'location' } });
|
||||
check('定位', loc.ok === true && loc.result?.available === true,
|
||||
loc.result?.available ? `lat=${loc.result.latitude} lon=${loc.result.longitude} ±${loc.result.accuracy_m}m` : loc.result?.hint || loc.error);
|
||||
|
||||
console.log('\n=== 7. 工具目录 ===');
|
||||
const dirs = sh(`ls /sdcard/Android/data/com.doubao.lynxclone/files/tools 2>/dev/null`);
|
||||
check('内置工具已播种到可写目录', dirs.includes('_protocol.py'), dirs.replace(/\s+/g, ' ').slice(0, 240));
|
||||
|
||||
console.log('\n=== 8. MCP:Python 写的服务(inproc)===');
|
||||
const mcpConfig = {
|
||||
servers: [
|
||||
{
|
||||
name: 'py-demo',
|
||||
enabled: true,
|
||||
transport: 'inproc',
|
||||
path: '/sdcard/Android/data/com.doubao.lynxclone/files/tools/_mcp_python_example.py',
|
||||
},
|
||||
],
|
||||
};
|
||||
const saved = post('/api/mcp/config', { text: JSON.stringify(mcpConfig, null, 2) });
|
||||
check('写入 MCP 配置并连接', saved.ok === true, d());
|
||||
if (saved.ok) {
|
||||
const wc = post('/api/tools/run', { name: 'mcp__py-demo__word_count', args: { text: 'hello 世界' } });
|
||||
check('调用 py 写的 MCP 工具', wc.ok === true, d());
|
||||
const host = post('/api/tools/run', { name: 'mcp__py-demo__host_info', args: {} });
|
||||
check('MCP 里能拿到手机信息', host.ok === true, d());
|
||||
}
|
||||
|
||||
console.log('\n=== 9. 语音接口 ===');
|
||||
// 这几项不需要任何 Key:验的是"接口在、默认走设备自带引擎"。
|
||||
// 云端合成要 Key,放在 verify-speech.mjs 里用 mock 单独验。
|
||||
const speechState = get('/api/speech');
|
||||
check('语音配置可读', speechState.ok === true && !!speechState.speech,
|
||||
`tts=${speechState.speech?.ttsEngine} stt=${speechState.speech?.sttEngine}`);
|
||||
check('音色列表已下发', Array.isArray(speechState.voices?.volc) && speechState.voices.volc.length > 0,
|
||||
`火山 ${speechState.voices?.volc?.length} 个 / OpenAI ${speechState.voices?.openai?.length} 个`);
|
||||
|
||||
// 把引擎临时切回 system 再打 /api/tts —— 否则用户配了云端时,跑一次验收就消耗一次额度。
|
||||
// ★ 一定要还原:验收脚本不该改用户的配置。
|
||||
const engineBefore = {
|
||||
ttsEngine: speechState.speech?.ttsEngine || 'system',
|
||||
sttEngine: speechState.speech?.sttEngine || 'system',
|
||||
};
|
||||
post('/api/settings', { speech: { ttsEngine: 'system', sttEngine: 'system' } });
|
||||
const tts = post('/api/tts', { text: '语音接口自检' });
|
||||
check('朗读接口在(system 不联网)', tts.ok === true && tts.engine === 'system', `engine=${tts.engine}`);
|
||||
|
||||
// /api/stt 收的是**原始音频字节**而不是 JSON,所以不能用 post(),单独发
|
||||
const sttB64 = Buffer.from('RIFF____WAVE').toString('base64');
|
||||
sh(`echo '${sttB64}' | base64 -d > /data/local/tmp/a.wav`);
|
||||
const sttOut = sh(
|
||||
`curl -s --max-time 30 -X POST -H 'Content-Type: audio/wav' -H 'X-Audio-Filename: a.wav' `
|
||||
+ `--data-binary @/data/local/tmp/a.wav http://127.0.0.1:${PORT}/api/stt`,
|
||||
);
|
||||
let stt = {};
|
||||
try {
|
||||
stt = JSON.parse(sttOut);
|
||||
} catch {
|
||||
stt = { __raw: sttOut.slice(0, 200) };
|
||||
}
|
||||
check('识别接口在(system 不联网)', stt.ok === true && stt.engine === 'system', `engine=${stt.engine}`);
|
||||
|
||||
const speechSettings = get('/api/state');
|
||||
check('语音 Token 不明文外泄',
|
||||
speechSettings.settings?.speech?.volcToken !== undefined &&
|
||||
(speechSettings.settings.speech.volcToken === '' || speechSettings.settings.speech.volcToken === '••••••••'),
|
||||
JSON.stringify(speechSettings.settings?.speech?.volcToken));
|
||||
|
||||
// 把用户原来的引擎设置还回去
|
||||
post('/api/settings', { speech: engineBefore });
|
||||
const restored = get('/api/state').settings?.speech;
|
||||
check('验收后原样还原了语音配置',
|
||||
restored?.ttsEngine === engineBefore.ttsEngine && restored?.sttEngine === engineBefore.sttEngine,
|
||||
`tts=${restored?.ttsEngine} stt=${restored?.sttEngine}`);
|
||||
|
||||
console.log(`\n结果:${pass} 通过 / ${fail} 失败`);
|
||||
fs.writeFileSync('phone-verify-result.json', JSON.stringify({ pass, fail, at: new Date().toISOString() }, null, 2));
|
||||
process.exit(fail === 0 ? 0 : 1);
|
||||
134
scripts/verify-pykernel.mjs
Normal file
134
scripts/verify-pykernel.mjs
Normal file
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* 对「Python 内核」(安卓端内置的那份)做完整验收。
|
||||
* 用法: node scripts/verify-pykernel.mjs [base] [mockBase]
|
||||
*/
|
||||
const BASE = process.argv[2] || 'http://127.0.0.1:5399';
|
||||
const MOCK = process.argv[3] || 'http://127.0.0.1:5299/v1';
|
||||
|
||||
let pass = 0;
|
||||
let fail = 0;
|
||||
|
||||
function check(label, ok, detail) {
|
||||
console.log(`${ok ? '✅' : '❌'} ${label}${detail ? ` → ${String(detail).slice(0, 220)}` : ''}`);
|
||||
if (ok) pass += 1;
|
||||
else fail += 1;
|
||||
}
|
||||
|
||||
const get = async (p) => (await fetch(BASE + p)).json();
|
||||
const post = async (p, body) => {
|
||||
const res = await fetch(BASE + p, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body ?? {}),
|
||||
});
|
||||
return res.json();
|
||||
};
|
||||
/** /api/chat 是 SSE,不能按 JSON 解,这里只把流读干 */
|
||||
const chatProbe = async (message) => {
|
||||
const res = await fetch(`${BASE}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ conversationId: 'c_main', message, history: [] }),
|
||||
});
|
||||
await res.text();
|
||||
};
|
||||
const put = async (p, body) => {
|
||||
const res = await fetch(BASE + p, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body ?? {}),
|
||||
});
|
||||
return res.json();
|
||||
};
|
||||
|
||||
console.log('=== 1. 状态 ===');
|
||||
const state = await get('/api/state');
|
||||
check('智能体 4 个', state.agents?.length === 4, state.agents?.map((a) => a.name).join(', '));
|
||||
check('内置工具齐全', ['calc', 'now', 'web_fetch', 'notes', 'shell', 'python_run'].every((n) => state.toolNames.includes(n)),
|
||||
state.toolNames.filter((n) => !n.startsWith('mcp__')).join(', '));
|
||||
|
||||
console.log('\n=== 2. shell 工具 ===');
|
||||
const sh = await post('/api/tools/run', { name: 'shell', args: { command: 'echo hello-shell' } });
|
||||
check('执行 echo', sh.ok && String(sh.result?.stdout || '').includes('hello-shell'), JSON.stringify(sh.result || sh.error).slice(0, 160));
|
||||
const shBad = await post('/api/tools/run', { name: 'shell', args: { command: 'rm -rf /' } });
|
||||
check('黑名单拦截', shBad.ok === false, shBad.error);
|
||||
|
||||
console.log('\n=== 3. python_run 工具 ===');
|
||||
const code = 'import sys, platform, json\nprint(json.dumps({"py": sys.version.split()[0], "os": platform.system()}))';
|
||||
const py = await post('/api/tools/run', { name: 'python_run', args: { code } });
|
||||
check('进程内执行代码', py.ok && String(py.result?.stdout || '').includes('py'), JSON.stringify(py.result || py.error).slice(0, 200));
|
||||
const libs = await post('/api/tools/run', { name: 'python_run', args: { action: 'libs' } });
|
||||
check('libs 动作', libs.ok && Array.isArray(libs.result?.available), `可用 ${libs.result?.available?.length || 0} 个`);
|
||||
const net = await post('/api/tools/run', {
|
||||
name: 'python_run',
|
||||
args: { code: 'import urllib.request\nprint(urllib.request.urlopen("https://example.com", timeout=15).status)' },
|
||||
});
|
||||
check('python_run 能联网', net.ok && String(net.result?.stdout || '').includes('200'), JSON.stringify(net.result?.stdout || net.error).slice(0, 120));
|
||||
|
||||
console.log('\n=== 4. 文件工具(证明能加载 tools/*.py)===');
|
||||
const calc = await post('/api/tools/run', { name: 'calc', args: { expression: 'sqrt(16)+log(100,10)' } });
|
||||
check('calc', calc.ok && calc.result?.value === 6, JSON.stringify(calc.result || calc.error).slice(0, 120));
|
||||
|
||||
console.log('\n=== 5. MCP(含 Python 写的服务)===');
|
||||
const mcpTools = state.toolNames.filter((n) => n.startsWith('mcp__'));
|
||||
check('MCP 工具已注册', mcpTools.length > 0, mcpTools.join(', '));
|
||||
if (mcpTools.length) {
|
||||
const target = mcpTools[0];
|
||||
const arg = target.includes('add') ? { a: 2, b: 3 } : target.includes('word_count') ? { text: 'hello 世界' } : {};
|
||||
const call = await post('/api/tools/run', { name: target, args: arg });
|
||||
check(`调用 ${target}`, call.ok === true, JSON.stringify(call.result ?? call.error).slice(0, 160));
|
||||
}
|
||||
|
||||
console.log('\n=== 6. 思考强度映射 ===');
|
||||
for (const level of ['off', 'high']) {
|
||||
await put('/api/settings', { thinkingLevel: level, provider: 'ark', baseUrl: MOCK, apiKey: 't', model: 'doubao-seed-2-1-pro-260628' });
|
||||
const s = await get('/api/state');
|
||||
check(`设置 thinkingLevel=${level}`, s.settings.thinkingLevel === level, s.settings.thinkingLevel);
|
||||
await chatProbe(`probe-${level}`);
|
||||
}
|
||||
await put('/api/settings', { provider: 'openai', model: 'gpt-5-mini', thinkingLevel: 'high' });
|
||||
await chatProbe('probe-openai');
|
||||
|
||||
console.log('\n=== 7. SSE 事件序列 ===');
|
||||
await put('/api/settings', { provider: 'ark', baseUrl: MOCK, apiKey: 't', model: 'doubao-seed-2-1-pro-260628', thinkingLevel: 'auto' });
|
||||
const res = await fetch(`${BASE}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ conversationId: 'c_main', message: '帮我算一下 (1+2)*3', history: [] }),
|
||||
});
|
||||
const events = [];
|
||||
let buf = '';
|
||||
const reader = res.body.getReader();
|
||||
const dec = new TextDecoder();
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buf += dec.decode(value, { stream: true });
|
||||
let i;
|
||||
while ((i = buf.indexOf('\n\n')) >= 0) {
|
||||
const block = buf.slice(0, i);
|
||||
buf = buf.slice(i + 2);
|
||||
for (const line of block.split('\n')) {
|
||||
const t = line.trim();
|
||||
if (t.startsWith('data:')) {
|
||||
try {
|
||||
events.push(JSON.parse(t.slice(5)));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const kinds = [...new Set(events.map((e) => e.type))];
|
||||
check('有 start/delta/done', ['start', 'delta', 'done'].every((k) => kinds.includes(k)), kinds.join(', '));
|
||||
const done = events.find((e) => e.type === 'done');
|
||||
check('done 里带正文', Boolean(done?.content), (done?.content || '').slice(0, 80));
|
||||
|
||||
console.log('\n=== 8. 会话持久化 ===');
|
||||
const convs = await get('/api/conversations');
|
||||
check('会话已落库', convs.conversations?.some((c) => c.messageCount > 0),
|
||||
convs.conversations?.map((c) => `${c.title}(${c.messageCount})`).join(', '));
|
||||
|
||||
console.log(`\n结果:${pass} 通过 / ${fail} 失败`);
|
||||
process.exit(fail === 0 ? 0 : 1);
|
||||
56
scripts/verify-round.mjs
Normal file
56
scripts/verify-round.mjs
Normal file
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* 验证:思考强度映射 + 两个新工具。
|
||||
* 用法: node scripts/verify-round.mjs [base]
|
||||
*/
|
||||
const BASE = process.argv[2] || 'http://127.0.0.1:5199';
|
||||
|
||||
async function post(path, body) {
|
||||
const res = await fetch(BASE + path, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body ?? {}),
|
||||
});
|
||||
return { status: res.status, json: await res.json().catch(() => null), text: res };
|
||||
}
|
||||
|
||||
async function put(path, body) {
|
||||
const res = await fetch(BASE + path, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body ?? {}),
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
console.log('=== python_run: 跑一段代码 ===');
|
||||
const code = [
|
||||
'import sys, json, platform',
|
||||
'print(json.dumps({"python": sys.version.split()[0], "os": platform.system(), "sum": sum(range(101))}))',
|
||||
].join('\n');
|
||||
const runRes = await post('/api/tools/run', { name: 'python_run', args: { code } });
|
||||
console.log(JSON.stringify(runRes.json).slice(0, 300));
|
||||
|
||||
console.log('\n=== python_run: 联网能力 ===');
|
||||
const netCode = [
|
||||
'import urllib.request, json',
|
||||
'try:',
|
||||
' with urllib.request.urlopen("https://example.com", timeout=15) as r:',
|
||||
' print("HTTP", r.status, "len", len(r.read()))',
|
||||
'except Exception as e:',
|
||||
' print("ERR", type(e).__name__, e)',
|
||||
].join('\n');
|
||||
const netRes = await post('/api/tools/run', { name: 'python_run', args: { code: netCode } });
|
||||
console.log(JSON.stringify(netRes.json).slice(0, 300));
|
||||
|
||||
console.log('\n=== 思考强度:依次切换,看上游收到的字段 ===');
|
||||
const levels = ['auto', 'off', 'low', 'high'];
|
||||
for (const level of levels) {
|
||||
await put('/api/settings', { thinkingLevel: level, provider: 'ark', model: 'doubao-seed-2-1-pro-260628' });
|
||||
await post('/api/chat', { conversationId: 'c_main', message: `probe-${level}`, history: [] });
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
}
|
||||
console.log('(上游字段见 mock 的 stderr 日志:thinking={...})');
|
||||
|
||||
console.log('\n=== 恢复默认 ===');
|
||||
await put('/api/settings', { thinkingLevel: 'auto' });
|
||||
console.log('done');
|
||||
284
scripts/verify-speech.mjs
Normal file
284
scripts/verify-speech.mjs
Normal file
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* 端到端验证语音链路(不需要任何真实 Key)。
|
||||
*
|
||||
* 做法:把 Python 内核跑起来,语音引擎指向本地 mock,然后打 /api/tts 和 /api/stt,
|
||||
* 看:
|
||||
* 1. 我们发出去的请求形状对不对(火山那个 `Bearer;` 分号头最容易写错);
|
||||
* 2. 返回的音频是不是真音频、能不能解出来;
|
||||
* 3. 各种失败路径(没 Key、厂商报错)会不会给出人话。
|
||||
*
|
||||
* 用法: node scripts/verify-speech.mjs [py|node]
|
||||
* py (默认)跑 android/kernel(手机用的那份)
|
||||
* node 跑 server/src(电脑/Web 用的那份)
|
||||
* 两份实现都要过同一套断言 —— 语音这块两边是分别写的,不各跑一遍不算数。
|
||||
*/
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const PY = 'C:\\Python313\\python.exe';
|
||||
const KPORT = 5433;
|
||||
const MOCK = 5388;
|
||||
const ROOT = process.cwd();
|
||||
const WHICH = (process.argv[2] || 'py').toLowerCase();
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const results = [];
|
||||
const check = (name, ok, detail) => {
|
||||
results.push({ name, ok, detail });
|
||||
console.log(` ${ok ? '✅' : '❌'} ${name}${detail ? ` → ${detail}` : ''}`);
|
||||
};
|
||||
|
||||
/* ---------------- 起 mock(语音 + 对话)---------------- */
|
||||
const mock = spawn('node', ['scripts/mock-llm.mjs'], {
|
||||
cwd: ROOT,
|
||||
env: { ...process.env, MOCK_PORT: String(MOCK) },
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
let mockLog = '';
|
||||
mock.stdout.on('data', (d) => { mockLog += d.toString(); });
|
||||
mock.stderr.on('data', (d) => { mockLog += d.toString(); });
|
||||
|
||||
/* ---------------- 起 Python 内核,语音指向 mock ---------------- */
|
||||
const kenv = {
|
||||
...process.env,
|
||||
// 两份内核的端口环境变量名不一样:Python 用 DOUBAO_PORT,Node 用 PORT
|
||||
DOUBAO_PORT: String(KPORT),
|
||||
PORT: String(KPORT),
|
||||
DOUBAO_DATA: path.join(os.tmpdir(), `doubao-speech-${Date.now()}`),
|
||||
DOUBAO_VOLC_TTS_URL: `http://127.0.0.1:${MOCK}/api/v1/tts`,
|
||||
PYTHONPATH: path.join(ROOT, 'android', 'kernel'),
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
};
|
||||
// 两份内核用同一套断言:语音是分别实现的,只验一份不算数
|
||||
const kernelCmd = WHICH === 'node'
|
||||
? { bin: 'node', args: [path.join(ROOT, 'server', 'src', 'index.mjs')] }
|
||||
: { bin: PY, args: [path.join(ROOT, 'android', 'kernel', 'main.py')] };
|
||||
const kern = spawn(kernelCmd.bin, kernelCmd.args, {
|
||||
cwd: ROOT,
|
||||
env: kenv,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
let kernLog = '';
|
||||
kern.stdout.on('data', (d) => { kernLog += d.toString(); });
|
||||
kern.stderr.on('data', (d) => { kernLog += d.toString(); });
|
||||
|
||||
const cleanup = () => {
|
||||
try { kern.kill(); } catch { /* ignore */ }
|
||||
try { mock.kill(); } catch { /* ignore */ }
|
||||
};
|
||||
process.on('exit', cleanup);
|
||||
|
||||
const waitKernel = async () => {
|
||||
for (let i = 0; i < 60; i += 1) {
|
||||
try {
|
||||
const r = await fetch(`http://127.0.0.1:${KPORT}/api/health`);
|
||||
if (r.ok) return true;
|
||||
} catch { /* 还没起来 */ }
|
||||
await sleep(500);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const api = async (p, opt) => {
|
||||
const r = await fetch(`http://127.0.0.1:${KPORT}${p}`, opt);
|
||||
return r.json();
|
||||
};
|
||||
|
||||
console.log('=== 启动 ===');
|
||||
if (!(await waitKernel())) {
|
||||
console.log(' 内核起不来:\n' + kernLog.slice(-1200));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(` 内核=${WHICH === 'node' ? 'Node' : 'Python'} :${KPORT} mock :${MOCK}`);
|
||||
|
||||
/* ---------------- 1. 默认状态 ---------------- */
|
||||
console.log('\n=== 1. 默认语音配置 ===');
|
||||
const st = await api('/api/state');
|
||||
check('默认引擎是 system(不联网)', st.speech?.ttsEngine === 'system', `ttsEngine=${st.speech?.ttsEngine}`);
|
||||
check('音色选项已下发', Array.isArray(st.speechVoices?.volc) && st.speechVoices.volc.length > 0,
|
||||
`火山 ${st.speechVoices?.volc?.length} 个 / OpenAI ${st.speechVoices?.openai?.length} 个`);
|
||||
|
||||
const ttsSystem = await api('/api/tts', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: '你好' }),
|
||||
});
|
||||
check('system 引擎不调云端', ttsSystem.ok && ttsSystem.engine === 'system', JSON.stringify(ttsSystem.engine));
|
||||
|
||||
/* ---------------- 2. OpenAI 兼容合成 ---------------- */
|
||||
console.log('\n=== 2. OpenAI 兼容 TTS ===');
|
||||
await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
speech: { ttsEngine: 'openai', ttsVoice: 'nova', ttsSpeed: 1.25, openaiApiKey: 'sk-mock', openaiBaseUrl: `http://127.0.0.1:${MOCK}/v1` },
|
||||
}),
|
||||
});
|
||||
const ttsOa = await api('/api/tts', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: '这是朗读测试' }),
|
||||
});
|
||||
check('合成成功', ttsOa.ok === true, ttsOa.ok ? '' : ttsOa.error);
|
||||
check('返回了音频', typeof ttsOa.audio === 'string' && ttsOa.audio.length > 100,
|
||||
`base64 ${ttsOa.audio?.length || 0} 字符, mime=${ttsOa.mime}`);
|
||||
if (ttsOa.audio) {
|
||||
const bytes = Buffer.from(ttsOa.audio, 'base64');
|
||||
check('是真 WAV(RIFF 头)', bytes.slice(0, 4).toString() === 'RIFF' && bytes.slice(8, 12).toString() === 'WAVE',
|
||||
`${bytes.length} 字节`);
|
||||
}
|
||||
check('mock 收到了 voice/speed', /voice=nova/.test(mockLog) && /speed=1\.25/.test(mockLog),
|
||||
(mockLog.match(/\[mock\]\[tts\][^\n]*/) || ['(没收到)'])[0].slice(0, 120));
|
||||
|
||||
/* ---------------- 3. 火山合成(重点:鉴权头)---------------- */
|
||||
console.log('\n=== 3. 火山 TTS(重点核对鉴权头)===');
|
||||
await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
speech: {
|
||||
ttsEngine: 'volc', volcAppId: 'app-123', volcToken: 'tok-abc',
|
||||
volcCluster: 'volcano_tts', ttsVoice: 'BV700_streaming', volcEncoding: 'mp3',
|
||||
},
|
||||
}),
|
||||
});
|
||||
mockLog = ''; // 只看这一段
|
||||
const ttsVolc = await api('/api/tts', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: '火山朗读测试' }),
|
||||
});
|
||||
check('火山合成成功', ttsVolc.ok === true, ttsVolc.ok ? '' : ttsVolc.error);
|
||||
const volcLine = (mockLog.match(/\[mock\]\[volc-tts\][^\n]*/) || ['(mock 没收到请求)'])[0];
|
||||
console.log(` 实际发出的请求:\n ${volcLine}`);
|
||||
check('鉴权头是 Bearer; 分号形式', /Authorization="Bearer;tok-abc"/.test(volcLine), '');
|
||||
check('body 有 app/user/audio/request 四层', /app\.appid=app-123/.test(volcLine) && /request\.text_type=plain/.test(volcLine) && /request\.operation=query/.test(volcLine), '');
|
||||
check('返回按 code=3000 判定', ttsVolc.ok === true && ttsVolc.engine === 'volc', `engine=${ttsVolc.engine}`);
|
||||
|
||||
/* ---------------- 4. 火山缺凭据 ---------------- */
|
||||
console.log('\n=== 4. 失败路径:火山没填 AppID ===');
|
||||
await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ speech: { volcAppId: '', volcToken: '' } }),
|
||||
});
|
||||
const ttsNoCred = await api('/api/tts', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: '你好' }),
|
||||
});
|
||||
check('给出人话而不是崩', ttsNoCred.ok === false && /App ID/.test(ttsNoCred.error || ''), ttsNoCred.error);
|
||||
|
||||
/* ---------------- 5. 语音识别 ---------------- */
|
||||
console.log('\n=== 5. OpenAI 兼容 STT ===');
|
||||
await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ speech: { sttEngine: 'openai', sttModel: 'whisper-1', openaiApiKey: 'sk-mock' } }),
|
||||
});
|
||||
// 造一段 0.2 秒的假音频(内容不重要,验的是请求形状)
|
||||
const fakeWav = Buffer.concat([
|
||||
Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WAVEfmt '), Buffer.alloc(4),
|
||||
Buffer.alloc(200),
|
||||
]);
|
||||
const sttRes = await api('/api/stt', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'audio/wav', 'X-Audio-Filename': 'rec.wav' },
|
||||
body: fakeWav,
|
||||
});
|
||||
check('识别成功', sttRes.ok === true, sttRes.ok ? '' : sttRes.error);
|
||||
check('拿到文字', sttRes.text === '这是语音识别的模拟结果', JSON.stringify(sttRes.text));
|
||||
const sttLine = (mockLog.match(/\[mock\]\[stt\][^\n]*/) || ['(mock 没收到)'])[0];
|
||||
console.log(` 实际发出的请求:\n ${sttLine}`);
|
||||
check('用的是 multipart 且带文件', /boundary=有/.test(sttLine) && /带文件=true/.test(sttLine), '');
|
||||
check('model 传对了', /model=whisper-1/.test(sttLine), '');
|
||||
|
||||
/* ---------------- 6. 设置脱敏 ---------------- */
|
||||
console.log('\n=== 6. Token 不能明文回给前端 ===');
|
||||
// 先把 token 填回去(上面第 4 步为了测"缺凭据"把它清零了)
|
||||
await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ speech: { volcToken: 'tok-should-be-masked', openaiApiKey: 'sk-should-be-masked' } }),
|
||||
});
|
||||
const st2 = await api('/api/state');
|
||||
check('volcToken 已脱敏', st2.settings?.speech?.volcToken === '••••••••', JSON.stringify(st2.settings?.speech?.volcToken));
|
||||
check('openaiApiKey 已脱敏', st2.settings?.speech?.openaiApiKey === '••••••••', JSON.stringify(st2.settings?.speech?.openaiApiKey));
|
||||
|
||||
/* ---------------- 7. 掩码值回写不能把真 Token 冲掉 ---------------- */
|
||||
console.log('\n=== 7. 前端把掩码原样发回来,真 Token 不能被覆盖 ===');
|
||||
// 真实的坏场景:界面读到的是掩码,用户只改了别的设置、顺手点了保存,
|
||||
// 掩码就跟着 patch 回来了 —— 如果内核不拦,真 Token 会被这八个点覆盖。
|
||||
await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ speech: { ttsEngine: 'volc', volcAppId: 'app-real', volcToken: 'tok-real-secret' } }),
|
||||
});
|
||||
const masked = (await api('/api/state')).settings?.speech;
|
||||
check('读回来的确实是掩码', masked?.volcToken === '••••••••', JSON.stringify(masked?.volcToken));
|
||||
|
||||
// 把掩码原样发回去(模拟界面保存)
|
||||
await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ speech: { volcToken: masked.volcToken, ttsVoice: 'BV001_streaming' } }),
|
||||
});
|
||||
|
||||
const ttsAfterMask = await api('/api/tts', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ text: '掩码回写测试' }),
|
||||
});
|
||||
check('掩码回写后仍能合成(真 token 还在)', ttsAfterMask.ok === true, ttsAfterMask.ok ? '' : ttsAfterMask.error);
|
||||
check('同一批改动的其它字段生效了', /voice_type=BV001_streaming/.test(mockLog), '');
|
||||
|
||||
/* ---------------- 8. 引擎字段不许被空值清掉 ---------------- */
|
||||
console.log('\n=== 8. 空的引擎字段不能被写进去 ===');
|
||||
// 引擎名一空,设置页一张卡片都不会高亮 —— 用户看到的就是"语音设置被清空了"
|
||||
const beforeGuard = (await api('/api/state')).settings.speech;
|
||||
await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ speech: { ttsEngine: '', sttEngine: '', sttModel: '', ttsModel: '', ttsVoice: 'BV701_streaming' } }),
|
||||
});
|
||||
const afterGuard = (await api('/api/state')).settings.speech;
|
||||
check('空的 ttsEngine 被忽略', afterGuard.ttsEngine === beforeGuard.ttsEngine,
|
||||
`${JSON.stringify(beforeGuard.ttsEngine)} → ${JSON.stringify(afterGuard.ttsEngine)}`);
|
||||
check('空的 sttEngine / sttModel 被忽略',
|
||||
afterGuard.sttEngine === beforeGuard.sttEngine && afterGuard.sttModel === beforeGuard.sttModel,
|
||||
`stt=${afterGuard.sttEngine} model=${afterGuard.sttModel}`);
|
||||
// ttsVoice 留空是合理需求,必须能改
|
||||
check('ttsVoice 这种"留空也合理"的字段照常生效', afterGuard.ttsVoice === 'BV701_streaming',
|
||||
JSON.stringify(afterGuard.ttsVoice));
|
||||
|
||||
/* ---------------- 9. 嵌套对象被发成字符串时不能把配置写坏 ---------------- */
|
||||
console.log('\n=== 9. 子对象被序列化成字符串(安卓 org.json 的坑)===');
|
||||
// 真实事故:安卓端 json.put("speech", mapOf(...)) 不会转成 JSON 对象,
|
||||
// 发出来是 {"speech":"{autoRead=true}"}。内核一旦让它覆盖进去,
|
||||
// 之后每次读配置都会抛 TypeError,/api/state 永远 500 ——
|
||||
// App 把错误当默认值,"点一下按钮模型/昵称/会话全没了"。
|
||||
const beforeStr = (await api('/api/state')).settings;
|
||||
const strAttack = await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ speech: '{autoRead=true}' }),
|
||||
});
|
||||
check('内核没有因此报错', !strAttack.error, strAttack.error || 'ok');
|
||||
|
||||
const afterStr = await api('/api/state');
|
||||
check('/api/state 依然能正常返回(没被写坏)', !!afterStr.settings && !afterStr.error,
|
||||
afterStr.error || `model=${afterStr.settings?.model}`);
|
||||
check('其它设置一个字没掉',
|
||||
afterStr.settings?.model === beforeStr.model && afterStr.settings?.nickname === beforeStr.nickname,
|
||||
`model=${afterStr.settings?.model} nickname=${afterStr.settings?.nickname}`);
|
||||
check('speech 仍是对象而不是字符串',
|
||||
afterStr.settings?.speech && typeof afterStr.settings.speech === 'object',
|
||||
typeof afterStr.settings?.speech);
|
||||
check('会话列表没被牵连', Array.isArray(afterStr.conversations),
|
||||
`${afterStr.conversations?.length ?? '?'} 个会话`);
|
||||
|
||||
// 顺带验一下自愈:手工把配置文件里的 speech 写成字符串,读出来要回落到默认值
|
||||
const heal = await api('/api/settings', {
|
||||
method: 'PUT', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tools: 'not-an-object', security: 42 }),
|
||||
});
|
||||
check('tools/security 被发成非对象时同样忽略', !heal.error, heal.error || 'ok');
|
||||
const healed = await api('/api/state');
|
||||
check('非对象值不会让接口挂掉', !!healed.settings && !healed.error, healed.error || 'ok');
|
||||
|
||||
/* ---------------- 汇总 ---------------- */
|
||||
const pass = results.filter((r) => r.ok).length;
|
||||
console.log(`\n=== 结果:${pass} 通过 / ${results.length - pass} 失败 ===`);
|
||||
if (pass !== results.length) {
|
||||
console.log('\n内核日志尾部:\n' + kernLog.slice(-800));
|
||||
process.exit(1);
|
||||
}
|
||||
process.exit(0);
|
||||
57
scripts/xelement-probe.mjs
Normal file
57
scripts/xelement-probe.mjs
Normal file
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* 确认 xelement 的坐标/版本,并打印 XElementBehaviors 的真实签名。
|
||||
* 用法: node scripts/xelement-probe.mjs [version]
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const VERSION = process.argv[2] || '4.1.0';
|
||||
const WORK = 'C:\\Android\\probe';
|
||||
const BASE = 'https://repo1.maven.org/maven2/org/lynxsdk/lynx';
|
||||
|
||||
async function listDir(url) {
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(60000) });
|
||||
if (!res.ok) return { status: res.status, files: [] };
|
||||
const html = await res.text();
|
||||
const files = [...html.matchAll(/href="([^"]+)"/g)]
|
||||
.map((m) => m[1])
|
||||
.filter((x) => !x.startsWith('..') && !x.startsWith('http') && !x.endsWith('/'));
|
||||
return { status: res.status, files };
|
||||
}
|
||||
|
||||
const root = await listDir(`${BASE}/`);
|
||||
console.log('== org/lynxsdk/lynx 下的 artifact:');
|
||||
console.log(root.files.join(' '));
|
||||
|
||||
for (const artifact of ['xelement', 'xelement-behaviors', 'x-element']) {
|
||||
const info = await listDir(`${BASE}/${artifact}/${VERSION}/`);
|
||||
console.log(`\n== ${artifact}/${VERSION} → HTTP ${info.status}`);
|
||||
const aar = info.files.find((f) => f.endsWith('.aar'));
|
||||
if (!aar) {
|
||||
console.log(' 没有 aar:', info.files.slice(0, 8).join(' '));
|
||||
continue;
|
||||
}
|
||||
const filePath = path.join(WORK, aar);
|
||||
if (!fs.existsSync(filePath)) {
|
||||
console.log(' 下载', aar);
|
||||
const res = await fetch(`${BASE}/${artifact}/${VERSION}/${aar}`, { signal: AbortSignal.timeout(600000) });
|
||||
fs.writeFileSync(filePath, Buffer.from(await res.arrayBuffer()));
|
||||
}
|
||||
const dir = path.join(WORK, `x-${artifact}`);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
spawnSync('tar', ['-xf', filePath, '-C', dir]);
|
||||
|
||||
const classesJar = path.join(dir, 'classes.jar');
|
||||
const res = spawnSync('jar', ['tf', classesJar], { encoding: 'utf8' });
|
||||
const classes = (res.stdout || '').split('\n').filter((c) => /Behaviors?\.class$/.test(c));
|
||||
console.log(' Behaviors 类:', classes.slice(0, 5).join(' ') || '(没找到)');
|
||||
|
||||
for (const cls of classes.slice(0, 2)) {
|
||||
const name = cls.replace(/\.class$/, '').replace(/\//g, '.');
|
||||
console.log(`\n===== ${name} =====`);
|
||||
const jp = spawnSync('javap', ['-classpath', classesJar, name], { encoding: 'utf8' });
|
||||
console.log((jp.stdout || jp.stderr || '').split('\n').filter((l) => /public/.test(l)).slice(0, 20).join('\n'));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user