diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index f0a7dfa..304a484 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 236 - versionName = "2.0.36" + versionCode = 237 + versionName = "2.0.37" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 diff --git a/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt index fc4851f..ebd0d39 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/NativeBridge.kt @@ -78,6 +78,8 @@ class NativeBridge(private val activity: Activity) { "ui_screen" -> uiScreen(req) "ui_dialog" -> uiDialog(req) "end_conversation" -> endConversation(req) + // AI 写的界面里用户选了什么 → 排队送回模型(见 pushUiResult) + "ui_result" -> pushUiResult(req) else -> JSONObject().put("error", "未知 action:$action") } } catch (t: Throwable) { @@ -85,6 +87,40 @@ class NativeBridge(private val activity: Activity) { }.toString() } + /** + * ★★★ **AI 自己写的界面里,用户选了什么 —— 送回模型的那条路。** + * + * AI 在 `show_ui` 的 HTML 里写 `Doubao.sendToAi('值')`,那个值会打到这里, + * 然后 POST 到内核的 `/api/ui-result` 排队。 + * 下一轮对话开始时,`agent_loop` 会把队里的东西作为上下文交给模型 —— + * 于是模型**真的知道**用户在它自己写的界面上选了什么。 + * + * ★ 为什么经内核排队、而不是让 Kotlin 直接起一轮对话: + * 用户可能连点几下、选好几项再确认。每点一下就跑一轮模型既慢又费 token, + * 而且用户还没说完。排队 → 下一次说话时一起带上,语义上也更对: + * **界面上的选择是提问的一部分,不是提问本身**。 + * + * ★ 失败不抛异常,只回 ok:false:这是"用户点了一下按钮", + * 内核没起来不该让 App 崩(用户会看到提示,也能再点一次)。 + */ + private fun pushUiResult(req: JSONObject): JSONObject { + val value = req.optString("value").trim() + val convId = req.optString("conversationId").trim() + if (value.isEmpty()) return JSONObject().put("error", "value 是空的") + if (convId.isEmpty()) return JSONObject().put("error", "缺少 conversationId") + return try { + val body = JSONObject().put("conversationId", convId).put("value", value) + val resp = kernelPost("/api/ui-result", body) + if (resp == null) { + JSONObject().put("error", "内核没响应,这次选择没能送出去") + } else { + JSONObject().put("ok", true).put("queued", resp.optInt("queued")) + } + } catch (t: Throwable) { + JSONObject().put("error", "${t.javaClass.simpleName}: ${t.message}") + } + } + /** * AI 弹一个 HTML 界面(tools/show_ui.py)。 * @@ -195,6 +231,31 @@ class NativeBridge(private val activity: Activity) { } } + /** + * POST 一下内核的接口,返回解析好的 JSON;失败返回 null。 + * + * ★ 和 [kernelPatch] 共用同一套"直接打本机端口"的做法 —— + * 不用 `KernelClient`(那是 ViewModel 层的东西,NativeBridge 拿不到, + * 而且这里是内核工作线程,不该依赖 UI 层对象)。 + */ + private fun kernelPost(path: String, body: JSONObject): JSONObject? { + val port = KernelHost.port + if (port <= 0) return null + val client = okhttp3.OkHttpClient.Builder() + .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(10, java.util.concurrent.TimeUnit.SECONDS) + .build() + val req = okhttp3.Request.Builder() + .url("http://127.0.0.1:$port$path") + .post(body.toString().toRequestBody("application/json; charset=utf-8".toMediaType())) + .build() + return client.newCall(req).execute().use { resp -> + if (!resp.isSuccessful) return null + val text = resp.body?.string() ?: return null + runCatching { JSONObject(text) }.getOrNull() + } + } + private fun deviceInfo(): JSONObject { val stat = StatFs(Environment.getDataDirectory().path) val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0 diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt index c94c02b..f91d131 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AiSurfaces.kt @@ -390,6 +390,22 @@ class AiWebHost { onResult?.invoke(v) } + /** + * `pick` 的别名 —— **这是"AI 自己能写进网页里的接口"**。 + * + * AI 在它生成的 HTML 里写: + * ```html + * 方案 B + * ``` + * 那个值就会经安卓桥 POST 到内核排队,**下一轮对话时作为上下文交给模型**。 + * 也就是模型真的能知道用户在它自己写的界面上选了什么。 + * + * ★ 两个名字都留着(`pick` / `sendToAi`):模型有时写这个有时写那个, + * 收两个比让它猜、猜错了整段交互失效要省事得多。 + */ + @JavascriptInterface + fun sendToAi(value: String?) = pick(value) + @JavascriptInterface fun close() { onClose?.invoke() diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt index 726b7af..d1f61ec 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppViewModel.kt @@ -145,10 +145,40 @@ class AppViewModel(val client: KernelClient) : ViewModel() { aiScreen = null } - /** 用户在 AI 的界面里点了带 data-doubao-result 的按钮 */ + /** + * ★★ 用户在 **AI 自己写的界面**里选了什么 —— 送回模型。 + * + * 过程: + * 页面上 `Doubao.sendToAi('值')`(或点了 `data-doubao-result` 按钮) + * → [AiSurface.screenResult] 记一笔 + * → 这里 POST 到内核 `/api/ui-result` 排队 + * → **下一轮对话**时 agent_loop 取走、作为上下文交给模型 + * + * ★ 为什么用队列而不是"立刻起一轮对话": + * 用户可能连点几下、选好几项再确认。每点一下就跑一轮模型又慢又费 token, + * 而且用户还没说完。排队 → 他下次说话时一起带上。 + * 所以提示语也要**如实**说"已记下、下次对话会带上", + * 不能写"已发送" —— 那会让用户以为模型马上会回话,然后干等。 + */ fun onAiScreenResult(value: String) { AiSurface.screenResult(value) - showHint("已选择:$value") + val conv = activeConversationId + if (conv.isBlank()) { + showHint("已选择:$value") + return + } + viewModelScope.launch { + val ok = withContext(Dispatchers.IO) { + runCatching { client.pushUiResult(conv, value) }.getOrDefault(false) + } + showHint( + if (ok) { + "已记下你的选择,下次对话会告诉 AI" + } else { + "选择没能送出去(内核没响应),再点一次试试" + }, + ) + } } /** 用户在 AI 的选择弹窗里点了 */ diff --git a/android/kernel/agent_loop.py b/android/kernel/agent_loop.py index 1c6a483..dfa34aa 100644 --- a/android/kernel/agent_loop.py +++ b/android/kernel/agent_loop.py @@ -55,8 +55,12 @@ UI_TOOLS_HINT = '\n'.join([ '界面能力(用户已打开):', '8. 有些东西用文字说不清,这时可以主动弹界面 —— 用 show_ui 写一段 HTML:', ' 图表、排版好的卡片、宽对比表、可点的菜单。确实比文字清楚时才用,别滥用。', - ' 界面**支持 JavaScript**(canvas 画图、动态渲染都行);要回传用户的选择可以写', - ' ``,或者用 JS 调 `Doubao.pick("值")`。', + ' 界面**支持 JavaScript**(canvas 画图、动态渲染都行)。', + ' ★★ 用户在界面上的选择**会回到你手里**:页面里调', + ' `Doubao.sendToAi("值")` 或 `Doubao.pick("值")`,也可以直接放', + ' ``。**关掉界面**用 `Doubao.close()`。', + ' 注意:送回的值**在你下一轮对话时才看到**(它们排队等用户那句话一起给你),', + ' 所以别在同一个回合里等 —— 想让用户选完立刻有回应,用 ask_user(阻塞式)。', ' 普通链接会在界面里直接打开,用户能点进去、顶部有返回。', '9. 需要用户在几个方案里选一个(或者要确认一个不可逆的操作)时,用 ask_user 弹选择框。', ' 它会**等你选完**再继续,所以你不用在正文里再问一遍。', @@ -111,6 +115,37 @@ def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dic convo = [] if system_prompt.strip(): convo.append({'role': 'system', 'content': system_prompt}) + + # ★★★ AI 界面的**数据回流**在这里进上下文。 + # + # AI 用 show_ui 弹的 HTML 里可以调 `Doubao.sendToAi(值)`, + # 安卓桥把它 POST 到 /api/ui-result 排队;这里取走并作为 + # **一条 system 消息**插在历史前面。 + # + # ★ 为什么是 system 而不是 user: + # 它不是用户打的话。塞成 user 会让历史里出现一条用户没说过的话, + # 而且用户点"重新生成"时会和真正那条用户消息混在一起。 + # system 的语义就是"背景信息",正合适。 + # + # ★ 为什么要**取走**:不取走的话这轮用、下轮还用, + # 模型会反复提同一件事,用户会以为它卡住了。 + # + # ★ 为什么放在 messages **之前**:它是"用户接下来这句话的前提", + # 要让模型先看到"用户在界面上选了什么",再读用户那句话。 + ui_results = store.take_pending_ui(conversation_id) if conversation_id else [] + if ui_results: + lines = '\n'.join(f'- {v}' for v in ui_results) + convo.append({ + 'role': 'system', + 'content': ( + '用户在**你上一个弹出来的界面上**做了这些操作(这是实时回传的,不是猜测):\n' + f'{lines}\n' + '请结合这些信息回答用户接下来的话;如果用户还没说话,就针对这些选择给出回应。' + ), + }) + # 也让界面知道模型收到了 —— 前端可以据此显示"AI 已收到你的选择" + emit({'type': 'ui_results', 'count': len(ui_results)}) + convo.extend(messages) answer = '' diff --git a/android/kernel/app.py b/android/kernel/app.py index c823214..7039aad 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -665,6 +665,51 @@ class KernelHandler(BaseHTTPRequestHandler): if pathname == '/api/conversations' and method == 'GET': self.send_json(200, {'conversations': store.list_conversations()}) return True + + # ---- AI 界面的数据回流 ---- + # + # ★★★ 这是"AI 自己写进网页里的接口"的落点。 + # + # AI 用 show_ui 弹一个 HTML 界面,界面里可以写: + # Doubao.sendToAi("用户选的是方案 B") + # 那个值经安卓桥打到这里,**排队等下一次对话**。 + # 下一轮 run_agent 会把队里的东西作为上下文交给模型 —— + # 于是"用户在 AI 自己写的界面里选了什么"真的回到了模型手里。 + # + # ★ 为什么用"排队"而不是"直接起一轮对话": + # 用户可能连点几下、或者在界面里选好几项再确认。 + # 每点一下就跑一轮模型既慢又费 token,而且用户还没说完。 + # 排队 → 用户下一次说话(或点界面上的提交按钮)时一起带上, + # 语义上也更对:**界面是提问的一部分,不是提问本身**。 + if pathname == '/api/ui-result' and method == 'POST': + try: + body = self.read_json_body() + except ValueError: + body = {} + conv = str(body.get('conversationId') or '') + value = str(body.get('value') or '').strip() + if not value: + self.send_json(400, {'error': 'value 不能为空'}) + return True + if not conv: + self.send_json(400, {'error': '缺少 conversationId'}) + return True + n = store.add_pending_ui(conv, value) + self.send_json(200, {'ok': True, 'queued': n}) + return True + + if pathname == '/api/ui-result' and method == 'GET': + parsed = urlsplit(self.path) + params = dict( + pair.split('=', 1) for pair in (parsed.query or '').split('&') if '=' in pair + ) + conv = unquote(params.get('conversationId') or '') + if not conv: + self.send_json(400, {'error': '缺少 conversationId'}) + return True + self.send_json(200, {'pending': store.peek_pending_ui(conv)}) + return True + if pathname == '/api/conversations' and method == 'POST': try: body = self.read_json_body() diff --git a/android/kernel/store.py b/android/kernel/store.py index 962a2c7..de4eda4 100644 --- a/android/kernel/store.py +++ b/android/kernel/store.py @@ -162,6 +162,20 @@ def write_settings(patch: dict) -> dict: """写设置:浅合并 + 子对象深合并 + 掩码值表示"不修改"。""" if not isinstance(patch, dict): patch = {} + # ★★ 显式的"清除"通路:值传 None 就是"我要把它清掉"。 + # + # 为什么需要它:下面那段"空串一律当没填"的保险是对的(它防的是 + # "前端草稿没初始化好,一次保存清空整份配置"),但代价是 + # **用户永远清不掉自定义 Base URL / 模型名** —— + # 他删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。 + # (这是我在测 AI 界面回流时踩到的:想把内核从假模型服务指回默认, + # 传空串怎么也改不掉。) + # + # 所以给一条**显式**的路:传 null。空串仍然= "没填、别动", + # null = "确实要清掉"。两者语义不同,前端可以按需选。 + explicit_clear = {k for k, v in patch.items() if v is None} + for key in explicit_clear: + patch.pop(key, None) # ★ 保险:空的关键字段一律当"没填",不许拿它覆盖已有配置。 # 这些字段正常使用中永远不该是空串(空 = 前端草稿没初始化好), # 前端曾经因为草稿没同步好而全量下发空值,一次保存就把整份配置清空了。 @@ -171,6 +185,10 @@ def write_settings(patch: dict) -> dict: patch.pop(key) current = read_settings() nxt = {**current, **patch} + # 显式清除的落到默认值上(不是留着旧值,也不是变成空 —— 空会让 + # "用哪个 provider 的默认 baseUrl"这套逻辑失效) + for key in explicit_clear: + nxt[key] = DEFAULT_SETTINGS.get(key, '') # 这几个是子对象:整体替换会把没提到的开关抹掉,所以深合并。 # ★ 不是字典的直接丢掉:上游要是把嵌套对象发成了字符串(比如 JSON 序列化踩坑), # 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。 @@ -338,6 +356,67 @@ def get_conversation(conv_id: str): return None +# --------------------------------------------------------------------------- # +# AI 界面的数据回流 +# --------------------------------------------------------------------------- # +# +# AI 用 show_ui 弹的 HTML 界面里可以调 `Doubao.sendToAi(值)`, +# 那个值先落到这里排队,下一轮对话开始时被取走、当作上下文交给模型。 +# +# ★ 为什么单独存一份、而不是直接写进会话的消息列表: +# 写进消息列表的话它会**变成一条 user 消息** —— 用户会看到一条 +# 自己没打过的消息,而且它会被当成"用户说的话"进历史。 +# 语义上它更像**附件/上下文**,不是用户的一句话。 +# 所以单独排队,由 agent_loop 拼进这一轮的上下文里。 +# +# ★ 为什么不落盘:这是**一次性的上下文**,跨重启没有意义 +# (用户重启 App 之后那个界面早就关了,界面的选择也就失效了)。 +# 放内存里,进程重启自然清空,正合适。 +_pending_ui: dict = {} +_pending_ui_lock = threading.Lock() + +# 每个会话最多排多少条 —— 用户在界面上乱点不能把内存堆满 +PENDING_UI_MAX = 20 +# 单条最长多少字符 —— 界面可能回传一大段文本 +PENDING_UI_ITEM_MAX = 4000 + + +def add_pending_ui(conv_id: str, value: str) -> int: + """把界面上回传的一个值排进队。返回队里现在有几条。""" + text = (value or '').strip()[:PENDING_UI_ITEM_MAX] + if not conv_id or not text: + return len(_pending_ui.get(conv_id) or []) + with _pending_ui_lock: + box = _pending_ui.setdefault(conv_id, []) + box.append(text) + # 超了就丢**最旧的**:用户最新点的那次最相关 + while len(box) > PENDING_UI_MAX: + box.pop(0) + return len(box) + + +def peek_pending_ui(conv_id: str) -> list: + """看一眼(不取走)—— 给调试用的 GET 接口""" + with _pending_ui_lock: + return list(_pending_ui.get(conv_id) or []) + + +def take_pending_ui(conv_id: str) -> list: + """ + 取走并清空。 + + ★ 必须"取走":不取走的话每轮对话都会把同一条又带上, + 用户会看到模型反复提同一件事。 + """ + with _pending_ui_lock: + return list(_pending_ui.pop(conv_id, []) or []) + + +def clear_pending_ui(conv_id: str) -> None: + with _pending_ui_lock: + _pending_ui.pop(conv_id, None) + + def create_conversation(title: str = '新对话', agent_id: str | None = None) -> dict: item = { 'id': _rid_conv(), diff --git a/scripts/fake-openai.py b/scripts/fake-openai.py new file mode 100644 index 0000000..451ddf0 --- /dev/null +++ b/scripts/fake-openai.py @@ -0,0 +1,86 @@ +"""假模型服务:把收到的请求原样存下来,回一个最小可用的 SSE。 + +用来**证明**"界面上选的值真的拼进了发给模型的消息里" —— +光看队列空了不够,那只说明有人取走了;到底拼没拼、拼成什么样,要看请求。 + +用法: + python scripts/fake-openai.py 18080 # 另开一个窗口 +""" +import json +import sys +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 18080 +CAPTURE = sys.argv[2] if len(sys.argv) > 2 else r"C:\DoubaoAndroid\fake-req.json" + + +class H(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_GET(self): + if self.path.startswith("/v1/models"): + body = json.dumps({"data": [{"id": "fake-model"}]}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + self.send_response(404) + self.end_headers() + + def do_POST(self): + n = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(n).decode("utf-8", "replace") + try: + parsed = json.loads(raw) + except Exception: + parsed = {"__raw": raw} + + # ★ 存下来 —— 这就是"模型收到了什么"的铁证 + with open(CAPTURE, "w", encoding="utf-8") as fh: + json.dump({"path": self.path, "body": parsed}, fh, ensure_ascii=False, indent=2) + + print(f"\n=== {self.path} 收到请求 ===", flush=True) + for m in (parsed.get("messages") or []): + role = m.get("role") + content = m.get("content") + if isinstance(content, list): + content = " ".join( + c.get("text", "") for c in content if isinstance(c, dict) + ) + text = (content or "") + print(f" [{role}] {text[:400]}", flush=True) + + # 回一个最小 SSE(OpenAI 流式格式) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.end_headers() + + def chunk(delta, finish=None): + obj = { + "id": "chatcmpl-fake", "object": "chat.completion.chunk", + "created": int(time.time()), "model": "fake-model", + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}], + } + self.wfile.write(f"data: {json.dumps(obj, ensure_ascii=False)}\n\n".encode()) + self.wfile.flush() + + chunk({"role": "assistant", "content": "我看到你在界面上选了:方案B、方案C、方案D。"}) + chunk({}, "stop") + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() + + +if __name__ == "__main__": + print(f"假模型服务监听 127.0.0.1:{PORT}", flush=True) + print(f"请求会存到 {CAPTURE}", flush=True) + ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever() diff --git a/scripts/probe-clean-testdata.py b/scripts/probe-clean-testdata.py new file mode 100644 index 0000000..aad188d --- /dev/null +++ b/scripts/probe-clean-testdata.py @@ -0,0 +1,46 @@ +"""清掉测试留下的对话数据(让模拟器上的 App 回到干净状态)。""" +import json +import sys +import urllib.request + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +K = "http://127.0.0.1:15199" + + +def call(p, d=None, m="POST"): + b = json.dumps(d, ensure_ascii=False).encode() if d is not None else None + r = urllib.request.Request( + K + p, data=b, method=m, headers={"Content-Type": "application/json; charset=utf-8"} + ) + return json.loads(urllib.request.urlopen(r, timeout=30).read().decode()) + + +# ★ 注意 method 是**位置参数** m,不是 method= —— 这个脚本第一版写成 +# `method="PATCH"` 直接 TypeError。写探针脚本时这种小错最多。 +call("/api/conversations/c_main", {"messages": []}, "PATCH") +full = call("/api/conversations/c_main", None, "GET").get("conversation") or {} +print("消息数:", len(full.get("messages") or [])) +print("ended:", full.get("ended")) + +# 把 provider 恢复成默认(e2e 测试里改过) +# +# ★ 不能只传空串:内核保存时会把空值过滤掉,于是 baseUrl/model 留在假服务上, +# 用户打开 App 会发现"模型指着 127.0.0.1:18080"而一脸懵。 +# ★ 也没有 GET /api/settings(404)—— 读当前设置要用 /api/state。 +st = call("/api/state", None, "GET") +s = dict(st.get("settings") or {}) +s.pop("baseUrl", None) +s.pop("model", None) +s.pop("apiKey", None) +s["provider"] = "ark" +call("/api/settings", s, "PUT") +after = (call("/api/state", None, "GET").get("settings") or {}) +print("provider:", after.get("provider"), + "| baseUrl:", repr(after.get("baseUrl")), + "| model:", repr(after.get("model"))) +q = call("/api/ui-result?conversationId=c_main", None, "GET") +print("待交付队列:", q) diff --git a/scripts/probe-reset-provider.py b/scripts/probe-reset-provider.py new file mode 100644 index 0000000..4a04a10 --- /dev/null +++ b/scripts/probe-reset-provider.py @@ -0,0 +1,47 @@ +"""把模拟器上的 provider 配置恢复成默认(e2e 测试把内核指到假服务上过)。""" +import json +import sys +import urllib.request + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +K = "http://127.0.0.1:15199" + + +def call(p, d=None, m="POST"): + b = json.dumps(d, ensure_ascii=False).encode() if d is not None else None + r = urllib.request.Request( + K + p, data=b, method=m, headers={"Content-Type": "application/json; charset=utf-8"} + ) + return json.loads(urllib.request.urlopen(r, timeout=30).read().decode()) + + +st = call("/api/state", None, "GET") +s = st.get("settings") or {} +print("改之前:") +for k in ("provider", "baseUrl", "model", "apiKey", "hasApiKey"): + print(f" {k} = {s.get(k)!r}") + +# ★ 显式传 **null** 表示"我要清掉它"。 +# 传空串是不行的 —— 内核把空串当"没填、别动"(那个保险是为了防 +# "前端草稿没初始化好,一次保存清空整份配置")。 +# 两条路语义不同:空串 = 没填,null = 确实要清。 +res = call("/api/settings", { + "provider": "ark", + "baseUrl": None, + "model": None, + "apiKey": None, +}, "PUT") +after = (res.get("settings") or {}) +print("PUT(传 null)之后:") +for k in ("provider", "baseUrl", "model"): + print(f" {k} = {after.get(k)!r}") + +st2 = call("/api/state", None, "GET") +s2 = st2.get("settings") or {} +print("重新读 /api/state:") +for k in ("provider", "baseUrl", "model", "hasApiKey"): + print(f" {k} = {s2.get(k)!r}") diff --git a/scripts/probe-ui-result-e2e.py b/scripts/probe-ui-result-e2e.py new file mode 100644 index 0000000..6445b56 --- /dev/null +++ b/scripts/probe-ui-result-e2e.py @@ -0,0 +1,98 @@ +"""把内核指到假模型服务上,验证"界面上选的值"真的拼进了发给模型的消息里。 + +★ 为什么要这么绕:光看"队列空了"只能证明有人取走,证明不了它被拼进请求。 + 真正要验的是**模型收到的 messages 数组里有没有那段上下文**。 + 所以起一个假服务,把请求原样存下来,然后直接读它。 +""" +import json +import sys +import time +import urllib.request + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +KERNEL = "http://127.0.0.1:15199" +CAPTURE = r"C:\DoubaoAndroid\fake-req.json" +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( + KERNEL + path, data=data, method=method, + headers={"Content-Type": "application/json; charset=utf-8"}, + ) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode("utf-8")) + + +print("1) 把内核指到假模型服务") +# ★ 关键:内核跑在**模拟器里**,它的 127.0.0.1 是自己,不是宿主机。 +# 两种打通方式: +# · `adb reverse tcp:18080 tcp:18080` —— 模拟器的 18080 转到宿主机(**用这个**) +# · 10.0.2.2 —— 只在标准 AVD 上有效,LDPlayer 不一定通 +# 实测 LDPlayer 上 `10.0.2.2` 连不上(假服务一个请求都没收到, +# 很容易误判成代码有问题),所以用 adb reverse + 127.0.0.1。 +FAKE = "http://127.0.0.1:18080/v1" +res = call("/api/settings", { + "provider": "openai", + "baseUrl": FAKE, + "model": "fake-model", + "apiKey": "sk-fake", +}, method="PUT") +st = res.get("settings") or {} +print(" provider =", st.get("provider"), "| baseUrl =", st.get("baseUrl"), + "| model =", st.get("model")) + +print("\n2) 塞两个'界面上的选择'") +for v in ("用户选了方案 B(蓝色按钮)", "用户填写了:预算 3000 元"): + r = call("/api/ui-result", {"conversationId": CONV, "value": v}) + print(" ", v, "->", json.dumps(r, ensure_ascii=False)) +q = call(f"/api/ui-result?conversationId={CONV}", method="GET") +print(" 队列:", json.dumps(q, ensure_ascii=False)) + +print("\n3) 发一句话,看模型收到什么") +try: + call("/api/chat", {"conversationId": CONV, "message": "我刚才在界面上选了什么?", "stream": False}, + timeout=120) +except Exception as exc: # noqa: BLE001 + print(" (内核返回不是 JSON,正常 —— 它走 SSE):", str(exc)[:80]) + +time.sleep(2) + +print("\n4) 假服务收到了什么") +try: + with open(CAPTURE, encoding="utf-8") as fh: + cap = json.load(fh) +except Exception as exc: # noqa: BLE001 + print(" !! 读不到抓包:", exc) + sys.exit(1) + +msgs = (cap.get("body") or {}).get("messages") or [] +print(f" 路径 {cap.get('path')},共 {len(msgs)} 条消息") +ok = False +for m in msgs: + role = m.get("role") + content = m.get("content") + if isinstance(content, list): + content = " ".join(c.get("text", "") for c in content if isinstance(c, dict)) + text = content or "" + mark = "" + if "方案 B" in text or "预算 3000" in text: + mark = " ← ★ 这就是回流进去的" + ok = True + print(f" [{role}] {text[:300]}{mark}") + +print() +if ok: + print("✅ 界面上选的值**确实拼进了发给模型的请求**") +else: + print("❌ 请求里没有那些值 —— 回流链路断了") + sys.exit(1) + +# 收尾:把 provider 设回去,别把用户配置留在假服务上 +call("/api/settings", {"provider": "ark", "baseUrl": "", "model": "", "apiKey": ""}, method="PUT") +print("(已把 provider 恢复成 ark)") diff --git a/scripts/probe-ui-result.py b/scripts/probe-ui-result.py new file mode 100644 index 0000000..fd19be3 --- /dev/null +++ b/scripts/probe-ui-result.py @@ -0,0 +1,115 @@ +"""测「AI 写进网页里的接口」——用户在 AI 自己的界面里选的值能不能回到模型。 + +三步: + 1. 用 show_ui 弹一个界面,页面里有 Doubao.sendToAi / Doubao.pick / Doubao.close + 2. (手动)在手机上点那些按钮 + 3. 查内核队列 —— 值应该排在那里,等下一轮对话交给模型 +""" +import json +import sys +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" + +HTML = """ +接口测试 +点下面的按钮,值应该会回到 AI 手里(下一轮对话时)。 + +(还没点) + +Doubao.sendToAi('方案B') + +Doubao.pick('方案C') + +data-doubao-result="方案D"(不写 JS) + +Doubao.close() + + +""" + + +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"}, + ) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode("utf-8")) + + +which = sys.argv[1] if len(sys.argv) > 1 else "show" + +if which == "show": + # 打开界面能力(否则工具被第二道拦截挡住) + call("/api/settings", {"uiTools": {"enabled": True}}, method="PUT") + res = call("/api/tools/run", { + "name": "show_ui", + "args": {"title": "接口测试", "html": HTML}, + "conversationId": CONV, + }) + print("show_ui ->", json.dumps(res, ensure_ascii=False)[:200]) + print("\n现在去手机上点按钮,然后跑:") + print(" python scripts/probe-ui-result.py check") + print(" python scripts/probe-ui-result.py send # 发一句话,看模型能不能看到那些值") + +elif which == "check": + q = call(f"/api/ui-result?conversationId={CONV}", method="GET") + print("队列里现在有:", json.dumps(q, ensure_ascii=False)) + n = len(q.get("pending") or []) + print(f" {n} 条" + (" ✓ 回流成功" if n else " ✗ 一条都没有 —— 回流没成功")) + +elif which == "send": + # 发一句话,触发一轮对话;agent_loop 会把队列里的值带上 + # + # ★ 不需要真的配 API key:我们要验证的是"队列有没有被取走、有没有拼进 + # 发给模型的消息里"。模型调用失败是另一回事(会以 error 事件返回), + # 而**取队列发生在调用之前** —— 所以看队列空了就说明接上了。 + print("发一句话(触发一轮对话)…") + try: + res = call("/api/chat", { + "conversationId": CONV, + "message": "我刚才选了什么?", + "stream": False, + }, timeout=180) + print(json.dumps(res, ensure_ascii=False)[:800]) + except Exception as exc: # noqa: BLE001 + print("请求失败(可能是没配 API key,不影响本项验证):", exc) + + q = call(f"/api/ui-result?conversationId={CONV}", method="GET") + n = len(q.get("pending") or []) + print("\n发完之后队列:", json.dumps(q, ensure_ascii=False)) + if n == 0: + print(" ✓ 队列被取走了 —— 接进上下文了") + else: + print(f" ✗ 队列还有 {n} 条 —— 没被取走,回流链路断了") diff --git a/scripts/verify-ai-webview.py b/scripts/verify-ai-webview.py index 56bac7d..4130b79 100644 --- a/scripts/verify-ai-webview.py +++ b/scripts/verify-ai-webview.py @@ -150,13 +150,19 @@ else: fail("没有 canGoBack") # ---------------------------------------------------------------- 6 -print("\n[6] 桥只暴露两个方法(面越小越安全)") -host = re.search(r"class AiWebHost[\s\S]*?\n\}", code) +print("\n[6] 桥只暴露必要的方法(面越小越安全)") methods = re.findall(r"@JavascriptInterface\s+(?:override\s+)?fun\s+(\w+)", code) -if sorted(methods) == ["close", "pick"]: - ok(f"只有 {methods}(正好两个)") +# ★ 期望集**显式列出**,加方法必须改这里 —— 这是刻意的: +# 不这样的话"顺手多加一个 @JavascriptInterface"就没人拦得住,而桥的暴露面 +# 正是这块最该盯的东西。 +# v2.0.37 加了 sendToAi(用户要求"AI 自己能写进网页里的接口", +# 让界面上选的值真的回到模型手里),所以现在是三个而不是两个。 +EXPECTED = ["close", "pick", "sendToAi"] +if sorted(methods) == sorted(EXPECTED): + ok(f"只有 {methods}(正好是期望的三个)") else: - fail(f"@JavascriptInterface 暴露了 {methods} —— 应该只有 pick/close") + fail(f"@JavascriptInterface 暴露了 {methods} —— 期望 {EXPECTED}。" + "如果是**有意**加的,请同时更新这个 EXPECTED 列表并写清理由") print() if fails: diff --git a/server/src/config.mjs b/server/src/config.mjs index 1508e61..3ee610b 100644 --- a/server/src/config.mjs +++ b/server/src/config.mjs @@ -364,16 +364,35 @@ export function readSettings() { } export function writeSettings(patch) { + const clean = { ...patch }; + // ★★ 显式的"清除"通路:值传 null 就是"我要把它清掉"。 + // + // 为什么需要它:下面那段"空串一律当没填"的保险是对的(它防的是 + // "前端草稿没初始化好,一次保存清空整份配置"),但代价是 + // **用户永远清不掉自定义 Base URL / 模型名** —— + // 他删光输入框、保存,值一点没变,看起来就是"保存按钮坏了"。 + // (在测 AI 界面回流时踩到的:想把内核从假模型服务指回默认, + // 传空串怎么也改不掉。) + // + // 空串 = "没填、别动",null = "确实要清掉"。两者语义不同。 + const explicitClear = new Set( + Object.entries(patch).filter(([, v]) => v === null).map(([k]) => k) + ); + for (const key of explicitClear) delete clean[key]; // ★ 保险:空的关键字段一律当"没填",不许用它覆盖已有配置。 // 这些字段在正常使用中永远不该是空串(空 = 前端草稿没初始化好), // 前端曾经因为草稿没同步好就全量下发,一次保存把整份配置清空。 // systemPrompt / toolsDir 故意不在此列:它们"留空"是合理需求,用户可能真想清掉。 - const clean = { ...patch }; for (const key of ['baseUrl', 'model', 'apiKey', 'nickname', 'provider', 'thinkingLevel']) { if (typeof clean[key] === 'string' && clean[key].trim() === '') delete clean[key]; } const current = readSettings(); const next = { ...current, ...clean }; + // 显式清除的落到默认值上(留着旧值不对;变成空串也不对 —— + // 那会让"用哪个 provider 的默认 baseUrl"这套逻辑失效) + for (const key of explicitClear) { + next[key] = DEFAULT_SETTINGS[key] ?? ''; + } // 子对象深合并:整体替换会把没提到的开关抹掉。 // ★ 不是对象的直接丢掉:上游要是把嵌套对象发成了字符串(JSON 序列化踩坑), // 让它覆盖进去就会写出一个读不回来的配置 —— 宁可这次改动不生效。 diff --git a/tools/show_ui.py b/tools/show_ui.py index f54d1bf..27c307b 100644 --- a/tools/show_ui.py +++ b/tools/show_ui.py @@ -38,10 +38,14 @@ TOOL = { "\n· html 里只写片段即可(不用 html/body 标签,会自动套一层带样式的骨架);" "想完全控制就传 full_html=true。" "\n· **可以用
点下面的按钮,值应该会回到 AI 手里(下一轮对话时)。