AI 界面能力补完:数据真的回流给模型 + 打开网页 + 点选 (v2.0.37)
用户四条要求,全部做完并实测:
1. "弹出的网页可再点进去" → 网页界面里链接在应用内打开,顶部有返回键
2. "支持 js" → javaScriptEnabled=true,同时把桥按页面收口
3. "你要单独开个按钮" → 消息操作栏加「打开网页」按钮 + 独立全屏网页界面
4. "是 ai 自己能写进网页里的" → ★ 本次核心:Doubao.sendToAi 真的把值送回模型
## ★★ 数据回流(本次最重要的一条)
以前 `Doubao.pick` 只是"关闭界面 + 弹个提示",**值根本到不了模型手里**。
现在是一条完整的链路:
AI 写的 HTML 里 Doubao.sendToAi('用户选了方案B')
→ JS 桥 AiWebHost.sendToAi
→ NativeBridge 的 ui_result action → POST /api/ui-result
→ store 里排队(内存,一次性的上下文,不落盘)
→ 下一轮 run_agent 取走,作为**一条 system 消息**插在历史前面
→ 模型真的看到"用户在界面上选了什么"
★ 为什么排队而不是"点了就起一轮对话":
用户可能连点几下、选好几项再确认。每点一下跑一轮模型又慢又费 token,
而且用户还没说完。语义上界面上的选择是**提问的一部分,不是提问本身**。
★ 为什么插成 system 而不是 user:它不是用户打的话。塞成 user 会让历史里
出现一条用户没说过的话,而且"重新生成"时会和真正那条用户消息混在一起。
★ 提示语如实写"已记下,下次对话会告诉 AI",不写"已发送" ——
后者会让用户以为模型马上回话,然后干等。
三个入口都收:`Doubao.sendToAi(v)` / `Doubao.pick(v)` / `<button data-doubao-result="v">`。
## 实测证据(不是"看代码应该没问题")
起了一个假的 OpenAI 兼容服务,把内核指过去,直接读它收到的请求体:
[system] 你是豆包,…(系统提示词)
[system] 用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):
- 用户选了方案 B(蓝色按钮)
- 用户填写了:预算 3000 元
[user] 我刚才在界面上选了什么?
假服务是在**模拟器里**连宿主机的,用 `adb reverse tcp:18080 tcp:18080`;
`10.0.2.2` 在 LDPlayer 上不通(假服务一个请求都收不到,很容易误判成代码有问题)。
## 顺带修的第三个真 bug:清不掉 Base URL
`store.write_settings` 有一段"保险":空串一律当"没填、别动"
(防的是"前端草稿没初始化好,一次保存清空整份配置")。
这个保险是对的,但代价是**用户永远清不掉自定义 Base URL / 模型名** ——
删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。
(我是在测回流时踩到的:想把内核从假服务指回默认,传空串怎么也改不掉。)
修法:加一条**显式**的清除通路 —— 值传 `null` 就是"确实要清掉",
落到默认值上。空串仍然="没填、别动"。Python 和 Node 两端都改了。
## 网页点选(用在真实网页上)
全屏网页界面顶部有「点选」横条,打开后可以在页面上点选内容、填写的表单值,
攒够了一起发给 AI。实现上**没有挂 JS 桥** —— 用"注入脚本写队列 +
Kotlin 主动轮询取走",数据只从页面流向 App,外部站点没有任何办法调 App。
★ 改过一版:第一版只认"看着能点"的元素(a/button/[role=button]…),
实测在 example.com 上一个都标不出来(那页全是纯文本),
于是点选模式看起来完全没生效。用户想点的是**任意一段内容**,
所以改成 `elementFromPoint` 点哪儿抓哪儿。
## 其他
· 正文里的 markdown 链接以前**没绑点击**(蓝色下划线,点了没反应)
—— 用户问"网页在哪点开"时才查出来。现在用 withLink 绑上了。
★ withLink 带 @ExperimentalTextApi,不 opt-in 报的是
`Unresolved reference 'withLink'`(不是"需要 opt-in"),
很容易误判成"这个版本没这个 API"。我是把 aar 拆开 javap 看注解才确认的。
· 链接列表用**独立全屏界面**(项目约定:列表这种要滚动的东西不用弹窗)
## 验证
新增 `scripts/verify-web-pick.py`(28 项)守:外部浏览**没有桥**、
取数要"取走"不清空会重复上报、input 用冒泡旁听不拦页面、
输入要防抖、多条要能累积、关闭入口、show_ui 说明里有 sendToAi。
★ 这个验证脚本自己绊了自己三次,都记在文件注释里了:
去注释的正则截断了字符串里的 "http://"、光找 "Doubao" 会命中 `Doubao.Blue`、
查 "Doubao.close()" 因为源码里是转义的 `\n` 而对不上。
**验证脚本自己有 bug 比没有更坏** —— 它会让人去改本来对的代码。
真机实测(Android 14 x86_64,新建的 LDPlayer 实例):
打开网页按钮 → 全屏链接列表 → 点进 example.com
点选模式 → 点一段文字,虚线框选中
sendToAi/pick/data-result → 队列 ["方案B","方案C","方案D"]
发一句话 → 队列被取走,假服务收到的请求里带上了那些值 ✓
This commit is contained in:
86
scripts/fake-openai.py
Normal file
86
scripts/fake-openai.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""假模型服务:把收到的请求原样存下来,回一个最小可用的 SSE。
|
||||
|
||||
用来**证明**"界面上选的值真的拼进了发给模型的消息里" ——
|
||||
光看队列空了不够,那只说明有人取走了;到底拼没拼、拼成什么样,要看请求。
|
||||
|
||||
用法:
|
||||
python scripts/fake-openai.py 18080 # 另开一个窗口
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18080
|
||||
CAPTURE = sys.argv[2] if len(sys.argv) > 2 else r"C:\DoubaoAndroid\fake-req.json"
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/v1/models"):
|
||||
body = json.dumps({"data": [{"id": "fake-model"}]}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(n).decode("utf-8", "replace")
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except Exception:
|
||||
parsed = {"__raw": raw}
|
||||
|
||||
# ★ 存下来 —— 这就是"模型收到了什么"的铁证
|
||||
with open(CAPTURE, "w", encoding="utf-8") as fh:
|
||||
json.dump({"path": self.path, "body": parsed}, fh, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"\n=== {self.path} 收到请求 ===", flush=True)
|
||||
for m in (parsed.get("messages") or []):
|
||||
role = m.get("role")
|
||||
content = m.get("content")
|
||||
if isinstance(content, list):
|
||||
content = " ".join(
|
||||
c.get("text", "") for c in content if isinstance(c, dict)
|
||||
)
|
||||
text = (content or "")
|
||||
print(f" [{role}] {text[:400]}", flush=True)
|
||||
|
||||
# 回一个最小 SSE(OpenAI 流式格式)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.end_headers()
|
||||
|
||||
def chunk(delta, finish=None):
|
||||
obj = {
|
||||
"id": "chatcmpl-fake", "object": "chat.completion.chunk",
|
||||
"created": int(time.time()), "model": "fake-model",
|
||||
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
|
||||
}
|
||||
self.wfile.write(f"data: {json.dumps(obj, ensure_ascii=False)}\n\n".encode())
|
||||
self.wfile.flush()
|
||||
|
||||
chunk({"role": "assistant", "content": "我看到你在界面上选了:方案B、方案C、方案D。"})
|
||||
chunk({}, "stop")
|
||||
self.wfile.write(b"data: [DONE]\n\n")
|
||||
self.wfile.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"假模型服务监听 127.0.0.1:{PORT}", flush=True)
|
||||
print(f"请求会存到 {CAPTURE}", flush=True)
|
||||
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|
||||
46
scripts/probe-clean-testdata.py
Normal file
46
scripts/probe-clean-testdata.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""清掉测试留下的对话数据(让模拟器上的 App 回到干净状态)。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
K = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(p, d=None, m="POST"):
|
||||
b = json.dumps(d, ensure_ascii=False).encode() if d is not None else None
|
||||
r = urllib.request.Request(
|
||||
K + p, data=b, method=m, headers={"Content-Type": "application/json; charset=utf-8"}
|
||||
)
|
||||
return json.loads(urllib.request.urlopen(r, timeout=30).read().decode())
|
||||
|
||||
|
||||
# ★ 注意 method 是**位置参数** m,不是 method= —— 这个脚本第一版写成
|
||||
# `method="PATCH"` 直接 TypeError。写探针脚本时这种小错最多。
|
||||
call("/api/conversations/c_main", {"messages": []}, "PATCH")
|
||||
full = call("/api/conversations/c_main", None, "GET").get("conversation") or {}
|
||||
print("消息数:", len(full.get("messages") or []))
|
||||
print("ended:", full.get("ended"))
|
||||
|
||||
# 把 provider 恢复成默认(e2e 测试里改过)
|
||||
#
|
||||
# ★ 不能只传空串:内核保存时会把空值过滤掉,于是 baseUrl/model 留在假服务上,
|
||||
# 用户打开 App 会发现"模型指着 127.0.0.1:18080"而一脸懵。
|
||||
# ★ 也没有 GET /api/settings(404)—— 读当前设置要用 /api/state。
|
||||
st = call("/api/state", None, "GET")
|
||||
s = dict(st.get("settings") or {})
|
||||
s.pop("baseUrl", None)
|
||||
s.pop("model", None)
|
||||
s.pop("apiKey", None)
|
||||
s["provider"] = "ark"
|
||||
call("/api/settings", s, "PUT")
|
||||
after = (call("/api/state", None, "GET").get("settings") or {})
|
||||
print("provider:", after.get("provider"),
|
||||
"| baseUrl:", repr(after.get("baseUrl")),
|
||||
"| model:", repr(after.get("model")))
|
||||
q = call("/api/ui-result?conversationId=c_main", None, "GET")
|
||||
print("待交付队列:", q)
|
||||
47
scripts/probe-reset-provider.py
Normal file
47
scripts/probe-reset-provider.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""把模拟器上的 provider 配置恢复成默认(e2e 测试把内核指到假服务上过)。"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
K = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(p, d=None, m="POST"):
|
||||
b = json.dumps(d, ensure_ascii=False).encode() if d is not None else None
|
||||
r = urllib.request.Request(
|
||||
K + p, data=b, method=m, headers={"Content-Type": "application/json; charset=utf-8"}
|
||||
)
|
||||
return json.loads(urllib.request.urlopen(r, timeout=30).read().decode())
|
||||
|
||||
|
||||
st = call("/api/state", None, "GET")
|
||||
s = st.get("settings") or {}
|
||||
print("改之前:")
|
||||
for k in ("provider", "baseUrl", "model", "apiKey", "hasApiKey"):
|
||||
print(f" {k} = {s.get(k)!r}")
|
||||
|
||||
# ★ 显式传 **null** 表示"我要清掉它"。
|
||||
# 传空串是不行的 —— 内核把空串当"没填、别动"(那个保险是为了防
|
||||
# "前端草稿没初始化好,一次保存清空整份配置")。
|
||||
# 两条路语义不同:空串 = 没填,null = 确实要清。
|
||||
res = call("/api/settings", {
|
||||
"provider": "ark",
|
||||
"baseUrl": None,
|
||||
"model": None,
|
||||
"apiKey": None,
|
||||
}, "PUT")
|
||||
after = (res.get("settings") or {})
|
||||
print("PUT(传 null)之后:")
|
||||
for k in ("provider", "baseUrl", "model"):
|
||||
print(f" {k} = {after.get(k)!r}")
|
||||
|
||||
st2 = call("/api/state", None, "GET")
|
||||
s2 = st2.get("settings") or {}
|
||||
print("重新读 /api/state:")
|
||||
for k in ("provider", "baseUrl", "model", "hasApiKey"):
|
||||
print(f" {k} = {s2.get(k)!r}")
|
||||
98
scripts/probe-ui-result-e2e.py
Normal file
98
scripts/probe-ui-result-e2e.py
Normal file
@@ -0,0 +1,98 @@
|
||||
"""把内核指到假模型服务上,验证"界面上选的值"真的拼进了发给模型的消息里。
|
||||
|
||||
★ 为什么要这么绕:光看"队列空了"只能证明有人取走,证明不了它被拼进请求。
|
||||
真正要验的是**模型收到的 messages 数组里有没有那段上下文**。
|
||||
所以起一个假服务,把请求原样存下来,然后直接读它。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
KERNEL = "http://127.0.0.1:15199"
|
||||
CAPTURE = r"C:\DoubaoAndroid\fake-req.json"
|
||||
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(
|
||||
KERNEL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
print("1) 把内核指到假模型服务")
|
||||
# ★ 关键:内核跑在**模拟器里**,它的 127.0.0.1 是自己,不是宿主机。
|
||||
# 两种打通方式:
|
||||
# · `adb reverse tcp:18080 tcp:18080` —— 模拟器的 18080 转到宿主机(**用这个**)
|
||||
# · 10.0.2.2 —— 只在标准 AVD 上有效,LDPlayer 不一定通
|
||||
# 实测 LDPlayer 上 `10.0.2.2` 连不上(假服务一个请求都没收到,
|
||||
# 很容易误判成代码有问题),所以用 adb reverse + 127.0.0.1。
|
||||
FAKE = "http://127.0.0.1:18080/v1"
|
||||
res = call("/api/settings", {
|
||||
"provider": "openai",
|
||||
"baseUrl": FAKE,
|
||||
"model": "fake-model",
|
||||
"apiKey": "sk-fake",
|
||||
}, method="PUT")
|
||||
st = res.get("settings") or {}
|
||||
print(" provider =", st.get("provider"), "| baseUrl =", st.get("baseUrl"),
|
||||
"| model =", st.get("model"))
|
||||
|
||||
print("\n2) 塞两个'界面上的选择'")
|
||||
for v in ("用户选了方案 B(蓝色按钮)", "用户填写了:预算 3000 元"):
|
||||
r = call("/api/ui-result", {"conversationId": CONV, "value": v})
|
||||
print(" ", v, "->", json.dumps(r, ensure_ascii=False))
|
||||
q = call(f"/api/ui-result?conversationId={CONV}", method="GET")
|
||||
print(" 队列:", json.dumps(q, ensure_ascii=False))
|
||||
|
||||
print("\n3) 发一句话,看模型收到什么")
|
||||
try:
|
||||
call("/api/chat", {"conversationId": CONV, "message": "我刚才在界面上选了什么?", "stream": False},
|
||||
timeout=120)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(" (内核返回不是 JSON,正常 —— 它走 SSE):", str(exc)[:80])
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
print("\n4) 假服务收到了什么")
|
||||
try:
|
||||
with open(CAPTURE, encoding="utf-8") as fh:
|
||||
cap = json.load(fh)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(" !! 读不到抓包:", exc)
|
||||
sys.exit(1)
|
||||
|
||||
msgs = (cap.get("body") or {}).get("messages") or []
|
||||
print(f" 路径 {cap.get('path')},共 {len(msgs)} 条消息")
|
||||
ok = False
|
||||
for m in msgs:
|
||||
role = m.get("role")
|
||||
content = m.get("content")
|
||||
if isinstance(content, list):
|
||||
content = " ".join(c.get("text", "") for c in content if isinstance(c, dict))
|
||||
text = content or ""
|
||||
mark = ""
|
||||
if "方案 B" in text or "预算 3000" in text:
|
||||
mark = " ← ★ 这就是回流进去的"
|
||||
ok = True
|
||||
print(f" [{role}] {text[:300]}{mark}")
|
||||
|
||||
print()
|
||||
if ok:
|
||||
print("✅ 界面上选的值**确实拼进了发给模型的请求**")
|
||||
else:
|
||||
print("❌ 请求里没有那些值 —— 回流链路断了")
|
||||
sys.exit(1)
|
||||
|
||||
# 收尾:把 provider 设回去,别把用户配置留在假服务上
|
||||
call("/api/settings", {"provider": "ark", "baseUrl": "", "model": "", "apiKey": ""}, method="PUT")
|
||||
print("(已把 provider 恢复成 ark)")
|
||||
115
scripts/probe-ui-result.py
Normal file
115
scripts/probe-ui-result.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""测「AI 写进网页里的接口」——用户在 AI 自己的界面里选的值能不能回到模型。
|
||||
|
||||
三步:
|
||||
1. 用 show_ui 弹一个界面,页面里有 Doubao.sendToAi / Doubao.pick / Doubao.close
|
||||
2. (手动)在手机上点那些按钮
|
||||
3. 查内核队列 —— 值应该排在那里,等下一轮对话交给模型
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
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"
|
||||
|
||||
HTML = """
|
||||
<h1>接口测试</h1>
|
||||
<p>点下面的按钮,值应该会回到 AI 手里(下一轮对话时)。</p>
|
||||
|
||||
<div id="log" style="margin:12px 0;padding:10px;background:#1d1f25;border-radius:8px;
|
||||
font-size:13px;color:#8c939d">(还没点)</div>
|
||||
|
||||
<button onclick="hit('sendToAi', '方案B')"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#2b7bff;color:#fff;font-size:16px">Doubao.sendToAi('方案B')</button>
|
||||
|
||||
<button onclick="hit('pick', '方案C')"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#2a2d34;color:#e8eaed;font-size:16px">Doubao.pick('方案C')</button>
|
||||
|
||||
<button data-doubao-result="方案D"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#2a2d34;color:#e8eaed;font-size:16px">data-doubao-result="方案D"(不写 JS)</button>
|
||||
|
||||
<button onclick="Doubao.close()"
|
||||
style="display:block;width:100%;margin:8px 0;padding:14px;border:0;border-radius:10px;
|
||||
background:#3a2a2a;color:#e8eaed;font-size:16px">Doubao.close()</button>
|
||||
|
||||
<script>
|
||||
function hit(fn, v) {
|
||||
var el = document.getElementById('log');
|
||||
try {
|
||||
Doubao[fn](v);
|
||||
el.textContent = '已调 Doubao.' + fn + '("' + v + '") —— 应该已经排队了';
|
||||
el.style.color = '#6ee787';
|
||||
} catch (e) {
|
||||
el.textContent = '调用失败:' + e;
|
||||
el.style.color = '#ff7b72';
|
||||
}
|
||||
}
|
||||
document.getElementById('log').textContent =
|
||||
'typeof Doubao = ' + (typeof Doubao);
|
||||
</script>
|
||||
"""
|
||||
|
||||
|
||||
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"},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
|
||||
|
||||
which = sys.argv[1] if len(sys.argv) > 1 else "show"
|
||||
|
||||
if which == "show":
|
||||
# 打开界面能力(否则工具被第二道拦截挡住)
|
||||
call("/api/settings", {"uiTools": {"enabled": True}}, method="PUT")
|
||||
res = call("/api/tools/run", {
|
||||
"name": "show_ui",
|
||||
"args": {"title": "接口测试", "html": HTML},
|
||||
"conversationId": CONV,
|
||||
})
|
||||
print("show_ui ->", json.dumps(res, ensure_ascii=False)[:200])
|
||||
print("\n现在去手机上点按钮,然后跑:")
|
||||
print(" python scripts/probe-ui-result.py check")
|
||||
print(" python scripts/probe-ui-result.py send # 发一句话,看模型能不能看到那些值")
|
||||
|
||||
elif which == "check":
|
||||
q = call(f"/api/ui-result?conversationId={CONV}", method="GET")
|
||||
print("队列里现在有:", json.dumps(q, ensure_ascii=False))
|
||||
n = len(q.get("pending") or [])
|
||||
print(f" {n} 条" + (" ✓ 回流成功" if n else " ✗ 一条都没有 —— 回流没成功"))
|
||||
|
||||
elif which == "send":
|
||||
# 发一句话,触发一轮对话;agent_loop 会把队列里的值带上
|
||||
#
|
||||
# ★ 不需要真的配 API key:我们要验证的是"队列有没有被取走、有没有拼进
|
||||
# 发给模型的消息里"。模型调用失败是另一回事(会以 error 事件返回),
|
||||
# 而**取队列发生在调用之前** —— 所以看队列空了就说明接上了。
|
||||
print("发一句话(触发一轮对话)…")
|
||||
try:
|
||||
res = call("/api/chat", {
|
||||
"conversationId": CONV,
|
||||
"message": "我刚才选了什么?",
|
||||
"stream": False,
|
||||
}, timeout=180)
|
||||
print(json.dumps(res, ensure_ascii=False)[:800])
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print("请求失败(可能是没配 API key,不影响本项验证):", exc)
|
||||
|
||||
q = call(f"/api/ui-result?conversationId={CONV}", method="GET")
|
||||
n = len(q.get("pending") or [])
|
||||
print("\n发完之后队列:", json.dumps(q, ensure_ascii=False))
|
||||
if n == 0:
|
||||
print(" ✓ 队列被取走了 —— 接进上下文了")
|
||||
else:
|
||||
print(f" ✗ 队列还有 {n} 条 —— 没被取走,回流链路断了")
|
||||
@@ -150,13 +150,19 @@ else:
|
||||
fail("没有 canGoBack")
|
||||
|
||||
# ---------------------------------------------------------------- 6
|
||||
print("\n[6] 桥只暴露两个方法(面越小越安全)")
|
||||
host = re.search(r"class AiWebHost[\s\S]*?\n\}", code)
|
||||
print("\n[6] 桥只暴露必要的方法(面越小越安全)")
|
||||
methods = re.findall(r"@JavascriptInterface\s+(?:override\s+)?fun\s+(\w+)", code)
|
||||
if sorted(methods) == ["close", "pick"]:
|
||||
ok(f"只有 {methods}(正好两个)")
|
||||
# ★ 期望集**显式列出**,加方法必须改这里 —— 这是刻意的:
|
||||
# 不这样的话"顺手多加一个 @JavascriptInterface"就没人拦得住,而桥的暴露面
|
||||
# 正是这块最该盯的东西。
|
||||
# v2.0.37 加了 sendToAi(用户要求"AI 自己能写进网页里的接口",
|
||||
# 让界面上选的值真的回到模型手里),所以现在是三个而不是两个。
|
||||
EXPECTED = ["close", "pick", "sendToAi"]
|
||||
if sorted(methods) == sorted(EXPECTED):
|
||||
ok(f"只有 {methods}(正好是期望的三个)")
|
||||
else:
|
||||
fail(f"@JavascriptInterface 暴露了 {methods} —— 应该只有 pick/close")
|
||||
fail(f"@JavascriptInterface 暴露了 {methods} —— 期望 {EXPECTED}。"
|
||||
"如果是**有意**加的,请同时更新这个 EXPECTED 列表并写清理由")
|
||||
|
||||
print()
|
||||
if fails:
|
||||
|
||||
Reference in New Issue
Block a user