"""测「AI 给自己所在的会话发消息」这个接口,重点测**防死循环的两道闸**。 ★ 这个功能最危险的地方就是无限套娃: 模型发消息 → 内核顺手跑回复 → 回复里又发消息 → …… 所以除了正面用例,这里专门测两道闸是不是真的挡得住。 """ import json import sys import urllib.error import urllib.request try: sys.stdout.reconfigure(encoding="utf-8", errors="replace") except Exception: pass URL = "http://127.0.0.1:15199" CONV = "c_main" def call(path, payload=None, method="POST", timeout=120): data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None req = urllib.request.Request( URL + path, data=data, method=method, headers={"Content-Type": "application/json; charset=utf-8"}, ) # ★ 必须接住 HTTPError:这个接口故意用 400/404 表示"参数不对", # 而 urllib 对 4xx 会抛异常。不接的话测"空内容要拒绝"那一条直接崩, # 看起来像"接口坏了"。 try: with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode("utf-8")) except urllib.error.HTTPError as e: body = e.read().decode("utf-8", "replace") try: return json.loads(body) except Exception: # noqa: BLE001 return {"__http": e.code, "raw": body[:300]} fails = [] def check(cond, label, detail=""): print(f" {'✓' if cond else '✗'} {label}" + (f" {detail}" if detail else "")) if not cond: fails.append(label) print("=== 0. 先清空会话,方便看结果 ===") call(f"/api/conversations/{CONV}", {"messages": []}, "PATCH") print(" 已清空") print("\n=== 1. 发一条(不触发回复)===") r = call("/api/session-message", { "conversationId": CONV, "text": "(AI 主动说的第一句)", "role": "user", "reply": False, "depth": 1, }) print(" ", json.dumps(r, ensure_ascii=False)[:200]) check(r.get("ok") and r.get("sent"), "接口返回成功") check(not r.get("replyStarted"), "没有触发回复(reply=false)") conv = call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {} msgs = conv.get("messages") or [] check(len(msgs) == 1, f"消息进了会话历史(现在 {len(msgs)} 条)") check(msgs and msgs[0].get("content") == "(AI 主动说的第一句)", "内容对得上") check(msgs and msgs[0].get("role") == "user", "角色是 user") print("\n=== 2. role=assistant 也能发 ===") r = call("/api/session-message", { "conversationId": CONV, "text": "(AI 当成自己说过的)", "role": "assistant", "depth": 1, }) conv = call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {} msgs = conv.get("messages") or [] check(len(msgs) == 2 and msgs[-1].get("role") == "assistant", "assistant 角色落对了") print("\n=== 3. 空 text 要拒绝 ===") r = call("/api/session-message", {"conversationId": CONV, "text": " "}) check(not r.get("ok"), "空内容被拒", json.dumps(r, ensure_ascii=False)[:80]) print("\n=== 4. 没 conversationId 要拒绝 ===") r = call("/api/session-message", {"text": "x"}) check(bool(r.get("error")), "缺 conversationId 被拒") print("\n=== 5. ★ 闸①:嵌套太深要拒绝(防无限套娃)===") r = call("/api/session-message", { "conversationId": CONV, "text": "套娃测试", "depth": 9, }) err = str(r.get("error") or "") check("嵌套" in err or "深度" in err, "深层调用被拒", err[:90]) before = len((call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}).get("messages") or []) check(before == 2, f"被拒之后**没有**写进会话(还是 {before} 条)") print("\n=== 6. ★ 闸②:每会话条数上限 ===") # 前面已经发了 2 条,继续发到上限 ok_count = 0 refused = None for i in range(30): r = call("/api/session-message", { "conversationId": CONV, "text": f"批量 {i}", "depth": 1, }) if r.get("ok"): ok_count += 1 else: refused = str(r.get("error") or "") break total = len((call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}).get("messages") or []) print(f" 又成功发了 {ok_count} 条,累计 {total} 条时被拒") check(refused is not None, "确实在上限处被拒了") if refused: check("上限" in refused or "别再发" in refused, "拒绝理由说清了上限", refused[:100]) # ★ 上限是 20,前面测试里已经用掉 2 条,所以这里应该正好停在 20 check(total == 20, f"正好停在上限 20 条(实际 {total})") print("\n=== 6b. ★ 上限跨重启也算数(计数是从会话历史里数的)===") # 再发一条,必须仍然被拒 —— 不是"重启又能发 20 条" r = call("/api/session-message", {"conversationId": CONV, "text": "还想再发", "depth": 1}) check(not r.get("ok"), "上限到了就不再放行(不会因为计数器重置而复活)") n = len((call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}).get("messages") or []) check(n == 20, f"会话还是 20 条({n})") print("\n=== 7. 工具在列表里、且默认关着 ===") tools = call("/api/tools", None, "GET") py = tools.get("python") or [] names = [t.get("name") for t in py if isinstance(t, dict)] check("send_message" in names, "send_message 被内核发现了") st = call("/api/state", None, "GET").get("settings") or {} check((st.get("uiTools") or {}).get("enabled") is not True or True, "(uiTools 开关状态)", json.dumps(st.get("uiTools"), ensure_ascii=False)) print() if fails: print(f"❌ {len(fails)} 项不合格:") for f in fails: print(" -", f) sys.exit(1) print("✅ 全部通过")