Skip to content

The agent that grows with you

fix(desktop): eslint import order + padding after the origin/main merge

ethernet00a9dbc60bcb
diff --git a/apps/desktop/electron/app-installer-file.test.ts b/apps/desktop/electron/app-installer-file.test.ts
index 482b653566d..6f267aab2c2 100644
--- a/apps/desktop/electron/app-installer-file.test.ts
+++ b/apps/desktop/electron/app-installer-file.test.ts
@@ -24,7 +24,9 @@ test('stages an actual HTTP descriptor and leaves a valid file intact on downloa
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
- if (!address || typeof address === 'string') { throw new Error('missing server address') }
+ if (!address || typeof address === 'string') {
+ throw new Error('missing server address')
+ }
const base = `http://127.0.0.1:${address.port}`
try {
diff --git a/apps/desktop/electron/app-installer-file.ts b/apps/desktop/electron/app-installer-file.ts
index 4290ee7c6b5..c703658b2ff 100644
--- a/apps/desktop/electron/app-installer-file.ts
+++ b/apps/desktop/electron/app-installer-file.ts
@@ -21,7 +21,9 @@ export async function stageAppInstallerFile(
for (;;) {
const { value, done } = await reader.read()
- if (done) { break }
+ if (done) {
+ break
+ }
size += value.byteLength
if (size > 1024 * 1024) {
@@ -34,7 +36,9 @@ export async function stageAppInstallerFile(
await reader.cancel()
}
- if (size === 0) { throw new Error('App Installer descriptor is empty') }
+ if (size === 0) {
+ throw new Error('App Installer descriptor is empty')
+ }
await fs.mkdir(directory, { recursive: true })
const target = path.join(directory, 'update.appinstaller')
const temporary = `${target}.tmp`
diff --git a/apps/desktop/electron/app-updater.ts b/apps/desktop/electron/app-updater.ts
index 6bb20134ed8..0338d00ca7c 100644
--- a/apps/desktop/electron/app-updater.ts
+++ b/apps/desktop/electron/app-updater.ts
@@ -29,10 +29,7 @@ import feedContract from '../update-feed.cjs'
* from its own subtree so the two variants can never serve each other's
* packages.
*/
-export function win32AppInstallerFeedPath(
- channel: string,
- light: boolean
-): string {
+export function win32AppInstallerFeedPath(channel: string, light: boolean): string {
feedContract.darwinFeed(channel, light)
const variant = light ? 'light/' : ''
@@ -86,10 +83,18 @@ export function parseCheckOutput(code: number, stdout: string): AppInstallerChec
}
if (typeof parsed?.available === 'boolean') {
- return { available: parsed.available, availability: parsed.availability, error: parsed.error, sourceUri: parsed.source_uri }
+ return {
+ available: parsed.available,
+ availability: parsed.availability,
+ error: parsed.error,
+ sourceUri: parsed.source_uri
+ }
}
- return { available: null, error: parsed?.error || (code !== 0 ? `checker exited ${code}` : 'checker returned no availability') }
+ return {
+ available: null,
+ error: parsed?.error || (code !== 0 ? `checker exited ${code}` : 'checker returned no availability')
+ }
}
/** Open a local descriptor. The ms-appinstaller protocol is disabled by default. */
@@ -101,7 +106,8 @@ export async function triggerAppInstallerUpdate(
beforeInstall?: () => void | Promise<void>,
sourceUri?: string
): Promise<{ ok: true }> {
- const appinstallerUrl = sourceUri ||
+ const appinstallerUrl =
+ sourceUri ||
`${feedBaseUrl.replace(/\/+$/, '')}/${win32AppInstallerFeedPath(channel, light)}${channel}.appinstaller`
const file = await installer.prepare(appinstallerUrl)
@@ -112,7 +118,9 @@ export async function triggerAppInstallerUpdate(
const error = await installer.open(file)
- if (error) { throw new Error(`App Installer could not open: ${error}`) }
+ if (error) {
+ throw new Error(`App Installer could not open: ${error}`)
+ }
return { ok: true }
}
diff --git a/apps/desktop/electron/app-version.test.ts b/apps/desktop/electron/app-version.test.ts
index 827f65821de..5b6c229589e 100644
--- a/apps/desktop/electron/app-version.test.ts
+++ b/apps/desktop/electron/app-version.test.ts
@@ -8,30 +8,73 @@ describe('artifact version identity', (): void => {
['v1.2.3', 'stable'],
['v1.2.4-canary.20260911010101', 'canary'],
[null, null]
- ] as const)('reports the client version and fixed channel for %s, not a remote runtime', (tag: string | null, channel: 'stable' | 'canary' | null): void => {
- const stamp: InstallStamp = {
- payload: 'bundled', tag, displayVersion: '1.2.3+gabcdef12',
- source: tag ? 'ci' : 'commit-build', updateMechanism: 'external'
- } as InstallStamp
+ ] as const)(
+ 'reports the client version and fixed channel for %s, not a remote runtime',
+ (tag: string | null, channel: 'stable' | 'canary' | null): void => {
+ const stamp: InstallStamp = {
+ payload: 'bundled',
+ tag,
+ displayVersion: '1.2.3+gabcdef12',
+ source: tag ? 'ci' : 'commit-build',
+ updateMechanism: 'external'
+ } as InstallStamp
- expect(appVersionInfo(stamp, '9.9.9-remote', '1.2.3')).toMatchObject({
- appVersion: stamp.displayVersion, channel, source: stamp.source
- })
- expect((): void => assertSourceUpdateChannel(stamp)).toThrow()
- })
+ expect(appVersionInfo(stamp, '9.9.9-remote', '1.2.3')).toMatchObject({
+ appVersion: stamp.displayVersion,
+ channel,
+ source: stamp.source
+ })
+ expect((): void => assertSourceUpdateChannel(stamp)).toThrow()
+ }
+ )
it('reports baked channel source version independently of native sequence version', (): void => {
const stamp: InstallStamp = {
- schemaVersion: 1, source: 'channel-build', payload: 'bundled', distribution: 'desktop-app',
- updateMechanism: 'electron-updater', tag: null, commit: 'a'.repeat(40), commitDate: null,
- branch: null, builtAt: null, dirty: false, baseVersion: '1.2.3', displayVersion: '0.0.7', distance: null,
- channelBuild: { schema: 1, buildId: 'b'.repeat(32), channel: 'new-name', sequence: 7,
- repository: 'example/hermes-agent', commit: 'a'.repeat(40), sourceVersion: '1.2.3', version: '0.0.7', windowsVersion: '0.0.7.0', publicBase: 'https://example.com', bundleEnv: {},
- identity: { token: '1234567890abcdef', displayName: 'Preview', appId: 'chat.preview', appNamePascal: 'Preview', artifactNamePascal: 'Preview', cliName: 'preview', windowsExecutableName: 'Preview.exe', msixAppIdWithOrg: 'Nous.Preview' } }
+ schemaVersion: 1,
+ source: 'channel-build',
+ payload: 'bundled',
+ distribution: 'desktop-app',
+ updateMechanism: 'electron-updater',
+ tag: null,
+ commit: 'a'.repeat(40),
+ commitDate: null,
+ branch: null,
+ builtAt: null,
+ dirty: false,
+ baseVersion: '1.2.3',
+ displayVersion: '0.0.7',
+ distance: null,
+ channelBuild: {
+ schema: 1,
+ buildId: 'b'.repeat(32),
+ channel: 'new-name',
+ sequence: 7,
+ repository: 'example/hermes-agent',
+ commit: 'a'.repeat(40),
+ sourceVersion: '1.2.3',
+ version: '0.0.7',
+ windowsVersion: '0.0.7.0',
+ publicBase: 'https://example.com',
+ bundleEnv: {},
+ identity: {
+ token: '1234567890abcdef',
+ displayName: 'Preview',
+ appId: 'chat.preview',
+ appNamePascal: 'Preview',
+ artifactNamePascal: 'Preview',
+ cliName: 'preview',
+ windowsExecutableName: 'Preview.exe',
+ msixAppIdWithOrg: 'Nous.Preview'
+ }
+ }
}
+
expect(appVersionInfo(stamp, '9.9.9-remote', '0.0.7')).toMatchObject({
- channel: 'new-name', baseVersion: '1.2.3', appVersion: '1.2.3 (new-name #7, aaaaaaaa)',
- sequence: 7, buildId: 'b'.repeat(32)
+ channel: 'new-name',
+ baseVersion: '1.2.3',
+ appVersion: '1.2.3 (new-name #7, aaaaaaaa)',
+ sequence: 7,
+ buildId: 'b'.repeat(32)
})
})
diff --git a/apps/desktop/electron/app-version.ts b/apps/desktop/electron/app-version.ts
index 2c4a29ca14a..69333f54fe8 100644
--- a/apps/desktop/electron/app-version.ts
+++ b/apps/desktop/electron/app-version.ts
@@ -27,20 +27,35 @@ export interface AppVersionInfo {
/** A release channel is an artifact identity, not a user preference. */
export function packagedReleaseChannel(stamp: Readonly<InstallStamp> | null): string | null {
- if (stamp?.channelBuild) { return stamp.channelBuild.channel }
- if (!stamp?.tag || stamp.source === 'commit-build') { return null }
+ if (stamp?.channelBuild) {
+ return stamp.channelBuild.channel
+ }
+
+ if (!stamp?.tag || stamp.source === 'commit-build') {
+ return null
+ }
return isCanaryTag(stamp.tag) ? 'canary' : 'stable'
}
/** The backend may live on another machine and run a different release. */
-export function appVersionInfo(stamp: Readonly<InstallStamp> | null, runtimeVersion: string, packageVersion: string): AppVersionInfo {
- if (!stamp) { return { appVersion: runtimeVersion, baseVersion: packageVersion } }
+export function appVersionInfo(
+ stamp: Readonly<InstallStamp> | null,
+ runtimeVersion: string,
+ packageVersion: string
+): AppVersionInfo {
+ if (!stamp) {
+ return { appVersion: runtimeVersion, baseVersion: packageVersion }
+ }
const build = stamp.channelBuild
+
return {
- appVersion: build ? `${build.sourceVersion} (${build.channel} #${build.sequence}, ${build.commit.slice(0, 8)})` :
- stamp.payload === 'bootstrap' ? runtimeVersion : stamp.displayVersion || packageVersion,
+ appVersion: build
+ ? `${build.sourceVersion} (${build.channel} #${build.sequence}, ${build.commit.slice(0, 8)})`
+ : stamp.payload === 'bootstrap'
+ ? runtimeVersion
+ : stamp.displayVersion || packageVersion,
baseVersion: build?.sourceVersion ?? stamp.baseVersion ?? undefined,
sequence: build?.sequence,
buildId: build?.buildId,
@@ -57,7 +72,9 @@ export function appVersionInfo(stamp: Readonly<InstallStamp> | null, runtimeVers
}
export function assertSourceUpdateChannel(stamp: Readonly<InstallStamp> | null): void {
- if (stamp?.source === 'commit-build') { throw new Error(COMMIT_BUILD_UPDATE_MESSAGE) }
+ if (stamp?.source === 'commit-build') {
+ throw new Error(COMMIT_BUILD_UPDATE_MESSAGE)
+ }
if (stamp && stamp.payload !== 'bootstrap') {
throw new Error('This package has a fixed update channel. Install the other package to change channels.')
diff --git a/apps/desktop/electron/appinstaller-checker.test.ts b/apps/desktop/electron/appinstaller-checker.test.ts
index 4ee610e5529..367afbf4613 100644
--- a/apps/desktop/electron/appinstaller-checker.test.ts
+++ b/apps/desktop/electron/appinstaller-checker.test.ts
@@ -14,12 +14,7 @@ interface CapturedCall {
function stubExecFile(behavior: (call: CapturedCall) => void) {
const calls: CapturedCall[] = []
- const impl = (
- file: string,
- args: readonly string[],
- options: CapturedCall['options'],
- callback: Callback
- ) => {
+ const impl = (file: string, args: readonly string[], options: CapturedCall['options'], callback: Callback) => {
const call: CapturedCall = { file, args, options, callback }
calls.push(call)
@@ -90,14 +85,20 @@ describe('runAppInstallerChecker', () => {
try {
let callback: Callback | undefined
- const { impl } = stubExecFile(call => { callback = call.callback })
+ 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 })
+ execFileImpl: impl,
+ timeoutMs: 50,
+ waitForExit: true
+ }).then(result => {
+ settled = true
+
+ return result
+ })
await vi.advanceTimersByTimeAsync(100)
expect(settled).toBe(false)
diff --git a/apps/desktop/electron/appinstaller-checker.ts b/apps/desktop/electron/appinstaller-checker.ts
index 87ab932a505..24fd01fcaa7 100644
--- a/apps/desktop/electron/appinstaller-checker.ts
+++ b/apps/desktop/electron/appinstaller-checker.ts
@@ -59,7 +59,7 @@ export function runAppInstallerChecker(
stdout: JSON.stringify({ available: null, error: `checker timed out after ${timeoutMs}ms` })
})
- return new Promise((resolve) => {
+ return new Promise(resolve => {
let settled = false
const finish = (result: AppInstallerCheckResult): void => {
@@ -79,7 +79,7 @@ export function runAppInstallerChecker(
try {
exec(
python,
- [script, ...deps.args ?? []],
+ [script, ...(deps.args ?? [])],
{ encoding: 'utf8', timeout: timeoutMs, windowsHide: true, env: deps.env },
(error, stdout, stderr) => {
if (stderr) {
diff --git a/apps/desktop/electron/backend-exit.test.ts b/apps/desktop/electron/backend-exit.test.ts
index 882eae88d61..be8c516a6fe 100644
--- a/apps/desktop/electron/backend-exit.test.ts
+++ b/apps/desktop/electron/backend-exit.test.ts
@@ -10,6 +10,7 @@ test('backend exit escalation rejects within its bound when no exit or close arr
try {
const child = Object.assign(new EventEmitter(), { exitCode: null, signalCode: null, kill: vi.fn() })
+
const waiting = assert.rejects(
waitForBackendExit(child, { forceKillProcessTree: (): void => {} }, 20),
/did not exit/
diff --git a/apps/desktop/electron/backend-probes-runtime.test.ts b/apps/desktop/electron/backend-probes-runtime.test.ts
index a44e8b7272c..3f140bafd18 100644
--- a/apps/desktop/electron/backend-probes-runtime.test.ts
+++ b/apps/desktop/electron/backend-probes-runtime.test.ts
@@ -9,7 +9,8 @@ import { test } from 'vitest'
import { canImportHermesCli } from './backend-probes'
const REPO: string = path.resolve(import.meta.dirname, '../../..')
-const PYTHON: string = process.env.HERMES_PYTHON || process.env.UV_PYTHON || (process.platform === 'win32' ? 'python' : 'python3')
+const PYTHON: string =
+ process.env.HERMES_PYTHON || process.env.UV_PYTHON || (process.platform === 'win32' ? 'python' : 'python3')
interface RuntimeFixture {
python: string
@@ -61,29 +62,45 @@ print(json.dumps({'python': str(python), 'site': str(site), 'dependencies': str(
`
try {
- const fixture: RuntimeFixture = JSON.parse(execFileSync(PYTHON, ['-I', '-c', setup, REPO, temp], {
- cwd: temp, env, encoding: 'utf8', timeout: 90_000, windowsHide: true
- })) as RuntimeFixture
+ const fixture: RuntimeFixture = JSON.parse(
+ execFileSync(PYTHON, ['-I', '-c', setup, REPO, temp], {
+ cwd: temp,
+ env,
+ encoding: 'utf8',
+ timeout: 90_000,
+ windowsHide: true
+ })
+ ) as RuntimeFixture
assert.equal(await canImportHermesCli(fixture.python, { cwd: REPO, env }), true)
- assert.equal(await canImportHermesCli(fixture.python, {
- cwd: REPO,
- env: { ...env, PYTHONHOME: path.join(temp, 'foreign-home') }
- }), true, 'Python home overrides must be scrubbed before the interpreter starts')
+ assert.equal(
+ await canImportHermesCli(fixture.python, {
+ cwd: REPO,
+ env: { ...env, PYTHONHOME: path.join(temp, 'foreign-home') }
+ }),
+ true,
+ 'Python home overrides must be scrubbed before the interpreter starts'
+ )
fs.unlinkSync(path.join(fixture.site, 'selected-dependencies.pth'))
const foreign: string = path.join(temp, 'foreign-packages')
fs.symlinkSync(fixture.dependencies, foreign, process.platform === 'win32' ? 'junction' : 'dir')
- assert.equal(await canImportHermesCli(fixture.python, {
- cwd: REPO,
- env: { ...env, PYTHONPATH: foreign }
- }), false, 'foreign dependencies must not conceal an empty selected environment')
- assert.equal(await canImportHermesCli(fixture.python, {
- cwd: REPO,
- env: { ...env, PYTHONHOME: path.join(temp, 'foreign-home') }
- }), false)
+ assert.equal(
+ await canImportHermesCli(fixture.python, {
+ cwd: REPO,
+ env: { ...env, PYTHONPATH: foreign }
+ }),
+ false,
+ 'foreign dependencies must not conceal an empty selected environment'
+ )
+ assert.equal(
+ await canImportHermesCli(fixture.python, {
+ cwd: REPO,
+ env: { ...env, PYTHONHOME: path.join(temp, 'foreign-home') }
+ }),
+ false
+ )
} finally {
fs.rmSync(temp, { recursive: true, force: true, maxRetries: 3 })
}
}, 120_000)
-
diff --git a/apps/desktop/electron/backend-probes.ts b/apps/desktop/electron/backend-probes.ts
index 9268a438759..78c7d071536 100644
--- a/apps/desktop/electron/backend-probes.ts
+++ b/apps/desktop/electron/backend-probes.ts
@@ -102,7 +102,10 @@ async function execProbe(
}
/** Probe the checkout at cwd with the same dependency activation as launch. */
-async function canImportHermesCli(pythonPath: string, opts: { env?: NodeJS.ProcessEnv; cwd?: string } = {}): Promise<boolean> {
+async function canImportHermesCli(
+ pythonPath: string,
+ opts: { env?: NodeJS.ProcessEnv; cwd?: string } = {}
+): Promise<boolean> {
if (!pythonPath) {
return false
}
@@ -111,13 +114,17 @@ async function canImportHermesCli(pythonPath: string, opts: { env?: NodeJS.Proce
const env: NodeJS.ProcessEnv = { ...process.env, ...opts.env }
// Bootstrap selects the committed generation before any dependency import.
- await execProbe(pythonPath, ['-c', 'import hermes_bootstrap; import hermes_yaml; import dotenv; import hermes_cli.config'], {
- cwd: opts.cwd,
- env: { ...env, ...buildDesktopBackendEnv({ currentEnv: env }) },
- stdio: 'ignore',
- timeout: PROBE_TIMEOUT_MS,
- windowsHide: true
- })
+ await execProbe(
+ pythonPath,
+ ['-c', 'import hermes_bootstrap; import hermes_yaml; import dotenv; import hermes_cli.config'],
+ {
+ cwd: opts.cwd,
+ env: { ...env, ...buildDesktopBackendEnv({ currentEnv: env }) },
+ stdio: 'ignore',
+ timeout: PROBE_TIMEOUT_MS,
+ windowsHide: true
+ }
+ )
return true
} catch {
diff --git a/apps/desktop/electron/backend-stop-overlap.test.ts b/apps/desktop/electron/backend-stop-overlap.test.ts
index fbc08cc103d..ef293055f58 100644
--- a/apps/desktop/electron/backend-stop-overlap.test.ts
+++ b/apps/desktop/electron/backend-stop-overlap.test.ts
@@ -56,7 +56,9 @@ test.skipIf(process.platform === 'win32')(
const deps = {
pool: new Map([['profile', { process: child }]]),
- stopChild: (c: unknown): void => { void lifecycle.stop(c as ChildProcess) },
+ stopChild: (c: unknown): void => {
+ void lifecycle.stop(c as ChildProcess)
+ },
waitForExit: (c: unknown): Promise<void> => lifecycle.stop(c as ChildProcess)
}
@@ -137,11 +139,15 @@ test.skipIf(process.platform === 'win32')(
child.once('exit', (): boolean => lifecycle.release(child))
const entry = { process: child, releaseLocalBackendSlot: release }
const entries = new Map([['claiming', entry]])
+
const pool = createPoolStopper({
pool: entries,
- stopChild: (c: unknown): void => { void lifecycle.stop(c as ChildProcess) },
+ stopChild: (c: unknown): void => {
+ void lifecycle.stop(c as ChildProcess)
+ },
waitForExit: (c: unknown): Promise<void> => lifecycle.stop(c as ChildProcess)
})
+
let finishClaim!: () => void
const claim = new Promise<void>((resolve: () => void): void => {
diff --git a/apps/desktop/electron/bootstrap-platform.ts b/apps/desktop/electron/bootstrap-platform.ts
index 9966c395180..89081720ac6 100644
--- a/apps/desktop/electron/bootstrap-platform.ts
+++ b/apps/desktop/electron/bootstrap-platform.ts
@@ -137,9 +137,4 @@ function resolveLinuxPasswordStore(options: { env?: NodeJS.ProcessEnv; platform?
return { store: requested, warning: null }
}
-export {
- detectRemoteDisplay,
- isWindowsBinaryPathInWsl,
- isWslEnvironment,
- resolveLinuxPasswordStore
-}
+export { detectRemoteDisplay, isWindowsBinaryPathInWsl, isWslEnvironment, resolveLinuxPasswordStore }
diff --git a/apps/desktop/electron/bootstrap-state.test.ts b/apps/desktop/electron/bootstrap-state.test.ts
index 08b74841758..a9231b0c518 100644
--- a/apps/desktop/electron/bootstrap-state.test.ts
+++ b/apps/desktop/electron/bootstrap-state.test.ts
@@ -5,19 +5,34 @@ import { type InstallStamp } from './install-stamp'
function stamp(payload: InstallStamp['payload']): InstallStamp {
return {
- schemaVersion: 2, commit: null, commitDate: null, branch: null,
- builtAt: null, dirty: false, source: 'build', distribution: 'desktop-app',
- updateMechanism: 'self', baseVersion: null, displayVersion: null,
- distance: null, payload, tag: null
+ schemaVersion: 2,
+ commit: null,
+ commitDate: null,
+ branch: null,
+ builtAt: null,
+ dirty: false,
+ source: 'build',
+ distribution: 'desktop-app',
+ updateMechanism: 'self',
+ baseVersion: null,
+ displayVersion: null,
+ distance: null,
+ payload,
+ tag: null
}
}
-test.each(['bundled', 'bootstrap', 'light'] as const)('bootstrap state retains the %s artifact fact across failure and reset', payload => {
- const artifact = stamp(payload)
- const state = { error: 'backend exited before setup', setupChoice: null }
- expect(bootstrapSnapshot(state, artifact)).toEqual({ ...state, bundled: payload === 'bundled' })
- expect(bootstrapSnapshot({ error: null, setupChoice: null }, artifact).bundled).toBe(payload === 'bundled')
- expect(state).not.toHaveProperty('bundled')
- expect(bootstrapSnapshot(state, null).bundled).toBe(false)
- expect(bootstrapSnapshot({ ...state, bundled: payload !== 'bundled' }, artifact).bundled).toBe(payload === 'bundled')
-})
+test.each(['bundled', 'bootstrap', 'light'] as const)(
+ 'bootstrap state retains the %s artifact fact across failure and reset',
+ payload => {
+ const artifact = stamp(payload)
+ const state = { error: 'backend exited before setup', setupChoice: null }
+ expect(bootstrapSnapshot(state, artifact)).toEqual({ ...state, bundled: payload === 'bundled' })
+ expect(bootstrapSnapshot({ error: null, setupChoice: null }, artifact).bundled).toBe(payload === 'bundled')
+ expect(state).not.toHaveProperty('bundled')
+ expect(bootstrapSnapshot(state, null).bundled).toBe(false)
+ expect(bootstrapSnapshot({ ...state, bundled: payload !== 'bundled' }, artifact).bundled).toBe(
+ payload === 'bundled'
+ )
+ }
+)
diff --git a/apps/desktop/electron/bundle-swap.test.ts b/apps/desktop/electron/bundle-swap.test.ts
index 7e3fafaf3b1..b517fa0396a 100644
--- a/apps/desktop/electron/bundle-swap.test.ts
+++ b/apps/desktop/electron/bundle-swap.test.ts
@@ -63,6 +63,4 @@ describe('detectBundleSwap', () => {
expect(detectBundleSwap(fallbackTagged, { ...RUNNING, commit: 'b'.repeat(40) })).toBe(false)
expect(detectBundleSwap(RUNNING, fallbackCommit)).toBe(false)
})
-
-
})
diff --git a/apps/desktop/electron/channel-build-version.test.ts b/apps/desktop/electron/channel-build-version.test.ts
index f55568df3d7..997c01b27ac 100644
--- a/apps/desktop/electron/channel-build-version.test.ts
+++ b/apps/desktop/electron/channel-build-version.test.ts
@@ -17,21 +17,37 @@ const repo: string = path.resolve(desktop, '../..')
function request(sequence: number = 65536, token: string = 'ab12cd34ef56ab78'): ChannelBuildRequest {
return {
- schema: 1, buildId: 'a'.repeat(32), channel: 'no-registry-needed', sequence,
- repository: 'fixture/project', commit: 'b'.repeat(40), sourceVersion: '1.2.3',
- version: `0.0.${sequence}`, windowsVersion: `0.${Math.floor(sequence / 65536)}.${sequence % 65536}.0`,
+ schema: 1,
+ buildId: 'a'.repeat(32),
+ channel: 'no-registry-needed',
+ sequence,
+ repository: 'fixture/project',
+ commit: 'b'.repeat(40),
+ sourceVersion: '1.2.3',
+ version: `0.0.${sequence}`,
+ windowsVersion: `0.${Math.floor(sequence / 65536)}.${sequence % 65536}.0`,
identity: {
- token, displayName: 'Hermes no-registry-needed', appId: `com.nousresearch.hermes-channel-${token}`,
- appNamePascal: `HermesChannel${token}`, artifactNamePascal: `HermesChannel${token}`,
- cliName: 'hermes-no-registry-needed', windowsExecutableName: 'hermes-no-registry-needed',
+ token,
+ displayName: 'Hermes no-registry-needed',
+ appId: `com.nousresearch.hermes-channel-${token}`,
+ appNamePascal: `HermesChannel${token}`,
+ artifactNamePascal: `HermesChannel${token}`,
+ cliName: 'hermes-no-registry-needed',
+ windowsExecutableName: 'hermes-no-registry-needed',
msixAppIdWithOrg: `NousResearch.HermesChannel${token}`
},
- bundleEnv: { HERMES_GUEST_ONBOARDING: '1' }, publicBase: 'https://builds.example.test'
+ bundleEnv: { HERMES_GUEST_ONBOARDING: '1' },
+ publicBase: 'https://builds.example.test'
}
}
-interface PackagingFacts { identity: ProductIdentity; config: Configuration }
-interface StampPayload { runtime: { repoDir: string; commands: { hermes: string } } }
+interface PackagingFacts {
+ identity: ProductIdentity
+ config: Configuration
+}
+interface StampPayload {
+ runtime: { repoDir: string; commands: { hermes: string } }
+}
function load(build: ChannelBuildRequest): PackagingFacts {
process.env.HERMES_DESKTOP_VARIANT = 'bundled'
@@ -45,17 +61,38 @@ function load(build: ChannelBuildRequest): PackagingFacts {
}
afterEach((): void => {
- for (const key of ['_HERMES_CHANNEL_REQUEST_JSON', 'HERMES_DESKTOP_VARIANT', 'HERMES_BUILD_COMMIT', 'HERMES_PAYLOAD_TAG']) {delete process.env[key]}
+ for (const key of [
+ '_HERMES_CHANNEL_REQUEST_JSON',
+ 'HERMES_DESKTOP_VARIANT',
+ 'HERMES_BUILD_COMMIT',
+ 'HERMES_PAYLOAD_TAG'
+ ]) {
+ delete process.env[key]
+ }
- for (const file of ['../product-identity.cjs', '../electron-builder.config.cjs']) {delete require.cache[require.resolve(file)]}
+ for (const file of ['../product-identity.cjs', '../electron-builder.config.cjs']) {
+ delete require.cache[require.resolve(file)]
+ }
})
test('channel packaging reuses admitted identity and rejects unsupported or unsafe identities', (): void => {
const first: ChannelBuildRequest = request()
const a: ReturnType<typeof load> = load(first)
- const b: ReturnType<typeof load> = load({ ...first, ...request(65537), commit: 'c'.repeat(40), sourceVersion: '0.1.0' })
-
- for (const field of ['displayName', 'appId', 'appNamePascal', 'cliName', 'windowsExecutableName', 'msixAppIdWithOrg'] as const) {
+ const b: ReturnType<typeof load> = load({
+ ...first,
+ ...request(65537),
+ commit: 'c'.repeat(40),
+ sourceVersion: '0.1.0'
+ })
+
+ for (const field of [
+ 'displayName',
+ 'appId',
+ 'appNamePascal',
+ 'cliName',
+ 'windowsExecutableName',
+ 'msixAppIdWithOrg'
+ ] as const) {
assert.equal(a.identity[field], first.identity[field])
assert.equal(a.identity[field], b.identity[field])
}
@@ -70,33 +107,64 @@ test('channel packaging reuses admitted identity and rejects unsupported or unsa
let displayName: string = ''
try {
- assert.equal(applyDesktopIdentity({
- getPath: (): string => appData,
- setPath: (_name: 'userData', value: string): void => { userData = value },
- setName: (value: string): void => { displayName = value }
- }, a.identity), first.identity.displayName)
+ assert.equal(
+ applyDesktopIdentity(
+ {
+ getPath: (): string => appData,
+ setPath: (_name: 'userData', value: string): void => {
+ userData = value
+ },
+ setName: (value: string): void => {
+ displayName = value
+ }
+ },
+ a.identity
+ ),
+ first.identity.displayName
+ )
assert.equal(userData, path.join(appData, first.identity.appNamePascal))
assert.equal(displayName, first.identity.displayName)
} finally {
fs.rmSync(appData, { recursive: true, force: true })
}
- assert.deepEqual(a.config.mac?.publish, [{ provider: 'generic', url: `${first.publicBase}/releases/channel-builds/${first.buildId}/darwin/`, channel: 'latest' }])
+ assert.deepEqual(a.config.mac?.publish, [
+ {
+ provider: 'generic',
+ url: `${first.publicBase}/releases/channel-builds/${first.buildId}/darwin/`,
+ channel: 'latest'
+ }
+ ])
process.env.HERMES_DESKTOP_VARIANT = 'light'
delete require.cache[require.resolve('../product-identity.cjs')]
- assert.throws((): void => { require('../product-identity.cjs') }, /bundled/)
+ assert.throws((): void => {
+ require('../product-identity.cjs')
+ }, /bundled/)
const invalid: ChannelBuildRequest = request()
invalid.identity.cliName = 'con'
- assert.throws((): void => { load(invalid) }, /identity/)
+ assert.throws((): void => {
+ load(invalid)
+ }, /identity/)
invalid.identity.cliName = first.identity.cliName
invalid.identity.windowsExecutableName = 'trailing.'
- assert.throws((): void => { load(invalid) }, /identity/)
+ assert.throws((): void => {
+ load(invalid)
+ }, /identity/)
})
test('channel stamps verify the real checkout and retain source version and native ownership', async (): Promise<void> => {
- const { resolveStamp, buildStampPayload, writeDesktopStamp }: {
+ const {
+ resolveStamp,
+ buildStampPayload,
+ writeDesktopStamp
+ }: {
resolveStamp: (options: { env: NodeJS.ProcessEnv; repoRoot: string }) => InstallStamp
- buildStampPayload: (stamp: InstallStamp, env: NodeJS.ProcessEnv, platform: string, payload: StampPayload) => InstallStamp
+ buildStampPayload: (
+ stamp: InstallStamp,
+ env: NodeJS.ProcessEnv,
+ platform: string,
+ payload: StampPayload
+ ) => InstallStamp
writeDesktopStamp: (directory: string, stamp: InstallStamp) => void
} = await import('../scripts/write-build-stamp.mjs')
@@ -104,9 +172,32 @@ test('channel stamps verify the real checkout and retain source version and nati
try {
execFileSync('git', ['init', '-q', dir])
- execFileSync('git', ['-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '-qm', 'fixture'], { cwd: dir })
- const build: ChannelBuildRequest = { ...request(), commit: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim() }
- const env: NodeJS.ProcessEnv = { ...process.env, HERMES_DESKTOP_VARIANT: 'bundled', _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(build), GITHUB_SHA: 'd'.repeat(40) }
+ execFileSync(
+ 'git',
+ [
+ '-c',
+ 'user.name=Fixture',
+ '-c',
+ '-c',
+ 'commit.gpgsign=false',
+ 'commit',
+ '--allow-empty',
+ '-qm',
+ 'fixture'
+ ],
+ { cwd: dir }
+ )
+ const build: ChannelBuildRequest = {
+ ...request(),
+ commit: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: dir, encoding: 'utf8' }).trim()
+ }
+ const env: NodeJS.ProcessEnv = {
+ ...process.env,
+ HERMES_DESKTOP_VARIANT: 'bundled',
+ _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(build),
+ GITHUB_SHA: 'd'.repeat(40)
+ }
const provenance: InstallStamp = resolveStamp({ env, repoRoot: dir })
const payload: StampPayload = { runtime: { repoDir: 'repo', commands: { hermes: 'bin/hermes' } } }
const built: InstallStamp = buildStampPayload(provenance, env, 'darwin', payload)
@@ -119,34 +210,74 @@ test('channel stamps verify the real checkout and retain source version and nati
assert.ok(Object.isFrozen(built.channelBuild?.identity))
fs.mkdirSync(path.join(dir, 'out/agent-payload/repo'), { recursive: true })
writeDesktopStamp(path.join(dir, 'out'), built)
- assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, 'out/install-stamp.json'), 'utf8')), JSON.parse(fs.readFileSync(path.join(dir, 'out/agent-payload/repo/install-stamp.json'), 'utf8')))
- assert.throws((): void => { resolveStamp({ env: { ...env, _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(request()) }, repoRoot: dir }) }, /checkout/)
+ assert.deepEqual(
+ JSON.parse(fs.readFileSync(path.join(dir, 'out/install-stamp.json'), 'utf8')),
+ JSON.parse(fs.readFileSync(path.join(dir, 'out/agent-payload/repo/install-stamp.json'), 'utf8'))
+ )
+ assert.throws((): void => {
+ resolveStamp({ env: { ...env, _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(request()) }, repoRoot: dir })
+ }, /checkout/)
delete process.env._HERMES_CHANNEL_REQUEST_JSON
process.env.HERMES_PAYLOAD_TAG = 'v0.0.1'
delete require.cache[require.resolve('../product-identity.cjs')]
const official: ProductIdentity = require('../product-identity.cjs')
delete process.env.HERMES_PAYLOAD_TAG
+
const receiver: ChannelBuildRequest = {
- ...build, channel: 'stable', sequence: 1, version: '0.0.1', windowsVersion: '0.0.1.0',
- releaseTag: 'v0.0.1', receiverCandidate: true, bundleEnv: {},
+ ...build,
+ channel: 'stable',
+ sequence: 1,
+ version: '0.0.1',
+ windowsVersion: '0.0.1.0',
+ releaseTag: 'v0.0.1',
+ receiverCandidate: true,
+ bundleEnv: {},
publicBase: 'https://builds.example.test/ci-disposable/1/2-1',
identity: { ...official, token: build.identity.token }
}
+
const receiverEnv: NodeJS.ProcessEnv = { ...env, _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(receiver) }
- const stable: InstallStamp = buildStampPayload(resolveStamp({ env: receiverEnv, repoRoot: dir }), receiverEnv, 'darwin', payload)
+ const stable: InstallStamp = buildStampPayload(
+ resolveStamp({ env: receiverEnv, repoRoot: dir }),
+ receiverEnv,
+ 'darwin',
+ payload
+ )
assert.equal(stable.channelBuild, undefined)
assert.equal(stable.source, 'build')
assert.equal(stable.tag, receiver.releaseTag)
assert.equal(stable.displayVersion, receiver.version)
assert.equal(stable.updateMechanism, 'electron-updater')
const packaged: PackagingFacts = load(receiver)
- assert.deepEqual(packaged.config.mac?.publish, [{ provider: 'generic', url: `${receiver.publicBase}/releases/darwin/stable/`, channel: 'stable' }])
- const { verifyBundleStamp }: { verifyBundleStamp: (stamp: InstallStamp, options: {
- commit: string; platform: string; channelRequest: ChannelBuildRequest
- }) => string } = await import('../../../tests/install/e2e-assets/bundle-smoke-metadata.mjs')
- assert.equal(verifyBundleStamp(stable, { commit: receiver.commit, platform: 'darwin', channelRequest: receiver }), receiver.version)
- assert.throws((): void => { verifyBundleStamp(built, { commit: receiver.commit, platform: 'darwin', channelRequest: receiver }) })
- execFileSync(process.env.HERMES_PYTHON || 'python3', ['-c', `
+ assert.deepEqual(packaged.config.mac?.publish, [
+ { provider: 'generic', url: `${receiver.publicBase}/releases/darwin/stable/`, channel: 'stable' }
+ ])
+
+ const {
+ verifyBundleStamp
+ }: {
+ verifyBundleStamp: (
+ stamp: InstallStamp,
+ options: {
+ commit: string
+ platform: string
+ channelRequest: ChannelBuildRequest
+ }
+ ) => string
+ } = await import('../../../tests/install/e2e-assets/bundle-smoke-metadata.mjs')
+
+ assert.equal(
+ verifyBundleStamp(stable, { commit: receiver.commit, platform: 'darwin', channelRequest: receiver }),
+ receiver.version
+ )
+ assert.throws((): void => {
+ verifyBundleStamp(built, { commit: receiver.commit, platform: 'darwin', channelRequest: receiver })
+ })
+ execFileSync(
+ process.env.HERMES_PYTHON || 'python3',
+ [
+ '-c',
+ `
import json, sys
from scripts.bundles.release_artifacts import stamp_matches
stamp, request = json.loads(sys.argv[1]), json.loads(sys.argv[2])
@@ -158,26 +289,50 @@ except ValueError:
pass
else:
raise AssertionError('receiver accepted preview updater ownership')
-`, JSON.stringify(stable), JSON.stringify(receiver)], { cwd: repo })
+`,
+ JSON.stringify(stable),
+ JSON.stringify(receiver)
+ ],
+ { cwd: repo }
+ )
} finally {
fs.rmSync(dir, { recursive: true, force: true })
}
})
-
test('actual MSIX manifest writer consumes the channel quad across rollover instead of semver patch', (): void => {
const root: string = fs.mkdtempSync(path.join(os.tmpdir(), 'channel-manifest-'))
const app: string = path.join(root, 'apps/desktop')
- interface ManifestFacts { version: string; semver: string; appId: string; xml: string }
- interface RecordedMetadata { applicationId: string; version: string }
+ interface ManifestFacts {
+ version: string
+ semver: string
+ appId: string
+ xml: string
+ }
+ interface RecordedMetadata {
+ applicationId: string
+ version: string
+ }
try {
- for (const file of ['apps/desktop/product-identity.cjs', 'apps/desktop/electron-builder.config.cjs',
- 'apps/desktop/package.json', 'apps/desktop/update-feed.cjs', 'apps/desktop/assets/msix-manifest.xml',
- 'apps/desktop/scripts/before-build.mjs', 'apps/desktop/scripts/mac-sign.mjs',
- 'apps/desktop/scripts/payload-digests.mjs', 'apps/desktop/scripts/utils.mjs',
- 'scripts/msix-shared.mjs', 'scripts/release-content-types.json', 'scripts/build/python.mjs',
- 'scripts/bundles/desktop_prepare.py', 'scripts/releases/bundle_env.py', 'hermes_cli/release_channels.py', 'hermes_cli/__init__.py']) {
+ for (const file of [
+ 'apps/desktop/product-identity.cjs',
+ 'apps/desktop/electron-builder.config.cjs',
+ 'apps/desktop/package.json',
+ 'apps/desktop/update-feed.cjs',
+ 'apps/desktop/assets/msix-manifest.xml',
+ 'apps/desktop/scripts/before-build.mjs',
+ 'apps/desktop/scripts/mac-sign.mjs',
+ 'apps/desktop/scripts/payload-digests.mjs',
+ 'apps/desktop/scripts/utils.mjs',
+ 'scripts/msix-shared.mjs',
+ 'scripts/release-content-types.json',
+ 'scripts/build/python.mjs',
+ 'scripts/bundles/desktop_prepare.py',
+ 'scripts/releases/bundle_env.py',
+ 'hermes_cli/release_channels.py',
+ 'hermes_cli/__init__.py'
+ ]) {
const destination: string = path.join(root, file)
fs.mkdirSync(path.dirname(destination), { recursive: true })
fs.copyFileSync(path.join(repo, file), destination)
@@ -192,7 +347,10 @@ test('actual MSIX manifest writer consumes the channel quad across rollover inst
}
fs.mkdirSync(path.join(app, 'build/agent-payload'), { recursive: true })
- fs.writeFileSync(path.join(app, 'build/agent-payload/manifest.json'), JSON.stringify({ launchers: ['hermes-no-registry-needed', 'hermes-no-registry-needed-acp'] }))
+ fs.writeFileSync(
+ path.join(app, 'build/agent-payload/manifest.json'),
+ JSON.stringify({ launchers: ['hermes-no-registry-needed', 'hermes-no-registry-needed-acp'] })
+ )
const facts: ManifestFacts[] = []
for (const sequence of [65535, 65536, 65537, 0xffffffff]) {
@@ -223,7 +381,9 @@ test('actual MSIX manifest writer consumes the channel quad across rollover inst
`
const output: string = execFileSync(process.execPath, ['-e', script], {
- cwd: root, encoding: 'utf8', env: { ...process.env, HERMES_DESKTOP_VARIANT: 'bundled', _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(build) }
+ cwd: root,
+ encoding: 'utf8',
+ env: { ...process.env, HERMES_DESKTOP_VARIANT: 'bundled', _HERMES_CHANNEL_REQUEST_JSON: JSON.stringify(build) }
})
const row: ManifestFacts = JSON.parse(output.trim().split('\n').at(-1)!)
@@ -258,8 +418,11 @@ else:
print(out.read_text(encoding='utf-8'))
`
- const recorded: string = execFileSync(process.env.HERMES_PYTHON || 'python3',
- ['-c', recordScript, repo, root, JSON.stringify(build)], { encoding: 'utf8' })
+ const recorded: string = execFileSync(
+ process.env.HERMES_PYTHON || 'python3',
+ ['-c', recordScript, repo, root, JSON.stringify(build)],
+ { encoding: 'utf8' }
+ )
const metadata: RecordedMetadata = JSON.parse(recorded)
assert.equal(metadata.applicationId, build.identity.appNamePascal)
@@ -272,7 +435,9 @@ print(out.read_text(encoding='utf-8'))
assert.ok(facts[index - 1].version.localeCompare(facts[index].version, undefined, { numeric: true }) < 0)
}
- assert.throws((): void => { load(request(0x100000000)) }, /sequence/)
+ assert.throws((): void => {
+ load(request(0x100000000))
+ }, /sequence/)
} finally {
fs.rmSync(root, { recursive: true, force: true })
}
diff --git a/apps/desktop/electron/cli-provision.test.ts b/apps/desktop/electron/cli-provision.test.ts
index cb64dedec2a..fd59c2f07f2 100644
--- a/apps/desktop/electron/cli-provision.test.ts
+++ b/apps/desktop/electron/cli-provision.test.ts
@@ -19,26 +19,29 @@ function fixture(): { root: string; binDir: string; source: string } {
return { root, binDir, source }
}
-test.runIf(process.platform !== 'win32')('retiring a bundle removes only its direct CLI links, including dangling ones', (): void => {
- const { root, binDir, source }: ReturnType<typeof fixture> = fixture()
- const payload: string = path.dirname(path.dirname(source))
- const target: string = path.join(binDir, 'hermes')
+test.runIf(process.platform !== 'win32')(
+ 'retiring a bundle removes only its direct CLI links, including dangling ones',
+ (): void => {
+ const { root, binDir, source }: ReturnType<typeof fixture> = fixture()
+ const payload: string = path.dirname(path.dirname(source))
+ const target: string = path.join(binDir, 'hermes')
- try {
- provisionCliLinks({ hermes: source }, binDir, (): void => {})
- fs.symlinkSync(path.join(root, 'other/agent-payload/bin/other'), path.join(binDir, 'other'))
- fs.symlinkSync(source, path.join(binDir, 'personal-alias'))
- fs.writeFileSync(path.join(binDir, 'custom'), 'keep')
- fs.rmSync(source)
- removeBundleCliLinks(payload, binDir)
- assert.equal(fs.lstatSync(target, { throwIfNoEntry: false }), undefined)
- assert.deepEqual(fs.readdirSync(binDir).sort(), ['custom', 'other', 'personal-alias'])
- removeBundleCliLinks(payload, binDir)
- assert.equal(fs.readFileSync(path.join(binDir, 'custom'), 'utf8'), 'keep')
- } finally {
- fs.rmSync(root, { recursive: true, force: true })
+ try {
+ provisionCliLinks({ hermes: source }, binDir, (): void => {})
+ fs.symlinkSync(path.join(root, 'other/agent-payload/bin/other'), path.join(binDir, 'other'))
+ fs.symlinkSync(source, path.join(binDir, 'personal-alias'))
+ fs.writeFileSync(path.join(binDir, 'custom'), 'keep')
+ fs.rmSync(source)
+ removeBundleCliLinks(payload, binDir)
+ assert.equal(fs.lstatSync(target, { throwIfNoEntry: false }), undefined)
+ assert.deepEqual(fs.readdirSync(binDir).sort(), ['custom', 'other', 'personal-alias'])
+ removeBundleCliLinks(payload, binDir)
+ assert.equal(fs.readFileSync(path.join(binDir, 'custom'), 'utf8'), 'keep')
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
}
-})
+)
test('repairs owned dangling CLI links without changing foreign or live entries', context => {
const { root, binDir, source } = fixture()
diff --git a/apps/desktop/electron/cli-provision.ts b/apps/desktop/electron/cli-provision.ts
index b8afeb3b120..749251ca29d 100644
--- a/apps/desktop/electron/cli-provision.ts
+++ b/apps/desktop/electron/cli-provision.ts
@@ -2,19 +2,30 @@ import { randomUUID } from 'node:crypto'
import * as fs from 'node:fs'
import path from 'node:path'
-type ProvisionFs = Pick<typeof fs, 'mkdirSync' | 'lstatSync' | 'readlinkSync' | 'statSync' | 'symlinkSync' | 'renameSync' | 'unlinkSync'>
+type ProvisionFs = Pick<
+ typeof fs,
+ 'mkdirSync' | 'lstatSync' | 'readlinkSync' | 'statSync' | 'symlinkSync' | 'renameSync' | 'unlinkSync'
+>
/** Remove only the absolute, same-name links this bundle's provisioner creates. */
export function removeBundleCliLinks(payloadRoot: string, binDir: string): void {
- if (!fs.existsSync(binDir)) { return }
+ if (!fs.existsSync(binDir)) {
+ return
+ }
const payloadBin: string = path.resolve(payloadRoot, 'bin')
for (const entry of fs.readdirSync(binDir, { withFileTypes: true })) {
- if (!entry.isSymbolicLink()) { continue }
+ if (!entry.isSymbolicLink()) {
+ continue
+ }
const link: string = path.join(binDir, entry.name)
const destination: string = fs.readlinkSync(link)
- if (path.isAbsolute(destination) && path.dirname(destination) === payloadBin && path.basename(destination) === entry.name) {
+ if (
+ path.isAbsolute(destination) &&
+ path.dirname(destination) === payloadBin &&
+ path.basename(destination) === entry.name
+ ) {
fs.unlinkSync(link)
}
}
@@ -71,8 +82,12 @@ export function provisionCliLinks(
const bin = path.dirname(destination)
// Only bundled CLI links have this absolute destination shape.
- if (!path.isAbsolute(destination) || path.basename(destination) !== name ||
- path.basename(bin) !== 'bin' || path.basename(path.dirname(bin)) !== 'agent-payload') {
+ if (
+ !path.isAbsolute(destination) ||
+ path.basename(destination) !== name ||
+ path.basename(bin) !== 'bin' ||
+ path.basename(path.dirname(bin)) !== 'agent-payload'
+ ) {
continue
}
@@ -88,7 +103,10 @@ export function provisionCliLinks(
io.unlinkSync(staged)
} catch (cleanupError) {
if ((cleanupError as NodeJS.ErrnoException).code !== 'ENOENT') {
- throw new AggregateError([error, cleanupError], `${String(error)}; temporary link cleanup failed: ${String(cleanupError)}`)
+ throw new AggregateError(
+ [error, cleanupError],
+ `${String(error)}; temporary link cleanup failed: ${String(cleanupError)}`
+ )
}
}
diff --git a/apps/desktop/electron/connection-apply.test.ts b/apps/desktop/electron/connection-apply.test.ts
index 329ae2b47ae..b1cee0460ce 100644
--- a/apps/desktop/electron/connection-apply.test.ts
+++ b/apps/desktop/electron/connection-apply.test.ts
@@ -19,37 +19,34 @@ function deferred() {
}
describe('applyConnectionChange', () => {
- it(
- 'serializes connection changes behind bootstrap rollback before teardown and apply',
- async () => {
- const gate = deferred()
- const events: string[] = []
-
- const run = applyConnectionChange({
- cancelAndWait: async () => {
- events.push('cancel')
- await gate.promise
- events.push('drained')
- },
- isPrimary: true,
- scope: '',
- sendApplied: () => events.push('applied'),
- stopPool: vi.fn(),
- teardownPrimary: async () => {
- events.push('primary')
- },
- teardownSsh: async () => {
- events.push('ssh')
- }
- })
+ it('serializes connection changes behind bootstrap rollback before teardown and apply', async () => {
+ const gate = deferred()
+ const events: string[] = []
- await Promise.resolve()
- expect(events).toEqual(['cancel'])
- gate.resolve()
- await run
- expect(events).toEqual(['cancel', 'drained', 'ssh', 'primary', 'applied'])
- }
- )
+ const run = applyConnectionChange({
+ cancelAndWait: async () => {
+ events.push('cancel')
+ await gate.promise
+ events.push('drained')
+ },
+ isPrimary: true,
+ scope: '',
+ sendApplied: () => events.push('applied'),
+ stopPool: vi.fn(),
+ teardownPrimary: async () => {
+ events.push('primary')
+ },
+ teardownSsh: async () => {
+ events.push('ssh')
+ }
+ })
+
+ await Promise.resolve()
+ expect(events).toEqual(['cancel'])
+ gate.resolve()
+ await run
+ expect(events).toEqual(['cancel', 'drained', 'ssh', 'primary', 'applied'])
+ })
it('tears down only a non-primary scope without applying the primary connection', async () => {
const events: string[] = []
@@ -98,10 +95,25 @@ it.each([
[false, 0, 0, true, true],
[true, 1, 1, true, false],
[false, 0, 0, false, false]
-] as const)('quit guard: done=%s connections=%s bootstrap=%s stopping=%s → %s',
- (teardownDone: boolean, connectionCount: number, bootstrapPending: number, stopping: boolean, expected: boolean): void => {
- expect(sshQuitShouldBlock({ teardownDone, connectionCount, bootstrapPending, inFlight: stopping ? Promise.resolve() : null })).toBe(expected)
- })
+] as const)(
+ 'quit guard: done=%s connections=%s bootstrap=%s stopping=%s → %s',
+ (
+ teardownDone: boolean,
+ connectionCount: number,
+ bootstrapPending: number,
+ stopping: boolean,
+ expected: boolean
+ ): void => {
+ expect(
+ sshQuitShouldBlock({
+ teardownDone,
+ connectionCount,
+ bootstrapPending,
+ inFlight: stopping ? Promise.resolve() : null
+ })
+ ).toBe(expected)
+ }
+)
describe('teardownSshState', () => {
it('terminates the owned remote backend before closing its tunnel and SSH transport', async () => {
diff --git a/apps/desktop/electron/desktop-boot-preference.ts b/apps/desktop/electron/desktop-boot-preference.ts
index 25846684130..768e8ccad84 100644
--- a/apps/desktop/electron/desktop-boot-preference.ts
+++ b/apps/desktop/electron/desktop-boot-preference.ts
@@ -18,7 +18,9 @@ export function readDesktopBootPreference(file: string): DesktopBootPreference |
try {
text = readFileSync(file, 'utf8')
} catch (error: unknown) {
- if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { return null }
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
+ return null
+ }
throw error
}
@@ -55,7 +57,10 @@ function parseDesktopBootPreference(text: string): DesktopBootPreference {
}
/* oxlint-enable anti-slop/no-runtime-typeof */
-function updatePreference(file: string, update: (current: DesktopBootPreference | null) => DesktopBootPreference): DesktopBootPreference {
+function updatePreference(
+ file: string,
+ update: (current: DesktopBootPreference | null) => DesktopBootPreference
+): DesktopBootPreference {
mkdirSync(path.dirname(file), { recursive: true })
const temporary: string = `${file}.${randomUUID()}.tmp`
@@ -74,11 +79,22 @@ function updatePreference(file: string, update: (current: DesktopBootPreference
writeFileSync(temporary, JSON.stringify(next, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
const handle: number = openSync(temporary, 'r+')
- try { fsyncSync(handle) } finally { closeSync(handle) }
+
+ try {
+ fsyncSync(handle)
+ } finally {
+ closeSync(handle)
+ }
renameSync(temporary, file)
+
if (process.platform !== 'win32') {
const directory: number = openSync(path.dirname(file), 'r')
- try { fsyncSync(directory) } finally { closeSync(directory) }
+
+ try {
+ fsyncSync(directory)
+ } finally {
+ closeSync(directory)
+ }
}
return next
@@ -88,7 +104,9 @@ function updatePreference(file: string, update: (current: DesktopBootPreference
}
export function writeDesktopProfile(file: string, profile: string | null): string | null {
- if (!validProfile(profile)) { throw new Error(`Invalid profile name: ${profile}`) }
+ if (!validProfile(profile)) {
+ throw new Error(`Invalid profile name: ${profile}`)
+ }
return updatePreference(file, (current: DesktopBootPreference | null): DesktopBootPreference => {
const next: DesktopBootPreference = { ...current, profile }
diff --git a/apps/desktop/electron/desktop-uninstall.test.ts b/apps/desktop/electron/desktop-uninstall.test.ts
index 6ef1d3127f4..351520286db 100644
--- a/apps/desktop/electron/desktop-uninstall.test.ts
+++ b/apps/desktop/electron/desktop-uninstall.test.ts
@@ -164,38 +164,60 @@ test('shouldRemoveAppBundle requires packaged AND a resolved path', () => {
assert.equal(shouldRemoveAppBundle(false, null), false)
})
-test.skipIf(process.platform === 'win32').each(['gui', 'lite', 'full'] as const)('POSIX cleanup executes %s in its sandbox and preserves its sibling', async (mode: string): Promise<void> => {
- const root: string = fs.mkdtempSync(path.join(os.tmpdir(), "uninstall-o'brien-"))
- const app: string = path.join(root, 'App with spaces')
- const sibling: string = path.join(root, 'App with spaces-other')
- const recorder: string = path.join(root, "recorder's.cjs")
- const resultFile: string = path.join(root, 'observed.json')
- const script: string = path.join(root, 'cleanup.sh')
- let child: ChildProcess | undefined
-
- try {
- fs.mkdirSync(app); fs.mkdirSync(sibling)
- fs.writeFileSync(recorder, `require('node:fs').writeFileSync(${JSON.stringify(resultFile)}, JSON.stringify({argv:process.argv.slice(2), home:process.env.HERMES_HOME, pythonPath:process.env.PYTHONPATH, cwd:process.cwd()}))`)
- fs.writeFileSync(script, buildPosixCleanupScript({
- desktopPid: 0, pythonExe: process.execPath, pythonPath: mode === 'gui' ? null : root,
- agentRoot: root, uninstallArgs: [recorder, ...uninstallArgsForMode(mode)],
- appPath: mode === 'lite' ? null : app, hermesHome: root
- }))
- child = spawn('bash', [script], { env: { ...process.env, PYTHONPATH: 'inherited', HERMES_HOME: root }, stdio: 'ignore' })
- await once(child, 'close')
- assert.equal(child.exitCode, 0)
- assert.deepEqual(JSON.parse(fs.readFileSync(resultFile, 'utf8')), {
- argv: ['-m', 'hermes_cli.uninstall', '--mode', mode], home: root,
- pythonPath: mode === 'gui' ? 'inherited' : `${root}:inherited`, cwd: root
- })
- assert.equal(fs.existsSync(app), mode === 'lite')
- assert.equal(fs.existsSync(sibling), true)
- assert.equal(fs.existsSync(script), false)
- } finally {
- if (child && child.exitCode === null && child.signalCode === null) { child.kill(); await once(child, 'close') }
- fs.rmSync(root, { recursive: true, force: true })
+test.skipIf(process.platform === 'win32').each(['gui', 'lite', 'full'] as const)(
+ 'POSIX cleanup executes %s in its sandbox and preserves its sibling',
+ async (mode: string): Promise<void> => {
+ const root: string = fs.mkdtempSync(path.join(os.tmpdir(), "uninstall-o'brien-"))
+ const app: string = path.join(root, 'App with spaces')
+ const sibling: string = path.join(root, 'App with spaces-other')
+ const recorder: string = path.join(root, "recorder's.cjs")
+ const resultFile: string = path.join(root, 'observed.json')
+ const script: string = path.join(root, 'cleanup.sh')
+ let child: ChildProcess | undefined
+
+ try {
+ fs.mkdirSync(app)
+ fs.mkdirSync(sibling)
+ fs.writeFileSync(
+ recorder,
+ `require('node:fs').writeFileSync(${JSON.stringify(resultFile)}, JSON.stringify({argv:process.argv.slice(2), home:process.env.HERMES_HOME, pythonPath:process.env.PYTHONPATH, cwd:process.cwd()}))`
+ )
+ fs.writeFileSync(
+ script,
+ buildPosixCleanupScript({
+ desktopPid: 0,
+ pythonExe: process.execPath,
+ pythonPath: mode === 'gui' ? null : root,
+ agentRoot: root,
+ uninstallArgs: [recorder, ...uninstallArgsForMode(mode)],
+ appPath: mode === 'lite' ? null : app,
+ hermesHome: root
+ })
+ )
+ child = spawn('bash', [script], {
+ env: { ...process.env, PYTHONPATH: 'inherited', HERMES_HOME: root },
+ stdio: 'ignore'
+ })
+ await once(child, 'close')
+ assert.equal(child.exitCode, 0)
+ assert.deepEqual(JSON.parse(fs.readFileSync(resultFile, 'utf8')), {
+ argv: ['-m', 'hermes_cli.uninstall', '--mode', mode],
+ home: root,
+ pythonPath: mode === 'gui' ? 'inherited' : `${root}:inherited`,
+ cwd: root
+ })
+ assert.equal(fs.existsSync(app), mode === 'lite')
+ assert.equal(fs.existsSync(sibling), true)
+ assert.equal(fs.existsSync(script), false)
+ } finally {
+ if (child && child.exitCode === null && child.signalCode === null) {
+ child.kill()
+ await once(child, 'close')
+ }
+ fs.rmSync(root, { recursive: true, force: true })
+ }
}
-})
+)
test('buildPosixCleanupScript waits for the PID, runs the uninstall module, removes bundle', (): void => {
const script = buildPosixCleanupScript({
diff --git a/apps/desktop/electron/external-open.ts b/apps/desktop/electron/external-open.ts
index 89475f4ea53..6e1d48fb44c 100644
--- a/apps/desktop/electron/external-open.ts
+++ b/apps/desktop/electron/external-open.ts
@@ -16,9 +16,7 @@
import type { ChildProcess, SpawnOptions } from 'node:child_process'
export type ExternalOpenResult =
- | { ok: true }
- | { ok: false; reason: 'invalid' }
- | { ok: false; reason: 'failed'; message: string }
+ { ok: true } | { ok: false; reason: 'invalid' } | { ok: false; reason: 'failed'; message: string }
export interface ExternalOpenDeps {
isWsl: boolean
@@ -41,10 +39,7 @@ export function externalOpenErrorMessage(error: unknown): string {
* failure is logged + reported through notifyFailure and resolves `failed`,
* so fire-and-forget callers can `void` the result safely.
*/
-export async function openExternalUrl(
- rawUrl: string,
- deps: ExternalOpenDeps
-): Promise<ExternalOpenResult> {
+export async function openExternalUrl(rawUrl: string, deps: ExternalOpenDeps): Promise<ExternalOpenResult> {
const raw = String(rawUrl || '').trim()
if (!raw) {
diff --git a/apps/desktop/electron/feature-flags.ts b/apps/desktop/electron/feature-flags.ts
index 9a23e22644c..197b0b45485 100644
--- a/apps/desktop/electron/feature-flags.ts
+++ b/apps/desktop/electron/feature-flags.ts
@@ -1,7 +1,6 @@
const featureFlags = {
/** Local-models GUI surfaces (settings pane, pickers, statusbar, tips). */
- localModels: ({ argv }) =>
- process.platform === 'win32' || process.platform === 'darwin' || argv.includes('--local')
+ localModels: ({ argv }) => process.platform === 'win32' || process.platform === 'darwin' || argv.includes('--local')
} satisfies Record<string, (args: FeatureFlagInput) => boolean>
export type FeatureFlags = { [K in keyof typeof featureFlags]: boolean }
diff --git a/apps/desktop/electron/first-run-setup-gate.ts b/apps/desktop/electron/first-run-setup-gate.ts
index 6f4a4a5a6b7..29101038eb2 100644
--- a/apps/desktop/electron/first-run-setup-gate.ts
+++ b/apps/desktop/electron/first-run-setup-gate.ts
@@ -60,11 +60,7 @@ export function createFirstRunSetupGate({
}
const shouldGate = (backend?: FirstRunSetupBackend | null) =>
- Boolean(
- backend &&
- backend.kind === 'bootstrap-needed' &&
- !localBootstrapConfirmed
- )
+ Boolean(backend && backend.kind === 'bootstrap-needed' && !localBootstrapConfirmed)
const wait = async (backend?: FirstRunSetupBackend | null) => {
if (!shouldGate(backend)) {
diff --git a/apps/desktop/electron/gateway-stop-before-update.test.ts b/apps/desktop/electron/gateway-stop-before-update.test.ts
index db32e847de4..bf692971ff9 100644
--- a/apps/desktop/electron/gateway-stop-before-update.test.ts
+++ b/apps/desktop/electron/gateway-stop-before-update.test.ts
@@ -2,10 +2,7 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
-import {
- GATEWAY_STOP_TIMEOUT_MS,
- stopGatewayBeforeUpdate
-} from './gateway-stop-before-update'
+import { GATEWAY_STOP_TIMEOUT_MS, stopGatewayBeforeUpdate } from './gateway-stop-before-update'
const CLI = 'C:\\Users\\x\\hermes\\hermes-agent\\venv\\Scripts\\hermes.exe'
const HOME = 'C:\\Users\\x\\hermes'
diff --git a/apps/desktop/electron/gateway-stop-before-update.ts b/apps/desktop/electron/gateway-stop-before-update.ts
index 6661d59ccd1..0028a3c2e1f 100644
--- a/apps/desktop/electron/gateway-stop-before-update.ts
+++ b/apps/desktop/electron/gateway-stop-before-update.ts
@@ -25,7 +25,6 @@ export function stopGatewayBeforeUpdate(
return runGatewayLifecycleCommand(hermesCliPath, ['gateway', 'stop', '--all'], deps)
}
-
function runGatewayLifecycleCommand(hermesCliPath: string, args: string[], deps: StopGatewayBeforeUpdateDeps): boolean {
const isWindows = deps.isWindows ?? process.platform === 'win32'
diff --git a/apps/desktop/electron/gateway-version.test.ts b/apps/desktop/electron/gateway-version.test.ts
index aa4619d2c60..0435c9aefd9 100644
--- a/apps/desktop/electron/gateway-version.test.ts
+++ b/apps/desktop/electron/gateway-version.test.ts
@@ -7,7 +7,9 @@ import { resolveGatewayVersion } from './gateway-version'
test('version follows each supplied gateway response without caching', async (): Promise<void> => {
let version: string = '1.2.3'
- const request: (endpoint: string) => Promise<{ version: string }> = async (endpoint: string): Promise<{ version: string }> => {
+ const request: (endpoint: string) => Promise<{ version: string }> = async (
+ endpoint: string
+ ): Promise<{ version: string }> => {
assert.equal(endpoint, '/api/health')
return { version }
@@ -23,5 +25,10 @@ test('unavailable gateway version stays unknown instead of using another install
assert.equal(await resolveGatewayVersion(async () => response), '')
}
- assert.equal(await resolveGatewayVersion(async () => { throw new Error('offline') }), '')
+ assert.equal(
+ await resolveGatewayVersion(async () => {
+ throw new Error('offline')
+ }),
+ ''
+ )
})
diff --git a/apps/desktop/electron/guest-onboarding.ts b/apps/desktop/electron/guest-onboarding.ts
index 997604a59e1..a82290d9c9a 100644
--- a/apps/desktop/electron/guest-onboarding.ts
+++ b/apps/desktop/electron/guest-onboarding.ts
@@ -20,7 +20,10 @@ export function guestOnboardingEnabled(
return env[GUEST_ONBOARDING_ENV] === '1' || argv.includes(GUEST_ONBOARDING_FLAG)
}
-export function skipIntroEnabled(argv: readonly string[] = process.argv, env: NodeJS.ProcessEnv = process.env): boolean {
+export function skipIntroEnabled(
+ argv: readonly string[] = process.argv,
+ env: NodeJS.ProcessEnv = process.env
+): boolean {
return env[SKIP_INTRO_ENV] === '1' || argv.includes(SKIP_INTRO_FLAG)
}
diff --git a/apps/desktop/electron/hardening.test.ts b/apps/desktop/electron/hardening.test.ts
index 98086285ea4..dee40ae0f32 100644
--- a/apps/desktop/electron/hardening.test.ts
+++ b/apps/desktop/electron/hardening.test.ts
@@ -156,19 +156,22 @@ test('encryptDesktopSecret stores safeStorage base64 payload', () => {
// ─── Owner-only credential files (connection.json) ─────────────────────────
-test.runIf(process.platform !== 'win32')('writeSecretFileAtomic creates the file owner-only, not at the 0644 umask default', () => {
- withTempDir(dir => {
- const target = path.join(dir, 'connection.json')
- const payload = JSON.stringify({ remote: { token: { encoding: SAFE_STORAGE_ENCODING, value: 'BLOB' } } })
+test.runIf(process.platform !== 'win32')(
+ 'writeSecretFileAtomic creates the file owner-only, not at the 0644 umask default',
+ () => {
+ withTempDir(dir => {
+ const target = path.join(dir, 'connection.json')
+ const payload = JSON.stringify({ remote: { token: { encoding: SAFE_STORAGE_ENCODING, value: 'BLOB' } } })
- writeSecretFileAtomic(target, payload)
+ writeSecretFileAtomic(target, payload)
- assert.equal(modeOf(target), SECRET_FILE_MODE)
- assert.equal(modeOf(target) & 0o077, 0, 'no group/other bits')
- assert.equal(fs.readFileSync(target, 'utf8'), payload, 'content round-trips')
- assertNoSecretDebris(dir, 'connection.json', 'BLOB')
- })
-})
+ assert.equal(modeOf(target), SECRET_FILE_MODE)
+ assert.equal(modeOf(target) & 0o077, 0, 'no group/other bits')
+ assert.equal(fs.readFileSync(target, 'utf8'), payload, 'content round-trips')
+ assertNoSecretDebris(dir, 'connection.json', 'BLOB')
+ })
+ }
+)
test('encryptDesktopSecret allows plain-text opt-in when encryption is unavailable', () => {
const secret = encryptDesktopSecret(
@@ -443,21 +446,24 @@ test('resolveRemoteTokenPlainText warns only when the token is plain and the mac
)
})
-test.runIf(process.platform !== 'win32')('writeSecretFileAtomic does not inherit loose bits from a stale temp file', () => {
- // renameSync keeps the TEMP file's permissions, and writeFileSync's `mode`
- // is ignored when the path already exists — so a temp left by a crashed
- // earlier write would otherwise hand 0644 straight to the target.
- withTempDir(dir => {
- const target = path.join(dir, 'connection.json')
- fs.writeFileSync(`${target}.tmp`, 'stale', { mode: 0o666 })
- assert.notEqual(modeOf(`${target}.tmp`), SECRET_FILE_MODE)
+test.runIf(process.platform !== 'win32')(
+ 'writeSecretFileAtomic does not inherit loose bits from a stale temp file',
+ () => {
+ // renameSync keeps the TEMP file's permissions, and writeFileSync's `mode`
+ // is ignored when the path already exists — so a temp left by a crashed
+ // earlier write would otherwise hand 0644 straight to the target.
+ withTempDir(dir => {
+ const target = path.join(dir, 'connection.json')
+ fs.writeFileSync(`${target}.tmp`, 'stale', { mode: 0o666 })
+ assert.notEqual(modeOf(`${target}.tmp`), SECRET_FILE_MODE)
- writeSecretFileAtomic(target, 'fresh')
+ writeSecretFileAtomic(target, 'fresh')
- assert.equal(modeOf(target), SECRET_FILE_MODE)
- assert.equal(fs.readFileSync(target, 'utf8'), 'fresh')
- })
-})
+ assert.equal(modeOf(target), SECRET_FILE_MODE)
+ assert.equal(fs.readFileSync(target, 'utf8'), 'fresh')
+ })
+ }
+)
/**
* Owner-only is carried by two independent mechanisms — the create-time `mode`
@@ -496,20 +502,23 @@ test.runIf(process.platform !== 'win32')('the written file is owner-only even wh
})
})
-test.runIf(process.platform !== 'win32')('the written file is owner-only even when a stale temp cannot be removed', () => {
- // The unlink is best-effort; if the stale temp survives, writeFileSync's
- // `mode` is ignored on an existing path and only the chmod before the rename
- // can still fix the bits.
- withTempDir(dir => {
- const target = path.join(dir, 'connection.json')
- fs.writeFileSync(`${target}.tmp`, 'stale', { mode: 0o666 })
+test.runIf(process.platform !== 'win32')(
+ 'the written file is owner-only even when a stale temp cannot be removed',
+ () => {
+ // The unlink is best-effort; if the stale temp survives, writeFileSync's
+ // `mode` is ignored on an existing path and only the chmod before the rename
+ // can still fix the bits.
+ withTempDir(dir => {
+ const target = path.join(dir, 'connection.json')
+ fs.writeFileSync(`${target}.tmp`, 'stale', { mode: 0o666 })
- writeSecretFileAtomic(target, 'tok', { fs: fsWith({ rmSync: () => void 0 }) })
+ writeSecretFileAtomic(target, 'tok', { fs: fsWith({ rmSync: () => void 0 }) })
- assert.equal(modeOf(target), SECRET_FILE_MODE, 'tightened before the rename handed the bits over')
- assert.equal(fs.readFileSync(target, 'utf8'), 'tok')
- })
-})
+ assert.equal(modeOf(target), SECRET_FILE_MODE, 'tightened before the rename handed the bits over')
+ assert.equal(fs.readFileSync(target, 'utf8'), 'tok')
+ })
+ }
+)
test('writeSecretFileAtomic cannot be redirected through a symlink planted at the temp path', context => {
// A stale temp path is attacker-controllable in a shared temp/userData dir.
@@ -544,69 +553,78 @@ test('writeSecretFileAtomic cannot be redirected through a symlink planted at th
})
})
-test.runIf(process.platform !== 'win32')('tightenSecretFileMode tightens a pre-existing world-readable config in place', () => {
- // The upgrade path: a connection.json written by an older build sits at 0644
- // with a real (encrypted) token in it. Tightening must change the mode and
- // nothing else — the token has to stay readable or the user loses their
- // configured gateway.
- withTempDir(dir => {
- const target = path.join(dir, 'connection.json')
+test.runIf(process.platform !== 'win32')(
+ 'tightenSecretFileMode tightens a pre-existing world-readable config in place',
+ () => {
+ // The upgrade path: a connection.json written by an older build sits at 0644
+ // with a real (encrypted) token in it. Tightening must change the mode and
+ // nothing else — the token has to stay readable or the user loses their
+ // configured gateway.
+ withTempDir(dir => {
+ const target = path.join(dir, 'connection.json')
+
+ const legacy = JSON.stringify({
+ mode: 'remote',
+ remote: {
+ url: 'https://gw.example.com',
+ authMode: 'token',
+ token: { encoding: SAFE_STORAGE_ENCODING, value: 'BLOB' }
+ }
+ })
- const legacy = JSON.stringify({
- mode: 'remote',
- remote: {
- url: 'https://gw.example.com',
- authMode: 'token',
- token: { encoding: SAFE_STORAGE_ENCODING, value: 'BLOB' }
- }
- })
+ fs.writeFileSync(target, legacy, { mode: 0o644 })
+ assert.equal(modeOf(target), 0o644)
- fs.writeFileSync(target, legacy, { mode: 0o644 })
- assert.equal(modeOf(target), 0o644)
+ assert.equal(tightenSecretFileMode(target), true)
- assert.equal(tightenSecretFileMode(target), true)
+ assert.equal(modeOf(target), SECRET_FILE_MODE)
+ assert.deepEqual(JSON.parse(fs.readFileSync(target, 'utf8')), JSON.parse(legacy), 'contents untouched')
+ })
+ }
+)
- assert.equal(modeOf(target), SECRET_FILE_MODE)
- assert.deepEqual(JSON.parse(fs.readFileSync(target, 'utf8')), JSON.parse(legacy), 'contents untouched')
- })
-})
+test.runIf(process.platform !== 'win32')(
+ 'tightenSecretFileMode leaves a non-safeStorage token payload readable',
+ () => {
+ // A hand-edited config (or one from a pre-release build) can hold a
+ // non-safeStorage token payload, which decryptDesktopSecret still reads
+ // verbatim on purpose. Tightening the mode must not disturb that fallback —
+ // it only narrows who can open the file.
+ withTempDir(dir => {
+ const target = path.join(dir, 'connection.json')
-test.runIf(process.platform !== 'win32')('tightenSecretFileMode leaves a non-safeStorage token payload readable', () => {
- // A hand-edited config (or one from a pre-release build) can hold a
- // non-safeStorage token payload, which decryptDesktopSecret still reads
- // verbatim on purpose. Tightening the mode must not disturb that fallback —
- // it only narrows who can open the file.
- withTempDir(dir => {
- const target = path.join(dir, 'connection.json')
+ const legacyPlain = JSON.stringify({
+ mode: 'remote',
+ remote: { url: 'https://gw.example.com', authMode: 'token', token: { encoding: 'plain', value: 'tok-live-42' } }
+ })
- const legacyPlain = JSON.stringify({
- mode: 'remote',
- remote: { url: 'https://gw.example.com', authMode: 'token', token: { encoding: 'plain', value: 'tok-live-42' } }
- })
+ fs.writeFileSync(target, legacyPlain, { mode: 0o644 })
- fs.writeFileSync(target, legacyPlain, { mode: 0o644 })
+ tightenSecretFileMode(target)
- tightenSecretFileMode(target)
+ assert.equal(modeOf(target), SECRET_FILE_MODE)
+ assert.equal(JSON.parse(fs.readFileSync(target, 'utf8')).remote.token.value, 'tok-live-42')
+ })
+ }
+)
- assert.equal(modeOf(target), SECRET_FILE_MODE)
- assert.equal(JSON.parse(fs.readFileSync(target, 'utf8')).remote.token.value, 'tok-live-42')
- })
-})
+test.runIf(process.platform !== 'win32')(
+ 'tightenSecretFileMode is idempotent and never throws on an unusable path',
+ () => {
+ withTempDir(dir => {
+ const target = path.join(dir, 'connection.json')
+ writeSecretFileAtomic(target, '{}')
-test.runIf(process.platform !== 'win32')('tightenSecretFileMode is idempotent and never throws on an unusable path', () => {
- withTempDir(dir => {
- const target = path.join(dir, 'connection.json')
- writeSecretFileAtomic(target, '{}')
-
- assert.equal(tightenSecretFileMode(target), true)
- assert.equal(tightenSecretFileMode(target), true)
- assert.equal(modeOf(target), SECRET_FILE_MODE)
+ assert.equal(tightenSecretFileMode(target), true)
+ assert.equal(tightenSecretFileMode(target), true)
+ assert.equal(modeOf(target), SECRET_FILE_MODE)
- // Missing file (fresh install, nothing saved yet) reports failure quietly
- // instead of breaking the read path it is called from.
- assert.equal(tightenSecretFileMode(path.join(dir, 'absent.json')), false)
- })
-})
+ // Missing file (fresh install, nothing saved yet) reports failure quietly
+ // instead of breaking the read path it is called from.
+ assert.equal(tightenSecretFileMode(path.join(dir, 'absent.json')), false)
+ })
+ }
+)
test('tightenSecretFileMode never changes a symlink target', context => {
// Matches readInstallationId in desktop-installation.ts. Without the lstat
@@ -633,38 +651,41 @@ test('tightenSecretFileMode never changes a symlink target', context => {
})
})
-test.runIf(process.platform !== 'win32')('tightenSecretFileMode only touches a regular file the current user owns', () => {
- // Directories, sockets, fifos and files owned by another account are all
- // "not ours to chmod". Injected lstat so the foreign-owner branch is
- // reachable without a second OS account.
- const chmodded: string[] = []
+test.runIf(process.platform !== 'win32')(
+ 'tightenSecretFileMode only touches a regular file the current user owns',
+ () => {
+ // Directories, sockets, fifos and files owned by another account are all
+ // "not ours to chmod". Injected lstat so the foreign-owner branch is
+ // reachable without a second OS account.
+ const chmodded: string[] = []
+
+ const fakeFs = (stat: Record<string, unknown>) =>
+ ({
+ chmodSync: (filePath: string) => void chmodded.push(filePath),
+ lstatSync: () => ({ isFile: () => true, isSymbolicLink: () => false, mode: 0o644, uid: 0, ...stat }),
+ renameSync: () => void 0,
+ rmSync: () => void 0,
+ writeFileSync: () => void 0
+ }) as any
+
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 0
- const fakeFs = (stat: Record<string, unknown>) =>
- ({
- chmodSync: (filePath: string) => void chmodded.push(filePath),
- lstatSync: () => ({ isFile: () => true, isSymbolicLink: () => false, mode: 0o644, uid: 0, ...stat }),
- renameSync: () => void 0,
- rmSync: () => void 0,
- writeFileSync: () => void 0
- }) as any
-
- const uid = typeof process.getuid === 'function' ? process.getuid() : 0
-
- assert.equal(
- tightenSecretFileMode('/x/connection.json', { fs: fakeFs({ isFile: () => false }), platform: 'linux' }),
- false
- )
- assert.equal(
- tightenSecretFileMode('/x/connection.json', { fs: fakeFs({ uid: uid + 1 }), platform: 'linux' }),
- false,
- 'a file owned by another user is left alone'
- )
- assert.deepEqual(chmodded, [], 'nothing was chmodded on the rejected paths')
+ assert.equal(
+ tightenSecretFileMode('/x/connection.json', { fs: fakeFs({ isFile: () => false }), platform: 'linux' }),
+ false
+ )
+ assert.equal(
+ tightenSecretFileMode('/x/connection.json', { fs: fakeFs({ uid: uid + 1 }), platform: 'linux' }),
+ false,
+ 'a file owned by another user is left alone'
+ )
+ assert.deepEqual(chmodded, [], 'nothing was chmodded on the rejected paths')
- // The same fs shape, but ours and loose: now it tightens.
- assert.equal(tightenSecretFileMode('/x/connection.json', { fs: fakeFs({ uid }), platform: 'linux' }), true)
- assert.deepEqual(chmodded, ['/x/connection.json'])
-})
+ // The same fs shape, but ours and loose: now it tightens.
+ assert.equal(tightenSecretFileMode('/x/connection.json', { fs: fakeFs({ uid }), platform: 'linux' }), true)
+ assert.deepEqual(chmodded, ['/x/connection.json'])
+ }
+)
test('tightenSecretFileMode leaves Windows alone rather than flipping the read-only bit', () => {
const chmods: string[] = []
diff --git a/apps/desktop/electron/install-stamp.ts b/apps/desktop/electron/install-stamp.ts
index 72e3722d36f..280b028393d 100644
--- a/apps/desktop/electron/install-stamp.ts
+++ b/apps/desktop/electron/install-stamp.ts
@@ -67,7 +67,18 @@ export interface InstallStamp {
builtAt: string | null
dirty: boolean
/** Build provenance: where the stamp's facts came from. */
- source: 'build' | 'commit-build' | 'channel-build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown' | null
+ source:
+ | 'build'
+ | 'commit-build'
+ | 'channel-build'
+ | 'ci'
+ | 'docker'
+ | 'fallback'
+ | 'git'
+ | 'local'
+ | 'nix'
+ | 'unknown'
+ | null
/** The steward of a sealed tree ('desktop-app' | 'docker' | 'nix'), when packaged. */
distribution: string | null
/** Who applies the next update. Required in every stamp. */
diff --git a/apps/desktop/electron/machine-profile.ts b/apps/desktop/electron/machine-profile.ts
index 98c7b3e8c3a..8d980139870 100644
--- a/apps/desktop/electron/machine-profile.ts
+++ b/apps/desktop/electron/machine-profile.ts
@@ -63,7 +63,7 @@ function readHardwareModel(): string {
async function hasNvidiaGpu(): Promise<boolean> {
try {
// Chromium already enumerates GPUs; no vendor tools or subprocess are needed.
- const info = await app.getGPUInfo('basic') as { gpuDevice?: { vendorId?: number }[] }
+ const info = (await app.getGPUInfo('basic')) as { gpuDevice?: { vendorId?: number }[] }
return (info.gpuDevice ?? []).some((device): boolean => device.vendorId === 0x10de)
} catch {
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 82ef485164e..93464abbf36 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -35,13 +35,7 @@ import {
import type { Session } from 'electron'
import { type ActiveRuntimeState, classifyActiveRuntime } from './active-runtime-state'
-import {
- destroyKeepaliveAgents,
- htmlResponseError,
- jsonAgentFor,
- readJsonErrorBody,
- withRetry
-} from './api-transport'
+import { destroyKeepaliveAgents, htmlResponseError, jsonAgentFor, readJsonErrorBody, withRetry } from './api-transport'
import { appIconCandidates, resolveAppIcon } from './app-icon'
import { stageAppInstallerFile } from './app-installer-file'
import { appVersionInfo, type AppVersionInfo, assertSourceUpdateChannel, packagedReleaseChannel } from './app-version'
@@ -65,17 +59,14 @@ import { createBackendConnectionState } from './backend-connection-state'
import { BackendDialClaims } from './backend-dial-claim'
import { buildDesktopBackendEnv } from './backend-env'
import { createBackendExitRecoveryLatch } from './backend-exit-recovery'
+import { isReauthRequiredError, waitForHermesReady } from './backend-health'
import {
- isReauthRequiredError,
- waitForHermesReady
-} from './backend-health'
-import { backendCommandMatches, type BackendOwnershipEntry, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'
-import {
- canImportHermesCli,
- PROBE_TIMEOUT_MS,
- shouldTrustHermesOverride,
- verifyHermesCli
-} from './backend-probes'
+ backendCommandMatches,
+ type BackendOwnershipEntry,
+ createBackendOwnership,
+ createBackendShutdownCoordinator
+} from './backend-ownership'
+import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyHermesCli } from './backend-probes'
import { waitForDashboardPortAnnouncement } from './backend-ready'
import { recycleOwnedBackend } from './backend-recycle'
import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate'
@@ -317,8 +308,8 @@ import {
import { registerMcpOauthCallbackIpc } from './mcp-oauth-callback-ipc'
import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'
import { fetchLocalMedia } from './media-range'
-import type { GatedDownloadAuth } from './native-auth-decisions'
import { createMinimizeToTray } from './minimize-to-tray'
+import type { GatedDownloadAuth } from './native-auth-decisions'
import {
oauthSessionIsLive,
resolveGatedDownloadAuth,
@@ -492,15 +483,18 @@ import { ChannelResolver, type ChannelTarget } from './updater/channel'
import { inspectRunningChannelApp } from './updater/channel-native'
import { ChannelStrategy } from './updater/channel-strategy'
import { verifyPreparedChannelInstaller } from './updater/channel-windows-host'
-import {
- createCheckoutStrategy
-} from './updater/checkout'
+import { createCheckoutStrategy } from './updater/checkout'
import { readSourceUpdate, type SourceUpdate } from './updater/checkout-source'
import { ExternalStrategy } from './updater/external'
import { readUpdatesFeedBaseFromConfig } from './updater/feed-config'
import { createChannelMacStrategy, createMacStrategy } from './updater/mac-client'
import { UpdateOperation } from './updater/operation'
-import { type ConsumedRelaunch, consumePendingRelaunch, registerUpdateRelaunch, type RelaunchRegistration } from './updater/relaunch'
+import {
+ type ConsumedRelaunch,
+ consumePendingRelaunch,
+ registerUpdateRelaunch,
+ type RelaunchRegistration
+} from './updater/relaunch'
import { startRelaunchWaiter } from './updater/relaunch-waiter'
import { preflightStateDb } from './updater/state-db-preflight'
import { createStoreStrategy } from './updater/store-client'
@@ -527,11 +521,7 @@ import {
MIN_WIDTH as WINDOW_MIN_WIDTH
} from './window-state'
import { hiddenWindowsChildOptions } from './windows-child-options'
-import {
- buildPathExtCandidates,
- chooseUpdaterArgs,
- resolveVenvHermesCommand
-} from './windows-hermes-path'
+import { buildPathExtCandidates, chooseUpdaterArgs, resolveVenvHermesCommand } from './windows-hermes-path'
import {
connectWindowsRemote,
detectRemotePlatform,
@@ -805,7 +795,9 @@ const DESKTOP_PROFILE_CONFIG_PATH: string = path.join(app.getPath('userData'), '
// Only the lock-owning destination may adopt a workspace or start a backend.
const isPrimaryInstance: boolean = app.requestSingleInstanceLock()
-if (!isPrimaryInstance) { app.exit(0) }
+if (!isPrimaryInstance) {
+ app.exit(0)
+}
const HERMES_HOME: string = resolveDesktopHermesHome({
home: app.getPath('home'),
@@ -813,7 +805,6 @@ const HERMES_HOME: string = resolveDesktopHermesHome({
readWindowsHome: (): string | null => readWindowsUserEnvVar('HERMES_HOME')
})
-
// ACTIVE_HERMES_ROOT — the canonical mutable Hermes install. Same path
// install.ps1 / install.sh use, so a desktop-only user and a CLI-only user end
// up with identical layouts and can share one install.
@@ -1400,7 +1391,8 @@ const localBackendLifecycle = createLocalBackendLifecycle<ChildProcess>({
stopBackendChildImpl(child, { forceKillProcessTree, isWindows: IS_WINDOWS })
}
},
- waitForExit: (child: ChildProcess): Promise<void> => waitForBackendExit(child, { forceKillProcessTree, isWindows: IS_WINDOWS }),
+ waitForExit: (child: ChildProcess): Promise<void> =>
+ waitForBackendExit(child, { forceKillProcessTree, isWindows: IS_WINDOWS }),
cancelSetup: (): void => {
firstRunSetupGate?.resetForRetry()
bootstrapAbortController?.abort()
@@ -3083,7 +3075,9 @@ async function checkUpdates(opts: { force?: boolean } = {}): Promise<UpdaterStat
try {
strategy = await resolvePackagedUpdateStrategy()
- if (strategy) { return await strategy.check(opts) }
+ if (strategy) {
+ return await strategy.check(opts)
+ }
} catch (error) {
return {
supported: true,
@@ -3121,21 +3115,32 @@ async function createPackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {
source: INSTALL_STAMP?.source
})
- if (mechanism === 'windows-handoff' || mechanism === 'posix-handoff') { return null }
-
+ if (mechanism === 'windows-handoff' || mechanism === 'posix-handoff') {
+ return null
+ }
if (INSTALL_STAMP?.channelBuild && (mechanism === 'electron-updater' || mechanism === 'app-installer')) {
const build = INSTALL_STAMP.channelBuild
const installed = await inspectRunningChannelApp(build)
const payload = bundledPayload(process.resourcesPath)
- if (!payload || (process.platform !== 'darwin' && process.platform !== 'win32') || (process.arch !== 'arm64' && process.arch !== 'x64')) {
+ if (
+ !payload ||
+ (process.platform !== 'darwin' && process.platform !== 'win32') ||
+ (process.arch !== 'arm64' && process.arch !== 'x64')
+ ) {
throw new Error('Channel updates require a supported bundled application')
}
return new ChannelStrategy({
- build, mechanism,
- resolver: new ChannelResolver({ build, platform: process.platform, arch: process.arch, signer: installed.signer }),
+ build,
+ mechanism,
+ resolver: new ChannelResolver({
+ build,
+ platform: process.platform,
+ arch: process.arch,
+ signer: installed.signer
+ }),
nativeFactory: (target: ChannelTarget): UpdaterStrategy => createNativePackagedStrategy(mechanism, target)
})
}
@@ -3143,8 +3148,10 @@ async function createPackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {
return createNativePackagedStrategy(mechanism)
}
-function createNativePackagedStrategy(mechanism: UpdaterStrategy['mechanism'], target?: ChannelTarget): UpdaterStrategy {
-
+function createNativePackagedStrategy(
+ mechanism: UpdaterStrategy['mechanism'],
+ target?: ChannelTarget
+): UpdaterStrategy {
if (mechanism === 'electron-updater') {
const deps: Parameters<typeof createMacStrategy>[0] = {
channel: resolveUpdaterChannelFromStamp(),
@@ -3168,10 +3175,11 @@ function createNativePackagedStrategy(mechanism: UpdaterStrategy['mechanism'], t
// The checker ships inside the payload's repo snapshot (git archive of
// the committed tree): <payload>/<repo>/apps/desktop/scripts/.
script: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'check-appinstaller-update.py'),
- run: (python, script) => runAppInstallerChecker(python, script, {
- env: { ...process.env, PYTHONPATH: payload.sitePackages },
- onStderr: stderr => console.error(`[app-installer] checker stderr: ${stderr.slice(0, 400)}`)
- }),
+ run: (python, script) =>
+ runAppInstallerChecker(python, script, {
+ env: { ...process.env, PYTHONPATH: payload.sitePackages },
+ onStderr: stderr => console.error(`[app-installer] checker stderr: ${stderr.slice(0, 400)}`)
+ }),
channel: resolveUpdaterChannelFromStamp(),
light: isLightVariant(),
feedBaseUrl: resolveDesktopFeedBaseUrl(),
@@ -3199,18 +3207,14 @@ function createNativePackagedStrategy(mechanism: UpdaterStrategy['mechanism'], t
processId: process.pid,
processStartTimeMs: Math.round(Date.now() - process.uptime() * 1000),
identityName: PRODUCT_IDENTITY.msixAppIdWithOrg,
- scriptPath: path.join(
- payload.repoDir,
- 'apps',
- 'desktop',
- 'scripts',
- 'update-relaunch-waiter.ps1'
- )
+ scriptPath: path.join(payload.repoDir, 'apps', 'desktop', 'scripts', 'update-relaunch-waiter.ps1')
})
})
}
- return target ? createChannelAppInstallerStrategy(deps, target, verifyPreparedChannelInstaller) : new AppInstallerStrategy(deps)
+ return target
+ ? createChannelAppInstallerStrategy(deps, target, verifyPreparedChannelInstaller)
+ : new AppInstallerStrategy(deps)
}
if (mechanism === 'microsoft-store') {
@@ -3227,17 +3231,18 @@ function createNativePackagedStrategy(mechanism: UpdaterStrategy['mechanism'], t
restore: restoreBundledBackend,
emitProgress: emitUpdateProgress,
quit: () => app.quit(),
- registerPendingRelaunch: (fromVersion: string): Promise<RelaunchRegistration> => registerUpdateRelaunch(app, 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
+ registerPendingRelaunch: (fromVersion: string): Promise<RelaunchRegistration> =>
+ registerUpdateRelaunch(app, 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 new ExternalStrategy(INSTALL_STAMP)
@@ -3257,14 +3262,15 @@ function resolveCheckoutUpdateStrategy(): UpdaterStrategy {
isMac: IS_MAC,
defaultUpdateBranch: DEFAULT_UPDATE_BRANCH,
updateHandoffDwellMs: UPDATE_HANDOFF_DWELL_MS,
- readSourceUpdate: async (updateRoot: string, opts: { force?: boolean }): Promise<SourceUpdate | null> => readSourceUpdate({
- python: await findPythonForRoot(updateRoot),
- git: resolveGitBinary(),
- updateRoot,
- hermesHome: HERMES_HOME,
- branchConfigPath: DESKTOP_UPDATE_CONFIG_PATH,
- force: opts.force
- }),
+ readSourceUpdate: async (updateRoot: string, opts: { force?: boolean }): Promise<SourceUpdate | null> =>
+ readSourceUpdate({
+ python: await findPythonForRoot(updateRoot),
+ git: resolveGitBinary(),
+ updateRoot,
+ hermesHome: HERMES_HOME,
+ branchConfigPath: DESKTOP_UPDATE_CONFIG_PATH,
+ force: opts.force
+ }),
resolveUpdateRoot,
resolveUpdaterBinary,
@@ -3275,7 +3281,12 @@ function resolveCheckoutUpdateStrategy(): UpdaterStrategy {
repairMacUpdaterHelper,
preflightStateDb: async (home: string, log: (message: string) => void): Promise<void> => {
const root: string = resolveUpdateRoot()
- preflightStateDb({ python: await findPythonForRoot(root), script: path.join(root, 'hermes_cli', 'backup_sqlite.py'), home, log })
+ preflightStateDb({
+ python: await findPythonForRoot(root),
+ script: path.join(root, 'hermes_cli', 'backup_sqlite.py'),
+ home,
+ log
+ })
},
runningAppBundle,
markQuittingForHandoff: () => {
@@ -3293,10 +3304,14 @@ function resolveCheckoutUpdateStrategy(): UpdaterStrategy {
function resolveDesktopFeedBaseUrl(): string {
const configured: string = readUpdatesFeedBaseFromConfig(path.join(HERMES_HOME, 'config.yaml'))
- if (configured) {return configured}
+ if (configured) {
+ return configured
+ }
const env: string | undefined = process.env.HERMES_DESKTOP_FEED_BASE_URL
- if (env) {return env}
+ if (env) {
+ return env
+ }
return ''
}
@@ -3896,13 +3911,15 @@ async function applyUpdates(): Promise<UpdaterApplyResultWire> {
let handedOff: boolean = false
try {
- const strategy: UpdaterStrategy = await resolvePackagedUpdateStrategy() ?? resolveCheckoutUpdateStrategy()
+ const strategy: UpdaterStrategy = (await resolvePackagedUpdateStrategy()) ?? resolveCheckoutUpdateStrategy()
const result: UpdaterApplyResultWire = await strategy.apply()
handedOff = result.handedOff === true
return result
} finally {
- if (!handedOff) { updateInFlight = false }
+ if (!handedOff) {
+ updateInFlight = false
+ }
}
})
}
@@ -3953,10 +3970,7 @@ async function handOffWindowsBootstrapRecovery(reason) {
// Recovery can run without Python. Keep the chosen branch; do not guess a replacement.
const branch: string = configuredBranch || DEFAULT_UPDATE_BRANCH
- const updaterArgs: string[] = chooseUpdaterArgs(
- { runtimeUsable: await isSourceRuntimeUsable(updateRoot) },
- branch
- )
+ const updaterArgs: string[] = chooseUpdaterArgs({ runtimeUsable: await isSourceRuntimeUsable(updateRoot) }, branch)
await stopBackendsForUpdate()
@@ -4067,22 +4081,24 @@ function readBootstrapMarker() {
// ever having written the bootstrap marker -- so we must be able to recognise
// "already installed" off the filesystem alone, not just the marker.
async function isSourceRuntimeUsable(root: string): Promise<boolean> {
- return await resolveSourceInstallationBackend(root, [], { hermesHome: HERMES_HOME }) !== null
+ return (await resolveSourceInstallationBackend(root, [], { hermesHome: HERMES_HOME })) !== null
}
function isActiveRuntimeUsable(): Promise<boolean> {
return isSourceRuntimeUsable(ACTIVE_HERMES_ROOT)
}
-function activeRuntimeState(
- backend: SourceBackend | null
-): ActiveRuntimeState {
+function activeRuntimeState(backend: SourceBackend | null): ActiveRuntimeState {
// We DELIBERATELY do NOT verify that the checkout is currently at the
// pinned commit -- users update via the in-app update path or `hermes
// update`, which moves HEAD legitimately. The marker only attests "a
// desktop-managed bootstrap ran here at least once"; runtime usability is
// what decides whether we can actually launch.
- const state: ActiveRuntimeState = classifyActiveRuntime(readBootstrapMarker(), BOOTSTRAP_MARKER_SCHEMA_VERSION, backend !== null)
+ const state: ActiveRuntimeState = classifyActiveRuntime(
+ readBootstrapMarker(),
+ BOOTSTRAP_MARKER_SCHEMA_VERSION,
+ backend !== null
+ )
// The canonical install stamp (written next to the runtime by the bootstrap)
// tells the UI where this runtime came from. Prefer it over the marker so
@@ -4411,10 +4427,15 @@ async function resolveHermesBackend(backendArgs: string[]): Promise<ResolvedHerm
// 1. Explicit override -- HERMES_DESKTOP_HERMES_ROOT points at a developer
// checkout. Honour it as-is (no bootstrap; the user is driving).
- const overrideRoot: string | undefined = process.env.HERMES_DESKTOP_HERMES_ROOT && path.resolve(process.env.HERMES_DESKTOP_HERMES_ROOT)
+ const overrideRoot: string | undefined =
+ process.env.HERMES_DESKTOP_HERMES_ROOT && path.resolve(process.env.HERMES_DESKTOP_HERMES_ROOT)
if (overrideRoot && isHermesSourceRoot(overrideRoot)) {
- const backend: SourceBackend | null = createSourcePythonBackend(overrideRoot, await findPythonForRoot(overrideRoot), backendArgs)
+ const backend: SourceBackend | null = createSourcePythonBackend(
+ overrideRoot,
+ await findPythonForRoot(overrideRoot),
+ backendArgs
+ )
if (backend) {
return backend
@@ -4426,7 +4447,11 @@ async function resolveHermesBackend(backendArgs: string[]): Promise<ResolvedHerm
// installed `hermes` on PATH so local Python edits are actually exercised.
// (In dev with no checkout, SOURCE_REPO_ROOT won't pass isHermesSourceRoot.)
if (!IS_PACKAGED && isHermesSourceRoot(SOURCE_REPO_ROOT)) {
- const backend: SourceBackend | null = createSourcePythonBackend(SOURCE_REPO_ROOT, await findPythonForRoot(SOURCE_REPO_ROOT), backendArgs)
+ const backend: SourceBackend | null = createSourcePythonBackend(
+ SOURCE_REPO_ROOT,
+ await findPythonForRoot(SOURCE_REPO_ROOT),
+ backendArgs
+ )
if (backend) {
return backend
@@ -4456,7 +4481,8 @@ async function resolveHermesBackend(backendArgs: string[]): Promise<ResolvedHerm
rememberLog(`Ignoring desktop app executable on PATH while resolving Hermes CLI: ${hermesCommand}`)
hermesCommand = null
} else {
- const unwrapped: Awaited<ReturnType<typeof unwrapWindowsVenvHermesCommand>> = await unwrapWindowsVenvHermesCommand(hermesCommand, backendArgs)
+ const unwrapped: Awaited<ReturnType<typeof unwrapWindowsVenvHermesCommand>> =
+ await unwrapWindowsVenvHermesCommand(hermesCommand, backendArgs)
if (unwrapped) {
return unwrapped
@@ -4464,7 +4490,10 @@ async function resolveHermesBackend(backendArgs: string[]): Promise<ResolvedHerm
const shellForProbe: boolean = isCommandScript(hermesCommand)
- if (shouldTrustHermesOverride(hermesOverride) || await verifyHermesCli(hermesCommand, { shell: shellForProbe })) {
+ if (
+ shouldTrustHermesOverride(hermesOverride) ||
+ (await verifyHermesCli(hermesCommand, { shell: shellForProbe }))
+ ) {
return {
label: `existing Hermes CLI at ${hermesCommand}`,
command: hermesCommand,
@@ -4492,7 +4521,9 @@ async function resolveHermesBackend(backendArgs: string[]): Promise<ResolvedHerm
// builds could leave a healthy install behind without the marker. If the
// active runtime is usable, launch it directly; only fall through to
// bootstrap when the runtime itself is unusable.
- const activeBackend: SourceBackend | null = await resolveSourceInstallationBackend(ACTIVE_HERMES_ROOT, backendArgs, { hermesHome: HERMES_HOME })
+ const activeBackend: SourceBackend | null = await resolveSourceInstallationBackend(ACTIVE_HERMES_ROOT, backendArgs, {
+ hermesHome: HERMES_HOME
+ })
const activeRuntime: ActiveRuntimeState = activeRuntimeState(activeBackend)
if (activeBackend && !bootstrapRepairRequested) {
@@ -4553,7 +4584,10 @@ interface ResolvedHermesBackend {
readyFile?: boolean
}
-async function ensureRuntime(backend: ResolvedHermesBackend, assertStillOwned: () => void): Promise<ResolvedHermesBackend> {
+async function ensureRuntime(
+ backend: ResolvedHermesBackend,
+ assertStillOwned: () => void
+): Promise<ResolvedHermesBackend> {
localBackendLifecycle.assertCanStart()
assertStillOwned()
@@ -9254,23 +9288,25 @@ async function teardownSshConnection(profile) {
// alone leaves the backend at pid 1 holding state.db (#91668).
// Windows remotes use a different lifecycle (connectWindowsRemote) and
// are left to a follow-up; POSIX is the leak that OOM'd gateways.
- await sshTeardowns.track(state.ssh, (): Promise<void> => teardownSshState(
- {
- ...state,
- ownershipId: state.ownershipId || sshOwnershipKey(profile)
- },
- {
- cleanupRemote:
- state.remotePlatform === 'Windows'
- ? async () => {
- // connectWindowsRemote does not share POSIX lock/kill. Stay
- // silent on the kill path, but leave a log so quit is not a
- // mysterious no-op on Windows remotes.
- sshRememberLog('[ssh] skip remote serve teardown on Windows remotes; POSIX disconnect does not apply')
- }
- : remoteLifecycle.disconnect
- }
- ))
+ await sshTeardowns.track(state.ssh, (): Promise<void> =>
+ teardownSshState(
+ {
+ ...state,
+ ownershipId: state.ownershipId || sshOwnershipKey(profile)
+ },
+ {
+ cleanupRemote:
+ state.remotePlatform === 'Windows'
+ ? async () => {
+ // connectWindowsRemote does not share POSIX lock/kill. Stay
+ // silent on the kill path, but leave a log so quit is not a
+ // mysterious no-op on Windows remotes.
+ sshRememberLog('[ssh] skip remote serve teardown on Windows remotes; POSIX disconnect does not apply')
+ }
+ : remoteLifecycle.disconnect
+ }
+ )
+ )
}
// CRITICAL: this must mirror resolveRemoteBackend's precedence, not just return
@@ -11456,7 +11492,9 @@ async function spawnPoolBackend(
)
}
- const cancelRequest = (): void => { spawnRequest.cancel() }
+ const cancelRequest = (): void => {
+ spawnRequest.cancel()
+ }
localBackendLifecycle.signal.addEventListener('abort', cancelRequest, { once: true })
try {
@@ -11540,25 +11578,28 @@ async function spawnPoolBackend(
backend.args,
hiddenWindowsChildOptions({
cwd: hermesCwd,
- env: desktopBackendSpawnEnv({
- ...process.env,
- HERMES_HOME,
- ...backend.env,
- // Pin the gateway's tool/terminal cwd to the same directory we chose for
- // the child process. Inherited TERMINAL_CWD (or a stale config bridge)
- // can still point at the install dir even when spawn cwd is home.
- TERMINAL_CWD: hermesCwd,
- HERMES_DASHBOARD_SESSION_TOKEN: token,
- // Marks this dashboard backend as desktop-spawned so it runs the cron
- // scheduler tick loop (the gateway isn't running under the app).
- HERMES_DESKTOP: '1',
- // Exact parent identity lets the backend self-exit after an unclean
- // Desktop death without mistaking a reused PID for its owner. If the
- // optional marker probe fails, retain legacy PID-only tracking.
- ...parentIdentityEnv,
- HERMES_WEB_DIST: webDist,
- ...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
- }, GUEST_ONBOARDING),
+ env: desktopBackendSpawnEnv(
+ {
+ ...process.env,
+ HERMES_HOME,
+ ...backend.env,
+ // Pin the gateway's tool/terminal cwd to the same directory we chose for
+ // the child process. Inherited TERMINAL_CWD (or a stale config bridge)
+ // can still point at the install dir even when spawn cwd is home.
+ TERMINAL_CWD: hermesCwd,
+ HERMES_DASHBOARD_SESSION_TOKEN: token,
+ // Marks this dashboard backend as desktop-spawned so it runs the cron
+ // scheduler tick loop (the gateway isn't running under the app).
+ HERMES_DESKTOP: '1',
+ // Exact parent identity lets the backend self-exit after an unclean
+ // Desktop death without mistaking a reused PID for its owner. If the
+ // optional marker probe fails, retain legacy PID-only tracking.
+ ...parentIdentityEnv,
+ HERMES_WEB_DIST: webDist,
+ ...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
+ },
+ GUEST_ONBOARDING
+ ),
shell: backend.shell,
stdio: ['ignore', 'pipe', 'pipe']
})
@@ -11773,10 +11814,14 @@ function reapInstallRootedStragglers(excludePids: number[]): void {
try {
reapPackageRootedProcesses({
installRoots: [payloadRoot],
- listProcesses: () => listWindowsProcesses((file, args, options) => execFileSync(file, args, {
- ...hiddenWindowsChildOptions({ encoding: 'utf8', timeout: options.timeout }),
- windowsHide: options.windowsHide
- }) as unknown as string),
+ listProcesses: () =>
+ listWindowsProcesses(
+ (file, args, options) =>
+ execFileSync(file, args, {
+ ...hiddenWindowsChildOptions({ encoding: 'utf8', timeout: options.timeout }),
+ windowsHide: options.windowsHide
+ }) as unknown as string
+ ),
killProcess: pid => process.kill(pid, 'SIGKILL'),
selfPid: process.pid,
excludePids,
@@ -11816,10 +11861,14 @@ const quitFinalization = createQuitFinalization({
async function teardownSshForQuit(): Promise<void> {
for (const scope of sshConnections.keys()) {
- void teardownSshConnection(scope || null).catch((error: unknown): void => rememberLog(`SSH teardown failed: ${error instanceof Error ? error.message : String(error)}`))
+ void teardownSshConnection(scope || null).catch((error: unknown): void =>
+ rememberLog(`SSH teardown failed: ${error instanceof Error ? error.message : String(error)}`)
+ )
}
- await sshTeardowns.finish(sshBootstrapCoordinator.promises(), (): Promise<void> => sshBootstrapCoordinator.forceCleanupAll())
+ await sshTeardowns.finish(sshBootstrapCoordinator.promises(), (): Promise<void> =>
+ sshBootstrapCoordinator.forceCleanupAll()
+ )
}
async function exitAfterBackendShutdown(code) {
@@ -12014,7 +12063,8 @@ function startHermes(): Promise<Awaited<ReturnType<typeof backendConnectionState
primaryRecoverySuppressed = false
primaryStartsInFlight += 1
- const start: Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> = localBackendLifecycle.start(runHermesStart)
+ const start: Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> =
+ localBackendLifecycle.start(runHermesStart)
const releaseStart = (): void => {
primaryStartsInFlight -= 1
@@ -12296,30 +12346,33 @@ async function runHermesStart(): Promise<Awaited<ReturnType<typeof backendConnec
backend.args,
hiddenWindowsChildOptions({
cwd: hermesCwd,
- env: desktopBackendSpawnEnv({
- ...process.env,
- // Explicitly pin HERMES_HOME for the child so Python's get_hermes_home()
- // resolves to the SAME location our resolveHermesHome() picked. Without
- // this pin, Python falls back to ~/.hermes on every platform — fine on
- // mac/linux (where our default matches), but on Windows our default is
- // %LOCALAPPDATA%\hermes, which differs from C:\Users\<u>\.hermes.
- // Mismatch would split config / sessions / .env / logs across two
- // directories. install.ps1 sets HERMES_HOME via setx; the desktop
- // can't reliably do that, so we set it inline for every spawn.
- HERMES_HOME,
- ...backend.env,
- TERMINAL_CWD: hermesCwd,
- HERMES_DASHBOARD_SESSION_TOKEN: token,
- // Marks this dashboard backend as desktop-spawned so it runs the cron
- // scheduler tick loop (the gateway isn't running under the app).
- HERMES_DESKTOP: '1',
- // Exact parent identity lets the backend self-exit after an unclean
- // Desktop death without mistaking a reused PID for its owner. If the
- // optional marker probe fails, retain legacy PID-only tracking.
- ...parentIdentityEnv,
- HERMES_WEB_DIST: webDist,
- ...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
- }, GUEST_ONBOARDING),
+ env: desktopBackendSpawnEnv(
+ {
+ ...process.env,
+ // Explicitly pin HERMES_HOME for the child so Python's get_hermes_home()
+ // resolves to the SAME location our resolveHermesHome() picked. Without
+ // this pin, Python falls back to ~/.hermes on every platform — fine on
+ // mac/linux (where our default matches), but on Windows our default is
+ // %LOCALAPPDATA%\hermes, which differs from C:\Users\<u>\.hermes.
+ // Mismatch would split config / sessions / .env / logs across two
+ // directories. install.ps1 sets HERMES_HOME via setx; the desktop
+ // can't reliably do that, so we set it inline for every spawn.
+ HERMES_HOME,
+ ...backend.env,
+ TERMINAL_CWD: hermesCwd,
+ HERMES_DASHBOARD_SESSION_TOKEN: token,
+ // Marks this dashboard backend as desktop-spawned so it runs the cron
+ // scheduler tick loop (the gateway isn't running under the app).
+ HERMES_DESKTOP: '1',
+ // Exact parent identity lets the backend self-exit after an unclean
+ // Desktop death without mistaking a reused PID for its owner. If the
+ // optional marker probe fails, retain legacy PID-only tracking.
+ ...parentIdentityEnv,
+ HERMES_WEB_DIST: webDist,
+ ...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})
+ },
+ GUEST_ONBOARDING
+ ),
shell: backend.shell,
stdio: ['ignore', 'pipe', 'pipe']
})
@@ -12350,13 +12403,18 @@ async function runHermesStart(): Promise<Awaited<ReturnType<typeof backendConnec
// surface as an unhandled rejection before the Promise.race below attaches.
portAnnouncement.catch(() => {})
- const processOwner = await backendConnectionState.claimProcess(connectionAttempt, hermesProcess, (child: ChildProcess): ReturnType<typeof claimBackendChild> => claimBackendChild(
- child,
- `${backend.command} ${backend.args.join(' ')}`,
- profile,
- backendNonce,
- primaryOutputTail
- ))
+ const processOwner = await backendConnectionState.claimProcess(
+ connectionAttempt,
+ hermesProcess,
+ (child: ChildProcess): ReturnType<typeof claimBackendChild> =>
+ claimBackendChild(
+ child,
+ `${backend.command} ${backend.args.join(' ')}`,
+ profile,
+ backendNonce,
+ primaryOutputTail
+ )
+ )
if (!processOwner) {
await localBackendLifecycle.stop(hermesProcess)
@@ -16222,9 +16280,14 @@ ipcMain.handle('hermes:api', async (_event, request) => {
// Speech claims outlive instant cues so throttled peer windows cannot replay a reply.
const ownsAmbientCue: ReturnType<typeof createAmbientClaimArbiter> = createAmbientClaimArbiter()
-ipcMain.handle('hermes:ambient:claim', (_event: IpcMainInvokeEvent, key: unknown): boolean => ownsAmbientCue(String(key ?? '')))
+ipcMain.handle('hermes:ambient:claim', (_event: IpcMainInvokeEvent, key: unknown): boolean =>
+ ownsAmbientCue(String(key ?? ''))
+)
-const nativeNotifications = registerNativeNotifications({ getMainWindow: (): BrowserWindow | null => mainWindow, focusWindow })
+const nativeNotifications = registerNativeNotifications({
+ getMainWindow: (): BrowserWindow | null => mainWindow,
+ focusWindow
+})
// Data-URL file load cap (composer attach + local previews). Main owns the
// persisted MB value so every IPC read honours Settings → Chat without the
@@ -17004,14 +17067,16 @@ const terminalIpc = registerTerminalIpc({
const disposeTerminalSession = terminalIpc.disposeTerminalSession
-ipcMain.handle('hermes:updates:check', async (_event: Electron.IpcMainInvokeEvent, opts?: { force?: boolean }): Promise<UpdaterStatusWire> =>
- checkUpdates({ force: Boolean(opts?.force) }).catch((error: Error & { kind?: string }): UpdaterStatusWire => ({
- supported: true,
- branch: readDesktopUpdateConfig().branch,
- error: error?.kind === GIT_UNUSABLE ? GIT_UNUSABLE : 'check-failed',
- message: error?.message || String(error),
- fetchedAt: Date.now()
- }))
+ipcMain.handle(
+ 'hermes:updates:check',
+ async (_event: Electron.IpcMainInvokeEvent, opts?: { force?: boolean }): Promise<UpdaterStatusWire> =>
+ checkUpdates({ force: Boolean(opts?.force) }).catch((error: Error & { kind?: string }): UpdaterStatusWire => ({
+ supported: true,
+ branch: readDesktopUpdateConfig().branch,
+ error: error?.kind === GIT_UNUSABLE ? GIT_UNUSABLE : 'check-failed',
+ message: error?.message || String(error),
+ fetchedAt: Date.now()
+ }))
)
ipcMain.handle('hermes:updates:apply', async (_event, payload) =>
@@ -17024,13 +17089,16 @@ ipcMain.handle('hermes:updates:apply', async (_event, payload) =>
ipcMain.handle('hermes:updates:branch:get', async () => readDesktopUpdateConfig())
-ipcMain.handle('hermes:updates:branch:set', async (_event: Electron.IpcMainInvokeEvent, name: unknown): Promise<{ branch: string }> => {
- assertSourceUpdateChannel(INSTALL_STAMP)
- const branch: string = typeof name === 'string' && name.trim() ? name.trim() : DEFAULT_UPDATE_BRANCH
- writeDesktopUpdateConfig({ branch })
+ipcMain.handle(
+ 'hermes:updates:branch:set',
+ async (_event: Electron.IpcMainInvokeEvent, name: unknown): Promise<{ branch: string }> => {
+ assertSourceUpdateChannel(INSTALL_STAMP)
+ const branch: string = typeof name === 'string' && name.trim() ? name.trim() : DEFAULT_UPDATE_BRANCH
+ writeDesktopUpdateConfig({ branch })
- return { branch }
-})
+ return { branch }
+ }
+)
function resolveHermesVersion(scope: { connectionId?: string; profile?: string } = {}): Promise<string> {
return resolveGatewayVersion(path => handleHermesApiRequest({ ...scope, path, timeoutMs: 5000 }))
@@ -17060,9 +17128,7 @@ function showAboutPanelFresh(): void {
const display: string = info.appVersion
app.setAboutPanelOptions({
applicationName: APP_NAME,
- applicationVersion: skew.outOfSync
- ? `${display} — app build out of date, update the desktop app`
- : display,
+ applicationVersion: skew.outOfSync ? `${display} — app build out of date, update the desktop app` : display,
copyright: 'Copyright © 2026 Nous Research'
})
app.showAboutPanel()
@@ -17123,12 +17189,7 @@ ipcMain.handle('hermes:app:relaunch', async () => {
* pm syncs (bisect disables, failed rebuilds), plugin update checks,
* and (embedded) updates. */
function readLatestSyncReceipt(): Record<string, unknown> | null {
- const receiptPath = path.join(
- HERMES_HOME,
- 'logs',
- 'update_receipts',
- 'latest.json'
- )
+ const receiptPath = path.join(HERMES_HOME, 'logs', 'update_receipts', 'latest.json')
try {
const text = fs.readFileSync(receiptPath, 'utf8')
@@ -17162,7 +17223,9 @@ function canonicalizeInstallPath(p: string): string {
* missing checkout (sealed bundled payloads, remote backends) is not
* installer-created. */
export function isInstallerCreatedCheckout(root: string | null = ACTIVE_HERMES_ROOT): boolean {
- if (!root) { return false }
+ if (!root) {
+ return false
+ }
try {
return fs.existsSync(path.join(root, path.basename(BOOTSTRAP_COMPLETE_MARKER)))
@@ -17851,8 +17914,11 @@ app.on('before-quit', event => {
shutdownPending: backendShutdown.isPending()
})
- const sshNeedsWait = sshConnections.size > 0 || sshBootstrapCoordinator.promises().length > 0 || sshTeardowns.hasPending()
- const teardownTasks: QuitTeardownTask[] = [{ run: (): Promise<void> => backendShutdown.run(), waitForCompletion: backendNeedsWait }]
+ const sshNeedsWait =
+ sshConnections.size > 0 || sshBootstrapCoordinator.promises().length > 0 || sshTeardowns.hasPending()
+ const teardownTasks: QuitTeardownTask[] = [
+ { run: (): Promise<void> => backendShutdown.run(), waitForCompletion: backendNeedsWait }
+ ]
if (sshNeedsWait) {
teardownTasks.push({ run: teardownSshForQuit, waitForCompletion: true })
diff --git a/apps/desktop/electron/managed-ssh-update.test.ts b/apps/desktop/electron/managed-ssh-update.test.ts
index 37accb15f07..d973ee55752 100644
--- a/apps/desktop/electron/managed-ssh-update.test.ts
+++ b/apps/desktop/electron/managed-ssh-update.test.ts
@@ -329,7 +329,10 @@ test.runIf(process.platform !== 'win32').each([0, 23])(
assert.equal(status, String(exitCode), `updater output: ${log}`)
assert.deepEqual(log.trimEnd().split('\n'), ['update', '--yes', home, CORRELATION, 'default', home, logPath])
assert.equal((await stat(statusPath)).mode & 0o777, 0o600)
- assert.equal((await readdir(home)).some((name: string): boolean => name.endsWith('.tmp')), false)
+ assert.equal(
+ (await readdir(home)).some((name: string): boolean => name.endsWith('.tmp')),
+ false
+ )
} finally {
await rm(home, { force: true, recursive: true })
}
@@ -382,75 +385,81 @@ test('remote observation rejects a receipt for another correlation', () => {
)
})
-test.runIf(process.platform !== 'win32')('POSIX observer reads the exact correlation receipt and terminal marker from disk', async () => {
- const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-update-'))
-
- try {
- const receipts = path.join(home, 'logs', 'update_receipts')
- await mkdir(receipts, { recursive: true })
- await writeFile(path.join(home, `.update_exit_code.${CORRELATION}`), '0')
- await writeFile(
- path.join(receipts, `update_${CORRELATION}.json`),
- JSON.stringify({
- correlation_id: CORRELATION,
- outcome: 'success',
- started_at: '2026-08-23T00:00:00Z',
- finished_at: '2026-08-23T00:01:00Z',
- pre_update: { sha: 'old' },
- post_update: { sha: 'new' }
- })
- )
-
- const command = buildRemoteUpdateObservationCommand(
- {
- ssh: { exec: async () => '' },
- platform: 'Linux',
- hermesPath: '/opt/hermes/hermes',
- hermesHome: home
- },
- CORRELATION
- )
-
- const { stdout } = await exec(command, { shell: 'sh' })
- const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)
-
- assert.equal(parsed.marker, 'absent')
- assert.equal(parsed.exitCode, 0)
- assert.equal(parsed.receipt?.correlationId, CORRELATION)
- assert.equal(parsed.receipt?.preSha, 'old')
- assert.equal(parsed.receipt?.postSha, 'new')
- } finally {
- await rm(home, { force: true, recursive: true })
+test.runIf(process.platform !== 'win32')(
+ 'POSIX observer reads the exact correlation receipt and terminal marker from disk',
+ async () => {
+ const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-update-'))
+
+ try {
+ const receipts = path.join(home, 'logs', 'update_receipts')
+ await mkdir(receipts, { recursive: true })
+ await writeFile(path.join(home, `.update_exit_code.${CORRELATION}`), '0')
+ await writeFile(
+ path.join(receipts, `update_${CORRELATION}.json`),
+ JSON.stringify({
+ correlation_id: CORRELATION,
+ outcome: 'success',
+ started_at: '2026-08-23T00:00:00Z',
+ finished_at: '2026-08-23T00:01:00Z',
+ pre_update: { sha: 'old' },
+ post_update: { sha: 'new' }
+ })
+ )
+
+ const command = buildRemoteUpdateObservationCommand(
+ {
+ ssh: { exec: async () => '' },
+ platform: 'Linux',
+ hermesPath: '/opt/hermes/hermes',
+ hermesHome: home
+ },
+ CORRELATION
+ )
+
+ const { stdout } = await exec(command, { shell: 'sh' })
+ const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)
+
+ assert.equal(parsed.marker, 'absent')
+ assert.equal(parsed.exitCode, 0)
+ assert.equal(parsed.receipt?.correlationId, CORRELATION)
+ assert.equal(parsed.receipt?.preSha, 'old')
+ assert.equal(parsed.receipt?.postSha, 'new')
+ } finally {
+ await rm(home, { force: true, recursive: true })
+ }
}
-})
+)
-test.runIf(process.platform !== 'win32')('managed observer unwraps a named profile home for the install-wide marker', async () => {
- const root = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-profile-marker-'))
- const profileHome = path.join(root, 'profiles', 'research')
+test.runIf(process.platform !== 'win32')(
+ 'managed observer unwraps a named profile home for the install-wide marker',
+ async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-profile-marker-'))
+ const profileHome = path.join(root, 'profiles', 'research')
- try {
- await mkdir(profileHome, { recursive: true })
- await writeFile(path.join(root, '.hermes-update-in-progress'), `${process.pid}\n1\n`)
+ try {
+ await mkdir(profileHome, { recursive: true })
+ await writeFile(path.join(root, '.hermes-update-in-progress'), `${process.pid}\n1\n`)
- const command = buildRemoteUpdateObservationCommand(
- {
- ssh: { exec: async () => '' },
- platform: 'Linux',
- hermesPath: '/opt/hermes/hermes',
- hermesHome: profileHome
- },
- CORRELATION
- )
+ const command = buildRemoteUpdateObservationCommand(
+ {
+ ssh: { exec: async () => '' },
+ platform: 'Linux',
+ hermesPath: '/opt/hermes/hermes',
+ hermesHome: profileHome
+ },
+ CORRELATION
+ )
- const { stdout } = await exec(command, { shell: 'sh' })
- const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)
+ const { stdout } = await exec(command, { shell: 'sh' })
+ const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)
- assert.equal(parsed.marker, 'live')
- assert.equal(parsed.markerPid, process.pid)
- } finally {
- await rm(root, { force: true, recursive: true })
+ assert.equal(parsed.marker, 'live')
+ assert.equal(parsed.markerPid, process.pid)
+ } finally {
+ await rm(root, { force: true, recursive: true })
+ }
}
-})
+)
test('Windows coordinator handoff is pending until its marker clears and correlated receipt is durable', async () => {
const replies = [
diff --git a/apps/desktop/electron/package-process-reap.test.ts b/apps/desktop/electron/package-process-reap.test.ts
index d20b1f38f1c..32c82da8995 100644
--- a/apps/desktop/electron/package-process-reap.test.ts
+++ b/apps/desktop/electron/package-process-reap.test.ts
@@ -86,41 +86,93 @@ const cases: SelectionCase[] = [
{ name: 'excluded daemon', processes: [proc(10, GPG_AGENT), proc(11, GPG_AGENT)], excludePids: [10], killed: [11] },
{ name: 'sibling-prefix daemon', processes: [proc(10, `${ROOT}-other\\gpg-agent.exe`)], killed: [] },
{ name: 'external daemon', processes: [proc(10, 'C:\\Git\\gpg-agent.exe'), proc(11, GPG_AGENT)], killed: [11] },
- { name: 'unidentified parent and daemon descendants', processes: [proc(12, GPG_AGENT, DAEMON_CMDLINE, 11), proc(11, GPG_AGENT, DAEMON_CMDLINE, 10), proc(10, null)], killed: [] },
- { name: 'shared runtime and daemon descendants', processes: [proc(12, GPG_AGENT, DAEMON_CMDLINE, 11), proc(11, GPG_AGENT, DAEMON_CMDLINE, 10), proc(10, PAYLOAD_PYTHON, '-u -X utf8 -m gateway.run')], killed: [] },
- { name: 'shared entrypoints irrespective of argv', processes: [proc(10, MAIN_EXE, '--app'), proc(11, PAYLOAD_PYTHON, null), proc(12, STORE_NODE, 'daemon.js'), proc(13, GPG_AGENT)], roots: [ROOT, TOOLS_ROOT], killed: [13] },
- { name: 'mutable tool roots', processes: [proc(10, `${TOOLS_ROOT}\\git\\gpg-agent.exe`), proc(11, GPG_AGENT)], roots: [null, TOOLS_ROOT], killed: [10] },
+ {
+ name: 'unidentified parent and daemon descendants',
+ processes: [proc(12, GPG_AGENT, DAEMON_CMDLINE, 11), proc(11, GPG_AGENT, DAEMON_CMDLINE, 10), proc(10, null)],
+ killed: []
+ },
+ {
+ name: 'shared runtime and daemon descendants',
+ processes: [
+ proc(12, GPG_AGENT, DAEMON_CMDLINE, 11),
+ proc(11, GPG_AGENT, DAEMON_CMDLINE, 10),
+ proc(10, PAYLOAD_PYTHON, '-u -X utf8 -m gateway.run')
+ ],
+ killed: []
+ },
+ {
+ name: 'shared entrypoints irrespective of argv',
+ processes: [
+ proc(10, MAIN_EXE, '--app'),
+ proc(11, PAYLOAD_PYTHON, null),
+ proc(12, STORE_NODE, 'daemon.js'),
+ proc(13, GPG_AGENT)
+ ],
+ roots: [ROOT, TOOLS_ROOT],
+ killed: [13]
+ },
+ {
+ name: 'mutable tool roots',
+ processes: [proc(10, `${TOOLS_ROOT}\\git\\gpg-agent.exe`), proc(11, GPG_AGENT)],
+ roots: [null, TOOLS_ROOT],
+ killed: [10]
+ },
{ name: 'unreadable path', processes: [proc(10, null)], killed: [] }
]
-it.each(cases)('safe kill selection: $name', ({ processes, roots = [ROOT], selfPid = 1, excludePids = [], killed }: SelectionCase): void => {
- const signalled: number[] = []
-
- const outcome: ReturnType<typeof reapPackageRootedProcesses> = reapPackageRootedProcesses({
- installRoots: roots, selfPid, excludePids, isWindows: true,
- listProcesses: (): RunningProcess[] => processes,
- killProcess: (pid: number): void => { signalled.push(pid) }
- })
-
- expect(outcome.killed).toEqual(killed)
- expect(outcome.matched).toBe(killed.length)
- expect(signalled).toEqual(killed)
-})
+it.each(cases)(
+ 'safe kill selection: $name',
+ ({ processes, roots = [ROOT], selfPid = 1, excludePids = [], killed }: SelectionCase): void => {
+ const signalled: number[] = []
+
+ const outcome: ReturnType<typeof reapPackageRootedProcesses> = reapPackageRootedProcesses({
+ installRoots: roots,
+ selfPid,
+ excludePids,
+ isWindows: true,
+ listProcesses: (): RunningProcess[] => processes,
+ killProcess: (pid: number): void => {
+ signalled.push(pid)
+ }
+ })
+
+ expect(outcome.killed).toEqual(killed)
+ expect(outcome.matched).toBe(killed.length)
+ expect(signalled).toEqual(killed)
+ }
+)
it('continues after kill failure and refuses absent roots or failed enumeration', (): void => {
const processes: RunningProcess[] = [proc(50, GPG_AGENT), proc(51, GPG_AGENT)]
const base: Parameters<typeof reapPackageRootedProcesses>[0] = {
- installRoots: [ROOT], isWindows: true, selfPid: 1,
+ installRoots: [ROOT],
+ isWindows: true,
+ selfPid: 1,
listProcesses: (): RunningProcess[] => processes,
- killProcess: (pid: number): void => { if (pid === 50) { throw new Error('Access denied') } }
+ killProcess: (pid: number): void => {
+ if (pid === 50) {
+ throw new Error('Access denied')
+ }
+ }
}
expect(reapPackageRootedProcesses(base)).toMatchObject({ failed: [50], killed: [51] })
- for (const overrides of [{ isWindows: false }, { installRoots: [null, ''] }, { listProcesses: (): never => { throw new Error('enumeration failed') } }]) {
+ for (const overrides of [
+ { isWindows: false },
+ { installRoots: [null, ''] },
+ {
+ listProcesses: (): never => {
+ throw new Error('enumeration failed')
+ }
+ }
+ ]) {
const killProcess = vi.fn<(pid: number) => void>()
- expect(reapPackageRootedProcesses({ ...base, ...overrides, killProcess })).toMatchObject({ skipped: true, killed: [] })
+ expect(reapPackageRootedProcesses({ ...base, ...overrides, killProcess })).toMatchObject({
+ skipped: true,
+ killed: []
+ })
expect(killProcess).not.toHaveBeenCalled()
}
})
@@ -129,12 +181,7 @@ describe('listWindowsProcesses', () => {
it('parses Win32_Process output (pid|parent|path|command line), mapping unreadable fields to null', () => {
// The real shape: ExecutablePath / CommandLine are null for processes we
// cannot open, so the script emits empty middle/tail fields.
- const stdout = [
- `48236|61728|${GPG_AGENT}|gpg-agent --daemon`,
- `22660|4|${MAIN_EXE}|`,
- '4|0||',
- ''
- ].join('\r\n')
+ const stdout = [`48236|61728|${GPG_AGENT}|gpg-agent --daemon`, `22660|4|${MAIN_EXE}|`, '4|0||', ''].join('\r\n')
const parsed = listWindowsProcesses(() => stdout)
diff --git a/apps/desktop/electron/package-process-reap.ts b/apps/desktop/electron/package-process-reap.ts
index b3960865fee..e8283f795b4 100644
--- a/apps/desktop/electron/package-process-reap.ts
+++ b/apps/desktop/electron/package-process-reap.ts
@@ -70,6 +70,7 @@ export interface ReapOutcome {
*/
function isSharedRuntime(imagePath: string): boolean {
const image = imagePath.replace(/^.*[\\/]/, '').toLowerCase()
+
return /^(?:pythonw?(?:[0-9.]+)?|node|hermes(?:-agent|-acp)?)(?:\.exe|\.cmd)?$/.test(image)
}
@@ -147,7 +148,11 @@ export function isUnderInstallRoot(
return false
}
- const normalize = (value: string): string => value.replace(/[\\/]+$/, '').replace(/\//g, '\\').toLowerCase()
+ const normalize = (value: string): string =>
+ value
+ .replace(/[\\/]+$/, '')
+ .replace(/\//g, '\\')
+ .toLowerCase()
const normalizedPath = normalize(imagePath)
const candidates = typeof roots === 'string' || roots == null ? [roots] : roots
diff --git a/apps/desktop/electron/payload-backend.test.ts b/apps/desktop/electron/payload-backend.test.ts
index d675991894f..764d67b6d94 100644
--- a/apps/desktop/electron/payload-backend.test.ts
+++ b/apps/desktop/electron/payload-backend.test.ts
@@ -10,23 +10,39 @@ import { bundledPayload, installIdForRoot } from './payload-backend'
function stamp(runtime: PayloadRuntime, payload: InstallStamp['payload'] = 'bundled'): InstallStamp {
return {
- schemaVersion: 1, commit: 'a'.repeat(40), commitDate: null, branch: null,
- builtAt: null, dirty: false, source: 'ci', distribution: 'desktop-app',
- updateMechanism: 'external', baseVersion: null, displayVersion: null,
- distance: null, payload, runtime, tag: 'v1.0.0'
+ schemaVersion: 1,
+ commit: 'a'.repeat(40),
+ commitDate: null,
+ branch: null,
+ builtAt: null,
+ dirty: false,
+ source: 'ci',
+ distribution: 'desktop-app',
+ updateMechanism: 'external',
+ baseVersion: null,
+ displayVersion: null,
+ distance: null,
+ payload,
+ runtime,
+ tag: 'v1.0.0'
}
}
test('bundled launch paths come from build metadata without filesystem access', () => {
const runtime: PayloadRuntime = {
- repoDir: 'source-tree', toolsDir: 'binary-store',
+ repoDir: 'source-tree',
+ toolsDir: 'binary-store',
storePython: 'binary-store/custom-python/python',
sitePackages: 'dependencies/lib/python3.14/site-packages',
commands: { hermes: 'commands/run-hermes', custom: 'commands/custom' }
}
- const probe = vi.spyOn(fs, 'existsSync').mockImplementation(() => { throw new Error('runtime probe') })
- const read = vi.spyOn(fs, 'readFileSync').mockImplementation(() => { throw new Error('runtime read') })
+ const probe = vi.spyOn(fs, 'existsSync').mockImplementation(() => {
+ throw new Error('runtime probe')
+ })
+ const read = vi.spyOn(fs, 'readFileSync').mockImplementation(() => {
+ throw new Error('runtime read')
+ })
try {
for (const resources of ['/not-created/resources', '/relocated app/resources']) {
@@ -63,4 +79,3 @@ test('installIdForRoot matches the Python install id (sha16 of the canonical pat
installIdForRoot('/real/hermes-agent')
)
})
-
diff --git a/apps/desktop/electron/pool-spawn-coordinator.ts b/apps/desktop/electron/pool-spawn-coordinator.ts
index 3911657791b..3d492054e45 100644
--- a/apps/desktop/electron/pool-spawn-coordinator.ts
+++ b/apps/desktop/electron/pool-spawn-coordinator.ts
@@ -84,6 +84,7 @@ export function assertPoolEntryStillOwned(
throw new Error(`Profile backend start for "${poolKey}" was cancelled during start.`)
}
}
+
/** A retry deferment is expected background control flow, not a start failure. */
export class BackgroundSlotRetryDeferredError extends Error {
constructor(key: string) {
diff --git a/apps/desktop/electron/preload-flags.test.ts b/apps/desktop/electron/preload-flags.test.ts
index 58f5922ed15..3486c8735d8 100644
--- a/apps/desktop/electron/preload-flags.test.ts
+++ b/apps/desktop/electron/preload-flags.test.ts
@@ -3,9 +3,9 @@ import { expect, it, vi } from 'vitest'
const host = vi.hoisted(() => ({
exposeInMainWorld: vi.fn(),
send: vi.fn<(channel: string, line: string) => void>(),
- sendSync: vi.fn((channel: string): unknown => channel === 'hermes:feature-flags'
- ? { localModels: true, guestOnboarding: true, skipIntro: true }
- : {})
+ sendSync: vi.fn((channel: string): unknown =>
+ channel === 'hermes:feature-flags' ? { localModels: true, guestOnboarding: true, skipIntro: true } : {}
+ )
}))
vi.mock('electron', () => ({
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index b91d7bdde39..e457a07b567 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -14,7 +14,8 @@ import { customWindowControlsEnabled } from './window-controls'
const translucencySupport = ipcRenderer.sendSync('hermes:translucency:support')
const hudWindowing = ipcRenderer.sendSync('hermes:hud:windowing')
const hudNativeDrag = hudWindowing?.nativeDrag === true
-const launchFlags: { localModels?: boolean; guestOnboarding?: boolean; skipIntro?: boolean } | undefined = ipcRenderer.sendSync('hermes:feature-flags')
+const launchFlags: { localModels?: boolean; guestOnboarding?: boolean; skipIntro?: boolean } | undefined =
+ ipcRenderer.sendSync('hermes:feature-flags')
contextBridge.exposeInMainWorld('hermesDesktop', {
glassSupported: translucencySupport?.glass === true,
diff --git a/apps/desktop/electron/product-identity.test.ts b/apps/desktop/electron/product-identity.test.ts
index b287ebaadae..b007d80ceab 100644
--- a/apps/desktop/electron/product-identity.test.ts
+++ b/apps/desktop/electron/product-identity.test.ts
@@ -121,45 +121,65 @@ test.each([
[undefined, 'Hermes', 'hermes', 'latest', 'canary'],
['bundled', 'Hermes Agent', 'hermes', 'latest', 'canary'],
['light', 'Hermes Light', 'hermes-light', 'light', 'light-canary']
-] as const)('%s separates stable, canary and independent commits', async (variant: string | undefined, display: string, cli: string, channel: string, canaryChannel: string): Promise<void> => {
- const stable: ProductIdentity = await identityForVariant(variant)
- assert.equal(stable.displayName, display)
- assert.equal(stable.channel, channel)
- assert.equal(stable.light, variant === 'light')
- assert.equal(stable.storeMsix, undefined)
- const identities: ProductIdentity[] = [stable]
-
- for (const [tag, commit, expectedCli, expectedChannel] of [
- ['v1.2.3-canary.20260818', '', `${cli}-canary`, canaryChannel],
- ['', 'abcdef1234567890abcdef1234567890abcdef12', `${cli}-abcdef1`, null],
- ['', '1234567890abcdef1234567890abcdef12345678', `${cli}-1234567`, null]
- ] as const) {
- process.env.HERMES_PAYLOAD_TAG = tag
- process.env.HERMES_BUILD_COMMIT = commit
- const current: ProductIdentity = await identityForVariant(variant)
- assert.equal(current.channel, expectedChannel)
- assert.equal(current.cliName, expectedCli)
- assert.equal(current.windowsExecutableName, expectedCli)
- assert.equal(current.artifactNamePascal, stable.artifactNamePascal)
- assert.deepEqual(current, await identityForVariant(variant))
-
- if (commit) { assert.equal(current.displayName, `${display} ${commit.slice(0, 7)}`) }
-
- for (const previous of identities) {
- for (const field of ['displayName', 'appId', 'appNamePascal', 'msixAppIdWithOrg', 'windowsExecutableName', 'cliName'] as const) {
- assert.notEqual(current[field], previous[field], `${field} must isolate installations`)
-
- if (commit) { assert.ok(current[field].includes(commit.slice(0, 7))) }
+] as const)(
+ '%s separates stable, canary and independent commits',
+ async (
+ variant: string | undefined,
+ display: string,
+ cli: string,
+ channel: string,
+ canaryChannel: string
+ ): Promise<void> => {
+ const stable: ProductIdentity = await identityForVariant(variant)
+ assert.equal(stable.displayName, display)
+ assert.equal(stable.channel, channel)
+ assert.equal(stable.light, variant === 'light')
+ assert.equal(stable.storeMsix, undefined)
+ const identities: ProductIdentity[] = [stable]
+
+ for (const [tag, commit, expectedCli, expectedChannel] of [
+ ['v1.2.3-canary.20260818', '', `${cli}-canary`, canaryChannel],
+ ['', 'abcdef1234567890abcdef1234567890abcdef12', `${cli}-abcdef1`, null],
+ ['', '1234567890abcdef1234567890abcdef12345678', `${cli}-1234567`, null]
+ ] as const) {
+ process.env.HERMES_PAYLOAD_TAG = tag
+ process.env.HERMES_BUILD_COMMIT = commit
+ const current: ProductIdentity = await identityForVariant(variant)
+ assert.equal(current.channel, expectedChannel)
+ assert.equal(current.cliName, expectedCli)
+ assert.equal(current.windowsExecutableName, expectedCli)
+ assert.equal(current.artifactNamePascal, stable.artifactNamePascal)
+ assert.deepEqual(current, await identityForVariant(variant))
+
+ if (commit) {
+ assert.equal(current.displayName, `${display} ${commit.slice(0, 7)}`)
}
+
+ for (const previous of identities) {
+ for (const field of [
+ 'displayName',
+ 'appId',
+ 'appNamePascal',
+ 'msixAppIdWithOrg',
+ 'windowsExecutableName',
+ 'cliName'
+ ] as const) {
+ assert.notEqual(current[field], previous[field], `${field} must isolate installations`)
+
+ if (commit) {
+ assert.ok(current[field].includes(commit.slice(0, 7)))
+ }
+ }
+ }
+
+ identities.push(current)
}
- identities.push(current)
+ process.env.HERMES_BUILD_COMMIT = 'not-a-sha'
+ process.env.HERMES_PAYLOAD_TAG = 'v1.2.3'
+ assert.deepEqual(await identityForVariant(variant), stable)
}
-
- process.env.HERMES_BUILD_COMMIT = 'not-a-sha'
- process.env.HERMES_PAYLOAD_TAG = 'v1.2.3'
- assert.deepEqual(await identityForVariant(variant), stable)
-})
+)
test('light and bundled retain distinct OS markers from the full client', async (): Promise<void> => {
const full: ProductIdentity = await identityForVariant(undefined)
@@ -167,7 +187,9 @@ test('light and bundled retain distinct OS markers from the full client', async
for (const variant of ['bundled', 'light']) {
const other: ProductIdentity = await identityForVariant(variant)
- for (const field of ['displayName', 'appId', 'appNamePascal'] as const) { assert.notEqual(other[field], full[field]) }
+ for (const field of ['displayName', 'appId', 'appNamePascal'] as const) {
+ assert.notEqual(other[field], full[field])
+ }
if (variant === 'light') {
assert.notEqual(other.msixAppIdWithOrg, full.msixAppIdWithOrg)
diff --git a/apps/desktop/electron/product-identity.ts b/apps/desktop/electron/product-identity.ts
index 5092b90ce8d..131694e0588 100644
--- a/apps/desktop/electron/product-identity.ts
+++ b/apps/desktop/electron/product-identity.ts
@@ -28,10 +28,16 @@ export const PRODUCT_IDENTITY: Readonly<ProductIdentity> =
* Stable keeps its historical userData and runtime naming behavior.
*/
export function applyDesktopIdentity(
- app: { getPath(name: 'appData'): string; setPath(name: 'userData', value: string): void; setName(name: string): void },
+ app: {
+ getPath(name: 'appData'): string
+ setPath(name: 'userData', value: string): void
+ setName(name: string): void
+ },
identity: Readonly<ProductIdentity> = PRODUCT_IDENTITY
): string | null {
- if (!identity.token && identity.appNamePascal === identity.artifactNamePascal) {return null}
+ if (!identity.token && identity.appNamePascal === identity.artifactNamePascal) {
+ return null
+ }
const userData: string = path.join(app.getPath('appData'), identity.appNamePascal)
mkdirSync(userData, { recursive: true })
app.setPath('userData', userData)
diff --git a/apps/desktop/electron/profile-migration.ts b/apps/desktop/electron/profile-migration.ts
index 34b0b11e6b4..f49fa758703 100644
--- a/apps/desktop/electron/profile-migration.ts
+++ b/apps/desktop/electron/profile-migration.ts
@@ -271,9 +271,8 @@ export function readExistingPreference(
*/
export function migrateActiveProfileIfMissing(desktopProfileConfigPath: string, deps: MigrationDeps): boolean {
const exists: boolean = deps.existsSync(desktopProfileConfigPath)
- const existing = exists
- ? readExistingPreference(desktopProfileConfigPath, deps.readFileSync)
- : null
+
+ const existing = exists ? readExistingPreference(desktopProfileConfigPath, deps.readFileSync) : null
if (exists && (!existing || !existing.migrated)) {
return false
diff --git a/apps/desktop/electron/remote-lifecycle.test.ts b/apps/desktop/electron/remote-lifecycle.test.ts
index 8bf2a800ea3..aa5ece515ac 100644
--- a/apps/desktop/electron/remote-lifecycle.test.ts
+++ b/apps/desktop/electron/remote-lifecycle.test.ts
@@ -880,17 +880,19 @@ test('buildSpawnCommand atomically reserves the ownership slot through spawn and
assert.ok(cmd.indexOf('lock_json') > cmd.indexOf('serve --isolated'))
})
-test.skipIf(process.platform === 'win32')('detached backend does not inherit the update mutex descriptor', async (): Promise<void> => {
- const shell: string = (await exec('command -v bash', { shell: 'bash' })).stdout.trim()
- const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-update-mutex-'))
- const hermesPath: string = path.join(directory, 'hermes')
- const reportPath: string = path.join(directory, 'descriptor-report')
- const logPath: string = path.join(directory, 'spawn.log')
-
- try {
- await writeFile(
- hermesPath,
- `#!${shell}
+test.skipIf(process.platform === 'win32')(
+ 'detached backend does not inherit the update mutex descriptor',
+ async (): Promise<void> => {
+ const shell: string = (await exec('command -v bash', { shell: 'bash' })).stdout.trim()
+ const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-update-mutex-'))
+ const hermesPath: string = path.join(directory, 'hermes')
+ const reportPath: string = path.join(directory, 'descriptor-report')
+ const logPath: string = path.join(directory, 'spawn.log')
+
+ try {
+ await writeFile(
+ hermesPath,
+ `#!${shell}
report=${expandRemotePath(reportPath)}
: > "$report.tmp"
for fd in /proc/$$/fd/*; do
@@ -901,36 +903,37 @@ for fd in /proc/$$/fd/*; do
done
mv "$report.tmp" "$report"
`,
- { encoding: 'utf8', mode: 0o700 }
- )
+ { encoding: 'utf8', mode: 0o700 }
+ )
- const command: string = buildSpawnCommand(hermesPath, '', {
- hermesHome: path.join(directory, 'home'),
- logPath
- })
+ const command: string = buildSpawnCommand(hermesPath, '', {
+ hermesHome: path.join(directory, 'home'),
+ logPath
+ })
- await exec(command, { shell, env: { ...process.env, HOME: directory, HERMES_HOME: directory } })
+ await exec(command, { shell, env: { ...process.env, HOME: directory, HERMES_HOME: directory } })
- for (let attempt: number = 0; attempt < 100; attempt += 1) {
- try {
- const report: string = await readFile(reportPath, 'utf8')
- assert.equal(report, '', 'the backend process must not retain the update mutex descriptor')
+ for (let attempt: number = 0; attempt < 100; attempt += 1) {
+ try {
+ const report: string = await readFile(reportPath, 'utf8')
+ assert.equal(report, '', 'the backend process must not retain the update mutex descriptor')
+
+ return
+ } catch (error: unknown) {
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) {
+ throw error
+ }
- return
- } catch (error: unknown) {
- if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) {
- throw error
+ await new Promise(resolve => setTimeout(resolve, 25))
}
-
- await new Promise(resolve => setTimeout(resolve, 25))
}
- }
- assert.fail('the detached backend did not write its descriptor report')
- } finally {
- await rm(directory, { recursive: true, force: true })
+ assert.fail('the detached backend did not write its descriptor report')
+ } finally {
+ await rm(directory, { recursive: true, force: true })
+ }
}
-})
+)
test('spawnRemoteDashboard returns exact ownership artifacts', async () => {
const ssh = fakeSsh([
diff --git a/apps/desktop/electron/ssh-config.test.ts b/apps/desktop/electron/ssh-config.test.ts
index 54a8dd55618..2180cf176f2 100644
--- a/apps/desktop/electron/ssh-config.test.ts
+++ b/apps/desktop/electron/ssh-config.test.ts
@@ -37,7 +37,7 @@ test('collectSshConfigHosts follows Include directives (read-only)', () => {
const hosts = collectSshConfigHosts('/home/u/.ssh/config', {
homeDir: '/home/u',
- readFile: p => files[p.replaceAll(path.sep, "/")] ?? null
+ readFile: p => files[p.replaceAll(path.sep, '/')] ?? null
})
assert.deepEqual(hosts.sort(), ['deep', 'home-abs', 'main', 'work-box'].sort())
@@ -55,7 +55,7 @@ test('collectSshConfigHosts does not loop on a self-include cycle', () => {
const hosts = collectSshConfigHosts('/home/u/.ssh/config', {
homeDir: '/home/u',
- readFile: p => files[p.replaceAll(path.sep, "/")] ?? null
+ readFile: p => files[p.replaceAll(path.sep, '/')] ?? null
})
assert.deepEqual(hosts.sort(), ['a', 'b'])
@@ -70,9 +70,11 @@ test('collectSshConfigHosts expands globbed includes via injected globSync', ()
const hosts = collectSshConfigHosts('/home/u/.ssh/config', {
homeDir: '/home/u',
- readFile: p => files[p.replaceAll(path.sep, "/")] ?? null,
+ readFile: p => files[p.replaceAll(path.sep, '/')] ?? null,
globSync: pattern =>
- pattern.replaceAll(path.sep, '/').endsWith('config.d/*') ? ['/home/u/.ssh/config.d/10-work', '/home/u/.ssh/config.d/20-home'] : [pattern]
+ pattern.replaceAll(path.sep, '/').endsWith('config.d/*')
+ ? ['/home/u/.ssh/config.d/10-work', '/home/u/.ssh/config.d/20-home']
+ : [pattern]
})
assert.deepEqual(hosts.sort(), ['home', 'root', 'work'].sort())
diff --git a/apps/desktop/electron/ssh-connection.test.ts b/apps/desktop/electron/ssh-connection.test.ts
index c5f6c749047..fb5866ce641 100644
--- a/apps/desktop/electron/ssh-connection.test.ts
+++ b/apps/desktop/electron/ssh-connection.test.ts
@@ -352,7 +352,10 @@ test('open() evicts a wedged master (check passes, exec hangs) and dials fresh',
return { code: 0 }
})
- const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true, controlDir: '/tmp/d', connectTimeoutMs: 50 })
+ const conn = new SshConnection(
+ { host: 'box', user: 'me' },
+ { spawnFn, mux: true, controlDir: '/tmp/d', connectTimeoutMs: 50 }
+ )
await conn.open()
assert.deepEqual(
@@ -1012,7 +1015,8 @@ test('closing one scope addresses only that scope control master', async () => {
{ host: 'box', user: 'me' },
{
spawnFn: firstSpawn,
- mux: true, controlDir: '/tmp/d',
+ mux: true,
+ controlDir: '/tmp/d',
ownershipId: 'installation',
scope: 'first'
}
@@ -1022,7 +1026,8 @@ test('closing one scope addresses only that scope control master', async () => {
{ host: 'box', user: 'me' },
{
spawnFn: secondSpawn,
- mux: true, controlDir: '/tmp/d',
+ mux: true,
+ controlDir: '/tmp/d',
ownershipId: 'installation',
scope: 'second'
}
diff --git a/apps/desktop/electron/update-prerequisites.test.ts b/apps/desktop/electron/update-prerequisites.test.ts
index 0d5256c9a3d..a95daacbca1 100644
--- a/apps/desktop/electron/update-prerequisites.test.ts
+++ b/apps/desktop/electron/update-prerequisites.test.ts
@@ -5,7 +5,11 @@ import path from 'node:path'
import { test } from 'vitest'
-import { launcherTargetsInstallation, resolveInstallationLauncher, windowsUpdatePrerequisiteError } from './updater-process'
+import {
+ launcherTargetsInstallation,
+ resolveInstallationLauncher,
+ windowsUpdatePrerequisiteError
+} from './updater-process'
test('PM update prerequisites use the exact published launcher, not checkout venv files', (): void => {
const root: string = fs.mkdtempSync(path.join(os.tmpdir(), 'update-launcher-'))
@@ -30,7 +34,6 @@ test('PM update prerequisites use the exact published launcher, not checkout ven
}
})
-
test('earlier PM user-bin launchers are accepted only for the reported source tree', (): void => {
const base: string = fs.mkdtempSync(path.join(os.tmpdir(), 'old-pm-launcher-'))
@@ -45,9 +48,10 @@ test('earlier PM user-bin launchers are accepted only for the reported source tr
fs.mkdirSync(path.join(home, 'bin'), { recursive: true })
const launcher: string = path.join(home, 'bin', process.platform === 'win32' ? 'hermes.cmd' : 'hermes')
- const body = (reported: string): string => process.platform === 'win32'
- ? `@echo off\r\necho Install directory: ${reported}\r\n`
- : `#!/bin/sh\nprintf '%s\\n' 'Install directory: ${reported}'\n`
+ const body = (reported: string): string =>
+ process.platform === 'win32'
+ ? `@echo off\r\necho Install directory: ${reported}\r\n`
+ : `#!/bin/sh\nprintf '%s\\n' 'Install directory: ${reported}'\n`
fs.writeFileSync(launcher, body(root), { mode: 0o755 })
assert.equal(launcherTargetsInstallation(launcher, root), true)
diff --git a/apps/desktop/electron/updater-process.ts b/apps/desktop/electron/updater-process.ts
index 65b58730321..432ac26411e 100644
--- a/apps/desktop/electron/updater-process.ts
+++ b/apps/desktop/electron/updater-process.ts
@@ -19,16 +19,23 @@ export function resolveVenvDir(updateRoot: string): string {
return path.join(updateRoot, 'venv')
}
+
import { hiddenWindowsChildOptions } from './windows-child-options'
/** Exact installation identity; PATH may refer to another checkout. */
-export function resolveInstallationLauncher(updateRoot: string, isWindows: boolean = process.platform === 'win32', hermesHome: string = process.env.HERMES_HOME ?? ''): string | null {
+export function resolveInstallationLauncher(
+ updateRoot: string,
+ isWindows: boolean = process.platform === 'win32',
+ hermesHome: string = process.env.HERMES_HOME ?? ''
+): string | null {
const names: string[] = isWindows ? ['hermes.exe', 'hermes.cmd'] : ['hermes']
for (const name of names) {
const candidate: string = path.join(updateRoot, '.hermes', 'bin', name)
- if (stagedFileExists(candidate)) { return candidate }
+ if (stagedFileExists(candidate)) {
+ return candidate
+ }
}
// Earlier PM installers published only to user-bin. Trust that historical
@@ -39,14 +46,20 @@ export function resolveInstallationLauncher(updateRoot: string, isWindows: boole
: path.join(os.homedir(), '.hermes')
const dirs: string[] = isWindows
- ? [path.join(hermesHome || defaultHome, 'bin'), path.join(defaultHome, 'bin'), path.join(path.dirname(updateRoot), 'bin')]
+ ? [
+ path.join(hermesHome || defaultHome, 'bin'),
+ path.join(defaultHome, 'bin'),
+ path.join(path.dirname(updateRoot), 'bin')
+ ]
: [path.join(os.homedir(), '.local', 'bin'), path.join(hermesHome || defaultHome, 'bin')]
for (const dir of new Set(dirs)) {
for (const name of names) {
const candidate: string = path.join(dir, name)
- if (stagedFileExists(candidate) && launcherTargetsInstallation(candidate, updateRoot)) { return candidate }
+ if (stagedFileExists(candidate) && launcherTargetsInstallation(candidate, updateRoot)) {
+ return candidate
+ }
}
}
}
@@ -55,7 +68,9 @@ export function resolveInstallationLauncher(updateRoot: string, isWindows: boole
if (!existsSync(path.join(updateRoot, 'pm'))) {
const legacy: string = path.join(updateRoot, 'venv', isWindows ? 'Scripts' : 'bin', names[0])
- if (stagedFileExists(legacy)) { return legacy }
+ if (stagedFileExists(legacy)) {
+ return legacy
+ }
}
return null
@@ -66,7 +81,11 @@ export function launcherTargetsInstallation(launcher: string, root: string): boo
const shell: boolean = process.platform === 'win32' && /\.cmd$/i.test(launcher)
const output: string = execFileSync(shell ? `"${launcher}"` : launcher, ['--version'], {
- cwd: root, encoding: 'utf8', timeout: 15000, windowsHide: true, shell,
+ cwd: root,
+ encoding: 'utf8',
+ timeout: 15000,
+ windowsHide: true,
+ shell,
env: { ...process.env, HERMES_INSTALL_ROOT: root }
})
diff --git a/apps/desktop/electron/updater/app-installer-recovery.test.ts b/apps/desktop/electron/updater/app-installer-recovery.test.ts
index 668a513571e..4ecd5633835 100644
--- a/apps/desktop/electron/updater/app-installer-recovery.test.ts
+++ b/apps/desktop/electron/updater/app-installer-recovery.test.ts
@@ -20,13 +20,21 @@ for (const failureAt of ['prepare', 'register', 'teardown', 'open', 'none']) {
const act = (at: string): void => {
calls.push(at)
- if (at === failureAt) {throw failure}
+ if (at === failureAt) {
+ throw failure
+ }
}
const deps: AppInstallerStrategyDeps = {
- python: 'unused-checker', script: 'unused.py',
- run: async () => { throw new Error('configured feed does not need the checker') },
- channel: 'stable', light: false, appVersion: '1.0', feedBaseUrl: 'https://example.invalid',
+ python: 'unused-checker',
+ script: 'unused.py',
+ run: async () => {
+ throw new Error('configured feed does not need the checker')
+ },
+ channel: 'stable',
+ light: false,
+ appVersion: '1.0',
+ feedBaseUrl: 'https://example.invalid',
installer: {
prepare: async () => {
act('prepare')
@@ -40,17 +48,32 @@ for (const failureAt of ['prepare', 'register', 'teardown', 'open', 'none']) {
return ''
}
},
- registerPendingRelaunch: (version: string): Promise<RelaunchRegistration> => registerUpdateRelaunch({ getPath: (): string => home }, version, {
- relaunch: async () => {
- act('register')
+ registerPendingRelaunch: (version: string): Promise<RelaunchRegistration> =>
+ registerUpdateRelaunch({ getPath: (): string => home }, version, {
+ relaunch: async () => {
+ act('register')
- return { cancel: async () => { calls.push('cancel') } }
- }
- }),
- teardownBundledBackend: async () => { running = false; act('teardown') },
- restoreBundledBackend: async () => { running = true; calls.push('restore') },
- emitUpdateProgress: value => { progress.push(value.stage) },
- quit: () => { calls.push('quit') }
+ return {
+ cancel: async () => {
+ calls.push('cancel')
+ }
+ }
+ }
+ }),
+ teardownBundledBackend: async () => {
+ running = false
+ act('teardown')
+ },
+ restoreBundledBackend: async () => {
+ running = true
+ calls.push('restore')
+ },
+ emitUpdateProgress: value => {
+ progress.push(value.stage)
+ },
+ quit: () => {
+ calls.push('quit')
+ }
}
try {
@@ -83,16 +106,43 @@ test('handoff errors retain cleanup failures while still restoring the backend',
const order: string[] = []
const deps: AppInstallerStrategyDeps = {
- python: 'unused', script: 'unused.py', run: async () => ({ code: 0, stdout: '' }),
- channel: 'stable', light: false, appVersion: '1.0', feedBaseUrl: 'https://example.invalid',
- installer: { prepare: async () => 'file', open: async () => { throw original } },
- registerPendingRelaunch: (version: string): Promise<RelaunchRegistration> => registerUpdateRelaunch({ getPath: (): string => home }, version, {
- relaunch: async () => ({ cancel: async () => { order.push('cancel'); throw cancellation } })
- }),
- teardownBundledBackend: async () => { order.push('stop') },
- restoreBundledBackend: async () => { order.push('restore'); throw recovery },
- emitUpdateProgress: event => { if (event.stage === 'error') {order.push('error')} },
- quit: () => { throw new Error('failed handoff must not quit') }
+ python: 'unused',
+ script: 'unused.py',
+ run: async () => ({ code: 0, stdout: '' }),
+ channel: 'stable',
+ light: false,
+ appVersion: '1.0',
+ feedBaseUrl: 'https://example.invalid',
+ installer: {
+ prepare: async () => 'file',
+ open: async () => {
+ throw original
+ }
+ },
+ registerPendingRelaunch: (version: string): Promise<RelaunchRegistration> =>
+ registerUpdateRelaunch({ getPath: (): string => home }, version, {
+ relaunch: async () => ({
+ cancel: async () => {
+ order.push('cancel')
+ throw cancellation
+ }
+ })
+ }),
+ teardownBundledBackend: async () => {
+ order.push('stop')
+ },
+ restoreBundledBackend: async () => {
+ order.push('restore')
+ throw recovery
+ },
+ emitUpdateProgress: event => {
+ if (event.stage === 'error') {
+ order.push('error')
+ }
+ },
+ quit: () => {
+ throw new Error('failed handoff must not quit')
+ }
}
try {
diff --git a/apps/desktop/electron/updater/app-installer-strategy.test.ts b/apps/desktop/electron/updater/app-installer-strategy.test.ts
index a19512d09cb..1aad9ecfdcf 100644
--- a/apps/desktop/electron/updater/app-installer-strategy.test.ts
+++ b/apps/desktop/electron/updater/app-installer-strategy.test.ts
@@ -7,7 +7,10 @@ import { describe, expect, it } from 'vitest'
import { AppInstallerStrategy } from './app-installer'
import type { AppInstallerStrategyDeps } from './app-installer'
-interface StrategyFixture { deps: AppInstallerStrategyDeps; calls: string[] }
+interface StrategyFixture {
+ deps: AppInstallerStrategyDeps
+ calls: string[]
+}
function makeDeps(over: Partial<AppInstallerStrategyDeps> = {}): StrategyFixture {
const calls: string[] = []
@@ -20,21 +23,33 @@ function makeDeps(over: Partial<AppInstallerStrategyDeps> = {}): StrategyFixture
light: false,
feedBaseUrl: 'https://updates.example/hermes-desktop',
installer: {
- prepare: async () => { calls.push('prepare');
+ prepare: async () => {
+ calls.push('prepare')
- return 'update.appinstaller' },
- open: async () => { calls.push('open');
+ return 'update.appinstaller'
+ },
+ open: async () => {
+ calls.push('open')
- return '' }
+ return ''
+ }
+ },
+ teardownBundledBackend: async () => {
+ calls.push('teardown')
+ },
+ restoreBundledBackend: async () => {
+ calls.push('restore')
},
- teardownBundledBackend: async () => { calls.push('teardown') },
- restoreBundledBackend: async () => { calls.push('restore') },
emitUpdateProgress: () => {},
appVersion: '0.18.2',
- quit: () => { calls.push('quit') },
- registerPendingRelaunch: async () => { calls.push('relaunch-marker');
+ quit: () => {
+ calls.push('quit')
+ },
+ registerPendingRelaunch: async () => {
+ calls.push('relaunch-marker')
- return { automatic: true, cancel: async () => {} } },
+ return { automatic: true, cancel: async () => {} }
+ },
...over
}
@@ -47,7 +62,9 @@ describe('AppInstallerStrategy.apply', () => {
const { deps, calls } = makeDeps({
registerPendingRelaunch: async () => ({ automatic: false, cancel: async () => {} }),
- emitUpdateProgress: event => { progress.push(event.message) }
+ emitUpdateProgress: event => {
+ progress.push(event.message)
+ }
})
const result = await new AppInstallerStrategy(deps).apply()
@@ -61,11 +78,16 @@ describe('AppInstallerStrategy.apply', () => {
const { deps, calls } = makeDeps({
feedBaseUrl: '',
- run: async () => ({ code: 2, stdout: JSON.stringify({ available: true, source_uri: 'https://registered.example/channel.appinstaller' }) }),
+ run: async () => ({
+ code: 2,
+ stdout: JSON.stringify({ available: true, source_uri: 'https://registered.example/channel.appinstaller' })
+ }),
installer: {
- prepare: async url => { prepared.push(url);
+ prepare: async url => {
+ prepared.push(url)
- return 'registered.appinstaller' },
+ return 'registered.appinstaller'
+ },
open: async () => ''
}
})
@@ -77,13 +99,33 @@ describe('AppInstallerStrategy.apply', () => {
it('uses an exact descriptor without a Python check, and rejects unverified prepared packages before teardown', async (): Promise<void> => {
const { deps, calls } = makeDeps({
- run: async (): Promise<never> => { throw new Error('Dynamic channels do not query the registered moving feed') },
- feed: { url: 'https://updates.example/releases/channel-builds/abc/win32/update.appinstaller', version: '0.0.2.0',
- verifyPrepared: async (): Promise<void> => { calls.push('verify'); throw new Error('wrong signature') }
+ run: async (): Promise<never> => {
+ throw new Error('Dynamic channels do not query the registered moving feed')
+ },
+ feed: {
+ url: 'https://updates.example/releases/channel-builds/abc/win32/update.appinstaller',
+ version: '0.0.2.0',
+ verifyPrepared: async (): Promise<void> => {
+ calls.push('verify')
+ throw new Error('wrong signature')
+ }
},
- appVersion: '0.0.1.0', feedBaseUrl: 'https://updates.example',
- installer: { prepare: async (url: string): Promise<string> => { calls.push(url); return 'pinned.appinstaller' }, open: async (): Promise<string> => { calls.push('open'); return '' } }
+ appVersion: '0.0.1.0',
+ feedBaseUrl: 'https://updates.example',
+ installer: {
+ prepare: async (url: string): Promise<string> => {
+ calls.push(url)
+
+ return 'pinned.appinstaller'
+ },
+ open: async (): Promise<string> => {
+ calls.push('open')
+
+ return ''
+ }
+ }
})
+
const strategy = new AppInstallerStrategy(deps)
expect(await strategy.check()).toMatchObject({ updateAvailable: true })
await expect(strategy.apply()).rejects.toThrow('wrong signature')
@@ -107,41 +149,53 @@ it.each([
[0, '', undefined, 'checker returned no availability'],
[1, 'boom', undefined, 'checker exited 1'],
[0, '{"available":"yes"}', undefined, 'checker returned no availability']
-] as const)('checker %s %s → available=%s error=%s', async (code: number, stdout: string, available: boolean | undefined, error: string | undefined): Promise<void> => {
- const { deps }: ReturnType<typeof makeDeps> = makeDeps({
- run: async (python: string, script: string): Promise<{ code: number; stdout: string }> => {
- expect([python, script]).toEqual(['python.exe', 'check.py'])
-
- return { code, stdout }
- }
- })
+] as const)(
+ 'checker %s %s → available=%s error=%s',
+ async (code: number, stdout: string, available: boolean | undefined, error: string | undefined): Promise<void> => {
+ const { deps }: ReturnType<typeof makeDeps> = makeDeps({
+ run: async (python: string, script: string): Promise<{ code: number; stdout: string }> => {
+ expect([python, script]).toEqual(['python.exe', 'check.py'])
+
+ return { code, stdout }
+ }
+ })
- expect(await new AppInstallerStrategy(deps).check()).toMatchObject({
- supported: true, mechanism: 'app-installer', currentVersion: '0.18.2', updateAvailable: available, error
- })
-})
+ expect(await new AppInstallerStrategy(deps).check()).toMatchObject({
+ supported: true,
+ mechanism: 'app-installer',
+ currentVersion: '0.18.2',
+ updateAvailable: available,
+ error
+ })
+ }
+)
it.each([
['stable', false, 'win32/stable/stable.appinstaller'],
['canary', false, 'win32/canary/canary.appinstaller'],
['stable', true, 'win32/light/stable/stable.appinstaller'],
['canary', true, 'win32/light/canary/canary.appinstaller']
-] as const)('stages %s light=%s from its feed and reports open errors', async (channel: 'stable' | 'canary', light: boolean, suffix: string): Promise<void> => {
- const { deps, calls }: ReturnType<typeof makeDeps> = makeDeps({ channel, light,
- installer: {
- prepare: async (url: string): Promise<string> => {
- expect(url).toBe(`https://updates.example/hermes-desktop/${suffix}`)
+] as const)(
+ 'stages %s light=%s from its feed and reports open errors',
+ async (channel: 'stable' | 'canary', light: boolean, suffix: string): Promise<void> => {
+ const { deps, calls }: ReturnType<typeof makeDeps> = makeDeps({
+ channel,
+ light,
+ installer: {
+ prepare: async (url: string): Promise<string> => {
+ expect(url).toBe(`https://updates.example/hermes-desktop/${suffix}`)
- return 'update.appinstaller'
- },
- open: async (file: string): Promise<string> => {
- expect(file).toBe('update.appinstaller')
+ return 'update.appinstaller'
+ },
+ open: async (file: string): Promise<string> => {
+ expect(file).toBe('update.appinstaller')
- return 'No file association'
+ return 'No file association'
+ }
}
- }
- })
+ })
- await expect(new AppInstallerStrategy(deps).apply()).rejects.toThrow('No file association')
- expect(calls).toEqual(['relaunch-marker', 'teardown', 'restore'])
-})
+ await expect(new AppInstallerStrategy(deps).apply()).rejects.toThrow('No file association')
+ expect(calls).toEqual(['relaunch-marker', 'teardown', 'restore'])
+ }
+)
diff --git a/apps/desktop/electron/updater/app-installer.ts b/apps/desktop/electron/updater/app-installer.ts
index d2c90cc1f9e..249a1b54cd6 100644
--- a/apps/desktop/electron/updater/app-installer.ts
+++ b/apps/desktop/electron/updater/app-installer.ts
@@ -79,12 +79,19 @@ export function createChannelAppInstallerStrategy(
target: ChannelTarget,
verifyPrepared: (file: string, target: ChannelTarget) => Promise<void>
): AppInstallerStrategy {
- if (target.package.platform !== 'win32') { throw new Error('Expected Windows channel target') }
+ if (target.package.platform !== 'win32') {
+ throw new Error('Expected Windows channel target')
+ }
return new AppInstallerStrategy({
- ...deps, channel: target.channel.name, feedBaseUrl: target.manifest.request.publicBase,
- feed: { url: target.feedUrl, version: target.package.version,
- verifyPrepared: (file: string): Promise<void> => verifyPrepared(file, target) }
+ ...deps,
+ channel: target.channel.name,
+ feedBaseUrl: target.manifest.request.publicBase,
+ feed: {
+ url: target.feedUrl,
+ version: target.package.version,
+ verifyPrepared: (file: string): Promise<void> => verifyPrepared(file, target)
+ }
})
}
@@ -95,8 +102,13 @@ export class AppInstallerStrategy {
async check(): Promise<UpdaterStatusWire> {
if (this.deps.feed) {
- return { supported: true, mechanism: this.mechanism, currentVersion: this.deps.appVersion,
- updateAvailable: newerWindowsVersion(this.deps.feed.version, this.deps.appVersion), fetchedAt: Date.now() }
+ return {
+ supported: true,
+ mechanism: this.mechanism,
+ currentVersion: this.deps.appVersion,
+ updateAvailable: newerWindowsVersion(this.deps.feed.version, this.deps.appVersion),
+ fetchedAt: Date.now()
+ }
}
const { code, stdout } = await this.deps.run(this.deps.python, this.deps.script)
@@ -113,9 +125,13 @@ export class AppInstallerStrategy {
channelPublicBase(sourceUri)
const base = channelPublicBase(feedBaseUrl)
- if (!sourceUri.startsWith(`${base}/`) || new URL(sourceUri).origin !== new URL(base).origin) { throw new Error('Native feed authority mismatch') }
+ if (!sourceUri.startsWith(`${base}/`) || new URL(sourceUri).origin !== new URL(base).origin) {
+ throw new Error('Native feed authority mismatch')
+ }
- if (!newerWindowsVersion(this.deps.feed!.version, this.deps.appVersion)) { return { ok: true, mechanism: this.mechanism } }
+ if (!newerWindowsVersion(this.deps.feed!.version, this.deps.appVersion)) {
+ return { ok: true, mechanism: this.mechanism }
+ }
}
if (!feedBaseUrl && !sourceUri) {
@@ -181,10 +197,14 @@ export class AppInstallerStrategy {
function newerWindowsVersion(target: string, current: string): boolean {
const parse = (version: string): number[] => {
- if (!/^\d+\.\d+\.\d+\.\d+$/.test(version)) { throw new Error('Windows channel updates require native numeric versions') }
+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(version)) {
+ throw new Error('Windows channel updates require native numeric versions')
+ }
const parts = version.split('.').map(Number)
- if (parts.some((part: number): boolean => part > 65535)) { throw new Error('Invalid Windows native version') }
+ if (parts.some((part: number): boolean => part > 65535)) {
+ throw new Error('Invalid Windows native version')
+ }
return parts
}
@@ -193,7 +213,9 @@ function newerWindowsVersion(target: string, current: string): boolean {
const right = parse(current)
for (let index = 0; index < 4; index += 1) {
- if (left[index] !== right[index]) { return left[index] > right[index] }
+ if (left[index] !== right[index]) {
+ return left[index] > right[index]
+ }
}
return false
diff --git a/apps/desktop/electron/updater/artifact.ts b/apps/desktop/electron/updater/artifact.ts
index f6fade1985c..0db6417169a 100644
--- a/apps/desktop/electron/updater/artifact.ts
+++ b/apps/desktop/electron/updater/artifact.ts
@@ -13,40 +13,67 @@ export interface PinnedArtifact {
export async function verifyPinnedArtifact(file: string, artifact: PinnedArtifact): Promise<void> {
const info = await lstat(file)
+
if (!info.isFile() || info.isSymbolicLink() || info.size !== artifact.size) {
throw new Error('Pinned artifact size or type mismatch')
}
+
const hash = createHash('sha256')
- for await (const chunk of createReadStream(file)) { hash.update(chunk) }
- if (hash.digest('hex') !== artifact.sha256) { throw new Error('Pinned artifact digest mismatch') }
+
+ for await (const chunk of createReadStream(file)) {
+ hash.update(chunk)
+ }
+
+ if (hash.digest('hex') !== artifact.sha256) {
+ throw new Error('Pinned artifact digest mismatch')
+ }
}
/** Caller owns private storage and its lifetime. Redirects cannot change authority. */
export async function downloadPinnedArtifact(directory: string, artifact: PinnedArtifact): Promise<string> {
const file: string = path.join(directory, `destination.${artifact.format}`)
+
try {
await verifyPinnedArtifact(file, artifact)
+
return file
} catch (error) {
- if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') { throw error }
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') {
+ throw error
+ }
}
+
const temporary: string = `${file}.partial`
await unlink(temporary).catch((error: NodeJS.ErrnoException): void => {
- if (error.code !== 'ENOENT') { throw error }
+ if (error.code !== 'ENOENT') {
+ throw error
+ }
})
const response: Response = await fetch(artifact.url, { redirect: 'error', signal: AbortSignal.timeout(600_000) })
- if (!response.ok || !response.body) { throw new Error(`Pinned artifact download failed (${response.status})`) }
+
+ if (!response.ok || !response.body) {
+ throw new Error(`Pinned artifact download failed (${response.status})`)
+ }
const handle: FileHandle = await open(temporary, 'wx', 0o600)
let size: number = 0
+
try {
for await (const chunk of response.body) {
size += chunk.byteLength
- if (size > artifact.size) { throw new Error('Pinned artifact download exceeds pinned size') }
+
+ if (size > artifact.size) {
+ throw new Error('Pinned artifact download exceeds pinned size')
+ }
await handle.writeFile(chunk)
}
+
await handle.sync()
- } finally { await handle.close() }
+ } finally {
+ await handle.close()
+ }
+
await verifyPinnedArtifact(temporary, artifact)
await rename(temporary, file)
+
return file
-}
\ No newline at end of file
+}
diff --git a/apps/desktop/electron/updater/channel-artifact-lifetime.test.ts b/apps/desktop/electron/updater/channel-artifact-lifetime.test.ts
index ab5e4745cf8..59fc38be99c 100644
--- a/apps/desktop/electron/updater/channel-artifact-lifetime.test.ts
+++ b/apps/desktop/electron/updater/channel-artifact-lifetime.test.ts
@@ -23,27 +23,76 @@ test('ordinary Windows preparation owns temporary bytes while a resumable downlo
const directory: string = await mkdtemp(path.join(os.tmpdir(), 'hermes-artifact-lifetime-'))
directories.push(directory)
const bytes: Buffer = Buffer.from('digest-bound download')
- const server = createServer((_request, response): void => { response.end(bytes) })
+ const server = createServer((_request, response): void => {
+ response.end(bytes)
+ })
server.listen(0, '127.0.0.1')
await once(server, 'listening')
const address = server.address()
- if (!address || !(address instanceof Object)) { throw new Error('Expected TCP server') }
+ if (!address || !(address instanceof Object)) {
+ throw new Error('Expected TCP server')
+ }
const url: string = `http://127.0.0.1:${address.port}/stable.msixbundle`
- const identity = { token: 'a'.repeat(16), displayName: 'Preview', appId: 'chat.nous.preview', appNamePascal: 'Preview',
- artifactNamePascal: 'Preview', cliName: 'preview', windowsExecutableName: 'preview', msixAppIdWithOrg: 'NousResearch.Preview' }
+ const identity = {
+ token: 'a'.repeat(16),
+ displayName: 'Preview',
+ appId: 'chat.nous.preview',
+ appNamePascal: 'Preview',
+ artifactNamePascal: 'Preview',
+ cliName: 'preview',
+ windowsExecutableName: 'preview',
+ msixAppIdWithOrg: 'NousResearch.Preview'
+ }
const target: ChannelTarget = {
- channel: { schema: 1, state: 'active', name: 'preview', repository: 'NousResearch/hermes-agent', policy: 'preview',
- revision: 1, nextSequence: 2, head: null, identity },
- manifest: { schema: 1, packages: [], request: { schema: 1, buildId: 'b'.repeat(32), channel: 'preview', sequence: 1,
- repository: 'NousResearch/hermes-agent', commit: 'c'.repeat(40), sourceVersion: '1.0.0', version: '0.0.1',
- windowsVersion: '0.0.1.0', identity, bundleEnv: {}, publicBase: 'https://example.com' } },
- package: { platform: 'win32', arch: 'x64', variant: 'bundled', version: '0.0.1.0', identity: identity.msixAppIdWithOrg,
- publisher: 'CN=Test', artifact: { key: 'stable.msixbundle', sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.length },
- feed: { key: 'stable.appinstaller', channel: 'stable' } },
- artifactUrl: url, feedUrl: 'https://example.com/stable.appinstaller', manifestSha256: 'd'.repeat(64)
+ channel: {
+ schema: 1,
+ state: 'active',
+ name: 'preview',
+ repository: 'NousResearch/hermes-agent',
+ policy: 'preview',
+ revision: 1,
+ nextSequence: 2,
+ head: null,
+ identity
+ },
+ manifest: {
+ schema: 1,
+ packages: [],
+ request: {
+ schema: 1,
+ buildId: 'b'.repeat(32),
+ channel: 'preview',
+ sequence: 1,
+ repository: 'NousResearch/hermes-agent',
+ commit: 'c'.repeat(40),
+ sourceVersion: '1.0.0',
+ version: '0.0.1',
+ windowsVersion: '0.0.1.0',
+ identity,
+ bundleEnv: {},
+ publicBase: 'https://example.com'
+ }
+ },
+ package: {
+ platform: 'win32',
+ arch: 'x64',
+ variant: 'bundled',
+ version: '0.0.1.0',
+ identity: identity.msixAppIdWithOrg,
+ publisher: 'CN=Test',
+ artifact: {
+ key: 'stable.msixbundle',
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ size: bytes.length
+ },
+ feed: { key: 'stable.appinstaller', channel: 'stable' }
+ },
+ artifactUrl: url,
+ feedUrl: 'https://example.com/stable.appinstaller',
+ manifestSha256: 'd'.repeat(64)
}
try {
@@ -59,9 +108,11 @@ test('ordinary Windows preparation owns temporary bytes while a resumable downlo
await verifyPreparedChannelInstaller(file, target, command)
expect(await readdir(directory)).toEqual(['stable.appinstaller'])
- await expect(verifyPreparedChannelInstaller(file, target, async (): Promise<never> => {
- throw new Error('native signature refused')
- })).rejects.toThrow('signature refused')
+ await expect(
+ verifyPreparedChannelInstaller(file, target, async (): Promise<never> => {
+ throw new Error('native signature refused')
+ })
+ ).rejects.toThrow('signature refused')
expect(await readdir(directory)).toEqual(['stable.appinstaller'])
const durable: string = path.join(directory, 'durable-download')
await mkdir(durable, { mode: 0o700 })
@@ -69,5 +120,8 @@ test('ordinary Windows preparation owns temporary bytes while a resumable downlo
const downloaded: string = await downloadPinnedArtifact(durable, artifact)
expect(await downloadPinnedArtifact(durable, artifact)).toBe(downloaded)
expect(await readFile(downloaded)).toEqual(bytes)
- } finally { server.close(); await once(server, 'close') }
+ } finally {
+ server.close()
+ await once(server, 'close')
+ }
})
diff --git a/apps/desktop/electron/updater/channel-native.test.ts b/apps/desktop/electron/updater/channel-native.test.ts
index 2990e868cb7..a37c533f3b7 100644
--- a/apps/desktop/electron/updater/channel-native.test.ts
+++ b/apps/desktop/electron/updater/channel-native.test.ts
@@ -14,10 +14,16 @@ test('download verification binds native bytes to the manifest size and digest b
try {
const content = Buffer.from('real local archive fixture bytes')
await writeFile(file, content)
- const artifact = { key: 'releases/fixture.zip', size: content.length, sha256: createHash('sha256').update(content).digest('hex') }
+ const artifact = {
+ key: 'releases/fixture.zip',
+ size: content.length,
+ sha256: createHash('sha256').update(content).digest('hex')
+ }
await verifyChannelDownload([file], artifact)
await writeFile(file, Buffer.alloc(content.length))
await expect(verifyChannelDownload([file], artifact)).rejects.toThrow('digest')
await expect(verifyChannelDownload([], artifact)).rejects.toThrow('one')
- } finally { await rm(directory, { recursive: true, force: true }) }
+ } finally {
+ await rm(directory, { recursive: true, force: true })
+ }
})
diff --git a/apps/desktop/electron/updater/channel-native.ts b/apps/desktop/electron/updater/channel-native.ts
index 5dc3b0c1e70..e2aecd3b7a3 100644
--- a/apps/desktop/electron/updater/channel-native.ts
+++ b/apps/desktop/electron/updater/channel-native.ts
@@ -7,15 +7,29 @@ import type { ChannelBuild, ChannelPackage } from './channel-protocol'
/** Native feeds carry their own hashes; also require the admitted build's hash. */
export async function verifyChannelDownload(files: string[], artifact: ChannelPackage['artifact']): Promise<void> {
- if (files.length !== 1) { throw new Error('Expected exactly one channel artifact') }
+ if (files.length !== 1) {
+ throw new Error('Expected exactly one channel artifact')
+ }
const file = await open(files[0], 'r')
+
try {
const stat = await file.stat()
- if (!stat.isFile() || stat.size !== artifact.size) { throw new Error('Channel artifact size mismatch') }
+
+ if (!stat.isFile() || stat.size !== artifact.size) {
+ throw new Error('Channel artifact size mismatch')
+ }
const digest = createHash('sha256')
- for await (const chunk of file.createReadStream({ autoClose: false })) { digest.update(chunk) }
- if (digest.digest('hex') !== artifact.sha256) { throw new Error('Channel artifact digest mismatch') }
- } finally { await file.close() }
+
+ for await (const chunk of file.createReadStream({ autoClose: false })) {
+ digest.update(chunk)
+ }
+
+ if (digest.digest('hex') !== artifact.sha256) {
+ throw new Error('Channel artifact digest mismatch')
+ }
+ } finally {
+ await file.close()
+ }
}
export interface NativeCommandResult {
@@ -51,11 +65,15 @@ export function runChannelCommand(
}
export async function runChannelPowerShell(script: string, input: string = ''): Promise<NativeCommandResult> {
- if (process.platform !== 'win32') { throw new Error('This operation requires Windows') }
+ if (process.platform !== 'win32') {
+ throw new Error('This operation requires Windows')
+ }
+
return runChannelCommand(
path.join(process.env.SystemRoot || 'C:\\Windows', 'System32/WindowsPowerShell/v1.0/powershell.exe'),
['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
- 600_000, input
+ 600_000,
+ input
)
}
@@ -97,19 +115,33 @@ export interface RunningChannelApp {
/** Derive trust from the signed running application, never from an R2 document. */
export async function inspectRunningChannelApp(build: ChannelBuild): Promise<RunningChannelApp> {
const executable: string = await canonicalChannelPath(process.execPath)
+
if (process.platform === 'darwin') {
const appPath: string = path.resolve(executable, '../../..')
await runChannelCommand('/usr/bin/codesign', ['--verify', '--deep', '--strict', appPath])
const signature: NativeCommandResult = await runChannelCommand('/usr/bin/codesign', ['-dv', '--verbose=4', appPath])
const signer: string = /^TeamIdentifier=(.+)$/m.exec(signature.stderr)?.[1] || ''
const identity: string = /^Identifier=(.+)$/m.exec(signature.stderr)?.[1] || ''
+
if (!/^[A-Z0-9]{10}$/.test(signer) || identity !== build.identity.appId) {
throw new Error('Running channel application signature does not match its baked identity')
}
- return { identity, signer, appPath, executable, nativeVersion: build.version,
- applicationId: null, packageFullName: null, packageFamilyName: null, removalRoots: [appPath] }
+
+ return {
+ identity,
+ signer,
+ appPath,
+ executable,
+ nativeVersion: build.version,
+ applicationId: null,
+ packageFullName: null,
+ packageFamilyName: null,
+ removalRoots: [appPath]
+ }
}
- const result: NativeCommandResult = await runChannelPowerShell(String.raw`
+
+ const result: NativeCommandResult = await runChannelPowerShell(
+ String.raw`
$ErrorActionPreference='Stop'
$p=[Console]::In.ReadToEnd() | ConvertFrom-Json
$packages=@(Get-AppxPackage -Name $p.identity | Where-Object { $_.Name -ceq $p.identity })
@@ -121,10 +153,19 @@ $manifest=Get-AppxPackageManifest -Package $pkg.PackageFullName
$apps=@($manifest.Package.Applications.Application | Where-Object { [IO.Path]::GetFullPath((Join-Path $pkg.InstallLocation $_.Executable)) -ieq $p.executable })
if ($apps.Count -ne 1) { throw 'Running executable is not the registered application' }
@{ identity=$pkg.Name; signer=$pkg.Publisher; appPath=$pkg.InstallLocation; nativeVersion=$pkg.Version.ToString(); executable=$p.executable; applicationId=$apps[0].Id; packageFullName=$pkg.PackageFullName; packageFamilyName=$pkg.PackageFamilyName; removalRoots=@($pkg.InstallLocation,(Join-Path ([Environment]::GetFolderPath('LocalApplicationData')) ('Packages\'+$pkg.PackageFamilyName))) } | ConvertTo-Json -Compress
-`, JSON.stringify({ identity: build.identity.msixAppIdWithOrg, executable }))
+`,
+ JSON.stringify({ identity: build.identity.msixAppIdWithOrg, executable })
+ )
+
const installed: RunningChannelApp = JSON.parse(result.stdout)
- if (installed.nativeVersion !== build.windowsVersion || installed.identity !== build.identity.msixAppIdWithOrg || !installed.signer) {
+
+ if (
+ installed.nativeVersion !== build.windowsVersion ||
+ installed.identity !== build.identity.msixAppIdWithOrg ||
+ !installed.signer
+ ) {
throw new Error('Running package does not match its baked channel version')
}
+
return installed
}
diff --git a/apps/desktop/electron/updater/channel-protocol.ts b/apps/desktop/electron/updater/channel-protocol.ts
index c2d5eb5c550..bbbd11f0e30 100644
--- a/apps/desktop/electron/updater/channel-protocol.ts
+++ b/apps/desktop/electron/updater/channel-protocol.ts
@@ -34,7 +34,12 @@ export interface ChannelRequest extends ChannelBuild {
controllerCommit?: string
releaseTag?: string
}
-export interface ChannelHead { buildId: string; sequence: number; manifestKey: string; sha256: string }
+export interface ChannelHead {
+ buildId: string
+ sequence: number
+ manifestKey: string
+ sha256: string
+}
interface ChannelRecordBase {
schema: 1
name: string
@@ -45,7 +50,9 @@ interface ChannelRecordBase {
identity: ChannelIdentity
head: ChannelHead | null
}
-export interface ActiveChannel extends ChannelRecordBase { state: 'active' }
+export interface ActiveChannel extends ChannelRecordBase {
+ state: 'active'
+}
export type ReceiverKind = 'in-place' | 'discontinued'
export interface RetiredChannel extends ChannelRecordBase {
state: 'retired'
@@ -68,8 +75,12 @@ export interface ChannelPackage {
teamId?: string
feed: { key: string; channel: string }
}
-export interface ChannelManifest { schema: 1; request: ChannelRequest; packages: ChannelPackage[]; receiverProtocol?: number }
-
+export interface ChannelManifest {
+ schema: 1
+ request: ChannelRequest
+ packages: ChannelPackage[]
+ receiverProtocol?: number
+}
const SHA256 = /^[a-f0-9]{64}$/
const COMMIT = /^[a-f0-9]{40}$/
@@ -82,16 +93,34 @@ function parseChannelJson(body: string): unknown {
// the same reject-duplicates contract as the publisher's object_pairs_hook.
const objects: Set<string>[] = []
const tokens = /"(?:[^"\\]|\\[\s\S])*"\s*:|"(?:[^"\\]|\\[\s\S])*"|[{}]/g
+
for (const match of body.matchAll(tokens)) {
const token = match[0]
- if (token === '{') { objects.push(new Set<string>()); continue }
- if (token === '}') { objects.pop(); continue }
- if (!token.endsWith(':')) { continue }
+
+ if (token === '{') {
+ objects.push(new Set<string>())
+
+ continue
+ }
+
+ if (token === '}') {
+ objects.pop()
+
+ continue
+ }
+
+ if (!token.endsWith(':')) {
+ continue
+ }
const key: string = JSON.parse(token.slice(0, -1))
const keys = objects[objects.length - 1]
- if (keys.has(key)) { throw new Error('Duplicate channel JSON member') }
+
+ if (keys.has(key)) {
+ throw new Error('Duplicate channel JSON member')
+ }
keys.add(key)
}
+
return parsed
}
@@ -99,57 +128,103 @@ function parseChannelJson(body: string): unknown {
class Fields {
private readonly input: object
constructor(input: unknown) {
- if (!input || typeof input !== 'object' || Array.isArray(input)) { throw new Error('Expected channel object') }
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
+ throw new Error('Expected channel object')
+ }
this.input = input
}
- get(key: string): unknown { return Reflect.get(this.input, key) }
- keys(): string[] { return Object.keys(this.input) }
+ get(key: string): unknown {
+ return Reflect.get(this.input, key)
+ }
+ keys(): string[] {
+ return Object.keys(this.input)
+ }
text(key: string, pattern: RegExp = /^[\s\S]{1,2048}$/): string {
const value: unknown = this.get(key)
- if (typeof value !== 'string' || [...value].some((character: string): boolean => character.charCodeAt(0) < 32) || !pattern.test(value)) { throw new Error(`Invalid channel ${key}`) }
+
+ if (
+ typeof value !== 'string' ||
+ [...value].some((character: string): boolean => character.charCodeAt(0) < 32) ||
+ !pattern.test(value)
+ ) {
+ throw new Error(`Invalid channel ${key}`)
+ }
+
return value
}
integer(key: string, maximum: number = Number.MAX_SAFE_INTEGER): number {
const value: unknown = this.get(key)
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > maximum) {
throw new Error(`Invalid channel ${key}`)
}
+
return value
}
- object(key: string): Fields { return new Fields(this.get(key)) }
+ object(key: string): Fields {
+ return new Fields(this.get(key))
+ }
optional(key: string, pattern?: RegExp): string | undefined {
return this.get(key) === undefined ? undefined : this.text(key, pattern)
}
- schema(): void { if (this.get('schema') !== 1) { throw new Error('Unsupported channel schema') } }
+ schema(): void {
+ if (this.get('schema') !== 1) {
+ throw new Error('Unsupported channel schema')
+ }
+ }
}
export function validateChannelName(name: string): string {
// This validates syntax, not whether R2 has registered the name.
feedContract.darwinFeed(name)
+
return name
}
export function channelPublicBase(value: string): string {
const url = new URL(value)
const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
- if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
- url.username || url.password || url.search || url.hash || /[%\\;\s]/.test(value) ||
- value.split('/').some((part: string): boolean => part === '.' || part === '..')) {
+
+ if (
+ (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
+ url.username ||
+ url.password ||
+ url.search ||
+ url.hash ||
+ /[%\\;\s]/.test(value) ||
+ value.split('/').some((part: string): boolean => part === '.' || part === '..')
+ ) {
throw new Error('Channel archive must use HTTPS or loopback HTTP without credentials or traversal')
}
+
return value.replace(/\/+$/, '')
}
export function channelKey(value: string): string {
- if (!/^releases\/[A-Za-z0-9_./+-]+$/.test(value) ||
- value.split('/').some((part: string): boolean => !part || part === '.' || part === '..' || part.endsWith('.') || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) {
+ if (
+ !/^releases\/[A-Za-z0-9_./+-]+$/.test(value) ||
+ value
+ .split('/')
+ .some(
+ (part: string): boolean =>
+ !part ||
+ part === '.' ||
+ part === '..' ||
+ part.endsWith('.') ||
+ /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)
+ )
+ ) {
throw new Error('Invalid channel object key')
}
+
return value
}
export function buildPrefix(buildId: string): string {
- if (!BUILD_ID.test(buildId)) { throw new Error('Invalid channel buildId') }
+ if (!BUILD_ID.test(buildId)) {
+ throw new Error('Invalid channel buildId')
+ }
+
return `releases/channel-builds/${buildId}/`
}
@@ -167,24 +242,45 @@ function identity(fields: Fields): ChannelIdentity {
}
export function sameChannelIdentity(left: ChannelIdentity, right: ChannelIdentity): boolean {
- return left.token === right.token && left.displayName === right.displayName && left.appId === right.appId &&
- left.appNamePascal === right.appNamePascal && left.artifactNamePascal === right.artifactNamePascal &&
- left.cliName === right.cliName && left.windowsExecutableName === right.windowsExecutableName &&
+ return (
+ left.token === right.token &&
+ left.displayName === right.displayName &&
+ left.appId === right.appId &&
+ left.appNamePascal === right.appNamePascal &&
+ left.artifactNamePascal === right.artifactNamePascal &&
+ left.cliName === right.cliName &&
+ left.windowsExecutableName === right.windowsExecutableName &&
left.msixAppIdWithOrg === right.msixAppIdWithOrg
+ )
}
function head(value: unknown): ChannelHead | null {
- if (value === null) { return null }
+ if (value === null) {
+ return null
+ }
const fields = new Fields(value)
const buildId = fields.text('buildId', BUILD_ID)
const manifestKey = fields.text('manifestKey')
- if (manifestKey !== `${buildPrefix(buildId)}build.json`) { throw new Error('Invalid channel manifestKey') }
- return { buildId, manifestKey, sequence: fields.integer('sequence', 0xffffffff), sha256: fields.text('sha256', SHA256) }
+
+ if (manifestKey !== `${buildPrefix(buildId)}build.json`) {
+ throw new Error('Invalid channel manifestKey')
+ }
+
+ return {
+ buildId,
+ manifestKey,
+ sequence: fields.integer('sequence', 0xffffffff),
+ sha256: fields.text('sha256', SHA256)
+ }
}
function requiredHead(value: unknown): ChannelHead {
const result = head(value)
- if (!result) { throw new Error('Missing retirement destination head') }
+
+ if (!result) {
+ throw new Error('Missing retirement destination head')
+ }
+
return result
}
@@ -192,29 +288,58 @@ export function decodeChannelRecord(body: string): ChannelRecord {
const fields = new Fields(parseChannelJson(body))
fields.schema()
const policy = fields.text('policy')
+
if (policy !== 'preview' && policy !== 'stable-release' && policy !== 'canary-release') {
throw new Error('Channel has no supported desktop delivery')
}
+
const common: ChannelRecordBase = {
- schema: 1, name: validateChannelName(fields.text('name')),
+ schema: 1,
+ name: validateChannelName(fields.text('name')),
repository: fields.text('repository', /^[A-Za-z0-9][A-Za-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*$/),
- policy, identity: identity(fields.object('identity')), revision: fields.integer('revision'),
- nextSequence: fields.integer('nextSequence', 0x100000000), head: head(fields.get('head'))
+ policy,
+ identity: identity(fields.object('identity')),
+ revision: fields.integer('revision'),
+ nextSequence: fields.integer('nextSequence', 0x100000000),
+ head: head(fields.get('head'))
+ }
+
+ if (common.head && common.head.sequence >= common.nextSequence) {
+ throw new Error('Channel head exceeds allocation')
}
- if (common.head && common.head.sequence >= common.nextSequence) { throw new Error('Channel head exceeds allocation') }
const state = fields.text('state')
- if (state === 'active') { return { ...common, state } }
- if (state !== 'retired') { throw new Error('Invalid channel state') }
+
+ if (state === 'active') {
+ return { ...common, state }
+ }
+
+ if (state !== 'retired') {
+ throw new Error('Invalid channel state')
+ }
const lastHead = head(fields.get('lastHead'))
- if (JSON.stringify(lastHead) !== JSON.stringify(common.head)) { throw new Error('Retirement lastHead mismatch') }
- if (fields.get('receiverProtocol') !== 1) { throw new Error('Unsupported retirement receiver protocol') }
+
+ if (JSON.stringify(lastHead) !== JSON.stringify(common.head)) {
+ throw new Error('Retirement lastHead mismatch')
+ }
+
+ if (fields.get('receiverProtocol') !== 1) {
+ throw new Error('Unsupported retirement receiver protocol')
+ }
const receiverFields = fields.object('receiver')
const kind = receiverFields.text('kind')
- if (kind !== 'in-place' && kind !== 'discontinued') { throw new Error('Invalid retirement receiver kind') }
+
+ if (kind !== 'in-place' && kind !== 'discontinued') {
+ throw new Error('Invalid retirement receiver kind')
+ }
+
return {
- ...common, state, lastHead, destination: validateChannelName(fields.text('destination')),
+ ...common,
+ state,
+ lastHead,
+ destination: validateChannelName(fields.text('destination')),
minimumVersion: fields.text('minimumVersion', VERSION),
- destinationHead: requiredHead(fields.get('destinationHead')), receiverProtocol: 1,
+ destinationHead: requiredHead(fields.get('destinationHead')),
+ receiverProtocol: 1,
receiver: { kind }
}
}
@@ -223,23 +348,48 @@ function request(fields: Fields): ChannelRequest {
fields.schema()
const environment = fields.object('bundleEnv')
const bundleEnv: ChannelBuild['bundleEnv'] = {}
+
for (const key of environment.keys()) {
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) { throw new Error('Invalid bundle environment name') }
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
+ throw new Error('Invalid bundle environment name')
+ }
const value: unknown = environment.get(key)
- if (value !== null && (typeof value !== 'string' || value.includes('\0'))) { throw new Error('Invalid bundle environment value') }
+
+ if (value !== null && (typeof value !== 'string' || value.includes('\0'))) {
+ throw new Error('Invalid bundle environment value')
+ }
Object.defineProperty(bundleEnv, key, { value, enumerable: true })
}
+
const publicBase = fields.text('publicBase')
- if (channelPublicBase(publicBase) !== publicBase) { throw new Error('Noncanonical request publicBase') }
+
+ if (channelPublicBase(publicBase) !== publicBase) {
+ throw new Error('Noncanonical request publicBase')
+ }
const releaseTag = fields.optional('releaseTag', /^v\d+\.\d+\.\d+(?:-canary\.\d+)?$/)
- const windowsVersion = fields.text('windowsVersion', releaseTag?.includes('-canary.') ? /^\d+\.\d+\.\d+\.\d+$/ : /^\d+\.\d+\.\d+\.0$/)
- if (windowsVersion.split('.').some((part: string): boolean => Number(part) > 65535)) { throw new Error('Invalid Windows version') }
+ const windowsVersion = fields.text(
+ 'windowsVersion',
+ releaseTag?.includes('-canary.') ? /^\d+\.\d+\.\d+\.\d+$/ : /^\d+\.\d+\.\d+\.0$/
+ )
+
+ if (windowsVersion.split('.').some((part: string): boolean => Number(part) > 65535)) {
+ throw new Error('Invalid Windows version')
+ }
+
return {
- schema: 1, buildId: fields.text('buildId', BUILD_ID), channel: validateChannelName(fields.text('channel')),
- sequence: fields.integer('sequence', 0xffffffff), repository: fields.text('repository', /^[A-Za-z0-9][A-Za-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*$/),
- commit: fields.text('commit', COMMIT), sourceVersion: fields.text('sourceVersion', VERSION),
- version: fields.text('version', VERSION), windowsVersion, publicBase, bundleEnv,
- identity: identity(fields.object('identity')), controllerCommit: fields.optional('controllerCommit', COMMIT),
+ schema: 1,
+ buildId: fields.text('buildId', BUILD_ID),
+ channel: validateChannelName(fields.text('channel')),
+ sequence: fields.integer('sequence', 0xffffffff),
+ repository: fields.text('repository', /^[A-Za-z0-9][A-Za-z0-9_-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*$/),
+ commit: fields.text('commit', COMMIT),
+ sourceVersion: fields.text('sourceVersion', VERSION),
+ version: fields.text('version', VERSION),
+ windowsVersion,
+ publicBase,
+ bundleEnv,
+ identity: identity(fields.object('identity')),
+ controllerCommit: fields.optional('controllerCommit', COMMIT),
releaseTag
}
}
@@ -248,29 +398,54 @@ function packageEntry(value: unknown): ChannelPackage {
const fields = new Fields(value)
const platform = fields.text('platform')
const arch = fields.text('arch')
- if ((platform !== 'darwin' && platform !== 'win32') || (arch !== 'x64' && arch !== 'arm64') || fields.get('variant') !== 'bundled') {
+
+ if (
+ (platform !== 'darwin' && platform !== 'win32') ||
+ (arch !== 'x64' && arch !== 'arm64') ||
+ fields.get('variant') !== 'bundled'
+ ) {
throw new Error('Unsupported channel package')
}
+
const artifact = fields.object('artifact')
const feed = fields.object('feed')
+
return {
- platform, arch, variant: 'bundled', version: fields.text('version', platform === 'darwin' ? VERSION : /^\d+\.\d+\.\d+\.\d+$/), identity: fields.text('identity'),
- artifact: { key: channelKey(artifact.text('key')), sha256: artifact.text('sha256', SHA256), size: artifact.integer('size') },
- publisher: fields.optional('publisher'), teamId: fields.optional('teamId', /^[A-Z0-9]{10}$/),
+ platform,
+ arch,
+ variant: 'bundled',
+ version: fields.text('version', platform === 'darwin' ? VERSION : /^\d+\.\d+\.\d+\.\d+$/),
+ identity: fields.text('identity'),
+ artifact: {
+ key: channelKey(artifact.text('key')),
+ sha256: artifact.text('sha256', SHA256),
+ size: artifact.integer('size')
+ },
+ publisher: fields.optional('publisher'),
+ teamId: fields.optional('teamId', /^[A-Z0-9]{10}$/),
feed: { key: channelKey(feed.text('key')), channel: feed.text('channel', /^[a-z][a-z0-9-]{0,31}$/) }
}
}
-
export function decodeChannelManifest(body: string): ChannelManifest {
const fields = new Fields(parseChannelJson(body))
fields.schema()
const entries: unknown = fields.get('packages')
- if (!Array.isArray(entries) || !entries.length || entries.length > 4) { throw new Error('Invalid channel packages') }
+
+ if (!Array.isArray(entries) || !entries.length || entries.length > 4) {
+ throw new Error('Invalid channel packages')
+ }
const packages: ChannelPackage[] = entries.map(packageEntry)
const keys = new Set(packages.map((entry: ChannelPackage): string => `${entry.platform}/${entry.arch}`))
- if (keys.size !== packages.length) { throw new Error('Duplicate channel package') }
+
+ if (keys.size !== packages.length) {
+ throw new Error('Duplicate channel package')
+ }
const manifest: ChannelManifest = { schema: 1, request: request(fields.object('request')), packages }
- if (fields.get('receiverProtocol') !== undefined) { manifest.receiverProtocol = fields.integer('receiverProtocol') }
+
+ if (fields.get('receiverProtocol') !== undefined) {
+ manifest.receiverProtocol = fields.integer('receiverProtocol')
+ }
+
return manifest
}
diff --git a/apps/desktop/electron/updater/channel-strategy.ts b/apps/desktop/electron/updater/channel-strategy.ts
index 493bab75290..a5fa1af75e5 100644
--- a/apps/desktop/electron/updater/channel-strategy.ts
+++ b/apps/desktop/electron/updater/channel-strategy.ts
@@ -15,8 +15,16 @@ export interface ChannelStrategyDeps {
mechanism: 'electron-updater' | 'app-installer'
nativeFactory: (target: ChannelTarget) => UpdaterStrategy
}
-interface NativeSelection { kind: 'native'; strategy: UpdaterStrategy; available: boolean }
-interface RetirementSelection { kind: 'retirement'; value: unknown; state: ChannelRetirementStatus['state'] }
+interface NativeSelection {
+ kind: 'native'
+ strategy: UpdaterStrategy
+ available: boolean
+}
+interface RetirementSelection {
+ kind: 'retirement'
+ value: unknown
+ state: ChannelRetirementStatus['state']
+}
type Selection = NativeSelection | RetirementSelection | { kind: 'empty' }
/** One selection owns a check/apply operation; background checks cannot retarget it. */
@@ -25,17 +33,25 @@ export class ChannelStrategy implements UpdaterStrategy {
private selection: Selection | null = null
private busy = false
- constructor(private readonly deps: ChannelStrategyDeps) { this.mechanism = deps.mechanism }
+ constructor(private readonly deps: ChannelStrategyDeps) {
+ this.mechanism = deps.mechanism
+ }
private enter(): void {
- if (this.busy) { throw new Error('An update operation is already in progress.') }
+ if (this.busy) {
+ throw new Error('An update operation is already in progress.')
+ }
this.busy = true
}
async check(): Promise<UpdaterStatusWire> {
this.enter()
- try { return await this.select() } finally { this.busy = false }
+ try {
+ return await this.select()
+ } finally {
+ this.busy = false
+ }
}
private async select(): Promise<UpdaterStatusWire> {
@@ -44,8 +60,11 @@ export class ChannelStrategy implements UpdaterStrategy {
const result = await this.deps.resolver.resolve()
const base: UpdaterStatusWire = {
- supported: true, mechanism: this.mechanism, channel: this.deps.build.channel,
- currentVersion: this.deps.build.version, fetchedAt: Date.now()
+ supported: true,
+ mechanism: this.mechanism,
+ channel: this.deps.build.channel,
+ currentVersion: this.deps.build.version,
+ fetchedAt: Date.now()
}
if (result.kind === 'empty') {
@@ -71,14 +90,23 @@ export class ChannelStrategy implements UpdaterStrategy {
this.selection = { kind: 'retirement', value: result.retirement, state: 'discontinued' }
return {
- ...base, retirement: { state: 'discontinued', destination: result.retirement.target.channel.name, version: result.retirement.target.manifest.request.version }
+ ...base,
+ retirement: {
+ state: 'discontinued',
+ destination: result.retirement.target.channel.name,
+ version: result.retirement.target.manifest.request.version
+ }
}
}
return await this.selectNative(base, result.target)
}
- private async selectNative(base: UpdaterStatusWire, target: ChannelTarget, options: { crossChannel?: boolean } = {}): Promise<UpdaterStatusWire> {
+ private async selectNative(
+ base: UpdaterStatusWire,
+ target: ChannelTarget,
+ options: { crossChannel?: boolean } = {}
+ ): Promise<UpdaterStatusWire> {
if (!options.crossChannel && target.manifest.request.sequence <= this.deps.build.sequence) {
this.selection = { kind: 'empty' }
@@ -88,24 +116,39 @@ export class ChannelStrategy implements UpdaterStrategy {
const strategy = this.deps.nativeFactory(target)
const status = await strategy.check()
- if (status.error || status.updateAvailable === undefined) { throw new Error(status.error || 'Native update availability unknown') }
+ if (status.error || status.updateAvailable === undefined) {
+ throw new Error(status.error || 'Native update availability unknown')
+ }
this.selection = { kind: 'native', strategy, available: status.updateAvailable }
- return { ...status, ...base, latestTag: `v${target.manifest.request.version}`, targetSha: target.manifest.request.commit }
+ return {
+ ...status,
+ ...base,
+ latestTag: `v${target.manifest.request.version}`,
+ targetSha: target.manifest.request.commit
+ }
}
async apply(): Promise<UpdaterApplyResultWire> {
this.enter()
try {
- if (!this.selection) { await this.select() }
+ if (!this.selection) {
+ await this.select()
+ }
const selected = this.selection
- if (selected?.kind === 'retirement') { return { ok: false, error: 'This build is discontinued; uninstall it and install an official release.' } }
+ if (selected?.kind === 'retirement') {
+ return { ok: false, error: 'This build is discontinued; uninstall it and install an official release.' }
+ }
- if (selected?.kind === 'native' && selected.available) { return await selected.strategy.apply() }
+ if (selected?.kind === 'native' && selected.available) {
+ return await selected.strategy.apply()
+ }
return { ok: true, mechanism: this.mechanism }
- } finally { this.busy = false }
+ } finally {
+ this.busy = false
+ }
}
}
diff --git a/apps/desktop/electron/updater/channel-windows-host.ts b/apps/desktop/electron/updater/channel-windows-host.ts
index f30e036674b..f2b451b960a 100644
--- a/apps/desktop/electron/updater/channel-windows-host.ts
+++ b/apps/desktop/electron/updater/channel-windows-host.ts
@@ -7,21 +7,27 @@ import { type NativeCommandResult, runChannelPowerShell } from './channel-native
/** Verify downloaded bytes and native metadata before App Installer can stop the backend. */
export async function verifyPreparedChannelInstaller(
- file: string, target: ChannelTarget,
+ file: string,
+ target: ChannelTarget,
command: (script: string, input: string) => Promise<NativeCommandResult> = runChannelPowerShell
): Promise<void> {
const pkg = target.package
- if (pkg.platform !== 'win32' || !pkg.publisher) { throw new Error('Expected a publisher-bound Windows package') }
+ if (pkg.platform !== 'win32' || !pkg.publisher) {
+ throw new Error('Expected a publisher-bound Windows package')
+ }
const directory: string = await mkdtemp(path.join(path.dirname(file), '.channel-artifact-'))
try {
- const artifact: string = await downloadPinnedArtifact(directory,
- { url: target.artifactUrl, sha256: pkg.artifact.sha256, size: pkg.artifact.size,
- format: pkg.artifact.key.endsWith('.msixbundle') ? 'msixbundle' : 'msix' }
- )
+ const artifact: string = await downloadPinnedArtifact(directory, {
+ url: target.artifactUrl,
+ sha256: pkg.artifact.sha256,
+ size: pkg.artifact.size,
+ format: pkg.artifact.key.endsWith('.msixbundle') ? 'msixbundle' : 'msix'
+ })
- await command(String.raw`
+ await command(
+ String.raw`
$ErrorActionPreference='Stop'
$p=[Console]::In.ReadToEnd() | ConvertFrom-Json
function Read-SafeXml($stream) {
@@ -50,7 +56,19 @@ try {
else { $identity=$native.Bundle.Identity; $slices=@($native.Bundle.Packages.Package | Where-Object { $_.Type -ceq 'application' -and $_.Architecture -ceq $p.arch -and $_.Version -ceq $p.version }); if ($slices.Count -ne 1) { throw 'Bundle architecture/version mismatch' } }
if ($identity.Name -cne $p.identity -or $identity.Publisher -cne $p.publisher -or $identity.Version -cne $p.version) { throw 'Native manifest binding mismatch' }
} finally { $zip.Dispose() }
-`, JSON.stringify({ file, artifact, feedUrl: target.feedUrl, artifactUrl: target.artifactUrl,
- identity: pkg.identity, publisher: pkg.publisher, version: pkg.version, arch: pkg.arch }))
- } finally { await rm(directory, { recursive: true, force: true }) }
+`,
+ JSON.stringify({
+ file,
+ artifact,
+ feedUrl: target.feedUrl,
+ artifactUrl: target.artifactUrl,
+ identity: pkg.identity,
+ publisher: pkg.publisher,
+ version: pkg.version,
+ arch: pkg.arch
+ })
+ )
+ } finally {
+ await rm(directory, { recursive: true, force: true })
+ }
}
diff --git a/apps/desktop/electron/updater/channel.test.ts b/apps/desktop/electron/updater/channel.test.ts
index 7de50b96157..bd27b16865c 100644
--- a/apps/desktop/electron/updater/channel.test.ts
+++ b/apps/desktop/electron/updater/channel.test.ts
@@ -12,15 +12,24 @@ import { ChannelStrategy } from './channel-strategy'
const servers: Server[] = []
afterEach(async (): Promise<void> => {
- await Promise.all(servers.splice(0).map((server: Server): Promise<void> => new Promise((resolve): void => {
- server.closeAllConnections()
- server.close((): void => resolve())
- })))
+ await Promise.all(
+ servers.splice(0).map(
+ (server: Server): Promise<void> =>
+ new Promise((resolve): void => {
+ server.closeAllConnections()
+ server.close((): void => resolve())
+ })
+ )
+ )
})
async function fixture(): Promise<{
- build: ChannelBuild; record: ChannelRecord; manifest: ChannelManifest;
- objects: Map<string, string>; requests: string[]; publish: () => void;
+ build: ChannelBuild
+ record: ChannelRecord
+ manifest: ChannelManifest
+ objects: Map<string, string>
+ requests: string[]
+ publish: () => void
}> {
const objects = new Map<string, string>()
const requests: string[] = []
@@ -33,21 +42,36 @@ async function fixture(): Promise<{
})
servers.push(server)
- await new Promise<void>((resolve): void => { server.listen(0, '127.0.0.1', resolve) })
+ await new Promise<void>((resolve): void => {
+ server.listen(0, '127.0.0.1', resolve)
+ })
const address = server.address()
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Node's listen() address boundary admits pipes or TCP; this fixture requires TCP.
- if (!address || typeof address === 'string') { throw new Error('No fixture port') }
+ if (!address || typeof address === 'string') {
+ throw new Error('No fixture port')
+ }
const build: ChannelBuild = {
- buildId: 'a'.repeat(32), channel: 'fresh-preview-29', sequence: 1,
- repository: 'example/hermes-agent', commit: 'b'.repeat(40), sourceVersion: '1.2.3',
- version: '0.0.1', windowsVersion: '0.0.1.0', publicBase: `http://127.0.0.1:${address.port}`,
- bundleEnv: {}, identity: {
- token: '1234567890abcdef', displayName: 'Hermes fresh-preview-29',
- appId: 'chat.nous.hermes.h1234567890abcdef', appNamePascal: 'HermesH1234567890abcdef',
- artifactNamePascal: 'HermesH1234567890abcdef', cliName: 'hermes-fresh-preview-29',
- windowsExecutableName: 'HermesH1234567890abcdef.exe', msixAppIdWithOrg: 'NousResearch.HermesH1234567890abcdef'
+ buildId: 'a'.repeat(32),
+ channel: 'fresh-preview-29',
+ sequence: 1,
+ repository: 'example/hermes-agent',
+ commit: 'b'.repeat(40),
+ sourceVersion: '1.2.3',
+ version: '0.0.1',
+ windowsVersion: '0.0.1.0',
+ publicBase: `http://127.0.0.1:${address.port}`,
+ bundleEnv: {},
+ identity: {
+ token: '1234567890abcdef',
+ displayName: 'Hermes fresh-preview-29',
+ appId: 'chat.nous.hermes.h1234567890abcdef',
+ appNamePascal: 'HermesH1234567890abcdef',
+ artifactNamePascal: 'HermesH1234567890abcdef',
+ cliName: 'hermes-fresh-preview-29',
+ windowsExecutableName: 'HermesH1234567890abcdef.exe',
+ msixAppIdWithOrg: 'NousResearch.HermesH1234567890abcdef'
}
}
@@ -55,24 +79,40 @@ async function fixture(): Promise<{
const prefix = `releases/channel-builds/${next.buildId}/`
const manifest: ChannelManifest = {
- schema: 1, request: { schema: 1, ...next }, packages: [{
- platform: 'darwin', arch: 'arm64', variant: 'bundled', version: next.version,
- identity: build.identity.appId, teamId: 'ABCDE12345',
- artifact: { key: `${prefix}darwin/Hermes.zip`, sha256: 'd'.repeat(64), size: 100 },
- feed: { key: `${prefix}darwin/stable-mac.yml`, channel: 'stable' }
- }]
+ schema: 1,
+ request: { schema: 1, ...next },
+ packages: [
+ {
+ platform: 'darwin',
+ arch: 'arm64',
+ variant: 'bundled',
+ version: next.version,
+ identity: build.identity.appId,
+ teamId: 'ABCDE12345',
+ artifact: { key: `${prefix}darwin/Hermes.zip`, sha256: 'd'.repeat(64), size: 100 },
+ feed: { key: `${prefix}darwin/stable-mac.yml`, channel: 'stable' }
+ }
+ ]
}
const record: ChannelRecord = {
- schema: 1, name: build.channel, repository: build.repository, policy: 'preview', state: 'active',
- revision: 2, nextSequence: 3, identity: build.identity,
+ schema: 1,
+ name: build.channel,
+ repository: build.repository,
+ policy: 'preview',
+ state: 'active',
+ revision: 2,
+ nextSequence: 3,
+ identity: build.identity,
head: { buildId: next.buildId, sequence: 2, manifestKey: `${prefix}build.json`, sha256: '' }
}
const publish = (): void => {
const body = JSON.stringify(manifest)
- if (record.state !== 'active' || !record.head) { throw new Error('Fixture requires active head') }
+ if (record.state !== 'active' || !record.head) {
+ throw new Error('Fixture requires active head')
+ }
record.head.sha256 = createHash('sha256').update(body).digest('hex')
objects.set(`/${record.head.manifestKey}`, body)
objects.set(`/releases/channels/${record.name}.json`, JSON.stringify(record))
@@ -83,13 +123,16 @@ async function fixture(): Promise<{
return { build, record, manifest, objects, requests, publish }
}
-async function retiredFixture(kind: 'in-place' | 'discontinued' = 'discontinued'): Promise<Awaited<ReturnType<typeof fixture>> & { retired: RetiredChannel }> {
+async function retiredFixture(
+ kind: 'in-place' | 'discontinued' = 'discontinued'
+): Promise<Awaited<ReturnType<typeof fixture>> & { retired: RetiredChannel }> {
const f = await fixture()
const sourceRecord: ChannelRecord = structuredClone(f.record)
f.record.name = 'stable'
f.record.policy = 'stable-release'
+
if (kind === 'in-place') {
// Mainline-like prerelease: the destination IS the stable identity.
f.build = { ...f.build, identity: structuredClone(sourceRecord.identity) }
@@ -97,18 +140,35 @@ async function retiredFixture(kind: 'in-place' | 'discontinued' = 'discontinued'
} else {
f.record.identity = { ...f.build.identity, appId: 'chat.nous.hermes', token: 'fedcba0987654321' }
}
- f.manifest.request = { ...f.manifest.request, channel: 'stable', identity: f.record.identity, version: '1.2.3', windowsVersion: '1.2.3.0', releaseTag: 'v1.2.3' }
+
+ f.manifest.request = {
+ ...f.manifest.request,
+ channel: 'stable',
+ identity: f.record.identity,
+ version: '1.2.3',
+ windowsVersion: '1.2.3.0',
+ releaseTag: 'v1.2.3'
+ }
f.manifest.packages[0].identity = f.record.identity.appId
f.manifest.packages[0].version = '1.2.3'
f.manifest.receiverProtocol = 1
f.publish()
- if (!f.record.head) { throw new Error('Expected published stable') }
+ if (!f.record.head) {
+ throw new Error('Expected published stable')
+ }
+
const retired: RetiredChannel = {
- ...sourceRecord, state: 'retired', destination: 'stable', minimumVersion: '1.0.0',
- destinationHead: structuredClone(f.record.head), receiverProtocol: 1,
- receiver: { kind }, lastHead: sourceRecord.head
+ ...sourceRecord,
+ state: 'retired',
+ destination: 'stable',
+ minimumVersion: '1.0.0',
+ destinationHead: structuredClone(f.record.head),
+ receiverProtocol: 1,
+ receiver: { kind },
+ lastHead: sourceRecord.head
}
+
f.objects.set(`/releases/channels/${retired.name}.json`, JSON.stringify(retired))
return { ...f, retired }
@@ -116,20 +176,24 @@ async function retiredFixture(kind: 'in-place' | 'discontinued' = 'discontinued'
test('receiver kind mirrors the identity comparison between retired channel and destination', async (): Promise<void> => {
const f = await retiredFixture()
- const read = (): RetiredChannel => decodeChannelRecord(
- f.objects.get(`/releases/channels/${f.retired.name}.json`)!) as RetiredChannel
+
+ const read = (): RetiredChannel =>
+ decodeChannelRecord(f.objects.get(`/releases/channels/${f.retired.name}.json`)!) as RetiredChannel
+
const stable = decodeChannelRecord(f.objects.get('/releases/channels/stable.json')!)
// The fixture destination identity is suffixed away from the preview's, so the
// publisher-pinned tier is the one a mismatch implies.
expect(sameChannelIdentity(read().identity, stable.identity)).toBe(false)
expect(read().receiver).toEqual({ kind: 'discontinued' })
// A mainline-like prerelease shares the destination identity: in-place.
- f.objects.set(`/releases/channels/${f.retired.name}.json`,
- JSON.stringify({ ...f.retired, receiver: { kind: 'in-place' } }))
+ f.objects.set(
+ `/releases/channels/${f.retired.name}.json`,
+ JSON.stringify({ ...f.retired, receiver: { kind: 'in-place' } })
+ )
expect(read().receiver).toEqual({ kind: 'in-place' })
+
for (const kind of ['unknown', 'In-Place', '', 'discontinue'] as const) {
- f.objects.set(`/releases/channels/${f.retired.name}.json`,
- JSON.stringify({ ...f.retired, receiver: { kind } }))
+ f.objects.set(`/releases/channels/${f.retired.name}.json`, JSON.stringify({ ...f.retired, receiver: { kind } }))
expect(read).toThrow(/kind/)
}
})
@@ -137,12 +201,25 @@ test('receiver kind mirrors the identity comparison between retired channel and
test('protected canary accepts bounded Windows revisions without relaxing stable', async (): Promise<void> => {
const f = await fixture()
f.record.policy = 'canary-release'
- f.manifest.packages = [{
- platform: 'win32', arch: 'x64', variant: 'bundled', version: '1.2.4.10',
- identity: f.build.identity.msixAppIdWithOrg, publisher: 'CN=Nous Research',
- artifact: { key: `releases/channel-builds/${f.manifest.request.buildId}/win32/Hermes.msixbundle`, sha256: 'd'.repeat(64), size: 100 },
- feed: { key: `releases/channel-builds/${f.manifest.request.buildId}/win32/stable.appinstaller`, channel: 'stable' }
- }]
+ f.manifest.packages = [
+ {
+ platform: 'win32',
+ arch: 'x64',
+ variant: 'bundled',
+ version: '1.2.4.10',
+ identity: f.build.identity.msixAppIdWithOrg,
+ publisher: 'CN=Nous Research',
+ artifact: {
+ key: `releases/channel-builds/${f.manifest.request.buildId}/win32/Hermes.msixbundle`,
+ sha256: 'd'.repeat(64),
+ size: 100
+ },
+ feed: {
+ key: `releases/channel-builds/${f.manifest.request.buildId}/win32/stable.appinstaller`,
+ channel: 'stable'
+ }
+ }
+ ]
f.manifest.request.releaseTag = 'v1.2.4-canary.20260913001000'
f.manifest.request.version = f.manifest.request.releaseTag.slice(1)
f.manifest.request.windowsVersion = '1.2.4.10'
@@ -173,10 +250,16 @@ test('offers a digest-bound retirement without a second proof document', async (
const result = await new ChannelResolver({ build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()
expect(result.kind).toBe('retirement')
- if (result.kind !== 'retirement') { throw new Error('Expected retirement') }
+ if (result.kind !== 'retirement') {
+ throw new Error('Expected retirement')
+ }
expect(result.retirement.target.channel.name).toBe('stable')
expect(result.retirement.target.manifestSha256).toBe(retired.destinationHead.sha256)
- expect(requests).toEqual([`/releases/channels/${build.channel}.json`, '/releases/channels/stable.json', `/${retired.destinationHead.manifestKey}`])
+ expect(requests).toEqual([
+ `/releases/channels/${build.channel}.json`,
+ '/releases/channels/stable.json',
+ `/${retired.destinationHead.manifestKey}`
+ ])
})
test('pins the checked target during apply even after R2 advances, and never auto-downloads', async (): Promise<void> => {
@@ -186,17 +269,24 @@ test('pins the checked target during apply even after R2 advances, and never aut
let enteredResolve: () => void = (): void => {}
let releaseResolve: () => void = (): void => {}
- const entered = new Promise<void>((resolve): void => { enteredResolve = resolve })
- const release = new Promise<void>((resolve): void => { releaseResolve = resolve })
+ const entered = new Promise<void>((resolve): void => {
+ enteredResolve = resolve
+ })
+ const release = new Promise<void>((resolve): void => {
+ releaseResolve = resolve
+ })
const strategy = new ChannelStrategy({
resolver: new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }),
- build: f.build, mechanism: 'electron-updater',
- nativeFactory: (target) => ({
+ build: f.build,
+ mechanism: 'electron-updater',
+ nativeFactory: target => ({
mechanism: 'electron-updater',
- check: async () => { calls.push('check');
+ check: async () => {
+ calls.push('check')
- return { supported: true, updateAvailable: true } },
+ return { supported: true, updateAvailable: true }
+ },
apply: async () => {
calls.push(target.manifest.request.buildId)
enteredResolve()
@@ -230,17 +320,27 @@ test('in-place retirement resolves with the receiver kind and routes through the
const result = await resolver.resolve()
expect(result.kind).toBe('retirement')
- if (result.kind !== 'retirement') { throw new Error('Expected retirement') }
+ if (result.kind !== 'retirement') {
+ throw new Error('Expected retirement')
+ }
expect(result.retirement.receiverKind).toBe('in-place')
const strategy = new ChannelStrategy({
- resolver, build: f.build, mechanism: 'electron-updater',
- nativeFactory: (target) => ({
+ resolver,
+ build: f.build,
+ mechanism: 'electron-updater',
+ nativeFactory: target => ({
mechanism: 'electron-updater',
- check: async () => { nativeCalls.push(`check:${target.manifest.request.buildId}`);
- return { supported: true, updateAvailable: true } },
- apply: async () => { nativeCalls.push('apply');
- return { ok: true, handedOff: true } }
+ check: async () => {
+ nativeCalls.push(`check:${target.manifest.request.buildId}`)
+
+ return { supported: true, updateAvailable: true }
+ },
+ apply: async () => {
+ nativeCalls.push('apply')
+
+ return { ok: true, handedOff: true }
+ }
})
})
@@ -265,12 +365,18 @@ test('discontinued retirement surfaces the notice and never downloads or applies
const result = await resolver.resolve()
expect(result.kind).toBe('retirement')
- if (result.kind !== 'retirement') { throw new Error('Expected retirement') }
+ if (result.kind !== 'retirement') {
+ throw new Error('Expected retirement')
+ }
expect(result.retirement.receiverKind).toBe('discontinued')
const strategy = new ChannelStrategy({
- resolver, build: f.build, mechanism: 'electron-updater',
- nativeFactory: (): never => { throw new Error('Discontinued retirement must never reach the native updater') }
+ resolver,
+ build: f.build,
+ mechanism: 'electron-updater',
+ nativeFactory: (): never => {
+ throw new Error('Discontinued retirement must never reach the native updater')
+ }
})
const status = await strategy.check()
@@ -278,10 +384,12 @@ test('discontinued retirement surfaces the notice and never downloads or applies
expect(status.retirement).toMatchObject({ state: 'discontinued', destination: 'stable', version: '1.2.3' })
// Neither the migration host nor the native updater was consulted.
expect(migrationCalls).toEqual([])
+
// Only channel records and the pinned manifest were read — no artifact fetch.
for (const request of f.requests) {
expect(request).toMatch(/^\/releases\/(channels\/|channel-builds\/[a-f0-9]+\/build\.json$)/)
}
+
expect(f.requests).not.toContain('/releases/channel-builds/cccccccccccccccccccccccccccccccc/darwin/Hermes.zip')
// The ordinary apply path refuses rather than downloading.
expect(await strategy.apply()).toMatchObject({ ok: false })
@@ -292,8 +400,11 @@ test('discontinued retirement never consults the migration callbacks; the apply
const strategy = new ChannelStrategy({
resolver: new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }),
- build: f.build, mechanism: 'electron-updater',
- nativeFactory: (): never => { throw new Error('Not a same-identity update') }
+ build: f.build,
+ mechanism: 'electron-updater',
+ nativeFactory: (): never => {
+ throw new Error('Not a same-identity update')
+ }
})
const status = await strategy.check()
@@ -302,57 +413,94 @@ test('discontinued retirement never consults the migration callbacks; the apply
expect(await strategy.apply()).toMatchObject({ ok: false })
})
-test.each(['hash', 'identity', 'repository', 'signer', 'escape', 'schema', 'version'] as const)('rejects untrusted %s without falling back', async (fault): Promise<void> => {
- const f = await fixture()
+test.each(['hash', 'identity', 'repository', 'signer', 'escape', 'schema', 'version'] as const)(
+ 'rejects untrusted %s without falling back',
+ async (fault): Promise<void> => {
+ const f = await fixture()
- if (fault === 'identity') { f.manifest.request.identity.appId = 'chat.other.identity' }
+ if (fault === 'identity') {
+ f.manifest.request.identity.appId = 'chat.other.identity'
+ }
- if (fault === 'repository') { f.manifest.request.repository = 'other/hermes-agent' }
+ if (fault === 'repository') {
+ f.manifest.request.repository = 'other/hermes-agent'
+ }
- if (fault === 'signer') { f.manifest.packages[0].teamId = 'ZZZZZ99999' }
+ if (fault === 'signer') {
+ f.manifest.packages[0].teamId = 'ZZZZZ99999'
+ }
- if (fault === 'escape') { f.manifest.packages[0].feed.key = 'releases/other/stable-mac.yml' }
+ if (fault === 'escape') {
+ f.manifest.packages[0].feed.key = 'releases/other/stable-mac.yml'
+ }
- if (fault === 'version') { f.manifest.request.version = '1.0.0' }
- f.publish()
+ if (fault === 'version') {
+ f.manifest.request.version = '1.0.0'
+ }
+ f.publish()
- if (fault === 'hash') { f.objects.set(`/${f.record.head!.manifestKey}`, '{}') }
+ if (fault === 'hash') {
+ f.objects.set(`/${f.record.head!.manifestKey}`, '{}')
+ }
- if (fault === 'schema') { f.objects.set(`/releases/channels/${f.record.name}.json`, '{"schema":2}') }
- await expect(new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()).rejects.toThrow()
-})
+ if (fault === 'schema') {
+ f.objects.set(`/releases/channels/${f.record.name}.json`, '{"schema":2}')
+ }
+ await expect(
+ new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()
+ ).rejects.toThrow()
+ }
+)
+
+test.each(['floor', 'cycle', 'protocol', 'receiver', 'digest', 'missing', 'unprotected'] as const)(
+ 'blocks retirement with invalid %s',
+ async (fault): Promise<void> => {
+ const f = await retiredFixture()
+
+ if (fault === 'unprotected') {
+ f.record.policy = 'preview'
+ f.manifest.request.version = '0.0.2'
+ f.manifest.request.windowsVersion = '0.0.2.0'
+ f.manifest.packages[0].version = '0.0.2'
+ f.publish()
+ }
-test.each(['floor', 'cycle', 'protocol', 'receiver', 'digest', 'missing', 'unprotected'] as const)('blocks retirement with invalid %s', async (fault): Promise<void> => {
- const f = await retiredFixture()
+ if (fault === 'floor') {
+ f.retired.minimumVersion = '2.0.0'
+ }
- if (fault === 'unprotected') {
- f.record.policy = 'preview'
- f.manifest.request.version = '0.0.2'
- f.manifest.request.windowsVersion = '0.0.2.0'
- f.manifest.packages[0].version = '0.0.2'
- f.publish()
- }
+ if (fault === 'receiver') {
+ delete f.manifest.receiverProtocol
+ f.publish()
+
+ if (!f.record.head) {
+ throw new Error('Expected published stable')
+ }
+ f.retired.destinationHead = structuredClone(f.record.head)
+ }
- if (fault === 'floor') { f.retired.minimumVersion = '2.0.0' }
+ if (fault === 'cycle') {
+ f.retired.destination = f.build.channel
+ }
- if (fault === 'receiver') {
- delete f.manifest.receiverProtocol
- f.publish()
- if (!f.record.head) { throw new Error('Expected published stable') }
- f.retired.destinationHead = structuredClone(f.record.head)
- }
+ if (fault === 'digest') {
+ f.retired.destinationHead.sha256 = 'f'.repeat(64)
+ }
- if (fault === 'cycle') { f.retired.destination = f.build.channel }
+ if (fault === 'missing') {
+ f.objects.delete(`/${f.retired.destinationHead.manifestKey}`)
+ }
+ f.objects.set(`/releases/channels/${f.retired.name}.json`, JSON.stringify(f.retired))
- if (fault === 'digest') { f.retired.destinationHead.sha256 = 'f'.repeat(64) }
+ if (fault === 'protocol') {
+ f.objects.set(`/releases/channels/${f.retired.name}.json`, JSON.stringify({ ...f.retired, receiverProtocol: 2 }))
+ }
- if (fault === 'missing') { f.objects.delete(`/${f.retired.destinationHead.manifestKey}`) }
- f.objects.set(`/releases/channels/${f.retired.name}.json`, JSON.stringify(f.retired))
- if (fault === 'protocol') {
- f.objects.set(`/releases/channels/${f.retired.name}.json`, JSON.stringify({ ...f.retired, receiverProtocol: 2 }))
+ await expect(
+ new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()
+ ).rejects.toThrow()
}
- await expect(new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()).rejects.toThrow()
-})
+)
test('missing and oversized metadata remain errors while unpublished channels are explicitly empty', async (): Promise<void> => {
const f = await fixture()
@@ -366,29 +514,56 @@ test('missing and oversized metadata remain errors while unpublished channels ar
expect((await resolver.resolve()).kind).toBe('empty')
})
-test.each(['UPPER', 'a--b', '../a', 'a%2fb', 'con', 'a\n', 'a'.repeat(33)])('refuses invalid channel slug %j without normalization', (name: string): void => {
- expect((): void => { feedContract.darwinFeed(name) }).toThrow()
-})
+test.each(['UPPER', 'a--b', '../a', 'a%2fb', 'con', 'a\n', 'a'.repeat(33)])(
+ 'refuses invalid channel slug %j without normalization',
+ (name: string): void => {
+ expect((): void => {
+ feedContract.darwinFeed(name)
+ }).toThrow()
+ }
+)
test('refuses public HTTP archive origins before network access', async (): Promise<void> => {
const f = await fixture()
f.build.publicBase = 'http://example.com'
- expect((): void => { new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }) }).toThrow('HTTPS')
+ expect((): void => {
+ new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' })
+ }).toThrow('HTTPS')
})
test('Windows resolves its numeric native version, publisher and immutable descriptor without Python', async (): Promise<void> => {
const f = await fixture()
- f.manifest.packages = [{
- platform: 'win32', arch: 'x64', variant: 'bundled', version: '0.0.2.0',
- identity: f.build.identity.msixAppIdWithOrg, publisher: 'CN=Nous Research',
- artifact: { key: `releases/channel-builds/${f.manifest.request.buildId}/win32/Hermes.msixbundle`, sha256: 'd'.repeat(64), size: 100 },
- feed: { key: `releases/channel-builds/${f.manifest.request.buildId}/win32/stable.appinstaller`, channel: 'stable' }
- }]
+ f.manifest.packages = [
+ {
+ platform: 'win32',
+ arch: 'x64',
+ variant: 'bundled',
+ version: '0.0.2.0',
+ identity: f.build.identity.msixAppIdWithOrg,
+ publisher: 'CN=Nous Research',
+ artifact: {
+ key: `releases/channel-builds/${f.manifest.request.buildId}/win32/Hermes.msixbundle`,
+ sha256: 'd'.repeat(64),
+ size: 100
+ },
+ feed: {
+ key: `releases/channel-builds/${f.manifest.request.buildId}/win32/stable.appinstaller`,
+ channel: 'stable'
+ }
+ }
+ ]
f.publish()
- const result = await new ChannelResolver({ build: f.build, platform: 'win32', arch: 'x64', signer: 'CN=Nous Research' }).resolve()
+ const result = await new ChannelResolver({
+ build: f.build,
+ platform: 'win32',
+ arch: 'x64',
+ signer: 'CN=Nous Research'
+ }).resolve()
expect(result.kind).toBe('active')
- if (result.kind !== 'active') { throw new Error('Expected active') }
+ if (result.kind !== 'active') {
+ throw new Error('Expected active')
+ }
expect(result.target.package.version).toBe('0.0.2.0')
expect(result.target.feedUrl).toContain('/win32/stable.appinstaller')
})
@@ -399,12 +574,16 @@ test('failed checks clear a previously checked selection, never authorizing a st
const strategy = new ChannelStrategy({
resolver: new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }),
- build: f.build, mechanism: 'electron-updater',
- nativeFactory: () => ({ mechanism: 'electron-updater',
+ build: f.build,
+ mechanism: 'electron-updater',
+ nativeFactory: () => ({
+ mechanism: 'electron-updater',
check: async () => ({ supported: true, updateAvailable: true }),
- apply: async () => { applied = true;
+ apply: async () => {
+ applied = true
- return { ok: true } }
+ return { ok: true }
+ }
})
})
@@ -418,18 +597,43 @@ test('failed checks clear a previously checked selection, never authorizing a st
test('long-offline previews retain the qualified migration target after stable advances', async (): Promise<void> => {
const f = await retiredFixture()
const qualifiedBuild = f.manifest.request.buildId
- f.manifest.request = { ...f.manifest.request, buildId: 'e'.repeat(32), sequence: 3, version: '1.3.0', windowsVersion: '1.3.0.0', sourceVersion: '1.3.0', releaseTag: 'v1.3.0' }
- f.record.head = { buildId: f.manifest.request.buildId, sequence: 3, manifestKey: `releases/channel-builds/${f.manifest.request.buildId}/build.json`, sha256: '' }
+ f.manifest.request = {
+ ...f.manifest.request,
+ buildId: 'e'.repeat(32),
+ sequence: 3,
+ version: '1.3.0',
+ windowsVersion: '1.3.0.0',
+ sourceVersion: '1.3.0',
+ releaseTag: 'v1.3.0'
+ }
+ f.record.head = {
+ buildId: f.manifest.request.buildId,
+ sequence: 3,
+ manifestKey: `releases/channel-builds/${f.manifest.request.buildId}/build.json`,
+ sha256: ''
+ }
f.record.nextSequence = 4
- f.manifest.packages[0] = { ...f.manifest.packages[0], version: '1.3.0',
- artifact: { ...f.manifest.packages[0].artifact, key: `releases/channel-builds/${f.manifest.request.buildId}/darwin/Hermes.zip` },
+ f.manifest.packages[0] = {
+ ...f.manifest.packages[0],
+ version: '1.3.0',
+ artifact: {
+ ...f.manifest.packages[0].artifact,
+ key: `releases/channel-builds/${f.manifest.request.buildId}/darwin/Hermes.zip`
+ },
feed: { key: `releases/channel-builds/${f.manifest.request.buildId}/darwin/stable-mac.yml`, channel: 'stable' }
}
f.publish()
- const result = await new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()
+ const result = await new ChannelResolver({
+ build: f.build,
+ platform: 'darwin',
+ arch: 'arm64',
+ signer: 'ABCDE12345'
+ }).resolve()
expect(result.kind).toBe('retirement')
- if (result.kind !== 'retirement') { throw new Error('Expected retirement') }
+ if (result.kind !== 'retirement') {
+ throw new Error('Expected retirement')
+ }
expect(result.retirement.target.manifest.request.buildId).toBe(qualifiedBuild)
expect(result.retirement.target.manifest.request.channel).toBe('stable')
})
@@ -438,7 +642,9 @@ test('rejects duplicate JSON members rather than disagreeing with the publisher
const f = await fixture()
const body = f.objects.get(`/releases/channels/${f.build.channel}.json`)!
f.objects.set(`/releases/channels/${f.build.channel}.json`, body.replace('"schema":1', '"schema":2,"schema":1'))
- await expect(new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()).rejects.toThrow('Duplicate')
+ await expect(
+ new ChannelResolver({ build: f.build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()
+ ).rejects.toThrow('Duplicate')
})
test('resolves an arbitrary R2 name through a real HTTP channel and digest-bound immutable build', async (): Promise<void> => {
@@ -446,8 +652,15 @@ test('resolves an arbitrary R2 name through a real HTTP channel and digest-bound
const result = await new ChannelResolver({ build, platform: 'darwin', arch: 'arm64', signer: 'ABCDE12345' }).resolve()
expect(result.kind).toBe('active')
- if (result.kind !== 'active') { throw new Error('Expected active build') }
+ if (result.kind !== 'active') {
+ throw new Error('Expected active build')
+ }
expect(result.target.manifest.request.sequence).toBe(2)
- expect(result.target.feedUrl).toBe(`${build.publicBase}/releases/channel-builds/${'c'.repeat(32)}/darwin/stable-mac.yml`)
- expect(requests).toEqual([`/releases/channels/${build.channel}.json`, `/releases/channel-builds/${'c'.repeat(32)}/build.json`])
+ expect(result.target.feedUrl).toBe(
+ `${build.publicBase}/releases/channel-builds/${'c'.repeat(32)}/darwin/stable-mac.yml`
+ )
+ expect(requests).toEqual([
+ `/releases/channels/${build.channel}.json`,
+ `/releases/channel-builds/${'c'.repeat(32)}/build.json`
+ ])
})
diff --git a/apps/desktop/electron/updater/channel.ts b/apps/desktop/electron/updater/channel.ts
index 3cae36e2e97..f4217cadfa4 100644
--- a/apps/desktop/electron/updater/channel.ts
+++ b/apps/desktop/electron/updater/channel.ts
@@ -1,9 +1,19 @@
import { createHash } from 'node:crypto'
import {
- type ActiveChannel, buildPrefix, type ChannelBuild, channelKey, type ChannelManifest,
- type ChannelPackage, channelPublicBase, decodeChannelManifest, decodeChannelRecord,
- type ReceiverKind, type RetiredChannel, sameChannelIdentity, validateChannelName
+ type ActiveChannel,
+ buildPrefix,
+ type ChannelBuild,
+ channelKey,
+ type ChannelManifest,
+ type ChannelPackage,
+ channelPublicBase,
+ decodeChannelManifest,
+ decodeChannelRecord,
+ type ReceiverKind,
+ type RetiredChannel,
+ sameChannelIdentity,
+ validateChannelName
} from './channel-protocol'
export interface ChannelTarget {
@@ -39,11 +49,18 @@ function assertVersionFloor(version: string, floor: string): void {
if (!/^\d+\.\d+\.\d+$/.test(version) || !/^\d+\.\d+\.\d+$/.test(floor)) {
throw new Error('Retirement version floor is not comparable')
}
+
const current = version.split('.').map(BigInt)
const minimum = floor.split('.').map(BigInt)
+
for (let index = 0; index < 3; index += 1) {
- if (current[index] > minimum[index]) { return }
- if (current[index] < minimum[index]) { throw new Error('Destination is below retirement minimum version') }
+ if (current[index] > minimum[index]) {
+ return
+ }
+
+ if (current[index] < minimum[index]) {
+ throw new Error('Destination is below retirement minimum version')
+ }
}
}
@@ -60,102 +77,184 @@ export class ChannelResolver {
async read(key: string, digest?: string): Promise<string> {
const url = `${this.base}/${channelKey(key)}`
+
const response = await this.fetcher(url, {
- redirect: 'error', signal: AbortSignal.timeout(30_000), cache: 'no-store',
+ redirect: 'error',
+ signal: AbortSignal.timeout(30_000),
+ cache: 'no-store',
headers: { 'Cache-Control': 'no-cache' }
})
- if (!response.ok || response.url !== url) { throw new Error(`Channel read unavailable: HTTP ${response.status}`) }
+
+ if (!response.ok || response.url !== url) {
+ throw new Error(`Channel read unavailable: HTTP ${response.status}`)
+ }
const maximum = 4 * 1024 * 1024
const reader = response.body?.getReader()
- if (!reader) { throw new Error('Channel metadata has no body') }
+
+ if (!reader) {
+ throw new Error('Channel metadata has no body')
+ }
const chunks: Uint8Array[] = []
let size = 0
+
try {
while (true) {
const { done, value } = await reader.read()
- if (done) { break }
+
+ if (done) {
+ break
+ }
size += value.byteLength
- if (size > maximum) { throw new Error('Channel metadata exceeds size limit') }
+
+ if (size > maximum) {
+ throw new Error('Channel metadata exceeds size limit')
+ }
chunks.push(value)
}
} finally {
await reader.cancel()
}
+
const body = Buffer.concat(chunks)
- if (digest && createHash('sha256').update(body).digest('hex') !== digest) { throw new Error('Channel metadata SHA256 mismatch') }
+
+ if (digest && createHash('sha256').update(body).digest('hex') !== digest) {
+ throw new Error('Channel metadata SHA256 mismatch')
+ }
+
return new TextDecoder('utf-8', { fatal: true }).decode(body)
}
async resolve(): Promise<ChannelResolution> {
let record = decodeChannelRecord(await this.read(`releases/channels/${this.deps.build.channel}.json`))
this.assertRecord(record, this.deps.build.channel)
- if (!sameChannelIdentity(record.identity, this.deps.build.identity)) { throw new Error('Installed channel identity changed') }
+
+ if (!sameChannelIdentity(record.identity, this.deps.build.identity)) {
+ throw new Error('Installed channel identity changed')
+ }
+
if (record.state === 'active') {
return record.head ? { kind: 'active', target: await this.target(record) } : { kind: 'empty', channel: record }
}
+
const retired: RetiredChannel = record
- if (retired.destination === retired.name) { throw new Error('Channel retirement cycle') }
+
+ if (retired.destination === retired.name) {
+ throw new Error('Channel retirement cycle')
+ }
record = decodeChannelRecord(await this.read(`releases/channels/${retired.destination}.json`))
this.assertRecord(record, retired.destination)
+
if (record.state !== 'active' || record.policy !== 'stable-release') {
throw new Error('Retirement requires a directly active stable-release destination')
}
+
if (!record.head || retired.destinationHead.sequence > record.head.sequence) {
throw new Error('Retirement destination exceeds published head')
}
+
// Stable may advance while preview is offline; preserve its first receiver.
const target: ChannelTarget = await this.target({ ...record, head: retired.destinationHead })
- if (target.manifest.receiverProtocol !== retired.receiverProtocol) { throw new Error('Stable build has no supported retirement receiver') }
+
+ if (target.manifest.receiverProtocol !== retired.receiverProtocol) {
+ throw new Error('Stable build has no supported retirement receiver')
+ }
assertVersionFloor(target.manifest.request.sourceVersion, retired.minimumVersion)
+
return { kind: 'retirement', retirement: { source: this.deps.build, target, receiverKind: retired.receiver.kind } }
}
private assertRecord(record: ActiveChannel | RetiredChannel, name: string): void {
- if (record.name !== name) { throw new Error('Channel name does not match object key') }
- if (record.repository.toLowerCase() !== this.deps.build.repository.toLowerCase()) { throw new Error('Channel repository authority mismatch') }
+ if (record.name !== name) {
+ throw new Error('Channel name does not match object key')
+ }
+
+ if (record.repository.toLowerCase() !== this.deps.build.repository.toLowerCase()) {
+ throw new Error('Channel repository authority mismatch')
+ }
}
private async target(channel: ActiveChannel): Promise<ChannelTarget> {
- if (!channel.head) { throw new Error('No destination build published') }
+ if (!channel.head) {
+ throw new Error('No destination build published')
+ }
const manifest = decodeChannelManifest(await this.read(channel.head.manifestKey, channel.head.sha256))
const request = manifest.request
- if (request.buildId !== channel.head.buildId || request.sequence !== channel.head.sequence || request.channel !== channel.name ||
- request.repository.toLowerCase() !== channel.repository.toLowerCase() || request.publicBase !== this.base ||
- !sameChannelIdentity(request.identity, channel.identity)) { throw new Error('Channel manifest request binding mismatch') }
- if (channel.policy === 'preview' && (request.version !== `0.0.${request.sequence}` ||
- request.windowsVersion !== `0.${Math.floor(request.sequence / 65536)}.${request.sequence % 65536}.0`)) {
+
+ if (
+ request.buildId !== channel.head.buildId ||
+ request.sequence !== channel.head.sequence ||
+ request.channel !== channel.name ||
+ request.repository.toLowerCase() !== channel.repository.toLowerCase() ||
+ request.publicBase !== this.base ||
+ !sameChannelIdentity(request.identity, channel.identity)
+ ) {
+ throw new Error('Channel manifest request binding mismatch')
+ }
+
+ if (
+ channel.policy === 'preview' &&
+ (request.version !== `0.0.${request.sequence}` ||
+ request.windowsVersion !== `0.${Math.floor(request.sequence / 65536)}.${request.sequence % 65536}.0`)
+ ) {
throw new Error('Channel package version does not match sequence')
}
+
this.assertPackages(channel, manifest)
- const entry = manifest.packages.find((item: ChannelPackage): boolean => item.platform === this.deps.platform && item.arch === this.deps.arch)
- if (!entry) { throw new Error('Channel has no package for this platform and architecture') }
+ const entry = manifest.packages.find(
+ (item: ChannelPackage): boolean => item.platform === this.deps.platform && item.arch === this.deps.arch
+ )
+
+ if (!entry) {
+ throw new Error('Channel has no package for this platform and architecture')
+ }
const signer = entry.platform === 'darwin' ? entry.teamId : entry.publisher
- if (!this.deps.signer || signer !== this.deps.signer) { throw new Error('Channel package signing identity mismatch') }
+
+ if (!this.deps.signer || signer !== this.deps.signer) {
+ throw new Error('Channel package signing identity mismatch')
+ }
+
return {
- channel, manifest, package: entry, manifestSha256: channel.head.sha256,
- artifactUrl: `${this.base}/${entry.artifact.key}`, feedUrl: `${this.base}/${entry.feed.key}`
+ channel,
+ manifest,
+ package: entry,
+ manifestSha256: channel.head.sha256,
+ artifactUrl: `${this.base}/${entry.artifact.key}`,
+ feedUrl: `${this.base}/${entry.feed.key}`
}
}
private assertPackages(channel: ActiveChannel, manifest: ChannelManifest): void {
const request = manifest.request
const prefixes = [buildPrefix(request.buildId)]
+
if (channel.policy !== 'preview') {
- if (!request.releaseTag || request.version !== request.releaseTag.slice(1)) { throw new Error('Protected release version mismatch') }
+ if (!request.releaseTag || request.version !== request.releaseTag.slice(1)) {
+ throw new Error('Protected release version mismatch')
+ }
prefixes.push(`releases/tag/${request.releaseTag}/`)
}
+
for (const entry of manifest.packages) {
const expectedIdentity = entry.platform === 'darwin' ? request.identity.appId : request.identity.msixAppIdWithOrg
const expectedVersion = entry.platform === 'darwin' ? request.version : request.windowsVersion
- if (entry.identity !== expectedIdentity || entry.version !== expectedVersion || entry.feed.channel !== 'stable' ||
- !prefixes.some((prefix: string): boolean => entry.artifact.key.startsWith(prefix)) ||
- !prefixes.some((prefix: string): boolean => entry.feed.key.startsWith(prefix))) {
+
+ if (
+ entry.identity !== expectedIdentity ||
+ entry.version !== expectedVersion ||
+ entry.feed.channel !== 'stable' ||
+ !prefixes.some((prefix: string): boolean => entry.artifact.key.startsWith(prefix)) ||
+ !prefixes.some((prefix: string): boolean => entry.feed.key.startsWith(prefix))
+ ) {
throw new Error('Channel package identity, version or immutable prefix mismatch')
}
+
if (entry.platform === 'darwin' && !entry.feed.key.endsWith(`/${entry.feed.channel}-mac.yml`)) {
throw new Error('Invalid native macOS feed descriptor')
}
- if (entry.platform === 'win32' && !entry.feed.key.endsWith('.appinstaller')) { throw new Error('Invalid native Windows feed descriptor') }
+
+ if (entry.platform === 'win32' && !entry.feed.key.endsWith('.appinstaller')) {
+ throw new Error('Invalid native Windows feed descriptor')
+ }
}
}
}
diff --git a/apps/desktop/electron/updater/checkout-legacy.test.ts b/apps/desktop/electron/updater/checkout-legacy.test.ts
index c485cb0ba82..2caa1e4479b 100644
--- a/apps/desktop/electron/updater/checkout-legacy.test.ts
+++ b/apps/desktop/electron/updater/checkout-legacy.test.ts
@@ -15,28 +15,43 @@ it('offers manual recovery only for a missing source probe, never for a broken p
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 probe: () => Promise<SourceUpdate | null> = (): Promise<SourceUpdate | null> =>
+ readSourceUpdate({
+ python: process.env.HERMES_PYTHON || 'python3',
+ git: 'git',
+ updateRoot: root,
+ hermesHome: home
+ })
const deps: CheckoutStrategyDeps = {
readSourceUpdate: probe,
- hermesHome: home, isWindows: process.platform === 'win32', isMac: process.platform === 'darwin',
- defaultUpdateBranch: 'main', updateHandoffDwellMs: 0,
- resolveUpdateRoot: (): string => root, resolveUpdaterBinary: vi.fn((): string => 'frozen-updater'),
- emitUpdateProgress: vi.fn(), rememberLog: vi.fn(),
+ hermesHome: home,
+ isWindows: process.platform === 'win32',
+ isMac: process.platform === 'darwin',
+ defaultUpdateBranch: 'main',
+ updateHandoffDwellMs: 0,
+ resolveUpdateRoot: (): string => root,
+ resolveUpdaterBinary: vi.fn((): string => 'frozen-updater'),
+ emitUpdateProgress: vi.fn(),
+ rememberLog: vi.fn(),
startHermes: vi.fn(async (): Promise<void> => {}),
stopBackendsForUpdate: vi.fn(async (): Promise<void> => {}),
- repairMacUpdaterHelper: vi.fn(), preflightStateDb: vi.fn(), runningAppBundle: (): null => null,
- markQuittingForHandoff: vi.fn(), quit: vi.fn()
+ 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) }
+ 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()
diff --git a/apps/desktop/electron/updater/checkout-ownership.test.ts b/apps/desktop/electron/updater/checkout-ownership.test.ts
index 97fe62c9b36..aedee23d871 100644
--- a/apps/desktop/electron/updater/checkout-ownership.test.ts
+++ b/apps/desktop/electron/updater/checkout-ownership.test.ts
@@ -6,9 +6,8 @@ import type { SourceUpdate } from './checkout-source'
it.each(['not-a-git-checkout', 'update-root-steward-owned-git-tree', 'fetch-failed'])(
'preserves the Python refusal or error before handoff: %s',
async (reason: string): Promise<void> => {
- const status: SourceUpdate = reason === 'fetch-failed'
- ? { supported: true, error: reason }
- : { supported: false, reason }
+ const status: SourceUpdate =
+ reason === 'fetch-failed' ? { supported: true, error: reason } : { supported: false, reason }
const deps: CheckoutStrategyDeps = {
readSourceUpdate: vi.fn(async (): Promise<SourceUpdate> => status),
diff --git a/apps/desktop/electron/updater/checkout-source.test.ts b/apps/desktop/electron/updater/checkout-source.test.ts
index cbfa733e89e..2b52c09a672 100644
--- a/apps/desktop/electron/updater/checkout-source.test.ts
+++ b/apps/desktop/electron/updater/checkout-source.test.ts
@@ -134,7 +134,12 @@ function channelRecord(channel: 'stable' | 'canary', sequence: number): FixtureR
}
/** Build manifest per hermes_cli.release_channels.validate_manifest. */
-function buildManifest(channel: 'stable' | 'canary', sha: string, tag: string, id: string = buildId(channel)): FixtureManifest {
+function buildManifest(
+ channel: 'stable' | 'canary',
+ sha: string,
+ tag: string,
+ id: string = buildId(channel)
+): FixtureManifest {
const identity: FixtureIdentity = {
token: 'b'.repeat(16),
displayName: channel === 'stable' ? 'Hermes Stable' : 'Hermes Canary',
@@ -145,7 +150,9 @@ function buildManifest(channel: 'stable' | 'canary', sha: string, tag: string, i
cliName: 'hermes',
windowsExecutableName: 'hermes'
}
+
const sequence: number = channel === 'stable' ? 1 : 2
+
return {
schema: 1,
request: {
@@ -171,7 +178,12 @@ function buildManifest(channel: 'stable' | 'canary', sha: string, tag: string, i
identity: 'chat.nous.hermes',
version: tag.replace(/^v/, ''),
teamId: 'TESTTEAM12',
- artifact: { key: `releases/channel-builds/${id}/darwin-arm64.zip`, sha256: 'd'.repeat(64), size: 1, format: 'zip' },
+ artifact: {
+ key: `releases/channel-builds/${id}/darwin-arm64.zip`,
+ sha256: 'd'.repeat(64),
+ size: 1,
+ format: 'zip'
+ },
feed: { channel: 'stable', key: `releases/channel-builds/${id}/darwin-arm64.xml` }
}
]
@@ -232,10 +244,18 @@ it('carries each install channel from Python publication checks into the source
git(['tag', '-a', tags[channel], sha, '-m', channel])
const manifest: FixtureManifest = buildManifest(channel, sha, tags[channel], buildId(channel))
const body: string = canonicalJson(manifest)
- responses.set(`/releases/channels/${channel}.json`, JSON.stringify({ ...channelRecord(channel, channel === 'stable' ? 1 : 2),
- head: { buildId: buildId(channel), sequence: channel === 'stable' ? 1 : 2,
- manifestKey: manifestKey(channel),
- sha256: crypto.createHash('sha256').update(body, 'utf8').digest('hex') } }))
+ responses.set(
+ `/releases/channels/${channel}.json`,
+ JSON.stringify({
+ ...channelRecord(channel, channel === 'stable' ? 1 : 2),
+ head: {
+ buildId: buildId(channel),
+ sequence: channel === 'stable' ? 1 : 2,
+ manifestKey: manifestKey(channel),
+ sha256: crypto.createHash('sha256').update(body, 'utf8').digest('hex')
+ }
+ })
+ )
responses.set(`/${manifestKey(channel)}`, body)
responses.set(`/repos/NousResearch/hermes-agent/releases/tags/${tags[channel]}`, {
tag_name: tags[channel],
@@ -247,11 +267,21 @@ it('carries each install channel from Python publication checks into the source
responses.set('/releases/stable/release-candidates.json', { tag: tags.stable, commit: commits[1] })
// The 'main' subscription is a source-branch channel record under the R2 protocol.
- responses.set('/releases/channels/main.json', JSON.stringify({
- schema: 1, name: 'main', repository: 'NousResearch/hermes-agent',
- policy: 'source-branch', state: 'active', revision: 1, nextSequence: 1,
- identity: null, head: null, delivery: { kind: 'source-branch', branch: 'main' }
- }))
+ responses.set(
+ '/releases/channels/main.json',
+ JSON.stringify({
+ schema: 1,
+ name: 'main',
+ repository: 'NousResearch/hermes-agent',
+ policy: 'source-branch',
+ state: 'active',
+ revision: 1,
+ nextSequence: 1,
+ identity: null,
+ head: null,
+ delivery: { kind: 'source-branch', branch: 'main' }
+ })
+ )
git(['tag', 'v99.0.0'])
git(['worktree', 'add', '-b', 'feature/gui', root])
git(['remote', 'add', 'origin', origin])
@@ -320,10 +350,15 @@ urllib.request.build_opener = local_build
}
const checkerPath: string = path.join(root, 'hermes_cli', 'source_check.py')
- fs.writeFileSync(checkerPath, fs.readFileSync(checkerPath, 'utf8').replace(
- 'from __future__ import annotations',
- `from __future__ import annotations\nimport runpy; runpy.run_path(${JSON.stringify(path.join(root, 'transport.py'))})`
- ))
+ fs.writeFileSync(
+ checkerPath,
+ fs
+ .readFileSync(checkerPath, 'utf8')
+ .replace(
+ 'from __future__ import annotations',
+ `from __future__ import annotations\nimport runpy; runpy.run_path(${JSON.stringify(path.join(root, 'transport.py'))})`
+ )
+ )
const deps: CheckoutStrategyDeps = {
hermesHome: home,
@@ -332,9 +367,14 @@ urllib.request.build_opener = local_build
defaultUpdateBranch: 'main',
updateHandoffDwellMs: 0,
resolveUpdateRoot: (): string => root,
- readSourceUpdate: (install: string, opts: { force?: boolean }): Promise<SourceUpdate | null> => readSourceUpdate({
- python, git: 'git', updateRoot: install, hermesHome: home, force: opts.force
- }),
+ readSourceUpdate: (install: string, opts: { force?: boolean }): Promise<SourceUpdate | null> =>
+ readSourceUpdate({
+ python,
+ git: 'git',
+ updateRoot: install,
+ hermesHome: home,
+ force: opts.force
+ }),
resolveUpdaterBinary: (): null => null,
emitUpdateProgress: vi.fn(),
@@ -412,7 +452,10 @@ urllib.request.build_opener = local_build
expect(spawned).toHaveLength(0)
await setChannel('main')
expect(await readSourceUpdate({ python, git: 'git', updateRoot: root, hermesHome: home })).toMatchObject({
- supported: true, branch: 'feature/gui', targetSha: commits[3], updateAvailable: false
+ supported: true,
+ branch: 'feature/gui',
+ targetSha: commits[3],
+ updateAvailable: false
})
const count: number = requests.length
expect(await strategy.check()).toMatchObject({
diff --git a/apps/desktop/electron/updater/checkout-source.ts b/apps/desktop/electron/updater/checkout-source.ts
index 68d140fc6df..9db5013e4c7 100644
--- a/apps/desktop/electron/updater/checkout-source.ts
+++ b/apps/desktop/electron/updater/checkout-source.ts
@@ -22,7 +22,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 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 = {
@@ -50,7 +51,12 @@ export async function readSourceUpdate(probe: SourceUpdateProbe): Promise<Source
// 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_check.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, '--home', probe.hermesHome, '--git', probe.git,
+ '--install-root',
+ probe.updateRoot,
+ '--home',
+ probe.hermesHome,
+ '--git',
+ probe.git,
...(probe.branch ? ['--branch', probe.branch] : []),
...(probe.channel ? ['--channel', probe.channel] : []),
...(probe.force ? ['--force'] : []),
@@ -77,7 +83,9 @@ export async function readSourceUpdate(probe: SourceUpdateProbe): Promise<Source
}
// The Python banner uses -1 for an available update with no exact count.
- if (selection.behind === -1) { selection.behind = null }
+ if (selection.behind === -1) {
+ selection.behind = null
+ }
return selection
}
diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.ts
index d56e779ef91..533ed1b01e8 100644
--- a/apps/desktop/electron/updater/checkout.ts
+++ b/apps/desktop/electron/updater/checkout.ts
@@ -69,8 +69,11 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
async function check(opts: { force?: boolean } = {}): Promise<UpdaterStatusWire> {
const root: string = deps.resolveUpdateRoot()
- const status: UpdaterStatusWire = await deps.readSourceUpdate(root, opts) ?? {
- supported: false, reason: 'source-probe-unavailable', message: SOURCE_PROBE_RECOVERY, hermesRoot: root
+ const status: UpdaterStatusWire = (await deps.readSourceUpdate(root, opts)) ?? {
+ supported: false,
+ reason: 'source-probe-unavailable',
+ message: SOURCE_PROBE_RECOVERY,
+ hermesRoot: root
}
status.mechanism = mechanism
@@ -91,7 +94,13 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
const status: UpdaterStatusWire = await check({ force: true })
if (status.reason === 'source-probe-unavailable') {
- return { ok: true, manual: true, command: 'hermes update --help', message: status.message, hermesRoot: status.hermesRoot }
+ return {
+ ok: true,
+ manual: true,
+ command: 'hermes update --help',
+ message: status.message,
+ hermesRoot: status.hermesRoot
+ }
}
if (!status.supported || status.error) {
@@ -101,7 +110,9 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
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 manualCommand: string = status.channel
+ ? `hermes update --channel ${status.channel}`
+ : buildManualUpdateCommand(branch)
const updater: string | null = deps.resolveUpdaterBinary()
const root: string = deps.resolveUpdateRoot()
@@ -110,11 +121,12 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
if (existsSync(path.join(root, 'pm')) && !existsSync(path.join(root, 'scripts', 'desktop-update', 'runtime.ps1'))) {
const launcher: string | null = resolveInstallationLauncher(root, deps.isWindows, deps.hermesHome)
- if (!launcher) { return { ok: false, error: 'installation-launcher-missing' } }
+ if (!launcher) {
+ return { ok: false, error: 'installation-launcher-missing' }
+ }
- const quote = (value: string): string => deps.isWindows
- ? `'${value.replace(/'/g, "''")}'`
- : `'${value.replace(/'/g, "'\\''")}'`
+ const quote = (value: string): string =>
+ deps.isWindows ? `'${value.replace(/'/g, "''")}'` : `'${value.replace(/'/g, "'\\''")}'`
const command: string = `${deps.isWindows ? '& ' : ''}${quote(launcher)} update ${targetArgs.map(quote).join(' ')}`
@@ -147,7 +159,9 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
if (!resolveUpdateScriptHandoff(updateRoot)) {
const command: string = manualCommand
- deps.rememberLog(`[updates] no staged updater; surfacing manual \`${command}\` for CLI install at ${updateRoot}`)
+ deps.rememberLog(
+ `[updates] no staged updater; surfacing manual \`${command}\` for CLI install at ${updateRoot}`
+ )
deps.emitUpdateProgress({ stage: 'manual', message: command, percent: null })
return { ok: true, manual: true, command, hermesRoot: updateRoot }
@@ -185,7 +199,6 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
updaterArgs.push('--target-app', targetApp)
}
-
// ── Pre-flight state.db integrity guard (#68474) ─────────────────
// Emergency backup and header verification before the update touches
// anything. Runs while the backend is still alive.
@@ -323,7 +336,6 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
deps.emitUpdateProgress({ stage: 'error', message, percent: null })
deps.startHermes().catch(() => {})
-
return { ok: false, error: 'updater-spawn-failed', message }
}
@@ -338,109 +350,120 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
return { ok: true, handedOff: true, updater }
}
- async function applyPosixHandoff(targetArgs: string[], targetLabel: string, manualCommand: string): Promise<UpdaterApplyResultWire> {
- const updateRoot = deps.resolveUpdateRoot()
- const handoff = resolvePosixScriptHandoff(updateRoot)
+ 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: manualCommand, percent: null })
+ if (!handoff) {
+ deps.emitUpdateProgress({ stage: 'manual', message: manualCommand, percent: null })
- return { ok: true, manual: true, command: manualCommand, hermesRoot: updateRoot }
- }
+ return { ok: true, manual: true, command: manualCommand, hermesRoot: updateRoot }
+ }
- const handoffConflict = updateHandoffConflict(deps.hermesHome)
+ const handoffConflict = updateHandoffConflict(deps.hermesHome)
- if (handoffConflict) {
- // Same hazard as the Windows path (#75778): a live foreign updater
- // already owns the marker — refuse rather than double-mutate the tree.
- deps.rememberLog(`[updates] refusing posix hand-off: ${handoffConflict.message}`)
- deps.emitUpdateProgress({ stage: 'error', message: handoffConflict.message, percent: null })
+ if (handoffConflict) {
+ // Same hazard as the Windows path (#75778): a live foreign updater
+ // already owns the marker — refuse rather than double-mutate the tree.
+ deps.rememberLog(`[updates] refusing posix hand-off: ${handoffConflict.message}`)
+ deps.emitUpdateProgress({ stage: 'error', message: handoffConflict.message, percent: null })
- return { ok: false, error: 'update-already-running', message: handoffConflict.message }
- }
+ return { ok: false, error: 'update-already-running', message: handoffConflict.message }
+ }
- // ── Pre-flight state.db integrity guard (#68474) ──
- await deps.preflightStateDb(deps.hermesHome, deps.rememberLog)
+ // ── Pre-flight state.db integrity guard (#68474) ──
+ await deps.preflightStateDb(deps.hermesHome, deps.rememberLog)
- const args: string[] = [...handoff.args, '--install-root', updateRoot, ...targetArgs, '--desktop-pid', String(process.pid)]
- const updateStartedAt = Math.floor(Date.now() / 1000)
+ 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
+ // rebuilt bundle over it), the running binary elsewhere. The script's gate
+ // (an exact port of update-relaunch.ts's decideRelaunchOutcome) relaunches
+ // only a binary the rebuild replaced with a launchable sandbox helper —
+ // replaying the original launch context (filtered args, cwd, sandbox
+ // opt-out) so a deep-link or --no-sandbox launch survives the update.
+ const targetApp = deps.isMac ? deps.runningAppBundle() : process.execPath
- // Relaunch target: the running .app bundle on mac (script swaps the
- // rebuilt bundle over it), the running binary elsewhere. The script's gate
- // (an exact port of update-relaunch.ts's decideRelaunchOutcome) relaunches
- // only a binary the rebuild replaced with a launchable sandbox helper —
- // replaying the original launch context (filtered args, cwd, sandbox
- // opt-out) so a deep-link or --no-sandbox launch survives the update.
- const targetApp = deps.isMac ? deps.runningAppBundle() : process.execPath
+ if (targetApp) {
+ args.push('--relaunch-target', targetApp)
+ }
- if (targetApp) {
- args.push('--relaunch-target', targetApp)
- }
+ const relaunchArgs = collectRelaunchArgs(process.argv.slice(1))
- const relaunchArgs = collectRelaunchArgs(process.argv.slice(1))
+ if (!deps.isMac) {
+ args.push('--relaunch-cwd', process.cwd())
- if (!deps.isMac) {
- args.push('--relaunch-cwd', process.cwd())
+ if (sandboxFallbackFromEnv(process.env, relaunchArgs)) {
+ args.push('--sandbox-fallback')
+ }
- if (sandboxFallbackFromEnv(process.env, relaunchArgs)) {
- args.push('--sandbox-fallback')
+ if (relaunchArgs.length) {
+ args.push('--', ...relaunchArgs)
+ }
}
- if (relaunchArgs.length) {
- args.push('--', ...relaunchArgs)
+ const child = spawnUpdaterProcess(handoff.command, args, {
+ cwd: deps.hermesHome,
+ env: {
+ ...sourceUpdateEnvironment(updateRoot, deps.hermesHome),
+ HERMES_UPDATE_STARTED_AT: String(updateStartedAt)
+ },
+ detached: true,
+ stdio: 'ignore'
+ })
+
+ // Bridge marker (same contract as the Windows hand-off): cover the gap
+ // until the script claims the marker with its own pid as step 0. If the
+ // script never starts, the dead pid reads as stale and self-deletes.
+ if (Number.isInteger(child.pid)) {
+ writeUpdateMarker(deps.hermesHome, child.pid, { startedAt: updateStartedAt })
}
- }
- const child = spawnUpdaterProcess(handoff.command, args, {
- cwd: deps.hermesHome,
- env: {
- ...sourceUpdateEnvironment(updateRoot, deps.hermesHome),
- HERMES_UPDATE_STARTED_AT: String(updateStartedAt)
- },
- detached: true,
- stdio: 'ignore'
- })
-
- // Bridge marker (same contract as the Windows hand-off): cover the gap
- // until the script claims the marker with its own pid as step 0. If the
- // script never starts, the dead pid reads as stale and self-deletes.
- if (Number.isInteger(child.pid)) {
- writeUpdateMarker(deps.hermesHome, child.pid, { startedAt: updateStartedAt })
- }
+ deps.rememberLog(`[updates] launched posix hand-off: ${handoff.scriptPath} (${targetLabel}); quitting to hand off`)
+ deps.emitUpdateProgress({
+ stage: 'restart',
+ message:
+ 'Updating Hermes — this window will close. Don’t reopen Hermes yourself; it restarts automatically when the update finishes.',
+ percent: 100
+ })
- deps.rememberLog(`[updates] launched posix hand-off: ${handoff.scriptPath} (${targetLabel}); quitting to hand off`)
- deps.emitUpdateProgress({
- stage: 'restart',
- message:
- 'Updating Hermes — this window will close. Don’t reopen Hermes yourself; it restarts automatically when the update finishes.',
- percent: 100
- })
-
- // Settle window (#66753): the reported macOS failure mode is exactly this
- // path — the app quits, bash/posix.sh dies early (or was never spawnable),
- // and the user is left with no app, no updater, and no relaunch. Watch the
- // child through the dwell; on spawn error or early death, stay alive and
- // surface the failure instead of quitting into nothing.
- const dwellStartedAt = Date.now()
- const handoffOutcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)
-
- if (!handoffOutcome.ok) {
- const message = `Update failed to start: ${handoffOutcome.message}. Hermes will keep running — try again, or run \`hermes update\` from a terminal.`
-
- deps.rememberLog(`[updates] posix hand-off not viable, aborting quit: ${handoffOutcome.message}`)
- deps.emitUpdateProgress({ stage: 'error', message, percent: null })
-
- return { ok: false, error: 'updater-spawn-failed', message }
- }
+ // Settle window (#66753): the reported macOS failure mode is exactly this
+ // path — the app quits, bash/posix.sh dies early (or was never spawnable),
+ // and the user is left with no app, no updater, and no relaunch. Watch the
+ // child through the dwell; on spawn error or early death, stay alive and
+ // surface the failure instead of quitting into nothing.
+ const dwellStartedAt = Date.now()
+ const handoffOutcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)
+
+ if (!handoffOutcome.ok) {
+ const message = `Update failed to start: ${handoffOutcome.message}. Hermes will keep running — try again, or run \`hermes update\` from a terminal.`
- deps.markQuittingForHandoff()
- setTimeout(
- () => {
- deps.quit()
- },
- Math.max(0, deps.updateHandoffDwellMs - (Date.now() - dwellStartedAt))
- )
+ deps.rememberLog(`[updates] posix hand-off not viable, aborting quit: ${handoffOutcome.message}`)
+ deps.emitUpdateProgress({ stage: 'error', message, percent: null })
+
+ return { ok: false, error: 'updater-spawn-failed', message }
+ }
+
+ deps.markQuittingForHandoff()
+ setTimeout(
+ () => {
+ deps.quit()
+ },
+ Math.max(0, deps.updateHandoffDwellMs - (Date.now() - dwellStartedAt))
+ )
- return { ok: true, handedOff: true, updater: handoff.scriptPath }
+ return { ok: true, handedOff: true, updater: handoff.scriptPath }
}
}
diff --git a/apps/desktop/electron/updater/commit-build.test.ts b/apps/desktop/electron/updater/commit-build.test.ts
index b269a992a9a..203a17f2497 100644
--- a/apps/desktop/electron/updater/commit-build.test.ts
+++ b/apps/desktop/electron/updater/commit-build.test.ts
@@ -9,20 +9,35 @@ import { resolveUpdaterMechanism, type UpdaterStrategy } from './index'
const message: string = "This build doesn't get updates. Ask the developer who gave it to you for a new build."
describe('one-commit artifacts', (): void => {
- it.each(['win32', 'darwin', 'linux'] as const)('cannot select an active updater on %s', (platform: NodeJS.Platform): void => {
- for (const updateMechanism of ['self', 'app-installer', 'electron-updater', 'microsoft-store', 'external'] as const) {
- expect(resolveUpdaterMechanism({ platform, updateMechanism, source: 'commit-build' })).toBe('external')
+ it.each(['win32', 'darwin', 'linux'] as const)(
+ 'cannot select an active updater on %s',
+ (platform: NodeJS.Platform): void => {
+ for (const updateMechanism of [
+ 'self',
+ 'app-installer',
+ 'electron-updater',
+ 'microsoft-store',
+ 'external'
+ ] as const) {
+ expect(resolveUpdaterMechanism({ platform, updateMechanism, source: 'commit-build' })).toBe('external')
+ }
}
- })
+ )
it('refuses both checks and apply with no manual-update escape', async (): Promise<void> => {
const stamp: InstallStamp = { source: 'commit-build' } as InstallStamp
const strategy: UpdaterStrategy = new ExternalStrategy(stamp)
expect(await strategy.check({ force: true })).toMatchObject({
- supported: false, mechanism: 'external', reason: 'commit-build', message
+ supported: false,
+ mechanism: 'external',
+ reason: 'commit-build',
+ message
})
expect(await strategy.apply()).toMatchObject({
- ok: false, mechanism: 'external', error: 'commit-build', message
+ ok: false,
+ mechanism: 'external',
+ error: 'commit-build',
+ message
})
expect(await strategy.apply()).not.toHaveProperty('command')
})
diff --git a/apps/desktop/electron/updater/external.ts b/apps/desktop/electron/updater/external.ts
index 04d4842cb77..4d68b08ce2a 100644
--- a/apps/desktop/electron/updater/external.ts
+++ b/apps/desktop/electron/updater/external.ts
@@ -7,8 +7,7 @@ import type { InstallStamp } from '../install-stamp'
import type { UpdaterApplyResultWire, UpdaterStatusWire } from './index'
-export const EXTERNAL_UNSUPPORTED_MESSAGE =
- 'Updates are managed by the package owner outside this app.'
+export const EXTERNAL_UNSUPPORTED_MESSAGE = 'Updates are managed by the package owner outside this app.'
export const COMMIT_BUILD_UPDATE_MESSAGE: string =
"This build doesn't get updates. Ask the developer who gave it to you for a new build."
diff --git a/apps/desktop/electron/updater/feed-config.test.ts b/apps/desktop/electron/updater/feed-config.test.ts
index ea71227af9d..0fa4939e044 100644
--- a/apps/desktop/electron/updater/feed-config.test.ts
+++ b/apps/desktop/electron/updater/feed-config.test.ts
@@ -34,7 +34,11 @@ it('leaves fallback selection available for missing, invalid or non-string confi
const config: string = join(home, 'config.yaml')
const documents: string[] = [
- '', 'updates: [', 'null', 'updates: null', 'updates: []',
+ '',
+ 'updates: [',
+ 'null',
+ 'updates: null',
+ 'updates: []',
'other: {desktop_feed_base_url: https://other.example}',
'updates: {desktop_feed_base_url: false}',
'updates: {desktop_feed_base_url: 123}',
diff --git a/apps/desktop/electron/updater/feed-config.ts b/apps/desktop/electron/updater/feed-config.ts
index 6b10e423da4..9f5ea2e0c12 100644
--- a/apps/desktop/electron/updater/feed-config.ts
+++ b/apps/desktop/electron/updater/feed-config.ts
@@ -7,11 +7,15 @@ export function readUpdatesFeedBaseFromConfig(configPath: string): string {
// YAML permits scalar and sequence roots; validate the nested string at this I/O boundary.
const config: unknown = load(readFileSync(configPath, 'utf8'))
- if (!config || typeof config !== 'object' || !('updates' in config)) {return ''}
+ if (!config || typeof config !== 'object' || !('updates' in config)) {
+ return ''
+ }
const updates: unknown = config.updates
- if (!updates || typeof updates !== 'object' || !('desktop_feed_base_url' in updates)) {return ''}
+ if (!updates || typeof updates !== 'object' || !('desktop_feed_base_url' in updates)) {
+ return ''
+ }
const value: unknown = updates.desktop_feed_base_url
diff --git a/apps/desktop/electron/updater/index.ts b/apps/desktop/electron/updater/index.ts
index 4f7f8e79cb3..291f9525aa3 100644
--- a/apps/desktop/electron/updater/index.ts
+++ b/apps/desktop/electron/updater/index.ts
@@ -20,13 +20,7 @@ import type { InstallStamp } from '../install-stamp'
import type { ChannelRetirementStatus } from './channel-strategy'
export type UpdaterMechanism =
- | 'app-installer'
- | 'electron-updater'
- | 'external'
- | 'microsoft-store'
- | 'windows-handoff'
- | 'posix-handoff'
- | 'manual'
+ 'app-installer' | 'electron-updater' | 'external' | 'microsoft-store' | 'windows-handoff' | 'posix-handoff' | 'manual'
/** The facts the mechanism dispatch keys on. Pure data — injectable for tests. */
export interface MechanismFacts {
@@ -40,7 +34,9 @@ export interface MechanismFacts {
* packaged app into a checkout, and Light needs no payload to update itself.
*/
export function resolveUpdaterMechanism(facts: MechanismFacts): UpdaterMechanism {
- if (facts.source === 'commit-build') { return 'external' }
+ if (facts.source === 'commit-build') {
+ return 'external'
+ }
if (facts.updateMechanism && facts.updateMechanism !== 'self') {
return facts.updateMechanism
diff --git a/apps/desktop/electron/updater/mac-client.test.ts b/apps/desktop/electron/updater/mac-client.test.ts
index 7d4cf9dc223..a7716af49d7 100644
--- a/apps/desktop/electron/updater/mac-client.test.ts
+++ b/apps/desktop/electron/updater/mac-client.test.ts
@@ -2,21 +2,44 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
const { client } = vi.hoisted(() => ({
client: {
- autoDownload: true, autoInstallOnAppQuit: true, autoRunAppAfterInstall: false,
- channel: '', allowPrerelease: true, allowDowngrade: true,
- on: vi.fn(), setFeedURL: vi.fn(), checkForUpdates: vi.fn(async () => null)
+ autoDownload: true,
+ autoInstallOnAppQuit: true,
+ autoRunAppAfterInstall: false,
+ channel: '',
+ allowPrerelease: true,
+ allowDowngrade: true,
+ on: vi.fn(),
+ setFeedURL: vi.fn(),
+ checkForUpdates: vi.fn(async () => null)
}
}))
vi.mock('electron', () => ({ autoUpdater: {} }))
-vi.mock('electron-updater', () => ({ default: { MacUpdater: class { constructor() { return client } } } }))
+vi.mock('electron-updater', () => ({
+ default: {
+ MacUpdater: class {
+ constructor() {
+ return client
+ }
+ }
+ }
+}))
import { createMacStrategy } from './mac-client'
afterEach(() => vi.clearAllMocks())
function deps(feedBaseUrl = '', light = false, channel: 'stable' | 'canary' = 'stable') {
- return { channel, light, feedBaseUrl, appVersion: '0.28.0', log: vi.fn(), emitProgress: vi.fn(), beforeInstall: vi.fn(), onInstallFailure: vi.fn() }
+ return {
+ channel,
+ light,
+ feedBaseUrl,
+ appVersion: '0.28.0',
+ log: vi.fn(),
+ emitProgress: vi.fn(),
+ beforeInstall: vi.fn(),
+ onInstallFailure: vi.fn()
+ }
}
describe('macOS client wiring', () => {
@@ -33,18 +56,33 @@ describe('macOS client wiring', () => {
})
it('pins a neutral immutable descriptor instead of interpolating the dynamic name', (): void => {
- createMacStrategy({ ...deps('https://updates.example'), channel: 'unknown-preview',
+ createMacStrategy({
+ ...deps('https://updates.example'),
+ channel: 'unknown-preview',
feed: { url: 'https://updates.example/releases/channel-builds/abc/darwin/latest-mac.yml', channel: 'latest' }
})
- expect(client.setFeedURL).toHaveBeenCalledWith({ provider: 'generic', url: 'https://updates.example/releases/channel-builds/abc/darwin/', channel: 'latest' })
+ expect(client.setFeedURL).toHaveBeenCalledWith({
+ provider: 'generic',
+ url: 'https://updates.example/releases/channel-builds/abc/darwin/',
+ channel: 'latest'
+ })
expect(client.allowDowngrade).toBe(false)
expect(client.autoDownload).toBe(false)
- expect((): void => { createMacStrategy({ ...deps('https://updates.example'), feed: { url: 'https://other.example/latest-mac.yml', channel: 'latest' } }) }).toThrow('authority')
+ expect((): void => {
+ createMacStrategy({
+ ...deps('https://updates.example'),
+ feed: { url: 'https://other.example/latest-mac.yml', channel: 'latest' }
+ })
+ }).toThrow('authority')
})
it('overrides the provider with the same variant/channel path as the publisher', () => {
createMacStrategy(deps('https://updates.example/', true, 'canary'))
- expect(client.setFeedURL).toHaveBeenCalledWith({ provider: 'generic', url: 'https://updates.example/releases/darwin/light/canary/', channel: 'canary' })
+ expect(client.setFeedURL).toHaveBeenCalledWith({
+ provider: 'generic',
+ url: 'https://updates.example/releases/darwin/light/canary/',
+ channel: 'canary'
+ })
expect(client.allowPrerelease).toBe(true)
expect(() => createMacStrategy(deps('http://untrusted.example'))).toThrow('HTTPS')
})
diff --git a/apps/desktop/electron/updater/mac-client.ts b/apps/desktop/electron/updater/mac-client.ts
index 7f1296914d9..3358db125d5 100644
--- a/apps/desktop/electron/updater/mac-client.ts
+++ b/apps/desktop/electron/updater/mac-client.ts
@@ -17,10 +17,14 @@ export interface MacClientDeps extends Omit<MacStrategyDeps, 'updater' | 'prepar
}
export function createChannelMacStrategy(deps: MacClientDeps, target: ChannelTarget): MacStrategy {
- if (target.package.platform !== 'darwin') { throw new Error('Expected macOS channel target') }
+ if (target.package.platform !== 'darwin') {
+ throw new Error('Expected macOS channel target')
+ }
return createMacStrategy({
- ...deps, channel: target.channel.name, feedBaseUrl: target.manifest.request.publicBase,
+ ...deps,
+ channel: target.channel.name,
+ feedBaseUrl: target.manifest.request.publicBase,
feed: { url: target.feedUrl, channel: target.package.feed.channel },
expectedVersion: target.package.version,
verifyDownload: (files: string[]): Promise<void> => verifyChannelDownload(files, target.package.artifact)
@@ -44,9 +48,13 @@ export function createMacStrategy(deps: MacClientDeps): MacStrategy {
const base = channelPublicBase(deps.feedBaseUrl)
const url = new URL(channelPublicBase(deps.feed.url))
- if (!deps.feed.url.startsWith(`${base}/`) || url.origin !== new URL(base).origin) { throw new Error('Native feed authority mismatch') }
+ if (!deps.feed.url.startsWith(`${base}/`) || url.origin !== new URL(base).origin) {
+ throw new Error('Native feed authority mismatch')
+ }
- if (!/^[a-z][a-z0-9-]*$/.test(channel) || !url.pathname.endsWith(`/${channel}-mac.yml`)) { throw new Error('Invalid macOS feed descriptor') }
+ if (!/^[a-z][a-z0-9-]*$/.test(channel) || !url.pathname.endsWith(`/${channel}-mac.yml`)) {
+ throw new Error('Invalid macOS feed descriptor')
+ }
updater.setFeedURL({ provider: 'generic', url: new URL('./', url).href, channel })
} else if (deps.feedBaseUrl) {
const base = channelPublicBase(deps.feedBaseUrl)
diff --git a/apps/desktop/electron/updater/mac.test.ts b/apps/desktop/electron/updater/mac.test.ts
index 6b55cb9f014..cb90807ed37 100644
--- a/apps/desktop/electron/updater/mac.test.ts
+++ b/apps/desktop/electron/updater/mac.test.ts
@@ -86,7 +86,10 @@ describe('macOS strategy', () => {
await expect(new MacStrategy(deps).apply()).rejects.toThrow('pinned channel version')
expect(events).toEqual(['check'])
deps.expectedVersion = '0.29.0'
- deps.verifyDownload = async (): Promise<void> => { throw new Error('artifact digest mismatch') }
+
+ deps.verifyDownload = async (): Promise<void> => {
+ throw new Error('artifact digest mismatch')
+ }
await expect(new MacStrategy(deps).apply()).rejects.toThrow('artifact digest')
expect(events).not.toContain('verify')
expect(events).not.toContain('stop')
diff --git a/apps/desktop/electron/updater/operation.test.ts b/apps/desktop/electron/updater/operation.test.ts
index b73d74d9073..0c0243d7e28 100644
--- a/apps/desktop/electron/updater/operation.test.ts
+++ b/apps/desktop/electron/updater/operation.test.ts
@@ -77,6 +77,9 @@ test('apply ownership precedes async resolution, survives restoration, and retai
await expect(first).rejects.toThrow('install failed')
expect(applications).toBe(1)
await expect(operation.apply(async () => ({ ok: false }))).resolves.toEqual({ ok: false })
- await expect(operation.apply(async () => ({ ok: true, handedOff: true }))).resolves.toEqual({ ok: true, handedOff: true })
+ await expect(operation.apply(async () => ({ ok: true, handedOff: true }))).resolves.toEqual({
+ ok: true,
+ handedOff: true
+ })
await expect(operation.apply(async () => ({ ok: true }))).rejects.toThrow('already in progress')
})
diff --git a/apps/desktop/electron/updater/operation.ts b/apps/desktop/electron/updater/operation.ts
index def83bbea05..4a3f705601e 100644
--- a/apps/desktop/electron/updater/operation.ts
+++ b/apps/desktop/electron/updater/operation.ts
@@ -17,7 +17,9 @@ export class UpdateOperation {
}
async apply(run: () => Promise<UpdaterApplyResultWire>): Promise<UpdaterApplyResultWire> {
- if (this.applying) { throw new Error('An update is already in progress.') }
+ if (this.applying) {
+ throw new Error('An update is already in progress.')
+ }
this.applying = true
let handedOff: boolean = false
@@ -27,7 +29,9 @@ export class UpdateOperation {
return result
} finally {
- if (!handedOff) { this.applying = false }
+ if (!handedOff) {
+ this.applying = false
+ }
}
}
}
diff --git a/apps/desktop/electron/updater/relaunch-isolation.test.ts b/apps/desktop/electron/updater/relaunch-isolation.test.ts
index faf4765d23c..825c167ee8c 100644
--- a/apps/desktop/electron/updater/relaunch-isolation.test.ts
+++ b/apps/desktop/electron/updater/relaunch-isolation.test.ts
@@ -102,7 +102,11 @@ test('cancellation and failed registration remove only their own installation ma
for (const automatic of [true, false]) {
let resolveReady!: (handle: RelaunchWaiterHandle | undefined) => void
- const ready: Promise<RelaunchWaiterHandle | undefined> = new Promise((resolve: (handle: RelaunchWaiterHandle | undefined) => void): void => { resolveReady = resolve })
+ const ready: Promise<RelaunchWaiterHandle | undefined> = new Promise(
+ (resolve: (handle: RelaunchWaiterHandle | undefined) => void): void => {
+ resolveReady = resolve
+ }
+ )
let registered: boolean = false
const pending: Promise<RelaunchRegistration> = registerUpdateRelaunch(canary, 'canary-old', {
@@ -116,7 +120,15 @@ test('cancellation and failed registration remove only their own installation ma
await new Promise(setImmediate)
assert.equal(registered, false)
assert.equal(fs.existsSync(marker(canary)), true)
- resolveReady(automatic ? { cancel: async (): Promise<void> => { cancelled++ } } : undefined)
+ resolveReady(
+ automatic
+ ? {
+ cancel: async (): Promise<void> => {
+ cancelled++
+ }
+ }
+ : undefined
+ )
const registration: RelaunchRegistration = await pending
assert.equal(registration.automatic, automatic)
await Promise.all([registration.cancel(), registration.cancel()])
@@ -166,7 +178,11 @@ test('cancellation and failed registration remove only their own installation ma
await sibling.cancel()
const blocked: RelaunchRegistration = await registerUpdateRelaunch(canary, 'old', {
- relaunch: (): RelaunchWaiterHandle => ({ cancel: async (): Promise<never> => { throw failure } })
+ relaunch: (): RelaunchWaiterHandle => ({
+ cancel: async (): Promise<never> => {
+ throw failure
+ }
+ })
})
fs.unlinkSync(marker(canary))
diff --git a/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts b/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts
index 9bca5a65dd4..55f20f8a539 100644
--- a/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts
+++ b/apps/desktop/electron/updater/relaunch-waiter-lifecycle.test.ts
@@ -37,40 +37,80 @@ for (const mode of [
const start: SpawnWaiter = (command: string, args: string[], options: Parameters<SpawnWaiter>[2]): ChildProcess => {
stage = options.cwd
const readyFile: string = path.join(stage, 'ready.txt')
- assert.equal(command, path.win32.join(process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'))
+ assert.equal(
+ command,
+ path.win32.join(
+ process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows',
+ 'System32',
+ 'WindowsPowerShell',
+ 'v1.0',
+ 'powershell.exe'
+ )
+ )
assert.deepEqual(options, { cwd: stage, detached: true, stdio: 'ignore', windowsHide: true })
assert.notEqual(stage, path.dirname(scriptPath))
assert.deepEqual(fs.readFileSync(path.join(stage, 'update-relaunch-waiter.ps1')), fs.readFileSync(scriptPath))
assert.deepEqual(args, [
- '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
- '-File', path.join(stage, 'update-relaunch-waiter.ps1'),
- '-ProcessId', String(process.pid), '-ProcessStartTimeMs', '1000000',
- '-IdentityName', 'disposable-waiter-test', '-ReadyFile', readyFile, '-TimeoutSeconds', '900'
+ '-NoProfile',
+ '-NonInteractive',
+ '-ExecutionPolicy',
+ 'Bypass',
+ '-File',
+ path.join(stage, 'update-relaunch-waiter.ps1'),
+ '-ProcessId',
+ String(process.pid),
+ '-ProcessStartTimeMs',
+ '1000000',
+ '-IdentityName',
+ 'disposable-waiter-test',
+ '-ReadyFile',
+ readyFile,
+ '-TimeoutSeconds',
+ '900'
])
- child = spawn(mode.missing ? path.join(stage, 'missing.exe') : process.execPath, ['-e', `
+ child = spawn(
+ mode.missing ? path.join(stage, 'missing.exe') : process.execPath,
+ [
+ '-e',
+ `
const fs = require('node:fs');
if (process.env.TEST_EXIT === 'yes') process.exit(3);
if (process.env.TEST_READY === 'yes') fs.writeFileSync(process.env.READY_FILE, 'ready');
setInterval(() => {}, 1000);
- `], {
- ...options,
- env: { ...process.env, READY_FILE: readyFile, TEST_READY: mode.ready ? 'yes' : 'no', TEST_EXIT: mode.earlyExit ? 'yes' : 'no' }
- })
+ `
+ ],
+ {
+ ...options,
+ env: {
+ ...process.env,
+ READY_FILE: readyFile,
+ TEST_READY: mode.ready ? 'yes' : 'no',
+ TEST_EXIT: mode.earlyExit ? 'yes' : 'no'
+ }
+ }
+ )
originalKill = child.kill.bind(child)
- if (mode.refuseKill) { child.kill = () => false }
- child.once('close', () => { closed = true })
+ if (mode.refuseKill) {
+ child.kill = () => false
+ }
+ child.once('close', () => {
+ closed = true
+ })
return child
}
try {
- const starting: Promise<RelaunchWaiterHandle | undefined> = startRelaunchWaiter({
- processId: process.pid,
- processStartTimeMs: 1_000_000,
- identityName: 'disposable-waiter-test',
- scriptPath
- }, { spawn: start, handshakeTimeoutMs: mode.ready ? 10_000 : 2_000, cancelTimeoutMs: 2_000, pollMs: 20 })
+ const starting: Promise<RelaunchWaiterHandle | undefined> = startRelaunchWaiter(
+ {
+ processId: process.pid,
+ processStartTimeMs: 1_000_000,
+ identityName: 'disposable-waiter-test',
+ scriptPath
+ },
+ { spawn: start, handshakeTimeoutMs: mode.ready ? 10_000 : 2_000, cancelTimeoutMs: 2_000, pollMs: 20 }
+ )
if (!mode.ready && mode.refuseKill) {
await assert.rejects(starting, /did not exit after cancellation/)
@@ -97,9 +137,11 @@ for (const mode of [
assert.equal(handle.cancel(), cancelled, 'concurrent cancellation shares its result')
if (mode.refuseKill || mode.refuseCleanup) {
- await assert.rejects(cancelled, error => mode.refuseCleanup
- ? error === cleanupError
- : error instanceof Error && error.message.includes('did not exit after cancellation'))
+ await assert.rejects(cancelled, error =>
+ mode.refuseCleanup
+ ? error === cleanupError
+ : error instanceof Error && error.message.includes('did not exit after cancellation')
+ )
assert.equal(handle.cancel(), cancelled)
assert.equal(closed, !mode.refuseKill)
assert.equal(fs.existsSync(stage), true)
@@ -118,19 +160,36 @@ for (const mode of [
} finally {
vi.restoreAllMocks()
- if (child && originalKill) { child.kill = originalKill }
+ if (child && originalKill) {
+ child.kill = originalKill
+ }
await stop(child)
- if (stage) {fs.rmSync(stage, { recursive: true, force: true })}
+ if (stage) {
+ fs.rmSync(stage, { recursive: true, force: true })
+ }
}
}, 20_000)
}
test('missing scripts refuse startup before spawning a waiter', async (): Promise<void> => {
let spawned: boolean = false
- assert.equal(await startRelaunchWaiter({
- processId: process.pid, processStartTimeMs: 1_000_000,
- identityName: 'disposable-waiter-test', scriptPath: path.join(scriptPath, 'absent.ps1')
- }, { spawn: (): never => { spawned = true; throw new Error('missing scripts must not spawn') } }), undefined)
+ assert.equal(
+ await startRelaunchWaiter(
+ {
+ processId: process.pid,
+ processStartTimeMs: 1_000_000,
+ identityName: 'disposable-waiter-test',
+ scriptPath: path.join(scriptPath, 'absent.ps1')
+ },
+ {
+ spawn: (): never => {
+ spawned = true
+ throw new Error('missing scripts must not spawn')
+ }
+ }
+ ),
+ undefined
+ )
assert.equal(spawned, false)
})
diff --git a/apps/desktop/electron/updater/relaunch-waiter.ts b/apps/desktop/electron/updater/relaunch-waiter.ts
index 9f0cc0c875f..a2c357b5f6d 100644
--- a/apps/desktop/electron/updater/relaunch-waiter.ts
+++ b/apps/desktop/electron/updater/relaunch-waiter.ts
@@ -12,7 +12,13 @@ export const DEFAULT_RELAUNCH_WAITER_TIMEOUT_SECONDS = 900
export const DEFAULT_RELAUNCH_WAITER_HANDSHAKE_MS = 10_000
/** Absolute path — never resolved via inherited PATH (it can point into the package). */
-export const POWERSHELL_PATH = path.win32.join(process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
+export const POWERSHELL_PATH = path.win32.join(
+ process.env.SystemRoot || process.env.SYSTEMROOT || 'C:\\Windows',
+ 'System32',
+ 'WindowsPowerShell',
+ 'v1.0',
+ 'powershell.exe'
+)
export interface RelaunchWaiterOptions {
/** The quitting app's pid — the waiter waits for this process to exit. */
@@ -112,15 +118,19 @@ export async function startRelaunchWaiter(
const cancelTimeoutMs = deps.cancelTimeoutMs ?? 10_000
const staging = await stageRelaunchWaiter(options)
- if (!staging) { return undefined }
+ if (!staging) {
+ return undefined
+ }
const cleanup = () => fs.promises.rm(staging.stageDir, { recursive: true, force: true })
let child: ChildProcess
try {
- child = spawn(POWERSHELL_PATH,
+ child = spawn(
+ POWERSHELL_PATH,
buildRelaunchWaiterArgs({ ...options, scriptPath: staging.scriptPath }, staging.readyFile),
- { detached: true, stdio: 'ignore', windowsHide: true, cwd: staging.stageDir })
+ { detached: true, stdio: 'ignore', windowsHide: true, cwd: staging.stageDir }
+ )
} catch (error) {
try {
await cleanup()
@@ -134,7 +144,10 @@ export async function startRelaunchWaiter(
let closed = false
const closedPromise = new Promise<void>(resolve => {
- child.once('close', () => { closed = true; resolve() })
+ child.once('close', () => {
+ closed = true
+ resolve()
+ })
})
let cancellation: Promise<void> | undefined
@@ -142,7 +155,9 @@ export async function startRelaunchWaiter(
const cancel = (): Promise<void> => {
cancellation ??= (async () => {
if (!closed) {
- if (child.pid !== undefined) { child.kill() }
+ if (child.pid !== undefined) {
+ child.kill()
+ }
let timeout: ReturnType<typeof setTimeout> | undefined
@@ -150,7 +165,10 @@ export async function startRelaunchWaiter(
await Promise.race([
closedPromise,
new Promise<never>((_, reject) => {
- timeout = setTimeout(() => reject(new Error('Relaunch waiter did not exit after cancellation')), cancelTimeoutMs)
+ timeout = setTimeout(
+ () => reject(new Error('Relaunch waiter did not exit after cancellation')),
+ cancelTimeoutMs
+ )
})
])
} finally {
@@ -170,7 +188,9 @@ export async function startRelaunchWaiter(
const deadline = Date.now() + handshakeTimeoutMs
const finish = (ready: boolean) => {
- if (settled) { return }
+ if (settled) {
+ return
+ }
settled = true
clearTimeout(timer)
resolve(ready)
@@ -180,7 +200,9 @@ export async function startRelaunchWaiter(
child.once('close', () => finish(false))
const check = () => {
- if (settled) { return }
+ if (settled) {
+ return
+ }
if (fs.existsSync(staging.readyFile)) {
finish(true)
diff --git a/apps/desktop/electron/updater/relaunch-waiter.windows-live.test.ts b/apps/desktop/electron/updater/relaunch-waiter.windows-live.test.ts
index 546ab4bea15..c152ec3366b 100644
--- a/apps/desktop/electron/updater/relaunch-waiter.windows-live.test.ts
+++ b/apps/desktop/electron/updater/relaunch-waiter.windows-live.test.ts
@@ -11,13 +11,17 @@ const scriptPath = path.resolve(__dirname, '..', '..', 'scripts', RELAUNCH_WAITE
const quote = (value: string) => `'${value.replaceAll("'", "''")}'`
describe.skipIf(process.platform !== 'win32')('real PowerShell waiter control flow', () => {
- it.each([false, true])('activates only after parent exit and package change (%s)', unavailable => {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'relaunch-control-'))
- const ready = path.join(root, 'ready.txt')
- const activation = path.join(root, 'activation.txt')
- const wrapper = path.join(root, 'run.ps1')
+ it.each([false, true])(
+ 'activates only after parent exit and package change (%s)',
+ unavailable => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'relaunch-control-'))
+ const ready = path.join(root, 'ready.txt')
+ const activation = path.join(root, 'activation.txt')
+ const wrapper = path.join(root, 'run.ps1')
- fs.writeFileSync(wrapper, `
+ fs.writeFileSync(
+ wrapper,
+ `
$global:checks = 0
$global:birth = Get-Date
$global:clock = $global:birth
@@ -44,22 +48,29 @@ function Start-Process {
$birthMs = ([DateTimeOffset]$global:birth).ToUnixTimeMilliseconds()
& ${quote(scriptPath)} -ProcessId $PID -ProcessStartTimeMs $birthMs -IdentityName audit-only -ReadyFile ${quote(ready)} -TimeoutSeconds 10 -PollMillis 1
exit $LASTEXITCODE
-`, 'utf8')
+`,
+ 'utf8'
+ )
- try {
- const result = spawnSync(POWERSHELL_PATH, ['-NoProfile', '-NonInteractive', '-File', wrapper], {
- cwd: root, encoding: 'utf8', windowsHide: true, timeout: 30_000
- })
+ try {
+ const result = spawnSync(POWERSHELL_PATH, ['-NoProfile', '-NonInteractive', '-File', wrapper], {
+ cwd: root,
+ encoding: 'utf8',
+ windowsHide: true,
+ timeout: 30_000
+ })
- expect(result.status, result.stdout + result.stderr).toBe(unavailable ? 2 : 0)
- expect(fs.existsSync(ready)).toBe(false)
- expect(fs.existsSync(activation)).toBe(!unavailable)
+ expect(result.status, result.stdout + result.stderr).toBe(unavailable ? 2 : 0)
+ expect(fs.existsSync(ready)).toBe(false)
+ expect(fs.existsSync(activation)).toBe(!unavailable)
- if (!unavailable) {
- expect(fs.readFileSync(activation, 'utf8').trim()).toBe('shell:AppsFolder\\audit-only!Hermes')
+ if (!unavailable) {
+ expect(fs.readFileSync(activation, 'utf8').trim()).toBe('shell:AppsFolder\\audit-only!Hermes')
+ }
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
}
- } finally {
- fs.rmSync(root, { recursive: true, force: true })
- }
- }, 40_000)
+ },
+ 40_000
+ )
})
diff --git a/apps/desktop/electron/updater/store-client.test.ts b/apps/desktop/electron/updater/store-client.test.ts
index 267e31c53fc..fcd0d17cfa4 100644
--- a/apps/desktop/electron/updater/store-client.test.ts
+++ b/apps/desktop/electron/updater/store-client.test.ts
@@ -3,7 +3,13 @@ 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 calls: {
+ python: string
+ args: readonly string[]
+ env?: NodeJS.ProcessEnv
+ timeout?: number
+ waitForExit?: boolean
+ }[] = []
const handle = Buffer.alloc(8)
handle.writeBigUInt64LE(0x1234567887654321n)
@@ -20,7 +26,13 @@ it('the production runner passes modes, full HWND and isolated payload imports',
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 })
+ calls.push({
+ python,
+ args: [script, ...(deps.args ?? [])],
+ env: deps.env,
+ timeout: deps.timeoutMs,
+ waitForExit: deps.waitForExit
+ })
return {
code: deps.args?.includes('check') ? 2 : 0,
diff --git a/apps/desktop/electron/updater/updater.test.ts b/apps/desktop/electron/updater/updater.test.ts
index 42645eb0493..071b3718503 100644
--- a/apps/desktop/electron/updater/updater.test.ts
+++ b/apps/desktop/electron/updater/updater.test.ts
@@ -13,8 +13,11 @@ describe('build stamp → update ownership', () => {
const provenance = { commit: 'a'.repeat(40), branch: 'main', dirty: false, source: 'ci' }
const runtime = {
- repoDir: 'app', toolsDir: 'tools', storePython: 'tools/python/python',
- sitePackages: 'deps', commands: { hermes: 'bin/hermes' }
+ repoDir: 'app',
+ toolsDir: 'tools',
+ storePython: 'tools/python/python',
+ sitePackages: 'deps',
+ commands: { hermes: 'bin/hermes' }
}
it.each([
@@ -30,7 +33,12 @@ describe('build stamp → update ownership', () => {
['darwin', '', 'self', 'posix-handoff'],
['linux', '', 'self', 'posix-handoff']
] as const)('%s %s dispatches its declared owner without a Store flag', (platform, variant, declared, strategy) => {
- const stamp: ReturnType<typeof buildStampPayload> = buildStampPayload(provenance, { HERMES_DESKTOP_VARIANT: variant, HERMES_PAYLOAD_TAG: 'v1.2.3' }, platform, { runtime })
+ const stamp: ReturnType<typeof buildStampPayload> = buildStampPayload(
+ provenance,
+ { HERMES_DESKTOP_VARIANT: variant, HERMES_PAYLOAD_TAG: 'v1.2.3' },
+ platform,
+ { runtime }
+ )
expect(stamp.updateMechanism).toBe(declared)
expect(stamp.payload).toBe(variant === 'store' ? 'bundled' : variant || 'bootstrap')
@@ -41,8 +49,9 @@ describe('build stamp → update ownership', () => {
})
it.each(['win32', 'darwin', 'linux'] as const)('unstamped %s development uses source updates', platform => {
- expect(resolveUpdaterMechanism({ platform, updateMechanism: undefined }))
- .toBe(platform === 'win32' ? 'windows-handoff' : 'posix-handoff')
+ expect(resolveUpdaterMechanism({ platform, updateMechanism: undefined })).toBe(
+ platform === 'win32' ? 'windows-handoff' : 'posix-handoff'
+ )
})
})
diff --git a/apps/desktop/electron/windows-hermes-path.ts b/apps/desktop/electron/windows-hermes-path.ts
index c6effda2543..6a9c2019244 100644
--- a/apps/desktop/electron/windows-hermes-path.ts
+++ b/apps/desktop/electron/windows-hermes-path.ts
@@ -163,9 +163,7 @@ export async function resolveVenvHermesCommand(
// Probe with the same semantics the real spawn uses: venv interpreter,
// cwd at the checkout root, no PYTHONPATH.
- if (
- !(await canImportHermesCli(python, { cwd: directoryExists(root) ? root : undefined }))
- ) {
+ if (!(await canImportHermesCli(python, { cwd: directoryExists(root) ? root : undefined }))) {
rememberLog?.(
`Ignoring venv Hermes at ${python}: runtime import probe failed (broken/partial venv); falling through to bootstrap.`
)
diff --git a/apps/desktop/src/api/local-models-owner.test.ts b/apps/desktop/src/api/local-models-owner.test.ts
index 91d5533ae23..a27f747265c 100644
--- a/apps/desktop/src/api/local-models-owner.test.ts
+++ b/apps/desktop/src/api/local-models-owner.test.ts
@@ -28,13 +28,23 @@ it('pins delayed reads and controls to their captured connection and profile', a
it.each([
['pause', pauseLocalDownload, { ok: true, paused: true }],
['resume', resumeLocalDownload, { ok: true, resumed: false }]
-] as const)('%s preserves the captured owner, request body and backend verdict', async (action: string, control: typeof pauseLocalDownload | typeof resumeLocalDownload, response: { ok: boolean; paused?: boolean; resumed?: boolean }): Promise<void> => {
- const owner: LocalModelsOwner = { connectionId: 'background', profile: 'work' }
- vi.mocked(window.hermesDesktop.api).mockResolvedValue(response)
- expect(await control('download', owner)).toEqual(response)
- expect(window.hermesDesktop.api).toHaveBeenCalledExactlyOnceWith({
- ...owner, method: 'POST', path: `/api/local-models/download/${action}`, body: { job_id: 'download' }
- })
- vi.mocked(window.hermesDesktop.api).mockRejectedValue(new Error('unknown download job'))
- await expect(control('gone', owner)).rejects.toThrow('unknown download job')
-})
+] as const)(
+ '%s preserves the captured owner, request body and backend verdict',
+ async (
+ action: string,
+ control: typeof pauseLocalDownload | typeof resumeLocalDownload,
+ response: { ok: boolean; paused?: boolean; resumed?: boolean }
+ ): Promise<void> => {
+ const owner: LocalModelsOwner = { connectionId: 'background', profile: 'work' }
+ vi.mocked(window.hermesDesktop.api).mockResolvedValue(response)
+ expect(await control('download', owner)).toEqual(response)
+ expect(window.hermesDesktop.api).toHaveBeenCalledExactlyOnceWith({
+ ...owner,
+ method: 'POST',
+ path: `/api/local-models/download/${action}`,
+ body: { job_id: 'download' }
+ })
+ vi.mocked(window.hermesDesktop.api).mockRejectedValue(new Error('unknown download job'))
+ await expect(control('gone', owner)).rejects.toThrow('unknown download job')
+ }
+)
diff --git a/apps/desktop/src/app/contrib/onboarding-kickoff.test.ts b/apps/desktop/src/app/contrib/onboarding-kickoff.test.ts
index a4a0c818d87..b23c523e270 100644
--- a/apps/desktop/src/app/contrib/onboarding-kickoff.test.ts
+++ b/apps/desktop/src/app/contrib/onboarding-kickoff.test.ts
@@ -86,9 +86,13 @@ it.each(['empty', 'wrong-session', 'wrong-profile', 'no-runtime'])(
async () => {
publishGuide(failure === 'wrong-session' ? 'other' : 'guide', failure !== 'empty')
- if (failure === 'wrong-profile') {$activeGatewayProfile.set('default')}
+ if (failure === 'wrong-profile') {
+ $activeGatewayProfile.set('default')
+ }
- if (failure === 'no-runtime') {$activeSessionId.set(null)}
+ if (failure === 'no-runtime') {
+ $activeSessionId.set(null)
+ }
},
request
)
diff --git a/apps/desktop/src/app/retirement-view.test.tsx b/apps/desktop/src/app/retirement-view.test.tsx
index 718bdff9c78..5964768040b 100644
--- a/apps/desktop/src/app/retirement-view.test.tsx
+++ b/apps/desktop/src/app/retirement-view.test.tsx
@@ -19,9 +19,14 @@ afterEach((): void => {
test('discontinued retirement shows the uninstall notice and persists dismissal per revision', async (): Promise<void> => {
const dismissed: string[] = []
const stored = new Map<string, string>()
- const original = { getItem: window.localStorage.getItem.bind(window.localStorage), setItem: window.localStorage.setItem.bind(window.localStorage) }
+ const original = {
+ getItem: window.localStorage.getItem.bind(window.localStorage),
+ setItem: window.localStorage.setItem.bind(window.localStorage)
+ }
vi.spyOn(window.localStorage, 'getItem').mockImplementation((key: string) => stored.get(key) ?? original.getItem(key))
- vi.spyOn(window.localStorage, 'setItem').mockImplementation((key: string, value: string) => { stored.set(key, value) })
+ vi.spyOn(window.localStorage, 'setItem').mockImplementation((key: string, value: string) => {
+ stored.set(key, value)
+ })
const retirement: NonNullable<DesktopUpdateStatus['retirement']> = {
state: 'discontinued',
@@ -34,7 +39,9 @@ test('discontinued retirement shows the uninstall notice and persists dismissal
<Dialog open>
<DialogContent>
<DiscontinuedNotice
- onDismiss={(): void => { dismissed.push('dismissed') }}
+ onDismiss={(): void => {
+ dismissed.push('dismissed')
+ }}
retirement={retirement}
/>
</DialogContent>
@@ -50,5 +57,7 @@ test('discontinued retirement shows the uninstall notice and persists dismissal
expect(screen.queryByRole('checkbox')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: en.updates.maybeLater }))
- await waitFor((): void => { expect(dismissed).toEqual(['dismissed']) })
+ await waitFor((): void => {
+ expect(dismissed).toEqual(['dismissed'])
+ })
})
diff --git a/apps/desktop/src/app/retirement-view.tsx b/apps/desktop/src/app/retirement-view.tsx
index 4b1ba334f68..8dee0712783 100644
--- a/apps/desktop/src/app/retirement-view.tsx
+++ b/apps/desktop/src/app/retirement-view.tsx
@@ -26,7 +26,9 @@ export function DiscontinuedNotice({
<DialogTitle>{t.updates.discontinuedTitle}</DialogTitle>
<DialogDescription>{t.updates.discontinuedBody}</DialogDescription>
<div className="flex justify-end">
- <Button onClick={onDismiss} variant="text">{t.updates.maybeLater}</Button>
+ <Button onClick={onDismiss} variant="text">
+ {t.updates.maybeLater}
+ </Button>
</div>
</div>
)
diff --git a/apps/desktop/src/app/settings/gateway-settings.test.tsx b/apps/desktop/src/app/settings/gateway-settings.test.tsx
index 1fc31689440..4e2583b6070 100644
--- a/apps/desktop/src/app/settings/gateway-settings.test.tsx
+++ b/apps/desktop/src/app/settings/gateway-settings.test.tsx
@@ -268,32 +268,32 @@ describe('GatewaySettings', () => {
registry.value = null
})
it('keeps saved Cloud instances usable without discovery and marks the live source, not the default', async () => {
- getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'cloud', remoteUrl: 'https://a.example' })
- registry.value = {
- connections: [
- { id: 'saved-a', kind: 'cloud', label: 'Research', url: 'https://a.example', authMode: 'oauth' },
- { id: 'saved-b', kind: 'cloud', label: 'Writing', url: 'https://b.example', authMode: 'oauth' }
- ]
- }
- const agentSignIn = vi.fn()
- const applyConnectionConfig = vi.fn()
- Object.assign(window.hermesDesktop, {
- applyConnectionConfig,
- cloud: {
- status: vi.fn().mockResolvedValue({ signedIn: false }),
- agentSignIn
+ getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'cloud', remoteUrl: 'https://a.example' })
+ registry.value = {
+ connections: [
+ { id: 'saved-a', kind: 'cloud', label: 'Research', url: 'https://a.example', authMode: 'oauth' },
+ { id: 'saved-b', kind: 'cloud', label: 'Writing', url: 'https://b.example', authMode: 'oauth' }
+ ]
}
+ const agentSignIn = vi.fn()
+ const applyConnectionConfig = vi.fn()
+ Object.assign(window.hermesDesktop, {
+ applyConnectionConfig,
+ cloud: {
+ status: vi.fn().mockResolvedValue({ signedIn: false }),
+ agentSignIn
+ }
+ })
+ render(<GatewaySettings embedded />)
+ const research = await screen.findByText('Research')
+ const row = research.closest('[data-slot]') ?? research.parentElement!.parentElement!
+ fireEvent.click(within(row as HTMLElement).getByRole('button', { name: 'Use gateway' }))
+ await waitFor(() => expect(selectConnection).toHaveBeenCalledWith('saved-a'))
+ expect(screen.getByText('Active in this window')).toBeTruthy()
+ expect(agentSignIn).not.toHaveBeenCalled()
+ expect(applyConnectionConfig).not.toHaveBeenCalled()
+ registry.value = null
})
- render(<GatewaySettings embedded />)
- const research = await screen.findByText('Research')
- const row = research.closest('[data-slot]') ?? research.parentElement!.parentElement!
- fireEvent.click(within(row as HTMLElement).getByRole('button', { name: 'Use gateway' }))
- await waitFor(() => expect(selectConnection).toHaveBeenCalledWith('saved-a'))
- expect(screen.getByText('Active in this window')).toBeTruthy()
- expect(agentSignIn).not.toHaveBeenCalled()
- expect(applyConnectionConfig).not.toHaveBeenCalled()
- registry.value = null
-})
it('authenticates and saves only the chosen discovered instance with its friendly name', async () => {
registry.value = null
getConnectionConfig.mockResolvedValue({ ...localConnection, mode: 'cloud' })
diff --git a/apps/desktop/src/app/settings/local-models-settings.test.tsx b/apps/desktop/src/app/settings/local-models-settings.test.tsx
index 1413679c3c1..e9ce845e657 100644
--- a/apps/desktop/src/app/settings/local-models-settings.test.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.test.tsx
@@ -126,11 +126,15 @@ const REFUSED_MODEL: LocalCatalogModel = {
function setInstallStarting(starting: boolean): void {
queryClient.getMutationCache().clear()
+
if (starting) {
- queryClient.getMutationCache().build(queryClient, {
- mutationKey: localModelsKey(localModelsOwner(), 'install'),
- mutationFn: (): Promise<void> => new Promise<void>((): void => {})
- }).execute(undefined)
+ queryClient
+ .getMutationCache()
+ .build(queryClient, {
+ mutationKey: localModelsKey(localModelsOwner(), 'install'),
+ mutationFn: (): Promise<void> => new Promise<void>((): void => {})
+ })
+ .execute(undefined)
}
}
diff --git a/apps/desktop/src/app/settings/local-models-settings.tsx b/apps/desktop/src/app/settings/local-models-settings.tsx
index cc34e49939a..9d0af0c976a 100644
--- a/apps/desktop/src/app/settings/local-models-settings.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.tsx
@@ -280,7 +280,9 @@ function ScopedLocalModelsSettings({ owner }: { owner: LocalModelsOwner }): Reac
j => (j.kind === 'runtime-install' || j.kind === 'model-download') && isActiveStatus(j.status)
)
- const failedInstall: boolean = jobs.some((job: LocalRuntimeJob): boolean => job.kind === 'runtime-install' && job.status === 'error')
+ const failedInstall: boolean = jobs.some(
+ (job: LocalRuntimeJob): boolean => job.kind === 'runtime-install' && job.status === 'error'
+ )
if ((qJob || (needsSetup && !configure && heroModel)) && !otherActiveJob && !installStarting && !failedInstall) {
// Stage rail derived from the job phase: engine -> model -> finish.
diff --git a/apps/desktop/src/app/settings/uninstall-section.test.tsx b/apps/desktop/src/app/settings/uninstall-section.test.tsx
index 9d6a8cd7fbf..8a2feeb42f2 100644
--- a/apps/desktop/src/app/settings/uninstall-section.test.tsx
+++ b/apps/desktop/src/app/settings/uninstall-section.test.tsx
@@ -28,9 +28,13 @@ it.each(['external', 'missing-policy', 'probe-failed', 'loading'] as const)(
'does not offer uninstall actions when ownership is %s',
async (state: 'external' | 'missing-policy' | 'probe-failed' | 'loading'): Promise<void> => {
const getSummary: ReturnType<typeof vi.fn> = vi.fn(async (): Promise<DesktopUninstallSummary> => {
- if (state === 'probe-failed') { throw new Error('IPC unavailable') }
+ if (state === 'probe-failed') {
+ throw new Error('IPC unavailable')
+ }
- if (state === 'loading') { return new Promise<DesktopUninstallSummary>((): void => {}) }
+ if (state === 'loading') {
+ return new Promise<DesktopUninstallSummary>((): void => {})
+ }
if (state === 'missing-policy') {
const { code_removal_allowed: _ignored, ...oldSummary }: ReturnType<typeof summary> = summary(true)
@@ -44,7 +48,9 @@ it.each(['external', 'missing-policy', 'probe-failed', 'loading'] as const)(
const run: ReturnType<typeof vi.fn> = vi.fn()
vi.stubGlobal('hermesDesktop', { uninstall: { summary: getSummary, run } })
- await act(async (): Promise<void> => { render(<UninstallSection />) })
+ await act(async (): Promise<void> => {
+ render(<UninstallSection />)
+ })
expect(getSummary).toHaveBeenCalledOnce()
expect(screen.queryByText('Uninstall Hermes')).toBeNull()
expect(screen.queryByRole('button', { name: /Uninstall/ })).toBeNull()
@@ -62,5 +68,7 @@ it('keeps owned-install removal modes and confirms the selected mode', async ():
fireEvent.click(await screen.findByRole('button', { name: /Uninstall Chat GUI only/ }))
expect(run).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'Yes, uninstall' }))
- await waitFor((): void => { expect(run).toHaveBeenCalledWith('gui') })
+ await waitFor((): void => {
+ expect(run).toHaveBeenCalledWith('gui')
+ })
})
diff --git a/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts b/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts
index 055be9ccbab..33d69d9c520 100644
--- a/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts
+++ b/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts
@@ -54,8 +54,11 @@ describe('useStatusSnapshot', () => {
expect(warning).toBeTypeOf('string')
- const wrapper: (props: { children: ReactNode }) => ReactElement = ({ children }: { children: ReactNode }): ReactElement =>
- createElement(I18nProvider, { configClient: null, initialLocale: locale, children })
+ const wrapper: (props: { children: ReactNode }) => ReactElement = ({
+ children
+ }: {
+ children: ReactNode
+ }): ReactElement => createElement(I18nProvider, { configClient: null, initialLocale: locale, children })
const requestGateway: GatewayRequester = vi.fn().mockResolvedValue({}) as unknown as GatewayRequester
diff --git a/apps/desktop/src/app/updates-overlay.manual.test.tsx b/apps/desktop/src/app/updates-overlay.manual.test.tsx
index c886aaf67fd..f4949d2e7a1 100644
--- a/apps/desktop/src/app/updates-overlay.manual.test.tsx
+++ b/apps/desktop/src/app/updates-overlay.manual.test.tsx
@@ -3,7 +3,14 @@ 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 {
+ $updateApply,
+ $updateOverlayOpen,
+ $updateOverlayTarget,
+ $updateStatus,
+ applyUpdates,
+ resetUpdateApplyState
+} from '@/store/updates'
import { UpdatesOverlay } from './updates-overlay'
@@ -19,7 +26,9 @@ afterEach((): void => {
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 }) }
+ 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)
@@ -27,7 +36,11 @@ it('shows manual recovery guidance without claiming the help command installs an
await applyUpdates()
expect($updateApply.get().message).toBe(message)
await act(async (): Promise<void> => {
- render(<I18nProvider configClient={null} initialLocale="en"><UpdatesOverlay /></I18nProvider>)
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <UpdatesOverlay />
+ </I18nProvider>
+ )
})
expect(screen.getByText(message)).toBeTruthy()
expect(screen.getByText('hermes update --help')).toBeTruthy()
diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsx
index e465d1c6a3f..c2733052669 100644
--- a/apps/desktop/src/app/updates-overlay.tsx
+++ b/apps/desktop/src/app/updates-overlay.tsx
@@ -18,7 +18,6 @@ import { Progress } from '@/components/ui/progress'
import { UpdateStatusCard, VersionHero } from '@/components/update-status'
import { VersionDetails } from '@/components/version-details'
import type {
-
DesktopUpdateCommit,
DesktopUpdateStage,
DesktopUpdateStatus,
@@ -95,7 +94,6 @@ export function UpdatesOverlay() {
? 'error'
: 'idle'
-
const handleClose = (next: boolean) => {
if (phase === 'applying') {
return
@@ -135,7 +133,6 @@ export function UpdatesOverlay() {
{phase === 'guiSkew' && <GuiSkewView message={apply.message} onDone={() => handleClose(false)} />}
-
{phase === 'error' ? (
<ErrorView message={apply.message} onDismiss={() => handleClose(false)} onRetry={handleInstall} />
) : null}
@@ -441,11 +438,7 @@ function ApplyingView({
const label = u.stages[apply.stage as DesktopUpdateStage] ?? u.stages.idle
const isWindowsPackage = statusMechanism === 'app-installer' || statusMechanism === 'microsoft-store'
- const body = isWindowsPackage
- ? u.applyingBodyAppInstaller
- : isBackend
- ? u.applyingBodyBackend
- : u.applyingBody
+ const body = isWindowsPackage ? u.applyingBodyAppInstaller : isBackend ? u.applyingBodyBackend : u.applyingBody
const currentMessage = apply.message.trim()
const recentLog = apply.log.slice(-4)
@@ -490,7 +483,6 @@ function ApplyingView({
)
}
-
function ErrorView({ message, onDismiss, onRetry }: { message: string; onDismiss: () => void; onRetry: () => void }) {
const { t } = useI18n()
const u = t.updates
diff --git a/apps/desktop/src/components/boot-failure-overlay.test.tsx b/apps/desktop/src/components/boot-failure-overlay.test.tsx
index 6d9ab1ca995..34be04e604c 100644
--- a/apps/desktop/src/components/boot-failure-overlay.test.tsx
+++ b/apps/desktop/src/components/boot-failure-overlay.test.tsx
@@ -299,7 +299,9 @@ describe('BootFailureOverlay', () => {
expect(screen.getByText(/reinstall the app to restore/i)).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /reinstall the app/i }))
- await waitFor(() => expect(openExternal).toHaveBeenCalledWith('https://hermes-agent.nousresearch.com/docs/user-guide/desktop'))
+ await waitFor(() =>
+ expect(openExternal).toHaveBeenCalledWith('https://hermes-agent.nousresearch.com/docs/user-guide/desktop')
+ )
} finally {
restore()
}
@@ -313,29 +315,35 @@ describe('BootFailureOverlay', () => {
value: { ...window.location, reload }
})
- const repair = failure === 'unavailable' ? undefined : vi.fn(async () => {
- if (failure === 'thrown') {
- throw new Error('installer permission denied')
- }
+ const repair =
+ failure === 'unavailable'
+ ? undefined
+ : vi.fn(async () => {
+ if (failure === 'thrown') {
+ throw new Error('installer permission denied')
+ }
- return { ok: false, error: 'bundled-immutable' }
- })
+ return { ok: false, error: 'bundled-immutable' }
+ })
- const restore = stubDesktop(
- { mode: 'local' },
- { repairBootstrap: repair }
- )
+ const restore = stubDesktop({ mode: 'local' }, { repairBootstrap: repair })
try {
render(<BootFailureOverlay />)
fireEvent.click(await screen.findByRole('button', { name: /repair install/i }))
- const message = failure === 'thrown' ? 'installer permission denied'
- : failure === 'refused' ? 'bundled-immutable' : en.boot.errors.ipcBridgeUnavailable
-
- await waitFor(() => expect($notifications.get()).toEqual(expect.arrayContaining([
- expect.objectContaining({ kind: 'error', message })
- ])))
+ const message =
+ failure === 'thrown'
+ ? 'installer permission denied'
+ : failure === 'refused'
+ ? 'bundled-immutable'
+ : en.boot.errors.ipcBridgeUnavailable
+
+ await waitFor(() =>
+ expect($notifications.get()).toEqual(
+ expect.arrayContaining([expect.objectContaining({ kind: 'error', message })])
+ )
+ )
expect(reload).not.toHaveBeenCalled()
expect(screen.getByRole('button', { name: /repair install/i }).hasAttribute('disabled')).toBe(false)
} finally {
@@ -353,10 +361,7 @@ describe('BootFailureOverlay', () => {
value: { ...window.location, reload }
})
- const restore = stubDesktop(
- { mode: 'local' },
- { repairBootstrap: vi.fn().mockResolvedValue({ ok: true }) }
- )
+ const restore = stubDesktop({ mode: 'local' }, { repairBootstrap: vi.fn().mockResolvedValue({ ok: true }) })
try {
render(<BootFailureOverlay />)
diff --git a/apps/desktop/src/components/desktop-install-overlay.test.tsx b/apps/desktop/src/components/desktop-install-overlay.test.tsx
index c1ee6e615a8..6e2c2a27959 100644
--- a/apps/desktop/src/components/desktop-install-overlay.test.tsx
+++ b/apps/desktop/src/components/desktop-install-overlay.test.tsx
@@ -94,7 +94,12 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('shows the remote/local choice without installer progress', async () => {
installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
+ setupChoice: {
+ platform: 'win32',
+ activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent',
+ local: 'none',
+ bundled: false
+ }
})
)
@@ -111,7 +116,12 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('continues local bootstrap only when Install Hermes locally is selected', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
+ setupChoice: {
+ platform: 'win32',
+ activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent',
+ local: 'none',
+ bundled: false
+ }
})
)
@@ -133,7 +143,12 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('surfaces a recoverable error when the local-bootstrap bridge is unavailable', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
+ setupChoice: {
+ platform: 'win32',
+ activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent',
+ local: 'none',
+ bundled: false
+ }
})
)
@@ -152,7 +167,12 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('keeps the local-start error when the first snapshot commits under the click', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
+ setupChoice: {
+ platform: 'win32',
+ activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent',
+ local: 'none',
+ bundled: false
+ }
})
)
@@ -175,7 +195,12 @@ describe('DesktopInstallOverlay first-run setup', () => {
it('clears a stale local-start error when a repair presents a different root', async () => {
const desktop = installDesktopMock(
bootstrapState({
- setupChoice: { platform: 'win32', activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent', local: 'none', bundled: false }
+ setupChoice: {
+ platform: 'win32',
+ activeRoot: 'C:\\Users\\me\\AppData\\Local\\hermes\\hermes-agent',
+ local: 'none',
+ bundled: false
+ }
})
)
@@ -422,19 +447,28 @@ describe('DesktopInstallOverlay first-run setup', () => {
})
it('does not authorize a new URL with an old login result or save before Apply', async () => {
- const desktop = installDesktopMock(bootstrapState({
- setupChoice: { platform: 'linux', activeRoot: '/tmp/hermes', local: 'none', bundled: false }
- }))
+ const desktop = installDesktopMock(
+ bootstrapState({
+ setupChoice: { platform: 'linux', activeRoot: '/tmp/hermes', local: 'none', bundled: false }
+ })
+ )
const saveConnectionConfig = vi.fn()
Object.assign(desktop, { saveConnectionConfig })
desktop.probeConnectionConfig.mockResolvedValue({
- authMode: 'oauth', baseUrl: 'https://a.example', reachable: true, providers: [], error: null, version: null
+ authMode: 'oauth',
+ baseUrl: 'https://a.example',
+ reachable: true,
+ providers: [],
+ error: null,
+ version: null
})
let finishLogin!: (value: { connected: boolean }) => void
- desktop.oauthLoginConnectionConfig.mockReturnValueOnce(new Promise<{ connected: boolean }>(resolve => {
- finishLogin = resolve
- }))
+ desktop.oauthLoginConnectionConfig.mockReturnValueOnce(
+ new Promise<{ connected: boolean }>(resolve => {
+ finishLogin = resolve
+ })
+ )
render(<DesktopInstallOverlay />)
fireEvent.click(await screen.findByText('Connect to existing Hermes'))
const url = screen.getByPlaceholderText('https://gateway.example.com/hermes')
@@ -517,15 +551,30 @@ it.each([
['installed', false, 'Use Hermes on this computer', /already installed here/i, false],
['bundled', true, 'Use Hermes on this computer', /included with this app/i, false],
[undefined, false, 'Install Hermes locally', /Will install to/i, true]
-] as const)('local presentation for %s (including old backends)', async (local: 'installed' | 'bundled' | undefined, bundled: boolean, title: string, description: RegExp, footer: boolean): Promise<void> => {
- const state: DesktopBootstrapState = bootstrapState({ setupChoice: { platform: 'win32', activeRoot: 'C:\\Hermes', local: local ?? 'none', bundled } })
-
- if (local === undefined && state.setupChoice) { Reflect.deleteProperty(state.setupChoice, 'local') }
- installDesktopMock(state)
- render(<DesktopInstallOverlay />)
- expect(await screen.findByText(title)).toBeTruthy()
- expect(screen.getByText(description)).toBeTruthy()
- expect(screen.queryByText(/Will install to/i) !== null).toBe(footer)
+] as const)(
+ 'local presentation for %s (including old backends)',
+ async (
+ local: 'installed' | 'bundled' | undefined,
+ bundled: boolean,
+ title: string,
+ description: RegExp,
+ footer: boolean
+ ): Promise<void> => {
+ const state: DesktopBootstrapState = bootstrapState({
+ setupChoice: { platform: 'win32', activeRoot: 'C:\\Hermes', local: local ?? 'none', bundled }
+ })
+
+ if (local === undefined && state.setupChoice) {
+ Reflect.deleteProperty(state.setupChoice, 'local')
+ }
+ installDesktopMock(state)
+ render(<DesktopInstallOverlay />)
+ expect(await screen.findByText(title)).toBeTruthy()
+ expect(screen.getByText(description)).toBeTruthy()
+ expect(screen.queryByText(/Will install to/i) !== null).toBe(footer)
- if (!footer) { expect(screen.queryByText('Install Hermes locally')).toBeNull() }
-})
+ if (!footer) {
+ expect(screen.queryByText('Install Hermes locally')).toBeNull()
+ }
+ }
+)
diff --git a/apps/desktop/src/components/external-open-failed-dialog.test.tsx b/apps/desktop/src/components/external-open-failed-dialog.test.tsx
index 0e6ab1336cf..c1e532c9fb8 100644
--- a/apps/desktop/src/components/external-open-failed-dialog.test.tsx
+++ b/apps/desktop/src/components/external-open-failed-dialog.test.tsx
@@ -54,9 +54,13 @@ describe('ExternalOpenFailedDialog', () => {
fail(listener, 'https://example.com/dead')
expect(screen.getByText('https://example.com/dead')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /copy/i }))
- await waitFor((): void => { expect(writeClipboard).toHaveBeenCalledWith('https://example.com/dead') })
+ await waitFor((): void => {
+ expect(writeClipboard).toHaveBeenCalledWith('https://example.com/dead')
+ })
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
- await waitFor((): void => { expect(screen.queryByText('https://example.com/dead')).toBeNull() })
+ await waitFor((): void => {
+ expect(screen.queryByText('https://example.com/dead')).toBeNull()
+ })
})
it('renders nothing in a HUD window', () => {
diff --git a/apps/desktop/src/components/external-open-failed-dialog.tsx b/apps/desktop/src/components/external-open-failed-dialog.tsx
index f2deb5179fb..4f24d542040 100644
--- a/apps/desktop/src/components/external-open-failed-dialog.tsx
+++ b/apps/desktop/src/components/external-open-failed-dialog.tsx
@@ -23,7 +23,9 @@ export function ExternalOpenFailedDialog() {
const [failure, setFailure] = useState<ExternalOpenFailedPayload | null>(null)
useEffect(() => {
- if (!window.hermesDesktop?.onExternalOpenFailed) {return}
+ if (!window.hermesDesktop?.onExternalOpenFailed) {
+ return
+ }
return window.hermesDesktop.onExternalOpenFailed(setFailure)
}, [])
@@ -41,9 +43,7 @@ export function ExternalOpenFailedDialog() {
<DialogTitle>{copy.title}</DialogTitle>
<DialogDescription>{copy.message}</DialogDescription>
</DialogHeader>
- <div className="max-h-40 overflow-auto break-all rounded-md border bg-muted p-3 select-all">
- {failure?.url}
- </div>
+ <div className="max-h-40 overflow-auto break-all rounded-md border bg-muted p-3 select-all">{failure?.url}</div>
<DialogFooter>
{failure ? <CopyButton text={failure.url}>{copy.copyUrl}</CopyButton> : null}
<Button onClick={() => setFailure(null)} variant="ghost">
diff --git a/apps/desktop/src/components/onboarding-chat/gate.test.tsx b/apps/desktop/src/components/onboarding-chat/gate.test.tsx
index 734197f426c..5c47b8b1933 100644
--- a/apps/desktop/src/components/onboarding-chat/gate.test.tsx
+++ b/apps/desktop/src/components/onboarding-chat/gate.test.tsx
@@ -19,10 +19,14 @@ it('starts the skipped-film splash before the backend connects and removes it on
$desktopOnboarding.set({ ...$desktopOnboarding.get(), firstRunSkipped: false })
let complete = (_ready: boolean) => {}
- const pending = new Promise<boolean>(resolve => { complete = resolve })
+ const pending = new Promise<boolean>(resolve => {
+ complete = resolve
+ })
const kickoff = vi.fn(() => pending)
- const request = async () => { throw new Error('No provider notice available') }
+ const request = async () => {
+ throw new Error('No provider notice available')
+ }
const view = (enabled: boolean) => (
<I18nProvider>
@@ -37,7 +41,10 @@ it('starts the skipped-film splash before the backend connects and removes it on
rerender(view(true))
await waitFor(() => expect(kickoff).toHaveBeenCalledOnce())
expect(screen.getByRole('status')).toBeTruthy()
- await act(async () => { complete(true); await pending })
+ await act(async () => {
+ complete(true)
+ await pending
+ })
expect(screen.queryByRole('status')).toBeNull()
expect($onboardingGate.get().guideKickoff).toBe('started')
})
@@ -51,13 +58,21 @@ it.each(['refused', 'rejected'])('restores the ordinary app after %s startup', a
$onboardingGate.set({ phase: 'cinematic', guideQueued: true, guideKickoff: 'idle' })
const kickoff = vi.fn(async () => {
- if (outcome === 'rejected') {throw new Error('Backend unavailable')}
+ if (outcome === 'rejected') {
+ throw new Error('Backend unavailable')
+ }
return false
})
- const request = async () => { throw new Error('No provider notice available') }
- render(<I18nProvider><OnboardingChatGate enabled onKickoff={kickoff} requestGateway={request} /></I18nProvider>)
+ const request = async () => {
+ throw new Error('No provider notice available')
+ }
+ render(
+ <I18nProvider>
+ <OnboardingChatGate enabled onKickoff={kickoff} requestGateway={request} />
+ </I18nProvider>
+ )
await waitFor(() => expect($onboardingGate.get().phase).toBe('skipped'))
expect(screen.queryByRole('status')).toBeNull()
expect($chatOnboardingSolo.get()).toBe(false)
diff --git a/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx b/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx
index 5c4d9838cf4..261f7b5dcfa 100644
--- a/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx
+++ b/apps/desktop/src/components/remote-setup/use-remote-setup.test.tsx
@@ -89,35 +89,70 @@ describe('remote setup owner', () => {
})
})
-it.each<RemoteSetupHost>(['first-run', 'settings', 'registry'])('stale probes and credential tests cannot authorize %s', async (host: RemoteSetupHost): Promise<void> => {
- const probe: ReturnType<typeof deferred<DesktopConnectionProbeResult>> = deferred<DesktopConnectionProbeResult>()
- const tested: ReturnType<typeof deferred<Awaited<ReturnType<Window['hermesDesktop']['testConnectionConfig']>>>> = deferred()
+it.each<RemoteSetupHost>(['first-run', 'settings', 'registry'])(
+ 'stale probes and credential tests cannot authorize %s',
+ async (host: RemoteSetupHost): Promise<void> => {
+ const probe: ReturnType<typeof deferred<DesktopConnectionProbeResult>> = deferred<DesktopConnectionProbeResult>()
+ const tested: ReturnType<typeof deferred<Awaited<ReturnType<Window['hermesDesktop']['testConnectionConfig']>>>> =
+ deferred()
- const bridge = {
- probeConnectionConfig: vi.fn<Window['hermesDesktop']['probeConnectionConfig']>().mockReturnValue(probe.promise),
- testConnectionConfig: vi.fn<Window['hermesDesktop']['testConnectionConfig']>().mockReturnValue(tested.promise)
- } satisfies Pick<Window['hermesDesktop'], 'probeConnectionConfig' | 'testConnectionConfig'>
+ const bridge = {
+ probeConnectionConfig: vi.fn<Window['hermesDesktop']['probeConnectionConfig']>().mockReturnValue(probe.promise),
+ testConnectionConfig: vi.fn<Window['hermesDesktop']['testConnectionConfig']>().mockReturnValue(tested.promise)
+ } satisfies Pick<Window['hermesDesktop'], 'probeConnectionConfig' | 'testConnectionConfig'>
- Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: bridge })
- const { result }: RenderHookResult<ReturnType<typeof useRemoteSetup>, void> = renderHook((): ReturnType<typeof useRemoteSetup> => useRemoteSetup({ host }))
- act((): void => { result.current.setAuthMode('oauth'); result.current.setUrl('https://a.example') })
- await act(async (): Promise<void> => { await vi.advanceTimersByTimeAsync(500) })
- act((): void => { result.current.setUrl('not-a-url') })
- await act(async (): Promise<void> => { probe.resolve(probeResult('token', 'old')) })
- expect(result.current.probeStatus).not.toBe('done')
- expect(result.current.canTest).toBe(false)
- expect(result.current.credentials.authMode).toBe('oauth')
+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: bridge })
+ const {
+ result
+ }: RenderHookResult<ReturnType<typeof useRemoteSetup>, void> = renderHook((): ReturnType<typeof useRemoteSetup> =>
+ useRemoteSetup({ host })
+ )
+ act((): void => {
+ result.current.setAuthMode('oauth')
+ result.current.setUrl('https://a.example')
+ })
+ await act(async (): Promise<void> => {
+ await vi.advanceTimersByTimeAsync(500)
+ })
+ act((): void => {
+ result.current.setUrl('not-a-url')
+ })
+ await act(async (): Promise<void> => {
+ probe.resolve(probeResult('token', 'old'))
+ })
+ expect(result.current.probeStatus).not.toBe('done')
+ expect(result.current.canTest).toBe(false)
+ expect(result.current.credentials.authMode).toBe('oauth')
- bridge.probeConnectionConfig.mockResolvedValue(probeResult('token', 'new'))
- act((): void => { result.current.setAuthMode('token'); result.current.setUrl('https://b.example'); result.current.setToken('token-a') })
- await act(async (): Promise<void> => { await vi.advanceTimersByTimeAsync(500) })
- expect(result.current.canTest).toBe(true)
- let pending!: Promise<void>
- await act(async (): Promise<void> => { pending = result.current.test() })
- expect(bridge.testConnectionConfig).toHaveBeenCalledExactlyOnceWith({ mode: 'remote', remoteUrl: 'https://b.example', remoteAuthMode: 'token', remoteToken: 'token-a' })
- act((): void => { result.current.setToken('token-b') })
- await act(async (): Promise<void> => { tested.resolve({ ok: true, baseUrl: 'https://b.example', version: null }); await pending })
- expect(result.current.success).toBeNull()
- expect(result.current.testing).toBe(false)
- expect(result.current.canCommit).toBe(host !== 'first-run')
-})
+ bridge.probeConnectionConfig.mockResolvedValue(probeResult('token', 'new'))
+ act((): void => {
+ result.current.setAuthMode('token')
+ result.current.setUrl('https://b.example')
+ result.current.setToken('token-a')
+ })
+ await act(async (): Promise<void> => {
+ await vi.advanceTimersByTimeAsync(500)
+ })
+ expect(result.current.canTest).toBe(true)
+ let pending!: Promise<void>
+ await act(async (): Promise<void> => {
+ pending = result.current.test()
+ })
+ expect(bridge.testConnectionConfig).toHaveBeenCalledExactlyOnceWith({
+ mode: 'remote',
+ remoteUrl: 'https://b.example',
+ remoteAuthMode: 'token',
+ remoteToken: 'token-a'
+ })
+ act((): void => {
+ result.current.setToken('token-b')
+ })
+ await act(async (): Promise<void> => {
+ tested.resolve({ ok: true, baseUrl: 'https://b.example', version: null })
+ await pending
+ })
+ expect(result.current.success).toBeNull()
+ expect(result.current.testing).toBe(false)
+ expect(result.current.canCommit).toBe(host !== 'first-run')
+ }
+)
diff --git a/apps/desktop/src/components/sync-status-card.test.tsx b/apps/desktop/src/components/sync-status-card.test.tsx
index 79120cee265..dd3889fa79a 100644
--- a/apps/desktop/src/components/sync-status-card.test.tsx
+++ b/apps/desktop/src/components/sync-status-card.test.tsx
@@ -5,7 +5,10 @@ import type { DesktopSyncReceipt } from '@/global'
import { SyncStatusCard } from './sync-status-card'
-afterEach((): void => { cleanup(); vi.unstubAllGlobals() })
+afterEach((): void => {
+ cleanup()
+ vi.unstubAllGlobals()
+})
const details: DesktopSyncReceipt = {
plugin_bisect: [
@@ -29,40 +32,98 @@ interface ReceiptCase {
const cases: ReceiptCase[] = [
{ name: 'missing', receipt: null, headline: null },
{ name: 'empty', receipt: {}, headline: null },
- { name: 'healthy no-op', receipt: { outcome: 'ok', venv_rebuild: { ok: false, reason: 'already in sync' } }, headline: null },
- { name: 'unknown availability', receipt: { plugin_checks: [{ name: 'mystery', update_available: null }] }, headline: null },
- { name: 'embedded failed', receipt: { ...details, outcome: 'ok', pm_sync_outcome: 'failed', pm_steps: [{ name: 'sync', ok: false, detail: 'network unavailable' }] }, headline: /rebuild failed — network unavailable/, tone: 'text-destructive' },
- { name: 'embedded refused', receipt: { ...details, pm_sync_outcome: 'refused' }, headline: /rebuild failed/, tone: 'text-destructive' },
- { name: 'legacy failed', receipt: { ...details, outcome: 'failed', venv_rebuild: { ok: false, reason: 'uv sync exited 1' } }, headline: /rebuild failed — uv sync exited 1/, tone: 'text-destructive' },
- { name: 'review beats bisect and updates', receipt: details, headline: /need update-url review/, tone: 'text-amber-600' },
- { name: 'bisect beats updates', receipt: { ...details, plugin_checks: details.plugin_checks?.slice(1) }, headline: /disabled by dependency conflicts/, tone: 'text-amber-600' },
- { name: 'updates only', receipt: { plugin_checks: details.plugin_checks?.slice(1) }, headline: /Plugin updates available/, tone: 'text-muted-foreground' }
+ {
+ name: 'healthy no-op',
+ receipt: { outcome: 'ok', venv_rebuild: { ok: false, reason: 'already in sync' } },
+ headline: null
+ },
+ {
+ name: 'unknown availability',
+ receipt: { plugin_checks: [{ name: 'mystery', update_available: null }] },
+ headline: null
+ },
+ {
+ name: 'embedded failed',
+ receipt: {
+ ...details,
+ outcome: 'ok',
+ pm_sync_outcome: 'failed',
+ pm_steps: [{ name: 'sync', ok: false, detail: 'network unavailable' }]
+ },
+ headline: /rebuild failed — network unavailable/,
+ tone: 'text-destructive'
+ },
+ {
+ name: 'embedded refused',
+ receipt: { ...details, pm_sync_outcome: 'refused' },
+ headline: /rebuild failed/,
+ tone: 'text-destructive'
+ },
+ {
+ name: 'legacy failed',
+ receipt: { ...details, outcome: 'failed', venv_rebuild: { ok: false, reason: 'uv sync exited 1' } },
+ headline: /rebuild failed — uv sync exited 1/,
+ tone: 'text-destructive'
+ },
+ {
+ name: 'review beats bisect and updates',
+ receipt: details,
+ headline: /need update-url review/,
+ tone: 'text-amber-600'
+ },
+ {
+ name: 'bisect beats updates',
+ receipt: { ...details, plugin_checks: details.plugin_checks?.slice(1) },
+ headline: /disabled by dependency conflicts/,
+ tone: 'text-amber-600'
+ },
+ {
+ name: 'updates only',
+ receipt: { plugin_checks: details.plugin_checks?.slice(1) },
+ headline: /Plugin updates available/,
+ tone: 'text-muted-foreground'
+ }
]
-it.each(cases)('$name receipt paints the dominant warning and subordinate rows', async ({ receipt, headline, tone }: ReceiptCase): Promise<void> => {
- vi.stubGlobal('hermesDesktop', {
- getSyncStatus: async (): Promise<DesktopSyncReceipt | null> => receipt
- } satisfies Pick<Window['hermesDesktop'], 'getSyncStatus'>)
- await act(async (): Promise<void> => { render(<SyncStatusCard />) })
+it.each(cases)(
+ '$name receipt paints the dominant warning and subordinate rows',
+ async ({ receipt, headline, tone }: ReceiptCase): Promise<void> => {
+ vi.stubGlobal('hermesDesktop', {
+ getSyncStatus: async (): Promise<DesktopSyncReceipt | null> => receipt
+ } satisfies Pick<Window['hermesDesktop'], 'getSyncStatus'>)
+ await act(async (): Promise<void> => {
+ render(<SyncStatusCard />)
+ })
- if (!headline) { expect(screen.queryByTestId('sync-status-card')).toBeNull();
+ if (!headline) {
+ expect(screen.queryByTestId('sync-status-card')).toBeNull()
- return }
+ return
+ }
- expect(screen.getByText(headline).className).toContain(tone)
+ expect(screen.getByText(headline).className).toContain(tone)
- if (receipt?.plugin_bisect) { expect(screen.getByText('conflictor: conflicts with core pin')).toBeTruthy() }
+ if (receipt?.plugin_bisect) {
+ expect(screen.getByText('conflictor: conflicts with core pin')).toBeTruthy()
+ }
- if (receipt?.plugin_checks?.some(row => row.needs_fixing)) { expect(screen.getByText('bad-url: update_url points at a fork')).toBeTruthy() }
- expect(screen.getByText('grower: 1.0.0 → 1.1.0')).toBeTruthy()
- expect(screen.queryByText('fine')).toBeNull()
- expect(screen.queryByText('kept')).toBeNull()
-})
+ if (receipt?.plugin_checks?.some(row => row.needs_fixing)) {
+ expect(screen.getByText('bad-url: update_url points at a fork')).toBeTruthy()
+ }
+ expect(screen.getByText('grower: 1.0.0 → 1.1.0')).toBeTruthy()
+ expect(screen.queryByText('fine')).toBeNull()
+ expect(screen.queryByText('kept')).toBeNull()
+ }
+)
it('a rejected bridge leaves the overlay usable', async (): Promise<void> => {
vi.stubGlobal('hermesDesktop', {
- getSyncStatus: async (): Promise<never> => { throw new Error('bridge gone') }
+ getSyncStatus: async (): Promise<never> => {
+ throw new Error('bridge gone')
+ }
} satisfies Pick<Window['hermesDesktop'], 'getSyncStatus'>)
- await act(async (): Promise<void> => { render(<SyncStatusCard />) })
+ await act(async (): Promise<void> => {
+ render(<SyncStatusCard />)
+ })
expect(screen.queryByTestId('sync-status-card')).toBeNull()
})
diff --git a/apps/desktop/src/components/sync-status.ts b/apps/desktop/src/components/sync-status.ts
index a8109ec543e..5c403683e39 100644
--- a/apps/desktop/src/components/sync-status.ts
+++ b/apps/desktop/src/components/sync-status.ts
@@ -20,9 +20,7 @@ export interface SyncStatusSummary {
updatesAvailable: Array<{ name: string; current: string | null; latest: string | null }>
}
-export function deriveSyncStatusSummary(
- receipt: DesktopSyncReceipt | null
-): SyncStatusSummary {
+export function deriveSyncStatusSummary(receipt: DesktopSyncReceipt | null): SyncStatusSummary {
const empty: SyncStatusSummary = {
headline: null,
level: 'ok',
@@ -31,7 +29,9 @@ export function deriveSyncStatusSummary(
updatesAvailable: []
}
- if (!receipt) {return empty}
+ if (!receipt) {
+ return empty
+ }
const disabledPlugins = (receipt.pm_plugin_bisect ?? receipt.plugin_bisect ?? [])
.filter(d => d.action === 'disabled')
@@ -52,19 +52,21 @@ export function deriveSyncStatusSummary(
const steps = receipt.pm_steps ?? receipt.steps ?? []
const failureDetail = steps.find(step => step.ok === false)?.detail ?? rebuild?.reason
- const rebuildFailed = outcome === 'failed' || outcome === 'refused' ||
+ const rebuildFailed =
+ outcome === 'failed' ||
+ outcome === 'refused' ||
(outcome !== 'ok' && outcome !== 'success' && rebuild?.ok === false)
let headline: string | null = null
let level: SyncStatusSummary['level'] = 'ok'
if (rebuildFailed) {
- headline = failureDetail ? `Dependency rebuild failed — ${failureDetail}` : 'Dependency rebuild failed — inspect the update receipt'
+ headline = failureDetail
+ ? `Dependency rebuild failed — ${failureDetail}`
+ : 'Dependency rebuild failed — inspect the update receipt'
level = 'error'
} else if (needsFixing.length > 0) {
- headline = `${needsFixing.length} plugin${
- needsFixing.length === 1 ? '' : 's'
- } need update-url review`
+ headline = `${needsFixing.length} plugin${needsFixing.length === 1 ? '' : 's'} need update-url review`
level = 'warn'
} else if (disabledPlugins.length > 0) {
headline = `${disabledPlugins.length} plugin${
diff --git a/apps/desktop/src/components/tips/local-runtime-update-offer.test.tsx b/apps/desktop/src/components/tips/local-runtime-update-offer.test.tsx
index 2c249fdceec..a907489161a 100644
--- a/apps/desktop/src/components/tips/local-runtime-update-offer.test.tsx
+++ b/apps/desktop/src/components/tips/local-runtime-update-offer.test.tsx
@@ -169,7 +169,9 @@ it.each(['connection', 'profile', 'tips-off', 'job-started'])(
}
if (context === 'job-started') {
- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [{ kind: 'quickstart', status: 'running' }] as never)
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
+ { kind: 'quickstart', status: 'running' }
+ ] as never)
}
action.onSelect()
@@ -231,7 +233,9 @@ it.each(['remote', 'flag-off', 'tips-off', 'runtime-install', 'quickstart'])(
}
if (guard === 'runtime-install' || guard === 'quickstart') {
- queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [{ kind: guard, status: 'running' }] as never)
+ queryClient.setQueryData(localModelsKey(localModelsOwner(), 'jobs'), [
+ { kind: guard, status: 'running' }
+ ] as never)
}
api.mockClear()
@@ -280,7 +284,13 @@ it('the real Update now button navigates and sends exactly one install POST, nev
})
expect(screen.getByRole('status').textContent).toBe(`${SETTINGS_ROUTE}?tab=providers&pview=local`)
expect(api.mock.calls.filter(([request]) => request.method === 'POST').map(([request]) => request)).toEqual([
- { body: { backend: null }, method: 'POST', path: '/api/local-models/runtime/install', connectionId: null, profile: 'default' }
+ {
+ body: { backend: null },
+ method: 'POST',
+ path: '/api/local-models/runtime/install',
+ connectionId: null,
+ profile: 'default'
+ }
])
expect($activeTip.get()).toBeNull()
})
diff --git a/apps/desktop/src/components/tips/local-runtime-update-offer.ts b/apps/desktop/src/components/tips/local-runtime-update-offer.ts
index 20d8bce141f..aa0903119a6 100644
--- a/apps/desktop/src/components/tips/local-runtime-update-offer.ts
+++ b/apps/desktop/src/components/tips/local-runtime-update-offer.ts
@@ -4,10 +4,7 @@ import { queryClient } from '@/lib/query-client'
import { localSetupDue } from '@/lib/tips/local-cta'
import { $activeGatewayRoute } from '@/store/gateway'
import { $localModelsEnabled } from '@/store/local-models-flag'
-import {
- localRuntimeInstallBusy,
- startLocalRuntimeInstall
-} from '@/store/local-runtime-jobs'
+import { localRuntimeInstallBusy, startLocalRuntimeInstall } from '@/store/local-runtime-jobs'
import { $connection } from '@/store/session'
import { $activeTip, $retiredTips, $tipsEnabled, $tipShownAt, dismissTip, showTip } from '@/store/tips'
import type { LocalModelsStatus, LocalRuntimeJob } from '@/types/hermes'
diff --git a/apps/desktop/src/components/update-status.tsx b/apps/desktop/src/components/update-status.tsx
index 5ffe381cb7f..bf3393af839 100644
--- a/apps/desktop/src/components/update-status.tsx
+++ b/apps/desktop/src/components/update-status.tsx
@@ -44,7 +44,14 @@ function retirementStatus(
u: Translations['updates']
): UpdateStatusView {
// Suffixed-identity build: nothing to download or migrate — just the notice.
- return { applying, supported, updateAvailable: false, tone: 'error', line: u.discontinuedTitle, error: u.discontinuedBody }
+ return {
+ applying,
+ supported,
+ updateAvailable: false,
+ tone: 'error',
+ line: u.discontinuedTitle,
+ error: u.discontinuedBody
+ }
}
/**
@@ -63,19 +70,18 @@ export function deriveUpdateStatus(input: UpdateStatusInput): UpdateStatusView {
const { apply, status, target, u } = input
if (target === 'client' && status?.retirement) {
- return retirementStatus(status.retirement, apply.applying || apply.stage === 'restart', status.supported !== false, u)
+ return retirementStatus(
+ status.retirement,
+ apply.applying || apply.stage === 'restart',
+ status.supported !== false,
+ u
+ )
}
return ordinaryUpdateStatus(input)
}
-function ordinaryUpdateStatus({
- apply,
- checking,
- status,
- target,
- u
-}: UpdateStatusInput): UpdateStatusView {
+function ordinaryUpdateStatus({ apply, checking, status, target, u }: UpdateStatusInput): UpdateStatusView {
const behind = status?.behind ?? 0
// behind is null when the exact count is unknowable (shallow clone): the
// backend flags that case via updateAvailable instead of a number.
@@ -91,6 +97,7 @@ function ordinaryUpdateStatus({
// A git that never ran is a local problem; leading with "couldn't reach
// the update server" would misdiagnose it as a network failure.
const prefix = status.error === 'git-unusable' ? '' : u.cantReach
+
return {
applying,
error: [status.message, status.error].filter(l => !!l).join('\n'),
@@ -177,7 +184,9 @@ export function VersionHero({
)}
<p className="mt-1 text-xs text-muted-foreground">
{version?.appVersion ? u.version(version.appVersion) : u.versionUnavailable}
- {version?.channel ? ` · ${Object.entries(u.channels).find(([name]: [string, string]): boolean => name === version.channel)?.[1] ?? version.channel}` : ''}
+ {version?.channel
+ ? ` · ${Object.entries(u.channels).find(([name]: [string, string]): boolean => name === version.channel)?.[1] ?? version.channel}`
+ : ''}
</p>
</div>
{(version?.bundleSwapPending || version?.bundleOutOfSync) && (
@@ -230,14 +239,22 @@ interface UpdateActionsProps {
}
function UpdateActions({ target, u, view }: UpdateActionsProps): ReactElement | null {
- if (view.applying) { return null }
+ if (view.applying) {
+ return null
+ }
- if (!view.updateAvailable || !view.supported) { return null }
+ if (!view.updateAvailable || !view.supported) {
+ return null
+ }
return (
<>
- <Button onClick={() => startActiveUpdate(target)} size="sm">{u.updateNow}</Button>
- <Button onClick={() => openUpdateOverlayFor(target)} size="sm" variant="textStrong">{u.seeWhatsNew}</Button>
+ <Button onClick={() => startActiveUpdate(target)} size="sm">
+ {u.updateNow}
+ </Button>
+ <Button onClick={() => openUpdateOverlayFor(target)} size="sm" variant="textStrong">
+ {u.seeWhatsNew}
+ </Button>
</>
)
}
@@ -311,11 +328,7 @@ export function UpdateStatusCard({
{checking ? u.checkingShort : u.checkNow}
</Button>
- <UpdateActions
- target={target}
- u={u}
- view={view}
- />
+ <UpdateActions target={target} u={u} view={view} />
{showReleaseNotes && (
<Button asChild className="ml-auto" size="sm" variant="text">
diff --git a/apps/desktop/src/components/version-details.test.tsx b/apps/desktop/src/components/version-details.test.tsx
index ec27a29b05d..15b14347cfa 100644
--- a/apps/desktop/src/components/version-details.test.tsx
+++ b/apps/desktop/src/components/version-details.test.tsx
@@ -22,49 +22,80 @@ const baseVersion: DesktopVersionInfo = {
}
describe('VersionDetails', () => {
- interface VersionCase { version: Partial<DesktopVersionInfo>; visible: string[]; absent?: string[] }
+ interface VersionCase {
+ version: Partial<DesktopVersionInfo>
+ visible: string[]
+ absent?: string[]
+ }
const cases: VersionCase[] = [
{ version: { source: 'ci', branch: null }, visible: ['Build Origin', 'CI'] },
{ version: { source: 'ci', branch: 'unknown' }, visible: ['CI (unknown)'] },
{ version: { source: 'nix', distribution: 'nix' }, visible: ['Build Origin', 'Nix', 'Distribution'] },
{ version: { source: 'ci', distribution: 'docker' }, visible: ['CI', 'Distribution', 'Docker'] },
- { version: { distribution: 'desktop-app', hermesRuntime: { type: 'embedded' } }, visible: ['Runtime', 'Embedded runtime'] },
- { version: { hermesRuntime: { type: 'external', source: { type: 'git', root: '/home/u/.hermes/hermes-agent' } } },
- visible: ['Runtime', 'git (/home/u/.hermes/hermes-agent)'], absent: ['External (uses the machine runtime)'] },
+ {
+ version: { distribution: 'desktop-app', hermesRuntime: { type: 'embedded' } },
+ visible: ['Runtime', 'Embedded runtime']
+ },
+ {
+ version: { hermesRuntime: { type: 'external', source: { type: 'git', root: '/home/u/.hermes/hermes-agent' } } },
+ visible: ['Runtime', 'git (/home/u/.hermes/hermes-agent)'],
+ absent: ['External (uses the machine runtime)']
+ },
{ version: { hermesRuntime: { type: 'external' } }, visible: ['Runtime', 'External (uses the machine runtime)'] },
- { version: { distribution: 'desktop-app', updateMechanism: 'microsoft-store' },
- visible: ['Distribution', 'Microsoft Store'], absent: ['Desktop app (MSIX)'] },
- { version: { distribution: 'desktop-app', updateMechanism: 'app-installer', payload: 'bundled' },
- visible: ['Desktop app (MSIX)'], absent: ['Microsoft Store'] },
- { version: { distribution: 'desktop-app', updateMechanism: 'electron-updater', payload: 'bundled' },
- visible: ['Desktop app'], absent: ['Desktop app (MSIX)'] },
+ {
+ version: { distribution: 'desktop-app', updateMechanism: 'microsoft-store' },
+ visible: ['Distribution', 'Microsoft Store'],
+ absent: ['Desktop app (MSIX)']
+ },
+ {
+ version: { distribution: 'desktop-app', updateMechanism: 'app-installer', payload: 'bundled' },
+ visible: ['Desktop app (MSIX)'],
+ absent: ['Microsoft Store']
+ },
+ {
+ version: { distribution: 'desktop-app', updateMechanism: 'electron-updater', payload: 'bundled' },
+ visible: ['Desktop app'],
+ absent: ['Desktop app (MSIX)']
+ },
// Old-style installer shell (bootstrap artifact over a managed checkout —
// e.g. iris's v0.17.6 .app): named as the installer, never as MSIX.
- { version: { distribution: 'desktop-app', updateMechanism: 'self', payload: 'bootstrap' },
- visible: ['Desktop app (installer)'], absent: ['Desktop app (MSIX)', 'Microsoft Store'] },
+ {
+ version: { distribution: 'desktop-app', updateMechanism: 'self', payload: 'bootstrap' },
+ visible: ['Desktop app (installer)'],
+ absent: ['Desktop app (MSIX)', 'Microsoft Store']
+ },
// install.sh / install.ps1 checkout (receipt present) vs a manual git
// clone (live provenance, no receipt): both honestly say Source.
- { version: { installedByScript: true },
- visible: ['Source (install script)'] },
- { version: { source: 'git' },
- visible: ['Distribution', 'Source'], absent: ['Source (install script)'] },
- { version: {},
- visible: ['Version'], absent: ['Distribution'] }
+ { version: { installedByScript: true }, visible: ['Source (install script)'] },
+ { version: { source: 'git' }, visible: ['Distribution', 'Source'], absent: ['Source (install script)'] },
+ { version: {}, visible: ['Version'], absent: ['Distribution'] }
]
it.each(cases)('renders $version', ({ version, visible, absent = [] }: VersionCase): void => {
- render(<I18nProvider configClient={null} initialLocale="en"><VersionDetails version={{ ...baseVersion, ...version }} /></I18nProvider>)
+ render(
+ <I18nProvider configClient={null} initialLocale="en">
+ <VersionDetails version={{ ...baseVersion, ...version }} />
+ </I18nProvider>
+ )
- for (const text of visible) { expect(screen.getAllByText(text).length).toBeGreaterThan(0) }
+ for (const text of visible) {
+ expect(screen.getAllByText(text).length).toBeGreaterThan(0)
+ }
- for (const text of absent) { expect(screen.queryByText(text)).toBeNull() }
+ for (const text of absent) {
+ expect(screen.queryByText(text)).toBeNull()
+ }
- if (version.source === 'nix') { expect(screen.getAllByText('Nix')).toHaveLength(2) }
+ if (version.source === 'nix') {
+ expect(screen.getAllByText('Nix')).toHaveLength(2)
+ }
})
it('opens the commit URL via the system-browser bridge without opening a preview tab', async () => {
- const openExternal: Mock<Window['hermesDesktop']['openExternal']> = vi.fn<Window['hermesDesktop']['openExternal']>().mockResolvedValue(undefined)
+ const openExternal: Mock<Window['hermesDesktop']['openExternal']> = vi
+ .fn<Window['hermesDesktop']['openExternal']>()
+ .mockResolvedValue(undefined)
vi.stubGlobal('hermesDesktop', { openExternal } satisfies Pick<Window['hermesDesktop'], 'openExternal'>)
render(
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index f1456f11938..28878bf2efb 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -2,8 +2,8 @@ import type { GatewayWsUrlResult } from '@hermes/shared'
import type { TranslucencyState } from '@hermes/shared/translucency'
import type { ScreenshotApi } from '../electron/command-screenshot-types'
-import type { MachineProfile } from '../electron/machine-profile'
import type { HudModifierApi } from '../electron/hud-modifier-types'
+import type { MachineProfile } from '../electron/machine-profile'
import type { HermesNotification } from '../electron/notification-types'
import type { PoolLimits } from '../electron/pool-limits'
import type { GrowRequest } from '../electron/window-growth'
@@ -744,7 +744,6 @@ export type RuntimeSource =
| { type: 'system-python'; command: string } // pip-installed hermes_cli on system Python
| { type: 'bootstrap' } // nothing usable yet; the first-launch installer runs
-
export type DesktopUninstallMode = 'full' | 'gui' | 'lite'
export interface DesktopUninstallSummary {
@@ -779,13 +778,7 @@ export interface DesktopUpdateCommit {
}
export type UpdaterMechanismClient =
- | 'app-installer'
- | 'electron-updater'
- | 'external'
- | 'microsoft-store'
- | 'windows-handoff'
- | 'posix-handoff'
- | 'manual'
+ 'app-installer' | 'electron-updater' | 'external' | 'microsoft-store' | 'windows-handoff' | 'posix-handoff' | 'manual'
export interface DesktopUpdateStatus {
supported: boolean
@@ -822,10 +815,8 @@ export interface DesktopUpdateStatus {
export type DesktopUpdateDirtyStrategy = 'abort' | 'stash' | 'force'
-
export interface DesktopUpdateApplyOptions {
dirtyStrategy?: DesktopUpdateDirtyStrategy
-
}
export interface DesktopUpdateApplyResult {
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index 9765712c172..e33f1150d02 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -175,7 +175,8 @@ export const ar = defineLocale({
}
},
notifications: {
- sharedProfileWarning: 'تستخدم نسخة أخرى من Hermes هذا الملف الشخصي. تتشارك النسختان إعداداته وبياناته، لذا قد تتعارض التغييرات. يمكنك المتابعة أو إغلاق النسخة الأخرى قبل إجراء تغييرات.',
+ sharedProfileWarning:
+ 'تستخدم نسخة أخرى من Hermes هذا الملف الشخصي. تتشارك النسختان إعداداته وبياناته، لذا قد تتعارض التغييرات. يمكنك المتابعة أو إغلاق النسخة الأخرى قبل إجراء تغييرات.',
region: 'الإشعارات',
hide: 'إخفاء',
show: 'إظهار',
@@ -851,7 +852,7 @@ export const ar = defineLocale({
'عندما يحدّث Hermes نفسه من التطبيق دون موجه طرفية، احتفظ بتعديلات المصدر المحلية أو تجاهلها.'
},
about: {
- updates: 'التحديثات',
+ updates: 'التحديثات'
},
config: {
@@ -2373,7 +2374,8 @@ export const ar = defineLocale({
updates: {
channels: { stable: 'مستقر', canary: 'تجريبي' },
bundleSwapPending: 'أعد التشغيل لإكمال التحديث',
- bundleSwapPendingDesc: 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',
+ bundleSwapPendingDesc:
+ 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',
bundleSwapPendingAction: 'إعادة تشغيل Hermes',
stages: {
idle: 'جار التحضير...',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 7ccb0db22a0..86dd55ec3e2 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -221,7 +221,8 @@ export const en: Translations = {
},
notifications: {
- sharedProfileWarning: 'Another Hermes installation is using this profile. Both installations share its settings and data, so changes can conflict. You can continue, or close the other installation before making changes.',
+ sharedProfileWarning:
+ 'Another Hermes installation is using this profile. Both installations share its settings and data, so changes can conflict. You can continue, or close the other installation before making changes.',
region: 'Notifications',
hide: 'Hide',
show: 'Show',
@@ -239,8 +240,7 @@ export const en: Translations = {
updateReadyTitle: 'Update ready',
updateReadyMessage: count => `${count} new change${count === 1 ? '' : 's'} available.`,
updateReadyMessageUnknown: 'A new update is available.',
- updateReadyMessageAppInstaller:
- 'A new version of Hermes is ready. Update now and Windows will finish it for you.',
+ updateReadyMessageAppInstaller: 'A new version of Hermes is ready. Update now and Windows will finish it for you.',
seeWhatsNew: "See what's new",
mcp: {
needsAuthTitle: 'MCP server needs re-authentication',
@@ -971,7 +971,7 @@ export const en: Translations = {
driverHealth: 'Driver health'
},
about: {
- updates: 'Updates',
+ updates: 'Updates'
},
config: {
minimizeToTrayTitle: 'Minimize to tray',
@@ -3327,10 +3327,12 @@ export const en: Translations = {
updates: {
discontinuedTitle: 'This build of Hermes is no longer supported',
- discontinuedBody: 'This build of Hermes is no longer supported and may break — uninstall it. Your data stays on disk.',
+ discontinuedBody:
+ 'This build of Hermes is no longer supported and may break — uninstall it. Your data stays on disk.',
channels: { stable: 'Stable', canary: 'Canary' },
bundleSwapPending: 'Restart to finish the update',
- bundleSwapPendingDesc: 'The updated app is already installed — Hermes only needs to restart to load it. Chats and settings are untouched.',
+ bundleSwapPendingDesc:
+ 'The updated app is already installed — Hermes only needs to restart to load it. Chats and settings are untouched.',
bundleSwapPendingAction: 'Restart Hermes',
stages: {
idle: 'Getting ready…',
@@ -3450,8 +3452,7 @@ export const en: Translations = {
checkingShort: 'Checking…',
releaseAvailable: tag => `Version ${tag} is available.`,
versionDetailsTitle: 'Version details',
- versionDetailsBody:
- 'This install is managed outside the app. Update it the same way you installed it.',
+ versionDetailsBody: 'This install is managed outside the app. Update it the same way you installed it.',
versionDetailsVersion: 'Version',
versionDetailsCommit: 'Commit',
versionDetailsBuildOrigin: 'Build Origin',
@@ -3502,8 +3503,7 @@ export const en: Translations = {
setupChoiceTitle: 'Set up Hermes Desktop',
setupChoiceDesc:
'Connect this app to a Hermes gateway you already run, or install Hermes locally on this computer.',
- setupChoiceDescLocal:
- 'Install Hermes on this computer, or connect to a Hermes gateway you already run.',
+ setupChoiceDescLocal: 'Install Hermes on this computer, or connect to a Hermes gateway you already run.',
connectExistingTitle: 'Connect to existing Hermes',
connectExistingShort: 'Connect existing',
connectExistingDesc: 'Use a remote backend with a session token or browser sign-in. No local install will start.',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 137ece97e1c..6c14ef54000 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -167,7 +167,8 @@ export const ja = defineLocale({
},
notifications: {
- sharedProfileWarning: '別の Hermes インストールがこのプロファイルを使用しています。両方が設定とデータを共有しているため、変更が競合する可能性があります。このまま続けるか、変更する前にもう一方を終了してください。',
+ sharedProfileWarning:
+ '別の Hermes インストールがこのプロファイルを使用しています。両方が設定とデータを共有しているため、変更が競合する可能性があります。このまま続けるか、変更する前にもう一方を終了してください。',
region: '通知',
hide: '非表示',
show: '表示',
@@ -932,7 +933,7 @@ export const ja = defineLocale({
}
}),
about: {
- updates: '更新',
+ updates: '更新'
},
config: {
minimizeToTrayTitle: 'トレイに最小化',
@@ -2754,7 +2755,8 @@ export const ja = defineLocale({
updates: {
channels: { stable: '安定版', canary: '先行版' },
bundleSwapPending: '再起動して更新を完了',
- bundleSwapPendingDesc: '更新されたアプリはすでにインストール済みです。Hermes を再起動するだけで新しいビルドが読み込まれます。チャットや設定はそのまま保持されます。',
+ bundleSwapPendingDesc:
+ '更新されたアプリはすでにインストール済みです。Hermes を再起動するだけで新しいビルドが読み込まれます。チャットや設定はそのまま保持されます。',
bundleSwapPendingAction: 'Hermes を再起動',
stages: {
idle: '準備中…',
diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts
index 7be500a9b00..fc39135cf45 100644
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@ -170,7 +170,8 @@ export const ru = defineLocale({
}
},
notifications: {
- sharedProfileWarning: 'Другая установка Hermes использует этот профиль. Обе установки используют общие настройки и данные, поэтому изменения могут конфликтовать. Можно продолжить работу или закрыть другую установку перед внесением изменений.',
+ sharedProfileWarning:
+ 'Другая установка Hermes использует этот профиль. Обе установки используют общие настройки и данные, поэтому изменения могут конфликтовать. Можно продолжить работу или закрыть другую установку перед внесением изменений.',
region: 'Уведомления',
hide: 'Скрыть',
show: 'Показать',
@@ -1014,7 +1015,7 @@ export const ru = defineLocale({
}
}),
about: {
- updates: 'Обновления',
+ updates: 'Обновления'
},
config: {
minimizeToTrayTitle: 'Сворачивать в трей',
@@ -3059,7 +3060,8 @@ export const ru = defineLocale({
updates: {
channels: { stable: 'Стабильный', canary: 'Тестовый' },
bundleSwapPending: 'Перезапустите, чтобы завершить обновление',
- bundleSwapPendingDesc: 'Обновлённое приложение уже установлено — достаточно перезапустить Hermes, чтобы загрузить его. Чаты и настройки не пострадают.',
+ bundleSwapPendingDesc:
+ 'Обновлённое приложение уже установлено — достаточно перезапустить Hermes, чтобы загрузить его. Чаты и настройки не пострадают.',
bundleSwapPendingAction: 'Перезапустить Hermes',
stages: {
idle: 'Готовимся…',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 25152fb056c..e84a7bf3f8e 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -64,7 +64,7 @@ export interface Translations {
message: string
copyUrl: string
close: string
- };
+ }
connectors: {
title: string
connect: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index cc3a09484b3..3a612f19842 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -163,7 +163,8 @@ export const zhHant = defineLocale({
},
notifications: {
- sharedProfileWarning: '另一個 Hermes 安裝實例正在使用此設定檔。兩個實例共用此設定檔的設定和資料,因此變更可能發生衝突。你可以繼續使用,也可以在變更前關閉另一個實例。',
+ sharedProfileWarning:
+ '另一個 Hermes 安裝實例正在使用此設定檔。兩個實例共用此設定檔的設定和資料,因此變更可能發生衝突。你可以繼續使用,也可以在變更前關閉另一個實例。',
region: '通知',
hide: '隱藏',
show: '顯示',
@@ -970,7 +971,7 @@ export const zhHant = defineLocale({
driverHealth: '驅動程式健康狀態'
},
about: {
- updates: '更新',
+ updates: '更新'
},
config: {
minimizeToTrayTitle: '最小化至系統匣',
@@ -2736,7 +2737,8 @@ export const zhHant = defineLocale({
updates: {
channels: { stable: '穩定版', canary: '預覽版' },
bundleSwapPending: '重新啟動以完成更新',
- bundleSwapPendingDesc: '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',
+ bundleSwapPendingDesc:
+ '更新後的應用程式已安裝完成,只需重新啟動 Hermes 即可載入新版本。聊天記錄和設定不會受到影響。',
bundleSwapPendingAction: '重新啟動 Hermes',
stages: {
idle: '準備中…',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 373a0a9700f..4771e3fbbb4 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -170,8 +170,7 @@ export const zh = defineLocale({
back: '返回',
openLogs: '打开日志',
repairHint: '修复会重新运行安装器,在新机器上可能需要几分钟。',
- bundledReinstallHint:
- '捆绑安装无法从应用内部自修复——重新安装 Hermes Desktop 以恢复其后端。',
+ bundledReinstallHint: '捆绑安装无法从应用内部自修复——重新安装 Hermes Desktop 以恢复其后端。',
reinstallApp: '重新安装 Hermes Desktop',
remoteSignInHint: signInLabel =>
`先退出已保存的远程浏览器会话,然后打开${signInLabel}。也可以使用本地网关切换到随应用提供的后端。`,
@@ -197,7 +196,8 @@ export const zh = defineLocale({
},
notifications: {
- sharedProfileWarning: '另一个 Hermes 安装实例正在使用此配置。两个实例共享此配置的设置和数据,因此更改可能发生冲突。你可以继续使用,也可以在更改前关闭另一个实例。',
+ sharedProfileWarning:
+ '另一个 Hermes 安装实例正在使用此配置。两个实例共享此配置的设置和数据,因此更改可能发生冲突。你可以继续使用,也可以在更改前关闭另一个实例。',
region: '通知',
hide: '隐藏',
show: '显示',
@@ -1184,7 +1184,7 @@ export const zh = defineLocale({
driverHealth: '驱动健康状态'
},
about: {
- updates: '更新',
+ updates: '更新'
},
config: {
minimizeToTrayTitle: '最小化到托盘',
@@ -3546,8 +3546,7 @@ export const zh = defineLocale({
notAvailable: '此后端无法更新。',
failed: '后端更新失败。',
noReturn: '后端未恢复在线。更新可能未完成——请检查后端主机。'
- }
- ,
+ },
// Update-status overlay + version-details (mechanism-aware update UI).
appName: 'Hermes',
version: value => `版本 ${value}`,
@@ -3570,14 +3569,12 @@ export const zh = defineLocale({
daysAgo: count => `${count} 天前`,
justNowSuffix: ' · 刚刚',
bundleOutOfSync: '应用版本过旧',
- bundleOutOfSyncDesc:
- 'Hermes 运行时已更新,但桌面应用仍是较旧的构建。请更新以获取最新修复。',
+ bundleOutOfSyncDesc: 'Hermes 运行时已更新,但桌面应用仍是较旧的构建。请更新以获取最新修复。',
bundleOutOfSyncAction: '获取安装程序',
checkingShort: '检查中…',
releaseAvailable: tag => `版本 ${tag} 可用。`,
versionDetailsTitle: '版本详情',
- versionDetailsBody:
- '此安装在应用外部管理。请使用与安装时相同的方式更新。',
+ versionDetailsBody: '此安装在应用外部管理。请使用与安装时相同的方式更新。',
versionDetailsVersion: '版本',
versionDetailsCommit: '提交',
versionDetailsBuildOrigin: '构建来源',
@@ -3620,8 +3617,7 @@ export const zh = defineLocale({
connectExistingTitle: '连接到现有 Hermes',
connectExistingShort: '连接现有环境',
connectExistingDesc: '使用会话令牌或浏览器登录连接远程后端。不会启动本地安装。',
- setupChoiceDescLocal:
- '在这台电脑上安装 Hermes,或连接到已在运行的 Hermes 网关。',
+ setupChoiceDescLocal: '在这台电脑上安装 Hermes,或连接到已在运行的 Hermes 网关。',
installLocalTitle: '本地安装 Hermes',
installLocalDesc: '下载 Hermes,创建 Python 环境,并在这台电脑上运行后端。',
diff --git a/apps/desktop/src/lib/distribution-label.ts b/apps/desktop/src/lib/distribution-label.ts
index f51c8f29d4d..e93ddae883b 100644
--- a/apps/desktop/src/lib/distribution-label.ts
+++ b/apps/desktop/src/lib/distribution-label.ts
@@ -61,6 +61,7 @@ export function distributionLabelKey(version: DistributionLabelInput): Distribut
if (version.installedByScript) {
return 'versionDetailsDistributionSourceInstaller'
}
+
return version.source && version.source !== 'unknown' ? 'versionDetailsDistributionSource' : null
}
diff --git a/apps/desktop/src/lib/update-copy.test.ts b/apps/desktop/src/lib/update-copy.test.ts
index 1eef990e245..3e33e266d24 100644
--- a/apps/desktop/src/lib/update-copy.test.ts
+++ b/apps/desktop/src/lib/update-copy.test.ts
@@ -56,10 +56,13 @@ describe('resolveUpdateCopy', () => {
expect(r.body).toBe(copy.availableBody)
})
- 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)
- })
+ 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)
+ }
+ )
it('app-installer mechanism with a known tag names the release', () => {
const r = resolveUpdateCopy({
@@ -79,7 +82,14 @@ describe('resolveUpdateCopy', () => {
})
it('macOS feed updates name the release without Windows or commit vocabulary', () => {
- expect(resolveUpdateCopy({ target: 'client', shownItems: 0, mechanism: 'electron-updater', latestTag: 'v0.29.0-canary.20260906000000', copy }).body)
- .toBe(copy.availableBodyRelease('v0.29.0-canary.20260906000000'))
+ expect(
+ resolveUpdateCopy({
+ target: 'client',
+ shownItems: 0,
+ mechanism: 'electron-updater',
+ latestTag: 'v0.29.0-canary.20260906000000',
+ copy
+ }).body
+ ).toBe(copy.availableBodyRelease('v0.29.0-canary.20260906000000'))
})
})
diff --git a/apps/desktop/src/lib/update-copy.ts b/apps/desktop/src/lib/update-copy.ts
index 532461aee38..e9d3a543df0 100644
--- a/apps/desktop/src/lib/update-copy.ts
+++ b/apps/desktop/src/lib/update-copy.ts
@@ -40,7 +40,14 @@ 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' | 'microsoft-store' | 'windows-handoff' | 'posix-handoff' | 'manual'
+ mechanism?:
+ | 'app-installer'
+ | 'electron-updater'
+ | 'external'
+ | 'microsoft-store'
+ | 'windows-handoff'
+ | 'posix-handoff'
+ | 'manual'
copy: UpdateCopyStrings
}
diff --git a/apps/desktop/src/lib/version-status.test.ts b/apps/desktop/src/lib/version-status.test.ts
index 735f16c8d16..61c157a7535 100644
--- a/apps/desktop/src/lib/version-status.test.ts
+++ b/apps/desktop/src/lib/version-status.test.ts
@@ -106,8 +106,13 @@ describe('resolveVersionStatus', () => {
})
it('stable channel never names a branch (a stable checkout sits on a tag)', () => {
- const tooltip = client({ behind: 1, branch: 'main', channel: 'stable', latestTag: 'v0.18.0', version: '0.4.2' })
- .tooltip
+ const tooltip = client({
+ behind: 1,
+ branch: 'main',
+ channel: 'stable',
+ latestTag: 'v0.18.0',
+ version: '0.4.2'
+ }).tooltip
expect(tooltip).not.toContain('main')
expect(tooltip).toContain(`${copy.releaseAvailable('v0.18.0')}`)
diff --git a/apps/desktop/src/store/local-models-surfaces.test.tsx b/apps/desktop/src/store/local-models-surfaces.test.tsx
index 704805ab350..56f4652cff0 100644
--- a/apps/desktop/src/store/local-models-surfaces.test.tsx
+++ b/apps/desktop/src/store/local-models-surfaces.test.tsx
@@ -89,8 +89,18 @@ let jobs: LocalRuntimeJob[] = []
let catalog: LocalCatalogModel[] = []
const model: LocalCatalogModel = {
- id: 'model', display_name: 'Download A', description: '', size_bytes: 2, size_label: '2 B',
- native_context: 4096, native_context_label: '4K', recommended: true, downloaded: false, fits: true, mtp: false, fit_summary: 'fits'
+ id: 'model',
+ display_name: 'Download A',
+ description: '',
+ size_bytes: 2,
+ size_label: '2 B',
+ native_context: 4096,
+ native_context_label: '4K',
+ recommended: true,
+ downloaded: false,
+ fits: true,
+ mtp: false,
+ fit_summary: 'fits'
}
const api = vi.fn(async (request: HermesApiRequest): Promise<unknown> => {
@@ -109,7 +119,12 @@ const api = vi.fn(async (request: HermesApiRequest): Promise<unknown> => {
if (request.path.endsWith('/download/pause') || request.path.endsWith('/download/resume')) {
expect(request).toMatchObject({ connectionId: 'A', profile: 'work', method: 'POST', body: { job_id: 'same-id' } })
const paused: boolean = request.path.endsWith('/pause')
- jobs = jobs.map((job: LocalRuntimeJob): LocalRuntimeJob => ({ ...job, status: paused ? 'paused' : 'running', can_pause: !paused, can_resume: paused }))
+ jobs = jobs.map((job: LocalRuntimeJob): LocalRuntimeJob => ({
+ ...job,
+ status: paused ? 'paused' : 'running',
+ can_pause: !paused,
+ can_resume: paused
+ }))
return paused ? { ok: true, paused: true } : { ok: true, resumed: true }
}
@@ -381,32 +396,42 @@ it('keeps menu focus and its scalar selection stable across byte updates and out
expect(window.document.activeElement).toBe(input)
})
-it.each(['model-download', 'quickstart', 'runtime-install'] as const)('%s pause and resume travel through the owner API and publish server truth', async (kind: LocalRuntimeJob['kind']): Promise<void> => {
- catalog = [model]
- jobs = [{ ...running, kind, can_pause: true, phase: kind === 'runtime-install' ? 'downloading-runtime' : 'downloading' }]
- const settings: RenderResult = mountSettings()
- await tick()
- fireEvent.click(screen.getByRole('button', { name: /pause/i }))
- await tick()
- expect(jobs[0].status).toBe('paused')
- expect(screen.getByRole('button', { name: /resume/i })).toBeTruthy()
- expect(screen.getAllByText(/paused/i).length).toBeGreaterThan(0)
- expect(screen.getAllByRole('progressbar').some((bar: HTMLElement): boolean => bar.getAttribute('aria-valuenow') === '50')).toBe(true)
- expect(notify).not.toHaveBeenCalled()
- expect(notifyError).not.toHaveBeenCalled()
+it.each(['model-download', 'quickstart', 'runtime-install'] as const)(
+ '%s pause and resume travel through the owner API and publish server truth',
+ async (kind: LocalRuntimeJob['kind']): Promise<void> => {
+ catalog = [model]
+ jobs = [
+ { ...running, kind, can_pause: true, phase: kind === 'runtime-install' ? 'downloading-runtime' : 'downloading' }
+ ]
+ const settings: RenderResult = mountSettings()
+ await tick()
+ fireEvent.click(screen.getByRole('button', { name: /pause/i }))
+ await tick()
+ expect(jobs[0].status).toBe('paused')
+ expect(screen.getByRole('button', { name: /resume/i })).toBeTruthy()
+ expect(screen.getAllByText(/paused/i).length).toBeGreaterThan(0)
+ expect(
+ screen.getAllByRole('progressbar').some((bar: HTMLElement): boolean => bar.getAttribute('aria-valuenow') === '50')
+ ).toBe(true)
+ expect(notify).not.toHaveBeenCalled()
+ expect(notifyError).not.toHaveBeenCalled()
- if (kind === 'quickstart') { expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull() }
- fireEvent.click(screen.getByRole('button', { name: /resume/i }))
- await tick()
- expect(jobs[0].status).toBe('running')
- expect(api.mock.calls.filter(([request]): boolean => request.method === 'POST').map(([request]): string => request.path))
- .toEqual(['/api/local-models/download/pause', '/api/local-models/download/resume'])
- jobs = [{ ...jobs[0], status: 'done' }]
- await tick(3_000)
- expect(notify).toHaveBeenCalledTimes(1)
- settings.unmount()
- watchLocalRuntimeJobs({ connectionId: 'A', profile: 'work' })
- await tick()
- expect(notify).toHaveBeenCalledTimes(1)
- expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status')).length).toBeGreaterThan(1)
-})
+ if (kind === 'quickstart') {
+ expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()
+ }
+ fireEvent.click(screen.getByRole('button', { name: /resume/i }))
+ await tick()
+ expect(jobs[0].status).toBe('running')
+ expect(
+ api.mock.calls.filter(([request]): boolean => request.method === 'POST').map(([request]): string => request.path)
+ ).toEqual(['/api/local-models/download/pause', '/api/local-models/download/resume'])
+ jobs = [{ ...jobs[0], status: 'done' }]
+ await tick(3_000)
+ expect(notify).toHaveBeenCalledTimes(1)
+ settings.unmount()
+ watchLocalRuntimeJobs({ connectionId: 'A', profile: 'work' })
+ await tick()
+ expect(notify).toHaveBeenCalledTimes(1)
+ expect(api.mock.calls.filter(([request]): boolean => request.path.endsWith('/status')).length).toBeGreaterThan(1)
+ }
+)
diff --git a/apps/desktop/src/store/local-runtime-jobs.ts b/apps/desktop/src/store/local-runtime-jobs.ts
index 1dbadc9d33b..991effcbae2 100644
--- a/apps/desktop/src/store/local-runtime-jobs.ts
+++ b/apps/desktop/src/store/local-runtime-jobs.ts
@@ -16,7 +16,13 @@ import { useEffect, useMemo } from 'react'
import { $apiRequestScope, getApiRequestConnection, getApiRequestProfile } from '@/api/client'
import type { LocalModelsScope } from '@/api/local-models'
-import { getLocalCatalog, getLocalHardware, getLocalModelsJobs, getLocalModelsStatus, installLocalRuntime } from '@/hermes'
+import {
+ getLocalCatalog,
+ getLocalHardware,
+ getLocalModelsJobs,
+ getLocalModelsStatus,
+ installLocalRuntime
+} from '@/hermes'
import { translateNow } from '@/i18n'
import { queryClient } from '@/lib/query-client'
import { useStoresSelector } from '@/lib/use-session-slice'
@@ -401,19 +407,31 @@ interface RuntimeInstallResult {
tag: string
}
-export function localRuntimeInstallStarting(owner: LocalModelsOwner = localModelsOwner(), client: QueryClient = queryClient): boolean {
+export function localRuntimeInstallStarting(
+ owner: LocalModelsOwner = localModelsOwner(),
+ client: QueryClient = queryClient
+): boolean {
return client.isMutating({ mutationKey: localModelsKey(owner, 'install') }) > 0
}
-export function localRuntimeInstallBusy(owner: LocalModelsOwner = localModelsOwner(), client: QueryClient = queryClient): boolean {
+export function localRuntimeInstallBusy(
+ owner: LocalModelsOwner = localModelsOwner(),
+ client: QueryClient = queryClient
+): boolean {
const jobs: readonly LocalRuntimeJob[] = client.getQueryData(localModelsKey(owner, 'jobs')) ?? EMPTY_JOBS
- return localRuntimeInstallStarting(owner, client) || jobs.some((job: LocalRuntimeJob): boolean =>
- isActive(job.status) && (job.kind === 'runtime-install' || job.kind === 'quickstart'))
+ return (
+ localRuntimeInstallStarting(owner, client) ||
+ jobs.some(
+ (job: LocalRuntimeJob): boolean =>
+ isActive(job.status) && (job.kind === 'runtime-install' || job.kind === 'quickstart')
+ )
+ )
}
export async function startLocalRuntimeInstall(
- owner: LocalModelsOwner = localModelsOwner(), client: QueryClient = queryClient
+ owner: LocalModelsOwner = localModelsOwner(),
+ client: QueryClient = queryClient
): Promise<void> {
if (localRuntimeInstallBusy(owner, client)) {
return
diff --git a/apps/desktop/src/store/notifications.test.ts b/apps/desktop/src/store/notifications.test.ts
index facbb830223..70383a70dc8 100644
--- a/apps/desktop/src/store/notifications.test.ts
+++ b/apps/desktop/src/store/notifications.test.ts
@@ -120,19 +120,29 @@ test('notifyError posts the full error to desktop.log, not the summary', () => {
}
})
-test.each(['missing', 'closed'] as const)('notifyError still shows a toast when the log bridge is %s', (state: 'missing' | 'closed'): void => {
- vi.stubGlobal('hermesDesktop', state === 'missing' ? undefined : {
- logLine: (): never => { throw new Error('IPC channel closed') }
- })
-
- try {
- const id: string = notifyError(new Error('database is locked'), 'Prompt failed')
-
- expect($notifications.get()[0]).toMatchObject({ id, kind: 'error', message: 'database is locked' })
- } finally {
- vi.unstubAllGlobals()
+test.each(['missing', 'closed'] as const)(
+ 'notifyError still shows a toast when the log bridge is %s',
+ (state: 'missing' | 'closed'): void => {
+ vi.stubGlobal(
+ 'hermesDesktop',
+ state === 'missing'
+ ? undefined
+ : {
+ logLine: (): never => {
+ throw new Error('IPC channel closed')
+ }
+ }
+ )
+
+ try {
+ const id: string = notifyError(new Error('database is locked'), 'Prompt failed')
+
+ expect($notifications.get()[0]).toMatchObject({ id, kind: 'error', message: 'database is locked' })
+ } finally {
+ vi.unstubAllGlobals()
+ }
}
-})
+)
test('code-skew 503 unwraps to a restart-required summary, not raw IPC JSON', () => {
notifyError(
diff --git a/apps/desktop/src/store/notifications.ts b/apps/desktop/src/store/notifications.ts
index 8a4dbbf187b..bc1c6d80cde 100644
--- a/apps/desktop/src/store/notifications.ts
+++ b/apps/desktop/src/store/notifications.ts
@@ -251,7 +251,8 @@ export function notify(input: NotificationInput): string {
function logErrorToDesktopLog(error: unknown, fallback: string): void {
try {
const label: string = new URLSearchParams(window.location.search).get('win') ?? 'main'
- const raw: string = error instanceof Error ? (error.stack ?? error.message) : typeof error === 'string' ? error : fallback
+ const raw: string =
+ error instanceof Error ? (error.stack ?? error.message) : typeof error === 'string' ? error : fallback
window.hermesDesktop?.logLine?.(`[renderer error:${label}] ${fallback}: ${raw}`)
} catch {
diff --git a/apps/desktop/src/store/onboarding-never-forces-sign-in.test.ts b/apps/desktop/src/store/onboarding-never-forces-sign-in.test.ts
index 013da475d3c..539a5a2857d 100644
--- a/apps/desktop/src/store/onboarding-never-forces-sign-in.test.ts
+++ b/apps/desktop/src/store/onboarding-never-forces-sign-in.test.ts
@@ -46,13 +46,18 @@ it.each(['cinematic', 'guided', 'handoff'])('the provider picker never opens ove
expect(onboarding.$desktopOnboarding.get().requested).toBe(false)
})
-it.each(['cinematic', 'guided', 'handoff'])('a credential warning during the guide is dropped, not deferred (%s)', async phase => {
- const { onboarding } = await load(phase)
+it.each(['cinematic', 'guided', 'handoff'])(
+ 'a credential warning during the guide is dropped, not deferred (%s)',
+ async phase => {
+ const { onboarding } = await load(phase)
- onboarding.requestDesktopOnboardingForCredentialWarning("No API key configured for provider 'nous'. First message will fail.")
+ onboarding.requestDesktopOnboardingForCredentialWarning(
+ "No API key configured for provider 'nous'. First message will fail."
+ )
- expect(onboarding.consumePendingCredentialWarning()).toBeNull()
-})
+ expect(onboarding.consumePendingCredentialWarning()).toBeNull()
+ }
+)
it.each(['idle', 'skipped', 'done'])('outside the guide the picker opens as before (%s)', async phase => {
const { onboarding } = await load(phase)
diff --git a/apps/desktop/src/store/updates.test.ts b/apps/desktop/src/store/updates.test.ts
index aa9efd3035c..d7cf820f3ee 100644
--- a/apps/desktop/src/store/updates.test.ts
+++ b/apps/desktop/src/store/updates.test.ts
@@ -153,7 +153,11 @@ describe('gateway version refresh', () => {
setApiRequestProfile('work')
const version: DesktopVersionInfo = {
- appVersion: '4.5.6', electronVersion: '40', nodeVersion: '26', platform: 'win32', hermesRoot: ''
+ appVersion: '4.5.6',
+ electronVersion: '40',
+ nodeVersion: '26',
+ platform: 'win32',
+ hermesRoot: ''
}
const getVersion = vi.fn().mockResolvedValue(version)
@@ -165,7 +169,12 @@ describe('gateway version refresh', () => {
expect(getVersion).toHaveBeenCalledWith({ connectionId: 'remote-box', profile: 'work' })
expect($desktopVersion.get()?.appVersion).toBe('4.5.6')
let finish!: (value: DesktopVersionInfo) => void
- getVersion.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
+ getVersion.mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ finish = resolve
+ })
+ )
const pending = refreshDesktopVersion()
setRemote(false)
$desktopVersion.set(null)
@@ -215,10 +224,20 @@ describe('maybeNotifyUpdateAvailable', () => {
})
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 }))
+ 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' }))
+ maybeNotifyUpdateAvailable(
+ status({
+ mechanism: 'microsoft-store',
+ targetSha: undefined,
+ behind: null,
+ updateAvailable: false,
+ error: 'Store unavailable'
+ })
+ )
expect(notifySpy).not.toHaveBeenCalled()
})
@@ -934,7 +953,6 @@ describe('applyUpdates terminal state', () => {
expect($updateApply.get().error).toBe('rebuild-failed')
})
-
it('keeps the manual command state for CLI installs with no staged updater', async () => {
applyMock.mockResolvedValue({ ok: true, manual: true, command: 'hermes update' })
diff --git a/apps/desktop/src/store/updates.ts b/apps/desktop/src/store/updates.ts
index 53502b00920..39251f5d7fa 100644
--- a/apps/desktop/src/store/updates.ts
+++ b/apps/desktop/src/store/updates.ts
@@ -9,7 +9,6 @@ import { connectionScoped, profileScoped } from '@/api/client'
import type {
DesktopUpdateApplyOptions,
DesktopUpdateApplyResult,
-
DesktopUpdateProgress,
DesktopUpdateStage,
DesktopUpdateStatus,
@@ -228,7 +227,8 @@ export function maybeNotifyUpdateAvailable(status: DesktopUpdateStatus | null, t
// 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'
+ const hasTargetIdentity =
+ Boolean(status.targetSha) || status.mechanism === 'app-installer' || status.mechanism === 'microsoft-store'
if (!hasTargetIdentity) {
return
@@ -288,8 +288,13 @@ export function dismissDiscontinuedNotice(retirement: NonNullable<DesktopUpdateS
* revision; a fresh retirement re-notifies.
*/
function maybeNotifyDiscontinued(retirement: NonNullable<DesktopUpdateStatus['retirement']>): void {
- if (retirement.state !== 'discontinued') { return }
- if (storedString(DISCONTINUED_DISMISS_KEY) === discontinuedDismissKey(retirement)) { return }
+ if (retirement.state !== 'discontinued') {
+ return
+ }
+
+ if (storedString(DISCONTINUED_DISMISS_KEY) === discontinuedDismissKey(retirement)) {
+ return
+ }
notify({
action: {
@@ -408,7 +413,9 @@ export async function refreshDesktopVersion(): Promise<DesktopVersionInfo | null
const connection = $connection.get()
const next = await window.hermesDesktop?.getVersion?.({ ...connectionScoped(), ...profileScoped() })
- if ($connection.get() !== connection) { return null }
+ if ($connection.get() !== connection) {
+ return null
+ }
if (next) {
$desktopVersion.set(next)
@@ -487,7 +494,10 @@ export async function checkUpdates({ force = false }: UpdateCheckOptions = {}):
try {
const status = await bridge.check({ force })
$updateStatus.set(status)
- if (status.retirement) { maybeNotifyDiscontinued(status.retirement) }
+
+ if (status.retirement) {
+ maybeNotifyDiscontinued(status.retirement)
+ }
maybeNotifyUpdateAvailable(status, 'client')
void refreshDesktopVersion()
@@ -590,7 +600,9 @@ export async function applyUpdates(opts: DesktopUpdateApplyOptions = {}): Promis
setUpdateOverlayOpen(false)
resetUpdateApplyState()
- if (result.updateAvailable === false) { return result }
+ if (result.updateAvailable === false) {
+ return result
+ }
notify({
durationMs: 8000,
id: UPDATE_TOAST_ID,