Skip to content

The agent that grows with you

fix(ci): predict the desktop smoke's Hermes home from the baked bundle env

ethernet0ecfcc28815d
diff --git a/apps/desktop/electron/data-paths.d.mts b/apps/desktop/electron/data-paths.d.mts
new file mode 100644
index 00000000000..8fbbc6c0cc2
--- /dev/null
+++ b/apps/desktop/electron/data-paths.d.mts
@@ -0,0 +1,17 @@
+export function platformDefaultHermesHome(
+ home: string,
+ env?: NodeJS.ProcessEnv,
+ platform?: NodeJS.Platform,
+): string
+
+export function resolveDesktopUserData(defaultPath: string, env?: NodeJS.ProcessEnv): string
+
+export interface HermesHomeOptions {
+ home: string
+ env?: NodeJS.ProcessEnv
+ platform?: NodeJS.Platform
+ directoryExists?: (directory: string) => boolean
+ readWindowsHome?: () => string | null
+}
+
+export function resolveDesktopHermesHome(options: HermesHomeOptions): string
diff --git a/apps/desktop/electron/data-paths.mjs b/apps/desktop/electron/data-paths.mjs
new file mode 100644
index 00000000000..1553bee1c7a
--- /dev/null
+++ b/apps/desktop/electron/data-paths.mjs
@@ -0,0 +1,66 @@
+// data-paths.mjs — the pure path-resolution core, shared by the desktop app
+// (via data-paths.ts, a typed re-export) and the CI smoke driver (which runs
+// under Node's type-stripping and therefore cannot import the app's
+// extensionless TypeScript directly). No Electron imports here; only node:path.
+//
+// data-paths.ts re-exports these names and adds the TypeScript-facing
+// `HermesHomeOptions` interface. Keep the two in lockstep: every behavior in
+// this file is exercised by data-paths.test.ts through the re-export.
+
+import path from 'node:path'
+
+/** A HERMES_HOME rooted inside a `profiles/` directory names the profile's
+ * parent (the home), not the profile directory itself. */
+function normalizeHermesHomeRoot(hermesHome, pathModule) {
+ if (!hermesHome) {
+ return hermesHome
+ }
+ const resolved = pathModule.resolve(String(hermesHome))
+ const parent = pathModule.dirname(resolved)
+ if (pathModule.basename(parent).toLowerCase() === 'profiles') {
+ return pathModule.dirname(parent)
+ }
+ return resolved
+}
+
+export function platformDefaultHermesHome(home, env = process.env, platform = process.platform) {
+ const suffix = env.HERMES_DATA_DIR_SUFFIX || ''
+ if (platform === 'win32') {
+ const base = (env.LOCALAPPDATA || '').trim() || path.win32.join(home, 'AppData', 'Local')
+ return path.win32.join(base, 'hermes') + suffix
+ }
+ return path.posix.join(home, '.hermes') + suffix
+}
+
+export function resolveDesktopUserData(defaultPath, env = process.env) {
+ return env.HERMES_DESKTOP_USER_DATA_DIR
+ ? path.resolve(env.HERMES_DESKTOP_USER_DATA_DIR)
+ : defaultPath + (env.HERMES_DATA_DIR_SUFFIX || '')
+}
+
+export function resolveDesktopHermesHome({ home, env = process.env, platform = process.platform, directoryExists = () => false, readWindowsHome = () => null }) {
+ const paths = platform === 'win32' ? path.win32 : path.posix
+ if (env.HERMES_HOME) {
+ return normalizeHermesHomeRoot(env.HERMES_HOME, paths)
+ }
+ // Fresh-install rehearsals must not touch the real Hermes home.
+ if (env.HERMES_DESKTOP_USER_DATA_DIR) {
+ return paths.join(paths.resolve(env.HERMES_DESKTOP_USER_DATA_DIR), 'hermes-home')
+ }
+ if (platform === 'win32' && env.HERMES_HOME === undefined) {
+ // Explorer can miss setx changes. An explicit empty value opts out of that fallback.
+ const registryHome = readWindowsHome()
+ if (registryHome) {
+ return normalizeHermesHomeRoot(registryHome, paths)
+ }
+ }
+ const defaultHome = platformDefaultHermesHome(home, env, platform)
+ // Keep the legacy migration for ordinary installs, not isolated suffix runs.
+ if (platform === 'win32' && !env.HERMES_DATA_DIR_SUFFIX) {
+ const legacy = paths.join(home, '.hermes')
+ if (!directoryExists(defaultHome) && directoryExists(legacy)) {
+ return legacy
+ }
+ }
+ return defaultHome
+}
diff --git a/apps/desktop/electron/data-paths.ts b/apps/desktop/electron/data-paths.ts
index c5515115d0f..f2ae0273520 100644
--- a/apps/desktop/electron/data-paths.ts
+++ b/apps/desktop/electron/data-paths.ts
@@ -1,74 +1,6 @@
-import path from 'node:path'
-
-import { normalizeHermesHomeRoot } from './backend-env'
-
-export function platformDefaultHermesHome(
- home: string,
- env: NodeJS.ProcessEnv = process.env,
- platform: NodeJS.Platform = process.platform
-): string {
- const suffix: string = env.HERMES_DATA_DIR_SUFFIX || ''
-
- if (platform === 'win32') {
- const base: string = env.LOCALAPPDATA?.trim() || path.win32.join(home, 'AppData', 'Local')
-
- return path.win32.join(base, 'hermes') + suffix
- }
-
- return path.posix.join(home, '.hermes') + suffix
-}
-
-export function resolveDesktopUserData(defaultPath: string, env: NodeJS.ProcessEnv = process.env): string {
- return env.HERMES_DESKTOP_USER_DATA_DIR
- ? path.resolve(env.HERMES_DESKTOP_USER_DATA_DIR)
- : defaultPath + (env.HERMES_DATA_DIR_SUFFIX || '')
-}
-
-interface HermesHomeOptions {
- home: string
- env?: NodeJS.ProcessEnv
- platform?: NodeJS.Platform
- directoryExists?: (directory: string) => boolean
- readWindowsHome?: () => string | null
-}
-
-export function resolveDesktopHermesHome({
- home,
- env = process.env,
- platform = process.platform,
- directoryExists = (): boolean => false,
- readWindowsHome = (): null => null
-}: HermesHomeOptions): string {
- const paths: typeof path = platform === 'win32' ? path.win32 : path.posix
-
- if (env.HERMES_HOME) {
- return normalizeHermesHomeRoot(env.HERMES_HOME, { pathModule: paths })
- }
-
- // Fresh-install rehearsals must not touch the real Hermes home.
- if (env.HERMES_DESKTOP_USER_DATA_DIR) {
- return paths.join(paths.resolve(env.HERMES_DESKTOP_USER_DATA_DIR), 'hermes-home')
- }
-
- 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) {
- return normalizeHermesHomeRoot(registryHome, { pathModule: paths })
- }
- }
-
- const defaultHome: string = platformDefaultHermesHome(home, env, platform)
-
- // Keep the legacy migration for ordinary installs, not isolated suffix runs.
- if (platform === 'win32' && !env.HERMES_DATA_DIR_SUFFIX) {
- const legacy: string = paths.join(home, '.hermes')
-
- if (!directoryExists(defaultHome) && directoryExists(legacy)) {
- return legacy
- }
- }
-
- return defaultHome
-}
+// data-paths.ts — typed re-export of the shared pure resolver in data-paths.mjs.
+// The app imports these names here (extensionless, for the tsc/esbuild build);
+// the CI smoke driver imports the .mjs directly because Node's type-stripping
+// cannot resolve extensionless TypeScript imports.
+export { platformDefaultHermesHome, resolveDesktopHermesHome, resolveDesktopUserData } from './data-paths.mjs'
+export type { HermesHomeOptions } from './data-paths.mjs'
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 6ecd8ec93bd..15693f80e50 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -16648,6 +16648,7 @@ ipcMain.handle('hermes:version', async (_event, scope?: { connectionId?: string;
nodeVersion: process.versions.node,
platform: process.platform,
hermesRoot: resolveUpdateRoot(),
+ hermesHome: HERMES_HOME,
bundleOutOfSync: skew.outOfSync,
bundleCommitsBehind: skew.desktopCommitsBehind,
// The install id: sha16 of the canonical install-root path — the key of
diff --git a/apps/desktop/scripts/bundle-env.d.mts b/apps/desktop/scripts/bundle-env.d.mts
new file mode 100644
index 00000000000..f6756922a05
--- /dev/null
+++ b/apps/desktop/scripts/bundle-env.d.mts
@@ -0,0 +1,8 @@
+export function validateBundleEnvironment(values: unknown): Record<string, string | null>
+
+export function applyBundleEnvironment(
+ env: Record<string, string | undefined>,
+ values: Record<string, string | null>,
+): Record<string, string | undefined>
+
+export function environmentDefaultsBanner(raw: string): string
diff --git a/apps/desktop/scripts/bundle-env.mjs b/apps/desktop/scripts/bundle-env.mjs
index f9698c35fe8..ca739150875 100644
--- a/apps/desktop/scripts/bundle-env.mjs
+++ b/apps/desktop/scripts/bundle-env.mjs
@@ -1,8 +1,11 @@
// Defaults must run before bundled modules resolve paths or onboarding flags.
// An esbuild define would replace reads, not populate the child process env.
-/** @param {string} raw @returns {string} */
-export function environmentDefaultsBanner(raw) {
- const values = JSON.parse(raw)
+
+/** Validate a bundle environment object: plain object of identifiers to
+ * strings (defaults) or null (clears). Shared by the banner writer and the
+ * smoke driver's stamp reader.
+ * @param {unknown} values @returns {Record<string, string|null>} */
+export function validateBundleEnvironment(values) {
if (!values || Array.isArray(values) || typeof values !== 'object') {
throw new Error('Bundle environment must be a JSON object')
}
@@ -11,6 +14,32 @@ export function environmentDefaultsBanner(raw) {
throw new Error('Bundle environment requires valid names and string values without NUL, or null to clear')
}
}
- // Keep clears present-but-empty so path resolution cannot restore registry defaults.
+ return /** @type {Record<string, string|null>} */ (values)
+}
+
+/** Apply bundle environment defaults/clears to a base environment and return a
+ * new object without mutating it. This is the pure twin of the side-effecting
+ * loop the bundled banner emits at launch — keep the two in lockstep (pinned
+ * by bundle-env.test.mjs). Clears (null) set the key to an empty string
+ * unconditionally so a stale registry or ambient value cannot win; defaults
+ * fill only an absent key, so an explicit runtime value always wins.
+ * @param {Record<string, string|undefined>} env
+ * @param {Record<string, string|null>} values */
+export function applyBundleEnvironment(env, values) {
+ const result = { ...env }
+ for (const [key, value] of Object.entries(values)) {
+ if (value === null) result[key] = ''
+ else if (result[key] == null) result[key] = value
+ }
+ return result
+}
+
+/** @param {string} raw @returns {string} */
+export function environmentDefaultsBanner(raw) {
+ const values = validateBundleEnvironment(JSON.parse(raw))
+ // Keep clears present-but-empty so path resolution cannot restore registry
+ // defaults. The emitted loop is the side-effecting twin of
+ // applyBundleEnvironment above; it cannot call it (the banner runs before
+ // the bundle's imports), so the two must stay in lockstep — see the test.
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 bc3d00503dd..79f37d7569d 100644
--- a/apps/desktop/scripts/bundle-env.test.mjs
+++ b/apps/desktop/scripts/bundle-env.test.mjs
@@ -6,7 +6,7 @@ import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { expect, test } from 'vitest'
-import { environmentDefaultsBanner } from './bundle-env.mjs'
+import { applyBundleEnvironment, 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-'))
@@ -41,6 +41,31 @@ test('explicit clears beat inherited homes and prevent Windows registry fallback
}
})
+test('applyBundleEnvironment replays the banner semantics for defaults, runtime overrides and clears', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'hermes-bundle-pure-'))
+ const defaults = { KEEP: 'default', MISSING: 'default', CLEARED: null, OVERRIDDEN: 'default', SUFFIX: 'baked' }
+ const keys = Object.keys(defaults)
+ const base = { KEEP: 'x', CLEARED: 'runtime', OVERRIDDEN: 'runtime', SUFFIX: 'explicit' }
+ try {
+ // The bundled banner must produce the same effective environment the pure
+ // function computes, so the smoke driver can predict the app's home from
+ // the same bundle env data without running a child process.
+ writeFileSync(join(root, 'reader.mjs'), `export const values = Object.fromEntries(${JSON.stringify(keys)}.map(key => [key, process.env[key]]));`, 'utf8')
+ const entry = join(root, 'entry.mjs')
+ writeFileSync(entry, `import {values} from './reader.mjs'; console.log(JSON.stringify(values));`, 'utf8')
+ const outfile = join(root, 'bundle.mjs')
+ await build({ entryPoints: [entry], bundle: true, platform: 'node', format: 'esm', outfile, banner: { js: environmentDefaultsBanner(JSON.stringify(defaults)) } })
+ const viaBanner = JSON.parse(execFileSync(process.execPath, [outfile], { env: { ...process.env, ...base }, encoding: 'utf8' }))
+ const viaFunction = Object.fromEntries(keys.map(key => [key, applyBundleEnvironment(base, defaults)[key]]))
+ expect(viaFunction).toEqual(viaBanner)
+ expect(viaFunction).toEqual({
+ KEEP: 'x', MISSING: 'default', CLEARED: '', OVERRIDDEN: 'runtime', SUFFIX: 'explicit',
+ })
+ } 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/apps/desktop/scripts/commit-stamp-identity.test.mjs b/apps/desktop/scripts/commit-stamp-identity.test.mjs
index fa6c6744711..b0b3232c5de 100644
--- a/apps/desktop/scripts/commit-stamp-identity.test.mjs
+++ b/apps/desktop/scripts/commit-stamp-identity.test.mjs
@@ -15,7 +15,7 @@ test('desktop stamp uses the admitted checkout rather than the dispatch SHA', ()
const git = (...args) => execFileSync('git', args, { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
try {
fs.mkdirSync(scripts, { recursive: true })
- for (const name of ['write-build-stamp.mjs', 'utils.mjs']) fs.copyFileSync(path.join(root, 'apps/desktop/scripts', name), path.join(scripts, name))
+ for (const name of ['write-build-stamp.mjs', 'utils.mjs', 'bundle-env.mjs']) fs.copyFileSync(path.join(root, 'apps/desktop/scripts', name), path.join(scripts, name))
fs.copyFileSync(path.join(root, 'apps/desktop/product-identity.cjs'), path.join(repo, 'apps/desktop/product-identity.cjs'))
fs.mkdirSync(path.join(repo, 'scripts'), { recursive: true })
fs.copyFileSync(path.join(root, 'scripts/msix-shared.mjs'), path.join(repo, 'scripts/msix-shared.mjs'))
@@ -51,8 +51,14 @@ test('desktop stamp uses the admitted checkout rather than the dispatch SHA', ()
assert.equal(stamp.source, 'commit-build')
assert.equal(stamp.tag, null)
assert.equal(stamp.updateMechanism, 'external')
+ assert.equal(stamp.bundleEnv, undefined)
assert.deepEqual(stamp.runtime, { ...runtime, commands: { hermes: `bin/hermes-${feature.slice(0, 7)}` } })
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(build, 'agent-payload/app/install-stamp.json'), 'utf8')), stamp)
+ // A commit bundle records its baked defaults/clears as data so the smoke
+ // driver can replay them without running the app.
+ const bundleEnv = { HERMES_HOME: null, HERMES_DATA_DIR_SUFFIX: '-suffix', HERMES_GUEST_ONBOARDING: '1' }
+ assert.equal(run({ HERMES_BUNDLE_ENV_JSON: JSON.stringify(bundleEnv) }).status, 0)
+ assert.deepEqual(JSON.parse(fs.readFileSync(out, 'utf8')).bundleEnv, bundleEnv)
const before = fs.readFileSync(out)
git('checkout', '-q', 'main')
assert.notEqual(run({}).status, 0)
diff --git a/apps/desktop/scripts/write-build-stamp.mjs b/apps/desktop/scripts/write-build-stamp.mjs
index 1e3ef81a32a..fa111a75df8 100644
--- a/apps/desktop/scripts/write-build-stamp.mjs
+++ b/apps/desktop/scripts/write-build-stamp.mjs
@@ -10,6 +10,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "
import { resolve, join, relative, posix } from "path"
import productIdentity from "../product-identity.cjs"
import { channelBuildRequest } from "../../../scripts/msix-shared.mjs"
+import { validateBundleEnvironment } from "./bundle-env.mjs"
import { execFileSync } from "child_process"
import { isMain } from "./utils.mjs"
@@ -215,6 +216,11 @@ export function buildStampPayload(stamp, env = process.env, platform = process.p
throw new Error('Commit builds cannot also set a release tag')
}
const version = env.HERMES_PAYLOAD_VERSION || (env.HERMES_PAYLOAD_TAG || '').replace(/^v/, '') || null
+ // The bundle's baked runtime defaults/clears, recorded as data so the smoke
+ // driver can predict the app's resolved Hermes home without reimplementing
+ // the banner. Only commit bundles carry one, but the field is harmless when
+ // absent elsewhere.
+ const bundleEnv = env.HERMES_BUNDLE_ENV_JSON ? validateBundleEnvironment(JSON.parse(env.HERMES_BUNDLE_ENV_JSON)) : undefined
const base = {
schemaVersion: STAMP_SCHEMA_VERSION,
commit: stamp.commit,
@@ -259,6 +265,7 @@ export function buildStampPayload(stamp, env = process.env, platform = process.p
updateMechanism: commitBuild ? 'external' : updateMechanism,
tag: channelBuild?.receiverCandidate ? channelBuild.releaseTag : env.HERMES_PAYLOAD_TAG || null,
+ ...(bundleEnv ? { bundleEnv } : {}),
...(bundled ? { runtime: payload.runtime } : {})
}
}
diff --git a/tests-js/scripts/desktop-chat-smoke.ts b/tests-js/scripts/desktop-chat-smoke.ts
index 22893d186eb..72b243ace06 100644
--- a/tests-js/scripts/desktop-chat-smoke.ts
+++ b/tests-js/scripts/desktop-chat-smoke.ts
@@ -24,6 +24,8 @@ export interface ChatIdentity {
commit: string | null
hermesRoot: string
platform: string
+ /** The resolved Hermes home (newer desktops report it; absent on older ones). */
+ hermesHome?: string
}
interface SmokeWindow extends Window {
@@ -53,7 +55,7 @@ export interface DesktopChatReceipt {
const identitySchema = z.object({
appVersion: z.string(), commit: z.string().nullable().optional(),
- hermesRoot: z.string(), platform: z.string(),
+ hermesRoot: z.string(), platform: z.string(), hermesHome: z.string().optional(),
})
export async function readChatIdentity(page: Page): Promise<ChatIdentity> {
diff --git a/tests-js/scripts/desktop-smoke-process.ts b/tests-js/scripts/desktop-smoke-process.ts
index add77d7673a..2cef4119288 100644
--- a/tests-js/scripts/desktop-smoke-process.ts
+++ b/tests-js/scripts/desktop-smoke-process.ts
@@ -31,6 +31,25 @@ export function readInstallationCommit(root: string, origin: 'source' | 'bundled
return z.string().regex(/^[0-9a-f]{40}$/).parse(commit)
}
+const bundleEnvSchema = z.record(z.string(), z.string().nullable())
+
+/** The baked runtime defaults/clears of a bundled artifact, recorded in the
+ * install stamp so the smoke driver can predict the app's resolved Hermes home
+ * without reimplementing the banner. Absent for artifacts built before the
+ * stamp carried it, and for source checkpoints. */
+export function readBundledBundleEnv(root: string): Record<string, string | null> | undefined {
+ const stampPath = path.join(root, '..', 'install-stamp.json')
+ // Absent for source checkpoints and artifacts built before the stamp carried
+ // bundleEnv; treat as "no baked env" and fall back to the pinned home.
+ if (!fs.existsSync(stampPath)) {
+ return undefined
+ }
+ const stamp = z.object({ payload: z.literal('bundled'), bundleEnv: bundleEnvSchema.optional() }).parse(
+ JSON.parse(fs.readFileSync(stampPath, 'utf8')),
+ )
+ return stamp.bundleEnv
+}
+
const windowsProcesses = z.array(z.object({
ProcessId: z.number(), ParentProcessId: z.number(), ExecutablePath: z.string().nullable(), CommandLine: z.string().nullable(),
}))
diff --git a/tests-js/scripts/desktop-smoke.test.ts b/tests-js/scripts/desktop-smoke.test.ts
index 4bafa91915b..1d2f86013b2 100644
--- a/tests-js/scripts/desktop-smoke.test.ts
+++ b/tests-js/scripts/desktop-smoke.test.ts
@@ -6,10 +6,10 @@ import path from 'node:path'
import yaml from 'js-yaml'
import { expect, test } from 'vitest'
-import { candidateSmokeHermesHomes, resolveSmokeLaunch, runInstalledDesktopSmoke, smokeEnvironment } from '../../tests/install/e2e-assets/desktop-smoke.ts'
+import { candidateSmokeHermesHomes, predictSmokeHermesHome, resolveSmokeLaunch, runInstalledDesktopSmoke, smokeEnvironment } from '../../tests/install/e2e-assets/desktop-smoke.ts'
import { assertChatCommit, newCompletedPair, readMockPrompts, type TranscriptMessage } from './desktop-chat-smoke.ts'
-import { assertBackendOrigin, localBackendProcess, readInstallationCommit } from './desktop-smoke-process.ts'
+import { assertBackendOrigin, localBackendProcess, readBundledBundleEnv, readInstallationCommit } from './desktop-smoke-process.ts'
import { writeEnvFile, writeMockProviderConfig } from './mock-provider-config.ts'
import { MOCK_REPLY, startMockServer } from './mock-server.ts'
@@ -196,6 +196,27 @@ test('driver strips caller secrets and records missing executables as failure wi
} finally { fs.rmSync(home, { recursive: true, force: true }) }
})
+test('predictSmokeHermesHome replays the bundle banner through the shared resolver', (): void => {
+ const launchEnv = { HERMES_HOME: '/pinned/home', HERMES_DESKTOP_USER_DATA_DIR: '/pinned/userdata', LOCALAPPDATA: 'C:/Users/runner/AppData/Local' }
+ // No baked env: the driver's own HERMES_HOME pin wins.
+ expect(predictSmokeHermesHome(launchEnv, {}, 'linux', '/real/home')).toBe('/pinned/home')
+ // HERMES_HOME cleared -> the <userData>/hermes-home fallback.
+ expect(predictSmokeHermesHome(launchEnv, { HERMES_HOME: null }, 'linux', '/real/home')).toBe('/pinned/userdata/hermes-home')
+ // Both cleared + baked suffix -> the platform default with that suffix.
+ expect(predictSmokeHermesHome(launchEnv, { HERMES_HOME: null, HERMES_DESKTOP_USER_DATA_DIR: null, HERMES_DATA_DIR_SUFFIX: '-magic' }, 'linux', '/real/home')).toBe('/real/home/.hermes-magic')
+ // On Windows the default derives from the sandboxed LOCALAPPDATA, not the OS home.
+ expect(predictSmokeHermesHome(launchEnv, { HERMES_HOME: null, HERMES_DESKTOP_USER_DATA_DIR: null, HERMES_DATA_DIR_SUFFIX: '-magic' }, 'win32', 'C:/Users/real')).toBe('C:\\Users\\runner\\AppData\\Local\\hermes-magic')
+})
+
+test('readBundledBundleEnv reads the stamped defaults/clears and is absent when unstamped', (): void => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-bundlenv-'))
+ try {
+ expect(readBundledBundleEnv(path.join(root, 'agent-payload'))).toBeUndefined()
+ fs.writeFileSync(path.join(root, 'install-stamp.json'), JSON.stringify({ payload: 'bundled', commit: 'a'.repeat(40), bundleEnv: { HERMES_HOME: null, SUFFIX: 'x' } }))
+ expect(readBundledBundleEnv(path.join(root, 'agent-payload'))).toEqual({ HERMES_HOME: null, SUFFIX: 'x' })
+ } finally { fs.rmSync(root, { recursive: true, force: true }) }
+})
+
test('a bundle-env HERMES_HOME clear cannot strand the mock config outside the resolved home', async (): Promise<void> => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'smoke-bundle-clear-'))
const home = path.join(root, 'home')
diff --git a/tests/install/e2e-assets/desktop-smoke.ts b/tests/install/e2e-assets/desktop-smoke.ts
index 9fa443c1517..a749205e315 100644
--- a/tests/install/e2e-assets/desktop-smoke.ts
+++ b/tests/install/e2e-assets/desktop-smoke.ts
@@ -1,4 +1,5 @@
import fs from 'node:fs'
+import os from 'node:os'
import { createRequire } from 'node:module'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
@@ -7,8 +8,10 @@ import { parseArgs } from 'node:util'
import { _electron, type ElectronApplication, type Page } from '@playwright/test'
import { z } from 'zod'
+import { resolveDesktopHermesHome } from '../../../apps/desktop/electron/data-paths.mjs'
+import { applyBundleEnvironment } from '../../../apps/desktop/scripts/bundle-env.mjs'
import { readChatIdentity, runDesktopChatSmoke, waitForChatReady } from '../../../tests-js/scripts/desktop-chat-smoke.ts'
-import { assertBackendOrigin, localBackendProcess, readInstallationCommit, within } from '../../../tests-js/scripts/desktop-smoke-process.ts'
+import { assertBackendOrigin, localBackendProcess, readBundledBundleEnv, readInstallationCommit, within } from '../../../tests-js/scripts/desktop-smoke-process.ts'
import { validateMockUrl, writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config.ts'
import { type MockServer, startMockServer } from '../../../tests-js/scripts/mock-server.ts'
@@ -94,6 +97,33 @@ export function candidateSmokeHermesHomes(home: string, userData: string): strin
return home === fallback ? [home] : [home, fallback]
}
+/** The home the app will resolve for a bundled artifact whose env defaults/clears
+ * are known from its stamp. Replays the bundle banner over the launch env, then
+ * runs the same resolver the app runs, so the driver can seed the home before
+ * boot instead of pinning HERMES_HOME and hoping the artifact honors it. */
+export function predictSmokeHermesHome(
+ launchEnv: NodeJS.ProcessEnv,
+ bundleEnv: Record<string, string | null>,
+ platform: NodeJS.Platform = process.platform,
+ home: string = platform === 'linux' ? launchEnv.HOME || os.homedir() : os.homedir(),
+): string {
+ const effective = applyBundleEnvironment(launchEnv, bundleEnv)
+ return resolveDesktopHermesHome({ home, env: effective, platform, directoryExists: (): boolean => false, readWindowsHome: (): null => null })
+}
+
+/** A predicted home must be empty before the driver seeds it: the smoke tests a
+ * fresh install, and a non-empty home means the prediction is wrong or the run
+ * is dirty. Never wipe — a wrong prediction should fail loudly, not delete data. */
+function requireEmptyHermesHome(home: string): void {
+ if (!fs.existsSync(home)) {
+ return
+ }
+ const entries = fs.readdirSync(home)
+ if (entries.length > 0) {
+ throw new Error(`Predicted Hermes home ${home} is not empty (${entries.length} entries); refusing to seed an existing profile`)
+ }
+}
+
export function resolveSmokeLaunch(options: SmokeOptions): Launch {
const spec = options['launch-spec'] ? launchSpecSchema.parse(JSON.parse(fs.readFileSync(options['launch-spec'], 'utf8').replace(/^\uFEFF/, ''))) : null
const env = smokeEnvironment({ ...process.env, ...spec?.env }, options.home, options['user-data'])
@@ -201,7 +231,7 @@ async function gracefulClose(app: ElectronApplication): Promise<void> {
}
}
-async function verifyRunningDesktop(app: ElectronApplication, options: SmokeOptions, launch: Launch): Promise<RunningDesktop> {
+async function verifyRunningDesktop(app: ElectronApplication, options: SmokeOptions, launch: Launch, predictedHome?: string): Promise<RunningDesktop> {
const running = await app.evaluate(({ app: electronApp }): RunningDesktop => {
// SAFETY: this callback runs in Electron main, whose process includes resourcesPath.
const runtime = process as ElectronProcess
@@ -211,11 +241,17 @@ async function verifyRunningDesktop(app: ElectronApplication, options: SmokeOpti
// (NSHomeDirectory) and Windows (CSIDL_PROFILE) ignore it, so the home
// equality is a contract only there. On those platforms the isolation proof
// is the userData pin plus the seeded Hermes home the backend booted from.
- const homeHonored = process.platform === 'linux'
- ? fs.realpathSync(running.home) === fs.realpathSync(launch.env.HOME!)
- : true
- if (fs.realpathSync(running.userData) !== fs.realpathSync(options['user-data']) || !homeHonored) {
- throw new Error('Desktop did not honor the isolated home and userData directories')
+ // When the artifact bakes its own env (bundleEnv known from the stamp), the
+ // driver's --user-data pin is not authoritative: the app may legitimately
+ // resolve a different userData, and the home the driver predicted and seeded
+ // is verified against the app's own report below instead.
+ if (!predictedHome) {
+ const homeHonored = process.platform === 'linux'
+ ? fs.realpathSync(running.home) === fs.realpathSync(launch.env.HOME!)
+ : true
+ if (fs.realpathSync(running.userData) !== fs.realpathSync(options['user-data']) || !homeHonored) {
+ throw new Error('Desktop did not honor the isolated home and userData directories')
+ }
}
if (fs.realpathSync(running.executable) !== fs.realpathSync(options.exe)) {
throw new Error('Running Electron executable differs from --exe')
@@ -233,6 +269,7 @@ export async function runInstalledDesktopSmoke(options: SmokeOptions): Promise<v
let mock: MockServer | undefined
let app: ElectronApplication | undefined
let page: Page | undefined
+ let predictedHome: string | undefined
const consoleLines: string[] = []
try {
fs.accessSync(options.exe, fs.constants.X_OK)
@@ -254,8 +291,13 @@ export async function runInstalledDesktopSmoke(options: SmokeOptions): Promise<v
const mockUrl = validateMockUrl(options['mock-url'] ?? mock!.url)
// A bundle-env HERMES_HOME clear (see candidateSmokeHermesHomes) can make the
// app resolve a different home than --home, so every candidate gets the mock
- // provider config and .env.
- for (const home of candidateSmokeHermesHomes(options.home, options['user-data'])) {
+ // provider config and .env. When the artifact's stamp carries its baked
+ // bundle env, predict the home the app will actually resolve and seed that
+ // too, refusing to seed a non-empty one.
+ const bundleEnv = options.origin === 'bundled' ? readBundledBundleEnv(options.root) : undefined
+ predictedHome = bundleEnv ? predictSmokeHermesHome(launch.env, bundleEnv) : undefined
+ for (const home of new Set([...candidateSmokeHermesHomes(options.home, options['user-data']), ...(predictedHome ? [predictedHome] : [])])) {
+ if (predictedHome && home === predictedHome) { requireEmptyHermesHome(home) }
writeMockProviderConfig(home, mockUrl)
writeEnvFile(home)
}
@@ -267,7 +309,7 @@ export async function runInstalledDesktopSmoke(options: SmokeOptions): Promise<v
page.on('pageerror', (error: Error): void => { consoleLines.push(redact(error.message)) })
await prepareWindowForInput(app, page)
await waitForChatReady(page)
- const running = await verifyRunningDesktop(app, options, launch)
+ const running = await verifyRunningDesktop(app, options, launch, predictedHome)
const connection = await backendConnection(page)
const base = new URL(connection.baseUrl)
if (connection.mode !== 'local' || !['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname)) {
@@ -277,6 +319,14 @@ export async function runInstalledDesktopSmoke(options: SmokeOptions): Promise<v
if (options.origin === 'source' && fs.realpathSync(identity.hermesRoot) !== fs.realpathSync(options.root)) {
throw new Error('Desktop resolved a different source installation')
}
+ // A bundled artifact that bakes its own env resolves its home itself; the
+ // app must report the home the driver predicted and seeded, not some other
+ // (possibly real, pre-existing) profile.
+ if (predictedHome) {
+ if (!identity.hermesHome || fs.realpathSync(identity.hermesHome) !== fs.realpathSync(predictedHome)) {
+ throw new Error(`Desktop resolved Hermes home ${identity.hermesHome ?? '(unreported)'} instead of the predicted ${predictedHome}`)
+ }
+ }
const backend = localBackendProcess(Number(base.port), running.pid)
assertBackendOrigin(backend, options.root, options.origin)
const provenanceCommit = readInstallationCommit(options.root, options.origin)
@@ -286,7 +336,7 @@ export async function runInstalledDesktopSmoke(options: SmokeOptions): Promise<v
await app.context().tracing.start({ screenshots: true, snapshots: false, sources: false })
const chat = await runDesktopChatSmoke(page, { mockUrl, phase: options.phase, outDir: out, expectCommit: options['expect-commit'], provenanceCommit })
fs.writeFileSync(receiptPath, `${JSON.stringify({ ...chat, status: 'closing' }, null, 2)}\n`)
- const result = { ...chat, origin: options.origin, root: options.root, executable: options.exe, running,
+ const result = { ...chat, origin: options.origin, root: options.root, executable: options.exe, running, predictedHome,
localModeConfigured: true, backend: { ...backend, command: redact(backend.command) }, launchKind: options.phase === 'new' ? 'post-update-launch' : 'installed-launch' }
await app.context().tracing.stop({ path: path.join(out, `desktop-chat-${options.phase}.zip`) })
await gracefulClose(app)
@@ -301,7 +351,7 @@ export async function runInstalledDesktopSmoke(options: SmokeOptions): Promise<v
} finally {
fs.writeFileSync(path.join(out, `desktop-app-${options.phase}.log`), consoleLines.join('\n'))
try {
- captureBackendLogs(candidateSmokeHermesHomes(options.home, options['user-data']), out, options.phase)
+ captureBackendLogs([...new Set([...candidateSmokeHermesHomes(options.home, options['user-data']), ...(predictedHome ? [predictedHome] : [])])], out, options.phase)
} finally {
if (app) { await gracefulClose(app).catch((error: Error): void => { console.error(redact(error.message)) }) }
if (mock) { await mock.close() }