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 落盘,横幅显示原因
This commit is contained in:
doubao
2026-10-14 15:36:52 +08:00
parent 6197b726a5
commit 52680b9eb7
23 changed files with 2011 additions and 39 deletions

85
tools/_ui_bridge.py Normal file
View File

@@ -0,0 +1,85 @@
"""
界面工具(AI 主动弹界面 / 弹窗 / 结束对话)和安卓原生桥之间的公共部分。
## 为什么单独一个模块
三个工具干的事不同,但**和安卓那一侧通话的方式完全一样**:都是往
`NativeBridge.device()` 发一个 JSON、收一个 JSON。把这段收在一处,
以后加第四个界面工具就只要写 TOOL + run,不用再抄一遍桥接代码 ——
这个仓库里"同一个逻辑抄两份,加功能时只改一份"的坑已经踩过好几次了。
## 为什么要带 conversationId
`end_conversation` 要**永久结束当前这次对话**,内核必须知道是哪一次。
内核在组装工具前会把当前对话 id 塞进 settings 的 `_conversationId`
(下划线开头,不会外泄给模型,也不会出现在 /api/state 里),
这里取出来一起发给安卓侧。
## 电脑端会怎样
没有 `_android` 桥(桌面版)时,这几个工具都**明确返回不可用**,
而不是假装成功 —— 让模型知道"这个端没有界面能力",它就不会反复重试。
"""
import json
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def _bridge():
"""
拿到安卓原生桥对象;电脑端返回 None。
`doubao_entry` 只在安卓上存在(它是 Chaquopy 的入口模块),
所以这里用 try/except 而不是判断平台字符串 —— 平台字符串判断错过一次
(sys.platform 在 Chaquopy 里也是 'linux',跟桌面 Linux 分不开)。
"""
try:
import doubao_entry # noqa: PLC0415 - 电脑端没有这个模块,只能运行时导入
return getattr(doubao_entry, '_android', None)
except Exception: # noqa: BLE001
return None
def call_device(payload: dict) -> dict:
"""
往安卓侧发一个 device 请求。
★ 参数名要和 Kotlin 侧 `NativeBridge.device()` 的 `req.optString(...)`
对得上 —— 对不上不会报错,只会**静默拿到空字符串**,
表现是"界面弹出来但标题是空的"。所以两边都写全。
@return 安卓侧回的 JSON;桥不在时返回 {'unavailable': True, ...}
"""
bridge = _bridge()
if bridge is None:
return {
'unavailable': True,
'error': '当前环境没有界面能力(电脑端的界面在桌面窗口里,这几个工具只在手机上生效)',
}
raw = bridge.device(json.dumps(payload, ensure_ascii=False))
try:
return json.loads(str(raw))
except (ValueError, TypeError):
return {'raw': str(raw)}
def conversation_id() -> str:
"""
当前对话 id。
★ 从内核的"当前调用上下文"里取。`tools_runtime.execute_tool` 在调用工具前
会把 settings 里的 `_conversationId` 放到 `_protocol` 能读到的地方 ——
见 tools_runtime.current_context()。取不到就返回空串(安卓侧会当成
"没有指定对话",只是不能结束对话,别的功能不受影响)。
"""
try:
import tools_runtime # noqa: PLC0415
ctx = tools_runtime.current_context() or {}
return str(ctx.get('conversationId') or '')
except Exception: # noqa: BLE001
return ''

152
tools/ask_user.py Normal file
View File

