Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Fix native dependency repair and isolate sharp in bundled Node (#73)

Orkas33bc31194b41
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..d2f521dc
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# Vite cannot transform hashbang ESM scripts with CRLF line endings.
+*.mjs text eol=lf
diff --git a/.github/workflows/linux-source-smoke.yml b/.github/workflows/linux-source-smoke.yml
index 9fcb3891..9af0ed79 100644
--- a/.github/workflows/linux-source-smoke.yml
+++ b/.github/workflows/linux-source-smoke.yml
@@ -56,6 +56,12 @@ jobs:
sudo apt-get install --yes xvfb
fi
+ - name: Restore standard read-only system font permissions
+ run: |
+ stat -c '%u:%g %a %n' /usr/share/fonts /usr/share/fonts/truetype
+ # Avoid Fontconfig mutating root-owned runner-writable font trees.
+ sudo chmod -R go-w /usr/share/fonts
+
- name: Prepare and verify built-in Linux dependencies
run: node scripts/ensure-dev-dependencies.cjs
diff --git a/.github/workflows/native-dependencies.yml b/.github/workflows/native-dependencies.yml
new file mode 100644
index 00000000..c922bb9f
--- /dev/null
+++ b/.github/workflows/native-dependencies.yml
@@ -0,0 +1,64 @@
+name: Native dependency repair
+
+on:
+ pull_request:
+ push:
+ branches: [main]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ native-dependencies:
+ name: Native dependencies (${{ matrix.runner }})
+ strategy:
+ fail-fast: false
+ matrix:
+ runner: [ubuntu-22.04, ubuntu-22.04-arm, windows-2022, macos-15, macos-15-intel]
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: 24
+ cache: npm
+ - name: Install the locked dependencies, including native optional packages
+ run: npm ci --include=optional
+ - name: Exercise the supported repair command and both target runtimes
+ run: npm run native:repair
+ - name: Collect native child diagnostics on a failed clean CI installation
+ if: failure()
+ shell: bash
+ run: |
+ node <<'NODE'
+ const { spawnSync } = require('node:child_process');
+ const { verifyNativeDependencies } = require('./scripts/verify-native-dependencies.cjs');
+ verifyNativeDependencies({ spawn: (...args) => {
+ const result = spawnSync(...args);
+ console.log(JSON.stringify({ status: result.status, signal: result.signal,
+ stdout: result.stdout, stderr: result.stderr, error: result.error?.code }));
+ return result;
+ } });
+ NODE
+ - name: Verify that repair preserved the manifests
+ run: git diff --exit-code -- package.json package-lock.json
+ - name: Restore standard read-only system font permissions on Linux
+ if: runner.os == 'Linux'
+ run: |
+ stat -c '%u:%g %a %n' /usr/share/fonts /usr/share/fonts/truetype
+ # Fontconfig cannot restore root-owned directory timestamps after
+ # removing legacy UUID files from runner-writable font directories.
+ # Keep system fonts readable and writable only by their owner.
+ sudo chmod -R go-w /usr/share/fonts
+ - name: Run native dependency regression cases under Electron
+ run: >-
+ npm run test:js -- --maxWorkers=1
+ test/main/util/sharp-runtime.test.ts
+ test/main/features/image_assets.test.ts
+ test/main/util/verify-native-dependencies.test.ts
+ test/main/util/ensure-sqlite-electron-abi.test.ts
+ test/main/util/ensure-deps.test.ts
+ test/main/util/ensure-dev-dependencies.test.ts
+ test/main/util/linux-source-dependencies.test.ts
diff --git a/README.md b/README.md
index 5e130e77..86d7a787 100644
--- a/README.md
+++ b/README.md
@@ -121,7 +121,7 @@ Yes. Beyond its own Commander and specialist agents, Orkas can drive five extern
Claude Desktop is a single assistant; CrewAI and LangChain are code-first frameworks. Orkas is a local-first multi-agent desktop app: the Commander coordinates specialist agents, keeps data and keys local, and gives each agent its own private skills and memory. See the [full comparisons](https://orkas.ai/compare/orkas-vs-langchain?source=gh-orkas).
**Which platforms does Orkas support?**
-macOS (Apple Silicon and Intel) and Windows 10+ have packaged installers. glibc 2.34+ Linux x64/arm64 runs from source today, with no installer yet. Local speech transcription is supported on Linux through the pinned whisper.cpp runtime prepared on first launch. Alpine and other musl-based distributions are not supported. The source bootstrap needs Node 20+; Python 3 and a C/C++ build toolchain are needed only when a native npm package has no compatible prebuilt binary and must be rebuilt locally.
+macOS (Apple Silicon and Intel) and Windows 10+ have packaged installers. glibc 2.34+ Linux x64/arm64 runs from source today, with no installer yet. Local speech transcription is supported on Linux through the pinned whisper.cpp runtime prepared on first launch. Alpine and other musl-based distributions are not supported. The source bootstrap needs Node 22.12+; Python 3 and a C/C++ build toolchain are needed only when a native npm package has no compatible prebuilt binary and must be rebuilt locally.
**Is Orkas free and open source?**
Yes — the app is MIT licensed and free to use. Bring your own model keys and you pay only your model providers; Orkas never takes a cut. Optionally, the desktop app also offers a built-in **Orkas model** for people who don't want to manage API keys — that one is billed by Orkas in credits (membership or credit packs). It is entirely opt-in, and every other feature works on your own keys. [Pricing →](https://orkas.ai/pricing/?source=gh-orkas)
@@ -132,7 +132,7 @@ Yes — the app is MIT licensed and free to use. Bring your own model keys and y
Want a packaged installer instead? See [Download](#download) above. To run from source — currently the way to run Orkas on Linux:
-**Requirements**: Node 20+ · macOS / Windows 10+ / glibc 2.34+ Linux x64 or arm64. Keep Python 3 and a C/C++ build toolchain available for the uncommon native-module source-build fallback.
+**Requirements**: Node 22.12+ · macOS / Windows 10+ / glibc 2.34+ Linux x64 or arm64. Keep Python 3 and a C/C++ build toolchain available for the uncommon native-module source-build fallback.
```bash
git clone https://github.com/Orkas-AI/Orkas.git
@@ -145,6 +145,13 @@ Linux source runs require glibc 2.34+. Alpine and other musl-based distributions
`run.sh` / `run.cmd` installs the locked npm dependency tree and prepares the pinned Python, uv, Node, embedding model (~95 MB), OfficeCLI, FFmpeg, whisper.cpp, and multilingual speech model resources on first launch. Linux startup then verifies the platform-native modules and Whisper runtime under Electron's ABI before opening the app. OCR and Skill-specific Python packages are installed into isolated local environments when those features are first used. First launch creates a workspace under `~/.orkas/` (macOS / Linux) or `<smallest non-system drive>:\.orkas\` (Windows). Then open **Settings → AI Providers** to add an API key or OAuth.
+Native dependency errors: use Node.js 24 LTS (minimum 22.12.0), then run
+`npm run native:repair` from this checkout. This restores optional packages,
+repairs SQLite for Electron, prepares bundled Node for isolated image processing,
+and checks SQL, sqlite-vec and sharp before success.
+Use `npm run native:check` for a check without installation.
+See [native dependency setup and troubleshooting](docs/native-dependencies.md).
+
---
## Screenshots
diff --git a/README.zh-CN.md b/README.zh-CN.md
index e2e9b001..0ea4cd3b 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -121,7 +121,7 @@ Orkas 是一个开源、本地优先的多智能体桌面应用。一个超强
Claude Desktop 是单个助理;CrewAI 和 LangChain 是代码优先的框架。Orkas 是一个本地优先的多智能体桌面应用:指挥官协调多个专业智能体,数据与 key 留在本地,每个智能体拥有私有技能与记忆。见[逐项对比](https://orkas.ai/compare/orkas-vs-langchain?source=gh-orkas)。
**支持哪些平台?**
-macOS(Apple 芯片与 Intel)和 Windows 10+ 提供安装包。基于 glibc 2.34+ 的 Linux x64/arm64 目前从源码运行,暂时没有安装包。本地语音转写通过首次启动时准备的固定版本 whisper.cpp 运行时提供。当前不支持 Alpine 及其他基于 musl 的发行版。源码启动需要 Node 20+;只有在原生 npm 包没有匹配的预编译二进制、必须本地编译时,才额外需要 Python 3 和 C/C++ 构建工具链。
+macOS(Apple 芯片与 Intel)和 Windows 10+ 提供安装包。基于 glibc 2.34+ 的 Linux x64/arm64 目前从源码运行,暂时没有安装包。本地语音转写通过首次启动时准备的固定版本 whisper.cpp 运行时提供。当前不支持 Alpine 及其他基于 musl 的发行版。源码启动需要 Node 22.12+;只有在原生 npm 包没有匹配的预编译二进制、必须本地编译时,才额外需要 Python 3 和 C/C++ 构建工具链。
**Orkas 免费且开源吗?**
是的 —— 应用本身 MIT 许可证、免费使用。自带模型 key 时,你只需为你的模型服务商付费,Orkas 不抽成。此外,桌面版还提供一个可选的内置 **Orkas 模型**,供不想自己配置 key 的用户使用 —— 这部分由 Orkas 按 credits 计费(会员或 credits 包)。它完全可选,其余所有功能用你自己的 key 即可。[价格 →](https://orkas.ai/pricing/?source=gh-orkas)
@@ -132,7 +132,7 @@ macOS(Apple 芯片与 Intel)和 Windows 10+ 提供安装包。基于 glibc 2
想直接用安装包?见上方 [下载](#下载)。以下是从源码运行的方式 —— 也是目前在 Linux 上运行 Orkas 的方式:
-**环境要求**:Node 20+ · macOS / Windows 10+ / 基于 glibc 2.34+ 的 Linux x64 或 arm64。建议保留 Python 3 与 C/C++ 构建工具链,用于少数原生模块需要源码编译的兜底场景。
+**环境要求**:Node 22.12+ · macOS / Windows 10+ / 基于 glibc 2.34+ 的 Linux x64 或 arm64。建议保留 Python 3 与 C/C++ 构建工具链,用于少数原生模块需要源码编译的兜底场景。
```bash
git clone https://github.com/Orkas-AI/Orkas.git
@@ -145,6 +145,11 @@ Linux 源码运行需要 glibc 2.34+,不支持 Alpine 及其他基于 musl 的
`run.sh` / `run.cmd` 会在首次启动时安装 lockfile 固定的 npm 依赖,并准备固定版本的 Python、uv、Node、嵌入模型(约 95 MB)、OfficeCLI、FFmpeg、whisper.cpp 与多语言语音模型。Linux 启动还会在 Electron ABI 下验证平台原生模块及 Whisper 运行时后再打开应用。OCR 与 Skill 专属 Python 包会在首次使用对应功能时安装到隔离的本地环境。首次启动会在 `~/.orkas/`(macOS / Linux)或 `<最小的非系统盘>:\.orkas\`(Windows)下创建工作区。随后进入 **设置 → AI 服务商** 配置 API key 或 OAuth。
+遇到原生依赖错误时,请使用 Node.js 24 LTS(最低 22.12.0),在此源码目录执行
+`npm run native:repair`。它会恢复可选依赖、修复 Electron 对应的 SQLite,并验证 SQL、
+sqlite-vec,并准备随包 Node、在独立进程中验证 sharp 后才报告成功。只检查、不安装可运行 `npm run native:check`。
+详见[原生依赖安装与排错说明](docs/native-dependencies.md)。
+
---
## 截图
diff --git a/bin/packaged-entrypoint-gate.cjs b/bin/packaged-entrypoint-gate.cjs
index 8421716f..d4572705 100644
--- a/bin/packaged-entrypoint-gate.cjs
+++ b/bin/packaged-entrypoint-gate.cjs
@@ -46,6 +46,9 @@ const INTERNAL_ENTRYPOINT_CONSUMERS = Object.freeze({
'kb-embed-worker.cjs': Object.freeze([
'src/main/features/kb_embed.ts',
]),
+ 'sharp-worker.cjs': Object.freeze([
+ 'src/main/util/sharp-runtime.ts',
+ ]),
'orkas-bridge.cjs': Object.freeze([
'src/main/features/local_agents/bridge.ts',
'src/main/features/local_agents/runner.ts',
@@ -282,6 +285,11 @@ function assertExactFiles(label, actual, expected) {
}
}
+const PACKAGED_IMAGE_RUNTIME_UNPACK_GLOBS = Object.freeze([
+ 'node_modules/sharp/**/*', 'node_modules/@img/**/*',
+ 'node_modules/detect-libc/**/*', 'node_modules/semver/**/*',
+]);
+
function verifyBuildFilesConfig(build) {
const files = Array.isArray(build?.files) ? build.files.map(String) : [];
const asarUnpack = Array.isArray(build?.asarUnpack) ? build.asarUnpack.map(String) : [];
@@ -291,7 +299,7 @@ function verifyBuildFilesConfig(build) {
if (!asarUnpack.includes('bin/**/*')) {
throw new Error('[packaged-entrypoint-gate] build.asarUnpack must include bin/**/*');
}
- for (const glob of PACKAGED_MCP_RUNTIME_UNPACK_GLOBS) {
+ for (const glob of [...PACKAGED_MCP_RUNTIME_UNPACK_GLOBS, ...PACKAGED_IMAGE_RUNTIME_UNPACK_GLOBS]) {
if (!files.includes(glob)) {
throw new Error(`[packaged-entrypoint-gate] build.files must include ${glob}`);
}
@@ -575,6 +583,7 @@ function verifyPackagedEntrypointPayload(pcRoot, options = {}) {
}
module.exports = {
+ PACKAGED_IMAGE_RUNTIME_UNPACK_GLOBS,
BUILD_ONLY_BIN_FILES,
CONNECTOR_CATALOG_ENTRYPOINTS,
CONNECTOR_AUTH_ENTRYPOINTS,
diff --git a/bin/sharp-worker.cjs b/bin/sharp-worker.cjs
new file mode 100644
index 00000000..8c517c55
--- /dev/null
+++ b/bin/sharp-worker.cjs
@@ -0,0 +1,190 @@
+'use strict';
+
+const { fork, spawnSync } = require('node:child_process');
+
+const REQUEST_TIMEOUT_MS = 60_000;
+const IDLE_TIMEOUT_MS = 30_000;
+
+function failure(code, message) {
+ return Object.assign(new Error(`${code}: ${message}`), { code });
+}
+
+// A single lazily started stock-Node process isolates libvips from Electron's
+// Linux GLib symbols. Only image bytes/options cross IPC; file access and
+// publication remain at the owning feature's existing sandbox boundary.
+function createSharpClient({ nodeExecutable, workerPath = __filename, timeoutMs = REQUEST_TIMEOUT_MS, idleMs = IDLE_TIMEOUT_MS, spawn = fork, onDiagnostic = () => {} }) {
+ let child;
+ let sequence = 0;
+ let idle;
+ let disposed = false;
+ const pending = new Map();
+
+ function terminate(error) {
+ clearTimeout(idle);
+ const previous = child;
+ child = undefined;
+ if (previous) previous.kill();
+ for (const item of pending.values()) {
+ clearTimeout(item.timer);
+ item.reject(error);
+ }
+ pending.clear();
+ }
+
+ function scheduleIdle() {
+ if (pending.size) return;
+ clearTimeout(idle);
+ idle = setTimeout(() => terminate(failure('E_IMAGE_RUNTIME_IDLE', 'Image worker released.')), idleMs);
+ idle.unref();
+ }
+
+ function ensureChild() {
+ if (disposed) throw failure('E_IMAGE_RUNTIME_CLOSED', 'Image processing has stopped.');
+ if (child) return child;
+ if (!nodeExecutable) throw failure('E_IMAGE_RUNTIME_MISSING', 'The bundled image runtime is missing. Prepare the app runtimes or reinstall Orkas.');
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ delete env.NODE_OPTIONS;
+ delete env.NODE_PATH;
+ const current = spawn(workerPath, [], {
+ execPath: nodeExecutable, execArgv: [], env,
+ serialization: 'advanced', stdio: ['ignore', 'pipe', 'pipe', 'ipc'], windowsHide: true,
+ });
+ child = current;
+ // Pending requests have referenced deadline timers. An idle image process
+ // must not keep the app/test host alive; disconnect also stops the worker.
+ current.unref();
+ current.channel?.unref();
+ current.stdout?.unref?.();
+ current.stderr?.unref?.();
+ let reportedDiagnostic = false;
+ const unexpectedOutput = () => {
+ if (child !== current || reportedDiagnostic) return;
+ reportedDiagnostic = true;
+ // libvips can warn yet produce a valid image. Preserve that behavior,
+ // expose a bounded diagnostic event, and never relay raw private output.
+ onDiagnostic();
+ };
+ current.stdout.on('data', unexpectedOutput);
+ current.stderr.on('data', unexpectedOutput);
+ current.on('error', () => {
+ if (child === current) terminate(failure('E_IMAGE_RUNTIME_START', 'Could not start the bundled image runtime. Prepare the app runtimes or reinstall Orkas.'));
+ });
+ current.on('exit', () => {
+ if (child === current) terminate(failure('E_IMAGE_RUNTIME_EXIT', 'Image processing stopped unexpectedly. Retry the image operation.'));
+ });
+ current.on('message', message => {
+ if (child !== current) return;
+ const item = pending.get(message?.id);
+ if (!item) return;
+ pending.delete(message.id);
+ clearTimeout(item.timer);
+ const result = message.result;
+ const valid = item.operation === 'metadata'
+ ? result && typeof result.format === 'string' && result.width > 0 && result.height > 0
+ : result && Buffer.isBuffer(result.data) && result.data.length > 0 && result.info?.size === result.data.length;
+ if (message.ok === true && valid) item.resolve(result);
+ else item.reject(failure(message.code === 'E_IMAGE_RUNTIME_ELECTRON' ? message.code : 'E_IMAGE_PROCESS',
+ message.code === 'E_IMAGE_RUNTIME_ELECTRON'
+ ? 'Image processing requires the bundled Node runtime. Prepare the app runtimes and retry.'
+ : 'The image could not be processed. Check the input image and requested dimensions.'));
+ scheduleIdle();
+ });
+ return current;
+ }
+
+ return {
+ request(operation, buffer, options = {}) {
+ let target;
+ try { target = ensureChild(); } catch (error) { return Promise.reject(error); }
+ clearTimeout(idle);
+ const id = ++sequence;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ if (pending.has(id)) terminate(failure('E_IMAGE_RUNTIME_TIMEOUT', 'Image processing timed out. Try a smaller image or retry.'));
+ }, timeoutMs);
+ pending.set(id, { resolve, reject, timer, operation });
+ try {
+ target.send({ id, operation, buffer, options }, error => {
+ if (error && child === target) terminate(failure('E_IMAGE_RUNTIME_SEND', 'Could not send the image for processing. Retry the image operation.'));
+ });
+ } catch {
+ terminate(failure('E_IMAGE_RUNTIME_SEND', 'Could not send the image for processing. Retry the image operation.'));
+ }
+ });
+ },
+ close() {
+ disposed = true;
+ terminate(failure('E_IMAGE_RUNTIME_CLOSED', 'Image processing has stopped.'));
+ },
+ };
+}
+
+async function processImage(operation, buffer, options = {}) {
+ if (process.versions.electron) throw failure('E_IMAGE_RUNTIME_ELECTRON', 'Stock Node is required.');
+ if (!Buffer.isBuffer(buffer) || !buffer.length) throw failure('E_IMAGE_PROCESS', 'Image bytes are required.');
+ if (!['metadata', 'encode'].includes(operation)) throw failure('E_IMAGE_PROCESS', 'Unknown image operation.');
+ const sharp = require('sharp');
+ let pipeline = sharp(buffer, {
+ ...(options.failOn ? { failOn: options.failOn } : {}),
+ ...(options.limitInputPixels !== undefined ? { limitInputPixels: options.limitInputPixels } : {}),
+ ...(options.density !== undefined ? { density: options.density } : {}),
+ });
+ if (operation === 'metadata') return pipeline.metadata();
+ if (options.resize) pipeline = pipeline.resize(options.resize.width, options.resize.height, { fit: options.resize.fit });
+ const encodeOptions = options.encodeOptions || {};
+ if (options.format === 'png') pipeline = pipeline.png(encodeOptions);
+ else if (options.format === 'jpeg') pipeline = pipeline.jpeg(encodeOptions);
+ else if (options.format === 'webp') pipeline = pipeline.webp(encodeOptions);
+ else throw failure('E_IMAGE_PROCESS', 'Unknown image output format.');
+ return pipeline.toBuffer({ resolveWithObject: true });
+}
+
+// Shared by source and packaged smoke checks; never load native images in the
+// caller's Electron process, including when verifying an unpacked application.
+function probeImageRuntime(nodeExecutable, workerPath = __filename, spawn = spawnSync, env = process.env) {
+ const childEnv = { ...env };
+ delete childEnv.ELECTRON_RUN_AS_NODE;
+ delete childEnv.NODE_OPTIONS;
+ delete childEnv.NODE_PATH;
+ const result = spawn(nodeExecutable, [workerPath, '--probe'], {
+ env: childEnv, encoding: 'utf8', timeout: REQUEST_TIMEOUT_MS,
+ maxBuffer: 1024 * 1024, windowsHide: true,
+ });
+ let record;
+ try { record = JSON.parse(String(result.stdout || '').trim()); } catch { /* fail closed */ }
+ if (result.error || result.status !== 0 || String(result.stderr || '').trim()
+ || record?.status !== 'passed' || record.sharp !== 'png-2x2' || record.electron !== null
+ || !Number.isFinite(Number(record.napi)) || Number(record.napi) < 9) {
+ throw failure('E_IMAGE_RUNTIME_VERIFY', 'The bundled image runtime failed verification. Run npm run native:repair in the source checkout or reinstall Orkas.');
+ }
+ return record;
+}
+
+if (require.main === module) {
+ if (process.argv[2] === '--probe') {
+ (async () => {
+ const input = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"><rect width="2" height="2" fill="#14283c"/></svg>');
+ const { data } = await processImage('encode', input, { format: 'png' });
+ const metadata = await processImage('metadata', data);
+ if (metadata.format !== 'png' || metadata.width !== 2 || metadata.height !== 2) throw new Error('Invalid probe output');
+ console.log(JSON.stringify({ status: 'passed', sharp: 'png-2x2', node: process.versions.node,
+ napi: process.versions.napi, electron: process.versions.electron || null, platform: process.platform, arch: process.arch }));
+ })().catch(() => { console.error('The bundled image runtime could not complete PNG encoding/decoding. Prepare the app runtimes or reinstall Orkas.'); process.exitCode = 1; });
+ } else if (!process.send) process.exitCode = 1;
+ else {
+ process.on('disconnect', () => process.exit(0));
+ process.on('message', async message => {
+ if (!Number.isSafeInteger(message?.id)) return;
+ try {
+ const result = await processImage(message.operation, message.buffer, message.options);
+ if (process.connected) process.send({ id: message.id, ok: true, result });
+ } catch (error) {
+ // Never return raw native errors, image contents or filesystem paths.
+ if (process.connected) process.send({ id: message.id, ok: false, code: error.code });
+ }
+ });
+ }
+}
+
+module.exports = { createSharpClient, processImage, probeImageRuntime, REQUEST_TIMEOUT_MS };
diff --git a/docs/native-dependencies.md b/docs/native-dependencies.md
new file mode 100644
index 00000000..00bd003a
--- /dev/null
+++ b/docs/native-dependencies.md
@@ -0,0 +1,78 @@
+# Native dependencies when running from source
+
+Use Node.js 24 LTS to bootstrap the checkout (minimum 22.12.0). The desktop
+app and `npm test` load SQLite addons in the pinned Electron runtime. Image
+processing uses a separate bundled Node process on every platform; neither
+uses the system Node that runs npm. Keep optional dependencies enabled and use a
+separate checkout/dependency tree for each platform and process architecture.
+
+From the directory containing the desktop `package.json`, stop the source
+app and run the supported repair command:
+
+```sh
+npm run native:repair
+```
+
+This checks the bootstrap Node version, runs `npm install --include=optional
+--no-save` using the lockfile, lets postinstall repair better-sqlite3 for the
+installed Electron, prepares the pinned bundled Node, and verifies both runtimes:
+
+- better-sqlite3: an in-memory SQL query in Electron.
+- sqlite-vec: extension loading and a vector-distance calculation in Electron.
+- sharp: PNG encoding and decoding in ordinary bundled Node, outside Electron.
+
+Installation may download npm packages, Electron, bundled Node and the embedding model.
+The command does not change package declarations or the lockfile. Any failed
+install or final check returns nonzero; do not continue launching after a
+failure. A successful installer exit is not proof that an addon can load.
+
+For verification without installation, use `npm run native:check`. It prints
+the actual Electron and image-worker Node versions, modules ABI, Node-API,
+platform and architecture.
+Source startup performs the same functionality check before reporting ready.
+`npm run rebuild:sqlite:electron` remains a narrower SQLite-only repair: it
+tries the matching upstream Electron prebuild, then compiles better-sqlite3
+from source when needed, and verifies loading again.
+
+## Compatibility and recovery
+
+| Dependency | Binary compatibility requirement |
+| --- | --- |
+| better-sqlite3 | Electron modules ABI plus OS and process architecture |
+| sqlite-vec | SQLite loadable extension for the OS/architecture; not a Node addon to rebuild for every Electron ABI |
+| sharp | Node-API v9 or newer plus the matching optional sharp/libvips platform packages and system libraries |
+
+The upstream npm/native releases provide prebuilt components. A local SQLite
+source-build fallback needs Python 3 and a C/C++ build toolchain: Xcode Command
+Line Tools on macOS, Visual Studio C++ Build Tools on Windows, or the compiler
+and make tools for the Linux distribution. Use the documented source-platform
+matrix for the checkout; an upstream package supporting another architecture
+does not imply the entire desktop app supports it.
+
+If repair still fails, check network access to npm/GitHub/Electron downloads,
+the compiler prerequisites, and the named native dependency. Missing shared
+libraries need the target OS runtime libraries; another Electron rebuild does
+not fix an incompatible libc or a missing libvips DLL. Do not copy node_modules
+between Windows/macOS/Linux or between native arm64 and Rosetta x64 shells.
+For a corrupted dependency tree, use a fresh checkout with `npm ci
+--include=optional`, then `npm run native:repair`. Keep user data unchanged.
+
+Do not run plain `npm rebuild` to switch this shared tree to the system Node
+ABI, and do not run `npx vitest` directly: `npm test`/`npm run test:js` use the
+Electron test wrapper. Packaged desktop users should reinstall the correct
+platform/architecture installer rather than rebuild addons locally.
+
+On Linux, sharp documents a conflict with GLib symbols exported by Electron;
+rebuilding for another ABI does not fix that conflict. Orkas isolates every
+application sharp operation in ordinary bundled Node on all platforms, using
+the same sharp/libvips packages. The worker never falls back to Electron.
+Unexpected native diagnostics fail verification; no GLib warning is ignored.
+See [sharp's Electron/Linux conflict](https://sharp.pixelplumbing.com/install#electron-and-linux).
+
+The image process starts on demand, reuses one process for concurrent requests,
+and exits after 30 seconds idle or during app shutdown. IPC copies image bytes
+and adds cold-start latency and memory overhead; image format, quality, dimensions
+and file publication rules stay the same. Requests time out after 60 seconds.
+A crash or timeout fails pending requests without replay; a subsequent caller
+request can start a new process. This isolates Electron's symbols, but does not
+claim compatibility with every Linux distribution, library or image workload.
diff --git a/package-lock.json b/package-lock.json
index 51885988..42b5aab1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -44,6 +44,9 @@
"tar": "7.5.21",
"typescript": "^6.0.3",
"vitest": "^4.1.11"
+ },
+ "engines": {
+ "node": ">=22.12.0"
}
},
"node_modules/@anthropic-ai/sdk": {
diff --git a/package.json b/package.json
index b46643cf..0957a709 100644
--- a/package.json
+++ b/package.json
@@ -51,7 +51,9 @@
"rebuild:sqlite:electron": "node scripts/ensure-sqlite-electron-abi.mjs",
"postinstall": "node scripts/ensure-sqlite-electron-abi.mjs && node scripts/fetch-embedding-model.mjs",
"prepare": "node scripts/install-git-hooks.mjs",
- "prepack": "node scripts/ensure-dev-dependencies.cjs && node bin/officecli-policy-gate.cjs --require-host-binary"
+ "prepack": "node scripts/ensure-dev-dependencies.cjs && node bin/officecli-policy-gate.cjs --require-host-binary",
+ "native:check": "node scripts/verify-native-dependencies.cjs",
+ "native:repair": "node scripts/verify-native-dependencies.cjs --host-only && npm install --include=optional --no-save && node bin/ensure-runtime.cjs --kind node && npm run native:check"
},
"devDependencies": {
"@electron/asar": "3.4.1",
@@ -142,6 +144,8 @@
"node_modules/json-schema-traverse/**/*",
"node_modules/undici/**/*",
"node_modules/sharp/**/*",
+ "node_modules/detect-libc/**/*",
+ "node_modules/semver/**/*",
"node_modules/@img/**/*",
"node_modules/pdf-lib/**/*",
"node_modules/@pdf-lib/**/*",
@@ -175,6 +179,8 @@
"node_modules/json-schema-traverse/**/*",
"node_modules/undici/**/*",
"node_modules/sharp/**/*",
+ "node_modules/detect-libc/**/*",
+ "node_modules/semver/**/*",
"node_modules/@img/**/*",
"node_modules/better-sqlite3/**/*",
"node_modules/bindings/**/*",
@@ -277,5 +283,8 @@
}
}
},
- "license": "MIT"
+ "license": "MIT",
+ "engines": {
+ "node": ">=22.12.0"
+ }
}
diff --git a/run.sh b/run.sh
index 80960da7..3f7d2a34 100755
--- a/run.sh
+++ b/run.sh
@@ -69,7 +69,7 @@ wait_for_relaunch_owner() {
wait_for_relaunch_owner
if ! command -v node >/dev/null 2>&1; then
- echo "[Orkas] Node.js 20+ is required to bootstrap the source checkout. Install Node.js, then run ./run.sh again." >&2
+ echo "[Orkas] Node.js 22.12+ is required to bootstrap the source checkout. Install Node.js, then run ./run.sh again." >&2
exit 1
fi
diff --git a/scripts/ensure-deps.cjs b/scripts/ensure-deps.cjs
index 0ad405a7..652c1586 100644
--- a/scripts/ensure-deps.cjs
+++ b/scripts/ensure-deps.cjs
@@ -8,6 +8,7 @@ const path = require('node:path');
const os = require('node:os');
const crypto = require('node:crypto');
const { spawnSync } = require('node:child_process');
+const { assertBootstrapNode } = require('./verify-native-dependencies.cjs');
const PC_DIR = path.resolve(__dirname, '..');
const PKG = path.join(PC_DIR, 'package.json');
@@ -728,6 +729,11 @@ function patchElectronAppName() {
}
function main() {
+ try { assertBootstrapNode(); }
+ catch (error) {
+ console.error(`[Orkas] ${error.message}`);
+ process.exit(1);
+ }
if (!fs.existsSync(PKG)) {
console.error('[Orkas] 找不到 package.json:', PKG);
process.exit(1);
diff --git a/scripts/ensure-dev-dependencies.cjs b/scripts/ensure-dev-dependencies.cjs
index 21498518..680e6bda 100644
--- a/scripts/ensure-dev-dependencies.cjs
+++ b/scripts/ensure-dev-dependencies.cjs
@@ -23,6 +23,7 @@ function shouldProvisionWhisper(platform = process.platform, arch = process.arch
}
function main() {
+ run('Node bootstrap', 'scripts/verify-native-dependencies.cjs', ['--host-only']);
console.log(`[dev-deps] preparing built-in dependencies for ${process.platform}-${process.arch}`);
if (process.platform === 'linux') {
run('Linux host preflight', 'scripts/verify-linux-source-dependencies.cjs', ['--host-only']);
@@ -46,6 +47,7 @@ function main() {
'--arch', process.arch,
]);
}
+ run('native dependencies', 'scripts/verify-native-dependencies.cjs');
// Whisper ships pinned prebuilt CLIs for a fixed target list only. On hosts
// without a contract target the fetch script must keep failing (packaging
// gates rely on that strictness); here it is simply not required — speech
diff --git a/scripts/ensure-sqlite-electron-abi.mjs b/scripts/ensure-sqlite-electron-abi.mjs
index 12ea7b94..edeafb6b 100644
--- a/scripts/ensure-sqlite-electron-abi.mjs
+++ b/scripts/ensure-sqlite-electron-abi.mjs
@@ -11,6 +11,7 @@ import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { delimiter, dirname, posix, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import nativeDependencies from './verify-native-dependencies.cjs';
export const SQLITE_ABI_PROBE_TIMEOUT_MS = 30_000;
export const SQLITE_ABI_INSTALL_TIMEOUT_MS = 5 * 60_000;
@@ -165,10 +166,12 @@ export function ensureSqliteElectronAbi({
+ `(${describeResult(result)}); source rebuild also failed (${describeResult(rebuildResult)})`,
);
probeElectronAbi();
- return rebuildResult.status ?? result.status ?? 1;
+ // Installer exit codes cannot override the failed runtime probes.
+ return rebuildResult.status || result.status || 1;
}
function main() {
+ nativeDependencies.assertBootstrapNode();
const here = dirname(fileURLToPath(import.meta.url));
const pcRoot = resolve(here, '..');
const require_ = createRequire(import.meta.url);
diff --git a/scripts/linux-native-dependency-probe.cjs b/scripts/linux-native-dependency-probe.cjs
index ec1fc782..1607262b 100644
--- a/scripts/linux-native-dependency-probe.cjs
+++ b/scripts/linux-native-dependency-probe.cjs
@@ -16,34 +16,9 @@ function requireCondition(condition, message) {
if (!condition) throw new Error(message);
}
-async function probeSqlite() {
- const Database = require('better-sqlite3');
- const sqliteVec = require('sqlite-vec');
- const db = new Database(':memory:');
- try {
- sqliteVec.load(db);
- const row = db.prepare('SELECT vec_version() AS version').get();
- requireCondition(typeof row?.version === 'string' && row.version.length > 0, 'sqlite-vec returned no version');
- } finally {
- db.close();
- }
-}
-
-async function probeSharp() {
- const sharp = require('sharp');
- const png = await sharp({
- create: {
- width: 2,
- height: 2,
- channels: 4,
- background: { r: 20, g: 40, b: 60, alpha: 1 },
- },
- }).png().toBuffer();
- requireCondition(
- png.length > 8 && png.subarray(1, 4).toString('ascii') === 'PNG',
- 'sharp did not produce a PNG',
- );
-}
+const native = require('./native-dependency-probe.cjs');
+const probeSqlite = () => native.probeSqlite(require);
+const probeSharp = () => require('./verify-native-dependencies.cjs').verifySharpRuntime();
async function probeCanvas() {
const { createCanvas } = require('@napi-rs/canvas');
diff --git a/scripts/native-dependency-probe.cjs b/scripts/native-dependency-probe.cjs
new file mode 100644
index 00000000..7742f42b
--- /dev/null
+++ b/scripts/native-dependency-probe.cjs
@@ -0,0 +1,30 @@
+'use strict';
+
+// These functions are also embedded in the packaged-app smoke process. Keep
+// them self-contained: resolve packages from the runtime being verified.
+async function probeSqlite(requirePackage, resolveExtensionPath = value => value) {
+ let db;
+ let dependency = 'better-sqlite3';
+ try {
+ const Database = requirePackage(dependency);
+ db = new Database(':memory:');
+ if (db.prepare('SELECT 42 AS answer').get().answer !== 42) {
+ throw new Error('SQL round trip failed');
+ }
+ dependency = 'sqlite-vec';
+ const sqliteVec = requirePackage(dependency);
+ db.loadExtension(resolveExtensionPath(sqliteVec.getLoadablePath()));
+ const row = db.prepare("SELECT vec_version() AS version, vec_distance_L2('[0,0]', '[3,4]') AS distance").get();
+ if (typeof row.version !== 'string' || !row.version || row.distance !== 5) {
+ throw new Error('Vector round trip failed');
+ }
+ return { sqliteVec: row.version, vectorDistance: row.distance };
+ } catch (error) {
+ // Do not expose native-loader paths or unrestricted exception messages.
+ throw new Error(`${dependency} could not complete its native operation; run npm run native:repair in the source checkout, or reinstall the matching desktop installer.`);
+ } finally {
+ if (db) db.close();
+ }
+}
+
+module.exports = { probeSqlite };
diff --git a/scripts/run-platform-native-tests.mjs b/scripts/run-platform-native-tests.mjs
index c226b2f2..6a74806b 100644
--- a/scripts/run-platform-native-tests.mjs
+++ b/scripts/run-platform-native-tests.mjs
@@ -20,6 +20,8 @@ if (!['win32', 'darwin', 'linux'].includes(process.platform)) {
// runs after dependency provisioning in the platform-specific Windows and
// Linux lanes because it requires downloaded FFmpeg, model, and native payloads.
const commonSuites = [
+ 'test/main/util/verify-native-dependencies.test.ts',
+ 'test/main/util/ensure-sqlite-electron-abi.test.ts',
'test/main/util/inspect-canary-logs.test.ts',
'src/core-agent/test/oauth-flow.test.ts',
'src/core-agent/test/tools.test.ts',
@@ -72,7 +74,6 @@ const platformSuites = process.platform === 'win32'
'test/main/util/linux-source-dependencies.test.ts',
'test/main/util/officecli-fetch.test.ts',
'test/main/util/ensure-dev-dependencies.test.ts',
- 'test/main/util/ensure-sqlite-electron-abi.test.ts',
];
console.log(`[platform-native-tests] host=${process.platform}; suites=${commonSuites.length + platformSuites.length}`);
diff --git a/scripts/verify-linux-source-dependencies.cjs b/scripts/verify-linux-source-dependencies.cjs
index 0b8cbcef..d9c5e169 100644
--- a/scripts/verify-linux-source-dependencies.cjs
+++ b/scripts/verify-linux-source-dependencies.cjs
@@ -14,7 +14,8 @@ const {
} = require('../bin/runtime-gate.cjs');
const PC_ROOT = path.resolve(__dirname, '..');
-const MINIMUM_NODE_MAJOR = 20;
+const { assertBootstrapNode } = require('./verify-native-dependencies.cjs');
+const MINIMUM_NODE_MAJOR = 22;
// The official whisper.cpp v1.9.1 Ubuntu x64/arm64 releases require symbols
// through GLIBC_2.34, so the source bootstrap must reject older hosts before
// downloading runtimes that cannot execute there.
@@ -56,9 +57,7 @@ function assertLinuxHost({
throw new Error(`unsupported Linux architecture ${arch}; Orkas source runs support x64 and arm64`);
}
const nodeMajor = Number.parseInt(String(nodeVersion).split('.', 1)[0], 10);
- if (!Number.isFinite(nodeMajor) || nodeMajor < MINIMUM_NODE_MAJOR) {
- throw new Error(`Node.js ${MINIMUM_NODE_MAJOR}+ is required; found ${nodeVersion || 'unknown'}`);
- }
+ assertBootstrapNode(nodeVersion);
if (!glibcVersionRuntime) {
throw new Error('glibc is required; Alpine and other musl-based Linux distributions are not supported');
}
diff --git a/scripts/verify-native-dependencies.cjs b/scripts/verify-native-dependencies.cjs
new file mode 100644
index 00000000..a22cd545
--- /dev/null
+++ b/scripts/verify-native-dependencies.cjs
@@ -0,0 +1,113 @@
+#!/usr/bin/env node
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { createRequire } = require('node:module');
+const { spawnSync } = require('node:child_process');
+const { probeSqlite } = require('./native-dependency-probe.cjs');
+
+const MINIMUM_NODE_VERSION = '22.12.0';
+const PROBE_TIMEOUT_MS = 60_000;
+const root = path.resolve(__dirname, '..');
+
+function verifySharpRuntime({ packageRoot = root, spawn = spawnSync, env = process.env } = {}) {
+ let nodeExecutable;
+ let nodeVersion;
+ try {
+ const { verifyRuntimeDir } = require('../bin/runtime-gate.cjs');
+ const runtimeRoot = path.join(packageRoot, 'resources', 'runtime');
+ const manifest = JSON.parse(fs.readFileSync(path.join(runtimeRoot, 'manifest.json'), 'utf8'));
+ const key = `${process.platform}-${process.arch}`;
+ nodeVersion = manifest.node.version;
+ nodeExecutable = verifyRuntimeDir('node', path.join(runtimeRoot, 'node', key), key,
+ manifest.node, manifest.node.assets[key], process.platform, process.arch);
+ } catch {
+ throw new Error('The bundled Node image runtime is missing or invalid; run npm run native:repair.');
+ }
+ const { probeImageRuntime } = require('../bin/sharp-worker.cjs');
+ const record = probeImageRuntime(nodeExecutable, path.join(packageRoot, 'bin', 'sharp-worker.cjs'), spawn, env);
+ if (record.node !== nodeVersion || record.platform !== process.platform || record.arch !== process.arch) {
+ throw new Error('sharp failed verification in the bundled Node image runtime; run npm run native:repair.');
+ }
+ return record;
+}
+
+// Built-ins only: this preflight also runs before node_modules exists.
+function assertBootstrapNode(version = process.versions.node) {
+ const parts = String(version).split('.');
+ const valid = parts.length === 3 && parts.every(part => /^\d+$/.test(part));
+ if (!valid || Number(parts[0]) < 22 || (Number(parts[0]) === 22 && Number(parts[1]) < 12)) {
+ throw new Error(`Node.js ${MINIMUM_NODE_VERSION}+ is required to prepare native dependencies; use Node.js 24 LTS and retry.`);
+ }
+}
+
+function verifyNativeDependencies({ packageRoot = root, spawn = spawnSync, env = process.env } = {}) {
+ assertBootstrapNode();
+ const requirePackage = createRequire(path.join(packageRoot, 'package.json'));
+ let lock;
+ try { lock = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package-lock.json'), 'utf8')); }
+ catch { throw new Error('Cannot read package-lock.json; restore the checkout lockfile, then run npm run native:repair.'); }
+ for (const name of ['electron', 'better-sqlite3', 'sqlite-vec', 'sharp']) {
+ const expected = lock.packages?.[`node_modules/${name}`]?.version;
+ let installed;
+ try { installed = JSON.parse(fs.readFileSync(path.join(packageRoot, 'node_modules', name, 'package.json'), 'utf8')).version; }
+ catch { /* handled as an incomplete installation below */ }
+ if (!expected || installed !== expected) {
+ throw new Error(`${name} does not match package-lock.json; run npm run native:repair in this checkout.`);
+ }
+ }
+ const electronVersion = lock.packages['node_modules/electron'].version;
+ let electronPath;
+ try { electronPath = requirePackage('electron'); }
+ catch { throw new Error('Electron is not installed correctly; run npm run native:repair in this checkout.'); }
+ // Use the target Electron's require, never this system Node's addon loader.
+ const script = `
+ const { createRequire } = require('node:module');
+ const requirePackage = createRequire(${JSON.stringify(path.join(packageRoot, 'package.json'))});
+ (async () => {
+ const sqlite = await (${probeSqlite.toString()})(requirePackage);
+ console.log(JSON.stringify({status:'passed', ...sqlite,
+ platform:process.platform, arch:process.arch, electron:process.versions.electron,
+ node:process.versions.node, modules:process.versions.modules, napi:process.versions.napi}));
+ })().catch(error => { console.error(error.message); process.exitCode = 1; });
+ `;
+ const result = spawn(electronPath, ['-e', script], {
+ cwd: packageRoot, env: { ...env, ELECTRON_RUN_AS_NODE: '1' },
+ encoding: 'utf8', timeout: PROBE_TIMEOUT_MS, maxBuffer: 1024 * 1024,
+ windowsHide: true,
+ });
+ let record;
+ try { record = JSON.parse(String(result.stdout || '').trim()); } catch { /* fail closed */ }
+ if (result.error || result.status !== 0 || String(result.stderr || '').trim()
+ || record?.status !== 'passed' || record.electron !== electronVersion
+ || record.platform !== process.platform || record.arch !== process.arch
+ || typeof record.sqliteVec !== 'string' || !record.sqliteVec
+ || record.vectorDistance !== 5) {
+ // Only relay the bounded messages authored by our probe. Native stderr can
+ // contain private paths; unknown loader failures keep the recovery context.
+ const known = ['better-sqlite3', 'sqlite-vec', 'sharp'].find(name =>
+ String(result.stderr || '').startsWith(`${name} could not complete`));
+ const reason = result.error?.code === 'ETIMEDOUT' ? 'timed out' : 'failed';
+ throw new Error(`Native dependency verification ${reason}${known ? ` (${known})` : ''} for Electron ${electronVersion} on ${process.platform}-${process.arch}. Run npm run native:repair; check optional packages, the target architecture and system shared libraries.`);
+ }
+ const imageRuntime = verifySharpRuntime({ packageRoot, spawn, env });
+ return { ...record, sharp: imageRuntime.sharp, imageRuntime };
+}
+
+if (require.main === module) {
+ try {
+ const args = process.argv.slice(2);
+ if (args.length > 1 || (args.length === 1 && args[0] !== '--host-only')) throw new Error('Use --host-only or no arguments.');
+ assertBootstrapNode();
+ if (process.argv[2] !== '--host-only') {
+ const result = verifyNativeDependencies();
+ console.log(JSON.stringify(result));
+ }
+ } catch (error) {
+ console.error(`[native-deps] ${error.message}`);
+ process.exitCode = 1;
+ }
+}
+
+module.exports = { MINIMUM_NODE_VERSION, PROBE_TIMEOUT_MS, assertBootstrapNode, verifySharpRuntime, verifyNativeDependencies };
diff --git a/src/main/features/image_assets.ts b/src/main/features/image_assets.ts
index fa7aff87..3a1ca53f 100644
--- a/src/main/features/image_assets.ts
+++ b/src/main/features/image_assets.ts
@@ -2,9 +2,10 @@ import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { randomUUID } from 'node:crypto';
-import type { Sharp, SharpConstructor } from 'sharp';
+import type { Metadata, OutputInfo } from 'sharp';
import { isPathAllowed } from '../util/path-sandbox';
+import { encodeImage, imageMetadata } from '../util/sharp-runtime';
export interface ImageAssetProcessResult {
output_path: string;
@@ -44,19 +45,6 @@ function assertProjectFile(projectDirAbs: string, absPath: string, label: string
}
}
-async function loadSharp(): Promise<SharpConstructor> {
- try {
- const module = await import('sharp');
- const factory = module.default;
- if (typeof factory !== 'function') {
- throw new Error('sharp did not expose a callable default export');
- }
- return factory;
- } catch (error) {
- throw new Error(`E_SHARP_UNAVAILABLE: the image output validator is unavailable (${(error as Error).message}).`);
- }
-}
-
export async function inspectImageAssetBuffer(buffer: Buffer): Promise<{
format: string;
width: number;
@@ -65,11 +53,11 @@ export async function inspectImageAssetBuffer(buffer: Buffer): Promise<{
bytes: number;
}> {
if (!Buffer.isBuffer(buffer) || buffer.length === 0) throw new Error('E_IMAGE_ASSET_INVALID: image response is empty.');
- const sharp = await loadSharp();
- let metadata: Awaited<ReturnType<Sharp['metadata']>>;
+ let metadata: Metadata;
try {
- metadata = await sharp(buffer, { failOn: 'error', limitInputPixels: MAX_AREA }).metadata();
+ metadata = await imageMetadata(buffer, { failOn: 'error', limitInputPixels: MAX_AREA });
} catch (error) {
+ if (String((error as NodeJS.ErrnoException).code || '').startsWith('E_IMAGE_RUNTIME_')) throw error;
throw new Error(`E_IMAGE_ASSET_INVALID: workflow output is not a readable image (${(error as Error).message}).`);
}
if (!metadata.format || !metadata.width || !metadata.height) throw new Error('E_IMAGE_ASSET_INVALID: workflow output has no image dimensions.');
@@ -98,10 +86,10 @@ export async function prepareLosslessModelImage(buffer: Buffer): Promise<Lossles
if (inspected.format !== 'png') {
throw new Error('E_IMAGE_ASSET_FORMAT: lossless model preprocessing requires PNG input.');
}
- const sharp = await loadSharp();
- const webp = await sharp(buffer, { failOn: 'error', limitInputPixels: MAX_AREA })
- .webp({ lossless: true, effort: 4 })
- .toBuffer();
+ const { data: webp } = await encodeImage(buffer, {
+ failOn: 'error', limitInputPixels: MAX_AREA,
+ format: 'webp', encodeOptions: { lossless: true, effort: 4 },
+ });
const useWebp = webp.length < buffer.length;
const selected = useWebp ? webp : buffer;
return {
@@ -130,16 +118,16 @@ export async function writeImageAssetBuffer(input: {
}
await inspectImageAssetBuffer(input.buffer);
const quality = input.quality === undefined ? 95 : finiteInteger(input.quality, 'quality', 1, 100);
- const sharp = await loadSharp();
- let pipeline = sharp(input.buffer, { failOn: 'error', limitInputPixels: MAX_AREA });
- if (extension === '.png') pipeline = pipeline.png({ quality });
- else if (extension === '.webp') pipeline = pipeline.webp({ quality });
- else pipeline = pipeline.jpeg({ quality });
+ const encoded = await encodeImage(input.buffer, {
+ failOn: 'error', limitInputPixels: MAX_AREA,
+ format: extension === '.png' ? 'png' : extension === '.webp' ? 'webp' : 'jpeg',
+ encodeOptions: { quality },
+ });
await fs.mkdir(path.dirname(outputAbsPath), { recursive: true });
const temporaryPath = `${outputAbsPath}.${process.pid}.${randomUUID()}.tmp${extension}`;
- let info: Awaited<ReturnType<Sharp['toFile']>>;
+ const info: OutputInfo = encoded.info;
try {
- info = await pipeline.toFile(temporaryPath);
+ await fs.writeFile(temporaryPath, encoded.data);
// A sibling hard link publishes the fully-written inode atomically and,
// unlike rename, refuses to replace an existing path on every supported
// platform. This also closes the race between the caller's uniquify check
diff --git a/src/main/features/video_studio_qa.ts b/src/main/features/video_studio_qa.ts
index a0446946..572142ad 100644
--- a/src/main/features/video_studio_qa.ts
+++ b/src/main/features/video_studio_qa.ts
@@ -10,6 +10,7 @@ import {
resolveApprovedShotReference,
} from './video_studio_source_alignment';
import { projectModelVisibleIssues } from '../util/tool-issue-policy';
+import { encodeImage } from '../util/sharp-runtime';
export type Issue = {
code: string;
@@ -3014,15 +3015,15 @@ export async function writeFrameContactSheet(
// contact sheet as the primary preview. Conversation attachments render PNG
// consistently, whereas an SVG attachment may be shown as a file chip and
// leave the separately published first frame looking like the whole preview.
- const sharpModule = await import('sharp');
- const sharp = sharpModule.default;
- await sharp(Buffer.from(svg), {
+ const { data } = await encodeImage(Buffer.from(svg), {
+ format: 'png',
density: 96,
failOn: 'error',
// librsvg reports density-adjusted pixels (96/72 on some builds), so keep
// a bounded margin above the declared sheet geometry.
limitInputPixels: Math.max(1, Math.min(100_000_000, width * height * 4)),
- }).png().toFile(pngPath);
+ });
+ await fs.writeFile(pngPath, data);
return pngPath;
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 6b63d40c..dda40165 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1603,6 +1603,10 @@ if (!gotLock) {
const kbEmbed = await import('./features/kb_embed');
kbEmbed.closeEmbedder();
} catch (err) { createLogger('kb_embed').warn('close failed', { error: logErrorSummary(err) }); }
+ try {
+ const images = await import('./util/sharp-runtime');
+ images.closeImageRuntime();
+ } catch { createLogger('image-runtime').warn('image runtime shutdown failed'); }
const webAssistSessions = await import('./features/web_assist_session');
await webAssistSessions.flushWebAssistSessions();
await sweepOfficeResidents('quit');
diff --git a/src/main/util/sharp-runtime.ts b/src/main/util/sharp-runtime.ts
new file mode 100644
index 00000000..9647e468
--- /dev/null
+++ b/src/main/util/sharp-runtime.ts
@@ -0,0 +1,48 @@
+import * as path from 'node:path';
+import type { Metadata, OutputInfo, SharpOptions, PngOptions, JpegOptions, WebpOptions } from 'sharp';
+import { PC_ROOT } from '../paths';
+import { createLogger } from '../logger';
+import { bundledNodeExecutable } from './bundled-runtime';
+
+interface ImageRequestOptions extends Pick<SharpOptions, 'failOn' | 'limitInputPixels' | 'density'> {
+ format?: 'png' | 'jpeg' | 'webp';
+ encodeOptions?: PngOptions | JpegOptions | WebpOptions;
+ resize?: { width: number; height: number; fit: 'fill' };
+}
+
+interface ImageClient {
+ request(operation: string, buffer: Buffer, options?: ImageRequestOptions): Promise<any>;
+ close(): void;
+}
+
+let client: ImageClient | undefined;
+function imageClient(): ImageClient {
+ if (!client) {
+ const unpackedRoot = PC_ROOT.replace(/([\\/])app\.asar(?=[\\/]|$)/, '$1app.asar.unpacked');
+ const workerPath = path.join(unpackedRoot, 'bin', 'sharp-worker.cjs');
+ try {
+ const { createSharpClient } = require(workerPath) as {
+ createSharpClient: (options: { nodeExecutable?: string; workerPath: string; onDiagnostic(): void }) => ImageClient;
+ };
+ client = createSharpClient({ nodeExecutable: bundledNodeExecutable(), workerPath,
+ onDiagnostic: () => createLogger('image-runtime').warn('image engine emitted native diagnostics'),
+ });
+ } catch {
+ throw Object.assign(new Error('E_IMAGE_RUNTIME_MISSING: The bundled image runtime is unavailable. Prepare the app runtimes or reinstall Orkas.'), { code: 'E_IMAGE_RUNTIME_MISSING' });
+ }
+ }
+ return client;
+}
+
+export function imageMetadata(buffer: Buffer, options: ImageRequestOptions = {}): Promise<Metadata> {
+ return imageClient().request('metadata', buffer, options);
+}
+
+export function encodeImage(buffer: Buffer, options: ImageRequestOptions): Promise<{ data: Buffer; info: OutputInfo }> {
+ return imageClient().request('encode', buffer, options);
+}
+
+export function closeImageRuntime(): void {
+ client?.close();
+ client = undefined;
+}
diff --git a/test/gui/inspect-canary-logs.mjs b/test/gui/inspect-canary-logs.mjs
index 3436e25d..80c93936 100644
--- a/test/gui/inspect-canary-logs.mjs
+++ b/test/gui/inspect-canary-logs.mjs
@@ -1,13 +1,10 @@
// Linux source builds retain these diagnostics in the successful main baseline
// (GitHub Actions run 34550610580). They are warnings, not clean-runtime evidence.
-// Sharp documents the GLib collision at https://sharp.pixelplumbing.com/install/#electron-and-linux.
+// Application sharp operations now run outside Electron; GLib collisions fail.
const chromium = String.raw`\[\d+:\d+/\d+\.\d+:ERROR:`;
const knownLinux = [
['dbus-address', new RegExp(`^${chromium}dbus/bus\\.cc:\\d+\\] Failed to connect to the bus: Could not parse server address: Unknown address type \\(examples of valid types are "tcp" and on UNIX "unix"\\)$`), 20],
['dbus-owner', new RegExp(`^${chromium}dbus/object_proxy\\.cc:\\d+\\] Failed to call method: org\\.freedesktop\\.DBus\\.NameHasOwner: object_path= /org/freedesktop/DBus: unknown error type: ?$`), 10],
- ['sharp-linux', /^\(node:\d+\) \[SharpElectronLinux\] Warning: Binaries provided by Electron for use on Linux may be incompatible with sharp - see https:\/\/sharp\.pixelplumbing\.com\/install#electron-and-linux$/, 1],
- ['sharp-trace', /^\(Use `electron --trace-warnings \.\.\.` to show where the warning was created\)$/, 1],
- ['glib-sharp', new RegExp(`^${chromium}content/browser/browser_main_loop\\.cc:\\d+\\] GLib-GObject: g_object_(?:ref|unref): assertion 'G_IS_OBJECT \\(object\\)' failed$`), 100],
['system-font-mtime', /^Unable to revert mtime: \/usr\/share\/fonts(?:\/truetype(?:\/(?:dejavu|lato|liberation|noto))?)?$/, 20],
];
@@ -22,8 +19,6 @@ export function reviewInspectStderr(stderr, platform = process.platform) {
warnings[name] = (warnings[name] || 0) + 1;
if (warnings[name] > limit) unexpected++;
}
- // A trace hint or GLib error without the specific Sharp warning is unexplained.
- if (!warnings['sharp-linux']) unexpected += (warnings['glib-sharp'] || 0) + (warnings['sharp-trace'] || 0);
return { warnings, unexpected };
}
diff --git a/test/main/model/core-agent/video-studio-state-tool.test.ts b/test/main/model/core-agent/video-studio-state-tool.test.ts
index a7821d6a..8fdf58ff 100644
--- a/test/main/model/core-agent/video-studio-state-tool.test.ts
+++ b/test/main/model/core-agent/video-studio-state-tool.test.ts
@@ -149,7 +149,8 @@ vi.mock('../../../../src/main/features/tts_capabilities', async (importOriginal)
};
});
-vi.mock('../../../../src/main/util/bundled-runtime', () => ({
+vi.mock('../../../../src/main/util/bundled-runtime', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../../../src/main/util/bundled-runtime')>(),
bundledFfmpegPaths: () => ({ ffmpeg: process.execPath, ffprobe: process.execPath }),
bundledWhisperPaths: () => ({ cli: process.execPath, model: process.execPath }),
}));
diff --git a/test/main/util/ensure-sqlite-electron-abi.test.ts b/test/main/util/ensure-sqlite-electron-abi.test.ts
index 22870bd2..f027718e 100644
--- a/test/main/util/ensure-sqlite-electron-abi.test.ts
+++ b/test/main/util/ensure-sqlite-electron-abi.test.ts
@@ -23,6 +23,17 @@ const OPTIONS = {
};
describe('SQLite Electron ABI repair orchestration', () => {
+ it.each([
+ ['successful rebuild with an unloadable addon', 1, 0],
+ ['interrupted rebuild after successful prebuild extraction', 0, null],
+ ])('rejects %s instead of allowing startup', (_label, prebuildStatus, rebuildStatus) => {
+ const statuses = [1, prebuildStatus, 1, rebuildStatus, 1, 1];
+ const spawn = vi.fn(() => ({ status: statuses.shift(), stderr: 'ABI mismatch' }));
+ const logError = vi.fn();
+ expect(ensureSqliteElectronAbi({ ...OPTIONS, spawn, logError })).not.toBe(0);
+ expect(logError).toHaveBeenCalledWith(expect.stringContaining('Electron ABI probe failed'));
+ });
+
it('adds macOS SDK C++ headers without leaking Electron-as-Node into rebuild helpers', () => {
expect(nativeBuildEnvironment({
env: {
diff --git a/test/main/util/inspect-canary-logs.test.ts b/test/main/util/inspect-canary-logs.test.ts
index ba15639b..eabc194e 100644
--- a/test/main/util/inspect-canary-logs.test.ts
+++ b/test/main/util/inspect-canary-logs.test.ts
@@ -9,16 +9,16 @@ const trace = '(Use `electron --trace-warnings ...` to show where the warning wa
describe('GUI canary process diagnostics', () => {
it('reports reviewed Linux baseline diagnostics separately from functional success', () => {
- const report = reviewInspectStderr([dbus, owner, sharp, trace, glib, 'Unable to revert mtime: /usr/share/fonts/truetype/noto'].join('\r\n'), 'linux');
+ const report = reviewInspectStderr([dbus, owner, 'Unable to revert mtime: /usr/share/fonts/truetype/noto'].join('\r\n'), 'linux');
expect(report).toEqual({ unexpected: 0, warnings: {
- 'dbus-address': 1, 'dbus-owner': 1, 'sharp-linux': 1, 'sharp-trace': 1, 'glib-sharp': 1, 'system-font-mtime': 1,
+ 'dbus-address': 1, 'dbus-owner': 1, 'system-font-mtime': 1,
} });
expect(inspectCanaryExitCode(0, false, report)).toBe(0);
expect(inspectCanaryExitCode(2, false, report)).toBe(2);
expect(inspectCanaryExitCode(0, true, report)).toBe(1);
});
- it.each(['darwin', 'win32'])('keeps Linux diagnostics fatal on %s', platform => {
+ it.each(['darwin', 'win32', 'linux'])('rejects an Electron/sharp collision on %s', platform => {
expect(reviewInspectStderr(sharp, platform).unexpected).toBe(1);
});
@@ -33,7 +33,7 @@ describe('GUI canary process diagnostics', () => {
});
it('rejects an unbounded warning loop and unexplained GLib or trace output', () => {
- expect(reviewInspectStderr(`${sharp}\n${Array(101).fill(glib).join('\n')}`, 'linux').unexpected).toBe(1);
+ expect(reviewInspectStderr(Array(21).fill(dbus).join('\n'), 'linux').unexpected).toBe(1);
expect(reviewInspectStderr(glib, 'linux').unexpected).toBe(1);
expect(reviewInspectStderr(trace, 'linux').unexpected).toBe(1);
});
diff --git a/test/main/util/linux-source-dependencies.test.ts b/test/main/util/linux-source-dependencies.test.ts
index 2eedf90d..7150f3d9 100644
--- a/test/main/util/linux-source-dependencies.test.ts
+++ b/test/main/util/linux-source-dependencies.test.ts
@@ -86,7 +86,7 @@ describe('Linux source dependency contract', () => {
})).toThrow(/glibc 2\.34\+ is required/);
expect(() => assertLinuxHost({
platform: 'linux', arch: 'x64', nodeVersion: '18.20.0', glibcVersionRuntime: '2.39',
- })).toThrow(/Node\.js 20\+ is required/);
+ })).toThrow(/Node\.js 22\.12\.0\+ is required/);
expect(() => assertLinuxHost({
platform: 'linux', arch: 'riscv64', nodeVersion: '24.17.0', glibcVersionRuntime: '2.39',
})).toThrow(/support x64 and arm64/);
@@ -174,7 +174,7 @@ describe('Linux source dependency contract', () => {
);
const launcher = fs.readFileSync(path.join(process.cwd(), 'run.sh'), 'utf8');
- expect(launcher).toContain('Node.js 20+ is required to bootstrap the source checkout');
+ expect(launcher).toContain('Node.js 22.12+ is required to bootstrap the source checkout');
expect(launcher).toContain('verify-linux-source-dependencies.cjs\" --host-only');
});
});
diff --git a/test/main/util/sharp-runtime.test.ts b/test/main/util/sharp-runtime.test.ts
new file mode 100644
index 00000000..49ac059d
--- /dev/null
+++ b/test/main/util/sharp-runtime.test.ts
@@ -0,0 +1,191 @@
+import { fork, type ChildProcess } from 'node:child_process';
+import { once } from 'node:events';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import ts from 'typescript';
+import { bundledNodeExecutable } from '../../../src/main/util/bundled-runtime';
+
+const { createSharpClient, probeImageRuntime, processImage } = require('../../../bin/sharp-worker.cjs');
+const worker = path.join(process.cwd(), 'bin/sharp-worker.cjs');
+const node = bundledNodeExecutable();
+const clients: Array<{ close(): void }> = [];
+const children: ChildProcess[] = [];
+const temporary: string[] = [];
+const input = (width = 4, height = 3) => Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><rect width="100%" height="100%" fill="#14283c"/></svg>`);
+
+function client(options: Record<string, unknown> = {}) {
+ const instance = createSharpClient({ nodeExecutable: node, workerPath: worker,
+ spawn: (...args: Parameters<typeof fork>) => { const child = fork(...args); children.push(child); return child; },
+ ...options });
+ clients.push(instance);
+ return instance;
+}
+
+function fixture(source: string): string {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-image-worker-'));
+ temporary.push(root);
+ const file = path.join(root, 'worker.cjs');
+ fs.writeFileSync(file, source);
+ return file;
+}
+
+afterEach(async () => {
+ const exiting = children.filter(c => c.exitCode === null && c.signalCode === null)
+ .map(c => once(c, 'exit').catch(() => undefined));
+ for (const instance of clients.splice(0)) instance.close();
+ await Promise.all(exiting);
+ children.splice(0);
+ for (const dir of temporary.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+});
+
+describe('isolated bundled-Node image processing', () => {
+ it('preserves image dimensions and format across concurrent calls in a reused process', async () => {
+ expect(node).toBeTruthy();
+ const images = client();
+ const results = await Promise.all([3, 7, 11].map(width => images.request('encode', input(width, 5), { format: 'png' })));
+ for (const [index, result] of results.entries()) {
+ expect(result.data.subarray(0, 8)).toEqual(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
+ expect(result.data.readUInt32BE(16)).toBe([3, 7, 11][index]);
+ expect(result.data.readUInt32BE(20)).toBe(5);
+ expect(await images.request('metadata', result.data)).toMatchObject({ format: 'png', height: 5 });
+ }
+ expect(children).toHaveLength(1);
+ for (const format of ['jpeg', 'webp']) {
+ const result = await images.request('encode', input(), { format });
+ expect(await images.request('metadata', result.data)).toMatchObject({ format, width: 4, height: 3 });
+ }
+ });
+
+ it('renders SVG contact-sheet text in stock Node without native diagnostics', async () => {
+ let stderr = '';
+ const images = client({ spawn: (...args: Parameters<typeof fork>) => {
+ const child = fork(...args);
+ child.stderr!.on('data', chunk => { stderr += String(chunk); });
+ children.push(child);
+ return child;
+ } });
+ const svg = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="320" height="80"><rect width="320" height="80" fill="white"/><text x="12" y="48" font-family="sans-serif" font-size="24">Contact sheet</text></svg>');
+ const result = await images.request('encode', svg, { format: 'png', density: 96 });
+ expect(result.data.readUInt32BE(16)).toBeGreaterThanOrEqual(320);
+ expect(stderr).toBe('');
+ });
+
+ it('surfaces invalid images and remains usable without restarting or replaying the failed request', async () => {
+ const images = client();
+ await expect(images.request('metadata', Buffer.from('not-an-image'))).rejects.toThrow('E_IMAGE_PROCESS');
+ expect(await images.request('metadata', input())).toMatchObject({ width: 4, height: 3 });
+ expect(children).toHaveLength(1);
+ });
+
+ it('fails before spawning when the bundled Node runtime is missing', async () => {
+ const spawn = vi.fn();
+ await expect(client({ nodeExecutable: undefined, spawn }).request('metadata', input())).rejects.toThrow(/E_IMAGE_RUNTIME_MISSING.*reinstall/);
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['crash', "process.on('message', () => process.exit(9));", 'E_IMAGE_RUNTIME_EXIT'],
+ ['timeout', "process.on('message', () => {});", 'E_IMAGE_RUNTIME_TIMEOUT'],
+ ])('rejects a %s without automatic replay, then recovers on a new caller request', async (_name, source, code) => {
+ const broken = fixture(source);
+ let starts = 0;
+ const images = client({ timeoutMs: 2000, spawn: (_file: string, args: string[], options: Parameters<typeof fork>[2]) => {
+ const child = fork(starts++ === 0 ? broken : worker, args, options);
+ children.push(child);
+ return child;
+ } });
+ await expect(images.request('metadata', input())).rejects.toThrow(code);
+ expect(starts).toBe(1);
+ expect(await images.request('metadata', input())).toMatchObject({ width: 4, height: 3 });
+ expect(starts).toBe(2);
+ });
+
+ it('never loads sharp in the Electron caller', async () => {
+ expect(process.versions.electron).toBeTruthy();
+ await expect(processImage('metadata', input())).rejects.toThrow('E_IMAGE_RUNTIME_ELECTRON');
+ });
+
+ it('reports a native warning without private text or discarding a valid image', async () => {
+ const onDiagnostic = vi.fn();
+ const images = client({ onDiagnostic, workerPath: fixture("process.on('message', msg => { process.stderr.write('/private/image.png: native warning'); setTimeout(() => process.send({id:msg.id,ok:true,result:{format:'png',width:4,height:3}}), 25); });") });
+ expect(await images.request('metadata', input())).toMatchObject({ width: 4 });
+ expect(await images.request('metadata', input())).toMatchObject({ width: 4 });
+ expect(onDiagnostic).toHaveBeenCalledExactlyOnceWith();
+ });
+
+ it('rejects an incomplete success response instead of accepting an empty image', async () => {
+ const images = client({ workerPath: fixture("process.on('message', msg => process.send({id:msg.id,ok:true,result:{}}));") });
+ await expect(images.request('encode', input(), { format: 'png' })).rejects.toThrow('E_IMAGE_PROCESS');
+ });
+
+ it('releases an idle process and starts a fresh worker for the next image', async () => {
+ const images = client({ idleMs: 30 });
+ expect(await images.request('metadata', input())).toMatchObject({ width: 4 });
+ await once(children[0], 'exit');
+ expect(await images.request('metadata', input(8))).toMatchObject({ width: 8 });
+ expect(children).toHaveLength(2);
+ });
+
+ it('rejects pending work when the application closes the worker', async () => {
+ const images = client({ workerPath: fixture("process.on('message', () => {});") });
+ const result = images.request('metadata', input());
+ const rejected = expect(result).rejects.toThrow('E_IMAGE_RUNTIME_CLOSED');
+ images.close();
+ await rejected;
+ });
+
+ it('loads the shipped dependency closure beside app.asar without checkout or Electron resolution', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-packaged-image-'));
+ temporary.push(root);
+ const unpacked = path.join(root, 'app.asar.unpacked');
+ const entry = path.join(unpacked, 'bin', 'sharp-worker.cjs');
+ fs.mkdirSync(path.dirname(entry), { recursive: true });
+ fs.copyFileSync(worker, entry);
+ const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8'));
+ const gate = require('../../../bin/packaged-entrypoint-gate.cjs');
+ for (const glob of gate.PACKAGED_IMAGE_RUNTIME_UNPACK_GLOBS) {
+ expect(pkg.build.files).toContain(glob);
+ expect(pkg.build.asarUnpack).toContain(glob);
+ const relative = glob.slice(0, -5);
+ fs.cpSync(path.join(process.cwd(), relative), path.join(unpacked, relative), { recursive: true });
+ }
+ expect(probeImageRuntime(node, entry)).toMatchObject({ status: 'passed', sharp: 'png-2x2', electron: null, arch: process.arch });
+ fs.rmSync(path.join(unpacked, 'node_modules', '@img'), { recursive: true });
+ expect(() => probeImageRuntime(node, entry)).toThrow(/E_IMAGE_RUNTIME_VERIFY.*reinstall/);
+ });
+
+ it.each(['files', 'asarUnpack'])('rejects an incomplete image dependency closure in build.%s', field => {
+ const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8'));
+ const gate = require('../../../bin/packaged-entrypoint-gate.cjs');
+ for (const glob of gate.PACKAGED_IMAGE_RUNTIME_UNPACK_GLOBS) {
+ const build = { ...pkg.build, [field]: pkg.build[field].filter((value: string) => value !== glob) };
+ expect(() => gate.verifyBuildFilesConfig(build)).toThrow('must include');
+ }
+ });
+
+ it('keeps every application sharp import behind the isolated image boundary', () => {
+ const offenders: string[] = [];
+ function visitFiles(directory: string) {
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
+ const file = path.join(directory, entry.name);
+ if (entry.isDirectory()) visitFiles(file);
+ else if (/\.(ts|js|mjs|cjs)$/.test(entry.name)) {
+ const source = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
+ function visit(node: ts.Node) {
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)
+ && node.moduleSpecifier.text === 'sharp' && !node.importClause?.isTypeOnly) offenders.push(file);
+ if (ts.isCallExpression(node) && node.arguments.length && ts.isStringLiteral(node.arguments[0])
+ && node.arguments[0].text === 'sharp'
+ && (node.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) offenders.push(file);
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ }
+ }
+ }
+ visitFiles(path.join(process.cwd(), 'src/main'));
+ expect(offenders.map(file => path.relative(process.cwd(), file))).toEqual([]);
+ });
+});
diff --git a/test/main/util/verify-native-dependencies.test.ts b/test/main/util/verify-native-dependencies.test.ts
new file mode 100644
index 00000000..39450118
--- /dev/null
+++ b/test/main/util/verify-native-dependencies.test.ts
@@ -0,0 +1,130 @@
+import { createRequire } from 'node:module';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import vm from 'node:vm';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const requirePackage = createRequire(path.join(process.cwd(), 'package.json'));
+const { assertBootstrapNode, verifySharpRuntime, verifyNativeDependencies, PROBE_TIMEOUT_MS } = requirePackage('./scripts/verify-native-dependencies.cjs');
+const { probeSqlite } = requirePackage('./scripts/native-dependency-probe.cjs');
+const temporary: string[] = [];
+const linuxSharpWarning = "(process:123): GLib-GObject-CRITICAL **: 03:37:35.946: g_object_ref: assertion 'G_IS_OBJECT (object)' failed\n(node:123) [SharpElectronLinux] Warning: Binaries provided by Electron for use on Linux may be incompatible with sharp - see https://sharp.pixelplumbing.com/install#electron-and-linux\n(Use `electron --trace-warnings ...` to show where the warning was created)\n";
+afterEach(() => { for (const dir of temporary.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); });
+
+describe('source native dependency readiness', () => {
+ it.each(['20.19.0', '22.11.0', 'invalid', '22.12', '22.12.0-rc.1'])('rejects unsupported bootstrap Node %s before installation', version => {
+ expect(() => assertBootstrapNode(version)).toThrow(/Node.js 22.12.0\+.*Node.js 24 LTS/);
+ });
+ it.each(['22.12.0', '22.23.2', '24.18.0'])('accepts supported bootstrap Node %s', version => {
+ expect(() => assertBootstrapNode(version)).not.toThrow();
+ });
+
+ it('performs SQL/vector operations in Electron and PNG operations in bundled Node', async () => {
+ expect(process.versions.electron).toBeTruthy();
+ expect(await probeSqlite(requirePackage)).toMatchObject({ vectorDistance: 5 });
+ expect(verifySharpRuntime()).toMatchObject({ sharp: 'png-2x2', electron: null });
+ });
+
+ it('runs the complete check in the installed Electron child', () => {
+ expect(verifyNativeDependencies()).toMatchObject({ status: 'passed', sharp: 'png-2x2', vectorDistance: 5 });
+ });
+
+ it('closes an in-memory database and identifies a missing vector extension without exposing paths', async () => {
+ const close = vi.fn();
+ const req = (name: string) => {
+ if (name === 'better-sqlite3') return class {
+ close = close;
+ prepare() { return { get: () => ({ answer: 42 }) }; }
+ loadExtension() { throw new Error('/private/user/library/vec0.dll'); }
+ };
+ return { getLoadablePath: () => '/private/user/library/vec0.dll' };
+ };
+ await expect(probeSqlite(req)).rejects.toThrow(/sqlite-vec.*native:repair/);
+ expect(close).toHaveBeenCalledOnce();
+ await expect(probeSqlite(req)).rejects.not.toThrow('/private');
+ });
+
+ it('rejects dependency version drift before launching any child', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-native-version-'));
+ temporary.push(root);
+ fs.writeFileSync(path.join(root, 'package.json'), '{}');
+ fs.writeFileSync(path.join(root, 'package-lock.json'), JSON.stringify({ packages: { 'node_modules/electron': { version: '42.8.0' } } }));
+ const spawn = vi.fn();
+ expect(() => verifyNativeDependencies({ packageRoot: root, spawn })).toThrow(/electron.*native:repair/);
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it('reports a missing lockfile with recovery instructions and no filesystem path', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-native-lock-'));
+ temporary.push(root);
+ const spawn = vi.fn();
+ expect(() => verifyNativeDependencies({ packageRoot: root, spawn })).toThrow(/restore.*lockfile.*native:repair/);
+ expect(() => verifyNativeDependencies({ packageRoot: root, spawn })).not.toThrow(root);
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['empty success', { status: 0, stdout: '' }],
+ ['incomplete success', { status: 0, stdout: '{"status":"passed"}' }],
+ ['timeout', { status: null, error: { code: 'ETIMEDOUT' } }],
+ ['loader failure', { status: 1, stderr: '/private/location: missing DLL' }],
+ ['known warning without functional proof', { status: 0, stdout: '{"status":"passed"}', stderr: linuxSharpWarning }],
+ ])('rejects %s with an actionable error', (_label, result) => {
+ const spawn = vi.fn(() => result);
+ expect(() => verifyNativeDependencies({ spawn })).toThrow(/native:repair/);
+ expect(() => verifyNativeDependencies({ spawn })).not.toThrow('/private');
+ expect(spawn.mock.calls[0][2]).toMatchObject({ timeout: PROBE_TIMEOUT_MS, env: { ELECTRON_RUN_AS_NODE: '1' } });
+ });
+
+ it('rejects a missing bundled Node without falling back to Electron', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-image-runtime-'));
+ temporary.push(root);
+ const spawn = vi.fn();
+ expect(() => verifySharpRuntime({ packageRoot: root, spawn })).toThrow(/bundled Node.*native:repair/);
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['missing functional proof', { status: 0, stdout: '{"status":"passed"}' }],
+ ['native diagnostic', { status: 0, stderr: linuxSharpWarning }],
+ ['loader failure', { status: 1, stderr: '/private/image.dll: missing library' }],
+ ['timeout', { status: null, error: { code: 'ETIMEDOUT' } }],
+ ])('rejects image runtime %s without exposing private diagnostics', (_label, result) => {
+ const spawn = vi.fn(() => result);
+ expect(() => verifySharpRuntime({ spawn })).toThrow(/native:repair/);
+ expect(() => verifySharpRuntime({ spawn })).not.toThrow('/private');
+ expect(spawn.mock.calls[0][2].env).not.toHaveProperty('ELECTRON_RUN_AS_NODE');
+ expect(spawn.mock.calls[0][2].timeout).toBe(PROBE_TIMEOUT_MS);
+ });
+
+ it('stops development preparation before reporting readiness when the native check fails', () => {
+ const calls: string[] = [];
+ const output: string[] = [];
+ const exit = vi.fn(() => { throw new Error('exit'); });
+ const entry = path.join(process.cwd(), 'scripts/ensure-dev-dependencies.cjs');
+ const module = { exports: {} };
+ const req: any = (name: string) => name === 'node:child_process'
+ ? { spawnSync: (_node: string, args: string[]) => {
+ const script = path.basename(args[0]); calls.push(script);
+ return { status: script === 'verify-native-dependencies.cjs' && !args.includes('--host-only') ? 1 : 0 };
+ } } : requirePackage(name.startsWith('.') ? path.resolve(path.dirname(entry), name) : name);
+ req.main = module;
+ expect(() => vm.runInNewContext(fs.readFileSync(entry, 'utf8'), {
+ require: req, module, __dirname: path.dirname(entry),
+ process: { execPath: process.execPath, env: {}, platform: 'win32', arch: 'x64', exit },
+ console: { log: (s: string) => output.push(s), error: (s: string) => output.push(s) },
+ })).toThrow('exit');
+ expect(calls).toContain('ensure-sqlite-electron-abi.mjs');
+ expect(calls.at(-1)).toBe('verify-native-dependencies.cjs');
+ expect(output.join('\n')).toContain('native dependencies failed');
+ expect(output.join('\n')).not.toContain('built-in dependencies ready');
+ });
+
+ it('keeps one repair command guarded before install and verified afterward', () => {
+ const pkg = requirePackage('./package.json');
+ expect(pkg.engines.node).toBe('>=22.12.0');
+ expect(pkg.scripts['native:repair']).toBe('node scripts/verify-native-dependencies.cjs --host-only && npm install --include=optional --no-save && node bin/ensure-runtime.cjs --kind node && npm run native:check');
+ expect(pkg.scripts['native:check']).toBe('node scripts/verify-native-dependencies.cjs');
+ });
+});