Compare commits

...
Author SHA1 Message Date
QiuSW 136765dbb0 docs: record Android last-batch repurchase behavior (#367) 2026-10-08 18:15:53 +08:00
QiuSW 5430dc1f64 feat(android): repurchase last failed batch in place (#367) 2026-10-08 18:12:40 +08:00
QiuSW b5a781b714 fix(android): require server clock for repurchase cutoff (#367) 2026-10-08 17:53:29 +08:00
QiuSW 87192f75d4 feat(android): discover last repurchase batch safely (#367) 2026-10-08 17:49:02 +08:00
QiuSW e450ac2898 merge: purchase failure diagnostics and readiness fixes (#364 #365 #366) 2026-10-08 15:17:34 +08:00
QiuSW 0c24c3897a docs: record private failure diagnostics contracts and operations (#364) 2026-10-08 15:13:36 +08:00
QiuSW 8c4940dc43 merge: integrate purchase diagnostics and readiness fixes (#364 #365 #366) 2026-10-08 15:05:33 +08:00
QiuSW dac66b8384 merge: refresh main before diagnostics integration (#364) 2026-10-08 15:05:33 +08:00
QiuSWandClaude Opus 5.5 5f459329ed merge: require Chinese replies in AGENTS rules
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-08 14:27:40 +08:00
QiuSWandClaude Opus 5.5 2cb8e1ad86 docs: require Chinese replies in AGENTS rules
The user may write in Chinese or English; agents must reply in Chinese
and keep technical English terms, identifiers, commands, paths, API
fields and error codes untranslated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-08 14:27:37 +08:00
QiuSW d2083e71fb test(android): verify address and order observation integration (#365, #366) 2026-10-08 11:49:58 +08:00
QiuSW 5206a6fd7d merge: integrate Android fixes for validation (#365, #366) 2026-10-08 11:48:00 +08:00
QiuSW c55455d35a docs: record bounded post-payment observation (#365) 2026-10-08 11:28:44 +08:00
QiuSW 37714d39b5 fix(android): extend passive order observation after payment back (#365) 2026-10-08 11:20:42 +08:00
QiuSW d1996d28ee docs: document address hint readiness guard (#366) 2026-10-08 11:02:14 +08:00
QiuSW 7fdfe04658 fix(android): reject address editor hint values (#366) 2026-10-08 10:57:38 +08:00
QiuSW 53143131be docs(#366): document initial editor readiness diagnostics 2026-10-08 10:39:51 +08:00
QiuSW 650f3a6ba1 fix(android): wait for unique ready address editor (#366) 2026-10-08 10:34:57 +08:00
21 changed files with 2183 additions and 54 deletions
+1
View File
@@ -44,6 +44,7 @@
- 保留与当前工单无关的工作区改动,不重置、不覆盖、不顺手修改。
- 测试结果必须真实;未执行或无法覆盖的真机、多设备、云环境和高风险行为必须明确记录。
- 高风险修改必须停止并等待人工确认:创建订单、权限、安全、并发、数据库迁移、删除数据、发布和其他不可逆操作。
- 回答语言:用户可以用中文或英文发言,Agent 一律用中文回答;技术英文词组、代码标识符、命令、文件路径、API 字段和错误码保持原文,不翻译。
## 2. 哪些改动需要工单
@@ -248,6 +248,8 @@ class GoAutoAccessibilityService : AccessibilityService(), UiDriver, PddCollecto
checked = node.isChecked,
enabled = node.isEnabled,
visible = node.isVisibleToUser,
hintText = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) node.hintText?.toString() else null,
showingHintText = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) node.isShowingHintText else null,
)
for (index in 0 until node.childCount) {
node.getChild(index)?.let { snapshot(it, "$path/$index", path) }
@@ -27,6 +27,9 @@ data class SnapshotNode(
val checked: Boolean,
val enabled: Boolean,
val visible: Boolean,
// In-memory accessibility metadata; not part of result or diagnostic payloads.
val hintText: String? = null,
val showingHintText: Boolean? = null,
) {
val label: String get() = text?.trim().takeUnless { it.isNullOrEmpty() }
?: contentDescription?.trim().orEmpty()
@@ -42,6 +42,7 @@ class PurchaseLiveAutomation(
private val pause: (Long) -> Unit = Thread::sleep,
/** Boolean/count-only diagnostics; never receives address text. */
private val panelDiagnostic: (String) -> Unit = {},
private val monotonicClockMs: () -> Long = { System.nanoTime() / 1_000_000L },
) {
private var submitAttempted = false
var lastOrderReadFailure: PurchaseOrderReadFailure? = null
@@ -366,48 +367,83 @@ class PurchaseLiveAutomation(
var consecutiveEmptySnapshots = 0
var unpaidStartSample: Int? = null
var unpaidSwipes = 0
repeat(ORDER_RESULT_MAX_SAMPLES + ORDER_RESULT_UNPAID_MAX_SAMPLES) { index ->
var paymentBackSucceededAt: Long? = null
var orderContextObserved = false
// Extra observations cannot reopen navigation/scroll budgets. Late unpaid evidence
// still receives its existing independent budget below.
var passiveExtension = false
fun observationRemainingMs(): Long? {
val startedAt = paymentBackSucceededAt ?: return null
if (unpaidStartSample != null || (orderContextObserved && !passiveExtension)) return null
return ORDER_RESULT_POST_PAYMENT_OBSERVATION_MS - (monotonicClockMs() - startedAt)
}
fun observePause(durationMs: Long) {
val remaining = observationRemainingMs()
val duration = if (remaining == null) durationMs else minOf(durationMs, remaining.coerceAtLeast(0))
if (duration > 0) pause(duration)
}
var nextSample = 0
while (true) {
val index = nextSample++
// The first unpaid page receives its own bounded budget, even after a long handoff.
// Never reset it on repeated labels or navigation back to payment.
val unpaidStart = unpaidStartSample
if ((unpaidStart == null && index >= ORDER_RESULT_MAX_SAMPLES) ||
if (unpaidStart == null && index >= ORDER_RESULT_MAX_SAMPLES &&
paymentBackSucceededAt != null && !orderContextObserved) {
passiveExtension = true
}
if ((observationRemainingMs()?.let { it <= 0 } == true) ||
(unpaidStart == null && index >= ORDER_RESULT_MAX_SAMPLES && !passiveExtension) ||
(unpaidStart != null && index - unpaidStart >= ORDER_RESULT_UNPAID_MAX_SAMPLES)) {
val failure = orderEvidenceFailure(labels)
return unknown(failure.code, failure.message)
}
val snapshot = driver.capture()
// A blocking capture can finish after the deadline. Do not act on or accept that frame.
if (observationRemainingMs()?.let { it <= 0 } == true) {
val failure = orderEvidenceFailure(labels)
return unknown(failure.code, failure.message)
}
if (snapshot.packageName.isNullOrBlank()) {
consecutiveEmptySnapshots++
if (consecutiveEmptySnapshots >= ORDER_RESULT_MAX_EMPTY_SAMPLES) {
return unknown("PURCHASE_ORDER_EMPTY_TIMEOUT", "等待订单页面时无障碍窗口持续为空")
}
pause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
return@repeat
observePause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
continue
}
consecutiveEmptySnapshots = 0
val currentLabels = snapshot.nodes.filter { it.visible }.map { it.label }
if (isKnownAndroidWechatChooser(snapshot, currentLabels)) {
if (passiveExtension && !backedOutOfChooser) {
val failure = orderEvidenceFailure(labels)
return unknown(failure.code, failure.message)
}
if (backedOutOfChooser || !driver.backPurchase()) {
return unknown("PURCHASE_ORDER_CHOOSER_BACK_FAILED", "系统应用选择页无法安全返回")
}
backedOutOfChooser = true
pause(500)
return@repeat
observePause(500)
continue
}
if (snapshot.packageName == WECHAT_PACKAGE) {
if (!restoredFromWechat) {
if (passiveExtension) {
val failure = orderEvidenceFailure(labels)
return unknown(failure.code, failure.message)
}
if (!driver.bringPddToForeground()) {
return unknown("PURCHASE_ORDER_WECHAT_RESTORE_FAILED", "从微信恢复拼多多的请求失败")
}
restoredFromWechat = true
pause(500)
return@repeat
observePause(500)
continue
}
if (pddObservedAfterWechatRestore || ++wechatRestorePendingSamples >= ORDER_RESULT_WECHAT_RESTORE_MAX_SAMPLES) {
return unknown("PURCHASE_ORDER_WECHAT_RESTORE_TIMEOUT", "从微信恢复拼多多后未在限定时间到达订单页面")
}
pause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
return@repeat
observePause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
continue
}
if (snapshot.packageName != PDD_PACKAGE) {
return unknown("PURCHASE_ORDER_UNEXPECTED_APP", "核单期间出现未授权应用")
@@ -426,7 +462,8 @@ class PurchaseLiveAutomation(
if (!driver.backPurchase()) {
return unknown("PURCHASE_ORDER_PAYMENT_BACK_FAILED", "支付页无法安全返回订单详情")
}
pause(500)
paymentBackSucceededAt = monotonicClockMs()
observePause(500)
} else {
consecutivePaymentSamplesAfterBack++
if (consecutivePaymentSamplesAfterBack >= ORDER_RESULT_PAYMENT_POST_BACK_MAX_SAMPLES) {
@@ -437,20 +474,21 @@ class PurchaseLiveAutomation(
"consecutivePaymentSamplesAfterBack=$consecutivePaymentSamplesAfterBack]",
)
}
pause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
observePause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
}
return@repeat
continue
}
consecutivePaymentSamplesAfterBack = 0
if (orderContextVisible) orderContextObserved = true
if (unpaidContextVisible) {
paymentPageObserved = true
if (unpaidStartSample == null) unpaidStartSample = index
}
if (!orderContextVisible && !unpaidContextVisible) {
if (unpaidStartSample != null) {
// After reaching the unpaid page only observe; never click a newly exposed control.
pause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
return@repeat
if (unpaidStartSample != null || passiveExtension) {
// Neither unpaid reading nor the added observation budget permits a new click.
observePause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
continue
}
val entries = orderDetailEntryTargets(snapshot)
if (entries.size > 1) {
@@ -466,27 +504,25 @@ class PurchaseLiveAutomation(
else -> return unknown("PURCHASE_ORDER_DETAIL_ENTRY_FAILED", "订单详情入口点击失败,已停止只读核单")
}
orderDetailEntryOpened = true
pause(500)
return@repeat
observePause(500)
continue
}
pause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
return@repeat
observePause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
continue
}
currentLabels.forEach(labels::add)
parseOrderEvidence(labels)?.let { return it }
if (unpaidStartSample != null && unpaidSwipes < ORDER_RESULT_UNPAID_MAX_SWIPES) {
unpaidSwipes++
driver.swipePurchase(SwipeDirection.UP, 400)
pause(ORDER_RESULT_UNPAID_SETTLE_MS)
return@repeat
observePause(ORDER_RESULT_UNPAID_SETTLE_MS)
continue
}
if (unpaidStartSample == null && index > 0 && index % ORDER_RESULT_SCROLL_SAMPLE_INTERVAL == 0) {
if (!passiveExtension && unpaidStartSample == null && index > 0 && index % ORDER_RESULT_SCROLL_SAMPLE_INTERVAL == 0) {
driver.swipePurchase(SwipeDirection.UP, 400)
}
pause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
observePause(ORDER_RESULT_SAMPLE_INTERVAL_MS)
}
val failure = orderEvidenceFailure(labels)
return unknown(failure.code, failure.message)
}
// orderEvidenceFailure 之外的路径(选择器卡住、微信恢复超时等)同样要带上
@@ -509,16 +545,12 @@ class PurchaseLiveAutomation(
val modify = addressModifyTargets(panel)
if (modify.size != 1) fail("PURCHASE_ADDRESS_EDIT_AMBIGUOUS", "没有找到唯一的地址修改按钮,未创建订单")
click(modify.single(), "修改地址")
val edit = waitFor("PURCHASE_ADDRESS_EDIT_TIMEOUT", "地址编辑页面打开超时,未创建订单") { snapshot ->
snapshot.nodes.any { it.visible && it.label.replace(" ", "").contains("详细地址") }
}
val editors = shippingAddressEditors(edit)
if (editors.size != 1) fail("PURCHASE_ADDRESS_UPDATE_FAILED", "没有找到唯一的详细地址输入框,未创建订单")
val current = editors.single().label.trim()
val editor = waitForInitialAddressEditor()
val current = editor.text.orEmpty().trim()
val body = current.split(Regex("[-_]"), limit = 2).firstOrNull()?.trim().orEmpty()
if (body.isBlank()) fail("PURCHASE_ADDRESS_UPDATE_FAILED", "当前详细地址无效,未创建订单")
val expected = body + suffix
if (driver.inputFresh(editors.single(), expected) != FreshActionResult.SUCCESS) fail("PURCHASE_ADDRESS_UPDATE_FAILED", "详细地址修改失败,未创建订单")
if (driver.inputFresh(editor, expected) != FreshActionResult.SUCCESS) fail("PURCHASE_ADDRESS_UPDATE_FAILED", "详细地址修改失败,未创建订单")
val stable = waitFor("PURCHASE_ADDRESS_INPUT_MISMATCH", "详细地址修改后回读不一致,未创建订单") { snapshot ->
snapshot.nodes.count { it.visible && it.enabled && it.className?.endsWith("EditText") == true && it.label == expected } == 1
}
@@ -539,6 +571,47 @@ class PurchaseLiveAutomation(
return ShippingAddressProof(expected, suffix)
}
/** Initial readiness only; return the same sampled node for the original value and fresh input anchor. */
private fun waitForInitialAddressEditor(): SnapshotNode {
fun isHint(editor: SnapshotNode): Boolean {
val hint = editor.hintText?.trim().orEmpty()
return editor.showingHintText == true || (hint.isNotEmpty() && editor.text?.trim() == hint)
}
var titleSeen = false
var structural = emptyList<SnapshotNode>()
var readyCount = 0
repeat(50) {
val snapshot = driver.capture()
pageProblem(snapshot)
val labels = snapshot.nodes.filter { it.visible && it.label.replace(" ", "").contains("详细地址") }
titleSeen = titleSeen || labels.isNotEmpty()
// Keep the existing same-row/rightward region, but count empty and disabled inputs too.
// Their presence is structural ambiguity, even when just one input is ready.
structural = snapshot.nodes.filter { editor ->
editor.visible && editor.className?.endsWith("EditText") == true &&
labels.any { label ->
editor.bounds.top <= label.bounds.bottom &&
editor.bounds.bottom >= label.bounds.top &&
editor.bounds.left >= label.bounds.left
}
}.distinctBy { it.path }
readyCount = structural.count { it.enabled && !it.text.isNullOrBlank() && !isHint(it) }
if (structural.size == 1 && readyCount == 1) return structural.single()
pause(200)
}
val reason = when {
!titleSeen -> "title_missing"
structural.isEmpty() -> "editor_missing"
structural.size > 1 -> "editor_ambiguous"
!structural.single().enabled -> "editor_disabled"
structural.single().text.isNullOrBlank() -> "editor_empty"
else -> "editor_hint"
}
val diagnostic = "stage=address_editor_ready;reason=$reason;titleSeen=$titleSeen;structural=${structural.size};ready=$readyCount"
if (!titleSeen) fail("PURCHASE_ADDRESS_EDIT_TIMEOUT", "地址编辑页面打开超时,未创建订单 [$diagnostic]")
fail("PURCHASE_ADDRESS_UPDATE_FAILED", "详细地址输入框未就绪,未创建订单 [$diagnostic]")
}
private fun isPurchaseConfirmationPanel(snapshot: UiSnapshot): Boolean {
if (snapshot.packageName != PDD_PACKAGE || shippingAddressEditors(snapshot).isNotEmpty()) return false
val screen = PddScreenParser.parse(snapshot, PurchaseRehearsalExecutor.DEFAULT_COLLECTOR, "", null)
@@ -1038,6 +1111,7 @@ class PurchaseLiveAutomation(
val ANDROID_CHOOSER_TITLES = setOf("选择要使用的应用", "使用以下应用打开", "完成操作时使用")
val PDD_PAYMENT_ACTIVITIES = setOf("com.xunmeng.pinduoduo.app_pay.core.PayActivity")
const val ORDER_RESULT_MAX_SAMPLES = 60
const val ORDER_RESULT_POST_PAYMENT_OBSERVATION_MS = 30_000L
const val ORDER_RESULT_MAX_EMPTY_SAMPLES = 15
const val ORDER_RESULT_WECHAT_RESTORE_MAX_SAMPLES = 15
const val ORDER_RESULT_PAYMENT_POST_BACK_MAX_SAMPLES = 25
@@ -100,6 +100,7 @@ data class PurchaseAgentTask(
val ruleSnapshot: String,
val ruleSnapshotHash: String,
val leaseVersion: Long,
val attemptNumber: Int = 0,
)
data class CollectionHistoryItem(
@@ -211,6 +212,8 @@ class AgentApiException(
) : Exception(message)
class AgentApiClient(private val serverUrl: String) {
@Volatile var lastResponseServerTimeMillis: Long? = null
private set
val failureSnapshotOrigin: String get() = ServerUrlPolicy.normalize(serverUrl)
/** Stream the two bounded parts; never build another combined copy of the archive. */
fun uploadFailureSnapshot(snapshot: cn.ilapage.goauto.agent.diagnostics.FailureSnapshot, token: String) {
@@ -666,6 +669,7 @@ class AgentApiClient(private val serverUrl: String) {
private fun purchaseTask(data: JSONObject) = PurchaseAgentTask(
taskId = data.getLong("taskId"),
taskAttemptId = data.optString("taskAttemptId"),
attemptNumber = data.optInt("attemptNumber"),
phase = data.optString("phase"),
executionMode = data.getString("executionMode"),
status = data.getString("status"),
@@ -709,6 +713,9 @@ class AgentApiClient(private val serverUrl: String) {
connection.outputStream.use { it.write(payload.toString().toByteArray(Charsets.UTF_8)) }
}
val status = connection.responseCode
// Metadata only: batch cutoff must use the API clock, never the phone's clock.
// A missing Date invalidates the sample instead of retaining an older response.
lastResponseServerTimeMillis = connection.getHeaderFieldDate("Date", 0L).takeIf { it > 0L }
if (status == HttpURLConnection.HTTP_NO_CONTENT) return null
val stream = if (status in 200..299) connection.inputStream else connection.errorStream
val body = stream?.bufferedReader(Charsets.UTF_8)?.use { it.readText() }.orEmpty()
@@ -85,6 +85,11 @@ class AgentForegroundService : Service() {
private val taskExecutor: ExecutorService = Executors.newSingleThreadExecutor()
private val diagnosticExecutor: ExecutorService = Executors.newSingleThreadExecutor()
private val snapshotUploadExecutor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
private val repurchaseExecutor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
private val repurchaseClosed = AtomicBoolean(false)
private val repurchase = RepurchaseCoordinator(SystemClock::elapsedRealtime, { UUID.randomUUID().toString() }, ::publishRepurchase)
private var repurchaseSession: RepurchaseSession? = null
private val repurchaseEvidence = java.util.concurrent.ConcurrentHashMap<Long, java.util.concurrent.ConcurrentHashMap<Long, RepurchaseExecutionEvidence>>()
private val taskMutex = TaskExecutionMutex()
private val backfillGuard = OrderBackfillGuard(taskMutex)
private val runningTaskId = AtomicReference<Long?>(null)
@@ -119,6 +124,7 @@ class AgentForegroundService : Service() {
identityStore = SecureDeviceStore(this)
settingsStore = AgentSettingsStore(this)
stateStore = AgentStateStore(this)
repurchaseState = RepurchaseState()
// Wake locks and cooldown tickets are process-local. Never restore a stale UI flag.
stateStore.setKeepScreenOn(false)
purchaseStore = PurchaseTaskStore(this)
@@ -145,9 +151,29 @@ class AgentForegroundService : Service() {
executor.scheduleWithFixedDelay(::triggerSync, 0, HEARTBEAT_SECONDS, TimeUnit.SECONDS)
// Independent retention/upload ticks run even when no further task is dispatched.
snapshotUploadExecutor.scheduleWithFixedDelay(::maintainFailureSnapshots, 0, 60, TimeUnit.SECONDS)
// Separate, serialized I/O ticks keep history reads and result observation off the
// heartbeat scheduler and, especially, off the single purchase execution thread.
repurchaseExecutor.scheduleWithFixedDelay(::tickRepurchase, 2, 2, TimeUnit.SECONDS)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_REPURCHASE_PREPARE -> {
repurchaseExecutor.execute(::prepareRepurchase)
return START_STICKY
}
ACTION_REPURCHASE_CONFIRM -> {
val roundId = intent.getStringExtra("roundId").orEmpty()
repurchaseExecutor.execute { repurchase.confirm(roundId); tickRepurchase() }
return START_STICKY
}
ACTION_REPURCHASE_STOP -> {
// Atomic: a network request must not delay the user's stop signal.
repurchase.requestStop(intent.getStringExtra("roundId").orEmpty())
repurchaseExecutor.execute(::tickRepurchase)
return START_STICKY
}
}
if (intent?.action == ACTION_BACKFILL_STOP) {
backfillGuard.cancelled.set(true)
return START_STICKY
@@ -171,6 +197,10 @@ class AgentForegroundService : Service() {
}
override fun onDestroy() {
repurchaseClosed.set(true)
repurchase.requestStop(repurchase.state.roundId)
repurchaseExecutor.shutdownNow()
repurchaseState = RepurchaseState(message = "服务已停止;不会恢复整轮重购")
backfillGuard.cancelled.set(true)
runCatching { connectivityManager.unregisterNetworkCallback(networkCallback) }
cancelIdleReturn("服务已停止")
@@ -333,6 +363,110 @@ class AgentForegroundService : Service() {
})
}
private data class RepurchaseSession(val origin: String, val deviceId: Long, val token: String)
private fun publishRepurchase(state: RepurchaseState) {
if (repurchaseClosed.get()) return
repurchaseState = state
sendBroadcast(Intent(ACTION_REPURCHASE_STATE).setPackage(packageName))
updateNotification(state.message, force = true)
}
private fun repurchaseLocalIdle(): Boolean = !working.get() && taskMutex.currentTaskId() == null &&
purchaseStore.activeTaskId() == null && purchaseStore.pendingOutbox().isEmpty() &&
stateStore.read().currentTaskId == null && !backfillState.running
private fun repurchaseEnvironment(session: RepurchaseSession): String? {
if (repurchaseClosed.get()) return "服务已经停止"
val credentials = identityStore.credentials()
if (credentials?.deviceId != session.deviceId || credentials.token != session.token ||
ServerUrlPolicy.normalize(settingsStore.serverUrl()) != session.origin) return "设备身份或服务器配置已变化,请重新连接"
if (!registeredThisProcess.get()) return "设备尚未完成连接校验,请先测试连接"
if (GoAutoAccessibilityService.instance == null) return "请先开启无障碍服务"
val network = connectivityManager.activeNetwork ?: return "网络不可用"
if (connectivityManager.getNetworkCapabilities(network)?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) != true) return "网络不可用"
return null
}
private fun prepareRepurchase() {
if (repurchaseClosed.get() || !repurchase.prepare()) return
repurchaseEvidence.clear()
try {
val credentials = identityStore.credentials() ?: error("missing credentials")
val session = RepurchaseSession(ServerUrlPolicy.normalize(settingsStore.serverUrl()), credentials.deviceId, credentials.token)
repurchaseSession = session
repurchaseEnvironment(session)?.let { repurchase.fail(it); return }
val port = repurchasePort(session)
if (!repurchaseLocalIdle() || port.hasOtherWork(null)) {
repurchase.fail("设备已有未结束工作或结果上传尚未收尾,请完成后再重购")
return
}
// Discovery owns its client. No other request can overwrite its page's Date sample.
val api = AgentApiClient(session.origin)
val batch = RepurchaseBatchDiscovery({ query ->
check(!repurchase.isStopRequested() && !repurchaseClosed.get())
check(repurchaseEnvironment(session) == null)
api.purchaseHistory(session.token, query.page, query.status, query.taskNo, query.days, query.pageSize)
}, { requireNotNull(api.lastResponseServerTimeMillis) }).discover()
repurchaseEnvironment(session)?.let { repurchase.fail(it); return }
if (!repurchaseLocalIdle() || port.hasOtherWork(null)) {
repurchase.fail("读取期间出现新的采集或采购工作,请完成后重新读取")
return
}
repurchase.prepared(batch)
} catch (error: RepurchaseBatchException) {
repurchase.fail(if (repurchase.isStopRequested()) "已停止读取,没有发起重购" else when (error.reason) {
RepurchaseBatchFailure.LIST_CHANGED -> "采购列表已变化,请重新读取"
RepurchaseBatchFailure.PAGE_FAILED -> "读取采购记录失败,请检查连接后重试"
else -> "无法完整确定最后一批采购记录,请检查时间或记录后重试(${error.reason})"
})
} catch (_: Exception) {
repurchase.fail("设备连接或记录读取失败,请恢复后重试")
}
}
private fun tickRepurchase() {
if (repurchaseClosed.get() || !repurchase.state.busy) return
val session = repurchaseSession ?: return
val previousTaskId = repurchase.state.currentTaskId
repurchase.tick(repurchasePort(session))
// Reset only makes the original task pending. The original dispatcher owns all
// claim/start/automation/upload steps; the round never executes a PDD action.
if (repurchase.state.currentTaskId != null && repurchase.state.currentTaskId != previousTaskId) triggerSync()
}
private fun repurchasePort(session: RepurchaseSession): RepurchasePort = object : RepurchasePort {
private val api = AgentApiClient(session.origin)
override fun environmentProblem() = repurchaseEnvironment(session)
override fun localIdle() = repurchaseLocalIdle()
override fun latestTaskId() = api.purchaseHistory(session.token, 1, null, null, 30, 1).items.firstOrNull()?.taskId
override fun detail(taskId: Long) = api.purchaseHistoryDetail(taskId, session.token)
override fun executionEvidence(taskId: Long) = repurchaseEvidence[taskId]?.values?.toList().orEmpty()
override fun hasOtherWork(currentTaskId: Long?): Boolean {
if (api.nextTask(session.token) != null) return true // collection IDs are a separate namespace
val next = api.nextPurchaseTask(session.token)
if (next != null && next.taskId != currentTaskId) return true
// /next returns the current running/probing purchase first and can conceal new pending work.
return listOf("pending", "running", "spec_probe_pending", "order_submit_started").any { status ->
val page = api.purchaseHistory(session.token, 1, status, null, 30, 50)
page.items.any { it.taskId != currentTaskId } || page.total > page.items.size
}
}
override fun reset(taskId: Long, requestId: String): cn.ilapage.goauto.agent.network.PurchaseResetResult {
val acquired = synchronized(taskMutex) {
!working.get() && taskMutex.tryAcquire(REPURCHASE_RESERVATION_ID)
}
if (!acquired) throw RepurchaseLocalBusy()
try {
if (environmentProblem() != null || repurchase.isStopRequested() || repurchaseClosed.get() ||
purchaseStore.activeTaskId() != null || purchaseStore.pendingOutbox().isNotEmpty()) {
throw AgentApiException(409, "DEVICE_BUSY", "本地工作边界变化", false)
}
return api.resetPurchaseTask(taskId, requestId, session.token)
} finally { taskMutex.release(REPURCHASE_RESERVATION_ID) }
}
}
private fun publishBackfill(state: OrderBackfillState) {
backfillState = state
sendBroadcast(Intent(ACTION_BACKFILL_STATE).setPackage(packageName))
@@ -607,6 +741,7 @@ class AgentForegroundService : Service() {
api.startPurchaseTask(claimed.taskId, UUID.randomUUID().toString(), token)
} else claimed
check(task.status == "running" && task.taskAttemptId.isNotBlank()) { "采购任务没有有效 attempt" }
recordRepurchaseExecution(task, null)
val diagnosticDeviceId = runCatching { identityStore.credentials()?.takeIf { it.token == token }?.deviceId }.getOrNull()
if (task.taskAttemptId.matches(Regex("[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}")) &&
(diagnosticDeviceId ?: 0) > 0 && task.phase in setOf("spec_probe", "purchase")) {
@@ -697,6 +832,7 @@ class AgentForegroundService : Service() {
// #334: a spec probe that read zero colors/sizes must fail explicitly
// instead of being reported as a normal, empty spec_probe_completed.
val outcome = PurchaseSpecProbePolicy.demote(rawOutcome)
recordRepurchaseExecution(task, outcome.resultType)
knownResultType = outcome.resultType
// The live read finishes before persistence, the new failure bubble, return to Agent, or lease release.
if (FailureSnapshotPolicy.eligible(task.phase, outcome.resultType, false)) failureSnapshot(outcome.resultType, outcome.errorCode ?: "PURCHASE_EXECUTION_FAILED")
@@ -730,6 +866,12 @@ class AgentForegroundService : Service() {
}
}
private fun recordRepurchaseExecution(task: PurchaseAgentTask, resultType: String?) {
if (!repurchaseState.busy || repurchaseState.currentTaskId != task.taskId || task.attemptNumber <= 0) return
val taskEvidence = repurchaseEvidence.getOrPut(task.taskId) { java.util.concurrent.ConcurrentHashMap() }
taskEvidence[task.attemptNumber.toLong()] = RepurchaseExecutionEvidence(task.attemptNumber.toLong(), task.taskAttemptId, task.phase, resultType)
}
private fun collectPurchaseProbe(
accessibility: GoAutoAccessibilityService, task: PurchaseAgentTask, purchaseRule: PurchaseRule,
diagnostic: (AgentDiagnosticEvent) -> Unit,
@@ -1239,6 +1381,7 @@ class AgentForegroundService : Service() {
}
private fun evaluateIdleReturn() {
if (repurchaseState.phase == RepurchasePhase.RUNNING) return
if (!idleReturn.isArmed()) return
val accessibility = GoAutoAccessibilityService.instance
if (accessibility == null) {
@@ -1383,10 +1526,20 @@ class AgentForegroundService : Service() {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
builder.addAction(Notification.Action.Builder(null, "停止回填", stop).build())
}
if (repurchaseState.busy) {
val stop = PendingIntent.getService(this, 367,
Intent(this, AgentForegroundService::class.java).setAction(ACTION_REPURCHASE_STOP).putExtra("roundId", repurchaseState.roundId),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
builder.addAction(Notification.Action.Builder(null, "停止重购", stop).build())
}
return builder
.setSmallIcon(android.R.drawable.stat_notify_sync)
.setContentTitle(getString(R.string.app_name))
.setContentText(if (backfillState.running) "订单回填 · 已检查 ${backfillState.checked}" else content)
.setContentText(when {
repurchaseState.busy -> "重购 ${repurchaseState.currentTaskId?.let { "CG-$it" }.orEmpty()} · 成功${repurchaseState.successCount} 失败${repurchaseState.failedCount} 跳过${repurchaseState.skippedCount}"
backfillState.running -> "订单回填 · 已检查 ${backfillState.checked}"
else -> content
})
.setContentIntent(pendingIntent)
.setOngoing(true)
.build()
@@ -1433,6 +1586,12 @@ class AgentForegroundService : Service() {
}
companion object {
const val ACTION_REPURCHASE_PREPARE = "cn.ilapage.goauto.agent.REPURCHASE_PREPARE"
const val ACTION_REPURCHASE_CONFIRM = "cn.ilapage.goauto.agent.REPURCHASE_CONFIRM"
const val ACTION_REPURCHASE_STOP = "cn.ilapage.goauto.agent.REPURCHASE_STOP"
const val ACTION_REPURCHASE_STATE = "cn.ilapage.goauto.agent.REPURCHASE_STATE"
@Volatile var repurchaseState = RepurchaseState()
private set
const val ACTION_BACKFILL_START = "cn.ilapage.goauto.agent.BACKFILL_START"
const val ACTION_BACKFILL_STOP = "cn.ilapage.goauto.agent.BACKFILL_STOP"
const val ACTION_BACKFILL_STATE = "cn.ilapage.goauto.agent.BACKFILL_STATE"
@@ -1468,6 +1627,7 @@ class AgentForegroundService : Service() {
private const val COOLDOWN_WAKE_GRACE_MILLIS = 5_000L
private const val RETURN_CONFIRM_DELAY_MILLIS = 750L
private const val CURRENT_PAGE_RESERVATION_ID = Long.MAX_VALUE
private const val REPURCHASE_RESERVATION_ID = Long.MAX_VALUE - 1
private const val PDD_PACKAGE = "com.xunmeng.pinduoduo"
private const val CURRENT_PAGE_RESULT_NOTIFICATION_MILLIS = 30_000L
@@ -0,0 +1,168 @@
package cn.ilapage.goauto.agent.service
import cn.ilapage.goauto.agent.network.HistoryPage
import cn.ilapage.goauto.agent.network.PurchaseHistoryItem
import java.text.ParsePosition
import java.text.SimpleDateFormat
import java.util.Collections
import java.util.Locale
import java.util.TimeZone
data class RepurchaseHistoryQuery(val page: Int, val pageSize: Int = 50, val days: Int = 30, val status: String? = null, val taskNo: String? = null)
enum class RepurchaseBatchFailure { PAGE_FAILED, INVALID_PAGE, INVALID_TIMESTAMP, INVALID_ORDER, INCOMPLETE_BATCH, LIST_CHANGED, PAGE_LIMIT }
class RepurchaseBatchException(val reason: RepurchaseBatchFailure) : IllegalStateException(reason.name)
class RepurchaseBatch internal constructor(items: List<PurchaseHistoryItem>) {
val items: List<PurchaseHistoryItem> = immutable(items)
val candidates: List<PurchaseHistoryItem> = immutable(items.filter { it.status == "failed" && it.retryable })
val failures: List<PurchaseHistoryItem> = immutable(items.filter { it.status == "failed" })
val skips: List<PurchaseHistoryItem> = immutable(failures.filterNot { it.retryable })
val headTaskId = items.firstOrNull()?.taskId
val newestCreatedAt = items.firstOrNull()?.createdAt
val oldestCreatedAt = items.lastOrNull()?.createdAt
private fun immutable(items: List<PurchaseHistoryItem>): List<PurchaseHistoryItem> =
Collections.unmodifiableList(ArrayList(items))
}
/** Read-only discovery. The callback must use the current device's authenticated history endpoint.
*
* [nowMillis] MUST return the trusted server Date time from the response to that fetch, and throw
* when it is missing or invalid. Never fall back to the phone clock or a previous response's Date:
* the server applies the rolling 30-day cutoff, and a slow phone could accept a truncated batch.
* Tests may inject a synthetic server clock. It is read only after each successful page response.
*
* Offset overlap is tolerated; a changed head is rejected. This is not a snapshot guarantee for
* arbitrary concurrent deletion, reassignment or timestamp edits on the server.
*/
class RepurchaseBatchDiscovery(
private val fetchPage: (RepurchaseHistoryQuery) -> HistoryPage<PurchaseHistoryItem>,
private val nowMillis: () -> Long,
private val maxPages: Int = 200,
) {
init { require(maxPages > 0) }
fun discover(): RepurchaseBatch {
var latestServerTime = 0L
fun readWithServerTime(pageNumber: Int): HistoryPage<PurchaseHistoryItem> {
val page = readPage(pageNumber)
val serverTime = try { nowMillis() } catch (_: Exception) {
refuse(RepurchaseBatchFailure.INCOMPLETE_BATCH)
}
if (serverTime <= 0) refuse(RepurchaseBatchFailure.INCOMPLETE_BATCH)
latestServerTime = maxOf(latestServerTime, serverTime)
return page
}
val seen = linkedMapOf<Long, Entry>()
val batch = mutableListOf<PurchaseHistoryItem>()
var head: Long? = null
var previous: Entry? = null
var originalTotal: Long? = null
var foundBoundary = false
var reachedEnd = false
for (pageNumber in 1..maxPages) {
val page = readWithServerTime(pageNumber)
if (originalTotal == null) originalTotal = page.total
else if (page.total != originalTotal) refuse(RepurchaseBatchFailure.LIST_CHANGED)
val entries = parseOrdered(page.items)
if (pageNumber == 1) head = entries.firstOrNull()?.item?.taskId
for (entry in entries) {
val duplicate = seen[entry.item.taskId]
if (duplicate != null) {
if (duplicate.time != entry.time) refuse(RepurchaseBatchFailure.INVALID_ORDER)
continue
}
val prior = previous
if (prior != null) {
if (ENTRY_ORDER.compare(prior, entry) > 0) refuse(RepurchaseBatchFailure.INVALID_ORDER)
if (prior.time.moreThanSixtySecondsAfter(entry.time)) {
foundBoundary = true
break
}
}
seen[entry.item.taskId] = entry
batch += entry.item
previous = entry
}
if (foundBoundary) break
if (pageNumber.toLong() * PAGE_SIZE >= page.total) {
// Offset overlap without enough unique rows cannot establish a complete tail.
if (seen.size.toLong() != page.total) refuse(RepurchaseBatchFailure.INCOMPLETE_BATCH)
reachedEnd = true
break
}
}
if (!foundBoundary && !reachedEnd) refuse(RepurchaseBatchFailure.PAGE_LIMIT)
val finalPage = readWithServerTime(1)
val finalHead = parseOrdered(finalPage.items).firstOrNull()?.item?.taskId
if (finalHead != head || finalPage.total != originalTotal) refuse(RepurchaseBatchFailure.LIST_CHANGED)
if (reachedEnd && previous != null) {
// The API applies a rolling 30-day range, not a midnight-based date filter.
// HTTP Date has whole-second precision; include its possible fractional second.
// Preserve the latest observed time if a later response's Date moves backwards.
val floorMillis = latestServerTime + 1000 - DAYS * 24L * 60 * 60 * 1000
val floorSeconds = floorMillis / 1000 - if (floorMillis < 0 && floorMillis % 1000 != 0L) 1 else 0
val floor = Timestamp(floorSeconds, ((floorMillis - floorSeconds * 1000) * 1_000_000).toInt())
if (!previous.time.moreThanSixtySecondsAfter(floor)) refuse(RepurchaseBatchFailure.INCOMPLETE_BATCH)
}
return RepurchaseBatch(batch)
}
private fun readPage(pageNumber: Int): HistoryPage<PurchaseHistoryItem> {
val page = try {
fetchPage(RepurchaseHistoryQuery(page = pageNumber))
} catch (_: Exception) {
// Do not expose a network exception that might contain credentials or response data.
refuse(RepurchaseBatchFailure.PAGE_FAILED)
}
val offset = (pageNumber - 1L) * PAGE_SIZE
if (page.page != pageNumber || page.pageSize != PAGE_SIZE || page.total < 0 ||
page.items.size.toLong() != (page.total - offset).coerceIn(0, PAGE_SIZE.toLong()) ||
page.items.any { it.taskId <= 0 } || page.items.map { it.taskId }.distinct().size != page.items.size
) refuse(RepurchaseBatchFailure.INVALID_PAGE)
return page
}
private fun parseOrdered(items: List<PurchaseHistoryItem>): List<Entry> {
val entries = items.map { Entry(it, parseTime(it.createdAt)) }
val ordered = entries.sortedWith(ENTRY_ORDER)
if (entries != ordered) refuse(RepurchaseBatchFailure.INVALID_ORDER)
return ordered
}
private fun parseTime(raw: String): Timestamp {
val match = TIMESTAMP.matchEntire(raw) ?: refuse(RepurchaseBatchFailure.INVALID_TIMESTAMP)
val zone = match.groupValues[3].let { if (it == "Z") "+0000" else it.replace(":", "") }
val normalized = match.groupValues[1] + zone
val position = ParsePosition(0)
val parsed = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ROOT).apply {
isLenient = false
timeZone = TimeZone.getTimeZone("UTC")
}.parse(normalized, position)
if (parsed == null || position.index != normalized.length) refuse(RepurchaseBatchFailure.INVALID_TIMESTAMP)
return Timestamp(parsed.time / 1000, match.groupValues[2].padEnd(9, '0').toInt())
}
private data class Entry(val item: PurchaseHistoryItem, val time: Timestamp)
private data class Timestamp(val seconds: Long, val nanos: Int) : Comparable<Timestamp> {
override fun compareTo(other: Timestamp): Int =
seconds.compareTo(other.seconds).takeIf { it != 0 } ?: nanos.compareTo(other.nanos)
fun moreThanSixtySecondsAfter(older: Timestamp): Boolean {
val secondsApart = seconds - older.seconds
return secondsApart > 60 || (secondsApart == 60L && nanos > older.nanos)
}
}
companion object {
private const val PAGE_SIZE = 50
private const val DAYS = 30
private val TIMESTAMP = Regex("(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2})(?:\\.(\\d{1,9}))?(Z|[+-]\\d{2}:\\d{2})")
private val ENTRY_ORDER = compareByDescending<Entry> { it.time }.thenByDescending { it.item.taskId }
private fun refuse(reason: RepurchaseBatchFailure): Nothing = throw RepurchaseBatchException(reason)
}
}
@@ -0,0 +1,235 @@
package cn.ilapage.goauto.agent.service
import cn.ilapage.goauto.agent.network.PurchaseHistoryDetail
import cn.ilapage.goauto.agent.network.PurchaseResetResult
import cn.ilapage.goauto.agent.network.AgentApiException
import java.util.concurrent.atomic.AtomicReference
interface RepurchasePort {
fun environmentProblem(): String?
fun localIdle(): Boolean
fun hasOtherWork(currentTaskId: Long?): Boolean
fun latestTaskId(): Long?
fun detail(taskId: Long): PurchaseHistoryDetail
fun reset(taskId: Long, requestId: String): PurchaseResetResult
fun executionEvidence(taskId: Long): List<RepurchaseExecutionEvidence> = emptyList()
}
/** Only emitted by the original executor after Start and after a known outcome. */
data class RepurchaseExecutionEvidence(val attemptNumber: Long, val attemptId: String, val phase: String, val resultType: String?)
class RepurchaseLocalBusy : IllegalStateException()
class RepurchaseCoordinator(
private val now: () -> Long,
private val requestId: () -> String,
private val publish: (RepurchaseState) -> Unit,
) {
@Volatile var state = RepurchaseState()
private set
private val stopRequest = AtomicReference<String?>(null)
private var position = 0
private var expectedAttempt = 0L
private var issuedAt = 0L
private var busySince: Long? = null
private var headChecked = false
private val resetRequestIds = mutableMapOf<Long, String>()
// All mutation except requestStop is confined to the Service's orchestration worker.
fun prepare(): Boolean {
if (state.busy) return false
stopRequest.set(null)
position = 0
expectedAttempt = 0
busySince = null
headChecked = false
resetRequestIds.clear()
emit(RepurchaseState(phase = RepurchasePhase.READING, roundId = requestId(), message = "正在读取本设备最后一批采购记录…"))
return true
}
fun prepared(batch: RepurchaseBatch) {
if (state.phase != RepurchasePhase.READING) return
if (isStopRequested()) { finish("已停止读取,没有发起重购"); return }
val skips = batch.skips.map { RepurchaseItemResult(it.taskId, RepurchaseResult.SKIPPED, it.retryDisabledReason ?: "当前不可重试") }
val message = when {
batch.items.isEmpty() -> "近30天没有采购记录"
batch.failures.isEmpty() -> "最后一批没有失败任务,不回退更早批次"
batch.candidates.isEmpty() -> "最后一批失败任务均不可重试,请查看逐条结果"
else -> "请确认本轮重购范围"
}
emit(state.copy(phase = if (batch.candidates.isEmpty()) RepurchasePhase.FINISHED else RepurchasePhase.READY,
batch = batch, results = skips, message = message))
}
fun confirm(roundId: String) {
if (state.phase != RepurchasePhase.READY || roundId != state.roundId) return
if (isStopRequested()) { finish("已取消重购"); return }
emit(state.copy(phase = RepurchasePhase.RUNNING, message = "正在复核本轮任务"))
}
fun requestStop(roundId: String) {
if (roundId.isNotBlank() && roundId == state.roundId) stopRequest.set(roundId)
}
fun isStopRequested(): Boolean = stopRequest.get() == state.roundId && state.roundId.isNotBlank()
fun fail(message: String) {
if (!state.busy) return
if (state.currentTaskId == null) finish(message)
else if (state.phase != RepurchasePhase.STOPPING) emit(state.copy(phase = RepurchasePhase.STOPPING, message = "$message;停止后续,当前任务沿用原流程收尾"))
}
fun tick(port: RepurchasePort) {
if (!state.busy) return
if (isStopRequested()) fail("已请求停止重购")
if (state.phase !in setOf(RepurchasePhase.RUNNING, RepurchasePhase.STOPPING)) return
if (state.currentTaskId != null && now() - issuedAt >= TASK_TIMEOUT_MILLIS) {
finish("单条等待已达15分钟,已停止编排;当前任务未被取消,请人工检查")
return
}
try {
port.environmentProblem()?.let { fail(it); return }
val current = state.currentTaskId
if (port.hasOtherWork(current)) fail("检测到新的采集或采购工作")
if (!state.busy) return
if (current != null) {
observe(port, current)
return
}
if (state.phase != RepurchasePhase.RUNNING) return
if (busySince != null && now() - requireNotNull(busySince) >= DRAIN_TIMEOUT_MILLIS) {
fail("设备忙碌或结果上传尚未收尾"); return
}
if (!port.localIdle()) {
val since = busySince ?: now().also { busySince = it }
if (now() - since >= DRAIN_TIMEOUT_MILLIS) fail("设备忙碌或结果上传尚未收尾")
return
}
val batch = requireNotNull(state.batch)
if (!headChecked) {
if (port.latestTaskId() != batch.headTaskId) { fail("采购列表已变化,请重新读取后确认"); return }
headChecked = true
}
if (position >= batch.candidates.size) { finish("本轮重购已结束"); return }
val taskId = batch.candidates[position].taskId
val detail = try { port.detail(taskId) } catch (error: AgentApiException) {
if (error.code == "PURCHASE_TASK_NOT_FOUND") { skip(taskId, "任务已过期或不再属于本设备"); return }
throw error
}
check(detail.task.taskId == taskId)
if (detail.task.status != "failed" || !detail.task.retryable) {
skip(taskId, detail.task.retryDisabledReason ?: "当前状态不可重试")
return
}
// Recheck after network reads. The reset adapter also holds a short local reservation.
if (isStopRequested()) { fail("已请求停止重购"); return }
port.environmentProblem()?.let { fail(it); return }
if (!port.localIdle()) return
if (port.hasOtherWork(null)) { fail("检测到新的采集或采购工作"); return }
if (isStopRequested()) { fail("已请求停止重购"); return }
issueReset(port, taskId, detail.attemptCount)
} catch (_: Exception) {
fail("连接、身份或服务端校验失败,请恢复后再操作")
}
}
private fun issueReset(port: RepurchasePort, taskId: Long, priorAttempt: Long) {
val fixedRequestId = resetRequestIds.getOrPut(taskId, requestId)
issuedAt = now()
expectedAttempt = 0
emit(state.copy(currentTaskId = taskId, message = "正在重置 CG-$taskId(原任务号)"))
var ambiguous = false
repeat(2) { attempt ->
// A stop while an ambiguous request was in flight must not start a fresh write.
if (attempt > 0 && isStopRequested()) { fail("重置响应不明确,已停止,请人工核对当前任务"); return }
try {
val result = port.reset(taskId, fixedRequestId)
check(result.taskId == taskId && result.attemptNumber > priorAttempt)
expectedAttempt = result.attemptNumber.toLong()
busySince = null
emit(state.copy(message = "等待 CG-$taskId 本次执行与结果上传"))
if (isStopRequested()) fail("已请求停止重购")
return
} catch (error: Exception) {
if (!ambiguous && error is RepurchaseLocalBusy) {
emit(state.copy(currentTaskId = null, message = "等待本地忙碌操作收尾"))
if (busySince == null) busySince = now()
return
}
if (!ambiguous && error is AgentApiException && error.status in 400..499 && error.code in BUSINESS_REFUSALS) {
emit(state.copy(currentTaskId = null))
skip(taskId, "当前业务资格拒绝:${error.code}")
return
}
if (error is AgentApiException && error.status in 400..499) {
if (!ambiguous) emit(state.copy(currentTaskId = null))
fail(if (ambiguous) "重置响应不明确,请人工核对" else "设备、规则或身份校验失败")
return
}
ambiguous = true
}
}
fail("重置响应仍不明确,已停止,请人工核对当前任务")
}
private fun observe(port: RepurchasePort, taskId: Long) {
if (expectedAttempt == 0L) return // Never treat an old failed result as this reset's outcome.
val detail = port.detail(taskId)
check(detail.task.taskId == taskId)
if (detail.attemptCount < expectedAttempt) return
if (detail.attemptCount > expectedAttempt) {
val evidence = port.executionEvidence(taskId)
var linkedAttempt = expectedAttempt
// Each extra attempt needs a completed probe/rematch and the original executor's
// Start evidence for the immediately following purchase attempt. A separate reset
// after failed/cancelled/success cannot satisfy this chain.
while (linkedAttempt < detail.attemptCount) {
val from = evidence.singleOrNull { it.attemptNumber == linkedAttempt }
val to = evidence.singleOrNull { it.attemptNumber == linkedAttempt + 1 }
if (from?.resultType !in setOf("spec_probe_completed", "spec_rematch_completed") ||
to?.phase != "purchase" || from?.attemptId.isNullOrBlank() || to.attemptId.isBlank() || from?.attemptId == to.attemptId) {
fail("同任务出现无法关联本轮的后续尝试,已停止,请人工核对")
if (port.localIdle()) finish(state.message)
return
}
linkedAttempt++
}
expectedAttempt = linkedAttempt
}
val status = detail.task.status
if (status == "order_result_unknown") {
fail("订单结果待核对,请人工检查,不能继续重购")
if (port.localIdle()) finish(state.message)
return
}
if (status !in TERMINAL) return
if (!port.localIdle()) return
val failed = status == "failed"
val result = when (status) {
"order_created" -> RepurchaseItemResult(taskId, RepurchaseResult.SUCCESS, "订单已创建")
"cancelled" -> RepurchaseItemResult(taskId, RepurchaseResult.SKIPPED, "本次任务已取消")
else -> RepurchaseItemResult(taskId, RepurchaseResult.FAILED, "再次失败:${detail.task.errorCode ?: "PURCHASE_FAILED"}")
}
position++
val stopping = state.phase == RepurchasePhase.STOPPING
emit(state.copy(currentTaskId = null, results = state.results + result))
if (failed && detail.task.errorCode in ENVIRONMENT_FAILURES) finish("登录、验证码、风控或设备环境异常,已停止后续重购")
else if (stopping || isStopRequested()) finish(state.message)
else if (position >= requireNotNull(state.batch).candidates.size) finish("本轮重购已结束;再次失败的任务不会在本轮重复执行")
}
private fun skip(taskId: Long, reason: String) {
position++
emit(state.copy(results = state.results + RepurchaseItemResult(taskId, RepurchaseResult.SKIPPED, reason)))
if (position >= requireNotNull(state.batch).candidates.size) finish("本轮重购已结束")
}
private fun finish(message: String) = emit(state.copy(phase = RepurchasePhase.FINISHED, message = message))
private fun emit(value: RepurchaseState) { state = value; publish(value) }
companion object {
const val TASK_TIMEOUT_MILLIS = 15 * 60 * 1000L
private const val DRAIN_TIMEOUT_MILLIS = 10_000L
private val TERMINAL = setOf("order_created", "failed", "cancelled")
private val BUSINESS_REFUSALS = setOf("PURCHASE_TASK_NOT_FOUND", "PURCHASE_RETRY_NOT_ALLOWED", "PURCHASE_RETRY_UNSAFE", "PURCHASE_RETRY_STALE", "PURCHASE_SPEC_MAPPING_REQUIRED")
private val ENVIRONMENT_FAILURES = setOf("PDD_LOGIN_REQUIRED", "PDD_CAPTCHA_REQUIRED", "PDD_RISK_CONTROL", "ACCESSIBILITY_NOT_READY", "DEVICE_OFFLINE", "AGENT_RESTARTED_DURING_EXECUTION")
}
}
@@ -0,0 +1,40 @@
package cn.ilapage.goauto.agent.service
enum class RepurchasePhase { IDLE, READING, READY, RUNNING, STOPPING, FINISHED }
enum class RepurchaseResult { SUCCESS, FAILED, SKIPPED }
data class RepurchaseItemResult(val taskId: Long, val result: RepurchaseResult, val message: String)
/** Process-local presentation only; never persists or resumes a round after process death. */
data class RepurchaseState(
val phase: RepurchasePhase = RepurchasePhase.IDLE,
val roundId: String = "",
val batch: RepurchaseBatch? = null,
val currentTaskId: Long? = null,
val results: List<RepurchaseItemResult> = emptyList(),
val message: String = "",
) {
val busy get() = phase in setOf(RepurchasePhase.READING, RepurchasePhase.READY, RepurchasePhase.RUNNING, RepurchasePhase.STOPPING)
val successCount get() = results.count { it.result == RepurchaseResult.SUCCESS }
val failedCount get() = results.count { it.result == RepurchaseResult.FAILED }
val skippedCount get() = results.count { it.result == RepurchaseResult.SKIPPED }
fun confirmationText(): String = buildString {
append("本设备最后一批(近30天全部状态)\n")
append("${batch?.oldestCreatedAt.orEmpty()} ~ ${batch?.newestCreatedAt.orEmpty()}\n")
append("共 ${batch?.items?.size ?: 0} 条 · 失败 ${batch?.failures?.size ?: 0} 条\n")
append("可重购 ${batch?.candidates?.size ?: 0} 条 · 跳过 ${batch?.skips?.size ?: 0} 条\n\n")
append("相邻创建时间不超过60秒推算为同批,不受当前搜索和筛选影响。\n")
append("逐条复用原任务号重试,本轮再次失败不重复执行。单条等待上限15分钟,超时只停止后续编排。\n\n")
append("可能真实创建拼多多待付款订单,系统不会付款。停止重购不取消已经提交或正在执行的任务。")
}
fun summaryText(): String = buildString {
if (message.isNotBlank()) append(message).append('\n')
currentTaskId?.let { append("当前 CG-$it\n") }
append("成功 $successCount · 再次失败 $failedCount · 跳过 $skippedCount")
batch?.let {
val candidateIds = it.candidates.map { task -> task.taskId }.toSet()
val handled = results.count { result -> result.taskId in candidateIds }
append("\n本轮已结束 $handled / ${it.candidates.size} · 未结束 ${(it.candidates.size - handled).coerceAtLeast(0)}")
}
}
}
@@ -142,8 +142,19 @@ class TaskHistoryFragment : Fragment() {
private val imageRequests = mutableListOf<HistoryImageRequest>()
private var currentPageReceiverRegistered = false
private var backfillPanel: LinearLayout? = null
private var repurchasePanel: LinearLayout? = null
private var repurchaseButton: MaterialButton? = null
private var repurchaseDialog: androidx.appcompat.app.AlertDialog? = null
private var repurchaseDialogRound: String? = null
private val currentPageReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == AgentForegroundService.ACTION_REPURCHASE_STATE) {
renderRepurchase()
if (!collection && isResumed && AgentForegroundService.repurchaseState.phase == cn.ilapage.goauto.agent.service.RepurchasePhase.FINISHED) {
detailState.taskId?.let(::loadPurchaseDetail) ?: load()
}
return
}
if (intent?.action == AgentForegroundService.ACTION_BACKFILL_STATE) {
renderBackfill()
if (!collection && isResumed && !AgentForegroundService.backfillState.running) {
@@ -191,6 +202,9 @@ class TaskHistoryFragment : Fragment() {
pageColumn.addView(context.screenTitle(if (collection) "采集记录" else "采购记录"))
pageColumn.addView(buildSearch())
if (!collection) {
repurchasePanel = context.column(0)
pageColumn.addView(repurchasePanel)
renderRepurchase()
backfillPanel = context.column(0)
pageColumn.addView(backfillPanel)
renderBackfill()
@@ -214,12 +228,19 @@ class TaskHistoryFragment : Fragment() {
override fun onResume() {
super.onResume()
renderRepurchase()
detailState.taskId?.let { taskId ->
if (collection) loadCollectionDetail(taskId) else loadPurchaseDetail(taskId)
} ?: load()
}
override fun onDestroyView() {
repurchaseDialog?.setOnDismissListener(null)
repurchaseDialog?.dismiss()
repurchaseDialog = null
repurchaseDialogRound = null
repurchasePanel = null
repurchaseButton = null
backfillPanel = null
requestGeneration++
cancelImageRequests()
@@ -289,11 +310,16 @@ class TaskHistoryFragment : Fragment() {
}, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, context.dp(48)).apply { marginStart = context.dp(8) })
} else {
row.addView(MaterialButton(context).apply {
text = "回填"
repurchaseButton = this
text = "重购"
textSize = 14f
minimumHeight = context.dp(48)
contentDescription = "回填拼多多订单号和下单时间"
setOnClickListener { showBackfillInput() }
contentDescription = "重试本设备最后一批失败采购"
isEnabled = !AgentForegroundService.repurchaseState.busy
setOnClickListener {
isEnabled = false
sendRepurchaseAction(AgentForegroundService.ACTION_REPURCHASE_PREPARE)
}
}, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, context.dp(48)).apply { marginStart = context.dp(8) })
}
addView(row, row.fullWidth())
@@ -302,6 +328,61 @@ class TaskHistoryFragment : Fragment() {
}
}
private fun sendRepurchaseAction(action: String, roundId: String = AgentForegroundService.repurchaseState.roundId) {
val context = context ?: return
val intent = Intent(context, AgentForegroundService::class.java).setAction(action).putExtra("roundId", roundId)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent) else context.startService(intent)
}
private fun renderRepurchase() {
val panel = repurchasePanel ?: return
val context = context ?: return
val state = AgentForegroundService.repurchaseState
val phase = state.phase
repurchaseButton?.isEnabled = !state.busy
panel.removeAllViews()
if (phase != cn.ilapage.goauto.agent.service.RepurchasePhase.READY) {
repurchaseDialog?.setOnDismissListener(null)
repurchaseDialog?.dismiss()
repurchaseDialog = null
repurchaseDialogRound = null
}
if (phase == cn.ilapage.goauto.agent.service.RepurchasePhase.IDLE) return
panel.addView(context.card(context.cardColumn().apply {
addView(context.label(if (state.busy) "本轮重购" else "重购结果", 16f))
addView(context.label(state.summaryText(), 14f))
if (state.busy) addView(MaterialButton(context).apply {
text = if (phase == cn.ilapage.goauto.agent.service.RepurchasePhase.STOPPING) "正在收尾…" else "停止重购"
minimumHeight = context.dp(48)
isEnabled = phase != cn.ilapage.goauto.agent.service.RepurchasePhase.STOPPING
setOnClickListener {
isEnabled = false
sendRepurchaseAction(AgentForegroundService.ACTION_REPURCHASE_STOP, state.roundId)
}
})
if (state.results.isNotEmpty()) addView(MaterialButton(context).apply {
text = "查看逐条结果"
minimumHeight = context.dp(48)
setOnClickListener {
MaterialAlertDialogBuilder(context).setTitle("本轮重购明细")
.setMessage(state.results.joinToString("\n") { "CG-${it.taskId}:${it.message}" })
.setPositiveButton("关闭", null).show()
}
})
}))
if (phase == cn.ilapage.goauto.agent.service.RepurchasePhase.READY && isResumed && repurchaseDialogRound != state.roundId) {
repurchaseDialogRound = state.roundId
repurchaseDialog = MaterialAlertDialogBuilder(context).setTitle("重购最后一批")
.setMessage(state.confirmationText())
.setNegativeButton("取消") { _, _ -> sendRepurchaseAction(AgentForegroundService.ACTION_REPURCHASE_STOP, state.roundId) }
.setPositiveButton("确认重购") { _, _ -> sendRepurchaseAction(AgentForegroundService.ACTION_REPURCHASE_CONFIRM, state.roundId) }
.create().also { dialog ->
dialog.setOnCancelListener { sendRepurchaseAction(AgentForegroundService.ACTION_REPURCHASE_STOP, state.roundId) }
dialog.show()
}
}
}
private fun showBackfillInput() {
if (AgentForegroundService.backfillState.running) {
toast("设备忙碌,请稍后操作")
@@ -729,6 +810,7 @@ class TaskHistoryFragment : Fragment() {
if (currentPageReceiverRegistered) return
val filter = IntentFilter(AgentForegroundService.ACTION_CURRENT_PAGE_RESULT)
filter.addAction(AgentForegroundService.ACTION_BACKFILL_STATE)
filter.addAction(AgentForegroundService.ACTION_REPURCHASE_STATE)
if (Build.VERSION.SDK_INT >= 33) {
requireContext().registerReceiver(currentPageReceiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@@ -18,6 +18,354 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class PurchaseLiveAutomationTest {
@Test
fun `hint delayed address update preserves fresh payment back budget for late order evidence`() {
val observationDriver = OrderObservationDriver { sample ->
observationPage(when {
sample == 1 -> "payment"
sample < 140 -> "loading"
else -> "complete"
})
}.apply { backDuration = 4_000 }
lateinit var addressDriver: LiveDriver
addressDriver = LiveDriver(initialEditFrame = { snapshot, sample ->
assertEquals(0, addressDriver.inputCount)
assertFalse(addressDriver.clicked.contains("保存"))
if (sample <= 4) observationDriver.elapsed += 10_000
snapshot.changeAddressEditor {
it.copy(
text = if (sample <= 4) "合成提示占位标记" else "合成测试区域示例路段1号-old",
hintText = "合成提示占位标记",
showingHintText = sample <= 4,
)
}
})
var observingOrder = false
val driver = object : PurchaseUiDriver by addressDriver {
override fun capture(): UiSnapshot =
if (observingOrder) observationDriver.capture() else addressDriver.capture()
override fun backPurchase(): Boolean =
if (observingOrder) observationDriver.backPurchase() else addressDriver.backPurchase()
override fun clickFresh(target: SnapshotNode): FreshActionResult =
if (observingOrder) observationDriver.clickFresh(target) else addressDriver.clickFresh(target)
override fun swipePurchase(direction: SwipeDirection, durationMs: Long): Boolean =
if (observingOrder) observationDriver.swipePurchase(direction, durationMs)
else addressDriver.swipePurchase(direction, durationMs)
override fun bringPddToForeground(): Boolean =
if (observingOrder) observationDriver.bringPddToForeground() else addressDriver.bringPddToForeground()
}
val automation = PurchaseLiveAutomation(
driver,
pause = { observationDriver.elapsed += it },
monotonicClockMs = { observationDriver.elapsed },
)
val address = automation.updateShippingAddress("_cg366")
assertEquals(5, addressDriver.initialEditCaptures)
assertEquals("合成测试区域示例路段1号-old", addressDriver.lastInputTarget?.text)
assertTrue(address.expectedAddress.endsWith("_cg366"))
assertFalse(address.expectedAddress.contains("合成提示占位标记"))
assertAddressEditorActions(addressDriver, saved = true)
assertTrue(observationDriver.elapsed > 40_000)
assertEquals("_cg366", automation.finalConfirmation(input().copy(addressSuffix = "_cg366"), address).addressSuffix)
automation.submitOrderOnce()
val clicksBeforeObservation = addressDriver.clicked.toList()
observingOrder = true
val order = automation.readOrderResult()
assertEquals("PDD-DEMO-365", order?.orderNo)
assertEquals("2026-10-08T03:21:43Z", order?.submittedAt)
assertEquals(140, observationDriver.captures)
val elapsedAfterBack = observationDriver.elapsed - observationDriver.backCompletedAt!!
assertTrue(elapsedAfterBack in 28_000L until 30_000L)
assertTrue(elapsedAfterBack + observationDriver.backDuration > 30_000)
assertObservationActions(observationDriver, backs = 1)
assertEquals(1, addressDriver.inputCount)
assertEquals(1, addressDriver.clicked.count { it == "保存" })
assertEquals(1, addressDriver.submitClicks)
assertEquals(clicksBeforeObservation, addressDriver.clicked)
assertEquals(0, addressDriver.genericSwipes + addressDriver.scopedSwipes)
assertFalse(addressDriver.clicked.any { it.contains("支付") })
}
@Test
fun `payment back observes late complete order beyond original sample budget`() {
val driver = OrderObservationDriver { sample ->
when {
sample == 1 -> observationPage("payment")
sample < 100 -> observationPage("loading")
else -> observationPage("complete")
}
}
val order = observationAutomation(driver).readOrderResult()
assertEquals("PDD-DEMO-365", order?.orderNo)
assertEquals(100, driver.captures)
assertEquals(1, driver.backs)
assertEquals(0, driver.swipes)
assertEquals(0, driver.clicks)
assertEquals(0, driver.foregroundRequests)
}
@Test
fun `deadline starts at late successful back and never resets on incomplete evidence or jitter`() {
val driver = OrderObservationDriver { sample ->
observationPage(when {
sample < 58 -> "loading"
sample == 58 -> "payment"
sample > 60 && sample % 3 == 0 -> "incomplete"
else -> "loading"
})
}.apply { backDuration = 4_000; captureDuration = 25 }
val automation = observationAutomation(driver, pauseOverhead = 17)
assertEquals(null, automation.readOrderResult())
assertTrue(driver.captures > 100)
assertEquals(driver.backCompletedAt!! + 30_000 + 17, driver.elapsed)
assertTrue(automation.lastOrderReadFailure!!.paymentPageObserved)
assertObservationActions(driver, backs = 1)
}
@Test
fun `capture that crosses deadline cannot accept late complete evidence or trigger unpaid scroll`() {
for (latePage in listOf("complete", "unpaid", "entry", "chooser", "wechat")) {
lateinit var driver: OrderObservationDriver
driver = OrderObservationDriver { sample ->
if (sample == 1) {
driver.captureDuration = 30_000
observationPage("payment")
} else observationPage(latePage)
}
val automation = observationAutomation(driver)
assertEquals(null, automation.readOrderResult())
assertEquals(2, driver.captures)
assertEquals(30_500L, driver.elapsed)
assertObservationActions(driver, backs = 1)
}
}
@Test
fun `slow captures exhaust fixed observation deadline before original sixty samples`() {
val driver = OrderObservationDriver { sample -> observationPage(if (sample == 1) "payment" else "loading") }
.apply { captureDuration = 1_000 }
val automation = observationAutomation(driver)
assertEquals(null, automation.readOrderResult())
assertTrue(driver.captures < 60)
assertTrue(driver.elapsed >= driver.backCompletedAt!! + 30_000)
assertTrue(driver.elapsed < driver.backCompletedAt!! + 31_000)
assertObservationActions(driver, backs = 1)
}
@Test
fun `incomplete context first appearing during extension stays passive until late time arrives`() {
val driver = OrderObservationDriver { sample -> observationPage(when {
sample == 1 -> "payment"
sample < 80 -> "loading"
sample < 100 -> "incomplete"
else -> "complete"
}) }
assertEquals("PDD-DEMO-365", observationAutomation(driver).readOrderResult()?.orderNo)
assertEquals(100, driver.captures)
assertObservationActions(driver, backs = 1)
}
@Test
fun `late detail entry chooser and WeChat cannot add navigation during extension`() {
for (latePage in listOf("entry", "chooser", "wechat")) {
val driver = OrderObservationDriver { sample -> observationPage(when {
sample == 1 -> "payment"
sample <= 60 -> "loading"
else -> latePage
}) }
val automation = observationAutomation(driver)
assertEquals(null, automation.readOrderResult())
assertEquals("PURCHASE_ORDER_CONTEXT_NOT_FOUND", automation.lastOrderReadFailure?.code)
assertTrue(driver.captures > 60)
assertObservationActions(driver, backs = 1)
}
}
@Test
fun `previous chooser and WeChat recovery retain repeat failures during extension`() {
for (kind in listOf("chooser", "wechat")) {
val driver = OrderObservationDriver { sample -> observationPage(when {
sample == 1 || sample > 60 -> kind
sample == 2 -> "payment"
else -> "loading"
}) }
val automation = observationAutomation(driver)
assertEquals(null, automation.readOrderResult())
assertEquals(
if (kind == "chooser") "PURCHASE_ORDER_CHOOSER_BACK_FAILED" else "PURCHASE_ORDER_WECHAT_RESTORE_TIMEOUT",
automation.lastOrderReadFailure?.code,
)
assertEquals(61, driver.captures)
assertEquals(if (kind == "chooser") 2 else 1, driver.backs)
assertEquals(if (kind == "wechat") 1 else 0, driver.foregroundRequests)
assertEquals(0, driver.swipes)
assertEquals(0, driver.clicks)
}
}
@Test
fun `late unpaid context retains its independent thirty samples and four swipes`() {
val driver = OrderObservationDriver { sample -> observationPage(when {
sample == 1 -> "payment"
sample < 140 -> "loading"
else -> "unpaid"
}) }
val automation = observationAutomation(driver)
assertEquals(null, automation.readOrderResult())
assertEquals(169, driver.captures)
assertTrue(driver.elapsed > 30_000)
assertObservationActions(driver, backs = 1, swipes = 4)
}
@Test
fun `unpaid markers alone never activate payment back extension`() {
val driver = OrderObservationDriver { observationPage("unpaid") }
val automation = observationAutomation(driver)
assertEquals(null, automation.readOrderResult())
assertEquals(30, driver.captures)
assertTrue(automation.lastOrderReadFailure!!.paymentPageObserved)
assertObservationActions(driver, swipes = 4)
}
@Test
fun `missing payment back retains original sixty samples and existing context scroll budget`() {
for (kind in listOf("loading", "incomplete")) {
val driver = OrderObservationDriver { observationPage(kind) }
assertEquals(null, observationAutomation(driver).readOrderResult())
assertEquals(60, driver.captures)
assertObservationActions(driver, swipes = if (kind == "incomplete") 3 else 0)
}
}
@Test
fun `order context within original budget retains original sampling and gestures after back`() {
val driver = OrderObservationDriver { sample -> observationPage(if (sample == 1) "payment" else "incomplete") }
assertEquals(null, observationAutomation(driver).readOrderResult())
assertEquals(60, driver.captures)
assertObservationActions(driver, backs = 1, swipes = 3)
}
@Test
fun `failed payment back stops immediately without activating observation`() {
val driver = OrderObservationDriver { observationPage("payment") }.apply { backSucceeds = false }
val automation = observationAutomation(driver)
assertEquals(null, automation.readOrderResult())
assertEquals("PURCHASE_ORDER_PAYMENT_BACK_FAILED", automation.lastOrderReadFailure?.code)
assertEquals(1, driver.captures)
assertEquals(0L, driver.elapsed)
assertObservationActions(driver, backs = 1)
}
@Test
fun `extension preserves repeated payment empty and unexpected app early failures`() {
for ((kind, code, expectedCaptures) in listOf(
Triple("payment", "PURCHASE_ORDER_PAYMENT_REPEATED", 85),
Triple("empty", "PURCHASE_ORDER_EMPTY_TIMEOUT", 75),
Triple("unexpected", "PURCHASE_ORDER_UNEXPECTED_APP", 61),
)) {
val driver = OrderObservationDriver { sample -> observationPage(when {
sample == 1 -> "payment"
sample <= 60 -> "loading"
else -> kind
}) }
val automation = observationAutomation(driver)
assertEquals(null, automation.readOrderResult())
assertEquals(code, automation.lastOrderReadFailure?.code)
assertEquals(expectedCaptures, driver.captures)
assertObservationActions(driver, backs = 1)
}
}
private fun observationAutomation(driver: OrderObservationDriver, pauseOverhead: Long = 0) = PurchaseLiveAutomation(
driver,
pause = { driver.elapsed += it + pauseOverhead },
monotonicClockMs = { driver.elapsed },
)
private fun assertObservationActions(driver: OrderObservationDriver, backs: Int = 0, swipes: Int = 0) {
assertEquals(backs, driver.backs)
assertEquals(swipes, driver.swipes)
assertEquals(0, driver.clicks)
assertEquals(0, driver.foregroundRequests)
}
private class OrderObservationDriver(
val frame: (Int) -> UiSnapshot,
) : PurchaseUiDriver by LiveDriver() {
var elapsed = 0L
var captures = 0
var backs = 0
var swipes = 0
var clicks = 0
var foregroundRequests = 0
var captureDuration = 0L
var backDuration = 0L
var backCompletedAt: Long? = null
var backSucceeds = true
override fun capture(): UiSnapshot {
elapsed += captureDuration
return frame(++captures)
}
override fun backPurchase(): Boolean {
backs++
elapsed += backDuration
if (backSucceeds) backCompletedAt = elapsed
return backSucceeds
}
override fun swipePurchase(direction: SwipeDirection, durationMs: Long): Boolean {
swipes++
return true
}
override fun clickFresh(target: SnapshotNode): FreshActionResult {
clicks++
return FreshActionResult.SUCCESS
}
override fun bringPddToForeground(): Boolean {
foregroundRequests++
return true
}
}
private fun observationPage(kind: String): UiSnapshot {
val labels = when (kind) {
"payment" -> listOf("立即支付")
"complete" -> listOf("订单号:PDD-DEMO-365", "下单时间:2026-10-08 11:21:43", "立即支付")
"incomplete" -> listOf("订单号:PDD-DEMO-365", "立即支付")
"unpaid" -> listOf("待付款")
"entry" -> listOf("查看订单")
"chooser" -> listOf("选择要使用的应用", "微信")
else -> emptyList()
}
return UiSnapshot(
when (kind) {
"empty" -> null
"wechat" -> "com.tencent.mm"
"unexpected" -> "com.example.unexpected"
"chooser" -> "android"
else -> PDD
},
when (kind) {
"payment" -> "com.xunmeng.pinduoduo.app_pay.core.PayActivity"
"chooser" -> "com.android.internal.app.ChooserActivity"
else -> ACTIVITY
},
labels.map { text ->
SnapshotNode(text, null, text, null, null, "android.widget.TextView",
NodeBounds(0, 100, 500, 180), true, false, false, false, true, true)
},
)
}
@Test
fun `two second payment transition and two needed scrolls yield order and payable amount without clicks`() {
val driver = ReadOnlyOrderDriver(paymentMs = 2500)
@@ -219,6 +567,338 @@ class PurchaseLiveAutomationTest {
assertFalse(driver.clicked.any { it.contains("支付") })
}
@Test
fun `address editor waits for an input arriving after its title`() {
assertDelayedAddressEditor { snapshot, sample ->
if (sample <= 4) snapshot.copy(nodes = snapshot.nodes.filterNot { it.path == "editor-address" }) else snapshot
}
}
@Test
fun `address editor waits for a populated value`() {
assertDelayedAddressEditor { snapshot, sample ->
snapshot.changeAddressEditor { if (sample <= 4) it.copy(text = " ") else it }
}
}
@Test
fun `address editor description cannot substitute for empty text`() {
for (text in listOf(null, "", " ")) {
assertAddressEditorTimeout("editor_empty", 1, 0) { snapshot, _ ->
snapshot.changeAddressEditor { it.copy(text = text, contentDescription = "合成说明占位标记") }
}
}
}
@Test
fun `address editor waits until hint is replaced by real text`() {
assertDelayedAddressEditor { snapshot, sample ->
snapshot.changeAddressEditor {
it.copy(
text = if (sample <= 4) "合成提示占位标记" else it.text,
hintText = "合成提示占位标记",
showingHintText = sample <= 4,
)
}
}
}
@Test
fun `address editor persistent hint text fails after the full budget`() {
assertAddressEditorTimeout("editor_hint", 1, 0) { snapshot, _ ->
snapshot.changeAddressEditor {
it.copy(text = "合成提示占位标记", hintText = "合成提示占位标记", showingHintText = true)
}
}
}
@Test
fun `address editor rejects text equal to trimmed hint despite false or absent showing flag`() {
for (showing in listOf(false, null)) {
assertAddressEditorTimeout("editor_hint", 1, 0) { snapshot, _ ->
snapshot.changeAddressEditor {
it.copy(text = " 合成提示占位标记 ", hintText = " 合成提示占位标记 ", showingHintText = showing)
}
}
}
}
@Test
fun `address editor showing hint flag blocks nonmatching or missing hint text`() {
for (hint in listOf(null, "", "合成提示占位标记")) {
assertAddressEditorTimeout("editor_hint", 1, 0) { snapshot, _ ->
snapshot.changeAddressEditor { it.copy(hintText = hint, showingHintText = true) }
}
}
}
@Test
fun `address editor empty text remains empty even when hint and description are present`() {
assertAddressEditorTimeout("editor_empty", 1, 0) { snapshot, _ ->
snapshot.changeAddressEditor {
it.copy(text = " ", contentDescription = "合成说明占位标记", hintText = "合成提示占位标记", showingHintText = true)
}
}
}
@Test
fun `address editor missing hint metadata remains compatible and uses actual text`() {
val driver = LiveDriver(initialEditFrame = { snapshot, _ ->
snapshot.changeAddressEditor {
assertEquals(null, it.hintText)
assertEquals(null, it.showingHintText)
it.copy(text = " 合成真实地址-old ", contentDescription = "合成说明占位标记")
}
})
val proof = PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg366")
assertEquals("合成真实地址_cg366", proof.expectedAddress)
assertEquals(1, driver.initialEditCaptures)
assertTrue(driver.lastInputTarget === driver.lastInitialEditSnapshot?.nodes?.single { it.path == "editor-address" })
assertAddressEditorActions(driver, saved = true)
}
@Test
fun `address editor accepts actual text with absent false or blank hint metadata`() {
for (showing in listOf(null, false)) {
for (hint in listOf(null, "", " ", "合成提示占位标记")) {
val driver = LiveDriver(initialEditFrame = { snapshot, _ ->
snapshot.changeAddressEditor { it.copy(hintText = hint, showingHintText = showing) }
})
val proof = PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg366")
assertTrue(proof.expectedAddress.endsWith("_cg366"))
assertEquals(1, driver.initialEditCaptures)
assertAddressEditorActions(driver, saved = true)
}
}
}
@Test
fun `address editor waits for an enabled input`() {
assertDelayedAddressEditor { snapshot, sample ->
snapshot.changeAddressEditor { if (sample <= 4) it.copy(enabled = false) else it }
}
}
@Test
fun `address editor tolerates more than three ambiguous frames before unique readiness`() {
assertDelayedAddressEditor { snapshot, sample ->
if (sample <= 4) snapshot.withSecondAddressEditor() else snapshot
}
}
@Test
fun `address editor uses the value and node from the successful readiness frame`() {
val driver = LiveDriver(initialEditFrame = { snapshot, sample ->
snapshot.changeAddressEditor { it.copy(text = if (sample == 1) "" else "合成地址第${sample}帧-old") }
})
val proof = PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg366")
assertEquals("合成地址第2帧_cg366", proof.expectedAddress)
assertEquals(2, driver.initialEditCaptures)
assertTrue(driver.lastInputTarget === driver.lastInitialEditSnapshot?.nodes?.single { it.path == "editor-address" })
assertAddressEditorActions(driver, saved = true)
}
@Test
fun `address editor structural ambiguity waits full budget even with only one ready input`() {
for (second in listOf<(SnapshotNode) -> SnapshotNode>(
{ it.copy(text = "") }, { it.copy(enabled = false) },
)) {
assertAddressEditorTimeout("editor_ambiguous", structural = 2, ready = 1) { snapshot, _ ->
snapshot.withSecondAddressEditor(second)
}
}
}
@Test
fun `address editor final zero inputs reports scalar missing reason`() {
assertAddressEditorTimeout("editor_missing", 0, 0) { snapshot, _ ->
snapshot.copy(nodes = snapshot.nodes.filterNot { it.path == "editor-address" })
}
}
@Test
fun `address editor final empty input reports scalar empty reason`() {
assertAddressEditorTimeout("editor_empty", 1, 0) { snapshot, _ ->
snapshot.changeAddressEditor { it.copy(text = " ") }
}
}
@Test
fun `address editor final disabled input reports scalar disabled reason`() {
assertAddressEditorTimeout("editor_disabled", 1, 0) { snapshot, _ ->
snapshot.changeAddressEditor { it.copy(enabled = false) }
}
}
@Test
fun `address editor final multiple inputs reports scalar ambiguity reason`() {
assertAddressEditorTimeout("editor_ambiguous", 2, 2) { snapshot, _ -> snapshot.withSecondAddressEditor() }
}
@Test
fun `address editor never seeing a title keeps edit timeout and one shared budget`() {
assertAddressEditorTimeout("title_missing", 0, 0, titleSeen = false) { snapshot, _ ->
snapshot.copy(nodes = snapshot.nodes.filterNot { it.path == "detail" })
}
}
@Test
fun `address editor remembers a title even when the final snapshot is empty`() {
assertAddressEditorTimeout("editor_missing", 0, 0) { snapshot, sample ->
if (sample == 1) snapshot.copy(nodes = snapshot.nodes.filterNot { it.path == "editor-address" })
else snapshot.copy(nodes = emptyList())
}
}
@Test
fun `address editor late title does not start a second wait budget`() {
assertAddressEditorTimeout("editor_empty", 1, 0) { snapshot, sample ->
val emptyEditor = snapshot.changeAddressEditor { it.copy(text = "") }
if (sample < 50) emptyEditor.copy(nodes = emptyEditor.nodes.filterNot { it.path == "detail" }) else emptyEditor
}
}
@Test
fun `address editor can become ready on the final sample of its shared budget`() {
val driver = LiveDriver(initialEditFrame = { snapshot, sample ->
if (sample < 50) snapshot.copy(nodes = emptyList()) else snapshot
})
val editPauses = mutableListOf<Long>()
PurchaseLiveAutomation(driver, pause = {
if (driver.currentPage == "edit" && driver.inputCount == 0) editPauses += it
}).updateShippingAddress("_cg366")
assertEquals(50, driver.initialEditCaptures)
assertEquals(listOf(500L) + List(49) { 200L }, editPauses)
assertAddressEditorActions(driver, saved = true)
}
@Test
fun `address editor excludes recipient phone invisible and leftward inputs and deduplicates paths`() {
val driver = LiveDriver(initialEditFrame = { snapshot, _ ->
val editor = snapshot.nodes.single { it.path == "editor-address" }
snapshot.copy(nodes = snapshot.nodes + listOf(
editor,
editor.copy(path = "hidden-input", visible = false),
editor.copy(path = "left-input", bounds = NodeBounds(0, 390, 10, 480)),
))
})
PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg366")
assertEquals(1, driver.initialEditCaptures)
assertEquals("editor-address", driver.lastInputTargetPath)
assertAddressEditorActions(driver, saved = true)
}
@Test
fun `address editor small screen row overlap remains ambiguous`() {
assertAddressEditorTimeout("editor_ambiguous", 2, 2) { snapshot, _ ->
snapshot.copy(nodes = snapshot.nodes.map {
if (it.path == "editor-phone") it.copy(bounds = NodeBounds(180, 360, 900, 410)) else it
})
}
}
@Test
fun `address editor fresh input failures never retry or save`() {
for (result in FreshActionResult.values().filter { it != FreshActionResult.SUCCESS }) {
val driver = LiveDriver(inputResult = result)
val error = runCatching { PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg366") }
.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_ADDRESS_UPDATE_FAILED", error.code)
assertEquals(1, driver.inputCount)
assertEquals(1, driver.initialEditCaptures)
assertEquals(listOf("138****5678", "修改"), driver.clicked)
assertEquals(0, driver.backCount)
assertEquals(0, driver.scopedSwipes + driver.genericSwipes + driver.submitClicks)
}
}
@Test
fun `address editor page safety problem interrupts readiness without input`() {
val driver = LiveDriver(initialEditFrame = { snapshot, sample ->
if (sample == 1) snapshot.changeAddressEditor { it.copy(text = "") }
else snapshot.copy(nodes = snapshot.nodes.map { if (it.path == "title") it.copy(text = "立即支付") else it })
})
val error = runCatching { PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg366") }
.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_PAYMENT_FORBIDDEN", error.code)
assertEquals(2, driver.initialEditCaptures)
assertAddressEditorActions(driver, saved = false)
}
private fun assertDelayedAddressEditor(frame: (UiSnapshot, Int) -> UiSnapshot) {
val driver = LiveDriver(initialEditFrame = frame)
val editPauses = mutableListOf<Long>()
val automation = PurchaseLiveAutomation(driver, pause = {
if (driver.currentPage == "edit" && driver.inputCount == 0) editPauses += it
})
val proof = automation.updateShippingAddress("_cg366")
assertTrue(proof.expectedAddress.endsWith("_cg366"))
assertEquals(5, driver.initialEditCaptures)
assertEquals(listOf(500L, 200L, 200L, 200L, 200L), editPauses)
assertEquals("editor-address", driver.lastInputTargetPath)
assertAddressEditorActions(driver, saved = true)
}
private fun assertAddressEditorTimeout(
reason: String,
structural: Int,
ready: Int,
titleSeen: Boolean = true,
frame: (UiSnapshot, Int) -> UiSnapshot,
) {
val driver = LiveDriver(initialEditFrame = frame)
val diagnostics = mutableListOf<String>()
val editPauses = mutableListOf<Long>()
val automation = PurchaseLiveAutomation(driver, pause = {
if (driver.currentPage == "edit" && driver.inputCount == 0) editPauses += it
}, panelDiagnostic = diagnostics::add)
val failure = runCatching { automation.updateShippingAddress("_cg366") }.exceptionOrNull()
assertTrue("Readiness must fail without changing the address", failure is PurchaseLiveException)
val error = failure as PurchaseLiveException
assertEquals(if (titleSeen) "PURCHASE_ADDRESS_UPDATE_FAILED" else "PURCHASE_ADDRESS_EDIT_TIMEOUT", error.code)
val diagnostic = "stage=address_editor_ready;reason=$reason;titleSeen=$titleSeen;structural=$structural;ready=$ready"
assertTrue(error.message.orEmpty(), error.message.orEmpty().endsWith("[$diagnostic]"))
assertEquals(50, driver.initialEditCaptures)
assertEquals(listOf(500L) + List(50) { 200L }, editPauses)
val emitted = error.message.orEmpty() + diagnostics.joinToString()
listOf("广东", "骏景", "测试收货人", "13800000000", "editor-address", "_cg366", "合成提示占位标记", "合成说明占位标记").forEach {
assertFalse("Sensitive fixture value in readiness diagnostics", emitted.contains(it))
}
assertAddressEditorActions(driver, saved = false)
}
private fun assertAddressEditorActions(driver: LiveDriver, saved: Boolean) {
assertEquals(if (saved) 1 else 0, driver.inputCount)
assertEquals(listOf("138****5678", "修改") + if (saved) listOf("保存") else emptyList(), driver.clicked)
assertEquals(if (saved) 1 else 0, driver.backCount)
assertEquals(1, driver.addressPathClicks)
assertEquals(0, driver.addressTaps + driver.genericSwipes + driver.scopedSwipes + driver.submitClicks)
}
private fun UiSnapshot.changeAddressEditor(change: (SnapshotNode) -> SnapshotNode): UiSnapshot =
copy(nodes = nodes.map { if (it.path == "editor-address") change(it) else it })
private fun UiSnapshot.withSecondAddressEditor(change: (SnapshotNode) -> SnapshotNode = { it }): UiSnapshot =
copy(nodes = nodes + change(nodes.single { it.path == "editor-address" }.copy(path = "editor-address-2")))
@Test
fun `split confirmation address keeps the unique saved task suffix proof`() {
val driver = LiveDriver(splitConfirmationAddress = true)
@@ -788,6 +1468,8 @@ class PurchaseLiveAutomationTest {
private val orderDetailEntryAfterSubmit: Boolean = false,
private val orderDetailEvidenceBelowFold: Boolean = false,
private val duplicateOrderDetailEntry: Boolean = false,
private val initialEditFrame: (UiSnapshot, Int) -> UiSnapshot = { snapshot, _ -> snapshot },
private val inputResult: FreshActionResult = FreshActionResult.SUCCESS,
postSubmitCaptureSequence: List<String> = emptyList(),
) : PurchaseUiDriver {
private var page = "confirmation"
@@ -802,6 +1484,10 @@ class PurchaseLiveAutomationTest {
var addressTaps = 0
var addressPathClicks = 0
var lastInputTargetPath: String? = null
var lastInputTarget: SnapshotNode? = null
var lastInitialEditSnapshot: UiSnapshot? = null
var initialEditCaptures = 0
var inputCount = 0
var backCount = 0
var postSubmitBackCount = 0
var pddRestoreCount = 0
@@ -814,7 +1500,12 @@ class PurchaseLiveAutomationTest {
postSubmitCaptureCount++
if (pendingPostSubmitPages.isNotEmpty()) page = pendingPostSubmitPages.removeAt(0)
}
return currentSnapshot()
val snapshot = currentSnapshot()
if (page == "edit" && inputCount == 0) {
initialEditCaptures++
return initialEditFrame(snapshot, initialEditCaptures).also { lastInitialEditSnapshot = it }
}
return snapshot
}
private fun currentSnapshot(): UiSnapshot = when (page) {
@@ -986,7 +1677,10 @@ class PurchaseLiveAutomationTest {
}
override fun inputFresh(target: SnapshotNode, value: String): FreshActionResult {
inputCount++
lastInputTarget = target
lastInputTargetPath = target.path
if (inputResult != FreshActionResult.SUCCESS) return inputResult
address = value
return FreshActionResult.SUCCESS
}
@@ -0,0 +1,37 @@
package cn.ilapage.goauto.agent
import cn.ilapage.goauto.agent.network.AgentApiClient
import org.junit.Assert.*
import org.junit.Test
import java.net.ServerSocket
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class RepurchaseServerClockTest {
@Test fun historyCapturesServerDateAndMissingDateClearsPreviousSample() {
ServerSocket(0).use { server ->
val executor = Executors.newSingleThreadExecutor()
val response = "{\"data\":{\"items\":[],\"total\":0,\"page\":1,\"pageSize\":50}}"
val serving = executor.submit {
repeat(2) { index ->
server.accept().use { socket ->
socket.soTimeout = 3000
val reader = socket.getInputStream().bufferedReader()
while (!reader.readLine().isNullOrEmpty()) { }
val date = if (index == 0) "Date: Thu, 08 Oct 2026 09:00:00 GMT\r\n" else ""
socket.getOutputStream().write(("HTTP/1.1 200 OK\r\n" + date +
"Content-Type: application/json\r\nContent-Length: ${response.toByteArray().size}\r\nConnection: close\r\n\r\n$response").toByteArray())
}
}
}
try {
val api = AgentApiClient("http://127.0.0.1:${server.localPort}")
api.purchaseHistory("synthetic", 1, null, null, 30, 50)
assertEquals(1791450000000L, api.lastResponseServerTimeMillis)
api.purchaseHistory("synthetic", 1, null, null, 30, 50)
assertNull(api.lastResponseServerTimeMillis)
serving.get(5, TimeUnit.SECONDS)
} finally { executor.shutdownNow() }
}
}
}
@@ -0,0 +1,241 @@
package cn.ilapage.goauto.agent.service
import cn.ilapage.goauto.agent.network.HistoryPage
import cn.ilapage.goauto.agent.network.PurchaseHistoryItem
import org.junit.Assert.*
import org.junit.Test
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
class RepurchaseBatchTest {
private val now = 1_791_446_400_000L
private fun at(secondsAgo: Long) = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).apply {
timeZone = TimeZone.getTimeZone("UTC")
}.format(Date(now - secondsAgo * 1000))
private fun item(id: Long, secondsAgo: Long = 0, status: String = "failed", retryable: Boolean = true) = PurchaseHistoryItem(
id, status, "synthetic", "synthetic", "synthetic", "", "", "", "", 1, null, "CNY", null, null,
null, null, retryable, if (retryable) null else "不可重试", at(secondsAgo),
)
private fun discover(items: List<PurchaseHistoryItem>): RepurchaseBatch = RepurchaseBatchDiscovery({ q ->
HistoryPage(items.drop((q.page - 1) * 50).take(50), items.size.toLong(), q.page, 50)
}, { now }).discover()
private fun refused(reason: RepurchaseBatchFailure, block: () -> Unit) {
try { block(); fail("Expected $reason") } catch (e: RepurchaseBatchException) { assertEquals(reason, e.reason) }
}
@Test fun sixtySecondsJoinsTransitivelyButSixtyOneStartsOlderBatch() {
val batch = discover(listOf(item(5), item(4, 60), item(3, 120), item(2, 181), item(1, 182)))
assertEquals(listOf(5L, 4L, 3L), batch.items.map { it.taskId })
assertEquals(at(0), batch.newestCreatedAt)
assertEquals(at(120), batch.oldestCreatedAt)
assertEquals(5L, batch.headTaskId)
}
@Test fun equalInstantsUseDescendingIdsAndRespectTimezones() {
val batch = discover(listOf(item(3).copy(createdAt = "2026-10-08T08:00:00.123456789+08:00"),
item(2).copy(createdAt = "2026-10-08T00:00:00.123456789Z"),
item(1).copy(createdAt = "2026-10-07T20:00:00.123456789-04:00")))
assertEquals(listOf(3L, 2L, 1L), batch.items.map { it.taskId })
}
@Test fun subMillisecondGapAboveSixtySecondsIsBoundary() {
val batch = discover(listOf(item(2).copy(createdAt = "2026-10-08T00:01:00.000000001Z"),
item(1).copy(createdAt = "2026-10-08T00:00:00Z")))
assertEquals(listOf(2L), batch.items.map { it.taskId })
}
@Test fun readsFullStateHistoryAcrossFiftyItemBoundaryAndRechecksHead() {
val requests = mutableListOf<RepurchaseHistoryQuery>()
val data = (70L downTo 1).map { item(it, 70 - it, if (it % 2 == 0L) "failed" else "order_created") }
val result = RepurchaseBatchDiscovery({ q ->
requests += q
HistoryPage(data.drop((q.page - 1) * 50).take(50), 70, q.page, 50)
}, { now }).discover()
assertEquals(70, result.items.size)
assertEquals(35, result.candidates.size)
assertEquals(listOf(1, 2, 1), requests.map { it.page })
assertTrue(requests.all { it.days == 30 && it.pageSize == 50 && it.status == null && it.taskNo == null })
}
@Test fun overlappingPagesDeduplicateTaskIdsBeforeBoundary() {
val data = (60L downTo 1).map { item(it, if (it >= 10) 60 - it else 300) }
val result = RepurchaseBatchDiscovery({ q ->
val page = if (q.page == 1) data.take(50) else data.drop(49)
HistoryPage(page, 61, q.page, 50)
}, { now }).discover()
assertEquals(51, result.items.size)
assertEquals(51, result.items.map { it.taskId }.distinct().size)
}
@Test fun headChangeRefusesEvenWhenBoundaryAlreadyFound() {
var calls = 0
refused(RepurchaseBatchFailure.LIST_CHANGED) {
RepurchaseBatchDiscovery({ q ->
calls++
HistoryPage(if (calls == 1) listOf(item(2), item(1, 100)) else listOf(item(3), item(2), item(1, 100)),
if (calls == 1) 2 else 3, q.page, 50)
}, { now }).discover()
}
}
@Test fun invalidDatesAndMissingZonesAreRefused() {
listOf("", "2026-02-30T00:00:00Z", "2026-10-08T00:00:00", "2026-10-08T00:00:00+25:00", "2026-10-08T00:00:00Zjunk").forEach {
refused(RepurchaseBatchFailure.INVALID_TIMESTAMP) { discover(listOf(item(1).copy(createdAt = it))) }
}
}
@Test fun invertedChronologicalOrIdOrderingIsRefused() {
refused(RepurchaseBatchFailure.INVALID_ORDER) { discover(listOf(item(2, 20), item(1))) }
refused(RepurchaseBatchFailure.INVALID_ORDER) { discover(listOf(item(1), item(2))) }
}
@Test fun nearThirtyDayCutoffCannotProveBatchComplete() {
val days30 = 30L * 24 * 60 * 60
listOf(days30, days30 - 60, days30 - 61, days30 + 1).forEach { age ->
refused(RepurchaseBatchFailure.INCOMPLETE_BATCH) { discover(listOf(item(1, age))) }
}
assertEquals(1, discover(listOf(item(1, days30 - 62))).items.size)
}
@Test fun usesServerResponseClockEvenWhenPhoneIsFiveMinutesSlow() {
val phoneNow = now
val serverNow = phoneNow + 5 * 60 * 1000
val ageFromPhoneSeconds = 30L * 24 * 60 * 60 - 5 * 60 - 30
var responseTime: Long? = null
refused(RepurchaseBatchFailure.INCOMPLETE_BATCH) {
RepurchaseBatchDiscovery({ q ->
responseTime = serverNow
HistoryPage(listOf(item(1, ageFromPhoneSeconds)), 1, q.page, 50)
}, { checkNotNull(responseTime) }).discover()
}
}
@Test fun responseTimeIsNotRequiredBeforeFirstFetch() {
var responseTime: Long? = null
val batch = RepurchaseBatchDiscovery({ q ->
responseTime = now
HistoryPage(listOf(item(1)), 1, q.page, 50)
}, { checkNotNull(responseTime) }).discover()
assertEquals(1, batch.items.size)
}
@Test fun missingServerResponseClockRefusesWithoutPhoneClockFallback() {
refused(RepurchaseBatchFailure.INCOMPLETE_BATCH) {
RepurchaseBatchDiscovery({ q -> HistoryPage(listOf(item(1)), 1, q.page, 50) },
{ error("No server Date") }).discover()
}
}
@Test fun retainsLatestObservedServerClockWhenLaterResponseTimeRegresses() {
var responseTime = now
var calls = 0
refused(RepurchaseBatchFailure.INCOMPLETE_BATCH) {
RepurchaseBatchDiscovery({ q ->
responseTime = if (++calls == 1) now + 300_000 else now
HistoryPage(listOf(item(1, 30L * 24 * 60 * 60 - 330)), 1, q.page, 50)
}, { responseTime }).discover()
}
}
@Test fun exactlyFiftyRecordsCanEstablishTrustworthyEnd() {
val requested = mutableListOf<Int>()
val batch = RepurchaseBatchDiscovery({ q ->
requested += q.page
HistoryPage((50L downTo 1).map { item(it, 50 - it) }, 50, q.page, 50)
}, { now }).discover()
assertEquals(50, batch.items.size)
assertEquals(listOf(1, 1), requested)
}
@Test fun latestSuccessfulBatchDoesNotFallBackToOlderFailures() {
val result = discover(listOf(item(2, status = "order_created"), item(1, 61)))
assertEquals(1, result.items.size)
assertTrue(result.failures.isEmpty())
assertTrue(result.candidates.isEmpty())
}
@Test fun onlyFailedRetryableAreCandidatesAndSecondRoundUsesRemainingFailures() {
val items = (10L downTo 1).map { item(it, status = if (it <= 4) "failed" else "order_created") }
val first = discover(items)
assertEquals(listOf(4L, 3L, 2L, 1L), first.candidates.map { it.taskId })
val second = discover(items.map { if (it.taskId in 3L..4L) it.copy(status = "order_created") else it })
assertEquals(listOf(2L, 1L), second.candidates.map { it.taskId })
val blocked = discover(listOf(item(2, retryable = false), item(1, status = "pending")))
assertEquals(1, blocked.failures.size)
assertEquals("不可重试", blocked.skips.single().retryDisabledReason)
assertTrue(blocked.candidates.isEmpty())
}
@Test fun pageFailureCannotReturnPartOfBatch() {
refused(RepurchaseBatchFailure.PAGE_FAILED) {
RepurchaseBatchDiscovery({ q ->
if (q.page == 2) error("synthetic network failure")
HistoryPage((60L downTo 11).map { item(it, 60 - it) }, 60, q.page, 50)
}, { now }).discover()
}
}
@Test fun shortPageWithUnseenTotalAndWrongMetadataAreRefused() {
listOf(HistoryPage(listOf(item(1)), 2, 1, 50), HistoryPage(listOf(item(1)), 1, 2, 50),
HistoryPage(listOf(item(1)), 1, 1, 20), HistoryPage(emptyList(), -1, 1, 50)).forEach { page ->
refused(RepurchaseBatchFailure.INVALID_PAGE) { RepurchaseBatchDiscovery({ page }, { now }).discover() }
}
}
@Test fun maximumPagesCannotReturnTruncatedBatch() {
refused(RepurchaseBatchFailure.PAGE_LIMIT) {
RepurchaseBatchDiscovery({ q -> HistoryPage((60L downTo 11).map { item(it, 60 - it) }, 60, q.page, 50) },
{ now }, maxPages = 1).discover()
}
}
@Test fun crossPageOrderInversionAndChangedDuplicateTimestampAreRefused() {
listOf(item(1, 1), item(11, 99)).forEach { next ->
refused(RepurchaseBatchFailure.INVALID_ORDER) {
RepurchaseBatchDiscovery({ q ->
HistoryPage(if (q.page == 1) (60L downTo 11).map { item(it, 60 - it) } else listOf(next),
51, q.page, 50)
}, { now }).discover()
}
}
}
@Test fun duplicatesCannotMakeAnIncompleteTailLookComplete() {
refused(RepurchaseBatchFailure.INCOMPLETE_BATCH) {
RepurchaseBatchDiscovery({ q ->
HistoryPage(if (q.page == 1) (60L downTo 11).map { item(it, 60 - it) } else listOf(item(11, 49)),
51, q.page, 50)
}, { now }).discover()
}
}
@Test fun failedHeadRecheckRefusesTheAlreadyFoundBatch() {
var calls = 0
refused(RepurchaseBatchFailure.PAGE_FAILED) {
RepurchaseBatchDiscovery({ q ->
if (++calls > 1) error("synthetic network failure")
HistoryPage(listOf(item(1)), 1, q.page, 50)
}, { now }).discover()
}
}
@Test fun emptyHistoryIsRecheckedAndReturnedEmpty() {
var calls = 0
val batch = RepurchaseBatchDiscovery({ q -> calls++; HistoryPage(emptyList(), 0, q.page, 50) }, { now }).discover()
assertTrue(batch.items.isEmpty())
assertNull(batch.headTaskId)
assertEquals(2, calls)
}
@Test fun immutableSnapshotDoesNotExposeMutableLists() {
val batch = discover(listOf(item(1)))
listOf(batch.items, batch.candidates, batch.failures).forEach { items ->
try { (items as MutableList).clear(); fail("Mutable snapshot") } catch (_: UnsupportedOperationException) { }
}
}
}
@@ -0,0 +1,182 @@
package cn.ilapage.goauto.agent.service
import cn.ilapage.goauto.agent.network.*
import org.junit.Assert.*
import org.junit.Test
import java.io.IOException
class RepurchaseCoordinatorTest {
private fun item(id: Long, status: String = "failed", retryable: Boolean = true, error: String? = null) = PurchaseHistoryItem(
id, status, "", "", "", "", "", "", "", 1, null, "CNY", null, null, error, null, retryable, "不可重试", "2026-10-08T09:00:00Z")
private fun detail(id: Long, status: String = "failed", count: Long = 1, retryable: Boolean = true, error: String? = null) =
PurchaseHistoryDetail(item(id, status, retryable, error), count, error, null, false, null, null, null, null, false, null)
private inner class Fake : RepurchasePort {
var clock = 0L
var busy = false
var otherWork = false
var environment: String? = null
var head: Long? = 2L
var resetFailure: Exception? = null
var failOnce = false
var duringReset: (() -> Unit)? = null
val details = mutableMapOf(2L to this@RepurchaseCoordinatorTest.detail(2), 1L to this@RepurchaseCoordinatorTest.detail(1))
val resets = mutableListOf<Pair<Long, String>>()
var evidence = emptyList<RepurchaseExecutionEvidence>()
override fun executionEvidence(taskId: Long) = evidence
override fun environmentProblem() = environment
override fun localIdle() = !busy
override fun hasOtherWork(currentTaskId: Long?) = otherWork
override fun latestTaskId() = head
override fun detail(taskId: Long) = details.getValue(taskId)
override fun reset(taskId: Long, requestId: String): PurchaseResetResult {
resets += taskId to requestId
duringReset?.invoke()
resetFailure?.let { if (failOnce) resetFailure = null; throw it }
return PurchaseResetResult(taskId, "CG-$taskId", 2, "pending", resets.size > 1)
}
fun runner(): RepurchaseCoordinator {
var sequence = 0
return RepurchaseCoordinator({ clock }, { "request-${++sequence}" }, {}).also {
assertTrue(it.prepare())
it.prepared(RepurchaseBatch(listOf(item(2), item(1))))
it.confirm(it.state.roundId)
}
}
}
@Test fun serialResetsWaitForNewAttemptAndLocalDrain() {
val p = Fake(); val r = p.runner()
r.tick(p); assertEquals(listOf(2L), p.resets.map { it.first })
r.tick(p); assertEquals(0, r.state.results.size) // old failed, attempt1
p.details[2] = detail(2, "order_created", 2); p.busy = true
r.tick(p); assertEquals(0, r.state.results.size)
p.busy = false; r.tick(p); assertEquals(1, r.state.successCount)
r.tick(p); assertEquals(listOf(2L, 1L), p.resets.map { it.first })
p.details[1] = detail(1, count = 2); r.tick(p); r.tick(p)
assertEquals(RepurchasePhase.FINISHED, r.state.phase)
assertEquals(1, r.state.failedCount); assertEquals(2, p.resets.size)
}
@Test fun lostResetResponseUsesSameRequestIdAndReplayIsNotTerminal() {
val p = Fake(); val r = p.runner(); p.resetFailure = IOException(); p.failOnce = true
r.tick(p); r.tick(p)
assertEquals(2, p.resets.size); assertEquals(p.resets[0], p.resets[1])
assertEquals(0, r.state.results.size)
}
@Test fun unresolvedMappedValuesDoNotPreventReset() {
val p = Fake(); val r = p.runner(); r.tick(p)
assertEquals(2L, p.resets.single().first)
}
@Test fun definiteBusinessRefusalSkipsButNetworkAmbiguityStops() {
val p = Fake(); val r = p.runner()
p.resetFailure = AgentApiException(409, "PURCHASE_RETRY_STALE", "safe", false)
r.tick(p); assertEquals(1, r.state.skippedCount)
p.resetFailure = IOException(); r.tick(p); r.tick(p)
assertTrue(r.state.phase in setOf(RepurchasePhase.STOPPING, RepurchasePhase.FINISHED))
assertEquals(3, p.resets.size)
}
@Test fun newWorkStopsSubsequentButNotCurrent() {
val p = Fake(); val r = p.runner(); r.tick(p); p.otherWork = true
r.tick(p); assertEquals(RepurchasePhase.STOPPING, r.state.phase)
p.details[2] = detail(2, "order_created", 2); r.tick(p); r.tick(p)
assertEquals(RepurchasePhase.FINISHED, r.state.phase); assertEquals(1, p.resets.size)
}
@Test fun stopBeforeResetIssuesNothingAndStaleStopIgnored() {
val p = Fake(); val r = p.runner(); r.requestStop("old"); r.tick(p)
assertEquals(1, p.resets.size)
val p2 = Fake(); val r2 = p2.runner(); r2.requestStop(r2.state.roundId); r2.tick(p2)
assertEquals(0, p2.resets.size); assertEquals(RepurchasePhase.FINISHED, r2.state.phase)
}
@Test fun stopDuringIssuedResetAllowsOnlyCurrentToDrain() {
val p = Fake(); val r = p.runner(); p.duringReset = { r.requestStop(r.state.roundId) }
r.tick(p); p.details[2] = detail(2, "order_created", 2); r.tick(p); r.tick(p)
assertEquals(1, p.resets.size); assertEquals(RepurchasePhase.FINISHED, r.state.phase)
}
@Test fun timeoutStopsOrchestrationWithoutAnotherReset() {
val p = Fake(); val r = p.runner(); r.tick(p); p.clock = 15 * 60 * 1000L
r.tick(p); assertEquals(RepurchasePhase.FINISHED, r.state.phase); assertEquals(1, p.resets.size)
}
@Test fun unknownAndCaptchaStopTheRound() {
for ((status, error) in listOf("order_result_unknown" to null, "failed" to "PDD_CAPTCHA_REQUIRED")) {
val p = Fake(); val r = p.runner(); r.tick(p); p.details[2] = detail(2, status, 2, error = error)
r.tick(p); r.tick(p)
assertEquals(RepurchasePhase.FINISHED, r.state.phase); assertEquals(1, p.resets.size)
}
}
@Test fun headChangedOrEnvironmentUnavailableDoesNotReset() {
val p = Fake(); val r = p.runner(); p.head = 3; r.tick(p)
assertEquals(RepurchasePhase.FINISHED, r.state.phase); assertTrue(p.resets.isEmpty())
val p2 = Fake(); val r2 = p2.runner(); p2.environment = "无障碍未开启"; r2.tick(p2)
assertEquals(RepurchasePhase.FINISHED, r2.state.phase); assertTrue(p2.resets.isEmpty())
}
@Test fun busyHasBoundedDrainAndProcessRestartDoesNotRestoreRound() {
val p = Fake(); val r = p.runner(); p.busy = true; r.tick(p)
p.clock = 10000; r.tick(p); assertEquals(RepurchasePhase.FINISHED, r.state.phase)
assertFalse(RepurchaseCoordinator({0}, {"x"}, {}).state.busy)
}
@Test fun noRetryableCandidatesDoesNotConfirmOrFallBack() {
val r = RepurchaseCoordinator({0}, {"x"}, {})
r.prepare(); r.prepared(RepurchaseBatch(listOf(item(3, "order_created"))))
assertEquals(RepurchasePhase.FINISHED, r.state.phase)
r.confirm(r.state.roundId); assertEquals(RepurchasePhase.FINISHED, r.state.phase)
}
@Test fun definiteEnvironmentRefusalStopsWithoutPretendingTaskWasIssued() {
val p = Fake(); val r = p.runner()
p.resetFailure = AgentApiException(401, "DEVICE_TOKEN_INVALID", "unauthorized", false)
r.tick(p)
assertEquals(RepurchasePhase.FINISHED, r.state.phase)
assertNull(r.state.currentTaskId)
assertEquals(1, p.resets.size)
}
@Test fun secondRoundOnlyUsesStillFailedCandidates() {
val p = Fake(); val r = p.runner(); r.tick(p)
p.details[2] = detail(2, "order_created", 2); r.tick(p); r.tick(p)
p.details[1] = detail(1, count = 2); r.tick(p)
assertTrue(r.prepare())
r.prepared(RepurchaseBatch(listOf(item(2, "order_created"), item(1))))
assertEquals(listOf(1L), r.state.batch!!.candidates.map { it.taskId })
r.confirm(r.state.roundId)
// New reset must return a strictly newer attempt than the refreshed detail.
p.details[1] = detail(1)
r.tick(p)
assertEquals(listOf(2L, 1L, 1L), p.resets.map { it.first })
}
@Test fun unexpectedExceptionDoesNotLeakRawErrorOrSkipRest() {
val p = Fake(); val r = p.runner(); p.resetFailure = IOException("private remote body")
r.tick(p)
assertFalse(r.state.message.contains("private"))
assertEquals(RepurchasePhase.STOPPING, r.state.phase)
assertEquals(listOf(2L, 2L), p.resets.map { it.first })
}
@Test fun externalLaterAttemptIsNotCountedAsThisRoundsResult() {
val p = Fake(); val r = p.runner(); r.tick(p)
p.details[2] = detail(2, "order_created", 3)
p.evidence = listOf(RepurchaseExecutionEvidence(2, "attempt2", "purchase", "failed"),
RepurchaseExecutionEvidence(3, "attempt3", "purchase", "order_created"))
r.tick(p); r.tick(p)
assertEquals(RepurchasePhase.FINISHED, r.state.phase)
assertEquals(0, r.state.successCount); assertEquals(1, p.resets.size)
}
@Test fun completedProbeCanLinkToOriginalExecutorsNextPurchaseAttempt() {
val p = Fake(); val r = p.runner(); r.tick(p)
p.details[2] = detail(2, "order_created", 3)
p.evidence = listOf(RepurchaseExecutionEvidence(2, "probe2", "spec_probe", "spec_probe_completed"),
RepurchaseExecutionEvidence(3, "purchase3", "purchase", "order_created"))
r.tick(p)
assertEquals(1, r.state.successCount)
r.tick(p); assertEquals(listOf(2L, 1L), p.resets.map { it.first })
}
@Test fun localReservationBusyNeverPretendsARequestWasSentAndUsesSameId() {
val p = Fake(); val r = p.runner(); p.resetFailure = RepurchaseLocalBusy(); p.failOnce = true
r.tick(p); assertNull(r.state.currentTaskId); assertEquals(RepurchasePhase.RUNNING, r.state.phase)
r.tick(p); assertEquals(p.resets[0], p.resets[1])
val p2 = Fake(); val r2 = p2.runner(); p2.resetFailure = RepurchaseLocalBusy()
r2.tick(p2); p2.clock = 10000; r2.tick(p2)
assertEquals(RepurchasePhase.FINISHED, r2.state.phase); assertNull(r2.state.currentTaskId)
}
}
@@ -0,0 +1,34 @@
package cn.ilapage.goauto.agent.service
import org.junit.Assert.*
import org.junit.Test
class RepurchaseStateTest {
@Test fun confirmationExplainsOriginalTaskAndUnpaidOrderRisk() {
val state = RepurchaseState(phase = RepurchasePhase.READY)
assertTrue(state.confirmationText().contains("不会付款"))
assertTrue(state.confirmationText().contains("原任务号"))
assertTrue(state.confirmationText().contains("15分钟"))
assertTrue(state.confirmationText().contains("60秒"))
}
@Test fun readingReadyRunningAndStoppingPreventDuplicateRounds() {
for (phase in listOf(RepurchasePhase.READING, RepurchasePhase.READY, RepurchasePhase.RUNNING, RepurchasePhase.STOPPING)) {
assertTrue(RepurchaseState(phase = phase).busy)
}
assertFalse(RepurchaseState().busy)
assertFalse(RepurchaseState(phase = RepurchasePhase.FINISHED).busy)
}
@Test fun countsDoNotMarkUnexecutedItemsAsFailures() {
val state = RepurchaseState(results = listOf(
RepurchaseItemResult(1, RepurchaseResult.SUCCESS, "订单已创建"),
RepurchaseItemResult(2, RepurchaseResult.FAILED, "再次失败"),
RepurchaseItemResult(3, RepurchaseResult.SKIPPED, "不可重试"),
))
assertEquals(1, state.successCount)
assertEquals(1, state.failedCount)
assertEquals(1, state.skippedCount)
assertTrue(state.summaryText().contains("成功 1"))
}
}
+28 -3
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Architecture-and-Code-Map
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Architecture-and-Code-Map.-
wiki_revision: b3d1c9b7ba1dd5820a20e59b0c21a971aaf1b8ee
synchronized_at: 2026-10-08T01:41:51Z
wiki_revision: bf3ce6efd67fde1fdb6eacd3248f186aea880391
synchronized_at: 2026-10-08T10:15:16Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -63,7 +63,7 @@ Android Portal/Agent
- 重置在事务中清空原结果,保留 URL、goods_id、规则和设备快照,状态恢复为 `pending`。
- Android 本地互斥与服务端原子领取共同保证单设备串行。
- 正式采购在 Android 本地 SQLite 事务中先保存不可逆状态、稳定服务端请求 ID 和脱敏最终确认快照,再通知服务端并只允许一次创建订单点击;重启后只重放服务端标记、只读核单或上报,不再次点击。
- 原始控件树和截图不持久化;Android Agent 端第一期不使用 OCR/VLM。服务端 SYB 登录验证码识别是唯一例外,见 [#48](https://git.ilapage.cn/OPC/goauto/issues/48)。
- 普通原始控件树和截图不持久化;采购失败私有现场诊断是 #364 的限定例外,见本页对应节;Android Agent 端第一期不使用 OCR/VLM。服务端 SYB 登录验证码识别是唯一例外,见 [#48](https://git.ilapage.cn/OPC/goauto/issues/48)。
- 蝦皮规格映射独立保存在 `shopee_product.specs_json`:颜色只能选择关联 PDD 当前可选颜色,允许多个蝦皮颜色共用一个 PDD 颜色。Admin 商品详情的“一键匹配颜色和尺码”在服务端统一计算两个维度:保留当前仍有效的已确认映射,将唯一确定匹配及达到阈值、具备理由且候选仍有效的 AI 匹配,在重新校验规格上下文后于同一事务直接写为 `confirmed`,无需人工确认;低置信度或无结果保持未匹配,Provider 异常或上下文变化时不写入任何本次结果。PDD 目标规格消失后页面标记失效,映射保存和采购创建均拒绝继续使用;无需新增数据库表或 Android 能力。
## 最小业务数据
@@ -639,3 +639,28 @@ Web 唯一展示位置为“采集采购 → SYB 同步记录”:列表状态
- 因预算超时不能再使用已取消context写统计,收尾仅使用最多5秒的独立上下文执行受所有权保护的完成更新,不启动新商品领取或AI调用;失租不强制落库。
- MySQL默认返回实际修改行数;续租更新返回0时,只在当前持有行锁的事务内再次核验owner/状态/槽位/实时有效租约,以区分同毫秒值未变化与真实失租;其他完成/工作项更新仍要求恰好一行。
- AI配置读取先返回数据库错误,再判断停用,避免基础设施错误被误记为业务跳过。仅批次私有上下文把基础设施错误作为本轮错误终止;普通单商品Provider重试策略保持不变。
## 采购失败现场诊断(#364,待真机验收)
实现绑定 `4581ee5`,后续合并记录见 #364;尚未发布。以下是普通原始控件树禁存规则的限定例外;普通采集、截图、OCR/VLM 和付款边界不变。
- Android `diagnostics/FailureSnapshotCapture.kt` 统一判断失败/待核对、成功排除及既有 ZIP;`FailureSnapshotExporter.kt` 独立导出有限公开属性,`AccessibilitySnapshotSource.kt` 只读默认显示屏交互窗口,不改变正常 `capture()` 或解析器。
- `AgentForegroundService` 在有效实际 attempt 的失败结果或执行异常处同步有界截取,先于新提示/返回/下一任务;恢复场景单独标识。成功结果后的保存/提示/上传异常不创建失败快照,不改变原业务状态和不可逆标记。
- `goauto_diagnostics.db` 升级 v4;独立 `purchase_failure_snapshot`、`purchase_failure_snapshot_queue`、`purchase_failure_snapshot_context` 表。旧 `agent_diagnostic` 保持 7 天/50 条,新快照30天/64MiB逻辑容量。SQL 核心 `FailureSnapshotRepository` 共用真实 SQLite 测试,Android适配器以256KiB块读取BLOB,避开CursorWindow单行限制。
- 队列绑定 Server Origin;已保存 ZIP 不覆盖,旧上传响应凭 fingerprint 不得清除首次恢复 ZIP 的新队列项。结果 Outbox 优先,诊断独立后台线程只上传已存字节,不持有设备任务锁;启动及每60秒执行维护。
- Server `purchase/failure_snapshot*.go` 提供专用上传/安全摘要/管理员ZIP下载;`models/purchase_failure_snapshot.go` 独立私有表。追加迁移 `1791400000000_purchase_failure_snapshot.go` 保存 LONGBLOB ZIP、LONGTEXT manifest、attempt唯一约束及到期索引。
- `access.AdminAPIs` 注册两个仅管理员读取接口;普通任务DTO和Client API不增加原始诊断字段。通用操作日志精确排除三个诊断端点,私有SQL读写使用静默logger。服务启动立即清理并每小时清理过期诊断,不依赖新任务。
- Web `purchase-tasks/FailureSnapshotCell.vue` 是现有执行记录末尾200px管理员专属列,独立摘要查询、固定原因中文和附件下载;无原始XML在线预览。
## Android 重购编排(#367)
实现绑定 `5430dc1`,工单分支尚未合并/安装/发布;无Server/Web、数据库或接口迁移。
- `TaskHistoryFragment` 把采购搜索栏入口改为“重购”,发送 PREPARE/CONFIRM/STOP、显示 Service 内存状态;一次确认与逐条摘要由 `RepurchaseState` 提供,不由 Fragment 驱动采购生命周期。
- `RepurchaseBatchDiscovery` 注入既有设备历史查询和服务端HTTP Date时钟,负责全状态/50条页/30天窗口、相邻60秒边界、去重、完整性及重读首页;最多200页,不使用本地历史缓存执行重购。
- `RepurchaseCoordinator` 通过小型 `RepurchasePort` 执行非阻塞状态推进;只调用原reset和只读详情,固定每任务requestId、expected attempt、10秒本地忙碌复核及15分钟单条上限。依靠原执行器的attemptNumber/UUID/phase/已知结果识别合法探测续行,拒绝外部更晚attempt冒充本轮结果。
- `AgentForegroundService` 独立单线程scheduled executor每2秒推进编排,历史网络不阻塞心跳或taskExecutor;发现使用独享API客户端,reset只短暂预留既有TaskExecutionMutex。原scheduler继续唯一负责claim/start/真实PDD操作及Outbox,编排不持整轮锁、不新建执行器路径。
- 新工作查询同时检查采集next、采购next及本设备活动状态历史,防止采购next优先返回本轮current而遮蔽其他pending。停止信号为原子roundId,配置/身份冻结,仅内存保存摘要;进程重启不恢复整轮,既有单任务恢复及失败私有诊断不变。
- `AgentApiClient` 仅补读已有采购payload的attemptNumber和标准HTTP Date响应元数据;不添加服务端字段或API。Date缺失清空样本,不沿用手机时间。
+54 -4
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Business-Rules-and-Glossary
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Business-Rules-and-Glossary.-
wiki_revision: 233b72e9e2415a2456bb8dd27c770df881960db4
synchronized_at: 2026-10-08T01:42:04Z
wiki_revision: c4870fd01a4569059fc0afc77179d14fbd286384
synchronized_at: 2026-10-08T10:15:21Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -213,7 +213,7 @@ Admin 的「创建时间」范围按 SYB 货运单列表的 `t_stock.created`(
- 浏览器“打开拼多多APP”和系统确认框“打开”属于允许动作。
- 登录失效、验证码、风控、人机验证和找不到唯一控件时失败并给出具体错误。
- Android Agent 到 GoAuto 服务端默认使用 HTTPS。管理员可在明确接受 Device Token、任务内容、设备状态和执行结果被链路监听或篡改的风险后,通过服务端 `GOAUTO_ALLOW_INSECURE_AGENT_HTTP=true` 显式允许全部 `/api/agent/v1/**` 使用 HTTP;该例外不放宽 PDD、SYB、OCR 或其他第三方服务约束。
- Android Agent 端不使用 OCR/VLM 兜底,不保存原始控件树或截图。采集阶段不猜测缺失数据。
- Android Agent 端不使用 OCR/VLM 兜底;普通采集不保存原始控件树或截图,采集阶段不猜测缺失数据。采购失败私有现场诊断是 #364 的限定例外,见本页对应节;历史各节的结构化日志/普通接口禁存规则保持不变。
- 服务端顺云宝(SYB)登录例外:允许调用配置的线上 OCR 服务识别登录验证码(见 [#48](https://git.ilapage.cn/OPC/goauto/issues/48))。验证码图片会离开本项目发送到该服务,更换服务地址前必须重新评估。此例外只适用于 SYB 登录,不扩大到 Agent 端或任何 PDD 相关流程。
- 采购阶段的规格匹配由服务端决策(见 [#46](https://git.ilapage.cn/OPC/goauto/issues/46)、[#62](https://git.ilapage.cn/OPC/goauto/issues/62)):Agent 本地不得自行猜测规格或点击相近候选,只执行服务端下发的精确规格;AI Provider 只有一个 OpenAI-compatible 配置,由管理员维护。根据 #62 已确认的内部部署例外,API Key 明文保存在专用设置表,并只向管理员设置接口返回以便查看和替换;它仍不得写入代码、日志、工单、Wiki、任务快照、采购员接口或 Android 接口。Provider Base URL 不限制内网或公网,支持 HTTP/HTTPS;HTTP 不加密传输中的 API Key,生产环境建议 HTTPS。
- 采购规则的 `openSpecPanel` 默认不写死页面文字。Agent 只在已由页面语义确认的规格入口或底部购买入口中选择;规则若提供 `textAliases`,只能进一步缩小这些安全候选,不能把任意同名页面文字变成可点击入口。
@@ -670,10 +670,21 @@ Web 唯一展示位置为“采集采购 → SYB 同步记录”:列表状态
实现分支 fix/325-order-result,2026-09-19;未部署、未真机验收。下单点击及不可逆边界不改。已知 PayActivity 允许一次原有 Back,随后从3次放宽为25次200ms采样(约5秒等待,不含页面捕获耗时),持续无证据仍为 PURCHASE_ORDER_PAYMENT_REPEATED。微信恢复、系统选择器、空窗口和陌生应用的既有边界保留。
过渡阶段最多60次采样。首次识别到待付款证据后单独分配30次采样预算,不被之前绕路消耗,不因文字反复出现重置;核单总采样上限90次。缺少唯一订单号或时间时立即向上滑动读取下方内容,最多4次、手势400ms、每次后等500ms;读全立即停止,已有完整字段不滑动。该待付款读取分支不点击任何控件,也不点击付款。纯支付页不使用该滑动分支;出现可读待付款证据优先于复用的 Activity 名称。按采样间隔约18秒加有限手势/额外等待,实际耗时还含capture等调用;未改变2分钟任务租约或5分钟唤醒锁,也不宣称新增了执行器总体墙钟超时机制。
原 #325 过渡阶段最多60次采样。首次识别到待付款证据后单独分配30次采样预算,不被之前绕路消耗,不因文字反复出现重置;原核单总采样上限90次。#365 工单分支增加下节所述成功支付页返回后的定时观察例外,不能再把90次视为该例外路径的总上限。缺少唯一订单号或时间时立即向上滑动读取下方内容,最多4次、手势400ms、每次后等500ms;读全立即停止,已有完整字段不滑动。该待付款读取分支不点击任何控件,也不点击付款。纯支付页不使用该滑动分支;出现可读待付款证据优先于复用的 Activity 名称。按采样间隔约18秒加有限手势/额外等待,实际耗时还含capture等调用;未改变2分钟任务租约或5分钟唤醒锁,也不宣称新增了执行器总体墙钟超时机制。
应付金额从同一订单的可见标签集合中读取,兼容“应付:,13元”等标点;不跨无关联节点拼接,不读拼单价、优惠或实付。父子重复同金额去重,多值/缺失/无效/溢出省略,不因金额失败丢弃订单号与时间。仅存Admin,不推断支付、不改SYB金额、不修改地址行为。历史回填及界面语义未在本单统一,详见API契约#325补充。
## 支付页安全返回后的核单观察(#365)
实现绑定 `37714d39b5ac8ff720cfa1d0d2609f9a8af3fbd9`,工单分支已实现,未合并 main、未安装或发布;自动化验证不代表真机核单成功率已改善。仅 Android 变化,Admin、Server、数据库和上传状态契约不改。
- 只有识别到 PDD 支付页且既有一次 Back 成功后,才记录单调时钟起点。在尚未取得订单/待付款上下文时,允许观察至该起点后约30秒,不因反复采样或上下文缺失重置;不能用 paymentPageObserved 代替成功返回事实。
- 无成功返回,或在原60次内已取得普通订单上下文的路径,保持原预算。返回失败、持续支付页25次、空窗口15次、微信恢复失败和未授权应用等独立失败保持,不保证每种失败等满30秒。
- 原60次之后的新增观察只采样,不因迟到的详情入口、选择器、微信页面新增点击、返回、拉前台或滑动。延长期出现非待付款不完整订单上下文,可只读等待迟到字段至同一期限;完整证据立即结束。
- 首次出现待付款证据后,仍使用原独立30次采样及最多4次有界读取滑动;不新增该分支额度。该分支有自己的预算,30秒不是整个核单方法的全局时限。
- 固定期限检查包含采样耗时与既有暂停,单次 capture 本身不能被此机制中断;不承诺严格墙钟总耗时。不增加采样硬上限来提前替代30秒期限。
- 仍无完整证据时沿用已有失败原因与 order_result_unknown 处理,不自动补录、重试采购或再次创建订单;永久禁止付款。这只是对加载慢的有界缓解,不是对历史未知原因的根因修复。
## 采购订单资料完整性及简化单号回填(#326)
用户2026-09-19确认内部系统简化流程,原型v1通过。实现3a2472d,尚未发布或真实SYB验收。
@@ -835,3 +846,42 @@ Android 0.9.64 / versionCode 77,源码 `6550b9f`(分支实现,尚未安装
- 正常完成或预算退出只保存最后已确定处理/跳过的位置;页中提前退出不跳到预取末尾。确实消费完末页才回绕0;下轮/进程重启从最近已终结且有有效游标的运行续扫,NULL不是有效游标,0是有效回绕点。
- 单运行所有权在分页续期、领取、Provider调用及保存映射时检查。失租旧运行不能继续领取或覆盖新owner;基础设施错误或失租不提交新游标。
- completed只表示本轮正常结束,处理0件可能合法;scanned为实际检查数,不是预取数或全表数,processed不是成功数,confirmed/unmatched是规格项数。商品变化后可能需要等扫描回绕,不保证固定小时内全部处理。
## 采购失败现场私有诊断(#364,尚未发布)
本节是用户已确认的原始控件树禁存规则限定例外,仅适用于采购 `spec_probe/purchase` 本次失败、结果待核对及有真实上下文的执行阶段异常。普通采集及此前各业务模块的普通日志/结果接口不因此放宽。
- 不采集正常执行的连续帧,不抓成功结果;空探测在 demote 后失败才进入诊断。已知成功结果即使后续本地保存、提示或结果上传异常也不新增失败快照。
- 使用实际已领取/开始的 task/device/attempt UUID/phase/规则快照哈希;无有效归属只留本机固定原因,无效hash如实标为无效,不为诊断伪造事实。前置失败只留未进入执行/无障碍不可用等状态,不把Agent页面当作PDD现场。
- 原失败上传重试只复用原ZIP。进程中断不补拍当前页冒充原现场;已有恢复核单失败可生成首次 `source=recovery` ZIP,记录恢复实际时间。恢复前的API/网络异常不抓,恢复成功不抓,不新增任何恢复点击、下单或任务重试。
- 原始订单/地址节点等可能含个人数据,只存手机私有诊断SQLite和服务端私有数据库,只允许管理员下载。不得写入普通日志、工单、Wiki、SynapBus、普通任务结果或采购员接口;不得保存整屏截图。密码标识为true、缺失或不可读时,内容文字及其编码备份、action label均不保存。
- 每attempt最多保留一份ZIP,已有ZIP不可覆盖;只有无ZIP未截取记录可升级为首次恢复ZIP。以该现场 recordedAt 起保留30天,重复上传不续期;新恢复ZIP采用真实恢复时刻。两端定期清理,手机快照逻辑总量64MiB,淘汰时同时终止上传队列。清理不修改采购结果。
- 管理员采购详情可见完整/部分/未截取/暂无现场数据及安全下载入口;普通采购员、售后、客户端密钥均无原始诊断下载权限。
- 1500ms、5000节点、2MiB ZIP、8MiB展开、128窗口与深度保护是合成测试覆盖的开发边界,未经过代表性真机样本验收;单次系统Binder读取不能被这些前后检查强行中断。未知/部分必须如实显示,不宣称拿到了系统未暴露的节点。
## 图搜采集部分完成的自动关联资格(#368)
实现基线:工单分支 `fix/368-image-search-partial-link` 提交 `15ccab3`(2026-10-08);尚未合并 main 或发布,生产是否启用以发布记录为准。
- 此规则仅作用于 `source=image_search` 的结果后置自动关联。正常 `completed` 沿用原行为,包括 `missing_json=[]`。
- `completed_partial` 仅在 `missing_json` 为可解析、非空字符串数组且每一项精确属于 `reviewCount`、`salesText`、`shopName` 时允许自动关联。三项均为可选描述信息。
- partial 的空值、JSON null、空数组、非法 JSON、非字符串项、空项、未知项、颜色/尺码/价格/不支持维度缺失一律不放宽。不修剪字段名、不按前缀推测。
- 保留原图搜快照、目标 PDD active、`OriginalPDDProductID` 乐观比较;人工改动后的关联不被覆盖。只有实际写入关联并返回 Linked,才进入既有规格同步和匹配流程。
- 采集任务仍为 `completed_partial`,missing 保留,界面仍显示部分完成;关联成功不等于 AI 匹配成功。匹配无结果或不可用沿用原处理,不自动创建采购。
- 不改变普通采集、手动当前页采集、手动关联、价格保护、映射算法、同步后置 hook 的耗时及重放机制。同图多结果沿用原提交顺序和乐观比较,不新增历史筛选、补关联或回退旧商品。
- 验证边界:自动化测试使用隔离 SQLite 与本地模拟 ERP 服务验证实际 SubmitResult、关联及映射落库;未以此宣称 MySQL、真实 AI、真机或线上发布验证。请求在匹配开始后取消时,匹配使用原有脱钩 context 继续;最后 Detail 读取仍使用原请求 context,可能向断开的调用端返回错误,已提交数据不因此回滚。
## Android 本设备最后一批重购(#367)
实现绑定 `5430dc1f64fc0a4d8ef124ada7356e21a975151f`(2026-10-08,工单分支 `feat/367-last-batch-repurchase`);未合并 main、未安装或发布,真机批量采购仍待独立授权验收。
- 采购页搜索栏的“回填”入口替换为“重购”。原回填弹窗、Service 动作和实现保留但不再由该按钮触发;原单条重试、继续采购不改。重购使用原任务的 `/reset`,保留 CG 编号,不使用创建替代任务的 `/retry`。
- 读取本设备近30天全部状态、不继承页面编号/状态筛选;按创建时间倒序、同刻任务ID倒序,从最新记录逐项比较相邻时间,不超过60秒归入同一推算批次。跨50条分页去重,最多200页,结束复核首页;头部或总量变化、日期/页结构异常、查询截断无法证明完整时不启动,不拿部分列表执行。批次时间边界使用独享API客户端的 HTTP Date,不使用手机时钟,缺少有效 Date 拒绝;此轻量方案不保证任意并发删除/归属变动的数据库快照。
- 最后一批没有失败或失败均不可重试时只提示,不回退更早批次。一次确认显示范围、总数、失败/可重购/跳过数量及真实待付款订单风险;系统永不付款。每轮冻结 `failed && retryable` 候选,每条只重置一次,本轮再次失败不重新入队;下次点击重新发现并确认剩余任务。
- 每条前重新检查当前资格、设备身份/Origin、网络、无障碍、新工作与本地执行/结果上传边界;不额外要求已存在完整映射,沿用服务端 unresolved 规格探测资格。明确业务资格拒绝可跳过;环境、规则、鉴权或结果未知停止后续。
- 每条固定 requestId;重置响应不明最多同ID发两次,仍不明确停止,不换UUID或把旧failed认成本次结果。本地短时忙碌且明确未发出请求时最多等待10秒复核;重放pending不是实时状态。后续 attempt 只有原执行器记录到连续探测/重匹配完成→正式采购启动的证据链才属于本轮,外部同任务另起attempt停止编排。
- Service 独立串行后台调度观察,真正领取、执行、上传仍由原执行器和租约/任务锁负责。终态且执行锁、活跃记录和Outbox均收尾后才继续。检测新采集或采购工作停止剩余,本轮当前task本身不算新工作。
- 页面和通知栏“停止重购”只停止后续,已提交/执行的任务沿用原流程;切Tab、切PDD、界面重建不中断。单条单调时钟等待上限15分钟,超时只停止编排,不取消任务、不重置或再次下单。进程死亡/服务重建不恢复整轮,原单任务恢复不改。
- 本轮摘要与最小attempt关联仅在内存,不新增地址/树采集或数据库。接口、服务端、Web、权限及 #364 诊断契约不变。自动化回归和APK构建通过不代表真机页面/批量下单已验收。
+14 -2
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Local-Development-and-Verification
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Local-Development-and-Verification.-
wiki_revision: 03ea269058b50fea2be7842b9c284018987c82d9
synchronized_at: 2026-09-21T08:14:42Z
wiki_revision: 4349298c740c0cb94d8c6bf33423c9c7965ff1c7
synchronized_at: 2026-10-08T07:10:50Z
<!-- gitea-wiki-mirror:end -->
# 本地开发与验证
@@ -350,3 +350,15 @@ node --check popup.js
```
自动化测试只使用合成 DOM 与 Chrome API mock,覆盖列表商品行负向选择、双展开与延迟字段、解析/冲突、启动互斥、停止、错误终态、扫描延迟增长、详情恢复、提交恢复、冻结配置、超时和可重试项。真实 PDD 浏览器点击、扩展安装和真实 Admin 上传不属于自动化验证,必须取得独立授权并在结果中明确区分。
## 采购失败现场诊断验证(#364)
实现 `4581ee5` 的合成验证不连接PDD、不创建订单、不付款、不读取真实个人数据。安装、真实现场抓取和上线须另行授权。
- Android:`cd android; .\\gradlew.bat test assembleDebug`;重点类为 FailureSnapshotExporterTest、FailureSnapshotCaptureTest、FailureSnapshotPolicyTest、FailureSnapshotUploadTest、FailureSnapshotRepositoryTest、AgentDiagnosticStoreMigrationTest。旧结构化诊断实际无障碍回调到Android SQLite的真机闭环仍须另验,不能用JVM测试冒称真机问题已解决。
- 跨端:仅测试时设置 `GOAUTO_DIAGNOSTIC_FIXTURE_DIR` 指向开发构建输出目录,运行 Android `FailureSnapshotExporterTest` 生成纯合成 `manifest.json/archive.zip`;保持同一环境目录后在 `server/` 执行 `go test ./app/goauto/purchase -run TestFailureSnapshotAndroidExporterContract -count=1`。这验证真实Android导出器生成的字节被Go校验器接受;未设置变量时该测试明确skip。禁止以真实下载ZIP替代该合成fixture,输出不提交Git。
- Server:`go test ./app/goauto/purchase ./app/goauto/access ./app/goauto/migrations ./common/middleware ./cmd/migrate/migration/version-local ./cmd/api`;覆盖所有权、成功/待执行attempt拒绝、终态补传、幂等/恢复升级、密码内容排除、ZIP/XML/HTTP容量、日志排除及空闲清理。
- Web:构建后本地preview,使用 `PLAYWRIGHT_TEST_BASE_URL=http://localhost:<端口>`(合成cookie域为localhost),执行 `pnpm exec playwright test tests/e2e/purchase-failure-snapshots.spec.ts tests/e2e/purchase-order-writeback.spec.ts --workers=1`;普通采购员角色为 `purchaser`。
- 迁移:`1791400000000_purchase_failure_snapshot.go` 仅追加私有表与版本记录,提供 `MigratePurchaseFailureSnapshot` 幂等入口;专用API依赖既有启动权限对账。独立测试 `TestFailureSnapshotAuthorizedLocalMySQL` 须获得本地初始化/权限写入授权后显式注入 `GOAUTO_364_LOCAL_MYSQL_DSN`;硬限制本机 `127.0.0.1:3308/goauto` 且采购任务为空。它执行追加迁移、完整既有API/采购员权限对账,并以事务回滚的合成数据验证64KiB manifest/2MiB BLOB回读与attempt唯一。不是只读测试;不得对线上或已有业务库运行,不输出DSN。
- 服务维护:Server清理启动立即运行并每小时运行;Android前台服务启动及每60秒维护,无新任务也清理。无需新增定时任务或开关。通过管理员专用下载路由取得ZIP,禁止把私有诊断表或下载目录暴露为静态资源。
+24 -2
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Troubleshooting
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Troubleshooting
wiki_revision: ac3a0b74704f398cec54149267089c87c8375a3e
synchronized_at: 2026-10-06T09:50:33Z
wiki_revision: fee37efc79b644ecfa3237283dd45f0a09796f44
synchronized_at: 2026-10-08T03:25:33Z
<!-- gitea-wiki-mirror:end -->
# 故障排查
@@ -114,3 +114,25 @@ adb -s <serial> shell run-as cn.ilapage.goauto.agent sqlite3 -readonly databases
- 保留现有加载、错误提示、取消和旧请求隔离逻辑,不增加自动重试。慢请求在 10~60 秒间完成时不再被原 10 秒客户端预算提前中止;超过 60 秒仍会超时,上游更短的超时也可能先终止请求。
- 此调整不优化后端执行速度。处理阶段筛选当前先加载候选并计算阶段、后分页;不选店铺且采购类型为全部时,候选可能很大。遇到持续慢查询,应另行分析候选预筛选与数据库执行计划,不能据此认为延长前端预算已解决后端性能问题。
- 只需发布包含该提交的 Web 资源即可生效,不要求数据库迁移、Android 安装或后端参数变更;发布仍需人工授权。
## Android 地址编辑页控件就绪等待(#366,环节②)
实现绑定 `7fdfe04658d16a05ebcb016ee964a7263eb74802`,位于独立工单分支,未合并 main、未装机或发布;合成测试与 APK 构建结果见 #366 工单,不代表真机采购验收。只修改点击“修改”后等待详细地址输入框就绪的环节;地址列表识别(①)仍缺真实单/多地址列表证据,保存退出(③)、返回与最终复核(④)不改。
- 标题出现不再立即触发输入框缺失失败。在“详细地址”标签的既有同排区域,统计可见 EditText 的 structural 数量(包括空值/禁用)及其 enabled、实际 text 非空且未判为 hint 的子集 ready 数量。只有 structural=1 且 ready=1 才继续,读取的地址与就绪判定来自同一帧;后续 inputFresh 仍重新定位且只尝试一次。
- 原地址只读取同帧实际 text.trim(),不使用 contentDescription 补空。API 26+ 捕获内存 hintText / showingHintText;showingHintText=true 或 text.trim() 等于非空 hintText.trim() 时不就绪,继续等待。全局 label 和其他调用方的语义保持不变,这两个新增元数据不落盘、不上报、不记日志。
- API <26 或应用未正确提供 hint 元数据时,不能完全区分非空 text 是提示还是实际值;仅凭此修复不能保证所有设备/页面的提示文字均被识别,不使用提示词猜测。
- 沿用单轮最多 50 次采样、原 200ms 暂停及点击后的既有暂停。不再叠加标题等待与控件等待,不设置“三次多候选即失败”;采样与解析另有耗时,不能将其表述为严格 10 秒墙钟超时。既有安全异常仍可提前终止。
- 等待超时使用现有错误码:从未观察到详细地址标题为 PURCHASE_ADDRESS_EDIT_TIMEOUT;曾见标题但候选未就绪/不唯一为 PURCHASE_ADDRESS_UPDATE_FAILED。titleSeen 跨帧保留,因此最后一帧空树不会抹掉此前的标题证据。
- 诊断仅含固定 stage=address_editor_ready、reason 分类以及 titleSeen、structural、ready 标量,不含地址、收货人、电话或节点文本。具体原因以实现和测试中的固定分类为准;这不是新增 SQLite 字段或上传接口。
- 收货人/电话不能作为备用目标;区域重叠造成歧义时不输入、不保存。无额外点击、滑动、返回、保存或下单重试,正常单次动作路径保持。
- 此修复不能证明历史失败均因慢加载,也不解决保存地址后返回超时。识别①不能仅凭“不是规格面板+无提交按钮”推断已进入地址列表:两项都依赖同一个面板解析结果。
## 支付页返回后核单仍缺少证据(#365)
实现绑定 `37714d39b5ac8ff720cfa1d0d2609f9a8af3fbd9`(工单分支,未合并、安装或发布)。成功执行既有一次支付页安全返回后,在无订单上下文阶段以固定单调时钟起点观察约30秒;原预算后的新增观察不增加页面动作,待付款分支仍沿用独立读取预算。
- 先确认运行版本是否包含此提交,再区分失败码:持续支付页、空窗口、微信恢复和未授权应用等独立条件可提前结束,并非所有失败都等待30秒。
- 完整订单证据出现就结束;超时保留原订单结果未知语义,不能因为等待更久就把任务改为可重试失败或自动重下单。
- 固定期限从 Back 成功时起算,不是从提交订单或进入核单函数起算,也不会因新样本重置;capture 阻塞不能被该检查中断,待付款分支拥有独立预算。
- 不因本次延长断言历史问题就是加载慢。延长期出现必须点击才能展开的入口仍不会新增点击;页面识别/挽留弹窗等原因需要真实诊断证据另行分析。#364 的失败现场诊断不属于本单实现。
+50 -2
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Android-Agent-API-Contract
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Android-Agent-API-Contract.-
wiki_revision: 640da0a86bf1057d418dbeb062c07a84cb5b1d8e
synchronized_at: 2026-10-08T01:42:56Z
wiki_revision: 2102252a3f0ecb646b49941cc603423abb76ca2c
synchronized_at: 2026-10-08T07:11:01Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -641,6 +641,17 @@ Agent 主动提交 `order_result_unknown` 时保持订单号和下单时间为
| `PURCHASE_ORDER_RESULT_UNKNOWN` | 无法确认订单是否创建,请人工检查 |
| `PURCHASE_PAYMENT_FORBIDDEN` | 系统禁止自动付款 |
### 地址编辑页初始等待诊断(#366,环节②)
实现绑定 `7fdfe04658d16a05ebcb016ee964a7263eb74802`(工单分支,尚未合并 main 或发布)。本修订只细化 Android 点击“修改”后的输入框等待及错误说明,不增加 HTTP 字段、数据库字段或错误码,不改变任务结果提交、设备/任务/规则关联和保存后的最终复核。
- 一个现有 50 次采样预算内,只有详细地址区域可见 EditText 的结构候选数为 1,且其中 enabled、实际 text 非空并排除明确 hint 的就绪候选数也为 1,才允许后续既有单次输入;结构计数包括空值和禁用候选。
- ready 和原地址不使用 contentDescription 补空;showingHintText=true 或实际 text.trim() 等于非空 hintText.trim() 时排除。hintText / showingHintText 仅为 API 26+ 的内存节点元数据,低版本为 null,不新增持久化或上传字段,不改变全局 label。应用缺失/错误的 hint 元数据或 API <26 时无法完全区分提示与实际值。
- 超时从未观察到“详细地址”标题时沿用 `PURCHASE_ADDRESS_EDIT_TIMEOUT`;曾见标题但输入框缺失、为空、仅显示 hint、禁用或存在歧义时沿用 `PURCHASE_ADDRESS_UPDATE_FAILED`。
- 此等待失败的 `errorMessage` 可附固定诊断 `stage=address_editor_ready;reason=<固定分类>;titleSeen=<布尔>;structural=<数量>;ready=<数量>`。reason 为 `title_missing`、`editor_missing`、`editor_ambiguous`、`editor_disabled`、`editor_empty` 或 `editor_hint`;titleSeen 累计保留,数量取最后采样帧,不包含地址值、收货人、电话及节点文本。
- 既有页面安全异常优先失败,不必耗尽预算;`inputFresh` 失败仍不重试。其它使用 `PURCHASE_ADDRESS_UPDATE_FAILED` 的路径保持原义,不要求它们附本段诊断。
- ①地址列表识别仍待真实场景证据,③保存退出、④返回与最终复核不改;本段不代表整单完成或真机验收。
## Agent 当前设备任务历史(#90)
四个只读接口统一使用设备注册所得的 Device Token,只返回该 Token 对应设备最近 30 天内的任务;设备 A 查询设备 B 的任务时按不存在处理,不泄露任务是否存在。
@@ -1482,3 +1493,40 @@ Web 输入去重后一个值提交旧标量、多个值提交重复集合键,
- `stopReason`:旧记录默认空字符串;完成原因是`batch_limit`、`scan_budget`、`time_budget`、`end_of_scan`、`lease_lost`或`error`。失租旧进程不能为填此字段越权更新;合法回收路径标记lease_lost。
- `scannedCount`改为实际检查的候选数;SQL已过滤的空档案及预取未检查项不计入。eligibleCount为Go资格通过数,processedCount为实际领取处理数;confirmedCount/unmatchedCount仍为规格项数,不能据此直接混算商品成功率。
- 单轮处理默认20、每页200、实际扫描上限2000、整轮预算10分钟。正常0处理仍可completed,预算退出有持久游标;错误/失租不提交新游标。
## 采购失败现场诊断 v1(#364,实现 4581ee5,2026-10-08)
本节契约在 `4581ee5` 实现,后续合并记录见 #364;尚未发布或完成真机验收。只覆盖采购spec_probe/purchase的本次失败/结果待核对,不修改正常capture、采购结果/不可逆状态;成功结果后网络/提示异常不抓取。普通采集不纳入。每attempt UUID最多一份ZIP;重启不能补拍当前页面冒充原现场,恢复核单现场必须source=recovery。
### 专用接口
- POST `/api/agent/v1/purchase-tasks/{taskId}/attempts/{attemptId}/failure-snapshot`:Device Token鉴权及现有Agent传输策略。流式multipart,`metadata` UTF-8 JSON(≤64KiB),`archive` 可选ZIP(≤2MiB);不得写临时原始文件。验证attempt持久化的task/device/phase,不依赖task当前设备或running状态,终态允许异步补传。响应沿用Agent JSON envelope,data含taskAttemptId/status/replayed。
- GET `/api/admin/v1/purchase-tasks/{taskId}/failure-snapshots`:仅管理员,返回`{code:200,data:{items:[...]}}`;items仅attemptId/phase/status/source/errorCode/agentVersion/capturedAt/recordedAt/expiresAt/partial/reasons/downloadAvailable/zipSize等安全标量,不包含窗口标题、节点或manifest原文。
- GET `/api/admin/v1/purchase-tasks/{taskId}/attempts/{attemptId}/failure-snapshot/download`:仅管理员,附件ZIP,Content-Type application/zip、Cache-Control no-store、nosniff,服务端生成安全文件名。无快照/过期不可下载,普通采购员/API Key及普通Agent业务接口不得读取。不得在线渲染XML。
### metadata / ZIP
schemaVersion=1、attributeVersion=1;taskId/deviceId正整数、taskAttemptId UUID、phase为spec_probe或purchase;ruleSnapshotHash为有效SHA256或null,ruleSnapshotHashValid明确标记;有效时必须与attempt快照hash相同,无效时仅not_captured并记录rule_hash_invalid,不伪造hash。errorCode为有界代码,agentVersion为有界版本;recordedAt/capturedAt为UTC RFC3339,未截取capturedAt=null。source为execution/recovery;status为complete/partial/not_captured;reasons固定代码数组;windows数组含id/fileName/status及可获取的窗口属性。窗口标题等实际文本只存私有诊断内容,不出现在Admin摘要。
ZIP含manifest.json(与metadata语义一致)和每个可取得root窗口的window-<id>.xml,每个XML仅一个hierarchy根,禁止DTD/外部实体/路径穿越/重复条目;保留系统原顺序及不可见节点。窗口缺失/属性失败/节点数/字节数/耗时超限明确partial且仍可解析。password节点所有可能承载内容的文字字段均省略(text/contentDescription/hint/stateDescription/tooltip/action label等);不反射任意extras。标准UIAutomator属性名,扩展属性合法;XML非法字符采用显式可逆编码,不能丢弃。schema区分空值、不支持和读取失败。
未截取时只上传metadata,无ZIP,不制造空XML;无attempt只保存本机最小原因,不上传虚构归属。服务端解压后总量≤8MiB,不能只相信ZIP声明大小;按白名单条目流式有界验证,异常不回显正文。
### 存储、幂等及清理
Android复用诊断库升级至v4,新独立快照/待上传/实际执行上下文表;旧结构化诊断保持7天/50条,新快照开发容量64MiB和30天独立清理,队列随过期/淘汰终止;无新任务也定期清理。结果上报优先,上传单独线程/持久队列,失败不改变采购结果或阻塞设备释放;重传只复用已存字节。每attempt已有ZIP不得覆盖;仅无ZIP未截取状态允许后续该attempt首次恢复核单ZIP,不能阻止真实恢复现场。
Server追加迁移 `1791400000000_purchase_failure_snapshot.go` 建立purchase_failure_snapshot独立表(ZIP LONGBLOB、私有manifest LONGTEXT、归属与安全摘要,attempt UUID唯一)。同一有效载荷重放返回replayed=true;已有ZIP不同载荷409且保留原件;终态补传有效。按recordedAt起30天,上传不续期,过期补传410供客户端停止;清理启动立即执行并每小时,无任务也执行,下载查询亦拒绝已过期数据。使用既有管理员身份和专用API注册,不给采购员开放权限。
2MiB/8MiB/64MiB是经工单声明的开发测试起点;节点/耗时开发保护暂为5000节点、1500ms,采样前后检查,无法中断系统单次Binder读取的事实须记录;deadline后停止遍历,不异步继续抓下一任务。上述不是代表性真机实测结论,正式现场验收前仍需确认。上线/安装/真机抓取另行授权。
### v1 编码与队列细节
- windows 条目含 id、fileName(可空)、type、layer、title、active、focused、bounds、packageName、activityName、capturedAt、status、reasons、attributeStates;无 root 不制造空 XML。未暴露属性不得猜测。
- XML 节点标准属性含 text/resource-id/class/package/content-desc/checkable/checked/clickable/enabled/focusable/focused/scrollable/long-clickable/password/selected/bounds;扩展 path、child-count、visible-to-user、editable、hint、state-description、tooltip、input-type、max-text-length、drawing-order,collection-* 与 range-* 为扁平字段;node 下的 action 子元素保留 id/label。版本1公开属性名单以 SnapshotXml.attributes 为准,不反射 extras。
- 非值属性使用 `<属性名>-state=null|unsupported|read_error` 区分空值、不支持、读取失败;XML非法代码单元使用 `<属性名>-base64` 保存原始 UTF-16BE 字节的 Base64(包括未配对 surrogate)。换行/回车/Tab 使用数值实体。密码标识为 true、缺失或读取失败时,文字字段、状态/编码备份及 action label 均省略;只有显式 password=false 才允许保存内容,子 action 不得覆盖父节点保护。
- 固定 reasons:rule_hash_invalid、execution_not_entered、accessibility_unavailable、process_interrupted、windows_unavailable、windows_unsupported、window_root_null、window_disappeared、window_read_error、node_read_error、attribute_unsupported、node_limit、time_limit、expanded_size_limit、archive_size_limit、capture_failed。
- 有ZIP的新上传只接受相符的非成功执行 attempt;不能向 pending/成功 attempt 新增失败诊断,已有有效载荷重放仍幂等。manifest 与 multipart metadata 语义相同;ZIP拒绝未知条目、重复路径、加密/未知压缩、CRC错误,XML拒绝DTD和处理指令,除限定XML声明。
- 本地队列绑定 Server Origin 和载荷 fingerprint,切换服务器不向新服务器转交旧ZIP;旧上传响应不删除后来首次恢复ZIP。每60秒维护,网络/408/429/5xx按60秒至1小时退避,410与其他永久4xx停止该队列项。结果Outbox优先,不因设备忙而永久饥饿;上传线程不持有任务互斥、不操作设备。
- 诊断接口不进入通用请求正文日志;私有SQL记录器不输出manifest/BLOB。管理员摘要不包含窗口和节点内容。默认HTTP例外只沿用既有Agent设置,不新增开关;传输私有原始内容时同样存在明文风险,部署须确认现有传输策略。
+14 -2
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Deployment-and-Operations
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Deployment-and-Operations.-
wiki_revision: db99427fa2460989d34d28ef864230a907fc5e6d
synchronized_at: 2026-10-08T01:42:22Z
wiki_revision: 6ca0b35cb1e8058b2930a9a01029822af8b571d2
synchronized_at: 2026-10-08T07:10:52Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -308,3 +308,15 @@ Provider 故障日志只允许记录调用关联 ID、操作类型、耗时、
- 新版启动日志结构检查未见panic/fatal/1146/1054。服务器systemd较旧,读取PID用 `systemctl show goauto -p MainPID` 并解析键值,不使用不支持的 `--value`;journalctl起始时间使用服务器本地格式 `YYYY-MM-DD HH:MM:SS`。
- Nginx配置检查通过,本次无配置变化、不需重启或reload;仅恢复发布目录可读性即恢复前端。真实多轮续扫、末尾回绕和AI实际匹配仍待自然运行验收,健康检查不等于业务效果验收。
- 回滚代码目标 `/home/goauto/releases/20261007-eb7cb6b-363` 保留;重启前核验任务空闲,保留追加列与已经保存的映射,不恢复旧备份覆盖此后业务。
## 采购失败现场诊断部署与保留(#364)
实现绑定 `4581ee5`;本节为新版本部署要求,不表示线上已迁移/发布。#365/#366 为Android局部行为,#366仅②编辑框就绪/hint保护已交付,①地址列表识别仍待现场证据。
1. 先取得目标环境的追加迁移及发布授权,核对唯一待执行版本 `1791400000000_purchase_failure_snapshot.go`,建立独立私有诊断表,再启动配套Server/Web。专用摘要/ZIP下载注册到既有启动权限对账,只允许管理员;对账会维护完整API目录及采购员既有权限,不是只写两条接口。
2. Server接收与权限验证就绪后再安装新Agent。旧Server不支持新诊断接口;不要把“本机保存成功”当作“已上传”。仅合并main不启动服务、不执行线上迁移、不自动安装APK。
3. Server启动立即清理过期诊断,其后每小时维护;Android前台服务启动及每60秒维护。两端默认30天,手机私有诊断逻辑容量64MiB;无需Admin定时任务或新开关,清理不修改采购任务与订单事实。不得把诊断ZIP/数据库映射成静态目录。
4. 管理员从采购详情执行记录下载ZIP;无现场、未截取、partial、上传中/失败应按实际结果区分。排错日志仅固定错误分类,禁止复制ZIP内容到日志、工单、Wiki或消息;分析只摘必要脱敏结构。沿用现有Agent HTTPS/显式HTTP例外,HTTP上传有个人数据明文风险。
5. 代码回滚时保留追加表和已存数据,不降级或删除手机数据库来恢复;回滚到尚不识别schema v4的旧Agent须先单独评估,不承诺可直接覆盖安装。保留期限清理须有仍在运行的相应新版维护组件。
6. 本机换机后的数据库经用户授权初始化于 `127.0.0.1:3308/goauto`,配置仍来自仓库根目录已忽略的config.yaml;已完成baseline迁移及#364幂等、容量、权限验证,未启动业务服务或连接线上。不是将历史3307运行说明套用于所有环境;实际Supervisor目录/发布按目标环境另核对。