Files
doubao-clone/scripts/verify-ui-tools.py
doubao 52680b9eb7 AI 界面能力:主动弹界面 / 弹窗 / 永久结束对话 (v2.0.35)
三个工具,**默认关**(「技能」页可开)。都是 AI 主动驱动界面,
属于"打扰性"能力 —— 装好就默认打开是产品事故。

## show_ui —— AI 自己写 HTML 弹一个全屏界面

有些东西用文字说不清:一张算出来的图表、排版好的报告卡片、宽对比表。
以前模型只能吐 markdown,表格一宽就乱。现在它能直接写 HTML。

  · html 写**片段**即可,自动套一层带样式的骨架(暗色主题、表格、代码块),
    模型不用每次重复写 viewport/字体/边距;想完全控制传 full_html=true
  · **不阻塞**:弹出来就返回,用户看完自己关(展示语义,不该卡住对话)
  · 界面里可以放 `<button data-doubao-result="值">`,用户点了那个值回到模型手里

★ 两个安全决定:
  1. **禁 JS**。允许 JS 的话模型生成的一段脚本就能拿到 `@JavascriptInterface`
     那个桥,等于把 App 内部接口暴露给模型。纯 CSS 足够渲染内容。
  2. **可点按钮不用 JS**:App 侧把 `data-doubao-result` 做**纯字符串替换**,
     改成 `doubao://pick?value=...` 链接,由 WebViewClient 拦下来。

## ask_user —— 弹选择框,等用户选完再继续

  · **阻塞**(最多 120 秒):问询语义,必须拿到答案才能继续。
    安卓侧用 CountDownLatch 等,跟已有的 pickFile 同一套路。
  · 超时必须有 —— 用户可能锁屏走了,不能让内核工作线程永远挂着
  · options 两种写法都收:对象数组 `[{label,value,description}]`
    和**裸字符串数组** `["A","B"]`(模型经常这么写,只认一种就平白报错)
  · 支持多选(multiple=true),选项超过 8 个自动截断并告诉模型

## end_conversation —— 永久结束这次对话

**用户明确要求的界面**:屏幕中间一个横幅,写 AI 关闭的原因。

  · 落盘(PATCH /api/conversations/<id> 写 `ended` / `endedReason`),
    不是界面状态 —— 只放 Compose 里的话一刷新就没了,用户重进会看到
    一个能继续输入的框,而模型以为自己已经结束了
  · 输入框整个不渲染,换成居中的横幅:「这次对话已结束」+ 原因 + 「开始新对话」
  · 拿不到对话 id 时**明确报错**,绝不假装成功

## 动画(用户要求)

  · HTML 界面:从中心长大 + 淡入(像开一扇门),退出反向
  · 选择弹窗:从下方滑上来 + 淡入 + 轻微放大;遮罩淡入
  · 结束横幅:从下方滑到**屏幕中间**停住 + 淡入 + 轻微放大,**不自动消失**
    (它是状态不是提示,消失了用户就不知道为什么发不出消息)
  · 选项选中:弹性放大 + 蓝底 + 勾

## 开关(两道拦截)

  settings.uiTools.enabled,默认 false。
  ① 关掉时工具**对模型隐藏**(build_tool_defs 里滤掉)
  ② 关掉时即使模型硬编名字**也拒绝执行** —— 只做①的话,用户关掉之后
     模型仍可能从历史消息里学会这个名字再调一次
  界面能力的用法说明**只在开关打开时**才追加到系统提示词 —— 写进
  DEFAULT_SYSTEM_PROMPT 的话会被存进用户的 settings.json,
  关着的时候还在教模型"你可以用 show_ui"。

## 顺带修的两个真 bug

1. **thread-local 不跨线程**(这个最隐蔽)
   `run_with_timeout` 把工具丢到**新线程**里跑,而 `threading.local()`
   不跨线程继承 —— 于是工具照常执行(参数都对),只有"当前是哪次对话"
   拿不到,`end_conversation` 报"拿不到当前对话 id"。
   我一开始以为是 app.py 没传 conversationId,查了一圈才发现是线程。
   修法:`run_python_tool` 执行前把父线程的上下文搬进工作线程。

