mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 只读验收模式、文件发送类型与消息定位补全
- 只读验收:TRACEMEMO_READ_ONLY=1 时跳过消息写入、自动发送与退群提示 - 微信发送新增 file 类型,文档、能力探测与 Reader Skill 同步 - 消息前后窗口按分片定位,补齐 wcdb4 定位与分片测试
This commit is contained in:
1 parent
0edbf60b2e
commit
518a9662a7
25 files changed
+1278
-154
No files matched your search
@@ -259,7 +259,13 @@ describe('GET /api/v1/events/messages', () => {
|
||||
const client = await openSse(handle)
|
||||
|
||||
const status = await client.waitFor((frame) => frame.event === 'status')
|
||||
expect(status.data).toMatchObject({ database: 'ready', filter: 'all', backfill: 'enabled' })
|
||||
expect(status.data).toMatchObject({
|
||||
database: 'ready',
|
||||
monitor: 'unknown',
|
||||
wechat: 'unknown',
|
||||
filter: 'all',
|
||||
backfill: 'enabled'
|
||||
})
|
||||
|
||||
broker.publish(normalize(SESSION_A, '1', '实时消息'))
|
||||
const message = await client.waitFor((frame) => frame.event === 'message')
|
||||
@@ -270,10 +276,9 @@ describe('GET /api/v1/events/messages', () => {
|
||||
text: '实时消息',
|
||||
isSelf: false
|
||||
})
|
||||
expect(decodeMessageRef(String(message.data?.messageRef))).toEqual({
|
||||
conversationId: CONVERSATION_A,
|
||||
messageId: '1'
|
||||
})
|
||||
const ref = decodeMessageRef(String(message.data?.messageRef))
|
||||
expect(ref?.conversationId).toBe(CONVERSATION_A)
|
||||
expect(ref?.messageId).toMatch(/^\d+:1$/)
|
||||
})
|
||||
|
||||
it('同一条消息重复发布只推送一次(事件去重)', async () => {
|
||||
@@ -344,10 +349,9 @@ describe('GET /api/v1/events/messages', () => {
|
||||
})
|
||||
const replayed = await second.waitFor((frame) => frame.event === 'message')
|
||||
expect(replayed.data).toMatchObject({ origin: 'replay', text: 'hello' })
|
||||
expect(decodeMessageRef(String(replayed.data?.messageRef))).toEqual({
|
||||
conversationId: CONVERSATION_A,
|
||||
messageId: '2'
|
||||
})
|
||||
const ref = decodeMessageRef(String(replayed.data?.messageRef))
|
||||
expect(ref?.conversationId).toBe(CONVERSATION_A)
|
||||
expect(ref?.messageId).toMatch(/^\d+:2$/)
|
||||
})
|
||||
|
||||
it('缓冲覆盖不到时先发 gap,再从数据库有界回补(origin=db_backfill)', async () => {
|
||||
@@ -373,6 +377,16 @@ describe('GET /api/v1/events/messages', () => {
|
||||
(frame) => frame.event === 'message' && frame.data?.origin === 'db_backfill'
|
||||
)
|
||||
expect(backfilled.data?.text).toBe('补回来的消息')
|
||||
const report = await client.waitFor((frame) => frame.event === 'backfill')
|
||||
expect(report.data).toMatchObject({
|
||||
requestedConversations: 1,
|
||||
processedConversations: 1,
|
||||
delivered: 1,
|
||||
truncated: false,
|
||||
complete: true,
|
||||
messageTruncated: false,
|
||||
conversationTruncated: false
|
||||
})
|
||||
expect(client.frames.findIndex((f) => f.event === 'gap')).toBeLessThan(
|
||||
client.frames.findIndex((f) => f.event === 'message' && f.data?.origin === 'db_backfill')
|
||||
)
|
||||
|
||||
@@ -64,7 +64,7 @@ function capabilityOf(
|
||||
supported: true,
|
||||
ready: true,
|
||||
status: 'ready',
|
||||
capabilities: { text: true, image: true, voice: true },
|
||||
capabilities: { text: true, image: true, voice: true, file: true },
|
||||
senderStatus: {} as PersonalWechatSendCapability['senderStatus'],
|
||||
message: '可以发送',
|
||||
...overrides
|
||||
@@ -164,6 +164,31 @@ describe('POST /api/v1/wechat/send', () => {
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('type=file 时接受 filePath 与可选 fileName,并按 file 动作投递', async () => {
|
||||
const filePath = path.join(root, '周报.txt')
|
||||
await fs.writeFile(filePath, 'hello')
|
||||
|
||||
const response = await post({
|
||||
to: 'filehelper',
|
||||
type: 'file',
|
||||
filePath,
|
||||
fileName: '周报.txt'
|
||||
})
|
||||
expect(response.status).toBe(200)
|
||||
expect((await response.json()).success).toBe(true)
|
||||
|
||||
const action = lastAction()
|
||||
expect(action.purpose).toBe('api_file')
|
||||
expect(action.content).toEqual({ type: 'file', path: filePath, name: '周报.txt' })
|
||||
})
|
||||
|
||||
it('type=file 缺少 filePath 时返回 400,不进入投递', async () => {
|
||||
const response = await post({ to: 'filehelper', type: 'file' })
|
||||
expect(response.status).toBe(400)
|
||||
expect((await response.json()).errorCode).toBe('INVALID_REQUEST')
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('发送能力未就绪时返回 503', async () => {
|
||||
capability = capabilityOf({
|
||||
ready: false,
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
MessageEventBroker,
|
||||
eventIdFor,
|
||||
parseLastEventId,
|
||||
type MessageBackfillReport,
|
||||
type MessageEventOrigin,
|
||||
type MessageEventRecord,
|
||||
type MessageGap
|
||||
@@ -53,6 +54,7 @@ interface Collected {
|
||||
statuses: unknown[]
|
||||
events: Array<{ event: MessageEventRecord; origin: MessageEventOrigin }>
|
||||
gaps: MessageGap[]
|
||||
backfills: MessageBackfillReport[]
|
||||
order: string[]
|
||||
}
|
||||
|
||||
@@ -61,9 +63,10 @@ function makeSink(): Collected & {
|
||||
onStatus: (status: unknown) => void
|
||||
onEvent: (event: MessageEventRecord, origin: MessageEventOrigin) => void
|
||||
onGap: (gap: MessageGap) => void
|
||||
onBackfill: (report: MessageBackfillReport) => void
|
||||
}
|
||||
} {
|
||||
const collected: Collected = { statuses: [], events: [], gaps: [], order: [] }
|
||||
const collected: Collected = { statuses: [], events: [], gaps: [], backfills: [], order: [] }
|
||||
return {
|
||||
...collected,
|
||||
get statuses() {
|
||||
@@ -75,6 +78,9 @@ function makeSink(): Collected & {
|
||||
get gaps() {
|
||||
return collected.gaps
|
||||
},
|
||||
get backfills() {
|
||||
return collected.backfills
|
||||
},
|
||||
get order() {
|
||||
return collected.order
|
||||
},
|
||||
@@ -90,6 +96,10 @@ function makeSink(): Collected & {
|
||||
onGap: (gap) => {
|
||||
collected.gaps.push(gap)
|
||||
collected.order.push('gap')
|
||||
},
|
||||
onBackfill: (report) => {
|
||||
collected.backfills.push(report)
|
||||
collected.order.push('backfill')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,6 +110,8 @@ function makeBroker(
|
||||
bufferSize?: number
|
||||
dbReady?: boolean
|
||||
reader?: ReturnType<typeof vi.fn>
|
||||
backfillLimit?: number
|
||||
backfillMaxConversations?: number
|
||||
} = {}
|
||||
): MessageEventBroker {
|
||||
return new MessageEventBroker({
|
||||
@@ -108,6 +120,10 @@ function makeBroker(
|
||||
isDatabaseReady: () => options.dbReady !== false,
|
||||
readMessages: options.reader as never,
|
||||
bufferSize: options.bufferSize ?? 10,
|
||||
...(options.backfillLimit !== undefined ? { backfillLimit: options.backfillLimit } : {}),
|
||||
...(options.backfillMaxConversations !== undefined
|
||||
? { backfillMaxConversations: options.backfillMaxConversations }
|
||||
: {}),
|
||||
bufferTtlMs: 10 * 60 * 1000,
|
||||
now: () => NOW
|
||||
})
|
||||
@@ -126,10 +142,26 @@ describe('事件 ID 与 messageRef', () => {
|
||||
expect(record).not.toBeNull()
|
||||
expect(decodeMessageRef(record!.messageRef)).toEqual({
|
||||
conversationId: CONVERSATION,
|
||||
messageId: '100'
|
||||
messageId: '1800000000:100'
|
||||
})
|
||||
})
|
||||
|
||||
it('同一 localId、不同 createTime 是两条消息(复合身份不被 localId 合并)', () => {
|
||||
const broker = makeBroker()
|
||||
const first = broker.publish(
|
||||
normalize(makeRow({ mesLocalID: '7', msgCreateTime: '1800000000' }))
|
||||
)
|
||||
const second = broker.publish(
|
||||
normalize(makeRow({ mesLocalID: '7', msgCreateTime: '1800000100' }))
|
||||
)
|
||||
|
||||
expect(first).not.toBeNull()
|
||||
expect(second).not.toBeNull()
|
||||
expect(first!.id).not.toBe(second!.id)
|
||||
expect(decodeMessageRef(first!.messageRef)!.messageId).toBe('1800000000:7')
|
||||
expect(decodeMessageRef(second!.messageRef)!.messageId).toBe('1800000100:7')
|
||||
})
|
||||
|
||||
it('无法映射会话时不发布,也不伪造 messageRef', () => {
|
||||
const broker = makeBroker()
|
||||
const other = normalizeIncomingMessage('unknown_session', makeRow())
|
||||
@@ -181,7 +213,7 @@ describe('订阅、过滤与重放', () => {
|
||||
expect(sink.events.map((item) => item.origin)).toEqual(['replay'])
|
||||
expect(decodeMessageRef(sink.events[0].event.messageRef)).toEqual({
|
||||
conversationId: CONVERSATION,
|
||||
messageId: '2'
|
||||
messageId: '1800000000:2'
|
||||
})
|
||||
})
|
||||
|
||||
@@ -261,6 +293,66 @@ describe('订阅、过滤与重放', () => {
|
||||
expect(startArg).toBeLessThan(endArg)
|
||||
expect(endArg - startArg).toBeLessThanOrEqual(300)
|
||||
expect(limitArg).toBeLessThanOrEqual(100)
|
||||
expect(sink.backfills).toHaveLength(1)
|
||||
expect(sink.backfills[0]).toMatchObject({
|
||||
truncated: false,
|
||||
complete: true,
|
||||
conversationTruncated: false,
|
||||
messageTruncated: false,
|
||||
processedConversations: 1
|
||||
})
|
||||
})
|
||||
|
||||
it('单会话回补读满 limit 时明确报告 messageTruncated', async () => {
|
||||
const reader = vi.fn(async () => [
|
||||
makeRow({ mesLocalID: '21' }),
|
||||
makeRow({ mesLocalID: '22' })
|
||||
])
|
||||
const broker = makeBroker({ bufferSize: 1, reader, backfillLimit: 2 })
|
||||
for (const id of ['1', '2', '3']) broker.publish(normalize(makeRow({ mesLocalID: id })))
|
||||
|
||||
const sink = makeSink()
|
||||
broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: '1' }, sink.sink)
|
||||
await vi.waitFor(() => expect(sink.backfills.length).toBe(1))
|
||||
|
||||
expect(sink.backfills[0]).toMatchObject({
|
||||
messageTruncated: true,
|
||||
conversationTruncated: false,
|
||||
truncated: true,
|
||||
complete: false,
|
||||
perConversationLimit: 2
|
||||
})
|
||||
})
|
||||
|
||||
it('订阅会话数超过上限时明确报告 conversationTruncated', async () => {
|
||||
const reader = vi.fn(async () => [makeRow({ mesLocalID: '31' })])
|
||||
const broker = new MessageEventBroker({
|
||||
resolveConversationId: (sessionId) => (sessionId === 'A@chatroom' ? 'conv-a' : 'conv-b'),
|
||||
resolveSessionId: (conversationId) => (conversationId === 'conv-a' ? 'A@chatroom' : 'B@chatroom'),
|
||||
isDatabaseReady: () => true,
|
||||
readMessages: reader as never,
|
||||
bufferSize: 1,
|
||||
backfillLimit: 10,
|
||||
backfillMaxConversations: 1,
|
||||
now: () => NOW
|
||||
})
|
||||
for (const id of ['1', '2', '3']) {
|
||||
broker.publish(normalizeIncomingMessage('A@chatroom', makeRow({ mesLocalID: id }))!)
|
||||
}
|
||||
|
||||
const sink = makeSink()
|
||||
broker.subscribe({ conversationIds: ['conv-a', 'conv-b'], lastEventId: '1' }, sink.sink)
|
||||
await vi.waitFor(() => expect(sink.backfills.length).toBe(1))
|
||||
|
||||
expect(sink.backfills[0]).toMatchObject({
|
||||
requestedConversations: 2,
|
||||
processedConversations: 1,
|
||||
conversationTruncated: true,
|
||||
messageTruncated: false,
|
||||
truncated: true,
|
||||
complete: false,
|
||||
maxConversations: 1
|
||||
})
|
||||
})
|
||||
|
||||
it('没有会话过滤时不做回补(无法有界),并如实说明', () => {
|
||||
@@ -371,7 +463,7 @@ describe('多订阅者与 Automation 扇出', () => {
|
||||
|
||||
for (const sink of sinks) {
|
||||
expect(sink.events).toHaveLength(1)
|
||||
expect(sink.events[0].event.id).toBe(eventIdFor(CONVERSATION, 'fanout-1'))
|
||||
expect(sink.events[0].event.id).toBe(eventIdFor(CONVERSATION, '1800000000:fanout-1'))
|
||||
}
|
||||
expect(broker.status().subscribers).toBe(5)
|
||||
})
|
||||
@@ -407,3 +499,73 @@ describe('多订阅者与 Automation 扇出', () => {
|
||||
expect(broker.stats().published).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('运行状态区分', () => {
|
||||
it('database / monitor / wechat 分别报告,不互相冒充', () => {
|
||||
const broker = new MessageEventBroker({
|
||||
resolveConversationId: () => CONVERSATION,
|
||||
isDatabaseReady: () => true,
|
||||
getMonitorState: () => 'running',
|
||||
getWechatProcessState: () => 'stopped',
|
||||
now: () => NOW
|
||||
})
|
||||
|
||||
expect(broker.status()).toMatchObject({
|
||||
database: 'ready',
|
||||
monitor: 'running',
|
||||
wechat: 'stopped'
|
||||
})
|
||||
})
|
||||
|
||||
it('未注入 monitor/wechat 时是 unknown,而不是默认 ready', () => {
|
||||
const broker = new MessageEventBroker({
|
||||
resolveConversationId: () => CONVERSATION,
|
||||
now: () => NOW
|
||||
})
|
||||
expect(broker.status()).toMatchObject({ monitor: 'unknown', wechat: 'unknown' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('重开库缓冲重置', () => {
|
||||
it('resetBuffer 清空缓冲但保留订阅者,新事件序号继续递增', () => {
|
||||
const broker = makeBroker()
|
||||
const sink = makeSink()
|
||||
broker.subscribe({}, sink.sink)
|
||||
broker.publish(normalize(makeRow({ mesLocalID: '1' })))
|
||||
broker.publish(normalize(makeRow({ mesLocalID: '2' })))
|
||||
expect(broker.status()).toMatchObject({ buffered: 2, subscribers: 1 })
|
||||
|
||||
broker.resetBuffer()
|
||||
expect(broker.status()).toMatchObject({
|
||||
buffered: 0,
|
||||
oldestSeq: null,
|
||||
newestSeq: null,
|
||||
subscribers: 1
|
||||
})
|
||||
|
||||
broker.publish(normalize(makeRow({ mesLocalID: '3' })))
|
||||
expect(broker.status().newestSeq).toBe(3)
|
||||
expect(sink.events.map((item) => item.event.seq)).toEqual([1, 2, 3])
|
||||
})
|
||||
})
|
||||
|
||||
describe('回补失败也必须标记不完整', () => {
|
||||
it('会话读取抛错时 complete=false,且不是 truncated 语义', async () => {
|
||||
const reader = vi.fn(async () => {
|
||||
throw new Error('shard unavailable')
|
||||
})
|
||||
const broker = makeBroker({ bufferSize: 1, reader })
|
||||
for (const id of ['1', '2', '3']) broker.publish(normalize(makeRow({ mesLocalID: id })))
|
||||
|
||||
const sink = makeSink()
|
||||
broker.subscribe({ conversationIds: [CONVERSATION], lastEventId: '1' }, sink.sink)
|
||||
await vi.waitFor(() => expect(sink.backfills.length).toBe(1))
|
||||
|
||||
expect(sink.backfills[0]).toMatchObject({
|
||||
failedConversations: 1,
|
||||
truncated: false,
|
||||
complete: false,
|
||||
delivered: 0
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
MessageListenerService,
|
||||
decodeSourcePayload,
|
||||
extractMentionTargets,
|
||||
isMessageIdentityUnsettled,
|
||||
normalizeIncomingMessage,
|
||||
type NormalizedIncomingMessage
|
||||
} from '../../src/main/services/message-listener-service'
|
||||
import { parseMonitorEvent } from '../../src/main/wcdb4-client'
|
||||
@@ -695,3 +697,133 @@ describe('MessageListener · 回读进行中到达的事件', () => {
|
||||
expect(listener.stats().readbacks).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('两阶段写库未稳定行延迟确认', () => {
|
||||
const v2Event = (sessionId: string): ReturnType<typeof parseMonitorEvent> =>
|
||||
parseMonitorEvent(
|
||||
JSON.stringify({ version: 2, kind: 'message_change', session_id: sessionId, table: 'message' })
|
||||
)
|
||||
|
||||
it('发送中中间态(status=1 / 缺 serverId / 缺 sender)暂缓投递,回填后再以 isSelf=true 投递', async () => {
|
||||
let phase = 0
|
||||
const client = {
|
||||
getSessions: vi.fn(() => [{ username: SESSION_DIRECT }]),
|
||||
getMessagesAsync: vi.fn(async () => {
|
||||
phase += 1
|
||||
if (phase === 1) {
|
||||
return [
|
||||
makeMessage({
|
||||
mesLocalID: '501',
|
||||
serverId: '0',
|
||||
mesDes: 1,
|
||||
sender: '',
|
||||
raw: { status: 1 }
|
||||
})
|
||||
]
|
||||
}
|
||||
return [
|
||||
makeMessage({
|
||||
mesLocalID: '501',
|
||||
serverId: '7000000000000000501',
|
||||
mesDes: 0,
|
||||
sender: 'SELF_USER',
|
||||
raw: { status: 2 }
|
||||
})
|
||||
]
|
||||
})
|
||||
} as unknown as Wcdb4Client
|
||||
|
||||
const listener = new MessageListenerService(client, {
|
||||
settleRetryMs: 400,
|
||||
maxSettleWaitMs: 2_000
|
||||
})
|
||||
collect(listener)
|
||||
|
||||
listener.handleNativeChange(v2Event(SESSION_DIRECT))
|
||||
await flush(200)
|
||||
expect(received).toHaveLength(0)
|
||||
|
||||
await flush(450)
|
||||
expect(received).toHaveLength(1)
|
||||
expect(received[0].localId).toBe('501')
|
||||
expect(received[0].isSelf).toBe(true)
|
||||
expect(received[0].serverId).toBe('7000000000000000501')
|
||||
})
|
||||
|
||||
it('超过最大等待时间仍未回填的未稳定行会兜底放行,不会永久丢消息', async () => {
|
||||
const unsettled = makeMessage({
|
||||
mesLocalID: '502',
|
||||
serverId: undefined,
|
||||
mesDes: 1,
|
||||
sender: '',
|
||||
raw: { status: 1 }
|
||||
})
|
||||
const client = makeClient([unsettled], SESSION_DIRECT)
|
||||
const listener = new MessageListenerService(client, {
|
||||
settleRetryMs: 300,
|
||||
maxSettleWaitMs: 900
|
||||
})
|
||||
collect(listener)
|
||||
|
||||
listener.handleNativeChange(v2Event(SESSION_DIRECT))
|
||||
await flush(200)
|
||||
expect(received).toHaveLength(0)
|
||||
|
||||
await flush(1_200)
|
||||
expect(received).toHaveLength(1)
|
||||
expect(received[0].localId).toBe('502')
|
||||
})
|
||||
|
||||
it('正常外部入站消息与系统消息不进入延迟暂存,立即投递', async () => {
|
||||
const incoming = makeMessage({
|
||||
mesLocalID: '503',
|
||||
serverId: '7000000000000000503',
|
||||
mesDes: 1,
|
||||
sender: 'OTHER_USER',
|
||||
raw: { status: 3 }
|
||||
})
|
||||
const systemMsg = makeMessage({
|
||||
mesLocalID: '504',
|
||||
serverId: undefined,
|
||||
mesDes: 1,
|
||||
messageType: '10000',
|
||||
sender: '',
|
||||
raw: {}
|
||||
})
|
||||
const normIncoming = normalizeIncomingMessage(SESSION_DIRECT, incoming)!
|
||||
const normSystem = normalizeIncomingMessage(SESSION_DIRECT, systemMsg)!
|
||||
expect(isMessageIdentityUnsettled(incoming, normIncoming)).toBe(false)
|
||||
expect(isMessageIdentityUnsettled(systemMsg, normSystem)).toBe(false)
|
||||
|
||||
const client = makeClient([incoming, systemMsg], SESSION_DIRECT)
|
||||
const listener = new MessageListenerService(client)
|
||||
collect(listener)
|
||||
|
||||
listener.handleNativeChange(v2Event(SESSION_DIRECT))
|
||||
await flush(200)
|
||||
expect(received.map((m) => m.localId)).toEqual(['503', '504'])
|
||||
expect(listener.stats().readbacks).toBe(1)
|
||||
})
|
||||
|
||||
it('dispose 会取消待执行的未稳定行重试定时器', async () => {
|
||||
const unsettled = makeMessage({
|
||||
mesLocalID: '505',
|
||||
serverId: '0',
|
||||
mesDes: 1,
|
||||
sender: '',
|
||||
raw: { status: 1 }
|
||||
})
|
||||
const client = makeClient([unsettled], SESSION_DIRECT)
|
||||
const listener = new MessageListenerService(client, { settleRetryMs: 400 })
|
||||
collect(listener)
|
||||
|
||||
listener.handleNativeChange(v2Event(SESSION_DIRECT))
|
||||
await flush(200)
|
||||
expect(listener.stats().readbacks).toBe(1)
|
||||
|
||||
listener.dispose()
|
||||
await flush(1_000)
|
||||
expect(listener.stats().readbacks).toBe(1)
|
||||
expect(received).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { sliceMessagesAroundWindow } from '../../src/main/services/messages-around'
|
||||
|
||||
/**
|
||||
* 消息跳转的身份匹配。
|
||||
*
|
||||
* 裸 `localId` 与 `createTime:localId` 都必须支持;后者是 SSE messageRef 的格式。
|
||||
*/
|
||||
describe('sliceMessagesAroundWindow', () => {
|
||||
const messages = [
|
||||
{ id: '7', createTime: 1_795_158_000, text: '前一天' },
|
||||
{ id: '7', createTime: 1_795_158_061, text: '目标' },
|
||||
{ id: '8', createTime: 1_795_158_062, text: '后一条' }
|
||||
]
|
||||
|
||||
it('复合身份同时匹配 createTime 与 localId,选中正确的那一条', () => {
|
||||
const result = sliceMessagesAroundWindow(messages, 'conv', '1795158061:7')
|
||||
expect(result.index).toBe(1)
|
||||
expect(result.window[result.index]).toMatchObject({ text: '目标' })
|
||||
})
|
||||
|
||||
it('只有 localId 时保持旧行为(第一条匹配)', () => {
|
||||
const result = sliceMessagesAroundWindow(messages, 'conv', '7')
|
||||
expect(result.index).toBe(0)
|
||||
})
|
||||
|
||||
it('时间不匹配时不会误选另一条同 localId 的消息', () => {
|
||||
const result = sliceMessagesAroundWindow(messages, 'conv', '1795158999:7')
|
||||
expect(result.index).toBe(-1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,144 @@
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => '/tmp/tracememo-readonly-test' }
|
||||
}))
|
||||
|
||||
import { READ_ONLY_ENV, isReadOnlyMode } from '../../src/main/services/read-only-mode'
|
||||
import { WechatActionGateway } from '../../src/main/services/wechat-action-gateway'
|
||||
import { reconcileMsgInsertRules } from '../../src/main/services/msg-insert-switch-service'
|
||||
import { AutomationService } from '../../src/main/services/automation-service'
|
||||
import { personalWechatSendService } from '../../src/main/services/personal-wechat-send-service'
|
||||
import { wechatLocalExitNoticeService } from '../../src/main/services/wechat-local-exit-notice-service'
|
||||
|
||||
/**
|
||||
* 只读闸门的有效性:不是「复制了 profile」,而是真实写入入口被短路。
|
||||
*/
|
||||
|
||||
const original = process.env[READ_ONLY_ENV]
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env[READ_ONLY_ENV]
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (original === undefined) delete process.env[READ_ONLY_ENV]
|
||||
else process.env[READ_ONLY_ENV] = original
|
||||
})
|
||||
|
||||
describe('isReadOnlyMode', () => {
|
||||
it('默认关闭,只有显式真值才开启', () => {
|
||||
expect(isReadOnlyMode()).toBe(false)
|
||||
for (const value of ['1', 'true', 'YES', 'on']) {
|
||||
process.env[READ_ONLY_ENV] = value
|
||||
expect(isReadOnlyMode()).toBe(true)
|
||||
}
|
||||
for (const value of ['0', 'false', '', 'off']) {
|
||||
process.env[READ_ONLY_ENV] = value
|
||||
expect(isReadOnlyMode()).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('只读模式下的写入入口', () => {
|
||||
it('发送网关直接 blocked,不调用底层 send', async () => {
|
||||
process.env[READ_ONLY_ENV] = '1'
|
||||
const send = vi.fn()
|
||||
const gateway = new WechatActionGateway({
|
||||
getCapability: vi.fn() as never,
|
||||
send: send as never,
|
||||
getUserDataPath: () => path.join(os.tmpdir(), 'tracememo-readonly-test'),
|
||||
now: () => new Date('2026-11-20T00:00:00.000Z'),
|
||||
wait: async () => undefined
|
||||
})
|
||||
|
||||
const result = await gateway.execute({
|
||||
origin: 'http_api',
|
||||
purpose: 'manual_text',
|
||||
triggerType: 'user',
|
||||
recipient: { type: 'contact', id: 'filehelper' },
|
||||
content: { type: 'text', text: '必须被拦住' }
|
||||
})
|
||||
|
||||
expect(result.status).toBe('blocked')
|
||||
expect(result.errorCode).toBe('READ_ONLY_MODE')
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('MsgInsert reconciliation 不 spawn helper,直接返回 READ_ONLY_MODE', async () => {
|
||||
process.env[READ_ONLY_ENV] = '1'
|
||||
const result = await reconcileMsgInsertRules({
|
||||
client: {} as never,
|
||||
monitoredRoomIds: [],
|
||||
myWxid: 'wxid_fixture',
|
||||
databaseKey: 'key_fixture'
|
||||
})
|
||||
expect(result).toEqual({
|
||||
done: false,
|
||||
rooms: 0,
|
||||
written: 0,
|
||||
errorCode: 'READ_ONLY_MODE'
|
||||
})
|
||||
})
|
||||
|
||||
it('Automation 不读规则、不执行定时任务', async () => {
|
||||
process.env[READ_ONLY_ENV] = '1'
|
||||
const listRules = vi.fn(() => [])
|
||||
const ruleStore = { listRules, getRule: vi.fn() } as never
|
||||
const service = new AutomationService({} as never, {
|
||||
ruleStore,
|
||||
executionLog: { record: vi.fn() } as never,
|
||||
runner: {} as never,
|
||||
isListening: () => true
|
||||
})
|
||||
|
||||
await service.handleMessage({
|
||||
sessionId: 'fixture@chatroom',
|
||||
localId: '1',
|
||||
createTime: 1_800_000_000,
|
||||
messageType: 1,
|
||||
isSelf: false,
|
||||
content: '@机器人 日报',
|
||||
isGroup: true,
|
||||
mentionTargets: []
|
||||
})
|
||||
expect(listRules).not.toHaveBeenCalled()
|
||||
|
||||
await expect(
|
||||
service.executeScheduledRule('rule-1', { trigger: 'schedule' })
|
||||
).resolves.toEqual({ executed: false, reason: 'read_only' })
|
||||
})
|
||||
|
||||
it('个人发送服务直连入口(语音 IPC 旁路)同样 blocked', async () => {
|
||||
process.env[READ_ONLY_ENV] = '1'
|
||||
const statusSpy = vi
|
||||
.spyOn(personalWechatSendService, 'getStatus')
|
||||
.mockResolvedValue({ state: 'ready' } as never)
|
||||
|
||||
const result = await personalWechatSendService.send({
|
||||
to: 'filehelper',
|
||||
isGroup: false,
|
||||
type: 'text',
|
||||
text: '必须被拦住'
|
||||
})
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toContain('只读测试模式')
|
||||
statusSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('退群本地提示不写微信库', async () => {
|
||||
process.env[READ_ONLY_ENV] = '1'
|
||||
const result = await wechatLocalExitNoticeService.handleExitEvent({
|
||||
eventId: 'fixture-event',
|
||||
conversationId: 'fixture@chatroom',
|
||||
memberWxid: 'wxid_fixture',
|
||||
memberName: '测试成员',
|
||||
occurredAt: 1_800_000_000
|
||||
} as never)
|
||||
|
||||
expect(result).toMatchObject({ outcome: 'disabled', code: 'READ_ONLY_MODE' })
|
||||
})
|
||||
})
|
||||
@@ -217,4 +217,71 @@ describe('WCDB message shard pagination', () => {
|
||||
)
|
||||
expect(fs.existsSync(path.join(publicRoot, 'TraceMemo'))).toBe(false)
|
||||
})
|
||||
|
||||
it('merges provisional cursor row with settled table-scan row without losing self identity', () => {
|
||||
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
|
||||
accountRoot: '/tmp/fixture-account/wxid_self',
|
||||
wxid: 'wxid_self',
|
||||
displayNameCache: new Map(),
|
||||
avatarCache: new Map()
|
||||
}) as Wcdb4Client
|
||||
|
||||
const normalize = Reflect.get(client, 'normalizeMessage').bind(client) as (
|
||||
row: Record<string, unknown>
|
||||
) => {
|
||||
mesLocalID: string
|
||||
serverId?: string
|
||||
mesDes: number
|
||||
sender: string
|
||||
}
|
||||
const merge = Reflect.get(client, 'mergeMessageRows').bind(client) as (
|
||||
current: ReturnType<typeof normalize>[],
|
||||
recovered: ReturnType<typeof normalize>[]
|
||||
) => ReturnType<typeof normalize>[]
|
||||
|
||||
// cursor 读到旧中间态(无 server_id、无 sender),tableScan 读到已回填的本人发出行。
|
||||
const cursorRow = normalize({
|
||||
local_id: 900,
|
||||
server_id: 0,
|
||||
local_type: 1,
|
||||
create_time: 1800000100,
|
||||
message_content: 'fixture text',
|
||||
computed_is_send: 0,
|
||||
status: 1
|
||||
})
|
||||
const tableRow = normalize({
|
||||
local_id: 900,
|
||||
server_id: '7000000000000000900',
|
||||
local_type: 1,
|
||||
create_time: 1800000100,
|
||||
message_content: 'fixture text',
|
||||
sender_username: 'wxid_self',
|
||||
status: 2
|
||||
})
|
||||
|
||||
const merged = merge([cursorRow], [tableRow])
|
||||
expect(merged).toHaveLength(1)
|
||||
expect(merged[0]).toMatchObject({
|
||||
mesLocalID: '900',
|
||||
serverId: '7000000000000000900',
|
||||
mesDes: 0,
|
||||
sender: 'wxid_self'
|
||||
})
|
||||
})
|
||||
|
||||
it('normalizes mesDes using 0=self and 1=peer semantics when is_send is absent', () => {
|
||||
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
|
||||
accountRoot: '/tmp/fixture-account/wxid_self',
|
||||
wxid: 'wxid_self',
|
||||
displayNameCache: new Map(),
|
||||
avatarCache: new Map()
|
||||
}) as Wcdb4Client
|
||||
|
||||
const normalize = Reflect.get(client, 'normalizeMessage').bind(client) as (
|
||||
row: Record<string, unknown>
|
||||
) => { mesDes: number }
|
||||
|
||||
expect(normalize({ local_id: 1, create_time: 1800000001, mesDes: 0 }).mesDes).toBe(0)
|
||||
expect(normalize({ local_id: 2, create_time: 1800000002, mesDes: 1 }).mesDes).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { selectMessageLocation, type Wcdb4MessageCursor } from '../../src/main/wcdb4-client'
|
||||
|
||||
/**
|
||||
* 跨分片 localId 重复时的定位回归。
|
||||
*
|
||||
* 真实事故:同一会话的 `local_id=31455` 在多个 message_N.db 中命中,
|
||||
* 只带 localId 的 messageRef 被判 `ambiguous_message`;带 create_time 的
|
||||
* 复合身份必须能唯一选中。
|
||||
*/
|
||||
describe('selectMessageLocation', () => {
|
||||
const hits: Wcdb4MessageCursor[] = [
|
||||
{ createTime: 1_795_158_061, localId: 31_455 },
|
||||
{ createTime: 1_795_158_099, localId: 31_455 }
|
||||
]
|
||||
|
||||
it('同 localId 跨分片命中时,create_time 唯一选中', () => {
|
||||
expect(selectMessageLocation(hits, 1_795_158_099)).toEqual({
|
||||
status: 'found',
|
||||
location: { createTime: 1_795_158_099, localId: 31_455 }
|
||||
})
|
||||
})
|
||||
|
||||
it('只给 localId(wantedTime=null)时必须报 ambiguous', () => {
|
||||
expect(selectMessageLocation(hits, null)).toEqual({ status: 'ambiguous' })
|
||||
})
|
||||
|
||||
it('create_time 不匹配时是 not_found,而不是随便挑一条', () => {
|
||||
expect(selectMessageLocation(hits, 1_795_158_000)).toEqual({ status: 'not_found' })
|
||||
})
|
||||
|
||||
it('单分片唯一命中时仍然可以只靠 localId 定位', () => {
|
||||
expect(selectMessageLocation([hits[0]], null)).toEqual({
|
||||
status: 'found',
|
||||
location: hits[0]
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { WECHAT_SEND_TYPES } from '../../src/shared/wechat-send'
|
||||
|
||||
/**
|
||||
* 发送类型的文档一致性守卫。
|
||||
*
|
||||
* 历史缺口:运行时白名单已经有 `file`,但 `docs/agent/api.md` 与 Reader Skill
|
||||
* 的 `type` 字段仍只写 `text/image/voice`,外部调用方会以为不支持文件。
|
||||
*
|
||||
* 这里直接比对「文档里 `type` 那一行」与运行时数组:新增类型但忘了改文档时,
|
||||
* 这两条会红,而不是等到用户试出来。
|
||||
*/
|
||||
|
||||
const ROOT = path.resolve(__dirname, '../..')
|
||||
|
||||
function read(relativePath: string): string {
|
||||
return readFileSync(path.join(ROOT, relativePath), 'utf8')
|
||||
}
|
||||
|
||||
function typeRowOf(markdown: string): string {
|
||||
const row = markdown
|
||||
.split('\n')
|
||||
.find((line) => /^\|\s*`type`\s*\|/.test(line))
|
||||
if (!row) throw new Error('文档里找不到 `type` 字段行')
|
||||
return row
|
||||
}
|
||||
|
||||
describe('WECHAT_SEND_TYPES 与 API 文档同步', () => {
|
||||
it('docs/agent/api.md 的 `type` 行覆盖全部运行时类型', () => {
|
||||
const row = typeRowOf(read('docs/agent/api.md'))
|
||||
for (const type of WECHAT_SEND_TYPES) {
|
||||
expect(row).toContain(`\`${type}\``)
|
||||
}
|
||||
})
|
||||
|
||||
it('Reader Skill 的 `type` 行覆盖全部运行时类型', () => {
|
||||
const row = typeRowOf(read('docs/skill/tracememo-reader/SKILL.md'))
|
||||
for (const type of WECHAT_SEND_TYPES) {
|
||||
expect(row).toContain(`\`${type}\``)
|
||||
}
|
||||
})
|
||||
|
||||
it('仍然包含 file(防止回退)', () => {
|
||||
expect(WECHAT_SEND_TYPES).toContain('file')
|
||||
expect(typeRowOf(read('docs/agent/api.md'))).toContain('`file`')
|
||||
expect(typeRowOf(read('docs/skill/tracememo-reader/SKILL.md'))).toContain('`file`')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user