From b39b9072cd071a786b1167a7c0582d529ef0236d Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 20:54:58 -0500 Subject: [PATCH 01/17] test: show Install skips first boot after Set up Set up imports the distro and returns while it is stopped. The next Install click is the first command into that distro. These tests fail while that command is still the 20 second tool check. Co-authored-by: Cursor --- src/main/targets/windowsRuntime.ts | 31 ++++++++++++---- test/windows-app-install.test.js | 58 +++++++++++++++++++++++++++++- 2 files changed, 81 insertions(+), 8 deletions(-) diff --git a/src/main/targets/windowsRuntime.ts b/src/main/targets/windowsRuntime.ts index 57fb50f..bffde49 100644 --- a/src/main/targets/windowsRuntime.ts +++ b/src/main/targets/windowsRuntime.ts @@ -416,11 +416,22 @@ function distroInstallDeps(): RuntimeInstallDeps { export async function installRuntimeInsideDistro( onProgress: (message: string) => void = () => {}, + // Tests pass host so this function can run without wsl.exe. Production omits it. + host: { + lookupWsl?: () => Promise; + listDistros?: () => Promise; + ensureRootfs?: () => Promise; + importDistro?: (installDir: string, rootfs: string) => Promise; + prepareImportDir?: (dir: string) => void; + runInDistro?: (args: readonly string[], timeoutMs: number) => Promise; + continueInstall?: (onProgress: (message: string) => void) => Promise; + } = {}, ): Promise { + const run = host.runInDistro ?? ((args: readonly string[], timeoutMs: number) => runWsl(args, timeoutMs)); await ensureElastosDistro({ - lookupWsl: () => lookupCommand('wsl.exe'), - listDistros, - ensureRootfs: () => ensureElastosRootfs({ + lookupWsl: host.lookupWsl ?? (() => lookupCommand('wsl.exe')), + listDistros: host.listDistros ?? listDistros, + ensureRootfs: host.ensureRootfs ?? (() => ensureElastosRootfs({ dest: path.join(os.homedir(), '.elastos-launcher', 'ubuntu-noble-wsl.rootfs.tar.gz'), exists: (file) => { try { return fs.statSync(file).isFile(); } catch { return false; } @@ -428,12 +439,18 @@ export async function installRuntimeInsideDistro( download: downloadPinnedRootfs, read: (file) => fs.readFileSync(file), accept: assertPinnedRootfs, - }), - importDistro: (installDir, rootfs) => runHost(importDistroArgs(installDir, rootfs), 10 * 60 * 1000), - hasTools: async () => (await runWsl(distroToolCheckArgs(), 20000)).code === 0, - installTools: async () => (await runWsl(distroPackageArgs(), 10 * 60 * 1000)).code, + })), + importDistro: host.importDistro ?? ((installDir, rootfs) => runHost(importDistroArgs(installDir, rootfs), 10 * 60 * 1000)), + prepareImportDir: host.prepareImportDir, + runInDistro: run, + hasTools: async () => (await run(distroToolCheckArgs(), 20000)).code === 0, + installTools: async () => (await run(distroPackageArgs(), 10 * 60 * 1000)).code, onProgress, }); + if (host.continueInstall) { + await host.continueInstall(onProgress); + return; + } await installRuntime(distroInstallDeps(), onProgress); } diff --git a/test/windows-app-install.test.js b/test/windows-app-install.test.js index 0dc95ba..6125aa0 100644 --- a/test/windows-app-install.test.js +++ b/test/windows-app-install.test.js @@ -21,6 +21,7 @@ const { DISTRO_INSTALL_DIR, DISTRO_SETUP_FAILED, ensureElastosDistro, + installRuntimeInsideDistro, factsAreElastos, readDistroLockPid, signalDistroGateway, @@ -28,7 +29,7 @@ const { wslSpawnEnv, } = require('../dist/main/targets/windowsRuntime'); const { createGatewaySupervisor } = require('../dist/main/targets/runtimeGateway'); -const { importDistroArgs } = require('../dist/main/targets/windowsHost'); +const { applyWindowsFix, importDistroArgs } = require('../dist/main/targets/windowsHost'); const { INSTALLER_ENV_NAMES } = require('../dist/main/targets/releaseHead'); const HEAD = 'QmXuy56RTFzXaifTuyCbMb6Ky1p5wuM9iP8eFbMghHxWij'; @@ -176,6 +177,61 @@ test('ensuring the distro imports the pinned rootfs and hides command failures', }); }); +const STOPPED_DISTRO = ' NAME STATE VERSION\n* ElastOS Stopped 2\n'; + +function importedDistroHost(runInDistro, extra = {}) { + return { + lookupWsl: async () => true, + listDistros: async () => STOPPED_DISTRO, + ensureRootfs: async () => { throw new Error('Install must not download the rootfs'); }, + importDistro: async () => { throw new Error('Install must not import again'); }, + runInDistro, + ...extra, + }; +} + +test('Install waits for first boot after Set up imported the distro', async () => { + const setup = []; + await applyWindowsFix( + { platform: 'win32', arch: 'x64', wslInstalled: true, distroReady: false }, + { + spawnHidden: async (file, args) => { + setup.push([file, ...args]); + return { code: 0, stdout: '', stderr: '' }; + }, + ensureRootfs: async () => 'C:\\ElastOS\\ubuntu-noble-wsl.rootfs.tar.gz', + prepareImportDir() {}, + }, + ); + assert.equal(setup.some((row) => row.includes('--import')), true); + assert.equal(setup.some((row) => row.includes('-d')), false); + + const commands = []; + await installRuntimeInsideDistro(() => {}, importedDistroHost( + async (args, timeoutMs) => { + commands.push({ args: [...args], timeoutMs }); + return { code: 0, stdout: '', stderr: '' }; + }, + { continueInstall: async () => { commands.push({ args: ['install-runtime'], timeoutMs: 0 }); } }, + )); + assert.deepEqual(commands[0], { args: ['true'], timeoutMs: 3 * 60 * 1000 }); + assert.match(commands[1].args.join(' '), /command -v python3/); + assert.equal(commands[1].timeoutMs, 20000); + assert.deepEqual(commands[2], { args: ['install-runtime'], timeoutMs: 0 }); +}); + +test('Install stops when first boot of an imported distro does not finish', async () => { + let continued = false; + await assert.rejects(() => installRuntimeInsideDistro(() => {}, importedDistroHost( + async () => { throw new Error('timed out'); }, + { continueInstall: async () => { continued = true; } }, + )), (err) => { + assert.equal(err.message, DISTRO_SETUP_FAILED); + return true; + }); + assert.equal(continued, false); +}); + test('the distro gateway identity uses the lock pid socket and a positive wsl pid', () => { const tcp = [ ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode', From af8f88929562f9be480b84b76de2bc918929fc32 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 20:55:07 -0500 Subject: [PATCH 02/17] fix: wait for first boot when the distro is already imported The 3 minute wait ran only when Install itself imported the distro. Set up imports first, so Install saw a listed distro and used the 20 second tool check for the first boot. CI run 42237456986 failed 20.3 seconds after that click. Co-authored-by: Cursor --- src/main/targets/windowsRuntime.ts | 20 ++++++++++---------- test/windows-app-install.test.js | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/targets/windowsRuntime.ts b/src/main/targets/windowsRuntime.ts index bffde49..08c2001 100644 --- a/src/main/targets/windowsRuntime.ts +++ b/src/main/targets/windowsRuntime.ts @@ -315,24 +315,24 @@ export async function ensureElastosDistro(deps: { lookup: async () => true, listDistros: deps.listDistros, }); + const run = deps.runInDistro ?? ((args, timeoutMs) => runWsl(args, timeoutMs)); if (!facts.distroReady) { const rootfs = await deps.ensureRootfs(); deps.onProgress('Rootfs SHA-256 matches the pin'); (deps.prepareImportDir ?? prepareImportDir)(DISTRO_INSTALL_DIR); const code = await deps.importDistro(DISTRO_INSTALL_DIR, rootfs); if (code !== 0) throw new Error(DISTRO_IMPORT_FAILED); - // The first command can block while the rootfs finishes its first boot. - // The tool check's 20 seconds is too short for that. deps.onProgress('Starting the Linux environment for the first time'); - const run = deps.runInDistro ?? ((args, timeoutMs) => runWsl(args, timeoutMs)); - let booted: WslResult; - try { - booted = await run(['true'], DISTRO_FIRST_BOOT_MS); - } catch { - throw new Error(DISTRO_SETUP_FAILED); - } - if (booted.code !== 0) throw new Error(DISTRO_SETUP_FAILED); } + // Set up imports the distro and returns while it is still stopped. + // The first command blocks in first boot. The tool check allows 20 seconds. + let booted: WslResult; + try { + booted = await run(['true'], DISTRO_FIRST_BOOT_MS); + } catch { + throw new Error(DISTRO_SETUP_FAILED); + } + if (booted.code !== 0) throw new Error(DISTRO_SETUP_FAILED); if (!(await deps.hasTools())) { const code = await deps.installTools(); if (code !== 0) throw new Error(DISTRO_SETUP_FAILED); diff --git a/test/windows-app-install.test.js b/test/windows-app-install.test.js index 6125aa0..3159d9e 100644 --- a/test/windows-app-install.test.js +++ b/test/windows-app-install.test.js @@ -157,7 +157,7 @@ test('ensuring the distro imports the pinned rootfs and hides command failures', assert.equal(/wsl\.exe|powershell|\bbash\b|apt-get/.test(err.message), false); return true; }); - assert.deepEqual(existingBoot, []); + assert.deepEqual(existingBoot, ['boot']); assert.equal(existingProgress.includes('Starting the Linux environment for the first time'), false); await assert.rejects(() => ensureElastosDistro({ From 37dff81cb320deb5ae521a510b227270fa4ddae5 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 20:59:40 -0500 Subject: [PATCH 03/17] docs: drop comments that repeat the first-boot wait The wait, the 20 second tool check, and the test already show the order. A second copy of that fact in a comment is not needed. Co-authored-by: Cursor --- src/main/targets/windowsRuntime.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/targets/windowsRuntime.ts b/src/main/targets/windowsRuntime.ts index 08c2001..185ec42 100644 --- a/src/main/targets/windowsRuntime.ts +++ b/src/main/targets/windowsRuntime.ts @@ -324,8 +324,6 @@ export async function ensureElastosDistro(deps: { if (code !== 0) throw new Error(DISTRO_IMPORT_FAILED); deps.onProgress('Starting the Linux environment for the first time'); } - // Set up imports the distro and returns while it is still stopped. - // The first command blocks in first boot. The tool check allows 20 seconds. let booted: WslResult; try { booted = await run(['true'], DISTRO_FIRST_BOOT_MS); @@ -416,7 +414,6 @@ function distroInstallDeps(): RuntimeInstallDeps { export async function installRuntimeInsideDistro( onProgress: (message: string) => void = () => {}, - // Tests pass host so this function can run without wsl.exe. Production omits it. host: { lookupWsl?: () => Promise; listDistros?: () => Promise; From b1f29a9a37193b40830122afc686366f21a7e838 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 21:07:39 -0500 Subject: [PATCH 04/17] test: cover Open, Stop, Start, and the update check on Windows The Windows Install job reached Open my computer and /healthz. It did not click Open Home, Stop, Start, or the update check. Co-authored-by: Cursor --- scripts/electron-e2e.js | 3 ++ scripts/windows-lifecycle-e2e.js | 77 ++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 scripts/windows-lifecycle-e2e.js diff --git a/scripts/electron-e2e.js b/scripts/electron-e2e.js index 8a19141..942240d 100644 --- a/scripts/electron-e2e.js +++ b/scripts/electron-e2e.js @@ -213,6 +213,9 @@ async function main() { executablePath: electronPath, cwd: root, args, env, timeout: 120000, }); } + if (process.platform === 'win32') { + electronApp = await require('./windows-lifecycle-e2e')(electronApp, page); + } return; } if (errorVisible && errorText && /Set up ElastOS on Windows|Windows needs Linux support|Windows needs one step/.test(errorText)) { diff --git a/scripts/windows-lifecycle-e2e.js b/scripts/windows-lifecycle-e2e.js new file mode 100644 index 0000000..0c7b05a --- /dev/null +++ b/scripts/windows-lifecycle-e2e.js @@ -0,0 +1,77 @@ +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +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 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) { + throw new Error(result.stderr || 'The update check file could not be read.'); + } + return JSON.parse(result.stdout); +} + +module.exports = async function (app, page) { + 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'); + + const checked = await page.evaluate(() => window.elastos.checkForUpdate()); + assert.equal(checked.updateAvailable, false); + const update = distroUpdateCheck(); + assert.equal(update.outcome, 'up_to_date'); + console.log('PASS elastos update --check writes up_to_date'); + return app; +}; From 089710bbab3385f995d04d6d35ad361d5ffa9146 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 21:19:31 -0500 Subject: [PATCH 05/17] fix: write the signed update record on Windows Runtime 2.0.0 does not write update-check.json. The Mac branch derives that record from the signed head. Windows now writes the same record inside the distro. Co-authored-by: Cursor --- src/main/targets/runtimeTarget.ts | 42 +++++++++++++++++++-- src/main/targets/windowsRuntime.ts | 4 ++ test/runtime-update.test.js | 60 ++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 3 deletions(-) diff --git a/src/main/targets/runtimeTarget.ts b/src/main/targets/runtimeTarget.ts index 21e6cc8..5e3784d 100644 --- a/src/main/targets/runtimeTarget.ts +++ b/src/main/targets/runtimeTarget.ts @@ -35,6 +35,7 @@ import { readDistroUpdateStatus, readDistroVersion, runDistroRuntimeCommand, + writeDistroUpdateStatus, } from './windowsRuntime'; import { LaunchTarget, UpdateCheck } from './types'; @@ -175,9 +176,15 @@ async function runtimeCheckForUpdate(): Promise { latest: null, }, releaseUrl); if (process.platform === 'win32') { - if (!distroIsInstalled()) return notInstalled; - const parsed = await checkRuntimeUpdate(runDistroRuntimeCommand, readDistroUpdateStatus); - return toUpdateCheck(readDistroVersion(), parsed, releaseUrl); + return checkDistroRuntimeUpdate({ + installed: distroIsInstalled, + current: readDistroVersion, + run: runDistroRuntimeCommand, + readStatus: readDistroUpdateStatus, + writeStatus: writeDistroUpdateStatus, + fetchText: runtimeInstall.fetchRuntimeText, + releaseUrl, + }); } if (runtimeInstallBlock(process.platform, process.arch)) return notInstalled; if (!findRuntimeBinary(os.homedir(), process.env.PATH ?? '')) return notInstalled; @@ -189,6 +196,35 @@ async function runtimeCheckForUpdate(): Promise { return toUpdateCheck(current, parsed, releaseUrl); } +export async function checkDistroRuntimeUpdate(deps: { + installed: () => boolean; + current: () => string; + run: RuntimeCommand; + readStatus: () => string; + writeStatus: (raw: string) => void; + fetchText: (url: string) => Promise; + releaseUrl: string; + pin?: ReturnType; +}): Promise { + const notInstalled = toUpdateCheck('not installed', { + updateAvailable: false, + detail: 'not installed', + latest: null, + }, deps.releaseUrl); + if (!deps.installed()) return notInstalled; + const current = deps.current(); + const compatibilityRecord = runtimeInstall.installedVersionMatches(current, '2.0.0') + ? () => writeSignedUpdateCheck( + current, + deps.pin ?? loadActiveRuntimePin(), + deps.fetchText, + deps.writeStatus, + ) + : undefined; + const parsed = await checkRuntimeUpdate(deps.run, deps.readStatus, compatibilityRecord); + return toUpdateCheck(current, parsed, deps.releaseUrl); +} + export async function rollbackRuntimeUpdate( onProgress: (message: string) => void = () => {}, ): Promise { diff --git a/src/main/targets/windowsRuntime.ts b/src/main/targets/windowsRuntime.ts index 185ec42..87e2818 100644 --- a/src/main/targets/windowsRuntime.ts +++ b/src/main/targets/windowsRuntime.ts @@ -205,6 +205,10 @@ export function readDistroUpdateStatus(): string { return readDistroFile(runtimeUpdateCheckPath(runtimeDataDir('linux', DISTRO_HOME, {}))); } +export function writeDistroUpdateStatus(raw: string): void { + writeDistroFile(runtimeUpdateCheckPath(runtimeDataDir('linux', DISTRO_HOME, {})), raw); +} + export function distroPackageArgs(): readonly string[] { return ['bash', '-lc', 'printf "nameserver 8.8.8.8\\n" > /etc/resolv.conf; apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 curl ca-certificates']; } diff --git a/test/runtime-update.test.js b/test/runtime-update.test.js index ccba8e0..e3e553f 100644 --- a/test/runtime-update.test.js +++ b/test/runtime-update.test.js @@ -222,3 +222,63 @@ test('Runtime 2.0.0 gets the #61 status record only after a successful check and () => raw, () => bridge(fixture.SIGNED_HEAD)), /network failed/); assert.equal(raw, undefined); }); + +test('Windows 2.0.0 update check writes the signed record and ignores the command text', async () => { + const fixture = require('./helpers/signed-release'); + const { checkDistroRuntimeUpdate } = require('../dist/main/targets/runtimeTarget'); + const pin = { channel: 'stable', version: '2.0.0', headCid: null, publishable: true, + maintainerDid: fixture.FIXTURE_DID, publisherGateway: 'https://publisher.example' }; + let raw; + let ran = false; + const absent = () => { throw new Error('missing'); }; + const result = await checkDistroRuntimeUpdate({ + installed: () => true, + current: () => 'ElastOS Runtime v2.0.0', + run: async (args) => { + ran = true; + assert.deepEqual(args, ['update', '--check']); + return { code: 0, stdout: 'update available 9.9.9\n', stderr: '' }; + }, + readStatus: () => { + if (raw === undefined) throw new Error('missing'); + return raw; + }, + writeStatus: (value) => { raw = value; }, + fetchText: async () => fixture.SIGNED_HEAD, + pin, + releaseUrl: 'https://publisher.example', + }); + assert.equal(ran, true); + assert.equal(result.updateAvailable, false); + assert.equal(result.current, 'ElastOS Runtime v2.0.0'); + assert.equal(JSON.parse(raw).outcome, 'up_to_date'); + + raw = undefined; + ran = false; + const missing = await checkDistroRuntimeUpdate({ + installed: () => false, + current: () => 'ElastOS Runtime v2.0.0', + run: async () => { ran = true; return { code: 0, stdout: '', stderr: '' }; }, + readStatus: absent, + writeStatus: () => { raw = 'written'; }, + fetchText: async () => fixture.SIGNED_HEAD, + pin, + releaseUrl: 'https://publisher.example', + }); + assert.equal(ran, false); + assert.equal(raw, undefined); + assert.equal(missing.updateAvailable, false); + assert.equal(missing.current, 'not installed'); + + await assert.rejects(() => checkDistroRuntimeUpdate({ + installed: () => true, + current: () => 'ElastOS Runtime v2.0.0', + run: async () => ({ code: 1, stdout: '', stderr: 'network failed' }), + readStatus: absent, + writeStatus: (value) => { raw = value; }, + fetchText: async () => fixture.SIGNED_HEAD, + pin, + releaseUrl: 'https://publisher.example', + }), /network failed/); + assert.equal(raw, undefined); +}); From f87e9b52ecf50db1467a1ac8e966c09b7f86830b Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 7 Nov 2026 22:06:41 -0500 Subject: [PATCH 06/17] fix: start Windows Home through the update controller elastos gateway never enters the update controller, so System update inside Home cannot run on Windows. Start home --browser, signal the proved controller on Stop, and start Home again after Update and Undo. Co-authored-by: Cursor --- scripts/electron-e2e.js | 11 + scripts/windows-lifecycle-e2e.js | 97 +++++++++ src/main/launchController.ts | 6 +- src/main/targets/runtimeGateway.ts | 6 +- src/main/targets/runtimeTarget.ts | 58 +++-- src/main/targets/types.ts | 2 + src/main/targets/windowsRuntime.ts | 325 ++++++++++++++++++++++++++--- src/preload/index.ts | 1 + src/renderer/app.js | 5 +- src/renderer/flow.js | 6 + test/installer-ux.test.js | 3 + test/runtime-gateway.test.js | 5 + test/runtime-update.test.js | 24 +++ test/windows-app-install.test.js | 105 +++++++++- 14 files changed, 598 insertions(+), 56 deletions(-) diff --git a/scripts/electron-e2e.js b/scripts/electron-e2e.js index 942240d..83e547d 100644 --- a/scripts/electron-e2e.js +++ b/scripts/electron-e2e.js @@ -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 = ''; @@ -214,6 +220,11 @@ async function main() { }); } 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); } return; diff --git a/scripts/windows-lifecycle-e2e.js b/scripts/windows-lifecycle-e2e.js index 0c7b05a..0ed000e 100644 --- a/scripts/windows-lifecycle-e2e.js +++ b/scripts/windows-lifecycle-e2e.js @@ -28,6 +28,99 @@ async function status(page, 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], { @@ -67,6 +160,10 @@ module.exports = async function (app, page) { 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); diff --git a/src/main/launchController.ts b/src/main/launchController.ts index a109b59..a788466 100644 --- a/src/main/launchController.ts +++ b/src/main/launchController.ts @@ -10,7 +10,6 @@ import { setRuntimeLogSink } from './targets/runtimeGateway'; import { loadActiveRuntimePin } from './targets/runtimePin'; import { browserNote } from './targets/runtimeSupport'; import { runtimeHeadStore } from './targets/runtimeUpdate'; -import { rollbackRuntimeUpdate } from './targets/runtimeTarget'; import { BackupDescription, describeRuntimeBackupOnThisComputer } from './targets/runtimeBackup'; import { resetRuntimeOnThisComputer, ResetResult } from './targets/runtimeUninstall'; import { describeDistroBackupOnThisComputer, resetRuntimeInDistroOnThisComputer } from './targets/windowsReset'; @@ -126,6 +125,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; @@ -258,7 +259,7 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L describeResetBackup: () => (process.platform === 'win32' ? describeDistroBackupOnThisComputer() : describeRuntimeBackupOnThisComputer()), - rollback: (onProgress) => runRuntime(() => rollbackRuntimeUpdate(onProgress)), + rollback: (onProgress) => runRuntime(() => active.rollback(onProgress ?? (() => {}))), getVersion: () => runRuntimeSync(() => active.getVersion()), checkForUpdate: () => runRuntime(() => active.checkForUpdate()), openInBrowser: () => { @@ -285,6 +286,7 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L status, platformNote: platform?.message ?? null, browserNote: browserNote(process.platform), + runtimeOpensBrowser: process.platform === 'darwin' || process.platform === 'win32', uninstallRemovesLinux: process.platform === 'win32', preflight, openAtLogin: readOpenAtLogin(), diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index c168918..b67060f 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -311,12 +311,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 { diff --git a/src/main/targets/runtimeTarget.ts b/src/main/targets/runtimeTarget.ts index 5e3784d..d7fccff 100644 --- a/src/main/targets/runtimeTarget.ts +++ b/src/main/targets/runtimeTarget.ts @@ -56,6 +56,31 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform await supervisor.stop({ adopt }); } + /** Stop Home, run one release command, then start `home --browser` again. */ + async function restartHomeAfter(run: () => Promise): Promise { + if (updating) throw new Error('An ElastOS update is already running.'); + updating = true; + try { + await stopGateway(true); + await run(); + } finally { + supervisor = null; + try { + if (platform === 'win32') { + if (!distroIsInstalled()) throw new Error('ElastOS is not installed yet. Click Install.'); + supervisor = createDistroGatewaySupervisor(); + } else { + const file = binary(); + if (!file) throw new Error('ElastOS is not installed yet. Click Install.'); + supervisor = createDefaultGatewaySupervisor(file, platform); + } + await supervisor.start(); + } finally { + updating = false; + } + } + } + return { id: 'runtime', descriptor: RUNTIME_TARGET, @@ -65,13 +90,20 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform if (supervisor) { const phase = supervisor.phase(); 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, process.arch)) return 'not-installed'; @@ -116,24 +148,14 @@ export function createRuntimeTarget(platform: NodeJS.Platform = process.platform }, install: (onProgress) => runtimeInstall.installRuntimeOnThisComputer(onProgress), update: async (onProgress) => { - if (platform !== 'darwin') return applyRuntimeUpdate(runtimeCommand(), runtimeHeadStore(), headVerify(), onProgress); - if (updating) throw new Error('An ElastOS update is already running.'); - updating = true; - try { - await stopGateway(true); - await applyRuntimeUpdate(runtimeCommand(), runtimeHeadStore(), headVerify(), onProgress); - } finally { - supervisor = null; - try { - const file = binary(); - if (!file) throw new Error('ElastOS is not installed yet. Click Install.'); - supervisor = createDefaultGatewaySupervisor(file, platform); - await supervisor.start(); - } finally { - updating = false; - } + if (platform !== 'darwin' && platform !== 'win32') { + return applyRuntimeUpdate(runtimeCommand(), runtimeHeadStore(), headVerify(), onProgress); } + await restartHomeAfter(() => applyRuntimeUpdate(runtimeCommand(), runtimeHeadStore(), headVerify(), onProgress)); }, + rollback: (onProgress) => (platform === 'win32' + ? restartHomeAfter(() => rollbackRuntimeUpdate(onProgress)) + : rollbackRuntimeUpdate(onProgress)), // On Windows the launch controller runs uninstallRuntimeInDistro (windowsUninstall.ts) with the two answers. uninstall: () => (platform === 'win32' ? Promise.reject(new Error('Uninstall on Windows needs your answer in the Uninstall window. Nothing was removed.')) : runtimeUninstall(() => stopGateway(true))), getVersion: () => (platform === 'win32' ? readDistroVersion() : readRuntimeVersion()), diff --git a/src/main/targets/types.ts b/src/main/targets/types.ts index dcf0dce..7e5d452 100644 --- a/src/main/targets/types.ts +++ b/src/main/targets/types.ts @@ -66,6 +66,8 @@ export interface LaunchTarget { restart(): Promise; install(onProgress: (message: string) => void): Promise; update(onProgress: (message: string) => void): Promise; + /** Stop Home, restore the previous release, and start it again on Windows. */ + rollback(onProgress: (message: string) => void): Promise; uninstall(): Promise; getVersion(): string; checkForUpdate(): Promise; diff --git a/src/main/targets/windowsRuntime.ts b/src/main/targets/windowsRuntime.ts index 87e2818..dd8f535 100644 --- a/src/main/targets/windowsRuntime.ts +++ b/src/main/targets/windowsRuntime.ts @@ -13,7 +13,6 @@ import { WINDOWS_NATIVE_MESSAGE } from './runtimeSupport'; import { createGatewaySupervisor, emitRuntimeLog, - GATEWAY_ARGS, GatewayProcess, InstalledGatewayKind, installedGatewayKind, @@ -185,8 +184,233 @@ export function distroInstallerArgs( ]; } +/** Runtime 2.0.0 enters the update controller only through this command. */ export function distroGatewayArgs(): string[] { - return [...wslCommandPrefix(), '/root/.local/bin/elastos', ...GATEWAY_ARGS]; + return [...wslCommandPrefix(), '/root/.local/bin/elastos', 'home', '--browser']; +} + +/** + * The controller binary the host lock's parent must be running. + * `queue_update` accepts a request only while that process is the live controller. + */ +export const DISTRO_CONTROLLER_COMMAND = + `${runtimeDataDir('linux', DISTRO_HOME, {})}/update-controller/runtime __update-controller`; + +/** Home's controller can take the runtime's full ready budget (120s) plus margin. Mac uses the same budget. */ +export const DISTRO_HOME_READY_MS = 150_000; + +export function distroHomeSpawnOptions(env: NodeJS.ProcessEnv = wslSpawnEnv()): { + detached: true; + windowsHide: true; + stdio: ['ignore', 'pipe', 'pipe']; + env: NodeJS.ProcessEnv; +} { + return { + detached: true, + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + env, + }; +} + +export interface DistroProcFact { + ppid: number | null; + command: string | null; +} + +/** Raw files from the distro. The stop decision does not trust this until `distroStopPid`. */ +export interface DistroStopReport { + lockText: string; + statusText: string | null; + procs: Readonly>; +} + +/** + * Pid to signal. A proved controller is the host's parent, shares the lock + * generation, and is the update-controller binary. Otherwise the host pid. + * Null when the lock names no usable pid. + */ +export function distroStopPid(report: DistroStopReport): number | null { + let lock: { pid?: unknown; generation?: unknown }; + try { + lock = JSON.parse(report.lockText) as { pid?: unknown; generation?: unknown }; + } catch { + return null; + } + const host = lock.pid; + if (typeof host !== 'number' || !Number.isInteger(host) || host <= 1) return null; + if (!report.statusText) return host; + let status: { host_pid?: unknown; generation?: unknown; controller_pid?: unknown }; + try { + status = JSON.parse(report.statusText) as { host_pid?: unknown; generation?: unknown; controller_pid?: unknown }; + } catch { + return host; + } + const controller = status.controller_pid; + const proved = status.host_pid === host + && typeof status.generation === 'string' + && status.generation.length > 0 + && status.generation === lock.generation + && typeof controller === 'number' + && Number.isInteger(controller) + && controller > 1 + && controller !== host; + if (!proved) return host; + const controllerFact = report.procs[String(controller)]; + const hostFact = report.procs[String(host)]; + if (!controllerFact || !hostFact) return host; + if (hostFact.ppid !== controller) return host; + if (!controllerFact.command || !controllerFact.command.includes(DISTRO_CONTROLLER_COMMAND)) return host; + return controller; +} + +export function parseDistroStopReport(raw: string): DistroStopReport | null { + let parsed: { lock?: unknown; status?: unknown; procs?: unknown }; + try { + parsed = JSON.parse(raw) as { lock?: unknown; status?: unknown; procs?: unknown }; + } catch { + return null; + } + if (typeof parsed.lock !== 'string') return null; + if (parsed.status !== null && typeof parsed.status !== 'string') return null; + if (!parsed.procs || typeof parsed.procs !== 'object') return null; + const procs: Record = {}; + for (const [key, value] of Object.entries(parsed.procs as Record)) { + if (!/^[1-9]\d*$/.test(key) || !value || typeof value !== 'object') return null; + const fact = value as { ppid?: unknown; command?: unknown }; + if (fact.ppid !== null && (typeof fact.ppid !== 'number' || !Number.isInteger(fact.ppid) || fact.ppid <= 0)) return null; + if (fact.command !== null && typeof fact.command !== 'string') return null; + procs[key] = { + ppid: typeof fact.ppid === 'number' ? fact.ppid : null, + command: typeof fact.command === 'string' ? fact.command : null, + }; + } + return { + lockText: parsed.lock, + statusText: parsed.status, + procs, + }; +} + +export const DISTRO_STOP_READER = ` +import json, os, stat +LIMIT = 16384 +ROOT = '/root/.local/share/elastos' +LOCK = ROOT + '/host-process.lock' +STATUS = ROOT + '/update-controller/status.json' + +def read_text(path, required): + current = '' + parts = path.strip('/').split('/') + info = None + for index, part in enumerate(parts): + current = current + '/' + part + try: + info = os.lstat(current) + except FileNotFoundError: + if required: + raise SystemExit(1) + return None + if stat.S_ISLNK(info.st_mode): + raise SystemExit(2) + if index == len(parts) - 1: + if not stat.S_ISREG(info.st_mode) or info.st_size > LIMIT: + raise SystemExit(2) + 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(2) + return data.decode('utf-8', 'replace') + +def read_proc(path): + try: + info = os.lstat(path) + except OSError: + return None + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_size > LIMIT: + return None + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + data = os.read(fd, LIMIT + 1) + finally: + os.close(fd) + if len(data) > LIMIT: + return None + return data + +def pid_of(text, key): + try: + value = json.loads(text).get(key) + except Exception: + return None + if type(value) is int and value > 1: + return value + return None + +def proc_fact(pid): + base = '/proc/' + str(pid) + try: + info = os.lstat(base) + except OSError: + return None + if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode): + return None + status = read_proc(base + '/status') + cmd = read_proc(base + '/cmdline') + ppid = None + if status: + for line in status.decode('utf-8', 'replace').split('\\n'): + if line.startswith('PPid:'): + raw = line[5:].strip() + if raw.isdigit(): + ppid = int(raw) + command = None + if cmd is not None: + command = cmd.replace(b'\\x00', b' ').decode('utf-8', 'replace').strip() + return {'ppid': ppid, 'command': command} + +lock = read_text(LOCK, True) +status = read_text(STATUS, False) +procs = {} +for key, text in (('pid', lock), ('host_pid', status), ('controller_pid', status)): + if not text: + continue + pid = pid_of(text, key) + if pid and str(pid) not in procs: + fact = proc_fact(pid) + if fact: + procs[str(pid)] = fact +print(json.dumps({'lock': lock, 'status': status, 'procs': procs})) +`.trim(); + +export function readDistroStopReport( + run: (args: readonly string[]) => { code: number; stdout: string } = (args) => runWslSync(args, undefined, 8000), +): DistroStopReport | null { + try { + const result = run(['python3', '-c', DISTRO_STOP_READER]); + if (result.code !== 0) return null; + return parseDistroStopReport(result.stdout); + } catch { + return null; + } +} + +function resolvedDistroStopPid(report: DistroStopReport | null, hostPid: number): number { + if (!report) return hostPid; + let lockPid: unknown; + try { + lockPid = (JSON.parse(report.lockText) as { pid?: unknown }).pid; + } catch { + return hostPid; + } + if (lockPid !== hostPid) return hostPid; + return distroStopPid(report) ?? hostPid; } export function distroToolCheckArgs(): readonly string[] { @@ -477,14 +701,29 @@ function runHost(args: readonly string[], timeoutMs: number): Promise { }); } -/** Signal the gateway recorded in the distro host lock. Never uses pid 0 or 1. */ +function signalResolvedDistroPid(name: 'TERM' | 'KILL'): void { + const report = readDistroStopReport(); + const host = (() => { + try { + return (JSON.parse(report?.lockText ?? '') as { pid?: unknown }).pid; + } catch { + return null; + } + })(); + if (typeof host !== 'number' || !Number.isInteger(host) || host <= 1) return; + const pid = resolvedDistroStopPid(report, host); + if (!Number.isInteger(pid) || pid <= 1) return; + runWslSync(distroStopArgs(name, pid), undefined, 5000); + // SIGKILL cannot ask the controller to drain its child. Stop the host group too. + if (name === 'KILL' && pid !== host) { + runWslSync(distroStopArgs(name, host), undefined, 5000); + } +} + +/** Signal the proved controller, or the host lock pid when no controller is proved. Never uses pid 0 or 1. */ export function signalDistroLock( signal: NodeJS.Signals, - stopInside: (name: 'TERM' | 'KILL') => void = (name) => { - const pid = readDistroLockPid(); - if (pid == null || pid <= 1) return; - runWslSync(distroStopArgs(name, pid), undefined, 5000); - }, + stopInside: (name: 'TERM' | 'KILL') => void = signalResolvedDistroPid, ): void { const name = signal === 'SIGKILL' ? 'KILL' : 'TERM'; stopInside(name); @@ -494,17 +733,16 @@ export function signalDistroGateway( wslPid: number, signal: NodeJS.Signals, kill: (pid: number, signal: NodeJS.Signals) => void = process.kill, - stopInside: (name: 'TERM' | 'KILL') => void = (name) => { - const pid = readDistroLockPid(); - if (pid == null || pid <= 1) return; - runWslSync(distroStopArgs(name, pid), undefined, 5000); - }, + stopInside: (name: 'TERM' | 'KILL') => void = signalResolvedDistroPid, ): void { try { signalDistroLock(signal, stopInside); } catch { // The lock may already be gone. } + // SIGTERM lets the controller drain Home. wsl.exe exits when that command exits. + // SIGKILL also ends wsl.exe if the distro command is still there. + if (signal !== 'SIGKILL') return; if (!Number.isInteger(wslPid) || wslPid <= 0) return; try { kill(wslPid, signal); @@ -519,11 +757,7 @@ export function signalDistroGateway( } export function spawnDistroGatewayProcess(): GatewayProcess { - const child = spawn('wsl.exe', distroGatewayArgs(), { - windowsHide: true, - env: wslSpawnEnv(), - stdio: ['ignore', 'pipe', 'pipe'], - }); + const child = spawn('wsl.exe', distroGatewayArgs(), distroHomeSpawnOptions()); const outputListeners: Array<(chunk: string) => void> = []; const exitListeners: Array<(code: number | null) => void> = []; let exited = false; @@ -557,6 +791,8 @@ export function createDistroGatewaySupervisor() { now: () => Date.now(), openUrl: openRuntimeHome, log: emitRuntimeLog, + adoptForControls: true, + healthTimeoutMs: DISTRO_HOME_READY_MS, confirmForeign: confirmDistroGateway, foreignIsLegacy: async () => (await distroListenerKind()) === 'legacy', // The Windows side of the forward has no pid this launcher can check. @@ -652,16 +888,18 @@ export async function distroListenerKind( } /** - * Adopt the installed distro gateway. The signal goes to the pid read from - * the lock, not to whatever the lock says later. hasExited asks the distro - * whether that pid is still there and treats an error as still running. - * A missing pid is not adopted, and pid 0 is never signaled. + * Adopt the installed distro Home. The host pid is the one the caller proved. + * A controller is signaled only when this same lock says it is that host's + * parent. hasExited asks the distro whether those pids are still there and + * treats an error as still running. A missing pid is not adopted, and pid 0 + * is never signaled. */ export function adoptDistroGatewayProcess(deps: { readPid?: () => number | null; alive?: (pid: number) => boolean | Promise; signal?: (pid: number, signal: NodeJS.Signals) => void; runStop?: (args: readonly string[]) => void; + report?: () => DistroStopReport | null; } = {}): GatewayProcess | null { const readPid = deps.readPid ?? (() => readDistroLockPid()); const alive = deps.alive ?? ((pid: number) => distroPidAlive(pid)); @@ -675,22 +913,42 @@ export function adoptDistroGatewayProcess(deps: { }); const pid = readPid(); if (pid == null || pid <= 1) return null; + let stopPid = pid; + if (deps.report) { + try { + stopPid = resolvedDistroStopPid(deps.report(), pid); + } catch { + stopPid = pid; + } + } + if (!Number.isInteger(stopPid) || stopPid <= 1) stopPid = pid; + const gone = (target: number): boolean | Promise => { + try { + const result = alive(target); + if (result && typeof (result as Promise).then === 'function') { + return (result as Promise).then((still) => still === false).catch(() => false); + } + return result === false; + } catch { + return false; + } + }; return { pid, onOutput() {}, onExit() {}, hasExited() { - try { - const result = alive(pid); - if (result && typeof (result as Promise).then === 'function') { - return (result as Promise).then((still) => still === false).catch(() => false); - } - return result === false; - } catch { - return false; + const hostGone = gone(pid); + const controllerGone = stopPid === pid ? true : gone(stopPid); + if (hostGone instanceof Promise || controllerGone instanceof Promise) { + return Promise.all([hostGone, controllerGone]).then((both) => both.every(Boolean)); } + return hostGone && controllerGone; + }, + signal(signal) { + signalInside(stopPid, signal); + if (signal === 'SIGKILL' && stopPid !== pid) signalInside(pid, signal); }, - signal(signal) { signalInside(pid, signal); }, }; } @@ -707,7 +965,10 @@ export async function adoptInstalledDistroGateway(deps: { adopt?: (pid: number) => GatewayProcess | null; } = {}): Promise { const identify = deps.identify ?? (() => distroListenerIdentity()); - const adopt = deps.adopt ?? ((pid: number) => adoptDistroGatewayProcess({ readPid: () => pid })); + const adopt = deps.adopt ?? ((pid: number) => adoptDistroGatewayProcess({ + readPid: () => pid, + report: () => readDistroStopReport(), + })); let seen: DistroListenerIdentity; try { seen = await identify(); diff --git a/src/preload/index.ts b/src/preload/index.ts index 15cc82a..4835a67 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -95,6 +95,7 @@ declare global { status: RuntimeStatus; platformNote: string | null; browserNote: string | null; + runtimeOpensBrowser: boolean; uninstallRemovesLinux: boolean; preflight: { ok: boolean; checks: Array<{ id: string; level: string; message: string }> }; openAtLogin: boolean; diff --git a/src/renderer/app.js b/src/renderer/app.js index 4a956fa..18a898f 100644 --- a/src/renderer/app.js +++ b/src/renderer/app.js @@ -216,7 +216,10 @@ async function runInstall() { renderSteps('Starting'); await window.elastos.start(); renderSteps('Your computer is ready'); - await window.elastos.openBrowser(); + const started = await window.elastos.getLaunchInfo(); + if (flow.shouldOpenBrowserAfterStart(started)) { + await window.elastos.openBrowser(); + } } catch (err) { showError(err && err.message ? err.message : 'Something went wrong. Try again.'); updateStatus('error'); diff --git a/src/renderer/flow.js b/src/renderer/flow.js index 7b4d83c..4bc7b53 100644 --- a/src/renderer/flow.js +++ b/src/renderer/flow.js @@ -141,6 +141,11 @@ function legacyPc2Copy(items) { }; } +/** False when `home --browser` already opens the tab. */ +function shouldOpenBrowserAfterStart(info) { + return !(info && info.runtimeOpensBrowser === true); +} + /** The info-panel Browser line. The main process sends it on Windows only. */ function browserNoteText(info) { return info && typeof info.browserNote === 'string' ? info.browserNote : ''; @@ -162,6 +167,7 @@ const api = { formatBytes, legacyPc2Copy, browserNoteText, + shouldOpenBrowserAfterStart, urlLabel, }; diff --git a/test/installer-ux.test.js b/test/installer-ux.test.js index e300494..098102d 100644 --- a/test/installer-ux.test.js +++ b/test/installer-ux.test.js @@ -165,6 +165,9 @@ test('Windows shows that its Browser is not available yet, and only Windows', () assert.equal(flow.browserNoteText({ browserNote: WINDOWS_BROWSER_MESSAGE }), WINDOWS_BROWSER_MESSAGE); assert.equal(flow.browserNoteText({ browserNote: null }), ''); assert.equal(flow.browserNoteText(undefined), ''); + assert.equal(flow.shouldOpenBrowserAfterStart({ runtimeOpensBrowser: true }), false); + assert.equal(flow.shouldOpenBrowserAfterStart({ runtimeOpensBrowser: false }), true); + assert.equal(flow.shouldOpenBrowserAfterStart(undefined), true); const html = fs.readFileSync(path.join(__dirname, '..', 'src', 'renderer', 'index.html'), 'utf8'); assert.match(html, /