From b5ac4ca4d40385dd19f9cc0b8fd7c31e37735f8d Mon Sep 17 00:00:00 2001 From: huanghaohao <759903577@qq.com> Date: Sat, 14 Nov 2026 09:34:26 +0800 Subject: [PATCH] =?UTF-8?q?feat:=201.=E5=AE=8C=E6=88=90=E5=A4=B4=E6=9D=A1?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E4=BA=8C=E7=BB=B4=E7=A0=81=E6=A0=B8=E9=AA=8C?= =?UTF-8?q?=EF=BC=8C=E4=BF=AE=E5=A4=8D=E9=A6=96=E9=A1=B5=E5=AF=BC=E8=88=AA?= =?UTF-8?q?=E5=8F=8A=E5=81=9C=E6=AD=A2=E5=90=8E=E9=87=8D=E8=AF=95=E3=80=82?= =?UTF-8?q?=202.=E8=A1=A5=E9=BD=90=E5=85=B1=E4=BA=AB=E6=8F=90=E4=BA=A4?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E3=80=81=E5=8F=96=E6=B6=88=E6=81=A2=E5=A4=8D?= =?UTF-8?q?=E5=92=8C=E6=9C=AA=E7=9F=A5=E7=B4=A0=E6=9D=90=E4=BF=9D=E6=8A=A4?= =?UTF-8?q?=E3=80=82=203.88=20=E9=A1=B9=20JVM=E3=80=8119=20=E9=A1=B9=20SQL?= =?UTF-8?q?ite=20=E6=B5=8B=E8=AF=95=E9=80=9A=E8=BF=87=EF=BC=9B=E7=9C=9F?= =?UTF-8?q?=E6=9C=BA=E8=B4=A6=E5=8F=B7=E6=A0=B8=E9=AA=8C=E3=80=81=E5=81=9C?= =?UTF-8?q?=E6=AD=A2=E3=80=81=E9=87=8D=E8=AF=95=E9=80=9A=E8=BF=87=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +- app/build.gradle.kts | 3 + app/src/main/AndroidManifest.xml | 4 + .../main/java/com/haorui/app/MainActivity.kt | 54 +++- .../haorui/app/automation/GestureRunner.kt | 56 ++++- .../automation/HaoRuiAccessibilityService.kt | 232 +++++++++++++++--- .../app/automation/machine/PublishMachine.kt | 90 ++++++- .../app/automation/scheduler/LaneScheduler.kt | 15 +- .../com/haorui/app/data/ConfigRepository.kt | 8 +- .../com/haorui/app/data/model/AppConfig.kt | 2 + .../com/haorui/app/ocr/CreditGateRunner.kt | 27 +- .../com/haorui/app/scheduler/QuotaManager.kt | 72 ++++-- .../com/haorui/app/scheduler/RecoveryChain.kt | 13 + .../java/com/haorui/app/ui/nav/HaoRuiNav.kt | 59 ++++- .../com/haorui/app/ui/screens/HomeScreens.kt | 16 +- .../haorui/app/ui/screens/UtilityScreens.kt | 31 ++- docs/ui-prototype.html | 12 +- docs/回归测试清单.md | 17 +- docs/开发计划.md | 14 +- docs/开发进度.md | 72 +++++- docs/技术架构与代码说明.md | 39 ++- docs/跨平台自动发布设计.md | 8 +- docs/选择器可用性报告.md | 30 ++- gradle.properties | 2 + 24 files changed, 754 insertions(+), 129 deletions(-) diff --git a/README.md b/README.md index 822c3f0..99df624 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 浩瑞使用 Kotlin 与 Jetpack Compose 构建,在安卓手机上调度内容采集、筛选、处理和今日头条发布。现有头条视频流程继续保留,跨平台图文与视频按独立模块逐步开发。 -当前状态见[开发进度](docs/开发进度.md),实施顺序与验收见[开发计划](docs/开发计划.md)。新增能力按[纯手机方案](docs/跨平台自动发布设计.md)实现,运行无需电脑后台;新功能尚未实现。[手机界面静态原型](docs/ui-prototype.html)可离线预览,所有数据与操作均为本地演示。 +当前状态见[开发进度](docs/开发进度.md),实施顺序与验收见[开发计划](docs/开发计划.md)。新增能力按[纯手机方案](docs/跨平台自动发布设计.md)实现,配置、Compose 工作台、本地任务库和启停代际已接入;真实来源采集与新发布器仍待开发和验收。运行无需电脑后台。[手机界面静态原型](docs/ui-prototype.html)可离线预览,其中的数据与操作均为本地演示。 --- @@ -45,7 +45,8 @@ JDK 位于 `C:\Program Files\Java\jdk-21`,为**本机既有安装**,本工 | 自动化 | AccessibilityService + GestureDescription | | OCR | Google ML Kit 中文文字识别(本地推理) | | 网络 | HttpURLConnection | -| 存储 | DataStore / SharedPreferences;新增任务库计划使用 SQLite | +| 存储 | DataStore / SharedPreferences;跨平台任务使用独立 SQLiteOpenHelper 库 | +| 名片二维码 | [ZXing core 3.5.3](https://github.com/zxing/zxing/tree/zxing-3.5.3),Apache-2.0;LICENSE/NOTICE 位于 app/src/main/assets/third_party | | 调度 | 协程 + LaneScheduler | | 接线 | 构造注入,未使用 Hilt | | 构建 | Gradle (Kotlin DSL) + Android Gradle Plugin | @@ -59,7 +60,7 @@ JDK 位于 `C:\Program Files\Java\jdk-21`,为**本机既有安装**,本工 | 目标平台版本 | **锁定今日头条 18.3.0**,不做版本自适应 | | 既有功能 | 视频采集发布、粉丝互动、休息浏览、参数与记录入口保留 | | 外部服务 | 模型由手机调用;不接入来源不明的中继或远程授权 | -| 新增跨平台图文与视频 | 纯手机运行,来源 App 采集,保留原视频流程;待开发 | +| 新增跨平台图文与视频 | 纯手机运行;配置、界面和本地任务框架已接入,来源与发布器待验收;保留原视频流程 | --- diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 8a11dd2..2f53c2a 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -19,6 +19,7 @@ android { targetSdk = 35 versionCode = 1 versionName = "0.1.0" + testInstrumentationRunner = "com.haorui.app.crossplatform.StoreInstrumentation" } buildTypes { @@ -71,5 +72,7 @@ dependencies { implementation("com.google.mlkit:text-recognition-chinese:16.0.1") debugImplementation("androidx.compose.ui:ui-tooling") + implementation("com.google.zxing:core:3.5.3") testImplementation("junit:junit:4.13.2") + androidTestImplementation("junit:junit:4.13.2") } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 39dd2c7..ecaff81 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -7,6 +7,10 @@ + + + + diff --git a/app/src/main/java/com/haorui/app/MainActivity.kt b/app/src/main/java/com/haorui/app/MainActivity.kt index a2acc38..5f50bdb 100644 --- a/app/src/main/java/com/haorui/app/MainActivity.kt +++ b/app/src/main/java/com/haorui/app/MainActivity.kt @@ -55,6 +55,7 @@ class MainActivity : ComponentActivity() { override fun onNewIntent(intent: android.content.Intent) { super.onNewIntent(intent) handleCommand(intent) + consumeAccountClipboardRequest() } /** @@ -67,6 +68,11 @@ class MainActivity : ComponentActivity() { */ override fun onResume() { super.onResume() + if (com.haorui.app.crossplatform.account.AccountClipboardRequests.shared.hasPending()) { + consumeAccountClipboardRequest() + return + } + consumeAccountClipboardRequest() // 前台读取触发点:仅在有待读取标志时处理并记录(避免刷屏) // ⚠️ 二轮审计:消费标志防一次请求读两次(onResume+handleCommand 双触发), // 读取代际号捕获在此刻,submit 回传 —— 跨轮迟到结果会被代际校验拒收。 @@ -78,6 +84,41 @@ class MainActivity : ComponentActivity() { } } + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + if (hasFocus) consumeAccountClipboardRequest() + } + + private fun consumeAccountClipboardRequest() { + if (!hasWindowFocus()) return + val requests = com.haorui.app.crossplatform.account.AccountClipboardRequests.shared + val request = requests.claim() ?: return + fun read(attempt: Int) { + window.decorView.postDelayed({ + if (!requests.isCurrent(request) || !hasWindowFocus()) return@postDelayed + val result = runCatching { + val manager = getSystemService(CLIPBOARD_SERVICE) as android.content.ClipboardManager + if (request.operation == com.haorui.app.crossplatform.account.AccountClipboardRequests.Operation.PREPARE && attempt == 0) { + manager.setPrimaryClip(android.content.ClipData.newPlainText(request.nonce, request.nonce)) + } + val clip = manager.primaryClip + val item = clip?.takeIf { it.itemCount == 1 }?.getItemAt(0) + val text = (item?.text?.toString() ?: item?.coerceToText(this)?.toString())?.takeIf { it.length <= 8192 } + if (attempt == 0 || attempt == 4) com.haorui.app.automation.RunLogger.i("AccountClipboard", + "operation=${request.operation} attempt=$attempt items=${clip?.itemCount} text=${item?.text != null} uri=${item?.uri != null} readable=${text != null}") + if (text == null) return@runCatching null + val stamp = clip?.description?.timestamp ?: return@runCatching null + com.haorui.app.crossplatform.account.AccountClipboardRequests.Result(text, stamp) + }.getOrNull() + val waitingForCopy = request.operation == com.haorui.app.crossplatform.account.AccountClipboardRequests.Operation.READ && + (result == null || result.text == request.nonce) + if (waitingForCopy && attempt < 4) read(attempt + 1) + else if (requests.complete(request, result)) moveTaskToBack(true) + }, if (attempt == 0) 900 else 400) + } + read(0) + } + private fun handleCommand(intent: android.content.Intent?) { if (intent?.action == com.haorui.app.automation.ClipboardBridge.ACTION_CONSUME_CLIP) { // ⚠️ 二轮审计:双触发防护 —— onResume 已消费则不再读(一次请求只读一次) @@ -105,6 +146,10 @@ class MainActivity : ComponentActivity() { com.haorui.app.automation.RunLogger.i("UI", "收到停止命令(intent extra)") com.haorui.app.automation.HaoRuiAccessibilityService.instance?.stopAutomation() } + "testAccount" -> if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0) { + val accepted = com.haorui.app.automation.HaoRuiAccessibilityService.instance?.verifyAccountSandbox() == true + com.haorui.app.automation.RunLogger.i("UI", "账号只读核验受理=$accepted") + } // ── 装机调试命令(adb 触发,验证 F1/F2 用)───────── "testCredit" -> { val svc = com.haorui.app.automation.HaoRuiAccessibilityService.instance @@ -139,6 +184,8 @@ class MainActivity : ComponentActivity() { private fun consumeClipboardInForeground(gen: Int) { com.haorui.app.automation.RunLogger.i("UI", "前台读取页已就绪,700ms 后读剪贴板") window.decorView.postDelayed({ + if (gen != com.haorui.app.automation.ClipboardBridge.generation || + com.haorui.app.crossplatform.account.AccountClipboardRequests.shared.hasPending()) return@postDelayed val url = com.haorui.app.automation.ClipboardBridge.readFromClipboard(applicationContext) { msg -> com.haorui.app.automation.RunLogger.i("UI", "前台剪贴板诊断: $msg") } @@ -161,12 +208,12 @@ class MainActivity : ComponentActivity() { @Composable private fun HaoRuiRoot(repository: ConfigRepository) { val saved by repository.config.collectAsState(initial = null) - var local by remember { mutableStateOf(AppConfig()) } + var local by remember { mutableStateOf(null) } val scope = rememberCoroutineScope() // DataStore 首个值到达时灌入本地副本(只灌一次,避免覆盖用户正在编辑的内容) LaunchedEffect(saved) { - saved?.let { if (local == AppConfig()) local = it } + saved?.let { if (local == null) local = it } } fun commit(next: AppConfig) { @@ -174,5 +221,6 @@ private fun HaoRuiRoot(repository: ConfigRepository) { scope.launch { repository.save(next) } } - HaoRuiApp(config = local, onConfigChange = ::commit) + val current = local + if (current != null) HaoRuiApp(config = current, onConfigChange = ::commit) } diff --git a/app/src/main/java/com/haorui/app/automation/GestureRunner.kt b/app/src/main/java/com/haorui/app/automation/GestureRunner.kt index 4d74f2b..fb2d1ce 100644 --- a/app/src/main/java/com/haorui/app/automation/GestureRunner.kt +++ b/app/src/main/java/com/haorui/app/automation/GestureRunner.kt @@ -49,6 +49,14 @@ class GestureRunner(private val service: AccessibilityService) { return tapAt(r.centerX(), r.centerY()) } + /** 外部正式提交使用单次坐标派发,拒绝/取消/超时均由提交日志进入核对。 */ + suspend fun tapNodeOnce(node: AccessibilityNodeInfo): Boolean { + val bounds = Rect() + node.getBoundsInScreen(bounds) + if (bounds.isEmpty) return false + return tapAt(bounds.centerX(), bounds.centerY(), retry = false) + } + /** * 坐标点击(带前摇 + 失败重试一次)。 * ⚠️ 二轮审计:仅**系统拒绝派发**(手势未开始)才重试 —— @@ -144,6 +152,9 @@ class GestureRunner(private val service: AccessibilityService) { ): Boolean { // 对照原 q0:手势期间压悬浮窗,防吃掉长按起点 com.haorui.app.overlay.MonitorOverlay.setHidden(true) + var heldStroke: GestureDescription.StrokeDescription? = null + var releaseAtMs = 0L + var finished = false try { val path = Path().apply { moveTo(x(fromX).toFloat(), y(fromY).toFloat()) @@ -153,18 +164,30 @@ class GestureRunner(private val service: AccessibilityService) { val desc = GestureDescription.Builder().addStroke(stroke).build() val dispatched = runCatching { service.dispatchGesture(desc, null, null) }.getOrDefault(false) if (!dispatched) return false + heldStroke = stroke + releaseAtMs = android.os.SystemClock.elapsedRealtime() + holdMs delay(holdMs + continueMs) - // 续接收尾段并终结(willContinue=false → 系统随后回调完成) - val endPath = Path().apply { moveTo(x(toX).toFloat(), y(toY).toFloat()) } - val endStroke = runCatching { stroke.continueStroke(endPath, 0, 50L, false) }.getOrNull() ?: return false - return runCatching { - service.dispatchGesture( - GestureDescription.Builder().addStroke(endStroke).build(), null, null, - ) - }.getOrDefault(false) } finally { - runCatching { com.haorui.app.overlay.MonitorOverlay.setHidden(false) } + kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) { + try { + finished = withTimeoutOrNull(GESTURE_TIMEOUT_MS) { + val stroke = heldStroke ?: return@withTimeoutOrNull false + delay((releaseAtMs - android.os.SystemClock.elapsedRealtime()).coerceAtLeast(0L)) + val endPath = Path().apply { moveTo(x(toX).toFloat(), y(toY).toFloat()) } + val endStroke = stroke.continueStroke(endPath, 0, 50L, false) + suspendCancellableCoroutine { cont -> + val accepted = service.dispatchGesture(GestureDescription.Builder().addStroke(endStroke).build(), + object : AccessibilityService.GestureResultCallback() { + override fun onCompleted(g: GestureDescription) { if (cont.isActive) cont.resume(true) } + override fun onCancelled(g: GestureDescription) { if (cont.isActive) cont.resume(false) } + }, null) + if (!accepted && cont.isActive) cont.resume(false) + } + } ?: false + } finally { com.haorui.app.overlay.MonitorOverlay.setHidden(false) } + } } + return finished } // ── 全局动作 ────────────────────────────────────────────── @@ -195,6 +218,8 @@ class GestureRunner(private val service: AccessibilityService) { x1: Float, y1: Float, x2: Float, y2: Float, ): StrokeOutcome { com.haorui.app.overlay.MonitorOverlay.setHidden(true) + val completed = kotlinx.coroutines.CompletableDeferred() + var accepted = false try { val path = Path().apply { moveTo(x1, y1) @@ -206,22 +231,27 @@ class GestureRunner(private val service: AccessibilityService) { suspendCancellableCoroutine { cont -> val dispatched = service.dispatchGesture(desc, object : AccessibilityService.GestureResultCallback() { override fun onCompleted(g: GestureDescription) { + completed.complete(Unit) if (cont.isActive) cont.resume(StrokeOutcome.COMPLETED) } override fun onCancelled(g: GestureDescription) { + completed.complete(Unit) // 已开始被取消 = 可能已部分执行,不能重放 if (cont.isActive) cont.resume(StrokeOutcome.UNCERTAIN) } }, null) + accepted = dispatched + if (!dispatched) completed.complete(Unit) if (!dispatched && cont.isActive) cont.resume(StrokeOutcome.REJECTED) } } ?: StrokeOutcome.UNCERTAIN } finally { - // 等手势回调落地后再恢复悬浮窗(对齐原 q0 的 j2+60ms 后恢复) - kotlinx.coroutines.withTimeoutOrNull(100L) { - kotlinx.coroutines.delay(60) + kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) { + try { + if (accepted) withTimeoutOrNull(GESTURE_TIMEOUT_MS) { completed.await() } + delay(60) + } finally { com.haorui.app.overlay.MonitorOverlay.setHidden(false) } } - com.haorui.app.overlay.MonitorOverlay.setHidden(false) } } } diff --git a/app/src/main/java/com/haorui/app/automation/HaoRuiAccessibilityService.kt b/app/src/main/java/com/haorui/app/automation/HaoRuiAccessibilityService.kt index 0139c7b..2a1a5cf 100644 --- a/app/src/main/java/com/haorui/app/automation/HaoRuiAccessibilityService.kt +++ b/app/src/main/java/com/haorui/app/automation/HaoRuiAccessibilityService.kt @@ -23,6 +23,13 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch +import kotlinx.coroutines.Job +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.cancel +import kotlinx.coroutines.ensureActive +import com.haorui.app.crossplatform.schedule.ForegroundCoordinator +import com.haorui.app.crossplatform.schedule.CrossRunLifecycle +import com.haorui.app.crossplatform.data.CrossPublishTaskStore import com.haorui.app.automation.scheduler.LaneScheduler /** @@ -55,6 +62,56 @@ class HaoRuiAccessibilityService : AccessibilityService() { * 而且恢复动作绝不能走主线程(主线程被卡时恢复回调自己也进不来)。 */ private val automationScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + val foregroundCoordinator = ForegroundCoordinator() + @Volatile + private var crossRunSession: CrossRunLifecycle.Session? = null + @Volatile private var sharedBudgetRestored = false + @Volatile private var hasSharedAccountHistory = true + private val stepJobs = java.util.Collections.synchronizedSet(mutableSetOf()) + private val stepLifecycleLock = Any() + private val _accountVerification = kotlinx.coroutines.flow.MutableStateFlow("头条账号尚未核验") + val accountVerification: kotlinx.coroutines.flow.StateFlow = _accountVerification + + /** 停止状态下独占前台,仅核验身份,不开启调度或绑定额度。 */ + fun verifyAccountSandbox(): Boolean = synchronized(stepLifecycleLock) { + if (!::scheduler.isInitialized || scheduler.isRunning || publisher.isWorking || interactor.isWorking || + restBrowse.isResting || frontGuard.creditNavigating) return@synchronized false + val ticket = foregroundCoordinator.tryEnterExclusive("ACCOUNT") ?: return@synchronized false + val generation = startGeneration + _accountVerification.value = "正在核验头条账号" + launchForegroundTask { + try { + val reader = com.haorui.app.crossplatform.account.ToutiaoAccountReader(this@HaoRuiAccessibilityService) { + instance === this@HaoRuiAccessibilityService && startGeneration == generation && foregroundCoordinator.isCurrent(ticket) + } + val verified = reader.verify() + _accountVerification.value = if (verified != null) "已核验:${verified.displayName}" else "核验未通过:${reader.failure}" + RunLogger.i(TAG, if (verified != null) "当前头条账号核验通过" else "头条账号核验未通过:${reader.failure}") + if (startGeneration == generation && foregroundCoordinator.isCurrent(ticket)) bringAppToForeground() + } catch (cancelled: kotlin.coroutines.cancellation.CancellationException) { + _accountVerification.value = "账号核验已取消" + throw cancelled + } catch (failure: Exception) { + _accountVerification.value = "账号核验中断,请重试" + RunLogger.w(TAG, "账号核验中断:${failure.javaClass.simpleName}") + } finally { foregroundCoordinator.release(ticket) } + } + true + } + + private fun launchForegroundTask(block: suspend () -> Unit): Job = synchronized(stepLifecycleLock) { + val generation = startGeneration + val job = automationScope.launch(start = CoroutineStart.LAZY) { + if (generation != startGeneration) return@launch + try { block() } + catch (ce: kotlin.coroutines.cancellation.CancellationException) { throw ce } + catch (t: Exception) { RunLogger.e(TAG, "前台任务失败: ${t.javaClass.simpleName}", t) } + } + stepJobs.add(job) + job.invokeOnCompletion { stepJobs.remove(job) } + job.start() + job + } private lateinit var scheduler: LaneScheduler lateinit var collector: CollectMachine @@ -106,6 +163,16 @@ class HaoRuiAccessibilityService : AccessibilityService() { instance = this RunLogger.init(applicationContext) DiagnosticLogger.init(applicationContext) + val taskStore = CrossPublishTaskStore.get(applicationContext) + crossRunSession = taskStore.runLifecycle.openSession() + automationScope.launch { + taskStore.runLifecycle.state.collect { state -> + state.error?.let { + RunLogger.w(TAG, it) + TaskStatusBus.status("$it,跨平台任务已暂停") + } + } + } // 进程存活心跳:独立于 RunLogger,用于区分「日志管道死亡」与「进程真死」 com.haorui.app.logging.Heartbeat.start(applicationContext) // ⚠️ 2026-10-29 根因修复:必须立刻拉起前台保活服务。 @@ -162,13 +229,15 @@ class HaoRuiAccessibilityService : AccessibilityService() { // RestBrowseMachine 全部吃构造默认值,用户配置(配额/休息/重置点/类目/ // 滑动上限/声明/封面/浏览)对自动化整体无效。此处统一注入并持续跟随。 // ⚠️ 二轮审计:原实现只打日志不替换,AI 改写恒走本地兜底、API 路径从未生效。 - kotlinx.coroutines.MainScope().launch { + automationScope.launch { try { var restored = false var lastResetHour = -1 var lastResetMinute = -1 ConfigRepository(applicationContext).config.collect { cfg -> latestConfig = cfg + foregroundCoordinator.configure(cfg.crossPlatform.enabled) + crossRunSession?.configure(cfg.crossPlatform.enabled) val resetChanged = restored && (cfg.reset.hour != lastResetHour || cfg.reset.minute != lastResetMinute) lastResetHour = cfg.reset.hour lastResetMinute = cfg.reset.minute @@ -220,7 +289,7 @@ class HaoRuiAccessibilityService : AccessibilityService() { .putInt("published_count", 0) .putString("segment_state", quotaManager.snapshotState()) .apply() - automationScope.launch { runDailyResetChain() } + launchForegroundTask { runDailyResetChain() } } // 三条状态机车道(命名车道,互不阻塞) @@ -233,14 +302,20 @@ class HaoRuiAccessibilityService : AccessibilityService() { // 每条车道的 step() 必须包 try/catch:协程内未捕获异常会被 // 默认 handler 静默吞掉(OEM 又限制 logcat),导致车道"静默停摆"。 - fun safeStep(name: String, block: suspend () -> Unit) { - automationScope.launch { + fun safeStep(lane: LaneScheduler.Lane, block: suspend () -> Unit) = synchronized(stepLifecycleLock) { + if (!scheduler.isScheduled(lane)) return@synchronized + launchForegroundTask { + val ticket = foregroundCoordinator.tryEnterLegacy(lane.name) ?: return@launchForegroundTask try { + kotlinx.coroutines.currentCoroutineContext().ensureActive() block() } catch (ce: kotlin.coroutines.cancellation.CancellationException) { - RunLogger.w(TAG, "[$name] step 被取消") + RunLogger.w(TAG, "[${lane.name}] step 被取消") + throw ce } catch (t: Throwable) { - RunLogger.e(TAG, "[$name] step 异常: ${t.javaClass.simpleName}:${t.message}", t) + RunLogger.e(TAG, "[${lane.name}] step 异常: ${t.javaClass.simpleName}:${t.message}", t) + } finally { + foregroundCoordinator.release(ticket) } } } @@ -259,7 +334,7 @@ class HaoRuiAccessibilityService : AccessibilityService() { RunLogger.i(TAG, "前台驱动者冲突(${frontGuard.describe()}),采集车道让路") return@register } - safeStep("Collect") { collector.step() } + safeStep(LaneScheduler.Lane.COLLECT) { collector.step() } } scheduler.register(LaneScheduler.Lane.PUBLISH) { // ⚠️ 2026-10-30 第一性审计:发布机空闲时消化管线暂存队列 @@ -269,14 +344,14 @@ class HaoRuiAccessibilityService : AccessibilityService() { if (publisher.isIdle && frontGuard.maySubmit()) { pipeline.processPending() } - safeStep("Publish") { publisher.step() } + safeStep(LaneScheduler.Lane.PUBLISH) { publisher.step() } } - scheduler.register(LaneScheduler.Lane.INTERACT) { safeStep("Interact") { interactor.step() } } + scheduler.register(LaneScheduler.Lane.INTERACT) { safeStep(LaneScheduler.Lane.INTERACT) { interactor.step() } } // ⚠️ 2026-10-31:mayRest 此前是死 API,REST 车道裸跑会与信用分导航/互动互踩。 // 倒计时播报不驱动前台可照常;浏览动作必须过互斥表。 scheduler.register(LaneScheduler.Lane.REST) { - safeStep("Rest") { restBrowse.step(mayBrowse = { frontGuard.mayRest() }) } + safeStep(LaneScheduler.Lane.REST) { restBrowse.step(mayBrowse = { frontGuard.mayRest() }) } } // 看门狗车道:执行恢复链检查(8 个核心检查项)+ 孤儿素材周期回收(P2) @@ -403,6 +478,11 @@ class HaoRuiAccessibilityService : AccessibilityService() { override fun onInterrupt() { RunLogger.w(TAG, "无障碍服务被中断") + if (foregroundCoordinator.hasSourceOwner()) { + stopAutomation() + TaskStatusBus.status("来源采集被中断,已暂停并保留本地任务") + return + } // ── 场景 1:互动进行中 → 不强拉车道(对照原 G1 停止本轮互动)── // 强拉会打断 doFinish 收尾(回关计数/退页);让 INTERACT 车道自然跑完。 @@ -416,8 +496,7 @@ class HaoRuiAccessibilityService : AccessibilityService() { if (::publisher.isInitialized && publisher.isWorking) { RunLogger.w(TAG, "发布任务进行中被中断,暂停自动化避免重复发布") TaskStatusBus.status("服务中断,发布结果待核对,自动任务已暂停,避免重复发布") - scheduler.clearIntent() - scheduler.stopAll() + stopAutomation() return } @@ -444,9 +523,18 @@ class HaoRuiAccessibilityService : AccessibilityService() { } } + override fun onUnbind(intent: Intent?): Boolean { + crossRunSession?.close() + stopAutomation() + if (instance === this) instance = null + return super.onUnbind(intent) + } + override fun onDestroy() { runCatching { unregisterReceiver(cmdReceiver) } - scheduler.stopAll() + crossRunSession?.close() + stopAutomation() + automationScope.cancel() // ⚠️ 2026-10-29 修复静态引用生命周期竞态: // 重装/服务重绑时,旧实例的 onDestroy 会晚于新实例的 onServiceConnected 执行, // 原来无条件 instance = null 会把刚设好的新实例清掉, @@ -510,7 +598,7 @@ class HaoRuiAccessibilityService : AccessibilityService() { } // ── 装机调试广播(不动前台,被测对象不被测试通道干扰)── "com.haorui.app.ACTION_TEST_CREDIT" -> { - automationScope.launch { + launchForegroundTask { val msg = com.haorui.app.ocr.CreditGateRunner.readOnce( this@HaoRuiAccessibilityService, ) @@ -541,13 +629,13 @@ class HaoRuiAccessibilityService : AccessibilityService() { // 评估完成时校验代际未变,用户的停止意图永不被覆盖(对齐 ClipboardBridge 模式)。 val myGen = startGeneration if (cfg.credit.gateEnabled && !dayBlocked) { - automationScope.launch { + launchForegroundTask { val verdict = com.haorui.app.ocr.CreditGateRunner.evaluate( this@HaoRuiAccessibilityService, cfg.credit.threshold, ) if (myGen != startGeneration) { RunLogger.i(TAG, "信用评估完成但启动代际已变(用户已停止),放弃拉起") - return@launch + return@launchForegroundTask } when (verdict) { com.haorui.app.ocr.CreditGateRunner.Verdict.BLOCKED -> { @@ -558,7 +646,7 @@ class HaoRuiAccessibilityService : AccessibilityService() { if (dayBlocked) { TaskStatusBus.status("今日任务已被禁止启动(信用分门控),等待下次重置解除") } else { - scheduler.start() + startScheduler(myGen) } } } @@ -569,19 +657,82 @@ class HaoRuiAccessibilityService : AccessibilityService() { TaskStatusBus.status("今日任务已被禁止启动(信用分门控),等待下次重置解除") return } - scheduler.start() + startScheduler(myGen) } - fun stopAutomation() { + private fun startScheduler(expectedGeneration: Int) = synchronized(stepLifecycleLock) { + if (expectedGeneration != startGeneration || instance !== this) return@synchronized + foregroundCoordinator.beginRun() + scheduler.start() + if (scheduler.isRunning) crossRunSession?.start() + } + + fun stopAutomation() = synchronized(stepLifecycleLock) { // F5:递增启动代际,使在途的异步信用评估失效(停止意图优先) startGeneration++ + foregroundCoordinator.stop() + crossRunSession?.stop() // 清除「应该在跑」的意愿,自愈监控据此不再拉起 - scheduler.clearIntent() - scheduler.stopAll() + if (::scheduler.isInitialized) { + scheduler.clearIntent() + scheduler.stopAll() + } + synchronized(stepJobs) { stepJobs.toList() }.forEach { it.cancel() } } fun isRunning(): Boolean = scheduler.isRunning + /** 新来源仅可在旧流程的完整安全边界入场,不在详情、编辑或回执中途切换。 */ + fun tryEnterSourceForeground(sourceId: String): ForegroundCoordinator.Ticket? { + if (currentCrossRunGeneration() == null) return null + val source = com.haorui.app.crossplatform.source.SourceRegistry.find(sourceId) ?: return null + val status = com.haorui.app.crossplatform.source.SourceRegistry.executionStatus( + sourceId, Targets.versionOf(this, source.packageName), latestConfig.crossPlatform, + ) + if (!status.canExecute) return null + return foregroundCoordinator.tryEnterSource(sourceId) { + currentCrossRunGeneration() != null && !publisher.isWorking && !interactor.isWorking && !restBrowse.isResting && + !frontGuard.creditNavigating && collector.phase == CollectMachine.Phase.SCAN + } + } + + /** 来源与后续任务写库使用此代际,不能使用前台 Ticket.generation。 */ + fun currentCrossRunGeneration(): Long? = crossRunSession?.currentGeneration() + + fun requiresSharedLegacyBudget(): Boolean = latestConfig.crossPlatform.enabled || hasSharedAccountHistory + + fun createLegacyPublishSession(mediaPath: String, payloadHash: String): com.haorui.app.crossplatform.publish.LegacyPublishSession? { + val generation = currentCrossRunGeneration() ?: return null + val current = { instance === this && currentCrossRunGeneration() == generation && requiresSharedLegacyBudget() } + val base = com.haorui.app.crossplatform.publish.StoreLegacyPublishJournal(CrossPublishTaskStore.get(applicationContext)) + val journal = object : com.haorui.app.crossplatform.publish.LegacyPublishSession.Journal by base { + override suspend fun bind(account: String, generation: Long, snapshot: com.haorui.app.crossplatform.model.AccountQuotaSnapshot): Boolean { + val bound = base.bind(account, generation, snapshot) + if (bound) synchronized(stepLifecycleLock) { + hasSharedAccountHistory = true + } + return bound + } + } + return com.haorui.app.crossplatform.publish.LegacyPublishSession(generation, mediaPath, payloadHash, + journal, + { com.haorui.app.crossplatform.account.ToutiaoAccountReader(this, current).verify() }, + { quotaManager.submissionBudget(latestConfig.crossPlatform) }, current) + } + + /** 混合正式发布等待 M6 健康与作品回执验收,不能绕回旧的独立计数入口。 */ + fun legacyFormalPublishRejection(): String? = when { + !sharedBudgetRestored -> "共享额度恢复中,正式发布暂缓" + requiresSharedLegacyBudget() -> "共享发布尚待验收,正式发布已暂停" + else -> null + } + + fun tryEnterCreditForeground(): ForegroundCoordinator.Ticket? { + if (latestConfig.crossPlatform.enabled && + (publisher.isWorking || interactor.isWorking || collector.phase != CollectMachine.Phase.SCAN)) return null + return foregroundCoordinator.tryEnterLegacy("CREDIT") + } + /** * 测试/沙盒启动一轮互动(装机死锁防护): * 调度器未运行时用 [LaneScheduler.startLaneOnly] 单车道沙盒驱动 @@ -630,7 +781,7 @@ class HaoRuiAccessibilityService : AccessibilityService() { * 日期键与 QuotaManager.effectiveDate 一致 —— 分时段 hour<6 归前一天, * 用 LocalDate.now() 会在凌晨重启误清当日计数。 */ - private fun restoreRunState() { + private suspend fun restoreRunState() { // ⚠️ 日期键必须与 QuotaManager.effectiveDate 一致(二轮审计): // 分时段 hour<6 归前一天,用 LocalDate.now() 会在凌晨重启误清当日计数。 val today = quotaManager.todayKey() @@ -661,6 +812,19 @@ class HaoRuiAccessibilityService : AccessibilityService() { RunLogger.i(TAG, "断点续排通道就绪(日期键 $today)") // 锚定完成,武装重置判定(此前 checkDailyReset 一律短路,防启动竞态误触发) quotaManager.armResetChain() + try { + val store = CrossPublishTaskStore.get(applicationContext) + hasSharedAccountHistory = store.hasSharedBudgetHistory() + store.legacyBudgetState(quotaManager.todayKey())?.let(quotaManager::mergeSharedLegacyState) + sharedBudgetRestored = true + foregroundCoordinator.configure(latestConfig.crossPlatform.enabled) + crossRunSession?.configure(latestConfig.crossPlatform.enabled) + } catch (ce: kotlin.coroutines.cancellation.CancellationException) { + throw ce + } catch (failure: Exception) { + RunLogger.w(TAG, "共享额度恢复失败:${failure.javaClass.simpleName}") + TaskStatusBus.status("共享额度未恢复,正式发布已暂停") + } } private suspend fun runDailyResetChain() { @@ -731,16 +895,26 @@ class HaoRuiAccessibilityService : AccessibilityService() { } private fun sweepOrphans() { - runCatching { - // 先取在用素材快照再删 —— 宁可少删不可错删(P2 事务边界) - val active = pipeline.activeFilePaths() - val n = videoDownloader.clearDownloadCache(active) - if (n > 0) RunLogger.i(TAG, "孤儿素材回收: 清理 $n 个陈旧缓存文件(排除在用 ${active.size} 个)") - }.onFailure { - RunLogger.w(TAG, "孤儿素材回收失败: ${it.message}") + automationScope.launch { + try { + // 先取在用素材快照再删 —— 宁可少删不可错删(P2 事务边界) + val protected = CrossPublishTaskStore.get(applicationContext).protectedSubmissionMediaPaths() + val active = pipeline.activeFilePaths() + protected + val n = videoDownloader.clearDownloadCache(active) + if (n > 0) RunLogger.i(TAG, "孤儿素材回收: 清理 $n 个陈旧缓存文件(排除在用 ${active.size} 个)") + } catch (ce: kotlin.coroutines.cancellation.CancellationException) { + throw ce + } catch (failure: Exception) { + RunLogger.w(TAG, "孤儿素材回收失败: ${failure.javaClass.simpleName}") + } } } + suspend fun clearUnusedDownloadCache(): Int = kotlinx.coroutines.withContext(Dispatchers.IO) { + val protected = CrossPublishTaskStore.get(applicationContext).protectedSubmissionMediaPaths() + videoDownloader.clearDownloadCache(pipeline.activeFilePaths() + protected) + } + /** 拉起目标 App(原 RecoveryResumeTask case 16→21 的 HOME+重开逻辑) */ fun launchApp(pkg: String) { val pm = packageManager diff --git a/app/src/main/java/com/haorui/app/automation/machine/PublishMachine.kt b/app/src/main/java/com/haorui/app/automation/machine/PublishMachine.kt index 6ac6ff2..da69f8b 100644 --- a/app/src/main/java/com/haorui/app/automation/machine/PublishMachine.kt +++ b/app/src/main/java/com/haorui/app/automation/machine/PublishMachine.kt @@ -12,6 +12,11 @@ import com.haorui.app.data.model.ToutiaoConfig import com.haorui.app.pipeline.VideoDownloader import com.haorui.app.scheduler.QuotaManager import kotlinx.coroutines.delay +import com.haorui.app.crossplatform.publish.LegacyPublishSession +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ensureActive /** * 视频发布状态机。 @@ -66,6 +71,7 @@ class PublishMachine( private var mediaUri: String = "" private var autoPublish: Boolean = true private var eligibilityCheck: (() -> String?)? = null + private var sharedSession: LegacyPublishSession? = null private var declaration: String = ToutiaoSelectors.TXT_DECLARATION_DEFAULT private var titleRetry = 0 @@ -99,10 +105,15 @@ class PublishMachine( log("发布机非空闲(phase=$phase),拒绝新任务") return false } + if (autoPublish) svc.legacyFormalPublishRejection()?.let { reason -> + TaskStatusBus.status(reason) + return false + } this.title = title this.mediaUri = mediaUri this.autoPublish = autoPublish this.eligibilityCheck = eligibilityCheck + this.sharedSession = null this.declaration = declaration ?: toutiaoConfig.workDeclaration this.titleRetry = 0 this.coverFramesTried = 0 @@ -183,6 +194,9 @@ class PublishMachine( Phase.DONE -> doDone() Phase.FAILED -> doFailed() } + } catch (cancelled: kotlinx.coroutines.CancellationException) { + withContext(NonCancellable) { runCatching { sharedSession?.markUnknown("发布步骤已取消,等待作品核对") } } + throw cancelled } finally { busy.set(false) } @@ -191,11 +205,20 @@ class PublishMachine( // ── 各相位实现 ──────────────────────────────────────────── private suspend fun doPrepare() { + if (pauseForSharedAccount()) return if (title.isBlank() || mediaUri.isBlank()) { log("标题或素材为空,任务作废") go(Phase.FAILED) return } + if (autoPublish && svc.requiresSharedLegacyBudget()) { + val context = sharedSession ?: svc.createLegacyPublishSession(mediaUri, payloadFingerprint()).also { sharedSession = it } + if (context == null || (context.state == LegacyPublishSession.State.NEW && !context.prepare())) { + TaskStatusBus.status(context?.reason ?: "共享发布运行尚未就绪") + go(Phase.FAILED) + return + } + } // ⚠️ 2026-10-29 补齐缺失环节:先用 ACTION_SEND 打开头条发布页并带入视频+标题。 // new Intent(ACTION_SEND).setType("video/mp4") // .putExtra(EXTRA_STREAM, uri).putExtra(EXTRA_TEXT, rewritten) @@ -515,6 +538,7 @@ class PublishMachine( /** 点发布 / 存草稿 */ private suspend fun doConfirm() { + if (pauseForSharedAccount()) return val root = rootOrNull() ?: return eligibilityCheck?.invoke()?.let { reason -> log("点击发布前筛选拒绝:$reason") @@ -553,8 +577,21 @@ class PublishMachine( delay(800) return } - val tapped = svc.gestures.tapNode(btn) + val context = sharedSession + val tapped = if (context != null) { + val titleNode = NodeLocator.byId(root, ToutiaoSelectors.ID_PUB_TITLE) + val exactTitle = titleNode?.text?.toString() == title + titleNode?.recycle() + context.dispatch(payloadFingerprint(), { exactTitle && svc.currentCrossRunGeneration() == context.generation }) { + svc.gestures.tapNodeOnce(btn) + } + } else svc.gestures.tapNode(btn) runCatching { btn.recycle() } + if (context != null && !tapped) { + TaskStatusBus.status(context.reason) + go(Phase.FAILED) + return + } // ⚠️ 二轮审计:tap 失败不能进 WAIT_RECEIPT 干等 30 分钟超时 if (!tapped) { log("发布按钮 tap 失败,重试") @@ -571,8 +608,23 @@ class PublishMachine( go(Phase.WAIT_RECEIPT) } + private fun pauseForSharedAccount(): Boolean { + if (!autoPublish) return false + val reason = svc.legacyFormalPublishRejection() ?: return false + TaskStatusBus.status(reason) + return true + } + /** 等回执(发布成功 / 发布失败 / 已发布)—— 未确认回执不计数 */ private suspend fun doWaitReceipt() { + sharedSession?.let { context -> + // M6 作品核对器尚未接通。共享尝试不能进入旧的分享面板/超时成功判定。 + context.markUnknown("发布动作已派发,等待明确作品回执") + TaskStatusBus.status("发布结果待核对,素材与额度已保留") + go(Phase.FAILED) + svc.stopAutomation() + return + } val root = rootOrNull() ?: return // ⚠️ 2026-10-29 真机实测:正式发布的回执文案是**「发布成功,分享给朋友一起看」**, @@ -647,6 +699,13 @@ class PublishMachine( } private suspend fun doDone() { + if (sharedSession != null) { + sharedSession?.markUnknown("缺少明确作品核对回执") + TaskStatusBus.status("共享发布回执待核对,素材与额度已保留") + go(Phase.FAILED) + svc.stopAutomation() + return + } // 对照原 m2():BACK 退出发布页 → 删除本地素材 → 进度计数 → 启动休息 log("收到成功回执,开始收尾(删素材 + 计数 + 休息)") svc.gestures.back() // performGlobalAction(BACK) 退出发布页 @@ -673,6 +732,17 @@ class PublishMachine( } private suspend fun doFailed() { + sharedSession?.let { context -> + context.markUnknown("发布流程中断,等待核对") + log("共享发布已暂停;提交日志和素材保留") + TaskStatusBus.status(context.reason.ifBlank { "共享发布已暂停,素材已保留" }) + title = "" + mediaUri = "" + eligibilityCheck = null + sharedSession = null + reset() + return + } log("发布失败,清理任务态") // ⚠️ 2026-10-30 第一性审计修复:失败也**删素材** —— // 任务不重试,已下载文件留着就是泄漏(对照原 f0 清理链)。 @@ -698,6 +768,24 @@ class PublishMachine( reset() } + private suspend fun payloadFingerprint(): String = withContext(Dispatchers.IO) { + val digest = java.security.MessageDigest.getInstance("SHA-256") + digest.update(title.toByteArray(Charsets.UTF_8)) + digest.update(0.toByte()) + digest.update(declaration.toByteArray(Charsets.UTF_8)) + digest.update(0.toByte()) + java.io.File(mediaUri).inputStream().use { input -> + val buffer = ByteArray(64 * 1024) + while (true) { + kotlin.coroutines.coroutineContext.ensureActive() + val count = input.read(buffer) + if (count < 0) break + digest.update(buffer, 0, count) + } + } + digest.digest().joinToString("") { "%02x".format(it) } + } + companion object { /** 回执等待上限(原 publish_timeout 默认 30 分钟) */ private const val RECEIPT_TIMEOUT_MS = 30L * 60L * 1000L diff --git a/app/src/main/java/com/haorui/app/automation/scheduler/LaneScheduler.kt b/app/src/main/java/com/haorui/app/automation/scheduler/LaneScheduler.kt index d8b1fb8..5a0b02d 100644 --- a/app/src/main/java/com/haorui/app/automation/scheduler/LaneScheduler.kt +++ b/app/src/main/java/com/haorui/app/automation/scheduler/LaneScheduler.kt @@ -72,7 +72,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) { } /** 启动全部车道 */ - fun start() { + @Synchronized fun start() { autoWanted = true if (isRunning) return if (!service.checkVersionGate()) { @@ -85,7 +85,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) { } /** 启动指定车道 */ - fun start(lane: Lane) { + @Synchronized fun start(lane: Lane) { autoWanted = true if (lane in running) return if (!service.checkVersionGate()) return @@ -100,7 +100,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) { * GO_MY 悬停 → isWorking 恒 true → 之后启动任务 COLLECT 永久让路。 * 不能用 [start]:它会置 autoWanted=true,自愈监控误判停摆把全部车道拉起。 */ - fun startLaneOnly(lane: Lane) { + @Synchronized fun startLaneOnly(lane: Lane) { if (lane in running) return if (!service.checkVersionGate()) return schedule(lane) @@ -112,7 +112,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) { * ⚠️ 不清除 [autoWanted] —— 意愿由 [clearIntent] 单独管理, * 否则 `onInterrupt` 里的 stopAll()+start() 会误伤恢复链。 */ - fun stopAll() { + @Synchronized fun stopAll() { jobs.values.forEach { runCatching { it.cancel() } } jobs.clear() running.clear() @@ -121,14 +121,14 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) { } /** 停止单条车道 */ - fun stop(lane: Lane) { + @Synchronized fun stop(lane: Lane) { jobs.remove(lane)?.let { runCatching { it.cancel() } } running.remove(lane) if (running.isEmpty()) isRunning = false } /** 清除「应该在跑」的意愿(用户主动停止时调用,自愈监控据此不再拉起) */ - fun clearIntent() { + @Synchronized fun clearIntent() { autoWanted = false } @@ -136,7 +136,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) { * 强制重启:不管当前 [isRunning] 状态如何,一律重建全部车道。 * 供自愈监控在「意外停摆」时调用(`start()` 遇 isRunning=true 会直接返回,救不了)。 */ - fun forceRestart() { + @Synchronized fun forceRestart() { if (!autoWanted) { RunLogger.w(TAG, "forceRestart 跳过:当前意愿为关,视为用户主动停止") return @@ -151,6 +151,7 @@ class LaneScheduler(private val service: HaoRuiAccessibilityService) { /** 某车道已跑过的节拍数(用于退出条件判定与自愈监控) */ fun tickOf(lane: Lane): Long = ticks[lane] ?: 0L + fun isScheduled(lane: Lane): Boolean = lane in running /** 柦车道上一拍的时间戳(诊断用) */ fun lastTickOf(lane: Lane): Long = lastTickMs[lane] ?: 0L diff --git a/app/src/main/java/com/haorui/app/data/ConfigRepository.kt b/app/src/main/java/com/haorui/app/data/ConfigRepository.kt index 53812d8..417e1f5 100644 --- a/app/src/main/java/com/haorui/app/data/ConfigRepository.kt +++ b/app/src/main/java/com/haorui/app/data/ConfigRepository.kt @@ -8,6 +8,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.haorui.app.automation.RunLogger import com.haorui.app.data.model.AppConfig +import com.haorui.app.crossplatform.model.CrossPlatformConfigCodec import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map @@ -41,7 +42,7 @@ class ConfigRepository(private val context: Context) { /** 整份覆盖写入 */ suspend fun save(cfg: AppConfig) { context.configStore.edit { prefs -> - prefs[keyConfig] = json.encodeToString(AppConfig.serializer(), cfg) + prefs[keyConfig] = json.encodeToString(AppConfig.serializer(), cfg.copy(crossPlatform = cfg.crossPlatform.normalized())) } } @@ -93,7 +94,7 @@ class ConfigRepository(private val context: Context) { segment = out.segment.copy(dailyTotal = 28), ) } - return out + return out.copy(crossPlatform = out.crossPlatform.normalized()) } private val migratedLogged = java.util.concurrent.atomic.AtomicBoolean(false) @@ -188,7 +189,7 @@ class ConfigRepository(private val context: Context) { "browse_stay_max" to c.browse.stayMaxSec.toString(), "collect_mode" to c.collectMode, - ) + ) + CrossPlatformConfigCodec.toFlatMap(c.crossPlatform) private fun buildFromExportMap(m: Map): AppConfig { fun s(k: String, d: String) = m[k] ?: d @@ -282,6 +283,7 @@ class ConfigRepository(private val context: Context) { stayMaxSec = i("browse_stay_max", d.browse.stayMaxSec), ), collectMode = s("collect_mode", d.collectMode), + crossPlatform = CrossPlatformConfigCodec.fromFlatMap(m), ) } } diff --git a/app/src/main/java/com/haorui/app/data/model/AppConfig.kt b/app/src/main/java/com/haorui/app/data/model/AppConfig.kt index fa54f25..d0663be 100644 --- a/app/src/main/java/com/haorui/app/data/model/AppConfig.kt +++ b/app/src/main/java/com/haorui/app/data/model/AppConfig.kt @@ -1,6 +1,7 @@ package com.haorui.app.data.model import kotlinx.serialization.Serializable +import com.haorui.app.crossplatform.model.CrossPlatformConfig /** * 浩瑞配置模型。集中维护采集、发布、互动与服务参数,保留扁平配置导入导出的键名兼容。 @@ -153,6 +154,7 @@ data class AppConfig( val ai: AiConfig = AiConfig(), val browse: BrowseConfig = BrowseConfig(), val collectMode: String = CollectMode.TOUTIAO.name, + val crossPlatform: CrossPlatformConfig = CrossPlatformConfig(), ) { companion object { const val PRESET_VERSION = "haorui-0.1.0" diff --git a/app/src/main/java/com/haorui/app/ocr/CreditGateRunner.kt b/app/src/main/java/com/haorui/app/ocr/CreditGateRunner.kt index 50aa121..55b1a13 100644 --- a/app/src/main/java/com/haorui/app/ocr/CreditGateRunner.kt +++ b/app/src/main/java/com/haorui/app/ocr/CreditGateRunner.kt @@ -179,15 +179,17 @@ object CreditGateRunner { service: HaoRuiAccessibilityService, region: Rect?, ): Int? { + val ticket = service.tryEnterCreditForeground() ?: return null service.frontGuard.creditNavigating = true try { return withOverlayHidden { + if (!service.foregroundCoordinator.isCurrent(ticket)) return@withOverlayHidden null val capturer = ScreenCapturer(service) // 快路径:当前屏已是信用分页(重复检查/误入时省导航) var score = CreditScoreReader.readFromScreen(capturer, region) if (score == null) { RunLogger.i(TAG, "当前屏未识别到信用分,导航至信用分页(我的→创作中心→全部服务→处罚中心)") - if (navigateToCreditPage(service)) { + if (navigateToCreditPage(service, ticket)) { score = CreditScoreReader.readFromScreen(capturer, region) } else { RunLogger.w(TAG, "信用分页导航失败(页面改版或定位失败),按 fail-open 放行") @@ -197,6 +199,7 @@ object CreditGateRunner { } } finally { service.frontGuard.creditNavigating = false + service.foregroundCoordinator.release(ticket) } } @@ -207,20 +210,21 @@ object CreditGateRunner { * (如视频详情页,底部 tab 不可见)→ back 退到有 tab 的页面再找。 * @return 是否走完全部四跳 */ - private suspend fun navigateToCreditPage(service: HaoRuiAccessibilityService): Boolean { + private suspend fun navigateToCreditPage(service: HaoRuiAccessibilityService, ticket: com.haorui.app.crossplatform.schedule.ForegroundCoordinator.Ticket): Boolean { + if (!service.foregroundCoordinator.isCurrent(ticket)) return false // 前台必须是头条(对照 InteractMachine.doGoMy 同款语义) if (service.currentPackage() != Targets.TOUTIAO_PKG) { RunLogger.i(TAG, "前台非头条(pkg=${service.currentPackage()}),先拉起头条") service.launchApp(Targets.TOUTIAO_PKG) delay(2500) } - if (!tapTarget(service, ToutiaoSelectors.TXT_ME, backOnFail = true, preferBottom = true)) return false + if (!tapTarget(service, ticket, ToutiaoSelectors.TXT_ME, backOnFail = true, preferBottom = true)) return false delay(1500) - if (!tapTarget(service, TXT_CREATION_CENTER)) return false + if (!tapTarget(service, ticket, TXT_CREATION_CENTER)) return false delay(1500) - if (!tapTarget(service, TXT_ALL_SERVICES)) return false + if (!tapTarget(service, ticket, TXT_ALL_SERVICES)) return false delay(1500) - if (!tapTarget(service, TXT_PENALTY_CENTER)) return false + if (!tapTarget(service, ticket, TXT_PENALTY_CENTER)) return false delay(2000) // 等信用分页渲染(Lynx) return true } @@ -232,14 +236,17 @@ object CreditGateRunner { */ private suspend fun tapTarget( service: HaoRuiAccessibilityService, + ticket: com.haorui.app.crossplatform.schedule.ForegroundCoordinator.Ticket, label: String, backOnFail: Boolean = false, preferBottom: Boolean = false, ): Boolean { repeat(3) { attempt -> + if (!service.foregroundCoordinator.isCurrent(ticket)) return false // back 兜底从第 2 次开始:首跳失败可能是页面未渲染完(不应急于退页) if (attempt > 0) { if (backOnFail) { + if (!service.foregroundCoordinator.isCurrent(ticket)) return false service.gestures.back() delay(1200) // 等页面退出动画 } else { @@ -252,6 +259,10 @@ object CreditGateRunner { NodeLocator.byText(it, label) ?: NodeLocator.byTextContains(it, label) } if (node != null) { + if (!service.foregroundCoordinator.isCurrent(ticket)) { + node.recycle() + return false + } val ok = service.gestures.tapNode(node) runCatching { node.recycle() } if (ok) { @@ -260,7 +271,7 @@ object CreditGateRunner { } } // ② OCR boundingBox 定位(Lynx 页无树节点,文字仍在像素里) - if (tapByOcr(service, label, preferBottom)) return true + if (tapByOcr(service, ticket, label, preferBottom)) return true RunLogger.w(TAG, "「$label」定位失败(第 ${attempt + 1}/3 次)") } return false @@ -278,6 +289,7 @@ object CreditGateRunner { */ private suspend fun tapByOcr( service: HaoRuiAccessibilityService, + ticket: com.haorui.app.crossplatform.schedule.ForegroundCoordinator.Ticket, label: String, preferBottom: Boolean = false, ): Boolean { @@ -331,6 +343,7 @@ object CreditGateRunner { TAG, "OCR 定位「$label」@$cx,$cy(质量级=${best.quality} 行内精修=${best.refinedCx != null} bbox=${best.box.flattenToString()})", ) + if (!service.foregroundCoordinator.isCurrent(ticket)) return false return service.gestures.tapAt(cx, cy) } } diff --git a/app/src/main/java/com/haorui/app/scheduler/QuotaManager.kt b/app/src/main/java/com/haorui/app/scheduler/QuotaManager.kt index 04ffbb6..ba60551 100644 --- a/app/src/main/java/com/haorui/app/scheduler/QuotaManager.kt +++ b/app/src/main/java/com/haorui/app/scheduler/QuotaManager.kt @@ -6,7 +6,11 @@ import com.haorui.app.data.model.ResetConfig import com.haorui.app.data.model.ToutiaoConfig import java.time.Instant import java.time.LocalTime -import java.time.ZoneId +import java.time.Clock +import com.haorui.app.crossplatform.model.AccountQuotaSnapshot +import com.haorui.app.crossplatform.model.LegacyBudgetState +import com.haorui.app.crossplatform.model.CrossPlatformConfig +import com.haorui.app.crossplatform.model.CrossSubmissionBudget /** * 发布配额管理器。管理每日总量、时段额度、休息与重置快照。 @@ -16,6 +20,7 @@ class QuotaManager( segmentConfig: SegmentConfig, resetConfig: ResetConfig, toutiaoConfig: ToutiaoConfig = ToutiaoConfig(), + private val clock: Clock = Clock.systemDefaultZone(), ) { companion object { private const val TAG = "HaoRui-Quota" @@ -112,7 +117,7 @@ class QuotaManager( val currentSegment: Int get() { // ⚠️ 二轮审计:两次取时钟会跨边界错归时段 → 一次取 now - val now = LocalTime.now() + val now = LocalTime.now(clock) val minutes = now.hour * 60 + now.minute return when { minutes < 360 -> 3 // 00-06 @@ -144,7 +149,7 @@ class QuotaManager( } // 休息期检查(两种模式统一生效) - val now = System.currentTimeMillis() + val now = clock.millis() if (now < restUntilMs) { return false } @@ -196,7 +201,7 @@ class QuotaManager( @Synchronized fun waitSeconds(): Long { checkDailyReset() - val now = System.currentTimeMillis() + val now = clock.millis() return maxOf(0, (restUntilMs - now) / 1000) } @@ -212,12 +217,12 @@ class QuotaManager( val seg = currentSegment segmentCounts[seg]++ dailyCount++ - lastPublishAtMs = System.currentTimeMillis() + lastPublishAtMs = clock.millis() // 设置随机休息期(对齐原 X2():分时段取 segment_N_rest_min/max,否则 rest_min/rest_max) val restRange = restRange() val restSec = (restRange.first..restRange.second).random() - restUntilMs = System.currentTimeMillis() + restSec * 1000L + restUntilMs = clock.millis() + restSec * 1000L log("发布 #$dailyCount (时段${seg + 1}: ${segmentCounts[seg]}/${segmentQuota(seg)}), 休息 ${restSec}s") onRecorded?.invoke(dailyCount) @@ -239,7 +244,7 @@ class QuotaManager( fun initDaily(count: Int) { dailyCount = maxOf(0, count) currentDate = effectiveDate() - lastResetAtMs = lastResetPointMs(System.currentTimeMillis()) + lastResetAtMs = lastResetPointMs(clock.millis()) log("发布计数已恢复: $dailyCount/$dailyTotal") } @@ -279,7 +284,7 @@ class QuotaManager( */ @Synchronized fun snapshotState(): String { - val remainRest = maxOf(0L, (restUntilMs - System.currentTimeMillis()) / 1000) + val remainRest = maxOf(0L, (restUntilMs - clock.millis()) / 1000) return segmentCounts.joinToString(",") + "|" + remainRest + "|" + lastResetAtMs } @@ -300,12 +305,12 @@ class QuotaManager( } parts.getOrNull(1)?.toLongOrNull()?.let { remainSec -> if (remainSec > 0) { - restUntilMs = System.currentTimeMillis() + remainSec * 1000L + restUntilMs = clock.millis() + remainSec * 1000L log("休息期已恢复: 剩余 ${remainSec}s") } } lastResetAtMs = parts.getOrNull(2)?.toLongOrNull() - ?.takeIf { it > 0 } ?: lastResetPointMs(System.currentTimeMillis()) + ?.takeIf { it > 0 } ?: lastResetPointMs(clock.millis()) } // ── 内部逻辑 ────────────────────────────────────────────── @@ -319,9 +324,8 @@ class QuotaManager( * 与日界自动重置共用同一标记,天然去重(无双触发竞态)。 * - 重置动作链(信用分检查/每日互动)经 [onDailyReset] 回调移交服务层。 */ - private fun checkDailyReset() { + private fun checkDailyReset(nowMs: Long = clock.millis()) { if (!resetArmed) return // 启动竞态防护:restoreRunState 锚定前不判定 - val nowMs = System.currentTimeMillis() val rp = lastResetPointMs(nowMs) if (rp > lastResetAtMs) { lastResetAtMs = rp @@ -347,7 +351,7 @@ class QuotaManager( * 重置触发判定与快照锚定共用此口径,保证「跨重启不误清、不漏重置」。 */ private fun lastResetPointMs(nowMs: Long): Long { - val zone = ZoneId.systemDefault() + val zone = clock.zone val now = Instant.ofEpochMilli(nowMs).atZone(zone) var rp = now.toLocalDate().atTime(boundaryTime()).atZone(zone) if (rp.toInstant().toEpochMilli() > nowMs) { @@ -364,8 +368,46 @@ class QuotaManager( * 默认重置点(00:00 / 分时段 06:00)下与原 effectiveDate() 行为完全一致。 */ private fun effectiveDate(): String { - val ms = lastResetPointMs(System.currentTimeMillis()) - return Instant.ofEpochMilli(ms).atZone(ZoneId.systemDefault()).toLocalDate().toString() + val ms = lastResetPointMs(clock.millis()) + return Instant.ofEpochMilli(ms).atZone(clock.zone).toLocalDate().toString() + } + + @Synchronized fun accountSnapshot(): AccountQuotaSnapshot { + check(resetArmed) { "旧配额恢复尚未完成" } + val now = clock.millis() + checkDailyReset(now) + val local = Instant.ofEpochMilli(now).atZone(clock.zone) + val start = lastResetPointMs(now) + val nextReset = Instant.ofEpochMilli(start).atZone(clock.zone).plusDays(1).toInstant().toEpochMilli() + val slot = local.hour / 6 + val segment = (slot + 3) % 4 + val day = Instant.ofEpochMilli(start).atZone(clock.zone).toLocalDate().toString() + val nextWindow = local.toLocalDate().atStartOfDay(clock.zone).plusHours((slot + 1) * 6L).toInstant().toEpochMilli() + return AccountQuotaSnapshot(now, if (segmentConfig.enabled) minOf(nextReset, nextWindow) else nextReset, + day, dailyTotal, dailyCount, "$day:$segment", if (segmentConfig.enabled) segmentQuota(segment) else null, + segmentCounts[segment], segmentCounts.toList(), restUntilMs) + } + + @Synchronized fun sharedRestUntil(): Long { + val range = restRange() + return clock.millis() + (range.first.coerceAtLeast(0)..range.second.coerceAtLeast(0)).random().toLong() * 1000L + } + + @Synchronized fun submissionBudget(config: CrossPlatformConfig): CrossSubmissionBudget { + val snapshot = accountSnapshot() + val normalized = config.normalized() + return CrossSubmissionBudget(snapshot.dayKey, snapshot.totalLimit, snapshot.legacyUsed, + normalized.articleDailyLimit, normalized.videoDailyLimit, snapshot, normalized.publishGapMinutes * 60_000L) + } + + @Synchronized fun mergeSharedLegacyState(state: LegacyBudgetState) { + checkDailyReset() + restUntilMs = maxOf(restUntilMs, state.restUntilMs) + if (state.dayKey == effectiveDate()) { + dailyCount = maxOf(dailyCount, state.used) + for (segment in 0..3) segmentCounts[segment] = maxOf(segmentCounts[segment], state.windows["${state.dayKey}:$segment"] ?: 0) + } + onRecorded?.invoke(dailyCount) } /** 取指定时段的配额 */ diff --git a/app/src/main/java/com/haorui/app/scheduler/RecoveryChain.kt b/app/src/main/java/com/haorui/app/scheduler/RecoveryChain.kt index c0f3b5b..36ec800 100644 --- a/app/src/main/java/com/haorui/app/scheduler/RecoveryChain.kt +++ b/app/src/main/java/com/haorui/app/scheduler/RecoveryChain.kt @@ -188,8 +188,20 @@ class RecoveryChain( * @return 恢复动作数量(0 = 一切正常) */ fun runOnce(): Int { + // 新来源持有整条采集会话期间,恢复链不能把来源页面当成错误页面拉回。 + if (service.foregroundCoordinator.hasSourceOwner()) return 0 + val ticket = service.foregroundCoordinator.tryEnterLegacy("RECOVERY") ?: return 0 + try { + return runChecks(ticket) + } finally { + service.foregroundCoordinator.release(ticket) + } + } + + private fun runChecks(ticket: com.haorui.app.crossplatform.schedule.ForegroundCoordinator.Ticket): Int { var recoveryCount = 0 for (action in actions) { + if (!service.foregroundCoordinator.isCurrent(ticket)) break val hasIssue = try { action.detector() } catch (e: Exception) { @@ -197,6 +209,7 @@ class RecoveryChain( continue } if (!hasIssue) continue + if (!service.foregroundCoordinator.isCurrent(ticket)) break RunLogger.w(TAG, "发现异常: ${action.name}") if (!action.recoverable) { diff --git a/app/src/main/java/com/haorui/app/ui/nav/HaoRuiNav.kt b/app/src/main/java/com/haorui/app/ui/nav/HaoRuiNav.kt index b122c5e..eed516f 100644 --- a/app/src/main/java/com/haorui/app/ui/nav/HaoRuiNav.kt +++ b/app/src/main/java/com/haorui/app/ui/nav/HaoRuiNav.kt @@ -3,6 +3,8 @@ package com.haorui.app.ui.nav import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home +import androidx.compose.material.icons.filled.AutoAwesome +import androidx.compose.material.icons.filled.Assignment import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Settings @@ -19,12 +21,14 @@ import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.font.FontWeight import androidx.navigation.NavGraph.Companion.findStartDestination @@ -34,6 +38,13 @@ import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.haorui.app.automation.HaoRuiAccessibilityService import com.haorui.app.automation.Targets +import com.haorui.app.crossplatform.data.CrossPublishTaskStore +import com.haorui.app.crossplatform.ui.CrossAutomationScreen +import com.haorui.app.crossplatform.ui.CrossTasksScreen +import com.haorui.app.crossplatform.ui.SourcesScreen +import com.haorui.app.crossplatform.ui.TopicFiltersScreen +import com.haorui.app.crossplatform.ui.TopicsScreen +import com.haorui.app.crossplatform.ui.rememberSourceVersions import com.haorui.app.data.model.AppConfig import com.haorui.app.data.model.CollectMode import com.haorui.app.ui.screens.A11yScreen @@ -52,6 +63,11 @@ import kotlinx.coroutines.launch object Routes { const val HOME = "home" const val COLLECT = "collect" + const val TOPICS = "topics" + const val TASKS = "tasks" + const val CROSS_SOURCES = "cross_sources" + const val CROSS_FILTERS = "cross_filters" + const val CROSS_AUTOMATION = "cross_automation" const val INTERACT = "interact" const val MINE = "mine" const val TOUTIAO = "toutiao" @@ -65,6 +81,11 @@ object Routes { val titles = mapOf( HOME to "浩瑞", COLLECT to "采集", + TOPICS to "热点", + TASKS to "任务", + CROSS_SOURCES to "来源 App 管理", + CROSS_FILTERS to "选题筛选", + CROSS_AUTOMATION to "自动化设置", INTERACT to "互动", MINE to "我的", TOUTIAO to "头条采集设置", @@ -90,12 +111,12 @@ object Routes { ) /** 底部 tab */ - val tabs = listOf(HOME, COLLECT, INTERACT, MINE) + val tabs = listOf(HOME, TOPICS, TASKS, INTERACT, MINE) /** 路由 → 所属 tab(用于返回键回落) */ fun tabOf(route: String): String = when (route) { - TOUTIAO, BAIDU -> COLLECT - API, BROWSE, LOGS, A11Y -> MINE + TOUTIAO, BAIDU, COLLECT, API, BROWSE, LOGS, A11Y, CROSS_AUTOMATION -> MINE + CROSS_SOURCES, CROSS_FILTERS -> TOPICS else -> route } } @@ -104,17 +125,24 @@ private data class TabDef(val route: String, val label: String, val icon: ImageV private val tabDefs = listOf( TabDef(Routes.HOME, "首页", Icons.Filled.Home), - TabDef(Routes.COLLECT, "采集", Icons.Filled.PlayArrow), + TabDef(Routes.TOPICS, "热点", Icons.Filled.AutoAwesome), + TabDef(Routes.TASKS, "任务", Icons.Filled.Assignment), TabDef(Routes.INTERACT, "互动", Icons.Filled.Settings), TabDef(Routes.MINE, "我的", Icons.Filled.Person), ) /** - * 浩瑞主壳:顶栏 + 内容 + 底部 4 tab + * 浩瑞主壳:顶栏 + 内容 + 底部五栏导航。 */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) { + val context = LocalContext.current.applicationContext + val taskStore = remember(context) { CrossPublishTaskStore.get(context) } + val crossTasks by taskStore.tasks.collectAsState() + val crossTasksLoaded by taskStore.isLoaded.collectAsState() + val crossTasksError by taskStore.loadError.collectAsState() + val sourceVersions = rememberSourceVersions() val nav = rememberNavController() val snackbar = remember { SnackbarHostState() } val scope = rememberCoroutineScope() @@ -171,7 +199,7 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) { Scaffold( topBar = { // ⚠️ 2026-10-29:去掉顶栏标题文字(用户要求)。 - // tab 页(首页/采集/互动/我的)完全无顶栏; + // 主导航页完全无顶栏; // 子页只保留返回箭头,不显示任何标题文字。 if (!onTab) { CenterAlignedTopAppBar( @@ -189,7 +217,7 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) { NavigationBar(containerColor = MaterialTheme.colorScheme.surface) { tabDefs.forEach { tab -> NavigationBarItem( - selected = currentRoute == tab.route, + selected = Routes.tabOf(currentRoute) == tab.route, onClick = { nav.navigate(tab.route) { popUpTo(nav.graph.findStartDestination().id) { saveState = true } @@ -217,8 +245,25 @@ fun HaoRuiApp(config: AppConfig, onConfigChange: (AppConfig) -> Unit) { onToggleRun = ::setRunning, onNavigate = { nav.navigate(it) }, onConfigChange = onConfigChange, + crossTasks = crossTasks, + crossTasksLoaded = crossTasksLoaded, ) } + composable(Routes.TOPICS) { + TopicsScreen(config, crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) } + } + composable(Routes.TASKS) { + CrossTasksScreen(crossTasks, crossTasksLoaded, crossTasksError) { nav.navigate(it) } + } + composable(Routes.CROSS_SOURCES) { + SourcesScreen(config, sourceVersions, onConfigChange, ::toast) + } + composable(Routes.CROSS_FILTERS) { + TopicFiltersScreen(config, onConfigChange, ::toast) + } + composable(Routes.CROSS_AUTOMATION) { + CrossAutomationScreen(config, onConfigChange, { nav.navigate(it) }, ::toast) + } composable(Routes.COLLECT) { CollectScreen( config = config, diff --git a/app/src/main/java/com/haorui/app/ui/screens/HomeScreens.kt b/app/src/main/java/com/haorui/app/ui/screens/HomeScreens.kt index b560ceb..6c446d9 100644 --- a/app/src/main/java/com/haorui/app/ui/screens/HomeScreens.kt +++ b/app/src/main/java/com/haorui/app/ui/screens/HomeScreens.kt @@ -33,6 +33,8 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.haorui.app.data.model.AppConfig import com.haorui.app.data.model.CollectMode +import com.haorui.app.crossplatform.model.CrossPublishTask +import com.haorui.app.crossplatform.ui.CrossWorkspaceOverview import com.haorui.app.ui.components.CheckRow import com.haorui.app.ui.components.NumberField import com.haorui.app.ui.components.DropdownField @@ -69,6 +71,8 @@ fun HomeScreen( onToggleRun: (Boolean) -> Unit, onNavigate: (String) -> Unit, onConfigChange: (AppConfig) -> Unit, + crossTasks: List = emptyList(), + crossTasksLoaded: Boolean = false, ) { Column( modifier = Modifier @@ -78,7 +82,9 @@ fun HomeScreen( verticalArrangement = Arrangement.spacedBy(18.dp), ) { - // ── ① 状态大卡:唯一的启动/停止入口 ────────────── + CrossWorkspaceOverview(config, crossTasks, crossTasksLoaded, onNavigate) + + // 唯一的既有视频启动/停止入口。 RunStatusCard( running = running, config = config, @@ -91,7 +97,7 @@ fun HomeScreen( title = "开始使用前,请先完成这三步", steps = listOf( "在「我的」开启无障碍服务(必需)" to "a11y", - "在「采集」设置采集参数" to "toutiao", + "在「我的」进入既有视频采集设置" to "collect", "在「我的」配置大模型 Key(可选)" to "api", ), onNavigate = onNavigate, @@ -149,8 +155,8 @@ private fun RunStatusCard( } Text( - text = if (running) "正在自动采集并发布内容。可锁屏等待,任务会继续执行。" - else "点击下方按钮启动当日任务。启动前请确认已完成上方三步准备。", + text = if (running) "头条视频任务正在运行,请保持手机解锁与页面可操作。" + else "下方启动的是既有头条视频流程,请先确认采集参数、发布模式与无障碍连接。", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -223,7 +229,7 @@ private fun RunStatusCard( ) PrimaryButton( - label = if (running) "停止任务" else "启动任务", + label = if (running) "停止头条视频任务" else "启动头条视频任务", onClick = { onToggleRun(!running) }, modifier = Modifier.fillMaxWidth(), danger = running, diff --git a/app/src/main/java/com/haorui/app/ui/screens/UtilityScreens.kt b/app/src/main/java/com/haorui/app/ui/screens/UtilityScreens.kt index 8b1da3a..82c0379 100644 --- a/app/src/main/java/com/haorui/app/ui/screens/UtilityScreens.kt +++ b/app/src/main/java/com/haorui/app/ui/screens/UtilityScreens.kt @@ -1,5 +1,7 @@ package com.haorui.app.ui.screens +import com.haorui.app.crossplatform.ui.CrossSettingsEntries + import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -10,6 +12,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -33,6 +36,7 @@ import androidx.compose.material.icons.Icons import com.haorui.app.ui.components.QuickAction import com.haorui.app.ui.components.FieldHelp import com.haorui.app.logging.LogExporter +import kotlinx.coroutines.launch import com.haorui.app.ui.components.GuideBanner import com.haorui.app.ui.components.Section import com.haorui.app.ui.components.NumberField @@ -49,6 +53,7 @@ fun MineScreen( ) { // 去重索引条数:从下载器实时读取,可被「清空」按钮更新 val context = androidx.compose.ui.platform.LocalContext.current + val cacheScope = androidx.compose.runtime.rememberCoroutineScope() var dedupCount by remember { mutableStateOf( com.haorui.app.automation.HaoRuiAccessibilityService.instance?.videoDownloader?.downloadedCount ?: 0 @@ -59,6 +64,8 @@ fun MineScreen( .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(18.dp), ) { + CrossSettingsEntries(onNavigate) + Section( title = "系统设置", help = "影响任务能否正常运行的关键配置", @@ -111,9 +118,10 @@ fun MineScreen( onToast("已清空 $n 条去重记录") }, Modifier.weight(1f), danger = true) HaoRuiButton("清除下载缓存", { - val dl = com.haorui.app.automation.HaoRuiAccessibilityService.instance?.videoDownloader - val n = dl?.clearDownloadCache() ?: 0 - onToast("已删除 $n 个下载缓存文件") + cacheScope.launch { + val result = runCatching { com.haorui.app.automation.HaoRuiAccessibilityService.instance?.clearUnusedDownloadCache() ?: 0 } + onToast(result.fold({ "已删除 $it 个下载缓存文件" }, { "缓存清理未完成,请稍后重试" })) + } }, Modifier.weight(1f), danger = true) } FieldHelp("清空后已发内容可能被重复采集发布,请谨慎操作") @@ -326,6 +334,9 @@ fun A11yScreen(onToast: (String) -> Unit) { // 真实连接状态:来自无障碍服务单例(非写死假值) var connected by remember { mutableStateOf(com.haorui.app.automation.HaoRuiAccessibilityService.isConnected()) } var probeLog by remember { mutableStateOf("尚未运行探测。") } + var accountService by remember { mutableStateOf(com.haorui.app.automation.HaoRuiAccessibilityService.instance) } + val emptyAccountState = remember { kotlinx.coroutines.flow.MutableStateFlow("头条账号尚未核验") } + val accountStatus by (accountService?.accountVerification ?: emptyAccountState).collectAsState() val context = androidx.compose.ui.platform.LocalContext.current val lifecycleOwner = androidx.lifecycle.compose.LocalLifecycleOwner.current @@ -336,6 +347,7 @@ fun A11yScreen(onToast: (String) -> Unit) { val observer = androidx.lifecycle.LifecycleEventObserver { _, event -> if (event == androidx.lifecycle.Lifecycle.Event.ON_RESUME) { connected = com.haorui.app.automation.HaoRuiAccessibilityService.isConnected() + accountService = com.haorui.app.automation.HaoRuiAccessibilityService.instance } } lifecycleOwner.lifecycle.addObserver(observer) @@ -373,6 +385,7 @@ fun A11yScreen(onToast: (String) -> Unit) { // 手动刷新兜底:ON_RESUME 万一未触发时使用 HaoRuiButton("刷新连接状态", { connected = com.haorui.app.automation.HaoRuiAccessibilityService.isConnected() + accountService = com.haorui.app.automation.HaoRuiAccessibilityService.instance onToast(if (connected) "无障碍服务已连接" else "无障碍服务未连接") }, Modifier.weight(1f)) } @@ -380,6 +393,18 @@ fun A11yScreen(onToast: (String) -> Unit) { FieldHelp("开启步骤:点上方按钮 → 找到【浩瑞自动发布】→ 打开开关 → 返回本页") } } + Section(title = "头条账号", help = "停止任务后核验当前登录账号") { + StatusBanner(accountStatus, if (accountStatus.startsWith("已核验")) StatusLevel.OK else StatusLevel.NEUTRAL) + HaoRuiButton("核验头条账号", { + val service = com.haorui.app.automation.HaoRuiAccessibilityService.instance + accountService = service + onToast(when { + service == null -> "请先开启浩瑞无障碍服务" + service.verifyAccountSandbox() -> "正在核验头条账号" + else -> "请先停止当前任务,再核验账号" + }) + }) + } Section(title = "探测工具") { StatusBanner("仅限已核对的今日头条 18.3.0。只保存计数,不调用接口或发布。", StatusLevel.WARN) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { diff --git a/docs/ui-prototype.html b/docs/ui-prototype.html index 27210e9..b1d6745 100644 --- a/docs/ui-prototype.html +++ b/docs/ui-prototype.html @@ -107,7 +107,7 @@ const previewItems=[['home','工作台总览'],['topics','热点与筛选'],['tasks','图文 / 视频任务'],['automation','自动化设置'],['sources','来源 App 管理'],['mine','原有功能与设置']]; const pageInfo={ home:{title:'浩瑞',subtitle:'手机里的创作工作台',note:'一眼掌握今天的工作',desc:'保留唯一启动入口,把运行状态、今日进度和手机来源放到同一页。',points:[['运行与停止','启动、暂停和草稿模式清晰可见。'],['图文和视频共用调度','同一时刻只有一个任务操作手机。'],['原有功能仍可进入','头条视频采集、粉丝互动与日志继续保留。']]}, - topics:{title:'发现热点',subtitle:'筛选社会话题,把热度变成选题',note:'先选对题,再做内容',desc:'来源、时效、内容类型和评分同时可见;不会只按播放量或单一热度决定选题。',points:[['跨来源看候选','知乎、小红书先接入,其余来源按适配状态开放。'],['筛选条件可以检查','发布时间、点赞和粉丝门槛提供独立开关。'],['先检查再加入任务','点击候选可查看选题说明和依据状态。']]}, + topics:{title:'发现热点',subtitle:'按所选分类发现合适的话题',note:'先选对题,再做内容',desc:'来源、时效、内容类型和评分同时可见;不会只按播放量或单一热度决定选题。',points:[['跨来源看候选','知乎、小红书先接入,其余来源按适配状态开放。'],['筛选条件可以检查','发布时间、点赞和粉丝门槛提供独立开关。'],['先检查再加入任务','点击候选可查看选题说明和依据状态。']]}, tasks:{title:'创作任务',subtitle:'从成品准备到发布回执',note:'图文视频,各有进度',desc:'每项任务都能看到内容预览、素材说明与发布状态,结果不明时先核对。',points:[['两种内容,一套队列','图文和视频明确标记,按同一节奏排队。'],['成品预览','点击作品可看文章排版或视频信息。'],['结果不明单独处理','待核对任务保留素材,不提供盲目重发。']]}, automation:{title:'自动化设置',subtitle:'',note:'把运行方式设置明白',desc:'配置一次后按选定方式执行,草稿与正式发布使用同一套筛选和检查。',points:[['模式明确','初次默认草稿模式,正式模式需主动选择。'],['账户总额度共享','原视频与新图文、新视频共用账户总量。'],['分开设置内容上限','图文、视频各自限额,避免新增来源扩大总量。']]}, sources:{title:'来源 App',subtitle:'',note:'手机安装,按能力启用',desc:'展示 App 登录、适配与可用能力;首批连接知乎和小红书。',points:[['来源独立开关','不需要安装或启用本期不用的平台。'],['后续来源明确标记','微博、抖音待适配时不能启用。'],['手机统一切换','不依赖电脑后台,不并发抢占手机屏幕。']]}, @@ -155,7 +155,7 @@ } function topicsPage(){ const filtered=topics.filter(t=>{const m=topicMetrics[t.id];return state.sourceEnabled[t.platform]&&(state.source==='all'||t.platform===state.source)&&(state.kind==='all'||t.kind===state.kind)&&state.selectedCategories.has(t.category)&&m.hours<=state.maxAge&&(!state.likesGate||(m.likes!==null&&m.likes>=state.likes))&&(!state.fansGate||(m.fans!==null&&m.fans<=state.fans))}); - return `
${[['all','全部来源'],['zhihu','知乎'],['xhs','小红书']].map(([id,name])=>``).join('')}
${[['all','全部选题'],['article','图文'],['video','视频']].map(([id,name])=>``).join('')}
示例选题 · ${state.maxAge} 小时内 · 社会方向${icon('sort')}综合优选
${filtered.length?filtered.map(t=>``).join(''):`
${icon('spark')}

这个条件下暂无示例选题
试试切换来源或内容类型

`}`; + return `
${[['all','全部来源'],['zhihu','知乎'],['xhs','小红书']].map(([id,name])=>``).join('')}
${[['all','全部选题'],['article','图文'],['video','视频']].map(([id,name])=>``).join('')}
示例选题 · ${state.maxAge} 小时内 · 所选分类${icon('sort')}综合优选
${filtered.length?filtered.map(t=>``).join(''):`
${icon('spark')}

这个条件下暂无示例选题
试试切换来源或内容类型

`}`; } function jobCard(j){ const pending=state.drafted.has(j.id); @@ -170,16 +170,16 @@ return `
${icon('phone')}

在手机里连接内容来源

仅需安装实际启用的 App,完成登录与授权

首批来源 · 状态为界面示例
${['zhihu','xhs'].map(id=>`
${platformMark(id)}

${platforms[id].name}

${badge('已适配','green')}

${id==='zhihu'?'热榜 · 问题详情 · 分享链接':'高互动笔记 · 图文 / 视频详情'}

${toggle('source:'+id,'启用'+platforms[id].name)}
`).join('')}
后续接入
${['weibo','douyin'].map(id=>`
${platformMark(id)}

${platforms[id].name}

${badge('待适配','gray')}

${id==='weibo'?'实时热搜与社会热点':'热点榜与有许可的视频素材'}

${toggle('source:'+id,'启用'+platforms[id].name,true)}
`).join('')}
采集节奏
${numberRow('每来源采集间隔','按顺序切换 App,不同时操作屏幕','sourceScan','分钟',5,120)}

来源登录失效或需要验证时暂停该来源。版本和能力以真机验收结果为准,本原型中的连接状态仅供预览。

`; } function filtersPage(){ - return `
保留的话题方向
${['民生生活','社会现象','职场','教育'].map(x=>``).join('')}

基础排除

娱乐八卦、广告软文及本期不采集的话题

${badge('始终开启','gray')}
时效 · 硬条件
${numberRow('距离发布时间不超过','发布时间不明的内容直接跳过','maxAge','小时',1,72)}
可选指标门槛
${setting('点赞数限制','启用后,点赞数未知的候选不放行','likesGate')}${numberRow('作品点赞至少','仅使用当前作品的实际点赞','likes','赞',0,10000000,true)}${setting('作者粉丝数限制','启用后,粉丝数未知的候选不放行','fansGate')}${numberRow('作者粉丝不超过','不把作者累计获赞当作粉丝数','fans','人',0,100000000,true)}
优选与去重

综合评分

热度 · 增长 · 新鲜度 · 方向 · 证据

${badge('按来源归一')}

同事件去重

跨平台、图文和视频共用事件记录

72 小时

此处仅修改当前页面的演示设置

`; + return `
保留的话题方向
${['民生生活','社会现象','职场','教育','生活','科技数码','体育','三农','美食','旅游','汽车','文化历史','宠物','家居','健康科普','影视娱乐','游戏','财经'].map(x=>``).join('')}

基础排除

广告软文、未核实内容及本期不采集的话题

${badge('始终开启','gray')}
时效 · 硬条件
${numberRow('距离发布时间不超过','发布时间不明的内容直接跳过','maxAge','小时',1,72)}
可选指标门槛
${setting('点赞数限制','启用后,点赞数未知的候选不放行','likesGate')}${numberRow('作品点赞至少','仅使用当前作品的实际点赞','likes','赞',0,10000000,true)}${setting('作者粉丝数限制','启用后,粉丝数未知的候选不放行','fansGate')}${numberRow('作者粉丝不超过','不把作者累计获赞当作粉丝数','fans','人',0,100000000,true)}
优选与去重

综合评分

热度 · 增长 · 新鲜度 · 方向 · 证据

${badge('按来源归一')}

同事件去重

跨平台、图文和视频共用事件记录

72 小时

此处仅修改当前页面的演示设置

`; } function automationPage(){ - return `
运行模式
${[['draft','草稿模式','完成全流程检查,只保存草稿'],['auto','自动发布','合格任务按节奏自动提交']].map(([id,title,desc])=>``).join('')}

${state.mode==='draft'?'初次使用默认草稿模式。':'已选择自动发布模式。'} 当前是静态原型,切换不会触发真实发布。

跨平台内容类型
${setting('图文文章','事实整理 · 原创分析 · 本地信息卡','article')}${setting('跨平台视频','本人或已获许可的视频素材','video')}
每日额度 · 与原有视频共用账户总量
${numberRow('账户每日提交总上限','原视频 + 新图文 + 新视频','totalCap','篇/条',1,28)}${numberRow('新图文每天最多','受账户总额度和发布时段共同限制','articleCap','篇',0,10)}${numberRow('新视频每天最多','受账户总额度和发布时段共同限制','videoCap','条',0,10)}${numberRow('新链路发布间隔','原头条视频参数保持独立','gap','分钟',60,720)}
发布时段
至
${rowLink('内容来源与适配','sources','layers')}${rowLink('社会选题与指标筛选','filters','filter')}${rowLink('原头条视频采集设置','legacy','video')}

账号、许可与内容校验通过后才进入发布

`; + return `
运行模式
${[['draft','草稿模式','完成全流程检查,只保存草稿'],['auto','自动发布','合格任务按节奏自动提交']].map(([id,title,desc])=>``).join('')}

${state.mode==='draft'?'初次使用默认草稿模式。':'已选择自动发布模式。'} 当前是静态原型,切换不会触发真实发布。

跨平台内容类型
${setting('图文文章','事实整理 · 原创分析 · 本地信息卡','article')}${setting('跨平台视频','本人或已获许可的视频素材','video')}
每日额度 · 与原有视频共用账户总量
${numberRow('账户每日提交总上限','原视频 + 新图文 + 新视频','totalCap','篇/条',1,28)}${numberRow('新图文每天最多','受账户总额度和发布时段共同限制','articleCap','篇',0,10)}${numberRow('新视频每天最多','受账户总额度和发布时段共同限制','videoCap','条',0,10)}${numberRow('新链路发布间隔','原头条视频参数保持独立','gap','分钟',60,720)}
发布时段
至
${rowLink('内容来源与适配','sources','layers')}${rowLink('分类与指标筛选','filters','filter')}${rowLink('原头条视频采集设置','legacy','video')}

账号、许可与内容校验通过后才进入发布

`; } function interactPage(){ return `

今日互动进度

06 / ${state.followCap} 次

与创作任务共享手机操作时机

${icon('heart')}

互动方式

${badge('原有功能','gray')}
${setting('感谢新粉关注','收到新关注后,按设置发送感谢','thanks')}${setting('随机回关','按原有逻辑执行,受每日额度限制','follow')}${numberRow('每日互动上限','原互动额度单独管理','followCap','次',1,200)}
互动节奏

避开编辑与提交

内容编辑、来源采集中不会插入互动

${badge('统一调度','green')}

任务记录

每次互动记录执行结果和暂停原因

`; } function minePage(){ - return `
浩

本机创作工作台

纯手机运行 · 今日头条 18.3.0

${icon('chevron')}

账号健康

100示例信用分

手机服务

已就绪示例状态
跨平台创作
${rowLink('来源 App 管理','sources','layers','2 个启用')}${rowLink('选题筛选','filters','filter','社会方向')}${rowLink('自动化与发布额度','automation','settings',state.mode==='draft'?'草稿模式':'自动发布')}
原有功能
${rowLink('头条视频采集设置','legacy','video')}${rowLink('粉丝互动','interact','heart')}${rowLink('定时浏览','browse','eye')}
服务与记录
${rowLink('解析 / 大模型','api','spark')}${rowLink('无障碍连接','a11y','phone')}${rowLink('运行记录','logs','list','1 项待核对')}
`; + return `
浩

本机创作工作台

纯手机运行 · 今日头条 18.3.0

${icon('chevron')}

账号健康

100示例信用分

手机服务

已就绪示例状态
跨平台创作
${rowLink('来源 App 管理','sources','layers','2 个启用')}${rowLink('选题筛选','filters','filter','所选分类')}${rowLink('自动化与发布额度','automation','settings',state.mode==='draft'?'草稿模式':'自动发布')}
原有功能
${rowLink('头条视频采集设置','legacy','video')}${rowLink('粉丝互动','interact','heart')}${rowLink('定时浏览','browse','eye')}
服务与记录
${rowLink('解析 / 大模型','api','spark')}${rowLink('无障碍连接','a11y','phone')}${rowLink('运行记录','logs','list','1 项待核对')}
`; } function legacyPage(){ return `
保留原头条视频采集流程。该设置与跨平台来源分开保存,共用账户发布总额度。
${setting('启用原视频采集','头条推荐视频 → 筛选 → 下载 → 发布','legacyEnabled')}

点赞 / 粉丝 / 时间限制

沿用已修复的三阶段采集校验

${badge('原有参数','gray')}

候选优选

先收集合格候选,再选择较优视频

5 选 1
后续开发保持的入口

原型只预览入口与信息层级,已有详细采集参数在 Android 开发时继续保留。

`; @@ -208,7 +208,7 @@ if(b.dataset.source){state.source=b.dataset.source;render();return} if(b.dataset.kind){state.kind=b.dataset.kind;render();return} if(b.dataset.mode){state.mode=b.dataset.mode;render(false);toast(state.mode==='auto'?'已切换为自动发布演示,不会触发真实发布':'已切换为草稿模式');return} - if(b.dataset.category){const c=b.dataset.category;if(state.selectedCategories.has(c)){if(state.selectedCategories.size===1){toast('至少保留一个社会话题方向');return}state.selectedCategories.delete(c)}else state.selectedCategories.add(c);render(false);return} + if(b.dataset.category){const c=b.dataset.category;if(state.selectedCategories.has(c)){if(state.selectedCategories.size===1){toast('至少选择一个内容分类');return}state.selectedCategories.delete(c)}else state.selectedCategories.add(c);render(false);return} if(b.dataset.topic){topicSheet(Number(b.dataset.topic));return} if(b.dataset.job){jobSheet(Number(b.dataset.job));return} if(b.dataset.addTopic){addTopic(Number(b.dataset.addTopic));return} diff --git a/docs/回归测试清单.md b/docs/回归测试清单.md index 37acf5d..aad9066 100644 --- a/docs/回归测试清单.md +++ b/docs/回归测试清单.md @@ -1,15 +1,18 @@ # 回归测试与设备准备 -更新:2026-11-13。新功能默认使用预演或草稿验证;实际公开发布仅在明确约定的测试账号与范围内执行。不会因回归结束自动切回正式发布。 +更新:2026-11-14。新功能默认使用预演或草稿验证;实际公开发布仅在明确约定的测试账号与范围内执行。不会因回归结束自动切回正式发布。 ## 已有验证与当前缺口 | 日期或范围 | 结果 | |---|---| | 2026-10-29、10-30 原视频链路 | 留存记录显示真机跑通过采集、解析、下载、草稿/发布与互斥;不等于新功能已验收 | -| 2026-11-13 视频筛选 | 16 项单测全通过,APK 构建成功 | -| 2026-11-13 作者往返与热度优选真机 | 本轮无连接设备,待验收 | -| 纯手机四来源、图文发布、跨平台视频 | 待实现,未执行真实来源或发布测试 | +| 2026-11-14 JVM | 88 项全通过,新增旧提交会话 10 项、账号策略 3 项、剪贴板请求 3 项、独占票据 1 项;原视频筛选 16 项仍通过 | +| 2026-11-14 M1 真机 SQLite | 19 项通过,新增意图/点击许可提交后丢失返回值的真实库取消测试;使用隔离库,未知额度与媒体跨重启保留 | +| 2026-11-13 M1 基础 UI | 五 tab、空任务、18 分类、作品形式独立保存、跨页不覆盖、旋转及进程重启保留配置通过 | +| 2026-11-14 账号核验 UI | 真机两次自身名片解码、返回复查、首页导航、按钮触发及成功状态回读通过;中途停止显示取消并保持浩瑞前台,残留分享弹层后直接重试再次通过。记录 `.tmp/account-ui/` | +| 截至 2026-11-14 作者往返与热度优选真机 | 用户已开启浩瑞无障碍;原视频真实采集、指标、作者往返与草稿整链路本轮仍未执行 | +| 纯手机四来源、图文发布、跨平台视频 | 配置与本地框架已接入,实际采集及新发布器待实现,未执行真实来源或发布测试 | ## 一 设备准备 @@ -77,7 +80,7 @@ powershell -File scripts\regress-stats.ps1 .tmp\regression.txt | 字段缺失 | 原链接、发布时间或关键详情不可确认时补全或跳过,不编造热度和日期 | | 来源切换 | 一次只操作一个 App;切源期间旧看门狗不抢前台;退出可恢复 | | 剪贴板身份 | 旧链接、同名内容、切页和运行代际变化不会串素材 | -| 分类与资格 | 社会类允许项可通过;推广、娱乐、排除题材与缺资质内容拒绝 | +| 分类与资格 | 用户已选分类且满足资质的候选可通过;未选分类、推广、排除题材与缺资质内容拒绝 | | 事实与模型 | 来源矛盾、过期政策、虚构引用、提示词注入、模型结构错误可拦截 | | 图文 | 长正文不截断,段落与图片顺序、封面、声明完整;草稿列表可核对 | | 视频 | 许可和目标平台相符,文件与来源对应,损坏、超限、格式未知、媒体授权失效不放行 | @@ -92,6 +95,10 @@ powershell -File scripts\regress-stats.ps1 .tmp\regression.txt ## 五 记录格式 +本轮记录(2026-11-14):`561baee` 之上的未提交工作树;vivo V1981A / Android 12,头条 18.3.0。应用及测试 APK 已安装;运行隔离库与账号读取验收。用户已手动开启浩瑞无障碍,instrumentation 后仅重绑该已启用服务,原打卡助手服务保持原值。旧视频草稿、新模块关闭,没有启动真实采集、互动或发布,没有执行手动清空缓存/去重。跨日首启曾触发旧信用分检查并读取失败,该旧门控不计为新增健康检查通过。 + +结果:JVM `88 / 0 失败 / 0 错误`,SQLite `19 / 0 失败`。全套构建日志 `.tmp/account-qr-build.log`,最终导航修复、APK 离线构建与 JVM 复查 `.tmp/account-navigation-build.log`,SQLite `.tmp/account-session-sqlite.log`。新增覆盖预占提交后取消、点击许可提交后取消、旧回调不归还后续前台、重复派发只点一次、同名不同账号与不合格 URL 拒绝。最终账号运行日志 `.tmp/budget-evidence/account-final-runtime.log` 记录 09:28:55 停止、09:29:18 重试核验通过;取消及成功回读截图在 `.tmp/account-ui/`,发布计数为 0。前轮基础 UI 在 `.tmp/continuation-ui/`。旧流程指标/作者往返与整机停止、不同账号及页面样本、混合正式发布/M6 强回执和所有新来源端到端仍未验收。 + 仅保留最近一轮有效结果:日期、提交版本/工作树、设备与 App 版本、运行模式、用例结果、日志位置、失败原因及未验收项。历史逐秒日志不追加到文档。 新功能实现后先跑相关单元/契约测试及草稿回归,再做预设故障注入与至少 24 小时调度观察。未执行的项目保持待验收。 diff --git a/docs/开发计划.md b/docs/开发计划.md index b44edf6..f44ffd3 100644 --- a/docs/开发计划.md +++ b/docs/开发计划.md @@ -1,12 +1,12 @@ # 浩瑞开发计划 -更新:2026-11-13。基线:main 的 02824ba 及本轮注释整理。本文维护实施顺序、交付物与验收门槛;详细规则见[纯手机设计](跨平台自动发布设计.md),实际完成情况见[开发进度](开发进度.md)。 +更新:2026-11-14。基线:main 的 561baee;M1 与接续开发仍位于未提交工作树。本文维护实施顺序、交付物与验收门槛;详细规则见[纯手机设计](跨平台自动发布设计.md),实际完成情况见[开发进度](开发进度.md)。 ## 目标与当前起点 -一部安卓手机完成“来源 App 采集 → 社会选题筛选 → 图文生成或视频准备 → 今日头条发布 → 结果核对”。正常合格任务无需逐篇人工干预;登录验证、账号限制和提交结果不明时暂停相关任务或进入核对。电脑仅用于开发、构建和调试。 +一部安卓手机完成“来源 App 采集 → 按用户所选分类筛选 → 图文生成或视频准备 → 今日头条发布 → 结果核对”。内容分类支持多选,不限社会类;图文与视频形式分别开关。正常合格任务无需逐篇人工干预;登录验证、账号限制和提交结果不明时暂停相关任务或进入核对。电脑仅用于开发、构建和调试。 -现有头条视频链路已实现,筛选策略已有 16 项单测,最新指标修复仍需真机回归。静态 UI 已可预览,尚未迁入 Compose。知乎、小红书、微博、抖音采集、文章发布和跨平台视频上下文均待开发。 +现有头条视频链路已实现,筛选策略已有 16 项单测,最新指标修复仍需真机回归。M1 已接入 Compose 工作台、配置、SQLite 任务库、前台票据、持久化启停、共享额度事务、账号读取与旧发布器提交会话代码。88 项 JVM 与 19 项隔离 SQLite 回归通过;真实账号读取、旧流程草稿与前台恢复按回归记录验收,不能认定 M1 整体验收完成。知乎、小红书、微博、抖音采集、文章发布和跨平台视频上下文均待开发。 品牌与界面统一使用“浩瑞”。新增模块独立设计;现有实现的来源复核与必要替换单独记录验收结果,来源事实集中见 [README](../README.md)。 @@ -19,7 +19,7 @@ | M0 基线与来源复核 | 固定既有视频、互动、休息、停止和配置行为;核对模块及依赖来源,列出可保留与需独立实现的部分 | 基线 APK、草稿回归记录、来源与替换清单 | 点赞/粉丝/时间限制、作者往返和发布前复查在真机生效;现有代码来源结论有依据 | | M1 本地框架与界面 | 新增 crossPlatform 配置、任务库、前台协调、共享账户额度;按静态原型实现 Compose 页面 | 默认关闭的新模块,首页/热点/任务/互动/我的及子页面 | 关闭新开关时既有行为不变;旧配置可迁移;同一时刻一个任务操作屏幕,停止后不会自动复活 | | M2 首批来源 | 先知乎,再小红书;分别适配榜单、详情、作者和分享链接,记录包名与已验证版本 | SourceRegistry 与两个来源采集器、页面样本及能力状态 | 每来源覆盖至少 20 条含异常场景的样本;标题、时间、热度口径与链接配对准确,缺值不伪造 | -| M3 社会选题 | 分类排除、时效与可选指标硬门槛、分来源归一排序、热度快照与跨平台事件去重 | TopicPolicy、事件记录、筛选结果及跳过原因 | 娱乐/广告等排除项不放行;启用门槛后指标未知即跳过;增长有两次真实快照;同事件跨体裁不重复发布 | +| M3 分类与选题 | 按所选类别匹配、内容排除、时效与可选指标硬门槛、分来源归一排序、热度快照与事件去重 | TopicPolicy、事件记录、筛选结果及跳过原因 | 未选类别/广告及未核实内容不放行;启用门槛后指标未知即跳过;增长有两次真实快照;同事件跨体裁不重复发布 | | M4 图文闭环 | 事实补全、结构化写作、标题核验、本地信息卡;适配头条文章入口、图文编辑、声明和草稿回读 | EvidenceBuilder、ArticleComposer、ArticlePublishMachine | 来源可回溯,关键事实可定位;长正文、图片、封面和声明可回读;完整保存并核对文章草稿 | | M5 视频闭环 | 素材许可、手机媒体导入/下载、文件校验、简介署名;通过上下文复用现有视频发布器 | SourceMediaProvider、CrossVideoPipeline、VideoTaskBridge | 素材与候选身份匹配;只接收自有或获许可的兼容 MP4;旧调用默认行为不变;完成视频草稿核对 | | M6 自动提交与恢复 | 账号健康检查、额度预占、提交意图、回执及作品管理核对;断网、停止、重启与跨日恢复 | AccountPublishGate、PublishCoordinator、恢复逻辑与运行诊断 | 点击前落库;同次尝试仅点击一次;未知结果保留素材和额度且不盲重发;混合连续运行 4 小时及跨日场景分别通过 | @@ -70,6 +70,6 @@ M4 与 M5 在 M1~M3 通过后可分别推进,最终在 M6 联合验收。微 ## 下一步执行 -1. 完成 M0 的真机基线与来源复核,确认首批来源版本和待替换模块。 -2. 从 M1 的配置默认值、本地任务库和前台协调接口开始,再将静态原型迁入 Compose。 -3. 按表推进,实际完成一项后更新进度,不提前把设计或模拟状态写成已实现。 +1. 补 M0 的旧采集、指标、作者往返与停止恢复草稿回归,记录无障碍启用状态和首批来源版本。 +2. 完成 M1 的不同账号/异常页面、旧流程草稿、在途服务重连与前台切换验收。本轮单账号名片读取、首页导航、中途停止和带残留弹层重试已通过。复用已有账号读取器、LegacyPublishSession 和共享事务,不重复搭计数器;提交前后实际账号、成品关联与强回执由 M6 完成,混合正式入口继续暂停。88 项 JVM、19 项隔离 SQLite 回归不能替代剩余整机验收。 +3. 通过上述门槛后推进 M2 知乎详情、真实时间、原链接及返回路径,再做小红书;来源保持独立能力门控。实际完成情况持续写入开发进度,不提前把设计或模拟状态写成已实现。 diff --git a/docs/开发进度.md b/docs/开发进度.md index e116903..c57bc10 100644 --- a/docs/开发进度.md +++ b/docs/开发进度.md @@ -1,6 +1,6 @@ # 项目状态与开发入口 -更新:2026-11-13。本文件维护当前事实、固定决策与下一步,不再保存调试流水账。代码行为以当前实现为准;功能进展同步更新状态表与最近变更。 +更新:2026-11-14。本轮接入 M1 账号读取器、只读核验入口及旧发布器共享提交会话,88 项 JVM、19 项隔离 SQLite 测试通过。API 30+ 自身名片二维码读取、首页导航、中途停止及残留弹层后的重试已通过真机验证。M1 尚未整体验收,M0 旧流程待回归,M2 目前仅取证;混合正式发布继续等待 M6 的健康与作品回执核对。 ## 文档导航 @@ -18,12 +18,32 @@ | 能力 | 状态与证据 | |---|---| | 原头条视频采集、解析、标题改写、下载和发布 | 已实现;2026-10-29、10-30 有历史真机回归记录 | -| 前台互斥、信用分读取、配额、休息与恢复 | 已接线;现有边界集中列在架构文档 | -| 点赞、作者粉丝、发布时间筛选和候选优选 | 2026-11-13 代码完成,16 项单测及 APK 构建通过;本次改动待真机回归 | +| 既有信用分、配额、休息与恢复 | 原有能力保留;本轮修改了前台入场、停止取消和导航失效检查,尚需整体真机回归 | +| 点赞、作者粉丝、发布时间筛选和候选优选 | 代码及原有 16 项策略单测通过;尚未完成本轮真实采集/发布回归 | | 百度采集 | 有配置和界面,服务未接独立百度采集器,不计为已跑通来源 | -| 知乎、小红书、微博、抖音采集 | 待开发,无已验收的来源 App 选择器 | -| 头条图文与跨平台视频转载 | 纯手机设计已确定,发布和媒体适配待开发 | -| 手机界面预览 | 已生成可离线打开的静态原型,展示热点、任务、筛选、来源及发布设置;不代表 Android 功能已实现 | +| 手机界面 | Compose 已接入首页/热点/任务/互动/我的及来源、筛选、自动化设置;基础五 tab、分类和配置持久化已有真机记录。本轮在无障碍连接页新增“核验头条账号”及真实状态回读;旧功能行为仍需单独回归 | +| 分类与作品形式 | 已实现 18 分类多选,不限社会类;图文/视频分别开关。配置持久化、JSON 与扁平导入导出、边界归一化有单测;新功能默认关闭、DRY_RUN | +| 本地任务库 | SQLite v2 共 10 张表,v1 保留升级;19 项真实 Android SQLite 测试通过。本轮支持调用方在事务前确定尝试 ID,以及仅释放同代际、从未领取点击许可的旧预占 | +| 统一前台协调 | ForegroundCoordinator 已接入旧步骤、信用分及恢复链;加入停止代际、在途票据和手势取消收尾。纯策略测试通过,来源切换及停止的整机行为待验收 | +| 持久化启停 | CrossRunLifecycle 已接入用户启停、模块开关、服务接管/解绑/销毁。停止立即撤回内存许可,事务串行保存;只有最新启动事务完成才公开数据库代际。8 项竞态/故障单测及隔离库接线测试通过;已观察到空闲服务重绑及核验状态失效,旧流程在途重连仍待验收 | +| 共享账户额度 | 共享事务与旧快照已实现;本轮新增 LegacyPublishSession,并接入旧 PublishMachine 的准备、指纹、单次点击、取消与未知回执分支。事务已提交而返回值因取消丢失时,按预生成 ID 定位;库中已领取点击许可的预占不释放。M6 强回执未接通,混合正式入口继续关闭;草稿及无共享历史的旧独立模式保留 | +| 稳定账号读取 | 18.3.0 自身主页、名片及二维码读取代码已实现,唯一数字 user_id 哈希为账户键;两次独立取证并复核自身资料,昵称和分享追踪字段不作为身份。只读核验不绑定预算,不授予后续运行发布许可 | +| 知乎、小红书、微博、抖音采集 | 注册与版本门控已实现,实际采集器尚未实现;知乎/小红书仅取证,所有来源执行能力仍禁用 | +| 头条图文与跨平台视频 | 事实补全、自动文章生成、文章编辑器、媒体许可及新发布上下文尚未实现;AUTO 未开放,没有执行真实跨平台发布 | + +## 本轮验证与交付物 + +- `:app:testDebugUnitTest`:88 项,0 失败、0 错误(原视频 16、配置 11、来源门控 4、任务策略 18、旧额度快照 7、前台票据 8、运行生命周期 8、账号策略 3、剪贴板请求 3、旧提交会话 10)。新增覆盖同名不同身份、迟到 UI 回调、独占入场、事务返回丢失、停止/取消与不重复点击。 +- `:app:assembleDebug` 与 `:app:assembleDebugAndroidTest`:构建成功;全套日志 `.tmp/account-qr-build.log`,最终导航修复和 88 项 JVM 离线复查见 `.tmp/account-navigation-build.log`。新增 ZXing core 3.5.3 从官方 Maven 下载到 D:/env,LICENSE/NOTICE 随 APK 分发;Kotlin 改为 Gradle JVM 内编译,避免独立守护进程回落 C 盘。 +- 应用 APK:`app/build/outputs/apk/debug/app-debug.apk`,2026-11-14 最终导航与二维码版本已覆盖安装,SHA-256 为 `6FDB63295473C130C08ACB950C6C5170C92830C73FC4AD9E93FEAEF5D0AF07FC`;测试 APK 已安装。 +- 真机 SQLite:输出 `SQLite tests: 19, failures: 0`,记录 `.tmp/account-session-sqlite.log`。本轮新增在真实库中模拟预占提交后及点击许可提交后的协程取消:前者按同一 ID 明确释放未点击预占,后者跨重启继续保留 UNKNOWN、额度和素材。使用独立缓存测试库。 +- 前轮基础 UI 验收仍有效,记录在 `.tmp/continuation-ui/`,没有重复执行整套验收。本轮账号链接/名片取证、运行诊断和新增入口结果保存于 `.tmp/budget-evidence/`。 +- 真机已完成两次独立名片解码及返回复查,调试入口与“无障碍连接→核验头条账号”按钮均返回成功,界面回读当前显示名。从头条首页进入自身资料页通过;修复启动后过早判断分享弹层已关闭的问题。最终核验途中于 09:28:55 停止,界面显示“账号核验已取消”,无迟到成功或跳页;从按钮重试后于 09:29:18 再次核验通过。日志 `.tmp/budget-evidence/account-final-runtime.log`,截图 `.tmp/account-ui/account-ui-stopped.png`、`account-ui-retried.png`;当天发布计数仍为 0。 +- `uiautomator dump` 与 instrumentation 可能触发服务重连,临时核验状态会失效;自动化运行中使用文件日志和 `screencap` 观察,避免调试工具自身中断会话。此行为不能当成身份缓存恢复或授权依据。 + +本轮手机:vivo V1981A / Android 12,头条 18.3.0。自身主页复制链接和名片二维码均已留存,观察到 `profile.zjurl.cn/rogue/ugc/profile` 的数字 `user_id`;原始身份及分享追踪值不写入文档和日志。知乎 11.15.0、小红书 9.54.0、抖音 39.8.0,微博未安装;其来源能力与前轮相同,尚未放行。 + +本轮用户已手动开启浩瑞无障碍;原 `com.example.clockin` 服务保留。隔离 instrumentation 结束后系统曾将浩瑞列为断开/崩溃服务,仅重新绑定已启用的浩瑞,并核对原启用列表完整恢复。未代用户登录、修改资料、发送分享、点赞、评论、关注或发布;旧视频保持草稿,新模块关闭。自身资料页及名片仅供只读取证。 ## 固定决策 @@ -34,15 +54,51 @@ 5. 头条锁定 18.3.0;来源 App 各自绑定已验证版本。APK minSdk 为 28,完整截图/OCR 流程要求 API 30+。 6. 不恢复卡密、远程授权或来源不明的中继。来源数据和媒体权限据实判断,正常合格任务全自动;验证、处罚或结果不明时暂停或核对。 7. 视频以自有或获得许可的转载为目标;图文从证据独立生成,不以标题改写替代新增内容。 +8. 内容分类由用户多选,不限社会类;首版 18 项目录,图文/视频形式独立开关,旧配置保留原选中分类。 -## 下一步 +## 下一对话继续入口 -按[开发计划](开发计划.md)的 M0~M7 顺序推进。下一步先完成真机基线和来源复核,再开发本地任务库、前台协调及 Compose 界面。未实现的能力不标为可用。 +1. 工作目录仍为 `D:/headlineScript`,本地 `HEAD` 保持 main 的 `561baee`;M1 首批代码及本次接续修改均未提交。远端 `origin/main` 上轮(11-13)核对为同一提交,本轮未拉取远端。继续前先看 `git log -1`、`git status`,按需核对远端,保留未提交修改,勿 reset、clean 或重复创建已有模块。 +2. 基础 UI 已验收,最新 APK 已装机;记录见本文验证结果与回归清单。后续仅在界面有改动或出现新问题时重做相关场景,不用点击旧视频正式启动来替代 UI 检查。 +3. 补 M0 的旧采集与启停回归,特别是指标限制、作者主页往返、停止时信用分导航/手势收尾及恢复链。本轮跨日首启的旧信用分检查未从浩瑞首页读到分数,后续头条导航失败并按旧规则放行;需补稳定启动入口与导航回归,不把该结果计为新增健康检查通过。单测及数据库测试不能替代上述行为验收。 +4. 继续 M1 的整机兼容回归与不同账号/异常页面验收;本轮已通过单账号读取、首页导航、停止和残留弹层后重试,不必无改动重复这些场景。复用 `account/ToutiaoAccountReader`、`publish/LegacyPublishSession` 和现有事务,勿另建计数器或用昵称/缓存绑定替代现场身份。当前混合正式入口仍关闭;M6 需要接通健康检查、编辑器最终账号/成品关联和明确作品回执,再开放正式路径。旧共享分支不复用分享面板/草稿超时成功判据。 +5. 再推进 M2:优先知乎热榜、具体详情身份/真实发布时间、分享原链接与返回路径,再做小红书。知乎回答时间不能当问题时间;小红书混淆资源 ID 不能直接当稳定选择器。未核验字段保留未知,来源版本/能力未通过不得放行。 +6. 来源稳定后按[开发计划](开发计划.md)推进分类优选、事实补全、图文、视频及新发布协调;整体验收前不开放 AUTO。 + +关键代码相对于 `app/src/main/java/com/haorui/app/`: + +| 位置 | 已有实现 / 接续注意 | +|---|---| +| crossplatform/model/CrossPlatformConfig.kt、data/ConfigRepository.kt | 新配置、18 分类、默认与迁移;旧配置/旧 autoPublish 保持兼容 | +| crossplatform/ui/CrossPlatformScreens.kt、ui/nav/HaoRuiNav.kt | 新 Compose 页面与导航;HomeScreens/UtilityScreens 保留旧入口 | +| crossplatform/model/CrossPublishTask.kt、CrossTaskPolicy.kt | 任务、事件、素材、尝试、额度模型及状态规则;未知时间/无限有效期不能进入发布准备 | +| crossplatform/data/CrossPublishTaskStore.kt | SQLite、Flow、代际、状态、预占/回执事务;切换运行及重启暂停旧任务,READY 和素材写入必须匹配运行代际 | +| crossplatform/data/AccountBudgetTransactions.kt、model/AccountBudget.kt、scheduler/QuotaManager.kt | 旧视频提交日志、共享总量/时段/休息、绝对基线和幂等恢复;`submissionBudget` 从旧配置产生新预算,不能额外增加总额度 | +| crossplatform/account/、crossplatform/publish/ | 自身名片二维码/低版本剪贴板读取、身份策略、旧提交会话及真实库适配器;只读核验不复用为发布授权 | +| crossplatform/schedule/CrossRunLifecycle.kt | 任务库作用域中的串行启停与服务 Session,生产入口通过它调用 `store.beginRun()/pauseRun()`;服务用 `currentCrossRunGeneration()` 取得已落库代际 | +| crossplatform/schedule/ForegroundCoordinator.kt | 票据仅由原持有者释放;停止/停用不提前释放在途操作,调用方必须 finally 收尾 | +| automation/HaoRuiAccessibilityService.kt、scheduler/RecoveryChain.kt、ocr/CreditGateRunner.kt、automation/GestureRunner.kt | 本轮改动的真实接线、停止取消与恢复边界,必须补整机回归 | +| crossplatform/source/SourceRegistry.kt | 四来源包名及版本/能力门控;目前 verifiedVersions、capabilities 均为空,不能仅因已安装就设为可执行 | + +测试位于 `app/src/test/java/com/haorui/app/crossplatform/`、`app/src/androidTest/java/com/haorui/app/crossplatform/`。最终构建与 JVM 日志 `.tmp/account-navigation-build.log`,JVM 结果为 `app/build/test-results/testDebugUnitTest/`,真机库结果为 `.tmp/account-session-sqlite.log`。测试库与正式任务库隔离,不把测试记录导入真实队列。 + +构建命令(PowerShell;有新增代码时再运行,不必因换对话重复所有检查): + +```powershell +. .\scripts\env.ps1 +gradle --offline :app:testDebugUnitTest :app:assembleDebug :app:assembleDebugAndroidTest --console=plain +``` + +若沙盒无法加载 Gradle 原生库或不允许写 D:/env,按环境权限流程申请在沙盒外使用现有工具链;不要把缓存迁到 C 盘。真机测试入口:`adb shell am instrument -w com.haorui.app.test/com.haorui.app.crossplatform.StoreInstrumentation`。先用 `adb devices` 核对当前设备。 ## 最近变更 | 日期 | 事项 | 验证范围 | |---|---|---| +| 2026-11-14 | 接入账号读取、只读入口、旧发布器共享提交会话与取消故障恢复,手动缓存清理保护未知素材;新增本机名片二维码读取 | 88 项 JVM、19 项真机 SQLite 全通过,最终 APK 已安装;实际账号与新增 UI 验收结果见本文,混合正式发布继续等待 M6 | +| 2026-11-13 | M1 共享额度事务、旧额度快照与幂等恢复、v1→v2 保留升级、未知文件保护及混合正式入口暂停保护 | 71 项 JVM、17 项真机 SQLite 全通过,最终应用及测试 APK 已安装;稳定账号核验与旧发布器日志调用仍待接通 | +| 2026-11-13 | 接通服务启停、模块开关与任务库运行代际;旧任务暂停、队列与素材代际检查、服务接管及调度器启停同步 | 59 项 JVM 与 9 项真机 SQLite 测试通过;基础 UI、跨页保存、旋转及进程重启通过;已安装新版 APK,真实服务重连和旧链路仍待验收 | +| 2026-11-13 | M1 首批代码、新 Compose 页面、18 分类与作品形式配置、任务库及前台协调落地,APK 已装机 | 最终构建成功,51 项 JVM 单测与 5 项 Android SQLite 测试通过;UI、旧链路和新来源端到端仍待验收 | | 2026-11-13 | 清理历史对照性注释,统一项目说明并补充分阶段开发计划 | 源码标记及 XML 结构指纹对比、引用检查;不改变运行逻辑 | | 2026-11-13 | 新增纯手机静态 UI 原型,保留原功能入口,展示热点、图文/视频任务与自动化设置 | JavaScript 语法、浏览器图文/视频弹层、示例联合筛选及 360px 窄屏检查;不调用真实平台 | | 2026-11-13 | 用户确定纯手机来源 App 采集;统一图文与视频方案,文档从 8 份整合为 5 份 | 文档、引用及非文档逻辑变更检查;不属于功能验收 | diff --git a/docs/技术架构与代码说明.md b/docs/技术架构与代码说明.md index 858d6df..bf13799 100644 --- a/docs/技术架构与代码说明.md +++ b/docs/技术架构与代码说明.md @@ -1,6 +1,6 @@ # 现有架构与开发约束 -更新:2026-11-13。本文描述当前代码;新增纯手机跨平台方案见[跨平台自动发布设计](跨平台自动发布设计.md)。 +更新:2026-11-14。本文描述当前代码;新增纯手机跨平台方案见[跨平台自动发布设计](跨平台自动发布设计.md)。 ## 工程与运行环境 @@ -25,7 +25,7 @@ APK 安装下限与完整 OCR 能力不同:安装声明为 API 28,依赖截 -> LinkResolver -> AiRewriteService -> VideoDownloader -> PublishMachine -> QuotaManager -> RestBrowseMachine -HaoRuiAccessibilityService 负责初始化、配置注入、命令广播和调度。LaneScheduler 有 12 路协程车道;前台操作通过 FrontStageGuard 判断让路。KeepAliveService 负责前台保活,日志与心跳独立于 UI 执行。 +HaoRuiAccessibilityService 负责初始化、配置注入、命令广播和调度。LaneScheduler 有 12 路协程车道;前台操作通过 FrontStageGuard 判断让路,并由 ForegroundCoordinator 记录在途票据。CrossRunLifecycle 将服务启停接入本地任务库。KeepAliveService 负责前台保活,日志与心跳独立于 UI 执行。 ## 代码定位 @@ -47,6 +47,12 @@ HaoRuiAccessibilityService 负责初始化、配置注入、命令广播和调 | data/model/AppConfig.kt、data/ConfigRepository.kt | 参数、DataStore JSON、迁移与扁平配置导入导出 | | ui/screens/、ui/nav/、overlay/ | 设置页、导航、首页状态及悬浮窗 | | automation/RunLogger.kt、logging/ | 文件日志、诊断导出与独立心跳 | +| crossplatform/data/CrossPublishTaskStore.kt | SQLite 任务、事件、素材、提交意图、额度预占和进程恢复 | +| crossplatform/data/AccountBudgetTransactions.kt、model/AccountBudget.kt | 账户绑定、旧视频提交日志、当日/时段基线、共享休息与幂等结算 | +| crossplatform/account/ | 自身主页核对、两次名片二维码/链接身份比对、独立剪贴板请求与只读核验入口 | +| crossplatform/publish/LegacyPublishSession.kt、StoreLegacyPublishJournal.kt | 旧发布器的共享提交会话、调用方预生成尝试 ID、单次点击与取消收尾 | +| crossplatform/schedule/ForegroundCoordinator.kt、CrossRunLifecycle.kt | 前台票据与持久化运行会话;两者代际独立 | +| crossplatform/model/、source/、ui/ | 18 分类与作品形式配置、来源能力门控、真实本地数据页面 | AndroidManifest.xml 管理组件、权限及包可见性;res/xml/file_paths.xml 管理 FileProvider。新增来源 App 时须补对应包可见性与页面适配,不能只增加一个类目名称。 @@ -72,12 +78,39 @@ AndroidManifest.xml 管理组件、权限及包可见性;res/xml/file_paths.xm - 标题写入后回读;声明与封面按当前配置处理。每次只受理一条任务,忙时保留已准备成品,不能重跑整个下载管线。 - QuotaManager 的非分时段日限额为 min(publishTotal, completionLimit),分时段使用对应配置;两种模式均检查休息。 - 配额快照包含时段计数、剩余休息与最近重置点;启动恢复完成后才武装每日重置,日期使用 todayKey 的同一语义。 -- FrontStageGuard 当前是纯读状态表,不是原子前台所有权锁。跨平台切换须新增统一入场协调,不能只让每个新模块各自检查空闲。 +- FrontStageGuard 是纯读状态表;ForegroundCoordinator 负责原子入场与票据归还。新功能关闭时保留旧步骤的入场方式,启用后每次只允许一个前台操作,来源仅在完整安全边界入场。 - 用户停止应清除启动意愿,恢复链不能复活主动停止的任务;协程取消异常必须重抛。 - 节点等待、网络与 OCR 都要有超时和有限重试。跨线程状态使用合适的同步;节点副本按现有 API 生命周期管理。 - OCR 截图先隐藏悬浮窗,结束后在 finally 恢复。剪贴板读取应保持前台与候选代际匹配。 - 文件日志不可阻塞状态机;诊断优先看应用文件日志与心跳,不仅依赖 logcat。 +## 本地任务运行生命周期 + +- CrossPublishTaskStore 持有进程级 CrossRunLifecycle;每个无障碍服务实例领取独立 Session。只有模块启用且用户已启动任务,数据库启动事务完成后才公开运行代际。重复启动不重复分配代际。 +- 用户停止、模块关闭、服务解绑或销毁立即撤回会话的内存入场许可,启停事务在任务库作用域中按顺序执行,不随服务协程取消。新服务接管后,旧 Session 的迟到操作无效;数据库失败时不给跨平台来源运行许可。 +- 持久化 runGeneration 来自任务库,不能用服务 startGeneration 或前台 Ticket.generation 替代。来源入场需等数据库代际就绪,READY 出队只领取相同代际的任务,素材写入也要求显式传入匹配代际。 +- 运行切换、停止和进程恢复会暂停未提交任务。重新启动不会自动认领旧 READY 或编辑任务;安全阶段显式恢复,EDITING 必须经过页面及成品核对。SUBMIT_INTENT 转为 RESULT_UNKNOWN,素材和额度预占保留,停止后仍可补记已核对的回执。 +- LaneScheduler 的启动、停止和 forceRestart 使用同一同步锁;异步信用分检查完成后,在服务启停锁内再次检查启动代际。真实手势取消、无障碍重连及混合运行仍需整机验收。 + +## 共享账户额度与恢复 + +共享额度持久层、账号读取器与旧发布器的提交会话代码已接入;真实账号读取与旧链路仍按回归记录验收,M1 未整体验收。混合正式入口等待 M6 健康与作品核对,不因只读核验通过而开放。具体约束如下: + +- 任务库 v2 共 10 表;v1 升级保留任务、素材、尝试和额度记录。旧预占缺少时段归属时保守占用当前窗口,不能当作空额度。 +- `QuotaManager.accountSnapshot()` 在旧状态恢复并武装后才可调用,日界沿用 00:00、分时段默认 06:00 或用户自定义时间。时段键为“配额日:时段编号”,保留旧管理器同一配额日内的四段累计语义。 +- `submissionBudget()` 使用旧总上限,新图文/视频各自的限制不增加总额度。快照最多有效 5 秒,跨配额日或当前时段边界提前失效;预占与正式点击前均需新鲜快照,正式点击许可只发放一次。 +- 已核验账户首次绑定导入旧计数及四个时段基线,后续取较大值;切换账号不能静默重绑。`bindLegacyAccount` 的调用方必须现场核验稳定账号身份,库中的绑定只供恢复,不能授权下次提交。 +- 旧视频与新任务在同一写事务内检查总量、时段与休息;新任务另检查类型限制和最小间隔。旧已确认记录只通过绝对基线计数,新任务已确认记录通过额度账本计数,未知预占跨日继续占位。 +- 旧回执事务将绝对基线加一且只执行一次,再由 `mergeSharedLegacyState()` 投影回旧管理器,不能重复 `recordPublish()`。实际提交的 `SubmissionBudgetPeriod` 与核对时刻的当前快照分开,迟到回执不误计到今天。 +- 停止/重启把旧日志 INTENT 转为 UNKNOWN,保留额度和媒体路径;只有明确未提交证据才释放。服务缓存回收排除新旧未知提交及关联素材,读取保护集失败时跳过清理。 +- 服务启动恢复已绑定账户的绝对基线和休息。关闭新模块仍撤销来源运行代际并暂停旧跨平台任务,已有共享历史则继续拦截旧正式入口,不绕过历史预占。混合正式入口在整体验收前暂停;旧草稿保留,新模块关闭且无共享历史时沿用旧模式。 +- `ToutiaoAccountReader` 启动后等待头条实际恢复并清理分享弹层,再定位“我的”页自身“编辑资料”和昵称,避免停止后的残留弹层阻挡重试;底栏文字没有有效边界时使用经过五项排列校验的可点击父节点。API 30+ 两次独立打开自身名片,在核对昵称与卡片文案后,本机截图裁剪 `id/kr` 名片框的下半部二维码区域,排除上方头像,解码后返回自身主页复核。两次数字身份必须相同,截图结束或取消时释放位图。更早系统保留带随机标记和时间戳的前台剪贴板流程,失败不降级到缓存身份。 +- `ToutiaoAccountIdentity` 仅接收已观察到的 `https://profile.zjurl.cn/rogue/ugc/profile` 链接,提取唯一数字 `user_id` 后哈希;昵称和分享追踪字段不生成账户键。二维码解码使用 ZXing core 3.5.3(Apache-2.0),只在手机本机处理像素,不打开链接;许可证与 NOTICE 随 APK assets 分发。只读核验入口位于无障碍连接页,不绑定额度,也不授权以后运行。 +- `AccountClipboardRequests` 独立于旧采集队列,UI 回调按请求对象和所有者配对;失效回调不读取后续数据或归还后续前台。账号核验即使新模块关闭也独占前台,用户停止取消整个读取过程。 +- `LegacyPublishSession` 在 IO 之前生成尝试 ID,预占或点击许可事务提交后即使返回值因取消丢失,仍可找到该尝试。库中 `click_claimed=0` 且运行代际匹配时才能按本地证据释放;已领取许可则保留 UNKNOWN、额度和媒体,不重试点击。 +- `PublishMachine` 的共享分支校验标题和成品指纹,使用单次手势并进入强回执核对边界;不会套用旧的分享面板/草稿超时成功判据。M6 核对器未接通时正式共享分支保持禁用,其会话、事务和取消边界已有故障测试。 +- 手动缓存清理与自动清理均排除当前管线及数据库中待核对的媒体;保护集读取失败则不清理。Kotlin 编译使用 Gradle JVM,避免独立 Kotlin 守护进程把运行文件写到 C 盘。 + ## 后续必须处理的现有边界 | 边界 | 对新增功能的要求 | diff --git a/docs/跨平台自动发布设计.md b/docs/跨平台自动发布设计.md index 784d3d6..fce5e7d 100644 --- a/docs/跨平台自动发布设计.md +++ b/docs/跨平台自动发布设计.md @@ -60,11 +60,13 @@ flowchart TD 详情与分享链接必须匹配当前候选和平台域名;保留访问必需参数,日志隐藏令牌。不能把旧剪贴板、首页推荐或他人累计获赞当作当前作品的数据。 -## 筛选与优选 +## 内容分类与优选 -保留民生、生活服务、社会现象、职场与教育生活话题;公共事件、政策变化另核对原始出处和账号所需资质。排除娱乐绯闻、推广软广、政治军事外交等本期排除内容。分类不确定时跳过,不靠删关键词放行。 +按用户多选的内容分类筛选,不再限定社会类。首版目录包括民生生活、社会现象、职场、教育、生活、科技数码、体育、三农、美食、旅游、汽车、文化历史、宠物、家居、健康科普、影视娱乐、游戏、财经。图文/视频是独立的作品形式开关;扩展目录不自动扩大已有账号的选中分类。 -规则初筛后,模型输出类别、推广判断、依据和所需资质。来源中的指令只作为资料,不能改变系统规则、读取凭据或发起发布。 +分类不确定时跳过;纯广告、来源无法核实的消息以及本期尚未适配的话题不放行。健康科普、财经及公共政策等另核对事实出处、适用范围和账号所需资质,不能用通用改写替代专门核验。 + +规则初筛后,模型输出类别、推广判断、依据和所需资质,再与用户分类选择匹配。来源中的指令只作为资料,不能改变系统规则、读取凭据或发起发布。 先完成分类、时效、身份和资格硬筛选,再排名。初始排序: diff --git a/docs/选择器可用性报告.md b/docs/选择器可用性报告.md index d20500c..5b96394 100644 --- a/docs/选择器可用性报告.md +++ b/docs/选择器可用性报告.md @@ -1,6 +1,6 @@ # 头条选择器与页面适配依据 -更新:2026-11-13。目标锁定今日头条 18.3.0;历史实测设备为 vivo V1981A、Android 12、1080×2408。完整常量以 automation/Targets.kt 为准。 +更新:2026-11-14。目标锁定今日头条 18.3.0;实测设备为 vivo V1981A、Android 12、1080×2408。旧流程常量见 automation/Targets.kt,新增账户读取见 crossplatform/account/。 ## 信息流 详情与作者主页 @@ -62,8 +62,36 @@ Lynx 页面可能持续更新,uiautomator dump 失败不能直接证明页面 ## 新来源适配记录要求 +### 2026-11-14 头条账户页与名片取证 + +在 18.3.0 的“我的”页确认自身“编辑资料”、昵称和分享入口。主页复制链接和名片二维码均指向 `https://profile.zjurl.cn/rogue/ugc/profile`,包含唯一数字 `user_id`;分享链接还带有追踪字段,均不作为身份。原始 ID 和追踪值不写入文档或日志。节点树、名片截图和脱敏诊断位于 `.tmp/budget-evidence/`。 + +| 对象 | 18.3.0 依据与限制 | +|---|---| +| 自身资料 | `id/hno` 描述“编辑资料”,`id/hqt` 昵称;分享入口 `id/hs2`。昵称仅作当前页面比对,不能作为账户键 | +| 首页底栏 | `id/llm` 五项相邻导航,顺序为首页/视频/赚钱/商城/我的;部分文字子节点没有有效边界。文本入口不可用时,仅在五项、位置和整行覆盖均匹配时使用最后一项,结构不符即暂停 | +| 分享横向列表 | `id/onk`,读取“名片分享”/“复制链接”具体项,按已定位控件操作,不点击分享给其他应用的目标 | +| 名片 | `id/kr` 名片框,包含当前昵称及“扫码关注我 获取更多信息”;二维码在框内下半部,排除上方头像二维码干扰 | +| 弹层复查 | 分享/名片打开时,背景仍可能暴露“编辑资料”节点;存在“分享至”弹层时不能认作已返回自身资料页。启动后持续等待头条实际恢复,再清理残留弹层;中途停止后带弹层重试已通过 | +| 剪贴板 | 此机正常前台读取复制结果仍返回空,用户确认未见隐私提示;取证工具读到 URL 不能代表 App 可运行。API 30+ 改为本机截图解码名片二维码;低版本剪贴板分支未做真机验收 | + +上述 `id/` 属于 `com.ss.android.article.news`。账号核验代码要求两次独立名片取证、返回复查与当前运行许可;只读入口不绑定预算,不能以缓存结果授权提交。真实切换账号、不同名片形态仍需补样本;未修改资料、发送分享或发布内容。 + 知乎、小红书、微博、抖音目前没有本工程已验收的选择器。每个平台记录:包名、版本、设备、页面指纹、榜单类型、详情字段、分享出口、媒体获取方式、退出路径及样本日期。 +### 2026-11-13 只读取证(尚未放行执行) + +本轮设备为 vivo V1981A,屏幕可操作;今日头条已安装版本为 18.3.0。下列仅说明实际观察,不代表来源链路已接通。截图和节点树保存在工程 `.tmp/source-evidence/`,不纳入仓库。 + +| 来源 | 安装版本 | 本轮观察与限制 | +|---|---|---| +| 知乎 `com.zhihu.android` | 11.15.0 | 热榜卡片可读 `id/title`、`id/metrics_text`,部分排名有 `id/ranking_no`;缺少可读排名的卡片保留未知。问题详情上部为无子节点 WebView;回答列表的 `id/tvTime` 是回答时间,不能当问题发布时间。分享链未核验,登录状态未知。 | +| 小红书 `com.xingin.xhs` | 9.54.0 | 屏幕可见发现推荐页;留存树捕获到通知开启引导,未授予权限,重复出现 `id/0_resource_name_obfuscated`,不能据此唯一定位。热榜、笔记详情、分享链接和发布时间尚未核验,登录状态未知。 | +| 微博 `com.sina.weibo` | 未安装 | 未安装、未取证。 | +| 抖音 `com.ss.android.ugc.aweme` | 39.8.0 | 仅核对安装版本,未验证页面或登录。 | + +上述 `id/` 前缀分别属于对应来源包名。本轮未执行登录、点赞、评论、关注或发布;来源注册表继续保留未验收状态,不能以“页面可见”替代完整能力验收。 + 必须覆盖缺字段、登录验证、页面改版、相同标题不同内容、迟到剪贴板、返回失败和来源切换。未经验证的包名、ID 与坐标不进入生产配置。 测试步骤统一见[回归测试清单](回归测试清单.md);新结构见[跨平台自动发布设计](跨平台自动发布设计.md)。 diff --git a/gradle.properties b/gradle.properties index 7c148b3..f9e62fd 100644 --- a/gradle.properties +++ b/gradle.properties @@ -14,6 +14,8 @@ org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8 -Djava.io.tmpdir=D:/headlineScri org.gradle.daemon=false org.gradle.caching=false org.gradle.parallel=false +# Kotlin 独立守护进程默认把运行文件写到系统用户目录;在 Gradle JVM 中编译以沿用 D 盘隔离。 +kotlin.compiler.execution.strategy=in-process # 编码 systemProp.file.encoding=UTF-8