Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
b39b907
test: show Install skips first boot after Set up
andersalm Nov 8, 2026
af8f889
fix: wait for first boot when the distro is already imported
andersalm Nov 8, 2026
37dff81
docs: drop comments that repeat the first-boot wait
andersalm Nov 8, 2026
8d048f4
Merge origin/test/launcher-mac-dmg into test/launcher-windows
andersalm Nov 8, 2026
b1f29a9
test: cover Open, Stop, Start, and the update check on Windows
andersalm Nov 8, 2026
0f0e6f1
Merge origin/test/launcher-mac-dmg into test/launcher-windows
andersalm Nov 8, 2026
089710b
fix: write the signed update record on Windows
andersalm Nov 8, 2026
f87e9b5
fix: start Windows Home through the update controller
andersalm Nov 8, 2026
23fd0e1
Merge origin/test/launcher-mac-dmg into test/launcher-windows
andersalm Nov 8, 2026
5e8989a
fix: cap the Windows Runtime update status read
andersalm Nov 8, 2026
e99b17c
fix: read the Windows update result from the launcher record
andersalm Nov 8, 2026
ab04442
fix: read the Windows launcher update record from the test home
andersalm Nov 8, 2026
07939c9
fix: signal only the proved Windows update controller
andersalm Nov 8, 2026
d87ed54
test: record the helper leak after a failed Windows Stop
andersalm Nov 8, 2026
0ea1baf
fix: release the Windows stop helper when Stop fails
andersalm Nov 8, 2026
bca0135
test: require the Windows facts helper to see the lock pid sockets
andersalm Nov 8, 2026
f0227b8
fix: read the distro gateway sockets from the lock pid net directory
andersalm Nov 8, 2026
41f15aa
test: a late Stop KILL must still use the original pidfd
andersalm Nov 8, 2026
51bca98
fix: refuse Windows Home unless every port 8090 listener is the WSL f…
andersalm Nov 8, 2026
387e5c1
fix: restore Windows Home open from the listen-table check
andersalm Nov 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions scripts/electron-e2e.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,12 @@ async function main() {
}

try {
if (process.platform === 'win32') {
await electronApp.evaluate(({ shell }) => {
global.__launcherOpened = [];
shell.openExternal = async (url) => { global.__launcherOpened.push(url); };
});
}
const page = await electronApp.firstWindow();
const readyDeadline = Date.now() + 60000;
let clicked = '';
Expand Down Expand Up @@ -225,6 +231,14 @@ async function main() {
executablePath: electronPath, cwd: root, args, env, timeout: 120000,
});
}
if (process.platform === 'win32') {
const opened = await electronApp.evaluate(() => global.__launcherOpened);
if (!Array.isArray(opened) || opened.length !== 0) {
throw new Error(`Install opened a browser tab after Start: ${JSON.stringify(opened)}`);
}
console.log('PASS install did not open a second browser tab');
electronApp = await require('./windows-lifecycle-e2e')(electronApp, page, home);
}
return;
}
if (errorVisible && errorText && /Set up ElastOS on Windows|Windows needs Linux support|Windows needs one step/.test(errorText)) {
Expand Down
195 changes: 195 additions & 0 deletions scripts/windows-lifecycle-e2e.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const path = require('node:path');
const { isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway');
const { runtimeDataDir, runtimeUpdateCheckPath } = require('../dist/main/targets/runtimePaths');

async function health(wanted) {
const deadline = Date.now() + 180000;
while (Date.now() < deadline) {
if (isHealthOk(await probeGatewayHealth()) === wanted) return;
await new Promise((resolve) => setTimeout(resolve, 500));
}
throw new Error(`Home health did not become ${wanted}`);
}

async function waitFor(check, timeoutMs, message) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (await check()) return;
await new Promise((resolve) => setTimeout(resolve, 500));
}
throw new Error(message);
}

async function status(page, wanted) {
await waitFor(async () => await page.evaluate(() => window.elastos.getStatus()) === wanted,
180000, `Launcher status did not become ${wanted}`);
await waitFor(async () => (await page.locator('#status-text').innerText()).toLowerCase() === wanted,
10000, `Window status did not become ${wanted}`);
}

