Skip to content

The agent that grows with you

fix(scale-to-zero): count an attached dashboard WS client as inbound activity

Ben Barclay5838b2f9d86a
diff --git a/gateway/run.py b/gateway/run.py
index 9b2e4b6f69d..3569d49b27e 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -9483,9 +9483,25 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
except Exception: # noqa: BLE001 - unreadable source => assume busy
logger.debug("scale-to-zero: api work count unreadable — staying awake", exc_info=True)
api_count = 1
+ # An attached dashboard/desktop/TUI client is inbound activity too. It
+ # lives in the DASHBOARD process, so it reaches us as a file mtime that
+ # process refreshes on every WS frame (gateway/scale_to_zero.py). Fold
+ # it into the inbound clock rather than adding a conjunct: the client
+ # then gets the same idle_timeout grace after it disconnects as a chat
+ # message does, and a lingering marker cannot pin the box (stale -> None).
+ last_inbound = self._last_inbound_at
+ try:
+ from gateway.scale_to_zero import dashboard_client_last_seen
+
+ seen = dashboard_client_last_seen()
+ except Exception: # noqa: BLE001 - unreadable source => assume busy
+ logger.debug("scale-to-zero: dashboard heartbeat unreadable — staying awake", exc_info=True)
+ seen = time.time()
+ if seen is not None and seen > last_inbound:
+ last_inbound = seen
return is_idle(
active_work_count=self._running_agent_count() + cron_count + api_count,
- seconds_since_last_inbound=time.time() - self._last_inbound_at,
+ seconds_since_last_inbound=time.time() - last_inbound,
idle_timeout_seconds=self._scale_to_zero_idle_timeout_seconds(),
has_live_background_work=self._scale_to_zero_has_live_background_work(),
)
diff --git a/gateway/scale_to_zero.py b/gateway/scale_to_zero.py
index 65c01515ad5..5a95e3dae85 100644
--- a/gateway/scale_to_zero.py
+++ b/gateway/scale_to_zero.py
@@ -164,6 +164,74 @@ def is_idle(
return seconds_since_last_inbound >= idle_timeout_seconds
+# Dashboard-client liveness marker. The dashboard process (tui_gateway/ws.py,
+# a DIFFERENT process from the gateway on hosted instances) touches this file
+# on every /api/ws connect and inbound frame — the desktop app, web dashboard
+# and TUI all send `gateway.ping` every 15s and treat 45s of silence as dead
+# (apps/shared/src/json-rpc-gateway.ts, ui-tui/src/gatewayClient.ts). The
+# gateway reads the mtime and counts a fresh marker as inbound activity, so an
+# open client holds the box awake exactly like a chat message does. Without
+# this the box suspends under the open client, the client's reconnect loop
+# re-pokes the Fly-proxied hostname, autostart resumes it, and the instance
+# flaps every ~60s (13 of 72 active opted-in prod instances, 2026-09-02).
+DASHBOARD_CLIENT_HEARTBEAT_REL = os.path.join("state", "dashboard_clients.heartbeat")
+DASHBOARD_CLIENT_STALE_SECONDS = 45.0
+
+
+def dashboard_client_heartbeat_path(hermes_home: Optional[os.PathLike | str] = None):
+ """Path of the dashboard-client liveness marker under HERMES_HOME."""
+ from pathlib import Path
+
+ if hermes_home is None:
+ from hermes_constants import get_hermes_home
+
+ hermes_home = get_hermes_home()
+ return Path(hermes_home) / DASHBOARD_CLIENT_HEARTBEAT_REL
+
+
+def touch_dashboard_client_heartbeat(path: Optional[os.PathLike | str] = None) -> bool:
+ """Mark "a dashboard client is attached right now". Best-effort, never raises."""
+ try:
+ p = dashboard_client_heartbeat_path() if path is None else path
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ with open(p, "a", encoding="utf-8"):
+ pass
+ os.utime(p, None)
+ return True
+ except Exception: # noqa: BLE001 - liveness garnish must never break the WS
+ logger.debug("scale-to-zero: dashboard heartbeat touch failed", exc_info=True)
+ return False
+
+
+def dashboard_client_last_seen(
+ path: Optional[os.PathLike | str] = None,
+ *,
+ now: Optional[float] = None,
+ stale_seconds: float = DASHBOARD_CLIENT_STALE_SECONDS,
+) -> Optional[float]:
+ """Epoch seconds a dashboard client was last seen, or None when no live client.
+
+ Missing marker -> None (the steady state on a box nobody has the dashboard
+ open on — NOT fail-awake, or every instance would never sleep). A marker
+ older than ``stale_seconds`` -> None (client gone; the file just lingers).
+ An unreadable marker -> ``now`` (fail-awake: an unreadable source counts as
+ activity, same rule as the work counters in ``is_idle``).
+ """
+ import time
+
+ current = time.time() if now is None else now
+ p = dashboard_client_heartbeat_path() if path is None else path
+ try:
+ mtime = os.stat(p).st_mtime
+ except FileNotFoundError:
+ return None
+ except OSError:
+ return current
+ if current - mtime >= stale_seconds:
+ return None
+ return mtime
+
+
def self_suspend_available(environ: Optional[dict] = None) -> bool:
"""Whether this process can suspend its own machine via the flaps socket.
diff --git a/tests/gateway/test_scale_to_zero_dashboard_client.py b/tests/gateway/test_scale_to_zero_dashboard_client.py
new file mode 100644
index 00000000000..d1cdfea7c6f
--- /dev/null
+++ b/tests/gateway/test_scale_to_zero_dashboard_client.py
@@ -0,0 +1,253 @@
+"""Scale-to-zero: an attached dashboard/desktop/TUI WS client counts as activity.
+
+Background (2026-09-02 fleet audit): 13 of 72 active opted-in prod instances
+flapped suspend -> proxy-wake every ~60s. The gateway only stamped
+``_last_inbound_at`` for messaging inbound, so it suspended under an open
+dashboard client; the client's reconnect loop re-poked the Fly-proxied hostname
+and autostart resumed the box. The dashboard runs in a separate process on
+hosted instances, so the signal crosses over as a marker-file mtime.
+
+These tests exercise the REAL seams — the pure helpers with a real temp
+HERMES_HOME, GatewayRunner._scale_to_zero_is_idle's composition, and
+tui_gateway.ws.handle_ws — rather than stubbing the collection under test
+(the F25 / #84327 lesson: bugs live at the call site, not in the pure predicate).
+"""
+from __future__ import annotations
+
+import asyncio
+import os
+import time
+
+import pytest
+
+from gateway import scale_to_zero as s2z
+from gateway.run import GatewayRunner
+
+
+def hermes_home(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ return tmp_path
+
+
+def _stat_denying(target):
+ """os.stat replacement that denies ONLY the marker path (stdlib callers unaffected)."""
+ real = os.stat
+
+ def _stat(path, *a, **k):
+ if os.fspath(path) == os.fspath(target):
+ raise PermissionError("nope")
+ return real(path, *a, **k)
+
+ return _stat
+
+
+# --- pure helpers -----------------------------------------------------------
+
+
+def test_heartbeat_path_lives_under_hermes_home_state(hermes_home):
+ p = s2z.dashboard_client_heartbeat_path()
+ assert p == hermes_home / "state" / "dashboard_clients.heartbeat"
+
+
+def test_last_seen_missing_marker_is_none_not_fail_awake(hermes_home):
+ # Steady state for a box nobody has the dashboard open on: must read as
+ # "no client", otherwise no instance would ever suspend.
+ assert s2z.dashboard_client_last_seen() is None
+
+
+def test_touch_creates_state_dir_and_marker(hermes_home):
+ assert s2z.touch_dashboard_client_heartbeat() is True
+ p = s2z.dashboard_client_heartbeat_path()
+ assert p.exists()
+ seen = s2z.dashboard_client_last_seen()
+ assert seen is not None and abs(seen - time.time()) < 5
+
+
+def test_last_seen_fresh_then_stale(hermes_home):
+ s2z.touch_dashboard_client_heartbeat()
+ p = s2z.dashboard_client_heartbeat_path()
+ mtime = os.stat(p).st_mtime
+ assert s2z.dashboard_client_last_seen(now=mtime + 10) == mtime
+ assert s2z.dashboard_client_last_seen(now=mtime + 44.9) == mtime
+ # A client that stopped pinging 45s ago is gone (client heartbeat deadline).
+ assert s2z.dashboard_client_last_seen(now=mtime + 45) is None
+ assert s2z.dashboard_client_last_seen(now=mtime + 3600) is None
+
+
+def test_last_seen_unreadable_marker_fails_awake(hermes_home, monkeypatch):
+ s2z.touch_dashboard_client_heartbeat()
+
+ monkeypatch.setattr(s2z.os, "stat", _stat_denying(s2z.dashboard_client_heartbeat_path()))
+ now = 1_000_000.0
+ # Unreadable (not missing) => counts as activity right now.
+ assert s2z.dashboard_client_last_seen(now=now) == now
+
+
+def test_touch_never_raises(hermes_home, monkeypatch):
+ monkeypatch.setattr(s2z.os, "utime", lambda *a, **k: (_ for _ in ()).throw(OSError("ro")))
+ assert s2z.touch_dashboard_client_heartbeat() is False
+
+
+# --- gateway side: the idle predicate composition ---------------------------
+
+
+def _runner(monkeypatch, *, last_inbound_at):
+ r = GatewayRunner.__new__(GatewayRunner)
+ r._running = True
+ r._last_inbound_at = last_inbound_at
+ r._running_agents = {}
+ r._background_tasks = set()
+ r.adapters = {}
+ monkeypatch.setattr(r, "_scale_to_zero_idle_timeout_seconds", lambda: 120.0, raising=False)
+ monkeypatch.setattr(r, "_scale_to_zero_has_live_background_work", lambda: False, raising=False)
+ monkeypatch.setattr("cron.scheduler.get_running_job_ids", lambda: [])
+ return r
+
+
+def test_idle_without_dashboard_client_unchanged(hermes_home, monkeypatch):
+ r = _runner(monkeypatch, last_inbound_at=time.time() - 600)
+ assert r._scale_to_zero_is_idle() is True
+
+
+def test_attached_dashboard_client_blocks_idle(hermes_home, monkeypatch):
+ r = _runner(monkeypatch, last_inbound_at=time.time() - 600)
+ s2z.touch_dashboard_client_heartbeat()
+ assert r._scale_to_zero_is_idle() is False
+
+
+def test_stale_marker_hands_back_to_the_gateway_clock(hermes_home, monkeypatch):
+ """Marker 100s old (> 45s staleness) => the client is gone; a lingering file
+ must NOT extend the inbound clock. The gateway's own _last_inbound_at (600s
+ ago) decides, so the box is idle."""
+ r = _runner(monkeypatch, last_inbound_at=time.time() - 600)
+ s2z.touch_dashboard_client_heartbeat()
+ p = s2z.dashboard_client_heartbeat_path()
+ old = time.time() - 100
+ os.utime(p, (old, old))
+ assert r._scale_to_zero_is_idle() is True
+
+
+def test_dashboard_client_seen_recently_extends_inbound_clock(hermes_home, monkeypatch):
+ # Marker 30s old (fresh, < 45s): inbound clock moves to 30s ago, which is
+ # inside the 120s window => not idle, even though the gateway's own
+ # _last_inbound_at is ancient.
+ r = _runner(monkeypatch, last_inbound_at=time.time() - 600)
+ s2z.touch_dashboard_client_heartbeat()
+ p = s2z.dashboard_client_heartbeat_path()
+ t = time.time() - 30
+ os.utime(p, (t, t))
+ assert r._scale_to_zero_is_idle() is False
+
+
+def test_newer_gateway_inbound_wins_over_older_marker(hermes_home, monkeypatch):
+ # Marker fresh at 40s ago, but a chat message landed 5s ago: max() keeps the
+ # message; either way the box stays awake. Pin no regression on the path.
+ r = _runner(monkeypatch, last_inbound_at=time.time() - 5)
+ s2z.touch_dashboard_client_heartbeat()
+ p = s2z.dashboard_client_heartbeat_path()
+ t = time.time() - 40
+ os.utime(p, (t, t))
+ assert r._scale_to_zero_is_idle() is False
+ # _last_inbound_at itself is not mutated by the read.
+ assert time.time() - r._last_inbound_at < 10
+
+
+def test_unreadable_marker_keeps_gateway_awake(hermes_home, monkeypatch):
+ r = _runner(monkeypatch, last_inbound_at=time.time() - 600)
+ s2z.touch_dashboard_client_heartbeat()
+ monkeypatch.setattr(s2z.os, "stat", _stat_denying(s2z.dashboard_client_heartbeat_path()))
+ assert r._scale_to_zero_is_idle() is False
+
+
+# --- dashboard side: the real handle_ws path touches the marker -------------
+
+
+def test_handle_ws_connect_touches_marker(hermes_home, monkeypatch):
+ from tui_gateway import server, ws as ws_mod
+
+ monkeypatch.setattr(server, "_start_backend_heartbeat_refresher", lambda: None)
+ monkeypatch.setattr(server, "_schedule_startup_orphan_sweep", lambda: None, raising=False)
+ monkeypatch.setattr(server, "resolve_skin", lambda: "default")
+ monkeypatch.setattr(server, "_ensure_skin_watcher", lambda: None)
+ monkeypatch.setattr(server, "register_live_transport", lambda *_a, **_k: None)
+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)
+ monkeypatch.setattr(ws_mod, "_dashboard_client_touched_at", 0.0)
+
+ class FakeWS:
+ async def accept(self):
+ pass
+
+ async def send_text(self, line):
+ pass
+
+ async def receive_text(self):
+ raise ws_mod._WebSocketDisconnect()
+
+ async def close(self):
+ pass
+
+ assert s2z.dashboard_client_last_seen() is None
+ asyncio.run(ws_mod.handle_ws(FakeWS()))
+ seen = s2z.dashboard_client_last_seen()
+ assert seen is not None and abs(seen - time.time()) < 5
+
+
+def test_handle_ws_inbound_frames_refresh_marker(hermes_home, monkeypatch):
+ from tui_gateway import server, ws as ws_mod
+
+ monkeypatch.setattr(server, "_start_backend_heartbeat_refresher", lambda: None)
+ monkeypatch.setattr(server, "_schedule_startup_orphan_sweep", lambda: None, raising=False)
+ monkeypatch.setattr(server, "resolve_skin", lambda: "default")
+ monkeypatch.setattr(server, "_ensure_skin_watcher", lambda: None)
+ monkeypatch.setattr(server, "register_live_transport", lambda *_a, **_k: None)
+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)
+ monkeypatch.setattr(ws_mod, "_dashboard_client_touched_at", 0.0)
+ # Disable the throttle so each frame is observable.
+ monkeypatch.setattr(ws_mod, "_DASHBOARD_CLIENT_TOUCH_MIN_INTERVAL_S", 0.0)
+
+ frames = ['{"jsonrpc":"2.0","method":"gateway.ping","id":1}'] * 2
+ touches: list[float] = []
+ real_touch = s2z.touch_dashboard_client_heartbeat
+
+ def _spy(path=None):
+ touches.append(time.time())
+ return real_touch(path)
+
+ monkeypatch.setattr(s2z, "touch_dashboard_client_heartbeat", _spy)
+
+ class FakeWS:
+ async def accept(self):
+ pass
+
+ async def send_text(self, line):
+ pass
+
+ async def receive_text(self):
+ if frames:
+ return frames.pop()
+ raise ws_mod._WebSocketDisconnect()
+
+ async def close(self):
+ pass
+
+ asyncio.run(ws_mod.handle_ws(FakeWS()))
+ # 1 on connect + 1 per inbound frame.
+ assert len(touches) == 3
+ assert s2z.dashboard_client_last_seen() is not None
+
+
+def test_note_activity_is_throttled(hermes_home, monkeypatch):
+ from tui_gateway import ws as ws_mod
+
+ calls = {"n": 0}
+ monkeypatch.setattr(
+ s2z, "touch_dashboard_client_heartbeat", lambda path=None: calls.__setitem__("n", calls["n"] + 1) or True
+ )
+ monkeypatch.setattr(ws_mod, "_dashboard_client_touched_at", 0.0)
+ ws_mod._note_dashboard_client_activity(force=True)
+ ws_mod._note_dashboard_client_activity()
+ ws_mod._note_dashboard_client_activity()
+ assert calls["n"] == 1
+ ws_mod._note_dashboard_client_activity(force=True)
+ assert calls["n"] == 2
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 988733a9b14..0eab4e29dfc 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -37,6 +37,30 @@ from tui_gateway.event_replay import replay_epoch
_log = logging.getLogger(__name__)
+# Scale-to-zero: tell the (separate) gateway process that a dashboard/desktop/
+# TUI client is attached, via the mtime of a marker file it reads in its idle
+# predicate. Clients ping every 15s; one mtime write per 5s per process is
+# plenty and keeps the volume quiet. See gateway/scale_to_zero.py.
+_DASHBOARD_CLIENT_TOUCH_MIN_INTERVAL_S = 5.0
+_dashboard_client_touched_at = 0.0
+_dashboard_client_touch_lock = threading.Lock()
+
+
+def _note_dashboard_client_activity(*, force: bool = False) -> None:
+ """Refresh the dashboard-client liveness marker (throttled, best-effort)."""
+ global _dashboard_client_touched_at
+ now = time.monotonic()
+ with _dashboard_client_touch_lock:
+ if not force and now - _dashboard_client_touched_at < _DASHBOARD_CLIENT_TOUCH_MIN_INTERVAL_S:
+ return
+ _dashboard_client_touched_at = now
+ try:
+ from gateway.scale_to_zero import touch_dashboard_client_heartbeat
+
+ touch_dashboard_client_heartbeat()
+ except Exception: # noqa: BLE001 - liveness garnish must never break the WS
+ _log.debug("dashboard client heartbeat touch failed", exc_info=True)
+
# Max seconds a pool-dispatched handler will block waiting for the event loop
# to flush a WS frame before we mark the transport dead. Protects handler
# threads from a wedged socket.
@@ -393,6 +417,7 @@ async def handle_ws(
# Track this peer for session-less global broadcasts (skin.changed
# from the background watcher) — write_json can't route those.
server.register_live_transport(transport)
+ _note_dashboard_client_activity(force=True)
# Cross-backend liveness (#94895): register a heartbeat row so
# the startup orphan sweep can distinguish "row owned by a live
# but idle backend" from "row truly orphaned". The stdio TUI's
@@ -420,6 +445,7 @@ async def handle_ws(
while True:
try:
raw = await ws.receive_text()
+ _note_dashboard_client_activity()
except _WebSocketDisconnect as exc:
disconnect_reason = (
"client_disconnect("