feat(scan-diag): 补齐一次性发版所需的日志面 - Window焦点/输入法状态入心跳、非正常退出检测、10分钟健康快照、无结束符扫码异常

This commit is contained in:
liufumingren 2026-09-25 01:50:21 +08:00
parent 1f11cc05d2
commit 72cecc8d63
5 changed files with 236 additions and 18 deletions

60
src/core/device-probe.js Normal file
View File

@ -0,0 +1,60 @@
/**
* App 端原生环境探测(仅 APP-PLUS 有效,其它平台返回空对象)
*
* 用途:把"按键能不能到 WebView"的两个决定性条件纳入心跳快照——
* 1. winFocus:Activity/Window 是否仍有焦点。失去焦点时 Android 不会把按键派发到 WebView,
* 表现出来就是"扫码完全没反应"(真机上曾出现过无聚焦元素导致设备不投递按键的情况)。
* 2. imeUp:输入法是否处于激活态。IME 位于 WebView 之前(dispatchKeyEventPreIme),
* 激活时按键会被输入法截获 —— 现场表现为"扫一次后不再接收"。
*
* 注意:Native.js 桥接对象在 service 层不支持点方法调用,实例方法必须用 plus.android.invoke;
* 探测失败一律静默返回,绝不影响业务。
*/
// 结果缓存:看门狗每 2s 调一次,桥接调用不宜过于频繁
const CACHE_MS = 10000
let cached = null
let cachedAt = 0
export function probeAppWindow() {
const now = Date.now()
if (cached && now - cachedAt < CACHE_MS) {
return cached
}
const result = {}
try {
if (
typeof plus === 'undefined' ||
!plus ||
!plus.android ||
typeof plus.android.runtimeMainActivity !== 'function'
) {
cached = result
cachedAt = now
return result
}
const main = plus.android.runtimeMainActivity()
if (!main) {
cached = result
cachedAt = now
return result
}
result.winFocus = !!plus.android.invoke(main, 'hasWindowFocus')
// Context.INPUT_METHOD_SERVICE = "input_method"(字符串直传,避免静态字段访问失败)
const imm = plus.android.invoke(main, 'getSystemService', 'input_method')
if (imm) {
result.imeUp = !!plus.android.invoke(imm, 'isActive')
}
} catch (e) {
// 探测失败静默
}
cached = result
cachedAt = now
return result
}
/** 清空缓存(页面切换/退后台后需要重新探测时调用) */
export function resetAppWindowProbe() {
cached = null
cachedAt = 0
}

View File

