Skip to content

The agent that grows with you

perf(desktop): reduce Windows startup I/O and blocking checks

Jibin Rajan Varghesedb63214c7b95
diff --git a/apps/desktop/electron/renderer-bundle.ts b/apps/desktop/electron/renderer-bundle.ts
index 03aed2ce21b..6b87bc52de6 100644
--- a/apps/desktop/electron/renderer-bundle.ts
+++ b/apps/desktop/electron/renderer-bundle.ts
@@ -74,6 +74,61 @@ export interface RendererBundleDeps {
existsSync?: (file: string) => boolean
}
+/** Vite's build-time graph avoids opening megabytes of lazy chunks at startup.
+ * Only trust a manifest paired with this index's entry and preload generation.
+ * Old builds, malformed manifests and interrupted replacements retain the
+ * existing JS graph walk below; a manifest is never an existence-only bypass.
+ */
+function manifestAssetRefs(
+ indexPath: string,
+ bootRefs: string[],
+ readFileSync: NonNullable<RendererBundleDeps['readFileSync']>
+): string[] | null {
+ try {
+ const manifest = JSON.parse(readFileSync(path.join(path.dirname(indexPath), 'renderer-manifest.json'), 'utf8'))
+
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {return null}
+
+ const entry = manifest['index.html']
+ const normalize = (ref: string) => ref.replace(/^\.?\//, '')
+
+ if (!entry?.isEntry || !bootRefs.map(normalize).includes(entry.file)) {return null}
+
+ const refs = new Set<string>()
+
+ const localRef = (ref: unknown): ref is string =>
+ typeof ref === 'string' && ref.length > 0 && !/^[a-z]+:|^[/\\]/i.test(ref) && !ref.split(/[/\\]/).includes('..')
+
+ for (const chunk of Object.values(manifest) as Record<string, unknown>[]) {
+ if (!chunk || typeof chunk !== 'object' || !localRef(chunk.file)) {return null}
+
+ refs.add(chunk.file)
+
+ for (const key of ['imports', 'dynamicImports']) {
+ const imports = chunk[key] ?? []
+
+ if (!Array.isArray(imports) || !imports.every(ref => typeof ref === 'string' && Object.hasOwn(manifest, ref))) {
+ return null
+ }
+ }
+
+ for (const key of ['css', 'assets']) {
+ const assets = chunk[key] ?? []
+
+ if (!Array.isArray(assets) || !assets.every(localRef)) {return null}
+
+ for (const ref of assets) {refs.add(ref)}
+ }
+ }
+
+ if (!bootRefs.every(ref => refs.has(normalize(ref)))) {return null}
+
+ return [...refs]
+ } catch {
+ return null
+ }
+}
+
/**
* The module files `indexPath`'s generation declares but that do not exist
* beside it — both the boot-critical refs named by index.html itself AND the
@@ -100,9 +155,16 @@ export function missingRendererAssets(indexPath: string, deps: RendererBundleDep
return []
}
+ const bootRefs = parseModuleAssetRefs(html)
+ const manifestRefs = manifestAssetRefs(indexPath, bootRefs, readFileSync)
+
+ if (manifestRefs !== null) {
+ return manifestRefs.filter(ref => !existsSync(path.join(dir, ref)))
+ }
+
const missing: string[] = []
const seen = new Set<string>()
- const queue = [...parseModuleAssetRefs(html)]
+ const queue = [...bootRefs]
while (queue.length > 0) {
const ref = queue.shift()!
diff --git a/apps/desktop/electron/renderer-manifest.test.ts b/apps/desktop/electron/renderer-manifest.test.ts
new file mode 100644
index 00000000000..92abf8c353f
--- /dev/null
+++ b/apps/desktop/electron/renderer-manifest.test.ts
@@ -0,0 +1,58 @@
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { test } from 'vitest'
+
+import { missingRendererAssets } from './renderer-bundle'
+
+test('Vite manifest validates lazy assets without opening their JavaScript', async () => {
+ const { build } = await import('vite')
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-renderer-manifest-'))
+
+ try {
+ fs.writeFileSync(path.join(root, 'index.html'), '<script type="module" src="/main.js"></script>')
+ fs.writeFileSync(path.join(root, 'main.js'), 'globalThis.loadFeature = () => import("./lazy.js")')
+ fs.writeFileSync(path.join(root, 'lazy.js'), 'export const feature = 42')
+ await build({ root, configFile: false, logLevel: 'silent', build: { manifest: 'renderer-manifest.json' } })
+ const dist = path.join(root, 'dist')
+ const index = path.join(dist, 'index.html')
+ const manifest = JSON.parse(fs.readFileSync(path.join(dist, 'renderer-manifest.json'), 'utf8'))
+ const reads: string[] = []
+
+ const deps = {
+ readFileSync(file: string, encoding: 'utf8') {
+ reads.push(file)
+
+ return fs.readFileSync(file, encoding)
+ }
+ }
+
+ assert.deepEqual(missingRendererAssets(index, deps), [])
+ assert.equal(reads.filter(file => /\.m?js$/.test(file)).length, 0)
+ fs.unlinkSync(path.join(dist, manifest['lazy.js'].file))
+ assert.deepEqual(missingRendererAssets(index, deps), [manifest['lazy.js'].file])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('a manifest from another generation falls back to the existing lazy graph check', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-renderer-stale-'))
+
+ try {
+ fs.mkdirSync(path.join(root, 'assets'))
+ fs.writeFileSync(path.join(root, 'index.html'), '<script type="module" src="assets/new.js"></script>')
+ fs.writeFileSync(path.join(root, 'assets/new.js'), 'const __vite__mapDeps = i => ["assets/missing.js"]')
+ fs.writeFileSync(
+ path.join(root, 'renderer-manifest.json'),
+ JSON.stringify({
+ 'index.html': { file: 'assets/old.js', isEntry: true }
+ })
+ )
+ assert.deepEqual(missingRendererAssets(path.join(root, 'index.html')), ['assets/missing.js'])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts
index 28ca0d797ab..393e0bc0c8a 100644
--- a/apps/desktop/vite.config.ts
+++ b/apps/desktop/vite.config.ts
@@ -129,6 +129,9 @@ export default defineConfig(({ command }) => ({
postcss: { plugins: [] }
},
build: {
+ // Validate the packaged generation with metadata checks at launch, without
+ // reading every lazy vendor chunk (and triggering on-access AV scans).
+ manifest: 'renderer-manifest.json',
// The renderer intentionally ships FEW chunks (not one, not thousands):
// · `codeSplitting: false` (the old setup) inlines every `lazy()` /
// dynamic import into the entry, so heavyweight lazy-only deps
diff --git a/hermes_cli/desktop_console.py b/hermes_cli/desktop_console.py
new file mode 100644
index 00000000000..5af13ea5261
--- /dev/null
+++ b/hermes_cli/desktop_console.py
@@ -0,0 +1,49 @@
+"""Keep Windows console backpressure off the packaged desktop startup path."""
+
+import logging
+import os
+import sys
+import threading
+from contextlib import contextmanager
+
+logger = logging.getLogger("hermes_cli.desktop")
+
+
+def desktop_launch_notice(message: str, *, source_mode: bool = False) -> None:
+ if sys.platform == "win32" and not source_mode:
+ # setup_logging() uses an async queue and rotating, redacted files.
+ logger.info(message)
+ else:
+ print(message)
+
+
+@contextmanager
+def desktop_console_output(*, source_mode: bool):
+ """Drain packaged Windows stdout/stderr into the existing rotating logs.
+
+ Inheriting the console lets an unresponsive console host/profiler block
+ Electron's synchronous startup messages before it can create a window.
+ Keep source launches interactive and preserve subprocess.run's lifecycle
+ and exit-code handling. Read bounded lines so output cannot grow a buffer
+ without limit, and never wait indefinitely on a descendant's open pipe.
+ """
+ if sys.platform != "win32" or source_mode:
+ yield {}
+ return
+
+ import subprocess
+
+ read_fd, write_fd = os.pipe()
+
+ def drain():
+ with os.fdopen(read_fd, "rb") as stream:
+ while data := stream.readline(8192):
+ logger.info("[desktop] %s", data.decode("utf-8", errors="replace").rstrip())
+
+ reader = threading.Thread(target=drain, name="desktop-console", daemon=True)
+ reader.start()
+ try:
+ yield {"stdout": write_fd, "stderr": subprocess.STDOUT}
+ finally:
+ os.close(write_fd)
+ reader.join(timeout=1)
diff --git a/hermes_cli/desktop_source_cache.py b/hermes_cli/desktop_source_cache.py
new file mode 100644
index 00000000000..0413487f68d
--- /dev/null
+++ b/hermes_cli/desktop_source_cache.py
@@ -0,0 +1,111 @@
+"""Reuse the desktop content hash while all source metadata is unchanged.
+
+This is a build-freshness cache, not an integrity/security check. Normal launches
+must not read thousands of source/test files (and trigger on-access AV scans).
+Changed metadata always falls back to the existing content hash, so checkout
+mtime churn alone still does not force a rebuild.
+"""
+
+import ctypes
+import contextlib
+import hashlib
+import json
+import os
+import tempfile
+from functools import lru_cache
+from pathlib import Path
+from typing import Callable
+
+
+@lru_cache(maxsize=1)
+def _windows_file_api():
+ from ctypes import wintypes
+
+ class FileBasicInfo(ctypes.Structure):
+ _fields_ = [(name, ctypes.c_longlong) for name in (
+ "creation", "access", "write", "change"
+ )] + [("attributes", wintypes.DWORD)]
+
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
+ ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
+ kernel.CreateFileW.restype = wintypes.HANDLE
+ kernel.GetFileInformationByHandleEx.argtypes = [wintypes.HANDLE, ctypes.c_int,
+ ctypes.c_void_p, wintypes.DWORD]
+ kernel.GetFileInformationByHandleEx.restype = wintypes.BOOL
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel.CloseHandle.restype = wintypes.BOOL
+ return kernel, FileBasicInfo
+
+
+def _change_time(path: Path, st: os.stat_result) -> int:
+ if os.name != "nt":
+ return st.st_ctime_ns
+ # Windows stat().st_ctime is CREATION time on supported Python versions.
+ # FILE_BASIC_INFO.ChangeTime also catches same-size edits with restored mtime.
+ # Request metadata only: never FILE_READ_DATA or a read of source contents.
+ kernel, info_type = _windows_file_api()
+ handle = kernel.CreateFileW(str(path), 0x80, 7, None, 3, 0x02000000, None)
+ if handle == ctypes.c_void_p(-1).value:
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ info = info_type()
+ if not kernel.GetFileInformationByHandleEx(handle, 0, ctypes.byref(info), ctypes.sizeof(info)):
+ raise ctypes.WinError(ctypes.get_last_error())
+ return info.change
+ finally:
+ kernel.CloseHandle(handle)
+
+
+def _source_metadata(project_root: Path, tree_dir: Path) -> str:
+ from hermes_cli.main_web_build import _source_tree_files
+
+ digest = hashlib.sha256()
+ for path in _source_tree_files(project_root, tree_dir):
+ st = path.stat()
+ record = (str(path.relative_to(project_root)), st.st_dev, st.st_ino,
+ st.st_size, st.st_mtime_ns, _change_time(path, st))
+ digest.update(json.dumps(record, ensure_ascii=True).encode())
+ digest.update(b"\0")
+ return digest.hexdigest()
+
+
+def cached_desktop_source_hash(project_root: Path, compute: Callable[[], str]) -> str:
+ from hermes_constants import get_hermes_home
+
+ tree_dir = project_root / "apps" / "desktop"
+ cache_file = get_hermes_home() / "desktop-source-cache.json"
+ scope = str(project_root.resolve())
+ try:
+ before = _source_metadata(project_root, tree_dir)
+ except OSError:
+ return compute() # Metadata unavailable: keep the full content check.
+ try:
+ cache = json.loads(cache_file.read_text(encoding="utf-8"))
+ if (isinstance(cache, dict) and cache.get("version") == 1
+ and cache.get("root") == scope and cache.get("metadata") == before
+ and isinstance(cache.get("contentHash"), str) and len(cache["contentHash"]) == 64):
+ return cache["contentHash"]
+ except (OSError, ValueError):
+ pass
+
+ content_hash = compute()
+ temporary = None
+ try:
+ # Do not cache a digest if an editor/update changed inputs while we read.
+ if before != _source_metadata(project_root, tree_dir):
+ return content_hash
+ cache_file.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=cache_file.parent,
+ prefix=".desktop-source-", delete=False) as stream:
+ temporary = Path(stream.name)
+ json.dump({"version": 1, "root": scope, "metadata": before,
+ "contentHash": content_hash}, stream)
+ temporary.replace(cache_file)
+ except OSError:
+ pass # Read-only cache locations must not prevent building/launching.
+ finally:
+ if temporary is not None:
+ with contextlib.suppress(OSError):
+ temporary.unlink(missing_ok=True)
+ return content_hash
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index da048c18425..e690badcf54 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -1909,17 +1909,34 @@ _WINDOWS_TASK_SUPERVISOR_STATES = frozenset({"Running", "Ready", "Queued"})
def _windows_scheduled_task_state(task_name: str) -> str | None:
- """English ``Get-ScheduledTask`` State, or None on failure. PowerShell, not ``schtasks``: schtasks
- localizes its output in the local codepage (utf-8 decoding mangles it); the State enum is stable."""
+ """Locale-independent Task Scheduler state, or None on failure.
+
+ Query the COM API directly: Get-ScheduledTask auto-loads the CIM module,
+ which can stall desktop backend startup for the entire ten-second timeout.
+ Keep the existing supervisor semantics (Ready and Queued count as owned).
+ """
if not is_windows():
return None
- ps_cmd = f"$t = Get-ScheduledTask -TaskName '{task_name}' -ErrorAction SilentlyContinue; if ($t) {{ $t.State }} else {{ 'MISSING' }}"
+ quoted_name = task_name.replace("'", "''")
+ ps_cmd = (
+ "$ErrorActionPreference = 'Stop'; "
+ "$s = [Activator]::CreateInstance([type]::GetTypeFromProgID('Schedule.Service')); "
+ "$s.Connect(); "
+ "try { "
+ f"$t = $s.GetFolder('\\').GetTask('{quoted_name}'); "
+ # TASK_STATE values are stable, unlike localized schtasks.exe output.
+ "@('Unknown', 'Disabled', 'Queued', 'Ready', 'Running')[[int]$t.State] "
+ "} catch { "
+ "$e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; "
+ "if ($e.HResult -in @(-2147024894, -2147024893)) { 'MISSING' } else { throw } "
+ "}"
+ )
try:
powershell = shutil.which("powershell") or shutil.which("pwsh")
if powershell is None:
return None
result = subprocess.run(
- [powershell, "-NoProfile", "-Command", ps_cmd],
+ [powershell, "-NoProfile", "-NonInteractive", "-Command", ps_cmd],
capture_output=True, text=True, encoding="utf-8", errors="ignore", timeout=10,
)
if result.returncode != 0:
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index 48aa89633fd..670e24cc702 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -19,6 +19,7 @@ import time as _time_mod
from pathlib import Path
from typing import Optional
+from hermes_cli.desktop_console import desktop_console_output, desktop_launch_notice
from hermes_cli.main_tui_launch import _npm_lifecycle_env
from hermes_cli.main_web_build import (
_hash_source_tree, _nixos_build_env, _stamp_is_current, _write_build_stamp)
@@ -36,7 +37,9 @@ def _desktop_dist_exists(desktop_dir: Path) -> bool:
def _compute_desktop_content_hash(project_root: Path) -> str:
"""SHA-256 of ``apps/desktop/`` (minus .gitignore matches) plus root workspace config."""
- return _hash_source_tree(project_root, project_root / "apps" / "desktop")
+ from hermes_cli.desktop_source_cache import cached_desktop_source_hash
+ return cached_desktop_source_hash(
+ project_root, lambda: _hash_source_tree(project_root, project_root / "apps" / "desktop"))
def _desktop_stamp_path() -> Path:
@@ -1490,7 +1493,7 @@ def _check_desktop_skip_build(
print(" Or drop --skip-build to package automatically.")
sys.exit(1)
else:
- print(f"→ Skipping desktop package build (--skip-build); using {packaged_executable}")
+ desktop_launch_notice(f"→ Skipping desktop package build (--skip-build); using {packaged_executable}")
def _packaged_desktop_launch_command(packaged_executable: Path) -> list[str]:
@@ -1534,8 +1537,11 @@ def cmd_gui(args: argparse.Namespace):
packaged_executable = _desktop_packaged_executable(desktop_dir)
+ needs_build = not skip_build and (
+ force_build or _desktop_build_needed(desktop_dir, PROJECT_ROOT, source_mode=source_mode)
+ )
npm = None
- if source_mode or not skip_build:
+ if source_mode or needs_build:
npm = _resolve_node_runtime_npm()
if not npm:
print("Desktop GUI requires Node.js/npm, but npm was not found on PATH.")
@@ -1546,14 +1552,14 @@ def cmd_gui(args: argparse.Namespace):
_check_desktop_skip_build(
desktop_dir, PROJECT_ROOT, source_mode=source_mode, packaged_executable=packaged_executable
)
- elif force_build or _desktop_build_needed(desktop_dir, PROJECT_ROOT, source_mode=source_mode):
+ elif needs_build:
# --force-build overrides the content-hash stamp and always rebuilds.
built = _build_desktop_app(desktop_dir, source_mode=source_mode, npm=npm, env=env)
if not source_mode:
packaged_executable = built
else:
build_label = "source build" if source_mode else "packaged app"
- print(f"✓ Desktop {build_label} is up to date (content stamp matches)")
+ desktop_launch_notice(f"✓ Desktop {build_label} is up to date (content stamp matches)", source_mode=source_mode)
# Best-effort and idempotent; a failure must never stop the app from launching.
# An app-grid launch (DESKTOP_STARTUP_ID) must not write its own entry while the
@@ -1595,12 +1601,15 @@ def cmd_gui(args: argparse.Namespace):
if getattr(args, "local", False):
launch_command.append("--local")
if not source_mode:
- print(f"→ Launching packaged Hermes Desktop: {' '.join(launch_command)}")
+ desktop_launch_notice(f"→ Launching packaged Hermes Desktop: {' '.join(launch_command)}")
pass_fds: tuple[int, ...] = ()
if deferred_entry is not None:
env = deferred_entry.child_env(env)
pass_fds = deferred_entry.pass_fds
- launch_result = subprocess.run(launch_command, cwd=desktop_dir, env=env, check=False, pass_fds=pass_fds)
+ with desktop_console_output(source_mode=source_mode) as streams:
+ launch_result = subprocess.run(
+ launch_command, cwd=desktop_dir, env=env, check=False, pass_fds=pass_fds, **streams
+ )
if deferred_entry is not None:
deferred_entry.finish()
sys.exit(launch_result.returncode)
diff --git a/hermes_cli/main_web_build.py b/hermes_cli/main_web_build.py
index 41cdbdad2c8..f5b77ce99ed 100644
--- a/hermes_cli/main_web_build.py
+++ b/hermes_cli/main_web_build.py
@@ -90,44 +90,42 @@ def _web_dist_dir(web_dir: Path) -> Path:
return _web_project_root(web_dir) / "hermes_cli" / "web_dist"
-def _hash_source_tree(project_root: Path, tree_dir: Path) -> str:
- """SHA-256 over *tree_dir* plus the root ``package.json`` / ``package-lock.json``.
-
- Ignored paths (``node_modules/``, ``dist/``, ``*.pyc``, ...) are skipped via
- the repo-root ``.gitignore`` (pathspec) so build output never feeds back into
- its own staleness check. Filenames are sorted for a deterministic digest.
- """
- h = hashlib.sha256()
-
- def _hash_file(path: Path) -> None:
- h.update(str(path.relative_to(project_root)).encode())
- h.update(b"\0")
- with contextlib.suppress(OSError):
- with open(path, "rb") as f:
- for chunk in iter(lambda: f.read(65536), b""):
- h.update(chunk)
- h.update(b"\0")
-
+def _source_tree_files(project_root: Path, tree_dir: Path):
+ """Build inputs, in the same order for content hashing and metadata validation."""
from pathspec import PathSpec
gitignore = project_root / ".gitignore"
lines = gitignore.read_text(encoding="utf-8").splitlines() if gitignore.is_file() else []
spec = PathSpec.from_lines("gitignore", lines)
- def _ignored(path: Path) -> bool:
- return spec.match_file(str(path.relative_to(project_root)))
+ def _ignored(path: Path, *, directory: bool = False) -> bool:
+ relative = path.relative_to(project_root).as_posix()
+ return spec.match_file(relative + "/" if directory else relative)
for name in ("package.json", "package-lock.json"):
p = project_root / name
if p.is_file() and not _ignored(p):
- _hash_file(p)
+ yield p
# Prune ignored directories in place so we never descend into them.
for dirpath, dirnames, filenames in os.walk(tree_dir, topdown=True):
- dirnames[:] = [d for d in dirnames if not _ignored(Path(dirpath) / d)]
+ dirnames[:] = [d for d in dirnames if not _ignored(Path(dirpath) / d, directory=True)]
for fn in sorted(filenames):
fp = Path(dirpath) / fn
if not _ignored(fp):
- _hash_file(fp)
+ yield fp
+
+
+def _hash_source_tree(project_root: Path, tree_dir: Path) -> str:
+ """SHA-256 over the source tree and workspace manifests, pruning .gitignore matches."""
+ h = hashlib.sha256()
+ for path in _source_tree_files(project_root, tree_dir):
+ h.update(str(path.relative_to(project_root)).encode())
+ h.update(b"\0")
+ with contextlib.suppress(OSError):
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(65536), b""):
+ h.update(chunk)
+ h.update(b"\0")
return h.hexdigest()
diff --git a/tests/hermes_cli/test_desktop_console.py b/tests/hermes_cli/test_desktop_console.py
new file mode 100644
index 00000000000..0bfa99c1a03
--- /dev/null
+++ b/tests/hermes_cli/test_desktop_console.py
@@ -0,0 +1,35 @@
+"""Real child output must drain even when no interactive console is consuming it."""
+
+import logging
+import subprocess
+import sys
+
+import pytest
+
+from hermes_cli.desktop_console import desktop_console_output, desktop_launch_notice
+
+
+def test_packaged_console_output_drains_both_streams(caplog, monkeypatch):
+ caplog.set_level(logging.INFO, logger="hermes_cli.desktop")
+
+ def blocked_console(*args, **kwargs):
+ raise AssertionError("packaged startup attempted a synchronous console write")
+
+ monkeypatch.setattr("builtins.print", blocked_console)
+ desktop_launch_notice("Starting Hermes")
+ with desktop_console_output(source_mode=False) as streams:
+ result = subprocess.run(
+ [sys.executable, "-c", "import sys; sys.stdout.write('x'*131072); "
+ "sys.stdout.flush(); sys.stderr.write('diagnostic\\n'); sys.exit(7)"],
+ timeout=15, check=False, **streams,
+ )
+ assert result.returncode == 7
+ messages = [record.getMessage() for record in caplog.records]
+ assert sum(message.count("x") for message in messages) == 131072
+ assert any("diagnostic" in message for message in messages)
+
+
+def test_source_launch_keeps_interactive_streams():
+ with desktop_console_output(source_mode=True) as streams:
+ assert streams == {}
diff --git a/tests/hermes_cli/test_desktop_startup_cost.py b/tests/hermes_cli/test_desktop_startup_cost.py
new file mode 100644
index 00000000000..5f038e83b38
--- /dev/null
+++ b/tests/hermes_cli/test_desktop_startup_cost.py
@@ -0,0 +1,86 @@
+"""Startup regressions exercised against real source trees on the current host."""
+
+import argparse
+import builtins
+import os
+import subprocess
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from hermes_cli import main as cli_main
+from hermes_cli import main_desktop as desktop
+
+
+def _tree(tmp_path):
+ root = tmp_path / "checkout"
+ app = root / "apps" / "desktop"
+ app.mkdir(parents=True)
+ (root / ".gitignore").write_text("dist/\nrelease/\nnode_modules/\n")
+ (root / "package.json").write_text("{}")
+ (app / "package.json").write_text("{}")
+ source = app / "app.ts"
+ source.write_text("export const x = 1")
+ return root, app, source
+
+
+def test_unchanged_desktop_hash_does_not_reopen_sources(tmp_path):
+ root, app, source = _tree(tmp_path)
+ ignored = app / "dist"
+ ignored.mkdir()
+ (ignored / "bundle.js").write_text("built output")
+ expected = desktop._compute_desktop_content_hash(root)
+ original_open = builtins.open
+ original_scandir = os.scandir
+ reads = []
+
+ def track(file, *args, **kwargs):
+ if isinstance(file, (str, os.PathLike)) and Path(file) == source:
+ reads.append(file)
+ return original_open(file, *args, **kwargs)
+
+ def scan(directory):
+ assert Path(directory) != ignored, "ignored build output must be pruned before traversal"
+ return original_scandir(directory)
+
+ with patch("builtins.open", side_effect=track), patch("os.scandir", side_effect=scan):
+ assert desktop._compute_desktop_content_hash(root) == expected
+ assert reads == [], "launch should use source metadata, not read every source file again"
+
+
+def test_desktop_hash_invalidates_for_edits_even_with_restored_mtime(tmp_path):
+ root, app, source = _tree(tmp_path)
+ original = desktop._compute_desktop_content_hash(root)
+ stamp = source.stat()
+ source.write_text("export const x = 2") # Same length; editors can preserve mtime.
+ os.utime(source, ns=(stamp.st_atime_ns, stamp.st_mtime_ns))
+ assert desktop._compute_desktop_content_hash(root) != original
+ source.write_text("export const x = 1")
+ assert desktop._compute_desktop_content_hash(root) == original
+ added = app / "new.ts"
+ added.write_text("new module")
+ assert desktop._compute_desktop_content_hash(root) != original
+ added.unlink()
+ assert desktop._compute_desktop_content_hash(root) == original
+ (root / "package.json").write_text('{"changed": true}')
+ assert desktop._compute_desktop_content_hash(root) != original
+
+
+def test_current_packaged_launch_does_not_require_npm(tmp_path, monkeypatch):
+ root, app, _ = _tree(tmp_path)
+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
+ executable = app / "Hermes.exe"
+ args = argparse.Namespace(source=False, skip_build=False, force_build=False, build_only=False)
+ with patch.object(desktop, "_desktop_launch_env", return_value=({}, [])), \
+ patch.object(desktop, "_desktop_packaged_executable", return_value=executable), \
+ patch.object(desktop, "_desktop_build_needed", return_value=False), \
+ patch.object(desktop, "_register_linux_desktop_entry"), \
+ patch.object(desktop, "_packaged_desktop_launch_command", return_value=[str(executable)]), \
+ patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value=None) as npm, \
+ patch.object(desktop.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)) as run, \
+ pytest.raises(SystemExit) as exited:
+ desktop.cmd_gui(args)
+ assert exited.value.code == 0
+ npm.assert_not_called()
+ run.assert_called_once()
diff --git a/tests/hermes_cli/test_gateway_task_probe.py b/tests/hermes_cli/test_gateway_task_probe.py
new file mode 100644
index 00000000000..c0cf2df56e0
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_task_probe.py
@@ -0,0 +1,28 @@
+"""The startup supervisor probe must not load the slow CIM ScheduledTasks module."""
+
+import subprocess
+import uuid
+from unittest.mock import patch
+
+import pytest
+
+from hermes_cli.gateway import _windows_scheduled_task_state
+
+
+def test_task_query_without_powershell_module_autoload():
+ real_run = subprocess.run
+
+ def run_without_modules(command, **kwargs):
+ command = list(command)
+ command[-1] = ("$ErrorActionPreference='Stop'; $PSModuleAutoLoadingPreference='None'; "
+ + command[-1])
+ result = real_run(command, **kwargs)
+ assert result.returncode == 0, result.stderr
+ return result
+
+ # A random absent task exercises real COM/RPC and task-name quoting without
+ # creating, stopping or changing any scheduled task on the developer's host.
+ task_name = "Hermes_test_'" + uuid.uuid4().hex
+ with patch("hermes_cli.gateway.subprocess.run", side_effect=run_without_modules):
+ assert _windows_scheduled_task_state(task_name) == "MISSING"
diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.py
index d0a55a5ff13..529d56c3393 100644
--- a/tests/hermes_cli/test_gui_command.py
+++ b/tests/hermes_cli/test_gui_command.py
@@ -144,12 +144,15 @@ def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):
desktop_dir = root / "apps" / "desktop"
monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
packaged_exe = _make_packaged_executable(root, monkeypatch)
+ # The pack double writes text, not a PE. The real integrity gate has its
+ # own filesystem tests; this test owns build/launch orchestration.
+ monkeypatch.setattr(main_desktop, "_desktop_exe_integrity_error", lambda _: None)
install_ok = subprocess.CompletedProcess(["npm", "ci"], 0)
pack_ok = subprocess.CompletedProcess(["npm", "run", "pack"], 0)
launch_ok = subprocess.CompletedProcess([str(packaged_exe)], 0)
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=install_ok) as mock_install, \
patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \
@@ -314,7 +317,7 @@ def test_gui_does_not_retry_after_packaged_executable_exists(tmp_path, monkeypat
# discriminator reads the staging dir, so the fake pack lays it down there.
pack_fail = _pack_into_staging(root, content="half-signed", returncode=1)
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=install_ok), \
patch("hermes_cli.main_desktop._desktop_macos_relaunchable_fixup"), \
patch("hermes_cli.main_desktop._purge_electron_build_cache", return_value=[Path("/c/electron.zip")]) as mock_purge, \
@@ -1142,11 +1145,12 @@ def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch):
root = _make_desktop_tree(tmp_path)
monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)
_make_packaged_executable(root, monkeypatch)
+ monkeypatch.setattr(main_desktop, "_desktop_exe_integrity_error", lambda _: None)
ok = subprocess.CompletedProcess([], 0)
cfg = {"desktop": {"ozone_platform_hint": "x11"}}
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=ok), \
patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \
@@ -1162,7 +1166,7 @@ def test_gui_bridges_ozone_hint_to_launch_env(tmp_path, monkeypatch):
assert launch_env.get("ELECTRON_OZONE_PLATFORM_HINT") == "x11"
monkeypatch.setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland")
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=ok), \
patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \
@@ -1243,7 +1247,7 @@ def test_gui_linux_packaged_launch_bridges_detected_password_store(tmp_path, mon
ok = subprocess.CompletedProcess([], 0)
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=ok), \
patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \
@@ -1268,7 +1272,7 @@ def test_gui_linux_source_launch_bridges_detected_password_store(tmp_path, monke
ok = subprocess.CompletedProcess([], 0)
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=ok), \
patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \
@@ -1294,7 +1298,7 @@ def test_gui_config_password_store_skips_detection(tmp_path, monkeypatch):
ok = subprocess.CompletedProcess([], 0)
cfg = {"desktop": {"password_store": "kwallet6"}}
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=ok), \
patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \
@@ -1323,7 +1327,7 @@ def test_gui_explicit_password_store_env_wins_over_config_and_detection(tmp_path
ok = subprocess.CompletedProcess([], 0)
cfg = {"desktop": {"password_store": "kwallet6"}}
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=ok), \
patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \
@@ -1350,7 +1354,7 @@ def test_gui_password_store_bridge_is_linux_only(tmp_path, monkeypatch):
ok = subprocess.CompletedProcess([], 0)
- with patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"), \
+ with patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"), \
patch("hermes_cli.main_web_build._run_npm_install_deterministic", return_value=ok), \
patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True), \
patch("hermes_cli.main_desktop._write_desktop_build_stamp"), \
@@ -1377,7 +1381,10 @@ def test_gui_password_store_bridge_is_linux_only(tmp_path, monkeypatch):
def _gui_build_patches(root: Path, run_side_effect):
return [
- patch("hermes_cli.main.shutil.which", return_value="/usr/bin/npm"),
+ patch("hermes_cli.main_install_repair._resolve_node_runtime_npm", return_value="/usr/bin/npm"),
+ # These staging doubles write text payloads; PE parsing is tested in
+ # test_desktop_exe_integrity.py with structurally valid binaries.
+ patch("hermes_cli.main_desktop._desktop_exe_integrity_error", return_value=None),
patch("hermes_cli.main_web_build._run_npm_install_deterministic",
return_value=subprocess.CompletedProcess(["npm", "ci"], 0)),
patch("hermes_cli.main_desktop._desktop_build_needed", return_value=True),