function proveLiveController() {
const script = [
'import json, os, stat',
'LIMIT = 16384',
'ROOT = "/root/.local/share/elastos"',
'LOCK = ROOT + "/host-process.lock"',
'DIRECTORY = ROOT + "/update-controller"',
'STATUS = DIRECTORY + "/status.json"',
'REQUEST = DIRECTORY + "/request.json"',
'ACTIVE = DIRECTORY + "/active-request.json"',
'def read_text(path):',
' current = ""',
' parts = path.strip("/").split("/")',
' info = None',
' for index, part in enumerate(parts):',
' current = current + "/" + part',
' info = os.lstat(current)',
' if stat.S_ISLNK(info.st_mode):',
' raise SystemExit("refusing a link at " + current)',
' if index == len(parts) - 1:',
' if not stat.S_ISREG(info.st_mode) or info.st_size > LIMIT:',
' raise SystemExit("refusing " + path)',
' fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)',
' try:',
' data = os.read(fd, LIMIT + 1)',
' finally:',
' os.close(fd)',
' if len(data) > LIMIT:',
' raise SystemExit("refusing " + path)',
' return data.decode("utf-8", "replace")',
'def start_id(pid):',
' raw = read_text("/proc/%d/stat" % pid)',
' tail = raw.rsplit(")", 1)[1].split()',
' start = tail[19]',
' boot = read_text("/proc/sys/kernel/random/boot_id").strip()',
' if boot:',
' return "linux:%s:%s" % (boot, start)',
' return "linux:%s" % start',
'def ppid_of(pid):',
' for line in read_text("/proc/%d/status" % pid).splitlines():',
' if line.startswith("PPid:"):',
' return int(line.split()[1])',
' raise SystemExit("no parent")',
'def command_of(pid):',
' fd = os.open("/proc/%d/cmdline" % pid, os.O_RDONLY | os.O_NOFOLLOW)',
' try:',
' data = os.read(fd, LIMIT)',
' finally:',
' os.close(fd)',
' return data.replace(b"\\x00", b" ").decode("utf-8", "replace")',
'status = json.loads(read_text(STATUS))',
'lock = json.loads(read_text(LOCK))',
'phase = status.get("phase")',
'if phase not in ("ready", "updated", "restored", "failed"):',
' raise SystemExit("phase " + str(phase))',
'controller = status.get("controller_pid")',
'host = status.get("host_pid")',
'if type(controller) is not int or type(host) is not int or controller <= 1 or host <= 1:',
' raise SystemExit("pid")',
'if lock.get("pid") != host or lock.get("addr") != "localhost:8090":',
' raise SystemExit("lock")',
'if not status.get("generation") or lock.get("generation") != status.get("generation"):',
' raise SystemExit("generation")',
'if start_id(controller) != status.get("controller_start"):',
' raise SystemExit("controller is not the live process")',
'if ppid_of(host) != controller:',
' raise SystemExit("host parent")',
'controller_command = command_of(controller)',
'host_command = command_of(host)',
'if "update-controller/runtime" not in controller_command or "__update-controller" not in controller_command:',
' raise SystemExit("controller command")',
'if "home" not in host_command or "--browser" not in host_command:',
' raise SystemExit("host command")',
'if os.path.lexists(REQUEST) or os.path.lexists(ACTIVE):',
' raise SystemExit("queue is not empty")',
'print(json.dumps({"phase": phase, "queue": "empty", "controller": controller, "host": host}))',
].join('\n');
const result = spawnSync('wsl.exe', ['-d', 'ElastOS', '-u', 'root', '--', 'python3', '-'], {
input: script,
encoding: 'utf8',
timeout: 60000,
windowsHide: true,
});
if (result.status !== 0) {
throw new Error((result.stderr || result.stdout || 'The update controller was not proved.').trim());
}
const proof = JSON.parse(result.stdout);
assert.equal(proof.queue, 'empty');
assert.equal(['ready', 'updated', 'restored', 'failed'].includes(proof.phase), true);
console.log(`PASS controller phase ${proof.phase} is live and the update queue is empty (controller ${proof.controller}, host ${proof.host})`);
console.log('NOT RUN: a System update apply. No newer signed release exists, and apply needs an owner step-up token.');
}