@ -327,6 +327,24 @@ function hookDiagSink() {
diag: diagDigest(DIAG_EXTRA_MAX_EVENTS),
},
})
return
}
if (kind === 'anomaly') {
const name = String(payload.name || 'anomaly')
reportClientError({
type: `scan-${name}`,
message: `扫码异常:${name}`,
extra: { anomaly: payload.data || {}, diag: diagDigest(DIAG_EXTRA_MAX_EVENTS) },
})
return
}
if (kind === 'health') {
// 周期健康快照:服务端拿到连续轨迹,能看出"哪一刻开始收不到按键"
reportClientError({
type: 'scan-health',
message: '扫码健康快照',
extra: { health: payload },
})
}
} catch (e) {
// 忽略:上报失败不影响扫码

View File

@ -34,6 +34,8 @@ const KEY_RESUME_GAP_MS = 60 * 1000
const KEY_BURST_GAP_MS = 500
// 心跳定时器迟到判定:实际间隔 > 设定周期 * 该倍数 → 主线程被卡住
const STALL_FACTOR = 2.5
// 服务端健康快照间隔:服务端拿到连续轨迹,而不只是异常点
const REPORT_HEALTH_INTERVAL_MS = 10 * 60 * 1000
const state = {
scope: 'unknown',
@ -53,6 +55,8 @@ const state = {
lastTickAt: 0,
maxTickGapMs: 0,
stallCount: 0,
lastHealthReportAt: 0,
healthReportKeys: 0,
loaded: false,
persistedAt: 0,
persistTimer: null,
@ -290,7 +294,34 @@ export function diagBegin(scope) {
}
state.scope = next
const prev = state.prevCounters
const abnormal = detectPrevAbnormalExit()
push('note', `session-start scope=${next}${prev ? ` 上次运行=${JSON.stringify(prev)}` : ''}`)
// 上次是"确实在用"的会话,且最后一条生命周期不是 onHide/onUnload → 疑似被系统杀掉/崩溃。
// 长跑场景里"用着用着没反应"可能就是应用被回收后重进,这条能直接区分。
if (abnormal && prev && (Number(prev.keys) >= 50 || Number(prev.flushes) >= 1)) {
diagAnomaly('abnormal-exit', abnormal)
}
}
/**
* 上一次运行是否非正常结束(被杀/崩溃):
* 判据是"日志在非收尾状态下停止,且已经静默超过 1 分钟"。
* 不能只看最后一条生命周期:页面切换时旧页 onHide 可能晚于新页 onShow,
* 但那种情况会在毫秒级继续写日志,gapMs 很小,不会命中。
*/
function detectPrevAbnormalExit() {
const newest = state.events[state.events.length - 1]
if (!newest) {
return null
}
if (newest.kind === 'note' && /onHide|onUnload|deactivated/.test(newest.msg)) {
return null
}
const gapMs = Date.now() - newest.t
if (gapMs < 60000) {
return null
}
return { lastEvent: newest.msg, lastKind: newest.kind, gapMs }
}
/** 更新门控快照(会随健康心跳一起落盘,是定位"为何没反应"的核心依据) */
@ -364,6 +395,21 @@ export function diagNote(name, data) {
push('note', String(name || ''), data)
}
/**
* 记录一次"值得服务端知道"的异常(除卡顿/自愈/丢弃之外的自定义异常)。
* 例:abnormal-exit(上次非正常退出)、partial-code-no-terminator(扫码未收到结束符)。
* 有外送上钩子时自动上报(error_type = scan-<name>)。
*/
export function diagAnomaly(name, data, options) {
load()
const key = String(name || 'anomaly')
push('anomaly', key, data)
// report:false 时只写本地日志不外送(用于需要本地限流的场景)
if (!options || options.report !== false) {
emitSink('anomaly', { name: key, data })
}
}
/**
* 设置/更新当前业务上下文(当前任务、期望条码等)。
* 变更时留一条记录:现场看日志时能直接对照“该收到哪个码 / 现在在做什么任务”。
@ -422,6 +468,25 @@ export function diagHeartbeat(options) {
`最近按键=${idleAgo} tick=${tickGap || intervalMs}ms 最大tick=${state.maxTickGapMs}ms 卡顿=${state.stallCount}`,
state.gates
)
// 服务端健康快照:本会话确实收到过按键后,每 10 分钟外送一次,
// 这样"某一刻开始收不到按键"即使无人上报也能在服务端看出来(轨迹而不是只有异常点)
if (state.counters.keys > 0 && now - state.lastHealthReportAt >= REPORT_HEALTH_INTERVAL_MS) {
const keysSinceReport = state.counters.keys - state.healthReportKeys
state.lastHealthReportAt = now
state.healthReportKeys = state.counters.keys
emitSink('health', {
keysSinceReport,
keysTotal: state.counters.keys,
flushes: state.counters.flushes,
drops: state.counters.drops,
heals: state.counters.heals,
lastKeyAgoMs: state.lastKeyAt ? now - state.lastKeyAt : null,
stallCount: state.stallCount,
maxTickGapMs: state.maxTickGapMs,
gates: state.gates,
context: state.context,
})
}
}
/** 立即落盘(页面 onHide/onUnload 时调用,避免节流窗口内丢日志) */

View File

@ -20,8 +20,10 @@ import {
diagHeartbeat,
diagSetGates,
diagNote,
diagAnomaly,
diagPersistNow,
} from './scan-diag'
import { probeAppWindow } from './device-probe'
// 空闲超过该时长后重新锁定 plus.key 实际生效的事件类型。
// 根因:本机实测只投递 keyup,若某次运行时锁被设成 'keydown'(其它来源的合成/注入事件),
@ -31,6 +33,8 @@ const IDLE_LOCK_RESET_MS = 1200
const LISTENER_REARM_IDLE_MS = 10 * 60 * 1000
// 自愈心跳间隔
const SELF_HEAL_INTERVAL_MS = 5000
// "无结束符"异常上报的最小间隔(本地日志仍逐次记录)
const NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS = 10 * 60 * 1000
// Android KeyEvent 符号键映射(KEYCODE_* → 字符)。
// 这些 keyCode 与 ASCII 字母/数字区间重叠,必须优先于 ASCII 分支判断,
@ -71,6 +75,7 @@ let lastAnyKeyAt = 0 // 最近一次按键到达(含被门控丢弃的),用于
let rearmedForIdle = false // 本次空闲是否已重挂过监听(收到按键后复位)
let selfHealTimer = null
let selfHealStartedAt = 0
let lastNoTerminatorAnomalyAt = 0
let plusKeyStyle = null // 'android' | 'ascii'
let plusShiftDown = false
let plusShiftPrev = false
@ -147,6 +152,28 @@ function flush(trigger, source) {
// 记录完整条码与按键数:事后要能回答"这条到底扫到了什么"、"按键是否中途停了"
diagFlush({ scope: receiverScope(), trigger, source, code, length: code.length, durationMs, keys: keyCount, lastKey })
debug('flush-buffer', { code, length: code.length, durationMs, trigger, source })
// 扫码枪通常以 Enter 结尾:没有结束符就靠空闲 flush,优先怀疑按键流在结束符前中断
if (trigger !== 'enter' && keyCount >= 4 && durationMs > 0 && durationMs <= 1500) {
const now = Date.now()
const shouldReport = now - lastNoTerminatorAnomalyAt >= NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS
if (shouldReport) {
lastNoTerminatorAnomalyAt = now
}
diagAnomaly(
'partial-code-no-terminator',
{
scope: receiverScope(),
source,
code,
keys: keyCount,
length: code.length,
durationMs,
lastKey,
reported: shouldReport ? 1 : 0,
},
{ report: shouldReport }
)
}
if (receiver && typeof receiver.onScanCode === 'function') {
try {
@ -546,14 +573,20 @@ export function startScanSelfHeal(intervalMs) {
// 从未收到过按键时以心跳启动时刻为基准,否则"一直收不到"的情况永远不会触发重挂
const now = Date.now()
const idleForRearmMs = now - (lastAnyKeyAt || selfHealStartedAt)
diagSetGates({
scope: receiverScope(),
paused,
receiver: !!receiver,
plusAttached,
eventTypeLock: plusKeyEventType || 'none',
idleSec: lastAnyKeyAt ? Math.round((now - lastAnyKeyAt) / 1000) : 'never',
})
diagSetGates(
Object.assign(
{
scope: receiverScope(),
paused,
receiver: !!receiver,
plusAttached,
eventTypeLock: plusKeyEventType || 'none',
idleSec: lastAnyKeyAt ? Math.round((now - lastAnyKeyAt) / 1000) : 'never',
},
// 真机:Window 焦点 / 输入法状态(决定按键能否到达 WebView),H5 返回空对象
probeAppWindow()
)
)
if (receiver && idleForRearmMs > LISTENER_REARM_IDLE_MS && !rearmedForIdle) {
rearmedForIdle = true
removePlusListener()

View File

@ -333,6 +333,7 @@ import {
} from '@/api/index'
import ScanDiagPanel from '@/components/scan-diag-panel.vue'
import {
diagAnomaly,
diagBegin,
diagDrop,
diagFlush,
@ -344,6 +345,7 @@ import {
diagSetContext,
diagSetGates,
} from '@/core/scan-diag'
import { probeAppWindow } from '@/core/device-probe'
// 扫码枪识别参数(广播扫描:扫码枪为键盘 HID 设备,按键事件全局广播)
// 无回车结束符时:停止输入超过该毫秒数视为一次完整扫码,自动提交
@ -353,6 +355,8 @@ const SCAN_MIN_LENGTH = 2
// 真机 plus 链路的最小码长:运单/商品码都是 8~13 位、工牌 64 位,
// 1~3 字符必然是误触/输入法/枪配置异常,不得当运单提交
const SCAN_CODE_MIN_LENGTH = 4
// "无结束符"异常上报的最小间隔(避免未配置后缀的枪刷爆服务端;本地日志仍逐次记录)
const NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS = 10 * 60 * 1000
// 手动输入识别:相邻按键间隔超过该毫秒数视为手动输入,不自动提交
const SCAN_BURST_MAX_GAP = 100
// Android KeyEvent 符号键映射(KEYCODE_* → 字符)。
@ -425,6 +429,9 @@ export default {
plusKeyLastAt: 0,
// 本次扫码已处理的按键数(诊断用:区分"只收到 1 个字符"与"整个码都收到了")
plusKeyBurstCount: 0,
// 最近一个原始 keyCode(诊断用)+ 无结束符异常上次上报时间
plusKeyLastCode: 0,
lastNoTerminatorAnomalyAt: 0,
// 字母大小写策略:'auto' 跟踪 Shift 键 / 'upper' 全大写 / 'lower' 全小写
// 注意:plus.key 只给 keyCode、无 Shift 状态;仅当扫码枪会额外上报
// Android Shift 键(KEYCODE_SHIFT_LEFT=59 / SHIFT_RIGHT=60)时 'auto' 才能还原大小写。
@ -2043,16 +2050,22 @@ export default {
this.attachGlobalKeyboardListener()
this.ensureScanInputFocus()
this.maybeRearmScanListenersWhenIdle()
diagSetGates({
scope: 'packaging',
pageActive: this.pageActive !== false,
plusListener: !!(this.plusKeyListener || this.plusKeyUpListener),
domListener: !!this.globalKeyListener,
eventTypeLock: this._plusKeyEventType || 'none',
idleSec: this.lastScanKeyArrivedAt
? Math.round((Date.now() - this.lastScanKeyArrivedAt) / 1000)
: 'never',
})
diagSetGates(
Object.assign(
{
scope: 'packaging',
pageActive: this.pageActive !== false,
plusListener: !!(this.plusKeyListener || this.plusKeyUpListener),
domListener: !!this.globalKeyListener,
eventTypeLock: this._plusKeyEventType || 'none',
idleSec: this.lastScanKeyArrivedAt
? Math.round((Date.now() - this.lastScanKeyArrivedAt) / 1000)
: 'never',
},
// 真机:Window 焦点 / 输入法状态(决定按键能否到达 WebView),H5 返回空对象
probeAppWindow()
)
)
diagHeartbeat({ intervalMs: 2000 })
}, 2000)
},
@ -2309,6 +2322,7 @@ export default {
handlePlusKeyEvent(event, type) {
// 先记录「按键到达 JS」这一事实(任何门控之前),用于区分「按键根本没到」与「到了被门控丢掉」
const keyCode = Number((event && event.keyCode) || 0)
this.plusKeyLastCode = keyCode
const gap = this.markScanKeyArrived('plus', { keyCode, type })
// 空闲后重新锁定实际生效的事件类型:自愈「锁错就永久静默」
if (this._plusKeyEventType && gap > SCAN_IDLE_LOCK_RESET_MS) {
@ -2423,8 +2437,36 @@ export default {
}
diagFlush({ trigger, source: 'plus', code, length: code.length, durationMs, keys: keyCount })
console.log('[packaging][scan] plus-buffer trigger =', trigger, 'code =', code, 'keys =', keyCount)
// 扫码枪通常以 Enter 结尾(真机日志 trigger=enter):没有结束符就靠空闲 flush,
// 优先怀疑按键流在结束符前中断(也可能枪未配置后缀,服务端按 10 分钟一条区分)
if (trigger !== 'enter' && keyCount >= 4 && durationMs > 0 && durationMs <= 1500) {
this.reportNoTerminatorScan(code, keyCount, durationMs)
}
this.submitScanCode(code, 'plus')
},
/**
* 扫码没收到结束符就被 flush:记一条 anomaly(本地逐次记录,服务端限流上报)。
* 服务端据此区分"枪无后缀"(常态化)与"按键中途停止投递"(异常)。
*/
reportNoTerminatorScan(code, keys, durationMs) {
const now = Date.now()
const shouldReport = now - (this.lastNoTerminatorAnomalyAt || 0) >= NO_TERMINATOR_ANOMALY_MIN_INTERVAL_MS
if (shouldReport) {
this.lastNoTerminatorAnomalyAt = now
}
diagAnomaly(
'partial-code-no-terminator',
{
code,
keys,
length: code.length,
durationMs,
lastKeyCode: this.plusKeyLastCode || 0,
reported: shouldReport ? 1 : 0,
},
{ report: shouldReport }
)
},
handleHiddenScanFocus() {
if (!this.isPageActive() || !this.enableHiddenInputCapture) {
return