Python
fix(inbox): a mirrored prompt must be answerable where it arrives
Darryl Pentz05d0afa5dd26
diff --git a/coworker/connectors/adapters.py b/coworker/connectors/adapters.pyindex ca89a7fb..64eab1ba 100644--- a/coworker/connectors/adapters.py+++ b/coworker/connectors/adapters.py@@ -145,6 +145,7 @@ class TelegramAdapter(BasePlatformAdapter):class SlackAdapter(BasePlatformAdapter):platform = "slack"+ supports_interactive = True # Block Kit buttons, resolved via the interactions handler# Watchdog cadence: how often to check the live Socket Mode connection and force a reconnect# if it has silently died. `start_async()` sleeps forever, so a dead socket looks alive to usdiff --git a/coworker/connectors/base.py b/coworker/connectors/base.pyindex 026f04e2..b4fc7e79 100644--- a/coworker/connectors/base.py+++ b/coworker/connectors/base.py@@ -157,6 +157,10 @@ class BasePlatformAdapter(ABC):`handle_message` for inbound events."""platform: str = "base"+ # Whether this platform renders choice buttons. False here is the honest+ # default: `send_interactive` below falls back to plain text, and a caller+ # that assumes buttons would leave the reader with no way to answer.+ supports_interactive: bool = Falsedef __init__(self) -> None:self._handler: Optional[MessageHandler] = Nonediff --git a/coworker/connectors/gateway.py b/coworker/connectors/gateway.pyindex 17eb5fd3..cd5e2996 100644--- a/coworker/connectors/gateway.py+++ b/coworker/connectors/gateway.py@@ -202,6 +202,15 @@ class Gateway:return SendResult(False, error=f"no adapter for {platform}")return await adapter.send(chat_id, text, thread_id=thread_id)+ def supports_interactive(self, target: str) -> bool:+ """Whether this target's platform actually renders buttons. Callers that offer a+ choice need to know: `deliver_interactive` silently degrades to plain text on an+ adapter without button support, which would strand the reader with a question and+ no way to answer it."""+ platform, _chat_id, _thread_id = parse_target(target)+ adapter = self._adapters.get(platform)+ return bool(getattr(adapter, "supports_interactive", False))+async def deliver_interactive(self, target: str, text: str, buttons) -> SendResult:"""Send a prompt with choice buttons (adapters without interactive support show text only)."""platform, chat_id, thread_id = parse_target(target)diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex b1696716..4846ae56 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -30,7 +30,7 @@ from ..connections import (SessionConnectionStore,effective as effective_connections,)-from ..inbox import VIS_INBOX, InboxStore, args_preview+from ..inbox import KIND_APPROVAL, VIS_INBOX, InboxStore, args_previewfrom ..inbox_routing import InboxRoutingfrom ..personas import PersonaRegistryfrom ..personas.registry import set_registry as set_persona_registry@@ -192,6 +192,17 @@ def _grant_offered(outcome, request) -> bool:return True+def _reply_hint(item, buttons) -> str:+ """How to answer this item in a chat that can't draw buttons. Naming the words the+ reply parser accepts is the difference between a prompt and a dead end."""+ if not buttons:+ return "(Open the app to respond.)"+ if getattr(item, "kind", "") == KIND_APPROVAL:+ return "Reply `approve` or `deny`, keeping the tag below."+ labels = ", ".join(b.label for b in buttons)+ return f"Reply with one of: {labels} — keeping the tag below."++def _approval_body(request) -> str:"""Approval card body: the tool's reason (if any) plus a compact preview of its args, so amirrored 'Run `write_file`?' shows the path/content rather than just the tool name.@@ -6524,8 +6535,12 @@ class SessionManager:# -- mirroring inbox items to a bound channel -------------------------------async def mirror_inbox_item(self, item) -> None:"""Mirror an Inbox item to its bound channel. Discrete choices (approve/deny, ask_user- options) render as BUTTONS — the item id rides in each, so a click resolves it- unambiguously. Free-text answers aren't offered over messaging (open the app).+ options) render as BUTTONS where the platform has them — the item id rides in each, so a+ click resolves it unambiguously. Where it doesn't (any adapter that hasn't implemented+ `send_interactive`, Telegram included), the same choice goes out as text carrying the+ `[ow:id]` tag and a line saying how to answer, because `_resolve_inbox_reply` needs that+ tag to correlate a reply. Without it the reader is shown a question they cannot answer+ from the surface it arrived on, and an agent suspended on that prompt waits forever."""from ..interactions import buttons_for@@ -6542,12 +6557,12 @@ class SessionManager:body = "\n".join(p for p in (item.title, item.body) if p).strip()buttons = buttons_for(item)try:- if buttons:+ if buttons and self.gateway.supports_interactive(target):await self.gateway.deliver_interactive(target, body, buttons)else:await self.gateway.deliver(target,- f"{body}\n(Open the app to respond.)\n[ow:{item.id}]".strip(),+ f"{body}\n{_reply_hint(item, buttons)}\n[ow:{item.id}]".strip(),)except Exception:passdiff --git a/tests/test_inbox_mirror_answerable.py b/tests/test_inbox_mirror_answerable.pynew file mode 100644index 00000000..060fafa6--- /dev/null+++ b/tests/test_inbox_mirror_answerable.py@@ -0,0 +1,85 @@+"""A mirrored prompt must be answerable from the surface it arrived on.++`buttons_for` returns buttons for approvals and option questions, but only an adapter+that implements `send_interactive` can draw them — the base class quietly sends plain+text instead. Mirroring on the presence of buttons alone therefore produced, on every+adapter but Slack, a question with no buttons, no `[ow:id]` tag for the reply parser to+correlate against, and no instructions: an agent suspended on that prompt waits forever.+"""++from __future__ import annotations++import asyncio++from coworker.inbox import KIND_APPROVAL+from coworker.providers import ModelCapabilities, ProviderClient+from coworker.server.manager import SessionManager+++class NoTurnsProvider(ProviderClient):+ def complete(self, *, model, messages, tools=None, **settings):+ raise AssertionError("no model turns expected")++ def capabilities(self, model):+ return ModelCapabilities()+++class GatewayStub:+ """Stands in for a platform pair: one that draws buttons, one that cannot."""++ def __init__(self, interactive: bool) -> None:+ self._interactive = interactive+ self.texts: list[str] = []+ self.interactive_sends: list[tuple] = []++ def supports_interactive(self, target: str) -> bool:+ return self._interactive++ async def deliver(self, target, text):+ self.texts.append(text)++ async def deliver_interactive(self, target, text, buttons):+ self.interactive_sends.append((target, text, buttons))+++def _manager(tmp_path) -> SessionManager:+ manager = SessionManager(data_dir=tmp_path / "data", provider=NoTurnsProvider())+ manager.inbox_routing.set_binding("default", channel="telegram", target="12345")+ return manager+++def test_approval_without_buttons_carries_tag_and_instructions(tmp_path):+ manager = _manager(tmp_path)+ manager.gateway = GatewayStub(interactive=False)+ item = manager.inbox.add_approval("s1", "Run `web_fetch`?", body="url: https://example.com")++ asyncio.run(manager.mirror_inbox_item(item))++ assert manager.gateway.interactive_sends == []+ (text,) = manager.gateway.texts+ assert f"[ow:{item.id}]" in text, "the reply parser correlates on this tag"+ assert "approve" in text.lower() and "deny" in text.lower()+ assert item.kind == KIND_APPROVAL+++def test_option_question_without_buttons_names_the_options(tmp_path):+ manager = _manager(tmp_path)+ manager.gateway = GatewayStub(interactive=False)+ item = manager.inbox.add_question("s1", "Which one?", options=["Blue", "Green"])++ asyncio.run(manager.mirror_inbox_item(item))++ (text,) = manager.gateway.texts+ assert f"[ow:{item.id}]" in text+ assert "Blue" in text and "Green" in text+++def test_buttons_still_used_where_the_platform_draws_them(tmp_path):+ manager = _manager(tmp_path)+ manager.gateway = GatewayStub(interactive=True)+ item = manager.inbox.add_approval("s1", "Run it?")++ asyncio.run(manager.mirror_inbox_item(item))++ assert manager.gateway.texts == []+ assert len(manager.gateway.interactive_sends) == 1