function distroUpdateCheck() {
const file = runtimeUpdateCheckPath(runtimeDataDir('linux', '/root', {}));
const result = spawnSync('wsl.exe', ['-d', 'ElastOS', '-u', 'root', '--', 'cat', file], {
encoding: 'utf8',
timeout: 60000,
windowsHide: true,
});
if (result.status !== 0) {
const detail = `${result.stderr || ''} ${result.stdout || ''}`;
if (!/No such file or directory/.test(detail)) {
throw new Error(detail.trim() || 'The update check file could not be read.');
}
return null;
}
return JSON.parse(result.stdout);
}

function launcherUpdateCheck(home) {
const file = path.join(home, '.elastos-launcher', 'update-check.json');
if (!fs.existsSync(file)) return null;
return JSON.parse(fs.readFileSync(file, 'utf8'));
}

module.exports = async function (app, page, home) {
await app.evaluate(({ shell }) => {
global.__openedHome = [];
shell.openExternal = async (url) => { global.__openedHome.push(url); };
});
await page.click('#open-btn');
assert.deepEqual(await app.evaluate(() => global.__openedHome), ['http://localhost:8090/home/']);
const response = await fetch('http://localhost:8090/home/');
assert.equal(response.status, 200);
console.log('PASS Open Home invokes the browser with localhost:8090/home/ and Home returns HTTP 200');

await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].close());
await new Promise((resolve) => setTimeout(resolve, 2500));
assert.equal(await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isVisible()), false);
await health(true);
console.log('PASS closing the window keeps Home running');
await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].show());

await page.click('#power-btn');
await status(page, 'stopped');
await health(false);
console.log('PASS Stop Home closes the listener');
await page.click('#open-btn');
await status(page, 'running');
await health(true);
console.log('PASS Start Home becomes healthy');
assert.deepEqual(await app.evaluate(() => global.__openedHome), ['http://localhost:8090/home/']);
const logs = await page.locator('#logs-content').innerText();
assert.equal(logs.includes('Keep this terminal open. Press Ctrl+C to stop Home.'), false);
proveLiveController();

const checked = await page.evaluate(() => window.elastos.checkForUpdate());
assert.equal(checked.updateAvailable, false);
const runtime = distroUpdateCheck();
if (runtime) {
assert.equal(runtime.outcome, 'up_to_date');
assert.equal(runtime.offered, false);
console.log('PASS elastos update --check keeps the Runtime up_to_date record');
} else {
const launcher = launcherUpdateCheck(home);
assert.ok(launcher);
assert.equal(launcher.outcome, 'up_to_date');
assert.equal(launcher.offered, false);
console.log('PASS elastos update --check stores up_to_date in the launcher record');
}
return app;
};
3 changes: 3 additions & 0 deletions src/main/launchController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ export interface LaunchInfo {
browserNote: string | null;
/** Windows: Uninstall saves the whole Linux environment as one file, then removes it. */
uninstallRemovesLinux: boolean;
/** `home --browser` opens one tab. The launcher does not open a second one after Start. */
runtimeOpensBrowser: boolean;
preflight: PreflightReport;
openAtLogin: boolean;
canRollback: boolean;
Expand Down Expand Up @@ -286,6 +288,7 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L
error: status === 'error' ? lastError : null,
platformNote: platform?.message ?? null,
browserNote: browserNote(process.platform),
runtimeOpensBrowser: process.platform === 'darwin' || process.platform === 'win32',
uninstallRemovesLinux: process.platform === 'win32',
preflight,
openAtLogin: readOpenAtLogin(),
Expand Down
52 changes: 36 additions & 16 deletions src/main/targets/runtimeGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ export interface GatewayProcess {
onExit(listener: (code: number | null) => void): void;
signal(signal: NodeJS.Signals): void;
hasExited(): boolean | Promise<boolean>;
/** Drop a stop helper. A process that has none does not implement this. */
dispose?(): void;
}

/**
Expand Down Expand Up @@ -318,12 +320,16 @@ export function isHealthOk(result: HealthResult | null): boolean {
return Boolean(result && result.status === 200 && result.body.trim() === 'OK');
}

/** The controller prints this on its own stdout. The launcher log does not show it. */
export const HOME_TERMINAL_LINE = 'Keep this terminal open. Press Ctrl+C to stop Home.';

/** Drop lines that can carry attach_secret. The coords files stay on disk, out of the log. */
export function scrubRuntimeLog(chunk: string): string {
if (/attach_secret|runtime-coords\.json|gateway-runtime-coords|home-runtime-coords/i.test(chunk)) {
return '[elastos] omitted a line that can contain a local secret\n';
}
return chunk;
if (!chunk.includes(HOME_TERMINAL_LINE)) return chunk;
return chunk.split(HOME_TERMINAL_LINE).join('');
}

export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySupervisor {
Expand Down Expand Up @@ -357,8 +363,13 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup
: `ElastOS stopped (exit ${code}). Click Start to try again.`);
}

