feat(portable): 便携版更新检测 — config-server 加 /api/update-status + check/publish 脚本 + CI 剥 BOM

config-server 新增 /api/update-status 和 /api/update-check,读取 check-update.mjs
写入的 update-available.json,便携版可提示有无新版本。publish-latest.mjs 用于
发布端生成 manifest。release.yml 顺手修打包时 .bat 的 UTF-8 BOM(BOM 会让 cmd.exe
把首条命令认错报 not internal/external command)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
hfshfg
2026-05-30 13:12:16 +08:00
parent c6a11b6aac
commit d9dd98d650
4 changed files with 352 additions and 0 deletions

View File

@@ -129,6 +129,10 @@ jobs:
# Windows batch files MUST be CRLF — cmd.exe mis-parses LF-only files
find "$stage_dir" -type f \( -name '*.bat' -o -name '*.cmd' -o -name '*.ps1' \) -print0 \
| xargs -0 -I {} sh -c 'sed -i "s/\r$//; s/$/\r/" "{}"'
# Strip UTF-8 BOM from .bat files — cmd.exe interprets BOM as
# part of the first command and reports "not internal/external command"
find "$stage_dir" -type f \( -name '*.bat' -o -name '*.cmd' \) -print0 \
| xargs -0 -I {} sh -c 'sed -i "1s/^\xef\xbb\xbf//" "{}"'
# Ensure shell scripts stay LF (mac/linux double-click won't run otherwise)
find "$stage_dir" -type f \( -name '*.sh' -o -name '*.command' -o -name '*.mjs' -o -name '*.js' \) -print0 \
| xargs -0 -I {} sh -c 'sed -i "s/\r$//" "{}"'

View File

