完善小红书连续回复与自动回执

修正搜索分类、近期评论识别和多图回执核对,记录图文与视频单次任务的真机验收结果。
This commit is contained in:
2026-11-27 09:29:45 +08:00
parent 5df863cd22
commit 7beaf36b20
10 changed files with 349 additions and 83 deletions
@@ -34,6 +34,7 @@ internal class AccessibleUi(
private val packageName: String,
private val cancelled: () -> Boolean,
private val pauseBetweenActions: () -> Unit,
private val checkPage: ((UiPage) -> Unit)? = null,
) {
private val mainHandler = Handler(Looper.getMainLooper())
@@ -65,7 +66,10 @@ internal class AccessibleUi(
fun <T> inspect(action: (UiPage) -> T): T? {
checkCancelled()
val root = targetRoot() ?: return null
return capture(root).use(action)
return capture(root).use { page ->
checkPage?.invoke(page)
action(page)
}
}
fun screenshotPhotos(windowId: Int, regions: List<Rect>): List<PhotoPixels>? {
@@ -71,7 +71,8 @@ object PlatformRegistry {
): PlatformAdapter {
val spec = platforms.firstOrNull { it.id == platformId }
if (spec == null || !spec.implemented) throw PlatformException("${spec?.label ?: platformId} 暂未接入")
val ui = AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions)
val checkPage = if (spec == xiaohongshu) UiPage::requireXhsCommentAccess else null
val ui = AccessibleUi(service, spec.packageName, cancelled, pauseBetweenActions, checkPage)
return when (spec.id) {
douyin.id -> DouyinAdapter(spec, ui, PhotoLibrary(service))
xiaohongshu.id -> XiaohongshuAdapter(spec, ui, PhotoLibrary(service), noteKind, targetNoteKey,
@@ -101,7 +101,6 @@ internal class XiaohongshuAdapter(
if (ui.inspect { it.searchHeader()?.editor?.focused == true } == true) return
ui.pace()
val opened = awaitPage(4_000, "小红书首页未显示可核对的搜索入口") { page ->
page.requireXhsCommentAccess()
val header = page.searchHeader()
if (header != null) return@awaitPage header.editor.focused || ui.click(header.editor)
val results = page.resultHeader()
@@ -169,17 +168,18 @@ internal class XiaohongshuAdapter(
it.bounds.width() >= bounds.width() * .35f } ?: return null
val tabs = nodes.singleOrNull { strip ->
strip.className == "android.widget.HorizontalScrollView" && strip.bounds.top >= row.bounds.bottom - 2 &&
strip.bounds.centerY() <= y(.28f) && nodes.any { item ->
item.isDescendantOf(strip) && item.className == "android.widget.TextView" &&
item.text in setOf("全部", "视频") && item.selected
}
strip.bounds.centerY() <= y(.28f) &&
(resultTab(strip, "全部") != null || resultTab(strip, "视频") != null)
} ?: return null
return ResultHeader(query, tabs)
}
private val desiredResultTab: String
get() = if (noteKind == XiaohongshuNoteKind.VIDEO) "视频" else "全部"
private fun UiPage.resultList(keyword: String): ResultList? {
val header = resultHeader()?.takeIf { it.query.text == keyword } ?: return null
if (noteKind == XiaohongshuNoteKind.VIDEO && videoResultTab(header.tabs)?.selected != true) return null
if (resultTab(header.tabs, desiredResultTab)?.selected != true) return null
val list = nodes.singleOrNull { it.className == "androidx.recyclerview.widget.RecyclerView" &&
it.bounds.width() >= bounds.width() * .90f && it.bounds.bottom >= y(.65f) &&
it.bounds.top <= header.tabs.bounds.bottom + 36 } ?: return null
@@ -189,27 +189,46 @@ internal class XiaohongshuAdapter(
return ResultList(list, viewport).takeUnless { viewport.isEmpty }
}
private fun UiPage.videoResultTab(strip: UiNode): UiNode? {
val label = nodes.singleOrNull { it.isDescendantOf(strip) && it.isUneditableText() && it.text == "视频" }
private fun UiPage.resultTab(strip: UiNode, name: String): UiNode? {
val label = nodes.singleOrNull { it.isDescendantOf(strip) && it.isUneditableText() && it.text == name }
?: return null
return label.directParent()?.takeIf { tab ->
tab.className == "androidx.appcompat.app.ActionBar\$Tab" && tab.isNativeClick() &&
// The All category uses a custom label nested inside the native tab.
return generateSequence(label.directParent(), UiNode::directParent).take(3).firstOrNull { tab ->
tab.className == "androidx.appcompat.app.ActionBar\$Tab" && tab.isNativeClick() && tab.isDescendantOf(strip) &&
strip.bounds.contains(tab.bounds) && tab.bounds.contains(label.bounds) && tab.selected == label.selected
}
}
private fun selectVideoResults(keyword: String) {
if (noteKind != XiaohongshuNoteKind.VIDEO) return
ui.pace()
val clicked = awaitPage(8_000, "未找到小红书当前搜索词的视频分类") { page ->
val header = page.resultHeader()?.takeIf { it.query.text == keyword } ?: return@awaitPage null
val tab = page.videoResultTab(header.tabs) ?: return@awaitPage null
tab.selected || ui.click(tab)
}
if (!clicked) throw PlatformException("小红书未确认切换到视频分类")
awaitPage(7_000, "小红书未显示当前搜索词的视频结果") { page ->
true.takeIf { page.resultList(keyword) != null }
private fun selectResults(keyword: String) {
if (ui.inspect { it.resultList(keyword) != null } == true) return
val name = desiredResultTab
repeat(4) { attempt ->
ui.pace()
val selected = awaitPage(8_000, "未找到小红书当前搜索词的${name}分类") { page ->
val header = page.resultHeader()?.takeIf { it.query.text == keyword } ?: return@awaitPage null
val tab = page.resultTab(header.tabs, name)
if (tab != null) {
if (!tab.selected && !ui.click(tab)) throw PlatformException("小红书未确认切换到${name}分类")
return@awaitPage true
}
if (attempt == 3) return@awaitPage null
val strip = header.tabs.takeIf { it.scrollable }?.bounds ?: return@awaitPage null
val left = strip.left + strip.width() * .18f
val right = strip.right - strip.width() * .18f
val y = strip.exactCenterY()
val towardStart = name == "全部"
val moved = if (towardStart) ui.touch(left, y, right, y, 450L) else ui.touch(right, y, left, y, 450L)
if (!moved) throw PlatformException("小红书搜索分类栏滚动未完成")
false
}
if (selected) {
awaitPage(7_000, "小红书未显示当前搜索词的${name}结果") { page ->
true.takeIf { page.resultList(keyword) != null }
}
return
}
}
throw PlatformException("小红书分类栏未显示${name}分类")
}
private fun UiPage.resultCards(surface: ResultList): List<ResultCard> {
@@ -244,7 +263,7 @@ internal class XiaohongshuAdapter(
}
val notFound = if (targetNoteKey == null) "小红书未找到下一条可核对的笔记"
else "小红书未在当前搜索结果中找到指定笔记"
selectVideoResults(keyword)
selectResults(keyword)
repeat(8) {
ui.pace()
val step = awaitPage(9_000, "小红书未显示当前关键词对应的可读笔记结果") { page ->
@@ -340,7 +359,7 @@ internal class XiaohongshuAdapter(
ui.back()
}
if (!left) throw PlatformException("小红书未确认退出当前搜索结果的笔记")
selectVideoResults(keyword)
selectResults(keyword)
awaitPage(6_000, "退出小红书笔记后未核对到同一搜索结果") { page ->
true.takeIf { page.resultList(keyword) != null }
}
@@ -418,9 +437,11 @@ internal class XiaohongshuAdapter(
private fun UiPage.hasNoteText(detail: NoteControls, title: String): Boolean {
val preview = title.normalizedPostText()
if (detail.caption != null) {
val caption = detail.caption.text.normalizedPostText()
return caption == preview || caption.length >= 16 && preview.startsWith(caption) ||
preview.length >= 16 && caption.startsWith(preview)
return detail.caption.labels().any { label ->
val caption = label.normalizedPostText()
caption == preview || caption.length >= 16 && preview.startsWith(caption) ||
preview.length >= 16 && caption.startsWith(preview)
}
}
val visibleText = nodes.filter { node ->
val exposedHeight = minOf(node.bounds.bottom, bounds.bottom, detail.toolbar.bounds.top) - node.bounds.top
@@ -351,7 +351,7 @@ internal class XiaohongshuComments(
!surface.viewport.contains(slot.bounds) || slot.bounds.bottom != original.nextTop) return null
val footer = labels.singleOrNull { node -> node.commentText() && !node.clickable &&
rowReplyFooter.matches(node.text) && slot.bounds.contains(node.bounds) &&
XhsCommentLabels.isOriginalReplyFooter(node.text) && slot.bounds.contains(node.bounds) &&
abs(node.bounds.left - original.author.bounds.left) <= 2 &&
node.bounds.top <= footerTop + original.author.bounds.height() }
return slot.takeIf { footer != null }
@@ -492,7 +492,6 @@ internal class XiaohongshuComments(
val ownLabels = setOf("我", "我发布的评论", "我发布的回复")
val replyControlClasses = setOf("android.widget.TextView", "android.widget.Button")
val attachmentClasses = setOf("android.widget.ImageView", "android.view.View")
val rowReplyFooter = Regex("(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[12][0-9]|3[01])\\s+\\p{IsHan}{2,8}\\s+回复")
val observedExpansion = Regex("展开\\s*[1-9][0-9]*\\s*条回复")
}
}
@@ -511,12 +510,17 @@ internal object XhsCommentLabels {
private val heading = Regex("共\\s*(\\d+)\\s*条评论")
private val empty = setOf("暂无评论", "还没有评论")
private val relativeTime = Regex("^(刚刚|[1-9][0-9]?\\s*分钟前|(?:[1-5][0-9]|[1-9])\\s*秒前)(?:\\s|$)")
private val originalReplyFooter = Regex(
"""(?:(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[12][0-9]|3[01])""" +
"""|(?:今天|昨天)\s+(?:[01]?\d|2[0-3]):[0-5]\d|刚刚|[1-9]\d?\s*(?:秒|分钟|小时|天)前)\s+\p{IsHan}{2,8}\s+回复""",
)
private val expand = Regex("(?:展开|查看)\\s*[1-9][0-9]*\\s*条回复|展开更多回复")
private val unknown = Regex("(?:展开|查看).{0,16}(?:回复|更多)")
private val photo = Regex("(?:查看)?图片(?:\\s*[1-9][0-9]*)?")
fun commentCount(text: String): Int? = if (text in empty) 0 else heading.matchEntire(text)?.groupValues?.get(1)?.toIntOrNull()
fun relativeTime(text: String): String? = relativeTime.find(text)?.groupValues?.get(1)
fun isOriginalReplyFooter(text: String): Boolean = originalReplyFooter.matches(text)
fun expandsReplies(label: String): Boolean = expand.matches(label)
fun blocksThreadBoundary(label: String): Boolean = expandsReplies(label) || unknown.matches(label)
fun photoDescription(label: String): Boolean = photo.matches(label)
@@ -1,6 +1,7 @@
package com.jieliu.app.platform
import android.graphics.Rect
import android.os.SystemClock
import android.view.accessibility.AccessibilityNodeInfo
import com.jieliu.app.data.PhotoLibrary
import com.jieliu.app.task.TaskPlan
@@ -152,7 +153,6 @@ internal class XiaohongshuReplyComposer(
val session = prepared?.takeIf { it.sendAttempted } ?: return false
return ui.await(3_000) {
ui.inspect { page ->
page.requireXhsCommentAccess()
if (!page.matchesTarget(session.target, session.originalWindow, session.surface)) return@inspect null
if (page.hasPrivateDraft() || page.nodes.any { it.editable && (it.focused || it.hasReplyPrompt()) }) return@inspect null
true.takeIf { page.nodes.none { it.replyCue(session.target) } }
@@ -211,12 +211,20 @@ internal class XiaohongshuReplyComposer(
}
picker.snapshot(page.windowId)
}
val crops = captureVisibleImages(empty)
?.takeIf { it.size == references.size } ?: throw PlatformException("无法核对小红书专用相册的全部缩略图")
val selected = MutableList(references.size) { 0 }
val stillUnselected = {
ui.inspect { page -> page.picker(album, references.size)?.matches(empty, page.windowId, selected, 0) == true } == true
}
var nextCaptureAt = 0L
val crops = ui.await(4_500) {
val now = SystemClock.elapsedRealtime()
if (now < nextCaptureAt || !stillUnselected()) return@await null
nextCaptureAt = now + 400
captureVisibleImages(empty)?.takeIf { it.size == references.size && stillUnselected() }
} ?: throw PlatformException("无法核对小红书专用相册的全部缩略图")
val order = pickerAttachmentOrder(references, crops)
?: throw PlatformException("小红书专用相册中的图片无法唯一对应本次附件")
val selected = MutableList(references.size) { 0 }
for ((index, tileIndex) in order.withIndex()) {
ui.pace()
val accepted = ui.inspect { page ->
@@ -1,6 +1,7 @@
package com.jieliu.app.platform
import android.graphics.Rect
import android.os.SystemClock
import android.view.accessibility.AccessibilityNodeInfo
import com.jieliu.app.data.PhotoLibrary
import com.jieliu.app.task.TemplatePhoto
@@ -16,10 +17,31 @@ internal class XiaohongshuReplyReceipt(
private data class SurfaceKey(val windowId: Int, val inline: Boolean)
private data class OriginalComment(val key: String, val author: String)
private data class ThreadStamp(val complete: Boolean, val replyIds: List<String>, val expandLabels: List<String>?)
private data class ThreadReadback(val stamp: ThreadStamp, val expectedBodyVisible: Boolean)
private data class Baseline(val stamp: ThreadStamp, val parentVisible: Boolean, val authorTop: Int, val bodies: List<String>)
private data class VisibleReceipt(val identity: String, val originalBody: Rect, val body: Rect, val photos: List<Rect>, val own: Boolean)
private data class VisibleReceipt(
val identity: String,
val originalBody: Rect,
val body: Rect,
val photos: List<Rect>,
val own: Boolean,
val timeLabel: String,
) {
fun samePosition(other: VisibleReceipt?): Boolean = this == other?.copy(timeLabel = timeLabel)
}
private enum class CommentRole { OWN, OTHER }
private data class RoleMenu(val windowId: Int, val scroll: Rect, val role: CommentRole?)
private class OwnershipCheck {
var anchor: VisibleReceipt? = null
var observedAt = 0L
var originalOther = false
var originalAttempts = 0
var replyAttempts = 0
fun timedAnchor(): VisibleReceipt? = anchor?.takeIf {
SystemClock.elapsedRealtime() - observedAt <= MENU_PROOF_WAIT_MS
}
}
private class Diagnostics(private val emit: (String) -> Unit) {
private val seen = mutableSetOf<String>()
@@ -42,7 +64,7 @@ internal class XiaohongshuReplyReceipt(
}
} ?: return false
// A missing own badge cannot turn an already visible identical body into evidence of a new reply.
if (baseline.bodies.any { it == expectedText }) return false
if (baseline.bodies.any { matchesXhsReplyBody(it, expectedText) }) return false
if (baseline.stamp.complete) {
return baseline.parentVisible && baseline.bodies.none(String::isBlank) &&
baseline.stamp.replyIds.none(String::isBlank) &&
@@ -101,16 +123,24 @@ internal class XiaohongshuReplyReceipt(
var expansions = 0
var revisitedOriginal = false
val opened = mutableSetOf<ThreadStamp>()
val ownershipChecks = mutableSetOf<String>()
val ownership = OwnershipCheck()
repeat(MAX_RECEIPT_PASSES) {
val confirmed = ui.await(RECEIPT_WAIT_MS) {
verifiedReceipt(scope, original, text, references, armedAt, ownershipChecks, diagnostics)
verifiedReceipt(scope, original, text, references, armedAt, ownership, diagnostics)
}
if (confirmed == true) return CommentPublishResult.CONFIRMED
val seen = readThread(scope, original) { _, _, thread -> stamp(thread) }
val thread = readThread(scope, original) { _, _, visible ->
ThreadReadback(stamp(visible), visible.replies.any { matchesXhsReplyBody(it.body.text, text) })
}
if (fromStart && ownership.anchor == null && thread != null && thread.stamp.complete && !thread.expectedBodyVisible) {
diagnostics.record("小红书回查已读到完整原评论线程,暂未找到本次回复")
return CommentPublishResult.UNCERTAIN
}
val seen = thread?.stamp
if (seen == null) {
diagnostics.record("小红书回查暂时无法读取原评论线程")
if (revisitedOriginal || !seekOriginal(scope, original, diagnostics, forwardLimit = 0)) {
val forwardLimit = if (ownership.originalOther) MAX_MENU_RECOVERY_SCROLLS else 0
if (revisitedOriginal || !seekOriginal(scope, original, diagnostics, forwardLimit = forwardLimit)) {
return CommentPublishResult.UNCERTAIN
}
revisitedOriginal = true
@@ -141,37 +171,72 @@ internal class XiaohongshuReplyReceipt(
text: String,
references: List<PhotoPixels>,
armedAt: Long,
ownershipChecks: MutableSet<String>,
ownership: OwnershipCheck,
diagnostics: Diagnostics,
): Boolean? {
val before = receiptRow(scope, original, text, references.size, armedAt, diagnostics) ?: return null
val captured = if (references.isEmpty()) emptyList() else ui.screenshotPhotos(scope.windowId, before.photos) ?: run {
diagnostics.record("小红书回查未能截取已发布的图片")
return null
val before = receiptRow(scope, original, text, references.size, armedAt, diagnostics, ownership.timedAnchor()) ?: return null
if (ownership.anchor?.identity?.let { it != before.identity } == true) return null
// Temporarily preserve the timestamp already seen on this exact row if its relative label freezes behind a menu.
val readSameReply = {
receiptRow(scope, original, text, references.size, armedAt, diagnostics, before)?.takeIf { it.identity == before.identity }
}
val after = receiptRow(scope, original, text, references.size, armedAt)
if (before != after) {
diagnostics.record("小红书回查截取图片时回复位置发生变化")
return null
}
if (captured.size != references.size || !references.indices.all { PublishedPhotoMatcher.matches(references[it], captured[it]) }) {
diagnostics.record("小红书回查的已发布图片未通过内容比对")
return null
}
if (references.isNotEmpty()) diagnostics.record("小红书回查已核对已发布图片")
if (before.own) {
if (!verifyReplyImages(scope, before, references, readSameReply, diagnostics)) return null
diagnostics.record("小红书回查已读取到本人回复标记")
return true
}
if (!ownershipChecks.add(before.identity)) return null
if (!ownership.originalOther) {
if (ownership.originalAttempts >= MAX_ROLE_ATTEMPTS) return null
if (!verifyReplyImages(scope, before, references, readSameReply, diagnostics)) return null
if (ownership.anchor == null) {
ownership.anchor = before
ownership.observedAt = SystemClock.elapsedRealtime()
}
// Compare the action menus when the exact reply has no self badge.
diagnostics.record("小红书回查正在比对评论菜单以核对本人身份")
ownership.originalAttempts++
ownership.originalOther = inspectRole(scope, readSameReply, VisibleReceipt::originalBody, diagnostics) == CommentRole.OTHER
if (!ownership.originalOther) {
diagnostics.record("小红书回查未能核对原评论的他人菜单")
return null
}
if (!awaitMenuReturn(readSameReply, diagnostics)) return null
}
if (ownership.replyAttempts >= MAX_ROLE_ATTEMPTS) return null
// Sample the exact reply immediately before opening its own menu, while the photos are unobstructed.
val ready = readSameReply() ?: return null
if (!verifyReplyImages(scope, ready, references, readSameReply, diagnostics)) return null
val readVerifiedPosition = { readSameReply()?.takeIf(ready::samePosition) }
ownership.replyAttempts++
if (inspectRole(scope, readVerifiedPosition, VisibleReceipt::body, diagnostics) != CommentRole.OWN) {
diagnostics.record("小红书回查未能核对回复的本人菜单")
return null
}
diagnostics.record("小红书回查已通过评论菜单确认本人身份")
return true
}
// XHS may hide the self badge. Compare the action menus on this exact reply and its original.
val current = { receiptRow(scope, original, text, references.size, armedAt) == before }
diagnostics.record("小红书回查正在比对评论菜单以核对本人身份")
val own = inspectRole(scope, before.originalBody, current) == CommentRole.OTHER &&
inspectRole(scope, before.body, current) == CommentRole.OWN && current()
diagnostics.record(if (own) "小红书回查已通过评论菜单确认本人身份" else "小红书回查未能通过评论菜单核对本人身份")
return true.takeIf { own }
private fun verifyReplyImages(
scope: SurfaceKey,
before: VisibleReceipt,
references: List<PhotoPixels>,
readCurrent: () -> VisibleReceipt?,
diagnostics: Diagnostics,
): Boolean {
val captured = if (references.isEmpty()) emptyList() else ui.screenshotPhotos(scope.windowId, before.photos) ?: run {
diagnostics.record("小红书回查未能截取已发布的图片")
return false
}
if (!before.samePosition(readCurrent())) {
diagnostics.record("小红书回查截取图片时回复位置发生变化")
return false
}
if (captured.size != references.size || !references.indices.all { PublishedPhotoMatcher.matches(references[it], captured[it]) }) {
diagnostics.record("小红书回查的已发布图片未通过内容比对")
return false
}
if (references.isNotEmpty()) diagnostics.record("小红书回查已核对已发布图片")
return true
}
private fun receiptRow(
@@ -181,19 +246,30 @@ internal class XiaohongshuReplyReceipt(
photoCount: Int,
armedAt: Long,
diagnostics: Diagnostics? = null,
previouslyTimed: VisibleReceipt? = null,
): VisibleReceipt? = readThread(scope, original) { surface, parent, thread ->
val viewport = surface.viewport
if (!contains(viewport, parent.body.bounds)) return@readThread null
val reply = thread.replies.singleOrNull { it.body.text == text } ?: run {
val reply = thread.replies.singleOrNull { matchesXhsReplyBody(it.body.text, text) } ?: run {
diagnostics?.record("小红书回查暂未读取到唯一匹配的回复正文")
return@readThread null
}
diagnostics?.record("小红书回查已找到匹配的回复正文")
val time = reply.timeLabel
if (reply.identity.isBlank() || thread.replies.count { it.identity == reply.identity } != 1 ||
!contains(viewport, reply.body.bounds) || time == null || !matchesXhsReceiptTime(time, armedAt, System.currentTimeMillis())
!contains(viewport, reply.body.bounds)
) {
diagnostics?.record("小红书回查无法核对回复位置、唯一性或发布时间")
diagnostics?.record("小红书回查无法核对回复位置或唯一性")
return@readThread null
}
val time = reply.timeLabel ?: run {
diagnostics?.record("小红书回查未读到回复时间标签")
return@readThread null
}
val now = System.currentTimeMillis()
val sameTimedRow = previouslyTimed != null && previouslyTimed.identity == reply.identity && previouslyTimed.timeLabel == time &&
validXhsReceiptAge(armedAt, now)
if (!sameTimedRow && !matchesXhsReceiptTime(time, armedAt, now)) {
diagnostics?.record("小红书回查的时间标签与提交时间不一致")
return@readThread null
}
@@ -205,32 +281,79 @@ internal class XiaohongshuReplyReceipt(
diagnostics?.record("小红书回查无法核对已发布图片的数量或位置")
return@readThread null
}
VisibleReceipt(reply.identity, Rect(parent.body.bounds), Rect(reply.body.bounds), crops, reply.own)
VisibleReceipt(reply.identity, Rect(parent.body.bounds), Rect(reply.body.bounds), crops, reply.own, time)
}
private fun inspectRole(scope: SurfaceKey, body: Rect, isSameReceipt: () -> Boolean): CommentRole? {
if (!isSameReceipt()) return null
private fun inspectRole(
scope: SurfaceKey,
readSameReply: () -> VisibleReceipt?,
bodyBounds: (VisibleReceipt) -> Rect,
diagnostics: Diagnostics,
): CommentRole? {
val body = readSameReply()?.let(bodyBounds) ?: run {
diagnostics.record("小红书回查长按前未能重新定位同一条回复")
return null
}
val x = body.exactCenterX()
val y = body.exactCenterY()
if (!ui.touch(x, y, x, y, 670L)) return null
val menu = ui.await(MENU_WAIT_MS) { ui.inspect { roleMenu(it, scope.windowId) } } ?: return null
if (!ui.touch(x, y, x, y, 670L)) {
diagnostics.record("小红书回查评论长按手势未完成")
return null
}
val menu = ui.await(MENU_WAIT_MS) { ui.inspect { roleMenu(it, scope.windowId, diagnostics) } } ?: run {
diagnostics.record("小红书回查长按后未能识别评论菜单")
return null
}
diagnostics.record("小红书回查已识别评论菜单")
var closed = false
val confirmed = try {
menu.role ?: run {
val area = menu.scroll
var role = menu.role
for (scrollIndex in 0 until MAX_MENU_SCROLLS) {
if (role != null) break
val current = ui.inspect { roleMenu(it, scope.windowId)?.takeIf { snapshot -> snapshot.windowId == menu.windowId } }
?: break
val area = current.scroll
val scrollX = area.exactCenterX()
if (!ui.touch(scrollX, area.top + area.height() * .83f, scrollX, area.top + area.height() * .19f, 450L)) {
null
} else ui.await(MENU_WAIT_MS) {
ui.inspect { page -> roleMenu(page, scope.windowId)?.takeIf { it.windowId == menu.windowId }?.role }
diagnostics.record("小红书回查菜单滚动手势未完成")
break
}
role = ui.await(MENU_WAIT_MS) {
ui.inspect { page -> roleMenu(page, scope.windowId, diagnostics)?.takeIf { it.windowId == menu.windowId }?.role }
}
}
role
} finally {
if (ui.inspect { page -> roleMenu(page, scope.windowId)?.windowId } == menu.windowId) ui.back()
val activeMenu = ui.await(MENU_WAIT_MS) {
ui.inspect { page -> true.takeIf { roleMenu(page, scope.windowId)?.windowId == menu.windowId } }
}
if (activeMenu == true) closed = ui.back()
}
return confirmed.takeIf { ui.await(MENU_WAIT_MS) { true.takeIf { isSameReceipt() } } == true }
diagnostics.record(when (confirmed) {
CommentRole.OWN -> "小红书回查已读到本人菜单终项"
CommentRole.OTHER -> "小红书回查已读到他人菜单终项"
null -> "小红书回查未读到有效的评论菜单终项"
})
if (!closed) diagnostics.record("小红书回查未能关闭已识别的评论菜单")
return confirmed
}
private fun roleMenu(page: UiPage, previousWindowId: Int): RoleMenu? {
private fun awaitMenuReturn(readSameReply: () -> VisibleReceipt?, diagnostics: Diagnostics): Boolean {
var previous: VisibleReceipt? = null
val restored = ui.await(MENU_RETURN_WAIT_MS) {
val current = readSameReply()
val stable = current?.samePosition(previous) == true
previous = current
true.takeIf { stable }
}
if (restored != true) {
diagnostics.record("小红书回查关闭菜单后未能重新定位同一条回复")
return false
}
return true
}
private fun roleMenu(page: UiPage, previousWindowId: Int, diagnostics: Diagnostics? = null): RoleMenu? {
if (page.windowId == previousWindowId || page.bounds.top <= 0 || hasOpenEditor(page)) return null
val scroll = page.nodes.singleOrNull { node ->
node.className == "android.widget.ScrollView" && node.scrollable && page.bounds.contains(node.bounds) &&
@@ -249,6 +372,9 @@ internal class XiaohongshuReplyReceipt(
node.text to cell
}
val labels = actions.map { it.first }
if (page.nodes.any { it.text == "举报" || it.text == "删除" } && labels.none { it == "举报" || it == "删除" }) {
diagnostics?.record("小红书回查菜单终项未通过控件结构核对")
}
if (sharedMenuActions.count { it in labels } < 2) return null
val finalAction = actions.singleOrNull { it.first == "删除" || it.first == "举报" }
val role = finalAction?.takeIf { (_, cell) ->
@@ -346,7 +472,6 @@ internal class XiaohongshuReplyReceipt(
private fun findSurface(): SurfaceKey? = ui.await(THREAD_WAIT_MS) {
ui.inspect { page ->
page.requireXhsCommentAccess()
if (hasOpenEditor(page)) return@inspect null
comments.surface(page)?.takeIf { it.windowId == page.windowId && contains(page.bounds, it.viewport) }
?.let { SurfaceKey(it.windowId, it.inline) }
@@ -354,7 +479,6 @@ internal class XiaohongshuReplyReceipt(
}
private fun matchingSurface(page: UiPage, scope: SurfaceKey): XhsCommentSurface? {
page.requireXhsCommentAccess()
if (page.windowId != scope.windowId || hasOpenEditor(page)) return null
return comments.surface(page)?.takeIf {
it.windowId == scope.windowId && it.inline == scope.inline && contains(page.bounds, it.viewport)
@@ -394,12 +518,22 @@ internal class XiaohongshuReplyReceipt(
const val THREAD_WAIT_MS = 1_550L
const val RECEIPT_WAIT_MS = 850L
const val MENU_WAIT_MS = 1_900L
const val MENU_RETURN_WAIT_MS = 6_000L
const val MENU_PROOF_WAIT_MS = 35_000L
const val MAX_MENU_SCROLLS = 2
const val MAX_MENU_RECOVERY_SCROLLS = 2
const val MAX_ROLE_ATTEMPTS = 2
val sharedMenuActions = setOf("分享到微信", "问点点", "搜索", "回复", "收藏", "复制")
}
}
private const val XHS_RECEIPT_CLOCK_SLACK_MS = 5_000L
private val xhsReceiptRelativeTime = Regex("([0-9]{1,2})[ \\u00a0]*(秒前|分钟前)")
// XHS can pad a single space between a Latin token and adjacent Chinese text on a published row.
private val xhsMixedTextPadding = Regex("(?<=\\p{IsLatin}) {3}(?=\\p{IsHan})")
internal fun matchesXhsReplyBody(visible: String, expected: String): Boolean =
visible == expected || xhsMixedTextPadding.replace(visible, " ") == expected
internal fun validXhsReceiptAge(armedAt: Long, now: Long): Boolean =
armedAt > 0 && armedAt <= now && now - armedAt <= XIAOHONGSHU_RECHECK_WINDOW_MS
@@ -7,6 +7,12 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class XhsCommentLabelsTest {
@Test fun recognizesOriginalReplyFootersForOlderAndRecentComments() {
listOf("11-18 美国 回复", "昨天 23:46 广东 回复", "5小时前 中国香港 回复", "4天前 福建 回复", "23分钟前 安徽 回复")
.forEach { assertTrue(it, XhsCommentLabels.isOriginalReplyFooter(it)) }
listOf("昨天 25:46 广东 回复", "5小时前 回复", "广东 回复", "4天前 福建 回复 发布为笔记")
.forEach { assertFalse(it, XhsCommentLabels.isOriginalReplyFooter(it)) }
}
@Test
fun syntheticHeadingRequiresStandaloneCommentCount() {
assertEquals(66, XhsCommentLabels.commentCount("共 66 条评论"))
@@ -7,6 +7,14 @@ import org.junit.Test
class XhsReceiptTimeTest {
private val armedAt = 1_790_000_000_000L
@Test fun replyBodyAllowsOnlyObservedPaddingAtTheLatinHanBoundary() {
assertTrue(matchesXhsReplyBody("Gemini 做科普", "Gemini 做科普"))
assertTrue(matchesXhsReplyBody("Gemini 做科普", "Gemini 做科普"))
assertFalse(matchesXhsReplyBody("Gemini 做科普", "Gemini 做科普"))
assertFalse(matchesXhsReplyBody("Gemini Pro 做科普", "Gemini Pro 做科普"))
assertFalse(matchesXhsReplyBody("Gemini 做题", "Gemini 做科普"))
}
@Test fun relativeLabelMustAgreeWithRecordedSubmission() {
assertTrue(matchesXhsReceiptTime("刚刚", armedAt, armedAt + 2_000L))
assertTrue(matchesXhsReceiptTime("12 秒前", armedAt, armedAt + 12_600L))
@@ -23,4 +31,15 @@ class XhsReceiptTimeTest {
assertFalse(matchesXhsReceiptTime("61分钟前", armedAt, armedAt + 61 * 60_000L))
assertFalse(validXhsReceiptAge(0, armedAt))
}
@Test fun capturedCommentFootersMatchOnlyDuringTheKnownRecheckWindow() {
val early = checkNotNull(XhsCommentLabels.relativeTime("2分钟前 北京 回复"))
val later = checkNotNull(XhsCommentLabels.relativeTime("32分钟前 北京 回复"))
assertTrue(matchesXhsReceiptTime(early, armedAt, armedAt + 135_600L))
assertTrue(matchesXhsReceiptTime(later, armedAt, armedAt + 1_940_400L))
assertFalse(matchesXhsReceiptTime(later, armedAt, armedAt + 104 * 60_000L))
assertTrue(validXhsReceiptAge(armedAt, armedAt + 3_600_000L))
assertFalse(validXhsReceiptAge(armedAt, armedAt + 3_600_001L))
}
}
@@ -3,6 +3,7 @@ package com.jieliu.app.task
import com.jieliu.app.platform.CommentPublishResult
import com.jieliu.app.platform.CommentTarget
import com.jieliu.app.platform.PlatformAdapter
import com.jieliu.app.platform.PlatformInteractionRestrictedException
import com.jieliu.app.platform.PlatformRegistry
import com.jieliu.app.platform.VideoContext
import org.junit.Assert.assertEquals
@@ -168,6 +169,51 @@ class TaskRunnerTest {
assertTrue(store.checkpoint.receipts.isEmpty())
}
@Test fun xiaohongshuRestrictionAfterSubmitPreservesTheArmedReplyAndStops() {
val plan = plan(firstType).copy(platformId = "xiaohongshu", limit = 2, repliesPerVideo = 2)
val store = RecordingStore(TaskCheckpoint("xhs-restricted-after-submit", plan))
val candidates = listOf(listOf(target("first", "API 充值"), target("second", "付款方式")))
val platform = FakePlatform(store, candidates).apply {
knownBaseline = true
afterPublish = { throw PlatformInteractionRestrictedException(XHS_RESTRICTION) }
}
execute(store, platform)
val submitted = platform.attempts.single()
assertEquals(1, platform.publishCalls)
assertEquals(1, store.pendingWrites)
assertEquals(listOf(firstType.name), platform.searches)
assertEquals(listOf("first"), platform.preparations)
assertTrue(platform.rechecks.isEmpty())
assertEquals(photos, submitted.photos)
assertTrue(submitted.armedAtEpochMs != null)
assertEquals(submitted, store.checkpoint.pending)
assertEquals(0, store.checkpoint.sentCount)
assertEquals("$XHS_RESTRICTION,已保留本次提交等待核对。", store.checkpoint.message)
}
@Test fun xiaohongshuRestrictionDuringStandaloneRecheckKeepsTheExistingReplyPending() {
val plan = plan(firstType).copy(platformId = "xiaohongshu")
val pending = PendingComment("video-0", "先前笔记", "已提交的话术", photos = photos,
targetKey = "original", targetAuthor = "测试用户", armedAtEpochMs = System.currentTimeMillis())
val store = RecordingStore(TaskCheckpoint("xhs-restricted-recheck", plan).startVideo(pending.videoKey).arm(pending))
val platform = FakePlatform(store).apply {
onRecheck = { throw PlatformInteractionRestrictedException(XHS_RESTRICTION) }
}
execute(store, platform, recheckPending = true)
assertEquals(listOf(firstType.name), platform.searches)
assertEquals(listOf("video-0" to pending), platform.rechecks)
assertTrue(platform.preparations.isEmpty())
assertEquals(0, platform.publishCalls)
assertEquals(0, store.pendingWrites)
assertEquals(pending, store.checkpoint.pending)
assertEquals(0, store.checkpoint.sentCount)
assertEquals("$XHS_RESTRICTION,已保留本次提交等待核对。", store.checkpoint.message)
}
@Test fun automaticRecheckFindsTheActiveVideoAndRecordsOnlyTheExistingReply() {
val plan = plan(firstType).copy(limit = 3, repliesPerVideo = 2)
val store = RecordingStore(TaskCheckpoint("auto-recheck", plan))
@@ -400,6 +446,7 @@ class TaskRunnerTest {
var onScroll: () -> Unit = {}
var beforePublish: () -> Unit = {}
var afterPublish: () -> Unit = {}
var onRecheck: () -> Unit = {}
var screensForVideo: ((VideoContext) -> List<List<CommentTarget>>)? = null
var launches = 0
private set
@@ -462,6 +509,7 @@ class TaskRunnerTest {
override fun confirmPendingReply(video: VideoContext, pending: PendingComment): CommentPublishResult {
rechecks.add(video.key to pending)
onRecheck()
return recheckResult
}
@@ -489,6 +537,7 @@ class TaskRunnerTest {
}
private companion object {
const val XHS_RESTRICTION = "小红书提示账号存在安全风险,社区评论互动功能受限"
val photos = listOf(TemplatePhoto(id("photo1"), "一.png"), TemplatePhoto(id("photo2"), "二.png"))
val apiRule = rule("API 充值", "API 充值对应的图文", photos)
val firstType = ContentType(id("大模型充值"), "大模型充值", listOf(apiRule, rule("付款方式", "付款方式对应的话术")))
+21 -1
View File
@@ -1,6 +1,26 @@
# 拾见开发进度
最近更新于 2026-11-26 14:52(UTC+8)。以下按开发轮次倒序记录。
最近更新于 2026-11-27 09:27(UTC+8)。以下按开发轮次倒序记录。
## 2026-11-27 · 拾见 0.1.22 小红书连续真机验收
在 vivo Android 12、小红书 9.54.0 上,从「开始任务」分别运行图文和视频。沿用已确认的两篇笔记,选择各自未用于上轮验收的原评论。
| 笔记类型 | 启动 | 自动回执 | 实发结果 |
| --- | --- | --- | --- |
| 图文 | 09:22:18 | 09:23:24 | 同一任务写入 1 条 `SENT` |
| 视频 | 09:26:14 | 09:27:07 | 同一任务写入 1 条 `SENT` |
- 每轮自动完成搜索、匹配关键词和提交,在原评论下找到同一条本人回复,核对正文及两张已绑定图片的内容和顺序,再写入回执。两轮均无手动补核、独立回查或待确认记录。
- 补充了原评论回复入口对「昨天 23:46」「5小时前」「4天前」等时间格式的识别。继续校验同一行的原生回复入口、地区和线程边界。未通过前置核验的图文尝试发送数均为 0。
- 57 项 JVM 单测通过。Lint 为 0 个错误、4 个既有警告。最新版 APK 已通过 v2 签名校验并安装,手机原配置和无障碍设置已恢复。
## 2026-11-26 · 拾见 0.1.22 小红书真机联调
- 在 vivo Android 12、小红书 9.54.0 上,图文和视频各从拾见的「开始任务」启动。两次均完成自动搜索、匹配原评论,并各实发一条带正文和两张绑定图片的回复。
- 修复后通过「自动核对回复」独立回查原笔记。视频在 18:57:11、图文在 19:10:15 自动写入 `SENT`。两次都核对了原评论下同一条本人回复的正文及两张图片的内容和顺序,回执沿用各自原任务和原评论。其中图文从保留的「视频」筛选自动切回「全部」。从一次「开始任务」连续完成到回执的真机验收仍待进行。
- 修复了跨任务沿用搜索分类、视频章节标题截短、相册截图短暂不可用,以及图文回复在英文和中文之间被补空格的问题。身份核对保留已读到的原评论菜单结果,并在查验本人菜单前重新核对同一条回复的正文、图片及位置。
- 最新 APK 已通过 v2 签名校验并安装到测试手机,56 项 JVM 单测通过。手机上的原配置和无障碍设置已恢复,图文回执留在设备上,两种笔记的回执证据均已归档。
## 2026-11-26 · 拾见 0.1.21 小红书评论回复适配