Files
doubao-clone/tools/ask_user.py
l c7fed95650 feat: 所有超时收成一份、全部可调(设置 → 超时,18 项)
用户要求"全部超时做成可调"。改造前 15 个超时散在 10 个文件里当模块级常量,
说不清一共有几个,也答不了"哪些能调"。

内核
- 新增 android/kernel/timeouts.py:**超时的唯一一份定义**(DEFAULT + SPECS),
  带每项的 名字/分组/说明/默认值/上下界;get() 一律夹取,用户填什么都不炸
- 新增 GET/POST /api/timeouts(清单 + 当前值 + 保存 + 恢复默认)
- 各处改现读:tools_runtime(tool)、builtin_tools(shell/pythonRun)、
  doubao_entry(termux)、providers(model)、speech(tts/stt)、
  mcp_client(请求/连接/调用)、meeting(meetingNode)、custom_nodes(customNode)、
  app.py 的 SSE 心跳
- ask_user / show_ui 用 TIMEOUT_KEYS 声明"哪个参数该用设置里的值",
  内核调用前注入(工具的默认值退化成单独跑时的兜底)
- store.py:timeouts 走**整体替换**而不是深合并 —— 深合并会让"改回默认"删不掉

安卓
- data/AppTimeouts.kt:客户端缓存(OkHttp 的 readTimeout、文件选择没法现问内核)
- KernelClient:readTimeout 跟着 sseRead 走,改完重建连接池;新增 timeouts 接口
- ui/TimeoutsScreen.kt:全屏界面,按分组列出、-/+ 与输入框、恢复默认
- 设置页加「超时」卡片入口;NativeBridge 的本地接口请求 / 选文件等待接上
- Settings 模型加 TimeoutItem / TimeoutsState(字段全部来自内核)

Node 端(Web/exe)
- 新增 server/src/timeouts.mjs(和 Python 那份逐字对应)
- config.mjs 加 timeouts(同样整体替换);speech / python-tools / mcp / providers
  各处改读;index.mjs 加 /api/timeouts

验证
- 新增 scripts/verify-timeouts.py:清单完整性、边界容错(文字/空串/负数/超大值/
  带单位/None)、**扫内核有没有漏网的硬编码超时**(带白名单)、
  工具侧声明、以及和 Node 端逐项对拍
- 实测真机:界面显示 18 项来自内核 → 点 + 保存 → 内核 heartbeat 15→25 →
  恢复默认 → 回 15;askUser 显示"不限时"

文档:README §3.13;docs/AI界面能力.md 的"不限时要三处一起改"补上可调入口。
版本 2.0.46。
2026-10-16 10:29:46 +08:00

