Skip to content

The agent that grows with you

fix(bot-screen): events pinned to the bot's connection, stale hero frames marked, lease fails closed

teknium1d22d03b9dd0f
diff --git a/apps/desktop/src/plugins/hermes-bots/i18n.ts b/apps/desktop/src/plugins/hermes-bots/i18n.ts
index 5eef7a47735..637a9ee4b9f 100644
--- a/apps/desktop/src/plugins/hermes-bots/i18n.ts
+++ b/apps/desktop/src/plugins/hermes-bots/i18n.ts
@@ -242,6 +242,7 @@ type BotsMessages = {
heroStopped: string
heroNotInstalled: string
heroConnecting: string
+ heroStale: string
heroOpenLive: string
heroInstall: string
heroStart: string
@@ -508,6 +509,7 @@ const en: BotsMessages = {
heroStopped: 'Screen is off',
heroNotInstalled: 'Not installed on this host',
heroConnecting: 'Checking the screen…',
+ heroStale: 'Last seen — screen unreachable',
heroOpenLive: 'Open live',
heroInstall: 'Install',
heroStart: 'Start',
@@ -769,6 +771,7 @@ const ja: BotsMessages = {
heroStopped: '画面は停止中',
heroNotInstalled: 'このホストには未インストール',
heroConnecting: '画面を確認中…',
+ heroStale: '最終表示 — 画面に接続できません',
heroOpenLive: 'ライブで開く',
heroInstall: 'インストール',
heroStart: '開始',
@@ -1025,6 +1028,7 @@ const zh: BotsMessages = {
heroStopped: '屏幕已关闭',
heroNotInstalled: '此主机未安装',
heroConnecting: '正在检查屏幕…',
+ heroStale: '最后画面 — 屏幕无法访问',
heroOpenLive: '实时打开',
heroInstall: '安装',
heroStart: '启动',
@@ -1281,6 +1285,7 @@ const zhHant: BotsMessages = {
heroStopped: '螢幕已關閉',
heroNotInstalled: '此主機未安裝',
heroConnecting: '正在檢查螢幕…',
+ heroStale: '最後畫面 — 螢幕無法連線',
heroOpenLive: '即時開啟',
heroInstall: '安裝',
heroStart: '啟動',
diff --git a/apps/desktop/src/plugins/hermes-bots/screen-connection.test.ts b/apps/desktop/src/plugins/hermes-bots/screen-connection.test.ts
new file mode 100644
index 00000000000..f4f36759bf7
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/screen-connection.test.ts
@@ -0,0 +1,44 @@
+/**
+ * Two remote hosts can share the same `~/.hermes` path, so a `display.*` event
+ * matched on `profile_key` alone would let host B's take-over repaint host A's
+ * screen pane. The event must also have arrived on the bot's own connection.
+ */
+
+import { describe, expect, it, vi } from 'vitest'
+
+import type { RosterRow } from './types'
+
+const routeMock = vi.fn<() => { connectionId: string; profile: string } | null>(() => null)
+
+vi.mock('@hermes/plugin-sdk', () => ({
+ host: { requestProfile: vi.fn() },
+ resolveSiblingWsUrl: vi.fn()
+}))
+
+vi.mock('./routing', () => ({
+ botConnectionRoute: () => routeMock()
+}))
+
+import { isEventForBotScreen } from './screen-connection'
+
+const bot = { name: 'ops' } as RosterRow
+const key = '/home/hermes/.hermes'
+
+describe('isEventForBotScreen', () => {
+ it('ignores a same-profile-path event that arrived from another host', () => {
+ routeMock.mockReturnValue({ connectionId: 'conn-a', profile: 'ops' })
+
+ const fromB = { connectionId: 'conn-b', payload: { profile_key: key }, type: 'display.lease' }
+ const fromA = { connectionId: 'conn-a', payload: { profile_key: key }, type: 'display.lease' }
+
+ expect(isEventForBotScreen(bot, fromB, key)).toBe(false)
+ expect(isEventForBotScreen(bot, fromA, key)).toBe(true)
+ })
+
+ it('still matches the untagged local socket for a local bot', () => {
+ routeMock.mockReturnValue({ connectionId: 'local', profile: 'ops' })
+
+ expect(isEventForBotScreen(bot, { payload: { profile_key: key }, type: 'display.lease' }, key)).toBe(true)
+ expect(isEventForBotScreen(bot, { payload: { profile_key: '/other' }, type: 'display.lease' }, key)).toBe(false)
+ })
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/screen-connection.ts b/apps/desktop/src/plugins/hermes-bots/screen-connection.ts
index 247a79ec0e0..75daaef936b 100644
--- a/apps/desktop/src/plugins/hermes-bots/screen-connection.ts
+++ b/apps/desktop/src/plugins/hermes-bots/screen-connection.ts
@@ -11,7 +11,7 @@
*/
import { host, resolveSiblingWsUrl } from '@hermes/plugin-sdk'
-import type { PluginProfileRoute } from '@hermes/plugin-sdk'
+import type { PluginProfileRoute, RpcEvent } from '@hermes/plugin-sdk'
import { botConnectionRoute } from './routing'
import type { RosterRow } from './types'
@@ -54,6 +54,24 @@ export function botScreenRoute(bot: RosterRow): PluginProfileRoute | string {
return botConnectionRoute(bot) ?? bot.name
}
+/**
+ * Does a `display.*` event belong to `bot`'s screen? Two hosts can share the same
+ * `~/.hermes` path, so the profile key alone is ambiguous: the event must also have
+ * arrived on the bot's registry connection (local/legacy events carry no tag).
+ */
+export function isEventForBotScreen(bot: RosterRow, event: RpcEvent, profileKey: null | string | undefined): boolean {
+ const payload = event.payload as { profile_key?: string } | undefined
+
+ if (!profileKey || payload?.profile_key !== profileKey) {
+ return false
+ }
+
+ const expected = botConnectionRoute(bot)?.connectionId ?? null
+ const actual = event.connectionId ?? null
+
+ return expected === actual || (expected === 'local' && actual === null)
+}
+
export function displayRequest<T>(bot: RosterRow, method: string, params: Record<string, unknown> = {}): Promise<T> {
return host.requestProfile<T>(botScreenRoute(bot), method, params)
}
diff --git a/apps/desktop/src/plugins/hermes-bots/screen-hero.tsx b/apps/desktop/src/plugins/hermes-bots/screen-hero.tsx
index 1154668df7f..32bca2d1fd6 100644
--- a/apps/desktop/src/plugins/hermes-bots/screen-hero.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/screen-hero.tsx
@@ -17,14 +17,19 @@ import { type PortalTone, useScreenPortalState } from './screen-portal'
import type { BotMeta, RosterRow } from './types'
const REFRESH_MS = 4000
+const STALE_AFTER = 3
function useLiveThumbnail(bot: RosterRow, running: boolean) {
const [dataUrl, setDataUrl] = useState<string | null>(null)
+ // Consecutive failed refreshes; past STALE_AFTER the frame is shown dimmed as "last seen" so a
+ // dead gateway never keeps looking live. Success resets it.
+ const [misses, setMisses] = useState(0)
const boxRef = useRef<HTMLButtonElement | null>(null)
useEffect(() => {
if (!running) {
setDataUrl(null)
+ setMisses(0)
return
}
@@ -59,10 +64,13 @@ function useLiveThumbnail(bot: RosterRow, running: boolean) {
.then(result => {
if (!cancelled) {
setDataUrl(result.data_url)
+ setMisses(0)
}
})
.catch(() => {
- /* transient: the next tick retries; the last good frame stays up */
+ if (!cancelled) {
+ setMisses(prev => prev + 1) // the last good frame stays up, marked stale past STALE_AFTER
+ }
})
.finally(() => {
if (!cancelled) {
@@ -83,7 +91,7 @@ function useLiveThumbnail(bot: RosterRow, running: boolean) {
}
}, [bot, running])
- return { dataUrl, boxRef }
+ return { dataUrl, boxRef, stale: misses >= STALE_AFTER }
}
const TONE_RING: Partial<Record<PortalTone, string>> = {
@@ -95,13 +103,13 @@ export function ScreenHero({ bot, meta }: { bot: RosterRow; meta?: BotMeta | nul
const t = useBots()
const { tone } = useScreenPortalState(bot)
const running = tone === 'live' || tone === 'human' || tone === 'other'
- const { dataUrl, boxRef } = useLiveThumbnail(bot, running)
+ const { dataUrl, boxRef, stale } = useLiveThumbnail(bot, running)
if (tone === 'unsupported') {
return null
}
- const caption = {
+ const caption = stale ? t.screen.heroStale : {
live: t.screen.portalWatching,
human: t.screen.portalYouControl,
other: t.screen.portalOtherControls,
@@ -123,7 +131,7 @@ export function ScreenHero({ bot, meta }: { bot: RosterRow; meta?: BotMeta | nul
type="button"
>
{dataUrl ? (
- <img alt="" className="absolute inset-0 size-full object-cover" draggable={false} src={dataUrl} />
+ <img alt="" className={stale ? 'absolute inset-0 size-full object-cover opacity-40 grayscale' : 'absolute inset-0 size-full object-cover'} draggable={false} src={dataUrl} />
) : (
<span className="absolute inset-0 grid place-items-center bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.08),transparent_70%)]">
<Codicon className="text-[2.25rem] text-white/30" name={running ? 'loading' : tone === 'missing' ? 'cloud-download' : 'vm'} />
@@ -131,7 +139,7 @@ export function ScreenHero({ bot, meta }: { bot: RosterRow; meta?: BotMeta | nul
)}
<span className="absolute inset-x-0 bottom-0 flex items-center gap-2 bg-gradient-to-t from-black/85 to-black/0 px-2.5 pb-2 pt-6 text-white">
- <span className={`size-2 shrink-0 rounded-full ${running ? (tone === 'live' ? 'bg-emerald-400' : tone === 'human' ? 'bg-red-400' : 'bg-amber-400') : 'bg-white/40'}`} />
+ <span className={`size-2 shrink-0 rounded-full ${running && !stale ? (tone === 'live' ? 'bg-emerald-400' : tone === 'human' ? 'bg-red-400' : 'bg-amber-400') : 'bg-white/40'}`} />
<span className="min-w-0 flex-1">
<span className="block truncate text-xs font-medium">{t.screen.portalTitle}</span>
<span className="block truncate text-[0.65rem] text-white/70">{caption}</span>
diff --git a/apps/desktop/src/plugins/hermes-bots/screen-install.tsx b/apps/desktop/src/plugins/hermes-bots/screen-install.tsx
index 2bc9a9131ba..d69498ba5a3 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 } from './screen-connection'
+import { displayRequest, type DisplayStatus, isEventForBotScreen } from './screen-connection'
import type { RosterRow } from './types'
const LOG_KEEP = 200
@@ -38,18 +38,18 @@ export function ScreenInstallCard({ bot, status, onInstalled }: ScreenInstallCar
useEffect(() => {
const offLog = host.onEvent('display.install.log', (event: RpcEvent) => {
- const payload = event.payload as { profile_key?: string; line?: string } | undefined
+ const payload = event.payload as { line?: string } | undefined
- if (payload?.profile_key === status.profile_key && typeof payload.line === 'string') {
+ if (isEventForBotScreen(bot, event, status.profile_key) && typeof payload?.line === 'string') {
const line = payload.line
setLog(prev => (prev.length >= LOG_KEEP ? [...prev.slice(1), line] : [...prev, line]))
}
})
const offDone = host.onEvent('display.install.done', (event: RpcEvent) => {
- const payload = event.payload as { profile_key?: string; code?: number; status?: DisplayStatus } | undefined
+ const payload = event.payload as { code?: number; status?: DisplayStatus } | undefined
- if (payload?.profile_key !== status.profile_key) {
+ if (!payload || !isEventForBotScreen(bot, event, status.profile_key)) {
return
}
@@ -66,7 +66,7 @@ export function ScreenInstallCard({ bot, status, onInstalled }: ScreenInstallCar
offLog()
offDone()
}
- }, [onInstalled, status.profile_key, t.screen.installCancelled, t.screen.installFailed])
+ }, [bot, onInstalled, status.profile_key, t.screen.installCancelled, t.screen.installFailed])
const install = useCallback(async () => {
setPhase('running')
diff --git a/apps/desktop/src/plugins/hermes-bots/screen-pane.tsx b/apps/desktop/src/plugins/hermes-bots/screen-pane.tsx
index e4cf6a12e9b..bfe65b6d69a 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, resolveScreenWsUrl, VIEWER_ID } from './screen-connection'
+import { type DisplayLease, type DisplayObserveResult, displayRequest, type DisplayStatus, isEventForBotScreen, resolveScreenWsUrl, VIEWER_ID } from './screen-connection'
import { ScreenInstallCard } from './screen-install'
import { $screenState, screenStateFor, setScreenLease, setScreenStatus } from './screen-state'
import type { RosterRow } from './types'
@@ -70,9 +70,9 @@ export function BotScreenPane({ bot }: { bot: RosterRow }) {
void refresh()
return host.onEvent('display.lease', (event: RpcEvent) => {
- const payload = event.payload as { profile_key?: string; lease?: DisplayLease } | undefined
+ const payload = event.payload as { lease?: DisplayLease } | undefined
- if (payload?.lease && payload.profile_key && payload.profile_key === status?.profile_key) {
+ if (payload?.lease && isEventForBotScreen(bot, event, status?.profile_key)) {
setScreenLease(bot, payload.lease)
}
})
@@ -257,6 +257,11 @@ export function BotScreenPane({ bot }: { bot: RosterRow }) {
<span className="rounded bg-amber-500/15 px-2 py-0.5 text-amber-600 dark:text-amber-400" title={lease.pending_handoff}>
<Codicon name="bell" /> {t.screen.handoffRequested}
</span>
+ ) : lease?.holder === 'human' && lease.reason ? (
+ // The agent's ask stays readable WHILE the human acts, not only before Take over.
+ <span className="max-w-[40%] truncate rounded bg-amber-500/15 px-2 py-0.5 text-amber-600 dark:text-amber-400" title={lease.reason}>
+ <Codicon name="bell" /> {lease.reason}
+ </span>
) : null}
{iHold ? (
<span className="rounded bg-red-500/15 px-2 py-0.5 font-medium text-red-600 dark:text-red-400">{t.screen.youControl}</span>
diff --git a/tests/tools/test_bot_desktop_lease.py b/tests/tools/test_bot_desktop_lease.py
index aa8e7b83dce..3b9da1a2cfe 100644
--- a/tests/tools/test_bot_desktop_lease.py
+++ b/tests/tools/test_bot_desktop_lease.py
@@ -101,3 +101,24 @@ def test_takeover_during_an_admitted_action_discards_its_result(monkeypatch):
monkeypatch.setattr(tool, "_dispatch", _dispatch_then_takeover)
res = json.loads(tool.handle_computer_use({"action": "capture"}))
assert res["code"] == "human_has_control" and "SECRET" not in json.dumps(res)
+
+
+def test_unreadable_lease_file_fails_closed_and_takeover_keeps_the_agents_reason(tmp_path):
+ """Missing file = fresh profile (agent). A file that exists but cannot be parsed must not read as
+ "agent holds": a torn write must never let the agent act on a human's screen. Taking over after a
+ request keeps the agent's reason so the human still sees WHY while they act."""
+ from hermes_constants import hermes_home_key
+
+ home = str(tmp_path)
+ assert lease.get(profile_key=home).holder == lease.AGENT
+ path = lease._path(home)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("{ torn", encoding="utf-8")
+ assert lease.get(profile_key=home).holder == lease.HUMAN
+ lease.release(profile_key=home) # a successful write repairs it
+ assert lease.get(profile_key=home).holder == lease.AGENT
+
+ lease.request_handoff("log in to the bank, 2FA on your phone", profile_key=home)
+ held = lease.acquire("desk-1", profile_key=home)
+ assert held.pending_handoff is None and held.reason == "log in to the bank, 2FA on your phone"
+ assert hermes_home_key(home) # sanity: the key derivation used by the bridge is available
diff --git a/tools/bot_desktop/lease.py b/tools/bot_desktop/lease.py
index 6cc4e65c270..2a3b84d5e5d 100644
--- a/tools/bot_desktop/lease.py
+++ b/tools/bot_desktop/lease.py
@@ -59,11 +59,20 @@ def _path(profile_key: Optional[str]) -> Path:
def _read(path: Path) -> Lease:
+ """No file = fresh profile, agent holds. A file that exists but cannot be parsed is a torn write
+ or tampering: fail CLOSED (human holds) — an unreadable lease must never let the agent act on a
+ screen a human may be using; the next successful write repairs it."""
try:
- data = json.loads(path.read_text(encoding="utf-8"))
- return Lease(**{k: v for k, v in data.items() if k in Lease.__dataclass_fields__})
- except (OSError, ValueError, TypeError):
+ raw = path.read_text(encoding="utf-8")
+ except FileNotFoundError:
return Lease()
+ except OSError:
+ return Lease(holder=HUMAN, viewer_id="unreadable-lease", reason="lease file unreadable")
+ try:
+ data = json.loads(raw)
+ return Lease(**{k: v for k, v in data.items() if k in Lease.__dataclass_fields__})
+ except (ValueError, TypeError):
+ return Lease(holder=HUMAN, viewer_id="unreadable-lease", reason="lease file corrupt")
def _write(path: Path, lease: Lease) -> None:
@@ -134,7 +143,10 @@ def acquire(viewer_id: str, *, profile_key: Optional[str] = None, reason: str =
"""Human ``viewer_id`` takes control. Last writer wins: a second viewer evicts the first, and the
RFB bridge closes the evicted socket so its UI drops to view-only."""
def _m(lease: Lease) -> bool:
- lease.holder, lease.viewer_id, lease.since, lease.reason = HUMAN, viewer_id, time.time(), reason
+ # The agent's ask ("please log in to X") stays as the takeover reason: the human needs it
+ # on screen WHILE they act, not only before they clicked Take over.
+ lease.holder, lease.viewer_id, lease.since = HUMAN, viewer_id, time.time()
+ lease.reason = reason or lease.pending_handoff or ""
lease.pending_handoff = None
return True
return _transition(profile_key, _m)