Skip to content

The agent that grows with you

fix desktop source updates to honor per-install channels

ethernet4e68c4afcf62
diff --git a/apps/desktop/electron/updater/checkout-check-live.test.ts b/apps/desktop/electron/updater/checkout-check-live.test.ts
index e1948b9717f..40c93f465b1 100644
--- a/apps/desktop/electron/updater/checkout-check-live.test.ts
+++ b/apps/desktop/electron/updater/checkout-check-live.test.ts
@@ -58,7 +58,8 @@ it('checks a real linked worktree through HTTP and reuses the disk cache until f
return { code: 0, stdout: git(args, options?.cwd), stderr: '' }
},
- fetchGitHubApi: async (url: string, accept?: string): Promise<unknown> => {
+ readSourceUpdate: async (): Promise<{ channel: 'main' }> => ({ channel: 'main' }),
+ fetchGitHubApi: async (url: string, accept?: string): Promise<unknown> => {
const parsed = new URL(url)
expect(parsed.hostname).toBe('api.github.com')
diff --git a/apps/desktop/electron/updater/checkout-check.test.ts b/apps/desktop/electron/updater/checkout-check.test.ts
index aac2bc03021..5b92b1edafd 100644
--- a/apps/desktop/electron/updater/checkout-check.test.ts
+++ b/apps/desktop/electron/updater/checkout-check.test.ts
@@ -43,6 +43,7 @@ function fixture(): CheckoutCheckDeps {
throw new Error(`Unexpected git operation: ${key}`)
}),
+ readSourceUpdate: async (): Promise<{ channel: 'main' }> => ({ channel: 'main' }),
fetchGitHubApi: vi.fn(async (url: string): Promise<unknown> =>
url.includes('/commits/') ? 'b'.repeat(40) : { ahead_by: 3, commits: [] }
),
diff --git a/apps/desktop/electron/updater/checkout-check.ts b/apps/desktop/electron/updater/checkout-check.ts
index e0397fd184b..23c84bd295b 100644
--- a/apps/desktop/electron/updater/checkout-check.ts
+++ b/apps/desktop/electron/updater/checkout-check.ts
@@ -5,6 +5,8 @@ import type { InstallStamp } from '../install-stamp'
import { branchTipApiUrl, cacheIsFresh, compareApiUrl, githubRepoSlug, parseCompare } from '../update-api-check'
import { classifyUpdateRoot } from '../update-root-policy'
+import type { SourceUpdate } from './checkout-source'
+
import type { UpdaterStatusWire } from './index'
export interface CheckoutCheckDeps {
@@ -13,6 +15,7 @@ export interface CheckoutCheckDeps {
isGitCheckout: (root: string) => boolean
readCanonicalInstallStamp: () => { updateMechanism?: InstallStamp['updateMechanism'] } | null
readDesktopUpdateConfig: () => { branch: string }
+ readSourceUpdate: (root: string) => Promise<SourceUpdate>
resolveUpdateRoot: () => string
resolveHealedBranch: (root: string, branch: string) => Promise<string>
getOriginUrl: (root: string) => Promise<string>
@@ -105,8 +108,8 @@ export async function checkCheckoutUpdates(
deps: CheckoutCheckDeps,
{ force = false }: { force?: boolean } = {}
): Promise<UpdaterStatusWire> {
- const updateRoot = deps.resolveUpdateRoot()
- let { branch } = deps.readDesktopUpdateConfig()
+ const updateRoot: string = deps.resolveUpdateRoot()
+ let { branch }: { branch: string } = deps.readDesktopUpdateConfig()
const policy = classifyUpdateRoot({
isGitTree: deps.isGitCheckout(updateRoot),
@@ -133,6 +136,24 @@ export async function checkCheckoutUpdates(
deps.getOriginUrl(updateRoot)
])
+ const selection: SourceUpdate = await deps.readSourceUpdate(updateRoot)
+
+ if (selection.channel !== 'main') {
+ return {
+ supported: true,
+ ...selection,
+ channel: selection.channel,
+ currentSha,
+ currentBranch,
+ dirty: dirty.length > 0,
+ hermesRoot: updateRoot,
+ fetchedAt: Date.now(),
+ updateAvailable: !selection.error && selection.targetSha !== currentSha,
+ behind: selection.targetSha === currentSha ? 0 : null,
+ commits: []
+ }
+ }
+
const cached = readCache(deps.updateCheckCachePath)
const now = Date.now()
diff --git a/apps/desktop/electron/updater/checkout-ownership.test.ts b/apps/desktop/electron/updater/checkout-ownership.test.ts
index dfb1d1fe3c4..21b6b34e716 100644
--- a/apps/desktop/electron/updater/checkout-ownership.test.ts
+++ b/apps/desktop/electron/updater/checkout-ownership.test.ts
@@ -7,6 +7,7 @@ function dependencies(): CheckoutStrategyDeps {
isGitCheckout: (): boolean => true,
updateCheckCachePath: 'unused-cache.json',
writeFileAtomic: vi.fn(),
+ readSourceUpdate: vi.fn(async (): Promise<{ channel: 'main' }> => ({ channel: 'main' })),
fetchGitHubApi: vi.fn(),
hermesHome: 'home',
isWindows: process.platform === 'win32',
@@ -46,6 +47,8 @@ describe('checkout update admission', () => {
const result = await strategy.check()
expect(result.supported).toBe(false)
+ expect(await strategy.apply({})).toMatchObject({ ok: false })
+ expect(deps.readSourceUpdate).not.toHaveBeenCalled()
expect(result.mechanism).toBe(strategy.mechanism)
expect(deps.runGit).not.toHaveBeenCalled()
expect(deps.releaseBackendLockForUpdate).not.toHaveBeenCalled()
diff --git a/apps/desktop/electron/updater/checkout-source.test.ts b/apps/desktop/electron/updater/checkout-source.test.ts
new file mode 100644
index 00000000000..030e94d9e5d
--- /dev/null
+++ b/apps/desktop/electron/updater/checkout-source.test.ts
@@ -0,0 +1,274 @@
+import { execFile, execFileSync, type SpawnOptions } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as http from 'node:http'
+import type { AddressInfo } from 'node:net'
+import * as os from 'node:os'
+import * as path from 'node:path'
+import { promisify } from 'node:util'
+
+import { expect, it, vi } from 'vitest'
+
+import * as updaterProcess from '../updater-process'
+import * as blockers from '../venv-blocker-scan'
+
+import { type CheckoutStrategyDeps, createCheckoutStrategy } from './checkout'
+import { readSourceUpdate, type SourceUpdate } from './checkout-source'
+
+const execute: typeof execFile.__promisify__ = promisify(execFile)
+const repository: string = path.resolve(import.meta.dirname, '../../../..')
+const python: string = process.env.HERMES_PYTHON || 'python3'
+
+it('carries each install channel from Python publication checks into the source handoff', async (): Promise<void> => {
+ const temporary: string = fs.mkdtempSync(path.join(os.tmpdir(), 'checkout-channel-'))
+ const origin: string = path.join(temporary, 'origin')
+ const root: string = path.join(temporary, 'checkout')
+ const home: string = path.join(temporary, 'profile')
+ const requests: string[] = []
+ const responses: Map<string, unknown> = new Map<string, unknown>()
+
+ const server: http.Server = http.createServer(
+ (request: http.IncomingMessage, response: http.ServerResponse): void => {
+ const url: string = request.url ?? ''
+ requests.push(url)
+ const body: unknown = responses.get(url)
+ response.statusCode = body === undefined ? 404 : 200
+ response.end(typeof body === 'string' ? body : JSON.stringify(body))
+ }
+ )
+
+ function git(args: string[], cwd: string = origin): string {
+ return execFileSync(
+ 'git',
+ [
+ '-c',
+ 'user.name=Fixture',
+ '-c',
+ '-c',
+ 'commit.gpgsign=false',
+ '-c',
+ 'tag.gpgsign=false',
+ ...args
+ ],
+ { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
+ ).trim()
+ }
+
+ try {
+ fs.mkdirSync(origin)
+ fs.mkdirSync(home)
+ git(['init', '-b', 'feature/gui'])
+ const commits: string[] = []
+
+ for (const label of ['old', 'stable', 'canary', 'unpublished']) {
+ git(['commit', '--allow-empty', '-m', label])
+ commits.push(git(['rev-parse', 'HEAD']))
+ }
+
+ const tags: Record<'stable' | 'canary', string> = { stable: 'v1.2.3', canary: 'v1.2.4-canary.20260911123456' }
+
+ for (const channel of ['stable', 'canary'] as const) {
+ const sha: string = commits[channel === 'stable' ? 1 : 2]
+ git(['tag', '-a', tags[channel], sha, '-m', channel])
+ responses.set(`/releases/${channel}/index.html`, `<meta name="hermes-build" content="${tags[channel]}">`)
+ responses.set(`/repos/NousResearch/hermes-agent/releases/tags/${tags[channel]}`, {
+ tag_name: tags[channel],
+ draft: false,
+ prerelease: channel === 'canary'
+ })
+ responses.set(`/repos/NousResearch/hermes-agent/commits/${tags[channel]}`, { sha })
+ }
+
+ responses.set('/releases/stable/release-candidates.json', { tag: tags.stable, commit: commits[1] })
+ git(['tag', 'v99.0.0'])
+ git(['clone', origin, root], temporary)
+ await new Promise<void>((resolve: () => void): void => {
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ const address: AddressInfo = server.address() as AddressInfo
+ // Redirect only network transport. Selection, config, tag validation and Git are real.
+ fs.cpSync(path.join(repository, 'hermes_cli'), path.join(root, 'hermes_cli'), { recursive: true })
+ fs.writeFileSync(
+ path.join(root, 'transport.py'),
+ `import sys, os
+sys.path.append(${JSON.stringify(repository)})
+assert not os.environ.get('HERMES_RUNTIME_DIR')
+import urllib.request\nfrom urllib.parse import urlsplit\noriginal = urllib.request.urlopen\ndef local(request, *args, **kwargs):\n parsed = urlsplit(request.full_url if isinstance(request, urllib.request.Request) else request)\n assert parsed.hostname in ('hermes-assets.nousresearch.com', 'api.github.com')\n return original('http://127.0.0.1:${address.port}' + parsed.path + ('?' + parsed.query if parsed.query else ''), *args, **kwargs)\nurllib.request.urlopen = local\n`
+ )
+ vi.stubEnv('HERMES_MANAGED', '')
+ vi.stubEnv('HERMES_RUNTIME_DIR', path.join(temporary, 'wrong-runtime'))
+ vi.stubEnv('PYTHONPATH', path.join(temporary, 'wrong-checkout'))
+ vi.stubEnv('PYTHONHOME', path.join(temporary, 'wrong-python'))
+ vi.stubEnv('HERMES_INSTALL_ROOT', origin)
+
+ const environment: NodeJS.ProcessEnv = {
+ ...process.env,
+ HERMES_HOME: home,
+ HERMES_INSTALL_ROOT: root,
+ PYTHONPATH: repository,
+ PYTHONHOME: '',
+ HERMES_RUNTIME_DIR: ''
+ }
+
+ async function setChannel(channel: 'stable' | 'canary' | 'main', install: string = root): Promise<void> {
+ await execute(
+ python,
+ [
+ '-c',
+ 'import sys; from pathlib import Path; from hermes_cli.update_channel import set_install_channel; set_install_channel(sys.argv[1], Path(sys.argv[2]))',
+ channel,
+ install
+ ],
+ { cwd: root, env: environment }
+ )
+ }
+
+ const deps: CheckoutStrategyDeps = {
+ hermesHome: home,
+ isWindows: process.platform === 'win32',
+ isMac: process.platform === 'darwin',
+ defaultUpdateBranch: 'main',
+ updateHandoffDwellMs: 0,
+ updateCheckCachePath: path.join(home, 'cache.json'),
+ writeFileAtomic: (file: string, contents: string): void => fs.writeFileSync(file, contents),
+ isGitCheckout: (): boolean => true,
+ readCanonicalInstallStamp: (): null => null,
+ readDesktopUpdateConfig: (): { branch: string } => ({ branch: 'feature/gui' }),
+ resolveUpdateRoot: (): string => root,
+ readSourceUpdate: async (install: string): Promise<SourceUpdate> => {
+ const result: { stdout: string } = await execute(
+ python,
+ [
+ '-c',
+ "import runpy,sys; runpy.run_path(sys.argv.pop(1)); runpy.run_module('hermes_cli.source_releases', run_name='__main__')",
+ path.join(root, 'transport.py'),
+ '--install-root',
+ install,
+ '--git',
+ 'git'
+ ],
+ { cwd: root, env: environment }
+ )
+
+ return JSON.parse(result.stdout) as SourceUpdate
+ },
+ resolveHealedBranch: async (_root: string, branch: string): Promise<string> => branch,
+ getOriginUrl: async (): Promise<string> => origin,
+ runGit: async (args: string[]): Promise<{ code: number; stdout: string; stderr: string }> => ({
+ code: 0,
+ stdout: git(args, root),
+ stderr: ''
+ }),
+ fetchGitHubApi: async (): Promise<never> => {
+ throw new Error('branch API must not resolve releases')
+ },
+ directoryExists: fs.existsSync,
+ resolveUpdaterBinary: (): null => null,
+ firstLine: (text: string): string => text.split('\n')[0],
+ pathWithVenvBin: (): string => process.env.PATH ?? '',
+ venvHermesShimPath: (): string => '',
+ emitUpdateProgress: vi.fn(),
+ rememberLog: vi.fn(),
+ startHermes: async (): Promise<void> => {},
+ startGatewaysAfterUpdateAbort: (): void => {},
+ releaseBackendLockForUpdate: vi.fn(async (): Promise<{ unlocked: boolean }> => ({ unlocked: true })),
+ repairMacUpdaterHelper: (): void => {},
+ preflightStateDb: (): void => {},
+ runningAppBundle: (): null => null,
+ markQuittingForHandoff: (): void => {},
+ quit: (): void => {}
+ }
+
+ const strategy: ReturnType<typeof createCheckoutStrategy> = createCheckoutStrategy(deps)
+ const spawned: { command: string; args: string[]; options: SpawnOptions }[] = []
+ vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation(
+ (command: string, args: string[], options: SpawnOptions): updaterProcess.UpdaterChild => {
+ spawned.push({ command, args, options })
+
+ return { unref: (): void => {} }
+ }
+ )
+ vi.spyOn(blockers, 'scanVenvBlockers').mockResolvedValue({
+ kind: 'clear',
+ result: { blocked: false, processes: [] }
+ })
+ const scriptDirectory: string = path.join(root, 'scripts', 'desktop-update')
+ const script: string = path.join(scriptDirectory, process.platform === 'win32' ? 'windows.ps1' : 'posix.sh')
+ fs.mkdirSync(path.join(root, 'venv', 'Scripts'), { recursive: true })
+ fs.writeFileSync(path.join(root, 'venv', 'Scripts', 'python.exe'), '')
+
+ for (const channel of ['stable', 'canary'] as const) {
+ await setChannel(channel)
+ await setChannel(channel === 'stable' ? 'canary' : 'stable', origin)
+ const sha: string = commits[channel === 'stable' ? 1 : 2]
+ const checked: unknown = await strategy.check()
+ expect(checked, JSON.stringify({ checked, requests })).toMatchObject({
+ supported: true,
+ channel,
+ latestTag: tags[channel],
+ targetSha: sha,
+ updateAvailable: true
+ })
+ fs.rmSync(scriptDirectory, { recursive: true, force: true })
+ expect(await strategy.apply({})).toMatchObject({ manual: true, command: `hermes update --channel ${channel}` })
+ deps.resolveUpdaterBinary = (): string => path.join(temporary, 'frozen-updater')
+ expect(await strategy.apply({})).toMatchObject({ manual: true, command: `hermes update --channel ${channel}` })
+ expect(spawned).toHaveLength(0)
+ fs.mkdirSync(scriptDirectory, { recursive: true })
+ fs.writeFileSync(script, '')
+ expect(await strategy.apply({})).toMatchObject({ ok: true, handedOff: true })
+ const handoff: (typeof spawned)[number] | undefined = spawned.pop()
+ expect(handoff?.args).toContain(script)
+ expect(handoff?.args).toContain(channel)
+ expect(handoff?.args).toContain(process.platform === 'win32' ? '-Channel' : '--channel')
+ expect(handoff?.args).not.toContain('--branch')
+ expect(handoff?.args).not.toContain('-Branch')
+ expect(handoff?.command).not.toBe(deps.resolveUpdaterBinary())
+ expect(handoff?.options.env?.HERMES_HOME).toBe(home)
+ expect(handoff?.options.env?.HERMES_INSTALL_ROOT).toBe(root)
+ expect(handoff?.options.env?.PYTHONPATH).toBe('')
+ expect(handoff?.options.env?.PYTHONHOME).toBe('')
+ expect(handoff?.options.env?.HERMES_RUNTIME_DIR).toBeUndefined()
+ deps.resolveUpdaterBinary = (): null => null
+ expect(git(['rev-parse', 'HEAD'], root)).toBe(commits[3])
+ git(['checkout', '--detach', sha], root)
+ expect(await strategy.check()).toMatchObject({ targetSha: sha, updateAvailable: false })
+ git(['checkout', 'feature/gui'], root)
+ }
+
+ responses.set(`/repos/NousResearch/hermes-agent/releases/tags/${tags.canary}`, {
+ tag_name: tags.canary,
+ draft: true,
+ prerelease: true
+ })
+ vi.mocked(deps.releaseBackendLockForUpdate).mockClear()
+ expect(await strategy.apply({})).toMatchObject({ ok: false, error: 'release-unavailable' })
+ expect(deps.releaseBackendLockForUpdate).not.toHaveBeenCalled()
+ expect(spawned).toHaveLength(0)
+ await setChannel('main')
+ expect(await readSourceUpdate({ python, git: 'git', updateRoot: root, hermesHome: home })).toEqual({
+ channel: 'main'
+ })
+ const count: number = requests.length
+ expect(await strategy.check()).toMatchObject({
+ branch: 'feature/gui',
+ targetSha: commits[3],
+ updateAvailable: false
+ })
+ expect(await strategy.apply({})).toMatchObject({ ok: true, handedOff: true })
+ expect(spawned.pop()?.args).toEqual(
+ expect.arrayContaining([process.platform === 'win32' ? '-Branch' : '--branch', 'feature/gui'])
+ )
+ fs.rmSync(scriptDirectory, { recursive: true, force: true })
+ expect(await strategy.apply({})).toMatchObject({ manual: true, command: 'hermes update --branch feature/gui' })
+ expect(requests).toHaveLength(count)
+ } finally {
+ vi.restoreAllMocks()
+ vi.unstubAllEnvs()
+ server.closeAllConnections()
+ await new Promise<void>((resolve: () => void): void => {
+ server.close((): void => resolve())
+ })
+ fs.rmSync(temporary, { recursive: true, force: true })
+ }
+}, 30000)
diff --git a/apps/desktop/electron/updater/checkout-source.ts b/apps/desktop/electron/updater/checkout-source.ts
new file mode 100644
index 00000000000..8ae0a5a1f98
--- /dev/null
+++ b/apps/desktop/electron/updater/checkout-source.ts
@@ -0,0 +1,70 @@
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+
+import { buildDesktopBackendEnv } from '../backend-env'
+import { hiddenWindowsChildOptions } from '../windows-child-options'
+
+export interface SourceUpdate {
+ channel: 'main' | 'stable' | 'canary'
+ latestTag?: string
+ targetSha?: string
+ error?: string
+ message?: string
+}
+
+export interface SourceUpdateProbe {
+ python: string | null
+ git: string
+ updateRoot: string
+ hermesHome: string
+}
+
+const execute: typeof execFile.__promisify__ = promisify(execFile)
+
+export function sourceUpdateEnvironment(updateRoot: string, hermesHome: string): NodeJS.ProcessEnv {
+ const env: NodeJS.ProcessEnv = {
+ ...process.env,
+ ...buildDesktopBackendEnv(),
+ HERMES_HOME: hermesHome,
+ HERMES_INSTALL_ROOT: updateRoot
+ }
+
+ delete env.HERMES_RUNTIME_DIR
+
+ return env
+}
+
+/** Python owns config identity and publication checks; this bridge only transports them. */
+export async function readSourceUpdate(probe: SourceUpdateProbe): Promise<SourceUpdate> {
+ if (!probe.python) {
+ throw new Error('No Python interpreter is available to check the source update channel.')
+ }
+
+ const result: { stdout: string; stderr: string } = await execute(
+ probe.python,
+ ['-m', 'hermes_cli.source_releases', '--install-root', probe.updateRoot, '--git', probe.git],
+ hiddenWindowsChildOptions({
+ cwd: probe.updateRoot,
+ env: sourceUpdateEnvironment(probe.updateRoot, probe.hermesHome),
+ encoding: 'utf8',
+ timeout: 360000,
+ maxBuffer: 1024 * 1024
+ })
+ )
+
+ const selection: SourceUpdate = JSON.parse(result.stdout) as SourceUpdate
+
+ if (!['main', 'stable', 'canary'].includes(selection.channel)) {
+ throw new Error('The source update check returned an invalid channel.')
+ }
+
+ if (
+ selection.channel !== 'main' &&
+ !selection.error &&
+ (!selection.latestTag || !/^[0-9a-f]{40}$/.test(selection.targetSha ?? ''))
+ ) {
+ throw new Error('The source update check returned no release commit.')
+ }
+
+ return selection
+}
diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.ts
index 6dc31967393..3ffcce75932 100644
--- a/apps/desktop/electron/updater/checkout.ts
+++ b/apps/desktop/electron/updater/checkout.ts
@@ -17,6 +17,7 @@ import {
import { formatBlockerMessage, formatProbeFailedMessage, scanVenvBlockers, stopSafeVenvBlockers } from '../venv-blocker-scan'
import { checkCheckoutUpdates, type CheckoutCheckDeps } from './checkout-check'
+import { sourceUpdateEnvironment } from './checkout-source'
import type { UpdaterApplyResultWire, UpdaterMechanism, UpdaterStatusWire, UpdaterStrategy } from './index'
@@ -84,9 +85,19 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
return { mechanism, check, apply }
async function applyBody(opts: { stopSafeBlockers?: boolean } = {}): Promise<UpdaterApplyResultWire> {
- const updater = deps.resolveUpdaterBinary()
+ const status: UpdaterStatusWire = await checkCheckoutUpdates(deps, { force: true })
- if (!updater && !deps.isWindows) {
+ if (!status.supported || status.error) {
+ return { ok: false, error: status.error ?? status.reason, message: status.message }
+ }
+
+ const branch: string = status.branch ?? deps.defaultUpdateBranch
+ const targetArgs: string[] = status.channel ? ['--channel', status.channel] : ['--branch', branch]
+ const targetLabel: string = status.channel ?? branch
+ const manualCommand: string = status.channel ? `hermes update --channel ${status.channel}` : buildManualUpdateCommand(branch)
+ const updater: string | null = deps.resolveUpdaterBinary()
+
+ if (!deps.isWindows && (!updater || status.channel)) {
// macOS/Linux: hand off to the repo-owned posix script — same shape as
// Windows (quit → detached orchestrator → `hermes update` → relaunch),
// minus the venv-lock gauntlet POSIX doesn't need. The old in-app
@@ -96,10 +107,10 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
// script owns swap/relaunch, and the app is DEAD during the update so
// there is nothing to reap around. Checkouts that predate the script
// get the manual `hermes update` card once; their next update pulls it.
- return await applyPosixHandoff(opts)
+ return await applyPosixHandoff(targetArgs, targetLabel, manualCommand)
}
- if (!updater) {
+ if (!updater || status.channel) {
// No staged updater binary — this is a CLI-installed user (they ran
// `hermes desktop`, never the Tauri installer that self-copies
// hermes-setup.exe into HERMES_HOME). On Windows the repo hand-off
@@ -110,25 +121,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
const updateRoot = deps.resolveUpdateRoot()
if (!resolveUpdateScriptHandoff(updateRoot)) {
- // They DO have a working `hermes` on PATH / in the venv, so the
- // correct path is the one-liner in their native medium. We show the
- // EXACT command, branch-pinned to the checkout they're on — bare
- // `hermes update` defaults to main and would silently switch a
- // bb/gui (or any non-main) install off-branch. Mirror the GUI
- // button's contract: append --branch <current> for non-main
- // checkouts, keep it bare for main so the card stays clean.
- let command = 'hermes update'
-
- try {
- const head = await deps.runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: updateRoot })
- const current = (head.stdout || '').trim()
-
- if (head.code === 0 && current && current !== 'HEAD') {
- command = buildManualUpdateCommand(await deps.resolveHealedBranch(updateRoot, current))
- }
- } catch {
- // Best-effort: fall back to bare `hermes update` if branch detection fails.
- }
+ const command: string = manualCommand
deps.rememberLog(`[updates] no staged updater; surfacing manual \`${command}\` for CLI install at ${updateRoot}`)
deps.emitUpdateProgress({ stage: 'manual', message: command, percent: null })
@@ -161,9 +154,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
deps.repairMacUpdaterHelper(updater)
const updateRoot = deps.resolveUpdateRoot()
- const { branch: configuredBranch } = deps.readDesktopUpdateConfig()
- const branch = await deps.resolveHealedBranch(updateRoot, configuredBranch || deps.defaultUpdateBranch)
- const updaterArgs = ['--update', '--branch', branch]
+ const updaterArgs: string[] = ['--update', ...targetArgs]
const targetApp = deps.isMac ? deps.runningAppBundle() : null
if (targetApp) {
@@ -308,8 +299,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
const wrapped = wrapHandoffForDetachedConsole(scriptHandoff, [
'-InstallRoot',
updateRoot,
- '-Branch',
- branch,
+ ...(status.channel ? ['-Channel', status.channel] : ['-Branch', branch]),
'-DesktopPid',
String(process.pid),
'-RelaunchExe',
@@ -319,8 +309,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
child = spawnUpdaterProcess(wrapped.command, wrapped.args, {
cwd: deps.hermesHome,
env: {
- ...process.env,
- HERMES_HOME: deps.hermesHome,
+ ...sourceUpdateEnvironment(updateRoot, deps.hermesHome),
HERMES_UPDATE_STARTED_AT: String(updateStartedAt),
PATH: deps.pathWithVenvBin(venvBin)
},
@@ -340,14 +329,13 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
}
deps.rememberLog(
- `[updates] launched repo hand-off script: ${scriptHandoff.scriptPath} (branch ${branch}); exiting desktop to release venv shim`
+ `[updates] launched repo hand-off script: ${scriptHandoff.scriptPath} (${targetLabel}); exiting desktop to release venv shim`
)
} else {
child = spawnUpdaterProcess(updater, updaterArgs, {
cwd: deps.hermesHome,
env: {
- ...process.env,
- HERMES_HOME: deps.hermesHome,
+ ...sourceUpdateEnvironment(updateRoot, deps.hermesHome),
PATH: deps.pathWithVenvBin(venvBin)
},
detached: true,
@@ -423,14 +411,14 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
return { ok: true, handedOff: true, updater }
}
- async function applyPosixHandoff(opts: any): Promise<UpdaterApplyResultWire> {
+ async function applyPosixHandoff(targetArgs: string[], targetLabel: string, manualCommand: string): Promise<UpdaterApplyResultWire> {
const updateRoot = deps.resolveUpdateRoot()
const handoff = resolvePosixScriptHandoff(updateRoot)
if (!handoff) {
- deps.emitUpdateProgress({ stage: 'manual', message: 'hermes update', percent: null })
+ deps.emitUpdateProgress({ stage: 'manual', message: manualCommand, percent: null })
- return { ok: true, manual: true, command: 'hermes update', hermesRoot: updateRoot }
+ return { ok: true, manual: true, command: manualCommand, hermesRoot: updateRoot }
}
const handoffConflict = updateHandoffConflict(deps.hermesHome)
@@ -447,22 +435,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
// ── Pre-flight state.db integrity guard (#68474) ──
deps.preflightStateDb(deps.hermesHome, deps.rememberLog)
- // Branch-pin so a non-main checkout doesn't get switched to main (and
- // self-heal to main when the pinned branch no longer exists on origin).
- let branch = 'main'
-
- try {
- const head = await deps.runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: updateRoot })
- const current = (head.stdout || '').trim()
-
- if (head.code === 0 && current && current !== 'HEAD') {
- branch = await deps.resolveHealedBranch(updateRoot, current)
- }
- } catch {
- // best effort
- }
-
- const args = [...handoff.args, '--install-root', updateRoot, '--branch', branch, '--desktop-pid', String(process.pid)]
+ const args: string[] = [...handoff.args, '--install-root', updateRoot, ...targetArgs, '--desktop-pid', String(process.pid)]
const updateStartedAt = Math.floor(Date.now() / 1000)
// Relaunch target: the running .app bundle on mac (script swaps the
@@ -494,8 +467,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
const child = spawnUpdaterProcess(handoff.command, args, {
cwd: deps.hermesHome,
env: {
- ...process.env,
- HERMES_HOME: deps.hermesHome,
+ ...sourceUpdateEnvironment(updateRoot, deps.hermesHome),
HERMES_UPDATE_STARTED_AT: String(updateStartedAt),
PATH: deps.pathWithVenvBin(path.join(updateRoot, 'venv', 'bin'))
},
@@ -510,7 +482,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
writeUpdateMarker(deps.hermesHome, child.pid, { startedAt: updateStartedAt })
}
- deps.rememberLog(`[updates] launched posix hand-off: ${handoff.scriptPath} (branch ${branch}); quitting to hand off`)
+ deps.rememberLog(`[updates] launched posix hand-off: ${handoff.scriptPath} (${targetLabel}); quitting to hand off`)
deps.emitUpdateProgress({
stage: 'restart',
message:
diff --git a/hermes_cli/source_releases.py b/hermes_cli/source_releases.py
index cc937fcb193..aea0321c3b7 100644
--- a/hermes_cli/source_releases.py
+++ b/hermes_cli/source_releases.py
@@ -166,3 +166,34 @@ def resolve_source_release(channel: str, git_cmd=None, cwd=None, *, repository=N
except (OSError, ValueError, subprocess.SubprocessError) as exc:
logger.warning("Could not resolve the %s source release: %s", channel, exc)
return None, None
+
+
+def main() -> None:
+ """Read-only JSON probe for the desktop, using the CLI's channel authority."""
+ import argparse
+ import contextlib
+ import sys
+ from pathlib import Path
+
+ from hermes_cli.config import load_config
+ from hermes_cli.update_channel import resolve_update_channel
+
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--install-root", type=Path, required=True)
+ parser.add_argument("--git", default="git")
+ args = parser.parse_args()
+ # Config diagnostics must not corrupt the JSON transport.
+ with contextlib.redirect_stdout(sys.stderr):
+ channel = resolve_update_channel(load_config(), args.install_root)
+ result = {"channel": channel}
+ if channel in ("stable", "canary"):
+ tag, sha = resolve_source_release(channel, [args.git], args.install_root)
+ if tag is None or sha is None:
+ result.update(error="release-unavailable", message=f"Could not resolve the {channel} release commit.")
+ else:
+ result.update(latestTag=tag, targetSha=sha)
+ print(json.dumps(result))
+
+
+if __name__ == "__main__":
+ main()