214 lines
8.5 KiB
Python
Raw 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 的分工
`show_ui` 展示用 —— **不阻塞**,弹出来就返回,用户看完自己关
`ask_user` 问询用 —— **阻塞**,等用户选完才返回,模型拿到选择继续干活
这两个刻意分开:展示性的东西不该把对话卡住;而"让用户在几个方案里选一个"
必须拿到答案才能继续。
## 阻塞是怎么实现的
安卓侧 `NativeBridge.device()` 是同步的 —— 它在 UI 线程上弹出界面,
然后用一个 `CountDownLatch` 等用户点,等到(或超时)才把结果回给 Python。
Python 这边就是一次普通调用,不需要轮询。
## ★★ 不限时(用户明确要求:"AI 询问界面不要限时")
`TIMEOUT_S = 0` 表示**一直等**。原来默认 120 秒,问题很实在:
· 用户看到选项、去翻了下手机算个数、回来弹窗没了;
· 模型收到 `timeout=true`,理解成"用户不想理我",于是自说自话往下走;
· 用户回来发现 AI 已经按它自己猜的答案干完了 —— 这一轮整个废掉。
"等用户回答"这件事本来就不该有截止时间:**要问就好好等,不想等就别问**。
所以默认无限等,模型真想限时得自己传 `timeout`(有上限,见下)。
放行的出口(不会死锁):点任意选项 / 点「取消」/ 关掉 App。
## 电脑端
明确返回不可用(桌面版的界面在桌面窗口里)。
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _protocol import serve # noqa: E402
from _ui_bridge import call_device, conversation_id # noqa: E402
# 等用户的秒数。**0 = 不限时**(默认,也是设置里的默认值)。
#
# ★ 这只是"工具单独跑"时的兜底 —— 真正生效的值来自设置
# (设置 → 超时 → AI 提问等多久)。内核调用前会把它注入到 args['timeout'] 里,
# 见 tools_runtime._with_default_timeouts 和下面的 TIMEOUT_KEYS。
TIMEOUT_S = 0
# 模型显式传 timeout 时的上限:1 小时。再长没有意义 ——
# 用户多半是走了,而内核那条 HTTP 工作线程会一直占着。
MAX_TIMEOUT_S = 3600
# ★★ 告诉内核:这个工具**会停下来等用户**,别拿工具执行超时卡它。
#
# 不声明的话后果很隐蔽:弹窗还开着(界面侧是不限时的),
# 但内核 60 秒就把这次调用判成"工具执行超时"、把结果丢掉了 ——
# 用户五分钟后点的那个选项**根本回不到模型手里**,模型已经开始自己编了。
# 见 android/kernel/tools_runtime.py 的 _waits_for_user。
WAIT_FOR_USER = True
# "我这个 timeout 参数如果模型没给,就用设置里 askUser 那一项的值"
TIMEOUT_KEYS = {'timeout': 'askUser'}
TOOL = {
"name": "ask_user",
"description": (
"弹一个选择弹窗问用户,**等用户选完**再继续(默认不限时,会一直等)。"
"适合:几个方案让人挑一个、要确认一个危险操作、需要用户补充一个选择。"
"options 传选项数组(每项 {label, value, description}):"
"label 是按钮上显示的字,value 是你要拿到的值(留空则用 label),"
"description 是选项下方的小字说明。"
"多选请传 multiple=true。返回里 choice/values 就是用户选的东西;"
"cancelled=true 表示用户点了取消,timeout=true 表示你显式设了 timeout 且等超了。"
"★ 默认一直等用户 —— 别在正文里催,也别自己替用户假设答案。"
),
"parameters": {
"type": "object",
"properties": {
"question": {
"type": "string",
"description": "要问的问题",
},
"options": {
"type": "array",
"description": "选项列表",
"items": {
"type": "object",
"properties": {
"label": {"type": "string", "description": "按钮上显示的文字"},
"value": {"type": "string", "description": "返回给模型的值,留空则用 label"},
"description": {"type": "string", "description": "选项下方的小字说明"},
},
"required": ["label"],
},
},
"multiple": {
"type": "boolean",
"description": "是否允许多选,默认 false",
},
"allow_cancel": {
"type": "boolean",
"description": "是否显示「取消」按钮,默认 true",
},
"timeout": {
"type": "number",
"description": (
"等用户的秒数。**默认 0 = 不限时**(推荐,别乱传)。"
f"只有确实需要「用户不在就算了」的场景才传,上限 {MAX_TIMEOUT_S} 秒。"
),
},
},
"required": ["question", "options"],
},
}
def _clean_options(raw) -> list:
"""
规整选项。
★ 模型经常把 options 写成裸字符串数组(`["A", "B"]`)而不是对象数组 ——
这在 tool calling 里非常常见,直接 `.get()` 会 AttributeError。
所以两种都收下,别让模型因为格式小错就吃一个报错。
"""
out = []
for item in raw or []:
if isinstance(item, dict):
label = str(item.get("label") or item.get("value") or "").strip()
if not label:
continue
out.append(
{
"label": label,
"value": str(item.get("value") or label),
"description": str(item.get("description") or ""),
}
)
elif isinstance(item, (str, int, float)):
text = str(item).strip()
if text:
out.append({"label": text, "value": text, "description": ""})
return out
def _timeout_ms(args: dict) -> int:
"""
算等多久。0 = 不限时。
★ 默认 0:模型不传就是一直等。这是刻意的 —— "问用户"这件事
没有一个合理的截止时间,120 秒的默认值只会制造"AI 不等我就自己决定"。
★ 模型传了才限时,并且夹在 [1, MAX_TIMEOUT_S]:传负数/0 会退化成"等 1 秒",
那是模型写错了,不该让它把弹窗变成一闪而过。
"""
raw = args.get("timeout")
if raw in (None, "", 0, "0"):
return TIMEOUT_S * 1000
try:
sec = float(raw)
except (TypeError, ValueError):
return TIMEOUT_S * 1000
if sec <= 0:
return TIMEOUT_S * 1000
return int(max(1.0, min(float(MAX_TIMEOUT_S), sec)) * 1000)
def run(args: dict) -> dict:
question = str(args.get("question") or "").strip()
if not question:
raise ValueError("question 不能为空")
options = _clean_options(args.get("options"))
if not options:
raise ValueError("options 至少要给一个选项")
# 选项太多按钮会挤成一屏,截断并告诉模型(而不是静默丢掉)
truncated = False
if len(options) > 8:
options = options[:8]
truncated = True
timeout_ms = _timeout_ms(args)
res = call_device(
{
"action": "ui_dialog",
"question": question,
"options": options,
"multiple": bool(args.get("multiple")),
"allowCancel": bool(args.get("allow_cancel", True)),
"timeoutMs": timeout_ms,
"conversationId": conversation_id(),
}
)
if res.get("unavailable"):
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
if res.get("error"):
raise RuntimeError(str(res["error"]))
out = {
"question": question,
"multiple": bool(res.get("multiple")),
"timeout": bool(res.get("timeout")),
"cancelled": bool(res.get("cancelled")),
"choice": res.get("choice") or "",
"values": res.get("values") or [],
}
if truncated:
out["note"] = "选项超过 8 个,只显示了前 8 个"
# ★ 用户点了取消:不是"没回答",别让模型以为可以照自己的意思继续
if out["cancelled"]:
out["note"] = "用户点了取消,不想在这几个选项里选。停下来问他想怎么做,别自己替他决定。"
return out
if __name__ == "__main__":
serve(TOOL, run)