From a799fc1490924253505850e7266ec43f16272511 Mon Sep 17 00:00:00 2001
From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com>
Date: Thu, 15 Oct 2026 15:37:05 +0800
Subject: [PATCH 1/6] =?UTF-8?q?style:=20=E5=BC=95=E7=94=A8=E6=B6=88?=
=?UTF-8?q?=E6=81=AF=E6=96=87=E6=9C=AC=E6=BA=A2=E5=87=BA?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../src/components/RichMessageBubble.tsx | 10 +-
src/renderer/src/styles/chat.scss | 12 ++-
tests/component/quote-bubble.test.tsx | 92 +++++++++++++++++++
.../quoted-text-overflow-contract.test.ts | 76 +++++++++++++++
4 files changed, 186 insertions(+), 4 deletions(-)
create mode 100644 tests/component/quote-bubble.test.tsx
create mode 100644 tests/unit/quoted-text-overflow-contract.test.ts
diff --git a/src/renderer/src/components/RichMessageBubble.tsx b/src/renderer/src/components/RichMessageBubble.tsx
index 1372445..8059283 100644
--- a/src/renderer/src/components/RichMessageBubble.tsx
+++ b/src/renderer/src/components/RichMessageBubble.tsx
@@ -382,12 +382,18 @@ function QuoteBubble({
}): JSX.Element {
const quotedText = data.quotedContent || data.content || '[引用消息]'
const replyText = data.content || data.title || ''
- const quotedSender = data.quotedSender || data.sender || ''
+ // 空白 sender 不渲染:否则只剩下 `.quoted-sender::after` 的冒号,看着像乱码。
+ const quotedSender = String(data.quotedSender || data.sender || '').trim()
const hasQuotedImage = Boolean(data.quotedImageMd5 || data.quotedImageDatName)
+ // 引用框里只放一行(超出用省略号),全文交给 hover 的 title 兜底。
+ const quotedTitle = quotedSender ? `${quotedSender}: ${quotedText}` : quotedText
return (
-
+
{quotedSender &&
{quotedSender}}
{hasQuotedImage ? (
({
+ getCachedLoadedImage: vi.fn(() => undefined),
+ requestImage: vi.fn(() => Promise.resolve({ data: '', isThumbnail: true }))
+}))
+
+import { RichMessageBubble } from '../../src/renderer/src/components/RichMessageBubble'
+
+/** 合成 fixture:正文刻意写长,才能触发引用框的单行截断。名字用仓库通用占位名。 */
+const LONG_QUOTED = [
+ '群发言统计',
+ '以下当前群成员在统计区间内的本地已归档消息中没有发言记录,这段正文刻意写长,用来触发引用框的单行省略',
+ '1. 张三',
+ '2. 李四',
+ '3. 王五'
+].join('\n')
+
+describe('引用气泡 — 截断之外必须能把全文交出来', () => {
+ it('引用框的 title 带完整引用内容,hover 就能看到被省略的部分', () => {
+ const { container } = render(
+
+ )
+
+ const box = container.querySelector('.quoted-message')
+ expect(box).not.toBeNull()
+ const title = box!.getAttribute('title') || ''
+ // 单行省略只是排版,title 里必须是**未截断**的原文
+ expect(title).toContain('1. 张三')
+ expect(title).toContain('3. 王五')
+ expect(title).not.toContain('…')
+ })
+
+ it('有名字时 title 里也带上名字', () => {
+ const { container } = render(
+
+ )
+
+ expect(container.querySelector('.quoted-sender')?.textContent).toBe('张三')
+ expect(container.querySelector('.quoted-message')?.getAttribute('title')).toBe(
+ `张三: ${LONG_QUOTED}`
+ )
+ })
+
+ it('空白 sender 不渲染名字,避免只剩一个冒号', () => {
+ const { container } = render(
+
+ )
+
+ expect(container.querySelector('.quoted-sender')).toBeNull()
+ expect(container.querySelector('.quoted-message')?.getAttribute('title')).toBe('被引用')
+ })
+
+ it('图片引用同样带 title,且不渲染正文 span', () => {
+ const { container } = render(
+
+ )
+
+ const box = container.querySelector('.quoted-message')
+ expect(box).toHaveClass('quoted-message-image')
+ expect(box?.getAttribute('title')).toBe('张三: [图片]')
+ expect(container.querySelector('.quoted-text')).toBeNull()
+ })
+})
diff --git a/tests/unit/quoted-text-overflow-contract.test.ts b/tests/unit/quoted-text-overflow-contract.test.ts
new file mode 100644
index 0000000..a166711
--- /dev/null
+++ b/tests/unit/quoted-text-overflow-contract.test.ts
@@ -0,0 +1,76 @@
+import { readFileSync } from 'fs'
+import { resolve } from 'path'
+import { describe, expect, it } from 'vitest'
+
+/**
+ * 引用内容(`.quoted-text`)的收缩不变量。
+ *
+ * 被引用的正文常见形态是「多行长文本被折成一行」——TraceMemo 自己发进群里的
+ * 发言统计、导出任务日志都是这种。`.quoted-message` 是 flex 容器,
+ * `.quote-message` 把引用框的宽度上限卡在 320px。
+ *
+ * 于是 `.quoted-text` 一旦写着 `flex: 0 0 auto`,它就会按 max-content 参与布局、
+ * 一步都不肯缩:文本先越出引用框,再越出气泡,直接画到聊天背景上。
+ *
+ * jsdom 没有排版引擎,量不出「文本溢出容器」,所以这里锁的是**让溢出不可能发生的
+ * 那几条声明**:可收缩(flex-shrink: 1 + min-width: 0)+ 单行省略。
+ */
+
+const chatStyles = readFileSync(resolve('src/renderer/src/styles/chat.scss'), 'utf8')
+
+/** 去掉注释,避免注释里的示例声明被当成真声明。 */
+const withoutComments = chatStyles.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^[ \t]*\/\/.*$/gm, '')
+
+/** 取出顶层选择器的声明块,返回声明文本。 */
+const ruleBody = (css: string, selector: string): string => {
+ const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ // 必须锚在行首且不留前导空格:`.quoted-message` 既是顶层选择器,
+ // 也是 `.wechat-message-row { &.mine { … } }` 里嵌着的子选择器的后缀。
+ const match = new RegExp(`^${escaped}[ \\t]*\\{`, 'm').exec(css)
+ if (!match) throw new Error(`selector not found: ${selector}`)
+ const open = css.indexOf('{', match.index)
+ const close = css.indexOf('}', open)
+ if (open < 0 || close < 0) throw new Error(`unterminated rule: ${selector}`)
+ return css.slice(open + 1, close)
+}
+
+describe('引用气泡 — 引用内容不得撑破引用框', () => {
+ const body = ruleBody(withoutComments, '.quoted-text')
+
+ it('引用内容必须可收缩', () => {
+ expect(body, 'flex: 0 0 auto 会让长引用按 max-content 撑破引用框').not.toMatch(/flex:\s*0\s+0/)
+ expect(body).toMatch(/flex:\s*0\s+1\s+auto/)
+ expect(body, 'flex 项不给 min-width: 0 就缩不到内容宽度以下').toMatch(/min-width:\s*0/)
+ })
+
+ it('引用内容单行省略,与 `.quoted-sender` 和微信的引用样式一致', () => {
+ expect(body).toMatch(/white-space:\s*nowrap/)
+ expect(body).toMatch(/overflow:\s*hidden/)
+ expect(body).toMatch(/text-overflow:\s*ellipsis/)
+ })
+
+ it('引用框的宽度上限由容器决定,不受引用正文长短影响', () => {
+ expect(ruleBody(withoutComments, '.quote-message')).toMatch(/max-width:\s*[\d.]+px/)
+ expect(ruleBody(withoutComments, '.quoted-message')).toMatch(/max-width:\s*100%/)
+ })
+})
+
+describe('引用气泡 — 名字优先,正文让位', () => {
+ const body = ruleBody(withoutComments, '.quoted-sender')
+
+ it('名字不参与收缩', () => {
+ // flex 项按比例收缩:名字一旦可缩,长引用会把它压成半个字(只剩一个冒号)
+ expect(body, 'flex-shrink: 1 会把名字压成一个字').not.toMatch(/flex:\s*0\s+1/)
+ expect(body).toMatch(/flex:\s*0\s+0/)
+ })
+
+ it('名字有宽度上限,不能把正文挤没', () => {
+ expect(body).toMatch(/max-width:\s*[\d.]+%/)
+ })
+
+ it('名字自带省略号,超长名字自己截断而不是撑破引用框', () => {
+ expect(body).toMatch(/overflow:\s*hidden/)
+ expect(body).toMatch(/text-overflow:\s*ellipsis/)
+ expect(body).toMatch(/white-space:\s*nowrap/)
+ })
+})
From 52c89bf0c743cabaa308186ce71cbad48edc5040 Mon Sep 17 00:00:00 2001
From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com>
Date: Mon, 19 Oct 2026 19:27:39 +0800
Subject: [PATCH 2/6] =?UTF-8?q?feat:=20=E5=9B=BE=E7=89=87=E5=A4=8D?=
=?UTF-8?q?=E5=88=B6=E5=AE=9A=E4=BD=8D=E4=BF=A1=E6=81=AF?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
src/main/index.ts | 81 +++++++++++++++++
src/preload/index.d.ts | 2 +
src/preload/index.ts | 3 +
src/renderer/src/components/ImageBubble.tsx | 35 +++++++
.../src/components/chat/MessageBubble.tsx | 3 +
src/shared/image-debug-info.ts | 58 ++++++++++++
tests/unit/image-debug-info.test.ts | 91 +++++++++++++++++++
7 files changed, 273 insertions(+)
create mode 100644 src/shared/image-debug-info.ts
create mode 100644 tests/unit/image-debug-info.test.ts
diff --git a/src/main/index.ts b/src/main/index.ts
index faae0bf..54642d5 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -91,6 +91,14 @@ import {
testImageDecryption
} from './services/image-decryption-status-service'
import type { SaveImageKeyRequest, TestImageDecryptionRequest } from '../shared/image-decryption'
+import { imageFileQuality } from '../shared/image-quality'
+import {
+ IMAGE_DEBUG_KIND,
+ type ImageDebugInfoRequest,
+ type ImageDebugInfoResult,
+ type ImageDebugPayload,
+ type ImageDebugQuality
+} from '../shared/image-debug-info'
import {
loadSettings,
saveSettings,
@@ -686,6 +694,16 @@ function getLocalMediaMimeType(filePath: string): string {
}
}
+/**
+ * 导出用的三档质量(original/medium/thumbnail)与调试信息的两档命名不同:
+ * 调试侧用 normal 表示「中图」,避免与 ExportImageQuality 的 medium 混淆。
+ */
+function toDebugQuality(quality: 'original' | 'medium' | 'thumbnail'): ImageDebugQuality {
+ if (quality === 'original') return 'original'
+ if (quality === 'thumbnail') return 'thumbnail'
+ return 'normal'
+}
+
function buildImageResponse(
image: DecodedImage,
includeData = false
@@ -1725,6 +1743,69 @@ app.whenReady().then(async () => {
ipcMain.handle('image:getConfig', () => imageKeyConfigService.getConfig())
+ /**
+ * 复制图片调试定位信息。
+ *
+ * 只回答「用户点中的是哪一条消息、当前展示的是哪份本地资源」。
+ * 刻意不返回资源密钥、完整 XML、fileid 或任何 CDN 凭据。
+ */
+ ipcMain.handle(
+ 'image:getDebugInfo', async (_, request: ImageDebugInfoRequest): Promise => {
+ try {
+ const service = ensureImageDecryptService()
+ const self = chat.getSelfAccountInfo()
+ const accountRoot = self?.accountRoot || loadSettings().dbRoot || ''
+ const sessionId = String(request?.sessionId || '').trim() || null
+ const localId =
+ typeof request?.localId === 'number' && Number.isFinite(request.localId)
+ ? String(request.localId)
+ : null
+ const serverId = String(request?.serverId || '').trim() || null
+ const createTimeSeconds =
+ typeof request?.createTime === 'number' && Number.isFinite(request.createTime)
+ ? request.createTime
+ : null
+
+ const md5 = String(request?.imageMd5 || '').trim() || null
+ const datName = String(request?.imageDatName || '').trim() || null
+
+ // 复用真实选图逻辑;找不到就是 null,不根据文件名猜。
+ const filePath = service
+ ? service.findImageFile(md5 || undefined, datName || undefined, { sessionId: sessionId || undefined })
+ : null
+ const quality = filePath ? toDebugQuality(imageFileQuality(filePath)) : 'unknown'
+ const relativePath =
+ filePath && accountRoot && filePath.startsWith(accountRoot)
+ ? path.relative(accountRoot, filePath).split(path.sep).join('/')
+ : null
+ const evidence = filePath ? path.basename(filePath) : null
+
+ const payload: ImageDebugPayload = {
+ kind: IMAGE_DEBUG_KIND,
+ message: {
+ accountId: self?.wxid || null,
+ conversationId: sessionId,
+ localId,
+ serverId,
+ createTimeSeconds
+ },
+ image: { md5, datName },
+ display: {
+ quality,
+ evidence,
+ path: relativePath
+ }
+ }
+ return { success: true, payload }
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ }
+ }
+ }
+ )
+
ipcMain.handle('image:getStatus', async () =>
inspectImageDecryptionStatus(imageKeyConfigService.getConfig())
)
diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts
index dda28e7..c52a41d 100644
--- a/src/preload/index.d.ts
+++ b/src/preload/index.d.ts
@@ -39,6 +39,7 @@ import type {
SaveImageKeyRequest,
TestImageDecryptionRequest
} from '../shared/image-decryption'
+import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
import type {
AIChatRequestOptions,
AiSearchExternalAuthorizationRequest,
@@ -458,6 +459,7 @@ declare global {
isThumb?: boolean
filePath?: string
}>
+ getImageDebugInfo: (request: ImageDebugInfoRequest) => Promise
getVideo: (
hashes: string[],
options?: {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index c660d18..e37ebca 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -83,6 +83,7 @@ import type {
import type { CacheClearScope, CacheSummary } from '../shared/cache'
import type { ExportRequest, ExportJobProgress } from '../shared/export'
import type { ImageDecoderSelectionResult, ImageDecoderStatus } from '../shared/image-decryption'
+import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
import type { AccountDiscoveryResult } from '../shared/database-key'
import type {
VoiceBatchConversationSummary,
@@ -394,6 +395,8 @@ const api = {
includeData?: boolean
}
) => ipcRenderer.invoke('db:getImage', imageMd5, imageDatNameOrThumb, sessionId, options),
+ getImageDebugInfo: (request: ImageDebugInfoRequest): Promise =>
+ ipcRenderer.invoke('image:getDebugInfo', request),
getVideo: (
hashes: string[],
options?: {
diff --git a/src/renderer/src/components/ImageBubble.tsx b/src/renderer/src/components/ImageBubble.tsx
index 660925a..ab2a366 100644
--- a/src/renderer/src/components/ImageBubble.tsx
+++ b/src/renderer/src/components/ImageBubble.tsx
@@ -6,6 +6,9 @@ interface ImageBubbleProps {
imageMd5?: string
imageDatName?: string
sessionId?: string
+ localId?: number
+ serverId?: string
+ createTime?: number
isThumb?: boolean
fallbackUrl?: string
onImageClick?: (imageUrl: string) => void
@@ -15,6 +18,9 @@ export function ImageBubble({
imageMd5,
imageDatName,
sessionId,
+ localId,
+ serverId,
+ createTime,
fallbackUrl,
onImageClick
}: ImageBubbleProps): JSX.Element {
@@ -125,6 +131,34 @@ export function ImageBubble({
alert('图片已复制')
}
+ /**
+ * 复制的是「消息定位信息」而非图片内容:
+ * 不带 aeskey / XML / fileid / 带票据的下载地址。
+ */
+ const handleCopyDebugInfo = async (event: MouseEvent): Promise => {
+ event.preventDefault()
+ event.stopPropagation()
+ try {
+ const result = await window.api.getImageDebugInfo({
+ sessionId,
+ localId,
+ serverId,
+ createTime,
+ imageMd5,
+ imageDatName
+ })
+ if (!result.success || !result.payload) {
+ alert(result.error ? `图片调试信息获取失败:${result.error}` : '图片调试信息获取失败')
+ return
+ }
+ const text = JSON.stringify(result.payload, null, 2)
+ await navigator.clipboard.writeText(text)
+ alert('图片调试信息已复制')
+ } catch (error) {
+ alert(error instanceof Error ? `图片调试信息复制失败:${error.message}` : '图片调试信息复制失败')
+ }
+ }
+
const handleClick = async (): Promise => {
if (!imageUrl && !error) return
if (!imageMd5 && !imageDatName) {
@@ -196,6 +230,7 @@ export function ImageBubble({
tabIndex={0}
aria-label="查看图片"
onClick={handleClick}
+ onContextMenu={handleCopyDebugInfo}
onKeyDown={handlePreviewKeyDown}
>
) : isVideo && message.contentData && message.contentData.type === 'video' ? (
diff --git a/src/shared/image-debug-info.ts b/src/shared/image-debug-info.ts
new file mode 100644
index 0000000..df546eb
--- /dev/null
+++ b/src/shared/image-debug-info.ts
@@ -0,0 +1,58 @@
+/**
+ * 图片调试定位信息。
+ *
+ * 只用于把「用户点中的那一条图片消息」精确交给本地排查工具,
+ * 不承载任何密钥、完整 XML 或图片内容。
+ *
+ * 所有消息 ID 一律用字符串:serverId 是 64 位整数,
+ * 经 Number 转换会在 2^53 以上丢精度,届时定位会指向另一条消息。
+ *
+ * 字段即契约:结构里只保留消费方实际使用的定位/验收字段;
+ * 拿不到的字段(如表名、宽高)直接不出现,不要加 null 占位。
+ */
+export const IMAGE_DEBUG_KIND = 'tracememo.image-debug' as const
+
+export type ImageDebugQuality = 'thumbnail' | 'normal' | 'original' | 'unknown'
+
+export interface ImageDebugMessage {
+ /** 本机账号定位标识;取不到时为 null。 */
+ accountId: string | null
+ conversationId: string | null
+ localId: string | null
+ /** 消息唯一键;跨库定位一律用它,不要依赖 localId。 */
+ serverId: string | null
+ /** 消息创建时间,单位:秒(epoch seconds),不是毫秒。 */
+ createTimeSeconds: number | null
+}
+
+export interface ImageDebugPayload {
+ kind: typeof IMAGE_DEBUG_KIND
+ message: ImageDebugMessage
+ image: {
+ md5: string | null
+ datName: string | null
+ }
+ display: {
+ quality: ImageDebugQuality
+ /** 已有的质量判定依据(如命中的候选文件名)。 */
+ evidence: string | null
+ /** 相对账号根目录的资源路径;取不到时为 null。 */
+ path: string | null
+ }
+}
+
+/** 渲染进程 → 主进程的查询入参。 */
+export interface ImageDebugInfoRequest {
+ sessionId?: string
+ localId?: number
+ serverId?: string
+ createTime?: number
+ imageMd5?: string
+ imageDatName?: string
+}
+
+export interface ImageDebugInfoResult {
+ success: boolean
+ payload?: ImageDebugPayload
+ error?: string
+}
diff --git a/tests/unit/image-debug-info.test.ts b/tests/unit/image-debug-info.test.ts
new file mode 100644
index 0000000..4017e50
--- /dev/null
+++ b/tests/unit/image-debug-info.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it } from 'vitest'
+import { IMAGE_DEBUG_KIND, type ImageDebugPayload } from '../../src/shared/image-debug-info'
+import { imageFileQuality } from '../../src/shared/image-quality'
+
+/** 复刻主进程的质量映射,确保导出档位与调试档位命名不会互串。 */
+function toDebugQuality(quality: 'original' | 'medium' | 'thumbnail'): string {
+ if (quality === 'original') return 'original'
+ if (quality === 'thumbnail') return 'thumbnail'
+ return 'normal'
+}
+
+function buildPayload(overrides: Partial = {}): ImageDebugPayload {
+ return {
+ kind: IMAGE_DEBUG_KIND,
+ message: {
+ accountId: 'wxid_placeholder0001',
+ conversationId: '12345678901@chatroom',
+ localId: '421',
+ serverId: '1371592385505492339',
+ createTimeSeconds: 1792372885
+ },
+ image: { md5: 'deadbeefdeadbeefdeadbeefdeadbeef', datName: 'cafebabecafebabecafebabecafebabe' },
+ display: {
+ quality: 'thumbnail',
+ evidence: 'cafebabecafebabecafebabecafebabe_t.dat',
+ path: 'msg/attach/xxx/2026-10/Img/xxx_t.dat'
+ },
+ ...overrides
+ }
+}
+
+describe('image debug info schema', () => {
+ it('keeps 64-bit serverId as an exact string', () => {
+ const payload = buildPayload()
+ // 超过 2^53 的 serverId 一旦走 Number 就会变成 1371592385505492300。
+ expect(payload.message.serverId).toBe('1371592385505492339')
+ expect(BigInt(payload.message.serverId as string)).toBe(BigInt('1371592385505492339'))
+ })
+
+ it('serialises without losing precision through JSON', () => {
+ const payload = buildPayload()
+ const restored = JSON.parse(JSON.stringify(payload)) as ImageDebugPayload
+ expect(restored.message.serverId).toBe('1371592385505492339')
+ expect(restored.message.createTimeSeconds).toBe(1792372885)
+ })
+
+ it('carries the schema marker', () => {
+ const payload = buildPayload()
+ expect(payload.kind).toBe('tracememo.image-debug')
+ })
+
+ it('contains only locator/verification fields — no filler', () => {
+ const payload = buildPayload()
+ const keys = Object.keys(payload)
+ expect(keys).toEqual(['kind', 'message', 'image', 'display'])
+ expect(Object.keys(payload.message)).toEqual([
+ 'accountId',
+ 'conversationId',
+ 'localId',
+ 'serverId',
+ 'createTimeSeconds'
+ ])
+ expect(Object.keys(payload.display)).toEqual(['quality', 'evidence', 'path'])
+ const serialised = JSON.stringify(payload)
+ expect(serialised).not.toMatch(/schemaVersion|incomplete|missingFields|sourceRelativePath/)
+ })
+
+ it('never carries key material or raw payload fields', () => {
+ const serialised = JSON.stringify(buildPayload())
+ expect(serialised).not.toMatch(/aeskey/i)
+ expect(serialised).not.toMatch(//i)
+ expect(serialised).not.toMatch(/cdnmidimgurl/i)
+ expect(serialised).not.toMatch(/https?:/i)
+ })
+})
+
+describe('debug quality naming', () => {
+ it('maps medium to normal so it cannot be mistaken for original', () => {
+ expect(toDebugQuality('medium')).toBe('normal')
+ expect(toDebugQuality('original')).toBe('original')
+ expect(toDebugQuality('thumbnail')).toBe('thumbnail')
+ })
+
+ it('derives quality from the real file name, not from a claimed value', () => {
+ expect(imageFileQuality('/a/b/xxx_t.dat')).toBe('thumbnail')
+ expect(imageFileQuality('/a/b/xxx_h.dat')).toBe('original')
+ expect(imageFileQuality('/a/b/xxx_hd.dat')).toBe('original')
+ expect(imageFileQuality('/a/b/xxx.dat')).toBe('medium')
+ expect(imageFileQuality('/a/b/xxx.jpg')).toBe('original')
+ })
+})
From 9ab71bf730124c3c6d37b60bb7d0c5d407efd688 Mon Sep 17 00:00:00 2001
From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com>
Date: Tue, 20 Oct 2026 16:07:58 +0800
Subject: [PATCH 3/6] =?UTF-8?q?feat:=20=E8=8E=B7=E5=8F=96=E5=AF=B9?=
=?UTF-8?q?=E5=BA=94=E5=9B=BE=E7=89=87=E5=8E=9F=E5=9B=BE?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.gitignore | 1 +
src/main/index.ts | 37 +++++++++++-
src/main/wcdb4-client.ts | 44 ++++++++++++++
src/preload/index.d.ts | 2 +
src/preload/index.ts | 4 ++
src/renderer/src/components/ImageBubble.tsx | 26 ++++-----
src/shared/image-message-xml.ts | 16 +++++
tests/component/image-bubble.test.tsx | 65 ++++++++++++++++++++-
8 files changed, 177 insertions(+), 18 deletions(-)
create mode 100644 src/shared/image-message-xml.ts
diff --git a/.gitignore b/.gitignore
index e15d7c9..a74f363 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,3 +28,4 @@ progress.md
task_plan.md
*tm-wcdb-config-helper*
+debug-originals
diff --git a/src/main/index.ts b/src/main/index.ts
index 54642d5..f1a2f5a 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -99,6 +99,7 @@ import {
type ImageDebugPayload,
type ImageDebugQuality
} from '../shared/image-debug-info'
+import type { ImageMessageXmlRequest, ImageMessageXmlResult } from '../shared/image-message-xml'
import {
loadSettings,
saveSettings,
@@ -704,6 +705,16 @@ function toDebugQuality(quality: 'original' | 'medium' | 'thumbnail'): ImageDebu
return 'normal'
}
+/** 反转义以 HTML 实体形式存库的正文(& 必须最后处理)。 */
+function unescapeXmlText(text: string): string {
+ return text
+ .replace(/</g, '<')
+ .replace(/>/g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, "'")
+ .replace(/&/g, '&')
+}
+
function buildImageResponse(
image: DecodedImage,
includeData = false
@@ -1806,10 +1817,34 @@ app.whenReady().then(async () => {
}
)
+ /** 取回一条图片消息的原始 XML。需 sessionId + localId 定位。 */
+ ipcMain.handle(
+ 'image:getMessageXml',
+ async (_, request: ImageMessageXmlRequest): Promise => {
+ const sessionId = String(request?.sessionId || '').trim()
+ const localId = Math.trunc(Number(request?.localId) || 0)
+ const createTime = Math.trunc(Number(request?.createTime) || 0)
+ if (!sessionId) return { success: false, error: '缺少会话标识,无法定位消息' }
+ if (localId <= 0) return { success: false, error: '缺少消息序号,无法定位消息' }
+
+ try {
+ const db = chat.getChatDb()
+ const client = db ? db.getWcdb4Client() : null
+ if (!client) return { success: false, error: '数据库尚未连接' }
+
+ const raw = client.getRawMessageContent(sessionId, localId, createTime || undefined)
+ if (!raw) return { success: false, error: '这条消息没有可读取的正文' }
+ const xml = raw.trim().includes('<') ? raw.trim() : unescapeXmlText(raw.trim())
+ return { success: true, xml }
+ } catch (error) {
+ return { success: false, error: error instanceof Error ? error.message : String(error) }
+ }
+ }
+ )
+
ipcMain.handle('image:getStatus', async () =>
inspectImageDecryptionStatus(imageKeyConfigService.getConfig())
)
-
ipcMain.handle('image:saveConfig', (_, request: SaveImageKeyRequest) => {
const result = imageKeyConfigService.save(request)
if (result.success) imageDecryptService = null
diff --git a/src/main/wcdb4-client.ts b/src/main/wcdb4-client.ts
index 6fcb7ad..c1ed2c0 100644
--- a/src/main/wcdb4-client.ts
+++ b/src/main/wcdb4-client.ts
@@ -3044,6 +3044,50 @@ export class Wcdb4Client {
return this.key
}
+ /** 按 (localId, createTime) 取回一条消息的原始 content。 */
+ getRawMessageContent(username: string, localId: number, createTime?: number): string | null {
+ if (!this.wcdbExecQuery) return null
+ const targetId = Math.trunc(Number(localId) || 0)
+ if (!username || targetId <= 0) return null
+ const anchorTime = Math.trunc(Number(createTime) || 0)
+
+ let stores: Wcdb4MessageStore[] = []
+ try {
+ stores = this.listMessageStores(username)
+ } catch {
+ return null
+ }
+
+ const candidates: string[] = []
+ for (const store of stores) {
+ const conditions = [`"local_id" = ${targetId}`]
+ if (anchorTime > 0) {
+ conditions.push(`"create_time" = ${anchorTime}`)
+ }
+ const sql = `${this.messageTableSelect(store)} WHERE ${conditions.join(' AND ')} LIMIT 5`
+ let rows: Record[] = []
+ try {
+ rows = this.executeMessageSql(store, sql)
+ } catch {
+ continue
+ }
+ for (const row of rows) {
+ try {
+ const message = this.normalizeMessage(row)
+ if (typeof message.msgContent === 'string' && message.msgContent.trim()) {
+ candidates.push(message.msgContent)
+ }
+ } catch {
+ // 单行解析失败不影响其它分片;定位信息不全时这里本来就可能拿不到。
+ }
+ }
+ }
+
+ if (candidates.length === 0) return null
+ candidates.sort((left, right) => right.length - left.length)
+ return candidates[0]
+ }
+
resolveImageHardlink(md5: string): Wcdb4ImageHardlink | null {
if (!this.wcdbResolveImageHardlink) return null
const normalizedMd5 = String(md5 || '')
diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts
index c52a41d..d161648 100644
--- a/src/preload/index.d.ts
+++ b/src/preload/index.d.ts
@@ -40,6 +40,7 @@ import type {
TestImageDecryptionRequest
} from '../shared/image-decryption'
import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
+import type { ImageMessageXmlRequest, ImageMessageXmlResult } from '../shared/image-message-xml'
import type {
AIChatRequestOptions,
AiSearchExternalAuthorizationRequest,
@@ -460,6 +461,7 @@ declare global {
filePath?: string
}>
getImageDebugInfo: (request: ImageDebugInfoRequest) => Promise
+ getImageMessageXml: (request: ImageMessageXmlRequest) => Promise
getVideo: (
hashes: string[],
options?: {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index e37ebca..9a7b3e1 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -84,6 +84,7 @@ import type { CacheClearScope, CacheSummary } from '../shared/cache'
import type { ExportRequest, ExportJobProgress } from '../shared/export'
import type { ImageDecoderSelectionResult, ImageDecoderStatus } from '../shared/image-decryption'
import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
+import type { ImageMessageXmlRequest, ImageMessageXmlResult } from '../shared/image-message-xml'
import type { AccountDiscoveryResult } from '../shared/database-key'
import type {
VoiceBatchConversationSummary,
@@ -397,6 +398,9 @@ const api = {
) => ipcRenderer.invoke('db:getImage', imageMd5, imageDatNameOrThumb, sessionId, options),
getImageDebugInfo: (request: ImageDebugInfoRequest): Promise =>
ipcRenderer.invoke('image:getDebugInfo', request),
+ /** 图片消息原始 XML。 */
+ getImageMessageXml: (request: ImageMessageXmlRequest): Promise =>
+ ipcRenderer.invoke('image:getMessageXml', request),
getVideo: (
hashes: string[],
options?: {
diff --git a/src/renderer/src/components/ImageBubble.tsx b/src/renderer/src/components/ImageBubble.tsx
index ab2a366..f025155 100644
--- a/src/renderer/src/components/ImageBubble.tsx
+++ b/src/renderer/src/components/ImageBubble.tsx
@@ -131,31 +131,25 @@ export function ImageBubble({
alert('图片已复制')
}
- /**
- * 复制的是「消息定位信息」而非图片内容:
- * 不带 aeskey / XML / fileid / 带票据的下载地址。
- */
- const handleCopyDebugInfo = async (event: MouseEvent): Promise => {
+ /** 右键复制消息原始 XML。 */
+ const handleCopyMessageXml = async (event: MouseEvent): Promise => {
event.preventDefault()
event.stopPropagation()
try {
- const result = await window.api.getImageDebugInfo({
+ const result = await window.api.getImageMessageXml({
sessionId,
localId,
serverId,
- createTime,
- imageMd5,
- imageDatName
+ createTime
})
- if (!result.success || !result.payload) {
- alert(result.error ? `图片调试信息获取失败:${result.error}` : '图片调试信息获取失败')
+ if (!result.success || !result.xml) {
+ alert(result.error ? `XML 获取失败:${result.error}` : 'XML 获取失败')
return
}
- const text = JSON.stringify(result.payload, null, 2)
- await navigator.clipboard.writeText(text)
- alert('图片调试信息已复制')
+ await navigator.clipboard.writeText(result.xml)
+ alert('图片消息 XML 已复制')
} catch (error) {
- alert(error instanceof Error ? `图片调试信息复制失败:${error.message}` : '图片调试信息复制失败')
+ alert(error instanceof Error ? `XML 复制失败:${error.message}` : 'XML 复制失败')
}
}
@@ -230,7 +224,7 @@ export function ImageBubble({
tabIndex={0}
aria-label="查看图片"
onClick={handleClick}
- onContextMenu={handleCopyDebugInfo}
+ onContextMenu={handleCopyMessageXml}
onKeyDown={handlePreviewKeyDown}
>
{
expect(await screen.findByAltText('图片')).toBeVisible()
})
+ it('copies the raw message xml when right clicked', async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined)
+ Object.defineProperty(navigator, 'clipboard', {
+ value: { writeText },
+ configurable: true
+ })
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => undefined)
+ const getImageMessageXml = vi
+ .fn()
+ .mockResolvedValue({ success: true, xml: '
' })
+ window.api = {
+ copyImage: vi.fn(),
+ getImageMessageXml
+ } as unknown as typeof window.api
+
+ requestImage.mockResolvedValueOnce({ data: thumbnail, isThumbnail: true })
+ render(
+
+ )
+
+ const image = await screen.findByAltText('图片')
+ fireEvent.contextMenu(image)
+
+ await waitFor(() =>
+ expect(writeText).toHaveBeenCalledWith('
')
+ )
+ expect(getImageMessageXml).toHaveBeenCalledWith({
+ sessionId: 'fixture-session',
+ localId: 42,
+ serverId: undefined,
+ createTime: 1700000000
+ })
+ expect(alertSpy).toHaveBeenCalledWith('图片消息 XML 已复制')
+ alertSpy.mockRestore()
+ })
+
+ it('surfaces a failure instead of copying anything when the xml is unavailable', async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined)
+ Object.defineProperty(navigator, 'clipboard', {
+ value: { writeText },
+ configurable: true
+ })
+ const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => undefined)
+ window.api = {
+ copyImage: vi.fn(),
+ getImageMessageXml: vi.fn().mockResolvedValue({ success: false, error: '数据库尚未连接' })
+ } as unknown as typeof window.api
+
+ requestImage.mockResolvedValueOnce({ data: thumbnail, isThumbnail: true })
+ render()
+
+ fireEvent.contextMenu(await screen.findByAltText('图片'))
+
+ await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('XML 获取失败:数据库尚未连接'))
+ expect(writeText).not.toHaveBeenCalled()
+ alertSpy.mockRestore()
+ })
+
it('places a quoted image on the line below the quoted sender', async () => {
requestImage.mockResolvedValueOnce({ data: thumbnail, isThumbnail: true })
const { container } = render(
From b36311e276cabe8842728e8c28cdd520e2d5c03c Mon Sep 17 00:00:00 2001
From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com>
Date: Thu, 22 Oct 2026 17:52:04 +0800
Subject: [PATCH 4/6] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E5=8F=91?=
=?UTF-8?q?=E9=80=81api?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
docs/agent/api.md | 91 ++++++-
docs/skill/tracememo-reader/SKILL.md | 72 ++++-
electron-builder.send-runtime.yml | 4 +
src/main/http-server.ts | 305 ++++++++++++++++++++++
src/shared/wechat-action.ts | 10 +
tests/integration/wechat-send-api.test.ts | 253 ++++++++++++++++++
tests/unit/wechat-action-gateway.test.ts | 29 ++
7 files changed, 754 insertions(+), 10 deletions(-)
create mode 100644 tests/integration/wechat-send-api.test.ts
diff --git a/docs/agent/api.md b/docs/agent/api.md
index 315c17c..e34682d 100644
--- a/docs/agent/api.md
+++ b/docs/agent/api.md
@@ -48,6 +48,7 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A
| GET | `/api/v1/agent/status` | Agent Hub、连接器和数据库状态 | 无 |
| POST | `/api/v1/agent/group-report` | 读取群聊并生成总结图片 | `{ "group": "群名或标识", "range": "today\|yesterday\|7days" }` |
| POST | `/api/v1/agent/send` | 通过已连接机器人测试发送文字或本地图片 | `{ "to": "接收者", "text": "...", "media_url": "..." }` |
+| POST | `/api/v1/wechat/send` | 用本机微信账号把消息发给别人 | `{ "to": "wxid 或 filehelper", "type": "text\|image\|voice", "text": "..." }` |
| GET | `/api/v1/wechat-personal/send-capability` | 个人微信发送能力状态 | 无 |
| GET | `/api/v1/scheduled-reports` | 定时日报任务列表 | 无 |
| POST | `/api/v1/scheduled-reports` | 创建定时日报任务 | `ScheduledReportApiCreateRequest` JSON |
@@ -76,6 +77,86 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A
`/api/v1/query/*` 是一组结构化的 Query 端点,见下方[LLM-friendly Query Tool API](#llm-friendly-query-tool-api)。
+## 发送消息 API
+
+两个发送端点走**完全不同的通道**,用途也不同,不要混用。
+
+| | `POST /api/v1/wechat/send` | `POST /api/v1/agent/send` |
+| --- | --- | --- |
+| 通道 | 本机微信(macOS native runtime / Windows hook) | Agent Hub 机器人(iLink) |
+| 身份 | 你本人当前登录的微信账号 | 已扫码接入的机器人 |
+| 用途 | **以你的身份把消息发给别人**(好友 / 群 / 文件传输助手) | **机器人给自己发通知**(测试连通性) |
+| 前置条件 | 本机微信已启动,发送能力为 `ready` | 连接器为 `online` |
+| 内容类型 | `text` / `image` / `voice`,媒体只接受本地文件 | `text` / `image`(URL 或本地路径) |
+| 典型失败 | 能力未就绪 `503`、发送失败 `502` | 连接器离线 `503`、凭证过期 `401` |
+
+### 本地发送:`POST /api/v1/wechat/send`
+
+用你正在登录的微信账号发消息。**这是唯一能把消息发给别人(而不是发给机器人自己)的端点。**
+
+```bash
+: "${TRACEMEMO_API_TOKEN:?Set TRACEMEMO_API_TOKEN from API Center}"
+curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \
+ -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{"to":"filehelper","type":"text","text":"来自 Agent 的一条消息"}'
+```
+
+请求体:
+
+| 字段 | 必填 | 说明 |
+| --- | --- | --- |
+| `to` | 是 | 接收者:好友 wxid、群 id(以 `@chatroom` 结尾),或 `filehelper`(文件传输助手)。**不做昵称解析**,先调 `/api/v1/resolve?q=张三` 换 wxid |
+| `type` | 否 | `text`(默认)/ `image` / `voice` |
+| `text` | `type=text` 时必填 | **最长 2000 字符**,超限返回 `400`,不会截断 |
+| `filePath` | `type=image\|voice` 时必填 | 本机**绝对路径**,必须已存在。不接受 URL —— 需要发网络图片时先落盘 |
+| `isGroup` | 否 | 通常可省略;`to` 以 `@chatroom` 结尾时自动判为群 |
+| `idempotencyKey` | 否 | 幂等键。**重试时请原样带上**,避免 Agent 超时重发导致重复消息 |
+
+发送前会先校验当前发送能力(等价于 `GET /api/v1/wechat-personal/send-capability`):`ready=false` 时直接返回 `503`,不会进入投递;`capabilities[type]=false` 时返回 `503 SEND_NOT_READY`。
+
+> **没有 3 秒节流。** 自动化规则(定时日报、退群通知)之间共享 3 秒发送间隔,但本端点属于手动发送,**不受该队列约束**:连续调用会连续投递。Agent 需要自行控制频率,不要用它循环刷消息。
+
+响应:
+
+```json
+{
+ "success": true,
+ "status": "sent",
+ "actionId": "5f0c…",
+ "recipient": { "type": "contact", "id": "filehelper" },
+ "contentType": "text",
+ "durationMs": 842
+}
+```
+
+| HTTP | `errorCode` | 含义 |
+| --- | --- | --- |
+| `400` | `INVALID_REQUEST` / `INVALID_RECIPIENT` | 字段缺失、`text` 超长、`filePath` 不存在 |
+| `403` | `POLICY_BLOCKED` / `ACTION_NOT_ALLOWED` / `RECIPIENT_SCOPE_VIOLATION` | 发送策略拒绝 |
+| `502` | `SEND_FAILED` | 已进入投递,底层发送失败(看 `error`) |
+| `503` | `SEND_CAPABILITY_UNAVAILABLE` | 微信未启动 / 未绑定 / 未初始化 |
+| `503` | `SEND_NOT_READY` | 能力在,但不支持该内容类型(例如语音 hook 未就绪) |
+| `503` | `UNSUPPORTED_PLATFORM` | 非 macOS / Windows |
+| `500` | `INTERNAL_ERROR` | 网关执行抛出未预期异常 |
+
+> **`status: "sent"` 只代表投递成功,不等于消息已写入本地数据库。** TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不会写入。因此不要用 `/api/v1/chatlog` 回查自己刚发的消息来判断是否发送成功 —— 查不到是正常现象;也**不要**因为本地库没有就重发,那会产生真实的重复消息。需要人工确认时,让对方用手机微信或另一个账号查看会话。
+
+每一次发送都会写入 `actions/wechat-actions.json` 审计记录(`origin` 为 `http_api`),可在 Send Log 中核对。这份记录证明的是「调用过并成功投递」,**不能**证明对方已收到或本地库已落库。
+
+### 机器人通知:`POST /api/v1/agent/send`
+
+走已扫码的 Agent Hub 连接器,给**自己**发一条测试消息,用于确认机器人链路是否通畅。它不适合「通知某人」这类场景 —— 那要用上面的 `/api/v1/wechat/send`。
+
+```bash
+curl -X POST http://127.0.0.1:6131/api/v1/agent/send \
+ -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{"to":"<你的 wxid>","text":"connector ok"}'
+```
+
+`to` 省略时回落到当前登录账号自己。`media_url` 可传 URL。连接器离线返回 `503`,凭证过期返回 `401`。
+
## Application Capabilities
`GET /api/v1/capabilities` 描述 TraceMemo 应用级能力和当前运行环境;`GET /api/v1/query/capabilities` 只描述结构化 Query primitive,两者不是同一份目录。应用能力使用 `supported` 和 `available` 分开表示“代码支持”与“当前可用”;运行时原因使用稳定的简短 code,不返回 Token、数据库路径、微信密钥或 sender 诊断路径。
@@ -390,7 +471,7 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/voice-t
Reader Skill 是随应用分发的说明文件。它被安装到 Agent 自己的 Skill 目录之后就与 TraceMemo 分离了,不再随应用升级自动变化,所以它必须能自己证明版本:
-- `SKILL.md` frontmatter 的 `version` 是**唯一真源**(形如 `1.3.0`);
+- `SKILL.md` frontmatter 的 `version` 是**唯一真源**(形如 `1.4.0`);
- `/api/v1/health` 的 `skill.version` 回报当前应用内置的版本;
- 两者不一致,就说明 Agent 手里那份已经过期,接口契约可能已经变化。
@@ -405,8 +486,8 @@ curl http://127.0.0.1:6131/api/v1/health
"ok": true,
"ready": true,
"service": "TraceMemo Reader",
- "version": "2.5.0",
- "skill": { "name": "tracememo-reader", "version": "1.3.0", "available": true },
+ "version": "2.5.1",
+ "skill": { "name": "tracememo-reader", "version": "1.4.0", "available": true },
"timestamp": "2026-10-13T08:43:52.863Z"
}
```
@@ -423,10 +504,10 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
```json
{
"name": "tracememo-reader",
- "version": "1.3.0",
+ "version": "1.4.0",
"contentHash": "",
"modifiedAt": "2026-10-13T08:37:30.000Z",
- "markdown": "---\nname: tracememo-reader\nversion: 1.3.0\n…"
+ "markdown": "---\nname: tracememo-reader\nversion: 1.4.0\n…"
}
```
diff --git a/docs/skill/tracememo-reader/SKILL.md b/docs/skill/tracememo-reader/SKILL.md
index 2b0176f..47c1ff0 100644
--- a/docs/skill/tracememo-reader/SKILL.md
+++ b/docs/skill/tracememo-reader/SKILL.md
@@ -1,7 +1,7 @@
---
name: tracememo-reader
-version: 1.3.0
-description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体,并管理定时日报任务。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
+version: 1.4.0
+description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体、管理定时日报任务,并用用户本机登录的微信账号发送消息。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
---
# TraceMemo Reader
@@ -76,6 +76,7 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
| POST | `/query/voice-transcribe` | 把指定语音消息转成文字(本机离线识别) |
| GET | `/query/capabilities` | Query 端点能力目录 |
| GET | `/wechat-personal/send-capability` | 个人微信发送能力状态(文字 / 图片 / 语音) |
+| POST | `/wechat/send` | 用本机微信账号发消息给他人(文字/图片/语音) |
| GET | `/scheduled-reports` | 查询全部定时日报任务 |
| GET | `/scheduled-reports/:id` | 查询单个定时日报任务 |
| POST | `/scheduled-reports` | 创建定时日报任务 |
@@ -91,7 +92,68 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
| POST | `/agent/group-report` | 按群和 `today`/`yesterday`/`7days` 生成总结图片 |
| POST | `/agent/send` | 已连接机器人发送测试(文字或本地图片) |
-这个 API **不只是只读的**:`/report` 会渲染并写文件,`/agent/send` 会真的发出微信消息,`/scheduled-reports*` 会创建、修改、删除或立刻执行定时任务。这些调用都要先确认用户意图;`DELETE` 与 `/agent/send` 尤其需要用户明确确认。
+这个 API **不只是只读的**:`/report` 会渲染并写文件,`/wechat/send` 会以用户本人的微信账号把消息真的发给别人,`/agent/send` 会通过机器人发出消息,`/scheduled-reports*` 会创建、修改、删除或立刻执行定时任务。这些调用都要先确认用户意图;`DELETE`、`/wechat/send` 与 `/agent/send` 尤其需要用户明确确认。
+
+## 发送微信消息
+
+两个发送端点的**身份和通道完全不同**,不要混用:
+
+| | `/wechat/send` | `/agent/send` |
+| -------- | ------------------------------ | -------------------------------- |
+| 发送身份 | 用户本机正在登录的微信账号 | 已扫码接入的 TraceMemo 机器人 |
+| 收件人 | 好友 / 群 / 文件传输助手 | 一般是自己,用于测试连接器连通性 |
+| 前置条件 | 本机微信已启动,发送能力 ready | Agent Hub 连接器 online |
+
+用户说“发消息给某人 / 某个群 / 文件传输助手”时,**只能用 `/wechat/send`**。`/agent/send` 不是用来通知别人的。
+
+### 调用前必须做
+
+1. 调用 `GET /wechat-personal/send-capability`,只有 `capability.ready === true` 且 `capability.capabilities[type] === true` 才继续。否则停下来说明需要先在 TraceMemo「设置 → 发送能力」里完成绑定,**不要**直接调用再解释失败。
+2. 通过 `/resolve` 把用户说的昵称换成 wxid;`to` 只接受 wxid、`xxx@chatroom` 群 id,或 `filehelper`。**不要猜 wxid,也不要把昵称直接写进 `to`。**
+3. 把「发给谁 + 发什么」复述给用户并得到确认后再发。这是不可撤回的外部操作。
+
+### 请求
+
+```json
+{ "to": "wxid_xxx", "type": "text", "text": "消息内容", "idempotencyKey": "可选" }
+```
+
+| 字段 | 必填 | 说明 |
+| ---------------- | ------------------ | ------------------------------------------------------------------- |
+| `to` | 是 | wxid / `xxx@chatroom` / `filehelper`;以 `@chatroom` 结尾自动判为群 |
+| `type` | 否 | `text`(默认)/ `image` / `voice` |
+| `text` | `type=text` 时必填 | **最多 2000 字符**,超限返回 `400`,不会自动截断 |
+| `filePath` | `type=image/voice` | 本机**绝对路径**且文件必须存在;**不接受 URL** |
+| `idempotencyKey` | 否 | 重试时原样带回,避免超时重发产生重复消息 |
+
+几个必须遵守的限制:
+
+- **超过 2000 字符不要硬发**。先告诉用户内容过长,征得同意后再拆成多条依次发送;不要静默截断。
+- **媒体只收本地文件**。用户给的是聊天里的图片时,先用 `/chatlog` 拿到 `media.url` 下载成临时文件,再把该路径传给 `filePath`;网络图片同样需要先落盘。不要试图传 URL。
+- **本端点没有节流**。automation 的 3 秒间隔对它不生效,连续调用就会连续投递。单个任务里连续发送超过 3 条前,先和用户确认节奏。
+
+### 结果
+
+成功返回 `success: true`、`status: "sent"`、`actionId`。失败时读 `errorCode`:
+
+- `400 INVALID_REQUEST` / `INVALID_RECIPIENT`:字段不合法,按 `error` 里的说明修正;
+- `403 POLICY_BLOCKED`:被发送策略拒绝,如实告知用户;
+- `502 SEND_FAILED`:已进入投递但微信侧失败,不要说成“已发送”;
+- `503 SEND_CAPABILITY_UNAVAILABLE` / `SEND_NOT_READY`:能力未就绪,引导用户去绑定;
+- `503 UNSUPPORTED_PLATFORM`:当前系统不支持。
+
+只有 `status === "sent"` 才能告诉用户发送成功。不要凭 `actionId` 或 HTTP 200 之外的任何信息推断结果。
+
+### 发送成功后不要用 `/chatlog` 自证
+
+`status: "sent"` 只表示消息已经交给微信完成投递,**不代表它会出现在本地聊天数据库里**。TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不写入。
+
+因此:
+
+- **不要**用 `/chatlog` 查自己刚发出的那条消息来确认发送成功。查不到是正常现象,不等于发送失败。
+- **不要**因为本地库没有这条消息就重发 —— 那会产生真实的重复消息。
+- 需要人工确认时,请用户用**手机微信**或**另一个微信号**查看该会话;这是唯一可靠的确认方式。
+- Send Log 与 `actions/wechat-actions.json` 记录的是 TraceMemo 自己的发送动作与结果,能证明“调用过并成功投递”,**不能**证明对方收到或本地库已落库。不要把它们混为一谈。
## 定时日报管理
@@ -199,8 +261,8 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
## 常见错误
- `401`:Token 缺失、错误或被轮换;请用户回 API Center 复制最新 Token。
-- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。
+- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。注意 `/wechat/send` 的 `403 POLICY_BLOCKED` 是被发送策略拒绝,含义不同。
- `404`:会话查询失败时先用 `/resolve` 确认会话标识;媒体请求表示标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在。
- `422`:媒体标识格式错误,或消息不是可读取的图片(`NOT_IMAGE`)。
-- `503`:用户还没有完成数据库连接或对应服务未就绪。
+- `503`:用户还没有完成数据库连接或对应服务未就绪。发送端点返回 `503` 时先查 `/wechat-personal/send-capability`,不要反复重试。
- 空结果:缩小/扩大时间范围,确认账号和会话,再检查媒体或语音是否可读。
diff --git a/electron-builder.send-runtime.yml b/electron-builder.send-runtime.yml
index 5162a30..21aac85 100644
--- a/electron-builder.send-runtime.yml
+++ b/electron-builder.send-runtime.yml
@@ -6,6 +6,10 @@ extraResources:
to: resources
filter:
- '**/*'
+ - from: resources/wcdb/macos/arm64
+ to: resources/wcdb/macos/arm64
+ filter:
+ - 'tm-wcdb-config-helper'
- from: docs/skill/tracememo-reader
to: skill/tracememo-reader
filter:
diff --git a/src/main/http-server.ts b/src/main/http-server.ts
index 1a55837..bcafe40 100644
--- a/src/main/http-server.ts
+++ b/src/main/http-server.ts
@@ -1,4 +1,5 @@
import crypto from 'crypto'
+import { existsSync } from 'fs'
import http, { IncomingMessage, ServerResponse, Server } from 'http'
import { app } from 'electron'
import {
@@ -35,6 +36,9 @@ import { automationRuleStore, AutomationRulePersistenceError } from './services/
import { automationExecutionLogService } from './services/automation-execution-log-service'
import { groupExitMonitorService } from './services/group-exit-monitor-service'
import { LocalAgentApiError, LocalAgentApiService } from './services/local-agent-api-service'
+import { wechatActionGateway } from './services/wechat-action-gateway'
+import type { WechatActionRequest, WechatActionResult } from '../shared/wechat-action'
+import type { PersonalWechatSendCapability } from '../shared/personal-wechat'
import type { GroupStatsService } from './services/group-stats-service'
import { encodeMessageRef } from '../shared/local-query-api'
import type {
@@ -77,6 +81,8 @@ export interface HttpServerOptions {
agentApiService?: LocalAgentApiService
groupStatsService?: Pick
appVersionProvider?: () => string
+ wechatSendCapabilityProvider?: () => Promise
+ wechatSendExecutor?: (request: WechatActionRequest) => Promise
}
let configuredQueryApiService: LocalQueryApiService | undefined
@@ -563,6 +569,298 @@ const routes: Record = {
const SCHEDULED_REPORTS_ROUTE = '/api/v1/scheduled-reports'
const WECHAT_SEND_CAPABILITY_ROUTE = '/api/v1/wechat-personal/send-capability'
+const WECHAT_SEND_ROUTE = '/api/v1/wechat/send'
+
+/**
+ * 文本上限必须与 `wechat-action-gateway.ts` 的 `normalizeActionRequest` 一致,
+ * 否则本层放过的请求会被网关静默拒绝;在此先拦是为了返回实际长度。
+ */
+const WECHAT_SEND_MAX_TEXT_LENGTH = 2_000
+const WECHAT_SEND_MAX_RECIPIENT_LENGTH = 512
+const WECHAT_SEND_MAX_IDEMPOTENCY_KEY_LENGTH = 200
+
+const WECHAT_SEND_CONTENT_TYPES = ['text', 'image', 'voice'] as const
+type WechatSendContentType = (typeof WECHAT_SEND_CONTENT_TYPES)[number]
+
+interface WechatSendApiDependencies {
+ getCapability: () => Promise
+ execute: (request: WechatActionRequest) => Promise
+}
+
+type ParsedWechatSend =
+ | {
+ ok: true
+ recipient: WechatActionRequest['recipient']
+ content: WechatActionRequest['content']
+ idempotencyKey?: string
+ }
+ | { ok: false; status: number; code: string; message: string }
+
+function readSendString(value: unknown): string {
+ return typeof value === 'string' ? value.trim() : ''
+}
+
+/**
+ * 请求体 → Gateway 动作。
+ *
+ * 字段在本层先校验:`WechatActionGateway` 对不合格请求只回一个 `INVALID_REQUEST`,
+ * 调用方拿不到具体是哪个字段的问题。
+ */
+function parseWechatSendPayload(payload: unknown): ParsedWechatSend {
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
+ return { ok: false, status: 400, code: 'INVALID_REQUEST', message: '请求体必须是 JSON 对象' }
+ }
+ const body = payload as Record
+
+ const to = readSendString(body.to)
+ if (!to) {
+ return {
+ ok: false,
+ status: 400,
+ code: 'INVALID_RECIPIENT',
+ message: '缺少 to:接收者 wxid、群 id 或 filehelper'
+ }
+ }
+ if (to.length > WECHAT_SEND_MAX_RECIPIENT_LENGTH) {
+ return {
+ ok: false,
+ status: 400,
+ code: 'INVALID_RECIPIENT',
+ message: `to 长度 ${to.length} 超过上限 ${WECHAT_SEND_MAX_RECIPIENT_LENGTH} 字符`
+ }
+ }
+ if (body.isGroup !== undefined && typeof body.isGroup !== 'boolean') {
+ return { ok: false, status: 400, code: 'INVALID_REQUEST', message: 'isGroup 必须是布尔值' }
+ }
+
+ const rawType = body.type === undefined ? 'text' : body.type
+ if (
+ typeof rawType !== 'string' ||
+ !WECHAT_SEND_CONTENT_TYPES.includes(rawType as WechatSendContentType)
+ ) {
+ return {
+ ok: false,
+ status: 400,
+ code: 'INVALID_REQUEST',
+ message: `type 必须是 ${WECHAT_SEND_CONTENT_TYPES.join(' / ')} 之一`
+ }
+ }
+ const type = rawType as WechatSendContentType
+
+ const rawKey = body.idempotencyKey
+ if (rawKey !== undefined && typeof rawKey !== 'string') {
+ return {
+ ok: false,
+ status: 400,
+ code: 'INVALID_REQUEST',
+ message: 'idempotencyKey 必须是字符串'
+ }
+ }
+ const idempotencyKey = readSendString(rawKey)
+ if (idempotencyKey.length > WECHAT_SEND_MAX_IDEMPOTENCY_KEY_LENGTH) {
+ return {
+ ok: false,
+ status: 400,
+ code: 'INVALID_REQUEST',
+ message: `idempotencyKey 长度 ${idempotencyKey.length} 超过上限 ${WECHAT_SEND_MAX_IDEMPOTENCY_KEY_LENGTH} 字符`
+ }
+ }
+
+ const recipient: WechatActionRequest['recipient'] = {
+ type: body.isGroup === true || to.endsWith('@chatroom') ? 'group' : 'contact',
+ id: to
+ }
+
+ let content: WechatActionRequest['content']
+ if (type === 'text') {
+ const text = typeof body.text === 'string' ? body.text.trim() : ''
+ if (!text) {
+ return {
+ ok: false,
+ status: 400,
+ code: 'INVALID_REQUEST',
+ message: 'type=text 时 text 不能为空'
+ }
+ }
+ if (text.length > WECHAT_SEND_MAX_TEXT_LENGTH) {
+ return {
+ ok: false,
+ status: 400,
+ code: 'INVALID_REQUEST',
+ message: `text 长度 ${text.length} 超过上限 ${WECHAT_SEND_MAX_TEXT_LENGTH} 字符`
+ }
+ }
+ content = { type: 'text', text }
+ } else {
+ const filePath = readSendString(body.filePath)
+ if (!filePath) {
+ return {
+ ok: false,
+ status: 400,
+ code: 'INVALID_REQUEST',
+ message: `type=${type} 时 filePath 必填,且必须是本机绝对路径(不接受 URL)`
+ }
+ }
+ if (!existsSync(filePath)) {
+ return {
+ ok: false,
+ status: 400,
+ code: 'INVALID_REQUEST',
+ message: `filePath 指向的文件不存在:${filePath}`
+ }
+ }
+ content = { type, path: filePath }
+ }
+
+ return {
+ ok: true,
+ recipient,
+ content,
+ ...(idempotencyKey ? { idempotencyKey } : {})
+ }
+}
+
+function wechatActionResultStatus(result: WechatActionResult): number {
+ if (result.status === 'sent') return 200
+ switch (result.errorCode) {
+ case 'INVALID_REQUEST':
+ case 'INVALID_RECIPIENT':
+ return 400
+ case 'ACTION_NOT_ALLOWED':
+ case 'POLICY_BLOCKED':
+ case 'RECIPIENT_SCOPE_VIOLATION':
+ return 403
+ case 'SEND_CAPABILITY_UNAVAILABLE':
+ case 'SEND_NOT_READY':
+ return 503
+ default:
+ return 502
+ }
+}
+
+function actionDurationMs(result: WechatActionResult): number {
+ const started = Date.parse(result.startedAt)
+ const finished = Date.parse(result.finishedAt)
+ if (!Number.isFinite(started) || !Number.isFinite(finished)) return 0
+ return Math.max(0, finished - started)
+}
+
+/**
+ * 本地个人微信发送:用本机登录的微信账号把消息发给**别人**(好友 / 群 / 文件传输助手)。
+ *
+ * 与 `/api/v1/agent/send` 的区别是传输通道:这个端点走本机 runtime/hook,
+ * 不依赖 Agent Hub 连接器在线,也不消耗机器人身份。
+ */
+function createWechatSendRoute(
+ pathname: string,
+ deps: WechatSendApiDependencies
+): RouteHandler | undefined {
+ if (pathname !== WECHAT_SEND_ROUTE) return undefined
+
+ return withMethods(['POST'], async ({ res, body }) => {
+ let payload: unknown
+ try {
+ payload = JSON.parse(typeof body === 'string' && body.trim() ? body : '{}')
+ } catch {
+ return sendWechatSendError(res, 400, 'INVALID_REQUEST', '请求体 JSON 解析失败')
+ }
+
+ const parsed = parseWechatSendPayload(payload)
+ if (!parsed.ok) {
+ return sendWechatSendError(res, parsed.status, parsed.code, parsed.message)
+ }
+
+ // 发送能力必须在真正投递前确认:否则失败只能等到 runtime 超时后才知道。
+ let capability: PersonalWechatSendCapability
+ try {
+ capability = await deps.getCapability()
+ } catch (error) {
+ return sendWechatSendError(
+ res,
+ 503,
+ 'SEND_CAPABILITY_UNAVAILABLE',
+ '个人微信发送能力探测失败',
+ { reason: error instanceof Error ? error.message : String(error) }
+ )
+ }
+ if (!capability.supported) {
+ return sendWechatSendError(
+ res,
+ 503,
+ 'UNSUPPORTED_PLATFORM',
+ capability.message || '当前平台不支持个人微信发送',
+ { capabilityStatus: capability.status }
+ )
+ }
+ if (!capability.ready) {
+ return sendWechatSendError(
+ res,
+ 503,
+ 'SEND_CAPABILITY_UNAVAILABLE',
+ capability.message || '个人微信发送能力未就绪',
+ {
+ capabilityStatus: capability.status,
+ ...(capability.error ? { reason: capability.error } : {})
+ }
+ )
+ }
+ const contentType = parsed.content.type
+ if (!capability.capabilities[contentType]) {
+ const label = contentType === 'text' ? '文字' : contentType === 'image' ? '图片' : '语音'
+ return sendWechatSendError(res, 503, 'SEND_NOT_READY', `当前微信发送能力不支持发送${label}`, {
+ capabilityStatus: capability.status,
+ capabilities: capability.capabilities
+ })
+ }
+
+ let result: WechatActionResult
+ try {
+ result = await deps.execute({
+ origin: 'http_api',
+ purpose: `api_${contentType}` as WechatActionRequest['purpose'],
+ triggerType: 'user',
+ recipient: parsed.recipient,
+ content: parsed.content,
+ ...(parsed.idempotencyKey ? { idempotencyKey: parsed.idempotencyKey } : {})
+ })
+ } catch (error) {
+ return sendWechatSendError(res, 500, 'INTERNAL_ERROR', '微信发送执行失败', {
+ reason: error instanceof Error ? error.message : String(error)
+ })
+ }
+
+ const status = wechatActionResultStatus(result)
+ sendJson(res, status, {
+ success: result.status === 'sent',
+ status: result.status,
+ actionId: result.actionId,
+ recipient: parsed.recipient,
+ contentType,
+ durationMs: actionDurationMs(result),
+ ...(result.errorCode ? { errorCode: result.errorCode } : {}),
+ ...(result.reason ? { error: result.reason } : {})
+ })
+ })
+}
+
+/**
+ * 发送端点的错误响应保持扁平:Agent 读 `errorCode` 就能分支,
+ * 不需要再往 `details` 里翻一层(`sendError` 的通用结构会多包一层)。
+ */
+function sendWechatSendError(
+ res: ServerResponse,
+ status: number,
+ errorCode: string,
+ message: string,
+ extra?: Record
+): void {
+ sendJson(res, status, {
+ success: false,
+ errorCode,
+ error: message,
+ ...(extra || {})
+ })
+}
function parseJsonBody(body: unknown): unknown {
if (typeof body !== 'string' || !body.trim()) {
@@ -1043,6 +1341,12 @@ export function startHttpServer(
const scheduledReportApi = createScheduledReportApi(options)
const queryApi = options.queryApiService || configuredQueryApiService || new LocalQueryApiService()
const agentApi = createAgentApiService(options)
+ const wechatSendApi: WechatSendApiDependencies = {
+ getCapability:
+ options.wechatSendCapabilityProvider ||
+ (() => personalWechatCapabilityService.getPersonalWechatSendCapability()),
+ execute: options.wechatSendExecutor || ((request) => wechatActionGateway.execute(request))
+ }
return new Promise((resolve, reject) => {
const server: Server = http.createServer(async (req, res) => {
const requestId = requestIdFor(req)
@@ -1064,6 +1368,7 @@ export function startHttpServer(
const handler =
routes[url.pathname] ||
createAgentApiRoute(url.pathname, agentApi) ||
+ createWechatSendRoute(url.pathname, wechatSendApi) ||
createScheduledReportRoute(url.pathname, scheduledReportApi) ||
(url.pathname.startsWith(QUERY_ROUTE_PREFIX)
? createQueryRoute(url.pathname, queryApi)
diff --git a/src/shared/wechat-action.ts b/src/shared/wechat-action.ts
index 5ee3d3d..709a0cc 100644
--- a/src/shared/wechat-action.ts
+++ b/src/shared/wechat-action.ts
@@ -16,6 +16,12 @@ export type WechatActionOrigin =
* 也不进 Send Log —— 排查「消息到底发没发出去」时会缺一份证据。
*/
| 'user_manual'
+ /**
+ * 外部 Agent 通过本地 HTTP API(`POST /api/v1/wechat/send`)发起的发送。
+ *
+ * 与 `user_manual` 分开登记,审计记录才能区分人工点击与 Agent 调用。
+ */
+ | 'http_api'
/** Automation(@我生成日报 / 退群通知)。与 `shared/automation.ts` 的 AUTOMATION_SEND_ORIGIN 一致。 */
| 'automation'
| 'unknown'
@@ -36,6 +42,10 @@ export type WechatActionPurpose =
| 'manual_image'
/** 用户手动发送文本。 */
| 'manual_text'
+ /** 外部 Agent 经本地 HTTP API 发送;按内容类型分开,便于审计统计。 */
+ | 'api_text'
+ | 'api_image'
+ | 'api_voice'
/** 用户确认后的日报图片;进入 automation 队列以复用 3 秒发送间隔。 */
| 'manual_report_image'
/** 日报图片成功后的后置词;只有图片 sent 后才会创建。 */
diff --git a/tests/integration/wechat-send-api.test.ts b/tests/integration/wechat-send-api.test.ts
new file mode 100644
index 0000000..4736aa6
--- /dev/null
+++ b/tests/integration/wechat-send-api.test.ts
@@ -0,0 +1,253 @@
+import fs from 'fs-extra'
+import path from 'node:path'
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const root = vi.hoisted(() => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const fs = require('node:fs') as typeof import('node:fs')
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const os = require('node:os') as typeof import('node:os')
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const path = require('node:path') as typeof import('node:path')
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'tracememo-wechat-send-api-'))
+})
+
+vi.mock('electron', () => ({
+ app: { getPath: () => root, getVersion: () => 'test-version' },
+ safeStorage: {
+ isEncryptionAvailable: () => true,
+ encryptString: (value: string) => Buffer.from(value, 'utf8'),
+ decryptString: (value: Buffer) => value.toString('utf8')
+ }
+}))
+
+vi.mock('../../src/main/services/chat-service', () => ({
+ isReady: () => true,
+ listContacts: () => [],
+ listContactsAsync: async () => [],
+ listMessages: () => [],
+ getGroupSnapshot: () => null,
+ listRecentChat: () => [],
+ resolveMd5: () => null
+}))
+
+vi.mock('../../src/main/group-report-service', () => ({ exportGroupReport: vi.fn() }))
+vi.mock('../../src/main/services/agent-group-report-service', () => ({
+ generateAgentGroupReport: vi.fn()
+}))
+vi.mock('../../src/main/services/agent-hub-service', () => ({
+ agentHubService: {
+ getStatus: () => ({ connector: 'offline' }),
+ testSend: vi.fn()
+ }
+}))
+vi.mock('../../src/main/services/group-exit-monitor-service', () => ({
+ groupExitMonitorService: {
+ getState: () => ({ enabled: false, running: false, monitoredRoomIds: [] })
+ }
+}))
+vi.mock('../../src/main/services/wechat-action-gateway', () => ({
+ wechatActionGateway: { execute: vi.fn() }
+}))
+
+import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat'
+import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action'
+import type { LocalAgentApiService } from '../../src/main/services/local-agent-api-service'
+import { startHttpServer, type HttpServerHandle } from '../../src/main/http-server'
+
+const TOKEN = 'T'.repeat(43)
+
+function capabilityOf(
+ overrides: Partial = {}
+): PersonalWechatSendCapability {
+ return {
+ supported: true,
+ ready: true,
+ status: 'ready',
+ capabilities: { text: true, image: true, voice: true },
+ senderStatus: {} as PersonalWechatSendCapability['senderStatus'],
+ message: '可以发送',
+ ...overrides
+ }
+}
+
+function sentResult(overrides: Partial = {}): WechatActionResult {
+ return {
+ actionId: 'action-1',
+ status: 'sent',
+ decision: 'allow',
+ startedAt: '2026-10-20T00:00:00.000Z',
+ finishedAt: '2026-10-20T00:00:00.500Z',
+ ...overrides
+ }
+}
+
+let handle: HttpServerHandle
+let capability: PersonalWechatSendCapability
+let executeResult: WechatActionResult
+const execute = vi.fn()
+const lastAction = (): WechatActionRequest => execute.mock.calls[0][0] as WechatActionRequest
+
+async function post(body: unknown, token: string | null = TOKEN): Promise {
+ return fetch(`http://${handle.host}:${handle.port}/api/v1/wechat/send`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
+ },
+ body: JSON.stringify(body)
+ })
+}
+
+beforeAll(async () => {
+ handle = await startHttpServer('127.0.0.1', 0, {
+ tokenProvider: () => TOKEN,
+ agentApiService: {} as LocalAgentApiService,
+ wechatSendCapabilityProvider: async () => capability,
+ wechatSendExecutor: execute
+ })
+})
+
+afterAll(async () => {
+ await handle.close()
+ await fs.remove(root)
+})
+
+beforeEach(() => {
+ capability = capabilityOf()
+ executeResult = sentResult()
+ execute.mockReset()
+ execute.mockImplementation(async () => executeResult)
+})
+
+describe('POST /api/v1/wechat/send', () => {
+ it('未携带 Token 时返回 401', async () => {
+ const response = await post({ to: 'filehelper', text: 'hi' }, null)
+ expect(response.status).toBe(401)
+ expect(execute).not.toHaveBeenCalled()
+ })
+
+ it('缺少 to 时返回 400 且不进入投递', async () => {
+ const response = await post({ text: 'hi' })
+ expect(response.status).toBe(400)
+ const body = await response.json()
+ expect(body.errorCode).toBe('INVALID_RECIPIENT')
+ expect(execute).not.toHaveBeenCalled()
+ })
+
+ it('text 超过 2000 字符时返回 400 并给出实际长度', async () => {
+ const response = await post({ to: 'filehelper', text: 'x'.repeat(2_001) })
+ expect(response.status).toBe(400)
+ const body = await response.json()
+ expect(body.errorCode).toBe('INVALID_REQUEST')
+ expect(body.error).toContain('2001')
+ expect(execute).not.toHaveBeenCalled()
+ })
+
+ it('type 非法时返回 400', async () => {
+ const response = await post({ to: 'filehelper', type: 'video', text: 'hi' })
+ expect(response.status).toBe(400)
+ expect((await response.json()).errorCode).toBe('INVALID_REQUEST')
+ })
+
+ it('媒体类型缺少 filePath 或文件不存在时返回 400', async () => {
+ const missing = await post({ to: 'filehelper', type: 'image' })
+ expect(missing.status).toBe(400)
+
+ const absent = await post({
+ to: 'filehelper',
+ type: 'image',
+ filePath: path.join(root, 'no-such-image.png')
+ })
+ expect(absent.status).toBe(400)
+ expect((await absent.json()).error).toContain('不存在')
+ expect(execute).not.toHaveBeenCalled()
+ })
+
+ it('发送能力未就绪时返回 503', async () => {
+ capability = capabilityOf({
+ ready: false,
+ status: 'needs_binding',
+ message: '请先绑定个人微信'
+ })
+ const response = await post({ to: 'filehelper', text: 'hi' })
+ expect(response.status).toBe(503)
+ const body = await response.json()
+ expect(body.errorCode).toBe('SEND_CAPABILITY_UNAVAILABLE')
+ expect(body.capabilityStatus).toBe('needs_binding')
+ expect(execute).not.toHaveBeenCalled()
+ })
+
+ it('能力就绪但不支持该内容类型时返回 503 SEND_NOT_READY', async () => {
+ capability = capabilityOf({ capabilities: { text: true, image: false, voice: false } })
+ const response = await post({ to: 'filehelper', type: 'voice', filePath: __filename })
+ expect(response.status).toBe(503)
+ expect((await response.json()).errorCode).toBe('SEND_NOT_READY')
+ expect(execute).not.toHaveBeenCalled()
+ })
+
+ it('文本发送成功时以 http_api 来源经过 Gateway', async () => {
+ const response = await post({ to: 'filehelper', type: 'text', text: ' 你好 ' })
+ expect(response.status).toBe(200)
+ const body = await response.json()
+ expect(body.success).toBe(true)
+ expect(body.actionId).toBe('action-1')
+ expect(body.recipient).toEqual({ type: 'contact', id: 'filehelper' })
+ expect(body.durationMs).toBe(500)
+
+ const action = lastAction()
+ expect(action.origin).toBe('http_api')
+ expect(action.purpose).toBe('api_text')
+ expect(action.triggerType).toBe('user')
+ expect(action.content).toEqual({ type: 'text', text: '你好' })
+ })
+
+ it('type 省略时按文本发送', async () => {
+ await post({ to: 'wxid_friend', text: 'hi' })
+ expect(lastAction().content).toEqual({ type: 'text', text: 'hi' })
+ })
+
+ it('群 id 自动判定为 group', async () => {
+ await post({ to: 'room@chatroom', text: 'hi' })
+ expect(lastAction().recipient).toEqual({ type: 'group', id: 'room@chatroom' })
+ })
+
+ it('idempotencyKey 原样透传给 Gateway', async () => {
+ await post({ to: 'filehelper', text: 'hi', idempotencyKey: 'agent-run-42' })
+ expect(lastAction().idempotencyKey).toBe('agent-run-42')
+ })
+
+ it('图片发送使用本地文件路径', async () => {
+ const imagePath = path.join(root, 'report.png')
+ await fs.writeFile(imagePath, 'png')
+ const response = await post({ to: 'filehelper', type: 'image', filePath: imagePath })
+ expect(response.status).toBe(200)
+ expect(lastAction().content).toEqual({ type: 'image', path: imagePath })
+ })
+
+ it('底层发送失败时返回 502 并带上 errorCode', async () => {
+ executeResult = sentResult({
+ status: 'failed',
+ decision: 'allow',
+ errorCode: 'SEND_FAILED',
+ reason: '微信发送失败'
+ })
+ const response = await post({ to: 'filehelper', text: 'hi' })
+ expect(response.status).toBe(502)
+ const body = await response.json()
+ expect(body.success).toBe(false)
+ expect(body.errorCode).toBe('SEND_FAILED')
+ expect(body.error).toBe('微信发送失败')
+ })
+
+ it('策略拒绝时返回 403', async () => {
+ executeResult = sentResult({
+ status: 'blocked',
+ decision: 'block',
+ errorCode: 'POLICY_BLOCKED',
+ reason: '该发送动作未通过策略检查'
+ })
+ const response = await post({ to: 'filehelper', text: 'hi' })
+ expect(response.status).toBe(403)
+ })
+})
diff --git a/tests/unit/wechat-action-gateway.test.ts b/tests/unit/wechat-action-gateway.test.ts
index 37c7ac3..1701727 100644
--- a/tests/unit/wechat-action-gateway.test.ts
+++ b/tests/unit/wechat-action-gateway.test.ts
@@ -524,6 +524,35 @@ describe('WechatActionGateway', () => {
expect(result.errorCode).toBe('INVALID_REQUEST')
expect(mocks.sender.send).not.toHaveBeenCalled()
})
+
+ it('放行 HTTP API 来源,并在审计里与人工发送区分开', async () => {
+ const userData = mkdtempSync(join(tmpdir(), 'tracememo-wechat-action-'))
+ directories.push(userData)
+ const gateway = new WechatActionGateway({ getUserDataPath: () => userData })
+
+ const result = await manualAction(gateway, {
+ origin: 'http_api',
+ purpose: 'api_text',
+ recipient: { type: 'contact', id: 'filehelper' },
+ content: { type: 'text', text: '来自 Agent' }
+ })
+
+ expect(result).toMatchObject({ status: 'sent', decision: 'allow' })
+ expect(mocks.sender.send).toHaveBeenCalledWith({
+ type: 'text',
+ to: 'filehelper',
+ isGroup: false,
+ text: '来自 Agent'
+ })
+ const audit = readJsonSync(join(userData, 'actions', 'wechat-actions.json'))
+ expect(audit[0]).toMatchObject({
+ origin: 'http_api',
+ purpose: 'api_text',
+ triggerType: 'user',
+ recipientId: 'filehelper',
+ sendStatus: 'sent'
+ })
+ })
})
describe('toPersonalWechatSendResult', () => {
From a0c729374fa2d3b30e0a08e996c94e04af8bad4e Mon Sep 17 00:00:00 2001
From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com>
Date: Mon, 26 Oct 2026 09:54:09 +0800
Subject: [PATCH 5/6] =?UTF-8?q?chore:=20=E4=BF=AE=E6=94=B9=E6=89=93?=
=?UTF-8?q?=E5=8C=85=E9=85=8D=E7=BD=AE?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
electron-builder.win.yml | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/electron-builder.win.yml b/electron-builder.win.yml
index 7d6c0ec..2f07f2e 100644
--- a/electron-builder.win.yml
+++ b/electron-builder.win.yml
@@ -39,6 +39,11 @@ extraResources:
- runtime/win32/**
- wcdb/win32/x64/**
- '!wcdb/**/tm-wcdb-config-helper*'
+ # 默认不打包helper
+ # - from: resources/wcdb/win32/x64
+ # to: resources/wcdb/win32/x64
+ # filter:
+ # - 'tm-wcdb-config-helper.exe'
- from: docs/skill/tracememo-reader
to: skill/tracememo-reader
filter:
From e17e2d908edfd258630568b9c34d7f42b6278d7e Mon Sep 17 00:00:00 2001
From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com>
Date: Tue, 27 Oct 2026 15:45:52 +0800
Subject: [PATCH 6/6] =?UTF-8?q?chore:=20=E6=8F=90=E5=8D=87=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
package.json | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/package.json b/package.json
index a24165b..806204a 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "tracememo",
- "version": "2.5.1",
+ "version": "2.5.2",
"packageManager": "pnpm@7.33.7",
"description": "TraceMemo(迹忆)是一款本地优先、可追溯的 AI 微信知识与分析工作台。 原名 WechatExplorer,支持聊天记录搜索、知识库、微信群聊总结和 Agent 助手。",
"keywords": [
@@ -175,4 +175,4 @@
"ffmpeg-static"
]
}
-}
+}
\ No newline at end of file