@mcviseron/dsh-qq-bridge 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,240 @@
1
+ """Quote recognition: platform msg_elements + msg_idx pool fallback (offline)."""
2
+ import os as _os, tempfile as _tempfile
3
+ _os.environ.setdefault("DSH_QQBOT_STATE_DIR", _tempfile.mkdtemp(prefix="qqbot-test-"))
4
+ import asyncio
5
+ import dataclasses
6
+ import os
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ sys.path.insert(0, str(Path('.').resolve()))
12
+ import main as M # noqa: E402
13
+ from main import DSHBot, PooledMessage, load_config # noqa: E402
14
+
15
+ REF_A = "REFIDX_Va1QXgH9XPMpoCdgZcchdogmkHICDjIm81"
16
+ REF_B = "REFIDX_HBGjHEIroev5tdT2nCIVRqHY6bQLRYDFzfUay0o92R"
17
+
18
+
19
+ class _RT:
20
+ def __init__(self, probe=False):
21
+ self.probe = probe
22
+
23
+ def get_bool(self, key, default=True):
24
+ if key == "group_at_only":
25
+ return False
26
+ return self.probe if key == "quote_probe" else default
27
+
28
+ def get_int(self, key, default=0):
29
+ return 0 if key == "debounce_ms" else default
30
+
31
+ def get_float(self, key, default=0.0):
32
+ return default
33
+
34
+ def get_str(self, key, default=""):
35
+ return default
36
+
37
+ def get(self, key, default=None):
38
+ return default
39
+
40
+
41
+ class StubAPI:
42
+ async def post_c2c_message(self, **kw):
43
+ return {"id": "m"}
44
+
45
+ async def post_c2c_stream_message(self, openid, **fields):
46
+ return {"id": "s"}
47
+
48
+
49
+ class StubBridge:
50
+ def __init__(self):
51
+ self.calls = []
52
+
53
+ async def inbound(self, **kw):
54
+ self.calls.append(kw)
55
+ return {"ok": True}
56
+
57
+ async def pull(self, cursor, wait):
58
+ return {"cursor": 0, "events": []}
59
+
60
+
61
+ class Msg:
62
+ def __init__(self, scene_ext=None, elements=None, message_id="M1", content="看看这个"):
63
+ scene = {"ext": list(scene_ext), "source": "default"} if scene_ext is not None else None
64
+ raw = {}
65
+ if scene:
66
+ raw["message_scene"] = scene
67
+ if elements is not None:
68
+ raw["msg_elements"] = elements
69
+ self.raw = raw
70
+ self.id = message_id
71
+ self.content = content
72
+ self.attachments = None
73
+ self.author = type("A", (), {"user_openid": "OWNER", "member_openid": "OWNER"})()
74
+
75
+
76
+ def make_bot():
77
+ config = dataclasses.replace(load_config(), ack_delay_s=0, debounce_s=0.0, debounce_max_s=0.0)
78
+ bot = DSHBot.__new__(DSHBot)
79
+ bot.config = config
80
+ bot.api = StubAPI()
81
+ bot.bridge = StubBridge()
82
+ bot.state = type("S", (), {"owner_openid": "OWNER", "group_owners": {}, "save": lambda self: None})()
83
+ bot.owner_openid = "OWNER"
84
+ bot.rt = _RT()
85
+ bot.pool = {}
86
+ bot._chat_turns = {}
87
+ bot.member_index = {}
88
+ bot.pool_idx = {}
89
+ bot._pending_quotes = {}
90
+ bot._suppress_reply = set()
91
+ bot._seen_ids = {}
92
+ bot._streamed_turns = {}
93
+ bot._streams = {}
94
+ bot._urgent_tasks = set()
95
+ bot._inflight = {}
96
+ bot._inflight_at = {}
97
+ bot._rate = {}
98
+ bot._submitted_at = {}
99
+ bot._bot_spoke_at = {}
100
+ bot._last_sent = {}
101
+ bot._last_bot_say = {}
102
+ bot._addressed_at = {}
103
+ bot.recent_images = {}
104
+ bot.chatter = {}
105
+ bot.queued = {}
106
+ bot.pending = {}
107
+ bot.targets = {}
108
+ bot.pending_approvals = {}
109
+ bot.group_state = {}
110
+ bot.chime = {}
111
+ bot._msg_seq = 0
112
+ bot._acks = {}
113
+ bot._pull_task = None
114
+ bot._watchdog_task = None
115
+ bot._in_quiet_hours = lambda: False
116
+ return bot
117
+
118
+
119
+ def check(name, ok, extra=""):
120
+ print(("ok " if ok else "FAIL ") + name + (f" {extra}" if extra else ""))
121
+ return 0 if ok else 1
122
+
123
+
124
+ async def main():
125
+ os.environ["QUOTE_PROBE"] = "0"
126
+ failures = 0
127
+
128
+ failures += check("ext 解析成字典",
129
+ M._scene_ext({"ext": [f"ref_msg_idx={REF_A}", f"msg_idx={REF_B}", "auth_token=x"]})
130
+ == {"ref_msg_idx": REF_A, "msg_idx": REF_B, "auth_token": "x"})
131
+ failures += check("出站序号取 ext_info.ref_idx",
132
+ M._sent_idx({"id": "x", "ext_info": {"ref_idx": REF_A}}) == REF_A)
133
+
134
+ bot = make_bot()
135
+ element_msg = Msg(elements=[{"content": "被引用的原话", "message_type": 103, "msg_idx": REF_A}])
136
+ quote = bot._quote_of(element_msg)
137
+ failures += check("平台直接给出被引用正文",
138
+ quote and quote["resolved"] and quote["text"] == "被引用的原话", str(quote))
139
+
140
+ bot.pool["MID-1"] = PooledMessage(
141
+ message_id="MID-1", conv_key="group:G", kind="group", openid="G",
142
+ author="主人", text="被引用的原话", outbound=False, at=time.time(), idx=REF_A)
143
+ bot.pool_idx[REF_A] = "MID-1"
144
+ quote = bot._quote_of(element_msg)
145
+ failures += check("正文 + 池里补出作者",
146
+ quote and quote["author"] == "主人" and quote["text"] == "被引用的原话", str(quote))
147
+
148
+ pool_only = Msg(scene_ext=[f"ref_msg_idx={REF_A}", f"msg_idx={REF_B}"])
149
+ quote = bot._quote_of(pool_only)
150
+ failures += check("没有 msg_elements 时用池兜底",
151
+ quote and quote["resolved"] and quote["text"] == "被引用的原话", str(quote))
152
+
153
+ missing = Msg(scene_ext=[f"ref_msg_idx=REFIDX_UNKNOWN00000", f"msg_idx={REF_B}"])
154
+ quote = bot._quote_of(missing)
155
+ failures += check("查不到就如实说看不到", quote and quote["resolved"] is False and quote["text"] == "")
156
+
157
+ plain = bot._quote_of(Msg(scene_ext=[f"msg_idx={REF_B}"]))
158
+ failures += check("只有 msg_idx 不算引用", plain is None)
159
+
160
+ failures += check("无 raw 不抛异常", bot._quote_of(Msg()) is None)
161
+
162
+ bot = make_bot()
163
+ bot._register("c2c:OWNER", "c2c", "OWNER", "M1")
164
+ await bot._handle_c2c(Msg(elements=[{"content": "被引用的原话", "message_type": 103, "msg_idx": REF_A}]))
165
+ await asyncio.sleep(0.3)
166
+ sent = bot.bridge.calls[-1] if bot.bridge.calls else {}
167
+ q = sent.get("quote")
168
+ failures += check("端到端:入站带上被引用正文", bool(q) and q["resolved"] and q["text"] == "被引用的原话", str(q))
169
+
170
+
171
+ # --- 引用来源区分:机器人本人 / 主人 / 群友 ---
172
+ bot = make_bot()
173
+ bot.pool["OUT-1"] = PooledMessage(
174
+ message_id="OUT-1", conv_key="group:G", kind="group", openid="G",
175
+ author=bot.config.botname, text="我自己说过的话", outbound=True, at=time.time(), idx="REFIDX_OWN000000001")
176
+ bot.pool_idx["REFIDX_OWN000000001"] = "OUT-1"
177
+ q_own = bot._quote_of(Msg(elements=[{"content": "我自己说过的话", "message_type": 103, "msg_idx": "REFIDX_OWN000000001"}]))
178
+ failures += check("引用机器人自己的话标成你自己",
179
+ q_own and q_own["outbound"] is True and "机器人" in q_own["author"], str(q_own))
180
+
181
+ bot.pool["IN-1"] = PooledMessage(
182
+ message_id="IN-1", conv_key="group:G", kind="group", openid="G",
183
+ author="主人", text="主人说的话", outbound=False, at=time.time(), idx="REFIDX_OWNR0000001")
184
+ bot.pool_idx["REFIDX_OWNR0000001"] = "IN-1"
185
+ q_owner = bot._quote_of(Msg(elements=[{"content": "主人说的话", "message_type": 103, "msg_idx": "REFIDX_OWNR0000001"}]))
186
+ failures += check("引用主人标成主人", q_owner and q_owner["author"] == "主人", str(q_owner))
187
+
188
+ bot.pool["IN-2"] = PooledMessage(
189
+ message_id="IN-2", conv_key="group:G", kind="group", openid="G",
190
+ author="群友AFF7F1", text="群友说的话", outbound=False, at=time.time(), idx="REFIDX_MATE0000001")
191
+ bot.pool_idx["REFIDX_MATE0000001"] = "IN-2"
192
+ q_mate = bot._quote_of(Msg(elements=[{"content": "群友说的话", "message_type": 103, "msg_idx": "REFIDX_MATE0000001"}]))
193
+ failures += check("引用群友标成群友", q_mate and q_mate["author"] == "群友AFF7F1", str(q_mate))
194
+
195
+ # --- 图片 / 文件引用(平台没给正文时按种类标注) ---
196
+ q_img = bot._quote_of(Msg(elements=[{"message_type": 101, "attachments": [{"url": "x"}], "msg_idx": "REFIDX_IMG00000001"}]))
197
+ failures += check("引用图片标成图片", q_img and q_img["kind"] == "image" and q_img["resolved"] is True, str(q_img))
198
+
199
+ q_file = bot._quote_of(Msg(elements=[{"message_type": 102, "file_name": "报告.pdf", "msg_idx": "REFIDX_FILE0000001"}]))
200
+ failures += check("引用文件带出文件名", q_file and q_file["kind"] == "file" and q_file["text"] == "报告.pdf", str(q_file))
201
+
202
+
203
+ # --- 私聊:message_reference 形态的引用 ---
204
+ bot = make_bot()
205
+ bot.pool["C2C-OUT"] = PooledMessage(
206
+ message_id="C2C-OUT", conv_key="c2c:OWNER", kind="c2c", openid="OWNER",
207
+ author=bot.config.botname, text="我私聊里说过的话", outbound=True, at=time.time(), idx="")
208
+ ref_msg = Msg()
209
+ ref_msg.raw = {"message_reference": {"message_id": "C2C-OUT"}}
210
+ q_ref = bot._quote_of(ref_msg)
211
+ failures += check("私聊 message_reference 命中池并标成机器人",
212
+ q_ref and q_ref["resolved"] and q_ref["outbound"] is True and q_ref["text"] == "我私聊里说过的话",
213
+ str(q_ref))
214
+
215
+ ref_text = Msg()
216
+ ref_text.raw = {"message_reference": {"message_id": "C2C-GONE", "content": "平台直接给的正文"}}
217
+ q_text = bot._quote_of(ref_text)
218
+ failures += check("私聊引用带正文时直接用",
219
+ q_text and q_text["resolved"] and q_text["text"] == "平台直接给的正文", str(q_text))
220
+
221
+ none_ref = Msg()
222
+ none_ref.raw = {"content": "没有引用的普通私聊"}
223
+ failures += check("私聊无 message_reference 不算引用", bot._quote_of(none_ref) is None)
224
+
225
+
226
+ # --- 引用图片:取出 URL 并交给下载流程 ---
227
+ failures += check("attachment url 解析", M._attachment_url({"url": "https://x/a.png"}) == "https://x/a.png"
228
+ and M._attachment_url({"file_url": "https://x/b.png"}) == "https://x/b.png"
229
+ and M._attachment_url("https://x/c.png") == "https://x/c.png"
230
+ and M._attachment_url({}) is None)
231
+
232
+ img_quote = bot._quote_of(Msg(elements=[{"message_type": 101, "attachments": [{"url": "https://cdn/x.jpg"}], "msg_idx": "REFIDX_IMGSAMPLE01"}]))
233
+ failures += check("引用图片带出 urls", img_quote and img_quote["kind"] == "image" and img_quote["urls"] == ["https://cdn/x.jpg"], str(img_quote))
234
+ failures += check("没有 url 时不下载", (await bot._quote_images({"kind": "image", "urls": []})) == [])
235
+
236
+ print("ALL PASS" if failures == 0 else f"{failures} FAILED")
237
+ return 0 if failures == 0 else 1
238
+
239
+
240
+ sys.exit(asyncio.run(main()))
@@ -0,0 +1,84 @@
1
+ import os as _os, tempfile as _tempfile
2
+ _os.environ.setdefault("DSH_QQBOT_STATE_DIR", _tempfile.mkdtemp(prefix="qqbot-test-"))
3
+ import asyncio, json, sys, pathlib, tempfile
4
+ sys.path.insert(0, '.')
5
+ import main
6
+
7
+
8
+ class FakeAPI:
9
+ def __init__(self, fail_at=None, fail_msg="其它流式消息发送中"):
10
+ self.calls = []
11
+ self.fail_at = fail_at
12
+ self.fail_msg = fail_msg
13
+
14
+ async def post_c2c_stream_message(self, **kw):
15
+ self.calls.append(kw)
16
+ if self.fail_at is not None and len(self.calls) - 1 == self.fail_at:
17
+ raise RuntimeError(self.fail_msg)
18
+ return {'id': 'STREAM1'}
19
+
20
+
21
+ def make_bot(api):
22
+ bot = main.DSHBot.__new__(main.DSHBot)
23
+ bot._streams = {}
24
+ bot._streamed_turns = {}
25
+ bot._suppress_reply = set()
26
+ bot._stream_locks = {}
27
+ bot._stream_holdoff = {}
28
+ bot._msg_seq = 0
29
+ bot.targets = {'c2c:OWNER': type('T', (), {'openid': 'OWNER', 'last_msg_id': 'M1', 'kind': 'c2c', 'conv_key': 'c2c:OWNER'})()}
30
+ bot.api = api
31
+ bot.rt_bool = lambda k, d=False: True
32
+ bot.rt_float = lambda k, d=0: d
33
+ bot.rt_int = lambda k, d=0: d
34
+ bot._persist_streams = lambda: None
35
+ bot._spawn_files = lambda conv, text: None
36
+ bot.sent = []
37
+ async def send_text(conv, text, keyboard=None):
38
+ bot.sent.append(text)
39
+ bot.send_text = send_text
40
+ return bot
41
+
42
+
43
+ async def case_index():
44
+ api = FakeAPI()
45
+ bot = make_bot(api)
46
+ for chunk in ['你', '你好', '你好呀']:
47
+ await bot._handle_stream({'convKey': 'c2c:OWNER', 'text': chunk, 'final': False, 'turnId': 't1'})
48
+ bot._streams['c2c:OWNER']['last'] = 0 # bypass the interval throttle
49
+ await bot._handle_stream({'convKey': 'c2c:OWNER', 'text': '。', 'final': True, 'turnId': 't1'})
50
+ idx = [c['index'] for c in api.calls]
51
+ states = [c['input_state'] for c in api.calls]
52
+ print('index 序列:', idx, '严格递增:', all(b > a for a, b in zip(idx, idx[1:])))
53
+ print('收尾帧数:', states.count(10), '| 最后一帧 index:', idx[-1])
54
+
55
+
56
+ async def case_fail_mid():
57
+ api = FakeAPI(fail_at=1)
58
+ bot = make_bot(api)
59
+ await bot._handle_stream({'convKey': 'c2c:OWNER', 'text': '第一段', 'final': False, 'turnId': 't2'})
60
+ bot._streams['c2c:OWNER']['last'] = 0
61
+ await bot._handle_stream({'convKey': 'c2c:OWNER', 'text': '第二段', 'final': False, 'turnId': 't2'})
62
+ print('中断后会话已丢弃:', 'c2c:OWNER' not in bot._streams, '| 已进入降级:', bot._stream_degraded('c2c:OWNER'))
63
+
64
+
65
+ async def case_degraded():
66
+ api = FakeAPI()
67
+ bot = make_bot(api)
68
+ bot._hold_stream('c2c:OWNER', 'test')
69
+ await bot._handle_stream({'convKey': 'c2c:OWNER', 'text': '整段回答', 'final': True, 'turnId': 't3'})
70
+ print('降级时调用流式次数:', len(api.calls), '| 普通消息:', bot.sent)
71
+
72
+
73
+ async def case_seq():
74
+ api = FakeAPI()
75
+ bot = make_bot(api)
76
+ await bot._handle_stream({'convKey': 'c2c:OWNER', 'text': 'a', 'final': False, 'turnId': 't4'})
77
+ await bot._handle_stream({'convKey': 'c2c:OWNER', 'text': 'b', 'final': True, 'turnId': 't4'})
78
+ await bot._handle_stream({'convKey': 'c2c:OWNER', 'text': 'c', 'final': False, 'turnId': 't5'})
79
+ seq = sorted({c['msg_seq'] for c in api.calls})
80
+ print('两次回合的 msg_seq:', seq, '| 互不相同:', len(seq) == 2)
81
+
82
+
83
+ for case in (case_index, case_fail_mid, case_degraded, case_seq):
84
+ asyncio.run(case())
@@ -0,0 +1,141 @@
1
+ """Offline check of the streaming delivery path (no QQ, no DSH)."""
2
+ import os as _os, tempfile as _tempfile
3
+ _os.environ.setdefault("DSH_QQBOT_STATE_DIR", _tempfile.mkdtemp(prefix="qqbot-test-"))
4
+ import asyncio, dataclasses, sys, time
5
+ from pathlib import Path
6
+ sys.path.insert(0, str(Path('.').resolve()))
7
+ from main import DSHBot, load_config
8
+
9
+
10
+ class _RT:
11
+ """Runtime-config stub: streaming on, everything else default."""
12
+
13
+ def get_bool(self, key, default=True):
14
+ if key == "group_at_only":
15
+ return False
16
+ return True if key == "stream_enabled" else default
17
+
18
+ def get_int(self, key, default=0):
19
+ return default
20
+
21
+ def get_float(self, key, default=0.0):
22
+ return default
23
+
24
+ def get_str(self, key, default=""):
25
+ return default
26
+
27
+ def get(self, key, default=None):
28
+ return default
29
+
30
+ class StubAPI:
31
+ def __init__(self):
32
+ self.streams = []
33
+ self.fail = False
34
+
35
+ async def post_c2c_message(self, **kw):
36
+ self.streams.append({'plain': True, **kw})
37
+ return {'id': 'p1'}
38
+
39
+ async def post_c2c_stream_message(self, openid, **fields):
40
+ if self.fail:
41
+ raise RuntimeError("platform rejected")
42
+ self.streams.append({"openid": openid, **fields})
43
+ return {"id": "m1"}
44
+
45
+
46
+ class StubBridge:
47
+ async def inbound(self, **kw): return {}
48
+ async def pull(self, cursor, wait): return {"cursor": 0, "events": []}
49
+
50
+
51
+ def make_bot():
52
+ config = dataclasses.replace(load_config(), ack_delay_s=0)
53
+ bot = DSHBot.__new__(DSHBot)
54
+ bot.config = config
55
+ bot.api = StubAPI()
56
+ bot.pool = {}
57
+ bot._chat_turns = {}
58
+ bot.member_index = {}
59
+ bot.pool_idx = {}
60
+ bot._pending_quotes = {}
61
+ bot._streamed_turns = {}
62
+ bot.bridge = StubBridge()
63
+ bot.state = type("S", (), {"owner_openid": "OWNER", "group_owners": {}, "save": lambda self: None})()
64
+ bot.owner_openid = "OWNER"
65
+ bot.targets = {}
66
+ bot.pending_approvals = {}
67
+ bot.pending = {}
68
+ bot.queued = {}
69
+ bot.chatter = {}
70
+ bot.recent_images = {}
71
+ bot.group_state = {}
72
+ bot.chime = {}
73
+ bot._seen_ids = {}
74
+ bot._submitted_at = {}
75
+ bot._inflight = {}
76
+ bot._inflight_at = {}
77
+ bot._rate = {}
78
+ bot._addressed_at = {}
79
+ bot._bot_spoke_at = {}
80
+ bot._last_sent = {}
81
+ bot._last_bot_say = {}
82
+ bot._streams = {}
83
+ bot._suppress_reply = set()
84
+ bot._acks = {}
85
+ bot._msg_seq = 0
86
+ bot._pull_task = None
87
+ bot._watchdog_task = None
88
+ bot._urgent_tasks = set()
89
+ bot.rt = _RT()
90
+ bot._in_quiet_hours = lambda: False
91
+ return bot
92
+
93
+
94
+ def target(bot, conv="c2c:OWNEROPENID000000000000000000"):
95
+ bot._register(conv, "c2c", conv.split(":", 1)[1], None)
96
+ return conv
97
+
98
+
99
+ async def main():
100
+ failures = 0
101
+
102
+ bot = make_bot()
103
+ conv = target(bot)
104
+ await bot._handle_stream({"convKey": conv, "text": "你", "final": False})
105
+ await bot._handle_stream({"convKey": conv, "text": "好", "final": False})
106
+ await bot._handle_stream({"convKey": conv, "text": "呀", "final": True})
107
+ calls = bot.api.streams
108
+ ok = len(calls) >= 2 and calls[-1]["input_state"] == 10 and "你好呀" in calls[-1]["content_raw"]
109
+ print(("ok " if ok else "FAIL ") + f"流式分片 -> 复用 stream_msg_id 收尾 (frames={len(calls)})")
110
+ failures += 0 if ok else 1
111
+ ok2 = "t" in str(bot._streamed_turns) or conv in bot._suppress_reply
112
+ print(("ok " if ok2 else "FAIL ") + "流式完成后抑制重复的耐久回复")
113
+ failures += 0 if ok2 else 1
114
+
115
+ await bot._handle_event({"type": "reply", "convKey": conv, "text": "你好呀", "tools": []})
116
+ ok3 = not bot.api.streams[0].get("dup") and conv not in bot._suppress_reply
117
+ print(("ok " if ok3 else "FAIL ") + "耐久回复被丢弃(不重复发)")
118
+ failures += 0 if ok3 else 1
119
+
120
+ bot = make_bot()
121
+ conv = target(bot)
122
+ bot.api.fail = True
123
+ await bot._handle_stream({"convKey": conv, "text": "失败测试", "final": True})
124
+ # 流式被拒、且没送出任何内容时必须清理状态且不抑制 durable 回复,
125
+ # 否则整段回答会被"静默丢失"(这是之前私聊没反应的那一类 bug)
126
+ ok4 = conv not in bot._streams and conv not in bot._suppress_reply
127
+ print(("ok " if ok4 else "FAIL ") + "流式失败 -> 清理状态,回落到一次性发送")
128
+ failures += 0 if ok4 else 1
129
+
130
+ bot = make_bot()
131
+ bot._register("group:CCE96DDF6F462E1010E5721BBA1B6CBB", "group", "CCE96DDF6F462E1010E5721BBA1B6CBB", None)
132
+ await bot._handle_stream({"convKey": "group:CCE96DDF6F462E1010E5721BBA1B6CBB", "text": "群聊不走流式", "final": True})
133
+ ok5 = not bot.api.streams
134
+ print(("ok " if ok5 else "FAIL ") + "群聊不发流式(平台不支持)")
135
+ failures += 0 if ok5 else 1
136
+
137
+ print("ALL PASS" if failures == 0 else f"{failures} FAILED")
138
+ return 0 if failures == 0 else 1
139
+
140
+
141
+ sys.exit(asyncio.run(main()))
@@ -0,0 +1,80 @@
1
+ """Turn-id based dedupe: a streamed turn must not eat the next answer."""
2
+ import os as _os, tempfile as _tempfile
3
+ _os.environ.setdefault("DSH_QQBOT_STATE_DIR", _tempfile.mkdtemp(prefix="qqbot-test-"))
4
+ import asyncio, dataclasses, sys
5
+ from pathlib import Path
6
+ sys.path.insert(0, str(Path('.').resolve()))
7
+ from main import DSHBot, load_config
8
+
9
+
10
+ class StubAPI:
11
+ def __init__(self): self.posts = []
12
+ async def post_c2c_message(self, **kw): self.posts.append(kw); return {"id": "m"}
13
+
14
+
15
+ class StubBridge:
16
+ def __init__(self): self.calls = []
17
+ async def inbound(self, **kw): self.calls.append(kw); return {"ok": True}
18
+ async def pull(self, cursor, wait): return {"cursor": 0, "events": []}
19
+ async def approve(self, *a, **k): return {"ok": True}
20
+
21
+
22
+ def make():
23
+ config = dataclasses.replace(load_config(), ack_delay_s=0)
24
+ bot = DSHBot.__new__(DSHBot)
25
+ bot.config = config; bot.api = StubAPI(); bot.bridge = StubBridge()
26
+ bot.state = type("S", (), {"owner_openid": "OWNER", "group_owners": {}, "save": lambda self: None})()
27
+ bot.pool = {}
28
+ bot._chat_turns = {}
29
+ bot.member_index = {}
30
+ bot.pool_idx = {}
31
+ bot._pending_quotes = {}
32
+ bot.owner_openid = "OWNER"
33
+ for name, value in dict(targets={}, pending_approvals={}, pending={}, queued={}, chatter={}, recent_images={},
34
+ group_state={}, chime={}, _seen_ids={}, _submitted_at={}, _inflight={}, _inflight_at={},
35
+ _rate={}, _addressed_at={}, _bot_spoke_at={}, _last_sent={}, _last_bot_say={}, _streams={},
36
+ _acks={}, _msg_seq=0, _pull_task=None, _watchdog_task=None, rt=None).items():
37
+ setattr(bot, name, value)
38
+ bot._suppress_reply = set()
39
+ bot._streamed_turns = {}
40
+ bot._urgent_tasks = set()
41
+ bot._in_quiet_hours = lambda: False
42
+ return bot
43
+
44
+
45
+ async def main():
46
+ failures = 0
47
+ conv = "c2c:OWNEROPENID000000000000000000"
48
+
49
+ bot = make(); bot._register(conv, "c2c", conv.split(":", 1)[1], None)
50
+ bot._streamed_turns["t-1"] = 1.0
51
+ bot._inflight[conv] = 1
52
+ await bot._handle_event({"type": "reply", "convKey": conv, "turnId": "t-1", "text": "重复", "tools": []})
53
+ ok = not bot.api.posts and bot._inflight.get(conv, 0) == 0 and "t-1" not in bot._streamed_turns
54
+ print(("ok " if ok else "FAIL ") + "同一 turnId 的耐久回复被丢弃且计数归还")
55
+ failures += 0 if ok else 1
56
+
57
+ bot = make(); bot._register(conv, "c2c", conv.split(":", 1)[1], None)
58
+ bot._streamed_turns["t-1"] = 1.0
59
+ bot._inflight[conv] = 1
60
+ await bot._handle_event({"type": "reply", "convKey": conv, "turnId": "t-2", "text": "新的一轮", "tools": []})
61
+ ok2 = len(bot.api.posts) == 1
62
+ print(("ok " if ok2 else "FAIL ") + f"新 turnId 正常发送 (posts={len(bot.api.posts)})")
63
+ failures += 0 if ok2 else 1
64
+
65
+ bot = make(); bot._register(conv, "c2c", conv.split(":", 1)[1], None)
66
+ bot._streamed_turns["old"] = 1.0
67
+ bot._inflight[conv] = 1
68
+ bot._inflight_at[conv] = 0.0
69
+ bot.rt = type("RT", (), {"get_float": lambda self, k, d=0.0: 0.0, "get_bool": lambda self, k, d=True: True,
70
+ "get_int": lambda self, k, d=0: d, "get_str": lambda self, k, d='': d})()
71
+ bot._release_if_stuck(conv)
72
+ ok3 = bot._inflight.get(conv, 0) == 0
73
+ print(("ok " if ok3 else "FAIL ") + "卡死回合会被释放(不再永久闭嘴)")
74
+ failures += 0 if ok3 else 1
75
+
76
+ print("ALL PASS" if failures == 0 else f"{failures} FAILED")
77
+ return 0 if failures == 0 else 1
78
+
79
+
80
+ sys.exit(asyncio.run(main()))