The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fmt(js): `npm run fix` on merge (#95969)
hermes-seaeye[bot]79b8703d005f
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 49f74093595..1f1c86b22ed 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -9817,7 +9817,6 @@ function clearManagedSshRecovery(connectionId, correlationId) {}}-const sshBootstrapCoordinator = createBootstrapCoordinator()let sshQuitTeardownDone = false@@ -10036,7 +10035,14 @@ async function effectiveSshConfigFingerprint(sshConfig) {return crypto.createHash('sha256').update(output).digest('hex')}-async function bootstrapSshConnection(profile, sshConfig, reuseToken, source, resolvedEffectiveFingerprint?, metadata: any = {}) {+async function bootstrapSshConnection(+ profile,+ sshConfig,+ reuseToken,+ source,+ resolvedEffectiveFingerprint?,+ metadata: any = {}+) {const scope = sshScopeKey(profile)const effectiveConfigFingerprint = resolvedEffectiveFingerprint || (await effectiveSshConfigFingerprint(sshConfig))const resolvedConfig = { ...sshConfig, effectiveConfigFingerprint }diff --git a/apps/desktop/electron/managed-ssh-update.test.ts b/apps/desktop/electron/managed-ssh-update.test.tsindex ad95861ac58..9f224029316 100644--- a/apps/desktop/electron/managed-ssh-update.test.ts+++ b/apps/desktop/electron/managed-ssh-update.test.ts@@ -76,11 +76,14 @@ test('inactive SSH crash recovery keeps ordinary dials fenced until positive clelet durableOwner: string | null = CORRELATIONconst relaunchedGate = new ManagedConnectionUpdateGate(id => (id === 'homelab' ? durableOwner : null))let releaseClearance!: () => void+const clearance = new Promise<void>(resolve => {releaseClearance = resolve})+let restoreCalls = 0let journalCleared = false+const recovery = recoverManagedSshScopes({scopes: [] as Array<{ profile: string }>,awaitClearance: () => clearance,@@ -109,11 +112,14 @@ test('managed update joins a pre-claim bootstrap until its final gate check rollconst gate = new ManagedConnectionUpdateGate()const coordinator = createBootstrapCoordinator()let releaseLifecycle!: () => void+const lifecycle = new Promise<void>(resolve => {releaseLifecycle = resolve})+let serveLive = falselet rollbackComplete = false+const startPromise = coordinator.start('','fingerprint',@@ -131,6 +137,7 @@ test('managed update joins a pre-claim bootstrap until its final gate check roll},{ managedScope: 'primary', registryConnectionId: 'homelab' })+// The fence rethrows managed-update-in-progress after rolling back — that// rejection propagating out of start() is the CONTRACT under test, not an// accident. Swallow it here so vitest doesn't flag the floating promise as@@ -286,6 +293,7 @@ test('POSIX managed launcher executes the updater command and atomically publish},CORRELATION)+const { stdout } = await exec(command, { shell: '/bin/sh' })const statusPath = path.join(home, `.update_exit_code.${CORRELATION}`)let status = ''@@ -316,6 +324,7 @@ test('Windows managed launcher starts a hidden child and leaves exit 75 to the e},CORRELATION)+const outer = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')const wrapperBase64 = outer.match(/"-EncodedCommand",'([^']+)'/)?.[1]@@ -368,6 +377,7 @@ test('POSIX observer reads the exact correlation receipt and terminal marker fropost_update: { sha: 'new' }}))+const command = buildRemoteUpdateObservationCommand({ssh: { exec: async () => '' },@@ -377,6 +387,7 @@ test('POSIX observer reads the exact correlation receipt and terminal marker fro},CORRELATION)+const { stdout } = await exec(command, { shell: '/bin/sh' })const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)@@ -397,6 +408,7 @@ test('managed observer unwraps a named profile home for the install-wide marker'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 () => '' },@@ -406,6 +418,7 @@ test('managed observer unwraps a named profile home for the install-wide marker'},CORRELATION)+const { stdout } = await exec(command, { shell: '/bin/sh' })const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)@@ -435,7 +448,9 @@ test('Windows coordinator handoff is pending until its marker clears and correlacoordinatorReady: { correlationId: CORRELATION, pid: 88 }})]+let calls = 0+const target = {platform: 'Windows' as const,hermesPath: 'C:\\Hermes\\hermes.exe',@@ -463,6 +478,7 @@ test('Windows coordinator handoff is pending until its marker clears and correlatest('terminal status without its durable receipt fails instead of claiming success', async () => {let now = 0+const target = {platform: 'Linux' as const,hermesPath: '~/.local/bin/hermes',@@ -485,12 +501,14 @@ test('terminal status without its durable receipt fails instead of claiming succtest('live or malformed remote markers fail actionably at bounded update and recovery deadlines', async () => {for (const marker of ['live', 'malformed'] as const) {let now = 0+const target = {platform: 'Linux' as const,hermesPath: '~/.local/bin/hermes',hermesHome: '~/.hermes',ssh: { exec: async () => observation({ marker, ...(marker === 'live' ? { markerPid: 44 } : {}) }) }}+const clock = {timeoutMs: 5,pollMs: 1,@@ -508,6 +526,7 @@ test('live or malformed remote markers fail actionably at bounded update and rectest('a journaled launch requires correlated terminal proof or an observed live-owner transition before restore', async () => {let now = 0+const target = {platform: 'Linux' as const,hermesPath: '~/.local/bin/hermes',@@ -541,6 +560,7 @@ test('a journaled launch requires correlated terminal proof or an observed live-test('remote launch intent fences crash recovery even before the local journal records launch proof', async () => {let now = 0+const target = {platform: 'Linux' as const,hermesPath: '~/.local/bin/hermes',@@ -572,11 +592,14 @@ test('before-quit join observes operations added while an earlier update settleslet releaseFirst!: () => voidlet releaseSecond!: () => voidconst operations = new Set<Promise<void>>()+const first = new Promise<void>(resolve => {releaseFirst = resolve})+operations.add(first)const joined = waitForManagedUpdateOperations(() => operations)+const second = new Promise<void>(resolve => {releaseSecond = resolve})@@ -599,6 +622,7 @@ test('before-quit join observes operations added while an earlier update settlestest('managed lifecycle restores every captured profile after update failure before releasing the gate', async () => {const events: string[] = []+const scopes = [{ key: 'conn:home::default', profile: 'default' },{ key: 'conn:home::research', profile: 'research' }@@ -658,6 +682,7 @@ test('managed lifecycle restores every captured profile after update failure beftest('inactive managed update journals before launch and clears only after remote clearance', async () => {const events: string[] = []+const result = await runManagedSshUpdate({connectionId: 'homelab',correlationId: CORRELATION,@@ -716,6 +741,7 @@ test('managed lifecycle attempts every drain and every restore when one ownershipreflightRemote: async () => {},drainScope: async scope => {drained.push(scope.profile)+if (scope.profile === 'default') {throw new Error('foreign owner')}@@ -744,6 +770,7 @@ test('managed lifecycle attempts every drain and every restore when one ownershitest('managed lifecycle journals before drain and leaves scopes stopped when clearance cannot be proved', async () => {const events: string[] = []+const result = await runManagedSshUpdate({connectionId: 'home',correlationId: CORRELATION,@@ -815,6 +842,7 @@ test('journal cleanup failure prevents a false successful update result', asynctest('preflight refusal leaves a healthy primary scope untouched and releases without waiting', async () => {const events: string[] = []+const result = await runManagedSshUpdate({connectionId: 'home',correlationId: CORRELATION,diff --git a/apps/desktop/electron/managed-ssh-update.ts b/apps/desktop/electron/managed-ssh-update.tsindex 2425e2f2b1c..3efb3b791e0 100644--- a/apps/desktop/electron/managed-ssh-update.ts+++ b/apps/desktop/electron/managed-ssh-update.ts@@ -153,6 +153,7 @@ function managedSshScopeRole(input: {if (input.state?.registryConnectionId === input.connectionId) {return input.state.primaryRegistryScope === true ? 'primary' : 'pool'}+if (input.key.startsWith(input.prefix) || input.routeConnectionId === input.connectionId) {return 'pool'}@@ -175,6 +176,7 @@ function managedSshRecoveryScopes(for (const scope of scopes) {const key = String(scope.key)const existing = unique.get(key)+const next = {key,kind: scope.primary ? 'primary' : key.startsWith(registryPrefix) ? 'registry' : 'legacy',@@ -218,6 +220,7 @@ function buildPosixManagedUpdateLaunch(target: RemoteUpdateTarget, correlationIdconst intentWord = expandRemotePath(intentPath)const outputWord = expandRemotePath(outputPath)const launcherWord = expandRemotePath(hermesPath)+const updateCommand =`env HERMES_HOME=${homeWord} ` +`HERMES_UPDATE_CORRELATION_ID=${shq(correlation)} ` +@@ -225,6 +228,7 @@ function buildPosixManagedUpdateLaunch(target: RemoteUpdateTarget, correlationId`HERMES_UPDATE_ORIGIN_HOME=${homeWord} ` +`HERMES_UPDATE_OUTPUT_PATH=${outputWord} ` +`${launcherWord} update --yes`+const inner =`set +e; if [ -r "/proc/$$/stat" ]; then ` +`intent_creation="linux:$(awk '{print $22}' "/proc/$$/stat")"; ` +@@ -257,6 +261,7 @@ function buildWindowsManagedUpdateLaunch(target: RemoteUpdateTarget, correlationconst readyPath = windowsChildPath(home, `.update_coordinator_ready.${correlation}`)const intentPath = windowsChildPath(home, `.update_launch_intent.${correlation}`)const outputPath = windowsChildPath(home, `logs\\desktop-update-${correlation}.log`)+const wrapper = ['$ErrorActionPreference="Continue"',`$env:HERMES_HOME=${psLiteral(home)}`,@@ -288,6 +293,7 @@ function buildWindowsManagedUpdateLaunch(target: RemoteUpdateTarget, correlation'}','exit $rc'].join(';')+const outer = ['$ErrorActionPreference="Stop"',`$output=${psLiteral(outputPath)}`,@@ -453,6 +459,7 @@ function buildRemoteUpdateObservationCommand(target: RemoteUpdateTarget, correlaif (target.platform === 'Windows') {const python = validateRemoteValue(target.pythonPath || '', 'Python path')+const script = ['$ErrorActionPreference="Stop"',`& ${psLiteral(python)} -c ${psLiteral(OBSERVATION_SCRIPT)} ${psLiteral(home)} ${psLiteral(correlation)}`,@@ -509,6 +516,7 @@ function parseRemoteUpdateObservation(raw: string, correlationId: string): Remot) {throw new Error('Remote update receipt did not match this transaction.')}+receipt = parsed.receipt as ManagedUpdateReceiptSummary}@@ -525,6 +533,7 @@ function parseRemoteUpdateObservation(raw: string, correlationId: string): Remot) {throw new Error('Remote update coordinator readiness proof was malformed.')}+coordinatorReady = { correlationId: correlation, pid }}@@ -572,6 +581,7 @@ async function launchManagedRemoteUpdate(target: RemoteUpdateTarget, correlationtarget.platform === 'Windows'? buildWindowsManagedUpdateLaunch(target, correlationId): buildPosixManagedUpdateLaunch(target, correlationId)+const output = await target.ssh.exec(command, { timeoutMs: 30_000 })if (target.platform === 'Windows') {@@ -583,6 +593,7 @@ async function launchManagedRemoteUpdate(target: RemoteUpdateTarget, correlation.trim().split(/\r?\n/).filter(Boolean)+parsed = JSON.parse(lines.at(-1) || 'null')} catch {parsed = null@@ -622,7 +633,9 @@ async function waitForManagedRemoteUpdate(if (now() >= deadline) {throw error}+await sleep(pollMs)+continue}@@ -633,7 +646,9 @@ async function waitForManagedRemoteUpdate('services remain stopped and Desktop recorded them for safe recovery.')}+await sleep(pollMs)+continue}@@ -741,6 +756,7 @@ async function waitForManagedRemoteClearance('services were not restarted and Desktop retained a durable recovery record.')}+await sleep(pollMs)}}@@ -753,6 +769,7 @@ function resultOutcome(updateOk: boolean, restoreOk: boolean): ManagedUpdateOutcif (updateOk && restoreOk) {return 'updated'}+if (!updateOk && !restoreOk) {return 'update-and-restore-failed'}@@ -782,17 +799,21 @@ async function runManagedSshUpdate<TScope extends ManagedSshScope>(const drainErrors: string[] = []restoreNeedsMarkerFence = scopes.length > 0+for (const scope of scopes) {restoreCandidates.add(scope)+try {await deps.drainScope(scope)} catch (error) {drainErrors.push(`${scope.profile}: ${errorMessage(error)}`)}}+if (drainErrors.length) {throw new Error(`Could not safely drain every managed SSH scope (${drainErrors.join('; ')}).`)}+// A zero-scope update still launches a mutator, so any subsequent error// must wait for its marker to clear before closing the update transport.restoreNeedsMarkerFence = true@@ -812,6 +833,7 @@ async function runManagedSshUpdate<TScope extends ManagedSshScope>(updateError = [updateError, restorationBlocked].filter(Boolean).join(' ')}}+try {await deps.closeTransports()} catch (error) {@@ -934,6 +956,7 @@ async function fenceManagedSshBootstrapPublication<T>(deps: {}): Promise<T> {try {deps.assertCanPublish()+// Deliberately no await between the final gate assertion and publication:// both run in this JavaScript turn, so a queued update claim either lands// before the assertion (and triggers rollback) or after the scope is@@ -951,6 +974,7 @@ async function waitForManagedSshBootstrapFence(): Promise<void> {const pending = [...entries].filter(entry => entry.metadata?.registryConnectionId === connectionId)const results = await Promise.allSettled(pending.map(entry => entry.promise))+const unsafe = results.find(result => result.status === 'rejected' && (result.reason as any)?.unsafeManagedBootstrap === true)@@ -973,6 +997,7 @@ class ManagedConnectionUpdateGate {if (!id || this.claims.has(id) || (durable && durable !== correlation)) {return false}+this.claims.set(id, correlation)return true@@ -1005,6 +1030,7 @@ class ManagedConnectionUpdateGate {const error: any = new Error(`SSH connection "${id}" cannot be edited or removed while its managed update recovery is pending.`)+error.code = 'managed-update-in-progress'throw error}diff --git a/apps/desktop/electron/remote-lifecycle.test.ts b/apps/desktop/electron/remote-lifecycle.test.tsindex 932c6c2c385..db473b3a93a 100644--- a/apps/desktop/electron/remote-lifecycle.test.ts+++ b/apps/desktop/electron/remote-lifecycle.test.ts@@ -99,6 +99,7 @@ function fakeSsh(rules: any[] = []) {}const mutexWrapped = cmd.includes('fcntl.flock(fd,fcntl.LOCK_EX)')+const applicableRules = rules.filter(([matcher]) => {if (cmd.includes('marker_clear()') && matcher instanceof RegExp && /kill -0/.test(matcher.source)) {return false@@ -110,6 +111,7 @@ function fakeSsh(rules: any[] = []) {if ((cmd.includes('os.kill(pid') && !cmd.includes('pidfd_open')) || cmd.includes('printf TERMINATED')) {return 'TERMINATED'}+for (const [matcher, resp] of applicableRules) {const hit = typeof matcher === 'function' ? matcher(cmd) : matcher.test(cmd)@@ -132,6 +134,7 @@ function fakeSsh(rules: any[] = []) {test('POSIX relaunch gate refuses live and uncertain install markers without executing Hermes', async () => {for (const observation of ['LIVE:4242', 'UNCERTAIN']) {const calls: string[] = []+const ssh = {async exec(command) {calls.push(command)@@ -139,12 +142,15 @@ test('POSIX relaunch gate refuses live and uncertain install markers without exeif (command === 'uname -s; uname -m') {return 'Linux\nx86_64\n'}+if (command.includes('HERMES_HOME')) {return '/home/alice/.hermes\n'}+if (command.includes('.hermes-update-in-progress')) {return observation}+throw new Error(`unexpected command after update gate: ${command}`)}}@@ -162,6 +168,7 @@ test('POSIX relaunch gate refuses live and uncertain install markers without exetest('POSIX relaunch gate permits absent/dead markers and normalizes named-profile homes install-wide', async () => {const commands: string[] = []+const ssh = {async exec(command) {commands.push(command)@@ -179,6 +186,7 @@ test('POSIX relaunch gate permits absent/dead markers and normalizes named-profitest('POSIX relaunch gate rechecks after token upload immediately before process creation', async () => {const calls: string[] = []let markerChecks = 0+const ssh = {async exec(command) {calls.push(command)@@ -186,23 +194,29 @@ test('POSIX relaunch gate rechecks after token upload immediately before processif (command === 'uname -s; uname -m') {return 'Linux\nx86_64\n'}+if (command.includes('HERMES_HOME')) {return '/home/alice/.hermes\n'}+if (command.includes('.hermes-update-in-progress')) {markerChecks += 1return markerChecks >= 3 ? 'LIVE:4242' : 'CLEAR'}+if (/\[ -x /.test(command)) {return 'OK'}+if (command.includes('serve --help')) {return 'YES\n'}+if (command.includes('python3 -c')) {return ''}+if (command.includes('lock.json')) {return ''}@@ -739,6 +753,7 @@ test('cleanupStale kills ONLY a provably-ours pid, always drops the lockfile', a[/print\("OWNED"/, 'OWNED\n'],[cmd => /printf TERMINATED/.test(cmd), 'TERMINATED\n']])+await cleanupStale(ours, OWNERSHIP_ID, {pid: 9,spawnNonce: SPAWN_NONCE,@@ -799,7 +814,10 @@ test('buildSpawnCommand atomically reserves the ownership slot through spawn andassert.ok(cmd.includes('.hermes-update-in-progress.mutex'))assert.match(cmd, /fcntl\.flock\(fd,fcntl\.LOCK_EX\)/)assert.match(cmd, /os\.O_CLOEXEC/)- assert.match(cmd, /subprocess\.run\(\["sh","-c",payload,"hermes-update-mutex",str\(fd\)\],pass_fds=\(fd,\),check=False\)/)+ assert.match(+ cmd,+ /subprocess\.run\(\["sh","-c",payload,"hermes-update-mutex",str\(fd\)\],pass_fds=\(fd,\),check=False\)/+ )assert.doesNotMatch(cmd, /os\.set_inheritable\(fd,True\)/)assert.match(cmd, /hermes-update-child "\$1"/)assert.match(cmd, /eval "exec \$1>&-"/)@@ -834,17 +852,20 @@ donehermesHome: path.join(directory, 'home'),logPath})+await exec(command, { shell: '/bin/bash' })for (let attempt = 0; attempt < 40; attempt += 1) {try {const report = await readFile(reportPath, 'utf8')assert.equal(report, '', 'the backend process must not retain the update mutex descriptor')+return} catch (error: any) {if (error?.code !== 'ENOENT') {throw error}+await new Promise(resolve => setTimeout(resolve, 25))}}@@ -1195,6 +1216,7 @@ test('connect() respawns when the lockfile pid is dead (killed dashboard)', asyntest('managed update drain preserves a live foreign POSIX owner and its lock bytes', async () => {const lock = ownedLock()const rawLock = JSON.stringify(lock)+const ssh = fakeSsh([[/cat .*lock\.json/, rawLock],[/kill -0 333/, 'ALIVE'],@@ -1219,6 +1241,7 @@ test('managed update drain rechecks the POSIX ownership record before signallingconst lock = ownedLock()const replacement = ownedLock({ pid: 334, spawnNonce: 'fedcba9876543210' })let reads = 0+const ssh = fakeSsh([[/cat .*lock\.json/,@@ -1243,6 +1266,7 @@ test('managed update drain rechecks the POSIX ownership record before signallingtest('managed update drain refuses Darwin termination because PID signals cannot be atomically bound', async () => {const lock = ownedLock()const rawLock = JSON.stringify(lock)+const ssh = fakeSsh([[/cat .*lock\.json/, rawLock],[/kill -0 333/, 'ALIVE'],@@ -1620,6 +1644,7 @@ test('cleanupStale never deletes a lock-supplied unexpected log path', async ()[/print\("OWNED"/, 'OWNED\n'],[cmd => /pidfd_open/.test(cmd), 'TERMINATED\n']])+await cleanupStale(ssh, OWNERSHIP_ID, ownedLock({ logPath: '~/.hermes/unrelated.log' }))assert.ok(!ssh.calls.some(command => command.includes('unrelated.log')))})diff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.tsindex 74a3c4611b1..de19bebb3d2 100644--- a/apps/desktop/electron/remote-lifecycle.ts+++ b/apps/desktop/electron/remote-lifecycle.ts@@ -358,11 +358,13 @@ async function assertRemoteInstallUpdateClear(ssh, hermesHome) {}const live = /^LIVE:([1-9][0-9]*)$/.exec(observation)+const error: any = new Error(live? `Remote Hermes update process ${live[1]} is still running; SSH startup is paused.`: 'The remote Hermes update marker is unreadable or malformed; refusing SSH startup.')+error.kind = 'update-in-progress'throw error}@@ -399,6 +401,7 @@ function assertSafeRemoteHome(home) {function remoteInstallRoot(home) {const value = assertSafeRemoteHome(home)const profile = value.match(/^(.*)\/profiles\/[^/]+$/)+return profile ? profile[1] : value}@@ -738,9 +741,11 @@ function buildOwnedStaleTerminationCommand(lock, ownershipId) {const nonce = shq(lock.spawnNonce)const profile = shq(lock.profile || '')const command = `$(ps -ww -o command= -p ${pid} 2>/dev/null || true)`+const executableMatch = lock.hermesHome? `case "$cmd" in *"$path"*|*"$home"*) ;; *) printf REFUSED; exit 0;; esac; `: `case "$cmd" in *"$path"*) ;; *) printf REFUSED; exit 0;; esac; `+const identity =`cmd=${command}; ` +`path=${expectedPath}; home=${expectedHome}; token=${expectedToken}; nonce=${nonce}; profile=${profile}; ` +@@ -779,6 +784,7 @@ function buildOwnedTerminationCommand(lock, ownershipId) {const pid = Number(lock.pid)const py = value => JSON.stringify(String(value || ''))const expectedToken = spawnTokenPath(ownershipId, lock.spawnNonce)+const script = `import os,select,shlex,signal,subprocess,sys,timepid=${pid}@@ -927,6 +933,7 @@ async function terminateOwnedDashboardForUpdate(ssh, expected) {error.kind = 'ownership-changed'throw error}+let lock = await readLockfile(ssh, ownershipId)if (!lock || !lockMatchesManagedUpdateScope(lock, expected)) {@@ -994,6 +1001,7 @@ async function terminateOwnedDashboardForUpdate(ssh, expected) {if (result === 'ALREADY_STOPPED') {return { pid: lock.pid, terminated: false, alreadyStopped: true }}+if (result !== 'TERMINATED') {const error: any = new Error(result === 'REFUSED'@@ -1002,13 +1010,16 @@ async function terminateOwnedDashboardForUpdate(ssh, expected) {? 'Darwin cannot atomically bind a signal to the verified PID; refusing termination.': 'The remote POSIX signal boundary was unavailable.')- error.kind = result === 'REFUSED' || result === 'DARWIN_UNAVAILABLE' ? 'ownership-changed' : 'transient-transport-error'++ error.kind =+ result === 'REFUSED' || result === 'DARWIN_UNAVAILABLE' ? 'ownership-changed' : 'transient-transport-error'throw error}} catch (cause: any) {if (cause?.kind === 'ownership-changed') {throw cause}+const error: any = new Error('Could not terminate the Desktop-owned remote serve for update.')error.kind = 'transient-transport-error'error.cause = cause@@ -1030,9 +1041,11 @@ function buildSpawnCommand(hermesPath, profile, opts: any = {}) {const ownerArg = opts.spawnNonce ? ` --ssh-owner-nonce ${validateSpawnNonce(opts.spawnNonce)}` : ''const subCmd = `serve --isolated --host 127.0.0.1 --port 0${tokenArg}${ownerArg}`const marker = expandRemotePath(`${remoteInstallRoot(opts.hermesHome || '~/.hermes')}/.hermes-update-in-progress`)+const updateMutex = expandRemotePath(`${remoteInstallRoot(opts.hermesHome || '~/.hermes')}/.hermes-update-in-progress.mutex`)+// The marker probe, ownership reservation, process creation, and initial// lockfile publication must be one remote command. A second Desktop process// can therefore never observe an empty lock and spawn before this one records@@ -1436,6 +1449,7 @@ async function connect(deps) {await writeLockfile(ssh, ownershipId, { ...lock, creationTime })lock.creationTime = creationTime}+assertBootstrapNotSuperseded(signal)await assertRemoteInstallUpdateClear(ssh, hermesHome)const localPort = await openForward(deps, lock.port)@@ -1523,6 +1537,7 @@ async function connect(deps) {const error: any = new Error('Another SSH connection owns this remote dashboard; a session token is required to reuse it.')+error.kind = 'remote-ownership-contended'throw error}diff --git a/apps/desktop/electron/windows-remote-lifecycle.test.ts b/apps/desktop/electron/windows-remote-lifecycle.test.tsindex 48df428834f..37fcd841eef 100644--- a/apps/desktop/electron/windows-remote-lifecycle.test.ts+++ b/apps/desktop/electron/windows-remote-lifecycle.test.ts@@ -52,6 +52,7 @@ test('Windows spawn publishes the initial ownership record before releasing thestartedAt: '2026-07-14T00:00:00.000Z'})+const encoded = command.split(' ').at(-1) || ''const script = encoded ? Buffer.from(encoded, 'base64').toString('utf16le') : ''@@ -73,6 +74,7 @@ test('PowerShell transport uses UTF-16LE encoded commands and literal escaping',test('Windows relaunch gate refuses live and uncertain markers before executing the remote runtime', async () => {for (const observation of ['LIVE:4242', 'UNCERTAIN']) {const scripts: string[] = []+const ssh = sshWith(async command => {const script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')scripts.push(script)@@ -86,9 +88,11 @@ test('Windows relaunch gate refuses live and uncertain markers before executingpython: 'C:\\Hermes\\python.exe'})}+if (script.includes('.hermes-update-in-progress')) {return observation}+throw new Error(`unexpected command after update gate: ${script}`)})@@ -114,6 +118,7 @@ test('Windows relaunch gate refuses live and uncertain markers before executingtest('Windows relaunch gate uses strict install-wide marker parsing and fail-closed PID probing', async () => {let script = ''+const ssh = sshWith(async command => {script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')@@ -134,6 +139,7 @@ test('Windows probe validates Hermes and Python topology before selection', asynawait probeWindowsRemote(sshWith(async command => {script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')+return JSON.stringify({os: 'Windows',arch: 'AMD64',@@ -300,7 +306,9 @@ test('managed update drain preserves a Windows owner when creation time does nothermesPath: 'C:\\h\\hermes.exe',hermesHome: 'C:\\h'}+const operations: string[] = []+const ssh = sshWith(async command => {const script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')operations.push(script)@@ -340,7 +348,9 @@ test('managed update drain rechecks Windows PID/create-time ownership before exahermesPath: 'C:\\h\\hermes.exe',hermesHome: 'C:\\h'}+const operations: string[] = []+const ssh = sshWith(async command => {const script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')operations.push(script)@@ -348,6 +358,7 @@ test('managed update drain rechecks Windows PID/create-time ownership before exaif (script.includes("'read-lock'")) {return JSON.stringify(lock)}+if (script.includes("'process-state'")) {return JSON.stringify({ alive: true, owned: true, indeterminate: false })}diff --git a/apps/desktop/electron/windows-remote-lifecycle.ts b/apps/desktop/electron/windows-remote-lifecycle.tsindex fce6ec46701..c1e21cc5279 100644--- a/apps/desktop/electron/windows-remote-lifecycle.ts+++ b/apps/desktop/electron/windows-remote-lifecycle.ts@@ -159,11 +159,13 @@ async function assertWindowsRemoteInstallUpdateClear(ssh, hermesHome) {}const live = /^LIVE:([1-9][0-9]*)$/.exec(observation)+const error: any = new Error(live? `Remote Hermes update process ${live[1]} is still running; SSH startup is paused.`: 'The remote Hermes update marker is unreadable or malformed; refusing SSH startup.')+error.kind = 'update-in-progress'throw error}@@ -247,6 +249,7 @@ async function helper(ssh, runtime, operation, args = [], stdinData?) {function atomicWindowsSpawnCommand(runtime, reservation: any = {}) {const argv = [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', 'spawn']const helper = operation => [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', operation]+const script = ['$ErrorActionPreference="Stop"',`$home=${psLiteral(runtime.hermesHome)}`,@@ -281,16 +284,19 @@ function atomicWindowsSpawnCommand(runtime, reservation: any = {}) {].filter(line => line !== '').join(';')+return powerShellCommand(script)}async function atomicWindowsSpawn(ssh, runtime, stdinData, reservation: any = {}) {const output = await ssh.exec(atomicWindowsSpawnCommand(runtime, reservation), { stdinData })+const lines = String(output || '').replace(/^\uFEFF/, '').trim().split(/\r?\n/).filter(Boolean)+const parsed = JSON.parse(lines[lines.length - 1] || 'null')if (parsed?.error) {@@ -421,9 +427,11 @@ async function terminateOwnedWindowsDashboardForUpdate(ssh, runtime, expected) {error.kind = 'transient-transport-error'throw error}+if (!state.alive) {return { pid: lock.pid, terminated: false, alreadyStopped: true }}+if (!state.owned) {const error: any = new Error('Refusing to terminate a remote Windows process whose ownership is unproven.')error.kind = 'foreign-backend'@@ -438,6 +446,7 @@ async function terminateOwnedWindowsDashboardForUpdate(ssh, runtime, expected) {error.kind = 'ownership-changed'throw error}+state = await processState(ssh, runtime, lock)if (state.indeterminate || !state.alive || !state.owned) {@@ -668,6 +677,7 @@ async function connectWindowsRemote(deps) {const error: any = new Error('Another SSH connection owns this remote dashboard; a session token is required to reuse it.')+error.kind = 'remote-ownership-contended'throw error}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 0e96be4ed0b..141b17e71fb 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -110,7 +110,12 @@ import {import { broadcastSessionsChanged } from '@/store/session-sync'import { forgetSessionUnread } from '@/store/session-unread'import { $archivedSessions } from '@/store/sidebar-archive'-import { dropTranscriptTail, dropTranscriptTailEverywhere, loadTranscriptTail, saveTranscriptTail } from '@/store/transcript-tail-cache'+import {+ dropTranscriptTail,+ dropTranscriptTailEverywhere,+ loadTranscriptTail,+ saveTranscriptTail+} from '@/store/transcript-tail-cache'import { isWatchWindow } from '@/store/windows'import type { SessionCreateResponse, SessionMessage, SessionResumeResponse, UsageStats } from '@/types/hermes'