Files
doubao-clone/tools/ask_user.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

153 lines
5.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 这边就是一次普通调用,不需要轮询。
★ 超时必须有:用户可能把手机锁屏走了,不能让内核线程永远挂着。
默认 120 秒,到点返回 `timeout: true`,模型据此知道"用户没理我"。
## 电脑端
明确返回不可用(桌面版的界面在桌面窗口里)。
"""
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
# 等用户的秒数上限。安卓侧也有自己的上限,两边都不设的话
# 用户锁屏走了会把内核的工作线程永远占住。
TIMEOUT_S = 120
TOOL = {
"name": "ask_user",
"description": (
"弹一个选择弹窗问用户,**等用户选完**再继续(最多等 120 秒)。"
"适合:几个方案让人挑一个、要确认一个危险操作、需要用户补充一个选择。"
"options 传选项数组(每项 {label, value, description}):"
"label 是按钮上显示的字,value 是你要拿到的值(留空则用 label),"
"description 是选项下方的小字说明。"
"多选请传 multiple=true。返回里 choice/values 就是用户选的东西;"
"timeout=true 表示用户没在时限内回答。"
),
"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",
},
},
"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 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
res = call_device(
{
"action": "ui_dialog",
"question": question,
"options": options,
"multiple": bool(args.get("multiple")),
"allowCancel": bool(args.get("allow_cancel", True)),
"timeoutMs": TIMEOUT_S * 1000,
"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 个"
return out
if __name__ == "__main__":
serve(TOOL, run)