"""让 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 = 不限时**(默认)。 TIMEOUT_S = 0 # 模型显式传 timeout 时的上限:1 小时。再长没有意义 —— # 用户多半是走了,而内核那条 HTTP 工作线程会一直占着。 MAX_TIMEOUT_S = 3600 # ★★ 告诉内核:这个工具**会停下来等用户**,别拿 60 秒的工具超时卡它。 # # 不声明的话后果很隐蔽:弹窗还开着(界面侧是不限时的), # 但内核 60 秒就把这次调用判成"工具执行超时"、把结果丢掉了 —— # 用户五分钟后点的那个选项**根本回不到模型手里**,模型已经开始自己编了。 # 见 android/kernel/tools_runtime.py 的 _waits_for_user。 WAIT_FOR_USER = True 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)