The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): preserve MSIX runtime and add Store updates
ethernetf5981cbd14b6
diff --git a/apps/desktop/BUILDING.md b/apps/desktop/BUILDING.mdindex df126dac64b..826d4c730b2 100644--- a/apps/desktop/BUILDING.md+++ b/apps/desktop/BUILDING.md@@ -188,11 +188,25 @@ update. Apply downloads the descriptor before teardown, then opens the localThe app registers a detached relaunch waiter before handoff.The build stamp declares `updateMechanism`: `app-installer` for sideload bundles,-`external` for Store builds, `electron-updater` for macOS packages, and `self`-for source-built apps. The runtime does not infer Store ownership from Electron-flags or carry a second Store boolean. Windows Light declares `external` because-it has no bundled Python checker. Its OS-registered App Installer source still-owns automatic updates.+`microsoft-store` for Store builds, `electron-updater` for macOS packages, and+`self` for source-built apps. Settings shows Microsoft Store for a Store build.+The runtime does not infer Store ownership from Electron flags or carry a+second Store boolean. Windows Light declares `external` because it has no+bundled Python checker. Its OS-registered App Installer source still owns+automatic updates.++Store builds use `Windows.Services.Store.StoreContext` to check, download,+and request installation inside Hermes. The native consent UI attaches to the+current desktop window. Download finishes before backend shutdown; the existing+relaunch waiter is registered before the install request. Unknown checks,+cancellation and request failures do not count as successful updates. Native+acceptance requires a Store-acquired package or flight, not a sideloaded MSIX.++On Windows bundles, PM copies the verified pinned base Python to its writable+store for uv builds. The app and execution aliases retain their signed bundled+launchers and bundled Python, which load the selected dependency generation.+The new venv's generated console scripts must not replace those launchers:+out-of-package Python cannot launch the packaged tools.Sideload stable versions are `X.Y.Z.0`. Canary revisions derive from elapsedminutes after the stable baseline. The release script rejects ambiguous ordiff --git a/apps/desktop/electron/appinstaller-checker.test.ts b/apps/desktop/electron/appinstaller-checker.test.tsindex aa6fa38333d..4ee610e5529 100644--- a/apps/desktop/electron/appinstaller-checker.test.ts+++ b/apps/desktop/electron/appinstaller-checker.test.ts@@ -85,6 +85,29 @@ describe('runAppInstallerChecker', () => {expect(calls[0].options.timeout).toBe(50)})+ it('waits for confirmed child exit when the helper can install an update', async () => {+ vi.useFakeTimers()++ try {+ let callback: Callback | undefined+ const { impl } = stubExecFile(call => { callback = call.callback })+ let settled = false++ const pending = runAppInstallerChecker('python.exe', 'store.py', {+ execFileImpl: impl, timeoutMs: 50, waitForExit: true+ }).then(result => { settled = true;++ return result })++ await vi.advanceTimersByTimeAsync(100)+ expect(settled).toBe(false)+ callback!(Object.assign(new Error('killed'), { killed: true }), '', '')+ expect((await pending).code).toBe(1)+ } finally {+ vi.useRealTimers()+ }+ })+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' }), '', ''))@@ -118,6 +141,13 @@ describe('runAppInstallerChecker', () => {expect(JSON.parse(result.stdout)).toEqual({ available: null, error: 'bad arguments' })})+ 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])+ })+it('passes the caller env through (PYTHONPATH for the payload site-packages)', async () => {const { impl, calls } = stubExecFile(call => call.callback(null, '', ''))diff --git a/apps/desktop/electron/appinstaller-checker.ts b/apps/desktop/electron/appinstaller-checker.tsindex 70e093dda64..87ab932a505 100644--- a/apps/desktop/electron/appinstaller-checker.ts+++ b/apps/desktop/electron/appinstaller-checker.ts@@ -17,6 +17,9 @@ export const APPINSTALLER_CHECK_TIMEOUT_MS = 20_000export interface AppInstallerCheckerDeps {env?: NodeJS.ProcessEnvtimeoutMs?: number+ args?: readonly string[]+ /** Mutating helpers must exit before their caller can restore the backend. */+ waitForExit?: boolean/** Diagnostic sink for checker stderr; never breaks the result. */onStderr?: (text: string) => voidexecFileImpl?: ExecFileImpl@@ -69,14 +72,14 @@ export function runAppInstallerChecker(resolve(result)}- // The resolve deadline is independent of the callback below: if the- // killed child never emits 'close', this still fires at the deadline.- const deadline = setTimeout(() => finish(deadlineResult()), timeoutMs)+ // Reads can return unknown at the deadline. Store mutations must wait for+ // execFile's close callback after its timeout kill before recovery starts.+ const deadline = deps.waitForExit ? undefined : setTimeout(() => finish(deadlineResult()), timeoutMs)try {exec(python,- [script],+ [script, ...deps.args ?? []],{ encoding: 'utf8', timeout: timeoutMs, windowsHide: true, env: deps.env },(error, stdout, stderr) => {if (stderr) {diff --git a/apps/desktop/electron/install-stamp.ts b/apps/desktop/electron/install-stamp.tsindex 988c6046027..9c9f4c93427 100644--- a/apps/desktop/electron/install-stamp.ts+++ b/apps/desktop/electron/install-stamp.ts@@ -42,7 +42,7 @@ export interface InstallStamp {/** The steward of a sealed tree ('desktop-app' | 'docker' | 'nix'), when packaged. */distribution: string | null/** Who applies the next update. Required in every stamp. */- updateMechanism: 'self' | 'app-installer' | 'electron-updater' | 'external'+ updateMechanism: 'self' | 'app-installer' | 'electron-updater' | 'external' | 'microsoft-store'baseVersion: string | nulldisplayVersion: string | nulldistance: number | nulldiff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex f7f797b396e..4bded3df2d9 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -419,6 +419,7 @@ import { ExternalStrategy } from './updater/external'import { createMacStrategy } from './updater/mac-client'import { consumePendingRelaunch, registerUpdateRelaunch } from './updater/relaunch'import { startRelaunchWaiter } from './updater/relaunch-waiter'+import { createStoreStrategy } from './updater/store-client'import { isHermesOwnedVenvDaemon } from './venv-holder-select'import { fetchMarketplaceThemes, searchMarketplaceThemes } from './vscode-marketplace'import { createWakeIndicatorWindowController } from './wake-indicator-window'@@ -3026,10 +3027,7 @@ async function resolveHealedBranch(updateRoot, branch) {}async function checkUpdates() {- // A bundled install has no checkout to pull — resolve the updater- // mechanism once and delegate. Out-of-store MSIX asks the OS whether a- // newer package is on the registered .appinstaller source; Store installs- // report unsupported (the steward owns their update loop).+ // A packaged install delegates to the update owner named by its stamp.let strategy: UpdaterStrategy | null = nulltry {@@ -3215,6 +3213,33 @@ function resolvePackagedUpdateStrategy(): UpdaterStrategy | null {return packagedUpdateStrategy}+ if (mechanism === 'microsoft-store') {+ const payload = bundledPayload(process.resourcesPath)!+ packagedUpdateStrategy = createStoreStrategy({+ python: payload.storePython,+ script: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'check-store-update.py'),+ sitePackages: payload.sitePackages,+ env: process.env,+ windowHandle: () => (BrowserWindow.getFocusedWindow() ?? mainWindow)?.getNativeWindowHandle() ?? null,+ appVersion: app.getVersion(),+ teardown: teardownBundledBackend,+ restore: restoreBundledBackend,+ emitProgress: emitUpdateProgress,+ quit: () => app.quit(),+ registerPendingRelaunch: fromVersion => registerUpdateRelaunch(HERMES_HOME, fromVersion, {+ relaunch: () => startRelaunchWaiter({+ 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'),+ timeoutSeconds: 1860+ })+ })+ })++ return packagedUpdateStrategy+ }+return new ExternalStrategy()}@@ -17352,6 +17377,7 @@ function resolveHermesVersionInfo(version: string) {branch: stamp.branch,source: stamp.source ?? undefined,distribution: stamp.distribution ?? undefined,+ updateMechanism: stamp.updateMechanism,dirty: stamp.dirty}}diff --git a/apps/desktop/electron/updater/index.ts b/apps/desktop/electron/updater/index.tsindex 9b55473a09a..08ffdf9979d 100644--- a/apps/desktop/electron/updater/index.ts+++ b/apps/desktop/electron/updater/index.ts@@ -3,8 +3,8 @@// Every install shape updates through a different owner:// app-installer out-of-store MSIX on win32 — the OS App Installer owns// the apply (the .appinstaller feed registered at install).-// external Microsoft Store / steward-owned deployments — no in-app-// updater at all.+// microsoft-store StoreContext checks and requests the package update.+// external Steward-owned deployments with no in-app updater.// windows-handoff git checkout on win32 — detached updater binary or the// repo hand-off script owns the swap.// posix-handoff git checkout on macOS/Linux — the repo posix hand-off@@ -21,6 +21,7 @@ export type UpdaterMechanism =| 'app-installer'| 'electron-updater'| 'external'+ | 'microsoft-store'| 'windows-handoff'| 'posix-handoff'| 'manual'diff --git a/apps/desktop/electron/updater/store-client.test.ts b/apps/desktop/electron/updater/store-client.test.tsnew file mode 100644index 00000000000..267e31c53fc--- /dev/null+++ b/apps/desktop/electron/updater/store-client.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from 'vitest'++import { createStoreStrategy } from './store-client'++it('the production runner passes modes, full HWND and isolated payload imports', async () => {+ const calls: { python: string; args: readonly string[]; env?: NodeJS.ProcessEnv; timeout?: number; waitForExit?: boolean }[] = []+ const handle = Buffer.alloc(8)+ handle.writeBigUInt64LE(0x1234567887654321n)++ const strategy = createStoreStrategy({+ python: 'packaged-python.exe',+ script: 'check-store-update.py',+ sitePackages: 'payload-deps',+ env: { PYTHONHOME: 'foreign', VIRTUAL_ENV: 'foreign', PYTHONPATH: 'foreign' },+ windowHandle: () => handle,+ appVersion: '1.0.0',+ teardown: async () => {},+ restore: async () => {},+ quit: () => {},+ emitProgress: () => {},+ registerPendingRelaunch: async () => ({ automatic: true, cancel: async () => {} }),+ run: async (python, script, deps) => {+ calls.push({ python, args: [script, ...(deps.args ?? [])], env: deps.env, timeout: deps.timeoutMs, waitForExit: deps.waitForExit })++ return {+ code: deps.args?.includes('check') ? 2 : 0,+ stdout: JSON.stringify({ ok: true, available: true, packages: ['package-v2'] })+ }+ }+ })++ await strategy.check()+ await strategy.apply()+ expect(calls.map(call => call.args)).toEqual(+ ['check', 'download', 'install'].map(mode => [+ 'check-store-update.py',+ '--mode',+ mode,+ '--hwnd',+ '1311768467139281697'+ ])+ )+ 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)+ ).toBe(true)+ expect(calls[1].timeout).toBeGreaterThan(calls[0].timeout!)+ expect(calls.map(call => call.waitForExit)).toEqual([false, true, true])+})++describe('Store runner refuses unusable replies', () => {+ it.each([+ { code: 1, stdout: '{"ok":true,"available":false}' },+ { code: 0, stdout: '{"ok":true,"available":null}' },+ { code: 0, stdout: 'not-json' }+ ])('does not turn $stdout into a current-version verdict', async response => {+ const strategy = createStoreStrategy({+ python: 'python',+ script: 'checker',+ sitePackages: 'deps',+ env: {},+ windowHandle: () => Buffer.alloc(8, 1),+ appVersion: '1',+ teardown: async () => {},+ restore: async () => {},+ quit: () => {},+ emitProgress: () => {},+ registerPendingRelaunch: async () => ({ automatic: true, cancel: async () => {} }),+ run: async () => response+ })++ const status = await strategy.check()+ expect(status.error).toBeTruthy()+ expect(status.updateAvailable).toBe(false)+ await expect(strategy.apply()).rejects.toThrow()+ })+})diff --git a/apps/desktop/electron/updater/store-client.ts b/apps/desktop/electron/updater/store-client.tsnew file mode 100644index 00000000000..d2d38bd4cac--- /dev/null+++ b/apps/desktop/electron/updater/store-client.ts@@ -0,0 +1,83 @@+import { APPINSTALLER_CHECK_TIMEOUT_MS, runAppInstallerChecker } from '../appinstaller-checker'++import { type StoreResult, StoreStrategy, type StoreStrategyDeps } from './store'++export interface StoreClientDeps extends Omit<StoreStrategyDeps, 'run'> {+ python: string+ script: string+ sitePackages: string+ env: NodeJS.ProcessEnv+ windowHandle: () => Buffer | null+ run?: typeof runAppInstallerChecker+}++function parseResult(code: number, stdout: string): StoreResult {+ const unknown = (error: string): StoreResult => ({ available: null, packages: [], ok: false, error })+ let value: unknown++ try {+ value = JSON.parse(stdout)+ } catch {+ return unknown(`Microsoft Store returned invalid JSON (exit ${code})`)+ }++ if (!value || typeof value !== 'object') {+ return unknown('Microsoft Store returned no result')+ }++ const row = value as Partial<StoreResult>++ if (+ (code !== 0 && code !== 2) ||+ row.ok !== true ||+ typeof row.available !== 'boolean' ||+ !Array.isArray(row.packages) ||+ !row.packages.every(item => typeof item === 'string')+ ) {+ return unknown(typeof row.error === 'string' ? row.error : `Microsoft Store request failed (exit ${code})`)+ }++ return { ok: true, available: row.available, packages: row.packages }+}++export function createStoreStrategy(deps: StoreClientDeps): StoreStrategy {+ const run = deps.run ?? runAppInstallerChecker++ return new StoreStrategy({+ ...deps,+ run: async mode => {+ const env: NodeJS.ProcessEnv = { ...deps.env, PYTHONPATH: deps.sitePackages }+ delete env.PYTHONHOME+ delete env.VIRTUAL_ENV+ delete env.PYTHONEXECUTABLE+ delete env.__PYVENV_LAUNCHER__+ const handle = deps.windowHandle()++ if (mode !== 'check' && !handle) {+ throw new Error('A desktop window is required for Microsoft Store consent')+ }++ const args = ['--mode', mode]++ if (handle) {+ const hwnd = handle.length === 8 ? handle.readBigUInt64LE().toString() : handle.readUInt32LE().toString()+ args.push('--hwnd', hwnd)+ }++ const result = await run(deps.python, deps.script, {+ args,+ env,+ timeoutMs: mode === 'check' ? APPINSTALLER_CHECK_TIMEOUT_MS : 1_830_000,+ waitForExit: mode !== 'check'+ })++ if (mode !== 'check' && result.code !== 0) {+ const failed = parseResult(result.code, result.stdout)++ return { ...failed, ok: false, error: failed.error || `Microsoft Store ${mode} did not complete` }+ }++ return parseResult(result.code, result.stdout)+ }+ })+}diff --git a/apps/desktop/electron/updater/store.test.ts b/apps/desktop/electron/updater/store.test.tsnew file mode 100644index 00000000000..3ed532176f3--- /dev/null+++ b/apps/desktop/electron/updater/store.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest'++import { StoreStrategy, type StoreStrategyDeps } from './store'++function dependencies(failAt?: string): { deps: StoreStrategyDeps; calls: string[] } {+ const calls: string[] = []++ const record = async (name: string): Promise<void> => {+ calls.push(name)++ if (name === failAt) {+ throw new Error(`${name} failed`)+ }+ }++ return {+ calls,+ deps: {+ run: async mode => {+ await record(mode)++ return { available: true, packages: ['package-v2'], ok: true }+ },+ appVersion: '1.0.0',+ registerPendingRelaunch: async () => {+ await record('register')++ return { automatic: true, cancel: () => record('cancel') }+ },+ teardown: () => record('teardown'),+ restore: () => record('restore'),+ quit: () => {+ calls.push('quit')+ },+ emitProgress: () => {}+ }+ }+}++describe('Microsoft Store update lifecycle', () => {+ it('downloads before shutdown, owns relaunch before install, and keeps no-update non-destructive', async () => {+ const { deps, calls } = dependencies()+ const strategy = new StoreStrategy(deps)+ expect((await strategy.check()).updateAvailable).toBe(true)+ calls.length = 0+ expect(await strategy.apply()).toMatchObject({ ok: true, handedOff: true, mechanism: 'microsoft-store' })+ expect(calls).toEqual(['download', 'register', 'teardown', 'install', 'quit'])++ const idle = new StoreStrategy({ ...deps, run: async () => ({ available: false, packages: [], ok: true }) })+ calls.length = 0+ expect(await idle.apply()).toMatchObject({ ok: true, updateAvailable: false })+ expect(calls).toEqual([])+ })++ it.each(['download', 'register', 'teardown', 'install'])(+ 'a %s failure never quits and restores only after shutdown began',+ async failAt => {+ const { deps, calls } = dependencies(failAt)+ await expect(new StoreStrategy(deps).apply()).rejects.toThrow(`${failAt} failed`)+ expect(calls).not.toContain('quit')+ expect(calls.includes('restore')).toBe(['teardown', 'install'].includes(failAt))+ expect(calls.includes('cancel')).toBe(['teardown', 'install'].includes(failAt))+ }+ )++ it('refuses unknown availability and preserves cancellation plus restore errors', async () => {+ const { deps, calls } = dependencies('install')++ const unknown = new StoreStrategy({+ ...deps,+ run: async () => ({ available: null, packages: [], ok: false, error: 'not Store acquired' })+ })++ expect(await unknown.check()).toMatchObject({ error: 'not Store acquired', updateAvailable: false })+ await expect(unknown.apply()).rejects.toThrow('not Store acquired')+ expect(calls).toEqual([])++ const broken = new StoreStrategy({+ ...deps,+ registerPendingRelaunch: async () => ({+ automatic: true,+ cancel: async () => {+ throw new Error('cancel failed')+ }+ }),+ restore: async () => {+ throw new Error('restore failed')+ }+ })++ await expect(broken.apply()).rejects.toThrow('install failed; cancel failed; restore failed')+ })+})diff --git a/apps/desktop/electron/updater/store.ts b/apps/desktop/electron/updater/store.tsnew file mode 100644index 00000000000..48a3b7297e5--- /dev/null+++ b/apps/desktop/electron/updater/store.ts@@ -0,0 +1,102 @@+import type { RelaunchRegistration } from './relaunch'++import type { UpdaterApplyResultWire, UpdaterStatusWire, UpdaterStrategy } from './index'++export type StoreMode = 'check' | 'download' | 'install'++export interface StoreResult {+ available: boolean | null+ packages: string[]+ ok: boolean+ error?: string+}++export interface StoreStrategyDeps {+ run: (mode: StoreMode) => Promise<StoreResult>+ appVersion: string+ registerPendingRelaunch: (fromVersion: string) => Promise<RelaunchRegistration>+ teardown: () => Promise<void>+ restore: () => Promise<void>+ quit: () => void+ emitProgress: (progress: { stage: string; message: string; percent: number | null }) => void+}++export class StoreStrategy implements UpdaterStrategy {+ readonly mechanism = 'microsoft-store' as const++ constructor(private readonly deps: StoreStrategyDeps) {}++ async check(): Promise<UpdaterStatusWire> {+ const result = await this.deps.run('check')++ return {+ supported: true,+ mechanism: this.mechanism,+ currentVersion: this.deps.appVersion,+ updateAvailable: result.ok && result.available === true,+ error: result.ok && result.available !== null ? undefined : result.error || 'Microsoft Store check unavailable',+ fetchedAt: Date.now()+ }+ }++ async apply(): Promise<UpdaterApplyResultWire> {+ let registration: RelaunchRegistration | undefined+ let stopped = false++ try {+ this.deps.emitProgress({ stage: 'fetch', message: 'Downloading the update from Microsoft Store.', percent: null })+ const downloaded = await this.deps.run('download')++ if (!downloaded.ok || downloaded.available === null) {+ throw new Error(downloaded.error || 'Microsoft Store download did not complete')+ }++ if (!downloaded.available) {+ return { ok: true, updateAvailable: false, mechanism: this.mechanism }+ }++ registration = await this.deps.registerPendingRelaunch(this.deps.appVersion)++ if (!registration.automatic) {+ throw new Error('Could not register automatic relaunch for the Store update')+ }++ stopped = true+ await this.deps.teardown()+ this.deps.emitProgress({+ stage: 'restart',+ message: 'Microsoft Store is installing the update. Hermes will reopen.',+ percent: null+ })+ const installed = await this.deps.run('install')++ if (!installed.ok || installed.available !== true) {+ throw new Error(installed.error || 'Microsoft Store did not confirm installation')+ }++ this.deps.quit()++ return { ok: true, bundled: true, handedOff: true, mechanism: this.mechanism }+ } catch (error) {+ const errors: unknown[] = [error]++ try {+ await registration?.cancel()+ } catch (cancelError) {+ errors.push(cancelError)+ }++ if (stopped) {+ try {+ await this.deps.restore()+ } catch (restoreError) {+ errors.push(restoreError)+ }+ }++ const message = errors.map(item => (item instanceof Error ? item.message : String(item))).join('; ')+ this.deps.emitProgress({ stage: 'error', message, percent: null })+ throw errors.length > 1 ? new AggregateError(errors, message, { cause: error }) : error+ }+ }+}diff --git a/apps/desktop/electron/updater/updater.test.ts b/apps/desktop/electron/updater/updater.test.tsindex 6fd3ae19433..750f1ee302e 100644--- a/apps/desktop/electron/updater/updater.test.ts+++ b/apps/desktop/electron/updater/updater.test.ts@@ -21,7 +21,7 @@ describe('build stamp → update ownership', () => {it.each([['win32', 'bundled', 'app-installer', 'app-installer'],- ['win32', 'store', 'external', 'external'],+ ['win32', 'store', 'microsoft-store', 'microsoft-store'],['win32', 'light', 'external', 'external'],['darwin', 'bundled', 'electron-updater', 'electron-updater'],['darwin', 'light', 'electron-updater', 'electron-updater'],diff --git a/apps/desktop/scripts/check-store-update.py b/apps/desktop/scripts/check-store-update.pynew file mode 100644index 00000000000..2a8aa6f2a93--- /dev/null+++ b/apps/desktop/scripts/check-store-update.py@@ -0,0 +1,101 @@+#!/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.+"""+from __future__ import annotations++import argparse+import json+import os+import site+import sys+import time+++def perform(context, mode, wait, completed_state) -> dict:+ """Use the same update objects for the query and the requested operation."""+ updates = wait(context.get_app_and_optional_store_package_updates_async())+ packages = [update.package.id.full_name for update in updates]+ result = {"available": bool(updates), "packages": packages, "ok": True}+ if mode == "check" or not updates:+ return result+ request = {+ "download": context.request_download_store_package_updates_async,+ "install": context.request_download_and_install_store_package_updates_async,+ }[mode]+ outcome = wait(request(updates))+ if outcome.overall_state != completed_state:+ result.update(ok=False, error=f"Microsoft Store {mode}: {outcome.overall_state.name}")+ return result+++def _wait(operation):+ """Keep the STA responsive while Store displays consent and progress UI."""+ import win32con+ import win32event+ import win32gui+ from winrt.windows.foundation import AsyncStatus++ deadline = time.monotonic() + 1800+ while operation.status == AsyncStatus.STARTED:+ if time.monotonic() >= deadline:+ operation.cancel()+ raise TimeoutError("Microsoft Store request timed out")+ win32event.MsgWaitForMultipleObjects((), False, 50, win32con.QS_ALLINPUT)+ if win32gui.PumpWaitingMessages():+ operation.cancel()+ raise RuntimeError("Microsoft Store request was interrupted")+ return operation.get_results()+++def _execute(mode: str, window_handle: int | None) -> dict:+ from winrt.runtime.interop import initialize_with_window+ from winrt.windows.services.store import StoreContext, StorePackageUpdateState+ import winrt.windows.applicationmodel # noqa: F401 — projected Package values+ import winrt.windows.foundation.collections # noqa: F401 — projected sequence++ if mode != "check" and not window_handle:+ raise ValueError("A desktop window is required for Microsoft Store consent")+ context = StoreContext.get_default()+ if window_handle:+ initialize_with_window(context, window_handle)+ return perform(context, mode, _wait, StorePackageUpdateState.COMPLETED)+++def main(argv=None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--mode", choices=("check", "download", "install"), default="check")+ parser.add_argument("--hwnd", type=int)+ args = parser.parse_args(argv)+ # The packaged interpreter receives its dependencies through PYTHONPATH.+ # Process their .pth files so pywin32 can find its extensions and DLLs.+ for directory in os.environ.get("PYTHONPATH", "").split(os.pathsep):+ if directory:+ site.addsitedir(directory)+ try:+ from winrt.runtime import ApartmentType, init_apartment, uninit_apartment++ init_apartment(ApartmentType.SINGLE_THREADED)+ except Exception as exc:+ print(json.dumps({"available": None, "ok": False, "error": str(exc)}), flush=True)+ return 1+ try:+ try:+ result = _execute(args.mode, args.hwnd)+ except Exception as exc:+ # Missing Store acquisition is not evidence that the app is current.+ result = {"available": None, "ok": False, "error": f"Microsoft Store request failed: {exc}"}+ finally:+ # _execute's COM objects must be released before apartment shutdown.+ uninit_apartment()+ print(json.dumps(result), flush=True)+ if not result["ok"]:+ return 1+ return 2 if args.mode == "check" and result["available"] else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/apps/desktop/scripts/write-build-stamp.mjs b/apps/desktop/scripts/write-build-stamp.mjsindex f7b3d319535..fc4f42a33fa 100644--- a/apps/desktop/scripts/write-build-stamp.mjs+++ b/apps/desktop/scripts/write-build-stamp.mjs@@ -185,7 +185,7 @@ export function buildStampPayload(stamp, env = process.env, platform = process.pconst updateMechanism = {'': 'self',bootstrap: 'self',- store: 'external',+ store: 'microsoft-store',bundled: { win32: 'app-installer', darwin: 'electron-updater' }[platform] || 'external',light: platform === 'darwin' ? 'electron-updater' : 'external'}[variant]diff --git a/apps/desktop/scripts/write-build-stamp.test.mjs b/apps/desktop/scripts/write-build-stamp.test.mjsindex c9b27724416..8223fbe8d91 100644--- a/apps/desktop/scripts/write-build-stamp.test.mjs+++ b/apps/desktop/scripts/write-build-stamp.test.mjs@@ -131,10 +131,10 @@ test('buildStampPayload with bundled variant declares the App Installer owner',assert.equal(payload.tag, 'v0.27.1-canary.20260901072553')})-test('macOS bundles and Light declare app-owned updates, never Store builds', () => {+test('macOS bundles and Light declare app-owned updates; the win32 store variant is Store owned', () => {for (const variant of ['bundled', 'light', 'store']) {const stamp = buildStampPayload(baseStamp, { HERMES_DESKTOP_VARIANT: variant }, 'darwin', { runtime })- assert.equal(stamp.updateMechanism, variant === 'store' ? 'external' : 'electron-updater')+ assert.equal(stamp.updateMechanism, variant === 'store' ? 'microsoft-store' : 'electron-updater')}})diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsxindex 0dda3a8a904..9f8684855ad 100644--- a/apps/desktop/src/app/updates-overlay.tsx+++ b/apps/desktop/src/app/updates-overlay.tsx@@ -434,9 +434,9 @@ function ApplyingView({const { t } = useI18n()const u = t.updatesconst label = u.stages[apply.stage as DesktopUpdateStage] ?? u.stages.idle- const isAppInstaller = statusMechanism === 'app-installer'+ const isWindowsPackage = statusMechanism === 'app-installer' || statusMechanism === 'microsoft-store'- const body = isAppInstaller+ const body = isWindowsPackage? u.applyingBodyAppInstaller: isBackend? u.applyingBodyBackenddiff --git a/apps/desktop/src/components/version-details-store.test.tsx b/apps/desktop/src/components/version-details-store.test.tsxnew file mode 100644index 00000000000..cf97d709362--- /dev/null+++ b/apps/desktop/src/components/version-details-store.test.tsx@@ -0,0 +1,42 @@+import { cleanup, render, screen } from '@testing-library/react'+import { afterEach, describe, expect, it } from 'vitest'++import type { DesktopVersionInfo } from '@/global'+import { I18nProvider } from '@/i18n'++import { VersionDetails } from './version-details'++const baseVersion: DesktopVersionInfo = {+ appVersion: '0.19.0',+ electronVersion: '37.0.0',+ hermesRoot: '/tmp/hermes',+ nodeVersion: '22.0.0',+ platform: 'linux'+}++afterEach(cleanup)++describe('VersionDetails Store identity label', () => {+ it('labels a Store-identity build from the stamp mechanism, not windowsStore', () => {+ render(+ <I18nProvider configClient={null} initialLocale="en">+ <VersionDetails version={{ ...baseVersion, distribution: 'desktop-app', updateMechanism: 'microsoft-store' }} />+ </I18nProvider>+ )++ expect(screen.getByText('Distribution')).toBeTruthy()+ expect(screen.getByText('Microsoft Store')).toBeTruthy()+ expect(screen.queryByText('Desktop app (MSIX)')).toBeNull()+ })++ it('keeps the MSIX label for the out-of-store app-installer build', () => {+ render(+ <I18nProvider configClient={null} initialLocale="en">+ <VersionDetails version={{ ...baseVersion, distribution: 'desktop-app', updateMechanism: 'app-installer' }} />+ </I18nProvider>+ )++ expect(screen.getByText('Desktop app (MSIX)')).toBeTruthy()+ expect(screen.queryByText('Microsoft Store')).toBeNull()+ })+})diff --git a/apps/desktop/src/components/version-details.test.tsx b/apps/desktop/src/components/version-details.test.tsxindex 7aad9a45f0b..4b697f25631 100644--- a/apps/desktop/src/components/version-details.test.tsx+++ b/apps/desktop/src/components/version-details.test.tsx@@ -1,11 +1,37 @@-import { cleanup, render, screen } from '@testing-library/react'-import { afterEach, describe, expect, it } from 'vitest'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'import type { DesktopVersionInfo } from '@/global'import { I18nProvider } from '@/i18n'+import { $previewTabs, closeRightRail } from '@/store/preview'import { VersionDetails } from './version-details'+const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }+const initialHermesDesktop = desktopWindow.hermesDesktop++function installDesktopBridge() {+ const openExternal = vi.fn().mockResolvedValue(undefined)++ desktopWindow.hermesDesktop = {+ openExternal+ } as unknown as Window['hermesDesktop']++ return openExternal+}++afterEach(() => {+ cleanup()+ closeRightRail()+ vi.restoreAllMocks()++ if (initialHermesDesktop) {+ desktopWindow.hermesDesktop = initialHermesDesktop+ } else {+ delete desktopWindow.hermesDesktop+ }+})+const baseVersion: DesktopVersionInfo = {appVersion: '0.19.0',electronVersion: '37.0.0',@@ -14,8 +40,6 @@ const baseVersion: DesktopVersionInfo = {platform: 'linux'}-afterEach(cleanup)-describe('VersionDetails', () => {it('omits the branch suffix when no branch is present', () => {render(@@ -106,4 +130,23 @@ describe('VersionDetails', () => {expect(screen.getByText('Runtime')).toBeTruthy()expect(screen.getByText('External (uses the machine runtime)')).toBeTruthy()})++ it('opens the commit URL via the system-browser bridge without opening a preview tab', async () => {+ const openExternal = installDesktopBridge()++ render(+ <I18nProvider configClient={null} initialLocale="en">+ <VersionDetails version={{ ...baseVersion, commit: 'd233b6d7a9c5b79288e48dfb3b29e2ead106ac73' }} />+ </I18nProvider>+ )++ fireEvent.click(screen.getByText('d233b6d7a9c5b7'))++ await waitFor(() => {+ expect(openExternal).toHaveBeenCalledWith(+ 'https://github.com/NousResearch/hermes-agent/commit/d233b6d7a9c5b79288e48dfb3b29e2ead106ac73'+ )+ })+ expect($previewTabs.get()).toHaveLength(0)+ })})diff --git a/apps/desktop/src/components/version-details.tsx b/apps/desktop/src/components/version-details.tsxindex 49b2de22fa9..6d4d8660717 100644--- a/apps/desktop/src/components/version-details.tsx+++ b/apps/desktop/src/components/version-details.tsx@@ -26,14 +26,17 @@ export function VersionDetails({ version }: { version: DesktopVersionInfo }) {const source =version.source === 'ci' ? 'CI' : version.source ? version.source[0].toUpperCase() + version.source.slice(1) : null+ // The stamp distinguishes Store builds from sideloaded MSIX builds.const distribution =version.distribution === 'nix'? 'Nix': version.distribution === 'docker'? 'Docker'- : version.distribution === 'desktop-app'- ? u.versionDetailsDistributionDesktop- : null+ : version.updateMechanism === 'microsoft-store'+ ? u.versionDetailsDistributionStore+ : version.distribution === 'desktop-app'+ ? u.versionDetailsDistributionDesktop+ : nullconst runtime =version.hermesRuntime?.type === 'embedded'@@ -60,6 +63,7 @@ export function VersionDetails({ version }: { version: DesktopVersionInfo }) {<ExternalLinkclassName="break-all font-mono text-xs"href={`https://github.com/NousResearch/hermes-agent/commit/${version.commit}`}+ native>{version.commit.slice(0, 14)}</ExternalLink>diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 17143e4fb8f..76d24256110 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -648,6 +648,10 @@ export interface DesktopVersionInfo {dirty?: booleansource?: 'build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown'distribution?: 'desktop-app' | 'docker' | 'nix'+ /** Who applies the next update (from the stamp). Names the Store on a+ * Store-identity build — the Settings label keys off this, never+ * process.windowsStore (which also matches sideloaded MSIX). */+ updateMechanism?: 'self' | 'app-installer' | 'electron-updater' | 'external' | 'microsoft-store'/** sha16 of the canonical install-root path — the per-install channel key and* the shape `hermes update --install-id` prints. */installId?: string@@ -715,6 +719,7 @@ export type UpdaterMechanismClient =| 'app-installer'| 'electron-updater'| 'external'+ | 'microsoft-store'| 'windows-handoff'| 'posix-handoff'| 'manual'@@ -768,6 +773,8 @@ export interface DesktopUpdateApplyOptions {export interface DesktopUpdateApplyResult {ok: boolean+ /** False when the apply-time check found nothing to install. */+ updateAvailable?: booleanbranch?: stringerror?: stringmessage?: stringdiff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex e098173fea8..c5eda257258 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2180,6 +2180,7 @@ export const ar = defineLocale({versionDetailsBuildOrigin: 'مصدر البناء',versionDetailsDistribution: 'التوزيع',versionDetailsDistributionDesktop: 'تطبيق سطح المكتب',+ versionDetailsDistributionStore: 'Microsoft Store',versionDetailsRuntimeEmbedded: 'وقت تشغيل مضمّن',versionDetailsRuntimeExternal: 'خارجي (يستخدم وقت تشغيل الجهاز)',versionDetailsRuntime: 'وقت التشغيل',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 1f424867a43..b825f8aef1c 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3009,6 +3009,7 @@ export const en: Translations = {versionDetailsBuildOrigin: 'Build Origin',versionDetailsDistribution: 'Distribution',versionDetailsDistributionDesktop: 'Desktop app (MSIX)',+ versionDetailsDistributionStore: 'Microsoft Store',versionDetailsRuntime: 'Runtime',versionDetailsRuntimeEmbedded: 'Embedded runtime',versionDetailsRuntimeExternal: 'External (uses the machine runtime)',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 717330c3a6f..e0084f9f243 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2505,6 +2505,7 @@ export const ja = defineLocale({unsupportedMessage: 'このバージョンの Hermes はアプリ内から自分を更新できません。',connectionRetry: '接続を確認してもう一度試してください。',latestBody: '最新バージョンを実行しています。',+ versionDetailsDistributionStore: 'Microsoft Store',latestBodyBackend: 'バックエンドは最新バージョンを実行しています。',allSetTitle: '準備完了',availableTitle: '新しい更新が利用可能',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 7aba670bb5a..cca668c26d6 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -2891,6 +2891,7 @@ export const ru = defineLocale({unsupportedMessage: 'Эта версия Hermes не может обновлять себя из приложения.',connectionRetry: 'Проверьте соединение и попробуйте снова.',latestBody: 'У вас последняя версия.',+ versionDetailsDistributionStore: 'Microsoft Store',latestBodyBackend: 'Бэкенд работает на последней версии.',allSetTitle: 'Всё готово',availableTitle: 'Доступно новое обновление',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex acc4662de82..6ed338cac89 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2578,6 +2578,7 @@ export interface Translations {versionDetailsBuildOrigin: stringversionDetailsDistribution: stringversionDetailsDistributionDesktop: string+ versionDetailsDistributionStore: stringversionDetailsRuntime: stringversionDetailsRuntimeEmbedded: stringversionDetailsRuntimeExternal: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 10a42042c14..edfa05c6bed 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -2423,6 +2423,7 @@ export const zhHant = defineLocale({unsupportedMessage: '此版本的 Hermes 無法在應用程式內自行更新。',connectionRetry: '請檢查網路連線後重試。',latestBody: '您正在執行最新版本。',+ versionDetailsDistributionStore: 'Microsoft Store',latestBodyBackend: '後端正在執行最新版本。',allSetTitle: '已是最新版本',availableTitle: '有可用更新',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 899bb97cc64..376e1cde908 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3164,6 +3164,7 @@ export const zh: Translations = {versionDetailsBuildOrigin: '构建来源',versionDetailsDistribution: '发行版',versionDetailsDistributionDesktop: '桌面应用 (MSIX)',+ versionDetailsDistributionStore: 'Microsoft Store',versionDetailsRuntime: '运行时',versionDetailsRuntimeEmbedded: '嵌入式(捆绑)',versionDetailsRuntimeExternal: '外部',diff --git a/apps/desktop/src/lib/update-copy.test.ts b/apps/desktop/src/lib/update-copy.test.tsindex cd066756ff0..1eef990e245 100644--- a/apps/desktop/src/lib/update-copy.test.ts+++ b/apps/desktop/src/lib/update-copy.test.ts@@ -56,8 +56,8 @@ describe('resolveUpdateCopy', () => {expect(r.body).toBe(copy.availableBody)})- it('app-installer mechanism uses the Windows-finishes-it body, not commit vocabulary', () => {- const r = resolveUpdateCopy({ target: 'client', shownItems: 5, mechanism: 'app-installer', copy })+ it.each(['app-installer', 'microsoft-store'] as const)('%s uses Windows update copy without commit vocabulary', mechanism => {+ const r = resolveUpdateCopy({ target: 'client', shownItems: 5, mechanism, copy })expect(r.body).toBe(copy.availableBodyAppInstaller)})diff --git a/apps/desktop/src/lib/update-copy.ts b/apps/desktop/src/lib/update-copy.tsindex 01536d4bfb4..532461aee38 100644--- a/apps/desktop/src/lib/update-copy.ts+++ b/apps/desktop/src/lib/update-copy.ts@@ -40,7 +40,7 @@ export interface ResolveUpdateCopyInput {* 'app-installer': the OS App Installer owns the apply (out-of-store MSIX)* — the body names Windows as the finisher, never commit vocabulary.*/- mechanism?: 'app-installer' | 'electron-updater' | 'external' | 'windows-handoff' | 'posix-handoff' | 'manual'+ mechanism?: 'app-installer' | 'electron-updater' | 'external' | 'microsoft-store' | 'windows-handoff' | 'posix-handoff' | 'manual'copy: UpdateCopyStrings}@@ -62,7 +62,7 @@ export function resolveUpdateCopy({// App-installer: the OS owns the apply, and there is no commit list by// construction (the OS checker answers yes/no). Name Windows as the// finisher; the tag is named when known.- if (mechanism === 'app-installer') {+ if (mechanism === 'app-installer' || mechanism === 'microsoft-store') {return { title, body: latestTag ? copy.availableBodyRelease(latestTag) : copy.availableBodyAppInstaller }}diff --git a/apps/desktop/src/store/updates.test.ts b/apps/desktop/src/store/updates.test.tsindex bebcdfe7e4a..a1dd0d097aa 100644--- a/apps/desktop/src/store/updates.test.ts+++ b/apps/desktop/src/store/updates.test.ts@@ -211,6 +211,14 @@ describe('maybeNotifyUpdateAvailable', () => {expect(notifySpy).toHaveBeenCalledTimes(1)})+ it('notifies for a Store update without a commit and never for an unknown check', () => {+ maybeNotifyUpdateAvailable(status({ mechanism: 'microsoft-store', targetSha: undefined, behind: null, updateAvailable: true }))+ expect(notifySpy).toHaveBeenCalledTimes(1)+ notifySpy.mockClear()+ maybeNotifyUpdateAvailable(status({ mechanism: 'microsoft-store', targetSha: undefined, behind: null, updateAvailable: false, error: 'Store unavailable' }))+ expect(notifySpy).not.toHaveBeenCalled()+ })+it('does nothing when already up to date', () => {maybeNotifyUpdateAvailable(status({ behind: 0 }))expect(notifySpy).not.toHaveBeenCalled()@@ -888,6 +896,14 @@ describe('applyUpdates terminal state', () => {expect(notifySpy).not.toHaveBeenCalled()})+ it('does not claim an installation when the Store reports no remaining update', async () => {+ applyMock.mockResolvedValue({ ok: true, updateAvailable: false })+ await applyUpdates()+ expect($updateApply.get().applying).toBe(false)+ expect($updateOverlayOpen.get()).toBe(false)+ expect(notifySpy).not.toHaveBeenCalled()+ })+it('closes the overlay + toasts when updated but not relaunched in place', async () => {// The Linux AppImage / dev-run path: backend + GUI updated, no in-place// relaunch. Must not strand the overlay on a closeless spinner.diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.tsindex 4edecad25ba..58f9eb6a012 100644--- a/apps/desktop/src/store/updates.ts+++ b/apps/desktop/src/store/updates.ts@@ -218,12 +218,9 @@ export function maybeNotifyUpdateAvailable(status: DesktopUpdateStatus | null, treturn}- // Eligibility is mechanism-specific: a git-style check proves an update is- // waiting by naming the target commit (targetSha). An App Installer check- // legitimately has no commit identity — the OS reports availability against- // the .appinstaller feed — so its eligibility signal is updateAvailable- // itself. Never fabricate a SHA to satisfy the key.- const hasTargetIdentity = Boolean(status.targetSha) || status.mechanism === 'app-installer'+ // The package update owner reports availability without a commit SHA.+ // Git checks must still identify their target commit.+ const hasTargetIdentity = Boolean(status.targetSha) || status.mechanism === 'app-installer' || status.mechanism === 'microsoft-store'if (!hasTargetIdentity) {return@@ -535,6 +532,8 @@ export async function applyUpdates(opts: DesktopUpdateApplyOptions = {}): Promis// rather than stranding them on an un-closeable spinner.setUpdateOverlayOpen(false)resetUpdateApplyState()++ if (result.updateAvailable === false) { return result }notify({durationMs: 8000,id: UPDATE_TOAST_ID,diff --git a/docs/shared-bundle-builds.md b/docs/shared-bundle-builds.mdindex d959b9aa9bc..ea64d97c1f6 100644--- a/docs/shared-bundle-builds.md+++ b/docs/shared-bundle-builds.md@@ -25,7 +25,7 @@ publishing their relative paths in the payload manifest. The desktop buildbakes this launch contract into its stamp. Electron uses the declared pathswithout payload probes, adoption, or repair. Non-bundled builds carry noplaceholder payload. The stamp also declares the update mechanism. Store-packages use `external`, and sideload bundles use `app-installer`. The runtime+packages use `microsoft-store`, and sideload bundles use `app-installer`. The runtimehas no separate Store probe or compatibility fallback.The MSIX hook reads the declared launcher namesrather than carrying a second entrypoint list. POSIX launchers followdiff --git a/hermes_cli/steward.py b/hermes_cli/steward.pyindex 2ca9e4ed7e0..aad8e175b87 100644--- a/hermes_cli/steward.py+++ b/hermes_cli/steward.py@@ -25,7 +25,7 @@ from pathlib import Pathfrom typing import OptionalBUILD_INFO_NAME = "install-stamp.json"-UPDATE_MECHANISMS = ("self", "app-installer", "electron-updater", "external")+UPDATE_MECHANISMS = ("self", "app-installer", "electron-updater", "external", "microsoft-store")STEWARD_DESKTOP = "desktop-app"STEWARD_DOCKER = "docker"diff --git a/hermes_cli/update_channel.py b/hermes_cli/update_channel.pyindex febfa3d2118..eddeacf68bf 100644--- a/hermes_cli/update_channel.py+++ b/hermes_cli/update_channel.py@@ -134,7 +134,7 @@ def default_channel(project_root: Optional[Path] = None) -> str:"""root = Path(project_root) if project_root is not None else _default_root()stamp = _read_stamp(root)- if stamp.get("updateMechanism") not in ("electron-updater", "app-installer"):+ if stamp.get("updateMechanism") not in ("electron-updater", "app-installer", "microsoft-store"):return CHANNEL_MAINreturn CHANNEL_CANARY if is_canary_tag(stamp.get("tag")) else CHANNEL_STABLE@@ -160,7 +160,7 @@ def resolve_update_channel(if channel == CHANNEL_CANARY:root = Path(project_root) if project_root is not None else _default_root()- if _read_stamp(root).get("updateMechanism") not in ("electron-updater", "app-installer"):+ if _read_stamp(root).get("updateMechanism") not in ("electron-updater", "app-installer", "microsoft-store"):# canary→main normalization for source installs.return CHANNEL_MAINreturn channel@@ -180,8 +180,8 @@ def set_install_channel() -> str:"""Persist ``channel`` for THIS install in config.yaml. Returns the id.- Refuses on ``external`` and ``app-installer`` mechanisms: their update- source belongs to the OS or package owner, not this configuration.+ Refuses when the update source belongs to the OS or package owner,+ including Microsoft Store, rather than this configuration.Raises ``ValueError`` for an invalid channel or an OS-owned install."""channel = (channel or "").strip().lower()@@ -192,7 +192,7 @@ def set_install_channel(root = Path(project_root) if project_root is not None else _default_root()stamp = _read_stamp(root)- if stamp.get("updateMechanism") in ("external", "app-installer"):+ if stamp.get("updateMechanism") in ("external", "app-installer", "microsoft-store"):distribution = stamp.get("distribution") or "an external steward"raise ValueError(f"channels don't apply here; updates are owned by {distribution}"diff --git a/pm/ensure.py b/pm/ensure.pyindex 5d96697337f..94df354fc79 100644--- a/pm/ensure.py+++ b/pm/ensure.py@@ -46,11 +46,12 @@ def _store() -> Store:def _installed_location(package: Package, lockfile: Lockfile, target: str, *,- verify: bool = False, allow_outdated: bool = False):+ verify: bool = False, allow_outdated: bool = False,+ roots: tuple[Path, ...] | None = None):"""Prefer the current pin. An explicit read may retain a prior PM install."""- roots = dict.fromkeys([paths.store_root(), paths.writable_store_root()])+ search_roots = dict.fromkeys(roots if roots is not None else (paths.store_root(), paths.writable_store_root()))fallback = None- for root in roots:+ for root in search_roots:store = Store(root)facts = _facts() if root == paths.store_root() else Facts(root / "facts.json")fact = facts.get(package.name)@@ -216,6 +217,8 @@ def _install(progress=None,pause_event: threading.Event | None = None,download_progress: ProgressFn | None = None,+ *,+ copy_from: tuple[Facts, Store] | None = None,) -> None:version = lockfile.version(package.name)if version is None:@@ -267,24 +270,35 @@ def _install(if download_progress is not None:download_progress(done, total, ranges)- archives = store.fetch_many(artifacts, scratch, progress=tick, pause_event=pause_event)- for index, archive in enumerate(archives):- if pause_event is not None and pause_event.is_set():- raise DownloadPaused("install paused")- label = f"{index + 1}/{len(artifacts)}" if len(artifacts) > 1 else ""- if progress is not None:- progress("unpack", 0, 0, label)- if index == 0:- package.unpack(archive, staged, target)- continue- # unpack() empties its destination; merge additional- # archives only after extracting them separately.- extra = scratch / f"extra-{index}"- package.unpack(archive, extra, target)- merge_tree(extra, staged)+ if copy_from is not None:+ source_facts, source_store = copy_from+ source = source_facts.get(package.name)+ if (not source_facts.installed(package.name, version, source_store.root,+ _identity(lockfile, package.name, target))+ or not _entry_verified(package, source, source_store, target)):+ raise InstallError(package.name, "bundled copy source failed verification")+ shutil.copytree(source_store.entry(source["entry"]), staged, symlinks=True)+ if tree_digest(staged) != source["digest"]:+ raise InstallError(package.name, "copied bytes do not match the bundled source")+ else:+ archives = store.fetch_many(artifacts, scratch, progress=tick, pause_event=pause_event)+ for index, archive in enumerate(archives):+ if pause_event is not None and pause_event.is_set():+ raise DownloadPaused("install paused")+ label = f"{index + 1}/{len(artifacts)}" if len(artifacts) > 1 else ""+ if progress is not None:+ progress("unpack", 0, 0, label)+ if index == 0:+ package.unpack(archive, staged, target)+ continue+ # unpack() empties its destination; merge additional+ # archives only after extracting them separately.+ extra = scratch / f"extra-{index}"+ package.unpack(archive, extra, target)+ merge_tree(extra, staged)+ package.stage(store, staged, version, target)if pause_event is not None and pause_event.is_set():raise DownloadPaused("install paused")- package.stage(store, staged, version, target)if progress is not None:progress("verify", 0, 0, "")reason = package.verify(staged, target)@@ -784,6 +798,22 @@ def uv(command: str = "uv", *, venv=None, realize: bool = True, explicit: bool =location = _installed_location(package, lockfile, target)if location is None:return None, env+ if name == "python" and target.startswith("win32") and sealed():+ # uv creates redirectors outside the MSIX. Their Python must also+ # live outside it; the app keeps its original packaged interpreter.+ writable = paths.writable_store_root()+ if location[1].root != writable:+ copied = _installed_location(package, lockfile, target, verify=explicit, roots=(writable,))+ if copied is None:+ if not realize:+ return None, env+ if not explicit and not lazy_installs_allowed():+ raise _refuse_lazy(name, "a writable Python is required for bundled uv builds")+ copy_store = Store(writable)+ copy_facts = Facts(writable / "facts.json")+ _install(package, lockfile, copy_facts, copy_store, target, copy_from=location)+ copied = copy_facts, copy_store+ location = copiedfacts, store = locationbinary = package.binary(store.entry(facts.get(name)["entry"]), target)if name == "uv" and binary is not None:diff --git a/pyproject.toml b/pyproject.tomlindex f17f9c3b9db..9f4b17a7fc3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -154,6 +154,9 @@ dependencies = [# supplies the URI and async result types projected when the checker runs."winrt-windows-applicationmodel>=3.2.1,<4; sys_platform == 'win32'","winrt-windows-foundation>=3.2.1,<4; sys_platform == 'win32'",+ # Store update queries and request results project collection interfaces.+ "winrt-windows-foundation-collections>=3.2.1,<4; sys_platform == 'win32'",+ "winrt-windows-services-store>=3.2.1,<4; sys_platform == 'win32'",# Image resize recovery for the vision tools. Pillow shrinks oversized images# (>5 MB or >8000px) at embed time; without it the byte AND pixel-dimension# shrink paths no-op, so an oversized image bakes into immutable history anddiff --git a/tests/desktop/test_check_store_update.py b/tests/desktop/test_check_store_update.pynew file mode 100644index 00000000000..fb02a6ca978--- /dev/null+++ b/tests/desktop/test_check_store_update.py@@ -0,0 +1,103 @@+"""Store update contracts use the actual API's sequence and result shapes."""+from __future__ import annotations++import importlib.util+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"+++class State(IntEnum):+ DOWNLOADING = 1+ COMPLETED = 3+ CANCELED = 4+ OTHER_ERROR = 5+++class Operation:+ def __init__(self, result):+ self.result = result+ self.progress = None+++class Context:+ def __init__(self, updates, state=State.COMPLETED):+ self.updates = updates+ self.state = state+ self.calls = []++ def get_app_and_optional_store_package_updates_async(self):+ self.calls.append("check")+ return Operation(self.updates)++ def request_download_store_package_updates_async(self, updates):+ assert updates is self.updates+ self.calls.append("download")+ return Operation(SimpleNamespace(overall_state=self.state))++ def request_download_and_install_store_package_updates_async(self, updates):+ assert updates is self.updates+ self.calls.append("install")+ return Operation(SimpleNamespace(overall_state=self.state))+++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++[email protected]("mode", ["check", "download", "install"])[email protected]("state", [State.COMPLETED, State.CANCELED, State.DOWNLOADING])+def test_store_operation_passes_update_sequence_and_requires_completed(checker, mode, state):+ updates = [SimpleNamespace(package=SimpleNamespace(id=SimpleNamespace(full_name="package-v2")))]+ context = Context(updates, state)+ result = checker.perform(context, mode, lambda operation: operation.result, State.COMPLETED)+ assert context.calls == (["check"] if mode == "check" else ["check", mode])+ assert result["available"] is True+ assert result["packages"] == ["package-v2"]+ if mode != "check":+ assert result["ok"] is (state == State.COMPLETED)+ assert ("error" in result) is (state != State.COMPLETED)+ empty = Context([])+ assert checker.perform(empty, mode, lambda operation: operation.result, State.COMPLETED) == {+ "available": False, "packages": [], "ok": True,+ }+ assert empty.calls == ["check"]++[email protected]("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; "+ "from winrt.windows.services.store import StoreContext,StorePackageUpdateState; "+ "from winrt.windows.foundation import IAsyncOperation, IAsyncOperationWithProgress; "+ "import winrt.windows.foundation.collections,win32gui; "+ "init_apartment(ApartmentType.SINGLE_THREADED); "+ "c=StoreContext.get_default(); "+ "assert callable(c.get_app_and_optional_store_package_updates_async); "+ "assert callable(c.request_download_store_package_updates_async); "+ "assert callable(c.request_download_and_install_store_package_updates_async); "+ "assert callable(initialize_with_window); "+ "assert StorePackageUpdateState.COMPLETED != StorePackageUpdateState.DOWNLOADING; "+ "assert callable(IAsyncOperation.get); "+ "assert callable(IAsyncOperationWithProgress.get); "+ "op=c.get_app_and_optional_store_package_updates_async(); "+ "assert callable(op.get_results); op.cancel(); del op; "+ "assert callable(win32gui.PumpWaitingMessages); "+ "del c; uninit_apartment(); print('store projection ready')"+ )+ result = subprocess.run([sys.executable, "-I", "-c", code], cwd=tmp_path,+ capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == "store projection ready"diff --git a/tests/hermes_cli/test_update_channel.py b/tests/hermes_cli/test_update_channel.pyindex fc462a8d6ed..3a5ea656180 100644--- a/tests/hermes_cli/test_update_channel.py+++ b/tests/hermes_cli/test_update_channel.py@@ -98,7 +98,7 @@ class TestResolve:assert resolve_update_channel({}, source) == CHANNEL_MAINassert resolve_update_channel({}, bundle) == CHANNEL_STABLE- @pytest.mark.parametrize("mechanism", ["electron-updater", "app-installer"])+ @pytest.mark.parametrize("mechanism", ["electron-updater", "app-installer", "microsoft-store"])def test_canary_artifact_defaults_to_its_own_feed(self, tmp_path, mechanism):"""A canary bundle with no per-install record tracks canary.@@ -226,7 +226,7 @@ class TestSetChannel:assert written["model"] == {"provider": "nous"}assert written["update"]["installs"][install_id(root)]["channel"] == "stable"- @pytest.mark.parametrize("mechanism", ["external", "app-installer"])+ @pytest.mark.parametrize("mechanism", ["external", "app-installer", "microsoft-store"])def test_os_owned_mechanism_refuses_channel_writes(self, tmp_path, monkeypatch, mechanism):self._home(tmp_path, monkeypatch)root = tmp_path / "os-owned-tree"diff --git a/tests/pm/test_uv_python.py b/tests/pm/test_uv_python.pyindex 077983aecf6..6b8566d722b 100644--- a/tests/pm/test_uv_python.py+++ b/tests/pm/test_uv_python.py@@ -126,3 +126,121 @@ def test_uv_refuses_discovery_when_pm_python_is_missing(installed_uv, monkeypatcensure.uv()assert facts.path.read_bytes() == recordedassert not list(entry.iterdir())++[email protected]("windows")+def test_bundled_uv_uses_a_verified_writable_python_without_changing_runtime(installed_uv, monkeypatch):+ import pm.paths as paths+ import pm.registry as registry+ from pm.store import Store, tree_digest++ root, uv_binary, facts, target, digest = installed_uv+ ensure = importlib.import_module("pm.ensure")+ shipped = uv_binary.parent.parent+ writable = root / "writable-tools"+ monkeypatch.setattr(paths, "writable_store_root", lambda: writable)+ (shipped.parent / "manifest.json").write_text("{}", encoding="utf-8")++ class FixturePython(Python):+ def verify(self, entry, target):+ return "" if self.binary(entry, target).read_bytes() == b"pinned interpreter" else "damaged Python"++ class FixtureUv(Uv):+ emulated_arch_targets = {target}++ monkeypatch.setitem(registry._packages, "uv", FixtureUv())+ facts.record("uv", "test", uv_binary.parent.name, {}, shipped,+ target=target, artifacts=[digest], digest=tree_digest(uv_binary.parent))+ python = FixturePython()+ monkeypatch.setitem(registry._packages, "python", python)+ entry = shipped / python.store_entry("test", target)+ entry.mkdir()+ binary = entry / "python.exe"+ binary.write_bytes(b"pinned interpreter")+ (entry / "python.dll").write_bytes(b"pinned runtime")+ facts.record("python", "test", entry.name, python.env(entry, target), shipped,+ target=target, artifacts=[digest], digest=tree_digest(entry))+ before = facts.path.read_bytes()+ shipped_digest = tree_digest(entry)+ monkeypatch.setattr(ensure, "lazy_installs_allowed", lambda: False)++ def no_download(*args, **kwargs):+ raise AssertionError("the verified Python must be copied without downloading")++ monkeypatch.setattr(Store, "fetch_many", no_download)+ assert ensure.uv(realize=False)[0] is None+ assert not writable.exists()+ with pytest.raises(InstallError, match="lazy installs are disabled"):+ ensure.uv()+ assert not writable.exists()++ resolved_uv, env = ensure.uv(explicit=True)+ copied = writable / entry.name+ assert resolved_uv == str(uv_binary)+ assert env["UV_PYTHON"] == str(copied / "python.exe")+ assert tree_digest(copied) == shipped_digest+ copied_fact = Facts(writable / "facts.json").get("python")+ assert copied_fact["digest"] == shipped_digest+ assert copied_fact["artifacts"] == [digest]+ assert copied_fact["target"] == target+ assert ensure.installed_package("python").binary == binary+ assert str(copied) not in ensure.env_for("python")["PATH"]++ def no_copy(*args, **kwargs):+ raise AssertionError("a matching copy must be reused")++ with monkeypatch.context() as reuse:+ reuse.setattr(shutil, "copytree", no_copy)+ assert ensure.uv(realize=False)[1]["UV_PYTHON"] == env["UV_PYTHON"]+ assert ensure.uv()[1]["UV_PYTHON"] == env["UV_PYTHON"]++ assert facts.path.read_bytes() == before+ assert tree_digest(entry) == shipped_digest++[email protected]("windows")[email protected]("damage", ["source", "copy", "publication"])+def test_copy_failure_preserves_previous_python(installed_uv, monkeypatch, damage):+ import pm.registry as registry+ from pm.store import Store, tree_digest++ root, _, facts, target, digest = installed_uv+ ensure = importlib.import_module("pm.ensure")+ shipped = facts.path.parent+ writable = root / "writable-tools"+ writable.mkdir()+ python = Python()+ monkeypatch.setattr(python, "verify", lambda *_: "")+ monkeypatch.setitem(registry._packages, "python", python)+ entry_name = python.store_entry("test", target)+ source = shipped / entry_name+ source.mkdir()+ (source / "python.exe").write_bytes(b"new interpreter")+ facts.record("python", "test", entry_name, {}, shipped,+ target=target, artifacts=[digest], digest=tree_digest(source))+ previous = writable / entry_name+ previous.mkdir()+ (previous / "python.exe").write_bytes(b"previous interpreter")+ previous_facts = Facts(writable / "facts.json")+ previous_facts.record("python", "previous", entry_name, {}, writable,+ target=target, artifacts=[digest], digest=tree_digest(previous))+ before = previous_facts.path.read_bytes()+ copytree = shutil.copytree++ if damage == "source":+ (source / "python.exe").write_bytes(b"damaged source")+ elif damage == "copy":+ def damaged_copy(src, dest, **kwargs):+ copytree(src, dest, **kwargs)+ (dest / "python.exe").write_bytes(b"damaged copy")+ monkeypatch.setattr(shutil, "copytree", damaged_copy)+ else:+ def failed_publication(*args, **kwargs):+ raise OSError("publication refused")+ monkeypatch.setattr(Store, "publish", failed_publication)++ with pytest.raises(InstallError, match="verification|copied bytes|publication refused"):+ ensure._install(python, ensure._lockfile(), previous_facts, Store(writable), target,+ copy_from=(facts, Store(shipped)))+ assert (previous / "python.exe").read_bytes() == b"previous interpreter"+ assert previous_facts.path.read_bytes() == beforediff --git a/uv.lock b/uv.lockindex b574dd277bf..708a7e85679 100644--- a/uv.lock+++ b/uv.lock@@ -1607,6 +1607,8 @@ dependencies = [{ name = "websockets" },{ name = "winrt-windows-applicationmodel", marker = "sys_platform == 'win32'" },{ name = "winrt-windows-foundation", marker = "sys_platform == 'win32'" },+ { name = "winrt-windows-foundation-collections", marker = "sys_platform == 'win32'" },+ { name = "winrt-windows-services-store", marker = "sys_platform == 'win32'" },][package.optional-dependencies]@@ -2005,6 +2007,8 @@ requires-dist = [{ name = "websockets", specifier = "==15.0.1" },{ name = "winrt-windows-applicationmodel", marker = "sys_platform == 'win32'", specifier = ">=3.2.1,<4" },{ name = "winrt-windows-foundation", marker = "sys_platform == 'win32'", specifier = ">=3.2.1,<4" },+ { name = "winrt-windows-foundation-collections", marker = "sys_platform == 'win32'", specifier = ">=3.2.1,<4" },+ { name = "winrt-windows-services-store", marker = "sys_platform == 'win32'", specifier = ">=3.2.1,<4" },{ name = "youtube-transcript-api", marker = "extra == 'youtube'", specifier = "==1.2.4" },]provides-extras = ["anthropic", "exa", "firecrawl", "parallel-web", "fal", "edge-tts", "modal", "daytona", "vercel", "hindsight", "dev", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "honcho", "telegram", "discord", "stt-whisper", "audio-io", "silk", "wake-openwakeword", "wake-sherpa", "wake-porcupine", "google-chat", "doc-extract", "trace-upload", "supermemory", "mem0", "vision", "pty", "mcp", "nemo-relay", "homeassistant", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"]@@ -4486,6 +4490,34 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ed/ed/b9d3a11cac73444c0a3703200161cd7267dab5ab85fd00e1f965526e74a8/winrt_windows_foundation-3.2.1-cp314-cp314-win_arm64.whl", hash = "sha256:3be7fbae829b98a6a946db4fbaf356b11db1fbcbb5d4f37e7a73ac6b25de8b87", size = 114360, upload-time = "2025-09-20T07:11:51.626Z" },]+[[package]]+name = "winrt-windows-foundation-collections"+version = "3.2.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "winrt-runtime" },+]+sdist = { url = "https://files.pythonhosted.org/packages/ef/62/d21e3f1eeb8d47077887bbf0c3882c49277a84d8f98f7c12bda64d498a07/winrt_windows_foundation_collections-3.2.1.tar.gz", hash = "sha256:0eff1ad0d8d763ad17e9e7bbd0c26a62b27215016393c05b09b046d6503ae6d5", size = 16043, upload-time = "2025-06-06T14:41:53.983Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e1/47/b3301d964422d4611c181348149a7c5956a2a76e6339de451a000d4ae8e7/winrt_windows_foundation_collections-3.2.1-cp314-cp314-win32.whl", hash = "sha256:33188ed2d63e844c8adfbb82d1d3d461d64aaf78d225ce9c5930421b413c45ab", size = 62211, upload-time = "2025-09-20T07:11:52.411Z" },+ { url = "https://files.pythonhosted.org/packages/20/59/5f2c940ff606297129e93ebd6030c813e6a43a786de7fc33ccb268e0b06b/winrt_windows_foundation_collections-3.2.1-cp314-cp314-win_amd64.whl", hash = "sha256:d4cfece7e9c0ead2941e55a1da82f20d2b9c8003bb7a8853bb7f999b539f80a4", size = 70399, upload-time = "2025-09-20T07:11:53.254Z" },+ { url = "https://files.pythonhosted.org/packages/f8/2d/2c8eb89062c71d4be73d618457ed68e7e2ba29a660ac26349d44fc121cbf/winrt_windows_foundation_collections-3.2.1-cp314-cp314-win_arm64.whl", hash = "sha256:3884146fea13727510458f6a14040b7632d5d90127028b9bfd503c6c655d0c01", size = 61392, upload-time = "2025-09-20T07:11:53.993Z" },+]++[[package]]+name = "winrt-windows-services-store"+version = "3.2.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "winrt-runtime" },+]+sdist = { url = "https://files.pythonhosted.org/packages/e2/3f/26b5fc590183eb2e8da811ab26345a50e2d9393c621613b91a30346a3d99/winrt_windows_services_store-3.2.1.tar.gz", hash = "sha256:eb04f60cc736d94324f2b9adba65a3030aa29150a2419232fa01b7cba15be2b0", size = 26864, upload-time = "2025-06-06T14:43:16.261Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/49/32/80856fc3df41afd8e42a3d96406819404b177c6ff1c75009c83cfd86a7d2/winrt_windows_services_store-3.2.1-cp314-cp314-win32.whl", hash = "sha256:2e508b990e617764096d8ab1affec2a67b8139fb24e3ff943b082d3a7d6ed11d", size = 164338, upload-time = "2025-09-20T07:16:47.41Z" },+ { url = "https://files.pythonhosted.org/packages/ef/08/c2865af5e2ac9b48e30c202fd9d84e1bed4e335f1e885e286985e9bb3b75/winrt_windows_services_store-3.2.1-cp314-cp314-win_amd64.whl", hash = "sha256:e236c92506ffd5555d4a4e016310a75d4772b1f567b290bcb72a867555cc4a02", size = 171019, upload-time = "2025-09-20T07:16:48.297Z" },+ { url = "https://files.pythonhosted.org/packages/ff/37/f5b8eda61de5da5d1f254e904fe2882ff5d4eef35a080f27c31e95a48462/winrt_windows_services_store-3.2.1-cp314-cp314-win_arm64.whl", hash = "sha256:469ebaea165689c48a64ec121a313dac93a7eea55641fd993ce0c70297d55424", size = 169705, upload-time = "2025-09-20T07:16:49.148Z" },+]+[[package]]name = "wrapt"version = "1.17.3"