@@ -419,6 +419,50 @@ const server = http.createServer((req, res) => {
return;
}
// API: Update status — read update-available.json written by check-update.mjs
// Returns { available: false } if no info or stale; otherwise the manifest payload.
if (req.url === '/api/update-status' && req.method === 'GET') {
try {
const stateDir = process.env.OPENCLAW_STATE_DIR
|| path.join(__dirname, '../data/.openclaw');
const updateFile = path.join(stateDir, 'update-available.json');
if (!fs.existsSync(updateFile)) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ available: false, reason: 'no-check-yet' }));
return;
}
const payload = JSON.parse(fs.readFileSync(updateFile, 'utf8'));
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(payload));
} catch (err) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ available: false, reason: 'read-failed', error: err.message }));
}
return;
}
// API: Trigger update check on demand (so users can press a "Check now" button)
if (req.url === '/api/update-check' && req.method === 'POST') {
(async () => {
try {
const mod = await import('../lib/check-update.mjs');
const portableRoot = path.join(__dirname, '..');
const versionFilePath = fs.existsSync(path.join(portableRoot, 'OPENCLAW_VERSION'))
? path.join(portableRoot, 'OPENCLAW_VERSION')
: path.join(portableRoot, '..', 'OPENCLAW_VERSION');
const stateDir = process.env.OPENCLAW_STATE_DIR
|| path.join(portableRoot, 'data/.openclaw');
const result = await mod.checkUpdate({ versionFilePath, stateDir });
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
})();
return;
}
// API: Re-run bootstrap to inject the uclaw-cloud provider
if (req.url === '/api/xiapan/bind' && req.method === 'POST') {
(async () => {

View File

@@ -0,0 +1,192 @@
// 自动更新检查(轻量版)
//
// 流程:
// 1. 读取 OPENCLAW_VERSION 文件得到当前版本号
// 2. 5s timeout 拉 OSS 上的 latest.json
// 3. 比对版本号,有新版就写 update-available.json 到 STATE_DIR
// 4. Welcome.html / Config.html 启动时读这个文件,有就显示提示条
//
// 设计原则:
// - 静默失败网络坏、OSS 挂、json 格式错、本地版本号缺失,都不能影响 OpenClaw 启动
// - 只读不下载:检查到新版只写 update-available.json下载交给用户点链接到浏览器去做
// - 异步:调用方应该 detach 跑Windows-Start.bat 用 start /B不阻塞主流程
//
// latest.json 格式(你在 OSS 上手动维护或用 publish-latest.mjs 生成):
// {
// "version": "2026.4.30",
// "releaseDate": "2026-05-03",
// "downloadUrl": "https://u-claw-oss.56chat.cn/u-claw-open/u-claw-portable-v2026.4.30.zip",
// "releasePageUrl": "https://github.com/dongsheng123132/u-claw/releases/tag/v2026.4.30",
// "notes": "修复 xxx新增 yyy"
// }
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
const DEFAULT_MANIFEST_URL = process.env.UCLAW_UPDATE_MANIFEST_URL
|| 'https://u-claw-oss.56chat.cn/u-claw-open/latest.json';
const DEFAULT_TIMEOUT_MS = 5000;
function log(level, msg) {
const stream = level === 'error' ? process.stderr : process.stdout;
stream.write(`[check-update] ${msg}\n`);
}
function readVersionFile(versionFilePath) {
try {
if (!existsSync(versionFilePath)) return null;
const raw = readFileSync(versionFilePath, 'utf8').trim();
return raw || null;
} catch (err) {
log('error', `cannot read ${versionFilePath}: ${err.message}`);
return null;
}
}
// 简单语义比较:把 "2026.4.30" 拆成 [2026, 4, 30] 后逐位比
// 不是 semver 但够用。返回 -1/0/1remote 相对 local
function compareVersions(local, remote) {
if (!local || !remote) return 0;
const a = String(local).split('.').map((s) => parseInt(s, 10) || 0);
const b = String(remote).split('.').map((s) => parseInt(s, 10) || 0);
const len = Math.max(a.length, b.length);
for (let i = 0; i < len; i++) {
const ai = a[i] || 0;
const bi = b[i] || 0;
if (bi > ai) return 1;
if (bi < ai) return -1;
}
return 0;
}
async function fetchLatest(url, timeoutMs) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, {
signal: controller.signal,
// 加随机参数避开 OSS / CDN 缓存
cache: 'no-store',
headers: { 'cache-control': 'no-cache' },
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return await res.json();
} finally {
clearTimeout(timer);
}
}
function writeUpdateInfo(stateDir, payload) {
const filePath = resolve(stateDir, 'update-available.json');
try {
if (!existsSync(stateDir)) mkdirSync(stateDir, { recursive: true });
writeFileSync(filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
return filePath;
} catch (err) {
log('error', `cannot write update-available.json: ${err.message}`);
return null;
}
}
function clearUpdateInfo(stateDir) {
const filePath = resolve(stateDir, 'update-available.json');
try {
if (existsSync(filePath)) {
writeFileSync(filePath, JSON.stringify({ available: false, checkedAt: new Date().toISOString() }, null, 2) + '\n', 'utf8');
}
} catch {
// 静默
}
}
export async function checkUpdate({
versionFilePath,
stateDir,
manifestUrl = DEFAULT_MANIFEST_URL,
timeoutMs = DEFAULT_TIMEOUT_MS,
} = {}) {
if (!versionFilePath || !stateDir) {
return { ok: false, reason: 'missing-paths' };
}
const localVersion = readVersionFile(versionFilePath);
if (!localVersion) {
log('error', 'local OPENCLAW_VERSION not found, skip');
return { ok: false, reason: 'no-local-version' };
}
let remote;
try {
remote = await fetchLatest(manifestUrl, timeoutMs);
} catch (err) {
// 静默失败 — 网络坏不能影响用户用 U-Claw
log('error', `fetch ${manifestUrl} failed: ${err.message}`);
return { ok: false, reason: 'fetch-failed', error: err.message };
}
if (!remote || typeof remote !== 'object' || !remote.version) {
log('error', 'remote manifest invalid (missing version)');
return { ok: false, reason: 'invalid-manifest' };
}
const cmp = compareVersions(localVersion, remote.version);
if (cmp <= 0) {
// 已是最新或更新(开发版可能比线上还新)
clearUpdateInfo(stateDir);
log('info', `up to date (local=${localVersion}, remote=${remote.version})`);
return { ok: true, available: false, localVersion, remoteVersion: remote.version };
}
// 有新版
const payload = {
available: true,
checkedAt: new Date().toISOString(),
localVersion,
remoteVersion: remote.version,
releaseDate: remote.releaseDate || null,
downloadUrl: remote.downloadUrl || null,
releasePageUrl: remote.releasePageUrl || null,
notes: remote.notes || null,
};
const filePath = writeUpdateInfo(stateDir, payload);
log('info', `new version available: ${remote.version} (local=${localVersion})`);
return { ok: true, available: true, ...payload, filePath };
}
// CLI:
// node check-update.mjs <version-file> <state-dir> [manifest-url]
// env UCLAW_VERSION_FILE / UCLAW_STATE_DIR / UCLAW_UPDATE_MANIFEST_URL
import { pathToFileURL } from 'node:url';
const isMain = (() => {
try {
if (!process.argv[1]) return false;
return import.meta.url === pathToFileURL(process.argv[1]).href;
} catch {
return false;
}
})();
if (isMain) {
const versionFilePath = process.argv[2] || process.env.UCLAW_VERSION_FILE;
const stateDir = process.argv[3] || process.env.UCLAW_STATE_DIR;
const manifestUrl = process.argv[4] || process.env.UCLAW_UPDATE_MANIFEST_URL || DEFAULT_MANIFEST_URL;
if (!versionFilePath || !stateDir) {
process.stderr.write('Usage: node check-update.mjs <version-file> <state-dir> [manifest-url]\n');
process.exit(2);
}
checkUpdate({ versionFilePath, stateDir, manifestUrl })
.then((res) => {
process.stdout.write(`${JSON.stringify(res)}\n`);
// 退出码0=正常无论是否有新版1=失败但已记录
process.exit(res.ok ? 0 : 1);
})
.catch((err) => {
process.stderr.write(`check-update fatal: ${err.message}\n`);
process.exit(1);
});
}

View File

@@ -0,0 +1,112 @@
// 发版辅助:生成 latest.json 用于上传到阿里云 OSS
//
// 用法(在仓库根目录跑):
// node portable/lib/publish-latest.mjs
// node portable/lib/publish-latest.mjs --notes "修复了 xxx"
//
// 输出:
// - dist/latest.json — 你手动(或 ossutil上传到 OSS 的同一个路径
//
// 上传命令示例(自己装 ossutil 后用):
// ossutil cp dist/latest.json oss://u-claw-oss/u-claw-open/latest.json
//
// 这个脚本不直接调 OSS避免硬编码 access key。把生成 + 上传分开,发版人自己负责上传。
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = resolve(__dirname, '../..');
// 默认 OSS 路径前缀(你可以改成自己的 bucket / domain
const DEFAULT_OSS_BASE = 'https://u-claw-oss.56chat.cn/u-claw-open';
const GH_RELEASES_BASE = 'https://github.com/dongsheng123132/u-claw/releases';
function parseArgs(argv) {
const args = { notes: '', ossBase: DEFAULT_OSS_BASE };
for (let i = 2; i < argv.length; i++) {
const a = argv[i];
if (a === '--notes' || a === '-n') args.notes = argv[++i] || '';
else if (a === '--oss-base') args.ossBase = argv[++i] || DEFAULT_OSS_BASE;
else if (a === '--help' || a === '-h') {
process.stdout.write([
'Usage: node portable/lib/publish-latest.mjs [options]',
' --notes "<text>" Release notes (single line)',
' --oss-base <url> OSS public URL prefix (default: ' + DEFAULT_OSS_BASE + ')',
' --help Show this help',
'',
'Output: dist/latest.json — upload it to <oss-base>/latest.json',
].join('\n') + '\n');
process.exit(0);
}
}
return args;
}
function readVersion() {
const versionFile = resolve(REPO_ROOT, 'OPENCLAW_VERSION');
if (!existsSync(versionFile)) {
throw new Error(`OPENCLAW_VERSION file not found at ${versionFile}`);
}
const v = readFileSync(versionFile, 'utf8').trim();
if (!v) throw new Error('OPENCLAW_VERSION is empty');
return v;
}
function todayIso() {
const d = new Date();
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, '0');
const dd = String(d.getDate()).padStart(2, '0');
return `${yyyy}-${mm}-${dd}`;
}
function main() {
const args = parseArgs(process.argv);
const version = readVersion();
const tag = `v${version}`;
// Naming convention matches release.yml:
// dist/u-claw-portable-${tag_name}.zip
const zipName = `u-claw-portable-${tag}.zip`;
const downloadUrl = `${args.ossBase}/${zipName}`;
const releasePageUrl = `${GH_RELEASES_BASE}/tag/${tag}`;
const manifest = {
version,
releaseDate: todayIso(),
downloadUrl,
releasePageUrl,
notes: args.notes || '',
// Mirror fallback if user wants — check-update.mjs only looks at the top-level fields
mirrors: {
oss: downloadUrl,
github: `${releasePageUrl}/${zipName}`,
},
};
const distDir = resolve(REPO_ROOT, 'dist');
if (!existsSync(distDir)) mkdirSync(distDir, { recursive: true });
const outFile = resolve(distDir, 'latest.json');
writeFileSync(outFile, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
process.stdout.write(`\nGenerated: ${outFile}\n`);
process.stdout.write(`Version: ${version}\n`);
process.stdout.write(`Download: ${downloadUrl}\n`);
process.stdout.write('\nNext steps (manual):\n');
process.stdout.write(` 1. Upload portable zip to OSS: ${args.ossBase}/${zipName}\n`);
process.stdout.write(` 2. Upload latest.json to OSS: ${args.ossBase}/latest.json\n`);
process.stdout.write('\nExample (with ossutil):\n');
process.stdout.write(` ossutil cp dist/${zipName} oss://<your-bucket>/u-claw-open/${zipName}\n`);
process.stdout.write(` ossutil cp dist/latest.json oss://<your-bucket>/u-claw-open/latest.json\n`);
process.stdout.write('\nVerify after upload:\n');
process.stdout.write(` curl -s ${args.ossBase}/latest.json | head -20\n\n`);
}
try {
main();
} catch (err) {
process.stderr.write(`publish-latest error: ${err.message}\n`);
process.exit(1);
}