From 0ad999b6e626e4a23c3378b646bfd0b8660d4edb Mon Sep 17 00:00:00 2001 From: doubao Date: Thu, 15 Oct 2026 10:32:14 +0800 Subject: [PATCH] =?UTF-8?q?WIP:=20=E6=89=93=E5=BC=80=E7=BD=91=E9=A1=B5?= =?UTF-8?q?=E6=8C=89=E9=92=AE=20+=20=E5=85=A8=E5=B1=8F=E7=BD=91=E9=A1=B5?= =?UTF-8?q?=E7=95=8C=E9=9D=A2=20+=20=E7=BD=91=E9=A1=B5=E7=82=B9=E9=80=89?= =?UTF-8?q?=EF=BC=88=E5=BE=85=E6=94=B9=E6=88=90=20AI=20=E5=8F=AF=E5=86=99?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E6=8D=AE=E5=9B=9E=E6=B5=81=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/doubao/lynxclone/ui/AppRoot.kt | 43 +- .../com/doubao/lynxclone/ui/AppViewModel.kt | 59 ++ .../com/doubao/lynxclone/ui/ChatScreen.kt | 25 + .../java/com/doubao/lynxclone/ui/DoubaoUi.kt | 49 ++ .../com/doubao/lynxclone/ui/MarkdownText.kt | 127 ++++- .../com/doubao/lynxclone/ui/WebPageScreen.kt | 536 ++++++++++++++++++ .../java/com/doubao/lynxclone/ui/WebPick.kt | 370 ++++++++++++ scripts/probe-check-conv.py | 34 ++ scripts/probe-seed-link-msg.py | 62 ++ scripts/verify-web-pick.py | 264 +++++++++ 10 files changed, 1547 insertions(+), 22 deletions(-) create mode 100644 android/app/src/main/java/com/doubao/lynxclone/ui/WebPageScreen.kt create mode 100644 android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt create mode 100644 scripts/probe-check-conv.py create mode 100644 scripts/probe-seed-link-msg.py create mode 100644 scripts/verify-web-pick.py diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt index 18a0eaf..366d540 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/AppRoot.kt @@ -7,7 +7,9 @@ import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutHorizontally +import androidx.compose.animation.slideOutVertically import androidx.compose.animation.togetherWith import androidx.compose.foundation.background import androidx.compose.foundation.clickable @@ -119,8 +121,9 @@ fun AppRoot( * 挂在 ChatScreen 里的话,用户在会议/设置页时弹不出来 —— * 而模型那边以为已经弹给用户看了,只能干等(ask_user 会一直等到超时)。 * - * 顺序(后写的盖在上面):选择弹窗 > HTML 界面。 - * `ask_user` 是阻塞的,用户必须先回答它,所以它压在最上面。 + * 顺序(后写的盖在上面):全屏网页 > 选择弹窗 > HTML 界面。 + * `ask_user` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的, + * 他最想看的是网页,所以网页在最上面。 */ AiHtmlScreenOverlay( screen = vm.aiScreen, @@ -131,6 +134,42 @@ fun AppRoot( dialog = vm.aiDialog, onAnswer = { values, cancelled -> vm.answerAiDialog(values, cancelled) }, ) + + // 「要打开哪个网页?」链接列表(**独立全屏界面**,不是弹窗)。 + // 排在网页界面之下:用户选完就直接进网页,中间那一层要能被盖住。 + AnimatedVisibility( + visible = vm.pickUrlFrom.isNotEmpty(), + enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)), + exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)), + ) { + UrlListScreen( + owner = "这条回复", + urls = vm.pickUrlFrom, + onPick = { vm.openWebPage(it) }, + onClose = { vm.dismissUrlPicker() }, + ) + } + + // 全屏看网页(点消息下方「打开网页」按钮进来) + AnimatedVisibility( + visible = vm.webPage != null, + enter = slideInVertically(tween(240)) { it / 5 } + fadeIn(tween(180)), + exit = slideOutVertically(tween(200)) { it / 6 } + fadeOut(tween(150)), + ) { + vm.webPage?.let { url -> + WebPageScreen( + url = url, + onClose = { vm.closeWebPage() }, + // 用户在网页上点选 → 发回给 AI。走的是**普通发消息**那条路 + // (所以会正常显示在对话里、正常存历史),而不是什么隐藏通道 —— + // 用户能看见自己"发了什么",也能反悔(重新生成)。 + onSendToAi = { text -> + vm.closeWebPage() + vm.sendExternal(text) + }, + ) + } + } } } 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 f3bb236..726b7af 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 @@ -81,6 +81,46 @@ class AppViewModel(val client: KernelClient) : ViewModel() { var endedReason by mutableStateOf("") private set + /** + * 正在全屏看的网页(点消息下方的「打开网页」按钮进来的);null 表示没开。 + * + * ★ 为什么要有这个独立界面,而不是让用户去点正文里那行小字: + * 链接做成蓝色下划线**没有可发现性** —— 用户不知道能点、也不知道点了 + * 会发生什么。产品上正确的是给一个**明确的按钮**。 + */ + var webPage by mutableStateOf(null) + private set + + /** + * 一条回复里有多个链接时,先展示这个列表让用户挑;空表示不展示。 + * + * ★ 按项目约定:**列表这种要滚动的东西不用弹窗**,用独立全屏界面。 + * 一条回复里挂五六个链接是常事,弹窗装不下、用户还得在里面滚动 —— + * 那还不如直接开一屏。(`UrlChooser` 那个弹窗版本已经删掉了。) + */ + var pickUrlFrom by mutableStateOf>(emptyList()) + private set + + fun askWhichUrl(urls: List) { + pickUrlFrom = urls + } + + fun dismissUrlPicker() { + pickUrlFrom = emptyList() + } + + /** 打开一个网页(全屏界面) */ + fun openWebPage(url: String) { + val u = url.trim() + if (u.isEmpty()) return + pickUrlFrom = emptyList() // 进网页界面时把"选哪个"收掉 + webPage = u + } + + fun closeWebPage() { + webPage = null + } + private var chatJob: AtomicBoolean? = null init { @@ -246,6 +286,25 @@ class AppViewModel(val client: KernelClient) : ViewModel() { runChat(lastUser.content, emptyList()) } + /** + * 从别处(现在只有"网页点选")发一条消息给 AI。 + * + * ★ 走的是**和手打消息完全一样的那条路** —— 所以它会正常出现在对话里、 + * 正常存进历史、也能被"重新生成"。 + * 刻意不做成什么"隐藏上下文注入":用户得看得见自己发了什么, + * 否则模型回一句"你选的这个……"而用户根本不知道自己选过什么。 + */ + fun sendExternal(text: String) { + val t = text.trim() + if (t.isEmpty() || streaming) return + if (conversationEnded) { + showHint("这次对话已结束,请开一个新对话") + return + } + screen = Screen.Chat + runChat(t, emptyList()) + } + private fun runChat(text: String, files: List) { messages.add(ChatMessage(role = "user", content = text, attachments = files)) messages.add(ChatMessage(role = "assistant", content = "", pending = true)) diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt index e840964..2531d77 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/ChatScreen.kt @@ -613,6 +613,31 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech: vm.showHint("已复制") } Spacer(Modifier.width(10.dp)) + /** + * ★★「打开网页」—— 用户明确要求"你要单独开个按钮"。 + * + * 以前只有正文里那行蓝色下划线,**没有可发现性**: + * 用户不知道它能点、也不知道点了会怎样。 + * 现在改成:回复里只要有 http(s) 链接,这里就出现一个按钮。 + * + * · 只有 1 个链接 → 直接打开 + * · 多个链接 → 进「链接列表」全屏界面让用户挑 + * (按项目约定:列表这种要滚动的东西**不用弹窗**) + * + * ★ 链接是从 markdown 里现算的(`extractUrls`),不额外存状态 —— + * 存了就要担心和 content 不同步(重新生成、编辑之后)。 + */ + val urls = remember(msg.content) { extractUrls(msg.content) } + if (urls.isNotEmpty()) { + RoundIconButton(Icons.Filled.Language, "打开网页") { + if (urls.size == 1) { + vm.openWebPage(urls.first()) + } else { + vm.askWhichUrl(urls) + } + } + Spacer(Modifier.width(10.dp)) + } if (speaking) { // 正在念这条:按钮变蓝 + 图标换成停止,一眼看出"再点就是停" RoundIconButton( diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt index 398bde0..df7312f 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/DoubaoUi.kt @@ -93,6 +93,55 @@ fun doubaoSurfaceAlt() = if (isDark()) Color(0xFF232830) else Doubao.CardBg @Composable fun doubaoTextDim() = if (isDark()) Color(0xFF8C939D) else Doubao.TextTertiary +/* ------------------------------ 打开链接 ------------------------------ */ + +/** + * 在系统浏览器里打开一个链接。 + * + * ## 为什么需要它 + * + * 聊天气泡里的 markdown 链接**以前渲染成蓝色下划线但没有绑点击** —— + * 看着像能点,点了完全没反应。用户会以为是"链接坏了"。 + * (这个坑是用户问"网页在哪点开"时才查出来的:我一直在讲 AI 弹的界面, + * 而最容易想到的"点链接"其实一直是坏的。) + * + * ## 为什么用系统浏览器而不是应用内 WebView + * + * AI 弹出的那个界面里点链接是**应用内**打开的(用户明确要的"可再点进去")。 + * 但聊天正文里的链接不一样:那里没有"返回 AI 界面"这个上下文, + * 在应用内开一个 WebView 会让用户迷失(返回键行为说不清)。 + * 交给系统浏览器,行为标准、有历史、有关闭 —— 对正文链接更合适。 + * + * ★ 必须 try/catch:设备上可能没有浏览器(精简 ROM), + * 或者链接协议没人能处理,那会抛 ActivityNotFoundException。 + * 不接的话点一下链接 App 就崩。 + */ +fun openInBrowser(context: android.content.Context, url: String): Boolean { + val u = url.trim() + if (u.isEmpty()) return false + val uri = try { + android.net.Uri.parse(u) + } catch (_: Throwable) { + return false + } + // 只放行有 scheme 的绝对地址;相对地址点了没意义,还会让 Intent 解析失败 + if (uri.scheme.isNullOrBlank()) return false + + return try { + context.startActivity( + android.content.Intent(android.content.Intent.ACTION_VIEW, uri) + .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK), + ) + true + } catch (t: Throwable) { + android.util.Log.w("DoubaoLink", "打不开 $u:${t.javaClass.simpleName}: ${t.message}") + android.widget.Toast + .makeText(context, "打不开这个链接", android.widget.Toast.LENGTH_SHORT) + .show() + false + } +} + /* ------------------------------ 动画 ------------------------------ */ /** 出现时淡入 + 上移一点点(消息气泡、卡片都用它) */ diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/MarkdownText.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/MarkdownText.kt index 3fbebf0..5ef7a0c 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/ui/MarkdownText.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/MarkdownText.kt @@ -13,14 +13,19 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.ExperimentalTextApi +import androidx.compose.ui.text.LinkAnnotation import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.withLink import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -99,17 +104,19 @@ fun MarkdownText( } } - is MdBlock.Heading -> Text( - inline(block.text, linkColor), - fontSize = when (block.level) { - 1 -> (fontSize + 6).sp - 2 -> (fontSize + 3).sp - else -> (fontSize + 1).sp - }, - fontWeight = FontWeight.SemiBold, - lineHeight = (lineHeight + 4).sp, - color = color, - ) + is MdBlock.Heading -> { + Text( + inline(block.text, linkColor), + fontSize = when (block.level) { + 1 -> (fontSize + 6).sp + 2 -> (fontSize + 3).sp + else -> (fontSize + 1).sp + }, + fontWeight = FontWeight.SemiBold, + lineHeight = (lineHeight + 4).sp, + color = color, + ) + } is MdBlock.Bullet -> Row(Modifier.fillMaxWidth()) { Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f)) @@ -147,12 +154,14 @@ fun MarkdownText( .background(color.copy(alpha = 0.15f)), ) - is MdBlock.Paragraph -> Text( - inline(block.text, linkColor), - fontSize = fontSize.sp, - lineHeight = lineHeight.sp, - color = color, - ) + is MdBlock.Paragraph -> { + Text( + inline(block.text, linkColor), + fontSize = fontSize.sp, + lineHeight = lineHeight.sp, + color = color, + ) + } } } } @@ -256,6 +265,38 @@ internal fun parseMarkdown(src: String): List { return out } +/** + * 从 markdown 里抽出所有链接地址(去重、保序)。 + * + * 给"这条回复里有几个网页可看"用 —— 界面据此决定: + * · 0 个 → 不显示「打开网页」按钮 + * · 1 个 → 直接开 + * · 多个 → 先让用户选一个 + * + * ★ 只认完整的绝对地址(有 scheme)。`[文档](docs/x.md)` 这种相对路径 + * 在手机上点了没意义,不算"网页"。 + */ +fun extractUrls(markdown: String): List { + if (!markdown.contains("](")) return emptyList() + val out = LinkedHashSet() + var i = 0 + while (i < markdown.length) { + val close = markdown.indexOf(']', i) + if (close < 0) break + if (close + 1 < markdown.length && markdown[close + 1] == '(') { + val end = markdown.indexOf(')', close + 1) + if (end > close + 1) { + val url = markdown.substring(close + 2, end).trim() + if (url.startsWith("http://") || url.startsWith("https://")) out.add(url) + i = end + 1 + continue + } + } + i = close + 1 + } + return out.toList() +} + /* ------------------------------ 行内解析 ------------------------------ */ /** @@ -264,8 +305,19 @@ internal fun parseMarkdown(src: String): List { * 用一个统一的扫描器而不是一串 replace: * 连环 replace 会把已经生成的标记再吃一遍(比如 `**a**` 生成粗体后, * 里面的 `*` 又会被斜体规则匹配到),结果就是格式错乱。 + * + * ★ 这是个 `@Composable`:链接要用 `withLink(...)` 挂点击, + * 而那个 API 是 composable 的(它内部要拿 `LocalTextLinkScope`)。 + * + * ★ 还要 `@OptIn(ExperimentalTextApi::class)` —— `withLink` 标了实验 API。 + * 不 opt-in 的话报的是 `Unresolved reference 'withLink'`(不是"需要 opt-in"), + * 很容易误判成"这个版本没有这个 API"。我是把 aar 拆开 javap 看了注解才确认的。 */ -internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnnotatedString { +@OptIn(ExperimentalTextApi::class) +@Composable +internal fun inline(text: String, linkColor: Color): AnnotatedString { + val ctx = LocalContext.current + return buildAnnotatedString { var i = 0 while (i < text.length) { when { @@ -325,8 +377,40 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnno val end = if (open > 0) text.indexOf(')', open) else -1 if (close > i && open > 0 && end > open) { val label = text.substring(i + 1, close) - withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) { - append(label) + val url = text.substring(open + 1, end).trim() + /** + * ★★ 给链接**真正绑上点击**。 + * + * 以前这里只有颜色和下划线,**没有 clickable** —— + * 看着像能点、点了完全没反应。用户会以为"链接坏了"。 + * (这是用户问"网页在哪点开"时才查出来的:我一直在讲 + * AI 弹的那个界面,而最容易想到的"点链接"一直是坏的。) + * + * ★ 用 `withLink(LinkAnnotation.Url(...))`:这是 Compose 1.7 + * 起的方式,和 `Text()` 直接配合(不需要 ClickableText), + * 而且**不需要在外部套 pointerInput 去算点击落在哪个字符上**。 + * 那个老办法要自己遍历 annotation 范围,容易算错。 + */ + if (url.isNotEmpty()) { + withLink( + LinkAnnotation.Url( + url = url, + styles = TextLinkStyles( + style = SpanStyle( + color = linkColor, + textDecoration = TextDecoration.Underline, + ), + ), + linkInteractionListener = { link -> + val target = (link as? LinkAnnotation.Url)?.url ?: url + openInBrowser(ctx, target) + }, + ), + ) { append(label) } + } else { + withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) { + append(label) + } } i = end + 1 } else { @@ -339,4 +423,7 @@ internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnno } } } + } } + + diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/WebPageScreen.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/WebPageScreen.kt new file mode 100644 index 0000000..837c001 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/WebPageScreen.kt @@ -0,0 +1,536 @@ +package com.doubao.lynxclone.ui + +import android.annotation.SuppressLint +import android.graphics.Color as AndroidColor +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.ArrowForward +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.OpenInNew +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.TouchApp +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import kotlinx.coroutines.delay + +/** + * ★★ 全屏看网页 —— 由一个**明确的按钮**打开,不靠去点正文里的小字。 + * + * ## 为什么单独做这个界面 + * + * 聊天气泡里的 markdown 链接做成蓝色下划线,**没有可发现性**: + * 用户不知道它能点、也不知道点了会发生什么(是开浏览器?还是在应用里开?)。 + * 用户的原话是"你要单独开个按钮" —— 对,产品上正确的就是给个按钮。 + * + * 所以:消息操作栏里出现一个「打开网页」按钮(只有回复里真有链接才出现), + * 点开就是这里 —— 一个像样的浏览器界面,而不是把用户丢给系统浏览器 + * (那样他就离开 App 了,回来还得重新找对话)。 + * + * ## 和 AI 那个 `show_ui` 界面的区别 + * + * `show_ui` 是 **AI 写的 HTML**,我们注入内容、页面里只有它写的东西 + * 这里 是**真的在浏览互联网**,用户能点链接、能返回、能前进 + * + * 两者都需要 JS,但**桥只有 `show_ui` 那边有** —— 这里浏览的是外部网站, + * 绝不能让它碰到 App 的接口(所以这个 WebView 里没有任何 + * `addJavascriptInterface`)。 + * + * ## 安全 + * + * 文件访问 / 跨域访问 / 混合内容全部关闭。没有注入任何 JS 桥。 + * 这是"浏览器",就该按浏览器的方式隔离。 + * + * ## 点选模式(把网页上的东西回传给 AI) + * + * 顶部有个「点选」按钮。打开之后页面上的可点元素会被描上虚线边框, + * 用户点哪个就把哪个的**文字/链接/位置**记下来,出现在底部确认条上, + * 用户点「发给 AI」才真的发出去(点错了不至于白跑一轮模型)。 + * + * ★ 实现上**没有挂 JS 桥** —— 用的是"注入脚本写进数组 + Kotlin 主动轮询取走", + * 数据只从页面流向 App。理由见 [WebPick] 的注释:这里浏览的是外部网站, + * 挂桥等于把 App 的内部接口交给互联网上任意一个站点。 + */ +@SuppressLint("SetJavaScriptEnabled") +@Composable +fun WebPageScreen( + url: String, + onClose: () -> Unit, + onSendToAi: (String) -> Unit = {}, +) { + val ctx = LocalContext.current + var web by remember { mutableStateOf(null) } + var title by remember(url) { mutableStateOf("") } + var canBack by remember { mutableStateOf(false) } + var canFwd by remember { mutableStateOf(false) } + var progress by remember { mutableStateOf(0) } + + /** 点选模式开着没有 */ + var picking by remember { mutableStateOf(false) } + + /** + * 用户选中/填写的条目(**累积**)。 + * + * ★ 累积而不是点一条发一条:用户可能在页面上选好几处、填几个框, + * 然后一起问"这些对不对"。分开发会触发好几轮模型调用,又慢又费 token。 + */ + val picked = remember { mutableStateListOf() } + + // WebView 没有"导航状态变了"的回调,只能轮询。 + // 400ms 在真机上完全够用(页面前进后退是用户动作,不是动画)。 + LaunchedEffect(web) { + while (web != null) { + canBack = web?.canGoBack() == true + canFwd = web?.canGoForward() == true + delay(400) + } + } + + // 点选模式下:每次加载完注入一次;然后每 500ms 取一次队列。 + // + // ★ 为什么要"每次加载完注入":用户点链接跳到新页面(或页面自己跳), + // 新文档里没有我们注入的脚本,不重注就没法点了。 + LaunchedEffect(web, picking) { + if (!picking || web == null) { + return@LaunchedEffect + } + web?.evaluateJavascript(WebPick.INSTALL_JS, null) + while (true) { + delay(500) + val w = web ?: break + // evaluateJavascript 的返回值经 JSON 编码:脚本返回字符串 'xxx', + // 这里拿到的是 "\"xxx\"" —— 所以要解两层 + w.evaluateJavascript(WebPick.DRAIN_JS) { raw -> + val parsed = decodeJsonString(raw) + if (parsed.isBlank() || parsed == "[]") return@evaluateJavascript + runCatching { + val arr = org.json.JSONArray(parsed) + for (i in 0 until arr.length()) { + val obj = arr.optJSONObject(i) ?: continue + picked.add( + PickedElement( + summary = WebPick.describe(obj), + kind = obj.optString("kind", "click"), + url = obj.optString("url"), + pageTitle = obj.optString("title").ifBlank { title }, + raw = obj.toString(), + ), + ) + } + // 只留最近 30 条,别让用户在页面上乱点把内存堆满 + while (picked.size > 30) picked.removeAt(0) + } + } + } + } + + // 系统返回键:先回退网页,退不了了才关界面 + BackHandler(enabled = true) { + if (web?.canGoBack() == true) web?.goBack() else onClose() + } + + Column( + Modifier + .fillMaxSize() + .background(doubaoBg()), + ) { + /* ------------------------------ 顶部栏 ------------------------------ */ + Row( + Modifier + .fillMaxWidth() + .background(doubaoSurface()) + .padding(start = 6.dp, end = 6.dp, top = 8.dp, bottom = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + NavIcon(Icons.AutoMirrored.Filled.ArrowBack, "后退", canBack) { web?.goBack() } + NavIcon(Icons.AutoMirrored.Filled.ArrowForward, "前进", canFwd) { web?.goForward() } + NavIcon(Icons.Filled.Refresh, "刷新", true) { web?.reload() } + + // 标题:能拿到网页 title 就用它,拿不到退回落 host —— + // 只显示一长串 URL 在手机窄屏上没法看 + Column(Modifier.weight(1f).padding(horizontal = 4.dp)) { + Text( + title.ifBlank { hostOf(url) }, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (title.isNotBlank()) { + Text( + hostOf(url), + fontSize = 11.sp, + color = doubaoTextDim(), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + + NavIcon(Icons.Filled.OpenInNew, "用系统浏览器打开", true) { + openInBrowser(ctx, web?.url ?: url) + } + NavIcon(Icons.Filled.Close, "关闭", true) { onClose() } + } + + /** + * 「点选」开关 —— 打开后能在网页上点东西回传给 AI。 + * + * ★ 做成一条**常驻的横条**而不是顶部一个图标: + * 这个能力不看说明根本发现不了(用户得先知道"能点选"才会去找按钮)。 + * 横条上写清楚现在是什么状态、点了会发生什么。 + */ + Row( + Modifier + .fillMaxWidth() + .background(if (picking) doubaoAccentSoft() else doubaoCard()) + .clickable { + if (picking) { + web?.evaluateJavascript(WebPick.UNINSTALL_JS, null) + picking = false + picked.clear() + } else { + picking = true + } + } + .padding(horizontal = 14.dp, vertical = 9.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + Icons.Filled.TouchApp, + null, + tint = if (picking) doubaoAccent() else doubaoTextSecondary(), + modifier = Modifier.size(17.dp), + ) + Spacer(Modifier.width(8.dp)) + Text( + if (picking) "点选已开启 —— 点网页上任意元素,内容会带回给 AI" else "点选:把网页上的内容带回给 AI", + fontSize = 13.sp, + color = if (picking) doubaoAccent() else doubaoText(), + modifier = Modifier.weight(1f), + ) + Text( + if (picking) "关闭" else "开启", + fontSize = 13.sp, + color = if (picking) doubaoAccent() else doubaoTextSecondary(), + ) + } + + // 加载进度:细一条,不占地方但能让人知道"在动" + AnimatedVisibility( + visible = progress in 1..99, + enter = fadeIn(tween(120)), + exit = fadeOut(tween(300)), + ) { + Box( + Modifier + .fillMaxWidth(progress / 100f) + .height(2.dp) + .background(doubaoAccent()), + ) + } + + AndroidView( + modifier = Modifier.fillMaxSize(), + factory = { c -> + WebView(c).apply { + setBackgroundColor(AndroidColor.TRANSPARENT) + settings.javaScriptEnabled = true + settings.domStorageEnabled = true // 正常浏览器行为 + settings.allowFileAccess = false + settings.allowContentAccess = false + settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW + settings.useWideViewPort = true + settings.loadWithOverviewMode = true + settings.builtInZoomControls = true + settings.displayZoomControls = false + settings.userAgentString = settings.userAgentString + " DoubaoClone" + + // ★ 这个 WebView 里**不挂任何 JS 桥** —— + // 浏览的是外部网站,绝不能让它碰到 App 的接口。 + // (点选回传走的是"页面写队列 + 我们主动 evaluateJavascript 取", + // 数据单向,页面没有办法主动调 App。见 WebPick 的注释。) + webViewClient = object : WebViewClient() { + override fun onPageStarted(view: WebView?, u: String?, favicon: android.graphics.Bitmap?) { + super.onPageStarted(view, u, favicon) + progress = 5 + } + + override fun onPageFinished(view: WebView?, u: String?) { + super.onPageFinished(view, u) + progress = 100 + title = view?.title.orEmpty() + // ★ 用户点链接跳到新页面(或页面自己跳)之后, + // 新文档里没有我们注入的脚本 —— 点选模式就失效了。 + // 所以每次加载完补注一次(脚本自己防重)。 + if (picking) view?.evaluateJavascript(WebPick.INSTALL_JS, null) + } + } + webChromeClient = object : android.webkit.WebChromeClient() { + override fun onProgressChanged(view: WebView?, newProgress: Int) { + progress = newProgress + } + + override fun onReceivedTitle(view: WebView?, t: String?) { + if (!t.isNullOrBlank()) title = t + } + } + loadUrl(url) + web = this + } + }, + ) + + /** + * 底部确认条:用户点中了什么,以及「发给 AI / 取消」。 + * + * ★ 为什么要有这一步而不是点了就发: + * 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token, + * 而模型会基于一个错误的前提回答。 + * 让用户确认一下,成本极低、收益很大。 + */ + /** + * 底部确认条:用户攒了哪些"选了/写了"的内容,以及 + * 「发给 AI」「清空」。 + * + * ★ 为什么要有这一步而不是点了就发: + * 用户可能点错元素。点错就直接触发一整轮模型调用,既慢又费 token, + * 而模型会基于一个错误的前提回答。 + * 让用户确认一下,成本极低、收益很大。 + * + * ★ 支持**累积多条**再一起发 —— 用户在页面上选几处、填几个框, + * 最后一起问"这些对不对"。分开发会跑好几轮模型。 + */ + AnimatedVisibility( + visible = picked.isNotEmpty(), + enter = slideInVertically(tween(220)) { it } + fadeIn(tween(160)), + exit = slideOutVertically(tween(180)) { it } + fadeOut(tween(120)), + ) { + Column( + Modifier + .fillMaxWidth() + .background(doubaoSurface()) + .padding(horizontal = 14.dp, vertical = 12.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + "已选 ${picked.size} 条,会一起发给 AI:", + fontSize = 12.sp, + color = doubaoTextSecondary(), + modifier = Modifier.weight(1f), + ) + Text( + "清空", + fontSize = 12.sp, + color = doubaoAccent(), + modifier = Modifier.clickable { picked.clear() }, + ) + } + Spacer(Modifier.height(6.dp)) + + // 条目多了要能滚 —— 但只占一段固定高度,别把网页挤没了 + Column( + Modifier + .heightIn(max = 120.dp) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + picked.forEach { p -> + Text( + "· " + p.summary, + fontSize = 13.sp, + lineHeight = 18.sp, + color = doubaoText(), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + + Spacer(Modifier.height(11.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + androidx.compose.material3.OutlinedButton( + onClick = { picked.clear() }, + modifier = Modifier.weight(1f), + ) { Text("取消") } + androidx.compose.material3.Button( + onClick = { + onSendToAi(WebPick.buildReport(picked.toList())) + picked.clear() + }, + modifier = Modifier.weight(1f), + ) { Text("发给 AI") } + } + } + } + } +} + +/** + * `evaluateJavascript` 的返回值是**经 JSON 编码的字符串**(脚本返回 `'abc'` + * 时 Kotlin 拿到的是 `"\"abc\""`)。 + * + * ★ 这个坑踩过两次([AiWebView] 的探针、这里),所以抽成一个函数, + * 并在名字上把"要解两层"这件事写出来。 + */ +private fun decodeJsonString(raw: String?): String { + val s = (raw ?: "").trim() + if (s.isEmpty() || s == "null") return "" + return try { + if (s.startsWith("\"")) org.json.JSONTokener(s).nextValue() as? String ?: "" else s + } catch (_: Throwable) { + s.trim('"') + } +} + +@Composable +private fun NavIcon( + icon: androidx.compose.ui.graphics.vector.ImageVector, + desc: String, + enabled: Boolean, + onClick: () -> Unit, +) { + Box( + Modifier + .size(34.dp) + .clip(CircleShape) + // 不能点的时候**也要占位**(否则顶部栏的图标会左右跳), + // 但变淡 + 不响应点击 + .clickable(enabled = enabled) { onClick() }, + contentAlignment = Alignment.Center, + ) { + Icon( + icon, + desc, + tint = if (enabled) doubaoText() else doubaoTextDim().copy(alpha = 0.35f), + modifier = Modifier.size(19.dp), + ) + } +} + +/** 从 URL 里取主机名(显示用)。解析不了就原样返回。 */ +private fun hostOf(url: String): String = try { + android.net.Uri.parse(url).host ?: url +} catch (_: Throwable) { + url +} + +/** + * 「要打开哪个网页?」—— **独立全屏界面**,不是弹窗。 + * + * ## 为什么不用 AlertDialog + * + * 项目约定:**列表这种要滚动的东西不用弹窗**。一条回复里挂五六个链接是常事, + * 弹窗一屏只装得下三四个,用户得在弹窗里滚动 —— 那还不如直接开一屏。 + * 而且弹窗盖住对话,用户没法一边看着回复一边挑链接。 + * + * 顶栏按项目约定:`← 返回 | 标题 | 副标题`。 + */ +@Composable +fun UrlListScreen(owner: String, urls: List, onPick: (String) -> Unit, onClose: () -> Unit) { + BackHandler(enabled = true) { onClose() } + + Column( + Modifier + .fillMaxSize() + .background(doubaoBg()), + ) { + ScreenHeader("打开网页", onBack = onClose) { + Text("${urls.size} 个链接", fontSize = 13.sp, color = doubaoTextSecondary()) + } + + LazyColumn( + Modifier.fillMaxSize(), + contentPadding = PaddingValues(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + item { + Text("$owner 里提到的网页:", fontSize = 13.sp, color = doubaoTextSecondary()) + } + items(urls.size) { index -> + val u = urls[index] + Row( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(14.dp)) + .background(doubaoSurfaceAlt()) + .clickable { onPick(u) } + .padding(horizontal = 14.dp, vertical = 13.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text( + hostOf(u), + fontSize = 15.sp, + fontWeight = FontWeight.Medium, + color = doubaoText(), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.height(3.dp)) + Text( + u, + fontSize = 12.sp, + color = doubaoTextDim(), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + Spacer(Modifier.width(10.dp)) + Icon( + Icons.Filled.OpenInNew, + null, + tint = doubaoTextDim(), + modifier = Modifier.size(18.dp), + ) + } + } + } + } +} diff --git a/android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt b/android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt new file mode 100644 index 0000000..313e889 --- /dev/null +++ b/android/app/src/main/java/com/doubao/lynxclone/ui/WebPick.kt @@ -0,0 +1,370 @@ +package com.doubao.lynxclone.ui + +import org.json.JSONObject + +/** + * ★★★ 在**真实网页**上点选,把点到的内容回传给 AI。 + * + * ## 为什么不用 `@JavascriptInterface` 桥 + * + * `show_ui` 那个界面里我们挂了 `Doubao` 桥,但那只挂在**我们自己注入的那一页**上, + * 一导航到外部站点就摘掉了(见 [AiWebView] 的注释)。 + * + * 这里不同:**用户就是在浏览外部网站**,全程都在别人的页面上。 + * 要是挂桥,等于把 App 的内部接口暴露给互联网上任意一个站点 —— 绝对不能这么干。 + * + * ## 改用"单向队列 + 主动轮询" + * + * ``` + * 注入的脚本(页面里) Kotlin 侧 + * ──────────────────── ────────────── + * 用户点了 → 写进 window.__doubaoPicks + * setInterval 每 500ms + * evaluateJavascript("取走队列") + * ← 拿到 JSON + * ``` + * + * 数据**只从页面流向 App**,而且只有这一个取数入口(`evaluateJavascript`)。 + * 页面**没有任何办法**主动调用 App —— 它只能往一个数组里塞东西, + * 而那个数组的内容是我们主动去读的、并且读之前会做类型和长度校验。 + * + * ★ 注意 `evaluateJavascript` 的返回值经 JSON 编码,所以脚本里用 + * `JSON.stringify(...)` 返回**字符串**,Kotlin 这边再解一层。 + * (这个坑在 [AiWebView] 那边也踩过。) + */ +object WebPick { + + /** 队列变量名。用不常见的名字,尽量不和页面自己的变量撞。 */ + private const val QUEUE = "__doubaoPicks" + + /** + * 注入的脚本。 + * + * 做三件事: + * 1. 给页面上**真正的链接/按钮**加虚线高亮(视觉提示) + * 2. 捕获点击(**捕获阶段**,抢在页面自己的 handler 前面) + * 3. 把点到的元素信息写进队列,并阻止这次跳转 + * + * ★★ 改过一版:从"只能点可点元素"改成"**点哪儿抓哪儿**"。 + * + * 第一版只给 `a,button,[role=button],...` 这些**看着能点**的元素加框, + * 点击也只认这些。实测在 example.com 上**一个都标不出来** —— + * 那页全是纯文本,没有任何按钮链接,于是"点选模式"看起来完全没生效。 + * + * 我的假设错了:用户想点的不一定是"可点元素",他想点的就是 + * **页面上任意一段内容**("把这段告诉 AI")。 + * 所以现在点击用 `elementFromPoint` 抓,**点哪儿抓哪儿**; + * 虚线框降级成纯视觉提示,不再限制能点什么。 + * + * ★ 为什么用捕获阶段 + `preventDefault`: + * 如果一个链接上挂着页面的点击统计脚本,冒泡阶段再加我们的监听就晚了。 + * 捕获阶段先拿到,`stopPropagation` 之后页面完全不知道被点过, + * 也就不会跳走 —— 用户点一下是"选中",不是"跳转"。 + * + * ★ 用 IIFE 包起来 + 可重复注入(先看有没有装过): + * 每次页面加载完都会注入一遍,不防重会叠出好几层监听, + * 一次点击写好几条重复记录。 + */ + val INSTALL_JS: String = """ +(function () { + if (window.__doubaoPickInstalled) { return '1'; } + window.__doubaoPickInstalled = 1; + window.$QUEUE = []; + + // 只用来**画虚线框**(提示哪些是链接/按钮)。点击不受它限制。 + var HINT_SEL = 'a,button,[role=button],input,select,textarea,label,summary'; + + function visible(el) { + if (!el || !el.getBoundingClientRect) { return false; } + var r = el.getBoundingClientRect(); + if (r.width < 8 || r.height < 8) { return false; } + var s = window.getComputedStyle(el); + return s.display !== 'none' && s.visibility !== 'hidden' && s.opacity !== '0'; + } + + function textOf(el) { + var t = (el.innerText || el.textContent || el.value || el.getAttribute('aria-label') + || el.getAttribute('title') || el.getAttribute('placeholder') || ''); + t = t.replace(/\s+/g, ' ').trim(); + return t.slice(0, 300); + } + + function mark() { + var list = document.querySelectorAll(HINT_SEL); + for (var i = 0; i < list.length && i < 400; i++) { + var el = list[i]; + if (el.__doubaoMarked || !visible(el)) { continue; } + el.__doubaoMarked = 1; + el.style.outline = '2px dashed rgba(76,141,255,.75)'; + el.style.outlineOffset = '1px'; + el.style.cursor = 'pointer'; + } + return list.length; + } + + function onClick(e) { + // ★★ 点哪儿抓哪儿:优先用坐标取元素,**不要求它"看起来能点"**。 + // + // 第一版是"从 e.target 往上找最近的可点元素",找不到就退回 e.target —— + // 在纯文本页面上用户点一段话,抓到的是最里层的 /, + // 甚至可能是个没文字的容器。用坐标取到的是**用户真正看到的那个块**。 + var el = null; + try { + if (e.clientX || e.clientY) { + el = document.elementFromPoint(e.clientX, e.clientY); + } + } catch (err) { el = null; } + if (!el) { el = e.target; } + + // 取到的可能是很里层的小元素(一个 、一个 )。 + // 往上走几层,让选中的是"一整段有意义的内容"而不是一个词。 + var hop = 0; + while (el && el.parentElement && hop < 3) { + var t = (el.innerText || el.textContent || '').trim(); + // 文字够多就停 —— 说明这一层已经是个完整段落了 + if (t.length >= 12) { break; } + // 或者这一层本身就是链接/按钮,那也停(点链接当然要抓链接) + if (el.matches && el.matches(HINT_SEL)) { break; } + el = el.parentElement; hop++; + } + if (!el || el === document.documentElement) { el = e.target; } + + var rec = { + tag: (el.tagName || '').toLowerCase(), + text: textOf(el), + href: el.href || '', + id: el.id || '', + cls: (typeof el.className === 'string' ? el.className : '').slice(0, 120), + path: (function () { + var p = [], n = el, d = 0; + while (n && n.tagName && d < 4) { + var s = n.tagName.toLowerCase(); + if (n.id) { s += '#' + n.id; } + else if (typeof n.className === 'string' && n.className) { + s += '.' + n.className.trim().split(/\s+/).slice(0, 2).join('.'); + } + p.unshift(s); n = n.parentElement; d++; + } + return p.join(' > '); + })(), + title: document.title || '', + url: location.href || '', + kind: 'click' + }; + window.$QUEUE.push(rec); + + // 选中效果:给点到的那个元素一个实线高亮,然后褪成虚线 + try { + el.style.outline = '3px solid #4c8dff'; + setTimeout(function () { el.style.outline = '2px dashed rgba(76,141,255,.75)'; }, 700); + } catch (err) {} + + // ★ 关键:拦掉这次点击 —— 用户是"选中"不是"跳转"。 + // 不拦的话点个链接页面就跳走了,用户根本来不及看"已选中"提示。 + e.preventDefault(); + e.stopPropagation(); + return false; + } + + /** + * 用户**写了什么** —— 表单输入 / 下拉选择 / 勾选框。 + * + * ★ 用户明确要求"让 AI 知道用户选择了什么、**写了什么**"。 + * 光有"点了什么"不够:填表场景里真正重要的是填进去的内容。 + * + * ★ 用 input/change 的**冒泡阶段**(不用捕获):这类事件页面自己也要处理 + * (自动补全、字数统计),拦掉会破坏页面功能。我们只是**旁听**,不干预。 + * + * ★ 同一个输入框连续打字会触发很多次 input —— 每 600ms 合并一次, + * 否则用户打十个字会往队列里塞十条,报告变得没法看。 + */ + var pending = {}; + function labelOf(el) { + var s = el.getAttribute('aria-label') || el.getAttribute('placeholder') + || el.getAttribute('name') || el.id || ''; + if (!s) { + var lab = el.closest ? el.closest('label') : null; + if (lab) { s = (lab.innerText || '').trim().slice(0, 60); } + } + if (!s && el.previousElementSibling) { + s = (el.previousElementSibling.innerText || '').trim().slice(0, 60); + } + return s; + } + + function flush(key) { + var el = pending[key]; + if (!el) { return; } + delete pending[key]; + var val = ''; + if (el.type === 'checkbox' || el.type === 'radio') { val = el.checked ? '已勾选' : '未勾选'; } + else { val = (el.value || '').slice(0, 500); } + if (!val) { return; } + window.$QUEUE.push({ + kind: 'input', + tag: (el.tagName || '').toLowerCase(), + type: el.type || '', + label: labelOf(el), + text: val, + href: '', + id: el.id || '', + cls: (typeof el.className === 'string' ? el.className : '').slice(0, 120), + path: '', + title: document.title || '', + url: location.href || '' + }); + } + + function onInput(e) { + var el = e.target; + if (!el || !el.tagName) { return; } + var t = (el.tagName || '').toLowerCase(); + if (t !== 'input' && t !== 'textarea' && t !== 'select') { return; } + var key = (el.id || '') + '|' + (el.name || '') + '|' + + (el.getAttribute('placeholder') || '') + '|' + (el.type || ''); + pending[key] = el; + if (el.__doubaoDebounce) { clearTimeout(el.__doubaoDebounce); } + el.__doubaoDebounce = setTimeout(function () { flush(key); }, 600); + } + + document.addEventListener('input', onInput, false); + document.addEventListener('change', onInput, false); + // 失焦时立刻结算(用户填完就去点别的地方了,不等那 600ms) + document.addEventListener('blur', function (e) { + var el = e.target; + if (!el || !el.tagName) { return; } + var key = (el.id || '') + '|' + (el.name || '') + '|' + + (el.getAttribute('placeholder') || '') + '|' + (el.type || ''); + flush(key); + }, true); + + document.addEventListener('click', onClick, true); + + // 动态加载的页面(下拉刷新、无限滚动)也要能点 —— 隔一会儿重新标一次 + var ticks = 0; + var timer = setInterval(function () { + mark(); ticks++; + if (ticks > 40) { clearInterval(timer); } + }, 1500); + + mark(); + return '1'; +})() +""" + + /** + * 取走队列(取完清空)。 + * + * ★ 一定要"取走"而不是"读":读的话每次轮询都会把同一条记录 + * 重复报上来,用户点一下会触发十几次。 + */ + val DRAIN_JS: String = """ +(function () { + try { + var q = window.$QUEUE || []; + window.$QUEUE = []; + return JSON.stringify(q.slice(0, 20)); + } catch (e) { return '[]'; } +})() +""" + + /** 撤销高亮 + 拆掉监听(退出点选模式时调) */ + val UNINSTALL_JS: String = """ +(function () { + try { + window.__doubaoPickInstalled = 0; + window.$QUEUE = []; + var list = document.querySelectorAll('[style]'); + for (var i = 0; i < list.length; i++) { + var el = list[i]; + if (el.__doubaoMarked) { + el.style.outline = ''; + el.style.outlineOffset = ''; + el.style.cursor = ''; + el.__doubaoMarked = 0; + } + } + return '1'; + } catch (e) { return '0'; } +})() +""" + + /** + * 把一条记录整理成给模型看的一行字。 + * + * ★ 刻意做成**紧凑的一行**,而不是把整个 JSON 丢给模型: + * 模型需要的是"用户干了什么",不是 DOM 的所有细节。 + * 附带页面标题和 URL,帮它知道用户在哪个页面操作的。 + * + * ★ 分两种 `kind`: + * · `click` —— 用户**点了/选了**一个元素(链接、按钮、一段文字) + * · `input` —— 用户**写了**内容(输入框、下拉、勾选框) + * 用户的原话是"让 AI 知道用户选择了什么、写了什么",就是这两类。 + */ + fun describe(json: JSONObject): String { + val parts = mutableListOf() + val kind = json.optString("kind", "click") + val text = json.optString("text").trim() + val tag = json.optString("tag") + val type = json.optString("type") + val label = json.optString("label").trim() + val href = json.optString("href") + val id = json.optString("id") + val path = json.optString("path") + + if (kind == "input") { + val what = if (type == "checkbox" || type == "radio") "勾选" else "填写" + parts.add("用户$what:${text.ifEmpty { "(空)" }}") + if (label.isNotEmpty()) parts.add("字段:$label") + parts.add("控件:<$tag" + (if (type.isNotEmpty()) " type=$type" else "") + ">") + } else { + if (text.isNotEmpty()) parts.add("内容:$text") + parts.add("元素:<$tag>" + (if (id.isNotEmpty()) " #$id" else "")) + if (href.isNotEmpty()) parts.add("链接:$href") + if (path.isNotEmpty()) parts.add("位置:$path") + } + return parts.joinToString(";") + } + + /** + * 把多条记录汇总成一段给模型的话。 + * + * ★ 一次性发送多条(而不是点一条发一条): + * 用户可能在页面上选了好几处、填了几个框,然后一起问"这些对不对"。 + * 分开发会触发好几轮模型调用,既慢又费 token。 + */ + fun buildReport(items: List): String = buildString { + append("我在网页上") + val clicks = items.count { it.kind != "input" } + val inputs = items.count { it.kind == "input" } + val bits = mutableListOf() + if (clicks > 0) bits.add("选了 $clicks 处") + if (inputs > 0) bits.add("填了 $inputs 处") + append(bits.joinToString("、").ifEmpty { "选了一些东西" }) + append(":\n") + items.forEachIndexed { i, it -> + append("${i + 1}. ${it.summary}\n") + } + val first = items.firstOrNull() + if (first != null && first.url.isNotBlank()) append("\n页面:${first.url}") + if (first != null && first.pageTitle.isNotBlank()) append("\n标题:${first.pageTitle}") + } +} + +/** + * 点选模式下用户选中/填写、但**还没决定要不要发给 AI** 的那一条。 + * + * ★ 为什么要中间这一步(而不是点了就直接发): + * 用户可能点错了元素。点错就直接触发一整轮模型调用,既慢又费 token, + * 而且模型会基于一个错误的前提回答。让用户确认一下,成本极低、收益很大。 + * + * ★ 支持累积多条:用户可以连着点好几处、填几个框,最后一起发。 + */ +data class PickedElement( + val summary: String, + /** click / input —— 是"点了什么"还是"写了什么" */ + val kind: String, + val url: String, + val pageTitle: String, + val raw: String, +) diff --git a/scripts/probe-check-conv.py b/scripts/probe-check-conv.py new file mode 100644 index 0000000..d2e3b38 --- /dev/null +++ b/scripts/probe-check-conv.py @@ -0,0 +1,34 @@ +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" + + +def call(path, payload=None, method="POST", timeout=60): + 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")) + + +convs = call("/api/conversations", method="GET").get("conversations") or [] +print("会话:") +for c in convs: + print(" ", c.get("id"), "|", c.get("title"), "| 消息", c.get("messageCount"), + "| updated", c.get("updatedAt")) + +# 直接看 c_main 里到底有没有消息 +full = call("/api/conversations/c_main", method="GET").get("conversation") or {} +msgs = full.get("messages") or [] +print(f"\nc_main 里 {len(msgs)} 条消息:") +for m in msgs: + print(" ", m.get("role"), "|", repr((m.get("content") or "")[:60])) diff --git a/scripts/probe-seed-link-msg.py b/scripts/probe-seed-link-msg.py new file mode 100644 index 0000000..873a7fa --- /dev/null +++ b/scripts/probe-seed-link-msg.py @@ -0,0 +1,62 @@ +"""给会话塞一条带链接的助手回复,用来测「打开网页」按钮。 + +★ 为什么要造数据而不是真让模型回一条: + 真回一条要配 API key、要等流式、还有网络不确定性 —— 而我们这里要测的是 + **界面上那个按钮在不在、点了对不对**,跟回复怎么来的无关。 + 直接写一条一样的消息,测起来快且稳定。 +""" +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" + + +def call(path, payload=None, method="POST", timeout=60): + 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")) + + +convs = call("/api/conversations", method="GET").get("conversations") or [] +print("会话数:", len(convs)) +for c in convs[:5]: + print(" ", c.get("id"), "|", c.get("title"), "| 消息", c.get("messageCount")) + +if not convs: + print("!! 没有会话") + sys.exit(1) + +cid = convs[0]["id"] +print(f"\n往 {cid} 里塞一条带链接的回复…") + +content = ( + "我查到了几个可能有用的页面:\n\n" + "- [Example 官网](https://example.com)\n" + "- [Example 中文](https://example.com/index-zh)\n\n" + "**说明**:这两个是示例域名,用来验证「打开网页」按钮。\n" + "还有一个没有链接的说法:这是个普通段落。" +) + +res = call(f"/api/conversations/{cid}", { + "messages": [ + {"role": "user", "content": "帮我找几个网页"}, + {"role": "assistant", "content": content}, + ], +}, method="PATCH") +print("写入结果:", json.dumps(res, ensure_ascii=False)[:200]) + +full = call(f"/api/conversations/{cid}", method="GET").get("conversation") or {} +msgs = full.get("messages") or [] +print("现在有", len(msgs), "条消息") +for m in msgs: + print(" ", m.get("role"), "|", (m.get("content") or "")[:50].replace("\n", " ")) diff --git a/scripts/verify-web-pick.py b/scripts/verify-web-pick.py new file mode 100644 index 0000000..15ef98f --- /dev/null +++ b/scripts/verify-web-pick.py @@ -0,0 +1,264 @@ +"""守「网页点选回传给 AI」这条链路的硬性质。 + +## 为什么这些性质值得钉住 + +这条链路最容易被"顺手写成不安全"的地方,就是**给外部网页挂 JS 桥**。 +看起来最省事:`addJavascriptInterface` 一下,页面里 `Doubao.pick(...)` 就完事。 +但这里浏览的是**互联网上任意一个站点** —— 挂桥等于把 App 的内部接口交出去。 + +所以这里守的第一条就是:**没有桥**,改用"页面写数组 + Kotlin 主动轮询取走", +数据只从页面流向 App,页面**没有任何办法**主动调 App。 + +用法: + python scripts/verify-web-pick.py +""" + +import os +import re +import sys + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +UI = os.path.join(WS, "android", "app", "src", "main", "java", "com", "doubao", "lynxclone", "ui") + +fails = [] + + +def fail(m): + fails.append(m) + print(f" ✗ {m}") + + +def ok(m): + print(f" ✓ {m}") + + +def read(name): + p = os.path.join(UI, name) + if not os.path.isfile(p): + print(f"!! 找不到 {p}") + sys.exit(1) + # ★ 只去块注释,不去行注释 —— 行注释里常有 "http://" 之类的字符串, + # 第一版验证脚本就是这么把自己坑了的(见 verify-ai-webview.py)。 + return re.sub(r"/\*.*?\*/", "", open(p, encoding="utf-8").read(), flags=re.DOTALL) + + +web = read("WebPageScreen.kt") +pick = read("WebPick.kt") +root = read("AppRoot.kt") +chat = read("ChatScreen.kt") +vm = read("AppViewModel.kt") +md = read("MarkdownText.kt") + +print("=== 一、安全性(最重要)===") + +# 1. 浏览外部网站的 WebView 绝不能挂桥 +# +# ★ 判据要**排除注释**:源码里有一句"这个 WebView 里不挂任何 JS 桥", +# 第一版直接在这份去块注释的文本里找 `addJavascriptInterface`,被那句话 +# 绊了个跟头(同一类误报在 verify-ai-webview.py 里也出过一次)。 +# 所以只看**去掉所有注释行**之后的代码。 +code_only = "\n".join( + ln for ln in web.splitlines() if not ln.strip().startswith("//") +) + +if "addJavascriptInterface" in code_only: + fail("WebPageScreen 里挂了 JavascriptInterface —— 浏览外部网站时绝不能这么干") +else: + ok("WebPageScreen 的代码里没有 addJavascriptInterface(外部页面碰不到 App)") + +# ★ 判据要收窄:`Doubao` 这个名字在这份文件里到处都有 +# (`Doubao.Blue`、`doubaoText()`、`DoubaoClone` 的 UA), +# 光找 "Doubao" 永远会红。真正该防的是**桥方法的调用**。 +bridge_call = re.search(r"Doubao\s*\.\s*(pick|close)\s*\(", code_only) +if bridge_call: + fail(f"外部浏览这条路上出现了桥方法调用:{bridge_call.group(0)}") +else: + ok("外部浏览这条路上没有桥方法调用(pick/close 都不在)") + +# 2. 通信必须是"页面写队列 + App 主动取",而不是页面主动调 +if "evaluateJavascript" in web: + ok("用 evaluateJavascript 主动取数据(单向)") +else: + fail("没有 evaluateJavascript,取不到页面数据") + +if "DRAIN_JS" in web and "INSTALL_JS" in web: + ok("注入脚本 + 取数脚本都在") +else: + fail("缺少注入或取数脚本") + +# 3. 取数必须"取走"而不是"只读"(否则每轮询一次重复报一次) +if "window.$QUEUE = [];" in pick or "window.__doubaoPicks = [];" in pick: + ok("取数时清空队列(不会重复上报)") +else: + fail("取数没清空队列 —— 用户点一下会被重复上报十几次") + +# 4. 危险开关仍然关着 +for name, pat in ( + ("allowFileAccess", r"allowFileAccess\s*=\s*false"), + ("allowContentAccess", r"allowContentAccess\s*=\s*false"), + ("混合内容", r"MIXED_CONTENT_NEVER_ALLOW"), +): + if re.search(pat, web): + ok(f"{name} 关着") + else: + fail(f"{name} 没关") + +print("\n=== 二、点选脚本本身的正确性 ===") + +# 点选要拦掉默认行为(用户是"选中"不是"跳转") +if "preventDefault" in pick and "stopPropagation" in pick: + ok("拦掉默认行为(点链接不会跳走)") +else: + fail("没拦默认行为 —— 点个链接页面就跳走了,用户来不及看选中提示") + +# 捕获阶段 +if re.search(r"addEventListener\('click',\s*onClick,\s*true\)", pick): + ok("用捕获阶段监听(抢在页面自己的 handler 前面)") +else: + fail("不是捕获阶段 —— 页面自己的点击脚本会先跑") + +# 防重注入 +if "__doubaoPickInstalled" in pick: + ok("防重注入(每次加载完补注不会叠监听)") +else: + fail("没有防重 —— 多次注入会叠出好几层监听,一次点击写多条重复记录") + +# 字段要够模型用 +for field in ("text", "href", "tag", "path", "title", "url"): + if f"{field}:" in pick: + ok(f"记录了 {field}") + break +else: + fail("记录里没有可用字段") + +print("\n=== 三、用户体验 ===") + +# 点错了要能反悔 +if "PickedElement" in web and "发给 AI" in web: + ok("有「发给 AI / 取消」确认条(点错了不会白跑一轮模型)") +else: + fail("点了就直接发 —— 点错会触发一整轮模型调用,又慢又费 token") + +# 发给 AI 要走普通发消息那条路 +if "sendExternal" in vm and "runChat" in vm: + ok("走普通发消息那条路(会显示在对话里、能重新生成)") +else: + fail("不是我预想的路径") + +if "sendExternal" in root: + ok("AppRoot 把点选结果接到 ViewModel") +else: + fail("点选结果没接上") + +print("\n=== 四、链接能被打开(用户之前问过的)===") + +if "extractUrls" in md: + ok("有 extractUrls(从 markdown 抽链接)") +else: + fail("没有 extractUrls") + +if "打开网页" in chat: + ok("消息下方有「打开网页」按钮(用户要求的『单独开个按钮』)") +else: + fail("没有「打开网页」按钮") + +if "withLink" in md and "LinkAnnotation" in md: + ok("正文里的链接也绑了点击(不只是按钮)") +else: + fail("正文链接没绑点击") + +if "ExperimentalTextApi" in md: + ok("withLink 做了 @OptIn(它是实验 API,不 opt-in 报的是 Unresolved reference)") +else: + fail("withLink 没有 @OptIn(ExperimentalTextApi) —— 编译会报 Unresolved reference") + +print("\n=== 五、按项目约定:列表用全屏界面而不是弹窗 ===") + +if "UrlListScreen" in web: + ok("链接列表是独立全屏界面") +else: + fail("没有 UrlListScreen") + +if "UrlChooser" in web or "UrlChooser" in root: + fail("还在用弹窗版的 UrlChooser —— 项目约定是列表要全屏") +else: + ok("没有残留的弹窗版 UrlChooser") + +print("\n=== 六、接口覆盖「选了 / 写了 / 关闭」三类 ===") + +# 用户明确要求:接口要让 AI 知道用户"选择了什么、写了什么",还能"关闭这个网页"。 + +# 1. 写了什么(表单输入) +if "addEventListener('input'" in pick or 'addEventListener("input"' in pick: + ok("监听 input(能知道用户**写了什么**)") +else: + fail("没监听 input —— AI 拿不到用户填的内容") + +if "kind: 'input'" in pick and "kind: 'click'" in pick: + ok("两类记录分开了(click 是'选了'、input 是'写了')") +else: + fail("记录没有区分类型") + +if "checkbox" in pick or "radio" in pick: + ok("勾选框/单选框也认(值是'已勾选/未勾选')") +else: + fail("勾选框没处理") + +# 输入事件不能拦(拦了会破坏页面的自动补全、字数统计) +if re.search(r"addEventListener\('input',\s*onInput,\s*false\)", pick): + ok("input 用冒泡阶段旁听,不拦页面自己的处理") +else: + fail("input 的处理方式不对(可能是捕获+拦截,会破坏页面功能)") + +# 防抖:连续打字不能塞一堆重复记录 +if "setTimeout" in pick and "600" in pick: + ok("输入做了防抖(打十个字不会塞十条记录)") +else: + fail("输入没防抖 —— 报告会变得没法看") + +# 2. 多条累积 +if "buildReport" in pick: + ok("有 buildReport(多条汇总成一段给模型的话)") +else: + fail("没有汇总函数 —— 用户选五处就得发五次") + +if "mutableStateListOf" in web: + ok("界面侧用列表累积多条") +else: + fail("界面侧只存了一条") + +# 3. 关闭这个网页 +if "closeWebPage" in vm: + ok("有 closeWebPage(接口能关闭这个网页)") +else: + fail("没有关闭网页的入口") + +if "onClose = { vm.closeWebPage() }" in root: + ok("网页界面接上了关闭") +else: + fail("关闭没接上") + +# 4. 我们自己的 HTML 页面(show_ui)那边能关闭 + 回传 +# +# ★ 只查 "Doubao.close"(不带括号):那个字符串在 py 源码里是 +# `"\n 也可以用 Doubao.close() 关掉界面。"` 的形式, +# `)` 后面紧跟的是 `\`,查带括号的完整串会因为转义而对不上。 +# (这是这个验证脚本第三次自己绊自己了,记一笔。) +show_ui_src = open(os.path.join(WS, "tools", "show_ui.py"), encoding="utf-8").read() +if "Doubao.close" in show_ui_src and "Doubao.pick" in show_ui_src: + ok("show_ui 的说明里告诉模型能关界面、能回传(Doubao.close / Doubao.pick)") +else: + fail("show_ui 的说明里没告诉模型能关界面或回传") + +print() +if fails: + print(f"❌ {len(fails)} 项不合格:") + for m in fails: + print(" -", m) + sys.exit(1) +print("✅ 全部通过")