diff --git a/extensions/openmate-wechat/assistant/instructions.md b/extensions/openmate-wechat/assistant/instructions.md
index 325bdaf..afe6073 100644
--- a/extensions/openmate-wechat/assistant/instructions.md
+++ b/extensions/openmate-wechat/assistant/instructions.md
@@ -4,7 +4,8 @@
- 会话 id:群是 `…@chatroom`,私聊是对方的微信 id。名字查不到时用 `matewechat_search` 按名字找,或先 `matewechat_chats` 看最近的会话。
- 这台电脑只收到登录之后的消息,更早的聊天记录读不到。
- 群公告用 `matewechat_group_notice`(chat 给群的会话 id `…@chatroom`):当场从微信读,返回公告正文、发布人和发布时间;只读,不会改公告。公告里可能有账号、密码之类的内容,回答时只用到用户问的部分,不要整段转发给别人。
-- 群接龙在消息里显示成「[接龙] 标题…」加完整的编号名单(1. …、2. …)。每有一个人接龙,群里就多一条带全部名单的新消息:要现在的名单,看最新的那一条。
+- 群接龙在消息里第一行是「[接龙] 共 N 条」,下面是标题和完整的编号名单(1. …、2. …)。每有一个人接龙,群里就多一条带全部名单的新消息:要现在的名单,看最新的那一条。
+ /agent 请求附带的聊天记录里,长消息会被截断,末尾是「…」。接龙以「…」结尾、或者数到的条数和「共 N 条」对不上时,名单不全:用 `matewechat_messages` 读这个群的消息(可以给 query 或 since / until 缩小范围),那里是全文。
- 图片、语音、视频、文件会自动下载到本机,消息里写着本地路径:`[图片] 本地文件:/…/123.jpg` 可以直接读图;语音是 WAV(设置了语音转文字才附文字,否则你听不到内容);视频给封面、视频文件和几张截图;合并转发的聊天记录直接展开成文字。还没下载完、下载失败或需要重新下载时用 `matewechat_media`(给消息 id)。下载不了时括号里写着原因(例如过期、超过 25 MB),如实转告,不要猜内容。能下载媒体之前收到的消息只有 `[图片]` 这样的占位,取不到内容。
- 微信不能编辑已发的消息,也没有表情回应:用户自己的 /agent 接单时,扩展会自动在原会话发一句“处理中”提示(设置里的“接单提示”);群里有人 @ 用户的自动代答不发这句。你只回复一次最终结果,不发中途进度。
连接 AgentWechat 时,撤回微信里的请求也会停止它触发的 Agent,包括 `@自己` 和自动代答。还没回复且提示发出不到两分钟时,它的「处理中」提示也会撤回。
diff --git a/extensions/openmate-wechat/openmate_wechat/hub.py b/extensions/openmate-wechat/openmate_wechat/hub.py
index 4adad84..dfcd348 100644
--- a/extensions/openmate-wechat/openmate_wechat/hub.py
+++ b/extensions/openmate-wechat/openmate_wechat/hub.py
@@ -122,11 +122,16 @@ def strip_label(body: str, label: str) -> str:
ERROR_CODE = re.compile(r"[a-z]{1,12}(?:_[a-z]{1,12})+")
+NUMBERED = re.compile(r"(?m)^[0-9]{1,4}\.(?: |$)") # an entry's line in a note's text, as the official clients number it
+
+
def group_note(body: str, summary: Any) -> str:
- """A Group Note (群接龙, app message 53) as matewechat-native shows it: "[接龙] " and the whole note. The hub's body is
- the note's text as WeChat shows it (title, example line, numbered entries, text after them); without one, the
- note is written out from the hub's summary (kind group_note) the same way."""
+ """A Group Note (群接龙, app message 53) as matewechat-native shows it: "[接龙] 共 N 条" and the whole note below
+ (the count stays when a reader gets the text cut short). The hub's body is the note's text as WeChat shows it
+ (title, example line, numbered entries, text after them), its entries counted by their numbered lines; without a
+ body, the note is written out from the hub's summary (kind group_note) the same way."""
text = body.strip()
+ count = len(NUMBERED.findall(text.replace("\r\n", "\n")))
s = summary if isinstance(summary, dict) and summary.get("kind") == "group_note" else {}
if not text and s:
entries = [str(e.get("text") or "").strip() for e in s.get("entries") or [] if isinstance(e, dict)]
@@ -136,8 +141,10 @@ def group_note(body: str, summary: Any) -> str:
text += "\n\n" + "\n".join("%d. %s" % (n, e) for n, e in enumerate(entries, 1))
if s.get("extra"):
text += "\n\n" + str(s["extra"]).strip()
- text = text.strip()
- return ("[接龙] %s" % text) if text else "[接龙]"
+ text, count = text.strip(), len(entries)
+ if not text:
+ return "[接龙]"
+ return ("[接龙] 共 %d 条\n%s" % (count, text)) if count else "[接龙] %s" % text
def frame_code(data: str) -> str:
diff --git a/extensions/openmate-wechat/openmate_wechat/install.py b/extensions/openmate-wechat/openmate_wechat/install.py
index 03b359c..991c559 100644
--- a/extensions/openmate-wechat/openmate_wechat/install.py
+++ b/extensions/openmate-wechat/openmate_wechat/install.py
@@ -21,12 +21,12 @@
log = logging.getLogger("openmate.wechat.install")
-VERSION = "0.1.12"
+VERSION = "0.1.13"
URL = "https://github.com/NginxL/openmate/releases/download/matewechat-native-v{version}/{name}"
ASSETS = {
("darwin", "arm64"): {
- "name": "matewechat-native-0.1.12-darwin-arm64",
- "sha256": "a5cedb2dfe1987098b1f0e6023103025203e7929a9e1263006188b4a53a0930c",
+ "name": "matewechat-native-0.1.13-darwin-arm64",
+ "sha256": "538603677ac30d5675f3093e6907b65fac3a20877bf126a8942fdbc850fb46fb",
"size": 8365440,
},
}
diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json
index 2646794..384a309 100644
--- a/extensions/openmate-wechat/persona-extension.json
+++ b/extensions/openmate-wechat/persona-extension.json
@@ -2,7 +2,7 @@
"manifest_version": 1,
"id": "openmate-wechat",
"name": "微信(OpenMate)",
- "version": "0.1.75",
+ "version": "0.1.76",
"description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
diff --git a/extensions/openmate-wechat/tests/test_hub.py b/extensions/openmate-wechat/tests/test_hub.py
index 51c707c..8336d92 100644
--- a/extensions/openmate-wechat/tests/test_hub.py
+++ b/extensions/openmate-wechat/tests/test_hub.py
@@ -1298,12 +1298,14 @@ def test_a_group_note_keeps_its_whole_list(self):
L = self.link()
body = "#接龙 周六羽毛球\n\n1. 张三\n2. 李四"
n = L.message_event(self.msg(type=49, appMessageType=53, body=body, link={"title": "#接龙 周六羽毛球"}), "live")
- self.assertEqual((n["type"], n["text"]), ("CARD", "[接龙] " + body))
+ self.assertEqual((n["type"], n["text"]), ("CARD", "[接龙] 共 2 条\n" + body))
summary = {"kind": "group_note", "noteId": "1_2", "title": "#接龙 周六羽毛球", "format": "写名字", "extra": "周五截止",
"entries": [{"text": "张三"}, {"text": "李四", "senderId": "wxid_b"}]}
n = L.message_event(self.msg(type=49, appMessageType=53, body=None, summary=summary), "live")
- self.assertEqual(n["text"], "[接龙] #接龙 周六羽毛球\n写名字\n\n1. 张三\n2. 李四\n\n周五截止")
+ self.assertEqual(n["text"], "[接龙] 共 2 条\n#接龙 周六羽毛球\n写名字\n\n1. 张三\n2. 李四\n\n周五截止")
self.assertEqual(L.message_event(self.msg(type=49, appMessageType=53, body=None), "live")["text"], "[接龙]")
+ odd = L.message_event(self.msg(type=49, appMessageType=53, body="#接龙 周六\n说明 3. 不算\n12345. 也不算"), "live")
+ self.assertEqual(odd["text"], "[接龙] #接龙 周六\n说明 3. 不算\n12345. 也不算", "no numbered line: no count")
link = L.message_event(self.msg(type=49, appMessageType=5, body=None, link={"title": "文章"}), "live")
self.assertEqual(link["text"], "[链接] 文章", "other cards are as before")
diff --git a/native/matewechat-native/Cargo.lock b/native/matewechat-native/Cargo.lock
index 9761537..09bcb7e 100644
--- a/native/matewechat-native/Cargo.lock
+++ b/native/matewechat-native/Cargo.lock
@@ -724,7 +724,7 @@ checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "matewechat-native"
-version = "0.1.12"
+version = "0.1.13"
dependencies = [
"anyhow",
"base64 0.22.1",
diff --git a/native/matewechat-native/Cargo.toml b/native/matewechat-native/Cargo.toml
index 1137307..652a289 100644
--- a/native/matewechat-native/Cargo.toml
+++ b/native/matewechat-native/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "matewechat-native"
-version = "0.1.12"
+version = "0.1.13"
edition = "2021"
license = "MIT"
publish = false
diff --git a/native/matewechat-native/src/message.rs b/native/matewechat-native/src/message.rs
index 756e6c3..cd7f3e4 100644
--- a/native/matewechat-native/src/message.rs
+++ b/native/matewechat-native/src/message.rs
@@ -134,9 +134,10 @@ fn app_message(content: &str) -> (&'static str, String, String, String, String)
}
}
-const NOTE_TITLE_MOST: usize = 128 * 1024; // a note's
holds its whole list
+const NOTE_TITLE_MOST: usize = 128 * 1024; // a note's holds its whole list; a note written out is no longer
const NOTE_XML_MOST: usize = 256 * 1024;
const NOTE_PART_MOST: usize = 16 * 1024; // one part or entry
+const NOTE_ENTRIES_MOST: usize = 200; // agent-wechat's MAX_ENTRIES: a note with more is shown as its
/// A Group Note (群接龙, app message 53) as text: "[接龙] " and the whole note, its list included, as WeChat shows it.
///
@@ -147,25 +148,45 @@ const NOTE_PART_MOST: usize = 16 * 1024; // one part or entry
/// (title), `ex` (example line), `tl` (text after the entries) and each entry's ``, which are `offset-length`
/// spans of the `` text in UTF-16 code units (`0-0`: the part is absent), and each entry's own text in ``.
/// Every new entry posts a new message with the whole list again. The note is written out from its parts when all of
-/// them can be read; otherwise the `` as it is.
+/// them can be read and it stays within bounds (at most NOTE_ENTRIES_MOST entries, NOTE_TITLE_MOST bytes in all: a
+/// range of a few bytes may select a whole part of the title, so a crafted note could otherwise grow a hundredfold);
+/// otherwise the `` as it is.
+///
+/// The first line says how many entries there are ("[接龙] 共 N 条"): a reader that gets the text cut short (the
+/// /agent prompt keeps 2000 characters of a message) still knows the list is longer.
fn group_note(app: roxmltree::Node) -> String {
let title: String = app
.children()
.find(|c| c.is_element() && c.tag_name().name() == "title")
.map(|t| t.descendants().filter(|n| n.is_text()).filter_map(|n| n.text()).collect())
.unwrap_or_default();
- let shown = solitaire(app, &title)
- .unwrap_or_else(|| title.trim_matches(|c: char| c.is_ascii_whitespace() || c == '\u{3000}').to_owned());
- if shown.is_empty() {
- "[接龙]".into()
- } else {
- format!("[接龙] {shown}")
+ let (shown, count) = solitaire(app, &title).unwrap_or_else(|| {
+ let t = title.trim_matches(|c: char| c.is_ascii_whitespace() || c == '\u{3000}').to_owned();
+ let n = numbered_lines(&t);
+ (t, n)
+ });
+ match (shown.is_empty(), count) {
+ (true, _) => "[接龙]".into(),
+ (false, 0) => format!("[接龙] {shown}"),
+ (false, n) => format!("[接龙] 共 {n} 条\n{shown}"),
}
}
-/// The note its `solitaire_info` describes, written the way the official clients write the ``; None when it is
-/// missing, malformed, too big, or any part or entry of it cannot be read.
-fn solitaire(app: roxmltree::Node, title: &str) -> Option {
+/// The entries a note's text shows: its lines that start "N. " (or are just "N."), as the official clients number
+/// them.
+fn numbered_lines(text: &str) -> usize {
+ text.lines()
+ .filter(|line| {
+ let digits = line.bytes().take_while(u8::is_ascii_digit).count();
+ (1..=4).contains(&digits) && matches!(&line.as_bytes()[digits..], [b'.'] | [b'.', b' ', ..])
+ })
+ .count()
+}
+
+/// The note its `solitaire_info` describes, written the way the official clients write the ``, and how many
+/// entries it has; None when it is missing, malformed, too big (more than NOTE_ENTRIES_MOST entries, or more than
+/// NOTE_TITLE_MOST bytes written out), or any part or entry of it cannot be read.
+fn solitaire(app: roxmltree::Node, title: &str) -> Option<(String, usize)> {
if title.len() > NOTE_TITLE_MOST {
return None;
}
@@ -185,16 +206,9 @@ fn solitaire(app: roxmltree::Node, title: &str) -> Option {
Some(n) => span(&units, &xml_text(n, &[])?),
};
let (head, example, tail) = (part("tt")?, part("ex")?, part("tl")?);
- let mut entries = vec![];
- for item in child(root, "content")?.children().filter(|n| n.is_element() && n.tag_name().name() == "i") {
- // the entry's own text, else the part of the title its range selects
- let text = match child(item, "c").and_then(|c| xml_text(c, &[])).filter(|t| !t.is_empty()) {
- Some(t) => shown(&t)?,
- None => span(&units, &xml_text(child(item, "r")?, &[])?)??,
- };
- entries.push(text);
- }
- if head.is_none() && entries.is_empty() {
+ let items: Vec<_> =
+ child(root, "content")?.children().filter(|n| n.is_element() && n.tag_name().name() == "i").collect();
+ if items.len() > NOTE_ENTRIES_MOST || (head.is_none() && items.is_empty()) {
return None;
}
let mut text = head.unwrap_or_default();
@@ -203,17 +217,25 @@ fn solitaire(app: roxmltree::Node, title: &str) -> Option {
text.push_str(&example);
}
text.push_str("\n\n");
- for (n, entry) in entries.iter().enumerate() {
+ for (n, item) in items.iter().enumerate() {
+ // the entry's own text, else the part of the title its range selects
+ let entry = match child(*item, "c").and_then(|c| xml_text(c, &[])).filter(|t| !t.is_empty()) {
+ Some(t) => shown(&t)?,
+ None => span(&units, &xml_text(child(*item, "r")?, &[])?)??,
+ };
if n > 0 {
text.push('\n');
}
text.push_str(&format!("{}. {entry}", n + 1));
+ if text.len() > NOTE_TITLE_MOST {
+ return None; // written out it would be bigger than any title: the title as it is
+ }
}
if let Some(tail) = tail {
text.push_str("\n\n");
text.push_str(&tail);
}
- Some(text.trim().to_owned())
+ (text.len() <= NOTE_TITLE_MOST).then(|| (text.trim().to_owned(), items.len()))
}
fn child<'a, 'input>(node: roxmltree::Node<'a, 'input>, name: &str) -> Option> {
@@ -741,15 +763,15 @@ mod tests {
let title = "周末 lunch 🍜\n\n1. Daniel 拉面\n2. Alex 饺子 🥟\n\nReply by Friday ✅";
let items = [note_item("16-9", Some("Daniel 拉面")), note_item("29-10", Some("Alex 饺子 🥟"))];
let text = note_text(¬e_xml(title, &solitaire("0-11", "0-0", "41-17", &items)));
- assert_eq!(text, format!("[接龙] {title}"));
+ assert_eq!(text, format!("[接龙] 共 2 条\n{title}"));
// a range that ends inside the noodle emoji's surrogate pair (10-1: its low half) gives up on the parts: the
// title as it is (here the same text)
let half = note_xml(title, &solitaire("0-11", "0-0", "10-1", &items));
assert_eq!(solitaire_of(&half, title), None);
- assert_eq!(note_text(&half), format!("[接龙] {title}"));
+ assert_eq!(note_text(&half), format!("[接龙] 共 2 条\n{title}"), "the count of the title's numbered lines");
}
- fn solitaire_of(xml: &str, title: &str) -> Option {
+ fn solitaire_of(xml: &str, title: &str) -> Option<(String, usize)> {
let doc = roxmltree::Document::parse(xml).unwrap();
super::solitaire(element(&doc, "appmsg").unwrap(), title)
}
@@ -759,7 +781,7 @@ mod tests {
let title = "#接龙\n周六羽毛球,写名字和几点到\n\n1. 张三 9点\n2. 李四 10点 🏸\n3. 王五";
let items: Vec = ["张三 9点", "李四 10点 🏸", "王五"].iter().map(|e| note_item(&range(title, e), None)).collect();
let sol = solitaire(&range(title, "#接龙"), &range(title, "周六羽毛球,写名字和几点到"), "0-0", &items);
- assert_eq!(note_text(¬e_xml(title, &sol)), format!("[接龙] {title}"));
+ assert_eq!(note_text(¬e_xml(title, &sol)), format!("[接龙] 共 3 条\n{title}"));
}
#[test]
@@ -767,7 +789,7 @@ mod tests {
let title = "#接龙 周六羽毛球";
let items = [note_item("0-0", Some("张三")), note_item("0-0", Some("李四"))];
let text = note_text(¬e_xml(title, &solitaire(&range(title, title), "0-0", "0-0", &items)));
- assert_eq!(text, "[接龙] #接龙 周六羽毛球\n\n1. 张三\n2. 李四");
+ assert_eq!(text, "[接龙] 共 2 条\n#接龙 周六羽毛球\n\n1. 张三\n2. 李四");
}
#[test]
@@ -784,13 +806,55 @@ mod tests {
note_xml(title, &solitaire("0-6", "0-0", "0-0", &[good.clone(), note_item("x", None)])), // an entry unread
note_xml(title, &solitaire("0-6", "0-0", "0-0", &[good]).replace("", "").replace("", "")),
] {
- assert_eq!(note_text(&xml), format!("[接龙] {title}"), "{xml}");
+ assert_eq!(note_text(&xml), format!("[接龙] 共 2 条\n{title}"), "{xml}");
}
assert_eq!(note_text("53"), "[接龙]");
+ // a title with no numbered lines and nothing else to go by: no count
+ assert_eq!(note_text("#接龙 周六53"), "[接龙] #接龙 周六");
// a link card is still a link
assert_eq!(note_text("t5"), "[链接] t");
}
+ #[test]
+ fn group_note_too_many_entries_shows_its_title() {
+ let names: Vec = (1..=201).map(|n| format!("成员{n}")).collect();
+ let list = |k: usize| names[..k].iter().enumerate().map(|(i, e)| format!("{}. {e}", i + 1)).collect::>().join("\n");
+ let items = |k: usize| names[..k].iter().map(|e| note_item("0-0", Some(e))).collect::>();
+ // 200 entries (agent-wechat's MAX_ENTRIES) are written out from the note
+ let title = format!("#接龙\n\n{}", list(200));
+ let xml = note_xml(&title, &solitaire("0-3", "0-0", "0-0", &items(200)));
+ assert_eq!(solitaire_of(&xml, &title).map(|(_, n)| n), Some(200));
+ assert_eq!(note_text(&xml), format!("[接龙] 共 200 条\n{title}"));
+ // 201: the title as it is, counted by its numbered lines
+ let title = format!("#接龙\n\n{}", list(201));
+ let xml = note_xml(&title, &solitaire("0-3", "0-0", "0-0", &items(201)));
+ assert_eq!(solitaire_of(&xml, &title), None);
+ assert_eq!(note_text(&xml), format!("[接龙] 共 201 条\n{title}"));
+ }
+
+ #[test]
+ fn group_note_cannot_grow_past_a_title() {
+ // a 16 KB title and entries that each select all of it: 200 of them would make 3.2 MB of one message
+ let title = "x".repeat(16 * 1024);
+ let whole = format!("0-{}", 16 * 1024);
+ let xml = note_xml(&title, &solitaire("0-0", "0-0", "0-0", &vec![note_item(&whole, None); 200]));
+ assert_eq!(solitaire_of(&xml, &title), None);
+ let text = note_text(&xml);
+ assert_eq!(text, format!("[接龙] {title}"), "the title as it is");
+ // the bound is NOTE_TITLE_MOST written out: 7 such entries fit (114,717 bytes), 8 do not (131,105)
+ let seven = solitaire_of(¬e_xml(&title, &solitaire("0-0", "0-0", "0-0", &vec![note_item(&whole, None); 7])), &title);
+ assert_eq!(seven.map(|(t, n)| (t.len() <= NOTE_TITLE_MOST, n)), Some((true, 7)));
+ let eight = note_xml(&title, &solitaire("0-0", "0-0", "0-0", &vec![note_item(&whole, None); 8]));
+ assert_eq!(solitaire_of(&eight, &title), None);
+ }
+
+ #[test]
+ fn numbered_lines_of_a_note() {
+ assert_eq!(numbered_lines("#接龙 晚饭\n\n1. 张三\n2.\n10. 李四\n说明 3. 王五\n12345. 太长\n4.x\n5、赵六"), 3);
+ assert_eq!(numbered_lines("1. a\r\n2. b"), 2);
+ assert_eq!(numbered_lines(""), 0);
+ }
+
#[test]
fn inline_data() {
let mut silk = vec![2u8];
diff --git a/packages/openmate-wechat/0.1.76/openmate-wechat-0.1.76.tar.gz b/packages/openmate-wechat/0.1.76/openmate-wechat-0.1.76.tar.gz
new file mode 100644
index 0000000..e07c3d9
Binary files /dev/null and b/packages/openmate-wechat/0.1.76/openmate-wechat-0.1.76.tar.gz differ
diff --git a/persona-extensions.json b/persona-extensions.json
index ef41744..f84cd3b 100644
--- a/persona-extensions.json
+++ b/persona-extensions.json
@@ -551,7 +551,7 @@
"manifest_version": 1,
"id": "openmate-wechat",
"name": "微信(OpenMate)",
- "version": "0.1.75",
+ "version": "0.1.76",
"description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。",
"publisher": "NginxL",
"homepage": "https://github.com/NginxL/openmate",
@@ -849,9 +849,9 @@
"icon": "assets/icon.png",
"packages": [
{
- "url": "packages/openmate-wechat/0.1.75/openmate-wechat-0.1.75.tar.gz",
- "sha256": "f71af229d40540ecf4b84f57408cfcb46c1567dc8cd45c9fc0b1c7c598671e74",
- "size": 318008
+ "url": "packages/openmate-wechat/0.1.76/openmate-wechat-0.1.76.tar.gz",
+ "sha256": "832c3d2ed643afe6ec7ca291cdd311570db763a72f0ebc5b020a333f96629807",
+ "size": 318320
}
]
}