Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support HarmonyOS development deployment

Daniel12becdafd64c
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 264cda6d0b..24a1634959 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -85,6 +85,10 @@ Desktop packaging runs `scripts/prepare-ocr.py` to prepare the pinned models and
* `gomobile bind -tags "fts5 sqlcipher" -ldflags "-s -w" -v -o kernel.aar -target android/arm64 -androidapi 26 ./mobile/`
* https://github.com/siyuan-note/siyuan-android
+On Windows, run `node scripts/android-dev-run.mjs` from the SiYuan repository root to build the mobile frontend, package resources, build `kernel.aar` and the debug APK, then install and launch the separate debug app through ADB. The default flavor is `official`. Prepare Node.js, pnpm, Go, gomobile, a JDK, the Android SDK and NDK, and ZIP-capable bsdtar (the bundled Windows `tar`). Configure `sdk.dir` in the Android project's `local.properties`, or set `ANDROID_HOME`; the script selects the highest NDK version under the SDK directory. Enable debugging on the device and authorize the connection.
+
+The Android project defaults to a sibling of the SiYuan repository; override it with `--android-dir=<path>` or `SIYUAN_ANDROID_DIR`. Use `--device=<serial>` to select an ADB connection. `--skip-ui` reuses existing frontend output (mobile, desktop, and export are required), `--skip-kernel` reuses and copies existing `kernel/kernel.aar`, and `--skip-gradle` only skips APK compilation while still performing resource packaging and kernel processing. Pass all three flags to reinstall an existing APK without rebuilding; the SDK and NDK must still be available. See `node scripts/android-dev-run.mjs --help` for more options.
+
### Harmony
Only support compilation under Linux, need to install Harmony SDK, and need to modify Go source code.
@@ -93,6 +97,10 @@ Only support compilation under Linux, need to install Harmony SDK, and need to m
* `./build.sh` (`./build-win.sh` for Windows Emulator)
* https://github.com/siyuan-note/siyuan-harmony
+For ARM64 devices, run `node scripts/harmony-dev-run.mjs` from the SiYuan repository root to build the mobile frontend, package resources, build the kernel and signed debug HAP, then install and launch the separate debug app through HDC. First configure the Harmony project's `debug` signing profile for your device in DevEco Studio and prepare the native OCR runtime and models (see the Harmony repository README). On Windows, WSL runs `kernel/harmony/build.sh` against the current checkout; the Harmony SDK and patched Go toolchain described below must be available inside WSL. The script requires ZIP-capable bsdtar (the bundled Windows `tar`) and never automatically uninstalls the app.
+
+Use `--deveco=<path>`, `--harmony-dir=<path>`, and `--device=<connect-key>` to select tools, project, and device. `--skip-ui` reuses existing frontend output (mobile, desktop, and export are required), `--skip-kernel` copies existing `kernel/harmony/libkernel.so` and `libkernel.h`, and `--skip-hvigor` only reinstalls and launches the existing debug HAP, skipping all builds and resource copies. See `node scripts/harmony-dev-run.mjs --help` for more options. Run script tests with `node --test app/scripts/harmony-dev-run.test.js`.
+
Modify Go source code:
1. go/src/runtime/vim tls_arm64.s
diff --git a/.github/CONTRIBUTING.zh-CN.md b/.github/CONTRIBUTING.zh-CN.md
index 7cf24d5498..faa0bd1d92 100644
--- a/.github/CONTRIBUTING.zh-CN.md
+++ b/.github/CONTRIBUTING.zh-CN.md
@@ -85,6 +85,10 @@ NPM 镜像:
* `gomobile bind -tags "fts5 sqlcipher" -ldflags "-s -w" -v -o kernel.aar -target android/arm64 -androidapi 26 ./mobile/`
* https://github.com/siyuan-note/siyuan-android
+Windows 下可在思源仓库根目录执行 `node scripts/android-dev-run.mjs`,构建移动端前端、打包资源、构建 `kernel.aar` 和调试 APK,然后通过 ADB 安装并启动独立调试包,默认使用 `official` 渠道。需准备 Node.js、pnpm、Go、gomobile、JDK、Android SDK 和 NDK,以及支持 ZIP 的 bsdtar(Windows 自带的 `tar`)。在 Android 工程的 `local.properties` 中配置 `sdk.dir`,或设置 `ANDROID_HOME`;脚本会选择 SDK 目录下版本最高的 NDK。设备需开启并授权调试连接。
+
+Android 工程默认位于思源仓库同级,可用 `--android-dir=<路径>` 或 `SIYUAN_ANDROID_DIR` 指定;使用 `--device=<序列号>` 选择 ADB 连接。`--skip-ui` 复用现有前端产物(需包含 mobile、desktop、export),`--skip-kernel` 复用并复制现有 `kernel/kernel.aar`,`--skip-gradle` 仅跳过 APK 构建,仍会执行前面的资源打包和内核处理。仅重新安装已有 APK 时同时传入这三个参数;SDK 和 NDK 仍需可用。更多参数见 `node scripts/android-dev-run.mjs --help`。
+
### Harmony
仅支持在 Linux 下编译,需要安装鸿蒙 SDK,并且需要修改 Go 源码。
@@ -93,6 +97,10 @@ NPM 镜像:
* `./build.sh` (Windows 模拟器使用 `./build-win.sh`)
* https://github.com/siyuan-note/siyuan-harmony
+ARM64 真机可在思源仓库根目录执行 `node scripts/harmony-dev-run.mjs`,构建移动端前端、打包资源、构建内核和已签名的调试 HAP,然后通过 HDC 安装并启动独立调试包。先在 DevEco Studio 为设备配置鸿蒙工程的 `debug` 签名,并准备原生 OCR 运行库和模型(参考鸿蒙仓库 README)。Windows 通过 WSL 在当前检出目录中执行 `kernel/harmony/build.sh`,WSL 内仍需具备下述鸿蒙 SDK 和修改后的 Go 工具链。脚本使用支持 ZIP 的 bsdtar(Windows 自带的 `tar`),不会自动卸载应用。
+
+通过 `--deveco=<路径>`、`--harmony-dir=<路径>`、`--device=<连接标识>` 指定工具、工程和设备。`--skip-ui` 复用现有前端产物(需包含 mobile、desktop、export),`--skip-kernel` 复制现有 `kernel/harmony/libkernel.so` 和 `libkernel.h`,`--skip-hvigor` 则仅重新安装并启动已有的调试 HAP,跳过所有构建及资源复制。更多参数见 `node scripts/harmony-dev-run.mjs --help`。运行脚本测试:`node --test app/scripts/harmony-dev-run.test.js`。
+
修改 Go 源码:
1. go/src/runtime/tls_arm64.s
diff --git a/app/scripts/harmony-dev-run.test.js b/app/scripts/harmony-dev-run.test.js
new file mode 100644
index 0000000000..d269b66ccb
--- /dev/null
+++ b/app/scripts/harmony-dev-run.test.js
@@ -0,0 +1,154 @@
+const {test} = require("node:test");
+const assert = require("node:assert/strict");
+const {mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync} = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+function fixture(t) {
+ const root = mkdtempSync(path.join(os.tmpdir(), "siyuan-harmony-test-"));
+ t.after(() => {
+ assert.equal(path.dirname(path.resolve(root)), path.resolve(os.tmpdir()));
+ rmSync(root, {recursive: true, force: true});
+ });
+ const write = (name, content = "fixture") => {
+ const file = path.join(root, name);
+ mkdirSync(path.dirname(file), {recursive: true});
+ writeFileSync(file, content);
+ return file;
+ };
+ const native = path.join(root, "native project");
+ write("native project/AppScope/app.json5");
+ const hap = "native project/entry/build/debug/outputs/default/entry-default-signed.hap";
+ const args = [`--harmony-dir=${native}`, "--hdc=test-hdc"];
+ return {root, write, native, hap, args};
+}
+
+test("Harmony arguments reject unknown/empty values and preserve paths containing spaces", async () => {
+ const {parseArgs} = await import("../../scripts/harmony-dev-run.mjs");
+ assert.throws(() => parseArgs(["--skip-gradle"], {}), /Unknown/);
+ assert.throws(() => parseArgs(["--device="], {}), /empty/);
+ const options = parseArgs(["--device=127.0.0.1:1234", "--skip-hvigor"], {SIYUAN_HARMONY_DIR: "native project"});
+ assert.equal(options.harmonyDir, path.resolve("native project"));
+ assert.equal(options.device, "127.0.0.1:1234");
+ assert.equal(options.skipHvigor, true);
+});
+
+test("Harmony requires an explicit choice for multiple devices and rejects missing targets", async () => {
+ const {selectDevice} = await import("../../scripts/harmony-dev-run.mjs");
+ assert.equal(selectDevice("device-a\r\n"), "device-a");
+ assert.equal(selectDevice("a\nb\n", "b"), "b");
+ assert.throws(() => selectDevice("[Empty]\n"), /found none/);
+ assert.throws(() => selectDevice("a\nb\n"), /--device/);
+ assert.throws(() => selectDevice("a\n", "b"), /not found/);
+});
+
+test("Harmony kernel validation rejects emulator and invalid libraries", async t => {
+ const {checkKernel} = await import("../../scripts/harmony-dev-run.mjs");
+ const {write} = fixture(t);
+ const header = Buffer.alloc(64);
+ Buffer.from("7f454c460201", "hex").copy(header);
+ header.writeUInt16LE(183, 18);
+ assert.doesNotThrow(() => checkKernel(write("arm.so", header)));
+ header.writeUInt16LE(62, 18);
+ assert.throws(() => checkKernel(write("x86.so", header)), /ARM64/);
+ assert.throws(() => checkKernel(write("bad.so")), /ARM64/);
+});
+
+test("Harmony reinstall skips all build tools and targets the debug bundle", async t => {
+ const {main} = await import("../../scripts/harmony-dev-run.mjs");
+ const {root, write, hap, args} = fixture(t);
+ write(hap);
+ const calls = [];
+ main([...args, "--skip-hvigor"], (command, argv) => {
+ calls.push([command, argv]);
+ return {status: 0, stdout: calls.length === 1 ? "phone\n" : calls.length === 2 ?
+ "install bundle successfully.\n" : "start ability successfully.\n"};
+ }, root);
+ assert.equal(calls.length, 3);
+ assert.equal(calls[1][0], "test-hdc");
+ assert.deepEqual(calls[1][1], ["-t", "phone", "install", "-r", path.join(root, hap)]);
+ assert.ok(calls[2][1].includes("org.b3log.siyuan.ho.debug"));
+ assert.ok(calls[2][1].includes("EntryAbility"));
+});
+
+test("Harmony stops on missing signed HAP, tool errors and zero-exit installation failures", async t => {
+ const {main} = await import("../../scripts/harmony-dev-run.mjs");
+ const {root, write, hap, args} = fixture(t);
+ const runArgs = [...args, "--skip-hvigor"];
+ assert.throws(() => main(runArgs, () => ({status: 0, stdout: "phone\n"}), root), /Missing or empty/);
+ write(hap);
+ assert.throws(() => main(runArgs, () => ({status: null, error: new Error("ENOENT")}), root), /ENOENT/);
+ let calls = 0;
+ assert.throws(() => main(runArgs, () => ({status: 0, stdout: ++calls === 1 ? "phone\n" :
+ "[Fail] signature mismatch\n"}), root), /did not confirm installation/);
+ assert.equal(calls, 2);
+ calls = 0;
+ assert.throws(() => main(runArgs, () => ({status: 0, stdout: ++calls === 1 ? "phone\n" : calls === 2 ?
+ "install bundle successfully.\n" : "error: failed to start ability\n"}), root), /ability startup/);
+});
+
+for (const reuse of [true, false]) {
+test(`Harmony build packages resources and builds signed debug HAP (reuse=${reuse})`, async t => {
+ const {main} = await import("../../scripts/harmony-dev-run.mjs");
+ const {root, native, write, hap, args} = fixture(t);
+ const deveco = path.join(root, "DevEco Studio");
+ for (const name of [process.platform === "win32" ? "node.exe" : "bin/node"]) write(`DevEco Studio/tools/node/${name}`);
+ write("DevEco Studio/tools/hvigor/bin/hvigorw.js");
+ write("DevEco Studio/tools/ohpm/bin/pm-cli.js");
+ write("app/stage/build/mobile/index.html");
+ write("app/stage/build/desktop/index.html");
+ write("app/stage/build/export/protyle-method.js");
+ write("app/stage/build/export/base.css");
+ write("app/stage/ocr/models/tiny/det/inference.onnx");
+ write("app/stage/ocr/models/tiny/rec/inference.onnx");
+ write("app/stage/ocr/runtime/desktop/lib.so");
+ write("native project/entry/src/main/resources/rawfile/app.zip");
+ write("native project/entry/libs/arm64-v8a/libonnxruntime.so");
+ write("native project/entry/src/main/cpp/include/libkernel.h");
+ const header = Buffer.alloc(64);
+ Buffer.from("7f454c460201", "hex").copy(header);
+ header.writeUInt16LE(183, 18);
+ write("kernel/harmony/libkernel.so", header);
+ write("kernel/harmony/libkernel.h", "kernel header");
+ write(hap, "stale HAP");
+ let list;
+ const calls = [];
+ main([...args, `--deveco=${deveco}`, ...(reuse ? ["--skip-ui", "--skip-kernel"] : [])], (command, argv, settings) => {
+ calls.push([command, argv]);
+ if (argv[0] === "list") return {status: 0, stdout: "phone\n"};
+ if (argv.includes("wslpath")) {
+ assert.deepEqual(settings.stdio, ["inherit", "pipe", "inherit"]);
+ return {status: 0, stdout: "/mnt/c/native project/kernel/harmony\n"};
+ }
+ if (command === "wsl.exe" && argv.includes("--cd")) {
+ assert.equal(argv[argv.indexOf("--cd") + 1], "/mnt/c/native project/kernel/harmony");
+ assert.ok(argv.includes("pipefail"));
+ }
+ if (command === "tar") {
+ list = argv[argv.indexOf("-T") + 1];
+ const files = readFileSync(list, "utf8");
+ assert.match(files, /stage\/build\/desktop\/index.html/);
+ assert.match(files, /stage\/build\/export\/base.css/);
+ assert.doesNotMatch(files, /ocr\/runtime/);
+ writeFileSync(argv[argv.indexOf("-cf") + 1], "zip");
+ }
+ if (argv.includes("assembleHap")) {
+ assert.equal(existsSync(path.join(root, hap)), false);
+ assert.equal(settings.cwd, native);
+ assert.ok(argv.includes("product=debug"));
+ assert.ok(argv.includes("buildMode=debug"));
+ assert.ok(argv.includes("module=entry@default"));
+ write(hap);
+ }
+ return {status: 0, stdout: argv.includes("install") && command === "test-hdc" ?
+ "install bundle successfully.\n" : argv.includes("start") ? "start ability successfully.\n" : ""};
+ }, root);
+ assert.equal(existsSync(list), false);
+ assert.deepEqual(readFileSync(path.join(native, "entry/libs/arm64-v8a/libkernel.so")), header);
+ assert.equal(readFileSync(path.join(native, "entry/src/main/cpp/include/libkernel.h"), "utf8"), "kernel header");
+ assert.ok(calls.some(([, argv]) => argv.includes("clean")));
+ assert.ok(calls.some(([, argv]) => argv[0].endsWith("pm-cli.js")));
+ assert.equal(calls.some(([command]) => command === "pnpm"), !reuse);
+ assert.equal(calls.some(([command]) => command === "wsl.exe" || command === "bash"), !reuse);
+});
+}
diff --git a/scripts/harmony-dev-run.mjs b/scripts/harmony-dev-run.mjs
new file mode 100644
index 0000000000..21f03bd82a
--- /dev/null
+++ b/scripts/harmony-dev-run.mjs
@@ -0,0 +1,190 @@
+#!/usr/bin/env node
+// 构建 ARM64 鸿蒙调试版并安装启动;签名和 SDK 配置沿用原生工程。
+import {spawnSync} from "node:child_process";
+import {copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync} from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import {fileURLToPath, pathToFileURL} from "node:url";
+import {androidStageFiles} from "./android-assets.mjs";
+
+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+
+export function parseArgs(args, env = process.env) {
+ const options = {
+ harmonyDir: env.SIYUAN_HARMONY_DIR || path.resolve(repoRoot, "..", "siyuan-harmony"),
+ deveco: env.DEVECO_STUDIO_HOME || "D:/Program Files/Huawei/DevEco Studio",
+ hdc: env.HDC || "",
+ device: "",
+ wslDistro: "",
+ wslUser: "",
+ skipUi: false,
+ skipKernel: false,
+ skipHvigor: false,
+ };
+ const values = {"harmony-dir": "harmonyDir", deveco: "deveco", hdc: "hdc", device: "device",
+ "wsl-distro": "wslDistro", "wsl-user": "wslUser"};
+ const flags = {"--skip-ui": "skipUi", "--skip-kernel": "skipKernel", "--skip-hvigor": "skipHvigor"};
+ for (const arg of args) {
+ if (arg === "--help" || arg === "-h") {
+ options.help = true;
+ } else if (flags[arg]) {
+ options[flags[arg]] = true;
+ } else {
+ const match = /^--([^=]+)=(.+)$/.exec(arg);
+ if (!match || !values[match[1]]) throw new Error(`Unknown or empty argument: ${arg}`);
+ options[values[match[1]]] = match[2];
+ }
+ }
+ options.harmonyDir = path.resolve(options.harmonyDir);
+ options.deveco = path.resolve(options.deveco);
+ return options;
+}
+
+export function selectDevice(output, requested = "") {
+ const devices = [...new Set(output.split(/\r?\n/).map(line => line.trim())
+ .filter(line => line && line !== "[Empty]"))];
+ if (requested && devices.includes(requested)) return requested;
+ if (!requested && devices.length === 1) return devices[0];
+ throw new Error(requested ? `Device ${requested} not found: ${devices.join(", ") || "none"}` :
+ `Expected one HDC device, found ${devices.join(", ") || "none"}. Connect a device or use --device=<connect-key>`);
+}
+
+function requireFile(file) {
+ if (!existsSync(file) || !statSync(file).isFile() || statSync(file).size === 0) {
+ throw new Error(`Missing or empty file: ${file}`);
+ }
+ return file;
+}
+
+function removeTemp(directory) {
+ if (path.dirname(path.resolve(directory)) !== path.resolve(os.tmpdir())) {
+ throw new Error(`Unexpected temporary path: ${directory}`);
+ }
+ rmSync(directory, {recursive: true, force: true});
+}
+
+export function checkKernel(file) {
+ const header = readFileSync(requireFile(file));
+ if (header.length < 20 || header.toString("hex", 0, 6) !== "7f454c460201" || header.readUInt16LE(18) !== 183) {
+ throw new Error(`Expected an ARM64 ELF kernel: ${file}`);
+ }
+}
+
+export function main(args = process.argv.slice(2), execute = spawnSync, root = repoRoot) {
+ const options = parseArgs(args);
+ if (options.help) {
+ console.log(`Usage: node scripts/harmony-dev-run.mjs [options]
+ --harmony-dir=<path> Native project (default: ../siyuan-harmony; SIYUAN_HARMONY_DIR)
+ --deveco=<path> DevEco Studio directory (DEVECO_STUDIO_HOME)
+ --hdc=<path> HDC executable (HDC, bundled SDK, or PATH)
+ --device=<key> HDC connect key; required when multiple devices are connected
+ --wsl-distro=<name> WSL distribution for kernel compilation on Windows
+ --wsl-user=<name> WSL user (default: distribution default user)
+ --skip-ui Reuse existing stage/build/{mobile,desktop,export}
+ --skip-kernel Copy existing kernel/harmony/libkernel.so and libkernel.h
+ --skip-hvigor Only reinstall and launch the existing signed debug HAP
+ -h, --help Show help
+
+Builds product=debug, buildMode=debug for ARM64 devices. Configure the debug
+signing profile in DevEco Studio for your device first. Uses build.sh and its
+Linux SDK / patched Go toolchain (see .github/CONTRIBUTING.md); Windows uses WSL
+against this checkout. Existing OCR native libraries and models are required.
+No uninstall is attempted if installation fails.`);
+ return;
+ }
+ const app = path.join(root, "app");
+ const native = options.harmonyDir;
+ requireFile(path.join(native, "AppScope/app.json5"));
+ const run = (command, argv, settings = {}) => {
+ console.log(`> ${command} ${argv.join(" ")}`);
+ const result = execute(command, argv, {cwd: root, env: process.env, encoding: "utf8",
+ stdio: ["inherit", "pipe", "pipe"], windowsHide: true, ...settings});
+ if (result.stdout) process.stdout.write(result.stdout);
+ if (result.stderr) process.stderr.write(result.stderr);
+ if (result.error || result.status !== 0) {
+ throw new Error(`${command} failed: ${result.error?.message || result.signal || result.status}`);
+ }
+ return result.stdout || "";
+ };
+ const sdkHdc = path.join(options.deveco, "sdk/default/openharmony/toolchains", process.platform === "win32" ? "hdc.exe" : "hdc");
+ const hdc = options.hdc || (existsSync(sdkHdc) ? sdkHdc : "hdc");
+ // 先确认设备,避免构建结束后才发现目标未连接或存在歧义。
+ const serial = selectDevice(run(hdc, ["list", "targets"]), options.device);
+ const hap = path.join(native, "entry/build/debug/outputs/default/entry-default-signed.hap");
+ if (!options.skipHvigor) {
+ const node = requireFile(path.join(options.deveco, "tools/node", process.platform === "win32" ? "node.exe" : "bin/node"));
+ const hvigor = requireFile(path.join(options.deveco, "tools/hvigor/bin/hvigorw.js"));
+ const ohpm = requireFile(path.join(options.deveco, "tools/ohpm/bin/pm-cli.js"));
+ const env = {...process.env, DEVECO_SDK_HOME: path.join(options.deveco, "sdk"),
+ JAVA_HOME: path.join(options.deveco, "jbr")};
+ env.PATH = path.dirname(node) + path.delimiter + (env.PATH || "");
+ if (!options.skipUi) {
+ // 使用现有开发资源目录,不运行会清空整个 stage 的总构建命令。
+ run("pnpm", ["run", "build:mobile"], {cwd: app, shell: process.platform === "win32", stdio: "inherit"});
+ }
+ const stageFiles = androidStageFiles(path.join(app, "stage"))
+ .filter(name => !name.startsWith("stage/ocr/runtime/"));
+ for (const kind of ["det", "rec"]) {
+ requireFile(path.join(app, `stage/ocr/models/tiny/${kind}/inference.onnx`));
+ }
+ const temp = mkdtempSync(path.join(os.tmpdir(), "siyuan-harmony-assets-"));
+ try {
+ const list = path.join(temp, "files.txt");
+ writeFileSync(list, stageFiles.join("\n") + "\n", "utf8");
+ const zip = path.join(temp, "app.zip");
+ // 与 Android 开发脚本一致,使用支持 ZIP 的 bsdtar,文件列表避免命令行超长。
+ run("tar", ["-a", "-cf", zip, "-C", app, "-T", list, "appearance", "guide", "changelogs",
+ "-C", root, "LICENSE", "THIRD_PARTY_NOTICES.md"], {stdio: "inherit"});
+ copyFileSync(requireFile(zip), path.join(native, "entry/src/main/resources/rawfile/app.zip"));
+ } finally {
+ removeTemp(temp);
+ }
+ const kernel = path.join(root, "kernel/harmony");
+ if (!options.skipKernel) {
+ if (process.platform === "win32") {
+ const wsl = [];
+ if (options.wslDistro) wsl.push("--distribution", options.wslDistro);
+ if (options.wslUser) wsl.push("--user", options.wslUser);
+ // WSL 的 Windows 侧诊断使用不同于 Linux 输出的编码,直接交给终端显示。
+ const linuxPath = run("wsl.exe", [...wsl, "--exec", "wslpath", "-a", "-u", kernel], {
+ stdio: ["inherit", "pipe", "inherit"],
+ }).trim();
+ // 去掉检出脚本的 CRLF,不更改工作树中的文件。
+ run("wsl.exe", [...wsl, "--cd", linuxPath, "--exec", "bash", "-e", "-o", "pipefail", "-c",
+ "sed 's/\\r$//' build.sh | bash -e"], {stdio: "inherit"});
+ } else {
+ run("bash", ["-e", "build.sh"], {cwd: kernel, stdio: "inherit"});
+ }
+ }
+ checkKernel(path.join(kernel, "libkernel.so"));
+ copyFileSync(path.join(kernel, "libkernel.so"), path.join(native, "entry/libs/arm64-v8a/libkernel.so"));
+ copyFileSync(requireFile(path.join(kernel, "libkernel.h")), path.join(native, "entry/src/main/cpp/include/libkernel.h"));
+ requireFile(path.join(native, "entry/libs/arm64-v8a/libonnxruntime.so"));
+ const hvigorArgs = ["--mode", "module", "-p", "product=debug", "-p", "buildMode=debug",
+ "-p", "module=entry@default", "--no-daemon"];
+ run(node, [ohpm, "install", "--all"], {cwd: native, env, stdio: "inherit"});
+ // 清理原生中间库和旧签名包,避免复用上次的内核或安装过期 HAP。
+ run(node, [hvigor, ...hvigorArgs, "clean"], {cwd: native, env, stdio: "inherit"});
+ rmSync(hap, {force: true});
+ run(node, [hvigor, ...hvigorArgs, "assembleHap"], {cwd: native, env, stdio: "inherit"});
+ }
+ requireFile(hap);
+ // HDC 部分版本在设备操作失败时仍返回零状态,必须同时核对成功回执。
+ const installed = run(hdc, ["-t", serial, "install", "-r", hap]);
+ if (!/install bundle successfully/i.test(installed)) {
+ throw new Error("HDC did not confirm installation. Check the signing profile and device authorization above");
+ }
+ const launched = run(hdc, ["-t", serial, "shell", "aa", "start", "-b", "org.b3log.siyuan.ho.debug",
+ "-a", "EntryAbility", "-m", "entry"]);
+ if (!/start ability successfully/i.test(launched)) throw new Error("HDC did not confirm ability startup");
+ console.log("Harmony debug app installed and started");
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
+ try {
+ main();
+ } catch (error) {
+ console.error(`Error: ${error.message}`);
+ process.exitCode = 1;
+ }
+}