Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
51 changes: 42 additions & 9 deletions .github/scripts/boot-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,28 @@ export function parseArgs(argv) {
}

/** Ambiente do exe: pasta de dados isolada e porta de depuração do WebView2. */
export function bootEnv(base, { dataDir, port }) {
export function bootEnv(base, { dataDir, port, viaRegistry = false }) {
const env = { ...base };
env.RAM_DATA_DIR = dataDir;
env.WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = `--remote-debugging-port=${port}`;
if (viaRegistry) {
// O WebView2 só lê o registro quando nenhuma variável WEBVIEW2_* existe (documentação do
// CreateCoreWebView2EnvironmentWithOptions): no caminho do registro, nenhuma vai.
for (const k of Object.keys(env)) if (k.toUpperCase().startsWith("WEBVIEW2_")) delete env[k];
} else {
env.WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = `--remote-debugging-port=${port}`;
}
return env;
}

/** A política por exe dos argumentos do WebView2 (HKCU), gravada (`on`) ou apagada. Só no runner do GitHub. */
const ARGS_POLICY_KEY = "HKCU:\\Software\\Policies\\Microsoft\\Edge\\WebView2\\AdditionalBrowserArguments";
export function registryArgsScript(exeName, port, on) {
const name = String(exeName).replace(/'/g, "");
return on
? `New-Item -Path "${ARGS_POLICY_KEY}" -Force | Out-Null; New-ItemProperty -Path "${ARGS_POLICY_KEY}" -Name '${name}' -Value '--remote-debugging-port=${Number(port)}' -PropertyType String -Force | Out-Null`
: `Remove-ItemProperty -Path "${ARGS_POLICY_KEY}" -Name '${name}' -ErrorAction SilentlyContinue`;
}

/** A janela principal entre os alvos do CDP (as outras janelas têm `?view=`). */
export function pickMainPage(targets) {
if (!Array.isArray(targets)) return undefined;
Expand Down Expand Up @@ -168,6 +183,9 @@ export function diagnosticsScript(pid, port = 9333) {
`$pv = (Get-ItemProperty -Path "HKLM:\\${WEBVIEW2_CLIENT_KEY}" -Name pv -ErrorAction SilentlyContinue).pv`,
`Write-Output ("WebView2 runtime: " + $(if ($pv) { $pv } else { "not installed" }))`,
// O processo principal do WebView2 (sem --type=) recebeu a porta de depuração? Ela escuta? Há política do Edge?
`$kids = @(Get-CimInstance Win32_Process -Filter "ParentProcessId=${Number(pid)}" | Where-Object { $_.Name -eq 'msedgewebview2.exe' })`,
`Write-Output ("WebView2 processes started by the app: " + $kids.Count)`,
`if ($kids.Count) { $flags = (($kids[0].CommandLine -split ' ') | Where-Object { $_ -like '--*' -and $_ -notlike '--user-data-dir*' }) -join ' '; Write-Output ("app WebView2 flags: " + $flags.Substring(0, [Math]::Min(700, $flags.Length))) }`,
`$b = Get-CimInstance Win32_Process -Filter "Name='msedgewebview2.exe'" | Where-Object { $_.CommandLine -notmatch '--type=' } | Select-Object -First 1`,
`if ($b) { Write-Output ("WebView2 browser process has remote-debugging-port: " + ($b.CommandLine -match 'remote-debugging-port')) } else { Write-Output "no WebView2 browser process" }`,
`Write-Output ("port ${Number(port)} listening: " + [bool](Get-NetTCPConnection -LocalPort ${Number(port)} -State Listen -ErrorAction SilentlyContinue))`,
Expand All @@ -180,15 +198,15 @@ function printDiagnostics(pid, port) {
for (const line of `${r.stdout ?? ""}`.split(/\r?\n/).filter(Boolean)) console.error(`boot-check: ${line}`);
}

export function spawnApp({ exe, port, dataDir }) {
return spawn(exe, [], { env: bootEnv(process.env, { dataDir, port }), stdio: "ignore", windowsHide: true });
export function spawnApp({ exe, port, dataDir, viaRegistry = false }) {
return spawn(exe, [], { env: bootEnv(process.env, { dataDir, port, viaRegistry }), stdio: "ignore", windowsHide: true });
}

/** `start` troca quem é aberto (os testes locais usam um navegador sem janela no lugar do app). */
export async function bootCheck({ exe, port, timeoutMs, settleMs }, { log = console.log, start = spawnApp } = {}) {
export async function bootCheck({ exe, port, timeoutMs, settleMs, viaRegistry = false }, { log = console.log, start = spawnApp } = {}) {
const dataDir = mkdtempSync(path.join(tmpdir(), "multialt-boot-"));
writeFileSync(path.join(dataDir, "RAMSettings.ini"), SEED_SETTINGS);
const child = start({ exe, port, dataDir });
const child = start({ exe, port, dataDir, viaRegistry });
let exitInfo;
child.on("exit", (code, signal) => (exitInfo = { code, signal }));
child.on("error", (e) => (exitInfo = { code: null, signal: String(e.message) }));
Expand All @@ -208,7 +226,8 @@ export async function bootCheck({ exe, port, timeoutMs, settleMs }, { log = cons
if (exitInfo) return fail(`the app exited (code ${exitInfo.code}, ${exitInfo.signal ?? "no signal"}) before the WebView2 page came up (another instance already running?)`);
if (!page) {
printDiagnostics(child.pid, port);
return fail(`no WebView2 page on port ${port} after ${timeoutMs / 1000}s`);
fail(`no WebView2 page on port ${port} after ${timeoutMs / 1000}s${viaRegistry ? " (registry route)" : ""}`);
return 2;
}
log(`boot-check: CDP page ${page.url}`);
cdp = await connect(page.webSocketDebuggerUrl, (m) => {
Expand Down Expand Up @@ -251,8 +270,22 @@ export async function bootCheck({ exe, port, timeoutMs, settleMs }, { log = cons
}

if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
bootCheck(parseArgs(process.argv.slice(2)))
.then((code) => process.exit(code))
const opts = parseArgs(process.argv.slice(2));
bootCheck(opts)
.then(async (code) => {
// Sem página pela variável de ambiente: no runner do GitHub (descartável) tenta pela política do registro.
// Nunca na máquina de ninguém: a política valeria para o MultiAlt instalado.
if (code !== 2 || process.env.GITHUB_ACTIONS !== "true" || process.platform !== "win32") return code;
const exeName = path.basename(opts.exe);
console.error(`boot-check: trying again with the WebView2 arguments policy for ${exeName}`);
spawnSync("powershell", ["-NoProfile", "-Command", registryArgsScript(exeName, opts.port, true)], { stdio: "inherit", windowsHide: true });
try {
return await bootCheck({ ...opts, viaRegistry: true });
} finally {
spawnSync("powershell", ["-NoProfile", "-Command", registryArgsScript(exeName, opts.port, false)], { stdio: "inherit", windowsHide: true });
}
})
.then((code) => process.exit(code ? 1 : 0))
.catch((e) => {
console.error(`boot-check: FAILED: ${e instanceof Error ? e.message : String(e)}`);
process.exit(1);
Expand Down
26 changes: 26 additions & 0 deletions .github/scripts/boot-check.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
bootVerdict,
describeCdpEvent,
diagnosticsScript,
registryArgsScript,
WEBVIEW2_CLIENT_KEY,
parseArgs,
pickMainPage,
Expand Down Expand Up @@ -36,6 +37,31 @@ describe("boot-check failure diagnostics", () => {
expect(script).toContain("Get-NetTCPConnection -LocalPort 9333 -State Listen");
expect(script).toContain("Policies\\Microsoft\\Edge");
});

// Terceira rodada (29/11/2026): o primeiro processo principal do WebView2 da máquina pode ser de outro programa.
// Só os filhos do app contam, com os argumentos que receberam (o --disable-features= do app prova que a variável chegou).
it("looks only at the WebView2 processes the app started and prints the flags they got", () => {
const script = diagnosticsScript(4242, 9333);
expect(script).toContain("ParentProcessId=4242");
expect(script).toMatch(/app WebView2 flags/);
});

it("the registry route clears every WEBVIEW2_ variable, so WebView2 reads the registry", () => {
const env = bootEnv({ PATH: "x", WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: "--a", WEBVIEW2_USER_DATA_FOLDER: "y" }, { dataDir: "d", port: 9333, viaRegistry: true });
expect(Object.keys(env).filter((k) => k.toUpperCase().startsWith("WEBVIEW2_"))).toEqual([]);
expect(env.RAM_DATA_DIR).toBe("d");
expect(env.PATH).toBe("x");
});

it("writes and removes the per-exe browser arguments policy", () => {
const set = registryArgsScript("roblox-account-manager.exe", 9333, true);
expect(set).toContain("Software\\Policies\\Microsoft\\Edge\\WebView2\\AdditionalBrowserArguments");
expect(set).toContain("roblox-account-manager.exe");
expect(set).toContain("--remote-debugging-port=9333");
const clear = registryArgsScript("roblox-account-manager.exe", 9333, false);
expect(clear).toContain("Remove-ItemProperty");
expect(clear).not.toContain("--remote-debugging-port");
});
});

describe("boot-check arguments", () => {
Expand Down
Loading