Merge branch 'develop' of github.com:Wxw-Gu/TraceMemo into develop

This commit is contained in:
Wxw-Gu committed 2026-11-12 11:18:37 +08:00
commit c50f8861a4
5 files changed
+442 -41

No files matched your search

+71 -3
View File
@@ -27,6 +27,8 @@ const fixture = vi.hoisted(() => ({
}
}
],
readMessages: vi.fn(),
syncReadMessages: vi.fn(),
testSend: vi.fn(async () => ({ success: true, status: 'sent' }))
}))
@@ -52,7 +54,8 @@ vi.mock('../../src/main/services/chat-service', () => ({
isReady: () => true,
listContacts: () => fixture.contacts,
listContactsAsync: async () => fixture.contacts,
listMessages: () => fixture.chatlogMessages,
listMessages: fixture.syncReadMessages,
listMessagesAsync: fixture.readMessages,
getGroupSnapshot: () => ({ members: [] }),
listRecentChat: () => [],
resolveMd5: () => fixture.contacts[0]
@@ -120,6 +123,8 @@ describe('Local API authentication', () => {
beforeEach(() => {
fixture.storageAvailable = true
fixture.readMessages.mockReset().mockImplementation(async () => fixture.chatlogMessages)
fixture.syncReadMessages.mockReset().mockImplementation(() => fixture.chatlogMessages)
})
afterEach(async () => {
@@ -135,7 +140,11 @@ describe('Local API authentication', () => {
const health = await fetch(`${baseUrl(handle)}/api/v1/health`)
expect(health.status).toBe(200)
const healthBody = await health.json()
expect(healthBody).toMatchObject({ ok: true, service: 'TraceMemo Reader', version: 'test-version' })
expect(healthBody).toMatchObject({
ok: true,
service: 'TraceMemo Reader',
version: 'test-version'
})
expect(JSON.stringify(healthBody)).not.toMatch(
/token|authorization|wxid|databasePath|provider/i
)
@@ -256,7 +265,10 @@ describe('Local API authentication', () => {
expect((await fetch(path)).status).toBe(401)
const response = await fetch(path, { headers: { Authorization: `Bearer ${VALID_TOKEN}` } })
expect(response.status).toBe(200)
await expect(response.json()).resolves.toMatchObject({ version: 1, tools: { query_messages: { limitMax: 200 } } })
await expect(response.json()).resolves.toMatchObject({
version: 1,
tools: { query_messages: { limitMax: 200 } }
})
})
it.each([
@@ -322,6 +334,62 @@ describe('Local API authentication', () => {
expect(provider).toHaveBeenCalledOnce()
})
it('keeps health responsive while an authenticated chatlog read is pending', async () => {
const handle = await startFixtureServer()
let finishRead!: (messages: typeof fixture.chatlogMessages) => void
let markStarted!: () => void
const started = new Promise<void>((resolve) => {
markStarted = resolve
})
fixture.readMessages.mockImplementationOnce(
() =>
new Promise((resolve) => {
finishRead = resolve
markStarted()
})
)
const pending = fetch(
`${baseUrl(handle)}/api/v1/chatlog?talker=fixture&time=2026-11-10/07:51~2026-11-10/07:56`,
{
headers: {
Authorization: `Bearer ${VALID_TOKEN}`,
'X-Request-Id': 'fixture-reader-pending'
}
}
)
await started
try {
const health = await fetch(`${baseUrl(handle)}/api/v1/health`, {
signal: AbortSignal.timeout(2000)
})
expect(health.status).toBe(200)
expect(fixture.syncReadMessages).not.toHaveBeenCalled()
expect(fixture.readMessages).toHaveBeenCalledWith(
'fixture-md5',
expect.any(Number),
expect.any(Number),
undefined,
'fixture-reader-pending'
)
} finally {
finishRead([])
const response = await pending
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ count: 0, messages: [] })
}
})
it('returns a failed chatlog read as an error instead of an empty success', async () => {
const handle = await startFixtureServer()
fixture.readMessages.mockRejectedValueOnce(new Error('fixture-shard-read-failed'))
const response = await fetch(`${baseUrl(handle)}/api/v1/chatlog?talker=fixture`, {
headers: { Authorization: `Bearer ${VALID_TOKEN}` }
})
expect(response.status).toBe(500)
expect(await response.json()).not.toHaveProperty('messages')
expect(fixture.syncReadMessages).not.toHaveBeenCalled()
})
it('adds media metadata to chatlog while redacting image keys', async () => {
const handle = await startFixtureServer()
const response = await fetch(`${baseUrl(handle)}/api/v1/chatlog?talker=测试联系人`, {
+5 -1
View File
@@ -124,7 +124,11 @@ describe('WCDB message shard pagination', () => {
expect(sql).toContain('n.user_name AS sender_username')
expect(sql).toContain('n.rowid = m.real_sender_id')
expect(sql).toContain('"create_time" <= 1800000000')
expect(sql).toContain('ORDER BY "create_time" DESC LIMIT 20')
// Sync queries keep their established ordering; async pagination adds a
// stable local-id tie break and an explicit first-page offset.
expect(sql).toMatch(
/ORDER BY "create_time" DESC(?:, "local_id" DESC)? LIMIT 20(?: OFFSET 0)?/
)
const isLatestShard = dbPath.endsWith('message_7.db')
return [
{
+253
View File
@@ -0,0 +1,253 @@
import { describe, expect, it, vi, type Mock } from 'vitest'
import { Wcdb4Client, type Wcdb4Message } from '../../src/main/wcdb4-client'
const message = (id: number): Wcdb4Message => ({
mesLocalID: String(id),
serverId: `server-${id}`,
mesDes: 0,
messageType: '1',
msgCreateTime: '150',
msgContent: `fixture-${id}`,
raw: {}
})
function makeClient(overrides: Record<string, unknown> = {}): Wcdb4Client {
return Object.assign(Object.create(Wcdb4Client.prototype), {
wcdbGetMessageTableStats: vi.fn(),
wcdbExecQuery: vi.fn(),
wcdbGetMessages: vi.fn(() => {
throw new Error('unbounded native fallback must not run')
}),
getMessagesByCursorAsync: vi.fn(async () => []),
listMessageStoresAsync: vi.fn(async () => [
{ tableName: 'Msg_fixture', dbPath: 'message_0.db' }
]),
// Native SQL returns normalized synthetic rows here. No real WeChat database is used.
finalizeMessages: vi.fn((_user: string, rows: Wcdb4Message[]) => rows),
...overrides
}) as Wcdb4Client
}
function makeCursorClient(fetch: { code: number; json?: string; hasMore?: number }[]): {
client: Wcdb4Client
read: () => Promise<Wcdb4Message[]>
call: Mock<(fn: unknown, ...args: unknown[]) => Promise<number>>
close: Mock
free: Mock
} {
const open = vi.fn()
const batch = vi.fn()
const close = vi.fn()
const free = vi.fn()
const call = vi.fn(async (fn: unknown, ...args: unknown[]) => {
if (fn === open) {
;(args[6] as [number])[0] = 123
return 0
}
if (fn === batch) {
const next = fetch.shift()!
;(args[2] as [unknown])[0] = next.json === undefined ? null : { json: next.json }
;(args[3] as [number])[0] = next.hasMore || 0
return next.code
}
return 0
})
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
wcdbOpenMessageCursor: open,
wcdbFetchMessageBatch: batch,
wcdbCloseMessageCursor: close,
wcdbFreeString: free,
ensureHandle: () => 1,
callAsyncCode: call,
koffi: { decode: (pointer: { json: string }) => pointer.json },
finalizeMessages: vi.fn((_user: string, rows: Wcdb4Message[]) => rows)
}) as Wcdb4Client
const read = (): Promise<Wcdb4Message[]> =>
Reflect.get(client, 'getMessagesByCursorAsync').call(client, 'fixture', 100, 200)
return { client, read, call, close, free }
}
describe('bounded Reader message reads', () => {
it('accepts an authoritative empty shard query without a full-conversation fallback', async () => {
const query = vi.fn<
(fn: unknown, kind: string, db: string, sql: string) => Promise<Wcdb4Message[]>
>(async () => [])
const client = makeClient({ callJsonAsync: query })
await expect(client.getMessagesAsync('fixture', 100, 200)).resolves.toEqual([])
expect(query).toHaveBeenCalledOnce()
expect(query.mock.calls[0][3]).toContain('"create_time" >= 100 AND "create_time" <= 200')
expect(Reflect.get(client, 'wcdbGetMessages')).not.toHaveBeenCalled()
})
it('reads more than 5,000 rows per shard when no limit was requested', async () => {
const first = Array.from({ length: 5000 }, (_, id) => message(id + 1))
const query = vi
.fn()
.mockResolvedValueOnce(first)
.mockResolvedValueOnce([message(5001)])
const client = makeClient({ callJsonAsync: query })
const result = await client.getMessagesAsync('fixture', 100, 200)
expect(result).toHaveLength(5001)
expect(result.at(-1)?.mesLocalID).toBe('5001')
expect(query.mock.calls[0][3]).toContain(
'ORDER BY "create_time" ASC, "local_id" ASC LIMIT 5000 OFFSET 0'
)
expect(query.mock.calls[1][3]).toContain('LIMIT 5000 OFFSET 5000')
expect(Reflect.get(client, 'wcdbGetMessages')).not.toHaveBeenCalled()
})
it('merges every matching historical store when the native cursor is empty', async () => {
const query = vi
.fn()
.mockResolvedValueOnce([message(1)])
.mockResolvedValueOnce([message(2)])
const client = makeClient({
callJsonAsync: query,
listMessageStoresAsync: vi.fn(async () => [
{ tableName: 'Msg_fixture', dbPath: 'message_0.db' },
{ tableName: 'Msg_fixture', dbPath: 'message_1.db' }
])
})
await expect(client.getMessagesAsync('fixture', 100, 200)).resolves.toHaveLength(2)
})
it('does not publish a partial range when a later shard fails', async () => {
const client = makeClient({
listMessageStoresAsync: vi.fn(async () => [
{ tableName: 'Msg_fixture', dbPath: 'message_0.db' },
{ tableName: 'Msg_fixture', dbPath: 'message_1.db' }
]),
callJsonAsync: vi
.fn()
.mockResolvedValueOnce([message(1)])
.mockRejectedValueOnce(new Error('locked'))
})
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow(
'历史消息分片读取失败'
)
})
it('rejects the complete range if a later SQL page fails', async () => {
const client = makeClient({
callJsonAsync: vi
.fn()
.mockResolvedValueOnce(Array.from({ length: 5000 }, (_, id) => message(id + 1)))
.mockRejectedValueOnce(new Error('second page unavailable'))
})
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow(
'历史消息分片读取失败'
)
})
it('fails closed when canonical shard discovery fails, but permits a missing conversation table', async () => {
const client = makeClient({
getMessageDatabasePaths: vi.fn(() => ['message_0.db']),
callJsonAsync: vi.fn(async () => {
throw new Error('cannot read sqlite_master')
})
})
const discover = Reflect.get(client, 'listFallbackMessageStoresAsync')
await expect(discover.call(client, 'fixture', true)).rejects.toThrow(
'cannot read sqlite_master'
)
// Non-Reader consumers retain their existing tolerant discovery contract.
await expect(discover.call(client, 'fixture')).resolves.toEqual([])
Reflect.set(
client,
'callJsonAsync',
vi.fn(async () => [])
)
await expect(discover.call(client, 'fixture', true)).resolves.toEqual([])
})
it('enables strict shard discovery for a complete Reader range', async () => {
const discover = vi.fn(async () => {
throw new Error('discovery failed')
})
const client = makeClient({ listMessageStoresAsync: discover })
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow(
'无法读取历史消息分片信息'
)
expect(discover).toHaveBeenCalledWith('fixture', true)
})
it('does not treat an unsupported or failed SQL read as a successful empty range', async () => {
const client = makeClient({
callJsonAsync: vi.fn(async () => {
throw new Error('native failure')
})
})
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow()
Reflect.set(client, 'wcdbExecQuery', undefined)
await expect(client.getMessagesAsync('fixture', 100, 200)).rejects.toThrow(
'无法检查历史消息分片'
)
})
it('keeps an explicit newest-message limit instead of paging an unlimited range', async () => {
const query = vi.fn<
(fn: unknown, kind: string, db: string, sql: string) => Promise<Wcdb4Message[]>
>(async () => [message(2)])
const client = makeClient({ callJsonAsync: query })
await expect(client.getMessagesAsync('fixture', 100, 200, { limit: 1 })).resolves.toHaveLength(
1
)
expect(query).toHaveBeenCalledOnce()
expect(query.mock.calls[0][3]).toContain('DESC LIMIT 1 OFFSET 0')
})
it.each([false, true])(
'keeps recall journal opt-in=%s on the async Reader path',
async (enabled) => {
const recovered = { ...message(2), raw: { _wxe_recovered: 1 } }
const journal = vi.fn(async () => [recovered])
const client = makeClient({
recallJournalEnabled: enabled,
callJsonAsync: vi.fn(async () => [message(1)]),
readRecallJournalAsync: journal
})
const result = await client.getMessagesAsync('fixture', 100, 200)
expect(result).toHaveLength(enabled ? 2 : 1)
expect(journal).toHaveBeenCalledTimes(enabled ? 1 : 0)
}
)
it('uses async SQL to read the optional journal with the original time bounds', async () => {
const query = vi.fn(async () => [{ ...message(2), raw: { _wxe_recovered: 1 } }])
const client = makeClient({ callJsonAsync: query })
const rows = await Reflect.get(client, 'readRecallJournalAsync').call(
client,
'fixture',
100,
200
)
expect(rows).toHaveLength(1)
const sql = (query.mock.calls as unknown[][])[0][3]
expect(sql).toContain(`"_wxe_source_table" = 'Msg_fixture'`)
expect(sql).toContain('"create_time" >= 100 AND "create_time" <= 200')
expect(sql).toContain('LIMIT 500')
})
it('distinguishes a completed empty cursor batch from a failed native fetch', async () => {
const valid = makeCursorClient([{ code: 0, json: '[]' }])
await expect(valid.read()).resolves.toEqual([])
expect(valid.free).toHaveBeenCalledOnce()
expect(valid.call).toHaveBeenLastCalledWith(valid.close, 1, 123)
const invalid = makeCursorClient([{ code: 5, json: '[]' }])
await expect(invalid.read()).rejects.toThrow('消息游标读取失败')
expect(invalid.free).toHaveBeenCalledOnce()
expect(invalid.call).toHaveBeenLastCalledWith(invalid.close, 1, 123)
})
it('closes the cursor and releases native output when JSON decoding fails', async () => {
const broken = makeCursorClient([{ code: 0, json: '{' }])
await expect(broken.read()).rejects.toThrow()
expect(broken.free).toHaveBeenCalledOnce()
expect(broken.call).toHaveBeenLastCalledWith(broken.close, 1, 123)
})
})