Files
waggle-os/packages/launcher/tests/installer.test.ts
shumeiko.it 1cfe337053 Merge licensing: shipped notices, Apache-2.0 core files and LGPL terms
Every installer and the server archive carry LICENSE and the
third-party notices, and Settings > General links to both. The files
copied from hive-mind-core keep Apache-2.0 with SPDX headers. The LGPL
components name their versions and where their source is. ADR-0010
settles the marketplace catalog question. Logs UF-069 and marks UF-059
Fixed.
2026-11-04 19:25:44 +01:00

276 lines
12 KiB
TypeScript

/**
* The installer: argument parsing, per-system paths, the server environment,
* and install / update / uninstall against an archive packed by
* scripts/build-server-archive.mjs.
*/
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { DEFAULT_PORT, parseArgs } from '../src/args.js';
import { UserError, doctor, install, uninstall, type Context } from '../src/commands.js';
import {
assetName,
currentHost,
defaultBinDir,
defaultDataDir,
defaultInstallDir,
isOnPath,
releaseTarget,
type Host,
} from '../src/platform.js';
import { layoutFor, parseChecksum, readRecord, serviceEnvironment, shimContent, shimFile } from '../src/payload.js';
const ROOT = path.resolve(import.meta.dirname, '..', '..', '..');
const VERSION = (JSON.parse(fs.readFileSync(path.join(ROOT, 'packages', 'launcher', 'package.json'), 'utf8')) as {
version: string;
}).version;
const temps: string[] = [];
function tempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
temps.push(dir);
return dir;
}
afterEach(() => {
for (const dir of temps.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
});
function host(platform: NodeJS.Platform, env: NodeJS.ProcessEnv = {}): Host {
return { platform, arch: 'x64', homedir: platform === 'win32' ? 'C:\\Users\\ana' : '/home/ana', env };
}
describe('parseArgs', () => {
it('runs the server when no command is given', () => {
expect(parseArgs([])).toEqual({ command: 'run', options: { port: DEFAULT_PORT, open: true, force: false } });
});
it('reads a command and its options', () => {
const parsed = parseArgs(['install', '--from', 'a.tar.gz', '--dir', '/opt/w', '--port', '4000', '--no-open', '--force']);
expect(parsed.error).toBeUndefined();
expect(parsed.command).toBe('install');
expect(parsed.options).toMatchObject({ from: 'a.tar.gz', dir: '/opt/w', port: 4000, open: false, force: true });
});
it('rejects bad ports, unknown words and malformed checksums', () => {
expect(parseArgs(['--port', '70000']).error).toMatch(/Invalid port/);
expect(parseArgs(['--port']).error).toMatch(/Invalid port/);
expect(parseArgs(['instal']).error).toMatch(/Unknown command/);
expect(parseArgs(['--fast']).error).toMatch(/Unknown option/);
expect(parseArgs(['install', '--from']).error).toMatch(/Missing value/);
expect(parseArgs(['install', '--sha256', 'abc']).error).toMatch(/64-character/);
});
it('treats --help and --version as commands', () => {
expect(parseArgs(['--help']).command).toBe('help');
expect(parseArgs(['-v']).command).toBe('version');
});
});
describe('platform paths', () => {
it('maps v1 systems to release targets and names the asset', () => {
expect(releaseTarget({ platform: 'win32', arch: 'x64' })).toBe('windows-x64');
expect(releaseTarget({ platform: 'darwin', arch: 'arm64' })).toBe('macos-arm64');
expect(releaseTarget({ platform: 'darwin', arch: 'x64' })).toBe('macos-x64');
expect(releaseTarget({ platform: 'linux', arch: 'x64' })).toBe('linux-x64');
expect(releaseTarget({ platform: 'linux', arch: 'arm64' })).toBeNull();
expect(assetName('1.2.3', 'linux-x64')).toBe('waggle-server-1.2.3-linux-x64.tar.gz');
});
it('installs into the per-user program directory of each system', () => {
expect(defaultInstallDir(host('win32', { LOCALAPPDATA: 'C:\\Users\\ana\\AppData\\Local' })))
.toBe('C:\\Users\\ana\\AppData\\Local\\Waggle\\server');
expect(defaultInstallDir(host('darwin'))).toBe('/home/ana/Library/Application Support/Waggle/server');
expect(defaultInstallDir(host('linux'))).toBe('/home/ana/.local/share/waggle/server');
expect(defaultInstallDir(host('linux', { XDG_DATA_HOME: '/data' }))).toBe('/data/waggle/server');
});
it('keeps the Windows shim inside the install and uses ~/.local/bin elsewhere', () => {
expect(defaultBinDir(host('win32'), 'C:\\W\\server')).toBe('C:\\W\\server\\bin');
expect(defaultBinDir(host('linux'), '/x')).toBe('/home/ana/.local/bin');
});
it('follows the sidecar data directory rule', () => {
expect(defaultDataDir(host('linux'))).toBe('/home/ana/.waggle-community');
expect(defaultDataDir(host('win32'))).toBe('C:\\Users\\ana\\.waggle-community');
expect(defaultDataDir(host('linux', { WAGGLE_DATA_DIR: '/srv/waggle' }))).toBe('/srv/waggle');
});
it('finds a directory on PATH, ignoring case on Windows', () => {
expect(isOnPath(host('linux', { PATH: '/usr/bin:/home/ana/.local/bin' }), '/home/ana/.local/bin')).toBe(true);
expect(isOnPath(host('linux', { PATH: '/usr/bin' }), '/home/ana/.local/bin')).toBe(false);
expect(isOnPath(host('win32', { Path: 'C:\\Windows;c:\\w\\BIN' }), 'C:\\W\\bin')).toBe(true);
});
});
describe('payload helpers', () => {
it('gives the server the environment the desktop shell gives it', () => {
const env = serviceEnvironment({
appDir: '/opt/w/app',
dataDir: '/home/ana/.waggle-community',
port: 4000,
platform: 'linux',
baseEnv: { PATH: '/usr/bin', WAGGLE_DATA_DIR: '/stale' },
explicitDataDir: false,
});
expect(env).toMatchObject({
WAGGLE_SKIP_LITELLM: '1',
WAGGLE_PORT: '4000',
WAGGLE_FRONTEND_DIR: '/opt/w/app/web',
NODE_PATH: '/opt/w/app/node_modules:/opt/w/app/native',
PATH: '/opt/w/app/node_modules/waggle-node-runtime/bin:/opt/w/app:/usr/bin',
NPM_CONFIG_PREFIX: '/home/ana/.waggle-community/npm/prefix',
NPM_CONFIG_CACHE: '/home/ana/.waggle-community/npm/cache',
});
expect(env.WAGGLE_DATA_DIR).toBeUndefined();
const windows = serviceEnvironment({
appDir: 'C:\\W\\app',
dataDir: 'D:\\data',
port: 3333,
platform: 'win32',
baseEnv: { Path: 'C:\\Windows' },
explicitDataDir: true,
});
expect(windows.Path).toBeUndefined();
expect(windows.PATH).toBe('C:\\W\\app\\node_modules\\waggle-node-runtime\\bin;C:\\W\\app;C:\\Windows');
expect(windows.WAGGLE_DATA_DIR).toBe('D:\\data');
});
it('writes shims that run the copied tool with the payload Node', () => {
const unix = layoutFor("/home/ana/it's/server", 'linux');
expect(shimContent(unix, 'linux')).toBe(
"#!/bin/sh\nexec '/home/ana/it'\\''s/server/app/node' '/home/ana/it'\\''s/server/launcher.mjs' \"$@\"\n",
);
const windows = layoutFor('C:\\W\\server', 'win32');
expect(shimContent(windows, 'win32')).toBe('@echo off\r\n"C:\\W\\server\\app\\node.exe" "C:\\W\\server\\launcher.mjs" %*\r\n');
expect(shimFile('C:\\W\\bin', 'waggle-server', 'win32')).toBe('C:\\W\\bin\\waggle-server.cmd');
});
it('reads sha256sum lines and bare digests', () => {
const digest = 'A'.repeat(64);
expect(parseChecksum(`${digest} waggle.tar.gz\n`)).toBe('a'.repeat(64));
expect(parseChecksum(digest)).toBe('a'.repeat(64));
expect(parseChecksum('not a digest')).toBeNull();
});
});
const target = releaseTarget(currentHost());
describe.skipIf(!target)('install, update and uninstall from a packed archive', () => {
function packArchive(): string {
const work = tempDir('waggle-archive-');
const resources = path.join(work, 'resources');
const web = path.join(work, 'web');
fs.mkdirSync(path.join(resources, 'node_modules', 'better-sqlite3'), { recursive: true });
fs.mkdirSync(path.join(resources, 'native'), { recursive: true });
fs.mkdirSync(web, { recursive: true });
fs.writeFileSync(path.join(resources, process.platform === 'win32' ? 'node.exe' : 'node'), 'not a real runtime');
fs.writeFileSync(path.join(resources, 'service.js'), 'console.log("service");\n');
fs.writeFileSync(path.join(resources, 'service.js.map'), '{}');
fs.writeFileSync(path.join(resources, 'LICENSE'), 'MIT License\n');
fs.writeFileSync(path.join(resources, 'THIRD_PARTY_NOTICES.md'), '# Third-party notices\n');
fs.writeFileSync(path.join(web, 'index.html'), '<!doctype html>');
const out = path.join(work, 'out');
const result = spawnSync(
process.execPath,
[
path.join(ROOT, 'scripts', 'build-server-archive.mjs'),
'--resources', resources, '--web', web, '--out', out, '--node-version', '22.0.0',
],
{ encoding: 'utf8' },
);
expect(result.status, result.stderr).toBe(0);
return path.join(out, assetName(VERSION, target!));
}
function context(lines: string[]): Context {
const launcher = path.join(tempDir('waggle-tool-'), 'cli.js');
fs.writeFileSync(launcher, '// bundled tool\n');
return { host: currentHost(), version: VERSION, launcherSource: launcher, out: (line) => lines.push(line) };
}
it('installs, reinstalls on request and removes the program but not the data', async () => {
const archive = packArchive();
const dir = path.join(tempDir('waggle-install-'), 'server');
const binDir = tempDir('waggle-bin-');
const dataDir = tempDir('waggle-data-');
fs.writeFileSync(path.join(dataDir, 'waggle.db'), 'user data');
const lines: string[] = [];
const ctx = context(lines);
const opts = { ...parseArgs([]).options, from: archive, dir, binDir, dataDir };
await install(ctx, opts);
const layout = layoutFor(dir, process.platform);
expect(fs.readFileSync(path.join(layout.appDir, 'service.js'), 'utf8')).toContain('service');
expect(fs.existsSync(path.join(layout.appDir, 'web', 'index.html'))).toBe(true);
expect(fs.existsSync(path.join(layout.appDir, 'service.js.map'))).toBe(false);
// UF-059: the license and the notices are installed next to service.js.
expect(fs.readFileSync(path.join(layout.appDir, 'THIRD_PARTY_NOTICES.md'), 'utf8')).toContain('Third-party notices');
expect(fs.existsSync(path.join(layout.appDir, 'LICENSE'))).toBe(true);
expect(fs.readFileSync(layout.launcherFile, 'utf8')).toBe('// bundled tool\n');
const record = readRecord(layout);
expect(record).toMatchObject({ version: VERSION, target, source: archive });
expect(record?.sha256).toBe(parseChecksum(fs.readFileSync(`${archive}.sha256`, 'utf8')));
const shim = shimFile(binDir, 'waggle-server', process.platform);
expect(fs.readFileSync(shim, 'utf8')).toContain(layout.launcherFile);
expect(record?.shim).toBe(shim);
lines.length = 0;
await install(ctx, { ...opts, from: undefined });
expect(lines.join('\n')).toMatch(/already installed/);
await install(ctx, { ...opts, force: true });
expect(fs.existsSync(path.join(dir, 'app.old'))).toBe(false);
expect(fs.existsSync(path.join(dir, 'app.new'))).toBe(false);
// The recorded shim is found without --bin-dir.
expect(await uninstall(ctx, { ...opts, binDir: undefined })).toBe(0);
expect(fs.existsSync(dir)).toBe(false);
expect(fs.existsSync(shim)).toBe(false);
expect(fs.readFileSync(path.join(dataDir, 'waggle.db'), 'utf8')).toBe('user data');
});
it('refuses an archive whose checksum does not match and keeps the installed one', async () => {
const archive = packArchive();
const dir = path.join(tempDir('waggle-install-'), 'server');
const ctx = context([]);
const opts = { ...parseArgs([]).options, from: archive, dir, binDir: tempDir('waggle-bin-') };
await install(ctx, opts);
await expect(install(ctx, { ...opts, force: true, sha256: 'b'.repeat(64) })).rejects.toThrow(UserError);
expect(fs.existsSync(path.join(dir, 'app', 'service.js'))).toBe(true);
expect(fs.existsSync(path.join(dir, 'app.new'))).toBe(false);
});
it('reports a runtime that does not start', async () => {
const archive = packArchive();
const dir = path.join(tempDir('waggle-install-'), 'server');
const lines: string[] = [];
const ctx = context(lines);
const opts = {
...parseArgs([]).options,
from: archive,
dir,
binDir: tempDir('waggle-bin-'),
dataDir: tempDir('waggle-data-'),
port: 1,
};
await install(ctx, opts);
lines.length = 0;
expect(await doctor(ctx, opts)).toBe(1);
const report = lines.join('\n');
expect(report).toMatch(/ok +Install: version/);
expect(report).toMatch(/FAIL +Node runtime: does not start/);
});
it('removes nothing from a directory that is not an install', async () => {
const dir = tempDir('waggle-not-install-');
fs.writeFileSync(path.join(dir, 'keep.txt'), 'mine');
await expect(uninstall(context([]), { ...parseArgs([]).options, dir })).rejects.toThrow(/not a Waggle server install/);
expect(fs.readFileSync(path.join(dir, 'keep.txt'), 'utf8')).toBe('mine');
});
});