2. **/api/tools/run 传的是假 settings**
   以前传 `{'security': {'mode': 'open'}}` 空壳(为了"手动试运行不受安全模式
   限制"),但界面工具的开关也在 settings 里 —— 于是用户在技能页点"试运行",
   明明开关是开的却收到"已关闭"。改成拿真实设置、只覆盖 security。

## 验证

`scripts/verify-ui-tools.py`(34 项)守:开关默认关、两道拦截都在、
选项两种写法都收、拿不到对话 id 必须报错、**上下文能跨线程**、
提示词按开关追加。`scripts/probe-ai-surfaces.py` 打
`adb forward` 之后的内核接口做端到端。

真机实测(Android 14 x86_64):
  show_ui        → 界面渲染正常(标题栏 + 暗色表格 + 可点按钮)
  ask_user 单选   → 等 21s,返回 {"choice":"B","values":["B"],"timeout":false}
  ask_user 多选   → 选 2 个,返回 {"values":["python","git"]}
  end_conversation → ended=True 落盘,横幅显示原因
2026-10-14 15:36:52 +08:00

305 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""守 AI 界面三件套(show_ui / ask_user / end_conversation)的硬性质。
这些性质每一条都对应一个"想当然会出错"的地方,光看代码看不出来:
1. **开关默认关**。这三个工具会让 AI 主动往用户脸上弹东西、甚至封掉对话,
默认打开是产品事故。而且必须**默认关**(新装/老设备升上来都是关)。
2. **两道拦截都要在**:关掉时① 工具对模型隐藏,② 即使模型硬编名字也拒绝执行。
只做①的话,用户关掉之后模型仍可能从历史消息里学会这个名字再调一次。
3. **ask_user 的 options 两种写法都要收**(对象数组 / 裸字符串数组)——
模型写裸字符串数组非常常见,只认一种就会平白吃一个报错。
4. **end_conversation 拿不到对话 id 时必须报错,不能假装成功** ——
假装成功会变成"界面封了、盘上没封",用户重启后又能发消息。
5. **不占用户的消息预算**:这几个工具的规则不能渗进系统提示词的
"回答要求"编号里(那会让模型把它们当成每轮都要考虑的事)。
用法:
python scripts/verify-ui-tools.py
"""
import json
import os
import sys
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
KERNEL = os.path.join(WS, "android", "kernel")
TOOLS = os.path.join(WS, "tools")
sys.path.insert(0, KERNEL)
sys.path.insert(0, TOOLS)
fails = []
def fail(m):
fails.append(m)
print(f" ✗ {m}")
def ok(m):
print(f" ✓ {m}")
# ---------------------------------------------------------------- 1
print("=== 1. 工具能被发现,spec 合法 ===")
import importlib.util
for name in ("show_ui", "ask_user", "end_conversation"):
path = os.path.join(TOOLS, name + ".py")
if not os.path.isfile(path):
fail(f"{name}.py 不存在")
continue
spec = importlib.util.spec_from_file_location("t_" + name, path)
mod = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(mod)
except Exception as exc: # noqa: BLE001
fail(f"{name}.py 导入失败:{type(exc).__name__}: {exc}")
continue
tool = getattr(mod, "TOOL", None)
if not isinstance(tool, dict) or not tool.get("name"):
fail(f"{name}.py 没有合法的 TOOL")
continue
if not callable(getattr(mod, "run", None)):
fail(f"{name}.py 没有 run(args)")
continue
if tool["name"] != name:
fail(f"{name}.py 的 TOOL.name 是 {tool['name']},和文件名不一致")
continue
params = tool.get("parameters") or {}
if params.get("type") != "object":
fail(f"{name} 的 parameters.type 不是 object")
continue
ok(f"{name}:spec 合法(必填 {params.get('required') or '无'})")
# ---------------------------------------------------------------- 2
print("\n=== 2. 开关默认关 + 两道拦截 ===")
import tools_runtime as TR
if TR.ui_tools_enabled({}):
fail("空 settings 时 ui_tools_enabled 竟然是 True —— 默认必须关")
else:
ok("空 settings → 关闭")
if TR.ui_tools_enabled({"uiTools": {"enabled": True}}):
ok("uiTools.enabled=True → 打开")
else:
fail("uiTools.enabled=True 没被认成打开")
if TR.ui_tools_enabled({"uiTools": True}):
ok("uiTools=True(老写法)→ 也认")
else:
fail("uiTools=True 没被认(兼容写法失效)")
# ① 关掉时对模型隐藏
defs_off = TR.filter_ui_tools([{"name": n} for n in TR.UI_TOOLS], {})
if defs_off:
fail(f"关闭时仍把 {[d['name'] for d in defs_off]} 给了模型")
else:
ok("关闭时三个工具对模型隐藏")
defs_on = TR.filter_ui_tools([{"name": n} for n in TR.UI_TOOLS], {"uiTools": {"enabled": True}})
if len(defs_on) == len(TR.UI_TOOLS):
ok("打开时三个工具都给模型")
else:
fail(f"打开时只给了 {len(defs_on)} 个")
# ② 关掉时即使硬编名字也拒绝
res = TR.execute_tool("ask_user", {"question": "x", "options": ["a"]}, {})
if res.get("ok") is False and "关闭" in str(res.get("error")):
ok("关闭时 execute_tool 拒绝执行(第二道拦截在)")
else:
fail(f"关闭时 execute_tool 没拦住:{res}")
# ---------------------------------------------------------------- 3
print("\n=== 3. ask_user 的选项规整 ===")
import ask_user as AU
cases = [
(["A", "B"], 2, "裸字符串数组"),
([{"label": "A"}, {"label": "B", "value": "b"}], 2, "对象数组"),
([{"value": "only"}], 1, "只有 value 没有 label"),
([{"label": "A", "description": "说明"}], 1, "带 description"),
(["A", {"label": ""}, " ", "B"], 2, "混杂空项(应被丢掉)"),
([], 0, "空数组"),
]
for raw, want, label in cases:
got = AU._clean_options(raw)
if len(got) == want:
ok(f"{label} → {len(got)} 项")
else:
fail(f"{label}:期望 {want} 项,实际 {len(got)} 项({got})")
opts = AU._clean_options([{"label": "A"}])
if opts and opts[0]["value"] == "A":
ok("value 留空时自动用 label")
else:
fail(f"value 没回落到 label:{opts}")
# 超过 8 个要截断
many = AU._clean_options([f"opt{i}" for i in range(20)])
if len(many) == 20:
ok("规整阶段不截断(截断在 run 里做)")
else:
fail(f"规整阶段就把选项截了:{len(many)}")
# ---------------------------------------------------------------- 4
print("\n=== 4. 拿不到对话 id 时必须报错 ===")
import _ui_bridge as UB
# 不在工具调用上下文里 → conversation_id() 应该是空
UB_ctx = TR.current_context()
if UB_ctx == {}:
ok("不在调用中时 current_context() 是空 dict")
else:
fail(f"current_context() 不是空的:{UB_ctx}")
# push 之后能读到
TR.push_context(conversationId="c_test", toolName="end_conversation")
if TR.current_context().get("conversationId") == "c_test":
ok("push_context 之后能读到 conversationId")
else:
fail(f"push_context 没生效:{TR.current_context()}")
# ★★★ 关键:**上下文必须能跨线程** —— run_with_timeout 是在新线程里跑工具的,
# 而 threading.local() 不跨线程继承。这里直接验"另一个线程里读得到"。
import threading
seen = {}
def _in_other_thread():
seen["ctx"] = TR.current_context()
worker = threading.Thread(target=_in_other_thread)
worker.start()
worker.join(5)
if seen.get("ctx") == {}:
ok("另一个线程里读不到(符合 thread-local 语义 —— 所以必须显式搬过去)")
else:
fail(f"另一个线程里读到了东西,语义和预期不符:{seen.get('ctx')}")
TR.clear_context()
if TR.current_context() == {}:
ok("clear_context 之后读不到了")
else:
fail("clear_context 之后还能读到")
# ---------------------------------------------------------------- 5
print("\n=== 5. 工具真的执行时,上下文能送到工具手里 ===")
# 造一个假工具:它把读到的上下文写进返回值。
#
# ★★ 必须走 **run_python_tool** 这条真实路径 —— 它内部会调 run_with_timeout,
# 而那个函数是在**新线程**里跑工具的。第一版验证脚本图省事直接调了
# run_with_timeout(lambda: mod.run(...)),绕开了被修的那段代码,
# 于是"修好了没有"根本没测到(脚本报红但红得不是地方)。
# 教训:验证要走**调用方真正走的那条路**。
probe_src = '''
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
TOOL = {"name": "probe_ctx", "description": "探针",
"parameters": {"type": "object", "properties": {}}}
def run(args):
import tools_runtime as TR
import _ui_bridge as UB
return {"ctx": TR.current_context(), "conv": UB.conversation_id()}
'''
import tempfile
tmpdir = tempfile.mkdtemp()
open(os.path.join(tmpdir, "probe_ctx.py"), "w", encoding="utf-8").write(probe_src)
# 让 tools_runtime 去 tmpdir 里找工具(改的是 `paths.get().tools_dir`,
# 不动用户真正的工具目录)
import paths as P
_orig_tools_dir = P.get().tools_dir
P.get().tools_dir = tmpdir
TR.discover_python_tools(force=True)
try:
TR.push_context(conversationId="c_from_parent", toolName="probe_ctx")
try:
res = TR.run_python_tool("probe_ctx", {})
finally:
TR.clear_context()
finally:
P.get().tools_dir = _orig_tools_dir
TR.discover_python_tools(force=True)
got = (res or {}).get("result") if isinstance(res, dict) else None
if not isinstance(got, dict):
fail(f"探针没返回 dict:{res}")
else:
if got.get("conv") == "c_from_parent":
ok("换线程之后工具仍拿得到 conversationId(修好了)")
else:
fail(f"换线程之后 conversationId 丢了:{got}")
# end_conversation.run 在没有对话 id 时应该抛错(而不是返回 ended:True)
import end_conversation as EC
try:
# 桥不在(电脑端)会先抛"没有界面能力",两种都算"没假装成功"
out = EC.run({"reason": "测试"})
if out.get("ended") is True:
fail("没有对话 id 却报 ended=True —— 这是最坏的失败模式(界面封了、盘上没封)")
else:
ok(f"没有对话 id 时没假装成功:{out}")
except Exception as exc: # noqa: BLE001
ok(f"没有对话 id 时抛错(正确):{type(exc).__name__}")
# ---------------------------------------------------------------- 6
print("\n=== 6. 界面能力的提示词只在开关打开时追加 ===")
import defaults as D
prompt = D.DEFAULT_SYSTEM_PROMPT
if "show_ui" in prompt or "ask_user" in prompt or "end_conversation" in prompt:
fail("默认提示词里点名了界面工具 —— 开关关着时会误导模型去调")
else:
ok("默认提示词里没点名界面工具(开关管得住)")
if "附件" in prompt:
ok("附件说明还在(没被覆盖)")
else:
fail("附件说明不见了")
# 追加的那段:关着不该出现,开着必须在
import agent_loop as AL
if not hasattr(AL, "UI_TOOLS_HINT"):
fail("agent_loop 里没有 UI_TOOLS_HINT")
else:
hint = AL.UI_TOOLS_HINT
if "show_ui" in hint and "ask_user" in hint and "end_conversation" in hint:
ok("UI_TOOLS_HINT 里三个工具都讲到了")
else:
fail("UI_TOOLS_HINT 没覆盖三个工具")
if "必须先在正文里" in hint:
ok("提示了 end_conversation 要先说明(这条很重要)")
else:
fail("UI_TOOLS_HINT 没要求'结束前先说明'")
# ★ 追加逻辑必须**按开关**走。这里直接验证那段代码的存在性 +
# ui_tools_enabled 的语义(真正的拼接在 run_agent 里,需要起网络,不在这儿跑)。
import inspect
src = inspect.getsource(AL.run_agent)
if "ui_tools_enabled" in src and "UI_TOOLS_HINT" in src:
ok("run_agent 里是按开关决定要不要追加")
else:
fail("run_agent 没按开关追加提示词")
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")
for m in fails:
print(" -", m)
sys.exit(1)
print("✅ 全部通过")