function ownAdopted(proc: GatewayProcess | null): void {
function replaceOwned(proc: GatewayProcess | null): void {
if (owned && owned !== proc) owned.dispose?.();
owned = proc;
}

function ownAdopted(proc: GatewayProcess | null): void {
replaceOwned(proc);
proc?.onExit((code) => recordExit(proc, code));
}

Expand All @@ -379,7 +390,7 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup
intentionalStop = false;
foreign = false;
const proc = deps.spawn(deps.binary, deps.args ?? GATEWAY_ARGS);
owned = proc;
replaceOwned(proc);
let output = '';
let exited = false;
let exitCode: number | null = null;
Expand Down Expand Up @@ -491,20 +502,27 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup
async function stopProcess(proc: GatewayProcess): Promise<void> {
intentionalStop = true;
current = 'stopping';
proc.signal('SIGTERM');
if (await confirmedStopped(proc, graceMs)) {
owned = null;
current = 'stopped';
return;
}
proc.signal('SIGKILL');
if (await confirmedStopped(proc, graceMs)) {
owned = null;
current = 'stopped';
return;
try {
proc.signal('SIGTERM');
if (await confirmedStopped(proc, graceMs)) {
proc.dispose?.();
owned = null;
current = 'stopped';
return;
}
proc.signal('SIGKILL');
if (await confirmedStopped(proc, graceMs)) {
proc.dispose?.();
owned = null;
current = 'stopped';
return;
}
current = 'error';
throw new Error('ElastOS is still running.');
} catch (err) {
proc.dispose?.();
throw err;
}
current = 'error';
throw new Error('ElastOS is still running.');
}

const supervisor: GatewaySupervisor = {
Expand Down Expand Up @@ -591,11 +609,13 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup
},
forceKill() {
if (!owned) return;
const failed = current === 'error';
try {
owned.signal('SIGKILL');
} catch {
// Quit still closes. The error from stop() is logged by the caller.
}
if (failed) owned.dispose?.();
},
openHome() {
deps.openUrl(HOME_URL);
Expand Down
13 changes: 10 additions & 3 deletions src/main/targets/runtimeTarget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform
}

function changeRuntime(action: () => Promise<void>): Promise<void> {
if (platform !== 'darwin') return serialize(action);
if (platform !== 'darwin' && platform !== 'win32') return serialize(action);
if (updating) return Promise.reject(new Error('An ElastOS update is already running.'));
updating = true;
requestedRunning = true;
Expand Down Expand Up @@ -113,13 +113,20 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform
if (supervisor) {
const phase = observedPhase;
if (phase === 'starting' || phase === 'stopping' || phase === 'error'
|| (phase === 'running' && platform !== 'darwin')) {
|| (phase === 'running' && platform !== 'darwin' && platform !== 'win32')) {
return phase;
}
}
if (platform === 'win32') {
if (!distroIsInstalled()) return 'not-installed';
if (isHealthOk(await readHealth())) return 'running';
if (isHealthOk(await readHealth())) {
// A live controller keeps Home up after the child pid changes. Health
// and the distro facts are the status, not the supervisor's old phase.
if (!(await confirmInstalledGateway())) {
throw new Error('Another program is answering on port 8090. Home was not adopted.');
}
return 'running';
}
return 'stopped';
}
if (runtimeInstallBlock(platform, arch)) return 'not-installed';
Expand Down
Loading
Loading