Skip to content

The agent that grows with you

fix(desktop): preserve source branches and recover older checkouts

ethernet78fceaaba5ec
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index f2d537ce9d1..069c62caeec 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -2853,14 +2853,14 @@ function recentHermesLog() {
// ─── Self-update (git-pull against the running backend's hermes root) ──────
-function readDesktopUpdateConfig() {
+function readDesktopUpdateConfig(): { branch: string; branchExplicit: boolean } {
try {
- const parsed = JSON.parse(fs.readFileSync(DESKTOP_UPDATE_CONFIG_PATH, 'utf8'))
- const branch = typeof parsed?.branch === 'string' ? parsed.branch.trim() : ''
+ const parsed: { branch?: unknown } | null = JSON.parse(fs.readFileSync(DESKTOP_UPDATE_CONFIG_PATH, 'utf8'))
+ const branch: string = typeof parsed?.branch === 'string' ? parsed.branch.trim() : ''
- return { branch: branch || DEFAULT_UPDATE_BRANCH }
+ return { branch: branch || DEFAULT_UPDATE_BRANCH, branchExplicit: branch.length > 0 }
} catch {
- return { branch: DEFAULT_UPDATE_BRANCH }
+ return { branch: DEFAULT_UPDATE_BRANCH, branchExplicit: false }
}
}
@@ -3198,7 +3198,7 @@ function resolveCheckoutUpdateStrategy(): UpdaterStrategy {
directoryExists,
readCanonicalInstallStamp,
readDesktopUpdateConfig,
- readSourceUpdate: (updateRoot: string): Promise<SourceUpdate> => readSourceUpdate({
+ readSourceUpdate: (updateRoot: string): Promise<SourceUpdate | null> => readSourceUpdate({
python: findPythonForRoot(updateRoot),
git: resolveGitBinary(),
updateRoot,
diff --git a/apps/desktop/electron/updater/checkout-check.test.ts b/apps/desktop/electron/updater/checkout-check.test.ts
index 5b92b1edafd..2c69f14b3a1 100644
--- a/apps/desktop/electron/updater/checkout-check.test.ts
+++ b/apps/desktop/electron/updater/checkout-check.test.ts
@@ -63,6 +63,56 @@ it('uses API checks and a disk cache while a forced check bypasses the cache', a
expect(deps.fetchGitHubApi).toHaveBeenCalledTimes(4)
})
+it('follows the current branch unless config explicitly overrides it, including cached checks', async (): Promise<void> => {
+ const deps: CheckoutCheckDeps = fixture()
+ const localGit: CheckoutCheckDeps['runGit'] = deps.runGit
+ let currentBranch: string = 'feature/foo'
+ let configuredBranch: string = 'main'
+ let branchExplicit: boolean = false
+ deps.readDesktopUpdateConfig = (): { branch: string; branchExplicit: boolean } => ({
+ branch: configuredBranch,
+ branchExplicit
+ })
+ deps.runGit = async (
+ args: string[],
+ options?: { cwd?: string }
+ ): Promise<{ code: number; stdout: string; stderr: string }> =>
+ args.join(' ') === 'rev-parse --abbrev-ref HEAD'
+ ? { code: 0, stdout: currentBranch, stderr: '' }
+ : localGit(args, options)
+
+ for (const scenario of [
+ { current: 'feature/foo', configured: 'main', explicit: false, target: 'feature/foo' },
+ { current: 'feature/foo', configured: 'main', explicit: true, target: 'main' },
+ { current: 'feature/foo', configured: 'release/next', explicit: true, target: 'release/next' },
+ { current: 'feature/foo', configured: 'main', explicit: false, target: 'feature/foo' },
+ { current: 'feature/bar', configured: 'main', explicit: false, target: 'feature/bar' },
+ { current: 'HEAD', configured: 'main', explicit: false, target: 'main' },
+ { current: '', configured: 'main', explicit: false, target: 'main' }
+ ]) {
+ currentBranch = scenario.current
+ configuredBranch = scenario.configured
+ branchExplicit = scenario.explicit
+ vi.mocked(deps.fetchGitHubApi).mockClear()
+ expect(await checkCheckoutUpdates(deps)).toMatchObject({
+ branch: scenario.target,
+ currentBranch,
+ targetSha: 'b'.repeat(40)
+ })
+
+ if (currentBranch) {
+ expect(deps.fetchGitHubApi).toHaveBeenCalledWith(
+ expect.stringContaining(`/commits/${encodeURIComponent(scenario.target)}`),
+ 'application/vnd.github.sha'
+ )
+ }
+
+ vi.mocked(deps.fetchGitHubApi).mockClear()
+ expect(await checkCheckoutUpdates(deps)).toMatchObject({ branch: scenario.target, currentBranch })
+ expect(deps.fetchGitHubApi).not.toHaveBeenCalled()
+ }
+})
+
it('does not report locally ahead commits as an update', async (): Promise<void> => {
const deps = fixture()
deps.fetchGitHubApi = async (url: string): Promise<unknown> =>
diff --git a/apps/desktop/electron/updater/checkout-check.ts b/apps/desktop/electron/updater/checkout-check.ts
index 23c84bd295b..fc9ef072d14 100644
--- a/apps/desktop/electron/updater/checkout-check.ts
+++ b/apps/desktop/electron/updater/checkout-check.ts
@@ -5,7 +5,7 @@ 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 { SOURCE_PROBE_RECOVERY, type SourceUpdate } from './checkout-source'
import type { UpdaterStatusWire } from './index'
@@ -14,8 +14,8 @@ export interface CheckoutCheckDeps {
updateCheckCachePath: string
isGitCheckout: (root: string) => boolean
readCanonicalInstallStamp: () => { updateMechanism?: InstallStamp['updateMechanism'] } | null
- readDesktopUpdateConfig: () => { branch: string }
- readSourceUpdate: (root: string) => Promise<SourceUpdate>
+ readDesktopUpdateConfig: () => { branch: string; branchExplicit?: boolean }
+ readSourceUpdate: (root: string) => Promise<SourceUpdate | null>
resolveUpdateRoot: () => string
resolveHealedBranch: (root: string, branch: string) => Promise<string>
getOriginUrl: (root: string) => Promise<string>
@@ -109,7 +109,8 @@ export async function checkCheckoutUpdates(
{ force = false }: { force?: boolean } = {}
): Promise<UpdaterStatusWire> {
const updateRoot: string = deps.resolveUpdateRoot()
- let { branch }: { branch: string } = deps.readDesktopUpdateConfig()
+ const config: ReturnType<CheckoutCheckDeps['readDesktopUpdateConfig']> = deps.readDesktopUpdateConfig()
+ let branch: string = config.branch
const policy = classifyUpdateRoot({
isGitTree: deps.isGitCheckout(updateRoot),
@@ -136,7 +137,15 @@ export async function checkCheckoutUpdates(
deps.getOriginUrl(updateRoot)
])
- const selection: SourceUpdate = await deps.readSourceUpdate(updateRoot)
+ if (config.branchExplicit === false && currentBranch && currentBranch !== 'HEAD') {
+ branch = currentBranch
+ }
+
+ const selection: SourceUpdate | null = await deps.readSourceUpdate(updateRoot)
+
+ if (selection === null) {
+ return { supported: false, reason: 'source-probe-unavailable', message: SOURCE_PROBE_RECOVERY, hermesRoot: updateRoot }
+ }
if (selection.channel !== 'main') {
return {
diff --git a/apps/desktop/electron/updater/checkout-legacy.test.ts b/apps/desktop/electron/updater/checkout-legacy.test.ts
new file mode 100644
index 00000000000..4dc02100689
--- /dev/null
+++ b/apps/desktop/electron/updater/checkout-legacy.test.ts
@@ -0,0 +1,70 @@
+import * as fs from 'node:fs'
+import * as os from 'node:os'
+import * as path from 'node:path'
+
+import { expect, it, vi } from 'vitest'
+
+import { type CheckoutStrategyDeps, createCheckoutStrategy } from './checkout'
+import { readSourceUpdate, type SourceUpdate } from './checkout-source'
+
+it('offers manual recovery only for a missing source probe, never for a broken probe', async (): Promise<void> => {
+ const root: string = fs.mkdtempSync(path.join(os.tmpdir(), 'legacy-channel-'))
+ const home: string = path.join(root, 'profile')
+ const modulePath: string = path.join(root, 'hermes_cli', 'source_releases.py')
+ fs.mkdirSync(path.dirname(modulePath))
+ fs.mkdirSync(home)
+ fs.writeFileSync(path.join(root, 'hermes_cli', '__init__.py'), '')
+
+ const probe: () => Promise<SourceUpdate | null> = (): Promise<SourceUpdate | null> => readSourceUpdate({
+ python: process.env.HERMES_PYTHON || 'python3', git: 'git', updateRoot: root, hermesHome: home
+ })
+
+ const deps: CheckoutStrategyDeps = {
+ isGitCheckout: (): boolean => true,
+ updateCheckCachePath: path.join(root, 'cache.json'),
+ writeFileAtomic: vi.fn(), readSourceUpdate: probe, fetchGitHubApi: vi.fn(),
+ hermesHome: home, isWindows: process.platform === 'win32', isMac: process.platform === 'darwin',
+ defaultUpdateBranch: 'main', updateHandoffDwellMs: 0,
+ directoryExists: fs.existsSync, readCanonicalInstallStamp: (): null => null,
+ readDesktopUpdateConfig: (): { branch: string } => ({ branch: 'main' }),
+ resolveUpdateRoot: (): string => root, resolveUpdaterBinary: vi.fn((): string => 'frozen-updater'),
+ resolveHealedBranch: vi.fn(async (_root: string, branch: string): Promise<string> => branch),
+ getOriginUrl: async (): Promise<string> => 'https://github.com/fixture/repo',
+ runGit: async (args: string[]): Promise<{ code: number; stdout: string; stderr: string }> => ({
+ code: 0, stdout: args.includes('--abbrev-ref') ? 'feature/work' : args.includes('HEAD') ? 'a'.repeat(40) : '', stderr: ''
+ }),
+ firstLine: (text: string): string => text.split('\n')[0], pathWithVenvBin: (): string => '',
+ venvHermesShimPath: (): string => '', emitUpdateProgress: vi.fn(), rememberLog: vi.fn(),
+ startHermes: vi.fn(async (): Promise<void> => {}), startGatewaysAfterUpdateAbort: vi.fn(),
+ releaseBackendLockForUpdate: vi.fn(async (): Promise<{ unlocked: boolean }> => ({ unlocked: true })),
+ repairMacUpdaterHelper: vi.fn(), preflightStateDb: vi.fn(), runningAppBundle: (): null => null,
+ markQuittingForHandoff: vi.fn(), quit: vi.fn()
+ }
+
+ const strategy: ReturnType<typeof createCheckoutStrategy> = createCheckoutStrategy(deps)
+
+ try {
+ for (const oldModule of ['def resolve_source_release(channel):\n return None, None\n', null]) {
+ if (oldModule !== null) { fs.writeFileSync(modulePath, oldModule) }
+ else { fs.rmSync(modulePath) }
+
+ expect(await strategy.check()).toMatchObject({ supported: false, reason: 'source-probe-unavailable' })
+ const result: Awaited<ReturnType<typeof strategy.apply>> = await strategy.apply({})
+ expect(result).toMatchObject({ manual: true, command: 'hermes update --help' })
+ expect(result.message).toContain('branch or channel')
+ expect(result.command).not.toContain('--branch')
+ expect(deps.releaseBackendLockForUpdate).not.toHaveBeenCalled()
+ expect(deps.resolveUpdaterBinary).not.toHaveBeenCalled()
+ expect(deps.fetchGitHubApi).not.toHaveBeenCalled()
+ expect(deps.quit).not.toHaveBeenCalled()
+ }
+
+ fs.writeFileSync(modulePath, 'def main():\n raise RuntimeError("invalid channel configuration")\n')
+ await expect(strategy.apply({})).rejects.toThrow('invalid channel configuration')
+ fs.writeFileSync(modulePath, 'import missing_probe_dependency\n')
+ await expect(probe()).rejects.toThrow('missing_probe_dependency')
+ expect(deps.releaseBackendLockForUpdate).not.toHaveBeenCalled()
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/updater/checkout-source.test.ts b/apps/desktop/electron/updater/checkout-source.test.ts
index 030e94d9e5d..f9429ef9a5e 100644
--- a/apps/desktop/electron/updater/checkout-source.test.ts
+++ b/apps/desktop/electron/updater/checkout-source.test.ts
@@ -133,7 +133,10 @@ import urllib.request\nfrom urllib.parse import urlsplit\noriginal = urllib.requ
writeFileAtomic: (file: string, contents: string): void => fs.writeFileSync(file, contents),
isGitCheckout: (): boolean => true,
readCanonicalInstallStamp: (): null => null,
- readDesktopUpdateConfig: (): { branch: string } => ({ branch: 'feature/gui' }),
+ readDesktopUpdateConfig: (): { branch: string; branchExplicit: boolean } => ({
+ branch: 'main',
+ branchExplicit: false
+ }),
resolveUpdateRoot: (): string => root,
readSourceUpdate: async (install: string): Promise<SourceUpdate> => {
const result: { stdout: string } = await execute(
diff --git a/apps/desktop/electron/updater/checkout-source.ts b/apps/desktop/electron/updater/checkout-source.ts
index 8ae0a5a1f98..cabcf4c470b 100644
--- a/apps/desktop/electron/updater/checkout-source.ts
+++ b/apps/desktop/electron/updater/checkout-source.ts
@@ -21,6 +21,8 @@ export interface SourceUpdateProbe {
const execute: typeof execFile.__promisify__ = promisify(execFile)
+export const SOURCE_PROBE_RECOVERY: string = 'This checkout predates desktop source-channel checks. Run `hermes update --help` in this installation, then choose the intended branch or channel explicitly before updating.'
+
export function sourceUpdateEnvironment(updateRoot: string, hermesHome: string): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {
...process.env,
@@ -35,14 +37,20 @@ export function sourceUpdateEnvironment(updateRoot: string, hermesHome: string):
}
/** Python owns config identity and publication checks; this bridge only transports them. */
-export async function readSourceUpdate(probe: SourceUpdateProbe): Promise<SourceUpdate> {
+export async function readSourceUpdate(probe: SourceUpdateProbe): Promise<SourceUpdate | null> {
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],
+ [
+ '-c',
+ // Inspect the target checkout's callable, not stderr strings or an editable
+ // install elsewhere on sys.path. Exceptions inside a present probe propagate.
+ 'from pathlib import Path; import runpy; p = Path("hermes_cli/source_releases.py"); entry = runpy.run_path(str(p)).get("main") if p.is_file() else None; entry() if callable(entry) else print("null")',
+ '--install-root', probe.updateRoot, '--git', probe.git
+ ],
hiddenWindowsChildOptions({
cwd: probe.updateRoot,
env: sourceUpdateEnvironment(probe.updateRoot, probe.hermesHome),
@@ -52,7 +60,11 @@ export async function readSourceUpdate(probe: SourceUpdateProbe): Promise<Source
})
)
- const selection: SourceUpdate = JSON.parse(result.stdout) as SourceUpdate
+ const selection: SourceUpdate | null = JSON.parse(result.stdout) as SourceUpdate | null
+
+ if (selection === null) {
+ return null
+ }
if (!['main', 'stable', 'canary'].includes(selection.channel)) {
throw new Error('The source update check returned an invalid channel.')
diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.ts
index 3ffcce75932..50bda7ff565 100644
--- a/apps/desktop/electron/updater/checkout.ts
+++ b/apps/desktop/electron/updater/checkout.ts
@@ -87,6 +87,10 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
async function applyBody(opts: { stopSafeBlockers?: boolean } = {}): Promise<UpdaterApplyResultWire> {
const status: UpdaterStatusWire = await checkCheckoutUpdates(deps, { force: true })
+ if (status.reason === 'source-probe-unavailable') {
+ return { ok: true, manual: true, command: 'hermes update --help', message: status.message, hermesRoot: status.hermesRoot }
+ }
+
if (!status.supported || status.error) {
return { ok: false, error: status.error ?? status.reason, message: status.message }
}
diff --git a/apps/desktop/src/app/updates-overlay.manual.test.tsx b/apps/desktop/src/app/updates-overlay.manual.test.tsx
new file mode 100644
index 00000000000..c886aaf67fd
--- /dev/null
+++ b/apps/desktop/src/app/updates-overlay.manual.test.tsx
@@ -0,0 +1,35 @@
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { I18nProvider } from '@/i18n/context'
+import { en } from '@/i18n/en'
+import { $updateApply, $updateOverlayOpen, $updateOverlayTarget, $updateStatus, applyUpdates, resetUpdateApplyState } from '@/store/updates'
+
+import { UpdatesOverlay } from './updates-overlay'
+
+afterEach((): void => {
+ cleanup()
+ $updateOverlayOpen.set(false)
+ $updateStatus.set(null)
+ resetUpdateApplyState()
+ Reflect.deleteProperty(window, 'hermesDesktop')
+ vi.restoreAllMocks()
+})
+
+it('shows manual recovery guidance without claiming the help command installs an update', async (): Promise<void> => {
+ const message: string = 'Choose the intended branch or channel before updating this older checkout.'
+ window.hermesDesktop = {
+ updates: { apply: async (): Promise<unknown> => ({ ok: true, manual: true, command: 'hermes update --help', message }) }
+ } as unknown as Window['hermesDesktop']
+ $updateOverlayTarget.set('client')
+ $updateOverlayOpen.set(true)
+ $updateStatus.set({ supported: false, reason: 'source-probe-unavailable', message })
+ await applyUpdates()
+ expect($updateApply.get().message).toBe(message)
+ await act(async (): Promise<void> => {
+ render(<I18nProvider configClient={null} initialLocale="en"><UpdatesOverlay /></I18nProvider>)
+ })
+ expect(screen.getByText(message)).toBeTruthy()
+ expect(screen.getByText('hermes update --help')).toBeTruthy()
+ expect(screen.queryByText(en.updates.manualPickedUp)).toBeNull()
+})
diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsx
index 9f8684855ad..1aa81281833 100644
--- a/apps/desktop/src/app/updates-overlay.tsx
+++ b/apps/desktop/src/app/updates-overlay.tsx
@@ -324,6 +324,7 @@ function ManualView({ command, message, onDone }: { command: string | null; mess
const { t } = useI18n()
const u = t.updates
const [copied, setCopied] = useState(false)
+ const guidance: string | undefined = message && message !== command ? message : undefined
const handleCopy = () => {
if (!command) {
@@ -361,7 +362,7 @@ function ManualView({ command, message, onDone }: { command: string | null; mess
<Terminal className="size-8 text-primary" />
<DialogTitle className="text-center text-xl">{u.manualTitle}</DialogTitle>
- <DialogDescription className="text-center text-sm">{u.manualBody}</DialogDescription>
+ <DialogDescription className="text-center text-sm">{guidance ?? u.manualBody}</DialogDescription>
</div>
<button
@@ -387,7 +388,7 @@ function ManualView({ command, message, onDone }: { command: string | null; mess
</span>
</button>
- <p className="text-center text-xs text-muted-foreground">{u.manualPickedUp}</p>
+ {!guidance && <p className="text-center text-xs text-muted-foreground">{u.manualPickedUp}</p>}
<Button className="font-semibold" onClick={onDone} size="lg" variant="secondary">
{u.done}
diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.ts
index 79f17b7463a..9b260f1a192 100644
--- a/apps/desktop/src/store/updates.ts
+++ b/apps/desktop/src/store/updates.ts
@@ -489,7 +489,7 @@ export async function applyUpdates(opts: DesktopUpdateApplyOptions = {}): Promis
...IDLE,
applying: false,
stage: 'manual',
- message: result.command ?? 'hermes update',
+ message: result.message ?? result.command ?? 'hermes update',
command: result.command ?? 'hermes update'
})
diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.md
index f939bf21a30..641d1636434 100644
--- a/website/docs/getting-started/updating.md
+++ b/website/docs/getting-started/updating.md
@@ -100,6 +100,12 @@ checkout's choice does not change another installation's channel. The source-bui
desktop uses that same selection for checks and update handoffs; it does not
replace a selected release channel with its default branch.
+For branch-tracking source installs, the desktop keeps the current named branch
+unless an explicit desktop branch override exists. A detached checkout uses the
+default branch. Older checkouts without source-channel probing show manual
+recovery instructions instead of guessing a target: inspect `hermes update --help`
+in that installation and choose the intended branch or channel before updating.
+
Packaged desktop feed channels derive from their build tag and package owner.
Changing a source channel is not an MSIX or Store channel switch. Canary builds
can advance stored data formats; switching back is not a schema rollback.