Skip to content

The agent that grows with you

fix(desktop): run the Windows update checkers from bundled core code

ethernet2bf86dd20cfe
diff --git a/apps/desktop/electron-builder.config.cjs b/apps/desktop/electron-builder.config.cjs
index 217667abe1f..92b22e15857 100644
--- a/apps/desktop/electron-builder.config.cjs
+++ b/apps/desktop/electron-builder.config.cjs
@@ -220,6 +220,10 @@ module.exports = {
executableName: windowsExecutableName,
legalTrademarks: displayName,
target: ['msix'],
+ // The updaters' relaunch waiter is PowerShell run outside the package. The
+ // sealed payload's snapshot omits scripts/, so it ships as a resource
+ // (RELAUNCH_WAITER_SCRIPT in electron/updater/relaunch-waiter.ts).
+ extraResources: [{ from: 'scripts/update-relaunch-waiter.ps1', to: 'update-relaunch-waiter.ps1' }],
...windowsSigning()
},
msix: {
diff --git a/apps/desktop/electron/app-updater.ts b/apps/desktop/electron/app-updater.ts
index 0338d00ca7c..ea6a1e96a97 100644
--- a/apps/desktop/electron/app-updater.ts
+++ b/apps/desktop/electron/app-updater.ts
@@ -55,10 +55,10 @@ export interface AppInstallerCheck {
export interface PayloadPythonRunner {
/** Absolute path to the bundled payload python (tools/<entry>/python.exe). */
python: string
- /** The checker script's absolute path. */
- script: string
- /** Run the script; resolve with {code, stdout}. */
- run: (python: string, script: string) => Promise<{ code: number; stdout: string }>
+ /** The checker's module name. */
+ module: string
+ /** Run the module; resolve with {code, stdout}. */
+ run: (python: string, module: string) => Promise<{ code: number; stdout: string }>
}
/**
@@ -68,7 +68,7 @@ export interface PayloadPythonRunner {
* installed version; it does NOT download anything.
*/
export async function checkAppInstallerUpdate(runner: PayloadPythonRunner): Promise<AppInstallerCheck> {
- const { code, stdout } = await runner.run(runner.python, runner.script)
+ const { code, stdout } = await runner.run(runner.python, runner.module)
return parseCheckOutput(code, stdout)
}
diff --git a/apps/desktop/electron/appinstaller-checker.test.ts b/apps/desktop/electron/appinstaller-checker.test.ts
index 5e790da69aa..cf0946fa76d 100644
--- a/apps/desktop/electron/appinstaller-checker.test.ts
+++ b/apps/desktop/electron/appinstaller-checker.test.ts
@@ -31,11 +31,11 @@ const UNKNOWN_JSON = JSON.stringify({ available: null, error: 'checker timed out
describe('runAppInstallerChecker', () => {
it('runs python on the script, hidden and with the default deadline', async () => {
const { impl, calls } = stubExecFile(call => call.callback(null, '{"available": false}', ''))
- const result = await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl })
+ const result = await runAppInstallerChecker('python.exe', 'check.module', { execFileImpl: impl })
expect(result).toEqual({ code: 0, stdout: '{"available": false}' })
expect(calls[0].file).toBe('python.exe')
- expect(calls[0].args).toEqual(['check.py'])
+ expect(calls[0].args).toEqual(['-P', '-m', 'check.module'])
expect(calls[0].options.windowsHide).toBe(true)
expect(calls[0].options.timeout).toBe(APPINSTALLER_CHECK_TIMEOUT_MS)
})
@@ -44,7 +44,7 @@ describe('runAppInstallerChecker', () => {
const stdout = '{"available": null, "error": "winrt import failed"}'
const { impl } = stubExecFile(call => call.callback(Object.assign(new Error('exited'), { code: 1 }), stdout, ''))
- const result = await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl })
+ const result = await runAppInstallerChecker('python.exe', 'check.module', { execFileImpl: impl })
expect(result).toEqual({ code: 1, stdout })
})
@@ -54,7 +54,7 @@ describe('runAppInstallerChecker', () => {
call.callback(Object.assign(new Error('killed'), { code: null, killed: true }), '', '')
)
- const result = await runAppInstallerChecker('python.exe', 'check.py', {
+ const result = await runAppInstallerChecker('python.exe', 'check.module', {
execFileImpl: impl,
timeoutMs: 50
})
@@ -70,7 +70,7 @@ describe('runAppInstallerChecker', () => {
const { impl, calls } = stubExecFile(() => undefined) // no callback, ever
const started = Date.now()
- const result = await runAppInstallerChecker('python.exe', 'check.py', {
+ const result = await runAppInstallerChecker('python.exe', 'check.module', {
execFileImpl: impl,
timeoutMs: 50
})
@@ -92,7 +92,7 @@ describe('runAppInstallerChecker', () => {
let settled = false
- const pending = runAppInstallerChecker('python.exe', 'store.py', {
+ const pending = runAppInstallerChecker('python.exe', 'store.module', {
execFileImpl: impl,
timeoutMs: 50,
waitForExit: true
@@ -114,7 +114,7 @@ describe('runAppInstallerChecker', () => {
it('an interpreter that cannot spawn resolves unknown, never "no update"', async () => {
const { impl } = stubExecFile(call => call.callback(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }), '', ''))
- const result = await runAppInstallerChecker('missing-python.exe', 'check.py', { execFileImpl: impl })
+ const result = await runAppInstallerChecker('missing-python.exe', 'check.module', { execFileImpl: impl })
expect(result.code).toBe(1)
expect(JSON.parse(result.stdout)).toEqual({ available: null, error: 'ENOENT' })
@@ -127,7 +127,7 @@ describe('runAppInstallerChecker', () => {
const { impl } = stubExecFile(call => call.callback(null, '{}', 'some warning'))
- const result = await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl, onStderr })
+ const result = await runAppInstallerChecker('python.exe', 'check.module', { execFileImpl: impl, onStderr })
expect(result).toEqual({ code: 0, stdout: '{}' })
expect(onStderr).toHaveBeenCalledWith('some warning')
@@ -138,7 +138,7 @@ describe('runAppInstallerChecker', () => {
throw new Error('bad arguments')
}) as unknown as ExecFileImpl
- const result = await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl, timeoutMs: 50 })
+ const result = await runAppInstallerChecker('python.exe', 'check.module', { execFileImpl: impl, timeoutMs: 50 })
expect(result.code).toBe(1)
expect(JSON.parse(result.stdout)).toEqual({ available: null, error: 'bad arguments' })
@@ -147,14 +147,14 @@ describe('runAppInstallerChecker', () => {
it('forwards the requested Store mode and window handle without a shell', async () => {
const { impl, calls } = stubExecFile(call => call.callback(null, '{"ok":true}', ''))
const args = ['--mode', 'install', '--hwnd', '1311768467139281697']
- await runAppInstallerChecker('packaged-python.exe', 'store.py', { execFileImpl: impl, args })
- expect(calls[0].args).toEqual(['store.py', ...args])
+ await runAppInstallerChecker('packaged-python.exe', 'store.module', { execFileImpl: impl, args })
+ expect(calls[0].args).toEqual(['-P', '-m', 'store.module', ...args])
})
it('passes the caller env through (PYTHONPATH for the payload site-packages)', async () => {
const { impl, calls } = stubExecFile(call => call.callback(null, '', ''))
- await runAppInstallerChecker('python.exe', 'check.py', { execFileImpl: impl, env: { PYTHONPATH: 'C:\\sp' } })
+ await runAppInstallerChecker('python.exe', 'check.module', { execFileImpl: impl, env: { PYTHONPATH: 'C:\\sp' } })
expect(calls[0].options.env).toEqual({ PYTHONPATH: 'C:\\sp' })
})
diff --git a/apps/desktop/electron/appinstaller-checker.ts b/apps/desktop/electron/appinstaller-checker.ts
index 24fd01fcaa7..0fc213582af 100644
--- a/apps/desktop/electron/appinstaller-checker.ts
+++ b/apps/desktop/electron/appinstaller-checker.ts
@@ -2,7 +2,7 @@
* appinstaller-checker.ts
*
* Bounded child run for the App Installer update checker
- * (scripts/check-appinstaller-update.py). The checker runs on the
+ * (hermes_cli/windows_appinstaller_update.py). The checker runs on the
* update-check path, so a wedged child must never hang the check: the
* deadline resolves the promise AT the deadline with an honest unknown,
* while execFile's own timeout performs the bounded kill. Two independent
@@ -41,14 +41,14 @@ export type ExecFileImpl = (
) => unknown
/**
- * Run `python <script>` with a hard deadline. Resolves (never rejects):
+ * Run `python -P -m <module>` with a hard deadline. Resolves (never rejects):
* exit code and stdout map through unchanged so the checker's own JSON
* contract survives; a deadline hit or an unspawnable interpreter resolves
* the caller's "unknown" shape instead of a fake "no update".
*/
export function runAppInstallerChecker(
python: string,
- script: string,
+ module: string,
deps: AppInstallerCheckerDeps = {}
): Promise<AppInstallerCheckResult> {
const timeoutMs = deps.timeoutMs ?? APPINSTALLER_CHECK_TIMEOUT_MS
@@ -79,7 +79,8 @@ export function runAppInstallerChecker(
try {
exec(
python,
- [script, ...(deps.args ?? [])],
+ // -P: the working directory never joins sys.path ahead of the bundle.
+ ['-P', '-m', module, ...(deps.args ?? [])],
{ encoding: 'utf8', timeout: timeoutMs, windowsHide: true, env: deps.env },
(error, stdout, stderr) => {
if (stderr) {
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index b6f6dc72f18..c94a4257625 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -416,7 +416,7 @@ import {
import { wireOauthSessionResponse } from './oauth-session-response'
import { listWindowsProcesses, reapPackageRootedProcesses } from './package-process-reap'
import { createParentStartMarkerResolver, parentWatchdogEnv } from './parent-process-identity'
-import { bundledPayload, installIdForRoot, type PayloadInfo } from './payload-backend'
+import { bundledPayload, installIdForRoot, type PayloadInfo, payloadPythonPath } from './payload-backend'
import { petOverlayClickThrough, shouldPopInOnOverlayClosed } from './pet-overlay'
import { placePetOverlay, registerPetOverlayIpc } from './pet-overlay-ipc'
import {
@@ -620,7 +620,7 @@ import {
registerUpdateRelaunch,
type RelaunchRegistration
} from './updater/relaunch'
-import { startRelaunchWaiter } from './updater/relaunch-waiter'
+import { relaunchWaiterScript, startRelaunchWaiter } from './updater/relaunch-waiter'
import { preflightStateDb } from './updater/state-db-preflight'
import { createStoreStrategy } from './updater/store-client'
import { isExternalVenvHolder, isHermesOwnedVenvDaemon } from './venv-holder-select'
@@ -3848,12 +3848,11 @@ function createNativePackagedStrategy(
const deps: ConstructorParameters<typeof AppInstallerStrategy>[0] = {
python: payload.storePython,
- // The checker ships inside the payload's repo snapshot (git archive of
- // the committed tree): <payload>/<repo>/apps/desktop/scripts/.
- script: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'check-appinstaller-update.py'),
- run: (python, script) =>
- runAppInstallerChecker(python, script, {
- env: { ...process.env, PYTHONPATH: payload.sitePackages },
+ // The checker is bundled core code, run with the payload python.
+ module: 'hermes_cli.windows_appinstaller_update',
+ run: (python, module) =>
+ runAppInstallerChecker(python, module, {
+ env: { ...process.env, PYTHONPATH: payloadPythonPath(payload) },
onStderr: stderr => console.error(`[app-installer] checker stderr: ${stderr.slice(0, 400)}`)
}),
channel: resolveUpdaterChannelFromStamp(),
@@ -3883,7 +3882,7 @@ function createNativePackagedStrategy(
processId: process.pid,
processStartTimeMs: Math.round(Date.now() - process.uptime() * 1000),
identityName: PRODUCT_IDENTITY.msixAppIdWithOrg,
- scriptPath: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'update-relaunch-waiter.ps1')
+ scriptPath: relaunchWaiterScript(process.resourcesPath)
})
})
}
@@ -3898,8 +3897,8 @@ function createNativePackagedStrategy(
return createStoreStrategy({
python: payload.storePython,
- script: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'check-store-update.py'),
- sitePackages: payload.sitePackages,
+ module: 'hermes_cli.windows_store_update',
+ pythonPath: payloadPythonPath(payload),
env: process.env,
windowHandle: () => (BrowserWindow.getFocusedWindow() ?? mainWindow)?.getNativeWindowHandle() ?? null,
appVersion: app.getVersion(),
@@ -3914,7 +3913,7 @@ function createNativePackagedStrategy(
processId: process.pid,
processStartTimeMs: Math.round(Date.now() - process.uptime() * 1000),
identityName: PRODUCT_IDENTITY.storeMsix!.identityName,
- scriptPath: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'update-relaunch-waiter.ps1'),
+ scriptPath: relaunchWaiterScript(process.resourcesPath),
timeoutSeconds: 1860
})
})
diff --git a/apps/desktop/electron/payload-backend.test.ts b/apps/desktop/electron/payload-backend.test.ts
index 5d35484dff9..4492fd2cca0 100644
--- a/apps/desktop/electron/payload-backend.test.ts
+++ b/apps/desktop/electron/payload-backend.test.ts
@@ -6,7 +6,7 @@ import path from 'node:path'
import { test, vi } from 'vitest'
import type { InstallStamp, PayloadRuntime } from './install-stamp'
-import { bundledPayload, installIdForRoot } from './payload-backend'
+import { bundledPayload, installIdForRoot, payloadPythonPath } from './payload-backend'
function stamp(runtime: PayloadRuntime, payload: InstallStamp['payload'] = 'bundled'): InstallStamp {
return {
@@ -80,3 +80,10 @@ test('installIdForRoot matches the Python install id (sha16 of the canonical pat
installIdForRoot('/real/hermes-agent')
)
})
+
+test('bundled core code precedes the dependencies, as the bin launchers order them', () => {
+ assert.equal(
+ payloadPythonPath({ repoDir: 'payload/hermes-agent', sitePackages: 'payload/venv/site-packages' }),
+ ['payload/hermes-agent', 'payload/venv/site-packages'].join(path.delimiter)
+ )
+})
diff --git a/apps/desktop/electron/payload-backend.ts b/apps/desktop/electron/payload-backend.ts
index 5936e58c774..ba1c2a39f8e 100644
--- a/apps/desktop/electron/payload-backend.ts
+++ b/apps/desktop/electron/payload-backend.ts
@@ -37,6 +37,15 @@ export function bundledPayload(
}
}
+/**
+ * PYTHONPATH for running a bundled core module with the payload python: the
+ * bundled core code first, then the venv's dependencies. This is the order the
+ * bin/ launchers give sys.path (scripts/build/launcher_wrapper.py).
+ */
+export function payloadPythonPath(payload: Pick<PayloadInfo, 'repoDir' | 'sitePackages'>): string {
+ return [payload.repoDir, payload.sitePackages].join(path.delimiter)
+}
+
// ─── update channel ─────────────────────────────────────────────────────────
//
// The CLI owns the channel records; Electron only reads the install id for
diff --git a/apps/desktop/electron/updater/app-installer-recovery.test.ts b/apps/desktop/electron/updater/app-installer-recovery.test.ts
index 4ecd5633835..04ba82544d5 100644
--- a/apps/desktop/electron/updater/app-installer-recovery.test.ts
+++ b/apps/desktop/electron/updater/app-installer-recovery.test.ts
@@ -27,7 +27,7 @@ for (const failureAt of ['prepare', 'register', 'teardown', 'open', 'none']) {
const deps: AppInstallerStrategyDeps = {
python: 'unused-checker',
- script: 'unused.py',
+ module: 'unused.module',
run: async () => {
throw new Error('configured feed does not need the checker')
},
@@ -107,7 +107,7 @@ test('handoff errors retain cleanup failures while still restoring the backend',
const deps: AppInstallerStrategyDeps = {
python: 'unused',
- script: 'unused.py',
+ module: 'unused.module',
run: async () => ({ code: 0, stdout: '' }),
channel: 'stable',
light: false,
diff --git a/apps/desktop/electron/updater/app-installer-strategy.test.ts b/apps/desktop/electron/updater/app-installer-strategy.test.ts
index 0e087708929..1319c48ebec 100644
--- a/apps/desktop/electron/updater/app-installer-strategy.test.ts
+++ b/apps/desktop/electron/updater/app-installer-strategy.test.ts
@@ -17,7 +17,7 @@ function makeDeps(over: Partial<AppInstallerStrategyDeps> = {}): StrategyFixture
const deps: AppInstallerStrategyDeps = {
python: 'python.exe',
- script: 'check.py',
+ module: 'check.module',
run: async () => ({ code: 0, stdout: '{"available": true}' }),
channel: 'stable',
light: false,
@@ -167,8 +167,8 @@ it.each([
'checker %s %s → available=%s error=%s',
async (code: number, stdout: string, available: boolean | undefined, error: string | undefined): Promise<void> => {
const { deps }: ReturnType<typeof makeDeps> = makeDeps({
- run: async (python: string, script: string): Promise<{ code: number; stdout: string }> => {
- expect([python, script]).toEqual(['python.exe', 'check.py'])
+ run: async (python: string, module: string): Promise<{ code: number; stdout: string }> => {
+ expect([python, module]).toEqual(['python.exe', 'check.module'])
return { code, stdout }
}
diff --git a/apps/desktop/electron/updater/app-installer.ts b/apps/desktop/electron/updater/app-installer.ts
index c95911f7052..91ee8c1c838 100644
--- a/apps/desktop/electron/updater/app-installer.ts
+++ b/apps/desktop/electron/updater/app-installer.ts
@@ -29,8 +29,8 @@ import type { UpdaterApplyResultWire, UpdaterStatusWire } from './index'
export interface AppInstallerStrategyDeps {
/** Absolute path to the bundled payload python (tools/<entry>/python.exe). */
python: string
- /** The checker script's absolute path (payload repo snapshot). */
- script: string
+ /** The checker's module name, run with the payload python. */
+ module: string
run: PayloadPythonRunner['run']
/** Channel + variant from the baked install stamp. */
channel: string
@@ -111,7 +111,7 @@ export class AppInstallerStrategy {
}
}
- const { code, stdout } = await this.deps.run(this.deps.python, this.deps.script)
+ const { code, stdout } = await this.deps.run(this.deps.python, this.deps.module)
const check = parseCheckOutput(code, stdout)
return appInstallerCheckToStatus(check, this.deps.appVersion)
@@ -136,7 +136,7 @@ export class AppInstallerStrategy {
}
if (!feedBaseUrl && !sourceUri) {
- const { code, stdout } = await this.deps.run(this.deps.python, this.deps.script)
+ const { code, stdout } = await this.deps.run(this.deps.python, this.deps.module)
sourceUri = parseCheckOutput(code, stdout).sourceUri
if (sourceUri) {
diff --git a/apps/desktop/electron/updater/relaunch-waiter-resource.test.ts b/apps/desktop/electron/updater/relaunch-waiter-resource.test.ts
new file mode 100644
index 00000000000..12047b94cad
--- /dev/null
+++ b/apps/desktop/electron/updater/relaunch-waiter-resource.test.ts
@@ -0,0 +1,29 @@
+// The sealed payload's repo snapshot has no scripts/, so the relaunch waiter
+// must be shipped by the packaging config at the path main resolves.
+
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+
+import { expect, test } from 'vitest'
+
+import { RELAUNCH_WAITER_SCRIPT, relaunchWaiterScript } from './relaunch-waiter'
+
+const require: NodeJS.Require = createRequire(import.meta.url)
+const desktop: string = path.resolve(import.meta.dirname, '..', '..')
+
+test('the windows packaging config ships the relaunch waiter at the resource root', () => {
+ const config = require('../../electron-builder.config.cjs')
+ const extra: { from: string; to: string }[] = config.win.extraResources ?? []
+ const shipped = extra.filter(item => item.to === RELAUNCH_WAITER_SCRIPT)
+
+ assert.equal(shipped.length, 1, `win.extraResources must ship ${RELAUNCH_WAITER_SCRIPT}`)
+ assert.ok(fs.existsSync(path.join(desktop, shipped[0].from)), `${shipped[0].from} must exist`)
+})
+
+test('the waiter resolves at the resources root', () => {
+ const resources = path.join('app', 'resources')
+
+ expect(relaunchWaiterScript(resources)).toBe(path.join(resources, RELAUNCH_WAITER_SCRIPT))
+})
diff --git a/apps/desktop/electron/updater/relaunch-waiter.ts b/apps/desktop/electron/updater/relaunch-waiter.ts
index 6d2b7547491..b63cd624978 100644
--- a/apps/desktop/electron/updater/relaunch-waiter.ts
+++ b/apps/desktop/electron/updater/relaunch-waiter.ts
@@ -7,6 +7,16 @@ import * as os from 'node:os'
import * as path from 'node:path'
export const RELAUNCH_WAITER_SCRIPT = 'update-relaunch-waiter.ps1'
+
+/**
+ * The waiter ships as an app resource (electron-builder win.extraResources):
+ * it is PowerShell run outside the package, not core code, and the sealed
+ * payload's snapshot omits scripts/.
+ */
+export function relaunchWaiterScript(resourcesPath: string): string {
+ return path.join(resourcesPath, RELAUNCH_WAITER_SCRIPT)
+}
+
export const RELAUNCH_WAITER_READY_FILENAME = 'ready.txt'
export const DEFAULT_RELAUNCH_WAITER_TIMEOUT_SECONDS = 900
export const DEFAULT_RELAUNCH_WAITER_HANDSHAKE_MS = 10_000
@@ -27,7 +37,7 @@ export interface RelaunchWaiterOptions {
processStartTimeMs: number
/** The MSIX identity name of this install (e.g. NousResearch.HermesBundled). */
identityName: string
- /** Absolute path to the waiter script inside the payload repo snapshot. */
+ /** Absolute path to the waiter script shipped in the app's resources. */
scriptPath: string
timeoutSeconds?: number
}
diff --git a/apps/desktop/electron/updater/store-client.test.ts b/apps/desktop/electron/updater/store-client.test.ts
index 731cee38061..9db29aa1430 100644
--- a/apps/desktop/electron/updater/store-client.test.ts
+++ b/apps/desktop/electron/updater/store-client.test.ts
@@ -16,8 +16,8 @@ it('the production runner passes modes, full HWND and isolated payload imports',
const strategy = createStoreStrategy({
python: 'packaged-python.exe',
- script: 'check-store-update.py',
- sitePackages: 'payload-deps',
+ module: 'hermes_cli.windows_store_update',
+ pythonPath: 'payload-core;payload-deps',
env: { PYTHONHOME: 'foreign', VIRTUAL_ENV: 'foreign', PYTHONPATH: 'foreign' },
windowHandle: () => handle,
appVersion: '1.0.0',
@@ -46,7 +46,7 @@ it('the production runner passes modes, full HWND and isolated payload imports',
await strategy.apply()
expect(calls.map(call => call.args)).toEqual(
['check', 'download', 'install'].map(mode => [
- 'check-store-update.py',
+ 'hermes_cli.windows_store_update',
'--mode',
mode,
'--hwnd',
@@ -55,7 +55,7 @@ it('the production runner passes modes, full HWND and isolated payload imports',
)
expect(calls.every(call => call.python === 'packaged-python.exe')).toBe(true)
expect(
- calls.every(call => call.env?.PYTHONPATH === 'payload-deps' && !call.env.PYTHONHOME && !call.env.VIRTUAL_ENV)
+ calls.every(call => call.env?.PYTHONPATH === 'payload-core;payload-deps' && !call.env.PYTHONHOME && !call.env.VIRTUAL_ENV)
).toBe(true)
expect(calls[1].timeout).toBeGreaterThan(calls[0].timeout!)
expect(calls.map(call => call.waitForExit)).toEqual([false, true, true])
@@ -69,8 +69,8 @@ describe('Store runner refuses unusable replies', () => {
])('does not turn $stdout into a current-version verdict', async response => {
const strategy = createStoreStrategy({
python: 'python',
- script: 'checker',
- sitePackages: 'deps',
+ module: 'checker',
+ pythonPath: 'deps',
env: {},
windowHandle: () => Buffer.alloc(8, 1),
appVersion: '1',
diff --git a/apps/desktop/electron/updater/store-client.ts b/apps/desktop/electron/updater/store-client.ts
index d2d38bd4cac..cbbc5d30872 100644
--- a/apps/desktop/electron/updater/store-client.ts
+++ b/apps/desktop/electron/updater/store-client.ts
@@ -4,8 +4,9 @@ import { type StoreResult, StoreStrategy, type StoreStrategyDeps } from './store
export interface StoreClientDeps extends Omit<StoreStrategyDeps, 'run'> {
python: string
- script: string
- sitePackages: string
+ module: string
+ /** PYTHONPATH for the payload python: the bundled core code, then its dependencies. */
+ pythonPath: string
env: NodeJS.ProcessEnv
windowHandle: () => Buffer | null
run?: typeof runAppInstallerChecker
@@ -46,7 +47,7 @@ export function createStoreStrategy(deps: StoreClientDeps): StoreStrategy {
return new StoreStrategy({
...deps,
run: async mode => {
- const env: NodeJS.ProcessEnv = { ...deps.env, PYTHONPATH: deps.sitePackages }
+ const env: NodeJS.ProcessEnv = { ...deps.env, PYTHONPATH: deps.pythonPath }
delete env.PYTHONHOME
delete env.VIRTUAL_ENV
delete env.PYTHONEXECUTABLE
@@ -64,7 +65,7 @@ export function createStoreStrategy(deps: StoreClientDeps): StoreStrategy {
args.push('--hwnd', hwnd)
}
- const result = await run(deps.python, deps.script, {
+ const result = await run(deps.python, deps.module, {
args,
env,
timeoutMs: mode === 'check' ? APPINSTALLER_CHECK_TIMEOUT_MS : 1_830_000,
diff --git a/apps/desktop/scripts/check-appinstaller-update.py b/hermes_cli/windows_appinstaller_update.py
similarity index 97%
rename from apps/desktop/scripts/check-appinstaller-update.py
rename to hermes_cli/windows_appinstaller_update.py
index dd98ba7ef07..9d49d493c75 100644
--- a/apps/desktop/scripts/check-appinstaller-update.py
+++ b/hermes_cli/windows_appinstaller_update.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python3
"""Check for an App Installer update for the running MSIX package.
The out-of-store desktop installs are App Installer owned: the OS registered
@@ -8,7 +7,7 @@ shows its own prompt + tears down before the OS applies the swap.
Run with the BUNDLED payload python (the winrt package ships there):
- <payload>/tools/<python-entry>/python.exe scripts/check-appinstaller-update.py
+ <payload>/tools/<python-entry>/python.exe -P -m hermes_cli.windows_appinstaller_update
Exit codes:
0 no update available, or this process has no package identity
diff --git a/apps/desktop/scripts/check-store-update.py b/hermes_cli/windows_store_update.py
similarity index 97%
rename from apps/desktop/scripts/check-store-update.py
rename to hermes_cli/windows_store_update.py
index 2a8aa6f2a93..7f2d8612c85 100644
--- a/apps/desktop/scripts/check-store-update.py
+++ b/hermes_cli/windows_store_update.py
@@ -1,9 +1,10 @@
-#!/usr/bin/env python3
"""Run a Store check, download, or install with the packaged interpreter.
The desktop keeps the backend alive during download, then stops it before
requesting installation. Each invocation reports one final JSON result.
Exit 0 means success, 2 means a check found updates, and 1 means failure.
+
+Run with the bundled payload python: ``python -P -m hermes_cli.windows_store_update``.
"""
from __future__ import annotations
diff --git a/tests/desktop/test_appinstaller_check_script.py b/tests/desktop/test_appinstaller_check_script.py
index db68412c110..042fe408d0a 100644
--- a/tests/desktop/test_appinstaller_check_script.py
+++ b/tests/desktop/test_appinstaller_check_script.py
@@ -24,10 +24,8 @@ import pytest
HERMES_PYTHON = sys.executable
-SCRIPT = (
- Path(__file__).resolve().parents[2]
- / "apps/desktop/scripts/check-appinstaller-update.py"
-)
+REPO = Path(__file__).resolve().parents[2]
+MODULE = "hermes_cli.windows_appinstaller_update"
@pytest.mark.parametrize("state,code,available", [
("not-packaged", 0, False), ("AVAILABLE", 2, True), ("REQUIRED", 2, True),
@@ -37,10 +35,10 @@ SCRIPT = (
])
def test_projection_outcomes(monkeypatch, capsys, state, code, available):
import enum
- import runpy
+ import importlib
from types import SimpleNamespace
- main = runpy.run_path(str(SCRIPT))["main"]
+ main = importlib.import_module(MODULE).main
availability = enum.IntEnum("Availability", "UNKNOWN NO_UPDATES AVAILABLE REQUIRED ERROR", start=0)
class PackageInstance:
def get_app_installer_info(self):
@@ -88,10 +86,12 @@ def test_projection_outcomes(monkeypatch, capsys, state, code, available):
def test_script_import_failure_json_and_exit(tmp_path):
- # A real subprocess executes __main__ and imports the absent projection.
+ # A real subprocess runs the entry the desktop spawns (python -P -m) and
+ # imports the absent projection.
(tmp_path / "winrt.py").write_text("raise ImportError('fixture unavailable')", encoding="utf-8")
- child = subprocess.run([HERMES_PYTHON, str(SCRIPT)], capture_output=True,
- text=True, timeout=30, env={**os.environ, "PYTHONPATH": str(tmp_path)})
+ child = subprocess.run([HERMES_PYTHON, "-P", "-m", MODULE], capture_output=True,
+ text=True, timeout=30,
+ env={**os.environ, "PYTHONPATH": os.pathsep.join([str(REPO), str(tmp_path)])})
assert child.returncode == 1, child.stderr
payload = json.loads(child.stdout)
assert payload["available"] is None
@@ -104,12 +104,13 @@ def test_installed_winrt_projects_checker_uri_and_async_types(tmp_path):
# packaged update call projects only after Package.current succeeds.
probe = subprocess.run(
[HERMES_PYTHON, "-I", "-c",
- "import runpy; "
+ f"import sys; sys.path.insert(0, {str(REPO)!r}); "
+ f"from {MODULE} import _load_projection; "
"from winrt.windows.foundation import IAsyncOperation, Uri; "
"uri = Uri('https://example.invalid/updates.appinstaller'); "
"assert uri.absolute_uri == 'https://example.invalid/updates.appinstaller'; "
"assert callable(IAsyncOperation.get); "
- f"runpy.run_path({str(SCRIPT)!r})['_load_projection'](); "
+ "_load_projection(); "
"print('WINRT_CHECKER_TYPES_OK')"],
cwd=tmp_path, capture_output=True, text=True, timeout=30,
)
diff --git a/tests/desktop/test_check_store_update.py b/tests/desktop/test_check_store_update.py
index fb02a6ca978..bbfbdac80d0 100644
--- a/tests/desktop/test_check_store_update.py
+++ b/tests/desktop/test_check_store_update.py
@@ -1,14 +1,19 @@
"""Store update contracts use the actual API's sequence and result shapes."""
from __future__ import annotations
-import importlib.util
+import importlib
+import json
+import os
+import subprocess
+import sys
from enum import IntEnum
from pathlib import Path
from types import SimpleNamespace
import pytest
-SCRIPT = Path(__file__).resolve().parents[2] / "apps/desktop/scripts/check-store-update.py"
+REPO = Path(__file__).resolve().parents[2]
+MODULE = "hermes_cli.windows_store_update"
class State(IntEnum):
@@ -47,10 +52,7 @@ class Context:
@pytest.fixture
def checker():
- spec = importlib.util.spec_from_file_location("store_update_checker", SCRIPT)
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
+ return importlib.import_module(MODULE)
@pytest.mark.parametrize("mode", ["check", "download", "install"])
@@ -74,9 +76,6 @@ def test_store_operation_passes_update_sequence_and_requires_completed(checker,
@pytest.mark.platforms("windows")
def test_native_projection_has_required_update_contract(tmp_path):
- import subprocess
- import sys
-
code = (
"from winrt.runtime import init_apartment,uninit_apartment,ApartmentType; "
"from winrt.runtime.interop import initialize_with_window; "
@@ -101,3 +100,16 @@ def test_native_projection_has_required_update_contract(tmp_path):
capture_output=True, text=True, timeout=30)
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == "store projection ready"
+
+
+def test_entry_reports_json_when_the_projection_is_unavailable(tmp_path):
+ # The desktop spawns `python -P -m <module>` and parses stdout as JSON; a
+ # failure inside the checker must still reach it as JSON, never as nothing.
+ (tmp_path / "winrt.py").write_text("raise ImportError('fixture unavailable')", encoding="utf-8")
+ child = subprocess.run([sys.executable, "-P", "-m", MODULE, "--mode", "check"], capture_output=True,
+ text=True, timeout=30,
+ env={**os.environ, "PYTHONPATH": os.pathsep.join([str(REPO), str(tmp_path)])})
+ assert child.returncode == 1, child.stderr
+ payload = json.loads(child.stdout)
+ assert payload["ok"] is False and payload["available"] is None
+ assert "fixture unavailable" in payload["error"]