用户要求"AI 询问界面不要限时"。v2.0.44 改了界面侧(AiSurface 无限等)和
工具侧(ask_user 的 timeout 默认 0),但**漏了内核的工具执行超时**:
实测:弹窗 135 秒确实还在,但工具调用在 60.0 秒返回
{"ok":false,"error":"工具执行超时(60s)"} —— 用户后来点的选项根本
回不到模型手里,模型已经拿着"超时"自己往下写了。
改动:
- builtin_tools.run_with_timeout:timeout_s <= 0 = 不限时(thread.join() 不带参)
- tools/ask_user.py、tools/show_ui.py:声明 WAIT_FOR_USER = True
- tools_runtime:新增 _waits_for_user(),会等用户的工具把超时预算设成 0;
普通工具仍是 60 秒(死循环的安全网没丢)
验证(scripts/probe-ask-user-forever.py,真机跑):
修之前 60.0 秒 → {"ok":false,"error":"工具执行超时(60s)"}
修之后 66.2 秒 → {"ok":true,"result":{...,"choice":"B","timeout":false}}
守门:scripts/verify-ui-tools.py 新增一节(声明在不在、豁免逻辑在不在、
预算 0 是不是真的无限等、普通工具的 60 秒还在不在)。
文档:docs/AI界面能力.md 补"不限时要三处一起改"和客户端长连接为什么不断
(15 秒心跳 vs 120 秒 readTimeout)。
版本 2.0.45。
375 lines
14 KiB
Python
375 lines
14 KiB
Python
"""守 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 没按开关追加提示词")
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# ★★ 会等用户的工具必须**豁免工具超时**
|
||
# --------------------------------------------------------------------------- #
|
||
# 用户要求"AI 询问界面不要限时"。这个需求**要三处一起改才算数**:
|
||
# ① 界面侧等多久(AiSurface.ask / showScreen)
|
||
# ② 内核侧给工具多少时间(tools_runtime 的 TOOL_TIMEOUT_S)
|
||
# ③ 工具自己声明的 timeout
|
||
# 只改 ①③ 的后果实测过:弹窗 135 秒还开着,**但工具调用 60 秒就被内核判超时**,
|
||
# 模型收到"工具执行超时(60s)",用户五分钟后点的选项根本回不到模型手里 ——
|
||
# 表现是"弹窗还在、AI 已经自己往下写了"。这种"看起来改了其实没生效"最坑,
|
||
# 所以在这里钉住。
|
||
print("\n=== 等用户的工具不被工具超时掐掉 ===")
|
||
|
||
import inspect # noqa: E402 - 上面那个分支里才 import,这里保证一定有
|
||
|
||
import tools_runtime as TR
|
||
|
||
for tool_name in ("ask_user", "show_ui"):
|
||
path = os.path.join(TOOLS, f"{tool_name}.py")
|
||
src = open(path, encoding="utf-8").read()
|
||
if "WAIT_FOR_USER = True" in src:
|
||
ok(f"{tool_name}.py 声明了 WAIT_FOR_USER = True")
|
||
else:
|
||
fail(f"{tool_name}.py 没声明 WAIT_FOR_USER —— 内核会在 60 秒时把这次调用判超时")
|
||
|
||
if hasattr(TR, "_waits_for_user"):
|
||
ok("tools_runtime 里有 _waits_for_user")
|
||
else:
|
||
fail("tools_runtime 没有 _waits_for_user,豁免逻辑不见了")
|
||
|
||
_src = inspect.getsource(TR.run_python_tool)
|
||
if "_waits_for_user" in _src and "budget" in _src:
|
||
ok("run_python_tool 是按它决定超时预算的")
|
||
else:
|
||
fail("run_python_tool 没用 _waits_for_user 决定预算")
|
||
|
||
# 引擎侧:0 必须真的等于"不限时"
|
||
import builtin_tools as BT
|
||
|
||
if "thread.join()" in inspect.getsource(BT.run_with_timeout):
|
||
ok("run_with_timeout 支持 timeout<=0 = 不限时")
|
||
else:
|
||
fail("run_with_timeout 不支持不限时(join 那支不见了)")
|
||
|
||
# 仿真一遍:给一个"永远不返回"的任务配 0 预算,它必须**不返回**
|
||
# (真跑起来要等到天荒地老,所以这里用一个 20ms 后自己结束的任务代替,
|
||
# 验证的是"0 走的是无限等待那支"而不是"0 立刻超时")
|
||
import threading as _th
|
||
|
||
_done = _th.Event()
|
||
|
||
|
||
def _slow():
|
||
_done.wait(0.05)
|
||
return "ok"
|
||
|
||
|
||
_r = BT.run_with_timeout(_slow, 0)
|
||
if _r == "ok":
|
||
ok("预算 0 时会一直等到任务真的跑完(不是立刻超时)")
|
||
else:
|
||
fail(f"预算 0 的行为不对,拿到 {_r!r}")
|
||
|
||
# 反面:非豁免工具仍然是 60 秒(安全网还在,别为了这个把超时全关了)
|
||
if TR.TOOL_TIMEOUT_S == 60:
|
||
ok("普通工具的超时还是 60 秒(死循环的安全网没丢)")
|
||
else:
|
||
fail(f"TOOL_TIMEOUT_S 被改成 {TR.TOOL_TIMEOUT_S},普通工具的兜底变了")
|
||
|
||
|
||
print()
|
||
if fails:
|
||
print(f"❌ {len(fails)} 项不合格:")
|
||
for m in fails:
|
||
print(" -", m)
|
||
sys.exit(1)
|
||
print("✅ 全部通过")
|