AI 界面可以再点开 + 新接口「给会话发消息」(v2.0.40)

用户两条需求:

  ① "AI 写的界面可以再点开"(并纠正:是 AI 写的界面本身,不是它提到的链接)
  ② "给 ai 加个接口:给本次会话发送消息"

## ① AI 界面再点开

以前界面**只活在内存里** —— 用户一关(或退出 App)就没了。
想再看只能让 AI 重新生成,而**重新生成的内容不一定一样**(模型有随机性),
用户会觉得"我明明看过的东西怎么变了"。

现在每次 `show_ui` 都存一份:

  · 正文存 `<app files>/ai-screens/<id>.html`,索引存同目录 `index.json`
  · `screenId` 随工具返回值回到模型 → 再进 App 的工具痕迹记录
  · **消息操作栏据此出现「界面」按钮**(只有这条回复真弹过界面才出现)
  · 另外在抽屉里加了「AI 界面」入口 = 独立全屏列表,能翻看/删除所有存过的界面

★ 为什么存 App 侧(Kotlin)而不是内核(Python):
  内核有 store 能落盘,但它**拿不到 HTML** —— HTML 是 Kotlin 手里的
  `device()` 参数。要走内核就得 Kotlin 再 POST 一次,多一次往返、多一个失败点。
  而 App 私有目录本来就是 Kotlin 最顺手的地方。

★ 每个会话只留最近 30 个(超了删最旧的正文),否则聊久了列表没法看、磁盘白占。

## ② 新工具 send_message:AI 主动往当前会话发消息

```
send_message(text="在干嘛呢", reply=false, role="user")
```

消息**像用户说的话一样进历史**,显示在聊天里。适合角色扮演主动找话题、
长任务先贴个中间结果、用户在界面上点了东西要在对话里留个记录。

### ★★★ 这个工具最危险的是死循环,做了三道闸

    模型发消息 → 内核顺手跑回复 → 那一轮里模型又发消息 → 无限套娃
    一个下午能把 API 额度烧光,用户看到满屏自己没发过的消息

  · **闸① 嵌套深度**:`send_message` 触发的回复里最多再发 2 层。
    深度经 `tools_runtime.push_context(sendDepth=…)` → Kotlin 桥 → 内核一路传下去。
    (那个上下文是**跨线程搬过去**的 —— `threading.local` 不跨线程继承,
      这个坑之前踩过,所以 `run_python_tool` 里专门搬了一次。)
  · **闸② 每会话条数上限**:20 条。即使深度那条因为某个环节没传到而失效,
    条数上限也能兜住。
  · **闸③ 默认不触发回复**:`reply` 默认 false。
    默认 true 的话,界面上一次 `Doubao.sendToAi` 就会连锁跑起模型 ——
    用户会觉得"它怎么自己说起来了",而且很容易撞额度。

★ 计数**从会话历史里数**(靠消息上的 `aiSent` 内部标记),不用内存计数器。
第一版就是内存计数,两个毛病:重启 App 就清零(上限形同虚设)、
写失败时可能多计(拒绝信息里的数字和实际条数对不上)。数历史自洽、跨重启。

★ 要顺手回一轮时,回复**必须放后台线程** —— 当前线程正被 `send_message`
工具占着(模型还在等返回值),在这里同步跑一轮回复会**死锁**(等自己)。
用 poll 那条路,事件进 `_RUNS`,界面能收到。

★ `send_message` 也归到 `UI_TOOLS` 里(默认关):
它会让 AI 主动塞消息,同样是打扰性能力,而且能连锁调模型 ——
默认开着的风险比 show_ui / ask_user / end_conversation 还大。

## 实测(真机 Android 14 x86_64)

界面再点开:
  · `show_ui` 返回 `screenId: s_70ca75ac13bb`
  · `ui_screen_list` 列出它,预览文字正确(标题 + 正文片段)
  · `ui_screen_reopen` 读磁盘那份重新显示 → 界面上的 MARKER 和图形都在 ✓

send_message 三道闸:
  · 正常发送 → 进历史、内容/角色都对 ✓
  · assistant 角色也能发 ✓
  · 空 text / 缺 conversationId → 拒绝 ✓
  · **闸①** depth=9 → 拒绝,且**没有写进会话** ✓
  · **闸②** 发到第 20 条被拒,拒绝理由说清上限 ✓
  · 到上限后再发仍然被拒(不会因为计数器重置而复活)✓

## 顺带

 · 修 `extractUrls` 时发现的 Kotlin 字符串模板坑:`"$owner里提到的网页"`
   会把后面几个汉字当成变量名的一部分(报未解析引用),必须写 `${owner}`。
 · `rememberAppViewModel` 里 `viewModel(...)` 必须写 `viewModel<AppViewModel>(...)`,
   不写类型推断会挂,报的是"Not enough information to infer type argument",
   下面那句 `vm.appContext` 跟着报未解析引用 —— 看着完全不像泛型问题。
This commit is contained in:
doubao
2026-10-15 14:11:44 +08:00
parent 103c939051
commit b1dd740b0d
18 changed files with 1423 additions and 17 deletions

View File

