feat(desktop): thin installer + first-launch install.ps1 bootstrap
Converges the Windows packaged desktop installer onto a single canonical
install topology: drop the Electron shell only (~80MB instead of ~500MB),
clone Hermes Agent at a build-time-pinned commit on first launch via
install.ps1's stage protocol, and treat the resulting git checkout at
%LOCALAPPDATA%\hermes\hermes-agent\ as the canonical install location
(same path the CLI installer uses). Future updates flow through the
existing applyUpdates() git-pull path.
Replaces the previous fat-installer architecture where the .exe bundled
a pre-staged hermes-agent source tree under resources/hermes-agent/ that
was then sync'd into ACTIVE_HERMES_ROOT at launch -- a complicated
factory-vs-active dance with several footguns (FACTORY_HERMES_ROOT
mismatch on path resolve, isGitCheckout guard regressions, pyproject
hash drift detection inside the sync loop).
Architecture overview
---------------------
Build time
apps/desktop/scripts/write-build-stamp.cjs writes
apps/desktop/build/install-stamp.json with {commit, branch, builtAt,
dirty}. Honours $GITHUB_SHA / $GITHUB_REF_NAME in CI, falls back to
`git rev-parse HEAD` locally.
apps/desktop/scripts/stage-native-deps.cjs copies the runtime subset
of @homebridge/node-pty-prebuilt-multiarch from the workspace-root
node_modules into apps/desktop/build/native-deps/. Workspace dedup
hoists this dep to the root, out of reach of electron-builder's
`files:`-restricted collector; staging gives us a deterministic
path to extraResources.
electron-builder ships both into resources/install-stamp.json and
resources/native-deps/ respectively.
Boot resolver (electron/main.cjs)
Resolver order:
1. HERMES_DESKTOP_HERMES_ROOT override
2. SOURCE_REPO_ROOT (dev mode)
3. ACTIVE_HERMES_ROOT git checkout WITH .hermes-bootstrap-complete
marker -- the post-install fast path
4. `hermes` on PATH (CLI-installed user adding the desktop)
5. pip-installed hermes_cli via system Python
6. bootstrap-needed sentinel -> hand off to runBootstrap
Deletes the entire FACTORY_HERMES_ROOT / RUNTIME_MARKER /
syncTreeExcludingVenv machinery (-200 lines). The isGitCheckout
guard that bit us in the install.ps1 PR is gone.
First-launch bootstrap (electron/bootstrap-runner.cjs)
1. Resolve install.ps1: prefer SOURCE_REPO_ROOT/scripts (dev), else
download from GitHub raw at INSTALL_STAMP.commit (cached at
HERMES_HOME\bootstrap-cache\install-<sha>.ps1).
2. Fetch the stage manifest via install.ps1 -Manifest -Commit X
-Branch Y.
3. Iterate stages: install.ps1 -Stage <name> -NonInteractive -Json
-Commit X -Branch Y per stage.
4. On all stages green: write the .hermes-bootstrap-complete
marker with {schemaVersion, pinnedCommit, pinnedBranch,
completedAt, desktopVersion}.
Per-run log to HERMES_HOME\logs\bootstrap-<ts>.log. Cancellation
via AbortSignal. Manifest cache so retries don't re-download.
Install overlay (src/components/desktop-install-overlay.tsx)
Mounted alongside the existing onboarding overlay; flexbox card
with header (static) + middle (scrollable) + footer (failure-only,
static). Subscribes to hermes:bootstrap:event IPC + resyncs from
hermes:bootstrap:get on mount/reload. Renders:
- 14-stage checklist with per-stage state icons
- Overall progress bar + current-stage spotlight
- Auto-expanded installer-output panel on failure
- "Copy output" button (full ring buffer + error to clipboard)
- "Reload and retry" wired through hermes:bootstrap:reset to
clear main.cjs's latched failure
Synthetic empty-manifest event from main.cjs flips the overlay to
'active' immediately so the slow install.ps1 download doesn't
leave the user staring at the generic Preparing splash.
Failure latching (main.cjs)
bootstrapFailure module-scope variable holds the rejection after
install.ps1 fails. startHermes() throws the latched error
immediately when set, bypassing the entire ensureRuntime +
runBootstrap chain. Without this, the renderer's ensureGatewayOpen
retries would re-run install.ps1 in a 5-10 min hot loop while the
user was still reading the failure overlay. Cleared via
hermes:bootstrap:reset on user-driven retry.
Unsupported-platform overlay (1F)
macOS / Linux packaged builds (no install.sh stage protocol yet)
emit an unsupported-platform event with a copy-pasteable install
command + docs URL. Dedicated overlay branch with "Copy command"
+ "I've run it -- retry" buttons.
install.ps1 additions (Phase 1F.3 + 1F.5)
-----------------------------------------
New -Commit and -Tag string params. Precedence Commit > Tag >
Branch. Honoured by all three code paths (update / fresh clone /
ZIP fallback), with archive URL selection that handles each
ref-type variant. Detached-HEAD checkouts intentionally -- they're
pins, not branches the user pulls into.
EAP=Continue wrap around the new pin-step git invocations. `git
fetch origin <commit>` writes the routine 'From <url>' info line to
stderr; under the script's global EAP=Stop that terminates the
script even though fetch+checkout succeed. Matches the established
pattern in Install-Uv, Test-Python, _Run-NpmInstall.
Backend fix (hermes_cli/web_server.py)
--------------------------------------
CORS allow_origin_regex now accepts Origin: 'null'. Packaged
Electron loads index.html via file://; Chromium sets the WebSocket
upgrade Origin header to the opaque origin 'null', which the old
regex rejected with HTTP 403 before gateway_ws() ever ran. This
failure mode was masked in the older FACTORY_HERMES_ROOT
architecture because the resolver often found an existing hermes
on PATH with different binding behavior.
Security maintained: localhost-only bind keeps cross-machine pages
out; per-process session token still gates every authenticated
/api/ endpoint regardless of Origin.
Desktop QoL
-----------
DevTools is now enabled in packaged builds (F12 / Cmd+Opt+I).
Field-debugging trade-off: tiny attack surface increase versus
a much better support story when CSP / WS / theme issues surface.
NSIS prereq-check page deleted (-767 lines). The standard
Welcome -> License -> Directory -> InstallFiles -> Finish wizard
now installs without custom Python/Git/ripgrep detection -- those
prereqs are install.ps1's job at first launch.
Test infrastructure (Phase 1G)
------------------------------
apps/desktop/scripts/test-desktop.mjs rewritten as a cross-platform
bundle validator (was darwin-only and asserted on dead factory-
payload paths):
NEGATIVE: hermes_cli/main.py is NOT shipped (regression guard)
POSITIVE: install-stamp.json carries a real commit + branch
POSITIVE: node-pty native deps shipped under resources/native-deps
POSITIVE: renderer dist/index.html reachable (asar or unpacked)
New nsis mode and npm run test:desktop:nsis script.
Validated end-to-end on clean Win10 VM
--------------------------------------
Confirmed: NSIS installer drops Electron shell, app launches,
install overlay shows progress, install.ps1 clones the pinned
commit, 14 stages run to completion, marker written, backend
spawns, WebSocket connects, onboarding overlay asks for API key,
main UI loads, integrated terminal works.
Failures handled: bootstrap stays failed (no hot-loop retry),
"Copy output" gives actionable transcript, "Reload and retry"
explicitly re-runs install.ps1.
What's deferred
---------------
- MSIX wrapping (Phase 2): same Electron .exe under MSIX manifest
with runFullTrust, signed and submitted to Microsoft Store.
- install.sh stage protocol parity (Phase 2): once shipped, the
unsupported-platform overlay becomes drive-it-yourself and
macOS/Linux packaged installers gain feature parity with Windows.
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* Desktop bundles ship precompiled renderer assets and a staged Hermes payload
|
||||
* from extraResources. Returning false here tells electron-builder to skip the
|
||||
* node_modules collector/install step, which avoids workspace dependency graph
|
||||
* explosions and keeps packaging deterministic across environments.
|
||||
* Desktop bundles ship precompiled renderer assets. Returning false here tells
|
||||
* electron-builder to skip the node_modules collector/install step, which
|
||||
* avoids workspace dependency graph explosions and keeps packaging
|
||||
* deterministic across environments. The Hermes Agent Python payload is no
|
||||
* longer bundled; the Electron app fetches it at first launch via
|
||||
* `install.ps1`'s stage protocol (Windows). See `electron/main.cjs`.
|
||||
*/
|
||||
module.exports = async function beforeBuild() {
|
||||
return false
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
import fs from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const DESKTOP_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const REPO_ROOT = path.resolve(DESKTOP_ROOT, '../..')
|
||||
const OUT_ROOT = path.join(DESKTOP_ROOT, 'build', 'hermes-agent')
|
||||
|
||||
const ROOT_FILES = [
|
||||
'README.md',
|
||||
'LICENSE',
|
||||
'pyproject.toml',
|
||||
'run_agent.py',
|
||||
'model_tools.py',
|
||||
'toolsets.py',
|
||||
'batch_runner.py',
|
||||
'trajectory_compressor.py',
|
||||
'toolset_distributions.py',
|
||||
'cli.py',
|
||||
'hermes_constants.py',
|
||||
'hermes_logging.py',
|
||||
'hermes_state.py',
|
||||
'hermes_time.py',
|
||||
'rl_cli.py',
|
||||
'utils.py'
|
||||
]
|
||||
|
||||
const ROOT_DIRS = [
|
||||
'acp_adapter',
|
||||
'agent',
|
||||
'cron',
|
||||
'gateway',
|
||||
'hermes_cli',
|
||||
'plugins',
|
||||
'scripts',
|
||||
'skills',
|
||||
'tools',
|
||||
'tui_gateway'
|
||||
]
|
||||
|
||||
const TUI_FILES = ['package.json', 'package-lock.json']
|
||||
const TUI_DIRS = ['dist', 'packages/hermes-ink/dist']
|
||||
|
||||
const EXCLUDED_NAMES = new Set([
|
||||
'.DS_Store',
|
||||
'.git',
|
||||
'.mypy_cache',
|
||||
'.pytest_cache',
|
||||
'.ruff_cache',
|
||||
'.venv',
|
||||
'__pycache__',
|
||||
'node_modules',
|
||||
'release',
|
||||
'venv'
|
||||
])
|
||||
|
||||
function keep(entry) {
|
||||
return !EXCLUDED_NAMES.has(entry.name) && !entry.name.endsWith('.pyc') && !entry.name.endsWith('.pyo')
|
||||
}
|
||||
|
||||
async function exists(target) {
|
||||
try {
|
||||
await fs.access(target)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function copyFileIfPresent(relativePath) {
|
||||
const from = path.join(REPO_ROOT, relativePath)
|
||||
if (!(await exists(from))) return
|
||||
|
||||
const to = path.join(OUT_ROOT, relativePath)
|
||||
await fs.mkdir(path.dirname(to), { recursive: true })
|
||||
await fs.copyFile(from, to)
|
||||
}
|
||||
|
||||
async function copyDirIfPresent(relativePath) {
|
||||
const from = path.join(REPO_ROOT, relativePath)
|
||||
if (!(await exists(from))) return
|
||||
|
||||
const to = path.join(OUT_ROOT, relativePath)
|
||||
await fs.cp(from, to, {
|
||||
recursive: true,
|
||||
filter: source => keep({ name: path.basename(source) })
|
||||
})
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await fs.rm(OUT_ROOT, { force: true, recursive: true })
|
||||
await fs.mkdir(OUT_ROOT, { recursive: true })
|
||||
|
||||
await Promise.all(ROOT_FILES.map(copyFileIfPresent))
|
||||
|
||||
for (const dir of ROOT_DIRS) {
|
||||
await copyDirIfPresent(dir)
|
||||
}
|
||||
|
||||
for (const file of TUI_FILES) {
|
||||
await copyFileIfPresent(path.join('ui-tui', file))
|
||||
}
|
||||
|
||||
for (const dir of TUI_DIRS) {
|
||||
await copyDirIfPresent(path.join('ui-tui', dir))
|
||||
}
|
||||
}
|
||||
|
||||
await main()
|
||||
@@ -0,0 +1,127 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Stage native node-modules dependencies for electron-builder packaging.
|
||||
*
|
||||
* Workspace dedup hoists @homebridge/node-pty-prebuilt-multiarch into the
|
||||
* root `node_modules/`, which electron-builder's default file collector
|
||||
* (when `files:` is explicitly set in package.json) cannot reach. The
|
||||
* result: packaged builds ship with no .node binaries and PTY initialization
|
||||
* fails at runtime ("PTY support is unavailable").
|
||||
*
|
||||
* Rather than restructure the workspace dedup (would require nohoist /
|
||||
* package.json shenanigans and risk breaking dev) or balloon the package
|
||||
* with the whole node_modules tree, we copy ONLY the runtime-essential
|
||||
* files of the native dep into apps/desktop/build/native-deps/ and ship
|
||||
* THAT subtree via extraResources. main.cjs falls back to require()-ing
|
||||
* from process.resourcesPath when the hoisted-root require fails.
|
||||
*
|
||||
* Runs as part of `npm run build`. Idempotent -- always re-stages on each
|
||||
* build to pick up native binary updates.
|
||||
*/
|
||||
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const APP_ROOT = path.resolve(__dirname, '..')
|
||||
const REPO_ROOT = path.resolve(APP_ROOT, '..', '..')
|
||||
const STAGE_ROOT = path.join(APP_ROOT, 'build', 'native-deps')
|
||||
|
||||
// Modules to stage. The "from" path is the hoisted location in the workspace
|
||||
// root; "to" is the layout we want inside build/native-deps/. The "include"
|
||||
// globs (relative to "from") select the runtime-essential files. Anything
|
||||
// outside the include list is left behind (source, deps/, scripts/, etc.).
|
||||
const NATIVE_DEPS = [
|
||||
{
|
||||
from: path.join(REPO_ROOT, 'node_modules', '@homebridge', 'node-pty-prebuilt-multiarch'),
|
||||
to: path.join(STAGE_ROOT, '@homebridge', 'node-pty-prebuilt-multiarch'),
|
||||
include: [
|
||||
'package.json',
|
||||
'lib/**',
|
||||
'build/Release/*.node'
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
function rmrf(target) {
|
||||
fs.rmSync(target, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
function ensureDir(target) {
|
||||
fs.mkdirSync(target, { recursive: true })
|
||||
}
|
||||
|
||||
function walk(root) {
|
||||
const results = []
|
||||
const stack = [root]
|
||||
while (stack.length) {
|
||||
const current = stack.pop()
|
||||
let entries
|
||||
try {
|
||||
entries = fs.readdirSync(current, { withFileTypes: true })
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const full = path.join(current, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
stack.push(full)
|
||||
} else if (entry.isFile()) {
|
||||
results.push(full)
|
||||
}
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
// Match a relative path against simple ** and * glob patterns. Implementation
|
||||
// is intentionally tiny -- the include lists are small and don't need full
|
||||
// minimatch support.
|
||||
function matchGlob(rel, pattern) {
|
||||
const r = rel.replace(/\\/g, '/')
|
||||
const re = new RegExp(
|
||||
'^' +
|
||||
pattern
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||||
.replace(/\*\*/g, '__DOUBLE_STAR__')
|
||||
.replace(/\*/g, '[^/]*')
|
||||
.replace(/__DOUBLE_STAR__/g, '.*') +
|
||||
'$'
|
||||
)
|
||||
return re.test(r)
|
||||
}
|
||||
|
||||
function stageOne(spec) {
|
||||
if (!fs.existsSync(spec.from)) {
|
||||
throw new Error(
|
||||
`stage-native-deps: source missing at ${spec.from}. Run \`npm install\` ` +
|
||||
`at the workspace root first.`
|
||||
)
|
||||
}
|
||||
rmrf(spec.to)
|
||||
ensureDir(spec.to)
|
||||
|
||||
const files = walk(spec.from)
|
||||
let copied = 0
|
||||
for (const abs of files) {
|
||||
const rel = path.relative(spec.from, abs)
|
||||
const included = spec.include.some(g => matchGlob(rel, g))
|
||||
if (!included) continue
|
||||
const dest = path.join(spec.to, rel)
|
||||
ensureDir(path.dirname(dest))
|
||||
fs.copyFileSync(abs, dest)
|
||||
copied += 1
|
||||
}
|
||||
console.log(`[stage-native-deps] ${path.relative(APP_ROOT, spec.to)}: ${copied} files`)
|
||||
}
|
||||
|
||||
function main() {
|
||||
rmrf(STAGE_ROOT)
|
||||
ensureDir(STAGE_ROOT)
|
||||
for (const spec of NATIVE_DEPS) {
|
||||
stageOne(spec)
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
@@ -10,12 +10,54 @@ const PACKAGE_JSON = JSON.parse(fs.readFileSync(path.join(DESKTOP_ROOT, 'package
|
||||
const MODE = process.argv[2] || 'help'
|
||||
const ARCH = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||
const RELEASE_ROOT = path.join(DESKTOP_ROOT, 'release')
|
||||
const APP_PATH = path.join(RELEASE_ROOT, `mac-${ARCH}`, 'Hermes.app')
|
||||
const APP_BIN = path.join(APP_PATH, 'Contents', 'MacOS', 'Hermes')
|
||||
// Default HERMES_HOME for non-sandboxed mac runs — matches main.cjs's
|
||||
// resolveHermesHome(). The fresh-install sandbox launchFresh() sets its own
|
||||
const PLATFORM = process.platform
|
||||
|
||||
// Platform-specific packaged-app layout. The thin installer ships an Electron
|
||||
// app shell plus extraResources (install-stamp.json + native-deps/) -- it
|
||||
// no longer bundles the Hermes Agent Python payload (that's fetched at first
|
||||
// launch via install.ps1 / install.sh, per the Phase 1 thin-installer flow).
|
||||
const APP = (() => {
|
||||
if (PLATFORM === 'darwin') {
|
||||
const appPath = path.join(RELEASE_ROOT, `mac-${ARCH}`, 'Hermes.app')
|
||||
return {
|
||||
appPath,
|
||||
binary: path.join(appPath, 'Contents', 'MacOS', 'Hermes'),
|
||||
resourcesPath: path.join(appPath, 'Contents', 'Resources'),
|
||||
asarPath: path.join(appPath, 'Contents', 'Resources', 'app.asar'),
|
||||
unpackedDistIndex: path.join(appPath, 'Contents', 'Resources', 'app.asar.unpacked', 'dist', 'index.html')
|
||||
}
|
||||
}
|
||||
if (PLATFORM === 'win32') {
|
||||
const unpacked = path.join(RELEASE_ROOT, 'win-unpacked')
|
||||
return {
|
||||
appPath: unpacked,
|
||||
binary: path.join(unpacked, 'Hermes.exe'),
|
||||
resourcesPath: path.join(unpacked, 'resources'),
|
||||
asarPath: path.join(unpacked, 'resources', 'app.asar'),
|
||||
unpackedDistIndex: path.join(unpacked, 'resources', 'app.asar.unpacked', 'dist', 'index.html')
|
||||
}
|
||||
}
|
||||
// linux unpacked layout matches windows but with different binary name
|
||||
const unpacked = path.join(RELEASE_ROOT, 'linux-unpacked')
|
||||
return {
|
||||
appPath: unpacked,
|
||||
binary: path.join(unpacked, 'hermes'),
|
||||
resourcesPath: path.join(unpacked, 'resources'),
|
||||
asarPath: path.join(unpacked, 'resources', 'app.asar'),
|
||||
unpackedDistIndex: path.join(unpacked, 'resources', 'app.asar.unpacked', 'dist', 'index.html')
|
||||
}
|
||||
})()
|
||||
|
||||
// Default HERMES_HOME for non-sandboxed runs -- matches main.cjs's
|
||||
// resolveHermesHome(). On Windows it's %LOCALAPPDATA%\hermes; elsewhere
|
||||
// it's ~/.hermes. The fresh-install sandbox launchFresh() sets its own
|
||||
// HERMES_HOME and never touches this.
|
||||
const DEFAULT_HERMES_HOME = path.join(os.homedir(), '.hermes')
|
||||
const DEFAULT_HERMES_HOME = (() => {
|
||||
if (PLATFORM === 'win32' && process.env.LOCALAPPDATA) {
|
||||
return path.join(process.env.LOCALAPPDATA, 'hermes')
|
||||
}
|
||||
return path.join(os.homedir(), '.hermes')
|
||||
})()
|
||||
const VENV_ROOT = path.join(DEFAULT_HERMES_HOME, 'hermes-agent', 'venv')
|
||||
const FRESH_SANDBOX_ROOT = path.join(os.tmpdir(), 'hermes-desktop-fresh-install')
|
||||
|
||||
@@ -28,7 +70,7 @@ function run(command, args, options = {}) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: options.cwd || DESKTOP_ROOT,
|
||||
env: options.env || process.env,
|
||||
shell: Boolean(options.shell),
|
||||
shell: Boolean(options.shell) || PLATFORM === 'win32',
|
||||
stdio: 'inherit'
|
||||
})
|
||||
|
||||
@@ -37,19 +79,43 @@ function run(command, args, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
function output(command, args) {
|
||||
const result = spawnSync(command, args, {
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'ignore']
|
||||
})
|
||||
|
||||
return result.status === 0 ? result.stdout.trim() : ''
|
||||
}
|
||||
|
||||
function exists(target) {
|
||||
return fs.existsSync(target)
|
||||
}
|
||||
|
||||
// Match nodepty native binding location to what main.cjs's resolver fallback
|
||||
// expects (apps/desktop/electron/main.cjs, packaged-build branch).
|
||||
function expectedNativeDepPaths() {
|
||||
const root = path.join(APP.resourcesPath, 'native-deps', '@homebridge', 'node-pty-prebuilt-multiarch')
|
||||
const releaseDir = path.join(root, 'build', 'Release')
|
||||
// Just check the package.json exists; the actual .node binary names vary
|
||||
// (pty.node + conpty.node on Windows; pty.node on Unix), so we let the
|
||||
// existence-of-the-directory + a non-empty list be enough.
|
||||
return {
|
||||
packageJson: path.join(root, 'package.json'),
|
||||
releaseDir,
|
||||
libIndex: path.join(root, 'lib', 'index.js')
|
||||
}
|
||||
}
|
||||
|
||||
function ensurePlatformBuilds() {
|
||||
if (PLATFORM === 'darwin') return
|
||||
if (PLATFORM === 'win32') return
|
||||
die(
|
||||
`Desktop bundle validation is only wired for darwin / win32 today; platform=${PLATFORM} ` +
|
||||
`is not yet supported. The thin-installer story for Linux ships in Phase 2 alongside ` +
|
||||
`install.sh's stage protocol.`
|
||||
)
|
||||
}
|
||||
|
||||
function ensurePackagedApp() {
|
||||
if (process.env.HERMES_DESKTOP_SKIP_BUILD === '1' && exists(APP.binary)) {
|
||||
return
|
||||
}
|
||||
|
||||
run('npm', ['run', 'pack'])
|
||||
}
|
||||
|
||||
function resolveDmgPath() {
|
||||
if (!exists(RELEASE_ROOT)) {
|
||||
return path.join(RELEASE_ROOT, `Hermes-${PACKAGE_JSON.version}-${ARCH}.dmg`)
|
||||
@@ -67,49 +133,68 @@ function resolveDmgPath() {
|
||||
return bMtime - aMtime
|
||||
})
|
||||
|
||||
if (candidates.length > 0) {
|
||||
return path.join(RELEASE_ROOT, candidates[0])
|
||||
}
|
||||
|
||||
return path.join(RELEASE_ROOT, `Hermes-${PACKAGE_JSON.version}-${ARCH}.dmg`)
|
||||
return candidates.length > 0
|
||||
? path.join(RELEASE_ROOT, candidates[0])
|
||||
: path.join(RELEASE_ROOT, `Hermes-${PACKAGE_JSON.version}-${ARCH}.dmg`)
|
||||
}
|
||||
|
||||
function ensureMac() {
|
||||
if (process.platform !== 'darwin') {
|
||||
die('Desktop launch tests are macOS-only from this script.')
|
||||
}
|
||||
}
|
||||
|
||||
function ensurePackagedApp() {
|
||||
if (process.env.HERMES_DESKTOP_SKIP_BUILD === '1' && exists(APP_BIN)) {
|
||||
return
|
||||
}
|
||||
|
||||
run('npm', ['run', 'pack'])
|
||||
function resolveNsisPath() {
|
||||
// electron-builder NSIS artifactName template is 'Hermes-${version}-${os}-${arch}.${ext}'
|
||||
if (!exists(RELEASE_ROOT)) return null
|
||||
const candidates = fs
|
||||
.readdirSync(RELEASE_ROOT)
|
||||
.filter(name => /\.exe$/i.test(name) && /win/i.test(name))
|
||||
.sort((a, b) => {
|
||||
const aMtime = fs.statSync(path.join(RELEASE_ROOT, a)).mtimeMs
|
||||
const bMtime = fs.statSync(path.join(RELEASE_ROOT, b)).mtimeMs
|
||||
return bMtime - aMtime
|
||||
})
|
||||
return candidates.length > 0 ? path.join(RELEASE_ROOT, candidates[0]) : null
|
||||
}
|
||||
|
||||
function ensureDmg() {
|
||||
if (PLATFORM !== 'darwin') {
|
||||
die('DMG mode is macOS-only; on Windows use the `nsis` mode instead.')
|
||||
}
|
||||
if (process.env.HERMES_DESKTOP_SKIP_BUILD === '1' && exists(resolveDmgPath())) {
|
||||
return
|
||||
}
|
||||
|
||||
run('npm', ['run', 'dist:mac:dmg'])
|
||||
}
|
||||
|
||||
function ensureNsis() {
|
||||
if (PLATFORM !== 'win32') {
|
||||
die('NSIS mode is win32-only; on macOS use the `dmg` mode instead.')
|
||||
}
|
||||
if (process.env.HERMES_DESKTOP_SKIP_BUILD === '1' && resolveNsisPath()) {
|
||||
return
|
||||
}
|
||||
run('npm', ['run', 'dist:win:nsis'])
|
||||
}
|
||||
|
||||
function openApp() {
|
||||
if (!exists(APP_PATH)) {
|
||||
die(`Missing packaged app: ${APP_PATH}`)
|
||||
if (!exists(APP.binary)) {
|
||||
die(`Missing packaged app: ${APP.binary}`)
|
||||
}
|
||||
|
||||
run('open', ['-n', APP_PATH])
|
||||
if (PLATFORM === 'darwin') {
|
||||
run('open', ['-n', APP.appPath])
|
||||
} else if (PLATFORM === 'win32') {
|
||||
// Spawn detached so the test script exits while the app keeps running.
|
||||
spawn(APP.binary, [], { detached: true, stdio: 'ignore' }).unref()
|
||||
} else {
|
||||
spawn(APP.binary, [], { detached: true, stdio: 'ignore' }).unref()
|
||||
}
|
||||
}
|
||||
|
||||
function openDmg() {
|
||||
if (PLATFORM !== 'darwin') {
|
||||
die('DMG mode is macOS-only.')
|
||||
}
|
||||
const dmgPath = resolveDmgPath()
|
||||
if (!exists(dmgPath)) {
|
||||
die(`Missing DMG: ${dmgPath}`)
|
||||
}
|
||||
|
||||
run('open', [dmgPath])
|
||||
}
|
||||
|
||||
@@ -145,13 +230,8 @@ function isCredentialEnvVar(name) {
|
||||
}
|
||||
|
||||
function launchFresh() {
|
||||
if (!exists(APP_BIN)) {
|
||||
die(`Missing app executable: ${APP_BIN}`)
|
||||
}
|
||||
|
||||
const python = output('which', ['python3'])
|
||||
if (!python) {
|
||||
die('python3 is required for fresh bundled-runtime bootstrap.')
|
||||
if (!exists(APP.binary)) {
|
||||
die(`Missing app executable: ${APP.binary}`)
|
||||
}
|
||||
|
||||
const sandbox = fs.mkdtempSync(`${FRESH_SANDBOX_ROOT}-`)
|
||||
@@ -164,9 +244,6 @@ function launchFresh() {
|
||||
fs.mkdirSync(cwd, { recursive: true })
|
||||
|
||||
// Strip every credential-shaped env var so the sandbox is actually fresh.
|
||||
// Without this, shell-set OPENAI_API_KEY/OPENAI_BASE_URL/etc. leak into the
|
||||
// packaged backend, making setup.status report "configured" while the
|
||||
// agent's own credential resolution still fails.
|
||||
const env = {}
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (isCredentialEnvVar(key)) continue
|
||||
@@ -181,7 +258,7 @@ function launchFresh() {
|
||||
delete env.HERMES_DESKTOP_HERMES
|
||||
delete env.HERMES_DESKTOP_HERMES_ROOT
|
||||
|
||||
const child = spawn(APP_BIN, [], {
|
||||
const child = spawn(APP.binary, [], {
|
||||
cwd: os.homedir(),
|
||||
detached: true,
|
||||
env,
|
||||
@@ -198,74 +275,143 @@ function launchFresh() {
|
||||
return { runtimeRoot: path.join(hermesHome, 'hermes-agent', 'venv') }
|
||||
}
|
||||
|
||||
// Validate the packaged bundle matches the thin-installer architecture:
|
||||
// - The Hermes Agent Python payload is NOT shipped (it's fetched at first
|
||||
// launch via install.ps1's stage protocol).
|
||||
// - install-stamp.json IS shipped in resources/ with a valid commit + branch.
|
||||
// - native-deps/@homebridge/node-pty-prebuilt-multiarch/ IS shipped with
|
||||
// the package.json + lib/ + at least one .node binary (the renderer's
|
||||
// integrated terminal needs this; see Phase 1F.6).
|
||||
// - The renderer's dist/index.html is reachable (either unpacked or
|
||||
// inside app.asar).
|
||||
function validateBundle() {
|
||||
const appAsar = path.join(APP_PATH, 'Contents', 'Resources', 'app.asar')
|
||||
const unpackedIndex = path.join(APP_PATH, 'Contents', 'Resources', 'app.asar.unpacked', 'dist', 'index.html')
|
||||
const required = [
|
||||
APP_BIN,
|
||||
path.join(APP_PATH, 'Contents', 'Resources', 'hermes-agent', 'hermes_cli', 'main.py')
|
||||
]
|
||||
|
||||
for (const target of required) {
|
||||
if (!exists(target)) {
|
||||
die(`Missing packaged payload file: ${target}`)
|
||||
}
|
||||
if (!exists(APP.binary)) {
|
||||
die(`Missing packaged app binary: ${APP.binary}`)
|
||||
}
|
||||
|
||||
if (exists(unpackedIndex)) {
|
||||
return
|
||||
// Negative assertion: the OLD fat-installer factory payload must NOT be
|
||||
// present anymore. If a stray ship of hermes_cli sneaks back in we want
|
||||
// to fail loudly rather than re-introduce the 400MB delta we just removed.
|
||||
const staleFactoryMarker = path.join(APP.resourcesPath, 'hermes-agent', 'hermes_cli', 'main.py')
|
||||
if (exists(staleFactoryMarker)) {
|
||||
die(
|
||||
`Thin-installer regression: factory-payload file should NOT be in the package: ${staleFactoryMarker}`
|
||||
)
|
||||
}
|
||||
|
||||
if (!exists(appAsar)) {
|
||||
die(`Missing renderer payload: neither ${unpackedIndex} nor ${appAsar} exists`)
|
||||
// Positive assertion: install-stamp.json carries a sane commit + branch
|
||||
const stampPath = path.join(APP.resourcesPath, 'install-stamp.json')
|
||||
if (!exists(stampPath)) {
|
||||
die(`Missing install-stamp.json (required for first-launch bootstrap pinning): ${stampPath}`)
|
||||
}
|
||||
let stamp
|
||||
try {
|
||||
stamp = JSON.parse(fs.readFileSync(stampPath, 'utf8'))
|
||||
} catch (err) {
|
||||
die(`install-stamp.json is not valid JSON: ${err.message}`)
|
||||
}
|
||||
if (!stamp.commit || typeof stamp.commit !== 'string' || stamp.commit.length < 7) {
|
||||
die(`install-stamp.json is missing a usable commit field: ${JSON.stringify(stamp)}`)
|
||||
}
|
||||
if (!stamp.branch || typeof stamp.branch !== 'string') {
|
||||
die(`install-stamp.json is missing the branch field: ${JSON.stringify(stamp)}`)
|
||||
}
|
||||
|
||||
const files = listPackage(appAsar)
|
||||
if (!files.includes('/dist/index.html') && !files.includes('dist/index.html')) {
|
||||
die(`Missing renderer payload file in app.asar: ${appAsar} (expected dist/index.html)`)
|
||||
// Positive assertion: node-pty native deps shipped
|
||||
const native = expectedNativeDepPaths()
|
||||
if (!exists(native.packageJson)) {
|
||||
die(`Missing node-pty package.json in resources/native-deps: ${native.packageJson}`)
|
||||
}
|
||||
if (!exists(native.libIndex)) {
|
||||
die(`Missing node-pty lib/index.js in resources/native-deps: ${native.libIndex}`)
|
||||
}
|
||||
if (!exists(native.releaseDir)) {
|
||||
die(`Missing node-pty build/Release directory: ${native.releaseDir}`)
|
||||
}
|
||||
const nodeBinaries = fs.readdirSync(native.releaseDir).filter(name => name.endsWith('.node'))
|
||||
if (nodeBinaries.length === 0) {
|
||||
die(`No .node native binaries found in: ${native.releaseDir}`)
|
||||
}
|
||||
|
||||
// Renderer payload check (either unpacked or in the asar)
|
||||
if (exists(APP.unpackedDistIndex)) {
|
||||
return { stamp, nodeBinaries }
|
||||
}
|
||||
if (!exists(APP.asarPath)) {
|
||||
die(`Missing renderer payload: neither ${APP.unpackedDistIndex} nor ${APP.asarPath} exists`)
|
||||
}
|
||||
const files = listPackage(APP.asarPath)
|
||||
// Normalize separators because @electron/asar's listPackage returns
|
||||
// backslash-prefixed entries on Windows ('\\dist\\index.html') and
|
||||
// forward-slash on Unix.
|
||||
const normalized = files.map(f => f.replace(/\\/g, '/').replace(/^\/+/, ''))
|
||||
if (!normalized.includes('dist/index.html')) {
|
||||
die(`Missing renderer payload file in app.asar: ${APP.asarPath} (expected dist/index.html)`)
|
||||
}
|
||||
return { stamp, nodeBinaries }
|
||||
}
|
||||
|
||||
function printArtifacts(options = {}) {
|
||||
const runtimeRoot = options.runtimeRoot || VENV_ROOT
|
||||
const stamp = options.stamp
|
||||
|
||||
console.log('\nDesktop artifacts:')
|
||||
console.log(` app: ${APP_PATH}`)
|
||||
console.log(` dmg: ${resolveDmgPath()}`)
|
||||
console.log(` app: ${APP.appPath}`)
|
||||
if (PLATFORM === 'darwin') {
|
||||
console.log(` dmg: ${resolveDmgPath()}`)
|
||||
} else if (PLATFORM === 'win32') {
|
||||
const exe = resolveNsisPath()
|
||||
if (exe) console.log(` installer: ${exe}`)
|
||||
}
|
||||
console.log(` runtime: ${runtimeRoot}`)
|
||||
if (stamp) {
|
||||
console.log(` install-stamp: ${stamp.commit.slice(0, 12)} on ${stamp.branch}`)
|
||||
}
|
||||
if (options.nodeBinaries && options.nodeBinaries.length > 0) {
|
||||
console.log(` node-pty binaries: ${options.nodeBinaries.join(', ')}`)
|
||||
}
|
||||
}
|
||||
|
||||
function help() {
|
||||
console.log(`Usage:
|
||||
npm run test:desktop:existing # build packaged app, launch with normal PATH/existing Hermes
|
||||
npm run test:desktop:fresh # build packaged app, launch with temp userData + HERMES_HOME
|
||||
npm run test:desktop:dmg # build DMG and open it
|
||||
npm run test:desktop:all # build DMG, validate app payload, print paths
|
||||
npm run test:desktop:dmg # (macOS only) build DMG and open it
|
||||
npm run test:desktop:nsis # (win32 only) build NSIS installer
|
||||
npm run test:desktop:all # build installer, validate app payload, print paths
|
||||
|
||||
Fast rerun:
|
||||
Fast rerun (skip rebuild if the packaged app already exists):
|
||||
HERMES_DESKTOP_SKIP_BUILD=1 npm run test:desktop:fresh
|
||||
`)
|
||||
}
|
||||
|
||||
ensureMac()
|
||||
ensurePlatformBuilds()
|
||||
|
||||
if (MODE === 'existing') {
|
||||
ensurePackagedApp()
|
||||
validateBundle()
|
||||
const result = validateBundle()
|
||||
openApp()
|
||||
printArtifacts()
|
||||
printArtifacts(result)
|
||||
} else if (MODE === 'fresh') {
|
||||
ensurePackagedApp()
|
||||
validateBundle()
|
||||
printArtifacts(launchFresh())
|
||||
const result = validateBundle()
|
||||
printArtifacts({ ...launchFresh(), ...result })
|
||||
} else if (MODE === 'dmg') {
|
||||
ensureDmg()
|
||||
openDmg()
|
||||
printArtifacts()
|
||||
} else if (MODE === 'nsis') {
|
||||
ensureNsis()
|
||||
printArtifacts(validateBundle())
|
||||
} else if (MODE === 'all') {
|
||||
ensureDmg()
|
||||
validateBundle()
|
||||
printArtifacts()
|
||||
if (PLATFORM === 'darwin') {
|
||||
ensureDmg()
|
||||
} else if (PLATFORM === 'win32') {
|
||||
ensureNsis()
|
||||
} else {
|
||||
ensurePackagedApp()
|
||||
}
|
||||
printArtifacts(validateBundle())
|
||||
} else {
|
||||
help()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
"use strict"
|
||||
|
||||
/**
|
||||
* Writes apps/desktop/build/install-stamp.json with the git ref the desktop
|
||||
* .exe should pin to at first-launch bootstrap time. This file ships inside
|
||||
* the packaged app via electron-builder's extraResources entry and is read
|
||||
* by electron/main.cjs to drive the install.ps1 stage bootstrap flow.
|
||||
*
|
||||
* Schema (subject to bump via STAMP_SCHEMA_VERSION):
|
||||
* {
|
||||
* "schemaVersion": 1,
|
||||
* "commit": "<40-char SHA>",
|
||||
* "branch": "<branch name>",
|
||||
* "builtAt": "<ISO 8601 UTC timestamp>",
|
||||
* "dirty": true|false,
|
||||
* "source": "ci" | "local"
|
||||
* }
|
||||
*
|
||||
* Source preference order:
|
||||
* 1. CI env vars ($GITHUB_SHA / $GITHUB_REF_NAME) -- avoid edge cases with
|
||||
* shallow clones, detached HEADs, etc. in CI.
|
||||
* 2. Local `git rev-parse` against the parent repo (../..).
|
||||
*
|
||||
* Dev / out-of-repo builds without git produce an explicit error rather than
|
||||
* silently writing an unstamped manifest -- the packaged app refuses to
|
||||
* bootstrap without a stamp.
|
||||
*/
|
||||
|
||||
const fs = require("fs")
|
||||
const path = require("path")
|
||||
const { execSync } = require("child_process")
|
||||
|
||||
const STAMP_SCHEMA_VERSION = 1
|
||||
|
||||
const DESKTOP_ROOT = path.resolve(__dirname, "..")
|
||||
const REPO_ROOT = path.resolve(DESKTOP_ROOT, "..", "..")
|
||||
const OUT_DIR = path.join(DESKTOP_ROOT, "build")
|
||||
const OUT_FILE = path.join(OUT_DIR, "install-stamp.json")
|
||||
|
||||
function tryExec(cmd, opts) {
|
||||
try {
|
||||
return execSync(cmd, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], ...opts }).trim()
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function fromCI() {
|
||||
const sha = process.env.GITHUB_SHA
|
||||
if (!sha) return null
|
||||
const branch = process.env.GITHUB_REF_NAME || process.env.GITHUB_HEAD_REF || null
|
||||
return {
|
||||
commit: sha,
|
||||
branch: branch,
|
||||
dirty: false, // CI builds from a checkout-of-ref by definition
|
||||
source: "ci"
|
||||
}
|
||||
}
|
||||
|
||||
function fromLocalGit() {
|
||||
const sha = tryExec("git rev-parse HEAD", { cwd: REPO_ROOT })
|
||||
if (!sha) return null
|
||||
const branch = tryExec("git rev-parse --abbrev-ref HEAD", { cwd: REPO_ROOT })
|
||||
// `git status --porcelain -uno` is empty iff tracked files match HEAD.
|
||||
// We exclude untracked files (-uno) intentionally: a developer who's
|
||||
// checked out an installer scratch dir alongside the repo shouldn't
|
||||
// poison every local build with a [DIRTY] stamp. We DO care about
|
||||
// tracked-but-modified files because those mean the .exe content
|
||||
// differs from the commit being pinned.
|
||||
const status = tryExec("git status --porcelain -uno", { cwd: REPO_ROOT })
|
||||
const dirty = status !== null && status.length > 0
|
||||
return {
|
||||
commit: sha,
|
||||
branch: branch === "HEAD" ? null : branch, // detached HEAD -> null
|
||||
dirty: dirty,
|
||||
source: "local"
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const stamp = fromCI() || fromLocalGit()
|
||||
if (!stamp || !stamp.commit) {
|
||||
console.error(
|
||||
"[write-build-stamp] ERROR: could not determine git commit.\n" +
|
||||
" - $GITHUB_SHA not set\n" +
|
||||
" - `git rev-parse HEAD` failed at " +
|
||||
REPO_ROOT +
|
||||
"\n" +
|
||||
"Packaged builds require a git ref to pin first-launch install.ps1\n" +
|
||||
"against. Run from a git checkout or set $GITHUB_SHA explicitly."
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (stamp.dirty) {
|
||||
console.warn(
|
||||
"[write-build-stamp] WARNING: working tree is dirty.\n" +
|
||||
" Pinning to " +
|
||||
stamp.commit.slice(0, 12) +
|
||||
" but the packaged code may differ from that commit.\n" +
|
||||
" Commit your changes before publishing this build."
|
||||
)
|
||||
}
|
||||
|
||||
const payload = {
|
||||
schemaVersion: STAMP_SCHEMA_VERSION,
|
||||
commit: stamp.commit,
|
||||
branch: stamp.branch,
|
||||
builtAt: new Date().toISOString(),
|
||||
dirty: stamp.dirty,
|
||||
source: stamp.source
|
||||
}
|
||||
|
||||
fs.mkdirSync(OUT_DIR, { recursive: true })
|
||||
fs.writeFileSync(OUT_FILE, JSON.stringify(payload, null, 2) + "\n", "utf8")
|
||||
console.log(
|
||||
"[write-build-stamp] wrote " +
|
||||
path.relative(REPO_ROOT, OUT_FILE) +
|
||||
" -> " +
|
||||
stamp.commit.slice(0, 12) +
|
||||
(stamp.branch ? " (" + stamp.branch + ")" : "") +
|
||||
(stamp.dirty ? " [DIRTY]" : "")
|
||||
)
|
||||
}
|
||||
|
||||
main()
|
||||
Reference in New Issue
Block a user