diff --git a/README.md b/README.md index a5ec06a..f618558 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ OpenMate 是一组开源(MIT)的 [Persona](https://github.com/nwverse/person | 功能 | 说明 | | --- | --- | | 登录 | 扫码登录,支持飞书和 Lark(国际版),可以配置代理 | -| 收件箱 | 最近 3 天、最多 200 个会话,每个会话一条:私聊里没回的、群里 @我 没回的、群里的新消息。没有 @我 的群消息按规则直接判为噪音,不调用模型;我最后回复了就算结束。可以写自己的分拣规则 | +| 收件箱 | 最近 3 天、最多 200 个会话:私聊里没回的、群里 @我 没回的、群里的新消息。私聊每个会话一条;群里话题外说的话是这个群的一条(id 照旧是会话 id),每个话题再各一条:话题里的上下文、“我回复了就算结束”、会话页(可往前翻、可在页里回复)和回复(发进这个话题)都只算这个话题;普通群里话题的根消息是在群聊主界面说的,仍算在群的那条里,我在这个话题里回复了,群的那条也算结束;话题模式的群每个话题一条。没有 @我 的群消息按规则直接判为噪音,不调用模型;在飞书里设了“消息免打扰”的群,没有 @我 的消息直接算已读、不留在待处理里(照旧存进知识库;@我 的照常分拣,之后的闲聊不顶掉它;读不出免打扰状态时照旧)。设置“照常分拣的群”里列的群,没有 @我 的消息也交给 AI 分拣(免打扰也一样);设置“不交给收件箱 AI 的私聊”里列的私聊照常进收件箱,但不调用模型,一律算“要你处理”,条目里也不带消息内容(打开会话看)。两项默认都空。我最后回复了就算结束。可以写自己的分拣规则 | | 收件箱回复 | 以你本人身份发出,同一条回复只发一次 | | 会话页 | 每页最多 50 条,可以往前翻,本地没有的旧消息会从飞书补拉;图片 4 MB 以内可以预览 | | 知识库 | 按游标增量归档聊天记录,附件 20 MB 以内按需下载 | diff --git a/core/openmate_core/app.py b/core/openmate_core/app.py index 593fc0e..f7768e0 100644 --- a/core/openmate_core/app.py +++ b/core/openmate_core/app.py @@ -179,6 +179,8 @@ def __init__(self, platform: Platform, timing: Optional[Timing] = None, backend_ self.people: Optional[People] = None # who is a bot (made at the start, with the store) self._avatars_by: Optional[threading.Thread] = None # the round asking the service for chats' pictures self._avatars_tried: Dict[str, float] = {} # chat id → when its picture was last asked for (monotonic) + self._mutes_by: Optional[threading.Thread] = None # the round asking the service whether groups are muted + self._mutes_tried: Dict[str, float] = {} # chat id → when its mute state was last asked for (monotonic) self._methods = { "status": self.m_status, "tools.list": lambda p: {"tools": toolmod.read_tools(self)}, @@ -914,6 +916,8 @@ def _bind_account(self, acct: Account) -> None: with self._done_mu: # a done round of the account before must not write into this one's with self._wipe_mu: # nor an ingest that asked the service before the switch self.store.wipe_account_data(acct.id) # another account: the previous one's chats forgotten + with self.lock: + self._mutes_tried.clear() # its groups are asked about for the new account at once self._names.clear() # and the names it looked up with self.lock: self._account_epoch += 1 @@ -1706,26 +1710,120 @@ def m_inbox_collect(self, params: dict) -> dict: if self.store is None: return {"things": []} t = self.timing + epoch = self.account_epoch() # one account's store: another's sign-in while it reads ends this read rules = str(self.config.get("triage_rules") or "").strip() + triage = set(_id_list(self._declared("inbox_triage_chats"))) # groups whose every message the model sorts + private = set(_id_list(self._declared("inbox_private_dms"))) # direct chats no Inbox model reads things = [] me = self.me_name() - for chat in self.store.chats_since(time.time() - t.inbox_window, t.inbox_most): - rows = self.store.inbox_rows(chat["id"], 60) - thing = views.inbox_thing(chat, rows, platform=self.platform.name, tz=self.tz, me=me, rules=rules, - can_reply=self.signed_in) - if thing is not None: + since = time.time() - t.inbox_window + chats = self.store.chats_since(since, t.inbox_most) + topics_from = 0.0 + if self.platform.inbox_topics: + # when a group's topics first became items of their own here: what a topic group said before then was its + # one item, which is handed over done (views.inbox_things) so no item of the version before stays open + try: + topics_from = float(self.store.meta_get("inbox_topics_at") or 0) + except ValueError: + topics_from = 0.0 + if not topics_from: + topics_from = time.time() + self.store.meta_set("inbox_topics_at", repr(topics_from)) + has_mute = self.backend is not None and getattr(self.backend, "has_mute", False) + groups = [c["id"] for c in chats if views.chat_kind(c) == "group"] + mutes = self.store.mutes(groups, self.store.meta_get("account_id")) if has_mute else {} + for chat in chats: + cid = chat["id"] + topics = self.platform.inbox_topics and views.chat_kind(chat) == "group" + # a group's topics each need their own lines: a busy topic must not push another's @ out of the window + rows = self.store.inbox_rows(cid, TOPIC_ROWS if topics else 60) + dm = views.chat_kind(chat) == "dm" + # listed by its id: whatever kind the store took it for (a chat first kept when its kind could not be read + # is a group till it is); by the other person: a direct chat's + hidden = bool(private) and (cid in private or (dm and (chat.get("peer_id") or self.store.dm_peer(cid)) in private)) + for thing in views.inbox_things(chat, rows, topics=topics, since=since, until=topics_from, + platform=self.platform.name, + tz=self.tz, me=me, rules=rules, can_reply=self.signed_in, + mute=mutes.get(cid, ("", 0.0))[0], triage=cid in triage, + private=hidden): + thing["_chat"] = cid things.append(thing) + if has_mute and groups: + now = time.time() + self._ask_mutes([c for c in groups if c not in mutes or mutes[c][1] < now - t.mute_ttl]) if things and self.backend is not None and getattr(self.backend, "has_avatars", False): - known = self.store.avatars(th["thread"] for th in things) + known = self.store.avatars(th["_chat"] for th in things) for th in things: - value = known.get(th["thread"], ("", 0.0))[0] + value = known.get(th["_chat"], ("", 0.0))[0] if value: th["avatar"] = value now = time.time() - self._ask_avatars([th["thread"] for th in things - if th["thread"] not in known or known[th["thread"]][1] < now - t.avatar_ttl]) + self._ask_avatars(list(dict.fromkeys(th["_chat"] for th in things + if th["_chat"] not in known or known[th["_chat"]][1] < now - t.avatar_ttl))) + for th in things: + del th["_chat"] + if epoch != self.account_epoch(): + return {"things": []} # read partly for another account (its rows, its pictures): none of it is handed over return {"things": things} + def _declared(self, name: str) -> Any: + """A setting's value, only where this extension's manifest has the setting (None else): a platform without it + never acts on one a config may carry.""" + props = ((self.manifest.get("configuration") or {}).get("properties") or {}) + return self.config.get(name) if name in props else None + + def _ask_mutes(self, chat_ids: List[str]) -> None: + """Ask the service, in the background, whether these groups are muted (none known, or an hour old), each at + most once per mute_retry; when one changed, the Inbox is told (connector.changed) to read the rows again.""" + t = self.timing + now = time.monotonic() + with self.lock: + if not chat_ids or self._mutes_by is not None or not self.signed_in or self.link != "up": + return + due = [c for c in chat_ids if self._mutes_tried.get(c, -1e18) <= now - t.mute_retry][:t.mute_batch] + if not due: + return + for c in due: + self._mutes_tried[c] = now + if len(self._mutes_tried) > 4 * t.inbox_most: # the ones asked about longest ago go first + for c, _ in sorted(self._mutes_tried.items(), key=lambda kv: kv[1])[:len(self._mutes_tried) // 2]: + del self._mutes_tried[c] + epoch = self.account_epoch() + self._mutes_by = threading.Thread(target=self._mutes_round, args=(due, epoch), name="openmate-mutes", + daemon=True) + self._mutes_by.start() + + def _mutes_round(self, due: List[str], epoch: int) -> None: + changed = False + try: + owner = self.store.meta_get("account_id") + before = self.store.mutes(due, owner) + for chat_id in due: + if self.closing.is_set() or not self.owns(epoch): + return + try: + muted = self.backend.chat_mute(chat_id) + except BackendError as e: + log.info("a group's mute state was not read: %s", e.kind) + muted = None # not known now: the Inbox goes the old way until it is read again (mute_ttl) + except Exception: + log.exception("chat_mute failed") + muted = None + state = "unknown" if muted is None else ("muted" if muted else "normal") + with self.owned(epoch) as ok: # another account's sign-in meanwhile: its store is not written + if not ok: + return + if self.store.get_chat(chat_id) is None: + continue + self.store.set_mute(chat_id, state, owner) + if state != before.get(chat_id, ("", 0.0))[0]: + changed = True + finally: + with self.lock: + self._mutes_by = None + if changed and self.changed is not None: + self.changed.mark("inbox") + def _ask_avatars(self, chat_ids: List[str]) -> None: """Ask the service, in the background, for the pictures of these chats (none, or a day old), each at most once per avatar_retry; when one changed, the Inbox is told (connector.changed) to read the rows again.""" @@ -1787,7 +1885,8 @@ def _avatars_round(self, due: List[str], epoch: int) -> None: def m_inbox_reply(self, params: dict) -> dict: if params.get("changes"): raise RPCError("%s会话不支持修改状态,只能回复文字" % self.platform.name) - chat_id = str(params.get("thread") or "") + thread = str(params.get("thread") or "") + chat_id, topic = self._thread_of(thread) text = str(params.get("text") or "") epoch = self.account_epoch() # the inbox it was asked from is this account's if not text.strip(): @@ -1800,7 +1899,14 @@ def m_inbox_reply(self, params: dict) -> dict: raise RPCError("本地没有这个%s会话" % self.platform.name) reply_to, root = None, None last_row = self.store.message(chat_id, last) if last else None - if last_row is not None and not last_row.get("mine"): + if topic: + # a topic's item: the reply goes into that topic, under its last line of someone else's (else its root) + if last_row is not None and not last_row.get("mine") and (last_row.get("root_id") or last_row["id"]) == topic: + reply_to = last_row["id"] + else: + reply_to = topic + root = topic + elif last_row is not None and not last_row.get("mine"): if last_row.get("root_id"): reply_to, root = last_row["id"], last_row["root_id"] elif chat.get("kind") != "dm": @@ -1809,7 +1915,7 @@ def m_inbox_reply(self, params: dict) -> dict: if client_id: key = "inbox:" + client_id else: - key = "inbox:" + hashlib.sha256("\x00".join([chat_id, last, text]).encode("utf-8")).hexdigest() + key = "inbox:" + hashlib.sha256("\x00".join([thread, last, text]).encode("utf-8")).hexdigest() def send(): if not self.owns(epoch): # another account signed in since it was asked: not said as that one @@ -1850,15 +1956,25 @@ def chat_from_service(self, chat_id: str, epoch: Optional[int] = None) -> Option self.store.upsert_chat(info) return self.store.get_chat(chat_id) + def _thread_of(self, thread: str) -> Tuple[str, str]: + """(chat id, topic root) an Inbox thread names: ":" is a group topic's (inbox_topics), anything + else the whole chat's ("" root).""" + if self.platform.inbox_topics and ":" in thread: + chat_id, _, root = thread.partition(":") + if chat_id and root: + return chat_id, root + return thread, "" + def m_thread_page(self, params: dict) -> dict: - chat_id = str(params.get("thread") or "") + thread = str(params.get("thread") or "") + chat_id, topic = self._thread_of(thread) if not chat_id or self.store is None: raise RPCError("缺少会话") epoch = self.account_epoch() # the page is of one account's store: another's sign-in meanwhile ends it limit = _int(params.get("limit"), 20, 1, THREAD_MOST) before = params.get("before") or "" before_pos: Optional[int] = None - if before: + if before and not topic: try: before_pos = int(before) except ValueError: @@ -1873,6 +1989,8 @@ def m_thread_page(self, params: dict) -> dict: if epoch != self.account_epoch(): raise RPCError("刚换了%s账号,请重新打开这个会话" % self.platform.name) raise RPCError("本地没有这个%s会话" % self.platform.name) + if topic: + return self._topic_page(chat, chat_id, topic, thread, limit, str(before), epoch) rows = [r for r in self.store.messages_before(chat_id, before_pos, limit) if views.has_content(r)] at_start = False if len(rows) < limit: @@ -1904,6 +2022,43 @@ def m_thread_page(self, params: dict) -> dict: raise RPCError("刚换了%s账号,请重新打开这个会话" % self.platform.name) return page + def _topic_page(self, chat: dict, chat_id: str, topic: str, thread: str, limit: int, before: str, + epoch: int) -> dict: + """One topic's page (an Inbox item of inbox_topics): the messages kept here of that topic, its root first, + oldest first, a page of limit at a time (before: where the page after it began). Its reply action is the send + tool's, into the topic (the tool reads ":" as that).""" + rows = [r for r in self.store.thread_messages(chat_id, topic, TOPIC_PAGE_MOST) if views.has_content(r)] + place = lambda r: (int(r["position"]), float(r.get("at") or 0), int(r.get("seq") or 0)) # noqa: E731 + rows.sort(key=place) + if before: # "t::" of the oldest line of the page after this one + try: + p, a, q = before[1:].split(":") if before.startswith("t") else ("", "", "") + bound = (int(p), float(a), int(q)) + except ValueError: + raise RPCError("before 不是这个连接器给出的位置") + rows = [r for r in rows if place(r) < bound] + page_rows = rows[-limit:] + me = self.me_name() + messages = [] + for r in page_rows: + parent = self.store.message(chat_id, r["parent_id"]) if r.get("parent_id") else None + messages.append(views.thread_message(r, me, parent)) + page = {"chat": {"id": thread, "name": views.chat_name(chat, chat_id), "kind": views.chat_kind(chat), + "reply": self.cid + "_send"}, + "messages": messages} + if len(rows) > len(page_rows): + p, a, q = place(page_rows[0]) + page["before"] = "t%d:%r:%d" % (p, a, q) + if chat.get("members"): + page["chat"]["members"] = int(chat["members"]) + if getattr(self.backend, "has_avatars", False): + known = self.store.avatars([chat_id]).get(chat_id) + if known is not None and known[0]: + page["chat"]["avatar"] = known[0] + if epoch != self.account_epoch(): + raise RPCError("刚换了%s账号,请重新打开这个会话" % self.platform.name) + return page + def _media(self, params: dict, most: int) -> dict: ref = str(params.get("ref") or "") if not ref: @@ -2145,6 +2300,19 @@ def _history_key(raw: str) -> tuple: return when, seq +TOPIC_ROWS = 300 # a group's newest lines an Inbox read looks at when its topics are items of their own +TOPIC_PAGE_MOST = 20000 # a topic's lines its page reads at most (all a store keeps of one, in practice) + + +def _id_list(v: Any) -> List[str]: + """A setting that lists chat or user ids (an array; a string of them split at commas, spaces or lines).""" + if isinstance(v, str): + v = v.replace(",", ",").replace(",", " ").split() + if not isinstance(v, (list, tuple)): + return [] + return [str(x).strip() for x in v if isinstance(x, (str, int)) and not isinstance(x, bool) and str(x).strip()] + + def _int(v: Any, default: int, lo: int, hi: int) -> int: try: n = int(v) diff --git a/core/openmate_core/backend.py b/core/openmate_core/backend.py index 4477e77..1c2d713 100644 --- a/core/openmate_core/backend.py +++ b/core/openmate_core/backend.py @@ -427,6 +427,16 @@ def create_chat(self, user_id: str) -> str: #: that have none yet, or whose picture is a day old has_avatars: bool = False + #: Whether chat_mute works: the service says whether the account muted a chat (Feishu's 消息免打扰). The core then + #: asks it about the groups in the Inbox now and then (in the background): a muted group's messages that do not @ + #: the user stay out of the Inbox (still archived); a group it could not tell about stays as before + has_mute: bool = False + + def chat_mute(self, chat_id: str) -> Optional[bool]: + """Whether the account muted this chat in the service's own client: True muted, False surely not, None when + the service did not say (or said both). BackendError when it could not be asked. With has_mute.""" + return None + #: Whether send_image works now (an /agent reply may carry a picture then; the tool offers it only then) can_send_images: bool = False diff --git a/core/openmate_core/fixture.py b/core/openmate_core/fixture.py index 0b31cfd..54d3a5d 100644 --- a/core/openmate_core/fixture.py +++ b/core/openmate_core/fixture.py @@ -90,6 +90,10 @@ def __init__(self, now: Optional[float] = None, seed: bool = True): self.format_ok = True # the backend sends formatted texts (rich=True: the Markdown subset) self.image_threads = False # …where a text with the same reply_to and root would go (Backend.image_threads) self.avatars_ok = False # chat_info says a chat's picture (Backend.has_avatars) + self.mute_ok = False # chat_mute says whether a group is muted (Backend.has_mute) + self.mutes: Dict[str, Optional[bool]] = {} # chat id → what chat_mute answers (missing: None) + self.mute_fail = False # chat_mute raises + self.mute_asked: List[str] = [] # chat_mute's calls, in order self.info_asked: List[str] = [] # chat_info's calls, in order self.image_fail: Optional[str] = None # "rejected" | "uncertain" for the next picture self.send_delay = 0.0 @@ -336,6 +340,18 @@ def search(self, query: str, limit: int = 20) -> List[Person]: out.append(Person("group", c.id, c.name, "%d 人" % c.members if c.members else "")) return out[:limit] + @property + def has_mute(self) -> bool: + return self.world.mute_ok + + def chat_mute(self, chat_id: str) -> Optional[bool]: + w = self.world + with w.lock: + w.mute_asked.append(chat_id) + if w.mute_fail: + raise BackendError("飞书暂时没有回答", "unreachable") + return w.mutes.get(chat_id) + @property def has_avatars(self) -> bool: return self.world.avatars_ok diff --git a/core/openmate_core/platform.py b/core/openmate_core/platform.py index 732a870..8939e9e 100644 --- a/core/openmate_core/platform.py +++ b/core/openmate_core/platform.py @@ -80,6 +80,10 @@ class Platform: media_tool: str = "" #: /agent can turn structured replies into pictures when the backend sends images but has no rich text. render_cards: bool = False + #: a group's Inbox items go by topic: each topic (a thread, by its root) is an item of its own (":"), + #: its context, done state, page and reply that topic's; what is said outside any topic stays the chat's item + #: (its id the chat's, as before). Feishu: yes. WeChat: no (no topics; one item per chat as always) + inbox_topics: bool = False @dataclass @@ -121,4 +125,7 @@ class Timing: avatar_ttl: float = 86400.0 # a chat's picture (has_avatars) is asked of the service again when it is this old… avatar_retry: float = 3600.0 # …or this long after asking failed… avatar_batch: int = 30 # …at most this many chats per round, in the background (an Inbox read never waits for it) + mute_ttl: float = 3600.0 # a group's mute state (has_mute) is asked of the service again when it is this old… + mute_retry: float = 600.0 # …and never sooner than this after it was asked (a failed read is "unknown" till mute_ttl)… + mute_batch: int = 10 # …at most this many groups per round, in the background (an Inbox read never waits for it) extra: Dict[str, float] = field(default_factory=dict) diff --git a/core/openmate_core/store.py b/core/openmate_core/store.py index 7e02944..bfa11d3 100644 --- a/core/openmate_core/store.py +++ b/core/openmate_core/store.py @@ -99,6 +99,12 @@ # a chat's picture (Chat.avatar: "" when the service said it has none) and when the service was last asked; a # table of its own, so an older version opening the store (a rollback) finds every table as it knew it "CREATE TABLE IF NOT EXISTS avatars (chat_id TEXT PRIMARY KEY, value TEXT NOT NULL, checked REAL NOT NULL)", + # whether the account muted a group in the service's own client (Backend.chat_mute): state "muted", "normal" or + # "unknown" (asked, and the service did not say), and when it was last asked; a table of its own, like avatars + # (owner: the account it was asked for; an older version's account switch does not empty this table, so a row of + # another account's is never read) + "CREATE TABLE IF NOT EXISTS mutes (chat_id TEXT PRIMARY KEY, state TEXT NOT NULL, checked REAL NOT NULL, " + "owner TEXT NOT NULL DEFAULT '')", # one row per guest run started (自动代答, 文档代答): the hourly and daily most count these, not the pruned runs "CREATE TABLE IF NOT EXISTS guest_quota (chat_id TEXT NOT NULL, kind TEXT NOT NULL, at REAL NOT NULL)", "CREATE INDEX IF NOT EXISTS guest_quota_chat ON guest_quota (chat_id, kind, at)", @@ -245,6 +251,8 @@ def __init__(self, path: str, legacy_blocked_texts: Iterable[str] = ()): self._migrate([str(t) for t in legacy_blocked_texts if t]) for stmt in _SCHEMA: self._db.execute(stmt) + if "owner" not in {r[1] for r in self._db.execute("PRAGMA table_info(mutes)").fetchall()}: + self._db.execute("ALTER TABLE mutes ADD COLUMN owner TEXT NOT NULL DEFAULT ''") # (made without it) if self._db.execute("PRAGMA user_version").fetchone()[0] == 0: # a new store; an older one's version is _migrate's to set (with what it marks), never set over here self._db.execute("PRAGMA user_version=%d" % SCHEMA_VERSION) @@ -366,6 +374,26 @@ def avatars(self, ids: Iterable[str]) -> Dict[str, Tuple[str, float]]: out.update({r["chat_id"]: (r["value"], float(r["checked"])) for r in rows}) return out + def set_mute(self, chat_id: str, state: str, owner: str = "", now: Optional[float] = None) -> None: + """A group's mute state as the service says it now: "muted", "normal" or "unknown", for the account owner.""" + if state not in ("muted", "normal", "unknown"): + state = "unknown" + self._tx(lambda db: db.execute( + "INSERT INTO mutes (chat_id, state, checked, owner) VALUES (?, ?, ?, ?) " + "ON CONFLICT(chat_id) DO UPDATE SET state = excluded.state, checked = excluded.checked, owner = excluded.owner", + (str(chat_id), state, now or time.time(), owner or ""))) + + def mutes(self, ids: Iterable[str], owner: str = "") -> Dict[str, Tuple[str, float]]: + """{chat id: (state, when it was asked)} of those of ids the service was asked about for the account owner.""" + ids = sorted({str(i) for i in ids if i}) + out: Dict[str, Tuple[str, float]] = {} + for i in range(0, len(ids), 500): + part = ids[i:i + 500] + rows = self._all("SELECT chat_id, state, checked FROM mutes WHERE owner = ? AND chat_id IN (%s)" + % ",".join("?" * len(part)), [owner or ""] + part) + out.update({r["chat_id"]: (r["state"], float(r["checked"])) for r in rows}) + return out + def people_kinds(self, ids: Iterable[str]) -> Dict[str, str]: """{id: "bot" | "user"} of those of ids the service told about.""" ids = sorted({str(i) for i in ids if i}) @@ -1114,7 +1142,7 @@ def run(db): runs = [r["id"] for r in db.execute("SELECT id FROM runs").fetchall()] # the groups marked for 自动代答 and who is a person were the old account's choices and knowledge for table in ("chats", "messages", "names", "runs", "seen", "autoreply", "people", "guest_quota", "gone", - "channel_msgs", "channel_asks", "avatars"): + "channel_msgs", "channel_asks", "avatars", "mutes"): db.execute("DELETE FROM " + table) db.execute("DELETE FROM dismissed WHERE key LIKE 'chat:%'") # its chats' 处理完 (and 恢复) marks # its history marks, and its name (the next one's is written next, when it has one) diff --git a/core/openmate_core/tools.py b/core/openmate_core/tools.py index 0557bab..613a504 100644 --- a/core/openmate_core/tools.py +++ b/core/openmate_core/tools.py @@ -10,7 +10,7 @@ import logging import re import time -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Optional, Tuple from . import cards, modelimages, views from .backend import BackendError @@ -580,10 +580,25 @@ def _opens_topic(app, chat_id: str) -> bool: return False -def _send_card(app, a: dict) -> tuple: +def _topic_of(app, a: dict) -> Tuple[str, str]: + """(chat id, topic root) the send's chat names: an Inbox topic's thread (":", inbox_topics: its page's + reply) is that chat, into that topic; any other chat id is itself ("" root).""" chat_id = _need(a, "chat", "会话 id") + if getattr(app.platform, "inbox_topics", False) and ":" in chat_id: + cid, _, root = chat_id.partition(":") + if cid and root: + return cid, root + return chat_id, "" + + +def _send_card(app, a: dict) -> tuple: + chat_id, topic = _topic_of(app, a) text = _check_text(_need(a, "text", "消息内容")) - reply_to = str(a.get("reply_to") or "").strip() + reply_to = str(a.get("reply_to") or "").strip() or topic + if topic and reply_to != topic and app.store is not None: # into that topic: what it quotes is one of its lines + quoted = app.store.message(chat_id, reply_to) + if quoted is not None and (quoted.get("root_id") or quoted["id"]) != topic: # (one not kept yet: as asked) + raise RPCError("reply_to 不是这个话题里的消息:要回复别的话题,chat 只填会话 id") mentions = _mentions(app, a, chat_id) names = [n for _, n in mentions] rich = _rich(app, text, names) @@ -702,8 +717,8 @@ def as_asked() -> None: if name == c + "_send": try: chat_id, text, reply_to, visible, _, mentions, rich = _send_card(app, a) - root = None - if reply_to: + root = _topic_of(app, a)[1] or None # an Inbox topic's page: into that topic + if reply_to and root is None: quoted = app.store.message(chat_id, reply_to) if quoted is not None and quoted.get("root_id"): root = quoted["root_id"] diff --git a/core/openmate_core/views.py b/core/openmate_core/views.py index b80a2ad..ba05057 100644 --- a/core/openmate_core/views.py +++ b/core/openmate_core/views.py @@ -71,10 +71,12 @@ def where(platform: str, chat: Optional[dict], chat_id: str) -> str: return "%s群「%s」%s" % (platform, name, "(%d 人)" % members if members else "") -def reply_target(platform: str, chat: Optional[dict], chat_id: str) -> str: +def reply_target(platform: str, chat: Optional[dict], chat_id: str, topic: bool = False) -> str: name = chat_name(chat, chat_id) if chat_kind(chat) == "dm": return "以你的身份发到%s私聊「%s」(对方能看到)" % (platform, name) + if topic: + return "以你的身份回复到%s群「%s」的这个话题(群里的人都能看到)" % (platform, name) return "以你的身份发到%s群「%s」(群里的人都能看到)" % (platform, name) @@ -86,9 +88,23 @@ def unanswered_run(rows: List[dict]) -> List[dict]: return rows[i:] +PRIVATE_PREVIEW = "(这个私聊设置为不交给收件箱 AI:内容不在这里,打开会话查看)" + + def inbox_thing(chat: dict, rows: List[dict], *, platform: str, tz, me: str, rules: str, can_reply: bool, - context_lines: int = 8) -> Optional[dict]: - """One thing for a chat from its recent rows (oldest first), or None when there is nothing to show.""" + context_lines: int = 8, root: str = "", lead: Optional[dict] = None, mute: str = "", + triage: bool = False, private: bool = False) -> Optional[dict]: + """One thing for a chat from its recent rows (oldest first), or None when there is nothing to show. + + root: the rows are one topic's of a group (inbox_things): the thing is that topic's (":"), its context, + done state and reply that topic's; lead: the topic's root message when it is the chat's own item's (an ordinary + group: the root was said in the main stream), shown first in the context and not counted as the topic's. + mute: the group's mute state ("muted", "normal", "unknown" or "": not asked). A muted group's thing that does not + @ the user is handed over as already done (read: Persona's own muted items are), and in one that does, what came + after the user's @ is not what it is about. triage: the user listed the group for AI triage (setting + inbox_triage_chats): its messages without an @ go to the triage model too, muted or not. private: the user listed + the direct chat as one not handed to the Inbox's AI (setting inbox_private_dms): its tier is the rule's and no + words of it are in the thing (preview, context): no model reads them.""" msgs = [r for r in rows if not is_system(r) and has_content(r)] if not msgs: return None @@ -115,31 +131,57 @@ def inbox_thing(chat: dict, rows: List[dict], *, platform: str, tz, me: str, rul kind = "mention" else: kind = "group" + muted = mute == "muted" and not triage and not kind_dm and not private + if muted and kind == "group" and not done: + done = "read" # muted in the service: nothing to do (still archived) + elif muted and kind == "mention" and not done: + # muted: the @ of the user is the thing, not the chatter after it + latest = [r for r in considered if r.get("at_me")][-1] name = chat_name(chat, chat_id) - lines = [where(platform, chat, chat_id)] - lines += [log_line(r, tz, me) for r in msgs[-context_lines:]] + head = where(platform, chat, chat_id) + if root: + head += "的一个话题(根消息 id=%s)" % root + hidden = private # (listed by its id: whatever kind it was kept as) + lines = [head] + if hidden: + lines.append(PRIVATE_PREVIEW) + else: + if lead is not None and has_content(lead) and not is_system(lead): + lines.append(log_line(lead, tz, me) + "(话题的根消息)") + upto = msgs.index(latest) + 1 if latest in msgs else len(msgs) + lines += [log_line(r, tz, me) for r in msgs[:upto][-context_lines:]] thing = { - "thread": chat_id, + "thread": "%s:%s" % (chat_id, root) if root else chat_id, "kind": kind, "label": LABELS[kind], "title": name, "sender": sender_of(latest, me), - "preview": one_line(text_of(latest), 200), + "preview": PRIVATE_PREVIEW if hidden else one_line(text_of(latest), 200), "context": "\n".join(lines), "at": rfc3339(latest.get("at") or 0), "last": latest["id"], } if can_reply: - thing["reply_to"] = reply_target(platform, chat, chat_id) + thing["reply_to"] = reply_target(platform, chat, chat_id, topic=bool(root)) thing["can_reply"] = True - if kind == "group": - thing["tier"] = "noise" - thing["why"] = "规则:群消息没有 @我,直接归为噪音(不调用模型)" - if done: + if hidden: + thing["tier"] = "action" + thing["why"] = "规则:这个私聊设置为不交给收件箱 AI(不调用模型)" + elif kind == "group": + if triage: + # sorted by the model with the user's rules; the rule's tier only where the model cannot be asked + thing["extra"] = {"rule_tier": "noise"} + else: + thing["tier"] = "noise" + thing["why"] = "规则:群消息没有 @我,直接归为噪音(不调用模型)" + if done == "read": + thing["done"] = "read" + thing["why"] = "规则:这个群在飞书里设了消息免打扰,没有 @我" + elif done: thing["done"] = done thing["why"] = "我已经回复" tags = [{"key": "chat", "value": chat_id, "name": name}] - last_other = considered[-1] + last_other = latest if not latest.get("mine") else considered[-1] # (a muted group's @: its sender) if last_other.get("sender_id"): tags.append({"key": "sender", "value": last_other["sender_id"], "name": sender_of(last_other, me)}) thing["tags"] = tags @@ -148,6 +190,68 @@ def inbox_thing(chat: dict, rows: List[dict], *, platform: str, tz, me: str, rul return thing +def _place(r: dict) -> tuple: + """A row's place in its chat: its position, then when it was said (a thread's replies may share a position), then + when it was kept.""" + return (int(r.get("position") or 0), float(r.get("at") or 0), int(r.get("seq") or 0)) + + +def inbox_things(chat: dict, rows: List[dict], *, topics: bool = False, since: float = 0.0, until: float = 0.0, + **kw) -> List[dict]: + """The chat's things from its recent rows (oldest first): one for the chat (inbox_thing), or, with topics, in a + group one for each topic its rows are in besides the chat's own. + + A group in topic mode (chat.topic: every message opens a topic or replies in one) has a thing per topic, its root + and replies. In an ordinary group a topic's thing is its replies (the root above them, for context): the root was + said in the main stream, so it stays the chat's own thing's, and the user's own replies in a topic whose root is + there end that thing as well (it asked, the user answered where it was asked). A topic whose last line is older + than since is left out. until: when topics became items of their own; a topic group's lines said before it were + its one item, which is handed over done (with those lines only, so it stays that one item).""" + if not topics or chat_kind(chat) == "dm": + thing = inbox_thing(chat, rows, **kw) + return [thing] if thing is not None else [] + rows = sorted(rows, key=_place) + topic_mode = bool(chat.get("topic")) + scopes: Dict[str, List[dict]] = {} + for r in rows: + key = str(r.get("root_id") or "") or (str(r.get("id") or "") if topic_mode else "") + scopes.setdefault(key, []).append(r) + out = [] + main = scopes.pop("", []) + if not topic_mode: + ids = {str(r.get("id") or "") for r in main} + answered = [r for key, part in scopes.items() if key in ids for r in part if r.get("mine")] + mine_too = sorted(main + answered, key=_place) + thing = inbox_thing(chat, mine_too, **kw) + if thing is not None: + out.append(thing) + else: + before = [r for r in rows if float(r.get("at") or 0) <= until] if until else [] + old = inbox_thing(chat, before, **kw) if before and not main else None + if old is not None: # the one item a version before this one kept for the whole group: ended + if not old.get("done"): + old["done"], old["why"] = "read", "规则:这个群的消息现在按话题各成一条" + out.append(old) + if main: # (a topic group's line outside any topic: the chat's own) + thing = inbox_thing(chat, main, **kw) + if thing is not None: + out.append(thing) + by_id = {str(r.get("id") or ""): r for r in rows} + for root, part in scopes.items(): + if not part or max(float(r.get("at") or 0) for r in part) < since: + continue + lead = None + if not topic_mode: + part = [r for r in part if str(r.get("id") or "") != root] + lead = by_id.get(root) + if not part: + continue + thing = inbox_thing(chat, part, root=root, lead=lead, **kw) + if thing is not None: + out.append(thing) + return out + + def media_list(row: dict) -> List[dict]: out = [] for m in row.get("media") or []: diff --git a/extensions/openmate-feishu/openmate_feishu/__init__.py b/extensions/openmate-feishu/openmate_feishu/__init__.py index 3f9b987..8484777 100644 --- a/extensions/openmate-feishu/openmate_feishu/__init__.py +++ b/extensions/openmate-feishu/openmate_feishu/__init__.py @@ -54,6 +54,7 @@ def platform(manifest_path: str = "") -> Platform: legacy_blocked_texts=(DLP_BLOCKED_TEXT,), # what told a blocked message before 0.11.29 stored the mark tools=_media_tools, # matefeishu_media: a message's pictures and files as local files (read-only) media_tool=CONNECTOR_ID + "_media", + inbox_topics=True, # a group's topics are Inbox items of their own (":") ) diff --git a/extensions/openmate-feishu/openmate_feishu/larkagentx.py b/extensions/openmate-feishu/openmate_feishu/larkagentx.py index 15f6764..58ddaa6 100644 --- a/extensions/openmate-feishu/openmate_feishu/larkagentx.py +++ b/extensions/openmate-feishu/openmate_feishu/larkagentx.py @@ -310,6 +310,22 @@ def group_alive(info: dict) -> bool: and not info.get("isDissolved") and not info.get("isFrozen") and info.get("role") not in CHAT_NOT_MEMBER) +def mute_of(info) -> Optional[bool]: + """Whether a chat's record (entities.Chat, as protobuf_to_dict gives it) says the account muted it (消息免打扰: + its reminder is off): True muted, False surely not, None when it does not say. Two fields say it, the chat's own + isRemind (27) and its userSetting's (29, isRemind 1); only a bool counts (a field the record leaves out is not + false), and when both are there and disagree it is not known either. userSetting.isMuteAtAll (no reminder for + @所有人) is another switch and is never read as this.""" + if not isinstance(info, dict): + return None + says = [] + setting = info.get("userSetting") + for remind in ((setting.get("isRemind") if isinstance(setting, dict) else None), info.get("isRemind")): + if type(remind) is bool: + says.append(not remind) + return says[0] if says and len(set(says)) == 1 else None + + def reacted_by(d: dict, user_id: str, only: Optional[Set[str]] = None, ignore: Tuple[str, ...] = ()) -> Dict[str, float]: """{message id: when (seconds, 0 when unknown)} of the messages user_id has a reaction on, from a reactions.PullReactionsResponse or a reactions.PushReactions read back (protobuf_to_dict): each message's @@ -915,6 +931,7 @@ class LarkXBackend(Backend): rerender_empty = RERENDER_EMPTY done_marks = True # a chat's 完成 has_avatars = True # chat_info's Chat carries the chat's picture (avatar_address) + has_mute = True # chat_mute: the chat record's reminder switch (消息免打扰, mute_of) thread_reply_quotes_root = True # send() passes only the root to LarkAgentX's builder # timings (tests shorten them) @@ -2402,6 +2419,11 @@ def chat_info(self, chat_id: str) -> Chat: client, me = self._signed_in() return self._chat_read(client, chat_id, me)[1] + def chat_mute(self, chat_id: str) -> Optional[bool]: + """Backend.chat_mute: the chat's record read now (mute_of).""" + client, me = self._signed_in() + return mute_of(self._chat_read(client, chat_id, me)[0]) + def chat_picture(self, chat_id: str, peer_id: str = "") -> Chat: """The chat as the service says it now (not a row kept from a list, which may not say its picture): what the core asks when it wants a chat's picture. peer_id is the other person of a direct chat as the core's store diff --git a/extensions/openmate-feishu/persona-extension.json b/extensions/openmate-feishu/persona-extension.json index fa2d547..ab2e315 100644 --- a/extensions/openmate-feishu/persona-extension.json +++ b/extensions/openmate-feishu/persona-extension.json @@ -241,9 +241,25 @@ "triage_rules": { "type": "string", "title": "收件箱分拣规则", - "description": "用你自己的话写飞书消息该怎么分拣(哪些要你处理、哪些看看就行、哪些是噪音)。留空就用 Persona 的全局规则。没有 @你 的群消息总是按噪音处理。", + "description": "用你自己的话写飞书消息该怎么分拣(哪些要你处理、哪些看看就行、哪些是噪音)。留空就用 Persona 的全局规则。没有 @你 的群消息按噪音处理,不调用模型;在飞书里设了消息免打扰的群,没有 @你 的消息直接算已读,不留在待处理里(照旧存进知识库)。下面“照常分拣的群”里列的群例外。", "maxLength": 4000 }, + "inbox_triage_chats": { + "type": "array", + "title": "照常分拣的群", + "description": "这些群里没有 @你 的消息也交给收件箱的 AI 按分拣规则分拣,群设了免打扰也一样。填群的会话 id(问 Persona 助手“飞书里 xx 群的 chat id”,或看 matefeishu_chats),一行一个。默认不填:没有 @你 的群消息照旧按噪音处理。", + "items": {"type": "string", "maxLength": 64}, + "maxItems": 100, + "default": [] + }, + "inbox_private_dms": { + "type": "array", + "title": "不交给收件箱 AI 的私聊", + "description": "这些私聊照常进收件箱,但不交给 AI 分拣,一律按“要你处理”放,条目里也不带消息内容(打开会话看)。填私聊的会话 id 或对方的用户 id(matefeishu_chats、matefeishu_search 给出),一行一个。默认不填:所有私聊照旧由 AI 分拣。", + "items": {"type": "string", "maxLength": 64}, + "maxItems": 100, + "default": [] + }, "lark_cli": { "type": "string", "title": "lark-cli 路径", diff --git a/extensions/openmate-feishu/tests/test_feishu.py b/extensions/openmate-feishu/tests/test_feishu.py index 1586b35..7d0fd61 100644 --- a/extensions/openmate-feishu/tests/test_feishu.py +++ b/extensions/openmate-feishu/tests/test_feishu.py @@ -95,7 +95,7 @@ def test_configuration(self): "auto_reply", "auto_reply_docs", "auto_reply_daily_most", "auto_reply_hourly_most", "auto_reply_header", "auto_reply_at_asker", "agent_reply_suffix", - "history_chats", "triage_rules", "lark_cli", "lark_cli_profile", "starkmesh_url", "needs_hours", "bookmarks"]) + "history_chats", "triage_rules", "inbox_triage_chats", "inbox_private_dms", "lark_cli", "lark_cli_profile", "starkmesh_url", "needs_hours", "bookmarks"]) self.assertEqual([(s["name"], s.get("hint")) for s in MANIFEST["secrets"]], [("starkmesh_key", "last4")]) self.assertIn("config:starkmesh_url:http", MANIFEST["permissions"]["network"]) self.assertNotIn("default", props["larkx_python"]) @@ -118,6 +118,7 @@ def test_configuration(self): self.assertIs(d["agent_mark_effort"], False, "the mark names the model alone") self.assertEqual((props["history_chats"]["minimum"], props["history_chats"]["maximum"], d["history_chats"]), (0, 50, 20)) self.assertLessEqual(props["triage_rules"]["maxLength"], 4000) + self.assertEqual((d["inbox_triage_chats"], d["inbox_private_dms"]), ([], []), "off unless the user lists some") self.assertIn("http://", props["http_proxy"]["description"]) self.assertNotIn("socks5://", props["http_proxy"]["description"]) self.assertEqual(MANIFEST["configuration"]["type"], "object") diff --git a/extensions/openmate-feishu/tests/test_larkagentx.py b/extensions/openmate-feishu/tests/test_larkagentx.py index b5cff05..de14c9a 100644 --- a/extensions/openmate-feishu/tests/test_larkagentx.py +++ b/extensions/openmate-feishu/tests/test_larkagentx.py @@ -1787,6 +1787,27 @@ def test_my_reactions_asks_by_message(self): with self.assertRaises(BackendError): self.b.my_reactions(["201"]) + def test_chat_mute_reads_the_reminder_switch(self): + cases = [ + ({"isRemind": False}, True), + ({"isRemind": True}, False), + ({"userSetting": {"isRemind": False}}, True), + ({"userSetting": {"isRemind": False}, "isRemind": False}, True), + ({"userSetting": {"isRemind": True}, "isRemind": False}, None), # the two disagree: not known + ({}, None), # neither field there: not known (left out is not false) + ({"isRemind": 0}, None), # only a bool counts + ({"userSetting": {"isMuteAtAll": True}}, None), # no @所有人 reminder is another switch + ] + for i, (fields, want) in enumerate(cases): + cid = str(600 + i) + S.chats[cid] = dict({"id": cid, "type": 2, "name": "群%d" % i}, **fields) + self.assertIs(self.b.chat_mute(cid), want, fields) + self.assertIsNone(larkagentx.mute_of(None)) + self.assertTrue(self.b.has_mute) + S.chats["699"] = OSError("down") + with self.assertRaises(BackendError): + self.b.chat_mute("699") + def test_chat_info_topic_and_cache(self): S.chats["502"] = {"id": "502", "type": 2, "chatMode": 3, "name": "", "i18nNames": {"zh_cn": "话题群"}} c = self.b.chat_info("502") diff --git a/tests/test_inbox_topics.py b/tests/test_inbox_topics.py new file mode 100644 index 0000000..31a38a4 --- /dev/null +++ b/tests/test_inbox_topics.py @@ -0,0 +1,345 @@ +"""inbox.collect for groups muted in the service, the groups listed for AI triage (inbox_triage_chats), the direct chats +no Inbox model reads (inbox_private_dms), and a group's topics as Inbox items of their own (Platform.inbox_topics), +with their reply and page; WeChat's Inbox as before.""" + +try: # first: every temporary directory of this run in one, removed at its end + import _runtmp # noqa: F401 +except ImportError: # (started by its path from elsewhere: its directory is not on the path) + pass +import os +import sys +import unittest + +from harness import ROOT, Harness, HubSideError, wait_until + +sys.path.insert(0, os.path.join(ROOT, "extensions", "openmate-wechat")) +import openmate_wechat # noqa: E402 + +TEAM, CHATTER, DM_A = "chat_example_team", "chat_example_chatter", "chat_example_dm_a" + + +def things(h): + return {t["thread"]: t for t in h.c("inbox.collect")["things"]} + + +def mutes(h, ids): + return h.app.store.mutes(ids, h.app.store.meta_get("account_id")) + + +def signed_in(test, mute_ok=False, mutes=None, **config): + h = Harness(test, config=config) + h.world.mute_ok = mute_ok + h.world.mutes.update(mutes or {}) + h.sign_in() + wait_until(lambda: len(things(h)) >= 4, what="the seeded chats") + return h + + +class MuteTest(unittest.TestCase): + def test_a_muted_group_without_an_at_is_done_and_an_at_stays_in(self): + h = signed_in(self, mute_ok=True, mutes={CHATTER: True, TEAM: True}) + wait_until(lambda: things(h)[CHATTER].get("done") == "read", what="the muted group's item done") + t = things(h) + self.assertIn("免打扰", t[CHATTER]["why"]) # handed over done: an item the Inbox kept from before ends too + self.assertEqual(t[TEAM]["kind"], "mention") # an @ of the user in a muted group is sorted as usual + self.assertNotIn("tier", t[TEAM]) + self.assertIn(DM_A, t) + self.assertEqual(set(h.world.mute_asked), {TEAM, CHATTER}) # groups only, never a direct chat + self.assertTrue(h.hub.changed("inbox"), "the Inbox is told to read again once a state is known") + # still archived: the knowledge base gets its messages + archived = h.c("archive.changes", cursor="", limit=100) + self.assertIn(CHATTER, {b["chat"]["id"] for b in archived["batches"]}) + + def test_not_muted_or_not_known_is_as_before(self): + h = signed_in(self, mute_ok=True, mutes={CHATTER: False}) + wait_until(lambda: mutes(h, [CHATTER, TEAM]).get(TEAM, ("",))[0] == "unknown", what="asked") + t = things(h) + self.assertEqual(t[CHATTER]["tier"], "noise") # a group the user did not mute: by rule, as before + self.assertEqual(mutes(h, [CHATTER])[CHATTER][0], "normal") + h.world.push(TEAM, "user_example_a", "大家看下这个") + h.world.push(TEAM, "me", "收到") + h.world.push(TEAM, "user_example_a", "好的") + wait_until(lambda: things(h)[TEAM]["kind"] == "group", what="the team group without an @") + self.assertEqual(things(h)[TEAM]["tier"], "noise") # the service did not say: as before + + def test_a_failed_read_keeps_the_inbox_as_it_was(self): + h = Harness(self) + h.world.mute_ok = True + h.world.mutes[CHATTER] = True + h.sign_in() + wait_until(lambda: things(h) and mutes(h, [CHATTER]).get(CHATTER, ("",))[0] == "muted", what="muted") + # the state goes stale and the next read fails: not known any more, so the old way (not the stale mute) + with h.app.store._lock: + h.app.store._db.execute("UPDATE mutes SET checked = 0") + h.app._mutes_tried.clear() + h.world.mute_fail = True + wait_until(lambda: things(h) and mutes(h, [CHATTER])[CHATTER][0] == "unknown", what="unknown after a failure") + self.assertEqual(things(h)[CHATTER]["tier"], "noise") + self.assertNotIn("done", things(h)[CHATTER]) + + def test_a_muted_group_s_at_is_the_item_not_the_chatter_after_it(self): + h = signed_in(self, mute_ok=True, mutes={TEAM: True}) + wait_until(lambda: mutes(h, [TEAM]).get(TEAM), what="asked") + at = [m for m in h.world.history[TEAM] if m.at_me][-1] + h.world.push(TEAM, "user_example_c", "顺便说一句,今天下雨") + wait_until(lambda: "今天下雨" in str(h.app.store.messages_before(TEAM, None, 5)), what="kept") + t = things(h)[TEAM] + self.assertEqual((t["kind"], t["last"]), ("mention", at.id)) + self.assertNotIn("今天下雨", t["context"]) + + def test_a_row_of_another_account_is_never_read(self): + h = signed_in(self) + h.app.store.set_mute(CHATTER, "muted", "someone_else") + self.assertEqual(mutes(h, [CHATTER]), {}) + + def test_a_reply_in_a_muted_group_still_ends_its_item(self): + h = signed_in(self, mute_ok=True, mutes={CHATTER: True}) + wait_until(lambda: things(h)[CHATTER].get("done") == "read", what="muted") + h.world.push(CHATTER, "me", "我也去") + t = wait_until(lambda: (lambda x: x if x.get("done") == "replied" else None)(things(h)[CHATTER]), what="done") + self.assertEqual(t["why"], "我已经回复") + + def test_no_mute_asked_without_the_capability(self): + h = signed_in(self, mute_ok=False, mutes={CHATTER: True}) + self.assertIn(CHATTER, things(h)) + self.assertEqual(h.world.mute_asked, []) + + +class TriageChatsTest(unittest.TestCase): + def test_a_listed_group_goes_to_the_model_muted_or_not(self): + h = signed_in(self, mute_ok=True, mutes={CHATTER: True}, inbox_triage_chats=[CHATTER]) + wait_until(lambda: mutes(h, [CHATTER]).get(CHATTER), what="asked") + g = things(h)[CHATTER] + self.assertNotIn("tier", g) + self.assertEqual(g["extra"], {"rule_tier": "noise"}) # the rule's tier only where the model cannot sort + self.assertEqual(g["kind"], "group") + + def test_default_is_as_before(self): + h = signed_in(self) + self.assertEqual(things(h)[CHATTER]["tier"], "noise") + self.assertNotIn("extra", things(h)[CHATTER]) + + +class PrivateDMsTest(unittest.TestCase): + def test_listed_by_chat_or_by_person_no_model_no_words(self): + for listed in (DM_A, "user_example_a"): + h = signed_in(self, inbox_private_dms=[listed]) + dm = things(h)[DM_A] + self.assertEqual(dm["tier"], "action") + self.assertIn("不交给收件箱 AI", dm["why"]) + self.assertIn("不交给收件箱 AI", dm["preview"]) + for words in ("评审", "文档", "图片"): # nothing of what was said: no model reads it from the item + self.assertNotIn(words, dm["preview"] + dm["context"]) + self.assertNotIn("tier", things(h)[TEAM]) + + def test_by_person_when_the_chat_does_not_say_who(self): + h = signed_in(self, inbox_private_dms=["user_example_a"]) + with h.app.store._lock: + h.app.store._db.execute("UPDATE chats SET peer_id = '' WHERE id = ?", (DM_A,)) + self.assertEqual(things(h)[DM_A]["tier"], "action") # the other person as their lines say + + def test_default_is_as_before(self): + h = signed_in(self) + self.assertNotIn("tier", things(h)[DM_A]) + + def test_by_chat_id_whatever_kind_it_was_kept_as(self): + h = signed_in(self, inbox_private_dms=[DM_A]) + with h.app.store._lock: # first kept when its kind could not be read: a group till it is + h.app.store._db.execute("UPDATE chats SET kind = 'group' WHERE id = ?", (DM_A,)) + t = things(h)[DM_A] + self.assertEqual((t["tier"], t["preview"]), ("action", "(这个私聊设置为不交给收件箱 AI:内容不在这里,打开会话查看)")) + self.assertNotIn("评审", t["context"]) + + def test_a_string_setting_is_split(self): + h = signed_in(self, inbox_private_dms="%s, other" % DM_A) + self.assertEqual(things(h)[DM_A]["tier"], "action") + + +class TopicsTest(unittest.TestCase): + def setUp(self): + self.h = signed_in(self) + w = self.h.world + self.root = w.push(TEAM, "user_example_a", "这个方案大家怎么看?") + self.reply = w.push(TEAM, "user_example_b", "我觉得可以", root_id=self.root.id, parent_id=self.root.id) + self.main = w.push(TEAM, "user_example_c", "另外,周会改到四点") + self.topic = "%s:%s" % (TEAM, self.root.id) + wait_until(lambda: self.topic in things(self.h) and things(self.h)[TEAM]["last"] == self.main.id, + what="the topic's item and the chat's") + + def test_a_topic_is_an_item_of_its_own(self): + t = things(self.h) + topic, chat = t[self.topic], t[TEAM] + self.assertEqual(topic["last"], self.reply.id) + self.assertIn("我觉得可以", topic["context"]) + self.assertIn("这个方案大家怎么看?(话题的根消息)", topic["context"]) + self.assertNotIn("周会改到四点", topic["context"]) + self.assertIn("话题", topic["context"].split("\n")[0]) + self.assertIn("这个话题", topic["reply_to"]) + self.assertIn({"key": "chat", "value": TEAM, "name": "示例项目群"}, topic["tags"]) + self.assertNotIn("我觉得可以", chat["context"]) + self.assertIn("这个方案大家怎么看", chat["context"]) # the root was said in the main stream: the chat's too + self.assertIn("周会改到四点", chat["context"]) + self.assertEqual(chat["kind"], "mention") # the @ before the topic is the chat's, as it was + + def test_a_reply_in_the_topic_ends_the_topic_and_what_its_root_asked(self): + w = self.h.world + w.push(TEAM, "me", "那就这么定", root_id=self.root.id, parent_id=self.reply.id) + wait_until(lambda: things(self.h)[self.topic].get("done") == "replied", what="the topic done") + # the chat's own item asked with the topic's root, and was answered there: done too (never left behind) + self.assertEqual(things(self.h)[TEAM].get("done"), "replied") + later = w.push(TEAM, "user_example_c", "下周呢?") + wait_until(lambda: things(self.h)[TEAM]["last"] == later.id, what="the chat open again") + self.assertNotIn("done", things(self.h)[TEAM]) + self.assertEqual(things(self.h)[self.topic].get("done"), "replied") # another line in the main stream + + def test_a_topic_mode_group_has_an_item_per_topic(self): + h = signed_in(self) + with h.app.store._lock: + h.app.store._db.execute("UPDATE chats SET topic = 1 WHERE id = ?", (CHATTER,)) + a = h.world.push(CHATTER, "user_example_a", "话题甲") + b = h.world.push(CHATTER, "user_example_b", "话题乙") + r = h.world.push(CHATTER, "me", "回甲", root_id=a.id, parent_id=a.id) + wait_until(lambda: ("%s:%s" % (CHATTER, b.id)) in things(h), what="topics") + t = things(h) + self.assertEqual(t["%s:%s" % (CHATTER, a.id)]["done"], "replied") + self.assertNotIn("done", t["%s:%s" % (CHATTER, b.id)]) + self.assertIn("话题乙", t["%s:%s" % (CHATTER, b.id)]["context"]) + self.assertNotIn("话题甲", t["%s:%s" % (CHATTER, b.id)]["context"]) + del r + + def test_a_busy_topic_pushes_no_other_topic_out(self): + w = self.h.world + at = w.push(TEAM, "user_example_b", "@示例用户 这个你看下", root_id=self.root.id, parent_id=self.root.id, at_me=True) + other = w.push(TEAM, "user_example_c", "另一个话题") + for i in range(80): + w.push(TEAM, "user_example_c", "刷屏 %d" % i, root_id=other.id, parent_id=other.id) + w.push(TEAM, "user_example_a", "补充一句", root_id=self.root.id, parent_id=at.id) + wait_until(lambda: "补充一句" in things(self.h)[self.topic]["context"], what="the topic's new line") + self.assertEqual(things(self.h)[self.topic]["kind"], "mention") + + def test_an_old_topic_is_left_out(self): + w = self.h.world + old = w.push(TEAM, "user_example_a", "四天前的话题", ago=4 * 86400) + w.push(TEAM, "user_example_b", "四天前的回复", ago=4 * 86400 - 60, root_id=old.id, parent_id=old.id) + w.push(TEAM, "user_example_c", "今天的消息") + wait_until(lambda: "今天的消息" in things(self.h)[TEAM]["context"], what="today") + self.assertNotIn("%s:%s" % (TEAM, old.id), things(self.h)) + + def test_the_send_tool_refuses_a_line_of_another_topic(self): + other = self.h.world.push(TEAM, "user_example_c", "别的话题") + r = self.h.world.push(TEAM, "user_example_a", "回复", root_id=other.id, parent_id=other.id) + wait_until(lambda: self.h.app.store.message(TEAM, r.id), what="kept") + with self.assertRaises(HubSideError): + self.h.c("actions.describe", name="matefeishu_send", args={"chat": self.topic, "text": "x", "reply_to": r.id}) + + def test_a_topic_group_s_one_item_from_before_is_ended(self): + h = signed_in(self) + old = [m for m in h.world.history[CHATTER]][-1] + with h.app.store._lock: + h.app.store._db.execute("UPDATE chats SET topic = 1 WHERE id = ?", (CHATTER,)) + t = things(h) + self.assertEqual((t[CHATTER]["done"], t[CHATTER]["last"]), ("read", old.id)) # the item before topics: ended + self.assertIn("%s:%s" % (CHATTER, old.id), t) + new = h.world.push(CHATTER, "user_example_a", "新话题") + wait_until(lambda: "%s:%s" % (CHATTER, new.id) in things(h), what="the new topic") + self.assertEqual(things(h)[CHATTER]["last"], old.id, "that ended item never moves") + + def test_the_send_tool_takes_a_topic_s_thread(self): + a = {"chat": self.topic, "text": "页里回复"} + card = self.h.c("actions.describe", name="matefeishu_send", args=a) + self.assertIn("示例项目群", card["summary"]) + self.h.c("actions.do", name="matefeishu_send", args=a, request_id="r-topic") + sent = self.h.sent()[-1] + self.assertEqual((sent["chat"], sent["reply_to"], sent["root"]), (TEAM, self.root.id, self.root.id)) + + def test_inbox_reply_goes_into_the_topic(self): + chat = things(self.h)[TEAM] # the chat's own item replies to the chat, as before + self.h.c("inbox.reply", thread=TEAM, last=chat["last"], text="好") + sent = self.h.sent()[-1] + self.assertEqual((sent["chat"], sent["reply_to"], sent["root"]), (TEAM, self.main.id, None)) + t = things(self.h)[self.topic] + self.h.c("inbox.reply", thread=t["thread"], last=t["last"], text="同意") + sent = self.h.sent()[-1] + self.assertEqual((sent["chat"], sent["reply_to"], sent["root"]), (TEAM, self.reply.id, self.root.id)) + wait_until(lambda: things(self.h)[self.topic].get("done") == "replied", what="done") + + def test_a_reply_to_a_topic_whose_last_is_mine_goes_under_its_root(self): + self.h.c("inbox.reply", thread=self.topic, last="", text="补充一下") + sent = self.h.sent()[-1] + self.assertEqual((sent["reply_to"], sent["root"]), (self.root.id, self.root.id)) + + def test_the_topic_page_and_the_chat_page(self): + page = self.h.c("thread.page", thread=self.topic, limit=20) + self.assertEqual([m["id"] for m in page["messages"]], [self.root.id, self.reply.id]) + self.assertEqual(page["chat"]["id"], self.topic) + self.assertEqual(page["chat"]["reply"], "matefeishu_send") + self.assertNotIn("before", page) + more = [self.h.world.push(TEAM, "user_example_b", "第 %d 条" % i, root_id=self.root.id, parent_id=self.root.id) + for i in range(5)] + wait_until(lambda: len(self.h.app.store.thread_messages(TEAM, self.root.id, 50)) == 7, what="kept") + first = self.h.c("thread.page", thread=self.topic, limit=3) + self.assertEqual([m["id"] for m in first["messages"]], [m.id for m in more[-3:]]) + second = self.h.c("thread.page", thread=self.topic, limit=3, before=first["before"]) + self.assertEqual([m["id"] for m in second["messages"]], [self.reply.id] + [m.id for m in more[:2]]) + newer = self.h.world.push(TEAM, "user_example_c", "又一条", root_id=self.root.id, parent_id=self.root.id) + wait_until(lambda: self.h.app.store.message(TEAM, newer.id), what="kept") + third = self.h.c("thread.page", thread=self.topic, limit=3, before=second["before"]) + self.assertEqual([m["id"] for m in third["messages"]], [self.root.id]) # a newer line moves no page + self.assertNotIn("before", third) + with self.assertRaises(HubSideError): + self.h.c("thread.page", thread=self.topic, limit=3, before="o3") + whole = self.h.c("thread.page", thread=TEAM, limit=50) + self.assertIn(self.main.id, [m["id"] for m in whole["messages"]]) + self.assertEqual(whole["chat"]["reply"], "matefeishu_send") + + def test_a_muted_group_s_topic_without_an_at_stays_out(self): + h = signed_in(self, mute_ok=True, mutes={TEAM: True}) + root = h.world.push(TEAM, "user_example_a", "话题一") + h.world.push(TEAM, "user_example_b", "回复", root_id=root.id, parent_id=root.id) + wait_until(lambda: mutes(h, [TEAM]).get(TEAM), what="asked") + t = things(h) + self.assertEqual(t["%s:%s" % (TEAM, root.id)]["done"], "read") + self.assertEqual(t[TEAM]["kind"], "mention") # the chat's own @ of the user stays + + +class WeChatTest(unittest.TestCase): + def test_no_topics_no_mutes_one_item_per_chat(self): + from openmate_wechat.backend import WeChatBackend + + self.assertFalse(WeChatBackend.has_mute) # it never says a chat is muted: nothing is asked or left out + h = Harness(self, platform=openmate_wechat.platform(), + config={"inbox_triage_chats": [CHATTER], "inbox_private_dms": [DM_A]}) + h.sign_in() + wait_until(lambda: len(things(h)) >= 4, what="the seeded chats") + root = h.world.push(TEAM, "user_example_a", "这个方案大家怎么看?") + r = h.world.push(TEAM, "user_example_b", "我觉得可以", root_id=root.id, parent_id=root.id) + wait_until(lambda: things(h)[TEAM]["last"] == r.id, what="one item for the chat") + self.assertEqual(sorted(things(h)), sorted([TEAM, CHATTER, DM_A, "chat_example_dm_b"])) + self.assertEqual(things(h)[CHATTER]["tier"], "noise") # no such settings there: as before + self.assertNotIn("tier", things(h)[DM_A]) + with self.assertRaises(HubSideError): # no topic ids there: a thread is a chat's id, whole + h.c("thread.page", thread=TEAM + ":" + root.id, limit=5) + + + +class StoreTest(unittest.TestCase): + def test_a_mutes_table_made_without_owner_gains_it(self): + import sqlite3 + import tempfile + + from openmate_core.store import Store + + d = tempfile.mkdtemp() + path = os.path.join(d, "openmate.db") + db = sqlite3.connect(path) + db.execute("CREATE TABLE mutes (chat_id TEXT PRIMARY KEY, state TEXT NOT NULL, checked REAL NOT NULL)") + db.commit() + db.close() + st = Store(path) + st.set_mute("c1", "muted", "a1") + self.assertEqual(st.mutes(["c1"], "a1")["c1"][0], "muted") + st.close() + + +if __name__ == "__main__": + unittest.main()