diff --git a/core/openmate_core/app.py b/core/openmate_core/app.py index e42f5bd..7d9f852 100644 --- a/core/openmate_core/app.py +++ b/core/openmate_core/app.py @@ -1807,6 +1807,11 @@ def m_inbox_collect(self, params: dict) -> dict: if th["_chat"] not in known or known[th["_chat"]][1] < now - t.avatar_ttl))) for th in things: del th["_chat"] + if self.platform.inbox_extra is not None: + try: + things.extend(self.platform.inbox_extra(self)) + except Exception as e: + log.warning("the platform Inbox source failed (%s)", type(e).__name__) 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} diff --git a/core/openmate_core/platform.py b/core/openmate_core/platform.py index ff48dc7..94d9db6 100644 --- a/core/openmate_core/platform.py +++ b/core/openmate_core/platform.py @@ -85,6 +85,10 @@ class Platform: #: run may answer {"text", "images"} instead, its pictures for the model (modelimages.Pictures), which go only to a #: hub that takes them (tool_images) tools: Optional[Callable[[Any], Dict[str, Any]]] = None + #: Platform actions: app → {tool name: (schema, describe(args), do(args, key, as_asked))}. + write_tools: Optional[Callable[[Any], Dict[str, Any]]] = None + #: Additional things for the connector Inbox, using the same wire shape as chat items. + inbox_extra: Optional[Callable[[Any], list]] = None #: the platform's read tool that fetches a message's pictures and files by its id (Feishu: matefeishu_media). The #: chat lines models read (the messages tool, /agent's context) name it after each message that has some; "" #: names nothing (WeChat writes its local paths into the text itself) diff --git a/core/openmate_core/tools.py b/core/openmate_core/tools.py index 79abe11..a17f2db 100644 --- a/core/openmate_core/tools.py +++ b/core/openmate_core/tools.py @@ -1,4 +1,4 @@ -"""The connector's tools (reads, no gate) and actions (writes: only after the hub's gate, the phone's confirmation). +"""The connector's read tools and actions (writes after confirmation through the hub). Names are _, so another platform's connector reuses this module with its own prefix. """ @@ -127,12 +127,17 @@ def _rich(app, text: str, names=()) -> bool: return bool(getattr(app.backend, "can_format", False)) and markup.formatted(text, names) +def _platform_writes(app) -> dict: + extra = getattr(app.platform, "write_tools", None) + return extra(app) if extra is not None else {} + + def write_tools(app) -> List[dict]: c, p = app.cid, app.platform.name send = {"chat": {"type": "string", "description": "会话 id"}, "text": {"type": "string", "description": _text_words(app)}, "reply_to": {"type": "string", "description": "要回复的消息 id,可选"}} - what = "以我的身份在%s会话(私聊或群)里发一条消息,可以回复某条消息。每次都要我在手机上确认全文和发给谁。" % p + what = "以我的身份在%s会话(私聊或群)里发一条消息,可以回复某条消息。每次都要我在确认卡片上确认全文和发给谁。" % p if getattr(app.backend, "can_mention", False): send["at"] = {"type": "array", "items": {"type": "string"}, "maxItems": MENTIONS_MOST, "description": "要 @ 的人的用户 id(%s_search 或消息里给出),可选。正文里写到的「@名字」会变成真正的 @," @@ -142,10 +147,10 @@ def write_tools(app) -> List[dict]: what += "话题群和开了话题模式的群里,不给 reply_to 会开一个新话题,给 reply_to 就回复到那条所在的话题。" return [ {"name": c + "_send", "description": what, "input_schema": _obj(send, ["chat", "text"])}, - {"name": c + "_send_dm", "description": "以我的身份私聊一个%s用户(没有私聊会话时先建一个)。每次都要我在手机上确认全文和发给谁。" % p, + {"name": c + "_send_dm", "description": "以我的身份私聊一个%s用户(没有私聊会话时先建一个)。每次都要我在确认卡片上确认全文和发给谁。" % p, "input_schema": _obj({"user": {"type": "string", "description": "对方的用户 id(%s_search 给出)" % c}, "text": {"type": "string", "description": _text_words(app)}}, ["user", "text"])}, - ] + ] + [schema for schema, _, _ in _platform_writes(app).values()] def _args(params: dict) -> dict: @@ -713,6 +718,10 @@ def describe(app, params: dict) -> dict: if name == c + "_send_dm": _, _, visible, summary, _ = _dm_card(app, a) return {"action": {"name": name, "visible": visible}, "summary": summary} + extra = _platform_writes(app).get(name) + if extra is not None: + visible, summary = extra[1](a) + return {"action": {"name": name, "visible": visible}, "summary": summary} raise RPCError("没有这个写操作:%s" % name) @@ -778,6 +787,10 @@ def send(): return {"text": "已私聊 %s" % who, "message_ref": mid} return _result(app.send_once(key, name, send)) + extra = _platform_writes(app).get(name) + if extra is not None: + known = app.send_known(key) + return _result(known if known is not None else extra[2](a, key, as_asked)) raise RPCError("没有这个写操作:%s" % name) diff --git a/extensions/openmate-feishu/assistant/instructions.md b/extensions/openmate-feishu/assistant/instructions.md index ba2632f..227cf60 100644 --- a/extensions/openmate-feishu/assistant/instructions.md +++ b/extensions/openmate-feishu/assistant/instructions.md @@ -6,8 +6,8 @@ OpenMate 把我的飞书私聊和群消息接进了 Persona,工具都以 `mate - **查某个会话一段时间的消息、或在会话里找某个词,用 `matefeishu_messages` 的 `since` / `until` / `query`**(例如 `since: "2026-11-12 15:49"`、`until: "2026-11-12 16:15"`、`query: "周报"`),不要自己用 lark-cli 写循环去拉。它会自己往前补读历史;回答末尾有 `before=` 时,带上同样的条件和这个 `before` 接着查。 - **看飞书消息里的图片和文件用 `matefeishu_media`,不要用 lark-cli。** `matefeishu_messages` 和 /agent 的上下文里,带图片或文件的消息写着 `[图片](看图:matefeishu_media message=…)`:把这个 id 给 `matefeishu_media`,它把图片或文件下载到本机临时目录(25 MB 以内)并给出本地路径,图片直接读这个文件就能看。它是只读的,不会弹确认。下载不了时它会说原因(已撤回或过期、超过上限、飞书没登录等),如实转告,不要猜内容。 - **要真正 @ 群里的人或机器人,先用 `matefeishu_members` 查。** 它列出一个群里的人和机器人,带用户 id 和在这个群里显示的准确名字(只读,列表缓存几分钟)。发消息时把查到的 id 填进 `at`,正文里写「@显示名」;只在正文里打「@名字」不会真的提醒到对方,也不要猜同名的人。 -- **必须自己用 lark-cli 读飞书时,一条命令只调一次 lark-cli,参数写成字面值。** 不要先把结果存进变量(`ids=$(jq … f)`),再把 `"$ids"` 传给 lark-cli:Persona 认不出这种写法是只读的,会把整条命令发到我手机上让我确认。要用上一步的结果,就把具体的值直接写进下一条命令;过滤输出用 `jq`、`head`、`grep`。 -- **发消息一律以我的身份,每一条都要我在手机上确认。** 用 `matefeishu_send`(发到会话、可回复某条消息)或 `matefeishu_send_dm`(私聊某人,用户 id 先用 `matefeishu_search` 查)。确认卡片会写清发给谁、回复哪条和全文,所以要把完整的最终内容放进去,不要分几条试探着发。 +- **必须自己用 lark-cli 读飞书时,一条命令只调一次 lark-cli,参数写成字面值。** 不要先把结果存进变量(`ids=$(jq … f)`),再把 `"$ids"` 传给 lark-cli:Persona 认不出这种写法是只读的,会显示整条命令的确认卡片。要用上一步的结果,就把具体的值直接写进下一条命令;过滤输出用 `jq`、`head`、`grep`。 +- **发消息一律以我的身份,每一条都要我在确认卡片上确认。** 用 `matefeishu_send`(发到会话、可回复某条消息)或 `matefeishu_send_dm`(私聊某人,用户 id 先用 `matefeishu_search` 查)。确认卡片会写清发给谁、回复哪条和全文,所以要把完整的最终内容放进去,不要分几条试探着发。 - **结果不确定的发送不要重试。** 如果写操作说“结果不确定”或“不会再发”,说明那条消息可能已经发出去了:告诉我去飞书里看一眼,不要换个说法再发一遍。 - **/agent 请求要用回复工具答。** 当一条消息说明这是飞书里的 /agent 请求时,用 `matefeishu_agent_reply` 回复,`request` 必须填说明里给出的那个请求 id,不要用 `matefeishu_send` 代替。回复会以我的名义出现在提问的地方(话题里问的回到话题,也发到群里的同样也发到群里,群聊主界面问的在主界面引用回复),并自动带上 AI 代答标记:只写做完的事和查到的事实,没做的写成建议,不替我答应任何事。 撤回飞书里的请求消息也会停止它触发的 Agent,包括 `@自己` 和自动代答。 diff --git a/extensions/openmate-feishu/openmate_feishu/__init__.py b/extensions/openmate-feishu/openmate_feishu/__init__.py index 2c05e29..4f61df4 100644 --- a/extensions/openmate-feishu/openmate_feishu/__init__.py +++ b/extensions/openmate-feishu/openmate_feishu/__init__.py @@ -7,6 +7,7 @@ from __future__ import annotations +import logging import os from typing import Dict @@ -52,13 +53,15 @@ def platform(manifest_path: str = "") -> Platform: login_hint_scanned="已扫码,请在飞书手机 App 上点“确认登录”", login_hint_expired="二维码过期了,已换一张新的,请重新扫码", ui_pages=_agenda_pages, - start_services=_start_meetings, - archive_feeds={"meetings": _archive_meetings}, + start_services=_start_services, + archive_feeds={"meetings": _archive_meetings, "mail": _archive_mail}, items_list=_meeting_items, items_doc_title=_meeting_doc_title, usage_query=_starkmesh_usage, # the sidebar's usage bars: the StarkMesh pool, from the 中转站 page's read legacy_blocked_texts=(DLP_BLOCKED_TEXT,), # what told a blocked message before 0.11.29 stored the mark tools=_read_tools, + write_tools=_write_tools, + inbox_extra=_inbox_extra, media_tool=CONNECTOR_ID + "_media", inbox_topics=True, agent_task_wait=True, # a request whose conversation handed out work stays open until the answer comes @@ -76,28 +79,50 @@ def _verify_at(app, chat_id, wanted): def _read_tools(app): + from .mail import tools as mail_tools from .media import media_tools from .meetings import tools as meeting_tools from .members import members_tools - return {**media_tools(app), **members_tools(app), **meeting_tools(app)} + return {**media_tools(app), **members_tools(app), **meeting_tools(app), **mail_tools(app)} -def _start_meetings(app): - from openmate_core.fixture import FixtureBackend +def _write_tools(app): + from .mail import write_tools - from .meetings import Meetings - from .today import PAGE + return write_tools(app) - def redraw(): - if app.peer is not None: - for page in (PAGE, "calendar"): - app.peer.notify("ui.invalidate", {"contribution": page}) - meetings = Meetings(app, on_change=redraw) - if app.connector_on and not isinstance(app.backend, FixtureBackend): - meetings.start() - app.meetings = meetings +def _start_services(app): + from openmate_core.fixture import FixtureBackend + + from .approvals import Approvals + from .mail import Mail + from .meetings import Meetings + from .today import CARD, PAGE + + def redraw(*pages): + def notify(): + if app.peer is not None: + for page in pages: + try: + app.peer.notify("ui.invalidate", {"contribution": page}) + except Exception: + pass + return notify + + for name, service_class, pages in ( + ("meetings", Meetings, (PAGE, "calendar")), + ("approvals", Approvals, (PAGE, CARD)), + ("mail", Mail, (PAGE,)), + ): + try: + service = service_class(app, on_change=redraw(*pages)) + setattr(app, name, service) + if app.connector_on and not isinstance(app.backend, FixtureBackend): + service.start() + except Exception as error: + logging.getLogger("openmate.feishu").warning("could not start %s (%s)", name, type(error).__name__) def _archive_meetings(app, after, limit): @@ -105,6 +130,16 @@ def _archive_meetings(app, after, limit): return service.archive(after, limit) if service else ([], after, False) +def _archive_mail(app, after, limit): + service = getattr(app, "mail", None) + return service.archive(after, limit) if service else ([], after, False) + + +def _inbox_extra(app): + service = getattr(app, "mail", None) + return service.inbox() if service else [] + + def _meeting_items(app, params): service = getattr(app, "meetings", None) return service.items(params) if service else {"items": []} @@ -137,6 +172,8 @@ def _agenda_pages(app): shared = agenda.Agenda(app) meetings = getattr(app, "meetings", None) + approvals = getattr(app, "approvals", None) + mail = getattr(app, "mail", None) persona = today.PersonaToday(app) wechat = today.PeerToday(app) # openmate-wechat's chats, when it is installed beside this one mesh_read = starkmesh.StarkMesh(app) @@ -162,8 +199,9 @@ def tell(): return { agenda.PAGE: agenda.CalendarPage(app, shared, meetings=meetings), agenda.CARD: agenda.CalendarPage(app, shared, card=True), - today.PAGE: today.TodayPage(app, shared, persona, mesh=mesh, agents=board, wechat=wechat, meetings=meetings), - today.CARD: today.TodayPage(app, shared, persona, card=True, wechat=wechat), + today.PAGE: today.TodayPage(app, shared, persona, mesh=mesh, agents=board, wechat=wechat, meetings=meetings, + approvals=approvals, mail=mail), + today.CARD: today.TodayPage(app, shared, persona, card=True, wechat=wechat, approvals=approvals), starkmesh.PAGE: mesh, starkmesh.CARD: starkmesh.StarkMeshCard(mesh), agents.PAGE: agents.AgentsPage(app, board), agents.CARD: agents.AgentsPage(app, board, card=True), } diff --git a/extensions/openmate-feishu/openmate_feishu/approvals.py b/extensions/openmate-feishu/openmate_feishu/approvals.py new file mode 100644 index 0000000..049afe5 --- /dev/null +++ b/extensions/openmate-feishu/openmate_feishu/approvals.py @@ -0,0 +1,170 @@ +"""Read-only pending approvals and tasks assigned to the CLI user.""" + +import datetime as dt +import json + +from openmate_core.ui import empty, row + +from .larkcli import CalendarError +from .meetings import _time, _url +from .sync_worker import Stopped, SyncWorker + +TITLE = "审批和任务" +ACTION = "approval-task:" +SOURCES = ( + ("approvals", ["approval", "tasks", "query", "--topic", "1", "--page-size", "100"], "tasks"), + ("tasks", ["task", "+get-my-tasks", "--complete=false", "--page-all"], "items"), +) +LABELS = {"approvals": "审批", "tasks": "任务"} + + +class Approvals(SyncWorker): + setting = "approvals" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.snapshot = self.owner, self._load(self.owner) + self.notices = {} + + def _load(self, owner): + try: + return json.loads(self.app.store.meta_get("approvals:" + owner, "{}")) if owner else {} + except ValueError: + return {} + + def owner_changed(self): + self.snapshot = self.owner, self._load(self.owner) + self.notices = {} + super().owner_changed() + + def on_error(self, error): + super().on_error(error) + self._set_notices({"identity": error.message} if error.kind in ("auth", "missing") else self.notices) + + def _set_notices(self, notices): + if notices != self.notices: + self.notices = notices + self.on_change() + + def _sync(self): + owner = self.sync_owner() + now = self.clock() + previous = self.snapshot[1] if self.snapshot[0] == owner else {} + snapshot = dict(previous) + seen = previous.get("seen", {}) + first_seen = now if "approvals" in previous else None + notices = {} + for kind, command, field in SOURCES: + try: + data = self.read(command) + if not isinstance(data, dict) or not isinstance(data.get(field), list): + raise CalendarError("lark-cli 的回答看不懂") + except CalendarError as error: + if error.kind in ("auth", "missing", "permission"): + notices[kind] = LABELS[kind] + "读不到:" + error.message + super().on_error(error) + continue + values = (self._approvals(data[field], seen, first_seen) if kind == "approvals" + else self._tasks(data[field], owner)) + unique = {item["id"]: item for item in values} + snapshot[kind] = [unique[key] for key in sorted(unique)] + if kind == "approvals": + count = data.get("count") + snapshot["approval_count"] = max(count, len(unique)) if isinstance(count, int) else len(unique) + snapshot["seen"] = {key: item["first"] for key, item in unique.items()} + if not self.running() or owner != self.current_owner: + raise Stopped() + if snapshot != previous: + # Verify a changed snapshot before associating it with the cached CLI identity. + if now - self._identity_at >= 30 and self.refresh_owner() != owner: + return + self.app.store.meta_set("approvals:" + owner, json.dumps(snapshot, ensure_ascii=False)) + changed = snapshot != previous or notices != self.notices + self.snapshot, self.notices = (owner, snapshot), notices + if changed: + self.on_change() + + @staticmethod + def _approvals(items, seen, first_seen): + for value in items: + if not isinstance(value, dict) or not value.get("task_id"): + continue + ident = str(value["task_id"]) + yield dict(id=ident, title=str(value.get("title") or value.get("definition_name") or "(无标题)"), + name=str(value.get("initiator_name") or ""), category=str(value.get("definition_name") or ""), + url=_url(value.get("link")), first=seen.get(ident, first_seen)) + + def _tasks(self, items, owner): + for value in items: + if not isinstance(value, dict) or not value.get("guid") or value.get("completed"): + continue + if not any(isinstance(m, dict) and m.get("role") == "assignee" and m.get("id") == owner + for m in value.get("members") or []): + continue + yield dict(id=str(value["guid"]), title=str(value.get("summary") or "(无标题)"), + url=_url(value.get("url")), due=_time(value.get("due_at"), self.app.tz), + created=_time(value.get("created_at"), self.app.tz) or 0) + + def view(self): + owner, current = self.snapshot + snapshot = current if self.enabled and owner and owner == self.current_owner else {} + notices = self.notices if self.enabled else {} + return snapshot, notices + + def counts(self, view): + snapshot, notices = view + return (snapshot.get("approval_count", 0) if "approvals" not in notices else 0, + len(snapshot.get("tasks", ())) if "tasks" not in notices else 0) + + def section(self, view, version, now): + snapshot, notices = view + if not snapshot and not notices: + return None + rows = [empty(text, "", version) for text in notices.values()] + approvals = sorted(snapshot.get("approvals", ()), key=lambda item: ( + item["first"] is not None, item["first"] or 0, item["id"])) + tasks = sorted(snapshot.get("tasks", ()), key=lambda item: ( + item["due"] is None, item["due"] or 0, item["created"], item["id"])) + if approvals and "approvals" not in notices: + rows.append({"type": "text", "text": "待我审批"}) + for item in approvals[:5]: + first = item["first"] + age = "" if first is None else "%d 小时前" % max(0, int((now.timestamp() - first) / 3600)) + detail = " · ".join(filter(None, (item["name"], item["category"]))) + rows.append(self._row("approvals", item, detail, age)) + if snapshot["approval_count"] > 5: + rows.append({"type": "text", "text": "还有 %d 条" % (snapshot["approval_count"] - 5)}) + if tasks and "tasks" not in notices: + rows.append({"type": "text", "text": "分给我的任务"}) + for item in tasks[:5]: + label, badge = self._due(item["due"], now) + rows.append(self._row("tasks", item, "", label, **({"badge": badge} if badge else {}))) + if len(tasks) > 5: + rows.append({"type": "text", "text": "还有 %d 条" % (len(tasks) - 5)}) + return {"title": TITLE, "items": rows or [empty("没有等你审批的单子和任务", "", version)]} + + @staticmethod + def _row(kind, item, detail, label, **extra): + key = ACTION + kind + ":" + item["id"] + return row(item["title"], detail, label, action=key if item["url"] else None, key=key, **extra) + + @staticmethod + def _due(due, now): + if due is None: + return "无截止日期", None + date = dt.datetime.fromtimestamp(due, now.tzinfo).date() + days = (date - now.date()).days + if days < 0: + return "", {"text": "逾期 %d 天" % -days, "tone": "danger"} + if not days: + return "", {"text": "今天到期", "tone": "caution"} + return date.isoformat(), None + + def open(self, aid): + kind, _, ident = aid[len(ACTION):].partition(":") + snapshot, notices = self.view() + if kind in LABELS and kind not in notices: + for item in snapshot.get(kind, ()): + if item["id"] == ident and item["url"]: + return {"open_url": item["url"]} + return {"toast": "这条待办没有可以打开的链接"} diff --git a/extensions/openmate-feishu/openmate_feishu/larkcli.py b/extensions/openmate-feishu/openmate_feishu/larkcli.py index e6d31e0..52743fb 100644 --- a/extensions/openmate-feishu/openmate_feishu/larkcli.py +++ b/extensions/openmate-feishu/openmate_feishu/larkcli.py @@ -30,11 +30,18 @@ r"token (?:is |has )?(?:invalid|expired)|not (?:logged in|signed in|authenticated)|(?:log ?in|sign ?in) required)\b" ) # Only these shortcuts return individually identifiable results in a failed envelope. -_BATCH_RESULTS = {"minutes +detail": ("minutes", "minute_token"), "vc +detail": ("meetings", "meeting_id")} +_BATCH_RESULTS = {"minutes +detail": ("minutes", "minute_token"), "vc +detail": ("meetings", "meeting_id"), + "mail +messages": ("messages", "message_id")} +_MAIL_TOP_LEVEL = { + "mail +triage": {"messages"}, + "mail +reply": {"message_id", "draft_id", "automation_send_disable_reason", "automation_send_disable_reference"}, + "mail +reply-all": {"message_id", "draft_id", "automation_send_disable_reason", "automation_send_disable_reference"}, +} def _command_size(args): - return 3 if tuple(args[:2]) in (("drive", "metas"), ("minutes", "minutes")) else 2 + return 3 if tuple(args[:2]) in (("drive", "metas"), ("minutes", "minutes"), + ("approval", "tasks"), ("mail", "user_mailboxes")) else 2 class CalendarError(Exception): @@ -124,6 +131,7 @@ def __init__(self, config: dict, run: Callable = subprocess.run, store=None): self._bin_lock = threading.Lock() self._store = store self._user = None + self._user_lock = threading.Lock() def bin(self, timeout: float = 15) -> str: deadline = time.monotonic() + timeout @@ -224,11 +232,22 @@ def call(self, args, timeout: float = TIMEOUT): if not getattr(p, "returncode", 0) and data is not None: if data.get("ok"): failed = False + if "data" not in data and data.keys() & _MAIL_TOP_LEVEL.get(command, ()): + return data return data.get("data") if list(args[:2]) == ["auth", "status"] and "identities" in data: failed = False return data + if "ok" not in data and not data.get("error") and data.keys() & _MAIL_TOP_LEVEL.get(command, ()): + failed = False + return data reports = [report for report in (data, _json_object(p.stderr)) if report] + if command == "mail +messages": + for report in reports: + if report.get("ok") is False: + payload = _batch_payload(command, report.get("data")) + if payload is not None: + return payload for report in reports: if report.get("error") or report.get("missing_scopes"): raise self._error(report) @@ -291,14 +310,15 @@ def user_name(self) -> str: return "" def user_open_id(self, refresh: bool = False) -> str: - if self._user is None or refresh: - self._user = None - user = self._identity() - owner = str(user.get("openId") or "").strip() - if self._store is not None and self._store.meta_get("lark_cli_open_id") != owner: - self._store.meta_set("lark_cli_open_id", owner) - self._user = user - return str(self._user.get("openId") or "").strip() + with self._user_lock: + if self._user is None or refresh: + self._user = None + user = self._identity() + owner = str(user.get("openId") or "").strip() + if self._store is not None and self._store.meta_get("lark_cli_open_id") != owner: + self._store.meta_set("lark_cli_open_id", owner) + self._user = user + return str(self._user.get("openId") or "").strip() @property def cached_user_name(self) -> str: diff --git a/extensions/openmate-feishu/openmate_feishu/layout.py b/extensions/openmate-feishu/openmate_feishu/layout.py index d265323..e8812dd 100644 --- a/extensions/openmate-feishu/openmate_feishu/layout.py +++ b/extensions/openmate-feishu/openmate_feishu/layout.py @@ -18,9 +18,11 @@ BLOCKS = ( ("status", "状态", True, "需要我、日程、飞书、微信、Agent、中转站,各一块,带状态标签"), ("needs", "需要我", True, "要你回复、决定或验收的事"), + ("approvals", "审批和任务", False, "等我审批的单子、分给我的飞书任务"), ("calendar", "日程", False, "今天的会和待回复的邀请"), ("meetings", "会议", False, "最近开完的会:纪要有没有进知识库、会上分给我的待办"), ("feishu", "飞书今天", False, "今天活跃的群"), + ("mail", "邮件", False, "飞书邮箱里重要的新邮件"), ("wechat", "微信今天", False, "今天活跃的微信群(装了微信扩展才有)"), ("agents", "Agent", False, "等你、可能卡住、在跑的 Agent"), ("mesh", "中转站", False, "StarkMesh 各窗口剩多少"), diff --git a/extensions/openmate-feishu/openmate_feishu/mail.py b/extensions/openmate-feishu/openmate_feishu/mail.py new file mode 100644 index 0000000..9d7d4b4 --- /dev/null +++ b/extensions/openmate-feishu/openmate_feishu/mail.py @@ -0,0 +1,555 @@ +"""Synchronize Feishu mail and serve the local cache to Today, Inbox and the knowledge base.""" + +import datetime as dt +from email.utils import getaddresses, parseaddr, parsedate_to_datetime +import hashlib +import json +import re +import threading + +from openmate_core.backend import BackendError, SendRejected +from openmate_core.textutil import one_line +from openmate_core.ui import empty, row, when +from openmate_core.views import rfc3339 +from openmate_core.wire import RPCError + +from .larkcli import CalendarError +from .mail_store import MailStore +from .meetings import _number, _time +from .sync_worker import ACTIVE, IDLE, Stopped, SyncWorker + +DAY = 86400 +BODY_LIMIT = 50 * 1024 +DETAIL_LIMIT = 8000 +STORE_CLIP = "\n(正文超过 50 KB,已截断)" +PAGE_CLIP = "\n(正文超过 8000 字,已截断)" +OPEN = "mail:open:" +BACK = "mail:back" +_PROFILE = ["mail", "user_mailboxes", "profile", "--params", '{"user_mailbox_id":"me"}'] +_ID = re.compile(r"[A-Za-z0-9=]+") +_ADDRESS = re.compile(r"[^\s<>@,;]+@[^\s<>@,;]+") +_NOTICE = re.compile(r"no[._-]?reply|notifications?|notices?|mailer[._-]?daemon|postmaster|do[._-]?not[._-]?reply", + re.IGNORECASE) +_REPLY_PREFIX = re.compile(r"^(?:re:|fw:|fwd:|回复:|转发:)\s*", re.IGNORECASE) + + +def _string(value): + return value if isinstance(value, str) else "" + + +def _address(value): + value = _string(value).strip() + return value if _ADDRESS.fullmatch(value) and all(ord(ch) >= 32 for ch in value) else "" + + +def _recipients(values): + return [dict(name=_string(v.get("name")), address=_address(v.get("mail_address"))) for v in values + if isinstance(v, dict) and _address(v.get("mail_address"))] if isinstance(values, list) else [] + + +def _labels(value): + if isinstance(value, str): + value = re.split(r"[\s,]+", value) + return sorted({v.upper() for v in value if isinstance(v, str) and v}) if isinstance(value, list) else [] + + +def _mail_date(value, tz): + try: + return dt.datetime.fromtimestamp(int(value) / 1000, tz).timestamp() if value else None + except (ValueError, TypeError, OverflowError, OSError): + return None + + +def _listing_date(value, tz): + at = _time(value, tz) + if at is not None: + return at + try: + parsed = parsedate_to_datetime(_string(value)) + return (parsed if parsed.tzinfo else parsed.replace(tzinfo=tz)).timestamp() + except (ValueError, OverflowError, OSError): + return None + + +def _clip_body(text): + data = text.encode("utf-8") + if len(data) <= BODY_LIMIT: + return text + return data[:BODY_LIMIT - len(STORE_CLIP.encode("utf-8"))].decode("utf-8", "ignore") + STORE_CLIP + + +def _sender(item): + return item["from_name"] or item["from_addr"] or "(发件人未知)" + + +def _brief(item): + return dict(message_id=item["message_id"], thread_id=item["thread_id"], at=rfc3339(item["at"]), + sender=_sender(item), from_addr=item["from_addr"], subject=item["subject"], + unread=bool(item["unread"]), important=bool(item["important"])) + + +def _subject(item): + return item["subject"] or "(无主题)" + + +def _triage(data, tz): + if not isinstance(data, dict) or not isinstance(data.get("messages"), list): + raise CalendarError("lark-cli 的邮件列表看不懂") + entries = {} + for item in data["messages"]: + if not isinstance(item, dict): + continue + mid, thread = _string(item.get("message_id")), _string(item.get("thread_id")) + if _ID.fullmatch(mid) and _ID.fullmatch(thread): + entries[mid] = dict(item, at=_listing_date(item.get("date"), tz)) + return entries + + +def _detail(mid, item, info, folder, floor, tz): + at = _mail_date(item.get("internal_date"), tz) or _listing_date(item.get("date_formatted"), tz) or info["at"] + if at < floor: + return None + thread = _string(item.get("thread_id")) or info["thread_id"] + if not _ID.fullmatch(thread): + return None + sender = item.get("head_from") + name, address = parseaddr(_string(info.get("from"))) + if isinstance(sender, dict): + name = _string(sender.get("name")) or name + address = _address(sender.get("mail_address")) or address + attachments = item.get("attachments") + return dict(message_id=mid, thread_id=thread, folder=folder, subject=_string(item.get("subject", info.get("subject"))), + from_name=name, from_addr=_address(address), to=_recipients(item.get("to")), cc=_recipients(item.get("cc")), + reply_to=[a for _, addr in getaddresses([_string(item.get("reply_to"))]) if (a := _address(addr))], + at=at, labels=_labels(info.get("labels", item.get("label_ids"))), + body=_clip_body(_string(item.get("body_plain_text"))), + attachments=[a["filename"] for a in attachments if isinstance(a, dict) and _string(a.get("filename"))] + if isinstance(attachments, list) else []) + + +def _direct(item, address): + sender = item["from_addr"] + return bool(address and sender and not _NOTICE.search(sender.partition("@")[0]) and + any(v["address"].casefold() == address.casefold() for v in item["to"])) + + +class Mail(SyncWorker): + setting = "mail" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.db = MailStore(self.app.store, self.clock()) + self._retry = {} + self._notice = "" + self._address_due = threading.Event() + + @property + def kb_enabled(self): + return self.enabled and self.app.config.get("mail_kb", True) + + @property + def inbox_enabled(self): + return self.enabled and self.app.config.get("mail_inbox", True) + + def owner_changed(self): + self._retry = {} + self._notice = "" + self.on_change() + self.app.mark_changed("inbox", "chats") + + def on_error(self, error): + super().on_error(error) + if error.kind in ("auth", "missing", "permission") and error.message != self._notice: + self._notice = error.message + self.on_change() + + def _list(self, folder, unread=False): + return _triage(self.read(["mail", "+triage", "--folder-id", folder, "--max", "20", "--labels"] + + (["--is-unread"] if unread else [])), self.app.tz) + + def _profile(self, read): + data = read(_PROFILE) + if isinstance(data, dict): + return _address(data.get("primary_email_address")) + return "" + + def _mailbox(self, sent): + try: + address = self._profile(self.read) + if address: + return address, True + except CalendarError as error: + super().on_error(error) + if sent: + latest = max(sent.values(), key=lambda item: item["at"] or 0) + return _address(parseaddr(_string(latest.get("from")))[1]), False + return "", False + + def _sync(self): + owner = self.sync_owner() + now, tz = self.clock(), self.app.tz + settings = self.db.settings(owner) + floor = settings.get("floor", now - 14 * DAY) + inbox = self._list("INBOX") + unseen = self._list("INBOX", unread=True) + sent = self._list("SENT") + listings = {mid: (item, "INBOX") for mid, item in {**unseen, **inbox}.items() + if item["at"] is not None and item["at"] >= floor} + listings.update({mid: (item, "SENT") for mid, item in sent.items() + if item["at"] is not None and item["at"] >= floor}) + unread = unseen.keys() - sent.keys() + in_inbox = (inbox.keys() | unseen.keys()) - sent.keys() + known = self.db.known(owner, listings) + pending = [mid for mid in listings if mid not in known and now >= self._retry.get(mid, (0, 0))[1]] + if owner != self.current_owner: + raise Stopped() + needs_profile = (not settings or self._address_due.is_set() or + (not settings.get("verified") and pending and now >= settings.get("address_retry", 0))) + if needs_profile: + self._address_due.clear() + address, verified = self._mailbox(sent) + settings.update(address=address, verified=verified, address_retry=now + IDLE) + settings["floor"] = floor + rows, errors = self._details(pending, listings, floor, now, tz) + if not self.running() or owner != self.current_owner: + raise Stopped() + if (pending or needs_profile) and self.refresh_owner() != owner: + return + address = settings.get("address", "") + inbox_on = self.inbox_enabled + updates = [] + for mid, cached in known.items(): + info, folder = listings[mid] + labels = _labels(info["labels"]) if "labels" in info else cached["labels"] + flag = mid in unread + visible = inbox_on and folder == "INBOX" and flag and "IMPORTANT" in labels and _direct(cached, address) + updates.append((mid, folder, labels, flag, cached["inbox_seen"] or visible)) + for item in rows: + item["mine"] = item["folder"] == "SENT" + item["important"] = "IMPORTANT" in item["labels"] + item["unread"] = item["message_id"] in unread + item["inbox_listed"] = item["message_id"] in in_inbox + item["inbox_seen"] = bool(inbox_on and not item["mine"] and item["unread"] and item["important"] + and _direct(item, address)) + sent_at = {} + for item in sent.values(): + thread = item["thread_id"] + if item["at"] is not None: + sent_at[thread] = max(item["at"], sent_at.get(thread, 0)) + changed, archived = self.db.save(owner, settings, rows, updates, unread, in_inbox, sent_at, now=now) + self._retry = {mid: retry for mid, retry in self._retry.items() if mid in listings} + notice = next((e.message for e in errors if e.kind in ("auth", "missing", "permission")), "") + if changed or notice != self._notice: + self._notice = notice + self.on_change() + if changed and self.inbox_enabled: + self.app.mark_changed("inbox") + if archived and self.kb_enabled: + self.app.mark_changed("chats") + + def _details(self, pending, listings, floor, now, tz): + if not pending: + return [], [] + try: + data = self.read(["mail", "+messages", "--message-ids", ",".join(pending), "--html=false"]) + except CalendarError as error: + if error.kind in ("auth", "missing"): + raise + data = None + batch_error = error + else: + batch_error = CalendarError("邮件正文暂时读不到") + returned = data.get("messages") if isinstance(data, dict) else None + items = {v.get("message_id"): v for v in returned if isinstance(v, dict) + and isinstance(v.get("message_id"), str)} if isinstance(returned, list) else {} + rows, errors = [], [] + for mid in pending: + item = items.get(mid) + if item is not None and not item.get("error"): + row_data = _detail(mid, item, *listings[mid], floor, tz) + if row_data is not None: + rows.append(row_data) + self._retry.pop(mid, None) + continue + error = self.cli._error(item) if item and item.get("error") else batch_error + super().on_error(error) + errors.append(error) + tries = self._retry.get(mid, (0, 0))[0] + 1 + self._retry[mid] = tries, now + ACTIVE * (2 ** min(tries - 1, 5)) + return rows, errors + + def inbox(self): + owner = self.current_owner + if not self.inbox_enabled or not owner: + return [] + things = {} + rules = str(self.app.config.get("triage_rules") or "").strip()[:4000] + for item in self.db.inbox(owner, self.clock() - 14 * DAY): + thread = "mail:" + item["thread_id"] + done = "replied" if item["replied"] else ( + "read" if not item["unread"] or not item["important"] or item["folder"] != "INBOX" else "") + if thread in things and (not things[thread].get("done") or done): + continue + sender, title = _sender(item), _subject(item) + text = "%s · %s" % (sender, one_line(item["excerpt"], 200)) if item["excerpt"] else sender + thing = dict(thread=thread, kind="mail", label="邮件", title=title, sender=sender, preview=text, + context=title + "\n" + text, at=rfc3339(item["at"]), last=item["message_id"], + extra={"rule_tier": "action"}, tags=[{"key": "sender", "name": sender, "value": item["from_addr"]}]) + if rules: + thing["rules"] = rules + if done: + thing.update(done=done, why="我已经回复" if done == "replied" else "邮件已读或移出了重要收件箱") + things[thread] = thing + return list(things.values()) if owner == self.current_owner else [] + + def archive(self, after, limit): + if not self.kb_enabled: + return [], max(after, self.db.high_water()), False + owner = self.current_owner + if not owner: + return [], after, False + data = self.db.archive(owner, after, 41) + out, cursor = {}, after + for item in data[:40]: + eligible = item["important"] or item["mine"] + chat = "mail-" + item["thread_id"] + if eligible and chat not in out and len(out) >= limit: + break + cursor = item["kb_seq"] + if not eligible: + continue + batch = out.setdefault(chat, {"chat": dict(id=chat, name=_subject(item), kind="mail", + updated_at=rfc3339(item["updated_at"])), "messages": []}) + body = "主题:" + _subject(item) + "\n" + item["body"] + if item["attachments"]: + body += "\n附件:" + "、".join(item["attachments"]) + handles = [{"kind": "email", "value": item["from_addr"]}] if item["from_addr"] else [] + batch["messages"].append(dict(id="mail-" + item["message_id"], position=str(cursor), type="TEXT", + text=body, at=rfc3339(item["at"]), sender_name=_sender(item), + sender_handles=handles, mine=bool(item["mine"]))) + more = bool(data and data[-1]["kb_seq"] > cursor) + return (list(out.values()), cursor, more) if owner == self.current_owner else ([], after, False) + + def section(self, version, now): + if not self.enabled: + return None + owner = self.current_owner + if not owner or not self.db.settings(owner): + return None + rows = self.db.recent(owner, now.timestamp() - 2 * DAY, now.timestamp(), 5, inbox=True) + if owner != self.current_owner: + return None + return {"title": "邮件", "items": [ + row(_subject(item), _sender(item), when(item["at"], self.app.tz, now.timestamp()), + action=OPEN + item["message_id"] + ":" + owner, key="mail:" + item["message_id"], + badge={"text": "未读", "tone": "caution"} if item["unread"] else None) for item in rows + ] or [empty("这两天没有重要邮件", "", version)]} + + def get(self, mid, owner): + return self.db.get(owner, mid) if self.enabled and owner and _ID.fullmatch(mid) else None + + def detail_items(self, mid, owner, version, now): + item = self.get(mid, owner) + if item is None or owner != self.current_owner: + return "邮件", [empty("这封邮件现在看不到", "", version)] + body = item["body"] + if len(body) > DETAIL_LIMIT: + body = body[:DETAIL_LIMIT - len(PAGE_CLIP)] + PAGE_CLIP + return _subject(item), [ + row("发件人", _sender(item) + (" <" + item["from_addr"] + ">" if item["from_name"] and item["from_addr"] else "")), + row("收件人", "、".join(v["address"] for v in item["to"]) or "—"), + *([row("抄送", "、".join(v["address"] for v in item["cc"]))] if item["cc"] else []), + row("时间", dt.datetime.fromtimestamp(item["at"], self.app.tz).strftime("%Y-%m-%d %H:%M")), + {"type": "text", "text": body}, + *([row("附件", name) for name in item["attachments"]]), + ] + + def tool(self, args): + if not self.enabled: + return "飞书邮箱功能没开" + self.look() + owner = self.current_owner + action = args.get("action", "list") + if action == "read": + mid = _string(args.get("message_id")).strip() + item = self.get(mid, owner) + if not item: + return "本地没有找到这封邮件" + others = self.db.thread(owner, item["thread_id"], mid) + result = dict(_brief(item), body=item["body"], to=item["to"], cc=item["cc"], attachments=item["attachments"], + thread=[dict(message_id=v["message_id"], sender=_sender(v), at=rfc3339(v["at"]), + preview=v["preview"]) for v in reversed(others)]) + elif action == "list": + days = _number(args.get("days"), 3, 1, 30) + now = self.clock() + items = self.db.recent(owner, now - days * DAY, now, 30, unread_only=args.get("unread_only") is True, + query=_string(args.get("query")).strip()) if owner else [] + result = {"messages": [_brief(item) for item in items]} + if self._notice: + result["notice"] = self._notice + else: + raise RPCError("action 必须是 list 或 read") + return json.dumps(result, ensure_ascii=False) if owner == self.current_owner else "刚换了飞书邮箱账号,请重新读取" + + def _reply_card(self, args): + if not self.enabled: + raise RPCError("飞书邮箱功能没开") + mid, body = _string(args.get("message_id")).strip(), _string(args.get("body")) + reply_all, send = args.get("reply_all", False), args.get("send", True) + if not body.strip() or "\x00" in body: + raise RPCError("请填写纯文本回复正文") + if not isinstance(reply_all, bool) or not isinstance(send, bool): + raise RPCError("reply_all 和 send 必须是布尔值") + owner = self.current_owner + item = self.get(mid, owner) + if item is None: + raise RPCError("本地没有找到要回复的邮件,请用 matefeishu_mail 查 message_id") + address = self.db.settings(owner).get("address", "") + if reply_all and not address: + raise RPCError("还没识别出你的邮箱地址,无法确认回复全部的收件人") + to, cc = _reply_recipients(item, address, reply_all) + if not to and not cc: + raise RPCError("没有可确认的回复收件人") + subject = one_line(item["subject"], len(item["subject"]) or 1) + while _REPLY_PREFIX.match(subject): + subject = _REPLY_PREFIX.sub("", subject, count=1) + subject = "Re: " + (subject or "(无主题)") + return (mid, body, reply_all, send), dict(owner=owner, thread_id=item["thread_id"], address=address, + subject=subject, to=to, cc=cc) + + def describe(self, args): + request, card = self._reply_card(args) + _, body, _, send = request + if card["owner"] != self.current_owner: + raise RPCError("刚换了飞书邮箱账号,请重新生成确认卡片") + # Describe has no request ID. Identical args must never rebind a pending card to another owner or recipients. + if not self.db.remember_reply_card(_digest(request), card, self.clock()): + raise RPCError("同一回复的账号或收件人有变化,请重新拟一份回复") + address, subject, to, cc = (card[k] for k in ("address", "subject", "to", "cc")) + visible = "、".join((*to, *cc)) + summary = ["直接发出" if send else "只存草稿", "发件邮箱:" + (address or "当前飞书邮箱"), + "To:" + ("、".join(to) or "—"), "Cc:" + ("、".join(cc) or "—"), + "主题:" + subject, "飞书会引用原邮件,并按邮箱设置添加默认回复签名。", "——", body] + return visible, "\n".join(summary) + + def do(self, args, key, as_asked): + request, card = self._reply_card(args) + mid, body, reply_all, send = request + owner, address, subject = (card[k] for k in ("owner", "address", "subject")) + + def reply(): + as_asked() + if self.db.reply_card(_digest(request), self.clock()) != card or owner != self.current_owner: + raise RPCError("账号或回复信息有变化,邮件没有发出,请重新打开确认卡片") + try: + fresh = self.cli.user_open_id(refresh=True) + except CalendarError as error: + self.set_owner("") + raise RPCError("无法核对飞书邮箱账号,邮件没有发出:" + error.message) from None + if fresh != owner: + self.set_owner(fresh) + raise RPCError("刚换了飞书邮箱账号,邮件没有发出") + if reply_all: + try: + primary = self._profile(self.cli.read) + except CalendarError: + primary = "" + if primary and primary.casefold() != address.casefold(): + self._address_due.set() + raise RPCError("飞书邮箱地址有变化,邮件没有发出,请在同步后重新确认") + as_asked() + if not self.enabled or owner != self.current_owner: + raise RPCError("飞书邮箱设置或账号有变化,邮件没有发出") + command = ["mail", "+reply-all" if reply_all else "+reply", "--message-id", mid, + "--body", body, "--plain-text", "--subject", subject] + if address: + command += ["--from", address, "--mailbox", "me"] + if send: + command.append("--confirm-send") + try: + result = self.cli.read(command) + except CalendarError as error: + if error.refused and error.kind != "timeout": + message = "lark-cli 没有完成此邮件操作的权限" if error.kind == "permission" else error.message + if send: + raise SendRejected(message) from None + raise RPCError("草稿没有保存:" + message) from None + return self._uncertain(send, error.message) + if isinstance(result, dict): + if send and (result.get("automation_send_disable_reason") or result.get("automation_send_disable_reference")): + return {"text": "没有发出去:邮箱设置拦截了发送,请到飞书邮箱查看草稿"} + ref = _string(result.get("message_id" if send else "draft_id")) + if _ID.fullmatch(ref): + if not send: + return {"text": "已保存回复草稿(草稿 id:%s)" % ref} + return {"text": "已发送邮件回复", "message_ref": ref} + return self._uncertain(send, "lark-cli 的回答看不懂") + + return self.app.send_once(key, self.app.cid + "_mail_reply", reply) + + @staticmethod + def _uncertain(send, message): + if send: + # send_once journals this as uncertain and prevents another attempt with the same request ID. + raise BackendError(message, "uncertain") + return {"text": "草稿保存结果不确定(%s),可能已经保存,请先到飞书邮箱查看" % message} + + +def _reply_recipients(item, address, reply_all): + original_to = [v["address"] for v in item["to"]] + original_cc = [v["address"] for v in item["cc"]] + sender = item["reply_to"] or ([item["from_addr"]] if item["from_addr"] else []) + if not reply_all: + return sender, [] + seen = {address.casefold()} + + def unique(values): + out = [] + for value in values: + if value.casefold() not in seen: + seen.add(value.casefold()) + out.append(value) + return out + + if item["from_addr"].casefold() == address.casefold(): + return unique(original_to + sender), unique(original_cc) + return unique(sender), unique(original_to + original_cc) + + +def _digest(request): + return hashlib.sha256(json.dumps(request, ensure_ascii=False).encode("utf-8")).digest() + + +def tools(app): + name = app.cid + "_mail" + schema = {"name": name, "description": "只读查询本地飞书邮箱。list 找最近的邮件,read 读一封正文和同一会话的摘要。", + "input_schema": {"type": "object", "properties": { + "action": {"type": "string", "enum": ["list", "read"], "default": "list"}, + "days": {"type": "integer", "minimum": 1, "maximum": 30, "default": 3}, + "unread_only": {"type": "boolean", "default": False}, + "query": {"type": "string", "description": "按主题、发件人和正文搜索"}, + "message_id": {"type": "string", "description": "read 要读取的邮件 id"}}}} + + def read(args): + service = getattr(app, "mail", None) + return service.tool(args) if service else "飞书邮箱尚未同步" + + return {name: (schema, read)} + + +def write_tools(app): + name = app.cid + "_mail_reply" + schema = {"name": name, "description": "回复飞书邮件。确认卡片会列出收件人、主题和完整正文。默认批准后直接发出,send=false 只存草稿。", + "input_schema": {"type": "object", "required": ["message_id", "body"], "properties": { + "message_id": {"type": "string", "description": "原邮件 id,由 matefeishu_mail 给出"}, + "body": {"type": "string", "description": "完整回复正文(纯文本)"}, + "reply_all": {"type": "boolean", "default": False}, + "send": {"type": "boolean", "default": True}}}} + + def service(): + value = getattr(app, "mail", None) + if value is None: + raise RPCError("飞书邮箱尚未同步") + return value + + return {name: (schema, lambda args: service().describe(args), lambda args, key, as_asked: service().do(args, key, as_asked))} diff --git a/extensions/openmate-feishu/openmate_feishu/mail_store.py b/extensions/openmate-feishu/openmate_feishu/mail_store.py new file mode 100644 index 0000000..63da4ec --- /dev/null +++ b/extensions/openmate-feishu/openmate_feishu/mail_store.py @@ -0,0 +1,175 @@ +"""Local mail cache and append-only positions for Persona's archive.""" + +import json + +_SCHEMA = ( + """CREATE TABLE IF NOT EXISTS mails ( + message_id TEXT PRIMARY KEY, owner TEXT NOT NULL, thread_id TEXT NOT NULL, folder TEXT NOT NULL, + subject TEXT NOT NULL, from_name TEXT NOT NULL, from_addr TEXT NOT NULL, "to" TEXT NOT NULL, + cc TEXT NOT NULL, reply_to TEXT NOT NULL, at REAL NOT NULL, labels TEXT NOT NULL, + important INTEGER NOT NULL, unread INTEGER NOT NULL, mine INTEGER NOT NULL, body TEXT NOT NULL, + attachments TEXT NOT NULL, kb_seq INTEGER NOT NULL DEFAULT 0, inbox_seen INTEGER NOT NULL DEFAULT 0, + inbox_listed INTEGER NOT NULL DEFAULT 0, + replied_at REAL NOT NULL DEFAULT 0 + )""", + "CREATE INDEX IF NOT EXISTS mails_at ON mails(owner, at DESC, message_id)", + "CREATE INDEX IF NOT EXISTS mails_thread ON mails(owner, thread_id, at DESC)", + "CREATE INDEX IF NOT EXISTS mails_kb ON mails(owner, kb_seq)", + "CREATE INDEX IF NOT EXISTS mails_inbox ON mails(owner, at DESC) WHERE inbox_seen=1", + """CREATE TABLE IF NOT EXISTS mail_reply_cards ( + digest BLOB PRIMARY KEY, card TEXT NOT NULL, saved_at REAL NOT NULL + )""", +) +_JSON = ("to", "cc", "reply_to", "labels", "attachments") +_COLUMNS = ('message_id', 'thread_id', 'folder', 'subject', 'from_name', 'from_addr', 'to', 'cc', + 'reply_to', 'at', 'labels', 'important', 'unread', 'mine', 'body', 'attachments', 'inbox_seen', 'inbox_listed') +_BRIEF = "message_id, thread_id, subject, from_name, from_addr, at, unread, important" +_SEQ_KEY = "mail_archive_seq" +_CARD_TTL = 7 * 86400 +_CARD_MOST = 256 + + +def _row(raw): + result = dict(raw) + for key in _JSON: + if key in result: + result[key] = json.loads(result[key]) + return result + + +def _marks(values): + return ",".join("?" for _ in values) + + +class MailStore: + def __init__(self, store, now): + self.store = store + + def setup(db): + for sql in _SCHEMA: + db.execute(sql) + self._prune_reply_cards(db, now) + + store._tx(setup) + + def settings(self, owner): + return json.loads(self.store.meta_get("mail:" + owner, "{}")) + + @staticmethod + def _prune_reply_cards(db, now): + db.execute("DELETE FROM mail_reply_cards WHERE saved_at<=?", (now - _CARD_TTL,)) + + def remember_reply_card(self, digest, card, now): + serialized = json.dumps(card, ensure_ascii=False) + + def write(db): + self._prune_reply_cards(db, now) + old = db.execute("SELECT card FROM mail_reply_cards WHERE digest=?", (digest,)).fetchone() + if old is not None and old[0] != serialized: + return False + db.execute("INSERT OR REPLACE INTO mail_reply_cards(digest, card, saved_at) VALUES (?,?,?)", + (digest, serialized, now)) + db.execute("DELETE FROM mail_reply_cards WHERE digest IN (" + "SELECT digest FROM mail_reply_cards ORDER BY saved_at DESC, rowid DESC LIMIT -1 OFFSET ?)", + (_CARD_MOST,)) + return True + + return self.store._tx(write) + + def reply_card(self, digest, now): + value = self.store._one("SELECT card FROM mail_reply_cards WHERE digest=? AND saved_at>?", + (digest, now - _CARD_TTL)) + return json.loads(value[0]) if value is not None else None + + def known(self, owner, ids): + if not ids: + return {} + return {r["message_id"]: _row(r) for r in self.store._all( + "SELECT message_id, folder, labels, \"to\", from_addr, inbox_seen FROM mails " + "WHERE owner=? AND message_id IN (%s)" % _marks(ids), (owner, *ids))} + + def save(self, owner, settings, details, updates, unread, inbox, sent, *, now): + """Commit successful details and the complete unread snapshot together.""" + def write(db): + self._prune_reply_cards(db, now) + current = db.execute("SELECT value FROM meta WHERE key='lark_cli_open_id'").fetchone() + if current is None or current[0] != owner: + return False, False + before = db.total_changes + for column, ids in (("unread", unread), ("inbox_listed", inbox)): + sql = "UPDATE mails SET " + column + "=0 WHERE owner=? AND " + column + "=1" + if ids: + sql += " AND message_id NOT IN (%s)" % _marks(ids) + db.execute(sql, (owner, *ids)) + quoted = ", ".join('"%s"' % column for column in _COLUMNS) + for item in details: + # A shared message ID must be fetched afresh before replacing the previous owner's cached copy. + db.execute("DELETE FROM mails WHERE message_id=? AND owner!=?", (item["message_id"], owner)) + vals = [json.dumps(item[key], ensure_ascii=False) if key in _JSON else item[key] for key in _COLUMNS] + db.execute("INSERT INTO mails (owner, " + quoted + ") VALUES (?," + _marks(vals) + ") " + "ON CONFLICT(message_id) DO NOTHING", (owner, *vals)) + for mid, folder, labels, unread_flag, inbox_seen in updates: + values = (folder, json.dumps(labels, ensure_ascii=False), "IMPORTANT" in labels, + unread_flag, folder == "SENT", inbox_seen, mid in inbox) + db.execute( + "UPDATE mails SET folder=?, labels=?, important=?, unread=?, mine=?, inbox_seen=?, inbox_listed=? " + "WHERE owner=? AND message_id=? " + "AND (folder,labels,important,unread,mine,inbox_seen,inbox_listed)!=(?,?,?,?,?,?,?)", + (*values, owner, mid, *values)) + db.executemany("UPDATE mails SET replied_at=? WHERE owner=? AND thread_id=? AND inbox_seen=1 " + "AND at0") + args.append(query) + return [dict(r) for r in self.store._all( + "SELECT " + _BRIEF + " FROM mails WHERE " + " AND ".join(clauses) + + " ORDER BY at DESC, message_id LIMIT ?", (*args, limit))] + + def get(self, owner, mid): + value = self.store._one("SELECT * FROM mails WHERE owner=? AND message_id=?", (owner, mid)) + return _row(value) if value else None + + def thread(self, owner, thread, mid): + return [dict(r) for r in self.store._all( + "SELECT " + _BRIEF + ", substr(body,1,500) AS preview, mine FROM mails " + "WHERE owner=? AND thread_id=? AND message_id!=? ORDER BY at DESC, message_id", (owner, thread, mid))] + + def inbox(self, owner, since): + return [dict(r) for r in self.store._all( + """SELECT """ + _BRIEF + """, folder, substr(body,1,200) AS excerpt, + (replied_at>at OR EXISTS(SELECT 1 FROM mails s WHERE s.owner=m.owner AND s.thread_id=m.thread_id + AND s.folder='SENT' AND s.at>m.at)) AS replied + FROM mails m WHERE owner=? AND inbox_seen=1 AND (at>=? OR unread=1) + ORDER BY at DESC, message_id""", (owner, since))] + + def high_water(self): + return int(self.store.meta_get(_SEQ_KEY, "0")) + + def archive(self, owner, after, limit): + return [_row(r) for r in self.store._all( + """SELECT m.*, (SELECT max(t.at) FROM mails t WHERE t.owner=m.owner AND t.thread_id=m.thread_id + AND t.kb_seq>0 AND (t.important=1 OR t.mine=1)) AS updated_at + FROM mails m WHERE owner=? AND kb_seq>? ORDER BY kb_seq LIMIT ?""", (owner, after, limit))] diff --git a/extensions/openmate-feishu/openmate_feishu/sync_worker.py b/extensions/openmate-feishu/openmate_feishu/sync_worker.py new file mode 100644 index 0000000..41f1194 --- /dev/null +++ b/extensions/openmate-feishu/openmate_feishu/sync_worker.py @@ -0,0 +1,114 @@ +"""Background timing and identity checks for the local Feishu caches.""" + +import logging +import threading +import time + +from .larkcli import CalendarError, LarkCLI + +ACTIVE = 300 +IDLE = 900 +OWNER_KEY = "lark_cli_open_id" +log = logging.getLogger("openmate.feishu.sync") + + +class Stopped(Exception): + pass + + +class SyncWorker: + def __init__(self, app, cli=None, clock=time.time, on_change=None): + self.app = app + self.cli = cli or LarkCLI(app.config, store=app.store) + self.clock = clock + self.on_change = on_change or (lambda: None) + self.looked = float("-inf") + self.owner = app.store.meta_get(OWNER_KEY) + self._identity_at = float("-inf") + self._round = threading.Lock() + + @property + def current_owner(self): + # A different service may discover the account change before this one. + owner = self.owner + return owner if owner and self.app.store.meta_get(OWNER_KEY) == owner else "" + + def start(self): + threading.Thread(target=self._loop, name="openmate-" + self.setting, daemon=True).start() + + def look(self): + if self.enabled: + self.looked = self.clock() + + @property + def enabled(self): + return self.app.config.get(self.setting, True) + + def running(self): + return self.enabled and not self.app.closing.is_set() + + def _loop(self): + last = float("-inf") + while not self.app.closing.is_set(): + now = self.clock() + interval = ACTIVE if now - self.looked < IDLE else IDLE + if self.enabled and now - last >= interval: + last = now + self.sync() + elif self.enabled and now - self._identity_at >= IDLE: + self._background(self.refresh_owner) + self.app.closing.wait(15) + + def sync(self): + self._background(self._sync) + + def _background(self, work): + if not self.running() or not self._round.acquire(blocking=False): + return + try: + work() + except Stopped: + pass + except CalendarError as error: + if self.running(): + self.on_error(error) + except Exception as error: + if self.running(): + log.warning("%s synchronization failed (%s)", self.setting, type(error).__name__) + finally: + self._round.release() + + def read(self, args): + if not self.running(): + raise Stopped() + return self.cli.read(args) + + def refresh_owner(self): + if not self.running(): + raise Stopped() + self._identity_at = self.clock() + try: + owner = self.cli.user_open_id(refresh=True) + except CalendarError as error: + if error.kind in ("auth", "missing"): + self.set_owner("") + raise + self.set_owner(owner) + if not owner: + raise CalendarError("还没授权:在这台电脑上运行 %s,按提示在飞书里确认" % + self.cli.login_hint(), "auth", refused=True) + return owner + + def set_owner(self, owner): + if owner != self.owner: + self.owner = owner + self.owner_changed() + + def sync_owner(self): + return self.current_owner if self._identity_at != float("-inf") and self.current_owner else self.refresh_owner() + + def owner_changed(self): + self.on_change() + + def on_error(self, error): + log.info("%s synchronization paused (%s)", self.setting, error.kind) diff --git a/extensions/openmate-feishu/openmate_feishu/today.py b/extensions/openmate-feishu/openmate_feishu/today.py index c82ccc1..5e08a3e 100644 --- a/extensions/openmate-feishu/openmate_feishu/today.py +++ b/extensions/openmate-feishu/openmate_feishu/today.py @@ -27,6 +27,8 @@ from . import layout as layout_mod from .agenda import PAGE as CALENDAR_PAGE from .agenda import Agenda, CalendarError, Event +from .approvals import ACTION as APPROVAL_OPEN +from .mail import BACK as MAIL_BACK, OPEN as MAIL_OPEN from .meetings import ACTION as MEETING_OPEN log = logging.getLogger("openmate.today") @@ -302,7 +304,7 @@ def todo_due(t: dict, tz) -> Tuple[Optional[_dt.datetime], str]: class TodayPage(Page): def __init__(self, app, agenda: Agenda, persona: PersonaToday, chats: Optional[ChatsToday] = None, card: bool = False, mesh=None, agents: Optional[agents_mod.AgentsRead] = None, - wechat: Optional[PeerToday] = None, meetings=None): + wechat: Optional[PeerToday] = None, meetings=None, approvals=None, mail=None): self.app = app self.agenda = agenda self.persona = persona @@ -312,6 +314,8 @@ def __init__(self, app, agenda: Agenda, persona: PersonaToday, chats: Optional[C self.agents = agents # the Agent progress read: the Agent block sorts by it (else Persona's working / waiting) self.wechat = wechat # WeChat's chats (one read shared by the page and the card) self.meetings = meetings + self.approvals = approvals + self.mail = mail def warm(self) -> None: self.agenda.warm() @@ -341,8 +345,10 @@ def _calendar(self, now) -> Tuple[List[Event], List[Event], int, str]: def render(self, params: dict) -> dict: version = int(params.get("ui_version") or 1) - if self.meetings is not None and not self.card: - self.meetings.look() + if not self.card: + for service in (self.meetings, self.approvals, self.mail): + if service is not None: + service.look() tz = self.app.tz now = _dt.datetime.fromtimestamp(self.agenda.clock(), tz) state = state_of(params) @@ -350,6 +356,8 @@ def render(self, params: dict) -> dict: return layout_mod.edit_view(self.layout(), version, self.title(now), state_text({"edit": 1}), self.absent()) if not self.card and state.get("wx") and self.wechat is not None: return self._wx_chat(str(state["wx"]), version, now, str(state.get("acct") or "")) + if not self.card and state.get("mail") and self.mail is not None: + return self._mail_message(str(state["mail"]), version, now, str(state.get("acct") or "")) t0 = time.monotonic() deadline = t0 + RENDER_BUDGET @@ -411,6 +419,20 @@ def action(self, params: dict) -> dict: aid = str(a.get("id") if isinstance(a, dict) else a or "") if self.meetings is not None and aid.startswith(MEETING_OPEN): return self.meetings.open(aid) + if self.approvals is not None and aid.startswith(APPROVAL_OPEN): + return self.approvals.open(aid) + if self.mail is not None and not self.card and aid.startswith(MAIL_OPEN): + mid, _, owner = aid[len(MAIL_OPEN):].partition(":") + if not owner or owner != self.mail.current_owner or not self.mail.enabled: + return {"toast": "这封邮件现在看不到"} + state = state_text({"mail": mid, "acct": owner}) + if int(params.get("ui_version") or 1) >= 3: + return {"push": {"ui": PAGE, "state": state, "title": "邮件"}} + return {"view": self.render(dict(params, state=state))} + if not self.card and aid == MAIL_BACK: + if int(params.get("ui_version") or 1) >= 3: + return {"pop": True} + return {"view": self.render(dict(params, state=""))} if aid.startswith("open:"): try: events = self.agenda.events(PAGE_WAIT_OPEN) @@ -503,6 +525,10 @@ def absent(self) -> set: absent = set() if self.meetings is None or not self.meetings.enabled: absent.add("meetings") + if self.approvals is None or not self.approvals.enabled: + absent.add("approvals") + if self.mail is None or not self.mail.enabled: + absent.add("mail") if self.wechat is None or self.wechat.read(1.0).get("state") in ("absent", "denied"): absent.add("wechat") return absent @@ -589,6 +615,12 @@ def _wx_chat(self, chat_id: str, version: int, now, account: str = "") -> dict: def _note(text: str) -> dict: return {"type": "text", "style": "caption", "text": text} + def _mail_message(self, mid, version, now, owner): + owner = owner or self.mail.current_owner + title, items = self.mail.detail_items(mid, owner, version, now) + return {"title": title, "state": state_text({"mail": mid, "acct": owner}), + "sections": [{"items": [row("返回", action=MAIL_BACK, key="mail-back"), *items]}]} + def _chat_title(self, chat_id: str) -> str: store = getattr(self.app, "store", None) try: @@ -605,6 +637,7 @@ class Day: def __init__(self, page: TodayPage, version, now, p, chat_needs, counts, groups, today, pending, later, cal_missing, wx: Optional[dict] = None, all_needs: bool = False, chats_failed: bool = False, deadline: Optional[float] = None): self.page, self.version, self.now, self.p = page, version, now, p + self.approvals = page._safe(page.approvals.view, ({}, {})) if page.approvals else None self.all_needs = all_needs # WeChat: None when it is not installed here (or the hub refused the call); else its read (state …) self.wx = wx if wx is not None and wx.get("state") not in ("absent", "denied") else None @@ -758,8 +791,12 @@ def card(self) -> dict: def full(self, state: Optional[dict] = None) -> dict: lay = self.page.layout() build = {"status": self.status_block, "needs": self.needs_card, "calendar": self.calendar_card, + "approvals": lambda: self.page.approvals.section(self.approvals, self.version, self.now) + if self.approvals else None, "meetings": lambda: self.page.meetings.section(self.version, today=True) if self.page.meetings else None, "feishu": self.feishu_card, "wechat": self.wechat_card, "agents": self.agents_block, + "mail": lambda: self.page._safe(lambda: self.page.mail.section(self.version, self.now), None) + if self.page.mail else None, "mesh": self.mesh_card, "auto": self.auto_card, "todos": self.todos_card, "shortcuts": self.shortcuts_block, "bookmarks": self.bookmarks_block} top: Dict[str, Any] = {"items": [row("调整布局", "上移、下移、隐藏每一块,或改成整行、半行", "", "layout:edit", key="layout", @@ -803,7 +840,13 @@ def status_blocks(self, mesh: bool = False) -> List[tuple]: parts += ["收件箱 %d" % len(self.inbox_needs), "Agent %d" % len(p["waiting"])] if self.asks: parts.append("待办 %d" % len(self.asks)) - if self.needs_total: + approvals, tasks = self.page.approvals.counts(self.approvals) if self.approvals else (0, 0) + if approvals: + parts.append("审批 %d" % approvals) + if tasks: + parts.append("任务 %d" % tasks) + has_needs = self.needs_total or approvals or tasks + if has_needs: needs_badge = {"text": "待处理", "tone": "danger"} elif self.wx_unknown: needs_badge = {"text": "微信读不到", "tone": "caution"} @@ -812,7 +855,7 @@ def status_blocks(self, mesh: bool = False) -> List[tuple]: else: needs_badge = {"text": "清空", "tone": "positive"} out = [ - ("需要我", str(self.needs_total), " · ".join(parts), "bell", "red" if self.needs_total else "gray", needs_badge, "b:needs"), + ("需要我", str(self.needs_total), " · ".join(parts), "bell", "red" if has_needs else "gray", needs_badge, "b:needs"), ("日程", "—" if self.cal_missing else str(len(self.today)), self.cal_line, "calendar", "blue", {"text": "读不到", "tone": "caution"} if self.cal_missing else {"text": "待回复 %d" % len(self.pending), "tone": "caution"} if self.pending else ok, "b:calendar"), diff --git a/extensions/openmate-feishu/persona-extension.json b/extensions/openmate-feishu/persona-extension.json index 506fc2d..deb50af 100644 --- a/extensions/openmate-feishu/persona-extension.json +++ b/extensions/openmate-feishu/persona-extension.json @@ -2,8 +2,8 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.74", - "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,手机确认后以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", + "version": "0.11.75", + "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", "icon": "assets/icon.png", @@ -17,15 +17,16 @@ "id": "matefeishu", "name": "飞书(OpenMate)", "capabilities": ["status", "tools", "actions", "events", "inbox", "archive", "history", "login", "threads", "outbound_send", "items"], - "agent_tools": ["matefeishu_status", "matefeishu_chats", "matefeishu_messages", "matefeishu_search", "matefeishu_docs", "matefeishu_agent_reply", "matefeishu_starkmesh", "matefeishu_media", "matefeishu_members", "matefeishu_meetings"], + "agent_tools": ["matefeishu_status", "matefeishu_chats", "matefeishu_messages", "matefeishu_search", "matefeishu_docs", "matefeishu_agent_reply", "matefeishu_starkmesh", "matefeishu_media", "matefeishu_members", "matefeishu_meetings", "matefeishu_mail", "matefeishu_mail_reply"], "confirm_always": ["matefeishu_*"], "sends_as_user": true, "poll_seconds": 60, - "kinds": ["dm", "mention", "group"], + "kinds": ["dm", "mention", "group", "mail"], "kind_descriptions": { "dm": "类型:飞书私聊里别人发给我、我还没回的消息", "mention": "类型:飞书群里有人 @我、我还没回的消息", - "group": "类型:飞书群里的新消息,没有 @我" + "group": "类型:飞书群里的新消息,没有 @我", + "mail": "类型:飞书邮箱里发给我、标为重要、还没读的邮件" } } ], @@ -300,6 +301,28 @@ "maximum": 30, "default": 14 }, + "approvals": { + "type": "boolean", + "title": "审批和飞书任务", + "description": "只读显示等你审批的单子和分给你的飞书任务,点开到飞书里处理。OpenMate 不替你同意、拒绝或完成。", + "default": true + }, + "mail": { + "type": "boolean", + "title": "飞书邮箱", + "description": "通过 lark-cli 只读同步飞书邮箱里最近的邮件,在今天页显示,重要邮件进收件箱和知识库。回复邮件要你在确认卡片上批准。", + "default": true + }, + "mail_inbox": { + "type": "boolean", + "title": "重要邮件进收件箱", + "default": true + }, + "mail_kb": { + "type": "boolean", + "title": "邮件进知识库", + "default": true + }, "starkmesh_url": { "type": "string", "format": "uri", diff --git a/extensions/openmate-feishu/tests/test_approvals.py b/extensions/openmate-feishu/tests/test_approvals.py new file mode 100644 index 0000000..36a17d9 --- /dev/null +++ b/extensions/openmate-feishu/tests/test_approvals.py @@ -0,0 +1,196 @@ +"""Local-only coverage for the two pending-work sources on Today.""" + +import datetime as dt +import json +import subprocess +import threading +import unittest +from unittest.mock import patch + +from test_agenda import NOW, TZ, items, section +from test_today import make + +from openmate_feishu.approvals import Approvals +from openmate_feishu.larkcli import LarkCLI +from openmate_feishu.sync_worker import ACTIVE, IDLE + + +def response(args, data, *, wrapped=True): + return subprocess.CompletedProcess(args, 0, json.dumps({"ok": True, "data": data} if wrapped else data), "") + + +def failed(args, data): + return subprocess.CompletedProcess(args, 1, "", json.dumps({"ok": False, **data})) + + +class ApprovalsTest(unittest.TestCase): + def setUp(self): + self.now = NOW + self.page, _, _ = make(clock=lambda: self.now) + self.app = self.page.app + self.addCleanup(self.app.store.close) + self.app.closing = threading.Event() + self.commands = [] + self.error = None + self.owner = "ou_example" + self.approvals = [dict(task_id=str(i), title="示例审批 %d" % i, initiator_name="发起人甲", + definition_name="示例流程", support_api_operate=False, + link="https://approval.example.org/item/%d" % i) for i in range(1, 8)] + self.tasks = [ + self.task("无期限"), self.task("下周", 4), self.task("今天", 0), self.task("逾期", -2), + self.task("只关注", role="follower"), self.task("别人的", owner="ou_other"), + dict(self.task("已完成", -3), completed=True), + ] + self.worker = self.create_worker() + + def create_worker(self): + self.page.approvals = Approvals(self.app, LarkCLI(self.app.config, run=self.run_cli, store=self.app.store), + clock=lambda: self.now) + return self.page.approvals + + def task(self, name, days=None, role="assignee", owner="ou_example"): + result = dict(guid=name, summary=name, members=[dict(id=owner, role=role, type="user")], + url="https://tasks.example.org/todo", created_at="2026-11-10T10:00:00+08:00", completed=False) + if days is not None: + result["due_at"] = dt.datetime.fromtimestamp(NOW + 86400 * days + 3600, TZ).isoformat() + return result + + def run_cli(self, args, **_): + command = args[3:] + self.commands.append(command) + if command == ["auth", "status"]: + return response(args, {"identities": {"user": {"available": True, "openId": self.owner}}}, wrapped=False) + if command[:3] == ["approval", "tasks", "query"]: + if self.error is not None: + return failed(args, self.error) + self.assertEqual(command, ["approval", "tasks", "query", "--as", "user", "--topic", "1", "--page-size", + "100", "--format", "json"]) + return response(args, dict(count=len(self.approvals), tasks=self.approvals)) + if command[:2] == ["task", "+get-my-tasks"]: + self.assertEqual(command, ["task", "+get-my-tasks", "--as", "user", "--complete=false", + "--page-all", "--format", "json"]) + return response(args, dict(items=self.tasks, has_more=False)) + self.fail("unexpected CLI command") + + def test_readonly_snapshot_sorts_tasks(self): + self.worker.sync() + self.assertEqual(len(self.commands), 3) + self.now += 7200 + self.approvals.reverse() + self.worker.sync() + reloaded = self.create_worker() + view = reloaded.section(reloaded.view(), 8, dt.datetime.fromtimestamp(self.now, TZ)) + top = [r for r in view["items"] if r.get("title", "").startswith("示例审批")] + self.assertEqual(len(top), 5) + self.assertNotIn("value", top[0]) + self.assertEqual(top[0]["subtitle"], "发起人甲 · 示例流程") + self.assertIn("还有 2 条", str(view)) + task_rows = [r for r in view["items"] if r.get("title") in ("逾期", "今天", "下周", "无期限")] + self.assertEqual([r["title"] for r in task_rows], ["逾期", "今天", "下周", "无期限"]) + self.assertEqual(task_rows[0]["badge"], {"text": "逾期 2 天", "tone": "danger"}) + self.assertEqual(task_rows[1]["badge"], {"text": "今天到期", "tone": "caution"}) + self.assertEqual(task_rows[2]["value"], "2026-11-20") + self.assertEqual(self.page.action({"action": top[0]["action"]}), {"open_url": self.approvals[-1]["link"]}) + self.assertEqual(reloaded.counts(reloaded.view()), (7, 4)) + + def test_preexisting_approvals_have_no_age_and_sort_before_new_items(self): + older, recent, latest = self.approvals[:3] + self.approvals = [dict(older, task_id="9")] + self.worker.sync() + self.now += 3600 + self.approvals.append(dict(recent, task_id="2")) + self.worker.sync() + self.now += 7200 + self.approvals.append(dict(latest, task_id="1")) + self.worker.sync() + reloaded = self.create_worker() + view = reloaded.section(reloaded.view(), 8, dt.datetime.fromtimestamp(self.now, TZ)) + rows = [r for r in view["items"] if r.get("title", "").startswith("示例审批")] + self.assertEqual([(r["title"], r.get("value")) for r in rows], + [(older["title"], None), (recent["title"], "2 小时前"), (latest["title"], "0 小时前")]) + + def test_seen_is_pruned_only_after_a_successful_approval_read(self): + older, recent = self.approvals[:2] + self.approvals = [older] + self.worker.sync() + self.now += 3600 + self.approvals.append(recent) + self.worker.sync() + key = "approvals:" + self.owner + kept = json.loads(self.app.store.meta_get(key))["seen"] + self.assertEqual(kept[recent["task_id"]], self.now) + self.approvals = [] + self.error = {"error": "request timed out"} + self.now += 3600 + self.worker.sync() + self.assertEqual(json.loads(self.app.store.meta_get(key))["seen"], kept) + self.error = None + self.worker.sync() + self.assertEqual(json.loads(self.app.store.meta_get(key))["seen"], {}) + self.approvals = [recent] + self.now += 3600 + self.worker.sync() + self.assertEqual(json.loads(self.app.store.meta_get(key))["seen"], {recent["task_id"]: self.now}) + + def test_today_cached_status_counts_disabled_empty_and_auth(self): + params = {"ui_version": 8} + old = self.page.render(params) + self.assertNotIn("审批和任务", str(old)) + self.worker.sync() + before = len(self.commands) + view = self.page.render(params) + items(view) + self.assertTrue(section(view, "审批和任务")) + self.assertIn("审批 7 · 任务 4", str(view)) + status = lambda v: next(t for i in items(v) for t in i.get("tiles", []) if t["key"] == "b:needs")["value"] + self.assertEqual(status(view), status(old)) + self.assertEqual(len(self.commands), before) + self.error = {"error": {"type": "authorization", "subtype": "missing_scope"}} + self.worker.sync() + self.assertIn("授权", str(section(self.page.render(params), "审批和任务"))) + self.assertEqual(self.worker.counts(self.worker.view()), (0, 4)) + self.app.config["approvals"] = False + self.assertNotIn("审批和任务", str(self.page.render(params))) + self.assertNotIn("任务 4", str(self.page.render(params))) + self.app.config["approvals"] = True + self.error, self.approvals, self.tasks = None, [], [] + self.worker.sync() + self.assertIn("没有等你审批的单子和任务", str(section(self.page.render(params), "审批和任务"))) + + def test_cadence_with_recent_page_visits(self): + offsets = [] + start = self.now + + class Stop: + def is_set(stop): + return self.now >= start + 2 * IDLE + 3 * ACTIVE + + def wait(stop, seconds): + self.now += seconds + if self.now == start + IDLE: + self.worker.look() + + self.worker._identity_at = start + with patch.object(self.app, "closing", Stop()), patch.object( + self.worker, "sync", side_effect=lambda: offsets.append(self.now - start) + ), patch.object(self.worker, "refresh_owner", side_effect=lambda: setattr(self.worker, "_identity_at", self.now)): + self.worker._loop() + self.assertEqual(offsets, [0, 900, 1200, 1500, 2400]) + + def test_account_switch_cannot_render_the_old_snapshot(self): + self.worker.sync() + self.app.store.meta_set("lark_cli_open_id", "ou_other") + self.assertEqual(self.worker.view(), ({}, {})) + self.owner = "ou_other" + self.tasks, self.approvals = [], [] + self.worker.sync() + self.assertEqual(self.worker.counts(self.worker.view()), (0, 0)) + + def test_missing_cli_shows_one_reason_without_reading(self): + self.app.config["lark_cli"] = "/nonexistent/example-lark-cli" + self.worker = self.create_worker() + self.worker.sync() + rows = section(self.page.render({"ui_version": 8}), "审批和任务") + self.assertEqual(len(rows), 1) + self.assertIn("没找到 lark-cli", str(rows[0])) + self.assertFalse(self.commands) diff --git a/extensions/openmate-feishu/tests/test_feishu.py b/extensions/openmate-feishu/tests/test_feishu.py index 314fde4..afd3b49 100644 --- a/extensions/openmate-feishu/tests/test_feishu.py +++ b/extensions/openmate-feishu/tests/test_feishu.py @@ -53,7 +53,7 @@ def test_connector(self): self.assertEqual(CONN["id"], openmate_feishu.CONNECTOR_ID) self.assertEqual(CONN["capabilities"], ["status", "tools", "actions", "events", "inbox", "archive", "history", "login", "threads", "outbound_send", "items"]) - self.assertEqual(CONN["kinds"], ["dm", "mention", "group"]) + self.assertEqual(CONN["kinds"], ["dm", "mention", "group", "mail"]) self.assertEqual(sorted(CONN["kind_descriptions"]), sorted(CONN["kinds"])) descs = list(CONN["kind_descriptions"].values()) self.assertEqual(len(set(descs)), len(descs)) @@ -99,7 +99,8 @@ def test_configuration(self): "agent_reply_suffix", "history_chats", "triage_rules", "inbox_triage_chats", "inbox_private_dms", "lark_cli", "lark_cli_profile", "meetings", "meetings_kb", "meeting_transcript", - "meetings_days", "starkmesh_url", "starkmesh_alerts", "starkmesh_alert_left", + "meetings_days", "approvals", "mail", "mail_inbox", "mail_kb", + "starkmesh_url", "starkmesh_alerts", "starkmesh_alert_left", "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"]) diff --git a/extensions/openmate-feishu/tests/test_layout.py b/extensions/openmate-feishu/tests/test_layout.py index 6e0554c..679a973 100644 --- a/extensions/openmate-feishu/tests/test_layout.py +++ b/extensions/openmate-feishu/tests/test_layout.py @@ -41,7 +41,8 @@ def test_edit_mode_moves_hides_and_widens(self): edit = out["view"] self.assertEqual(json.loads(edit["state"]), {"edit": 1}) rows = [it for it in edit["sections"][0]["items"] if it["type"] == "row"] - self.assertEqual([r["title"] for r in rows], [b[1] for b in layout.BLOCKS if b[0] not in ("wechat", "meetings")]) + self.assertEqual([r["title"] for r in rows], + [b[1] for b in layout.BLOCKS if b[0] not in ("wechat", "meetings", "approvals", "mail")]) first = [a["title"] for a in rows[0]["actions"]] self.assertEqual(first, ["下移", "隐藏", "改成半行"], "the first can't go up; status is a whole row") self.assertIn("hub 升级后生效", rows[2]["subtitle"], "a half row before UI version 8 says when it counts") @@ -66,12 +67,12 @@ def test_edit_mode_moves_hides_and_widens(self): def test_a_stored_layout_meets_a_newer_version(self): page, _, _ = make() - older = ["todos"] + [b[0] for b in layout.BLOCKS if b[0] not in ("todos", "agents", "meetings")] + older = ["todos"] + [b[0] for b in layout.BLOCKS if b[0] not in ("todos", "agents", "meetings", "approvals", "mail")] page.app.store.meta_set(layout.KEY, json.dumps({"order": older[:3] + ["gone", "needs"] + older[3:], "hidden": ["gone", "status"], "wide": {"todos": True, "needs": "yes"}})) lay = page.layout() - self.assertEqual(lay.order, ["todos", "status", "needs", "calendar", "meetings", "feishu", "wechat", "agents", "mesh", - "auto", "shortcuts", "bookmarks"], + self.assertEqual(lay.order, ["todos", "status", "needs", "approvals", "calendar", "meetings", "feishu", "mail", + "wechat", "agents", "mesh", "auto", "shortcuts", "bookmarks"], "a block the stored order lacks goes after the one before it by default; unknown and repeated ones go") self.assertEqual(lay.hidden, ["status"]) self.assertEqual(lay.wide, {"todos": True}) diff --git a/extensions/openmate-feishu/tests/test_mail.py b/extensions/openmate-feishu/tests/test_mail.py new file mode 100644 index 0000000..1c4e1ea --- /dev/null +++ b/extensions/openmate-feishu/tests/test_mail.py @@ -0,0 +1,475 @@ +"""Exercise the Feishu mail connector with synthetic responses and no real subprocess calls.""" + +import datetime as dt +import json +import os +import subprocess +import tempfile +import unittest +from email.utils import format_datetime +from unittest.mock import Mock + +from test_agenda import NOW, TZ, items, section +from test_approvals import failed, response +from test_today import make + +from openmate_core.app import ConnectorApp +from openmate_core.store import Store +from openmate_core.wire import RPCError +from openmate_feishu import platform +from openmate_feishu.layout import Layout +from openmate_feishu.larkcli import LarkCLI +from openmate_feishu.mail import BODY_LIMIT, DAY, PAGE_CLIP, STORE_CLIP, Mail +from openmate_feishu.meetings import Meetings + +ADDRESS = "self@example.org" +FROM = "source@example.org" +READ = "matefeishu_mail" +REPLY = "matefeishu_mail_reply" + + +class FakeMailCLI: + def __init__(self, test): + self.test = test + self.owner = "ou_example" + self.address = ADDRESS + self.calls = [] + self.inbox, self.unread, self.sent, self.details = {}, set(), {}, {} + self.batch_error, self.list_error, self.profile_error, self.reply_answer = None, None, None, None + self.identity_after_details = "" + + def add(self, mid, thread=None, *, at=NOW - 3600, sent=False, unread=True, labels="IMPORTANT", + sender=FROM, to=(ADDRESS,), cc=(), body="这是合成的邮件正文", reply_to=""): + def contact(addr): + return {"mail_address": addr, "name": ""} + + thread = thread or "T" + mid + title = "合成主题 " + mid + folder = "SENT" if sent else "INBOX" + fields = dict(message_id=mid, thread_id=thread, subject=title) + date = dt.datetime.fromtimestamp(at, TZ).strftime("%Y-%m-%d %H:%M") + addresses = dict(head_from=contact(sender), to=[contact(addr) for addr in to], cc=[contact(addr) for addr in cc]) + listing = dict(fields, date=date, folder=folder, labels=labels, **{"from": "示例寄件人 <%s>" % sender}) + (self.sent if sent else self.inbox)[mid] = listing + if unread and not sent: + self.unread.add(mid) + self.details[mid] = dict(fields, **addresses, date_formatted=date, internal_date=str(int(at * 1000)), + label_ids=[labels], body_plain_text=body, reply_to=reply_to, + attachments=[dict(filename="示例附件.txt", other="不落库")]) + + def __call__(self, args, **_): + a = args[3:] + self.calls.append(a) + if a == ["auth", "status"]: + return response(args, {"identities": {"user": {"available": True, "openId": self.owner}}}, wrapped=False) + assert a[a.index("--as") + 1] == "user" and a[-2:] == ["--format", "json"], a + if a[:3] == ["mail", "user_mailboxes", "profile"]: + return (failed(args, self.profile_error) if self.profile_error else + response(args, {"primary_email_address": self.address})) + if a[:2] == ["mail", "+triage"]: + folder = a[a.index("--folder-id") + 1] + assert a[a.index("--max") + 1] == "20" and "--labels" in a + assert "--page-token" not in a + if self.list_error and "--is-unread" in a: + return failed(args, self.list_error) + entries = self.sent if folder == "SENT" else self.inbox + data = [item for mid, item in entries.items() if "--is-unread" not in a or mid in self.unread] + return response(args, dict(messages=data, count=len(data), has_more=True, page_token="unused"), + wrapped=folder == "SENT") + if a[:2] == ["mail", "+messages"]: + assert "--html=false" in a + keys = a[a.index("--message-ids") + 1].split(",") + if self.identity_after_details: + self.owner = self.identity_after_details + rows = [self.details[mid] for mid in keys if mid in self.details] + data = {"messages": rows, "total": len(rows), "unavailable_message_ids": [i for i in keys if i not in self.details]} + return failed(args, {"data": data, **self.batch_error}) if self.batch_error is not None else response(args, data) + if a[:2] in (["mail", "+reply"], ["mail", "+reply-all"]): + if isinstance(self.reply_answer, BaseException): + raise self.reply_answer + if isinstance(self.reply_answer, dict): + return failed(args, self.reply_answer) + if self.reply_answer is not None: + return subprocess.CompletedProcess(args, 0, self.reply_answer, "") + if "--confirm-send" in a: + return response(args, {"message_id": "SentReply==", "thread_id": "ThreadReply=="}) + return response(args, {"draft_id": "DraftReply=="}) + self.test.fail("unexpected CLI command") + + def commands(self, command): + return [a for a in self.calls if " ".join(a[:2]) == command] + + +class MailTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.app = ConnectorApp(platform(), env={}) + self.app.config = dict(lark_cli="/bin/sh", lark_cli_profile="example") + self.app.tz = TZ + self.store_path = os.path.join(tmp.name, "openmate.db") + self.app.store = Store(self.store_path) + self.addCleanup(lambda: self.app.store.close()) + self.app.initialized = True + self.app.ready.set() + self.now = NOW + self.fake = FakeMailCLI(self) + self.cli = LarkCLI(self.app.config, run=self.fake, store=self.app.store) + self.mail = self.app.mail = Mail(self.app, self.cli, clock=lambda: self.now) + self.app.record_sent = Mock() + + def restart_mail(self): + self.app.store.close() + self.app.store = Store(self.store_path) + self.app._account_epoch = 0 + self.cli = LarkCLI(self.app.config, run=self.fake, store=self.app.store) + self.mail = self.app.mail = Mail(self.app, self.cli, clock=lambda: self.now) + + def rpc(self, method, **params): + return self.app.handle("connector." + method, params) + + def collect(self): + return {t["thread"]: t for t in self.rpc("inbox.collect")["things"]} + + def describe(self, **args): + return self.rpc("actions.describe", name=REPLY, args=args) + + def do(self, request_id, **args): + return self.rpc("actions.do", name=REPLY, request_id=request_id, args=args) + + def test_triage_shapes_new_body_batch_unread_and_14_day_floor(self): + self.fake.add("Recent==") + self.fake.add("Read==", unread=False) + self.fake.inbox["Read=="]["date"] = format_datetime(dt.datetime.fromtimestamp(NOW - 3600, TZ)) + self.fake.add("Old==", at=NOW - 15 * DAY) + self.fake.add("Outgoing==", sender=ADDRESS, sent=True, labels="OTHER") + self.mail.sync() + body_call, = self.fake.commands("mail +messages") + self.assertEqual(set(body_call[body_call.index("--message-ids") + 1].split(",")), + {"Recent==", "Read==", "Outgoing=="}) + rows = self.app.store._all("SELECT message_id, unread, mine, body FROM mails ORDER BY message_id") + self.assertEqual([(r["message_id"], r["unread"], r["mine"]) for r in rows], + [("Outgoing==", 0, 1), ("Read==", 0, 0), ("Recent==", 1, 0)]) + self.assertTrue(all(r["body"] == "这是合成的邮件正文" for r in rows)) + self.fake.unread.clear() + self.fake.calls.clear() + self.now += 300 + self.mail.sync() + self.assertEqual(self.fake.calls, self.fake.commands("mail +triage")) + self.assertEqual(len(self.fake.calls), 3) + self.assertFalse(self.mail.get("Recent==", self.fake.owner)["unread"]) + self.assertIsNone(self.mail.get("Old==", self.fake.owner)) + + def test_profile_falls_back_to_latest_sent_sender(self): + self.fake.profile_error = {"error": {"type": "permission_denied"}} + self.fake.add("Incoming==") + self.fake.add("SentOlder==", at=NOW - 7200, sent=True, sender="alias@example.org", labels="OTHER") + self.fake.add("SentNewer==", at=NOW - 300, sent=True, sender=ADDRESS, labels="OTHER") + self.mail.sync() + self.assertEqual(self.mail.db.settings(self.fake.owner)["address"], ADDRESS) + self.assertIn("mail:TIncoming==", self.collect()) + + def test_batch_successes_survive_failures_and_backoff(self): + self.fake.add("Available==") + self.fake.add("Denied==") + self.fake.add("Unavailable==") + del self.fake.details["Unavailable=="] + self.fake.details["Denied=="] = {"message_id": "Denied==", "error": {"type": "permission_denied"}} + self.fake.batch_error = {"error": {"type": "api", "message": "batch incomplete"}} + self.mail.sync() + self.assertIsNotNone(self.mail.get("Available==", self.fake.owner)) + self.assertIsNone(self.mail.get("Denied==", self.fake.owner)) + self.assertIsNone(self.mail.get("Unavailable==", self.fake.owner)) + self.assertEqual(set(self.mail._retry), {"Denied==", "Unavailable=="}) + self.fake.inbox.pop("Available==") + self.now += 299 + self.fake.calls.clear() + self.mail.sync() + self.assertEqual(len(self.fake.calls), 3) + self.now += 1 + self.mail.sync() + self.assertIn("权限", self.mail._notice) + self.assertEqual(self.mail._retry["Denied=="], (2, self.now + 600)) + self.assertEqual(len(self.fake.commands("mail +messages")), 1) + + def test_failed_unread_snapshot_does_not_close_anything(self): + self.fake.add("Incoming==") + self.mail.sync() + self.fake.unread.clear() + self.fake.list_error = {"error": "request timed out"} + self.mail.sync() + self.assertNotIn("done", self.collect()["mail:TIncoming=="]) + + def test_switch_hides_old_account_and_rejects_inflight_details(self): + self.fake.add("Incoming==") + self.fake.identity_after_details = "ou_other" + self.mail.sync() + self.assertEqual(self.app.store._all("SELECT * FROM mails"), []) + self.fake.identity_after_details = "" + self.fake.inbox.clear() + self.fake.unread.clear() + self.fake.details.clear() + self.fake.add("New==") + self.mail.sync() + self.assertEqual(set(self.collect()), {"mail:TNew=="}) + self.app.store.meta_set("lark_cli_open_id", "ou_example") + self.assertEqual(self.collect(), {}) + self.assertEqual(self.rpc("archive.changes", cursor="0")["batches"], []) + self.assertIn("没有找到", self.rpc("tools.call", name=READ, args={"action": "read", "message_id": "New=="})["text"]) + + def test_inbox_filters_deduplicates_and_closes_read_and_replied(self): + self.fake.add("Older==", "Thread==", at=NOW - 7200) + self.fake.add("Incoming==", "Thread==", to=(ADDRESS.upper(),)) + self.fake.add("CcOnly==", to=("copy@example.org",), cc=(ADDRESS,)) + self.fake.add("UnreadOther==", labels="OTHER") + self.fake.add("ReadImportant==", unread=False) + for i, sender in enumerate(("NO-REPLY-list", "list-notification", "notice2", "mailer-daemon", "postmaster")): + self.fake.add("Notice%d==" % i, sender=sender + "@example.org") + self.fake.add("EndByRead==") + self.app.config["triage_rules"] = "示例分拣规则" + self.mail.sync() + things = self.collect() + self.assertEqual(set(things), {"mail:Thread==", "mail:TEndByRead=="}) + thing = things["mail:Thread=="] + self.assertEqual((thing["kind"], thing["last"], thing["title"]), ("mail", "Incoming==", "合成主题 Incoming==")) + self.assertEqual((thing["extra"], thing["rules"]), ({"rule_tier": "action"}, "示例分拣规则")) + self.assertIn("示例寄件人 · 这是合成的邮件正文", thing["preview"]) + self.assertNotIn("tier", thing) + self.fake.unread.remove("EndByRead==") + self.fake.add("SentLater==", "Thread==", at=NOW - 600, sender=ADDRESS, sent=True, labels="OTHER") + del self.fake.details["SentLater=="] + self.mail.sync() + updated = self.collect() + self.assertEqual(updated["mail:Thread=="]["done"], "replied") + self.assertEqual(updated["mail:TEndByRead=="]["done"], "read") + self.app.config["mail_inbox"] = False + self.assertEqual(self.collect(), {}) + + def test_archive_legacy_and_independent_meeting_and_mail_cursors(self): + self.fake.add("Incoming==", "Thread==") + self.fake.add("Outgoing==", "Thread==", sent=True, sender=ADDRESS, labels="OTHER", at=NOW - 600) + self.fake.add("Other==", labels="OTHER") + self.mail.sync() + meetings = self.app.meetings = Meetings(self.app, self.cli, clock=lambda: self.now) + meetings._set_identity(self.now) + owner = self.fake.owner + meetings.db.discover(owner, {"example": ("合成会议", "")}, self.now) + meetings.db.save(owner, "example", {"start": self.now - 600, "end": self.now - 300, + "state": "ready", "summary": "虚构会议摘要"}) + first = self.rpc("archive.changes", cursor="0", limit=1) + self.assertEqual(first["next"], "v1:0:mail=0:meetings=1") + self.assertEqual(first["batches"][0]["chat"]["kind"], "meeting") + self.assertTrue(first["more"]) + follow = self.rpc("archive.changes", cursor=first["next"], limit=1) + self.assertEqual(follow["next"], "v1:0:mail=2:meetings=1") + batch, = follow["batches"] + self.assertEqual((batch["chat"]["id"], batch["chat"]["kind"]), ("mail-Thread==", "mail")) + self.assertEqual([m["id"] for m in batch["messages"]], ["mail-Incoming==", "mail-Outgoing=="]) + for m, sender in zip(batch["messages"], (FROM, ADDRESS)): + self.assertEqual(m["sender_handles"], [{"kind": "email", "value": sender}]) + self.assertIn("附件:示例附件.txt", m["text"]) + self.assertNotIn("不落库", m["text"]) + self.assertTrue(batch["messages"][-1]["mine"]) + self.assertEqual(self.rpc("archive.changes", cursor=follow["next"])["batches"], []) + legacy = self.rpc("archive.changes", cursor="v1:0:meetings=1") + self.assertEqual(legacy["batches"], [batch]) + self.fake.add("Late==") + self.mail.sync() + self.app.config["mail_kb"] = False + off = self.rpc("archive.changes", cursor=follow["next"]) + self.assertEqual(off, {"batches": [], "next": "v1:0:mail=3:meetings=1", "more": False}) + + def test_today_mail_and_detail_are_local_with_return_and_truncation(self): + page, _, _ = make(clock=lambda: self.now) + self.addCleanup(page.app.store.close) + page.mail = self.mail + params = {"ui_version": 8} + self.assertNotIn("邮件", str(page.render(params))) + self.fake.add("Long==", body="合" * 30000) + self.fake.add("Other==", labels="OTHER") + self.fake.add("Earlier==", at=NOW - 3 * DAY) + self.mail.sync() + calls = len(self.fake.calls) + view = page.render(params) + items(view) + mail_rows = section(view, "邮件") + self.assertEqual(len(mail_rows), 1) + entry, = mail_rows + self.assertEqual(entry["badge"]["text"], "未读") + target = page.action(dict(params, action=entry["action"]))["push"] + detail = page.render(dict(params, state=target["state"])) + contents = items(detail) + self.assertEqual(detail["title"], "合成主题 Long==") + self.assertEqual(contents[0]["title"], "返回") + self.assertEqual(page.action(dict(params, action=contents[0]["action"])), {"pop": True}) + text, = [v["text"] for v in contents if v["type"] == "text"] + self.assertTrue(text.endswith(PAGE_CLIP)) + self.assertEqual(len(text), 8000) + self.assertIn("示例附件.txt", str(contents)) + saved = self.mail.get("Long==", self.fake.owner)["body"] + self.assertLessEqual(len(saved.encode()), BODY_LIMIT) + self.assertTrue(saved.endswith(STORE_CLIP)) + self.assertEqual(len(self.fake.calls), calls) + self.app.config["mail"] = False + self.assertNotIn("邮件", str(page.render(params))) + self.assertIn("现在看不到", str(page.render(dict(params, state=target["state"])))) + + def test_today_layout_and_empty_mail_block(self): + page, _, _ = make(clock=lambda: self.now) + self.addCleanup(page.app.store.close) + page.mail = self.mail + layout = Layout.load(page.app.store) + self.assertEqual(layout.order[layout.order.index("needs") + 1], "approvals") + self.assertEqual(layout.order[layout.order.index("feishu") + 1], "mail") + self.mail.sync() + view = page.render({"ui_version": 8}) + self.assertIn("这两天没有重要邮件", str(section(view, "邮件"))) + layout.change("hide", "mail") + layout.save(page.app.store) + self.assertFalse(any(s.get("title") == "邮件" for s in page.render({"ui_version": 8})["sections"])) + + def test_manifest_mail_defaults_and_action_confirmation_wording(self): + conn = self.app.manifest["contributes"]["connectors"][0] + self.assertIn("mail", conn["kinds"]) + self.assertEqual(conn["agent_tools"][-2:], [READ, REPLY]) + self.assertEqual(conn["confirm_always"], ["matefeishu_*"]) + settings = self.app.manifest["configuration"]["properties"] + for name in ("approvals", "mail", "mail_inbox", "mail_kb"): + self.assertTrue(settings[name]["default"]) + actions = self.rpc("actions.list")["tools"] + self.assertEqual([a["name"] for a in actions], ["matefeishu_send", "matefeishu_send_dm", REPLY]) + for action in actions[:2]: + self.assertIn("每次都要我在确认卡片上确认", action["description"]) + + def test_read_tools_list_and_read_thread(self): + self.fake.add("First==", "Thread==", at=NOW - 7200, body="合" * 600, unread=False) + self.fake.add("Second==", "Thread==", body="示例关键词") + self.fake.add("FourDays==", at=NOW - 4 * DAY) + self.mail.sync() + before = len(self.fake.calls) + + def tool(**args): + return self.rpc("tools.call", name=READ, args=args)["text"] + + self.assertEqual([m["message_id"] for m in json.loads(tool())["messages"]], ["Second==", "First=="]) + self.assertEqual(len(json.loads(tool(days=100))["messages"]), 3) + self.assertEqual(json.loads(tool(query="示例关键词", unread_only=True))["messages"][0]["thread_id"], "Thread==") + found = json.loads(tool(action="read", message_id="Second==")) + self.assertEqual(found["body"], "示例关键词") + self.assertEqual(len(found["thread"][0]["preview"]), 500) + self.assertEqual(found["thread"][0]["sender"], "示例寄件人") + self.app.config["mail"] = False + self.assertIn("没开", tool()) + self.assertEqual(len(self.fake.calls), before) + + def test_reply_describe_send_draft_and_dedup_with_default_signature_and_hub_ledger(self): + self.fake.add("Original==", "ThreadReply==", to=(ADDRESS, "to@example.org"), cc=("cc@example.org",), + reply_to="reply@example.org") + self.mail.sync() + send = dict(message_id="Original==", body=" <完整正文>\n第二行\n", reply_all=True) + draft = dict(message_id="Original==", body="保存这个文本", send=False) + self.fake.calls.clear() + card = self.describe(**send) + self.assertEqual(card["action"]["visible"], "reply@example.org、to@example.org、cc@example.org") + self.assertIn("To:reply@example.org\nCc:to@example.org、cc@example.org", card["summary"]) + self.assertIn("主题:Re: 合成主题 Original==", card["summary"]) + self.assertIn("直接发出", card["summary"]) + self.assertTrue(card["summary"].endswith(send["body"])) + self.assertIn("Cc:—", self.describe(**draft)["summary"]) + self.assertIn("只存草稿", self.describe(**draft)["summary"]) + self.assertFalse(self.fake.calls) + with self.assertRaisesRegex(RPCError, "request_id"): + self.do("", **send) + result = self.do("send", **send) + self.assertEqual(result, self.do("send", **send)) + self.assertEqual(result["message_ref"], "SentReply==") + reply, = self.fake.commands("mail +reply-all") + self.assertIn("--confirm-send", reply) + self.assertIn("--plain-text", reply) + self.assertNotIn("--no-signature", reply) + self.assertEqual(reply[reply.index("--body") + 1], send["body"]) + first = self.do("draft", **draft) + self.assertIn("DraftReply==", first["text"]) + self.assertEqual(first, self.do("draft", **draft)) + saved, = self.fake.commands("mail +reply") + self.assertNotIn("--confirm-send", saved) + self.assertNotIn("--no-signature", saved) + self.app.record_sent.assert_not_called() + + def test_reply_refuses_new_account_or_args_changed_since_card(self): + self.fake.add("Original==") + self.mail.sync() + args = {"message_id": "Original==", "body": "示例回复"} + self.describe(**args) + with self.assertRaisesRegex(RPCError, "没有发出"): + self.do("changed", **dict(args, body="修改后的示例回复")) + self.fake.owner = "ou_replacement" + with self.assertRaisesRegex(RPCError, "换了飞书邮箱账号"): + self.do("changed-owner", **args) + self.assertEqual(self.fake.commands("mail +reply"), []) + self.app.record_sent.assert_not_called() + + def test_reply_card_survives_restart_with_different_process_epoch(self): + self.fake.add("Original==") + self.mail.sync() + args = {"message_id": "Original==", "body": "示例回复"} + self.app._account_epoch = 3 + self.describe(**args) + self.now += 6 * DAY + self.restart_mail() + self.assertEqual(self.do("restart", **args)["message_ref"], "SentReply==") + self.assertEqual(len(self.fake.commands("mail +reply")), 1) + self.app.record_sent.assert_not_called() + + def test_reply_card_refuses_changed_recipients_after_restart(self): + self.fake.add("Original==", to=(ADDRESS, "first@example.org")) + self.mail.sync() + args = {"message_id": "Original==", "body": "示例回复", "reply_all": True} + self.assertIn("first@example.org", self.describe(**args)["summary"]) + self.restart_mail() + self.app.store._tx(lambda db: db.execute( + 'UPDATE mails SET "to"=? WHERE message_id=?', + (json.dumps([{"address": ADDRESS}, {"address": "changed@example.org"}]), "Original=="))) + with self.assertRaisesRegex(RPCError, "收件人有变化"): + self.describe(**args) + with self.assertRaisesRegex(RPCError, "没有发出"): + self.do("changed-recipients", **args) + self.assertEqual(self.fake.commands("mail +reply-all"), []) + + def test_reply_cards_keep_only_the_latest_256_and_expire_in_seven_days(self): + self.fake.add("Original==") + self.mail.sync() + for i in range(257): + self.describe(message_id="Original==", body="示例回复 %d" % i) + self.assertEqual(self.app.store._one("SELECT count(*) FROM mail_reply_cards")[0], 256) + with self.assertRaisesRegex(RPCError, "没有发出"): + self.do("evicted", message_id="Original==", body="示例回复 0") + self.now += 7 * DAY + self.restart_mail() + with self.assertRaisesRegex(RPCError, "没有发出"): + self.do("expired", message_id="Original==", body="示例回复 256") + self.assertFalse(self.fake.commands("mail +reply")) + self.assertEqual(self.app.store._one("SELECT count(*) FROM mail_reply_cards")[0], 0) + self.describe(message_id="Original==", body="示例回复 0") + self.assertEqual(self.app.store._one("SELECT count(*) FROM mail_reply_cards")[0], 1) + + def test_reply_timeout_or_unknown_journals_uncertain_and_rejection_does_not(self): + self.fake.add("Original==") + self.mail.sync() + args = {"message_id": "Original==", "body": "示例回复"} + self.describe(**args) + for key, answer in (("timeout", subprocess.TimeoutExpired("lark-cli", 25)), ("unknown", "{}")): + with self.subTest(key=key): + self.fake.reply_answer = answer + with self.assertRaisesRegex(RPCError, "可能已经发出"): + self.do(key, **args) + with self.assertRaisesRegex(RPCError, "可能已经发出"): + self.do(key, **args) + self.assertEqual(self.app.store.send_get("action:" + key)["state"], "uncertain") + self.assertEqual(len(self.fake.commands("mail +reply")), 2) + self.fake.reply_answer = {"error": {"type": "validation", "subtype": "invalid_argument"}} + with self.assertRaisesRegex(RPCError, "没有发出去"): + self.do("rejected", **args) + self.assertIsNone(self.app.store.send_get("action:rejected")) + self.assertEqual(len(self.fake.commands("mail +reply")), 3) + self.app.record_sent.assert_not_called() diff --git a/extensions/openmate-feishu/tests/test_meetings.py b/extensions/openmate-feishu/tests/test_meetings.py index 46cd5a8..5d11251 100644 --- a/extensions/openmate-feishu/tests/test_meetings.py +++ b/extensions/openmate-feishu/tests/test_meetings.py @@ -372,7 +372,7 @@ def test_legacy_and_incremental_archive_with_limits(self): self.assertEqual(chat["batches"][0]["chat"]["id"], "chat_example") self.assertTrue(chat["more"]) first = self.archive(chat["next"], limit=1) - self.assertEqual(first["next"], "v1:1:meetings=1") + self.assertEqual(first["next"], "v1:1:mail=0:meetings=1") batch = first["batches"][0] self.assertEqual(batch["chat"], {"id": "meeting-example1", "name": "周会", "kind": "meeting", "updated_at": "2026-11-16T01:30:00Z"}) @@ -395,7 +395,7 @@ def test_archive_cap_and_disabled_cursor_skips_delivered_window(self): self.assertTrue(first["more"]) self.app.config["meetings_kb"] = False skipped = self.archive(first["next"]) - self.assertEqual(skipped, {"batches": [], "next": "v1:0:meetings=22", "more": False}) + self.assertEqual(skipped, {"batches": [], "next": "v1:0:mail=0:meetings=22", "more": False}) self.assertEqual(self.app.handle("connector.items.list", {}), {"items": []}) self.app.config["meetings_kb"] = True self.assertFalse(self.archive(skipped["next"])["batches"]) diff --git a/extensions/openmate-feishu/tests/test_today_wechat.py b/extensions/openmate-feishu/tests/test_today_wechat.py index 905dbc3..4f02962 100644 --- a/extensions/openmate-feishu/tests/test_today_wechat.py +++ b/extensions/openmate-feishu/tests/test_today_wechat.py @@ -250,7 +250,7 @@ def test_a_layout_keeps_its_order_while_wechat_is_away(self): st = json.dumps({"edit": 1}) page.action({"ui_version": 6, "action": {"id": "layout:down:feishu"}, "state": st}) page.action({"ui_version": 6, "action": {"id": "layout:up:feishu"}, "state": st}) - self.assertEqual(page.layout().order[4:7], ["feishu", "wechat", "agents"], "back as it was, 微信今天 in its place") + self.assertEqual(page.layout().order, layout.Layout.default().order, "back as it was, 微信今天 in its place") def test_one_read_for_the_page_and_the_card(self): page, card, hub, _ = make() @@ -259,7 +259,8 @@ def test_one_read_for_the_page_and_the_card(self): self.assertEqual(len([c for c in hub.calls if c[1] == BASE + "today"]), 1) def test_layout_block_and_manifest(self): - self.assertEqual([b[0] for b in layout.BLOCKS].index("wechat"), [b[0] for b in layout.BLOCKS].index("feishu") + 1) + order = [b[0] for b in layout.BLOCKS] + self.assertEqual(order[order.index("feishu"):order.index("wechat") + 1], ["feishu", "mail", "wechat"]) m = json.load(open(os.path.join(os.path.dirname(HERE), "persona-extension.json"), encoding="utf-8")) self.assertIn("extensions.call:openmate-wechat", m["permissions"]["hub"]) diff --git a/extensions/openmate-wechat/assistant/instructions.md b/extensions/openmate-wechat/assistant/instructions.md index 72c66d3..6108f15 100644 --- a/extensions/openmate-wechat/assistant/instructions.md +++ b/extensions/openmate-wechat/assistant/instructions.md @@ -1,6 +1,6 @@ # 微信(OpenMate) -- 这是用户本人的微信,以一台新电脑的身份登录。`matewechat_*` 工具读用户本人的微信会话;`matewechat_send` / `matewechat_send_dm` 以用户的身份发出,每次都要用户在手机上确认。私聊和群里 @用户 的消息会进收件箱;私聊进知识库,群聊默认不进。 +- 这是用户本人的微信,以一台新电脑的身份登录。`matewechat_*` 工具读用户本人的微信会话;`matewechat_send` / `matewechat_send_dm` 以用户的身份发出,每次都要用户在确认卡片上确认。私聊和群里 @用户 的消息会进收件箱;私聊进知识库,群聊默认不进。 - 会话 id:群是 `…@chatroom`,私聊是对方的微信 id。名字查不到时用 `matewechat_search` 按名字找,或先 `matewechat_chats` 看最近的会话。 - 这台电脑只收到登录之后的消息,更早的聊天记录读不到。 - 图片、语音、视频、文件会自动下载到本机,消息里写着本地路径:`[图片] 本地文件:/…/123.jpg` 可以直接读图;语音是 WAV(设置了语音转文字才附文字,否则你听不到内容);视频给封面、视频文件和几张截图;合并转发的聊天记录直接展开成文字。还没下载完、下载失败或需要重新下载时用 `matewechat_media`(给消息 id)。下载不了时括号里写着原因(例如过期、超过 25 MB),如实转告,不要猜内容。能下载媒体之前收到的消息只有 `[图片]` 这样的占位,取不到内容。 diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json index 3d3dbe0..e960366 100644 --- a/extensions/openmate-wechat/persona-extension.json +++ b/extensions/openmate-wechat/persona-extension.json @@ -2,8 +2,8 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.68", - "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在手机上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", + "version": "0.1.69", + "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", "icon": "assets/icon.png", diff --git a/packages/openmate-feishu/0.11.75/openmate-feishu-0.11.75.tar.gz b/packages/openmate-feishu/0.11.75/openmate-feishu-0.11.75.tar.gz new file mode 100644 index 0000000..75518f3 Binary files /dev/null and b/packages/openmate-feishu/0.11.75/openmate-feishu-0.11.75.tar.gz differ diff --git a/packages/openmate-wechat/0.1.69/openmate-wechat-0.1.69.tar.gz b/packages/openmate-wechat/0.1.69/openmate-wechat-0.1.69.tar.gz new file mode 100644 index 0000000..831214c Binary files /dev/null and b/packages/openmate-wechat/0.1.69/openmate-wechat-0.1.69.tar.gz differ diff --git a/persona-extensions.json b/persona-extensions.json index f3bbc05..768cf12 100644 --- a/persona-extensions.json +++ b/persona-extensions.json @@ -9,8 +9,8 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.74", - "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,手机确认后以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", + "version": "0.11.75", + "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", "engines": { @@ -51,7 +51,9 @@ "matefeishu_starkmesh", "matefeishu_media", "matefeishu_members", - "matefeishu_meetings" + "matefeishu_meetings", + "matefeishu_mail", + "matefeishu_mail_reply" ], "confirm_always": [ "matefeishu_*" @@ -61,12 +63,14 @@ "kinds": [ "dm", "mention", - "group" + "group", + "mail" ], "kind_descriptions": { "dm": "类型:飞书私聊里别人发给我、我还没回的消息", "mention": "类型:飞书群里有人 @我、我还没回的消息", - "group": "类型:飞书群里的新消息,没有 @我" + "group": "类型:飞书群里的新消息,没有 @我", + "mail": "类型:飞书邮箱里发给我、标为重要、还没读的邮件" } } ], @@ -419,6 +423,28 @@ "maximum": 30, "default": 14 }, + "approvals": { + "type": "boolean", + "title": "审批和飞书任务", + "description": "只读显示等你审批的单子和分给你的飞书任务,点开到飞书里处理。OpenMate 不替你同意、拒绝或完成。", + "default": true + }, + "mail": { + "type": "boolean", + "title": "飞书邮箱", + "description": "通过 lark-cli 只读同步飞书邮箱里最近的邮件,在今天页显示,重要邮件进收件箱和知识库。回复邮件要你在确认卡片上批准。", + "default": true + }, + "mail_inbox": { + "type": "boolean", + "title": "重要邮件进收件箱", + "default": true + }, + "mail_kb": { + "type": "boolean", + "title": "邮件进知识库", + "default": true + }, "starkmesh_url": { "type": "string", "format": "uri", @@ -508,9 +534,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-feishu/0.11.74/openmate-feishu-0.11.74.tar.gz", - "sha256": "159d2b84b267fe8f3644c76a45f2910f932ddf76052e7b3976beb3a6d73bff97", - "size": 395090 + "url": "packages/openmate-feishu/0.11.75/openmate-feishu-0.11.75.tar.gz", + "sha256": "03ed3937cda8584e550266688acebb93b49b232338b2035bbfc5115055a0366d", + "size": 409623 } ] }, @@ -519,8 +545,8 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.68", - "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在手机上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", + "version": "0.1.69", + "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", "engines": { @@ -816,9 +842,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-wechat/0.1.68/openmate-wechat-0.1.68.tar.gz", - "sha256": "7ce721ea93ca5adc295f419f2162604c89db55ade78523604b9e56d5150aaa57", - "size": 307349 + "url": "packages/openmate-wechat/0.1.69/openmate-wechat-0.1.69.tar.gz", + "sha256": "a64ca8c20176c460000f96ebdc0e4fdbd9a3da9bc9a89a0aae4af8c21b9d2263", + "size": 307560 } ] } diff --git a/tests/test_actions.py b/tests/test_actions.py index 749961d..e08820e 100644 --- a/tests/test_actions.py +++ b/tests/test_actions.py @@ -1,4 +1,4 @@ -"""Read tools (no gate) and the two writes (send, send_dm): their cards, request ids, uncertain sends.""" +"""Connector read tools and their gated writes, cards, request IDs and uncertain sends.""" try: # first: every temporary directory of this run in one, removed at its end import _runtmp # noqa: F401 @@ -22,8 +22,8 @@ def test_names_schemas_and_manifest(self): actions = h.c("actions.list")["tools"] names = [t["name"] for t in tools] self.assertEqual(names, [CID + "_" + n for n in ("status", "chats", "messages", "search", "docs", "agent_reply", - "starkmesh", "media", "members", "meetings")]) - self.assertEqual([a["name"] for a in actions], [CID + "_send", CID + "_send_dm"]) + "starkmesh", "media", "members", "meetings", "mail")]) + self.assertEqual([a["name"] for a in actions], [CID + "_send", CID + "_send_dm", CID + "_mail_reply"]) for t in tools + actions: self.assertTrue(t["description"]) self.assertEqual(t["input_schema"]["type"], "object") @@ -31,9 +31,11 @@ def test_names_schemas_and_manifest(self): self.assertTrue({"chat", "text", "reply_to", "at"} <= set(send), "the example backend can @") self.assertIn("at", actions[0]["description"]) self.assertIn("开一个新话题", actions[0]["description"]) + for action in actions[:2]: + self.assertIn("每次都要我在确认卡片上确认", action["description"]) with open(os.path.join(ROOT, "extensions", "openmate-feishu", "persona-extension.json"), encoding="utf-8") as f: conn = json.load(f)["contributes"]["connectors"][0] - self.assertEqual(conn["agent_tools"], names) # every read tool and agent_reply; no write + self.assertEqual(conn["agent_tools"], names + [CID + "_mail_reply"]) self.assertEqual(conn["confirm_always"], [CID + "_*"]) def test_empty_args_answer_or_refuse_in_words(self):