The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): run and surface Heartbeats reliably
Jerry Gooch45b7dabfb9f4
diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsxindex 29781ed95c0..7308cdcec31 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx@@ -133,8 +133,19 @@ export const SessionControlGoalSection = memo(function SessionControlGoalSection? 'done': 'active'+ const iconClass =+ goal.last_verdict === 'blocked'+ ? 'text-red-500'+ : visibleState === 'done'+ ? 'text-muted-foreground/70'+ : visibleState === 'active'+ ? 'text-emerald-500'+ : 'text-amber-500'+const stateLabel =- visibleState === 'waiting'+ goal.last_verdict === 'blocked'+ ? s.goalBlocked+ : visibleState === 'waiting'? s.goalWaiting: visibleState === 'paused'? s.goalPaused@@ -297,7 +308,7 @@ export const SessionControlGoalSection = memo(function SessionControlGoalSection</DropdownMenu>}defaultCollapsed={false}- icon={<Codicon className="text-muted-foreground/70" name="target" size="0.8rem" />}+ icon={<Codicon className={iconClass} name="target" size="0.8rem" />}label={headerLabel}><div className="space-y-1.5 px-1 py-1">@@ -337,7 +348,12 @@ export const SessionControlGoalSection = memo(function SessionControlGoalSection{/* Criteria subsection */}<div className="mt-2 border-t border-(--ui-stroke-tertiary)/40 pt-1.5"><div className="flex items-center justify-between pb-1 text-[0.68rem] font-medium text-muted-foreground/75">- <span>{ctrl.criteriaHeader(goal.subgoals.length)}</span>+ <div className="flex items-center gap-1.5">+ <span aria-hidden="true" className={`inline-flex ${iconClass}`} data-slot="criteria-state-marker">+ <Codicon name="target" size="0.68rem" />+ </span>+ <span>{ctrl.criteriaHeader(goal.subgoals.length)}</span>+ </div><div className="flex items-center gap-1"><ButtonclassName="text-[0.68rem] text-muted-foreground/75 hover:text-foreground/90"diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control-heartbeat.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control-heartbeat.tsxindex 20692516bf3..643767fe18b 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control-heartbeat.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control-heartbeat.tsx@@ -1,4 +1,4 @@-import { memo, useCallback, useState } from 'react'+import { memo, useCallback, useEffect, useState } from 'react'import { StatusSection } from '@/components/chat/status-section'import { Button } from '@/components/ui/button'@@ -27,7 +27,7 @@ import {type SessionControlHeartbeat} from '@/store/session-control'-import { type ConfirmState, formatApproximateTime, formatHeartbeatInterval } from './session-control-utils'+import { type ConfirmState, formatHeartbeatCountdown, formatHeartbeatInterval } from './session-control-utils'interface HeartbeatSectionProps {heartbeat: SessionControlHeartbeat@@ -36,6 +36,23 @@ interface HeartbeatSectionProps {onFeedback: (error: string | null, success: string | null) => void}+function useHeartbeatClock(active: boolean): number {+ const [now, setNow] = useState(() => Date.now())++ useEffect(() => {+ if (!active) {+ return+ }++ const tick = () => setNow(Date.now())+ const interval = window.setInterval(tick, 1_000)++ return () => window.clearInterval(interval)+ }, [active])++ return now+}+export const SessionControlHeartbeatSection = memo(function SessionControlHeartbeatSection({heartbeat,sessionId,@@ -70,13 +87,19 @@ export const SessionControlHeartbeatSection = memo(function SessionControlHeartb)const stateLabel = heartbeat.status === 'paused' ? ctrl.heartbeatPaused : ctrl.heartbeatActive-+ const now = useHeartbeatClock(heartbeat.status === 'active')const intervalLabel = formatHeartbeatInterval(heartbeat.interval_seconds, t)-const nextDueTimestamp = (heartbeat.last_fired_at || heartbeat.created_at) + heartbeat.interval_seconds+ const nextDueMs = nextDueTimestamp > 1e11 ? nextDueTimestamp : nextDueTimestamp * 1_000+ const isDue = heartbeat.status === 'active' && nextDueMs <= nowconst nextRunLabel =- heartbeat.status === 'active' ? ` · ${ctrl.heartbeatNext(formatApproximateTime(nextDueTimestamp))}` : ''+ heartbeat.status === 'active'+ ? ` · ${isDue ? ctrl.heartbeatDueWaitingForIdle : ctrl.heartbeatNext(formatHeartbeatCountdown(nextDueTimestamp, now))}`+ : ''++ const iconClass =+ heartbeat.status === 'paused' ? 'text-red-500' : isDue ? 'text-amber-500' : 'text-emerald-500'const headerLabel = `${stateLabel} · ${intervalLabel}${nextRunLabel}`@@ -163,7 +186,7 @@ export const SessionControlHeartbeatSection = memo(function SessionControlHeartb</DropdownMenu>}defaultCollapsed={true}- icon={<Codicon className="text-muted-foreground/70" name="pulse" size="0.8rem" />}+ icon={<Codicon className={iconClass} name="pulse" size="0.8rem" />}label={headerLabel}><div className="space-y-1 px-1 py-1 text-xs">diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control-loop.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control-loop.tsxindex 5b459b00e1b..de0d8864624 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control-loop.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control-loop.tsx@@ -50,6 +50,13 @@ export const SessionControlLoopSection = memo(function SessionControlLoopSectionconst [menuOpen, setMenuOpen] = useState(false)const isBusy = Boolean(pendingAction)+ const iconClass =+ loop.status === 'done'+ ? 'text-muted-foreground/70'+ : loop.status === 'paused' || loop.deferred_by_goal+ ? 'text-amber-500'+ : 'text-emerald-500'+const handleAction = useCallback(async (action: SessionControlAction, args?: SessionControlActionArgs): Promise<boolean> => {onFeedback(null, null)@@ -185,7 +192,7 @@ export const SessionControlLoopSection = memo(function SessionControlLoopSection</DropdownMenu>}defaultCollapsed={true}- icon={<Codicon className="text-muted-foreground/70" name="sync" size="0.8rem" />}+ icon={<Codicon className={iconClass} name="sync" size="0.8rem" />}label={headerLabel}><div className="space-y-1 px-1 py-1 text-xs">diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control-utils.ts b/apps/desktop/src/app/chat/composer/status-stack/session-control-utils.tsindex 7a254d02b99..b75079ff4d0 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control-utils.ts+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control-utils.ts@@ -57,6 +57,20 @@ export function formatApproximateTime(targetTimestamp: number): string {return `~${days}d`}+/** Formats a countdown precisely without exposing the user's local timezone. */+export function formatHeartbeatCountdown(targetTimestamp: number, now = Date.now()): string {+ const targetMs = targetTimestamp > 1e11 ? targetTimestamp : targetTimestamp * 1000+ const remainingSeconds = Math.max(0, Math.ceil((targetMs - now) / 1000))+ const days = Math.floor(remainingSeconds / 86_400)+ const hours = Math.floor((remainingSeconds % 86_400) / 3_600)+ const minutes = Math.floor((remainingSeconds % 3_600) / 60)+ const seconds = remainingSeconds % 60+ const padded = (value: number) => String(value).padStart(2, '0')+ const clock = `${padded(hours)}:${padded(minutes)}:${padded(seconds)}`++ return days > 0 ? `${days}d ${clock}` : clock+}+export function formatInterval(seconds: number, t: Translations): string {if (seconds % 3600 === 0) {return t.statusStack.control.loopEveryHours(seconds / 3600)diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control.test.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control.test.tsxindex 5af0f5a2b65..fce8eb5e9b6 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control.test.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control.test.tsx@@ -461,6 +461,137 @@ describe('ComposerStatusStack session-control UI', () => {})// 12. heartbeat interval/next/fire count and controls+ it("shows a precise live countdown and makes an overdue heartbeat's idle wait explicit", () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date(1_700_000_030_000))++ try {+ $sessionControlBySession.set({+ [SID]: mockEntry({+ snapshot: sampleSnapshot({+ goal: null,+ heartbeat: sampleHeartbeat({+ created_at: 1_700_000_000,+ fire_count: 0,+ interval_seconds: 90,+ last_fired_at: 0,+ status: 'active'+ })+ })+ })+ })++ renderStack()++ expect(screen.getByText(/Heartbeat active · every 90s · next 00:01:00/)).toBeTruthy()++ act(() => {+ vi.advanceTimersByTime(60_000)+ })++ expect(screen.getByText(/Heartbeat active · every 90s · due — waiting for idle/)).toBeTruthy()+ } finally {+ vi.useRealTimers()+ }+ })++ it('colors the heartbeat icon for active, due, and paused states', () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date(1_700_000_030_000))++ try {+ $sessionControlBySession.set({+ [SID]: mockEntry({+ snapshot: sampleSnapshot({+ goal: null,+ heartbeat: sampleHeartbeat({+ created_at: 1_700_000_000,+ interval_seconds: 90,+ last_fired_at: 0,+ status: 'active'+ })+ })+ })+ })++ renderStack()++ const icon = () => window.document.querySelector('[data-slot="session-control-heartbeat"] .codicon-pulse')++ expect(icon()?.className).toContain('text-emerald-500')++ act(() => {+ vi.advanceTimersByTime(60_000)+ })++ expect(icon()?.className).toContain('text-amber-500')++ act(() => {+ $sessionControlBySession.set({+ [SID]: mockEntry({+ snapshot: sampleSnapshot({ heartbeat: sampleHeartbeat({ status: 'paused' }) })+ })+ })+ })++ expect(icon()?.className).toContain('text-red-500')+ } finally {+ vi.useRealTimers()+ }+ })++ it('colors the loop, goal, and criteria markers from their verified state', () => {+ $sessionControlBySession.set({+ [SID]: mockEntry({+ snapshot: sampleSnapshot({+ goal: sampleGoal({ status: 'active', last_verdict: 'continue' }),+ loop: sampleLoop({ status: 'active' })+ })+ })+ })++ renderStack()++ const loopIcon = () => window.document.querySelector('[data-slot="session-control-loop"] .codicon-sync')+ const goalIcon = () => window.document.querySelector('[data-slot="session-control-goal"] .codicon-target')+ const criteriaMarker = () => window.document.querySelector('[data-slot="session-control-goal"] [data-slot="criteria-state-marker"]')++ expect(loopIcon()?.className).toContain('text-emerald-500')+ expect(goalIcon()?.className).toContain('text-emerald-500')+ expect(criteriaMarker()?.className).toContain('text-emerald-500')++ act(() => {+ $sessionControlBySession.set({+ [SID]: mockEntry({+ snapshot: sampleSnapshot({+ goal: sampleGoal({ status: 'paused', paused_reason: 'Paused for review' }),+ loop: sampleLoop({ status: 'paused', paused_reason: 'Paused for review' })+ })+ })+ })+ })++ expect(loopIcon()?.className).toContain('text-amber-500')+ expect(goalIcon()?.className).toContain('text-amber-500')+ expect(criteriaMarker()?.className).toContain('text-amber-500')++ act(() => {+ $sessionControlBySession.set({+ [SID]: mockEntry({+ snapshot: sampleSnapshot({+ goal: sampleGoal({ last_verdict: 'blocked', status: 'active' }),+ loop: sampleLoop({ status: 'done', last_stop_reason: 'Reached configured run count' })+ })+ })+ })+ })++ expect(screen.getByText(/Goal blocked · Turn 3\/20/)).toBeTruthy()+ expect(goalIcon()?.className).toContain('text-red-500')+ expect(criteriaMarker()?.className).toContain('text-red-500')+ expect(loopIcon()?.className).toContain('text-muted-foreground/70')+ })+it('renders heartbeat and triggers heartbeat.pause', async () => {mockRunSessionControlAction.mockResolvedValue({type: 'exec',diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 8b33fc5f5b5..75d26ebcb30 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -1985,6 +1985,11 @@ export const ar = defineLocale({statusStack: {agents: 'الوكلاء',background: count => `${count} في الخلفية`,+ goalActive: 'الهدف نشط',+ goalBlocked: 'الهدف متعذر',+ goalDone: 'اكتمل الهدف',+ goalPaused: 'الهدف متوقف مؤقتًا',+ goalWaiting: 'الهدف قيد الانتظار',subagents: count => `${count} ${count === 1 ? 'وكيل فرعي' : 'وكيل فرعي'}`,todos: (done, total) => `المهام ${done}/${total}`,running: 'قيد التشغيل',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex d06fd8a6ed0..a3c529d60cc 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -2700,6 +2700,7 @@ export const en: Translations = {agents: 'Agents',background: count => `${count} Background`,goalActive: 'Goal active',+ goalBlocked: 'Goal blocked',goalDone: 'Goal done',goalPaused: 'Goal paused',goalWaiting: 'Goal waiting',@@ -2779,6 +2780,7 @@ export const en: Translations = {heartbeatEveryHours: hours => `every ${hours}h`,heartbeatEverySeconds: seconds => `every ${seconds}s`,heartbeatNext: time => `next ${time}`,+ heartbeatDueWaitingForIdle: 'due — waiting for idle',heartbeatActions: 'Heartbeat actions',pauseHeartbeat: 'Pause heartbeat',resumeHeartbeat: 'Resume heartbeat',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 3fd1a14ae68..65767047a1a 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2325,6 +2325,7 @@ export const ja = defineLocale({agents: 'エージェント',background: count => `バックグラウンド ${count} 件`,goalActive: '目標進行中',+ goalBlocked: '目標がブロックされています',goalDone: '目標達成',goalPaused: '目標一時停止中',goalWaiting: '目標待機中',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 26d4ad708b3..c43bee54593 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -2736,6 +2736,7 @@ export const ru = defineLocale({agents: 'Агенты',background: count => `${count} ${RU_NOUN(count, 'фоновая задача', 'фоновые задачи', 'фоновых задач')}`,goalActive: 'Цель активна',+ goalBlocked: 'Цель заблокирована',goalDone: 'Цель выполнена',goalPaused: 'Цель на паузе',goalWaiting: 'Цель ожидает',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 42a0d10a8ed..c823289fd0b 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2294,6 +2294,7 @@ export interface Translations {agents: stringbackground: (count: number) => stringgoalActive: string+ goalBlocked: stringgoalDone: stringgoalPaused: stringgoalWaiting: string@@ -2373,6 +2374,7 @@ export interface Translations {heartbeatEveryHours: (hours: number) => stringheartbeatEverySeconds: (seconds: number) => stringheartbeatNext: (time: string) => string+ heartbeatDueWaitingForIdle: stringheartbeatActions: stringpauseHeartbeat: stringresumeHeartbeat: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 533270c044e..f0fd9a28744 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -2245,6 +2245,7 @@ export const zhHant = defineLocale({agents: '代理',background: count => `${count} 個背景任務`,goalActive: '目標進行中',+ goalBlocked: '目標受阻',goalDone: '目標已完成',goalPaused: '目標已暫停',goalWaiting: '目標等待中',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex e1acc87657d..e6c7d6d3ab1 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -2864,6 +2864,7 @@ export const zh: Translations = {agents: '代理',background: count => `${count} 个后台任务`,goalActive: '目标进行中',+ goalBlocked: '目标受阻',goalDone: '目标已完成',goalPaused: '目标已暂停',goalWaiting: '目标等待中',@@ -2943,6 +2944,7 @@ export const zh: Translations = {heartbeatEveryHours: hours => `每 ${hours} 小时`,heartbeatEverySeconds: seconds => `每 ${seconds} 秒`,heartbeatNext: time => `下次 ${time}`,+ heartbeatDueWaitingForIdle: '已到期,等待会话空闲',heartbeatActions: '心跳操作',pauseHeartbeat: '暂停心跳',resumeHeartbeat: '恢复心跳',diff --git a/tests/tui_gateway/test_desktop_heartbeat_driver.py b/tests/tui_gateway/test_desktop_heartbeat_driver.pynew file mode 100644index 00000000000..b0569349551--- /dev/null+++ b/tests/tui_gateway/test_desktop_heartbeat_driver.py@@ -0,0 +1,118 @@+"""Regression coverage for Desktop-owned Heartbeat scheduling."""++from __future__ import annotations++import io+import threading+import time+++def test_due_heartbeat_dispatches_a_desktop_turn_and_publishes_the_new_count(tmp_path, monkeypatch):+ """A due idle Desktop session must fire through the normal turn path exactly once."""+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))++ from hermes_cli import goals+ from hermes_cli.heartbeat import HeartbeatManager, HeartbeatState, save_heartbeat+ from tui_gateway import server++ goals._DB_CACHE.clear()+ sid, key = "desktop-heartbeat-sid", "desktop-heartbeat-key"+ session = {+ "session_key": key,+ "history_lock": threading.RLock(),+ "running": False,+ "queued_prompt": None,+ "queued_prompts": [],+ "_closing": False,+ "agent": object(),+ "attached_images": [],+ }+ server._sessions[sid] = session+ save_heartbeat(+ key,+ HeartbeatState(+ prompt="Check the desktop Heartbeat path.",+ interval_seconds=60,+ created_at=time.time() - 61,+ ),+ )+ dispatched, events = [], []+ monkeypatch.setattr(+ server,+ "_run_prompt_submit",+ lambda rid, got_sid, got_session, text, **kwargs: dispatched.append((rid, got_sid, got_session, text)),+ )+ monkeypatch.setattr(server, "_emit", lambda event, got_sid, payload: events.append((event, got_sid, payload)))++ try:+ assert server._poll_desktop_heartbeats_once() == 1+ assert len(dispatched) == 1+ assert dispatched[0][1:3] == (sid, session)+ assert "[Heartbeat — recurring instruction" in dispatched[0][3]+ assert session["running"] is True+ assert HeartbeatManager(key).state.fire_count == 1+ assert any(+ event == "session.control.update"+ and got_sid == sid+ and payload["control"]["heartbeat"]["fire_count"] == 1+ for event, got_sid, payload in events+ )+ finally:+ server._sessions.pop(sid, None)+ goals._DB_CACHE.clear()+++def test_entry_starts_desktop_heartbeat_driver(monkeypatch):+ from hermes_cli import model_switch_providers+ from tui_gateway import entry, server++ started = {"count": 0}+ monkeypatch.setattr(server, "_start_desktop_heartbeat_driver", lambda: started.__setitem__("count", started["count"] + 1))+ monkeypatch.setattr(server, "_start_backend_heartbeat_refresher", lambda: None)+ monkeypatch.setattr(server, "_schedule_startup_orphan_sweep", lambda: None)+ monkeypatch.setattr(entry, "_install_sidecar_publisher", lambda: None)+ monkeypatch.setattr(entry, "ensure_mcp_discovery_started", lambda: None)+ monkeypatch.setattr(entry, "resolve_skin", lambda: "default")+ monkeypatch.setattr(entry.server, "_ensure_skin_watcher", lambda: None)+ monkeypatch.setattr(entry, "_log_exit", lambda reason: None)+ monkeypatch.setattr(entry, "handle_spurious_eof", lambda *args: False)+ monkeypatch.setattr(entry, "write_json", lambda payload: True)+ monkeypatch.setattr(entry.sys, "stdin", io.StringIO(""))+ monkeypatch.setattr(model_switch_providers, "prewarm_picker_cache_async", lambda: None)++ entry.main()+ assert started["count"] == 1+++def test_websocket_starts_desktop_heartbeat_driver(monkeypatch):+ import asyncio++ from tui_gateway import server, ws++ started = {"count": 0}+ monkeypatch.setattr(server, "_start_desktop_heartbeat_driver", lambda: started.__setitem__("count", started["count"] + 1))+ monkeypatch.setattr(server, "_start_backend_heartbeat_refresher", lambda: None)+ monkeypatch.setattr(server, "_schedule_startup_orphan_sweep", lambda: None)+ monkeypatch.setattr(server, "resolve_skin", lambda: "default")+ monkeypatch.setattr(server, "_ensure_skin_watcher", lambda: None)+ monkeypatch.setattr(server, "register_live_transport", lambda *args, **kwargs: None)+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)++ class FakeWS:+ async def accept(self):+ pass++ async def send_text(self, line):+ pass++ async def receive_text(self):+ raise ws._WebSocketDisconnect()++ async def close(self):+ pass++ asyncio.run(ws.handle_ws(FakeWS()))+ assert started["count"] == 1diff --git a/tests/tui_gateway/test_desktop_heartbeat_slash_sync.py b/tests/tui_gateway/test_desktop_heartbeat_slash_sync.pynew file mode 100644index 00000000000..8acef7f4bd2--- /dev/null+++ b/tests/tui_gateway/test_desktop_heartbeat_slash_sync.py@@ -0,0 +1,57 @@+"""Desktop must receive Heartbeat state immediately after slash setup."""++from __future__ import annotations+++class _Worker:+ def __init__(self, output: str) -> None:+ self.output = output+ self.commands: list[str] = []++ def run(self, command: str) -> str:+ self.commands.append(command)+ return self.output+++def test_worker_backed_heartbeat_slash_publishes_control_snapshot(monkeypatch):+ """A slash-created Heartbeat appears without leaving and re-entering its chat."""+ from tui_gateway import server++ sid = "heartbeat-session"+ session_key = "persistent-heartbeat-session"+ worker = _Worker("♥ Heartbeat set (every 1m): Reply HEARTBEAT_OK")+ snapshot = {+ "goal": None,+ "heartbeat": {+ "created_at": 1_700_000_000,+ "fire_count": 0,+ "interval_seconds": 60,+ "last_fired_at": 1_700_000_000,+ "prompt": "Reply HEARTBEAT_OK",+ "status": "active",+ },+ "loop": None,+ "revision": "heartbeat-created",+ "updated_at": 1_700_000_000,+ }+ emitted: list[tuple[str, str, dict]] = []+ session = {+ "agent": None,+ "running": False,+ "session_key": session_key,+ "slash_worker": worker,+ }+ server._sessions[sid] = session+ monkeypatch.setattr(server, "_snapshot_control", lambda key: snapshot if key == session_key else None)+ monkeypatch.setattr(server, "_emit", lambda event, event_sid, payload=None: emitted.append((event, event_sid, payload)))++ try:+ response = server._methods["slash.exec"](+ "request-1", {"command": "/heartbeat every 1m Reply HEARTBEAT_OK", "session_id": sid}+ )+ finally:+ server._sessions.pop(sid, None)++ assert response["result"]["output"] == worker.output+ assert worker.commands == ["/heartbeat every 1m Reply HEARTBEAT_OK"]+ assert emitted == [("session.control.update", sid, {"control": snapshot})]diff --git a/tui_gateway/desktop_heartbeat_driver.py b/tui_gateway/desktop_heartbeat_driver.pynew file mode 100644index 00000000000..eedfb1d6f4f--- /dev/null+++ b/tui_gateway/desktop_heartbeat_driver.py@@ -0,0 +1,86 @@+"""Desktop-owned Heartbeat scheduling through the normal TUI turn path."""++from __future__ import annotations++import threading+import time+import uuid++from .method_ctx import bind_module+++_HEARTBEAT_POLL_SECONDS = 5.0+_desktop_heartbeat_driver_started = False+_desktop_heartbeat_driver_lock = threading.Lock()+++def _poll_desktop_heartbeats_once() -> int:+ """Start one due Heartbeat turn per idle live Desktop session.++ The session lock covers the persisted fire claim and the in-memory ``running``+ claim. That makes a user prompt win whenever it arrived first, and prevents two+ poll passes from incrementing the same Heartbeat more than once.+ """+ fired = 0+ for sid, session in list(_sessions.items()):+ if not isinstance(session, dict):+ continue+ session_key = str(session.get("session_key") or "")+ if not session_key:+ continue+ lock = session.get("history_lock")+ if lock is None:+ continue+ try:+ with lock:+ if (+ session.get("_closing")+ or session.get("running")+ or session.get("queued_prompt") is not None+ or session.get("queued_prompts")+ ):+ continue+ with _session_profile_runtime_scope(session):+ from hermes_cli.heartbeat import HeartbeatManager++ prompt = HeartbeatManager(session_key).due_prompt()+ if not prompt:+ continue+ control = _snapshot_control(session_key)+ session["running"] = True+ except Exception as exc:+ logger.debug("desktop heartbeat check failed for %s: %s", sid, exc)+ continue++ try:+ _emit("session.control.update", sid, {"control": control})+ _run_prompt_submit(f"heartbeat-{uuid.uuid4().hex}", sid, session, prompt)+ fired += 1+ except Exception as exc:+ with lock:+ session["running"] = False+ logger.debug("desktop heartbeat dispatch failed for %s: %s", sid, exc)+ return fired+++def _start_desktop_heartbeat_driver() -> None:+ """Start the one daemon poller that drives active Desktop session Heartbeats."""+ global _desktop_heartbeat_driver_started+ with _desktop_heartbeat_driver_lock:+ if _desktop_heartbeat_driver_started:+ return+ _desktop_heartbeat_driver_started = True++ def _loop() -> None:+ while True:+ try:+ _poll_desktop_heartbeats_once()+ except Exception:+ logger.debug("desktop heartbeat driver tick failed", exc_info=True)+ time.sleep(_HEARTBEAT_POLL_SECONDS)++ threading.Thread(target=_loop, name="desktop-heartbeat-driver", daemon=True).start()+++def register(server) -> None:+ bind_module(globals(), server, skip=("_",))diff --git a/tui_gateway/entry.py b/tui_gateway/entry.pyindex 8697e01f0d3..95d759ad6ff 100644--- a/tui_gateway/entry.py+++ b/tui_gateway/entry.py@@ -241,10 +241,10 @@ def _write_or_exit(payload: dict, reason: str) -> None:def main():_install_sidecar_publisher()- # The heartbeat row lets the orphan sweep tell "live but idle" from "truly orphaned",- # so it must start BEFORE the sweep.+ # The process liveness row and the Desktop session heartbeat driver must start before the sweep.for start, what in ((server._start_backend_heartbeat_refresher, "backend heartbeat refresher start"),+ (server._start_desktop_heartbeat_driver, "desktop heartbeat driver start"),(server._schedule_startup_orphan_sweep, "startup orphan sweep scheduling")):try:start()diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex 9d9e457f75c..be0b3f0d00f 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -810,6 +810,25 @@ _SLASH_BUILTINS = {"loop": _cmd_loop, "undo": _cmd_undo, "snapshot": _cmd_snapshot, "snap": _cmd_snapshot,"compress": _cmd_compress, "compact": _cmd_compress}+_SESSION_CONTROL_SLASHES = frozenset({"goal", "heartbeat", "loop", "subgoal"})+++def _publish_session_control_snapshot(sid: str, session: dict, command_name: str) -> None:+ """Best-effort immediate Desktop repaint after a worker-backed automation slash command."""+ session_key = str(session.get("session_key") or "")+ if not session_key:+ return+ try:+ with _session_profile_runtime_scope(session):+ control = _snapshot_control(session_key)+ except Exception:+ logger.debug("session.control snapshot after /%s failed", command_name, exc_info=True)+ return+ try:+ _emit("session.control.update", sid, {"control": control})+ except Exception:+ logger.debug("session.control.update emit after /%s failed", command_name, exc_info=True)+@method("command.dispatch")def _(rid, params: dict) -> dict:@@ -876,6 +895,8 @@ def _(rid, params: dict) -> dict:payload = {"output": worker.run(cmd) or "(no output)"}if warning := _mirror_slash_side_effects(sid, session, cmd):payload["warning"] = warning+ if base in _SESSION_CONTROL_SLASHES:+ _publish_session_control_snapshot(sid, session, base)return _ok(rid, payload)except Exception as e:with contextlib.suppress(Exception):diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 316ad72ba1d..582d3cb6966 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -3208,7 +3208,7 @@ from . import ( # noqa: E402methods_profiles as _methods_profiles, methods_prompt as _methods_prompt, methods_session as _methods_session,methods_tools as _methods_tools, prompt_turn as _prompt_turn, billing_view as _billing_view,methods_projects as _methods_projects, methods_session_foreign as _methods_session_foreign,- methods_session_control as _methods_session_control)+ methods_session_control as _methods_session_control, desktop_heartbeat_driver as _desktop_heartbeat_driver)for _m in (_session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,@@ -3218,6 +3218,6 @@ for _m in (_methods_browser_control, _methods_session, _methods_prompt, _methods_config,_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,_methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,- _methods_session_control):+ _methods_session_control, _desktop_heartbeat_driver):_m.register(sys.modules[__name__])del _mdiff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex fb7e866a979..8a5ec42be60 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -280,11 +280,10 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:# global broadcasts write_json can't route.server._ensure_skin_watcher()server.register_live_transport(transport)- # Cross-backend liveness: a heartbeat row lets the startup orphan sweep tell "live but idle- # backend" from "truly orphaned". Idempotent and once-per-process, like the orphan sweep (the- # desktop app and web dashboard reach the agent via this sidecar, not entry.main()).+ # The process liveness row and Desktop session driver are both idempotent and once-per-process.for start, what in ((server._start_backend_heartbeat_refresher, "backend heartbeat refresher start"),+ (server._start_desktop_heartbeat_driver, "desktop heartbeat driver start"),(server._schedule_startup_orphan_sweep, "startup orphan sweep scheduling"),):try: