Compare commits

...

3 Commits

Author SHA1 Message Date
手瓜一十雪
f04ec3ec36 Probe and reconnect to existing hooks
Add a lightweight pipe liveness probe and use it to detect/reconnect to existing SnowLuma hooks instead of always re-injecting. Introduces PROBE_TIMEOUT_MS (400ms) and QqHookClient.probePipe(pid, timeout) which quickly checks if the control pipe accepts a connection (no hello exchange). HookManager now parallel-probes freshly-enumerated processes (probeAndSeed) and fast-checks before injecting in loadProcess; positive hits mark the state as injected with method="reconnect" and avoid redundant injection. Also deduplicate login notifications in handleLoginState (skip if already logged in with the same UIN) and adjust the loginState emission ordering in QqHookClient.
2026-05-03 16:49:06 +08:00
手瓜一十雪
82c1721466 CI: add matrix builds & cross-platform packaging
Restructure GitHub Actions to build Windows and Linux matrix targets and produce platform-specific artifacts.

- .github/workflows/dev-build.yml: split cleanup/build jobs, add matrix (win-x64, linux-x64), set SNOWLUMA_TARGET for builds, produce full and -lite archives (.zip on Windows, .tar.gz on Linux), unify upload step and ensure errors when artifacts missing.
- .github/workflows/release.yml: convert release build to matrix, produce platform archives, download/collect artifacts, generate multi-platform release notes (bash), and create the GitHub release with both .zip and .tar.gz assets.
- packages/core/vite.config.ts: add fs import and SNOWLUMA_TARGET handling, pick platform-specific runtime files (launcher.bat or launcher.sh), enumerate native files per target, fail CI if expected native binaries are missing, and copy native files into dist/native.
- packages/runtime/launcher.sh: add a portable launcher for Linux that prefers a bundled node binary or falls back to PATH and execs index.mjs.

These changes enable cross-target CI packaging and enforce that native binaries are present before releasing.
2026-05-03 16:20:39 +08:00
DrSmoothl
df73f58598 fix: dll path do not work on Linux/UNIX systems 2026-05-03 16:00:14 +08:00
10 changed files with 273 additions and 94 deletions

View File

@@ -8,8 +8,8 @@ on:
- 'v*'
jobs:
build:
runs-on: windows-latest
cleanup:
runs-on: ubuntu-latest
permissions:
actions: write
contents: read
@@ -38,6 +38,25 @@ jobs:
page++;
}
build:
needs: cleanup
permissions:
contents: read
strategy:
fail-fast: false
matrix:
include:
- name: win-x64
os: windows-latest
target: win32-x64
- name: linux-x64
os: ubuntu-latest
target: linux-x64
- name: linux-arm64
os: ubuntu-24.04-arm
target: linux-arm64
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -58,45 +77,41 @@ jobs:
# Always builds the WebUI flavor — no separate "core-only" artifact.
- name: Build project
env:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
- name: Verify native files
shell: pwsh
run: |
if (!(Test-Path "dist\native\snowluma-win32-x64.node")) { throw "Missing dist\native\snowluma-win32-x64.node" }
if (!(Test-Path "dist\native\snowluma-win32-x64.dll")) { throw "Missing dist\native\snowluma-win32-x64.dll" }
if (!(Test-Path "dist\native\websocket-win32-x64.node")) { throw "Missing dist\native\websocket-win32-x64.node" }
- name: Bundle runtime dependencies
working-directory: dist
run: npm install --omit=dev
# Two artifacts:
# * SnowLuma-dev.zip – full bundle, ships node.exe (zero-install)
# * SnowLuma-dev-no-node.zip – same bundle without node.exe (user provides Node >= 22)
- name: Package artifact (no-node)
shell: pwsh
run: |
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-no-node.zip"
- name: Package artifact (with node.exe)
# Naming convention:
# SnowLuma-dev-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-dev-<arch>-lite.zip|tar.gz – user provides Node >= 22
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
run: |
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-${{ matrix.name }}-lite.zip"
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev.zip"
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-dev-${{ matrix.name }}.zip"
- name: Upload artifact (with node.exe)
- name: Package (linux)
if: startsWith(matrix.os, 'ubuntu')
run: |
chmod +x dist/launcher.sh
tar -czf "SnowLuma-dev-${{ matrix.name }}-lite.tar.gz" -C dist .
cp "$(command -v node)" dist/node
chmod +x dist/node
tar -czf "SnowLuma-dev-${{ matrix.name }}.tar.gz" -C dist .
# Single upload step — glob picks up both variants (.zip on Windows,
# .tar.gz on Linux) for this matrix row.
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: SnowLuma-dev-${{ github.sha }}
path: SnowLuma-dev.zip
retention-days: 3
overwrite: true
- name: Upload artifact (no-node)
uses: actions/upload-artifact@v4
with:
name: SnowLuma-dev-${{ github.sha }}-no-node
path: SnowLuma-dev-no-node.zip
name: SnowLuma-dev-${{ github.sha }}-${{ matrix.name }}
path: SnowLuma-dev-${{ matrix.name }}*
retention-days: 3
overwrite: true
if-no-files-found: error