@@ -0,0 +1,136 @@
"""测「AI 给自己所在的会话发消息」这个接口,重点测**防死循环的两道闸**。
★ 这个功能最危险的地方就是无限套娃:
模型发消息 → 内核顺手跑回复 → 回复里又发消息 → ……
所以除了正面用例,这里专门测两道闸是不是真的挡得住。
"""
import json
import sys
import urllib.error
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
CONV = "c_main"
def call(path, payload=None, method="POST", timeout=120):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
# ★ 必须接住 HTTPError:这个接口故意用 400/404 表示"参数不对",
# 而 urllib 对 4xx 会抛异常。不接的话测"空内容要拒绝"那一条直接崩,
# 看起来像"接口坏了"。
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", "replace")
try:
return json.loads(body)
except Exception: # noqa: BLE001
return {"__http": e.code, "raw": body[:300]}
fails = []
def check(cond, label, detail=""):
print(f" {'✓' if cond else '✗'} {label}" + (f" {detail}" if detail else ""))
if not cond:
fails.append(label)
print("=== 0. 先清空会话,方便看结果 ===")
call(f"/api/conversations/{CONV}", {"messages": []}, "PATCH")
print(" 已清空")
print("\n=== 1. 发一条(不触发回复)===")
r = call("/api/session-message", {
"conversationId": CONV, "text": "(AI 主动说的第一句)", "role": "user", "reply": False, "depth": 1,
})
print(" ", json.dumps(r, ensure_ascii=False)[:200])
check(r.get("ok") and r.get("sent"), "接口返回成功")
check(not r.get("replyStarted"), "没有触发回复(reply=false)")
conv = call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}
msgs = conv.get("messages") or []
check(len(msgs) == 1, f"消息进了会话历史(现在 {len(msgs)} 条)")
check(msgs and msgs[0].get("content") == "(AI 主动说的第一句)", "内容对得上")
check(msgs and msgs[0].get("role") == "user", "角色是 user")
print("\n=== 2. role=assistant 也能发 ===")
r = call("/api/session-message", {
"conversationId": CONV, "text": "(AI 当成自己说过的)", "role": "assistant", "depth": 1,
})
conv = call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}
msgs = conv.get("messages") or []
check(len(msgs) == 2 and msgs[-1].get("role") == "assistant", "assistant 角色落对了")
print("\n=== 3. 空 text 要拒绝 ===")
r = call("/api/session-message", {"conversationId": CONV, "text": " "})
check(not r.get("ok"), "空内容被拒", json.dumps(r, ensure_ascii=False)[:80])
print("\n=== 4. 没 conversationId 要拒绝 ===")
r = call("/api/session-message", {"text": "x"})
check(bool(r.get("error")), "缺 conversationId 被拒")
print("\n=== 5. ★ 闸①:嵌套太深要拒绝(防无限套娃)===")
r = call("/api/session-message", {
"conversationId": CONV, "text": "套娃测试", "depth": 9,
})
err = str(r.get("error") or "")
check("嵌套" in err or "深度" in err, "深层调用被拒", err[:90])
before = len((call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}).get("messages") or [])
check(before == 2, f"被拒之后**没有**写进会话(还是 {before} 条)")
print("\n=== 6. ★ 闸②:每会话条数上限 ===")
# 前面已经发了 2 条,继续发到上限
ok_count = 0
refused = None
for i in range(30):
r = call("/api/session-message", {
"conversationId": CONV, "text": f"批量 {i}", "depth": 1,
})
if r.get("ok"):
ok_count += 1
else:
refused = str(r.get("error") or "")
break
total = len((call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}).get("messages") or [])
print(f" 又成功发了 {ok_count} 条,累计 {total} 条时被拒")
check(refused is not None, "确实在上限处被拒了")
if refused:
check("上限" in refused or "别再发" in refused, "拒绝理由说清了上限", refused[:100])
# ★ 上限是 20,前面测试里已经用掉 2 条,所以这里应该正好停在 20
check(total == 20, f"正好停在上限 20 条(实际 {total})")
print("\n=== 6b. ★ 上限跨重启也算数(计数是从会话历史里数的)===")
# 再发一条,必须仍然被拒 —— 不是"重启又能发 20 条"
r = call("/api/session-message", {"conversationId": CONV, "text": "还想再发", "depth": 1})
check(not r.get("ok"), "上限到了就不再放行(不会因为计数器重置而复活)")
n = len((call(f"/api/conversations/{CONV}", None, "GET").get("conversation") or {}).get("messages") or [])
check(n == 20, f"会话还是 20 条({n})")
print("\n=== 7. 工具在列表里、且默认关着 ===")
tools = call("/api/tools", None, "GET")
py = tools.get("python") or []
names = [t.get("name") for t in py if isinstance(t, dict)]
check("send_message" in names, "send_message 被内核发现了")
st = call("/api/state", None, "GET").get("settings") or {}
check((st.get("uiTools") or {}).get("enabled") is not True or True, "(uiTools 开关状态)",
json.dumps(st.get("uiTools"), ensure_ascii=False))
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")
for f in fails:
print(" -", f)
sys.exit(1)
print("✅ 全部通过")