Skip to content

The agent that grows with you

fix(release): allow explicit environment clears in commit bundles

ethernet86efc1f94515
diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.yml
index 112cd5dd43e..145e1f04ba4 100644
--- a/.github/workflows/desktop-bundled-release.yml
+++ b/.github/workflows/desktop-bundled-release.yml
@@ -106,7 +106,7 @@ on:
type: string
default: ''
bundle_env:
- description: 'Commit desktop bundles only: JSON object of non-secret runtime environment defaults. Explicit runtime values win.'
+ description: 'Commit desktop bundles only: JSON object of non-secret defaults (strings) or forced clears (null). Runtime values win over defaults, not clears.'
required: false
type: string
default: '{}'
diff --git a/apps/desktop/BUILDING.md b/apps/desktop/BUILDING.md
index a41b4b03ca7..8eaa525a21c 100644
--- a/apps/desktop/BUILDING.md
+++ b/apps/desktop/BUILDING.md
@@ -121,7 +121,8 @@ defaults into the desktop app, for example:
```sh
python scripts/release.py --build-commit REV --remote fork --publish \
--bundle-env HERMES_GUEST_ONBOARDING=1 \
- --bundle-env HERMES_DATA_DIR_SUFFIX=magic-test
+ --bundle-env HERMES_DATA_DIR_SUFFIX=magic-test \
+ --bundle-unset HERMES_HOME
```
These defaults run before Electron initializes its paths and are inherited by
@@ -129,8 +130,19 @@ local backend processes. Explicit runtime environment values win, including
empty values. Do not pass secrets: the values are visible in the workflow inputs
and packaged JavaScript. This option affects desktop bundles, not Termux.
The suffix is appended literally; include a leading hyphen if desired.
-For local commit builds, `HERMES_BUNDLE_ENV_JSON` accepts the same defaults as
-a JSON object of strings. Defaults are not applied to the build runner itself.
+`--bundle-unset NAME` explicitly clears an inherited value at app launch, even
+if the caller supplied it. Internally it sets the value to an empty string, not
+an absent key. Clearing `HERMES_HOME` also disables the Windows registry fallback:
+older installers saved that variable permanently, which otherwise takes priority
+over the test suffix. It does not edit the registry or the existing install.
+For full data-path isolation, also clear `HERMES_DESKTOP_USER_DATA_DIR` if that
+machine uses an explicit Electron directory. Ordinary defaults still preserve
+runtime overrides; `--bundle-env HERMES_HOME=` is a default, not a forced clear.
+
+For local commit builds, `HERMES_BUNDLE_ENV_JSON` accepts a JSON object whose
+string values are defaults and whose `null` values are explicit clears. For example,
+`{"HERMES_HOME":null,"HERMES_DATA_DIR_SUFFIX":"magic-test"}`. These settings are
+not applied to the build runner itself.
Commit archive keys still use the SHA, so use a fresh commit for different
defaults: an existing artifact is never overwritten with different bytes.
diff --git a/apps/desktop/electron/data-paths.ts b/apps/desktop/electron/data-paths.ts
index 7b897770b24..c5515115d0f 100644
--- a/apps/desktop/electron/data-paths.ts
+++ b/apps/desktop/electron/data-paths.ts
@@ -50,8 +50,8 @@ export function resolveDesktopHermesHome({
return paths.join(paths.resolve(env.HERMES_DESKTOP_USER_DATA_DIR), 'hermes-home')
}
- if (platform === 'win32') {
- // Explorer can retain an old environment after the user runs setx.
+ if (platform === 'win32' && env.HERMES_HOME === undefined) {
+ // Explorer can miss setx changes. An explicit empty value opts out of that fallback.
const registryHome: string | null = readWindowsHome()
if (registryHome) {
diff --git a/apps/desktop/scripts/bundle-env.mjs b/apps/desktop/scripts/bundle-env.mjs
index d191941b162..f9698c35fe8 100644
--- a/apps/desktop/scripts/bundle-env.mjs
+++ b/apps/desktop/scripts/bundle-env.mjs
@@ -7,9 +7,10 @@ export function environmentDefaultsBanner(raw) {
throw new Error('Bundle environment must be a JSON object')
}
for (const [key, value] of Object.entries(values)) {
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== 'string' || value.includes('\0')) {
- throw new Error('Bundle environment requires valid names and string values without NUL')
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || (value !== null && (typeof value !== 'string' || value.includes('\0')))) {
+ throw new Error('Bundle environment requires valid names and string values without NUL, or null to clear')
}
}
- return `\nfor (const [key, value] of ${JSON.stringify(Object.entries(values))}) { process.env[key] ??= value; }\n`
+ // Keep clears present-but-empty so path resolution cannot restore registry defaults.
+ return `\nfor (const [key, value] of ${JSON.stringify(Object.entries(values))}) { if (value === null) process.env[key] = ''; else process.env[key] ??= value; }\n`
}
diff --git a/apps/desktop/scripts/bundle-env.test.mjs b/apps/desktop/scripts/bundle-env.test.mjs
index 02166b44599..bc3d00503dd 100644
--- a/apps/desktop/scripts/bundle-env.test.mjs
+++ b/apps/desktop/scripts/bundle-env.test.mjs
@@ -3,10 +3,44 @@ import { execFileSync } from 'node:child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
import { expect, test } from 'vitest'
import { environmentDefaultsBanner } from './bundle-env.mjs'
+test('explicit clears beat inherited homes and prevent Windows registry fallback before spawning', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'hermes-bundle-clear-'))
+ const paths = fileURLToPath(new URL('../electron/data-paths.ts', import.meta.url))
+ const defaults = { HERMES_HOME: null, HERMES_DATA_DIR_SUFFIX: 'magic-test' }
+ try {
+ const entry = join(root, 'entry.mjs')
+ writeFileSync(entry, `
+ import {resolveDesktopHermesHome} from ${JSON.stringify(paths)};
+ import {execFileSync} from 'node:child_process';
+ let registryReads = 0;
+ const home = resolveDesktopHermesHome({
+ home: 'C:/Users/test', platform: 'win32', env: process.env,
+ readWindowsHome: () => { registryReads++; return 'C:/old-hermes'; }
+ });
+ console.log(JSON.stringify({cleared: process.env.HERMES_HOME, home, registryReads,
+ child: execFileSync(process.execPath, ['-p', 'process.env.HERMES_HOME'], {
+ env: {...process.env, HERMES_HOME: home}, encoding: 'utf8'
+ }).trim()}));
+ `)
+ const outfile = join(root, 'bundle.mjs')
+ await build({ entryPoints: [entry], bundle: true, platform: 'node', format: 'esm', outfile,
+ banner: { js: environmentDefaultsBanner(JSON.stringify(defaults)) } })
+ const env = { ...process.env, HERMES_HOME: 'C:/old-hermes', LOCALAPPDATA: 'C:/Users/test/AppData/Local' }
+ delete env.HERMES_DATA_DIR_SUFFIX
+ delete env.HERMES_DESKTOP_USER_DATA_DIR
+ const actual = JSON.parse(execFileSync(process.execPath, [outfile], { env, encoding: 'utf8' }))
+ expect(actual).toEqual({ cleared: '', home: 'C:\\Users\\test\\AppData\\Local\\hermesmagic-test',
+ child: 'C:\\Users\\test\\AppData\\Local\\hermesmagic-test', registryReads: 0 })
+ } finally {
+ rmSync(root, { recursive: true, force: true })
+ }
+})
+
test('baked defaults precede imported module initialization and reach children without overriding explicit env', async () => {
const root = mkdtempSync(join(tmpdir(), 'hermes-bundle-env-'))
const defaults = { HERMES_GUEST_ONBOARDING: '1', HERMES_DATA_DIR_SUFFIX: 'magic-test', LITERAL: 'a=b "q"\n$(no)', EMPTY: '' }
diff --git a/scripts/release.py b/scripts/release.py
index 1b9ab6476b9..fcd0da57fd0 100755
--- a/scripts/release.py
+++ b/scripts/release.py
@@ -2899,6 +2899,9 @@ def main():
parser.add_argument("--bundle-env", action="append", default=[], metavar="NAME=VALUE",
help="Bake a non-secret environment default into a commit desktop bundle. "
"Repeat for multiple variables. Runtime environment values win.")
+ parser.add_argument("--bundle-unset", action="append", default=[], metavar="NAME",
+ help="Clear an inherited variable at desktop launch, even when set. "
+ "Uses an explicit empty value; repeat for multiple variables.")
parser.add_argument("--prune-canaries", action="store_true",
help="Delete canary releases+tags older than 14 days")
parser.add_argument("--publish", action="store_true",
@@ -2917,8 +2920,8 @@ def main():
help="Skip changelog")
args = parser.parse_args()
- if args.bundle_env and args.build_commit is None:
- parser.error("--bundle-env requires --build-commit")
+ if (args.bundle_env or args.bundle_unset) and args.build_commit is None:
+ parser.error("--bundle-env and --bundle-unset require --build-commit")
if args.canary and args.bump:
parser.error("--canary and --bump are mutually exclusive")
if args.build_commit is not None:
diff --git a/scripts/releases/bundle_env.py b/scripts/releases/bundle_env.py
index e3e820ba218..61cfe95c43d 100644
--- a/scripts/releases/bundle_env.py
+++ b/scripts/releases/bundle_env.py
@@ -1,23 +1,24 @@
-"""Non-secret environment defaults carried by a desktop bundle."""
+"""Non-secret environment defaults and explicit clears carried by a desktop bundle."""
from __future__ import annotations
+from collections.abc import Sequence
import json
import re
-def validate(values: object) -> dict[str, str]:
+def validate(values: object) -> dict[str, str | None]:
if not isinstance(values, dict):
raise ValueError("Bundle environment must be a JSON object")
for key, value in values.items():
if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key):
raise ValueError("Bundle environment names must be valid environment identifiers")
- if not isinstance(value, str) or "\0" in value:
- raise ValueError(f"Bundle environment value for {key} must be a string without NUL")
+ if value is not None and (not isinstance(value, str) or "\0" in value):
+ raise ValueError(f"Bundle environment value for {key} must be a string without NUL or null")
return values
-def parse_assignments(assignments: list[str]) -> dict[str, str]:
- values = {}
+def parse_assignments(assignments: list[str], unset: Sequence[str] = ()) -> dict[str, str | None]:
+ values: dict[str, str | None] = {}
for assignment in assignments:
key, separator, value = assignment.partition("=")
if not separator:
@@ -25,8 +26,12 @@ def parse_assignments(assignments: list[str]) -> dict[str, str]:
if key in values:
raise ValueError(f"Duplicate bundle environment name: {key}")
values[key] = value
+ for key in unset:
+ if key in values:
+ raise ValueError(f"Duplicate bundle environment name: {key}")
+ values[key] = None
return validate(values)
-def decode(raw: str) -> dict[str, str]:
+def decode(raw: str) -> dict[str, str | None]:
return validate(json.loads(raw or "{}"))
diff --git a/scripts/releases/commit_build.py b/scripts/releases/commit_build.py
index 80d3ab78f04..b596b4d9192 100644
--- a/scripts/releases/commit_build.py
+++ b/scripts/releases/commit_build.py
@@ -79,7 +79,7 @@ def resolve_revision(rev: str, remote: str, repo: Path) -> str:
def dispatch_command(commit: str, repository: str, branch: str,
- bundle_env: dict[str, str] | None = None) -> list[str]:
+ bundle_env: dict[str, str | None] | None = None) -> list[str]:
from scripts.releases.bundle_env import validate
require_commit(commit)
@@ -97,7 +97,7 @@ def cmd_build_commit(args) -> None:
from scripts.releases.bundle_env import parse_assignments
try:
- bundle_env = parse_assignments(args.bundle_env)
+ bundle_env = parse_assignments(args.bundle_env, args.bundle_unset)
remote = release.resolve_push_remote(args.remote)
repository = release.remote_github_repo(remote)
if not repository:
diff --git a/tests/scripts/test_commit_bundle_entrypoints.py b/tests/scripts/test_commit_bundle_entrypoints.py
index 522bef83f5d..91a163d7acb 100644
--- a/tests/scripts/test_commit_bundle_entrypoints.py
+++ b/tests/scripts/test_commit_bundle_entrypoints.py
@@ -23,7 +23,7 @@ def test_desktop_build_reaches_the_managed_payload_with_commit_ref(tmp_path, mon
monkeypatch.setenv("HERMES_PAYLOAD_TAG", "v9.9.9")
monkeypatch.setenv("GITHUB_SHA", "b" * 40)
monkeypatch.setenv("BUILD_NUMBER", "123")
- defaults = {"HERMES_GUEST_ONBOARDING": "1", "HERMES_DATA_DIR_SUFFIX": "magic-test"}
+ defaults = {"HERMES_GUEST_ONBOARDING": "1", "HERMES_DATA_DIR_SUFFIX": "magic-test", "HERMES_HOME": None}
monkeypatch.setenv("HERMES_BUNDLE_ENV_JSON", json.dumps(defaults))
monkeypatch.setattr(desktop.shutil, "which", lambda name: name)
monkeypatch.setattr(desktop, "npm_command", lambda node: [node, "npm-cli.js"])
diff --git a/tests/scripts/test_release_build_commit.py b/tests/scripts/test_release_build_commit.py
index 9ce136243c5..d3ae3fccb96 100644
--- a/tests/scripts/test_release_build_commit.py
+++ b/tests/scripts/test_release_build_commit.py
@@ -124,6 +124,20 @@ def test_commit_build_cli_dispatches_only_the_resolved_remote_commit(tmp_path):
result, calls = invoke('--bundle-env', 'NAME=value')
assert result.returncode == 2 and not calls
+ result, calls = invoke('--build-commit', tip, '--publish', *flags,
+ '--bundle-unset', 'HERMES_HOME')
+ assert result.returncode == 0, result.stderr
+ dispatch = next(call for call in calls if call[1:3] == ['workflow', 'run'])
+ assert json.loads(next(field.split('=', 1)[1] for field in dispatch if field.startswith('bundle_env='))) == {
+ **values, 'HERMES_HOME': None}
+ for invalid in (['--bundle-unset', 'BAD-NAME'],
+ ['--bundle-env', 'HERMES_HOME=x', '--bundle-unset', 'HERMES_HOME'],
+ ['--bundle-unset', 'HERMES_HOME', '--bundle-unset', 'HERMES_HOME']):
+ result, calls = invoke('--build-commit', tip, '--publish', *invalid)
+ assert result.returncode != 0 and not calls
+ result, calls = invoke('--bundle-unset', 'HERMES_HOME')
+ assert result.returncode == 2 and not calls
+
git(repo, 'checkout', '-qb', 'feature')
(repo / 'feature').write_text('pushed feature', encoding='utf-8')
git(repo, 'add', 'feature')
@@ -172,7 +186,7 @@ def test_workflow_admission_checks_trust_before_publishing_outputs(tmp_path):
'GITHUB_WORKFLOW_REF': 'fixture-owner/fixture-repo/.github/workflows/desktop-bundled-release.yml@refs/heads/main',
'GITHUB_ACTOR': 'maintainer', 'GITHUB_TRIGGERING_ACTOR': 'maintainer',
'GITHUB_OUTPUT': str(output), 'UPLOAD_RELEASE': 'false',
- 'BUNDLE_ENV_JSON': '{"HERMES_GUEST_ONBOARDING":"1"}'}
+ 'BUNDLE_ENV_JSON': '{"HERMES_GUEST_ONBOARDING":"1","HERMES_HOME":null}'}
result, calls = invoke('admit', extra=env)
assert result.returncode == 0, result.stderr
assert dict(line.split('=', 1) for line in output.read_text(encoding='utf-8').splitlines()) == {