Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Ship Linux natives as prebuilds and check them before upload (#5308)

Nick Gomez10c84761e2b4
diff --git a/.github/scripts/release-cascade-shape.test.mjs b/.github/scripts/release-cascade-shape.test.mjs
index 2982bd0d8..1198039e2 100644
--- a/.github/scripts/release-cascade-shape.test.mjs
+++ b/.github/scripts/release-cascade-shape.test.mjs
@@ -1,7 +1,7 @@
// biome-ignore-all lint/suspicious/noTemplateCurlyInString: shell and GitHub expression fixtures must remain literal.
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
@@ -1159,3 +1159,112 @@ describe('the macOS artifact is attested signed before it can ship', () => {
}
});
});
+
+describe('Linux packaging ships the native prebuilds and checks them before upload', () => {
+ const NATIVE_GUARD =
+ 'pnpm exec vitest run tests/unit/linux-package-native-guards.test.ts tests/unit/linux-package-terminal-spawn.test.ts';
+ const linuxJobs = [
+ ['desktop-release.yml', parse(desktopRelease).jobs['build-linux']],
+ ['desktop-build-win-linux.yml', parse(desktopBuildWinLinux).jobs['build-linux']],
+ ];
+ const uploads = (step) =>
+ step.uses?.startsWith('actions/upload-artifact@') ||
+ /\bgh\s+release\s+(upload|create|edit)\b/.test(step.run ?? '');
+
+ test.each(linuxJobs)('%s installs without forcing an Electron-ABI rebuild', (_name, job) => {
+ const install = job.steps.find((step) => step.name === 'Install dependencies');
+ expect(install.env).toEqual({ ELECTRON_SKIP_REBUILD: '1' });
+ });
+
+ test.each(linuxJobs)(
+ '%s runs the native guard after packaging and before every upload, unskippably',
+ (name, job) => {
+ const packaged = job.steps.findIndex((step) => step.name?.startsWith('Package '));
+ const guarded = job.steps.findIndex((step) => step.run?.trim() === NATIVE_GUARD);
+ expect(packaged, `${name} build-linux has no "Package" step`).toBeGreaterThan(-1);
+ expect(guarded, `${name} build-linux runs no native guard after packaging`).toBeGreaterThan(
+ packaged,
+ );
+ const uploadSteps = job.steps.flatMap((step, index) =>
+ uploads(step) ? [[index, step.name ?? step.uses]] : [],
+ );
+ expect(uploadSteps.length, `${name} build-linux uploads nothing`).toBeGreaterThan(0);
+ for (const [index, label] of uploadSteps) {
+ expect(index, `step "${label}" uploads before the native guard`).toBeGreaterThan(guarded);
+ }
+ const guard = job.steps[guarded];
+ expect(guard['working-directory']).toBe('packages/desktop');
+ expect(guard.env).toEqual({
+ OK_LINUX_PACKAGE_DIR: 'dist-desktop/${{ matrix.unpacked_dir }}',
+ });
+ expect(guard).not.toHaveProperty('if');
+ expect(guard).not.toHaveProperty('continue-on-error');
+ },
+ );
+
+ test.each(linuxJobs)(
+ '%s installs the runtime dependencies the built deb declares before the native guard, unskippably',
+ (name, job) => {
+ const packaged = job.steps.findIndex((step) => step.name?.startsWith('Package '));
+ const guarded = job.steps.findIndex((step) => step.run?.trim() === NATIVE_GUARD);
+ const provisioned = job.steps.findIndex((step) =>
+ /\bdpkg-deb\s+--field\s+\S+\s+Depends\b/.test(step.run ?? ''),
+ );
+ expect(packaged, `${name} build-linux has no "Package" step`).toBeGreaterThan(-1);
+ expect(
+ provisioned,
+ `${name} build-linux reads no built deb's Depends after packaging`,
+ ).toBeGreaterThan(packaged);
+ expect(provisioned, `${name} build-linux provisions after the native guard`).toBeLessThan(
+ guarded,
+ );
+ const step = job.steps[provisioned];
+ const lines = step.run
+ .split('\n')
+ .map((line) => line.trim())
+ .filter((line) => !line.startsWith('#'));
+ const operands = lines.flatMap((line) =>
+ (/\bapt-get\s+satisfy\b(.*)$/.exec(line)?.[1] ?? '')
+ .split(/\s+/)
+ .filter((token) => token && !token.startsWith('-')),
+ );
+ expect(
+ operands.length,
+ `${name} provisioning does not install with apt-get satisfy`,
+ ).toBeGreaterThan(0);
+ for (const operand of operands) {
+ const variable = /^"?\$\{?(\w+)/.exec(operand)?.[1];
+ expect(variable, `${name} satisfies "${operand}", not a variable`).toBeDefined();
+ const fromDeb = new RegExp(
+ `^${variable}\\+=\\("\\$\\(dpkg-deb\\s+--field\\s+\\S+\\s+Depends\\)"\\)$`,
+ );
+ const empty = new RegExp(`^(?:declare\\s+-a\\s+)?${variable}=\\(\\)$`);
+ const written = new RegExp(`(?<![\\w$#!{])${variable}\\b`);
+ const writes = lines.filter((line) => written.test(line));
+ expect(
+ writes.some((line) => fromDeb.test(line)),
+ `${name} never fills ${variable} from the built deb's Depends`,
+ ).toBe(true);
+ expect(
+ writes.filter((line) => !fromDeb.test(line) && !empty.test(line)),
+ `${name} fills ${variable} from something other than the built deb's Depends`,
+ ).toEqual([]);
+ }
+ expect(step.run).not.toMatch(/\bapt-get\s+install\b/);
+ expect(step['working-directory']).toBe('packages/desktop');
+ expect(step).not.toHaveProperty('if');
+ expect(step).not.toHaveProperty('continue-on-error');
+ },
+ );
+
+ test('every test file the native guard names exists in the desktop package', () => {
+ const desktop = join(WORKFLOWS, '..', '..', 'packages', 'desktop');
+ const files = /\bvitest run (.+)$/.exec(NATIVE_GUARD)[1].split(/\s+/);
+ expect(files.length).toBeGreaterThan(0);
+ for (const file of files) {
+ expect(existsSync(join(desktop, file)), `${file} is missing from packages/desktop`).toBe(
+ true,
+ );
+ }
+ });
+});
diff --git a/.github/workflows/desktop-build-win-linux.yml b/.github/workflows/desktop-build-win-linux.yml
index 2f098df44..260bfe9d4 100644
--- a/.github/workflows/desktop-build-win-linux.yml
+++ b/.github/workflows/desktop-build-win-linux.yml
@@ -463,9 +463,7 @@ jobs:
- name: Install dependencies
env:
- # Rebuild native modules against Electron's Node ABI — mirrors
- # desktop-release.yml.
- ELECTRON_SKIP_REBUILD: "0"
+ ELECTRON_SKIP_REBUILD: "1"
run: pnpm install --frozen-lockfile
- name: Download workspace bundle
@@ -497,8 +495,7 @@ jobs:
# host's `rpmbuild` to assemble an `.rpm` — and an Ubuntu runner has no
# rpm tooling preinstalled, so the rpm target dies with "Can't find
# rpmbuild". Ubuntu's `rpm` package carries /usr/bin/rpmbuild. The deb
- # and AppImage targets need nothing extra, so this is the only apt step
- # in the job.
+ # and AppImage targets need nothing extra.
- name: Install rpmbuild (fpm's rpm backend)
run: |
set -euo pipefail
@@ -518,11 +515,28 @@ jobs:
run: |
pnpm exec node "$GITHUB_WORKSPACE/.github/scripts/package-desktop.mjs" --linux ${{ matrix.targets }} --publish never
+ - name: Install the packaged deb's runtime dependencies
+ working-directory: packages/desktop
+ run: |
+ set -euo pipefail
+ shopt -s nullglob
+ debs=(dist-desktop/*.deb)
+ if [[ ${#debs[@]} -eq 0 ]]; then
+ echo "::error::No .deb found under dist-desktop to read runtime dependencies from."
+ exit 1
+ fi
+ depends=()
+ for deb in "${debs[@]}"; do
+ depends+=("$(dpkg-deb --field "$deb" Depends)")
+ done
+ sudo apt-get update
+ sudo apt-get satisfy -y --no-install-recommends "${depends[@]}"
+
- name: Assert Linux terminal native package compatibility
working-directory: packages/desktop
env:
OK_LINUX_PACKAGE_DIR: dist-desktop/${{ matrix.unpacked_dir }}
- run: pnpm exec vitest run tests/unit/linux-package-native-guards.test.ts
+ run: pnpm exec vitest run tests/unit/linux-package-native-guards.test.ts tests/unit/linux-package-terminal-spawn.test.ts
# Fail before uploading an installer that cannot start (see the Windows
# step for the full rationale). This is the control that would have caught
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml
index b3c82aa6c..ab112c20b 100644
--- a/.github/workflows/desktop-release.yml
+++ b/.github/workflows/desktop-release.yml
@@ -1412,11 +1412,7 @@ jobs:
- name: Install dependencies
env:
- # Rebuild native modules against Electron's Node ABI — mirrors the
- # mac job. (The packaging pass itself skips @electron/rebuild via
- # the generated variant config; this install-time rebuild provides
- # the ABI-correct prebuilds that decision depends on.)
- ELECTRON_SKIP_REBUILD: "0"
+ ELECTRON_SKIP_REBUILD: "1"
run: pnpm install --frozen-lockfile
- name: Download workspace bundle
@@ -1457,7 +1453,7 @@ jobs:
# host's `rpmbuild` to assemble an `.rpm` — and an Ubuntu runner has no
# rpm tooling preinstalled, so the rpm target dies with "Can't find
# rpmbuild". Ubuntu's `rpm` package carries /usr/bin/rpmbuild. The deb
- # target needs nothing extra, so this is the only apt step in the job.
+ # target needs nothing extra.
- name: Install rpmbuild (fpm's rpm backend)
run: |
set -euo pipefail
@@ -1510,6 +1506,29 @@ jobs:
echo "::notice::Retry wrapper materialized from workflow SHA ${GITHUB_WORKFLOW_SHA}."
node "$WRAPPER" --label "electron-builder (Linux ${LINUX_TARGETS})" --max-attempts 3 --deadline-epoch-ms "$PACKAGING_DEADLINE_EPOCH_MS" --attempt-timeout "15m" --shell -- "$PKG_CMD"
+ - name: Install the packaged deb's runtime dependencies
+ working-directory: packages/desktop
+ run: |
+ set -euo pipefail
+ shopt -s nullglob
+ debs=(dist-desktop/*.deb)
+ if [[ ${#debs[@]} -eq 0 ]]; then
+ echo "::error::No .deb found under dist-desktop to read runtime dependencies from."
+ exit 1
+ fi
+ depends=()
+ for deb in "${debs[@]}"; do
+ depends+=("$(dpkg-deb --field "$deb" Depends)")
+ done
+ sudo apt-get update
+ sudo apt-get satisfy -y --no-install-recommends "${depends[@]}"
+
+ - name: Assert Linux terminal native package compatibility
+ working-directory: packages/desktop
+ env:
+ OK_LINUX_PACKAGE_DIR: dist-desktop/${{ matrix.unpacked_dir }}
+ run: pnpm exec vitest run tests/unit/linux-package-native-guards.test.ts tests/unit/linux-package-terminal-spawn.test.ts
+
# Fail before staging an installer that cannot start (see the Windows
# step for the full rationale). This is the control that would have
# caught the 0.42.2 arm64 deb, which installed cleanly and then died on
diff --git a/packages/desktop/tests/unit/linux-package-native-guards.test.ts b/packages/desktop/tests/unit/linux-package-native-guards.test.ts
index eb736b5ee..1f7906449 100644
--- a/packages/desktop/tests/unit/linux-package-native-guards.test.ts
+++ b/packages/desktop/tests/unit/linux-package-native-guards.test.ts
@@ -8,7 +8,7 @@ import {
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
-import { dirname, join, relative, resolve } from 'node:path';
+import { basename, dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'vitest';
@@ -62,6 +62,30 @@ function findNativeAddons(root: string): string[] {
return found.sort();
}
+interface FloorViolation {
+ addon: string;
+ family: NativeVersionFamily;
+ required: string;
+ maximum: string;
+}
+
+function floorViolations(root: string): FloorViolation[] {
+ return findNativeAddons(root).flatMap((addon) => {
+ const versions = requiredNativeVersions(readFileSync(addon));
+ return (Object.entries(MAX_NATIVE_VERSIONS) as Array<[NativeVersionFamily, string]>).flatMap(
+ ([family, maximum]) => {
+ const required = versions.get(family);
+ if (required === undefined || compareVersions(required, maximum) <= 0) return [];
+ return [{ addon: relative(root, addon), family, required, maximum }];
+ },
+ );
+ });
+}
+
+function describeFloorViolation({ addon, family, required, maximum }: FloorViolation): string {
+ return `${addon} requires ${family}_${required}, above the recorded ${family}_${maximum} Electron floor`;
+}
+
const fixtureDirs: string[] = [];
afterEach(() => {
for (const dir of fixtureDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
@@ -86,6 +110,59 @@ describe('Linux package native-version guard helpers', () => {
writeFileSync(sibling, 'not native');
expect(findNativeAddons(root)).toEqual([addon]);
});
+
+ test.each<[string, Record<string, string>, FloorViolation[]]>([
+ ['passes addons at the floor', { 'a.node': 'GLIBC_2.31\0GLIBCXX_3.4.28' }, []],
+ [
+ 'refuses one GLIBC step over the floor',
+ { 'a.node': 'GLIBC_2.32' },
+ [{ addon: 'a.node', family: 'GLIBC', required: '2.32', maximum: '2.31' }],
+ ],
+ [
+ 'refuses one GLIBCXX step over the floor',
+ { 'a.node': 'GLIBCXX_3.4.29' },
+ [{ addon: 'a.node', family: 'GLIBCXX', required: '3.4.29', maximum: '3.4.28' }],
+ ],
+ [
+ 'refuses a planted too-new addon beside a compliant one',
+ { 'ok.node': 'GLIBC_2.28', 'new.node': 'GLIBC_2.38' },
+ [{ addon: 'new.node', family: 'GLIBC', required: '2.38', maximum: '2.31' }],
+ ],
+ [
+ 'names every addon over the floor',
+ { 'pty.node': 'GLIBC_2.34', 'watcher.node': 'GLIBC_2.38' },
+ [
+ { addon: 'pty.node', family: 'GLIBC', required: '2.34', maximum: '2.31' },
+ { addon: 'watcher.node', family: 'GLIBC', required: '2.38', maximum: '2.31' },
+ ],
+ ],
+ ])('%s', (_label, addons, expected) => {
+ const root = mkdtempSync(join(tmpdir(), 'ok-linux-native-floor-'));
+ fixtureDirs.push(root);
+ const dir = join(root, 'resources', 'app.asar.unpacked', 'node_modules', 'fixture');
+ mkdirSync(dir, { recursive: true });
+ for (const [name, tags] of Object.entries(addons)) {
+ writeFileSync(join(dir, name), `\x7fELF\0${tags}\0`);
+ }
+ const found = floorViolations(root).map((violation) => ({
+ ...violation,
+ addon: basename(violation.addon),
+ }));
+ expect(found).toEqual(expected);
+ });
+
+ test('describes a violation by its addon, its requirement and the floor', () => {
+ expect(
+ describeFloorViolation({
+ addon: 'resources/app.asar.unpacked/node_modules/w/watcher.node',
+ family: 'GLIBC',
+ required: '2.38',
+ maximum: '2.31',
+ }),
+ ).toBe(
+ 'resources/app.asar.unpacked/node_modules/w/watcher.node requires GLIBC_2.38, above the recorded GLIBC_2.31 Electron floor',
+ );
+ });
});
describe('Linux package native guard lane visibility', () => {
@@ -124,19 +201,6 @@ describe.skipIf(packageDir === null)('packaged Linux native modules', () => {
test('keeps every shipped native addon within Electron’s Debian 11 ABI floor', () => {
const addons = findNativeAddons(packageDir as string);
expect(addons.length, `no .node binaries found under ${packageDir}`).toBeGreaterThan(0);
-
- for (const addon of addons) {
- const versions = requiredNativeVersions(readFileSync(addon));
- for (const [family, maximum] of Object.entries(MAX_NATIVE_VERSIONS) as Array<
- [NativeVersionFamily, string]
- >) {
- const required = versions.get(family);
- if (required === undefined) continue;
- expect(
- compareVersions(required, maximum),
- `${relative(packageDir as string, addon)} requires ${family}_${required}, above the recorded ${family}_${maximum} Electron floor`,
- ).toBeLessThanOrEqual(0);
- }
- }
+ expect(floorViolations(packageDir as string).map(describeFloorViolation)).toEqual([]);
});
});
diff --git a/packages/desktop/tests/unit/linux-package-terminal-spawn.test.ts b/packages/desktop/tests/unit/linux-package-terminal-spawn.test.ts
new file mode 100644
index 000000000..b67a264cf
--- /dev/null
+++ b/packages/desktop/tests/unit/linux-package-terminal-spawn.test.ts
@@ -0,0 +1,347 @@
+import { spawn, spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join, relative, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, type TestContext, test } from 'vitest';
+import { DESKTOP_VARIANTS, parseDesktopVariantName } from '../../src/shared/desktop-variant';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const desktopRoot = resolve(__dirname, '../..');
+const packageDirInput = process.env.OK_LINUX_PACKAGE_DIR?.trim() ?? '';
+const packageDir = packageDirInput === '' ? null : resolve(desktopRoot, packageDirInput);
+
+const PTY_PROBE_OUTPUT = 'node-pty-spawned';
+
+interface NodePtyProbeRun {
+ error: Error | null;
+ code: number | null;
+ signal: NodeJS.Signals | null;
+ stdout: string;
+ stderr: string;
+}
+
+function runNodePtyProbe(
+ executable: string,
+ nodePty: string,
+ signal: AbortSignal,
+): Promise<NodePtyProbeRun> {
+ const probe = [
+ `const pty = require(${JSON.stringify(nodePty)});`,
+ `const child = pty.spawn('/bin/sh', ['-c', 'printf ${PTY_PROBE_OUTPUT}'], {});`,
+ "let output = '';",
+ 'child.onData((data) => { output += data; });',
+ 'child.onExit(({ exitCode }) => process.stdout.write(JSON.stringify({ output, exitCode })));',
+ ].join('\n');
+ return new Promise((resolveRun) => {
+ const run: NodePtyProbeRun = { error: null, code: null, signal: null, stdout: '', stderr: '' };
+ const child = spawn(executable, ['-e', probe], {
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
+ signal,
+ });
+ child.stdout.setEncoding('utf8').on('data', (chunk: string) => {
+ run.stdout += chunk;
+ });
+ child.stderr.setEncoding('utf8').on('data', (chunk: string) => {
+ run.stderr += chunk;
+ });
+ child.on('error', (error) => {
+ run.error = error;
+ });
+ child.on('close', (code, closeSignal) => {
+ run.code = code;
+ run.signal = closeSignal;
+ resolveRun(run);
+ });
+ });
+}
+
+function nodePtyProbeProblems(executable: string, run: NodePtyProbeRun): string[] {
+ if (run.error?.name === 'AbortError') return ['it was stopped when the test timed out'];
+ if (run.error) return [`${executable} could not be run: ${run.error.message}`];
+ if (run.signal !== null) return [`it was killed by ${run.signal}`];
+ if (run.code !== 0) return [`it exited ${run.code}`];
+ let result: { output?: unknown; exitCode?: unknown };
+ try {
+ result = JSON.parse(run.stdout);
+ } catch {
+ return ['it printed no node-pty result'];
+ }
+ const problems: string[] = [];
+ if (result.exitCode !== 0) problems.push(`the shell node-pty spawned exited ${result.exitCode}`);
+ if (!String(result.output).includes(PTY_PROBE_OUTPUT)) {
+ problems.push(`the shell's output lacks "${PTY_PROBE_OUTPUT}"`);
+ }
+ return problems;
+}
+
+function probeTranscript(executable: string, run: NodePtyProbeRun): string {
+ return [
+ `node-pty probe through ${executable}`,
+ `stdout: ${JSON.stringify(run.stdout.slice(-400))}`,
+ `stderr: ${JSON.stringify(run.stderr)}`,
+ ].join('\n');
+}
+
+async function expectNodePtyProbeSpawns(
+ executable: string,
+ nodePty: string,
+ { signal, onTestFailed }: TestContext,
+): Promise<void> {
+ const probe = runNodePtyProbe(executable, nodePty, signal);
+ const expectSpawned = (run: NodePtyProbeRun) =>
+ expect(nodePtyProbeProblems(executable, run), probeTranscript(executable, run)).toEqual([]);
+ onTestFailed(async () => {
+ if (signal.aborted) expectSpawned(await probe);
+ });
+ expectSpawned(await probe);
+}
+
+const workspaceNodePty = () => dirname(dirname(createRequire(import.meta.url).resolve('node-pty')));
+
+type ProbeTest = readonly [suite: string, name: string];
+
+const LOCAL_PROBE_TEST: ProbeTest = [
+ 'node-pty probe',
+ 'loads node-pty in Node mode and spawns a command',
+];
+const PACKAGED_PROBE_TEST: ProbeTest = [
+ 'packaged Linux terminal',
+ 'loads node-pty from the packaged app with its own Electron and spawns a command',
+];
+
+const FAIL_NATIVE_LOADS = [
+ "if (process.env.ELECTRON_RUN_AS_NODE === '1') {",
+ ' const dlopen = process.dlopen;',
+ ' process.dlopen = (module, _filename, ...flags) => dlopen(module, __filename, ...flags);',
+ '}',
+].join('\n');
+
+function hangAfterPrinting(stdout: string, stderr: string): string {
+ return [
+ "if (process.env.ELECTRON_RUN_AS_NODE === '1') {",
+ " const { writeSync } = require('node:fs');",
+ ` writeSync(1, ${JSON.stringify(`${stdout}\n`)});`,
+ ` writeSync(2, ${JSON.stringify(`${stderr}\n`)});`,
+ ' Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);',
+ '}',
+ ].join('\n');
+}
+
+function scratchDirectory(onTestFinished: TestContext['onTestFinished']): string {
+ const directory = mkdtempSync(join(tmpdir(), 'ok-pty-probe-report-'));
+ onTestFinished(() => rmSync(directory, { recursive: true, force: true }));
+ return directory;
+}
+
+function faultEnvironment(scratch: string, fault: string): Record<string, string> {
+ const preload = join(scratch, 'fault.cjs');
+ writeFileSync(preload, fault);
+ const env: Record<string, string> = {};
+ for (const [key, value] of Object.entries(process.env)) {
+ if (value === undefined || key.startsWith('VITEST')) continue;
+ if (key === 'GITHUB_STEP_SUMMARY' || key === 'ELECTRON_RUN_AS_NODE') continue;
+ env[key] = value;
+ }
+ env.NODE_OPTIONS = `${env.NODE_OPTIONS ?? ''} --require ${JSON.stringify(preload)}`.trim();
+ return env;
+}
+
+async function failureReport(
+ [suite, name]: ProbeTest,
+ env: Record<string, string>,
+ signal: AbortSignal,
+): Promise<{ report: string; output: string }> {
+ const vitest = join(
+ dirname(createRequire(import.meta.url).resolve('vitest/package.json')),
+ 'vitest.mjs',
+ );
+ const output = await new Promise<string>((resolveOutput, reject) => {
+ const child = spawn(
+ process.execPath,
+ [
+ vitest,
+ 'run',
+ relative(desktopRoot, fileURLToPath(import.meta.url)),
+ '--testNamePattern',
+ `${suite} ${name}$`,
+ '--reporter=github-actions',
+ '--maxWorkers=1',
+ ],
+ { cwd: desktopRoot, env, signal },
+ );
+ let captured = '';
+ child.stdout.setEncoding('utf8').on('data', (chunk: string) => {
+ captured += chunk;
+ });
+ child.stderr.setEncoding('utf8').on('data', (chunk: string) => {
+ captured += chunk;
+ });
+ child.on('error', reject);
+ child.on('close', () => resolveOutput(captured));
+ });
+ const report = output
+ .split('\n')
+ .filter((line) => line.startsWith('::error '))
+ .map((line) => [line.slice(0, line.indexOf('::', 2)), line.slice(line.indexOf('::', 2) + 2)])
+ .filter(([properties]) => properties?.includes(`${suite} > ${name}`))
+ .map(([, data]) =>
+ (data ?? '').replace(/%(0A|0D|25)/g, (_escape, hex: string) =>
+ String.fromCharCode(Number.parseInt(hex, 16)),
+ ),
+ )
+ .join('\n');
+ return { report, output };
+}
+
+async function expectHangReported(
+ probeTest: ProbeTest,
+ scratch: string,
+ signal: AbortSignal,
+ env: Record<string, string> = {},
+): Promise<void> {
+ const stdout = `probe-stdout-${randomUUID()}`;
+ const stderr = `probe-stderr-${randomUUID()}`;
+ const { report, output } = await failureReport(
+ probeTest,
+ { ...faultEnvironment(scratch, hangAfterPrinting(stdout, stderr)), ...env },
+ signal,
+ );
+ expect(report, output).toMatch(/timed? ?out/i);
+ expect(report, output).toContain(stdout);
+ expect(report, output).toContain(stderr);
+}
+
+describe('node-pty probe', () => {
+ const finished = { error: null, code: 0, signal: null, stderr: '' };
+ const result = (output: string, exitCode: number) => JSON.stringify({ output, exitCode });
+
+ test.each<[string, NodePtyProbeRun, string[]]>([
+ [
+ 'passes a shell that printed the marker and exited 0',
+ { ...finished, stdout: result(PTY_PROBE_OUTPUT, 0) },
+ [],
+ ],
+ [
+ 'names the executable it could not run',
+ { ...finished, error: new Error('spawn /app/openknowledge ENOENT'), code: -2, stdout: '' },
+ ['/app/openknowledge could not be run: spawn /app/openknowledge ENOENT'],
+ ],
+ [
+ 'names the test timeout that stopped it',
+ {
+ ...finished,
+ error: Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }),
+ code: null,
+ signal: 'SIGTERM',
+ stdout: '',
+ },
+ ['it was stopped when the test timed out'],
+ ],
+ [
+ 'names the signal that killed it',
+ { ...finished, code: null, signal: 'SIGSEGV', stdout: '' },
+ ['it was killed by SIGSEGV'],
+ ],
+ ['names its exit status', { ...finished, code: 1, stdout: '' }, ['it exited 1']],
+ [
+ 'names output that is not a probe result',
+ { ...finished, stdout: '' },
+ ['it printed no node-pty result'],
+ ],
+ [
+ 'names the exit status of the shell node-pty spawned',
+ { ...finished, stdout: result(PTY_PROBE_OUTPUT, 2) },
+ ['the shell node-pty spawned exited 2'],
+ ],
+ [
+ 'names shell output without the marker',
+ { ...finished, stdout: result('', 0) },
+ [`the shell's output lacks "${PTY_PROBE_OUTPUT}"`],
+ ],
+ ])('%s', (_label, run, expected) => {
+ expect(nodePtyProbeProblems('/app/openknowledge', run)).toEqual(expected);
+ });
+
+ test.skipIf(process.platform === 'win32')(
+ 'loads node-pty in Node mode and spawns a command',
+ (context) => expectNodePtyProbeSpawns(process.execPath, workspaceNodePty(), context),
+ );
+
+ test('reports an executable that does not exist', async ({ signal }) => {
+ const missing = join(desktopRoot, 'dist-desktop', 'missing', 'openknowledge');
+ const run = await runNodePtyProbe(missing, workspaceNodePty(), signal);
+ expect(nodePtyProbeProblems(missing, run)).toEqual([
+ `${missing} could not be run: spawn ${missing} ENOENT`,
+ ]);
+ });
+
+ test('ends the probe when its signal aborts', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const run = await runNodePtyProbe(process.execPath, workspaceNodePty(), controller.signal);
+ expect(nodePtyProbeProblems(process.execPath, run)).toEqual([
+ 'it was stopped when the test timed out',
+ ]);
+ });
+});
+
+describe.skipIf(packageDir === null)('packaged Linux terminal', () => {
+ test('loads node-pty from the packaged app with its own Electron and spawns a command', async (context) => {
+ expect(
+ process.platform,
+ 'OK_LINUX_PACKAGE_DIR must only be set in a Linux packaging lane',
+ ).toBe('linux');
+ const variant = DESKTOP_VARIANTS[parseDesktopVariantName(process.env.OK_DESKTOP_VARIANT)];
+ const executable = join(packageDir as string, variant.linuxExecutableName);
+ await expectNodePtyProbeSpawns(
+ executable,
+ join(packageDir as string, 'resources', 'app.asar', 'node_modules', 'node-pty'),
+ context,
+ );
+ });
+});
+
+describe.skipIf(packageDir !== null)('node-pty probe failure report', () => {
+ test.skipIf(process.platform === 'win32')(
+ 'names the timeout and attaches the output so far when the probe hangs',
+ async ({ signal, onTestFinished }) => {
+ await expectHangReported(LOCAL_PROBE_TEST, scratchDirectory(onTestFinished), signal);
+ },
+ Number.POSITIVE_INFINITY,
+ );
+
+ test.skipIf(process.platform !== 'linux')(
+ 'names the timeout and attaches the output so far when the packaged probe hangs',
+ async ({ signal, onTestFinished }) => {
+ const scratch = scratchDirectory(onTestFinished);
+ const packageRoot = join(scratch, 'package');
+ mkdirSync(packageRoot);
+ const variant = DESKTOP_VARIANTS[parseDesktopVariantName(process.env.OK_DESKTOP_VARIANT)];
+ symlinkSync(process.execPath, join(packageRoot, variant.linuxExecutableName));
+ await expectHangReported(PACKAGED_PROBE_TEST, scratch, signal, {
+ OK_LINUX_PACKAGE_DIR: packageRoot,
+ });
+ },
+ Number.POSITIVE_INFINITY,
+ );
+
+ test.skipIf(process.platform === 'win32')(
+ 'names the error a failed node-pty load threw',
+ async ({ signal, onTestFinished }) => {
+ const env = faultEnvironment(scratchDirectory(onTestFinished), FAIL_NATIVE_LOADS);
+ const direct = spawnSync(
+ process.execPath,
+ ['-e', `require(${JSON.stringify(workspaceNodePty())})`],
+ { env: { ...env, ELECTRON_RUN_AS_NODE: '1' }, encoding: 'utf8' },
+ );
+ const [, thrown = ''] = /^\w*Error: (.+)$/m.exec(direct.stderr) ?? [];
+ expect(thrown, direct.stderr).not.toBe('');
+ const { report, output } = await failureReport(LOCAL_PROBE_TEST, env, signal);
+ expect(report, output).toContain(thrown);
+ },
+ Number.POSITIVE_INFINITY,
+ );
+});