Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Check the packaged helper where CI packages the app (#5289)

Nick Gomezedb12315d888
diff --git a/knip.config.ts b/knip.config.ts
index be41ab16c..37d9ce912 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -145,11 +145,15 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: ['yjs'],
+ ignoreDependencies: [
+ 'yjs',
+ ],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index 8a60e5826..a28cc2b18 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 6fcdc23f2..4fc2c11f9 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 40b5cdfd6..9f2f6feb6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 93666af70..2a085742b 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 867598d34..878d5196b 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 0970ac12f..4ada3cf26 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index b632185e1..cbe2b705f 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,3 +1,4 @@
+
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index c530ce4ba..89bc9b4d9 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index d3767adc9..a78aeb0e4 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,3 +1,4 @@
+
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index b076f955c..e7cc69c3f 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 7935e35f8..9ddcd0730 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index fc267cbea..fb0ba5a7c 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/desktop/build/helper-bundle/Info.plist b/packages/desktop/build/helper-bundle/Info.plist
index fc4bd772a..12f62d82f 100644
--- a/packages/desktop/build/helper-bundle/Info.plist
+++ b/packages/desktop/build/helper-bundle/Info.plist
@@ -6,7 +6,8 @@
boot and silently SIGTRAPs (exit 133, empty stderr) unless it is
`<productName> Helper`, so `CFBundleExecutable` carries that name
(Stable here; `scripts/desktop-variant-config.ts` rewrites it for Beta).
- Runtime guard: `tests/integration/packaged-helper-runs-as-node.test.ts`.
+ Runtime guard: `scripts/assert-packaged-helper-runs-as-node.mjs`, run in CI against the
+ packaged app.
`LSUIElement=true` is the Dock-suppression key that PR #1290 was
written to introduce — without it, LaunchServices keys on the spawn
diff --git a/packages/desktop/scripts/assert-packaged-helper-runs-as-node.mjs b/packages/desktop/scripts/assert-packaged-helper-runs-as-node.mjs
new file mode 100755
index 000000000..6deba0377
--- /dev/null
+++ b/packages/desktop/scripts/assert-packaged-helper-runs-as-node.mjs
@@ -0,0 +1,149 @@
+#!/usr/bin/env node
+
+import { spawnSync } from 'node:child_process';
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { posix as pathPosix } from 'node:path';
+import { resolveHelperBundleBinary } from '@inkeep/open-knowledge-core/helper-bundle';
+
+export const HELPER_PROBE_TIMEOUT_MS = 10_000;
+
+const HELPER_PROBE_SOURCE = 'console.log("ok-helper-node-mode", process.versions.node)';
+const NODE_MODE_LINE = /ok-helper-node-mode\s+(\d+\.\d+\.\d+)/;
+
+function listDir(path) {
+ try {
+ return readdirSync(path);
+ } catch (error) {
+ if (error.code === 'ENOENT') return [];
+ throw error;
+ }
+}
+
+function bundleExecutable(bundle) {
+ const plist = pathPosix.join(bundle, 'Contents', 'Info.plist');
+ if (!existsSync(plist)) return null;
+ const name = readFileSync(plist, 'utf8').match(
+ /<key>CFBundleExecutable<\/key>\s*<string>([^<]*)<\/string>/,
+ )?.[1];
+ return name === undefined ? null : pathPosix.join(bundle, 'Contents', 'MacOS', name);
+}
+
+export function findPackagedApps(searchRoot) {
+ return listDir(searchRoot)
+ .filter((name) => name.startsWith('mac-'))
+ .flatMap((subdir) =>
+ listDir(pathPosix.join(searchRoot, subdir))
+ .filter((name) => name.endsWith('.app'))
+ .map((name) => pathPosix.join(searchRoot, subdir, name)),
+ )
+ .sort();
+}
+
+export function probeHelper(helper) {
+ return spawnSync(helper, ['-e', HELPER_PROBE_SOURCE], {
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
+ encoding: 'utf8',
+ timeout: HELPER_PROBE_TIMEOUT_MS,
+ });
+}
+
+export function helperProbeProblems(result) {
+ if (result.error && result.error.code !== 'ETIMEDOUT') {
+ return [`it could not be run: ${result.error.message}`];
+ }
+ const problems = [];
+ if (result.error) problems.push(`it did not exit within ${HELPER_PROBE_TIMEOUT_MS} ms`);
+ else if (result.signal !== null) problems.push(`it was killed by ${result.signal}`);
+ else if (result.status !== 0) problems.push(`it exited ${result.status}`);
+ if (!NODE_MODE_LINE.test(result.stdout)) {
+ problems.push(
+ `its stdout lacks the "ok-helper-node-mode <version>" line: ${JSON.stringify(result.stdout.slice(-200))}`,
+ );
+ }
+ if (result.stderr !== '') {
+ problems.push(`it wrote to stderr: ${JSON.stringify(result.stderr.slice(-400))}`);
+ }
+ return problems;
+}
+
+export function checkPackagedApp(app, probe = probeHelper) {
+ const executable = bundleExecutable(app);
+ if (executable === null) {
+ return { app, problems: [`${app} has no Contents/Info.plist naming its CFBundleExecutable`] };
+ }
+ const frameworks = pathPosix.join(app, 'Contents', 'Frameworks');
+ const servers = listDir(frameworks).filter((name) => name.endsWith(' Server.app'));
+ if (servers.length !== 1) {
+ return {
+ app,
+ problems: [
+ `${app} holds ${servers.length} "* Server.app" helper bundles in Contents/Frameworks, ` +
+ `not exactly one: ${servers.join(', ') || 'none'}`,
+ ],
+ };
+ }
+ const server = pathPosix.join(frameworks, servers[0]);
+ const helper = bundleExecutable(server);
+ if (helper === null) {
+ return {
+ app,
+ problems: [`${server} has no Contents/Info.plist naming its CFBundleExecutable`],
+ };
+ }
+ if (!existsSync(helper)) {
+ return {
+ app,
+ helper,
+ problems: [
+ `${server} names ${helper}, which does not exist: afterPack.mjs clones Electron's helper ` +
+ 'stub into that slot when it packages for darwin',
+ ],
+ };
+ }
+ const problems = [];
+ const resolved = resolveHelperBundleBinary(executable);
+ if (resolved !== helper) {
+ problems.push(
+ `the spawn site's resolver maps ${executable} to ${resolved}, not to the packaged helper ${helper}`,
+ );
+ }
+ const result = probe(helper);
+ for (const problem of helperProbeProblems(result)) {
+ problems.push(`${helper} under ELECTRON_RUN_AS_NODE=1: ${problem}`);
+ }
+ return { app, helper, nodeVersion: result.stdout?.match(NODE_MODE_LINE)?.[1], problems };
+}
+
+function main([searchRoot, label = searchRoot]) {
+ if (!searchRoot) {
+ console.error('usage: assert-packaged-helper-runs-as-node.mjs <search-root> [label]');
+ return 2;
+ }
+ const apps = findPackagedApps(searchRoot);
+ if (apps.length === 0) {
+ console.error(
+ `::error::${label}: no packaged mac-*/*.app under ${searchRoot}, so the detached-server ` +
+ 'helper was not checked. Package the macOS app (electron-builder --mac --dir) and point ' +
+ 'this check at its output directory.',
+ );
+ return 1;
+ }
+ let failed = false;
+ for (const app of apps) {
+ const { helper, nodeVersion, problems } = checkPackagedApp(app);
+ if (problems.length > 0) {
+ failed = true;
+ for (const problem of problems) console.error(`::error::${label}: ${problem}`);
+ } else {
+ console.log(
+ `packaged helper OK (${label}): ${helper} runs as Node ${nodeVersion} under ` +
+ 'ELECTRON_RUN_AS_NODE=1, and the spawn-site resolver lands on it',
+ );
+ }
+ }
+ if (failed) return 1;
+ console.log(`packaged helper: ${apps.length} app(s) checked under ${searchRoot}`);
+ return 0;
+}
+
+if (import.meta.main) process.exitCode = main(process.argv.slice(2));
diff --git a/packages/desktop/scripts/assert-packaged-helper-runs-as-node.test.mjs b/packages/desktop/scripts/assert-packaged-helper-runs-as-node.test.mjs
new file mode 100644
index 000000000..2b24fa079
--- /dev/null
+++ b/packages/desktop/scripts/assert-packaged-helper-runs-as-node.test.mjs
@@ -0,0 +1,274 @@
+import { spawnSync } from 'node:child_process';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { posix as pathPosix } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import {
+ checkPackagedApp,
+ findPackagedApps,
+ HELPER_PROBE_TIMEOUT_MS,
+ helperProbeProblems,
+ probeHelper,
+} from './assert-packaged-helper-runs-as-node.mjs';
+
+const SCRIPT = fileURLToPath(new URL('./assert-packaged-helper-runs-as-node.mjs', import.meta.url));
+const NODE_MODE_HELPER = `#!/bin/sh\nexec "${process.execPath}" "$@"\n`;
+const DYLD_FAILING_HELPER =
+ '#!/bin/sh\necho "dyld[1]: Library not loaded: @rpath/Electron Framework.framework/Electron Framework" >&2\nexit 1\n';
+const passingProbe = () => ({
+ status: 0,
+ signal: null,
+ stdout: 'ok-helper-node-mode 24.18.0\n',
+ stderr: '',
+});
+
+let root;
+
+beforeEach(() => {
+ root = mkdtempSync(pathPosix.join(tmpdir(), 'assert-packaged-helper-'));
+});
+
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+function plist(executable) {
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0">\n<dict>\n <key>CFBundleExecutable</key>\n <string>${executable}</string>\n</dict>\n</plist>\n`;
+}
+
+function plantApp({
+ arch = 'mac-arm64',
+ product = 'OpenKnowledge',
+ servers = [product],
+ helperName = `${product} Helper`,
+ helper = NODE_MODE_HELPER,
+ helperMode = 0o755,
+} = {}) {
+ const app = pathPosix.join(root, arch, `${product}.app`);
+ mkdirSync(pathPosix.join(app, 'Contents', 'MacOS'), { recursive: true });
+ writeFileSync(pathPosix.join(app, 'Contents', 'Info.plist'), plist(product));
+ writeFileSync(pathPosix.join(app, 'Contents', 'MacOS', product), '');
+ for (const server of servers) {
+ const bundle = pathPosix.join(app, 'Contents', 'Frameworks', `${server} Server.app`);
+ mkdirSync(pathPosix.join(bundle, 'Contents', 'MacOS'), { recursive: true });
+ writeFileSync(pathPosix.join(bundle, 'Contents', 'Info.plist'), plist(helperName));
+ if (helper !== null) {
+ const binary = pathPosix.join(bundle, 'Contents', 'MacOS', helperName);
+ writeFileSync(binary, helper);
+ chmodSync(binary, helperMode);
+ }
+ }
+ return app;
+}
+
+function helperOf(app, server, helperName) {
+ return pathPosix.join(
+ app,
+ 'Contents',
+ 'Frameworks',
+ `${server} Server.app`,
+ 'Contents',
+ 'MacOS',
+ helperName,
+ );
+}
+
+function runCli(...args) {
+ return spawnSync(process.execPath, ['--conditions=development', SCRIPT, ...args], {
+ encoding: 'utf8',
+ });
+}
+
+describe('findPackagedApps', () => {
+ test('finds every mac-*/*.app and nothing else', () => {
+ const stable = plantApp();
+ const beta = plantApp({ arch: 'mac-universal', product: 'OpenKnowledge Beta' });
+ mkdirSync(pathPosix.join(root, 'linux-unpacked', 'OpenKnowledge.app'), { recursive: true });
+ expect(findPackagedApps(root)).toEqual([stable, beta].sort());
+ });
+
+ test('finds nothing under a missing root', () => {
+ expect(findPackagedApps(pathPosix.join(root, 'absent'))).toEqual([]);
+ });
+});
+
+describe('checkPackagedApp', () => {
+ test('passes a Stable app whose helper the spawn-site resolver lands on', () => {
+ expect(checkPackagedApp(plantApp(), passingProbe).problems).toEqual([]);
+ });
+
+ test('passes a Beta app whose helper carries the Beta product name', () => {
+ const app = plantApp({ product: 'OpenKnowledge Beta' });
+ expect(checkPackagedApp(app, passingProbe).problems).toEqual([]);
+ });
+
+ test('refuses a Beta app whose helper carries the Stable names', () => {
+ const app = plantApp({
+ product: 'OpenKnowledge Beta',
+ servers: ['OpenKnowledge'],
+ helperName: 'OpenKnowledge Helper',
+ });
+ expect(checkPackagedApp(app, passingProbe).problems).toEqual([
+ expect.stringContaining("the spawn site's resolver maps"),
+ ]);
+ });
+
+ test('refuses an app with no Server.app helper bundle', () => {
+ const app = plantApp({ servers: [] });
+ expect(checkPackagedApp(app, passingProbe).problems).toEqual([
+ expect.stringContaining('holds 0 "* Server.app" helper bundles'),
+ ]);
+ });
+
+ test('refuses an app with two Server.app helper bundles', () => {
+ const app = plantApp({ servers: ['OpenKnowledge', 'OpenKnowledge Extra'] });
+ expect(checkPackagedApp(app, passingProbe).problems).toEqual([
+ expect.stringContaining('holds 2 "* Server.app" helper bundles'),
+ ]);
+ });
+
+ test('refuses a helper bundle whose executable is missing', () => {
+ const app = plantApp({ helper: null });
+ expect(checkPackagedApp(app, passingProbe).problems).toEqual([
+ expect.stringContaining(
+ `${helperOf(app, 'OpenKnowledge', 'OpenKnowledge Helper')}, which does not exist`,
+ ),
+ ]);
+ });
+});
+
+describe('helperProbeProblems', () => {
+ test('accepts a helper that runs as Node', () => {
+ expect(helperProbeProblems(passingProbe())).toEqual([]);
+ });
+
+ test('refuses a helper killed by SIGTRAP', () => {
+ expect(
+ helperProbeProblems({ status: null, signal: 'SIGTRAP', stdout: '', stderr: '' }),
+ ).toContain('it was killed by SIGTRAP');
+ });
+
+ test('refuses a helper that cannot load Electron Framework', () => {
+ const problems = helperProbeProblems({
+ status: 1,
+ signal: null,
+ stdout: '',
+ stderr: 'dyld[1]: Library not loaded: @rpath/Electron Framework.framework/Electron Framework',
+ });
+ expect(problems).toEqual([
+ 'it exited 1',
+ expect.stringContaining('lacks the "ok-helper-node-mode <version>" line'),
+ expect.stringContaining('Library not loaded'),
+ ]);
+ });
+
+ test('refuses a helper that exits 0 in Node mode but writes to stderr', () => {
+ expect(
+ helperProbeProblems({
+ status: 0,
+ signal: null,
+ stdout: 'ok-helper-node-mode 24.18.0\n',
+ stderr: 'unexpected diagnostic\n',
+ }),
+ ).toEqual(['it wrote to stderr: "unexpected diagnostic\\n"']);
+ });
+
+ test('refuses a zero exit without the Node-mode line', () => {
+ expect(
+ helperProbeProblems({ status: 0, signal: null, stdout: 'renderer\n', stderr: '' }),
+ ).toEqual([expect.stringContaining('lacks the "ok-helper-node-mode <version>" line')]);
+ });
+
+ test('refuses a helper that could not be spawned', () => {
+ const enoent = Object.assign(new Error('spawnSync helper ENOENT'), { code: 'ENOENT' });
+ expect(helperProbeProblems({ error: enoent, status: null, signal: null })).toEqual([
+ 'it could not be run: spawnSync helper ENOENT',
+ ]);
+ });
+
+ test('refuses a helper that did not exit, with what it printed before the timeout', () => {
+ const timeout = Object.assign(new Error('spawnSync helper ETIMEDOUT'), { code: 'ETIMEDOUT' });
+ expect(
+ helperProbeProblems({
+ error: timeout,
+ status: null,
+ signal: 'SIGTERM',
+ stdout: 'partial\n',
+ stderr: 'boot log\n',
+ }),
+ ).toEqual([
+ `it did not exit within ${HELPER_PROBE_TIMEOUT_MS} ms`,
+ 'its stdout lacks the "ok-helper-node-mode <version>" line: "partial\\n"',
+ 'it wrote to stderr: "boot log\\n"',
+ ]);
+ });
+
+ test('accepts a real Node binary probed the way the packaged helper is', () => {
+ expect(helperProbeProblems(probeHelper(process.execPath))).toEqual([]);
+ });
+});
+
+describe('the CLI', () => {
+ test('exits 1 and names the search root when no packaged app exists', () => {
+ const result = runCli(root, 'self-test');
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain(`::error::self-test: no packaged mac-*/*.app under ${root}`);
+ });
+
+ test('exits 1 and names the helper when the helper cannot run', () => {
+ const app = plantApp({ helper: 'not an executable', helperMode: 0o644 });
+ const result = runCli(root, 'self-test');
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain(
+ `${helperOf(app, 'OpenKnowledge', 'OpenKnowledge Helper')} under ELECTRON_RUN_AS_NODE=1: it could not be run`,
+ );
+ });
+
+ test('exits 1 when the helper exits non-zero with a dyld error', (ctx) => {
+ ctx.skip(process.platform === 'win32', 'a POSIX shell script plays the macOS helper binary');
+ plantApp({ helper: DYLD_FAILING_HELPER });
+ const result = runCli(root, 'self-test');
+ expect(result.status).toBe(1);
+ expect(result.stderr).toContain('it exited 1');
+ expect(result.stderr).toContain('Library not loaded');
+ });
+
+ test('checks every app, and one bad app fails the run', (ctx) => {
+ ctx.skip(process.platform === 'win32', 'a POSIX shell script plays the macOS helper binary');
+ const good = plantApp();
+ const bad = plantApp({ arch: 'mac-x64', helper: DYLD_FAILING_HELPER });
+ const result = runCli(root, 'self-test');
+ expect(result.status).toBe(1);
+ expect(result.stdout).toContain(
+ `packaged helper OK (self-test): ${helperOf(good, 'OpenKnowledge', 'OpenKnowledge Helper')}`,
+ );
+ expect(result.stderr).toContain(
+ `${helperOf(bad, 'OpenKnowledge', 'OpenKnowledge Helper')} under ELECTRON_RUN_AS_NODE=1: it exited 1`,
+ );
+ });
+
+ test('exits 1 and names a mac-* directory it cannot read', (ctx) => {
+ ctx.skip(
+ process.platform === 'win32' || process.getuid?.() === 0,
+ 'a mode-000 directory keeps out only a non-root POSIX reader',
+ );
+ plantApp({ arch: 'mac-universal', product: 'OpenKnowledge Beta' });
+ const unreadable = pathPosix.dirname(plantApp());
+ chmodSync(unreadable, 0o000);
+ const result = runCli(root, 'self-test');
+ chmodSync(unreadable, 0o755);
+ expect(result.stderr).toContain(`EACCES: permission denied, scandir '${unreadable}'`);
+ expect(result.status).toBe(1);
+ });
+
+ test('exits 0 when every app carries a helper that runs as Node', (ctx) => {
+ ctx.skip(process.platform === 'win32', 'a POSIX shell script plays the macOS helper binary');
+ plantApp();
+ plantApp({ arch: 'mac-universal', product: 'OpenKnowledge Beta' });
+ const result = runCli(root, 'self-test');
+ expect(result.stderr).toBe('');
+ expect(result.status).toBe(0);
+ expect(result.stdout).toContain(`packaged helper: 2 app(s) checked under ${root}`);
+ });
+});
diff --git a/packages/desktop/tests/integration/packaged-helper-runs-as-node.test.ts b/packages/desktop/tests/integration/packaged-helper-runs-as-node.test.ts
deleted file mode 100644
index 2aa5447b1..000000000
--- a/packages/desktop/tests/integration/packaged-helper-runs-as-node.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { spawnSync } from 'node:child_process';
-import { existsSync, readdirSync, readFileSync } from 'node:fs';
-import { dirname, join, resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { resolveHelperBundleBinary } from '@inkeep/open-knowledge-core/helper-bundle';
-import { describe, expect, test } from 'vitest';
-
-const HERE = dirname(fileURLToPath(import.meta.url));
-const desktopRoot = resolve(HERE, '../..');
-const distDesktopDir = resolve(desktopRoot, 'dist-desktop');
-
-function listDir(path: string): readonly string[] {
- try {
- return readdirSync(path);
- } catch {
- return [];
- }
-}
-
-function bundleExecutable(bundle: string): string | null {
- const plistPath = join(bundle, 'Contents/Info.plist');
- if (!existsSync(plistPath)) return null;
- const name = readFileSync(plistPath, 'utf8').match(
- /<key>CFBundleExecutable<\/key>\s*<string>([^<]*)<\/string>/,
- )?.[1];
- return name === undefined ? null : join(bundle, 'Contents/MacOS', name);
-}
-
-interface PackagedApp {
- readonly app: string;
- readonly executable: string | null;
- readonly helper: string | null;
-}
-
-function findPackagedApps(): readonly PackagedApp[] {
- return listDir(distDesktopDir)
- .filter((name) => name.startsWith('mac-'))
- .flatMap((subdir) =>
- listDir(join(distDesktopDir, subdir))
- .filter((name) => name.endsWith('.app'))
- .map((name) => join(distDesktopDir, subdir, name)),
- )
- .map((app) => {
- const frameworks = join(app, 'Contents/Frameworks');
- const servers = listDir(frameworks).filter((name) => name.endsWith(' Server.app'));
- const helper = servers.length === 1 ? bundleExecutable(join(frameworks, servers[0])) : null;
- return { app, executable: bundleExecutable(app), helper };
- });
-}
-
-const haveDarwin = process.platform === 'darwin';
-const packagedApps = haveDarwin ? findPackagedApps() : [];
-
-describe('packaged helper binary runs under ELECTRON_RUN_AS_NODE=1', () => {
- test('test environment gate (packaged build present)', (ctx) => {
- ctx.skip(!haveDarwin, `darwin-only test; platform=${process.platform}`);
- ctx.skip(
- packagedApps.length === 0,
- `no packaged app found under ${distDesktopDir}/mac-<arch>/ — run ` +
- `\`pnpm exec electron-builder --dir --publish never\` (or \`okdesk\`) to enable this test`,
- );
- expect(packagedApps.length).toBeGreaterThan(0);
- });
-
- describe.each(packagedApps.map((packaged) => [packaged.app, packaged] as const))(
- '%s',
- (_app, packaged) => {
- test('carries exactly one Server.app helper with an existing executable', () => {
- expect(packaged.helper, `${packaged.app} has no usable Server.app helper`).not.toBeNull();
- expect(existsSync(packaged.helper as string)).toBe(true);
- });
-
- test('the spawn-site resolver lands on that helper', () => {
- expect(packaged.executable).not.toBeNull();
- expect(resolveHelperBundleBinary(packaged.executable as string)).toBe(packaged.helper);
- });
-
- test('helper binary exits 0 with stdout under ELECTRON_RUN_AS_NODE=1 (no SIGTRAP)', () => {
- const result = spawnSync(
- packaged.helper as string,
- ['-e', 'console.log("ok-helper-node-mode", process.versions.node)'],
- {
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
- encoding: 'utf8',
- timeout: 10_000,
- },
- );
-
- expect({
- status: result.status,
- signal: result.signal,
- stdout: result.stdout,
- stderrTail: result.stderr.slice(-200),
- }).toEqual({
- status: 0,
- signal: null,
- stdout: expect.stringMatching(/ok-helper-node-mode\s+\d+\.\d+\.\d+/),
- stderrTail: '',
- });
- });
-
- test('helper binary loads Electron Framework via @rpath without dyld errors', () => {
- const result = spawnSync(packaged.helper as string, ['-e', 'process.exit(0)'], {
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
- encoding: 'utf8',
- timeout: 10_000,
- });
-
- expect(result.stderr).not.toContain('Library not loaded');
- expect(result.stderr).not.toContain('Unable to find helper app');
- expect(result.status).toBe(0);
- });
- },
- );
-});
diff --git a/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts b/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts
index d7ed28418..c2536a7d6 100644
--- a/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/launch-desktop.test.ts
@@ -1,4 +1,5 @@
-import { readdirSync, readFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
@@ -70,13 +71,27 @@ describe('resolveDesktopTarget', () => {
expect(target.appPath).toBe('/mnt/OpenKnowledge.app');
});
- it('reports existence and a mode-appropriate skip reason', () => {
+ it('reports a mode-appropriate skip reason', () => {
const missing = resolveDesktopTarget({ env: { [PACKAGED_APP_ENV]: '/nope/Absent.app' } });
- expect(missing.exists).toBe(false);
expect(missing.missingReason).toContain('/nope/Absent.app/Contents/MacOS/Absent');
expect(resolveDesktopTarget({ env: {} }).missingReason).toContain('pnpm run build:desktop');
expect(resolveDesktopTarget({ env: {} }).missingReason).not.toContain('bun run');
});
+
+ it('probes the target when existence is read, not when the target resolves', () => {
+ const root = mkdtempSync(join(tmpdir(), 'ok-launch-target-'));
+ try {
+ const target = resolveDesktopTarget({
+ env: { [PACKAGED_APP_ENV]: join(root, 'Absent.app') },
+ });
+ expect(target.exists).toBe(false);
+ mkdirSync(dirname(target.targetPath), { recursive: true });
+ writeFileSync(target.targetPath, '');
+ expect(target.exists).toBe(true);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
});
describe('executableForAppBundle', () => {
diff --git a/packages/desktop/tests/smoke/_helpers/launch-desktop.ts b/packages/desktop/tests/smoke/_helpers/launch-desktop.ts
index 722aa18e8..09e74a379 100644
--- a/packages/desktop/tests/smoke/_helpers/launch-desktop.ts
+++ b/packages/desktop/tests/smoke/_helpers/launch-desktop.ts
@@ -29,7 +29,7 @@ export interface DesktopTarget {
mode: DesktopLaunchMode;
appPath?: string;
targetPath: string;
- exists: boolean;
+ readonly exists: boolean;
missingReason: string;
}
@@ -42,6 +42,15 @@ export function executableForAppBundle(appPath: string): string {
return join(appPath, 'Contents', 'MacOS', basename(appPath, '.app'));
}
+function probedOnRead(target: Omit<DesktopTarget, 'exists'>): DesktopTarget {
+ return {
+ ...target,
+ get exists() {
+ return existsSync(target.targetPath);
+ },
+ };
+}
+
export function resolveDesktopTarget(options: ResolveDesktopTargetOptions = {}): DesktopTarget {
const env = options.env ?? process.env;
const override = env[PACKAGED_APP_ENV];
@@ -54,21 +63,19 @@ export function resolveDesktopTarget(options: ResolveDesktopTargetOptions = {}):
if (appPath !== undefined) {
const targetPath = executableForAppBundle(appPath);
- return {
+ return probedOnRead({
mode: 'packaged',
appPath,
targetPath,
- exists: existsSync(targetPath),
missingReason: `Packaged desktop build missing at ${targetPath} — build a packaged app, or point ${PACKAGED_APP_ENV} at one.`,
- };
+ });
}
- return {
+ return probedOnRead({
mode: 'unpackaged',
targetPath: UNPACKAGED_MAIN_ENTRY,
- exists: existsSync(UNPACKAGED_MAIN_ENTRY),
missingReason: `Main build missing at ${UNPACKAGED_MAIN_ENTRY} — run "pnpm run build:desktop" first.`,
- };
+ });
}
export interface DesktopLaunchOptionsInput {
diff --git a/packages/desktop/tests/unit/preload-single-entry.test.ts b/packages/desktop/tests/unit/preload-single-entry.test.ts
index eafa285c6..6fd657cf8 100644
--- a/packages/desktop/tests/unit/preload-single-entry.test.ts
+++ b/packages/desktop/tests/unit/preload-single-entry.test.ts
@@ -1,40 +1,92 @@
-import { existsSync, readFileSync } from 'node:fs';
-import { isBuiltin } from 'node:module';
-import { resolve } from 'node:path';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { PreloadConfigFactory, type PreloadViteConfig } from 'electron-vite';
+import { build } from 'vite';
import { describe, expect, test } from 'vitest';
const desktopRoot = resolve(fileURLToPath(new URL('../../', import.meta.url)));
-interface PreloadBuild {
- rolldownOptions?: { input?: Record<string, string> };
+/* UPSTREAM([email protected]): a sandboxed preload's require resolves only the module names that
+ lib/sandboxed_renderer/init.ts maps, and lib/sandboxed_renderer/preload.ts throws
+ "module not found" for any other name, Node builtins such as fs included. */
+const SANDBOXED_PRELOAD_MODULES = new Set([
+ 'electron',
+ 'electron/common',
+ 'electron/renderer',
+ 'events',
+ 'node:events',
+ 'timers',
+ 'node:timers',
+ 'url',
+ 'node:url',
+]);
+
+function requiredModules(source: string): string[] {
+ return [...source.matchAll(/require\(["']([^"']+)["']\)/g)].flatMap((match) =>
+ match[1] === undefined ? [] : [match[1]],
+ );
+}
+
+function unresolvableInSandbox(source: string): string[] {
+ return requiredModules(source).filter((name) => !SANDBOXED_PRELOAD_MODULES.has(name));
+}
+
+async function preloadConfig(): Promise<PreloadViteConfig> {
+ const config: { preload?: PreloadViteConfig } = (await import('../../electron.vite.config'))
+ .default;
+ if (config.preload === undefined) throw new Error('electron.vite.config declares no preload');
+ return config.preload;
}
-async function preloadInput(): Promise<Record<string, string>> {
- const config: { preload?: { build?: PreloadBuild } } = (
- await import('../../electron.vite.config')
- ).default;
- const input = config.preload?.build?.rolldownOptions?.input;
- if (input === undefined) throw new Error('preload build declares no entry input');
- return input;
+async function buildPreloadForProduction(): Promise<string> {
+ const outDir = mkdtempSync(join(tmpdir(), 'ok-preload-bundle-'));
+ const environment = { ...process.env };
+ process.env.NODE_ENV = 'production';
+ process.env.NODE_ENV_ELECTRON_VITE = 'production';
+ try {
+ const preload = await new PreloadConfigFactory(
+ await preloadConfig(),
+ { configFile: false, logLevel: 'warn', mode: 'production' },
+ { root: desktopRoot },
+ ).build();
+ await build({ ...preload, build: { ...preload.build, outDir, emptyOutDir: true } });
+ return readFileSync(join(outDir, 'index.js'), 'utf-8');
+ } finally {
+ for (const key of Object.keys(process.env)) {
+ if (!(key in environment)) delete process.env[key];
+ }
+ Object.assign(process.env, environment);
+ rmSync(outDir, { recursive: true, force: true });
+ }
}
describe('preload bundle self-containment', () => {
test('the preload build declares exactly one entry', async () => {
- expect(Object.keys(await preloadInput())).toEqual(['index']);
+ const input = (await preloadConfig()).build?.rolldownOptions?.input;
+ if (input === undefined) throw new Error('preload build declares no entry input');
+ expect(Object.keys(input)).toEqual(['index']);
});
- test('the built preload requires only specifiers the sandbox can resolve', (ctx) => {
- const built = resolve(desktopRoot, 'out', 'preload', 'index.js');
- ctx.skip(!existsSync(built), 'the desktop preload is not built (out/preload/index.js)');
- const requires = [...readFileSync(built, 'utf-8').matchAll(/require\(["']([^"']+)["']\)/g)].map(
- (match) => match[1],
- );
- expect(requires.length).toBeGreaterThan(0);
+ test("the sandbox's module map admits Electron's names and refuses the rest", () => {
expect(
- requires.filter(
- (specifier) => specifier !== undefined && specifier !== 'electron' && !isBuiltin(specifier),
+ unresolvableInSandbox(
+ 'require("electron/renderer"); require("node:events"); require("timers"); require("url");',
),
).toEqual([]);
+ expect(
+ unresolvableInSandbox(
+ 'require("node:fs"); require("fs"); require("./chunks/shared.js"); require("@inkeep/open-knowledge-core");',
+ ),
+ ).toEqual(['node:fs', 'fs', './chunks/shared.js', '@inkeep/open-knowledge-core']);
+ });
+
+ test('the production preload bundle requires only modules the sandbox resolves', async () => {
+ const nodeEnv = process.env.NODE_ENV;
+ const bundle = await buildPreloadForProduction();
+ expect(process.env.NODE_ENV).toBe(nodeEnv);
+ expect(requiredModules(bundle)).toContain('electron');
+ expect(unresolvableInSandbox(bundle)).toEqual([]);
});
});