Skip to content

The agent that grows with you

fix(desktop): open registered App Installer descriptors without disabled protocol

ethernet0ea7a75f4188
diff --git a/apps/desktop/electron/app-installer-file.test.ts b/apps/desktop/electron/app-installer-file.test.ts
new file mode 100644
index 00000000000..482b653566d
--- /dev/null
+++ b/apps/desktop/electron/app-installer-file.test.ts
@@ -0,0 +1,43 @@
+import * as fs from 'node:fs/promises'
+import * as http from 'node:http'
+import * as os from 'node:os'
+import * as path from 'node:path'
+
+import { expect, test } from 'vitest'
+
+import { stageAppInstallerFile } from './app-installer-file'
+
+test('stages an actual HTTP descriptor and leaves a valid file intact on download failure', async () => {
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'hermes-installer-file-'))
+ const descriptor = '<?xml version="1.0"?><AppInstaller Uri="https://updates.example/app.appinstaller" />'
+
+ const server = http.createServer((request, response) => {
+ if (request.url === '/missing') {
+ response.writeHead(404).end()
+ } else if (request.url === '/large') {
+ response.end(Buffer.alloc(1024 * 1024 + 1))
+ } else {
+ response.end(descriptor)
+ }
+ })
+
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const address = server.address()
+
+ if (!address || typeof address === 'string') { throw new Error('missing server address') }
+ const base = `http://127.0.0.1:${address.port}`
+
+ try {
+ const target = await stageAppInstallerFile(`${base}/update`, directory)
+ expect(target.endsWith('.appinstaller')).toBe(true)
+ expect(await fs.readFile(target, 'utf8')).toBe(descriptor)
+ await expect(stageAppInstallerFile(`${base}/missing`, directory)).rejects.toThrow('404')
+ await expect(stageAppInstallerFile(`${base}/large`, directory)).rejects.toThrow('1 MiB')
+ expect(await fs.readFile(target, 'utf8')).toBe(descriptor)
+ expect(await fs.readdir(directory)).toEqual(['update.appinstaller'])
+ } finally {
+ server.closeAllConnections()
+ await new Promise<void>(resolve => server.close(() => resolve()))
+ await fs.rm(directory, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/app-installer-file.ts b/apps/desktop/electron/app-installer-file.ts
new file mode 100644
index 00000000000..4290ee7c6b5
--- /dev/null
+++ b/apps/desktop/electron/app-installer-file.ts
@@ -0,0 +1,50 @@
+import * as fs from 'node:fs/promises'
+import * as path from 'node:path'
+
+/** Download the descriptor before teardown. Windows verifies the referenced package. */
+export async function stageAppInstallerFile(
+ url: string,
+ directory: string,
+ fetchFile: typeof fetch = fetch
+): Promise<string> {
+ const response = await fetchFile(url, { signal: AbortSignal.timeout(30_000) })
+
+ if (!response.ok || !response.body) {
+ throw new Error(`App Installer descriptor download failed: HTTP ${response.status}`)
+ }
+
+ const chunks: Uint8Array[] = []
+ let size = 0
+ const reader = response.body.getReader()
+
+ try {
+ for (;;) {
+ const { value, done } = await reader.read()
+
+ if (done) { break }
+ size += value.byteLength
+
+ if (size > 1024 * 1024) {
+ throw new Error('App Installer descriptor exceeds 1 MiB')
+ }
+
+ chunks.push(value)
+ }
+ } finally {
+ await reader.cancel()
+ }
+
+ if (size === 0) { throw new Error('App Installer descriptor is empty') }
+ await fs.mkdir(directory, { recursive: true })
+ const target = path.join(directory, 'update.appinstaller')
+ const temporary = `${target}.tmp`
+
+ try {
+ await fs.writeFile(temporary, Buffer.concat(chunks))
+ await fs.rename(temporary, target)
+ } finally {
+ await fs.rm(temporary, { force: true })
+ }
+
+ return target
+}
diff --git a/apps/desktop/electron/app-updater.test.ts b/apps/desktop/electron/app-updater.test.ts
index 987d638f9a2..9ae9e70475f 100644
--- a/apps/desktop/electron/app-updater.test.ts
+++ b/apps/desktop/electron/app-updater.test.ts
@@ -4,19 +4,12 @@ import { test } from 'vitest'
import {
checkAppInstallerUpdate,
- PLACEHOLDER_FEED_BASE_URL,
triggerAppInstallerUpdate,
win32AppInstallerFeedPath
} from './app-updater'
// ── feed hosting + paths ────────────────────────────────────────────
-test('the feed base URL placeholder is a documented dead end', () => {
- // Overridden by `updates.desktop_feed_base_url` (read inline in main.ts);
- // the placeholder itself must never resolve to a real host.
- assert.equal(PLACEHOLDER_FEED_BASE_URL, 'https://updates.invalid/hermes-desktop')
-})
-
test('win32 App Installer feed paths are per-channel and per-variant', () => {
assert.equal(win32AppInstallerFeedPath('stable', false), 'win32/stable/')
assert.equal(win32AppInstallerFeedPath('canary', false), 'win32/canary/')
@@ -66,36 +59,37 @@ test('win32 check surfaces an unknown verdict (missing winrt) without crashing',
assert.match(result.error || '', /winrt import failed/)
})
-test('win32 trigger opens ms-appinstaller with the channel .appinstaller after teardown', async () => {
+test('win32 trigger prepares a local descriptor before teardown and file activation', async () => {
const calls: string[] = []
- const shell = {
- openExternal: async (url: string) => void calls.push(`open:${url}`)
+ const installer = {
+ prepare: async (url: string) => { calls.push(`download:${url}`);
+
+ return 'update.appinstaller' },
+ open: async (file: string) => { calls.push(`open:${file}`);
+
+ return '' }
}
const result = await triggerAppInstallerUpdate(
- 'https://updates.example.com/',
- 'stable',
- false,
- shell as any,
+ 'https://updates.example.com/', 'stable', false, installer,
() => void calls.push('teardown')
)
assert.equal(result.ok, true)
assert.deepEqual(calls, [
- 'teardown',
- 'open:ms-appinstaller:?source=https%3A%2F%2Fupdates.example.com%2Fwin32%2Fstable%2Fstable.appinstaller'
+ 'download:https://updates.example.com/win32/stable/stable.appinstaller',
+ 'teardown', 'open:update.appinstaller'
])
})
-test('win32 trigger light+canary targets the light canary feed dir', async () => {
- const calls: string[] = []
-
- const shell = {
- openExternal: async (url: string) => void calls.push(url)
- }
-
- await triggerAppInstallerUpdate('https://updates.example.com', 'canary', true, shell as any)
-
- assert.equal(calls[0], 'ms-appinstaller:?source=https%3A%2F%2Fupdates.example.com%2Fwin32%2Flight%2Fcanary%2Fcanary.appinstaller')
+test('win32 trigger refuses failed downloads before teardown and surfaces file-open errors', async () => {
+ const teardown = () => { throw new Error('unexpected teardown') }
+ await assert.rejects(triggerAppInstallerUpdate('https://updates.example.com', 'canary', true, {
+ prepare: async url => { assert.match(url, /win32\/light\/canary\/canary.appinstaller$/); throw new Error('download failed') },
+ open: async () => ''
+ }, teardown), /download failed/)
+ await assert.rejects(triggerAppInstallerUpdate('https://updates.example.com', 'stable', false, {
+ prepare: async () => 'update.appinstaller', open: async () => 'No file association'
+ }), /No file association/)
})
diff --git a/apps/desktop/electron/app-updater.ts b/apps/desktop/electron/app-updater.ts
index cd6380f35f2..d050b64c542 100644
--- a/apps/desktop/electron/app-updater.ts
+++ b/apps/desktop/electron/app-updater.ts
@@ -6,7 +6,7 @@
// wholesale. The app's only job is the checker: ask the OS whether
// an update is available (via the bundled payload python's winrt),
// show its own prompt, run graceful teardown, then trigger
-// ms-appinstaller: and quit. Installations that Windows manages
+// the downloaded App Installer file and quit. Installations that Windows manages
// for us — Microsoft Store deployments (process.windowsStore) and
// stamps whose updateMechanism is 'external' — get NO in-app
// updater at all: the store/steward owns the update loop.
@@ -28,20 +28,6 @@
// ─── feed hosting ───────────────────────────────────────────────────────────
-/**
- * PLACEHOLDER — the default base URL of the desktop release feeds.
- *
- * W3 (R2 hosting) supplies the real value; until it lands, this default is
- * a documented dead end that config overrides (`updates.desktop_feed_base_url`
- * in config.yaml — read inline by main.ts). Layout under the base:
- *
- * <base>/win32/<channel>/ — App Installer feed dir (.appinstaller
- * + .msixbundle) for out-of-store MSIX.
- *
- * `<channel>` is 'stable' or 'canary'.
- */
-export const PLACEHOLDER_FEED_BASE_URL = 'https://updates.invalid/hermes-desktop'
-
/**
* The App Installer feed dir for a channel. The .appinstaller for a channel
* lives under this dir; the OS re-reads it on launch (HoursBetweenUpdateChecks)
@@ -67,6 +53,7 @@ export interface AppInstallerCheck {
/** Human-readable availability string from the OS, when reported. */
availability?: string
error?: string
+ sourceUri?: string
}
/**
@@ -84,60 +71,53 @@ export interface PayloadPythonRunner {
/**
* win32 arm: ask the OS whether an App Installer update is available, via
- * the bundled payload python's winrt (PackageManager.CheckPackageUpdateAvailabilityAsync).
+ * the bundled payload python's winrt (Package.check_update_availability_async).
* The OS compares the package's registered .appinstaller source against the
* installed version; it does NOT download anything.
*/
-export async function checkAppInstallerUpdate(
- runner: PayloadPythonRunner
-): Promise<AppInstallerCheck> {
+export async function checkAppInstallerUpdate(runner: PayloadPythonRunner): Promise<AppInstallerCheck> {
const { code, stdout } = await runner.run(runner.python, runner.script)
- const text = stdout.trim()
- let parsed: { available?: boolean | null; availability?: string; error?: string; reason?: string } | null = null
- try {
- parsed = text ? JSON.parse(text) : null
- } catch {
- parsed = null
- }
+ return parseCheckOutput(code, stdout)
+}
- if (parsed && typeof parsed.available === 'boolean') {
- return { available: parsed.available, availability: parsed.availability, error: parsed.error }
- }
+export function parseCheckOutput(code: number, stdout: string): AppInstallerCheck {
+ let parsed: { available?: boolean | null; availability?: string; error?: string; source_uri?: string } | null = null
- if (parsed && parsed.available === null) {
- return { available: null, error: parsed.error || 'checker returned unknown' }
+ try {
+ parsed = stdout.trim() ? JSON.parse(stdout) : null
+ } catch {
+ return { available: null, error: code !== 0 ? `checker exited ${code}` : 'checker returned invalid JSON' }
}
- if (code !== 0) {
- return { available: null, error: parsed?.error || `checker exited ${code}` }
+ if (typeof parsed?.available === 'boolean') {
+ return { available: parsed.available, availability: parsed.availability, error: parsed.error, sourceUri: parsed.source_uri }
}
- return { available: null, error: 'checker returned no availability' }
+ return { available: null, error: parsed?.error || (code !== 0 ? `checker exited ${code}` : 'checker returned no availability') }
}
-/**
- * win32 arm: trigger the OS App Installer to apply the update and quit.
- * `ms-appinstaller:?source=<feed .appinstaller URL>` makes the OS re-read the
- * package's update source and install the newer bundle; the app then exits so
- * the package swap is not contested. `beforeInstall` runs first (backend
- * teardown while the process is still alive).
- */
+/** Open a local descriptor. The ms-appinstaller protocol is disabled by default. */
export async function triggerAppInstallerUpdate(
feedBaseUrl: string,
channel: 'stable' | 'canary',
light: boolean,
- shell: { openExternal: (url: string) => Promise<void> },
- beforeInstall?: () => void | Promise<void>
+ installer: { prepare: (url: string) => Promise<string>; open: (file: string) => Promise<string> },
+ beforeInstall?: () => void | Promise<void>,
+ sourceUri?: string
): Promise<{ ok: true }> {
+ const appinstallerUrl = sourceUri ||
+ `${feedBaseUrl.replace(/\/+$/, '')}/${win32AppInstallerFeedPath(channel, light)}${channel}.appinstaller`
+
+ const file = await installer.prepare(appinstallerUrl)
+
if (beforeInstall) {
await beforeInstall()
}
- const appinstallerUrl =
- `${feedBaseUrl.replace(/\/+$/, '')}/${win32AppInstallerFeedPath(channel, light)}${channel}.appinstaller`
+ const error = await installer.open(file)
- await shell.openExternal(`ms-appinstaller:?source=${encodeURIComponent(appinstallerUrl)}`)
+ if (error) { throw new Error(`App Installer could not open: ${error}`) }
return { ok: true }
}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 79f2d3b610c..4fc154db2db 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -33,7 +33,7 @@ import {
import { classifyActiveRuntime } from './active-runtime-state'
import { destroyKeepaliveAgents, downloadAgentFor, jsonAgentFor, withRetry } from './api-transport'
import { appIconCandidates, resolveAppIcon } from './app-icon'
-import { PLACEHOLDER_FEED_BASE_URL } from './app-updater'
+import { stageAppInstallerFile } from './app-installer-file'
import { runAppInstallerChecker } from './appinstaller-checker'
import { stopBackendChild as stopBackendChildImpl, stopBackendTreesForUpdate } from './backend-child'
import {
@@ -3222,7 +3222,10 @@ function resolveBundledUpdateStrategy(bundledPayload) {
channel: resolveUpdaterChannelFromStamp(),
light: isLightVariant(),
feedBaseUrl: resolveDesktopFeedBaseUrl(),
- shell: { openExternal: url => shell.openExternal(url) },
+ installer: {
+ prepare: url => stageAppInstallerFile(url, path.join(app.getPath('userData'), 'updates')),
+ open: file => shell.openPath(file)
+ },
teardownBundledBackend,
emitUpdateProgress,
appVersion: app.getVersion(),
@@ -3317,7 +3320,7 @@ function isWindowsStore(): boolean {
/**
* The App Installer feed base URL for a bundled MSIX install: config.yaml's
* `updates.desktop_feed_base_url`, then HERMES_DESKTOP_FEED_BASE_URL, then
- * the documented placeholder. Empty only when nothing configured the feed.
+ * Windows' registered App Installer source when no override is set.
*/
function resolveDesktopFeedBaseUrl(): string {
const configured = readUpdatesFeedBaseFromConfig()
@@ -3327,7 +3330,7 @@ function resolveDesktopFeedBaseUrl(): string {
if (env) {return env}
- return PLACEHOLDER_FEED_BASE_URL
+ return ''
}
/** Read `updates.desktop_feed_base_url` from the user's config.yaml. */
diff --git a/apps/desktop/electron/updater/app-installer-strategy.test.ts b/apps/desktop/electron/updater/app-installer-strategy.test.ts
index 263c8b42c15..7d33c935648 100644
--- a/apps/desktop/electron/updater/app-installer-strategy.test.ts
+++ b/apps/desktop/electron/updater/app-installer-strategy.test.ts
@@ -17,7 +17,14 @@ function makeDeps(over: Partial<AppInstallerStrategyDeps> = {}) {
channel: 'stable',
light: false,
feedBaseUrl: 'https://updates.example/hermes-desktop',
- shell: { openExternal: async () => { calls.push('openExternal') } },
+ installer: {
+ prepare: async () => { calls.push('prepare');
+
+ return 'update.appinstaller' },
+ open: async () => { calls.push('open');
+
+ return '' }
+ },
teardownBundledBackend: async () => { calls.push('teardown') },
emitUpdateProgress: () => {},
appVersion: '0.18.2',
@@ -38,7 +45,7 @@ describe('AppInstallerStrategy.apply', () => {
const result = await strategy.apply({})
expect(result).toEqual({ ok: true, manual: false, bundled: true, mechanism: 'app-installer' })
- expect(calls).toEqual(['relaunch-marker', 'teardown', 'openExternal', 'quit'])
+ expect(calls).toEqual(['prepare', 'relaunch-marker', 'teardown', 'open', 'quit'])
})
it('fails open: a marker-write failure never blocks the update', async () => {
@@ -55,6 +62,25 @@ describe('AppInstallerStrategy.apply', () => {
expect(progress.some(message => message.includes('Reopen Hermes'))).toBe(true)
})
+ it('uses the package registered source when no feed override is configured', async () => {
+ const prepared: string[] = []
+
+ const { deps, calls } = makeDeps({
+ feedBaseUrl: '',
+ run: async () => ({ code: 2, stdout: JSON.stringify({ available: true, source_uri: 'https://registered.example/channel.appinstaller' }) }),
+ installer: {
+ prepare: async url => { prepared.push(url);
+
+ return 'registered.appinstaller' },
+ open: async () => ''
+ }
+ })
+
+ expect((await new AppInstallerStrategy(deps).apply({})).manual).toBe(false)
+ expect(prepared).toEqual(['https://registered.example/channel.appinstaller'])
+ expect(calls).toEqual(['relaunch-marker', 'teardown', 'quit'])
+ })
+
it('no feed URL → manual card, no teardown, no quit', async () => {
const { deps, calls } = makeDeps({ feedBaseUrl: '' })
const result = await new AppInstallerStrategy(deps).apply({})
diff --git a/apps/desktop/electron/updater/app-installer.ts b/apps/desktop/electron/updater/app-installer.ts
index 17509d14f27..4fe5c5acbc6 100644
--- a/apps/desktop/electron/updater/app-installer.ts
+++ b/apps/desktop/electron/updater/app-installer.ts
@@ -5,7 +5,7 @@
// the OS checks it and swaps the package wholesale. The app's only jobs:
// check() ask the OS whether an update is available (via the bundled
// payload python's winrt), surfacing UNKNOWN honestly;
-// apply() run graceful teardown, trigger ms-appinstaller:, quit — and
+// apply() stage the descriptor, tear down, open it, and quit with
// a pending-relaunch marker so Hermes comes back by itself.
//
// Pure-injectable: the impure pieces (python runner, shell, quit, relaunch
@@ -13,6 +13,7 @@
import {
type AppInstallerCheck,
+ parseCheckOutput,
type PayloadPythonRunner,
triggerAppInstallerUpdate,
win32AppInstallerFeedPath
@@ -31,7 +32,7 @@ export interface AppInstallerStrategyDeps {
light: boolean
/** The App Installer feed base URL; empty when nothing configured it. */
feedBaseUrl: string
- shell: { openExternal: (url: string) => Promise<void> }
+ installer: { prepare: (url: string) => Promise<string>; open: (file: string) => Promise<string> }
/** Graceful backend teardown before the package swap. */
teardownBundledBackend: () => void | Promise<void>
/** Progress emitter for the updates overlay. */
@@ -85,8 +86,14 @@ export class AppInstallerStrategy {
async apply(_opts: { stopSafeBlockers?: boolean }): Promise<UpdaterApplyResultWire> {
const feedBaseUrl = this.deps.feedBaseUrl
+ let sourceUri: string | undefined
if (!feedBaseUrl) {
+ const { code, stdout } = await this.deps.run(this.deps.python, this.deps.script)
+ sourceUri = parseCheckOutput(code, stdout).sourceUri
+ }
+
+ if (!feedBaseUrl && !sourceUri) {
this.deps.emitUpdateProgress({
stage: 'manual',
message: 'bundled install: update by installing the new app release',
@@ -102,26 +109,24 @@ export class AppInstallerStrategy {
percent: 100
})
- // Unconditional relaunch: register the mechanism BEFORE the swap so
- // Hermes comes back on the new version with no user action. The
- // handshake is awaited so the app never quits into an unregistered
- // waiter (false = the waiter lost the race or failed to spawn; the
- // update proceeds and relaunch stays manual).
- const registered = await this.deps.registerPendingRelaunch(this.deps.appVersion)
-
- if (!registered) {
- this.deps.emitUpdateProgress({
- stage: 'restart', percent: 100,
- message: 'Automatic relaunch could not be registered. Reopen Hermes after App Installer finishes.'
- })
- }
-
await triggerAppInstallerUpdate(
feedBaseUrl,
this.deps.channel,
this.deps.light,
- this.deps.shell,
- this.deps.teardownBundledBackend
+ this.deps.installer,
+ async () => {
+ const registered = await this.deps.registerPendingRelaunch(this.deps.appVersion)
+
+ if (!registered) {
+ this.deps.emitUpdateProgress({
+ stage: 'restart', percent: 100,
+ message: 'Automatic relaunch could not be registered. Reopen Hermes after App Installer finishes.'
+ })
+ }
+
+ await this.deps.teardownBundledBackend()
+ },
+ sourceUri
)
this.deps.quit()
@@ -130,31 +135,7 @@ export class AppInstallerStrategy {
}
}
-/** Parse the payload-python checker's output into an AppInstallerCheck. */
-export function parseCheckOutput(code: number, stdout: string): AppInstallerCheck {
- const text = stdout.trim()
- let parsed: { available?: boolean | null; availability?: string; error?: string; reason?: string } | null = null
-
- try {
- parsed = text ? JSON.parse(text) : null
- } catch {
- parsed = null
- }
-
- if (parsed && typeof parsed.available === 'boolean') {
- return { available: parsed.available, availability: parsed.availability, error: parsed.error }
- }
-
- if (parsed && parsed.available === null) {
- return { available: null, error: parsed.error || 'checker returned unknown' }
- }
-
- if (code !== 0) {
- return { available: null, error: parsed?.error || `checker exited ${code}` }
- }
-
- return { available: null, error: 'checker returned no availability' }
-}
+export { parseCheckOutput }
export { win32AppInstallerFeedPath }
export type { AppInstallerCheck, PayloadPythonRunner }
diff --git a/apps/desktop/scripts/check-appinstaller-update.py b/apps/desktop/scripts/check-appinstaller-update.py
index 5fd8272c692..b37e87c626b 100644
--- a/apps/desktop/scripts/check-appinstaller-update.py
+++ b/apps/desktop/scripts/check-appinstaller-update.py
@@ -62,6 +62,8 @@ def main() -> int:
return 1
try:
+ source = package.get_app_installer_info()
+ source_uri = source.uri.absolute_uri if source is not None else None
result = package.check_update_availability_async().get()
availability = PackageUpdateAvailability(result.availability)
except Exception as exc: # noqa: BLE001
@@ -73,11 +75,11 @@ def main() -> int:
# them as such would suppress a real update prompt — so they surface as
# an unknown with the availability name as the extended error.
if availability == PackageUpdateAvailability.NO_UPDATES:
- print(json.dumps({"available": False, "availability": availability.name}))
+ print(json.dumps({"available": False, "availability": availability.name, "source_uri": source_uri}))
return 0
if availability in (PackageUpdateAvailability.AVAILABLE, PackageUpdateAvailability.REQUIRED):
- print(json.dumps({"available": True, "availability": availability.name}))
+ print(json.dumps({"available": True, "availability": availability.name, "source_uri": source_uri}))
return 2
print(json.dumps({"available": None, "error": f"availability unknown: {availability.name}"}))
diff --git a/tests/desktop/test_appinstaller_check_script.py b/tests/desktop/test_appinstaller_check_script.py
index 1f0e9873cd0..e155708132b 100644
--- a/tests/desktop/test_appinstaller_check_script.py
+++ b/tests/desktop/test_appinstaller_check_script.py
@@ -70,6 +70,9 @@ def _stub_module(*, identity_error: bool, availability: str | None, check_raises
get_body,
"",
"class _FakePackage:",
+ " def get_app_installer_info(self):",
+ " from types import SimpleNamespace",
+ " return SimpleNamespace(uri=SimpleNamespace(absolute_uri='https://registered.example/updates.appinstaller'))",
" def check_update_availability_async(self):",
check_body,
"",
@@ -132,6 +135,7 @@ def test_update_available_exit_2(tmp_path):
assert code == 2
assert payload["available"] is True
assert payload["availability"] == "AVAILABLE"
+ assert payload["source_uri"] == "https://registered.example/updates.appinstaller"
def test_no_update_exit_0(tmp_path):