View File

@@ -10,7 +10,20 @@ permissions:
jobs:
build:
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
include:
- name: win-x64
os: windows-latest
target: win32-x64
- name: linux-x64
os: ubuntu-latest
target: linux-x64
- name: linux-arm64
os: ubuntu-24.04-arm
target: linux-arm64
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -34,70 +47,112 @@ jobs:
# Always builds the WebUI flavor — no separate "core-only" artifact.
- name: Build project
env:
SNOWLUMA_TARGET: ${{ matrix.target }}
run: pnpm run build:all
- name: Verify native files
shell: pwsh
run: |
if (!(Test-Path "dist\native\snowluma-win32-x64.node")) { throw "Missing dist\native\snowluma-win32-x64.node" }
if (!(Test-Path "dist\native\snowluma-win32-x64.dll")) { throw "Missing dist\native\snowluma-win32-x64.dll" }
if (!(Test-Path "dist\native\websocket-win32-x64.node")) { throw "Missing dist\native\websocket-win32-x64.node" }
- name: Bundle runtime dependencies
working-directory: dist
run: npm install --omit=dev
# Two release archives:
# * SnowLuma-<tag>-win-x64.zip – zero-install bundle (ships node.exe)
# * SnowLuma-<tag>-win-x64-no-node.zip – same bundle without node.exe
- name: Package release (no-node)
shell: pwsh
run: |
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-win-x64-no-node.zip"
- name: Package release (with node.exe)
# Naming convention:
# SnowLuma-<tag>-<arch>.zip|tar.gz – zero-install (node bundled)
# SnowLuma-<tag>-<arch>-lite.zip|tar.gz – user provides Node >= 22
- name: Package (windows)
if: matrix.os == 'windows-latest'
shell: pwsh
run: |
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}-lite.zip"
Copy-Item (Get-Command node).Source -Destination "dist\node.exe"
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-win-x64.zip"
Compress-Archive -Path "dist\*" -DestinationPath "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.zip"
- name: Package (linux)
if: startsWith(matrix.os, 'ubuntu')
run: |
chmod +x dist/launcher.sh
tar -czf "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}-lite.tar.gz" -C dist .
cp "$(command -v node)" dist/node
chmod +x dist/node
tar -czf "SnowLuma-${{ github.ref_name }}-${{ matrix.name }}.tar.gz" -C dist .
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: release-${{ matrix.name }}
path: SnowLuma-${{ github.ref_name }}-${{ matrix.name }}*
if-no-files-found: error
retention-days: 1
release:
needs: build
runs-on: ubuntu-latest
steps:
- name: Checkout (for git log)
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Collect release assets
run: |
mkdir -p release
find artifacts -type f \( -name '*.zip' -o -name '*.tar.gz' \) -exec cp {} release/ \;
ls -lh release/
- name: Generate release note
shell: pwsh
shell: bash
run: |
$tag = "${{ github.ref_name }}"
$previousTag = git describe --tags --abbrev=0 "$tag^" 2>$null
if ($LASTEXITCODE -ne 0) { $previousTag = "" }
if ($previousTag) {
$range = "$previousTag..$tag"
$changes = git log --pretty=format:"- %s (%h)" $range
} else {
$changes = git log --pretty=format:"- %s (%h)" $tag
}
if (!$changes) { $changes = "- No commit changes detected." }
$body = @"
# SnowLuma $tag
tag="${GITHUB_REF_NAME}"
previousTag="$(git describe --tags --abbrev=0 "${tag}^" 2>/dev/null || true)"
if [[ -n "$previousTag" ]]; then
changes="$(git log --pretty=format:'- %s (%h)' "$previousTag..$tag")"
else
changes="$(git log --pretty=format:'- %s (%h)' "$tag")"
fi
[[ -z "$changes" ]] && changes="- No commit changes detected."
cat > release-notes.md <<EOF
# SnowLuma ${tag}
## 发布概览
本次发布提供 SnowLuma 的 Windows x64 构建产物,默认包含 WebUI。
本次发布提供 SnowLuma 的 Windows x64 / Linux x64 / Linux arm64 构建产物,默认包含 WebUI。
## 下载说明
- ``SnowLuma-$tag-win-x64.zip``:完整版本,内置 ``node.exe`` 与运行时依赖,解压即可使用。
- ``SnowLuma-$tag-win-x64-no-node.zip``:不含 ``node.exe``,需自行安装 Node.js 22 及以上版本后再运行 ``launcher.bat`` 或 ``node index.mjs``。
命名约定:
- 无后缀 \`.zip/.tar.gz\`:完整版本,内置 \`node\`/\`node.exe\` 与运行时依赖,解压即可使用。
- \`-lite\` 后缀:精简版本,不含 Node.js 运行时,需自行安装 Node.js 22+。
Windows:
- \`SnowLuma-${tag}-win-x64.zip\`
- \`SnowLuma-${tag}-win-x64-lite.zip\`
Linux x64:
- \`SnowLuma-${tag}-linux-x64.tar.gz\`
- \`SnowLuma-${tag}-linux-x64-lite.tar.gz\`
Linux arm64:
- \`SnowLuma-${tag}-linux-arm64.tar.gz\`
- \`SnowLuma-${tag}-linux-arm64-lite.tar.gz\`
## 更新内容
$changes
${changes}
## 使用说明
- 仅支持 Windows x64 环境。
- 两个压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:8080 选择进程、调整配置或查看日志。
- ``no-node`` 版本要求系统 ``node`` 可执行文件版本 >= 22。
"@
$body -replace "(?m)^ ", "" | Set-Content -Path "release-notes.md" -Encoding utf8
- Windows x64:\`launcher.bat\` 或 \`node index.mjs\`。
- Linux:\`./launcher.sh\` 或 \`node index.mjs\`。
- 所有压缩包均已内置 WebUI 静态资源;启动后访问 http://localhost:8080。
- Linux 版本仅提供 OneBot 桥接能力,NTQQ 进程注入仅在 Windows 下生效。
EOF
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
files: SnowLuma-*.zip
files: |
release/*.zip
release/*.tar.gz
body_path: release-notes.md
overwrite_files: true
draft: false

1
.gitignore vendored
View File

@@ -8,6 +8,7 @@ CMakePresets.json
*.obj
*.exe
*.so
!native/snowluma-linux-x64.so
*.dylib
*.a
*.lib

Binary file not shown.

Binary file not shown.

View File

@@ -47,6 +47,16 @@ export class HookManager {
state.path = proc.path;
}
// Probe every freshly-enumerated PID in parallel to detect hooks left over
// from a previous SnowLuma run. Positive hits are reconnected immediately
// so the login-state snapshot can update the UI without a manual load.
await Promise.all(
processes
.map(proc => this.states.get(proc.pid)!)
.filter(state => !state.injected && !this.loadTasks.has(state.pid))
.map(state => this.probeAndSeed(state)),
);
const seen = new Set(processes.map(proc => proc.pid));
const result: HookProcessInfo[] = [];
for (const proc of processes) {
@@ -109,10 +119,18 @@ export class HookManager {
try {
if (!state.injected) {
state.injectResult = injectHookProcess(pid);
state.injected = true;
state.method = state.injectResult.method;
log.info('SnowLuma loaded into PID=%d via %s', pid, state.method);
// Fast path: if QQ.exe still hosts a hook DLL from a previous SnowLuma
// run, the control pipe is already listed. Skip re-injection on a hit.
if (await QqHookClient.probePipe(pid)) {
state.injected = true;
state.method = 'reconnect';
log.info('SnowLuma reconnected to existing hook in PID=%d', pid);
} else {
state.injectResult = injectHookProcess(pid);
state.injected = true;
state.method = state.injectResult.method;
log.info('SnowLuma loaded into PID=%d via %s', pid, state.method);
}
}
state.status = state.connected ? (state.loggedIn ? 'online' : 'loaded') : 'loaded';
this.startClient(state);
@@ -248,11 +266,14 @@ export class HookManager {
}
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
const wasLoggedIn = state.loggedIn;
const previousUin = state.uin;
state.uin = loginState.uin || loginState.uinNumber.toString();
state.loggedIn = loginState.loggedIn && isRealUin(state.uin);
state.status = state.loggedIn ? 'online' : (state.connected ? 'loaded' : state.status);
if (!state.loggedIn || !state.sender) return;
if (wasLoggedIn && previousUin === state.uin) return;
this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender);
log.success('login detected: PID=%d UIN=%s', state.pid, state.uin);

View File

@@ -37,11 +37,21 @@ function loadNativeAddon(addonPath: string): NativeHookAddon {
return mod.exports as unknown as NativeHookAddon;
}
function platformBinaryName(ext: 'node' | 'dll'): string {
type HookBinaryExt = 'node' | 'dll' | 'so';
function platformBinaryName(ext: HookBinaryExt): string {
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
return `snowluma-${process.platform}-${process.arch}.${ext}`;
}
function platformInjectableExt(): 'dll' | 'so' {
return process.platform === 'win32' ? 'dll' : 'so';
}
function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
@@ -56,7 +66,7 @@ function nativeSearchDirs(): string[] {
];
}
export function resolveHookNativePath(ext: 'node' | 'dll'): string | null {
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
const fileName = platformBinaryName(ext);
for (const dir of nativeSearchDirs()) {
const fullPath = path.join(dir, fileName);
@@ -92,7 +102,7 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
return [...new Set(addon.getAllMainProcess())]
.filter(pid => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map(pid => ({ pid, name: 'QQ.exe', path: '' }));
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
}
export function injectHookProcess(pid: number): HookInjectResult {
@@ -100,9 +110,10 @@ export function injectHookProcess(pid: number): HookInjectResult {
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
const dllPath = resolveHookNativePath('dll');
const injectableExt = platformInjectableExt();
const dllPath = resolveHookNativePath(injectableExt);
if (!dllPath) {
throw new Error(`No hook DLL found for ${process.platform}-${process.arch}`);
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
}
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
}

View File

@@ -1,4 +1,7 @@
import net from 'net';
import os from 'os';
import path from 'path';
import { promises as fs } from 'fs';
import { EventEmitter } from 'events';
export const PIPE_MAGIC = 0x31504851;
@@ -81,8 +84,22 @@ interface PendingAck {
wantReply: boolean;
}
function linuxRuntimeDir(): string {
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
if (explicit && explicit.length > 0) return explicit;
const xdg = process.env.XDG_RUNTIME_DIR;
if (xdg && xdg.length > 0) return xdg;
// Mirrors hook_stub.cpp runtime_dir() fallback.
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
return `/tmp/snowluma-${uid}`;
}
function mojoPipeName(pid: number, suffix: string): string {
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
if (process.platform === 'win32') {
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
}
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
}
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
@@ -266,6 +283,27 @@ export class QqHookClient extends EventEmitter {
return mojoPipeName(pid, 'recv');
}
/**
* Lightweight liveness check for the control pipe. Used to detect whether an
* existing SnowLuma hook is still hosted inside the QQ.exe process without
* opening the pipe, so probing cannot disturb the first real client connect.
*/
static async probePipe(pid: number): Promise<boolean> {
try {
const pipeFileName = process.platform === 'win32'
? `mojo.${pid}.control`
: `mojo.${pid}.control.sock`;
if (process.platform === 'win32') {
const names = await fs.readdir('\\\\.\\pipe\\');
return names.some(name => name.toLowerCase() === pipeFileName.toLowerCase());
}
const names = await fs.readdir(linuxRuntimeDir());
return names.includes(pipeFileName);
} catch {
return false;
}
}
async connect(): Promise<QqHookHello> {
if (this.closed) {
throw new Error('qq_hook client is closed');
@@ -576,8 +614,8 @@ export class QqHookClient extends EventEmitter {
const previous = this.loginState;
const next = { loggedIn, uin, uinNumber };
this.loginState = next;
this.emit('loginState', next);
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
this.emit('loginState', next);
if (next.loggedIn) {
const waiters = this.loginWaiters;
this.loginWaiters = [];

View File

@@ -1,5 +1,6 @@
import { defineConfig, PluginOption, UserConfig } from 'vite';
import { fileURLToPath } from 'url';
import fs from 'fs';
import path from 'path';
import { builtinModules } from 'module';
import cp from 'vite-plugin-cp';
@@ -22,19 +23,40 @@ const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`
const runtimeSrc = toPosix(runtimeDir);
const nativeSrc = toPosix(nativeDir);
// Only the runtime distribution assets land in dist/.
// (.gitignore and other dev artifacts must NOT be shipped.)
const runtimeDistFiles = ['launcher.bat', 'package.json'];
// Only ship native binaries matching the current build host's platform/arch.
// Override via SNOWLUMA_TARGET=<platform>-<arch> for cross-target packaging.
// Target selection: `SNOWLUMA_TARGET=<platform>-<arch>` overrides the host
// detection, enabling cross-target packaging on CI.
const targetTriple = process.env.SNOWLUMA_TARGET ?? `${process.platform}-${process.arch}`;
const nativeGlobs = [
`snowluma-${targetTriple}.dll`,
`snowluma-${targetTriple}.node`,
`websocket-${targetTriple}.node`,
const targetPlatform = targetTriple.split('-')[0];
// Runtime scaffolding files copied into dist/. The NTQQ hook is Windows-only,
// so its launcher/shell script differ per target.
const runtimeDistFiles = ['package.json',
targetPlatform === 'win32' ? 'launcher.bat' : 'launcher.sh',
];
// Native binaries shipped for the selected target:
// * `snowluma-*.{dll,node}` – NTQQ hook (Windows-only).
// * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms).
const nativeFiles = [
`websocket-${targetTriple}.node`,
...(targetPlatform === 'win32'
? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`]
: []),
];
// Fail fast if any expected native binary is missing from packages/runtime/native/.
// vite-plugin-cp only emits a warning on missing source files; we want a hard
// error so CI can't accidentally ship an incomplete archive.
const missingNatives = nativeFiles.filter(
(f) => !fs.existsSync(path.join(nativeDir, f)),
);
if (missingNatives.length > 0) {
throw new Error(
`Missing native binaries for target ${targetTriple}:\n` +
missingNatives.map((f) => ` - ${path.join(nativeDir, f)}`).join('\n'),
);
}
const BaseConfigPlugin: PluginOption[] = [
cp({
targets: [
@@ -43,8 +65,8 @@ const BaseConfigPlugin: PluginOption[] = [
dest: distDir,
flatten: true,
})),
...nativeGlobs.map((g) => ({
src: `${nativeSrc}/${g}`,
...nativeFiles.map((f) => ({
src: `${nativeSrc}/${f}`,
dest: path.join(distDir, 'native'),
flatten: true,
})),

View File

@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
# Prefer bundled node when present; fall back to $PATH.
if [[ -x "./node" ]]; then
NODE_BIN="./node"
else
NODE_BIN="$(command -v node || true)"
if [[ -z "$NODE_BIN" ]]; then
echo "error: 'node' not found on PATH and no bundled ./node; install Node.js >= 22." >&2
exit 127
fi
fi
exec "$NODE_BIN" ./index.mjs "$@"