@@ -0,0 +1,152 @@
"""让 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)

90
tools/end_conversation.py Normal file
View File

@@ -0,0 +1,90 @@
"""让 AI 主动**永久结束**当前这次对话。
## "永久"是什么意思
不是"这一轮说完了",而是这次对话就此封笔:
· 会话被标记 `ended`(落盘,重启 App 也还在)
· 界面上输入框变成「这次对话已结束」+ 一个「开始新对话」按钮
· 再往里发消息会被挡住(用户想继续就开新的)
## 模型什么时候该用
· 用户要的事情已经彻底办完,且没有后续可聊的("帮我查完这趟航班" → 结束)
· 用户自己说"就这样吧 / 不用了 / 结束"
· 任务走进了死胡同,继续聊下去只会兜圈子
★ 提示词里明确要求它**先说明再结束** —— 直接封笔会让人莫名其妙。
所以这个工具的 description 里写死了"要先在正文里说明已经结束"。
## 为什么要落盘而不是只改界面状态
界面状态一刷新就没了。用户关掉 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
TOOL = {
"name": "end_conversation",
"description": (
"**永久结束当前这次对话**(落盘,重启 App 也生效):之后再发消息会被挡住,"
"用户需要开一个新对话。"
"只在事情真的办完、用户说了不用了、或者继续聊只会兜圈子时才用。"
"★ 调用前必须先在正文里跟用户说明这次对话已经结束,别默默封笔。"
"reason 用一句话说明为什么结束(会给用户看)。"
),
"parameters": {
"type": "object",
"properties": {
"reason": {
"type": "string",
"description": "为什么结束(一句话,会给用户看)",
},
"summary": {
"type": "string",
"description": "这次对话做了什么(可选,留作记录)",
},
},
"required": ["reason"],
},
}
def run(args: dict) -> dict:
reason = str(args.get("reason") or "").strip()
if not reason:
raise ValueError("reason 不能为空(要告诉用户为什么结束)")
conv = conversation_id()
if not conv:
# 拿不到对话 id 时**不能假装成功** —— 那样界面封了、盘上没封,
# 用户重启后又能发消息,而模型以为自己结束了。
raise RuntimeError("拿不到当前对话 id,无法结束对话")
res = call_device(
{
"action": "end_conversation",
"conversationId": conv,
"reason": reason,
"summary": str(args.get("summary") or ""),
}
)
if res.get("unavailable"):
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
if res.get("error"):
raise RuntimeError(str(res["error"]))
return {
"ended": True,
"conversationId": conv,
"reason": reason,
"note": "这次对话已永久结束。用户需要开新对话才能继续。",
}
if __name__ == "__main__":
serve(TOOL, run)

89
tools/show_ui.py Normal file
View File

@@ -0,0 +1,89 @@
"""让 AI 主动弹出一个 WebView 界面(自己写 HTML)。
## 这个工具存在的意义
普通的对话是一来一回的文本。有些东西**用界面表达比用文字好得多**:
一张自己算出来的图表、一个把结果排版好的报告卡片、一个可以点的菜单、
一段带样式的对比表。以前模型只能吐 markdown,表格一宽就乱。
这个工具让模型**直接写 HTML**,App 用一个全屏 WebView 渲染出来。
## 用法约定(也是给模型看的)
· `html` 里写**片段**就行(不用 <html>/<body>),会自动套一层带样式的骨架 ——
这样模型不用每次重复写 viewport、暗色主题这些
· 想要完整控制就传 `full_html=true`,那时 html 必须是一份完整文档
· 界面里可以放按钮:`<button data-doubao-result="选了A">A</button>`
—— 用户点了之后,那个 `data-doubao-result` 的值会回到模型手里
(走 [ask_user] 那条回传通道,所以不需要模型自己写 JS)
## 电脑端
桌面版的界面在桌面窗口里,这个工具**明确返回不可用**,不假装成功。
"""
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
TOOL = {
"name": "show_ui",
"description": (
"在用户手机/平板上弹出一个界面,自己写 HTML 渲染(全屏 WebView)。"
"适合:图表、排版好的报告卡片、对比表、可点的菜单、任何用文字说不清的东西。"
"html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);"
"想完全控制就传 full_html=true。"
"界面里可以放 <button data-doubao-result=\"值\">文字</button>,"
"用户点了之后那个值会回到你手里。"
"调用后界面立刻显示、本工具立刻返回,用户看到之后再继续对话。"
),
"parameters": {
"type": "object",
"properties": {
"html": {
"type": "string",
"description": "要渲染的 HTML(片段即可,除非 full_html=true)",
},
"title": {
"type": "string",
"description": "顶部标题栏文字,可留空",
},
"full_html": {
"type": "boolean",
"description": "true 表示 html 是一份完整文档,不再套骨架。默认 false",
},
},
"required": ["html"],
},
}
def run(args: dict) -> dict:
html = str(args.get("html") or "").strip()
if not html:
raise ValueError("html 不能为空")
res = call_device(
{
"action": "ui_screen",
"html": html,
"title": str(args.get("title") or ""),
"full_html": bool(args.get("full_html")),
"conversationId": conversation_id(),
}
)
if res.get("unavailable"):
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
if res.get("error"):
raise RuntimeError(str(res["error"]))
return {
"shown": True,
"bytes": len(html),
"note": "界面已弹出,用户看完会自己关掉。你不需要再重复内容。",
}
if __name__ == "__main__":
serve(TOOL, run)