The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-screen): keep the bot's pooled socket open across install and attach
teknium1d623d4d5e7a9
diff --git a/apps/desktop/src/plugins/hermes-bots/screen-connection.ts b/apps/desktop/src/plugins/hermes-bots/screen-connection.tsindex 90dfd846260..e77ffea9b80 100644--- a/apps/desktop/src/plugins/hermes-bots/screen-connection.ts+++ b/apps/desktop/src/plugins/hermes-bots/screen-connection.ts@@ -109,6 +109,29 @@ export function displayRequest<T>(bot: RosterRow, method: string, params: Recordreturn host.requestProfile<T>(botScreenRoute(bot), method, params)}+/**+ * Hold the bot's pooled gateway socket open across a `display.*` sequence. The+ * SDK disposes an inactive registry-routed socket once its request count hits+ * zero, so without this the `display.install.*` / `display.lease` events that+ * follow the request never arrive. Feature-detected: older hosts (and local+ * routes, which never close) get a no-op release.+ */+export async function retainBotScreen(bot: RosterRow): Promise<() => void> {+ const noop = () => undefined++ if (typeof host.retainProfile !== 'function') {+ return noop+ }++ try {+ const release = await host.retainProfile(botScreenRoute(bot))++ return typeof release === 'function' ? release : noop+ } catch {+ return noop+ }+}+/*** Resolve the RFB WebSocket URL for `bot`: the bot's gateway `/api/ws` origin* (fresh credential for OAuth remotes) with the path swapped for the displaydiff --git a/apps/desktop/src/plugins/hermes-bots/screen-install-retention.test.tsx b/apps/desktop/src/plugins/hermes-bots/screen-install-retention.test.tsxnew file mode 100644index 00000000000..1f057dacce5--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/screen-install-retention.test.tsx@@ -0,0 +1,107 @@+/**+ * An INACTIVE registry-routed bot's pooled socket is disposed by the SDK as soon+ * as its request count hits zero — so `display.install.log/done` (and the+ * pane's `display.lease` events) would never arrive. The install card must hold+ * a retention from before `display.install` until the done event lands.+ */++import { act, fireEvent, render } from '@testing-library/react'+import { beforeEach, expect, it, vi } from 'vitest'++import type { DisplayStatus } from './screen-connection'+import type { RosterRow } from './types'++const calls = vi.hoisted(() => [] as string[])++vi.mock('@hermes/plugin-sdk', async () => {+ const { onGatewayEvent } = await import('../../contrib/events')++ return {+ Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => <button {...props}>{children}</button>,+ Codicon: () => null,+ GlyphSpinner: () => null,+ resolveSiblingWsUrl: vi.fn(),+ host: {+ onEvent: onGatewayEvent,+ requestProfile: vi.fn(async (_route: unknown, method: string) => {+ calls.push(`request:${method}`)++ return {}+ }),+ retainProfile: vi.fn(async () => {+ calls.push('retain')++ return () => {+ calls.push('release')+ }+ })+ }+ }+})+vi.mock('./routing', () => ({+ botConnectionRoute: () => ({ connectionId: 'host-a', profile: 'ops', targetProfile: 'ops' })+}))+vi.mock('./i18n', () => ({+ useBots: () => ({+ screen: {+ notInstalledTitle: 'Missing',+ notInstalledBody: 'Body',+ installHint: 'Hint',+ install: 'Install on host',+ installing: 'Installing',+ installCancelled: 'Cancelled',+ installFailed: 'Failed',+ noPackageManager: 'None'+ }+ })+}))++// eslint-disable-next-line no-restricted-imports+import { emitGatewayEvent } from '../../contrib/events'++import { ScreenInstallCard } from './screen-install'++const bot: RosterRow = { name: 'ops', sourceScoped: true, connectionId: 'host-a', connectionKind: 'remote' }++const status: DisplayStatus = {+ profile: 'ops',+ profile_key: '/home/hermes/.hermes',+ supported: true,+ installed: false,+ missing: ['tigervnc'],+ running: false,+ pid: null,+ display: null,+ socket: null,+ geometry: '1440x900',+ install_command: 'sudo apt-get install -y tigervnc-standalone-server',+ lease: { holder: 'agent', viewer_id: null, pending_handoff: null, since: 1, reason: '' }+}++beforeEach(() => {+ calls.length = 0+})++it('retains the bot socket before display.install and releases it when the done event lands', async () => {+ const onInstalled = vi.fn()+ const view = render(<ScreenInstallCard bot={bot} onInstalled={onInstalled} status={status} />)++ await act(async () => {+ fireEvent.click(view.getByText('Install on host'))+ })+ expect(calls).toEqual(['retain', 'request:display.install'])++ act(() =>+ emitGatewayEvent({+ type: 'display.install.done',+ connectionId: 'host-a',+ profile: 'ops',+ payload: { profile_key: status.profile_key, code: 0, status: { ...status, installed: true } }+ })+ )+ expect(calls).toEqual(['retain', 'request:display.install', 'release'])+ expect(onInstalled).toHaveBeenCalledTimes(1)+ view.unmount()+ // Unmount after done must not double-release.+ expect(calls.filter(call => call === 'release')).toHaveLength(1)+})diff --git a/apps/desktop/src/plugins/hermes-bots/screen-install.tsx b/apps/desktop/src/plugins/hermes-bots/screen-install.tsxindex d69498ba5a3..f5509527c5f 100644--- a/apps/desktop/src/plugins/hermes-bots/screen-install.tsx+++ b/apps/desktop/src/plugins/hermes-bots/screen-install.tsx@@ -14,7 +14,7 @@ import type { RpcEvent } from '@hermes/plugin-sdk'import { useCallback, useEffect, useRef, useState } from 'react'import { useBots } from './i18n'-import { displayRequest, type DisplayStatus, isEventForBotScreen } from './screen-connection'+import { displayRequest, type DisplayStatus, isEventForBotScreen, retainBotScreen } from './screen-connection'import type { RosterRow } from './types'const LOG_KEEP = 200@@ -31,6 +31,16 @@ export function ScreenInstallCard({ bot, status, onInstalled }: ScreenInstallCarconst [log, setLog] = useState<string[]>([])const [error, setError] = useState<null | string>(null)const logEnd = useRef<HTMLDivElement>(null)+ // Keeps the bot's socket open from display.install until done/failed: the log+ // and done events ride that socket, and the SDK closes an idle one otherwise.+ const retention = useRef<(() => void) | null>(null)++ const releaseRetention = useCallback(() => {+ retention.current?.()+ retention.current = null+ }, [])++ useEffect(() => releaseRetention, [releaseRetention])useEffect(() => {logEnd.current?.scrollIntoView({ block: 'end' })@@ -53,6 +63,8 @@ export function ScreenInstallCard({ bot, status, onInstalled }: ScreenInstallCarreturn}+ releaseRetention()+if (payload.code === 0 && payload.status?.installed) {setPhase('idle')onInstalled(payload.status)@@ -66,7 +78,7 @@ export function ScreenInstallCard({ bot, status, onInstalled }: ScreenInstallCaroffLog()offDone()}- }, [bot, onInstalled, status.profile_key, t.screen.installCancelled, t.screen.installFailed])+ }, [bot, onInstalled, releaseRetention, status.profile_key, t.screen.installCancelled, t.screen.installFailed])const install = useCallback(async () => {setPhase('running')@@ -74,12 +86,14 @@ export function ScreenInstallCard({ bot, status, onInstalled }: ScreenInstallCarsetError(null)try {+ retention.current = await retainBotScreen(bot)await displayRequest(bot, 'display.install')} catch (err) {+ releaseRetention()setPhase('failed')setError(err instanceof Error ? err.message : String(err))}- }, [bot])+ }, [bot, releaseRetention])return (<div className="grid min-h-48 place-items-center p-6 text-center">diff --git a/apps/desktop/src/plugins/hermes-bots/screen-pane-lifecycle.test.tsx b/apps/desktop/src/plugins/hermes-bots/screen-pane-lifecycle.test.tsxindex bfab9a0d38d..75fc46120f9 100644--- a/apps/desktop/src/plugins/hermes-bots/screen-pane-lifecycle.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/screen-pane-lifecycle.test.tsx@@ -6,6 +6,7 @@ import type * as ScreenConnection from './screen-connection'import type { RosterRow } from './types'const sockets = vi.hoisted(() => [] as Array<{ closeCodes: number[]; closed: boolean; close: (code?: number) => void }>)+const retention = vi.hoisted(() => ({ held: 0 }))vi.mock('@hermes/plugin-sdk', async () => {const { useStore } = await import('@nanostores/react')@@ -19,9 +20,21 @@ vi.mock('@hermes/plugin-sdk', async () => {GlyphSpinner: () => null,EmptyState: () => null,useValue: useStore,- host: { onEvent: onGatewayEvent }+ host: {+ onEvent: onGatewayEvent,+ retainProfile: async () => {+ retention.held += 1++ return () => {+ retention.held -= 1+ }+ }+ }}})+vi.mock('./routing', () => ({+ botConnectionRoute: () => ({ connectionId: 'host-a', profile: 'default', targetProfile: 'default' })+}))vi.mock('./data', () => ({ botSelectionKey: (bot: RosterRow) => bot.name }))vi.mock('./i18n', () => ({useBots: () => ({@@ -85,6 +98,7 @@ const status: DisplayStatus = {beforeEach(() => {$screenState.set({})sockets.length = 0+ retention.held = 0vi.mocked(displayRequest).mockReset().mockResolvedValue({ ...status, ticket: 'test-ticket', viewer_id: 'this-viewer' })@@ -119,6 +133,18 @@ it('sends an intentional close before noVNC can send its statusless close on panexpect(sockets[0].closeCodes).toEqual([1000])})+it('pins the bot socket for the attach lifetime and lets go on unmount', async () => {+ const view = render(<BotScreenPane bot={bot} />)+ await waitFor(() => expect(sockets).toHaveLength(1))+ await act(async () => {})+ expect(retention.held).toBe(1)+ fireEvent.click(view.getByTitle('Reconnect'))+ await waitFor(() => expect(sockets).toHaveLength(2))+ expect(retention.held).toBe(1)+ view.unmount()+ expect(retention.held).toBe(0)+})+it('does not hand back while replacing a stream to reconnect the same viewer', async () => {const view = render(<BotScreenPane bot={bot} />)await waitFor(() => expect(sockets).toHaveLength(1))diff --git a/apps/desktop/src/plugins/hermes-bots/screen-pane.tsx b/apps/desktop/src/plugins/hermes-bots/screen-pane.tsxindex bfd9ce0e44f..fde4957389d 100644--- a/apps/desktop/src/plugins/hermes-bots/screen-pane.tsx+++ b/apps/desktop/src/plugins/hermes-bots/screen-pane.tsx@@ -15,7 +15,7 @@ import type { RpcEvent } from '@hermes/plugin-sdk'import { useCallback, useEffect, useRef, useState } from 'react'import { useBots } from './i18n'-import { type DisplayLease, type DisplayObserveResult, displayRequest, type DisplayStatus, isEventForBotScreen, leaseHeldBy, resolveScreenWsUrl, viewerHash } from './screen-connection'+import { type DisplayLease, type DisplayObserveResult, displayRequest, type DisplayStatus, isEventForBotScreen, leaseHeldBy, resolveScreenWsUrl, retainBotScreen, viewerHash } from './screen-connection'import { ScreenInstallCard } from './screen-install'import { $screenState, screenStateFor, setScreenLease, setScreenStatus, setScreenViewer } from './screen-state'import type { RosterRow } from './types'@@ -54,6 +54,9 @@ export function BotScreenPane({ bot }: { bot: RosterRow }) {const canvasHost = useRef<HTMLDivElement | null>(null)const rfb = useRef<RfbLike | null>(null)const socket = useRef<WebSocket | null>(null)+ // Pins the bot's pooled gateway socket for the attach lifetime so display.lease+ // events keep arriving for an inactive registry-routed bot.+ const retention = useRef<(() => void) | null>(null)const [conn, setConn] = useState<ConnState>('idle')const [error, setError] = useState<null | string>(null)const [busy, setBusy] = useState(false)@@ -94,6 +97,8 @@ export function BotScreenPane({ bot }: { bot: RosterRow }) {rfb.current = nullsocket.current?.close()socket.current = null+ retention.current?.()+ retention.current = null}, [])const attach = useCallback(async () => {@@ -110,6 +115,15 @@ export function BotScreenPane({ bot }: { bot: RosterRow }) {// Load the client BEFORE dialing: noVNC's Websock installs its own `onopen`, so a socket that// opened while the dynamic import was still in flight never hands it the open event.const Rfb = await loadRfb()+ const retain = await retainBotScreen(bot)++ if (generation !== attachGeneration.current) {+ retain()++ return+ }++ retention.current = retainconst observe = await displayRequest<DisplayObserveResult>(bot, 'display.observe')const minted = { id: observe.viewer_id, hash: await viewerHash(observe.viewer_id) }setScreenStatus(bot, observe)