Skip to content
Python

fix(connectors): telegram approval owners, bound-chat check and refusal reply (#712)

Devika Verma58ca5a533199
diff --git a/coworker/connectors/gateway.py b/coworker/connectors/gateway.py
index 226966ee..17eb5fd3 100644
--- a/coworker/connectors/gateway.py
+++ b/coworker/connectors/gateway.py
@@ -30,6 +30,11 @@ logger = logging.getLogger("coworker.connectors")
_RECENT_CAP = 20 # most-recent distinct senders kept for chat-ID auto-capture
+# One sentence for a human whose approve/deny was refused by the owner check — sent as a
+# Slack ephemeral for button clicks and as a plain reply for tagged text replies on any
+# transport, so a refusal never looks like the bot ignoring them (OPE-217 / #712).
+APPROVAL_OWNER_REQUIRED = "Only a designated approval owner can respond to this request."
+
class Gateway:
def __init__(
@@ -93,7 +98,7 @@ class Gateway:
async def reject_interaction(
self,
event: InteractionEvent,
- text: str = "Only a designated approval owner can respond to this request.",
+ text: str = APPROVAL_OWNER_REQUIRED,
) -> None:
"""Best-effort private feedback for a rejected Slack button click."""
response_url = str(event.response_url or "")
diff --git a/coworker/server/app.py b/coworker/server/app.py
index 872073ad..b435b133 100644
--- a/coworker/server/app.py
+++ b/coworker/server/app.py
@@ -2235,6 +2235,20 @@ def create_app(manager: SessionManager) -> FastAPI:
str(body.get("user_id", "")), add=False
)
+ @app.post("/v1/connectors/telegram/approval-owners/add")
+ def telegram_approval_owner_add(body: dict) -> dict[str, Any]:
+ return manager.set_telegram_approval_owner(
+ str(body.get("user_id", "")),
+ add=True,
+ display_name=str(body.get("name", "")),
+ )
+
+ @app.post("/v1/connectors/telegram/approval-owners/remove")
+ def telegram_approval_owner_remove(body: dict) -> dict[str, Any]:
+ return manager.set_telegram_approval_owner(
+ str(body.get("user_id", "")), add=False
+ )
+
# -- audit / browser observability ------------------------------------------
@app.get("/v1/audit")
def audit_list(
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index 2026c0c4..b8d93539 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -4986,6 +4986,80 @@ class SessionManager:
if str(user_id).strip()
}
+ # -- Telegram approval owners (OPE-217 / #712) -------------------------------
+ # Telegram has no OAuth installer, so like manual Slack Socket Mode the humans who may
+ # resolve consequential prompts are listed explicitly on the connector profile.
+ def telegram_approval_owner_ids(self) -> set[str]:
+ profile = self.secrets.get("telegram:default") or {}
+ return {
+ str(user_id).strip()
+ for user_id in (profile.get("approval_owner_ids") or [])
+ if str(user_id).strip()
+ }
+
+ def set_telegram_approval_owner(
+ self, user_id: str, *, add: bool, display_name: str = ""
+ ) -> dict[str, Any]:
+ """Edit the Telegram approval owners. Owner status implies inbound permission."""
+ user_id = str(user_id).strip()
+ if not user_id:
+ return {"ok": False, "error": "user_id required"}
+ profile = self.secrets.get("telegram:default")
+ if not profile:
+ return {"ok": False, "error": "Telegram is not connected."}
+ owners = self.telegram_approval_owner_ids()
+ if add:
+ owners.add(user_id)
+ else:
+ owners.discard(user_id)
+ profile["approval_owner_ids"] = sorted(owners)
+ if add:
+ allowed = set(profile.get("allowed_users") or [])
+ allowed.add(user_id)
+ profile["allowed_users"] = sorted(allowed)
+ self.secrets.put("telegram:default", profile)
+ if display_name:
+ self._note_person("telegram", user_id, display_name)
+ if self.gateway is not None and "telegram" in self.gateway.settings:
+ self.gateway.settings["telegram"].allowed_users = set(
+ profile.get("allowed_users") or []
+ )
+ return {
+ "ok": True,
+ "approval_owner_ids": sorted(owners),
+ "allowed_users": list(profile.get("allowed_users") or []),
+ }
+
+ def _telegram_actor_owns_item(
+ self, item, *, actor_id: str, chat_id: str
+ ) -> bool:
+ """Authorize a Telegram resolution of a protected item.
+
+ Two conditions, mirroring the Slack rule (owner + bound channel):
+
+ - the reply must arrive in the chat the item's inbox is bound to — a reply from any
+ other chat is refused whoever sent it (an in-app-only inbox is not remotely
+ resolvable at all);
+ - the sender must be an approval owner. With owners configured that is the list.
+ With none configured, a binding to a private chat means exactly one allowed
+ human lives there (a Telegram DM's chat id IS the user's id), so that person is
+ the owner — single-user bots need no setup. A group binding (negative chat id)
+ with no owners configured refuses: a whole group never gains approval rights by
+ accident.
+ """
+ binding = self.inbox_routing.binding_for(item.inbox)
+ if binding.channel != "telegram" or not binding.target:
+ return False
+ bound_chat = str(binding.target).strip()
+ if str(chat_id or "").strip() != bound_chat or not actor_id:
+ return False
+ owners = self.telegram_approval_owner_ids()
+ if owners:
+ return actor_id in owners
+ if bound_chat.startswith("-"):
+ return False # group/supergroup: owners must be chosen explicitly
+ return actor_id == bound_chat
+
def set_slack_approval_owner(
self, user_id: str, *, add: bool, display_name: str = ""
) -> dict[str, Any]:
@@ -5089,8 +5163,9 @@ class SessionManager:
- cross-transport is refused: an item bound to one channel can only be resolved from
that same channel (an in-app-only item is not remotely resolvable at all);
- Slack defers to the existing owner + bound-channel check;
- - no other transport (e.g. Telegram) has an approval-owner model, so it cannot
- resolve protected items remotely — they stay pending for in-app resolution.
+ - Telegram checks the bound chat and its own approval-owner list (OPE-217);
+ - any other transport has no approval-owner model, so it cannot resolve protected
+ items remotely — they stay pending for in-app resolution.
"""
binding = self.inbox_routing.binding_for(item.inbox)
if binding.channel and binding.channel != platform:
@@ -5099,8 +5174,34 @@ class SessionManager:
return self._slack_actor_owns_item(
item, actor_id=actor_id, chat_id=chat_id, team_id=team_id
)
+ if platform == "telegram":
+ return self._telegram_actor_owns_item(
+ item, actor_id=actor_id, chat_id=chat_id
+ )
return False
+ def _notify_refused_reply(self, platform: str, chat_id: str, thread_id=None) -> None:
+ """Tell a human their tagged reply was refused by the owner check. Best-effort and
+ off the caller's path: the resolver runs synchronously inside the gateway's loop, so
+ the send is scheduled as a task; with no running loop (tests, CLI) it is skipped."""
+ if self.gateway is None or not platform or not chat_id:
+ return
+ from ..connectors.base import format_target
+ from ..connectors.gateway import APPROVAL_OWNER_REQUIRED
+
+ target = format_target(platform, str(chat_id), thread_id)
+
+ async def _send() -> None:
+ try:
+ await self.gateway.deliver(target, APPROVAL_OWNER_REQUIRED)
+ except Exception:
+ logger.debug("refusal reply to %s failed", target, exc_info=True)
+
+ try:
+ asyncio.get_running_loop().create_task(_send())
+ except RuntimeError:
+ pass
+
def set_inbox_binding(
self, name: str, *, channel: Optional[str], target: str
) -> dict[str, Any]:
@@ -6150,8 +6251,22 @@ class SessionManager:
chat_id=getattr(event, "chat_id", "") or "",
team_id=getattr(event, "team_id", None),
):
+ platform = str(getattr(event, "platform", "") or "")
if self.gateway is not None:
+ # Slack answers with an ephemeral; everywhere else the gateway's
+ # reject path is a no-op, so send the same sentence as a plain reply.
await self.gateway.reject_interaction(event)
+ if platform != "slack":
+ from ..connectors.base import format_target
+ from ..connectors.gateway import APPROVAL_OWNER_REQUIRED
+
+ try:
+ await self.gateway.deliver(
+ format_target(platform, str(getattr(event, "chat_id", "") or "")),
+ APPROVAL_OWNER_REQUIRED,
+ )
+ except Exception:
+ logger.debug("refusal reply failed", exc_info=True)
return
already = item is not None and item.state != "pending"
resolved = await self.resolve_inbox(item_id, resolution)
@@ -6192,6 +6307,11 @@ class SessionManager:
chat_id=getattr(event.source, "chat_id", "") or "",
team_id=getattr(event.source, "team_id", None),
):
+ self._notify_refused_reply(
+ str(getattr(event.source, "platform", "") or ""),
+ getattr(event.source, "chat_id", "") or "",
+ getattr(event.source, "thread_id", None),
+ )
return False
return self.inbox.resolve(item_id, resolution)
diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.ts
index cc276b7f..2cb4d204 100644
--- a/surfaces/gui/src/api.ts
+++ b/surfaces/gui/src/api.ts
@@ -873,7 +873,7 @@ export interface Connector {
mcp?: boolean; // MCP-backed one-click (vendor-hosted MCP + local OAuth — no cloud sign-in)
allowed_users: string[]; // the allow-list (managed inline in the Connectors tab)
allowed_user_names?: Record<string, string | null>; // id → display name (people directory)
- approval_owner_ids?: string[]; // Manual Slack: humans allowed to resolve approvals
+ approval_owner_ids?: string[]; // Manual Slack / Telegram: humans allowed to resolve approvals
approval_owner_names?: Record<string, string | null>;
recent?: RecentSender[]; // recently-seen senders on a connected two-way connector
unauthorized?: ParkedMessage[]; // parked messages from unallowed senders (§19)
@@ -2737,6 +2737,32 @@ export async function removeSlackApprovalOwner(
return res.json();
}
+export async function addTelegramApprovalOwner(
+ userId: string,
+ displayName?: string,
+): Promise<{ ok: boolean; error?: string }> {
+ const res = await fetch(`${httpBase()}/v1/connectors/telegram/approval-owners/add`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ user_id: userId,
+ ...(displayName ? { name: displayName } : {}),
+ }),
+ });
+ return res.json();
+}
+
+export async function removeTelegramApprovalOwner(
+ userId: string,
+): Promise<{ ok: boolean; error?: string }> {
+ const res = await fetch(`${httpBase()}/v1/connectors/telegram/approval-owners/remove`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ user_id: userId }),
+ });
+ return res.json();
+}
+
/** Stop relaying one managed Slack workspace (the app stays installed in Slack). */
export async function disconnectSlackWorkspace(teamId: string): Promise<{ ok: boolean; error?: string; remaining_workspaces?: number }> {
const res = await fetch(
diff --git a/surfaces/gui/src/components/ManageTabs.tsx b/surfaces/gui/src/components/ManageTabs.tsx
index 6598b3ed..0a880578 100644
--- a/surfaces/gui/src/components/ManageTabs.tsx
+++ b/surfaces/gui/src/components/ManageTabs.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { getI18n, useTranslation } from "react-i18next";
import {
+ addTelegramApprovalOwner,
allowUser,
connectConnector,
connectManaged,
@@ -9,6 +10,7 @@ import {
getSettings,
getSubscriptions,
removeModel,
+ removeTelegramApprovalOwner,
resolveUnauthorized,
unsubscribeChannel,
setDefaultModel,
@@ -436,6 +438,95 @@ export function AllowlistBlock({
);
}
+// Who may APPROVE from this Telegram bot — a stricter list than "allowed to message"
+// (OPE-217 / #712). Empty means: the one person in a bound private chat may approve;
+// a bound group needs owners chosen here before anyone can.
+export function TelegramApprovalOwnersBlock({ c, onChanged }: { c: Connector; onChanged: () => void }) {
+ const { t } = useTranslation();
+ const [err, setErr] = useState<string | null>(null);
+ const [pick, setPick] = useState("");
+ const owners = c.approval_owner_ids ?? [];
+ const names = { ...(c.allowed_user_names ?? {}), ...(c.approval_owner_names ?? {}) };
+ const candidates = c.allowed_users.filter((u) => !owners.includes(u));
+ const label = (u: string) => names[u] || u;
+ const add = async (userId: string) => {
+ const result = await addTelegramApprovalOwner(userId, names[userId] || undefined);
+ if (!result.ok) {
+ setErr(result.error || t("manage.owners_update_failed"));
+ return;
+ }
+ setErr(null);
+ setPick("");
+ onChanged();
+ };
+ const remove = async (userId: string) => {
+ const result = await removeTelegramApprovalOwner(userId);
+ if (!result.ok) {
+ setErr(result.error || t("manage.owners_update_failed"));
+ return;
+ }
+ setErr(null);
+ onChanged();
+ };
+ return (
+ <div className="border-t border-line px-3.5 py-3" data-testid="telegram-approval-owners">
+ <div className={SEC_H + " mb-1"}>{t("manage.approval_owners")}</div>
+ <div className="text-meta text-faint mb-2">{t("manage.approval_owners_help")}</div>
+ <div className="flex flex-wrap items-center gap-1.5">
+ {owners.length === 0 && (
+ <span className="text-meta text-faint">{t("manage.approval_owners_empty")}</span>
+ )}
+ {owners.map((u) => (
+ <span
+ key={u}
+ className="inline-flex items-center gap-1.5 pl-2 pr-1 py-1 rounded-full bg-paper border border-line text-meta"
+ title={t("manage.id_title", { id: u })}
+ data-testid={`telegram-approval-owner-${u}`}
+ >
+ <span className="w-4 h-4 rounded-full bg-accentSoft text-accent grid place-items-center text-[9px] font-bold">
+ {initials(label(u))}
+ </span>
+ {label(u)}
+ <button
+ className="w-4 h-4 grid place-items-center text-faint hover:text-danger"
+ title={t("common.remove")}
+ onClick={() => remove(u)}
+ >
+ ×
+ </button>
+ </span>
+ ))}
+ {candidates.length > 0 && (
+ <span className="inline-flex items-center gap-1">
+ <select
+ className="text-meta bg-paper border border-line rounded-md px-1.5 py-0.5"
+ value={pick}
+ onChange={(e) => setPick(e.target.value)}
+ data-testid="telegram-approval-owner-pick"
+ >
+ <option value="">{t("manage.approval_owners_pick")}</option>
+ {candidates.map((u) => (
+ <option key={u} value={u}>
+ {label(u)}
+ </option>
+ ))}
+ </select>
+ <button
+ className="text-meta px-2 py-0.5 rounded-md bg-accent text-white disabled:opacity-50"
+ disabled={!pick}
+ onClick={() => pick && add(pick)}
+ data-testid="telegram-approval-owner-add"
+ >
+ {t("manage.add_btn")}
+ </button>
+ </span>
+ )}
+ {err && <span className="basis-full text-meta text-warnInk">{err}</span>}
+ </div>
+ </div>
+ );
+}
+
export function ConnectorTools({ c, onChanged }: { c: Connector; onChanged: () => void }) {
const { t } = useTranslation();
const toggle = async (toolName: string, enabled: boolean) => {
diff --git a/surfaces/gui/src/components/connectors/ConnectorsSection.tsx b/surfaces/gui/src/components/connectors/ConnectorsSection.tsx
index 3004c923..66ada9d6 100644
--- a/surfaces/gui/src/components/connectors/ConnectorsSection.tsx
+++ b/surfaces/gui/src/components/connectors/ConnectorsSection.tsx
@@ -13,7 +13,7 @@ import {
} from "../../api";
import { McpServerDetail } from "./CustomMcp";
import { ConnectorBadge } from "../../connectors/ConnectorIcon";
-import { AllowlistBlock, ConnectorTools, ListeningSessionsBlock, UnauthorizedBlock } from "../ManageTabs";
+import { AllowlistBlock, ConnectorTools, ListeningSessionsBlock, TelegramApprovalOwnersBlock, UnauthorizedBlock } from "../ManageTabs";
import { AccountsDetail } from "./AccountsDetail";
import { AvailableDetail } from "./AvailableDetail";
import { CalendarDetail } from "./CalendarDetail";
@@ -200,6 +200,7 @@ function GenericDetail({
{c.two_way && (
<div className={GRP + " mt-4"}>
<AllowlistBlock c={c} onChanged={onChanged} />
+ {c.name === "telegram" && <TelegramApprovalOwnersBlock c={c} onChanged={onChanged} />}
<UnauthorizedBlock c={c} onChanged={onChanged} />
{/* Channel subscriptions are a chat-platform concept — GitHub is two_way via the
relay (inbound mentions) but has no channels. */}
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index ed2c5653..3a521fe8 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -1206,6 +1206,11 @@
"add_btn": "Add",
"allowed_empty": "nobody yet — Allow a recent sender →",
"allowed_to_message": "Allowed to message",
+ "approval_owners": "Allowed to approve",
+ "approval_owners_empty": "Nobody chosen. In a private chat, the person the Inbox is mirrored to may approve. In a group, choose owners here first.",
+ "approval_owners_help": "Who may approve commands, folder access and plans from this bot. Everyone else allowed to message can still chat and answer questions.",
+ "approval_owners_pick": "Choose an allowed user…",
+ "owners_update_failed": "could not update approval owners",
"cancel": "cancel",
"check_browser": "Check your browser…",
"coming_soon": "Coming soon",
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 0a967356..683b427e 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -1189,6 +1189,11 @@
"add_btn": "添加",
"allowed_empty": "暂无 —— 允许一位近期发送者 →",
"allowed_to_message": "允许发送消息",
+ "approval_owners": "允许批准",
+ "approval_owners_empty": "尚未选择。私聊中,收件箱镜像到的那个人可以批准。群组请先在此选择负责人。",
+ "approval_owners_help": "谁可以通过此机器人批准命令、文件夹访问和计划。其他允许发送消息的人仍可聊天和回答问题。",
+ "approval_owners_pick": "选择一位已允许的用户…",
+ "owners_update_failed": "无法更新批准负责人",
"cancel": "取消",
"check_browser": "请查看你的浏览器…",
"coming_soon": "即将推出",
diff --git a/tests/test_telegram_approval_owners.py b/tests/test_telegram_approval_owners.py
new file mode 100644
index 00000000..e5b8f94d
--- /dev/null
+++ b/tests/test_telegram_approval_owners.py
@@ -0,0 +1,227 @@
+"""Telegram approval owners (OPE-217 / #712), the follow-up to #567.
+
+#567 made `_actor_owns_protected_item` refuse every Telegram reply because Telegram had no
+approval-owner model. These tests pin the model that replaces that blanket refusal:
+
+- the reply must arrive in the chat the item's inbox is bound to;
+- with owners configured, the sender must be one of them;
+- with no owners and a private-chat binding, the one allowed human in that chat is the
+ owner (a Telegram DM's chat id is the user's id), so single-user bots need no setup;
+- with no owners and a group binding, nobody may approve until owners are chosen;
+- a refused tagged reply gets a one-line answer instead of silence.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+from coworker.connectors.base import InteractionEvent, MessageEvent, SessionSource
+from coworker.connectors.gateway import APPROVAL_OWNER_REQUIRED
+from coworker.interactions import encode
+from coworker.providers import ModelCapabilities, ProviderClient
+from coworker.server.manager import SessionManager
+
+OWNER = "8894780782" # bound DM: chat id == user id
+OTHER = "8883353200" # allowed to message, never an owner
+GROUP = "-1001234567890"
+
+
+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:
+ """Records outbound text so the refusal reply can be asserted."""
+
+ def __init__(self):
+ self.sent: list[tuple[str, str]] = []
+ self.rejections: list = []
+ self.settings: dict = {}
+
+ async def deliver(self, target, text):
+ self.sent.append((target, text))
+
+ async def reject_interaction(self, event, text=""):
+ self.rejections.append(getattr(event, "user_id", None))
+
+ async def update_message(self, *args):
+ raise AssertionError("a refused interaction must not update the message")
+
+
+def _manager(tmp_path, *, owners=None, allowed=(OWNER, OTHER), bind_to=OWNER) -> SessionManager:
+ manager = SessionManager(data_dir=tmp_path / "data", provider=NoTurnsProvider())
+ profile = {"bot_token": "123:abc", "enabled": True, "allowed_users": list(allowed)}
+ if owners is not None:
+ profile["approval_owner_ids"] = list(owners)
+ manager.secrets.put("telegram:default", profile)
+ if bind_to is not None:
+ manager.inbox_routing.set_binding("default", channel="telegram", target=bind_to)
+ return manager
+
+
+def _reply(text: str, *, user_id: str, chat_id: str) -> MessageEvent:
+ return MessageEvent(
+ text=text,
+ source=SessionSource(
+ platform="telegram",
+ chat_id=chat_id,
+ user_id=user_id,
+ user_name="someone",
+ chat_type="group" if chat_id.startswith("-") else "dm",
+ ),
+ )
+
+
+def _approve(manager, item, *, user_id, chat_id) -> bool:
+ return manager._resolve_inbox_reply(
+ _reply(f"approve [ow:{item.id}]", user_id=user_id, chat_id=chat_id)
+ )
+
+
+# -- no owners configured, bound to the owner's private chat ------------------------------
+
+def test_bound_dm_user_approves_without_configuring_owners(tmp_path):
+ manager = _manager(tmp_path)
+ item = manager.inbox.add_approval("s1", "Run it?")
+ assert _approve(manager, item, user_id=OWNER, chat_id=OWNER) is True
+ assert manager.inbox.get(item.id).state == "resolved"
+ assert manager.inbox.get(item.id).resolution == "allow"
+
+
+def test_allowed_non_owner_replying_from_their_own_dm_is_refused(tmp_path):
+ # The #519 scenario: allowed to message, replies from a different chat than the bound one.
+ manager = _manager(tmp_path)
+ item = manager.inbox.add_approval("s1", "Run it?")
+ consumed = _approve(manager, item, user_id=OTHER, chat_id=OTHER)
+ assert consumed is True # the tag was recognised, so the message is not routed as a turn
+ assert manager.inbox.get(item.id).state == "pending"
+
+
+def test_owner_replying_from_another_chat_is_refused(tmp_path):
+ manager = _manager(tmp_path)
+ item = manager.inbox.add_approval("s1", "Run it?")
+ assert _approve(manager, item, user_id=OWNER, chat_id=GROUP) is True
+ assert manager.inbox.get(item.id).state == "pending"
+
+
+# -- owners configured -------------------------------------------------------------------
+
+def test_configured_owner_approves_and_allowed_non_owner_is_refused(tmp_path):
+ manager = _manager(tmp_path, owners=[OWNER])
+ item = manager.inbox.add_approval("s1", "Run it?")
+ assert _approve(manager, item, user_id=OTHER, chat_id=OWNER) is True
+ assert manager.inbox.get(item.id).state == "pending"
+ assert _approve(manager, item, user_id=OWNER, chat_id=OWNER) is True
+ assert manager.inbox.get(item.id).state == "resolved"
+
+
+def test_group_binding_with_owners_lets_only_owners_approve(tmp_path):
+ manager = _manager(tmp_path, owners=[OWNER], bind_to=GROUP)
+ item = manager.inbox.add_approval("s1", "Run it?")
+ assert _approve(manager, item, user_id=OTHER, chat_id=GROUP) is True
+ assert manager.inbox.get(item.id).state == "pending"
+ assert _approve(manager, item, user_id=OWNER, chat_id=GROUP) is True
+ assert manager.inbox.get(item.id).state == "resolved"
+
+
+def test_group_binding_without_owners_refuses_everyone(tmp_path):
+ manager = _manager(tmp_path, bind_to=GROUP)
+ item = manager.inbox.add_approval("s1", "Run it?")
+ for user in (OWNER, OTHER):
+ assert _approve(manager, item, user_id=user, chat_id=GROUP) is True
+ assert manager.inbox.get(item.id).state == "pending"
+
+
+def test_in_app_only_inbox_is_not_resolvable_from_telegram(tmp_path):
+ manager = _manager(tmp_path, bind_to=None)
+ item = manager.inbox.add_approval("s1", "Run it?")
+ assert _approve(manager, item, user_id=OWNER, chat_id=OWNER) is True
+ assert manager.inbox.get(item.id).state == "pending"
+
+
+def test_questions_stay_answerable_by_any_allowed_member(tmp_path):
+ manager = _manager(tmp_path)
+ question = manager.inbox.add_question("s1", "Which region?", options=["A", "B"])
+ assert manager._resolve_inbox_reply(
+ _reply(f"A [ow:{question.id}]", user_id=OTHER, chat_id=OTHER)
+ ) is True
+ assert manager.inbox.get(question.id).resolution == "A"
+
+
+# -- owner list editing -------------------------------------------------------------------
+
+def test_adding_an_owner_implies_allowed_and_removal_keeps_allowed(tmp_path):
+ manager = _manager(tmp_path, allowed=())
+ assert manager.set_telegram_approval_owner("42", add=True, display_name="Rohit")["ok"]
+ profile = manager.secrets.get("telegram:default")
+ assert profile["approval_owner_ids"] == ["42"]
+ assert profile["allowed_users"] == ["42"]
+ assert manager.set_telegram_approval_owner("42", add=False)["ok"]
+ profile = manager.secrets.get("telegram:default")
+ assert profile["approval_owner_ids"] == []
+ assert profile["allowed_users"] == ["42"]
+
+
+def test_owner_edit_requires_a_connected_telegram(tmp_path):
+ manager = SessionManager(data_dir=tmp_path / "data", provider=NoTurnsProvider())
+ result = manager.set_telegram_approval_owner("42", add=True)
+ assert not result["ok"]
+
+
+# -- refusal feedback ---------------------------------------------------------------------
+
+def test_refused_text_reply_gets_a_one_line_answer(tmp_path):
+ manager = _manager(tmp_path)
+ gateway = GatewayStub()
+ manager.gateway = gateway
+ item = manager.inbox.add_approval("s1", "Run it?")
+
+ async def run():
+ # The resolver is called synchronously from inside the gateway's loop in production.
+ assert _approve(manager, item, user_id=OTHER, chat_id=OTHER) is True
+ await asyncio.sleep(0) # let the scheduled send run
+
+ asyncio.run(run())
+ assert manager.inbox.get(item.id).state == "pending"
+ assert gateway.sent == [(f"telegram:{OTHER}", APPROVAL_OWNER_REQUIRED)]
+
+
+def test_accepted_reply_sends_no_refusal(tmp_path):
+ manager = _manager(tmp_path)
+ gateway = GatewayStub()
+ manager.gateway = gateway
+ item = manager.inbox.add_approval("s1", "Run it?")
+
+ async def run():
+ assert _approve(manager, item, user_id=OWNER, chat_id=OWNER) is True
+ await asyncio.sleep(0)
+
+ asyncio.run(run())
+ assert manager.inbox.get(item.id).state == "resolved"
+ assert gateway.sent == []
+
+
+def test_refused_button_click_on_telegram_gets_a_plain_reply(tmp_path):
+ manager = _manager(tmp_path)
+ gateway = GatewayStub()
+ manager.gateway = gateway
+ item = manager.inbox.add_approval("s1", "Run it?")
+ asyncio.run(
+ manager._on_interaction(
+ InteractionEvent(
+ platform="telegram",
+ chat_id=OTHER,
+ message_id="1",
+ value=encode(item.id, "allow"),
+ user_id=OTHER,
+ user_name="someone",
+ )
+ )
+ )
+ assert manager.inbox.get(item.id).state == "pending"
+ assert gateway.sent == [(f"telegram:{OTHER}", APPROVAL_OWNER_REQUIRED)]
+ assert gateway.rejections == [OTHER] # the generic reject path still runs (no-op off Slack)