Skip to content

The agent that grows with you

fix(bot-relay): a claimed envelope the Desktop never delivered is re-offered, and the first reply stands

teknium12a294a756e7d
diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.py
index 81ef17651e5..3e8fdaf4892 100644
--- a/tests/tools/test_bot_relay.py
+++ b/tests/tools/test_bot_relay.py
@@ -149,6 +149,17 @@ def test_write_reply_validates_envelope_id(root):
assert data["reply"] == "pong" and not data["error"]
+def test_write_reply_keeps_the_first_settled_reply_for_an_envelope(root):
+ """Idempotent by envelope id: a re-offered delivery's second outcome (or a late duplicate) must
+ not displace the reply the waiter already read, so the answer never turns into an error."""
+ env_id = "a" * 32
+ first = bot_relay.write_reply(root, env_id, reply="the answer")
+ second = bot_relay.write_reply(root, env_id, error="target busy", reason="target_busy")
+ assert second == first
+ record = json.loads(first.read_text(encoding="utf-8"))
+ assert (record["reply"], record["error"], record["reason"]) == ("the answer", "", "")
+
+
def test_write_reply_reason_passthrough_and_classification(root):
# explicit reason is persisted verbatim
path = bot_relay.write_reply(root, "c" * 32, error="boom", reason="delivery_timeout")
diff --git a/tests/tui_gateway/test_bot_relay_methods.py b/tests/tui_gateway/test_bot_relay_methods.py
index 73682b72ea3..fb3c5c56a1a 100644
--- a/tests/tui_gateway/test_bot_relay_methods.py
+++ b/tests/tui_gateway/test_bot_relay_methods.py
@@ -63,6 +63,35 @@ def test_outbox_drain_returns_each_envelope_once(home):
assert second["envelopes"] == []
+def test_outbox_drain_reoffers_a_claimed_envelope_the_desktop_never_delivered(home):
+ """A Desktop that disconnects between ``outbox.drain`` and ``bot_relay.deliver`` leaves the
+ envelope in ``claimed/`` with no reply: silent until the waiter's deadline, then swept, while
+ every later drain saw an empty outbox (#111021, redo of #111207). Once it has sat unanswered
+ for ``REOFFER_AFTER_SECONDS`` the next drain hands it out again — exactly once per window — and
+ an envelope whose reply already landed is never re-offered."""
+ import os
+ import time
+
+ target = {"profile": "scout", "handle": "scout", "connection_id": "cloud-1",
+ "connection_label": "", "title": "", "description": ""}
+ lost = bot_relay.enqueue_envelope(home, target=target, message="lost", sender_profile="w", sender_handle="w")
+ done = bot_relay.enqueue_envelope(home, target=target, message="done", sender_profile="w", sender_handle="w")
+ drain = srv._methods["bot_relay.outbox.drain"]
+ assert sorted(e["id"] for e in _result(drain(1, {}))["envelopes"]) == sorted([lost["id"], done["id"]])
+ bot_relay.write_reply(home, done["id"], reply="answered")
+ # Fresh claims are the Desktop's for a whole window: nothing to re-offer yet.
+ assert _result(drain(2, {}))["envelopes"] == []
+ claimed_dir = bot_relay.relay_root(home) / bot_relay.CLAIMED_DIR
+ old = time.time() - bot_relay.REOFFER_AFTER_SECONDS - 1
+ for path in claimed_dir.glob("*.json"):
+ os.utime(path, (old, old))
+ reoffered = _result(drain(3, {}))["envelopes"]
+ assert [(e["id"], e["message"]) for e in reoffered] == [(lost["id"], "lost")]
+ # The re-offer opened a new window (mtime bumped): the same drain does not hand it out twice.
+ assert _result(drain(4, {}))["envelopes"] == []
+ assert (claimed_dir / f"{lost['id']}.json").stat().st_mtime > old + 1
+
+
def test_deliver_validates_profile_and_runs_transport(home, monkeypatch):
calls = {}
diff --git a/tools/bot_relay.py b/tools/bot_relay.py
index af382af5e16..ed695579bcd 100644
--- a/tools/bot_relay.py
+++ b/tools/bot_relay.py
@@ -53,6 +53,11 @@ DESKTOP_DELIVER_TIMEOUT_SECONDS = (
REPLY_WAIT_SECONDS = DESKTOP_DELIVER_TIMEOUT_SECONDS + 60
# Envelopes/replies older than this are stale artifacts (Desktop closed) and are swept.
STALE_AFTER_SECONDS = 6 * 3600
+# A claimed envelope still unanswered this long after its claim was taken by a Desktop that died
+# before ``bot_relay.deliver``; the next drain re-offers it (once per window), while the waiter
+# (``REPLY_WAIT_SECONDS``) is still listening. Two full turn attempts: a live delivery is never in
+# flight that long without the Desktop having posted its own timeout reply.
+REOFFER_AFTER_SECONDS = 2 * TURN_ATTEMPT_TIMEOUT_SECONDS
# Only a recent roster is authoritative for the fail-fast offline check: the
# Desktop re-pushes roster.sync on connection-state changes.
ROSTER_FRESH_SECONDS = 600
@@ -342,7 +347,8 @@ def claim_pending_envelopes(root: Path | str) -> list[dict]:
_sweep_stale(base)
ttl = _envelope_ttl_seconds()
now = time.time()
- out: list[dict] = []
+ # Re-offers first: they are the oldest mail this drain hands out.
+ out: list[dict] = _reoffer_unanswered(base, now)
# Oldest first: the Desktop delivers each target's claimed envelopes in the order this list
# gives them, so a sender's two DMs to one agent arrive in the order they were sent. Sorting
# by filename ordered them by ``uuid4().hex`` — at random.
@@ -354,6 +360,7 @@ def claim_pending_envelopes(root: Path | str) -> list[dict]:
claimed = base / CLAIMED_DIR / path.name
with contextlib.suppress(OSError, ValueError):
os.replace(path, claimed) # atomic claim
+ os.utime(claimed, (now, now)) # the re-offer window counts from the claim, not the enqueue
envelope = json.loads(claimed.read_text(encoding="utf-8"))
if not isinstance(envelope, dict):
raise ValueError(f"expected a JSON object, got {type(envelope).__name__}")
@@ -361,6 +368,27 @@ def claim_pending_envelopes(root: Path | str) -> list[dict]:
return out
+def _reoffer_unanswered(base: Path, now: float) -> list[dict]:
+ """``claimed/`` envelopes older than ``REOFFER_AFTER_SECONDS`` with no ``replies/<id>.json``.
+
+ The claim is the Desktop's: one that disconnects between ``outbox.drain`` and ``bot_relay.deliver``
+ leaves the envelope here with no reply, silent until the waiter's deadline and then swept, while
+ the reconnected Desktop's drains see an empty outbox (#111021, #111207). Re-offering it hands the
+ message to the next drain; the mtime bump makes that once per window."""
+ out: list[dict] = []
+ for path in sorted((base / CLAIMED_DIR).glob("*.json"), key=_queued_at):
+ if (base / REPLIES_DIR / path.name).exists():
+ continue
+ with contextlib.suppress(OSError, ValueError):
+ if now - path.stat().st_mtime < REOFFER_AFTER_SECONDS:
+ continue
+ os.utime(path, (now, now))
+ envelope = json.loads(path.read_text(encoding="utf-8"))
+ if isinstance(envelope, dict):
+ out.append(envelope)
+ return out
+
+
def write_reply(root: Path | str, envelope_id: str, *, reply: str = "", error: str = "", reason: str = "") -> Path:
"""Persist the relayed reply (or delivery error) for the waiter. ``reason`` (typed
code, ``tools.bot_failure_reasons``) is classified from ``error`` when omitted."""
@@ -368,12 +396,16 @@ def write_reply(root: Path | str, envelope_id: str, *, reply: str = "", error: s
safe = str(envelope_id or "").strip()
if not re.match(r"^[0-9a-f]{32}$", safe):
raise ValueError(f"invalid envelope id: {envelope_id!r}")
+ path = base / REPLIES_DIR / f"{safe}.json"
+ if path.exists():
+ # Idempotent by envelope id: the first settled reply is the one the waiter already read (or
+ # will). A re-offered delivery's second outcome — or a late duplicate — never displaces it.
+ return path
err, code = str(error or ""), str(reason or "")
if not code and err:
from tools.bot_failure_reasons import classify_agent_error
code = classify_agent_error(err)
- path = base / REPLIES_DIR / f"{safe}.json"
_atomic_write_json(path, {"id": safe, "at": int(time.time()), "reply": str(reply or ""), "error": err, "reason": code})
return path
diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.md
index 69fe0ff0c35..f6de5a55fce 100644
--- a/website/docs/user-guide/bot-mode.md
+++ b/website/docs/user-guide/bot-mode.md
@@ -224,7 +224,7 @@ Every gateway you register in **Settings → Connections** — local, remote URL
- **Rosters propagate on their own.** While the Desktop runs, it periodically tells each connected gateway which agents live on the *other* connections. Every Bot Chat's teammate roster then lists them ("Teammates on OTHER connected machines"), with names, roles, and which machine they're on — and the roster refreshes when agents appear, disappear, or get renamed (capability epoch).
- **`message_agent` reaches them directly.** A Bot on your laptop messages the cloud agent with `message_agent(target="moxie", …)` exactly like a local teammate. If the same handle exists on several machines, disambiguate with `target="moxie@<connection>"` (the tool's error tells the Bot the exact forms). Delivery rides the Desktop: the sending gateway queues the message, the Desktop relays it to the target connection's own gateway, the target Bot runs a turn in its canonical Bot Chat, and the reply comes back to the sender as the same background completion notification local DMs use (the process that waits for it is a Hermes entrypoint, so it starts under `approvals.single_query_mode: deny` — the default for a Bot's one-shot reply turn — too). Messages to different Bots are delivered side by side, so one Bot's long turn never delays another Bot's mail (or ages it past `bot_mode.envelope_ttl_seconds`); messages to the *same* Bot are delivered in order, one turn at a time.
-- **The Desktop is the courier.** Cross-connection delivery works while a Desktop that knows both connections is running (it holds the sockets and the credentials — gateways never see each other's auth). If the Desktop is closed mid-delivery, the sender's Bot is told the reply didn't arrive rather than left hanging. For always-on machine-to-machine messaging with no Desktop in the loop, register a peer (`hermes peer`, below) — the two routes coexist.
+- **The Desktop is the courier.** Cross-connection delivery works while a Desktop that knows both connections is running (it holds the sockets and the credentials — gateways never see each other's auth). If the Desktop is closed mid-delivery, the sender's Bot is told the reply didn't arrive rather than left hanging; a message the Desktop picked up but never handed to the target (it disconnected in between) is offered to the next drain again after two turn budgets — while the sender is still waiting — and the first reply recorded for a message is the one that stands. For always-on machine-to-machine messaging with no Desktop in the loop, register a peer (`hermes peer`, below) — the two routes coexist.
- **A remote `default` goes by its title.** Every machine's `default` is `@hermes`, so a remote one is offered — and reachable — under its Bot Mode title instead (a remote `default` titled *CoS Bot* is `@cos-bot`; with no title, `hermes@<connection>`), and a DM it sends arrives signed with that same reply-safe form rather than a bare `@hermes` that would point back at your own default.
### Bot-initiated DMs across machines (`hermes peer`)