feat:机器接线+Port+6 缺陷修复+文档

This commit is contained in:
2026-11-15 21:02:13 +08:00
parent 282a5b4407
commit b6fa23a3f2
8 changed files with 759 additions and 7 deletions
@@ -43,6 +43,12 @@ class HaoRuiAccessibilityService : AccessibilityService() {
companion object {
private const val TAG = "HaoRui"
/** 文章发布机链路验证的缺省测试正文(全角字符为主,字数口径为整数便于对账)。 */
private const val DEFAULT_ARTICLE_TEST_BODY =
"浩瑞机器链路验证正文开始。本段验证文章发布机真机链路:标题写入、正文写入、字数对账、" +
"首尾锚点回读与草稿回执确认。写入通道为浩瑞调试输入法直写,绕开拼音挂起丢字问题。" +
"尾部标记浩瑞机器链路验证结束。"
/** 孤儿素材周期回收间隔(P2:30 分钟) */
private const val ORPHAN_SWEEP_INTERVAL_MS = 30L * 60L * 1000L
@@ -424,6 +430,8 @@ class HaoRuiAccessibilityService : AccessibilityService() {
addAction("com.haorui.app.ACTION_TEST_WEIBO")
// 调试输入法直写(M4 文章编辑器;需先 adb ime set 切到浩瑞调试输入法)
addAction("com.haorui.app.ACTION_IME_COMMIT")
// 文章发布机链路验证(debug APK:编辑器写入→回读→草稿确认;不碰「下一步」)
addAction("com.haorui.app.ACTION_TEST_ARTICLE")
// 回归测试:发布模式切换(草稿/正式)
addAction("com.haorui.app.ACTION_SET_DRAFT")
addAction("com.haorui.app.ACTION_SET_PUBLISH")
@@ -663,6 +671,13 @@ class HaoRuiAccessibilityService : AccessibilityService() {
val ok = com.haorui.app.automation.ime.HaoRuiDebugIme.commit(text)
RunLogger.i(TAG, "调试输入法提交:len=${text.length} ok=$ok ready=${com.haorui.app.automation.ime.HaoRuiDebugIme.isServiceReady()}")
}
// 文章发布机链路验证(M4;title/body 缺省用内置测试文本)
"com.haorui.app.ACTION_TEST_ARTICLE" -> {
val title = intent.getStringExtra("title")?.takeIf { it.isNotBlank() } ?: "浩瑞机器链路验证1115"
val body = intent.getStringExtra("body")?.takeIf { it.isNotBlank() } ?: DEFAULT_ARTICLE_TEST_BODY
val accepted = startArticleMachineVerify(title, body)
RunLogger.i(TAG, "文章验证受理=$accepted(广播 ACTION_TEST_ARTICLE title=$title bodyLen=${body.length})")
}
// 回归测试发布模式切换(草稿/正式;autoPublish 无 UI 开关,走广播)
"com.haorui.app.ACTION_SET_DRAFT" -> setAutoPublish(false)
"com.haorui.app.ACTION_SET_PUBLISH" -> setAutoPublish(true)
@@ -902,6 +917,63 @@ class HaoRuiAccessibilityService : AccessibilityService() {
true
}
/**
* M4 文章发布机真机验证(debug APK):导航进文章编辑器 → 机器全链
* (标题/正文写入→字数对账+锚点回读→草稿回执)→ HOME 收尾。
* 只写草稿不发布;**不触碰「下一步」**(发布二阶段未取证,保持关闭)。
* 前置:浩瑞调试输入法已启用并选中(adb shell ime enable/set)。
*/
fun startArticleMachineVerify(title: String, body: String): Boolean =
synchronized(stepLifecycleLock) {
if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE == 0 ||
!::scheduler.isInitialized || scheduler.isRunning || publisher.isWorking || interactor.isWorking ||
frontGuard.creditNavigating || !foregroundCoordinator.isIdle()) return@synchronized false
_weiboCollectState.value = WeiboCollectUiState(running = true, categoryLabel = "文章验证")
launchForegroundTask {
val ticket = foregroundCoordinator.tryEnterLegacy("ARTICLE-VERIFY") ?: run {
_weiboCollectState.value = WeiboCollectUiState(done = true, reason = "前台被其他任务占用,稍后重试")
return@launchForegroundTask
}
try {
val ime = android.provider.Settings.Secure.getString(contentResolver, "default_input_method").orEmpty()
if (!ime.startsWith("com.haorui.app/")) {
RunLogger.w(TAG, "M4 文章验证:当前输入法非调试输入法($ime),请先 adb shell ime set com.haorui.app/.automation.ime.HaoRuiDebugIme")
_weiboCollectState.value = WeiboCollectUiState(done = true, reason = "请先切换浩瑞调试输入法")
return@launchForegroundTask
}
val port = com.haorui.app.crossplatform.publish.ToutiaoArticlePort(this@HaoRuiAccessibilityService)
RunLogger.i(TAG, "M4 文章验证开始:导航文章编辑器")
if (!port.openArticleEditor()) {
RunLogger.w(TAG, "M4 文章验证:未进入文章编辑器")
_weiboCollectState.value = WeiboCollectUiState(done = true, reason = "未进入文章编辑器")
return@launchForegroundTask
}
val machine = com.haorui.app.crossplatform.publish.ArticlePublishMachine(port) { msg ->
RunLogger.i(TAG, "M4-Machine: $msg")
}
val result = machine.run(title, body)
RunLogger.i(
TAG,
"M4 文章验证结果:outcome=${result.outcome} phase=${result.phase} " +
"reason=${result.reason} exited=${result.exitedSafely}",
)
// 终态屏抽样(排障用:判定失败时看实际 OCR 到了什么)
RunLogger.i(TAG, "M4 文章验证终态屏:${port.readEditorOcr().take(6).joinToString(" | ")}")
_weiboCollectState.value = WeiboCollectUiState(
done = true,
reason = if (result.outcome == "草稿已核对") "" else result.reason,
collected = if (result.outcome == "草稿已核对") listOf(title to "") else emptyList(),
)
} catch (t: Throwable) {
RunLogger.e(TAG, "M4 文章验证异常: ${t.javaClass.simpleName}:${t.message}", t)
_weiboCollectState.value = WeiboCollectUiState(done = true, reason = "异常: ${t.javaClass.simpleName}")
} finally {
foregroundCoordinator.release(ticket)
}
}
true
}
/** 微博采集执行状态(UI 直读;替代早期"服务日志中转"的过渡实现)。 */
data class WeiboCollectUiState(
val running: Boolean = false,
@@ -0,0 +1,160 @@
package com.haorui.app.crossplatform.publish
import com.haorui.app.crossplatform.compose.ArticleComposer
/**
* 文章发布机(M4 编排层,2026-11-15):标题/正文 → 编辑器写入 → 回读核对 → 草稿确认。
*
* 原语已真机定案(选择器可用性报告「文章编辑器写入实验」):
* - 写入 = focus + 调试输入法 commitText(自绘无 EditText 节点,ACTION_SET_TEXT 不可用);
* - 回读 = OCR(顶栏「N字/草稿已保存」字数对账 + 首尾双锚点);
* - 草稿 = 编辑器自动保存,回执为顶栏常驻「草稿已保存」(区别于「草稿将自动保存」)。
*
* 失败语义(对齐 WeiboHotListCollector 与固定决策 6):
* - **失败**:确定性操作失败(不在编辑器/焦点/写入失败/标题越出 2~30 约束)——记录原因,安全退出;
* - **暂停核对**:核验不可判定或不吻合(字数对不上/锚点缺失/草稿回执未见)——回读规则仍在
* 标定期(字数口径单样本、OCR 有噪声),不吻合一律进人工核对,不宣称成功也不误判失败;
* - 任何路径都在 finally 走 EXIT 安全退出(不碰「下一步」——发布二阶段未取证,保持关闭)。
*
* 图片/封面/声明与「下一步」二阶段:待取证后接入(固定决策:不预设未核验能力)。
* Port 契约:每个方法是一次页面操作/读取,实现方负责可见性核对,不抛异常(返回 false 表失败)。
*/
class ArticlePublishMachine(
private val port: Port,
private val logger: (String) -> Unit = {},
) {
/** 真机驱动接口(编辑器侧;实现绑定调试输入法与 OCR 管线)。 */
interface Port {
/** 已在文章编辑器(标题占位/取消/草稿箱特征可辨)。 */
fun ensureEditorOpen(): Boolean
fun focusTitle(): Boolean
fun focusBody(): Boolean
/** 调试输入法 commitText 直写(分批由 [ArticleTextPolicy.commitBatches] 处理)。 */
fun commitText(text: String): Boolean
/** 当前屏 OCR 行(含顶栏「N字/…」与「草稿已保存」状态)。 */
fun readEditorOcr(): List<String>
/** 正文逐屏滚动全文 OCR 行(回读锚点核验用)。 */
fun readBodyOcrFull(): List<String>
/** 安全退出编辑器(取消/返回;绝不触碰「下一步」)。 */
fun exitEditor(): Boolean
}
enum class Phase {
PREPARE, WRITE_TITLE, WRITE_BODY, READBACK, CONFIRM_DRAFT, EXIT, DONE, FAILED, PAUSED,
}
/** 结果:outcome ∈ 草稿已核对 / 失败 / 暂停核对。 */
data class Result(
val outcome: String,
val phase: Phase,
val reason: String = "",
val exitedSafely: Boolean = false,
)
var phase: Phase = Phase.PREPARE
private set
/**
* 跑完整链路。
* @param title 成品标题(2~30 字,页面自带约束,超界直接失败不落编辑器)。
* @param body 成品正文(非空;长度/数字一致性由上游 ArticleBodyComposer 核验)。
*/
fun run(title: String, body: String): Result {
var failure: String? = null
var paused: String? = null
var failedAt: Phase? = null
var exitedSafely = false
try {
phase = Phase.PREPARE
val titleCp = title.codePointCount(0, title.length)
if (titleCp < ArticleComposer.TITLE_MIN || titleCp > ArticleComposer.TITLE_MAX) {
fail("标题 $titleCp 字不在 ${ArticleComposer.TITLE_MIN}~${ArticleComposer.TITLE_MAX} 约束内")
}
if (body.isBlank()) fail("正文为空")
if (!port.ensureEditorOpen()) fail("未在文章编辑器")
phase = Phase.WRITE_TITLE
if (!port.focusTitle()) fail("标题区未获焦点")
if (!port.commitText(title)) fail("标题写入失败")
logger("标题已写入($titleCp 字)")
phase = Phase.WRITE_BODY
if (!port.focusBody()) fail("正文区未获焦点")
if (!port.commitText(body)) fail("正文写入失败")
logger("正文已写入(口径 ${ArticleTextPolicy.toutiaoWordCountUnits(body) / 2} 字)")
phase = Phase.READBACK
// 顶栏字数多拍采样(最多 3 拍):OCR 偶发粘连(2026-11-15 真机「70097」=
// 「97字/」与相邻数字行合并)或草稿保存未刷新——取每拍全部「数字字」候选,
// 任一候选与正文口径吻合即通过;全部不吻合才进核对。
var wordCountOk = false
var displayed = -1
for (attempt in 1..3) {
val topLines = port.readEditorOcr()
val topText = ArticleTextPolicy.normalize(topLines.joinToString("\n"))
val candidates = WORD_COUNT_REGEX.findAll(topText).mapNotNull {
it.groupValues[1].toIntOrNull()
}
val expected = ArticleTextPolicy.toutiaoWordCountUnits(body) / 2
val hit = candidates.firstOrNull {
ArticleTextPolicy.wordCountMatches(body, it)
}
if (hit != null) {
displayed = hit
wordCountOk = true
break
}
logger("字数采样第${attempt}拍不吻合(候选 ${candidates.toList()},正文口径 $expected)")
}
if (!wordCountOk) {
pause("字数对账不符:正文口径 ${ArticleTextPolicy.toutiaoWordCountUnits(body) / 2},3 拍均未命中")
}
val bodyOcr = port.readBodyOcrFull()
if (!ArticleTextPolicy.titleMatches(title, port.readEditorOcr() + bodyOcr)) {
pause("标题回读锚点缺失(OCR 抽样:${bodyOcr.take(3).joinToString(" | ").take(120)})")
}
if (!ArticleTextPolicy.bodyMatches(body, bodyOcr)) {
pause("正文回读锚点缺失(OCR 抽样:${(bodyOcr.firstOrNull().orEmpty() + "…" + bodyOcr.lastOrNull().orEmpty()).take(160)})")
}
logger("回读核对通过:字数 $displayed、标题/正文锚点可定位")
phase = Phase.CONFIRM_DRAFT
// 回执判定经归一(真机 OCR「已→己」误读,2026-11-15)——见 ArticleTextPolicy.normalizeReceipt
val receiptNormalized = ArticleTextPolicy.normalizeReceipt(port.readEditorOcr().joinToString("\n"))
if (!receiptNormalized.contains(SAVED_MARK)) {
pause("未见「草稿已保存」回执(自动保存可能滞后,结果未知进核对)")
}
logger("草稿回执确认:$SAVED_MARK")
// 图片/封面/声明与「下一步」二阶段未取证——保持关闭,草稿即本链路终点
} catch (stop: StopRequest) {
failure = stop.message
failedAt = phase
} catch (hold: PauseRequest) {
paused = hold.message
failedAt = phase
} finally {
phase = Phase.EXIT
exitedSafely = runCatching { port.exitEditor() }.getOrDefault(false)
}
val outcome = when {
failure != null -> "失败"
paused != null -> "暂停核对"
else -> "草稿已核对"
}
return Result(outcome, failedAt ?: Phase.DONE, failure ?: paused.orEmpty(), exitedSafely)
}
private class StopRequest(message: String) : RuntimeException(message)
private class PauseRequest(message: String) : RuntimeException(message)
private fun fail(reason: String): Nothing = throw StopRequest(reason)
private fun pause(reason: String): Nothing = throw PauseRequest(reason)
companion object {
/** 顶栏字数形态(实测「547字/草稿已保存」)。 */
private val WORD_COUNT_REGEX = Regex("(\\d+)\\s*字")
/** 草稿保存回执(顶栏常驻文本;区别于未保存态「草稿将自动保存」)。 */
const val SAVED_MARK = "草稿已保存"
}
}
@@ -22,9 +22,14 @@ object ArticleTextPolicy {
/** 默认分批大小(字符数):经验值,覆盖编辑器单次 commit 稳定区间。 */
const val DEFAULT_BATCH = 500
/** 回读锚点长度(字符数)。 */
/** 回读锚点分片长度(字符数)与模糊命中阈值。
* OCR 单字误读实测:「请输→清輪」「正文→正女」「已→己」——30 字锚点切 6 片,
* 错 2 片=0.667,0.7 阈值会误拒(2026-11-15 第八轮真机);放宽到 0.6(≥4/6 片),
* 无关内容 0 命中仍拒绝。 */
private const val ANCHOR_LEN = 30
private const val ANCHOR_MIN = 6
private const val SHARD_LEN = 5
const val FUZZY_HIT_RATE = 0.6
/** 超长文本分批(按码点切分,不切开代理对)。空文本返回空表。 */
fun commitBatches(text: String, batchSize: Int = DEFAULT_BATCH): List<String> {
@@ -57,22 +62,72 @@ object ArticleTextPolicy {
}
}
/** 标题回读:规范化后非空且可完整定位。 */
/** 标题回读:规范化后非空且模糊定位(分片命中率 ≥ [FUZZY_HIT_RATE],容忍 OCR 局部误读)。 */
fun titleMatches(expected: String, ocrLines: List<String>): Boolean {
val want = normalize(expected)
if (want.isEmpty()) return false
return normalize(ocrLines.joinToString("\n")).contains(want)
return fuzzyContains(normalize(ocrLines.joinToString("\n")), want)
}
/** 正文回读:首段前 [ANCHOR_LEN] 字 + 尾段后 [ANCHOR_LEN] 字双锚点均能定位。 */
/**
* 正文回读:首段前 [ANCHOR_LEN] 字 + 尾段后 [ANCHOR_LEN] 字双锚点均模糊定位。
* 2026-11-15 真机修订:逐字精确包含过脆(OCR 把「请输」误读为「清輪」,错 1 字即缺失),
* 改分片命中——锚点切 [SHARD_LEN] 字片,命中率 ≥ [FUZZY_HIT_RATE] 即判定位;
* 弱锚点(<6 字)仍拒绝,无关内容 0 命中仍拒绝——不放行假一致。
*/
fun bodyMatches(expected: String, ocrLines: List<String>): Boolean {
val paragraphs = expected.split('\n').map { normalize(it) }.filter { it.isNotEmpty() }
if (paragraphs.isEmpty()) return false
val first = paragraphs.first().take(ANCHOR_LEN)
val last = paragraphs.last().takeLast(ANCHOR_LEN)
// 锚点过短(<6 字)不具定位力,判不一致(宁可进人工核对,不放行假一致)
if (first.length < ANCHOR_MIN || last.length < ANCHOR_MIN) return false
val joined = normalize(ocrLines.joinToString("\n"))
return joined.contains(first) && joined.contains(last)
return fuzzyContains(joined, first) && fuzzyContains(joined, last)
}
/** 分片模糊包含:[needle] 切 [SHARD_LEN] 字片,[haystack] 命中率 ≥ [FUZZY_HIT_RATE]。 */
internal fun fuzzyContains(haystack: String, needle: String): Boolean {
if (needle.isEmpty()) return true
if (haystack.isEmpty()) return false
val shards = if (needle.length <= SHARD_LEN) {
listOf(needle)
} else {
(0 until needle.length step SHARD_LEN)
.map { needle.substring(it, minOf(it + SHARD_LEN, needle.length)) }
}
val hits = shards.count { haystack.contains(it) }
return hits.toDouble() / shards.size >= FUZZY_HIT_RATE
}
/**
* 头条编辑器字数口径(2026-11-15 真机标定):**全角=1 字、半角=0.5 字、空白不计**。
* 实测对账:456 汉字 + 35 全角标点 + 112 半角字母×0.5 = 547(编辑器顶栏实显 547 字)。
* 返回半字单位(全角=2、半角=1),避免小数。
* ⚠️ 数字/ASCII 标点按半角计属推断(实测样本未覆盖),比对留 1 半字容差。
*/
fun toutiaoWordCountUnits(text: String): Int {
var units = 0
var i = 0
while (i < text.length) {
val cp = text.codePointAt(i)
val size = Character.charCount(cp)
if (!Character.isWhitespace(cp)) {
units += if (cp >= 0x80) 2 else 1
}
i += size
}
return units
}
/** 字数对账:编辑器顶栏显示字数 [displayedCount] 与 [text] 口径吻合(±1 半字容差)。 */
fun wordCountMatches(text: String, displayedCount: Int): Boolean {
if (displayedCount < 0) return false
return Math.abs(toutiaoWordCountUnits(text) - displayedCount * 2) <= 1
}
/**
* 草稿回执归一:真机 OCR 实测「已→己」误读(2026-11-15「97字/草稿己保存」)。
* 仅回执匹配使用;正文回读保持字面一致性要求,不受本归一影响。
*/
fun normalizeReceipt(ocrText: String): String = normalize(ocrText).replace("草稿己保存", "草稿已保存")
}
@@ -0,0 +1,266 @@
package com.haorui.app.crossplatform.publish
import android.graphics.Bitmap
import android.os.SystemClock
import com.haorui.app.automation.HaoRuiAccessibilityService
import com.haorui.app.automation.RunLogger
import com.haorui.app.automation.ime.HaoRuiDebugIme
import com.haorui.app.ocr.OcrProcessor
import com.haorui.app.ocr.OcrTextLine
import com.haorui.app.ocr.ScreenCapturer
/**
* 头条文章编辑器真机 Port(M4,2026-11-15)。
*
* 坐标纪律(误点「发布」事故红线):**每步先 OCR 核屏、按 OCR 行 bounds 求坐标再点击**;
* 无 bounds 的兜底坐标仅在屏幕状态标记命中后使用(取证记录见选择器可用性报告)。
* 全程不触碰「下一步」(发布二阶段)与任何发布按钮;收尾 HOME(编辑器草稿自动保存,
* 不受 HOME 影响;下轮 openArticleEditor 总是从 +发布 开新稿)。
*
* 输入前置:需先 `adb shell ime enable/set` 切换到浩瑞调试输入法(commitText 直写通道);
* 未切换时 [commitText] 明确失败并记日志,不静默吞。
*/
class ToutiaoArticlePort(
private val service: HaoRuiAccessibilityService,
) : ArticlePublishMachine.Port {
companion object {
private const val TAG = "TT-Article"
private const val TOUTIAO_PKG = "com.ss.android.article.news"
private const val NAV_TIMEOUT_MS = 60_000L
private const val MAX_BODY_SCREENS = 8
/** 截屏最小间隔(takeScreenshot 系统频率限制;实测连拍 <1s 即 errorCode=3)。 */
private const val MIN_CAPTURE_INTERVAL_MS = 1_200L
/** 兜底坐标(2026-11-15 取证+实测;仅在 OCR 定位失败且屏幕标记命中后使用)。 */
private const val FALLBACK_TITLE_X = 500
private const val FALLBACK_TITLE_Y = 340
private const val FALLBACK_BODY_X = 500
private const val FALLBACK_BODY_Y = 520
/** 编辑器顶栏字数前缀形态(「547字/草稿已保存」)。 */
private val WORD_COUNT_PREFIX = Regex("\\d+\\s*字[//]")
}
// ── ArticlePublishMachine.Port ────────────────────────────
/**
* 编辑器状态判定。⚠️ 灰字占位「请输入标题/请输入正文」OCR 命中率低(2026-11-15 真机:
* 单拍约三成,连 3 拍全丢)——改以**头部深色标记**为主判据(「草稿将自动保存」/
* 「草稿已保存」/「N字/」+「取消」),占位符为辅;重试 6 拍任一命中即认。
* 注意:本判定含已写内容的编辑器(草稿已保存态);空稿约束依赖 openArticleEditor
* 恒从「+发布」新开稿件保证。
*/
override fun ensureEditorOpen(): Boolean = (1..6).any { editorMarkers(screen()) }
override fun focusTitle(): Boolean {
val lines = screen()
val target = lines.firstOrNull { it.text.contains("请输入标题") || it.text.contains("个字") }
return if (target != null && tapCenter(target)) true
else tapFallback(FALLBACK_TITLE_X, FALLBACK_TITLE_Y, "标题占位 OCR 未定位,走兜底坐标")
}
override fun focusBody(): Boolean {
val lines = screen()
val target = lines.firstOrNull { it.text.contains("请输入正文") }
return if (target != null && tapCenter(target)) true
else tapFallback(FALLBACK_BODY_X, FALLBACK_BODY_Y, "正文占位 OCR 未定位,走兜底坐标")
}
override fun commitText(text: String): Boolean {
if (!isDebugImeCurrent()) {
log("当前输入法非浩瑞调试输入法,无法直写(请先 adb shell ime set)")
return false
}
return HaoRuiDebugIme.commit(text)
}
override fun readEditorOcr(): List<String> = screen().map { it.text }
/**
* 正文逐屏全文 OCR。⚠️ commit 后光标停在正文末尾——必须**先滚回顶部**再逐屏下扫,
* 否则正文开头(回读首锚点)永不进入视野(2026-11-15 真机:字数对账 97=97 通过、
* 仅首锚点缺失,即此根因)。半屏上滑+行序去重;连续两屏无新行/滑不动即止。
*/
override fun readBodyOcrFull(): List<String> {
scrollToTop()
val all = mutableListOf<String>()
val seen = HashSet<String>()
var noNewCount = 0
for (i in 0 until MAX_BODY_SCREENS) {
val lines = screen().map { it.text.trim() }.filter { it.isNotEmpty() }
if (lines.isEmpty()) {
Thread.sleep(800)
continue
}
var appended = 0
lines.forEach { if (seen.add(it)) { all.add(it); appended++ } }
if (appended == 0) {
noNewCount++
if (noNewCount >= 2) {
log("回读全文连续两屏无新行,判定到页底")
break
}
} else {
noNewCount = 0
}
val scrolled = kotlinx.coroutines.runBlocking {
service.gestures.swipe(0.5f, 0.62f, 0.5f, 0.25f)
}
if (!scrolled) break
Thread.sleep(1_000)
}
return all
}
/** 滚回正文顶部:反向滑动(指纹下移=内容上移),内容签名稳定即到顶。 */
private fun scrollToTop(maxSwipes: Int = 10) {
var prevSignature = ""
for (i in 0 until maxSwipes) {
val signature = screen().map { it.text.trim() }.joinToString("|")
if (signature == prevSignature) {
log("回读:已滚动到顶部(第 $i 次反向滑)")
return
}
prevSignature = signature
val ok = kotlinx.coroutines.runBlocking {
service.gestures.swipe(0.5f, 0.30f, 0.5f, 0.70f)
}
if (!ok) return
Thread.sleep(800)
}
log("回读:反向滑 $maxSwipes 次未稳定(文档可能超长),按当前顶部继续")
}
/** 安全收尾:HOME 离开编辑器(红线:不点「下一步」/「发布」;草稿自动保存不受影响)。 */
override fun exitEditor(): Boolean = kotlinx.coroutines.runBlocking { service.gestures.home() }
// ── 导航:我的→创作中心→+发布→文章 ───────────────────────
/**
* 打开文章编辑器(新空稿)。循环核屏导航:每步以 OCR 文本+区域约束定位,
* 命中才点;未知页面等待重试。
* @return true=编辑器空稿就绪(占位「请输入标题」可见)。
*/
fun openArticleEditor(): Boolean {
val deadline = SystemClock.elapsedRealtime() + NAV_TIMEOUT_MS
while (SystemClock.elapsedRealtime() < deadline) {
if (service.currentPackage() != TOUTIAO_PKG) {
service.launchApp(TOUTIAO_PKG)
Thread.sleep(1_500)
continue
}
val lines = screen()
val height = runCatching { service.gestures.screenHeight }.getOrDefault(2408)
// ⓪ 干扰弹层(成就海报/活动页)→ BACK 关闭。
// 2026-11-15 真机:发文触发「恭喜你的发文累计阅读量破N」成就弹层挡住创作中心,
// 机器不认识导致 58s 轮询超时;BACK 可关该弹层,不动弹层内任何按钮。
val popup = lines.firstOrNull {
it.text.contains("保存海报并分享") || it.text.contains("编辑后发文") ||
it.text.contains("恭喜你的发文") || it.text.contains("累计阅读量破")
}
if (popup != null) {
log("导航:发现成就/活动弹层,BACK 关闭")
kotlinx.coroutines.runBlocking { service.gestures.back() }
Thread.sleep(1_500); continue
}
// ① 已在编辑器空稿
if (editorMarkers(lines)) return true
// ② 发布面板(微头条撰写页)→「文章」Tab(底部)。
// ⚠️ 文章编辑器底部有同款「文章/微头条」Tab 行——必须先排除编辑器标记,
// 否则会在编辑器里反复点 Tab(2026-11-15 真机缺陷)。
val articleTab = lines.firstOrNull {
it.text.contains("文章") && (it.boundingBox?.top ?: 0) > height * 0.8
}
if (articleTab != null && lines.any { it.text.contains("微头条") } && !editorMarkers(lines)) {
log("导航:发布面板 →「文章」Tab")
tapCenter(articleTab); Thread.sleep(1_500); continue
}
// ③ 创作中心(作品管理/创作权益特征)→ 右上「+发布」
val publish = lines.firstOrNull {
it.text.contains("发布") && (it.boundingBox?.top ?: Int.MAX_VALUE) < height * 0.12
}
if (publish != null && lines.any { it.text.contains("作品管理") || it.text.contains("创作权益") }) {
log("导航:创作中心 →「+发布」")
tapCenter(publish); Thread.sleep(1_500); continue
}
// ④ 我的页 →「查看我的创作中心」卡片
val creator = lines.firstOrNull { it.text.contains("查看我的创作中心") }
if (creator != null) {
log("导航:我的 → 创作中心")
tapCenter(creator); Thread.sleep(1_500); continue
}
// ⑤ 头条首页(底栏首页+我的)→「我的」Tab
val myTab = lines.firstOrNull {
it.text.trim() == "我的" && (it.boundingBox?.top ?: 0) > height * 0.85
}
val homeTab = lines.any {
it.text.trim() == "首页" && (it.boundingBox?.top ?: 0) > height * 0.85
}
if (myTab != null && homeTab) {
log("导航:首页 →「我的」Tab")
tapCenter(myTab); Thread.sleep(1_500); continue
}
Thread.sleep(1_200) // 未知页面(加载中/弹层):核屏等待
}
return false
}
// ── 内部工具 ──────────────────────────────────────────────
/**
* 编辑器标记(多组取或):
* ① 头部深色标记(高对比度,OCR 稳):「草稿将自动保存/草稿已保存/数字字/」+「取消」;
* ② 灰字占位「请输入标题/请输入正文」(辅助信号)。
* 微头条撰写页只有「取消/草稿箱/说点什么」,不会命中本判据。
*/
private fun editorMarkers(lines: List<OcrTextLine>): Boolean {
val texts = lines.map { it.text }
val placeholder = texts.any { it.contains("请输入标题") || it.contains("请输入正文") }
val header = texts.any {
it.contains("草稿将自动保存") || it.contains("草稿已保存") || WORD_COUNT_PREFIX.containsMatchIn(it)
} && texts.any { it.contains("取消") }
return placeholder || header
}
private var lastCaptureAtMs = 0L
/**
* 单屏 OCR。⚠️ `AccessibilityService.takeScreenshot` 有系统频率限制——过密连拍会
* 全部 errorCode=3 被拒(2026-11-15 真机:machine 连拍 6 次全灭→误判"不在编辑器")。
* 本函数统一节流到至少 [MIN_CAPTURE_INTERVAL_MS] 一拍,保护全部调用方。
*/
private fun screen(): List<OcrTextLine> {
val since = SystemClock.elapsedRealtime() - lastCaptureAtMs
if (since < MIN_CAPTURE_INTERVAL_MS) Thread.sleep(MIN_CAPTURE_INTERVAL_MS - since)
lastCaptureAtMs = SystemClock.elapsedRealtime() // 尝试也占限流额度
val bitmap: Bitmap = kotlinx.coroutines.runBlocking {
ScreenCapturer(service).capture()
} ?: return emptyList()
return try {
kotlinx.coroutines.runBlocking { OcrProcessor.recognize(bitmap) }
.flatMap { it.lines }
.filter { it.text.isNotBlank() }
} finally {
bitmap.recycle()
}
}
/** 按 OCR 行 bounds 求中心点击(红线:坐标出自核屏内容)。 */
private fun tapCenter(line: OcrTextLine): Boolean {
val box = line.boundingBox ?: return false
val x = (box.left + box.right) / 2
val y = (box.top + box.bottom) / 2
log("点击「${line.text.take(12)}」@($x,$y)")
return kotlinx.coroutines.runBlocking { service.gestures.tapAt(x, y) }
}
private fun tapFallback(x: Int, y: Int, reason: String): Boolean {
log(reason)
return kotlinx.coroutines.runBlocking { service.gestures.tapAt(x, y) }
}
private fun isDebugImeCurrent(): Boolean =
android.provider.Settings.Secure.getString(service.contentResolver, "default_input_method")
?.startsWith("com.haorui.app/") == true
private fun log(msg: String) = RunLogger.i(TAG, msg)
}
@@ -0,0 +1,141 @@
package com.haorui.app.crossplatform.publish
import org.junit.Assert.*
import org.junit.Test
/**
* 文章发布机验收:相位顺序(写入→回读→草稿确认→安全退出)、失败/暂停分流
* (确定性操作失败=失败;核验不吻合或不可核=暂停核对)、标题约束前置、
* 「不碰下一步」契约(Port 无下一步方法,EXIT 恒安全退出)。
*/
class ArticlePublishMachineTest {
private val title = "浩瑞调试标题勿发布1115"
private val body = "浩瑞实验标记A开始。这是正文内容,长度足以支撑首尾锚点定位,尾部需要三十字符以上确保锚点稳健可靠。浩瑞实验标记B结束。"
private class FakePort(private val title: String, private val body: String) : ArticlePublishMachine.Port {
val calls = mutableListOf<String>()
var editorOpenOk = true
var titleFocusOk = true
var bodyFocusOk = true
var commitOk = true
var savedOk = true
var exitOk = true
var displayedCount: Int? = null // null=顶栏不显字数
var bodyOcrLines: List<String> = listOf(title, body)
private fun topLine(): String {
val count = displayedCount ?: return "取消 草稿将自动保存 草稿箱"
val saved = if (savedOk) "草稿已保存" else "草稿将自动保存"
return "取消 ${count}字/${saved} 草稿箱"
}
override fun ensureEditorOpen(): Boolean { calls += "ensureEditorOpen"; return editorOpenOk }
override fun focusTitle(): Boolean { calls += "focusTitle"; return titleFocusOk }
override fun focusBody(): Boolean { calls += "focusBody"; return bodyFocusOk }
override fun commitText(text: String): Boolean {
calls += "commitText(${text.take(6)})"
return commitOk
}
override fun readEditorOcr(): List<String> { calls += "readEditorOcr"; return listOf(topLine()) }
override fun readBodyOcrFull(): List<String> { calls += "readBodyOcrFull"; return bodyOcrLines }
override fun exitEditor(): Boolean { calls += "exitEditor"; return exitOk }
}
private fun port(displayed: Int? = null) = FakePort(title, body).apply {
displayedCount = displayed ?: ArticleTextPolicy.toutiaoWordCountUnits(body) / 2
}
@Test fun happyPathRunsPhasesInOrderAndConfirmsDraft() {
val p = port()
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("草稿已核对", result.outcome)
assertEquals(ArticlePublishMachine.Phase.DONE, result.phase)
assertTrue(result.exitedSafely)
// 相位顺序:写入 → 回读(顶栏+全文)→ 草稿确认 → 安全退出
val order = listOf("ensureEditorOpen", "focusTitle", "commitText(浩瑞调试标题)", "focusBody",
"commitText(浩瑞实验标记)", "readEditorOcr", "readBodyOcrFull", "readEditorOcr", "readEditorOcr", "exitEditor")
assertEquals(order, p.calls)
}
@Test fun titleOutOfRangeFailsInPrepareBeforeAnyWrite() {
val p = port()
val result = ArticlePublishMachine(p).run("这是一个远超三十个字的标题因为它包含了太多无意义的填充内容导致超限", body)
assertEquals("失败", result.outcome)
assertEquals(ArticlePublishMachine.Phase.PREPARE, result.phase)
assertTrue(result.reason.contains("约束"))
assertFalse(p.calls.any { it.startsWith("commitText") }) // 未写入任何内容
assertTrue(result.exitedSafely) // 依然安全退出
}
@Test fun commitFailureFailsAndExitsSafely() {
val p = port().apply { commitOk = false }
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("失败", result.outcome)
assertEquals(ArticlePublishMachine.Phase.WRITE_TITLE, result.phase)
assertTrue(result.reason.contains("标题写入失败"))
assertTrue(result.exitedSafely)
}
@Test fun bodyFocusFailureFailsAtWriteBody() {
val p = port().apply { bodyFocusOk = false }
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("失败", result.outcome)
assertEquals(ArticlePublishMachine.Phase.WRITE_BODY, result.phase)
assertTrue(result.reason.contains("正文区"))
}
@Test fun notInEditorFailsAtPrepare() {
val p = port().apply { editorOpenOk = false }
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("失败", result.outcome)
assertTrue(result.reason.contains("未在文章编辑器"))
}
@Test fun wordCountMismatchPausesForManualReview() {
// 核验不吻合=暂停核对(不误判失败、不宣称成功)
val p = port(displayed = 999)
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("暂停核对", result.outcome)
assertEquals(ArticlePublishMachine.Phase.READBACK, result.phase)
assertTrue(result.reason.contains("字数对账不符"))
assertTrue(result.exitedSafely)
}
@Test fun unreadableWordCountPausesForManualReview() {
val p = port().apply { displayedCount = null }
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("暂停核对", result.outcome)
assertTrue(result.reason.contains("3 拍均未命中"))
}
@Test fun missingReadbackAnchorPausesForManualReview() {
val p = port().apply { bodyOcrLines = listOf("完全无关的页面内容") }
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("暂停核对", result.outcome)
assertTrue(result.reason.contains("锚点缺失"))
}
@Test fun missingDraftReceiptPausesAsUnknownResult() {
// 未见「草稿已保存」= 结果未知进核对(未知结果保护),不宣称已保存
val p = port().apply { savedOk = false }
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("暂停核对", result.outcome)
assertEquals(ArticlePublishMachine.Phase.CONFIRM_DRAFT, result.phase)
assertTrue(result.reason.contains("草稿已保存"))
}
@Test fun draftReceiptToleratesYiToJiOcrMisread() {
// 归一逻辑在 Policy 层验证(ArticleTextPolicyTest);此处验证「将自动保存」未被放宽吞掉
val p = port().apply { savedOk = false }
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("暂停核对", result.outcome)
}
@Test fun exitFailureStillReportsButDoesNotClaimSafeExit() {
val p = port().apply { exitOk = false }
val result = ArticlePublishMachine(p).run(title, body)
assertEquals("草稿已核对", result.outcome) // 链路本体成功
assertFalse(result.exitedSafely) // 但退出未确认,如实上报
}
}
@@ -97,4 +97,59 @@ class ArticleTextPolicyTest {
assertFalse(ArticleTextPolicy.bodyMatches("短" + System.lineSeparator() + "太短", listOf("短 太短")))
assertFalse(ArticleTextPolicy.bodyMatches("", listOf("任意")))
}
// ── 分片模糊命中(2026-11-15 真机修订:OCR 误读「请输→清輪」逐字精确不可行)──────
@Test fun fuzzyContainsToleratesLocalizedOcrErrors() {
// 真机实测误读形态:整行精确匹配失败,分片命中 4/6 ≥ 0.6 放行(0.7 会误拒)
val haystack = "浩瑞机器链路验证正文开始。本段验证文章发布机真机链路:标题写入、正文写入"
assertTrue(ArticleTextPolicy.fuzzyContains(haystack, "浩瑞机器链路验证正文开始。本段验证文章"))
// 无关内容 0 命中:仍拒绝
assertFalse(ArticleTextPolicy.fuzzyContains("完全无关的页面内容文字", "浩瑞机器链路验证正文"))
}
@Test fun bodyMatchesWithFuzzyAnchorAfterOcrMisread() {
// 锚点内混入误读字(「清輪入标题」式),分片命中率仍过阈
val body = "首段内容足够长用于锚点定位,这里写满三十个字符以上的开场句,确保锚点稳健可靠。" +
"中间是过渡内容。" +
"尾段内容同样足够长用于尾部锚点定位,结尾句写满三十个字符以上,确保双锚点都能命中。"
// OCR 误读首锚点中 1~2 字(5 字片里错 1 字 → 该片 miss,其余 hit)
val ocr = listOf(
"首段内完足够长用于锚点定位,这里写满三十个字符以上的开场句,确保锚点稳健可靠。中间是过渡内容。",
"尾段内容同样足够长用于尾部锚点定位,结尾句写满三十个字符以上,确保双锚点都能命中。",
)
assertTrue(ArticleTextPolicy.bodyMatches(body, ocr))
}
// ── 草稿回执归一(真机「已→己」误读)──────────────────────
@Test fun normalizeReceiptFixesJiMisreadAndKeepsUnsavedState() {
// 真机实测形态:97字/草稿己保存 → 归一为已保存回执
assertTrue(ArticleTextPolicy.normalizeReceipt("97字/草稿己保存").contains("草稿已保存"))
// 未保存态「草稿将自动保存」不因归一被误吞
assertFalse(ArticleTextPolicy.normalizeReceipt("取消 草稿将自动保存 草稿箱").contains("草稿已保存"))
}
// ── 头条字数对账(真机标定口径)───────────────────────────
@Test fun wordCountGoldenFromDeviceExperiment() {
// 真机实测金样本(2026-11-15 文章编辑器写入实验):603 字符
// (456 汉字 + 35 全角标点 + 112 半角字母),编辑器顶栏实显 547 字
val sentence = "正文写入通道为浩瑞调试输入法commitText直写,绕开拼音输入法挂起丢字问题,逐段验证换行与长度约束。"
val body = "浩瑞实验标记A开始。" + sentence.repeat(11) + "浩瑞实验标记B结束。"
assertEquals(603, body.length)
assertEquals(1094, ArticleTextPolicy.toutiaoWordCountUnits(body)) // 547 字 × 2 半字单位
assertTrue(ArticleTextPolicy.wordCountMatches(body, 547))
assertFalse(ArticleTextPolicy.wordCountMatches(body, 548))
}
@Test fun wordCountTreatsHalfwidthAsHalfAndSkipsWhitespace() {
assertEquals(4, ArticleTextPolicy.toutiaoWordCountUnits("测试")) // 全角×2=4 半字
assertEquals(3, ArticleTextPolicy.toutiaoWordCountUnits("abc")) // 半角×3=3 半字
assertEquals(3, ArticleTextPolicy.toutiaoWordCountUnits("a b c")) // 空白不计
// ±1 半字容差(数字/ASCII 标点口径未标定,四舍五入语义未知)
assertTrue(ArticleTextPolicy.wordCountMatches("abc", 1))
assertTrue(ArticleTextPolicy.wordCountMatches("abc", 2))
assertFalse(ArticleTextPolicy.wordCountMatches("abc", 3))
}
}