mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 17:25:15 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ea73c3414 | ||
|
|
b20e514c90 | ||
|
|
fccca5b459 | ||
|
|
a47756795c | ||
|
|
9b2174a097 | ||
|
|
dc7b46aa38 | ||
|
|
a7df502219 | ||
|
|
9b9a1722cd | ||
|
|
8f37ded71e | ||
|
|
eac16ad8a7 | ||
|
|
518a9662a7 | ||
|
|
0edbf60b2e | ||
|
|
bc3a560830 | ||
|
|
c0b921c109 | ||
|
|
e89980f7a0 | ||
|
|
9238c6694b | ||
|
|
d436b064c3 | ||
|
|
b86582e606 | ||
|
|
0c6bf3ec2b | ||
|
|
4b533f035a |
No files matched your search
+15
@@ -39,3 +39,18 @@ debug-originals
|
||||
|
||||
# 官方扩展模板构建产物(由 scripts/build-extension-templates.cjs 生成)
|
||||
/build/extension-templates/
|
||||
|
||||
# 诊断产物与数据库快照(含密钥派生脚本、消息正文、zstd blob)——严禁入库
|
||||
/dump*.js
|
||||
/dump*.cjs
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.zst
|
||||
/snapshot/
|
||||
/blobs/
|
||||
/database-keys/
|
||||
|
||||
.dev-verify/
|
||||
@@ -137,7 +137,7 @@ TraceMemo 最早叫 **WechatExplorer**。
|
||||
## 💬 交流与反馈
|
||||
|
||||
<p align="center">
|
||||
<img src="./public/二维码.png" alt="TraceMemo 交流与售后群二维码" width="280" />
|
||||
<img src="./public/二维码.jpg" alt="TraceMemo 交流与售后群二维码" width="280" />
|
||||
</p>
|
||||
|
||||
## 从你的任务开始
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
!include "LogicLib.nsh"
|
||||
!include "getProcessInfo.nsh"
|
||||
|
||||
Var tmSelfPid
|
||||
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
Var tmTempRedirected
|
||||
Var tmOrigTemp
|
||||
Var tmOrigTmp
|
||||
Var tmAltTempDir
|
||||
Var tmOldInstDir
|
||||
Var tmOldDrive
|
||||
Var tmTempDrive
|
||||
!endif
|
||||
|
||||
!macro TM_FIND_PROCESS _FILE _ERR
|
||||
!ifdef INSTALL_MODE_PER_ALL_USERS
|
||||
${nsProcess::FindProcess} "${_FILE}" ${_ERR}
|
||||
!else
|
||||
nsExec::Exec `"$SYSDIR\cmd.exe" /c tasklist /FI "USERNAME eq %USERNAME%" /FI "IMAGENAME eq ${_FILE}" /FO csv | "$SYSDIR\find.exe" /I "${_FILE}"`
|
||||
Pop ${_ERR}
|
||||
!endif
|
||||
!macroend
|
||||
|
||||
!macro TM_TASKKILL_SOFT _FILE _PID
|
||||
!ifdef INSTALL_MODE_PER_ALL_USERS
|
||||
nsExec::Exec `taskkill /im "${_FILE}" /fi "PID ne ${_PID}"`
|
||||
!else
|
||||
nsExec::Exec `"$SYSDIR\cmd.exe" /c taskkill /im "${_FILE}" /fi "PID ne ${_PID}" /fi "USERNAME eq %USERNAME%"`
|
||||
!endif
|
||||
Pop $R9
|
||||
!macroend
|
||||
|
||||
!macro TM_TASKKILL_FORCE_TREE _FILE _PID
|
||||
!ifdef INSTALL_MODE_PER_ALL_USERS
|
||||
nsExec::Exec `taskkill /f /t /im "${_FILE}" /fi "PID ne ${_PID}"`
|
||||
!else
|
||||
nsExec::Exec `"$SYSDIR\cmd.exe" /c taskkill /f /t /im "${_FILE}" /fi "PID ne ${_PID}" /fi "USERNAME eq %USERNAME%"`
|
||||
!endif
|
||||
Pop $R9
|
||||
!macroend
|
||||
|
||||
!macro customHeader
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
; 旧版卸载器在 --updated 模式下会把文件 Rename 到 %TEMP% 下的 $PLUGINSDIR\old-install。
|
||||
; 若旧版装在非系统盘,把子进程继承的 TEMP/TMP 暂指同盘符可写目录,避免跨卷 Rename 必败。
|
||||
Function tmPrepareCrossDriveUpdateTemp
|
||||
Push $0
|
||||
Push $1
|
||||
|
||||
StrCpy $tmTempRedirected "0"
|
||||
StrCpy $tmAltTempDir ""
|
||||
StrCpy $tmOldInstDir ""
|
||||
|
||||
ReadRegStr $tmOldInstDir SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation
|
||||
${if} $tmOldInstDir == ""
|
||||
ReadRegStr $tmOldInstDir HKEY_CURRENT_USER "${INSTALL_REGISTRY_KEY}" InstallLocation
|
||||
${endIf}
|
||||
${if} $tmOldInstDir == ""
|
||||
StrCpy $tmOldInstDir "$INSTDIR"
|
||||
${endIf}
|
||||
|
||||
StrCpy $tmOldDrive $tmOldInstDir 2
|
||||
StrCpy $tmTempDrive $TEMP 2
|
||||
${if} $tmOldDrive == ""
|
||||
${orIf} $tmTempDrive == ""
|
||||
${orIf} $tmOldDrive == $tmTempDrive
|
||||
Goto tm_temp_done
|
||||
${endIf}
|
||||
|
||||
StrCpy $0 $tmOldInstDir 1 -1
|
||||
${if} $0 == "\"
|
||||
StrCpy $tmOldInstDir $tmOldInstDir -1
|
||||
${endIf}
|
||||
|
||||
StrCpy $tmAltTempDir "$tmOldInstDir._tm_upd_tmp"
|
||||
CreateDirectory "$tmAltTempDir"
|
||||
ClearErrors
|
||||
FileOpen $1 "$tmAltTempDir\.probe" w
|
||||
${if} ${Errors}
|
||||
StrCpy $tmAltTempDir "$tmOldDrive\.tracememo_upd_tmp"
|
||||
CreateDirectory "$tmAltTempDir"
|
||||
ClearErrors
|
||||
FileOpen $1 "$tmAltTempDir\.probe" w
|
||||
${if} ${Errors}
|
||||
StrCpy $tmAltTempDir ""
|
||||
Goto tm_temp_done
|
||||
${endIf}
|
||||
${endIf}
|
||||
FileClose $1
|
||||
Delete "$tmAltTempDir\.probe"
|
||||
|
||||
ReadEnvStr $tmOrigTemp "TEMP"
|
||||
ReadEnvStr $tmOrigTmp "TMP"
|
||||
System::Call 'kernel32::SetEnvironmentVariableW(w "TEMP", w "$tmAltTempDir") i.r0'
|
||||
System::Call 'kernel32::SetEnvironmentVariableW(w "TMP", w "$tmAltTempDir") i.r0'
|
||||
StrCpy $tmTempRedirected "1"
|
||||
|
||||
tm_temp_done:
|
||||
Pop $1
|
||||
Pop $0
|
||||
FunctionEnd
|
||||
|
||||
Function tmRestoreCrossDriveUpdateTemp
|
||||
Push $0
|
||||
${if} $tmTempRedirected == "1"
|
||||
${if} $tmOrigTemp != ""
|
||||
System::Call 'kernel32::SetEnvironmentVariableW(w "TEMP", w "$tmOrigTemp") i.r0'
|
||||
${endIf}
|
||||
${if} $tmOrigTmp != ""
|
||||
System::Call 'kernel32::SetEnvironmentVariableW(w "TMP", w "$tmOrigTmp") i.r0'
|
||||
${endIf}
|
||||
${if} $tmAltTempDir != ""
|
||||
RMDir /r "$tmAltTempDir"
|
||||
${endIf}
|
||||
StrCpy $tmTempRedirected "0"
|
||||
${endIf}
|
||||
Pop $0
|
||||
FunctionEnd
|
||||
!else
|
||||
Var /GLOBAL tmOldBackupRoot
|
||||
|
||||
Function un.tmAtomicMoveToBackup
|
||||
Exch $R0
|
||||
Push $R1
|
||||
Push $R2
|
||||
Push $R3
|
||||
|
||||
StrCpy $R3 "$INSTDIR$R0\*.*"
|
||||
FindFirst $R1 $R2 $R3
|
||||
|
||||
tm_move_loop:
|
||||
StrCmp $R2 "" tm_move_break
|
||||
StrCmp $R2 "." tm_move_continue
|
||||
StrCmp $R2 ".." tm_move_continue
|
||||
|
||||
IfFileExists "$INSTDIR$R0\$R2\*.*" tm_move_is_dir tm_move_is_file
|
||||
|
||||
tm_move_is_dir:
|
||||
CreateDirectory "$tmOldBackupRoot$R0\$R2"
|
||||
Push "$R0\$R2"
|
||||
Call un.tmAtomicMoveToBackup
|
||||
Pop $R3
|
||||
${if} $R3 != 0
|
||||
Goto tm_move_done
|
||||
${endIf}
|
||||
Goto tm_move_continue
|
||||
|
||||
tm_move_is_file:
|
||||
ClearErrors
|
||||
Rename "$INSTDIR$R0\$R2" "$tmOldBackupRoot$R0\$R2"
|
||||
StrCmp "$R0\$R2" "\${UNINSTALL_FILENAME}" 0 +2
|
||||
ClearErrors
|
||||
StrCmp "$R0\$R2" "${UNINSTALL_FILENAME}" 0 +2
|
||||
ClearErrors
|
||||
|
||||
IfErrors 0 +3
|
||||
StrCpy $R3 "$INSTDIR$R0\$R2"
|
||||
Goto tm_move_done
|
||||
|
||||
tm_move_continue:
|
||||
FindNext $R1 $R2
|
||||
Goto tm_move_loop
|
||||
|
||||
tm_move_break:
|
||||
StrCpy $R3 0
|
||||
|
||||
tm_move_done:
|
||||
FindClose $R1
|
||||
StrCpy $R0 $R3
|
||||
Pop $R3
|
||||
Pop $R2
|
||||
Pop $R1
|
||||
Exch $R0
|
||||
FunctionEnd
|
||||
|
||||
Function un.tmRestoreFromBackup
|
||||
Exch $R0
|
||||
Push $R1
|
||||
Push $R2
|
||||
Push $R3
|
||||
|
||||
StrCpy $R3 "$tmOldBackupRoot$R0\*.*"
|
||||
FindFirst $R1 $R2 $R3
|
||||
|
||||
tm_restore_loop:
|
||||
StrCmp $R2 "" tm_restore_break
|
||||
StrCmp $R2 "." tm_restore_continue
|
||||
StrCmp $R2 ".." tm_restore_continue
|
||||
|
||||
IfFileExists "$tmOldBackupRoot$R0\$R2\*.*" tm_restore_is_dir tm_restore_is_file
|
||||
|
||||
tm_restore_is_dir:
|
||||
CreateDirectory "$INSTDIR$R0\$R2"
|
||||
Push "$R0\$R2"
|
||||
Call un.tmRestoreFromBackup
|
||||
Pop $R3
|
||||
Goto tm_restore_continue
|
||||
|
||||
tm_restore_is_file:
|
||||
Rename "$tmOldBackupRoot$R0\$R2" "$INSTDIR$R0\$R2"
|
||||
|
||||
tm_restore_continue:
|
||||
FindNext $R1 $R2
|
||||
Goto tm_restore_loop
|
||||
|
||||
tm_restore_break:
|
||||
StrCpy $R0 0
|
||||
FindClose $R1
|
||||
Pop $R3
|
||||
Pop $R2
|
||||
Pop $R1
|
||||
Exch $R0
|
||||
FunctionEnd
|
||||
!endif
|
||||
!macroend
|
||||
|
||||
!macro customCheckAppRunning
|
||||
${GetProcessInfo} 0 $tmSelfPid $1 $2 $3 $4
|
||||
${if} $3 != "${APP_EXECUTABLE_FILENAME}"
|
||||
${if} ${isUpdated}
|
||||
Sleep 500
|
||||
${endIf}
|
||||
|
||||
!insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0
|
||||
${if} $R0 == 0
|
||||
${if} ${isUpdated}
|
||||
Sleep 1000
|
||||
!insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0
|
||||
${if} $R0 != 0
|
||||
Goto tm_app_not_running
|
||||
${endIf}
|
||||
Goto tm_do_stop_process
|
||||
${endIf}
|
||||
MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "$(appRunning)" /SD IDOK IDOK tm_do_stop_process
|
||||
Quit
|
||||
|
||||
tm_do_stop_process:
|
||||
DetailPrint `Closing running "${PRODUCT_NAME}"...`
|
||||
!insertmacro TM_TASKKILL_SOFT "${APP_EXECUTABLE_FILENAME}" $tmSelfPid
|
||||
Sleep 500
|
||||
|
||||
StrCpy $R1 0
|
||||
|
||||
tm_stop_loop:
|
||||
IntOp $R1 $R1 + 1
|
||||
|
||||
!insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0
|
||||
${if} $R0 == 0
|
||||
Sleep 1000
|
||||
!insertmacro TM_TASKKILL_FORCE_TREE "${APP_EXECUTABLE_FILENAME}" $tmSelfPid
|
||||
Sleep 500
|
||||
!insertmacro TM_FIND_PROCESS "${APP_EXECUTABLE_FILENAME}" $R0
|
||||
${if} $R0 == 0
|
||||
DetailPrint `Waiting for "${PRODUCT_NAME}" to close.`
|
||||
Sleep 1500
|
||||
${else}
|
||||
Goto tm_app_not_running
|
||||
${endIf}
|
||||
${else}
|
||||
Goto tm_app_not_running
|
||||
${endIf}
|
||||
|
||||
${if} $R1 > 1
|
||||
MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "$(appCannotBeClosed)" /SD IDCANCEL IDRETRY tm_stop_loop
|
||||
Quit
|
||||
${else}
|
||||
Goto tm_stop_loop
|
||||
${endIf}
|
||||
|
||||
tm_app_not_running:
|
||||
${endIf}
|
||||
${endIf}
|
||||
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
Call tmPrepareCrossDriveUpdateTemp
|
||||
!endif
|
||||
!macroend
|
||||
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
!macro customInstall
|
||||
Call tmRestoreCrossDriveUpdateTemp
|
||||
!macroend
|
||||
!endif
|
||||
|
||||
!ifdef BUILD_UNINSTALLER
|
||||
; 同盘符沿用原生 $PLUGINSDIR\old-install,跨盘符改用同卷旁路目录避免 Rename 必败。
|
||||
!macro customRemoveFiles
|
||||
${if} ${isUpdated}
|
||||
StrCpy $0 $INSTDIR 2
|
||||
StrCpy $1 $PLUGINSDIR 2
|
||||
${if} $0 == $1
|
||||
CreateDirectory "$PLUGINSDIR\old-install"
|
||||
Push ""
|
||||
Call un.atomicRMDir
|
||||
Pop $R0
|
||||
${if} $R0 != 0
|
||||
DetailPrint "File is busy, aborting: $R0"
|
||||
Push ""
|
||||
Call un.restoreFiles
|
||||
Pop $R0
|
||||
Abort `Can't rename "$INSTDIR" to "$PLUGINSDIR\old-install".`
|
||||
${endIf}
|
||||
${else}
|
||||
StrCpy $2 $INSTDIR
|
||||
StrCpy $3 $2 1 -1
|
||||
${if} $3 == "\"
|
||||
StrCpy $2 $2 -1
|
||||
${endIf}
|
||||
StrCpy $tmOldBackupRoot "$2._tm_old"
|
||||
RMDir /r "$tmOldBackupRoot"
|
||||
CreateDirectory "$tmOldBackupRoot"
|
||||
|
||||
ClearErrors
|
||||
FileOpen $4 "$tmOldBackupRoot\.probe" w
|
||||
${ifNot} ${Errors}
|
||||
FileClose $4
|
||||
Delete "$tmOldBackupRoot\.probe"
|
||||
Push ""
|
||||
Call un.tmAtomicMoveToBackup
|
||||
Pop $R0
|
||||
${if} $R0 != 0
|
||||
DetailPrint "File is busy, aborting: $R0"
|
||||
Push ""
|
||||
Call un.tmRestoreFromBackup
|
||||
Pop $R0
|
||||
RMDir /r "$tmOldBackupRoot"
|
||||
Abort `Can't rename "$INSTDIR" to "$tmOldBackupRoot".`
|
||||
${endIf}
|
||||
RMDir /r "$tmOldBackupRoot"
|
||||
${else}
|
||||
; 父目录不可写时检测主程序是否被锁,未锁再清理安装目录。
|
||||
${if} ${FileExists} "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
|
||||
ClearErrors
|
||||
Rename "$INSTDIR\${APP_EXECUTABLE_FILENAME}" "$INSTDIR\${APP_EXECUTABLE_FILENAME}.tm_bak"
|
||||
${if} ${Errors}
|
||||
Abort `File is busy: "$INSTDIR\${APP_EXECUTABLE_FILENAME}".`
|
||||
${endIf}
|
||||
Rename "$INSTDIR\${APP_EXECUTABLE_FILENAME}.tm_bak" "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
|
||||
${endIf}
|
||||
${endIf}
|
||||
${endIf}
|
||||
${endIf}
|
||||
|
||||
RMDir /r $INSTDIR
|
||||
!macroend
|
||||
!endif
|
||||
@@ -54,6 +54,7 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A
|
||||
- [扩展 API 参考](./extensions/api-reference.md)
|
||||
- [界面开发规范:按钮与主题色](./development/ui-guidelines.md)
|
||||
- [微信系统消息解析与格式兼容](./development/wechat-system-message-parsing.md)
|
||||
- [企业微信插件会话只读验收](./development/wecom-enterprise-acceptance.md)
|
||||
- [Query Agent POC(开发测试入口)](./development/query-agent-poc.md)
|
||||
- [本地启动排障](./development/local-startup-troubleshooting.md)
|
||||
- [macOS 数据访问说明](./platform/macos.md)
|
||||
|
||||
+10
-3
@@ -87,7 +87,7 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A
|
||||
| 身份 | 你本人当前登录的微信账号 | 已扫码接入的机器人 |
|
||||
| 用途 | **以你的身份把消息发给别人**(好友 / 群 / 文件传输助手) | **机器人给自己发通知**(测试连通性) |
|
||||
| 前置条件 | 本机微信已启动,发送能力为 `ready` | 连接器为 `online` |
|
||||
| 内容类型 | `text` / `image` / `voice`,媒体只接受本地文件 | `text` / `image`(URL 或本地路径) |
|
||||
| 内容类型 | `text` / `image` / `voice` / `file`,媒体只接受本地文件 | `text` / `image`(URL 或本地路径) |
|
||||
| 典型失败 | 能力未就绪 `503`、发送失败 `502` | 连接器离线 `503`、凭证过期 `401` |
|
||||
|
||||
### 本地发送:`POST /api/v1/wechat/send`
|
||||
@@ -100,6 +100,12 @@ 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 的一条消息"}'
|
||||
|
||||
# 发送本地文件(macOS / Windows 均走本机发送能力)
|
||||
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":"file","filePath":"/abs/path/report.pdf","fileName":"周报.pdf"}'
|
||||
```
|
||||
|
||||
请求体:
|
||||
@@ -107,9 +113,10 @@ curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \
|
||||
| 字段 | 必填 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `to` | 是 | 接收者:好友 wxid、群 id(以 `@chatroom` 结尾),或 `filehelper`(文件传输助手)。**不做昵称解析**,先调 `/api/v1/resolve?q=张三` 换 wxid |
|
||||
| `type` | 否 | `text`(默认)/ `image` / `voice` |
|
||||
| `type` | 否 | `text`(默认)/ `image` / `voice` / `file` |
|
||||
| `text` | `type=text` 时必填 | **最长 2000 字符**,超限返回 `400`,不会截断 |
|
||||
| `filePath` | `type=image\|voice` 时必填 | 本机**绝对路径**,必须已存在。不接受 URL —— 需要发网络图片时先落盘 |
|
||||
| `filePath` | `type=image\|voice\|file` 时必填 | 本机**绝对路径**,必须已存在。不接受 URL —— 需要发网络文件时先落盘 |
|
||||
| `fileName` | 否 | 仅 `type=file`:接收方看到的文件名。macOS 会透传;Windows 当前由 runtime 使用 `filePath` 的 basename,`fileName` 可能被忽略 |
|
||||
| `isGroup` | 否 | 通常可省略;`to` 以 `@chatroom` 结尾时自动判为群 |
|
||||
| `idempotencyKey` | 否 | 幂等键。**重试时请原样带上**,避免 Agent 超时重发导致重复消息 |
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
# 企业微信插件会话:只读验收报告
|
||||
|
||||
本文记录 Mac 微信 4.x 企业微信插件会话(群 `*@qy_g`、单聊 `*@qy_u`)在 TraceMemo 中的
|
||||
真实数据验收结果,用于回答 review 中「需要真实环境证据」的那一项。
|
||||
|
||||
结论先行:**会话列表、群名、群成员、消息、发送者、图片六条链路在真实库上都已跑通**,
|
||||
且全程只读;报告中所有会话 id、群名、成员名、消息正文均以 sha256 前缀代替,不含原文。
|
||||
|
||||
## 验收环境
|
||||
|
||||
| 项 | 值 |
|
||||
| --- | --- |
|
||||
| 客户端 | Mac 微信 4.x(企业微信插件会话已存在) |
|
||||
| 账号规模 | 5521 个会话,其中企业会话 7 个 = 5 个 `@qy_g` 群 + 2 个 `@qy_u` 单聊 |
|
||||
| 消息库 | `db_storage`(会话/消息)+ `bizchat/bizchat.db`(企业群名与成员) |
|
||||
| 运行方式 | 以只读模式(`TRACEMEMO_READ_ONLY=1`)直接调用主进程的 `Wcdb4Client` / `chat-service` |
|
||||
| 数据隔离 | 数据库目录用 APFS clone(写时复制)复制后再读;媒体目录只做 `existsSync`/`readFileSync` |
|
||||
|
||||
### 只读是怎么保证的
|
||||
|
||||
1. 数据库侧:`src/main/wcdb4-client.ts` 中不存在 `writeFileSync` / `mkdirSync` / `renameSync` /
|
||||
`unlinkSync` 等写调用,所有 SQL 都是 `SELECT`;验收时读的是 clone 出来的副本。
|
||||
2. 媒体侧:只读取 `msg/attach/<session md5>/<YYYY-MM>/Img|Thumb` 下的 `.dat` 文件,
|
||||
不写回、不删除、不改名。
|
||||
3. 密钥:数据库密钥与图片 AES 密钥从本机已有的安全存储中取出后仅用于本次进程内解密,
|
||||
不落盘、不进入任何报告或提交。
|
||||
|
||||
## 六条链路的实测结果
|
||||
|
||||
### 1. 会话列表与群名(冷启动顺序无关)
|
||||
|
||||
`getSessions()` 是同步路径,会在异步 hydration 之前返回;旧实现只读 `displayNameCache`,
|
||||
冷启动第一次取群名时缓存为空,就会把 `ww...@qy_g` 原样当群名显示。现在的
|
||||
`resolveSessionNickname()` 统一走「企业群名 → 缓存 → 会话昵称 → username」,
|
||||
并且 `getEnterpriseGroupName()` 在缓存未命中时同步查一次 `bizchat.chat_group.chat_name`。
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 冷启动同步列表里 5 个企业群是否用 raw id 当群名 | 0/5(全部已解析) |
|
||||
| 2 个企业单聊 | 保持自身昵称(单聊本无群名,符合预期) |
|
||||
| 异步 `getSessionsAsync({hydrateDisplayNames:true})` 之后 | 5 个群名与冷启动完全一致 |
|
||||
| `getGroupNamesAsync()`(退群提示/自动化取群名) | 5/5 企业群在列,名字与会话列表一致 |
|
||||
|
||||
### 2. 联系人列表(群列表与群日报的群名来源)
|
||||
|
||||
群日报的 `groupName` 取 `contact.m_nsNickName`,并过滤内部标识符
|
||||
(`src/renderer/src/utils/group-report-facts.ts:114`)。用真实的 `listContactsAsync()` 复核:
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 7 个企业会话是否都出现在联系人列表 | 7/7 |
|
||||
| `type` 判定 | 5 个 `group`(`@qy_g`)、2 个 `user`(`@qy_u`) |
|
||||
| 群名能否通过 `isInternalIdentifier` 过滤(即日报不显示「未命名会话」) | 7/7 |
|
||||
|
||||
### 3. 群成员(失败与空列表已区分)
|
||||
|
||||
`getEnterpriseGroupMembers(Async)` 现在返回 `Wcdb4GroupMember[] | null`:
|
||||
读不到(缺 native 入口、非 `@qy_g`、查询抛错)返回 `null`,只有 `user_list` 真正为空才返回 `[]`。
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 5 个企业群的群快照 | 5/5 可解析 |
|
||||
| 群名与同步通道一致 | 5/5 |
|
||||
| 成员数 | 每群 2 人 |
|
||||
| 成员显示名(`user_info.user_name`) | 2/2 每群都解析到非 id 名称 |
|
||||
|
||||
### 4. 消息数量与发送者
|
||||
|
||||
90 天窗口,每会话最多 500 条:
|
||||
|
||||
| 会话 | 消息数 | 发送者已解析 | 不同发送者 |
|
||||
| --- | --- | --- | --- |
|
||||
| 企业群 A | 350 | 350/350 | 2 |
|
||||
| 企业群 B | 500 | 500/500 | 1 |
|
||||
| 企业群 C | 379 | 379/379 | 1 |
|
||||
| 企业群 D | 369 | 369/369 | 2 |
|
||||
| 企业群 E | 61 | 61/61 | 1 |
|
||||
| 企业单聊 1 | 10 | 10/10 | 2 |
|
||||
| 企业单聊 2 | 3 | 3/3 | 1 |
|
||||
|
||||
所有会话的发送者解析率均为 100%:企业消息的 `source` 是 zstd 压缩的
|
||||
`enterprise_info` XML,`parseEnterpriseSource()` 从中取 `sender` / `nickname` / `bizchat_id`。
|
||||
|
||||
### 5. 图片
|
||||
|
||||
企业图片的 `message_content` 里**没有 md5**(只有 `aeskey` / `encryver` / CDN 地址等属性),
|
||||
所以不能用普通消息的 md5 路线定位文件。实际链路是:`packed_info_data` → `parseImageDatNameFromRow()`
|
||||
解出 32 位 datName → 在 `msg/attach/<session md5>/<YYYY-MM>/Img` 命中 `.dat` → 用图片 AES 密钥解密。
|
||||
|
||||
| 会话 | 图片数 | 抽样 | 定位到文件 | 解密成功 | 格式 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 企业群 A | 188 | 5 | 5/5 | 5/5 | JPEG / PNG |
|
||||
| 企业群 B | 316 | 5 | 5/5 | 5/5 | JPEG |
|
||||
| 企业群 C | 184 | 5 | 5/5 | 5/5 | JPEG |
|
||||
| 企业群 D | 184 | 5 | 5/5 | 5/5 | JPEG / PNG |
|
||||
| 企业群 E | 0 | — | — | — | 该群 90 天内只有文字 |
|
||||
| 企业单聊 1 | 1 | 1 | 1/1 | 1/1 | PNG |
|
||||
| 企业单聊 2 | 0 | — | — | — | — |
|
||||
|
||||
解密结果按文件头判定(`FF D8 FF` / `89 50 4E 47`),不是「解出非空 buffer」就算通过。
|
||||
|
||||
### 6. 企业群的成员批量读取与退群监控
|
||||
|
||||
native 的 `wcdb_get_group_members_batch` **只认 `@chatroom`**。实测:
|
||||
|
||||
- 只请求 3 个普通群 → 正常返回,成员数 500 / 412 / 488;
|
||||
- 只请求 5 个企业群 → 整批失败(nativeCode `-2001`);
|
||||
- 混合请求 3 个普通群 + 5 个企业群 → **整批失败**,普通群的结果也一起丢掉。
|
||||
|
||||
因此在 `chat-service.getGroupMemberIdsBatchAsync()` 里按通道分流:普通群仍走一次 native 批量,
|
||||
企业群逐个走 bizchat 成员通道,最后按调用方请求顺序合并。修复后同一批 8 个会话返回 8 条结果
|
||||
(普通群 500 / 412 / 488,企业群各 2),不再互相拖累。
|
||||
|
||||
退群监控侧(`src/main/services/group-exit-monitor-service.ts`):
|
||||
|
||||
- `normalizeRoomIds()`(:914)与 `normalizeSnapshots()`(:951)都要求 `@chatroom`,
|
||||
所以 `@qy_g` 永远进不了 `monitoredRoomIds`,也不会被写进持久化快照;
|
||||
- 只有「微信内退群提示」开着时,`@qy_g` 才会经 `getGroupNamesAsync()` 进入检测范围;
|
||||
- 此时成员读取失败(`null`)会得到 `membersValid === false`,`applyCurrentMemberships()`
|
||||
直接 `continue`,不会把「读不到」当成「全员退群」。
|
||||
|
||||
## 复现方式(不含任何密钥)
|
||||
|
||||
1. 以只读模式启动主进程,指向 clone 出来的 `db_storage`;
|
||||
2. 调 `getSessions()` 看冷启动群名,再调 `getSessionsAsync({hydrateDisplayNames:true})` 比对;
|
||||
3. 调 `listContactsAsync()` / `getGroupNamesAsync()` / `getGroupSnapshotAsync()` 复核群名与成员;
|
||||
4. 调 `getMessages()` 统计消息数、发送者解析率与图片数;
|
||||
5. 对图片样本调 `parseImageDatNameFromRow()` + `ImageDecryptService.findImageFileAsync()` + `decryptImage()`;
|
||||
6. 调 `getGroupMemberIdsBatchAsync()` 混合普通群与企业群,确认不再整批失败。
|
||||
|
||||
## 隐私说明
|
||||
|
||||
- 本文只出现 sha256 前缀、计数与布尔判定,不含 wxid、群名、成员名、消息正文、文件路径或密钥;
|
||||
- 验收脚本与原始 JSON 均为本机临时产物,不在仓库内,也不会进入提交历史。
|
||||
+111
-107
@@ -8,7 +8,7 @@
|
||||
| `id` | 是 | 反向域名,小写;禁止 `com.tracememo.` / `tracememo.` / `tm.` 前缀 |
|
||||
| `name` | 是 | 展示名,≤ 64 字 |
|
||||
| `version` | 是 | `x.y.z`(可带 prerelease) |
|
||||
| `apiVersion` | 是 | 必须为 `1` |
|
||||
| `apiVersion` | 是 | 必须为 `1`(向后兼容所有 v1 扩展) |
|
||||
| `minAppVersion` | 否 | 低于该版本拒绝安装 |
|
||||
| `description` / `author` / `homepage` | 否 | 展示用;homepage 仅接受 http(s) |
|
||||
| `permissions` | 是 | 见权限表;未知权限直接判 manifest 非法 |
|
||||
@@ -16,6 +16,7 @@
|
||||
| `entrypoints.background` | 二选一 | 后台入口相对路径 |
|
||||
| `subscriptions` | 条件 | 申请 `messages.subscribe` 时必填 |
|
||||
| `contributions.pages` | 否 | `[{ id, title, entry? }]`,`id` 形如 `settings` |
|
||||
| `contributions.navigation` | 否 | `{ label, icon?, pageId?, order? }`,供用户「固定到一级菜单」;`icon` 仅支持内置安全图标集 `spark / bot / digest / bell / media / puzzle / compass / message` |
|
||||
| `contributions.automationActions` | 否 | `[{ id, title, description? }]`,有此项必须提供 background |
|
||||
|
||||
路径规则:相对路径、不允许 `..`、反斜杠、盘符、控制字符、Windows 保留名;
|
||||
@@ -26,24 +27,31 @@
|
||||
| 权限 | 风险 | 能力 |
|
||||
| --- | --- | --- |
|
||||
| `messages.subscribe` | 高 | 接收 `message.received` |
|
||||
| `messages.query` | 高 | `tm.messages.query` |
|
||||
| `messages.query` | 高 | `tm.messages.query`(支持游标分页与类型过滤) |
|
||||
| `media.read` | 高 | `tm.media.readImage` / `readVoice` / `readVideo`(按需解密并写入扩展私有缓存目录) |
|
||||
| `media.ocr` | 中 | `tm.media.ocrImage`(纯本地系统 OCR,优先复用既有索引缓存) |
|
||||
| `media.transcribe` | 中 | `tm.media.transcribeVoice`(复用 `VoiceTranscriptionGateway` 与转写缓存) |
|
||||
| `contacts.list` | 中 | 配置页读取群列表(`contacts.listGroups`),不含聊天内容 |
|
||||
| `wechat.send.text` | 高 | `tm.wechat.send`(文本)与自动化 `reply` |
|
||||
| `wechat.send.image` | 高 | `tm.wechat.send({ type: 'image' })` |
|
||||
| `wechat.send.video` | 高 | `tm.wechat.send({ type: 'video' })`,原生 Host 走 `/SendMsg` video |
|
||||
| `wechat.send.voice` | 高 | `tm.wechat.send({ type: 'voice' })`,支持传入 `text` 用宿主 TTS 音色合成发送或传入音频 `path` |
|
||||
| `ai.chat` | 中 | `tm.ai.chat` |
|
||||
| `ai.vision` | 中 | `tm.media.analyzeImage` / `tm.ai.analyzeImage`(复用已配置的视觉 AI Provider) |
|
||||
| `render.html` | 低 | `tm.render.htmlToImage`(离线隔离渲染静态 HTML/CSS 为 PNG 长图) |
|
||||
| `notifications.create` | 中 | `tm.notifications.create`(写入扩展通知中心与未读角标) |
|
||||
| `storage` | 低 | `tm.storage.*` 与页面存储 |
|
||||
| `automation.action` | 中 | `tm.automation.registerAction` |
|
||||
| `secrets` | 中 | `tm.secrets.*`(经系统安全存储加密保存私有凭据) |
|
||||
|
||||
安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。
|
||||
安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。所有权限均由主进程独立校验,不依赖 SDK 侧检查。
|
||||
|
||||
## 后台 API
|
||||
|
||||
### tm.extension
|
||||
|
||||
- `id: string`
|
||||
- `dataDir: string`(扩展私有数据目录,媒体文件写这里才能通过发送校验)
|
||||
- `dataDir: string`(扩展私有数据目录,媒体与渲染产物落盘于此)
|
||||
- `permissions: string[]`(当前已授予)
|
||||
|
||||
### tm.events
|
||||
@@ -51,109 +59,114 @@
|
||||
- `on('message.received', handler): () => void`
|
||||
- `off('message.received', handler): void`
|
||||
|
||||
事件字段见 `TraceMemoMessageEvent`:`eventId / accountId / conversationId / messageId /
|
||||
senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。
|
||||
事件字段见 `TraceMemoMessageEvent`:`eventId / messageRef / accountId / conversationId / messageId / senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。
|
||||
其中 `messageRef` 与 `tm.messages.query` 返回的 `messageRef` 格式完全统一,包含账号、会话与消息身份隔离校验。
|
||||
|
||||
### tm.messages.query
|
||||
|
||||
```ts
|
||||
await tm.messages.query({ conversationId, startTime?, endTime?, limit? })
|
||||
// → { messages: [{ messageId, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }] }
|
||||
await tm.messages.query({
|
||||
conversationId,
|
||||
startTime?,
|
||||
endTime?,
|
||||
limit?,
|
||||
cursor?,
|
||||
order?, // 'asc' | 'desc';省略时保持 v1 默认最新一页语义并支持向更早历史续页
|
||||
types? // 如 ['text', 'image', 'voice']
|
||||
})
|
||||
// → { messages: [{ messageId, messageRef, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }], nextCursor?, hasMore }
|
||||
```
|
||||
|
||||
- 时间参数是 **epoch 毫秒**;默认最近 24 小时。
|
||||
- 单次窗口最多 7 天,`limit` 上限 200。
|
||||
- 时间参数是 **epoch 毫秒**;默认最近 24 小时,单次最大 35 天,`limit` 上限 500。
|
||||
- 游标以 `(timestamp, messageId)` 为确定性边界,同时间戳多条消息分页不遗漏、不重复。
|
||||
- 数据库未连接时抛 `DATABASE_NOT_READY`。
|
||||
|
||||
### tm.media(扩展媒体 Gateway)
|
||||
|
||||
```ts
|
||||
// 按需读取媒体副本(写入扩展私有目录,不暴露原始微信数据库路径与密钥)
|
||||
await tm.media.readImage({ messageRef, quality?: 'original' | 'thumbnail' })
|
||||
await tm.media.readVoice({ messageRef })
|
||||
await tm.media.readVideo({ messageRef })
|
||||
|
||||
// 本地 OCR / 语音转写 / AI 图片理解(自动复用主程序缓存与并发限制)
|
||||
await tm.media.ocrImage({ messageRef, language?, force? })
|
||||
await tm.media.transcribeVoice({ messageRef, force?, waitMs? })
|
||||
await tm.media.analyzeImage({ messageRef, prompt?, force? })
|
||||
|
||||
// 批量按需处理(单次最多 20 项,并发上限 4,单项失败隔离返回)
|
||||
await tm.media.batch({
|
||||
concurrency: 2,
|
||||
items: [
|
||||
{ op: 'ocrImage', messageRef: imgRef },
|
||||
{ op: 'transcribeVoice', messageRef: voiceRef }
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
- 跨账号 `messageRef` 触发 `ACCOUNT_MISMATCH`;消息类型不匹配触发 `MEDIA_UNSUPPORTED`;缺失文件触发 `MEDIA_NOT_FOUND`;并发满载触发 `CONCURRENCY_LIMITED`。
|
||||
- `tm.ai.analyzeImage` 是 `tm.media.analyzeImage` 的等价别名,均要求 `ai.vision` 权限。
|
||||
|
||||
### tm.render.htmlToImage
|
||||
|
||||
```ts
|
||||
await tm.render.htmlToImage({
|
||||
html: '<main><h1>晨报</h1></main>',
|
||||
css: 'main { padding: 20px; }',
|
||||
fileName: 'morning-2026-12-01.png', // 可选,仅接受安全相对路径
|
||||
width: 460,
|
||||
maxHeight: 16000,
|
||||
backgroundColor: '#ffffff',
|
||||
timeoutMs: 20000
|
||||
})
|
||||
// → { path, previewUrl, width, height, pixelWidth, pixelHeight, deviceScaleFactor, bytes, mimeType: 'image/png', sha256 }
|
||||
```
|
||||
|
||||
- 与官方群聊日报共用同一 `HtmlRenderService` 离线渲染引擎。
|
||||
- 仅接受静态 HTML/CSS:自动拦截 `<script>`、`<iframe>`、内联事件、`javascript:`、`srcset`/`xlink:href` 与外链资源,独立窗口 + 临时 Session + 严格 CSP,输出至 `<dataDir>/rendered/`;生成路径可直接交给 `tm.wechat.send({ type: 'image', to, path })`,`previewUrl`(`tm-extension://<extensionId>/_data/rendered/...`)可直接用于扩展沙箱页面 `<img>` 预览。
|
||||
|
||||
### tm.notifications
|
||||
|
||||
```ts
|
||||
await tm.notifications.create({
|
||||
title: '今日晨报已生成',
|
||||
body: '覆盖 3 个群聊,共提炼 5 条重点',
|
||||
level: 'success', // 'info' | 'success' | 'warning' | 'error'
|
||||
dedupeKey: 'morning-2026-12-01',
|
||||
pageId: 'digest'
|
||||
})
|
||||
// → { id, deduped, createdAt }
|
||||
|
||||
const ownItems = await tm.notifications.list()
|
||||
const { changed } = await tm.notifications.markRead({ id: ownItems[0]?.id })
|
||||
```
|
||||
|
||||
- 由宿主持久化管理;同扩展相同 `dedupeKey` 仅更新内容不重复累加未读数,并受滑动窗口防刷屏限频保护(超限抛 `CONCURRENCY_LIMITED`)。
|
||||
- `list` 与 `markRead` 强绑定调用方 `extensionId`,只能读写本扩展自己的通知。
|
||||
- 已固定到一级菜单的扩展在固定入口显示独立未读角标;未固定扩展聚合到「扩展」导航的未读角标,与红色 `!` 发送能力异常提示严格区分。
|
||||
- 停用扩展拒绝写入新通知(`EXTENSION_DISABLED`);卸载扩展自动清理其全部通知状态。
|
||||
|
||||
### tm.wechat.send
|
||||
|
||||
```ts
|
||||
// 文本
|
||||
await tm.wechat.send({ to, text, at?, dedupeKey? })
|
||||
|
||||
// 图片
|
||||
await tm.wechat.send({ type: 'image', to, path: '/abs/path/cover.png', dedupeKey? })
|
||||
|
||||
// 视频(原生 Host 以 {toWxid, type:'video', msg:<路径>} 提交)
|
||||
await tm.wechat.send({ type: 'video', to, path: '/abs/path/clip.mp4', dedupeKey? })
|
||||
|
||||
// 语音(传 text 由宿主用已配置的 TTS 音色合成发送,或传 path 发送音频文件)
|
||||
await tm.wechat.send({ type: 'voice', to, text: '你好呀', voiceId?, dedupeKey? })
|
||||
// → { actionId, status: 'sent' }
|
||||
```
|
||||
|
||||
按顺序检查:权限 → 参数(文本 ≤ 2000 字)→ manifest 会话范围 → 频率
|
||||
(同扩展 2 秒一条、每分钟 10 条)→ 本机发送能力 → 授权校验 → Gateway。
|
||||
任何一步不通过都抛带错误码的异常,不会「静默丢弃」。
|
||||
按顺序检查:权限 → 参数 → manifest 会话范围 → 频率 → 本机发送能力 → Pro 授权校验 → Action Gateway。任何一步不通过都抛带错误码的异常。
|
||||
|
||||
媒体路径额外约束:
|
||||
### tm.ai.chat / tm.storage / tm.secrets / tm.automation / tm.capabilities / tm.log
|
||||
|
||||
- 必须是**绝对路径**的普通文件,realpath 后仍位于**扩展数据目录**或**系统临时目录**;
|
||||
- 大小 1B–100MB;
|
||||
- 图片扩展名:jpg/jpeg/png/gif/webp/bmp;视频扩展名:mp4/mov/m4v;
|
||||
- 视频走 `type: 'video'`,不复用图片通道;发送失败不会降级成图片。
|
||||
|
||||
### tm.ai.chat
|
||||
|
||||
```ts
|
||||
await tm.ai.chat([{ role: 'user', content: '...' }])
|
||||
// → { text }
|
||||
```
|
||||
|
||||
使用 TraceMemo 已配置的 AI Provider;扩展拿不到 API Key。
|
||||
|
||||
### tm.storage
|
||||
|
||||
```ts
|
||||
await tm.storage.set('config', { ... })
|
||||
await tm.storage.get('config')
|
||||
await tm.storage.remove('config')
|
||||
await tm.storage.list()
|
||||
```
|
||||
|
||||
键:`[A-Za-z0-9._-]{1,64}`;单值 ≤ 256KB,总量 ≤ 1MB;只接受 JSON 值。
|
||||
|
||||
### tm.automation.registerAction
|
||||
|
||||
```ts
|
||||
tm.automation.registerAction({ id, title, description?, inputSchema?, handler })
|
||||
```
|
||||
|
||||
`id`:`[a-z0-9][a-z0-9._-]{1,63}`。`handler` 返回:
|
||||
|
||||
```ts
|
||||
{ success: boolean, output?: object, reply?: { type: 'text', text, at? }, error?: string }
|
||||
```
|
||||
|
||||
`inputSchema` 只支持 `object` + `string|number|boolean` 属性的浅校验;必填项缺失会直接拒绝。
|
||||
|
||||
执行超时默认 15 秒(宿主可配,最大 60 秒),超时返回 `ACTION_TIMEOUT`。
|
||||
|
||||
### tm.capabilities.get
|
||||
|
||||
返回只读快照:`enabled / permissions / platform / databaseReady / send{...} / ai{...}`。
|
||||
|
||||
### tm.log
|
||||
|
||||
`info / warn / error`,写入扩展日志(详情页可见,最多保留 200 条,单行 ≤ 500 字)。
|
||||
|
||||
## 页面桥
|
||||
|
||||
页面 → 宿主:
|
||||
|
||||
```ts
|
||||
{ source: 'tracememo-extension-page', extensionId, requestId, method, params }
|
||||
```
|
||||
|
||||
宿主 → 页面:
|
||||
|
||||
```ts
|
||||
{ source: 'tracememo-extension-host', requestId, ok: true, result }
|
||||
{ source: 'tracememo-extension-host', requestId, ok: false, error: { code, message } }
|
||||
```
|
||||
|
||||
页面方法白名单:`storage.get|set|remove|list`、`capabilities.get`、`contacts.listGroups`、`extension.info`。
|
||||
页面不能发送微信消息、不能查询消息、不能调用 AI。
|
||||
- `tm.ai.chat(messages)`:调用 TraceMemo 已配置的 AI Provider,不暴露 API Key。
|
||||
- `tm.storage.{get,set,remove,list}`:键 `[A-Za-z0-9._-]{1,64}`,单值 ≤ 256KB,总量 ≤ 1MB。
|
||||
- `tm.secrets.{get,set,delete,has}`:系统安全存储加密凭据。
|
||||
- `tm.automation.registerAction({ id, title, description?, inputSchema?, handler })`:注册自动化动作。
|
||||
- `tm.page.onRequest(method, handler)`:注册页面到同扩展后台的受限请求处理器(响应 ≤ 64KB 纯 JSON)。
|
||||
- `tm.capabilities.get()`:返回只读环境能力快照。
|
||||
- `tm.log.{info,warn,error}`:写入扩展日志(最多保留 200 条,单行 ≤ 500 字)。
|
||||
|
||||
## 错误码
|
||||
|
||||
@@ -163,29 +176,20 @@ tm.automation.registerAction({ id, title, description?, inputSchema?, handler })
|
||||
| `EXTENSION_DISABLED` | 扩展未启用 |
|
||||
| `EXTENSION_INCOMPATIBLE` | apiVersion 或 minAppVersion 不满足 |
|
||||
| `EXTENSION_INVALID_MANIFEST` | manifest 不合法 |
|
||||
| `EXTENSION_INVALID_PATH` | 入口 / 资源路径越界 |
|
||||
| `EXTENSION_INVALID_PATH` | 入口或输出路径越界 |
|
||||
| `EXTENSION_HOST_UNAVAILABLE` | 后台进程未运行 |
|
||||
| `PERMISSION_DENIED` | 未授予权限,或超出声明范围 |
|
||||
| `CAPABILITY_UNAVAILABLE` | 本机能力不具备(未绑定 / 未就绪) |
|
||||
| `LICENSE_REQUIRED` | 无有效授权 |
|
||||
| `PERMISSION_DENIED` | 未授予权限或超出声明范围 |
|
||||
| `CAPABILITY_UNAVAILABLE` | 本机能力不具备或未配置 |
|
||||
| `LICENSE_REQUIRED` | 无有效 Pro 授权 |
|
||||
| `DATABASE_NOT_READY` | 微信数据库未连接 |
|
||||
| `SEND_NOT_SUPPORTED` | 当前平台或内容类型不支持 |
|
||||
| `MEDIA_NOT_FOUND` | 找不到消息对应的本地媒体文件 |
|
||||
| `MEDIA_UNSUPPORTED` | 该消息类型不支持所请求的媒体操作 |
|
||||
| `ACCOUNT_MISMATCH` | `messageRef` 不属于当前已连接账号 |
|
||||
| `CONCURRENCY_LIMITED` | 媒体解析或渲染并发达到上限 |
|
||||
| `RENDER_FAILED` | 离线 HTML 渲染失败 |
|
||||
| `ACTION_TIMEOUT` | 处理超时 |
|
||||
| `ACTION_FAILED` | 执行失败 |
|
||||
| `RATE_LIMITED` | 触发频率限制 |
|
||||
| `INVALID_REQUEST` | 参数非法 |
|
||||
| `STORAGE_LIMIT_EXCEEDED` | 存储超限 |
|
||||
|
||||
## 自动化动作输入
|
||||
|
||||
规则里保存的静态 `input` 会与宿主注入字段合并,同名键以宿主为准:
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://example.com/video",
|
||||
"conversationId": "xxx@chatroom",
|
||||
"isGroup": true,
|
||||
"accountId": "wxid_self",
|
||||
"message": { "eventId": "message:...", "text": "...", "mentionsMe": false }
|
||||
}
|
||||
```
|
||||
| `INVALID_REQUEST` | 参数非法或恶意输入被拒绝 |
|
||||
| `STORAGE_LIMIT_EXCEEDED` | 存储或产出文件体积超限 |
|
||||
@@ -1,9 +1,8 @@
|
||||
# 扩展中心架构(v1)
|
||||
# 扩展中心架构
|
||||
|
||||
## 目标
|
||||
|
||||
把用户二次开发从官方源码里剥离:扩展装在自己的目录、走稳定的 SDK、由宿主做权限与能力检查。
|
||||
官方升级只替换应用本体,不触碰扩展目录与数据目录。
|
||||
将二次开发能力以稳定、可演进的 SDK 暴露给扩展,同时复用 TraceMemo 主程序既有的消息监听、媒体解密、语音转写、系统 OCR、视觉模型、HTML 离线渲染与发送网关,不维护第二套平行实现。
|
||||
|
||||
## 分层
|
||||
|
||||
@@ -12,88 +11,59 @@ TraceMemo Core(Electron 主进程 / 渲染层)
|
||||
│
|
||||
ExtensionManager ─── ExtensionRegistry(启用状态 / 授权集合)
|
||||
│ ExtensionInstaller(目录 / ZIP 安装,原子替换)
|
||||
│ ExtensionLogStore(日志)
|
||||
│ ExtensionActionRegistry(自动化动作)
|
||||
│ ExtensionEventBus(消息事件分发)
|
||||
│ ExtensionNavigationStore(固定到一级菜单的状态与排序)
|
||||
│ ExtensionNotificationStore(通知持久化、去重与未读汇总)
|
||||
│ ExtensionLogStore / ExtensionActionRegistry / ExtensionEventBus
|
||||
│
|
||||
ExtensionHost(每个扩展一个 Node 子进程)
|
||||
ExtensionHost(每个扩展一个独立 Node 子进程)
|
||||
│ require(background/index.js),注入 tm
|
||||
│
|
||||
tm.* ── 白名单 RPC ──▶ 宿主能力
|
||||
├─ storage → extensions-data/<id>
|
||||
├─ messages.query→ chat-service(有界窗口)
|
||||
├─ wechat.send → ExtensionSendGateway → WechatActionGateway
|
||||
├─ ai.chat → AIProviderService
|
||||
└─ capabilities → 只读快照
|
||||
tm.* ── 白名单 RPC(主进程独立权限校验)──▶ 宿主能力
|
||||
├─ storage / secrets → extensions-data/<id> / safeStorage
|
||||
├─ messages.query → chat-service(游标分页 + 统一 messageRef)
|
||||
├─ media.* → ExtensionMediaGateway
|
||||
│ ├─ ImageDecryptService / VoiceService / VideoAssetService
|
||||
│ ├─ SystemOcrService + imageTextIndexService 缓存
|
||||
│ ├─ VoiceTranscriptionGateway
|
||||
│ └─ ImageInsightService / AIProviderService
|
||||
├─ render.htmlToImage → HtmlRenderService(与官方群聊日报共用)
|
||||
├─ notifications → ExtensionNotificationStore → 一级导航角标 & 通知中心
|
||||
├─ wechat.send → ExtensionSendGateway → WechatActionGateway
|
||||
├─ ai.chat / vision → AIProviderService
|
||||
└─ capabilities → 只读快照
|
||||
```
|
||||
|
||||
关键边界:
|
||||
|
||||
- **主进程从不 `require` 扩展代码**;扩展只在子进程里加载。
|
||||
- 扩展不 import 官方业务模块,只通过 JSON RPC 申请能力。
|
||||
- 发送、消息读取、AI 调用全部复用既有服务,没有第二套监听或发送实现。
|
||||
|
||||
## 目录
|
||||
## 目录与宿主状态
|
||||
|
||||
```text
|
||||
<userData>/
|
||||
extensions/<id>/ 代码(manifest.json / ui / background)
|
||||
extensions-data/<id>/ 扩展私有数据(storage.json)
|
||||
extensions-state/ 宿主状态
|
||||
registry.json 启用状态与已授予权限
|
||||
logs/<id>.jsonl 运行日志(轮转一份 .1)
|
||||
extensions-staging/ 安装临时目录(成功后原子改名)
|
||||
extensions/<id>/ 扩展代码(manifest.json / ui / background)
|
||||
extensions-data/<id>/ 扩展私有数据
|
||||
storage.json JSON 键值存储
|
||||
media-cache/{images,voices,videos}/ 按需解密的媒体副本缓存
|
||||
rendered/ tm.render.htmlToImage 生成的 PNG 长图
|
||||
extensions-state/ 宿主管理状态
|
||||
registry.json 启用状态与已授予权限
|
||||
pinned-navigation.json 用户固定到一级导航的扩展顺序
|
||||
notifications.json 扩展通知中心持久化记录
|
||||
logs/<id>.jsonl 运行日志
|
||||
extensions-staging/ 安装临时目录
|
||||
```
|
||||
|
||||
三者分离的原因:
|
||||
## 统一 messageRef 与按需媒体流水线
|
||||
|
||||
| 场景 | 结果 |
|
||||
| --- | --- |
|
||||
| 官方应用升级 | `userData` 不变,扩展与配置原样保留 |
|
||||
| 扩展升级(同 id 新版本) | 只替换 `extensions/<id>`,`extensions-data` 不动 |
|
||||
| 卸载并选择保留数据 | 删除代码目录,保留 `extensions-data` |
|
||||
| 卸载并清除数据 | 同时删除数据目录与日志 |
|
||||
- 实时事件 `ExtensionMessageEvent` 与历史查询 `ExtensionQueriedMessage` 输出同一套 `tmref1_*` 编码的 `messageRef`,内含 `accountId / conversationId / messageId / localId? / timestamp?`。
|
||||
- 扩展通过 `messageRef` 按需请求媒体与派生解析;`ExtensionMediaGateway` 强制校验当前账号一致、权限充足、并发与超时上限,并将文件副本隔离写入该扩展自己的 `extensions-data/<id>/media-cache/`。
|
||||
- 本地 OCR、语音转写与图片视觉理解优先复用主程序已有缓存,避免重复解密或重复调用模型。
|
||||
|
||||
## 生命周期
|
||||
## 通用 HTML 渲染服务
|
||||
|
||||
```text
|
||||
install → 校验 manifest / 入口 → 临时目录 → 原子替换 → 登记(默认未启用)
|
||||
enable → 授予 manifest 声明的权限 → 启动子进程 → activate 握手 → active
|
||||
message → ExtensionEventBus 去重 → 按 subscriptions 过滤 → 投递给子进程
|
||||
action → 自动化 runner → ExtensionHost.invokeAction → 返回 reply / output
|
||||
disable → 停止子进程 → 撤销高风险权限(仅保留 storage)→ inactive
|
||||
upgrade → 停进程 → 替换目录 → 保留 enabled 与授权 → 重启
|
||||
```
|
||||
- `src/main/services/html-render-service.ts` 统一承接官方群聊日报截图(`group-report-service.ts`)与扩展 `tm.render.htmlToImage`。
|
||||
- 每次渲染创建独立隐藏 `BrowserWindow` 与临时 `Session` 分区,限制网络请求仅放行目标 HTML 文件,校验静态 HTML 与输出尺寸/体积/并发/超时,并在 `finally` 中保证销毁窗口并删除临时文件。
|
||||
|
||||
崩溃处理:子进程异常退出时按 1s / 2s / 4s 退避重启,5 分钟内超过 3 次标记为
|
||||
`crashed` 并停止自动重启,等用户手动停用再启用。
|
||||
## 动态一级导航与通知聚合
|
||||
|
||||
## 消息事件
|
||||
|
||||
- 事件来源只有 `MessageListenerService` 的规范化结果,不直连数据库。
|
||||
- `eventId = message:<sha1(sessionId:localId)>`,同一条消息稳定不变。
|
||||
- `mentionsMe` 来自 `source.atuserlist` ∩ 当前账号 username;拿不到自身身份时为 `false`。
|
||||
- 分发前做 manifest 级过滤(消息类型 / 会话范围 / 是否 @我 / 是否包含自己)。
|
||||
- 子进程侧有令牌桶(容量 100,按 60/秒补充);超出时丢弃并记一条 warn,
|
||||
不让扩展拖慢主进程监听循环。
|
||||
|
||||
**已知降级**:旧 Native Runtime 的事件不带 `sessionId`,监听层只能回读「最近活跃会话」。
|
||||
事件总线不掩盖这一点,自动化状态与扩展能力快照都按「降级」标记。
|
||||
|
||||
## 发送链路
|
||||
|
||||
```text
|
||||
tm.wechat.send
|
||||
→ ExtensionHost(权限检查)→ ExtensionSendGateway(权限 / 范围 / 频率 / 能力 / 授权校验)
|
||||
→ WechatActionGateway.executeFromExtension(origin=extension, purpose=extension_send)
|
||||
→ WechatSendGateway → Windows / macOS sender
|
||||
```
|
||||
|
||||
自动化动作返回的 `reply` 走同一条 Gateway,但 purpose 是 `extension_action`,
|
||||
幂等键由 `executionId` 派生。扩展无法传入 `origin` / `purpose` / `triggerType`。
|
||||
|
||||
## 与自动化的关系
|
||||
|
||||
- 扩展注册动作,自动化负责触发、过滤、冷却、幂等、执行日志。
|
||||
- 自动化规则里的 `extensionAction` 只保存 `extensionId + actionId + 静态 input`;
|
||||
卸载扩展后规则**保留**,执行时明确报 `EXTENSION_NOT_FOUND`,不会静默删除用户配置。
|
||||
- 扩展可在 `manifest.json` 声明 `contributions.navigation`(安全内置图标 + 标签 + 默认页);用户在扩展详情页主动选择「固定到一级菜单 / 取消固定 / 上移 / 下移」。
|
||||
- 固定入口渲染在左侧一级导航「设置」上方,点击直接复用同一个 `ExtensionPageHost` 打开扩展页面,不新建第二套页面容器。
|
||||
- 已固定扩展的未读通知显示在对应固定入口角标;未固定扩展的未读通知聚合到「扩展」导航的蓝色数字角标,与红色 `!` 发送能力异常提示严格区分。
|
||||
- 卸载扩展时宿主自动清理其固定导航项与全部通知记录。
|
||||
@@ -1,27 +1,19 @@
|
||||
# 扩展开发入门
|
||||
|
||||
从克隆源码到创建独立扩展的完整流程见[克隆 TraceMemo 后开发自己的扩展](./clone-and-customize.md)。本页保留 API 用法速查。
|
||||
从克隆源码到创建独立扩展的完整流程见[克隆 TraceMemo 后开发自己的扩展](./clone-and-customize.md)。本页提供第二阶段新增能力与基础 API 的快速上手。
|
||||
|
||||
## 1. 安装示例
|
||||
## 1. 官方模板一览
|
||||
|
||||
1. 打开 TraceMemo,左侧一级导航点「扩展」。
|
||||
2. 点「安装目录」,选择 `examples/extensions/keyword-bot`。
|
||||
3. 列表里出现 **关键词回复机器人**,状态为「已停用」。
|
||||
4. 点「启用」→「打开页面」;页面顶部的「启用机器人」默认关闭,打开后修改规则并保存。
|
||||
5. 完全退出并重启 TraceMemo,配置仍在。
|
||||
在 TraceMemo 左侧点击「扩展」→「官方模板」可一键安装以下示例:
|
||||
|
||||
`examples/extensions/douyin-sender` 用同样的方式安装;它依赖本机 `python3`、Chrome 和抖音解析脚本,先看它自己的 README。
|
||||
| 模板 | 演示能力 |
|
||||
| --- | --- |
|
||||
| `keyword-bot` | 消息事件订阅、关键词回复、Gateway 发送、自动化动作 |
|
||||
| `group-chat-bot` | 多套群聊人格、长短期记忆、文字/语音回复、按需图片 OCR/视觉与语音转写 |
|
||||
| `morning-digest` | 分页消息查询、批量媒体解析、AI 总结、离线 HTML 长图渲染、扩展通知、一级导航固定与可选微信发送 |
|
||||
| `douyin-sender` | 外部 Python 脚本协作、视频下载与发送 |
|
||||
|
||||
## 2. 最小扩展
|
||||
|
||||
```text
|
||||
my-extension/
|
||||
manifest.json
|
||||
ui/index.html
|
||||
background/index.js
|
||||
```
|
||||
|
||||
`manifest.json`:
|
||||
## 2. 最小扩展与固定到一级菜单
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -30,112 +22,70 @@ my-extension/
|
||||
"name": "我的扩展",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.6.0",
|
||||
"permissions": ["storage"],
|
||||
"minAppVersion": "2.7.0",
|
||||
"permissions": ["storage", "notifications.create"],
|
||||
"entrypoints": { "page": "ui/index.html", "background": "background/index.js" },
|
||||
"contributions": { "pages": [{ "id": "settings", "title": "设置" }] }
|
||||
}
|
||||
```
|
||||
|
||||
`background/index.js`:
|
||||
|
||||
```js
|
||||
module.exports = function activate(tm) {
|
||||
tm.log.info('我的扩展已启动')
|
||||
}
|
||||
```
|
||||
|
||||
`ui/index.html` 里不能直接用 `window.api`。页面通过 postMessage 与宿主通信:
|
||||
|
||||
```js
|
||||
const requestId = `req-${Date.now()}`
|
||||
parent.postMessage(
|
||||
{
|
||||
source: 'tracememo-extension-page',
|
||||
extensionId: 'com.example.my-extension',
|
||||
requestId,
|
||||
method: 'storage.get',
|
||||
params: { key: 'greeting' }
|
||||
},
|
||||
'*'
|
||||
)
|
||||
window.addEventListener('message', (event) => {
|
||||
const data = event.data
|
||||
if (!data || data.source !== 'tracememo-extension-host' || data.requestId !== requestId) return
|
||||
console.log(data.ok ? data.result : data.error)
|
||||
})
|
||||
```
|
||||
|
||||
页面可调用的方法只有:`storage.get` / `storage.set` / `storage.remove` / `storage.list` /
|
||||
`capabilities.get` / `extension.info`。
|
||||
|
||||
## 3. 订阅消息
|
||||
|
||||
manifest 必须同时声明权限与订阅:
|
||||
|
||||
```json
|
||||
{
|
||||
"permissions": ["messages.subscribe"],
|
||||
"subscriptions": {
|
||||
"messageTypes": ["text"],
|
||||
"conversationIds": [],
|
||||
"requireMentionMe": false,
|
||||
"includeSelf": false
|
||||
"contributions": {
|
||||
"pages": [{ "id": "main", "title": "我的扩展" }],
|
||||
"navigation": { "label": "我的工具", "icon": "spark", "pageId": "main" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
用户在扩展详情页点击「固定到一级菜单」后,该入口会出现在左侧「设置」上方;点击可直接打开扩展页面。
|
||||
|
||||
## 3. 按需分页读取消息与解析图片/语音
|
||||
|
||||
```js
|
||||
module.exports = function activate(tm) {
|
||||
tm.events.on('message.received', async (event) => {
|
||||
if (event.isSelf) return
|
||||
if (!event.mentionsMe) return
|
||||
await tm.wechat.send({
|
||||
to: event.conversationId,
|
||||
text: '收到',
|
||||
dedupeKey: event.eventId
|
||||
tm.page.onRequest('runDigest', async ({ conversationId }) => {
|
||||
const endTime = Date.now()
|
||||
const startTime = endTime - 24 * 60 * 60 * 1000
|
||||
const messages = []
|
||||
let cursor
|
||||
|
||||
do {
|
||||
const page = await tm.messages.query({
|
||||
conversationId,
|
||||
startTime,
|
||||
endTime,
|
||||
order: 'asc',
|
||||
limit: 100,
|
||||
cursor
|
||||
})
|
||||
messages.push(...page.messages)
|
||||
cursor = page.nextCursor
|
||||
if (!page.hasMore) break
|
||||
} while (cursor)
|
||||
|
||||
const items = messages
|
||||
.filter((m) => m.type === 'image' || m.type === 'voice')
|
||||
.slice(-6)
|
||||
.map((m) => ({
|
||||
op: m.type === 'image' ? 'ocrImage' : 'transcribeVoice',
|
||||
messageRef: m.messageRef
|
||||
}))
|
||||
|
||||
const media = items.length ? await tm.media.batch({ items, concurrency: 2 }) : { results: [] }
|
||||
const rendered = await tm.render.htmlToImage({
|
||||
html: `<main><h1>今日速览</h1><p>共 ${messages.length} 条消息</p></main>`,
|
||||
css: 'main{padding:24px;font-family:-apple-system,sans-serif;}',
|
||||
width: 460
|
||||
})
|
||||
await tm.notifications.create({
|
||||
title: '今日速览已生成',
|
||||
body: `分析 ${messages.length} 条消息,解析 ${media.results.length} 条媒体`,
|
||||
level: 'success',
|
||||
dedupeKey: `digest-${new Date().toISOString().slice(0, 10)}`,
|
||||
pageId: 'main'
|
||||
})
|
||||
return { count: messages.length, imagePath: rendered.path }
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
`dedupeKey` 建议直接用 `event.eventId`:同一条消息重复投递时,Gateway 会按审计记录短路。
|
||||
## 4. 开发调试与安全约定
|
||||
|
||||
## 4. 注册自动化动作
|
||||
|
||||
```js
|
||||
tm.automation.registerAction({
|
||||
id: 'douyin.process',
|
||||
title: '抖音视频处理',
|
||||
description: '处理指定视频链接',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { url: { type: 'string' } },
|
||||
required: ['url']
|
||||
},
|
||||
async handler(input) {
|
||||
return {
|
||||
success: true,
|
||||
output: { url: input.url },
|
||||
reply: { type: 'text', text: '已收到链接' }
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
扩展中心会展示动作声明与运行时注册状态。当前自动化规则编辑器尚未提供扩展动作选择入口,因此暂时不能从界面配置该动作。宿主侧执行契约与输入结构见[扩展 API 参考](./api-reference.md#自动化动作输入)。
|
||||
|
||||
扩展动作返回的 `reply` 由宿主经 Gateway 发送;扩展本身不调用发送接口也能完成回复。
|
||||
|
||||
## 5. 开发与调试
|
||||
|
||||
- TraceMemo 会把扩展复制到用户数据目录;改完源码后先在扩展中心重新安装同一目录,更新已安装的文件。需要时再「停用 → 启用」重启后台进程。
|
||||
- 页面资源更新后重新打开或刷新扩展页面。
|
||||
- 日志在扩展详情页底部,`宿主` 表示生命周期与错误,`扩展` 表示 `tm.log.*` 写入的内容。
|
||||
- 想看完整后台输出,可以在终端启动 `pnpm dev`,子进程 stderr 会进主进程日志。
|
||||
|
||||
## 6. 升级与保留
|
||||
|
||||
- 扩展升级只替换代码目录;`storage` 数据与启用状态保留。
|
||||
- 官方 TraceMemo 升级不触碰 `extensions/`、`extensions-data/`、`extensions-state/`。
|
||||
- 卸载默认保留数据(v1 界面只提供「保留数据」这一条路径;`keepData: false` 已在 IPC 中实现,界面暂未暴露)。
|
||||
- 后台进程属于受信任本地代码;涉及敏感权限(读取消息/媒体、发微信、写通知)均由主进程独立校验,请按最小权限原则声明。
|
||||
- 涉及微信发送的扩展默认应关闭自动发送,先通过离线渲染与预览确认内容后再由用户手动触发测试发送。
|
||||
- 修改源码后可通过「二次开发 → 链接本地项目 + 重载」快速验证,无需反复重新打包安装。
|
||||
+29
-71
@@ -1,86 +1,44 @@
|
||||
# 扩展安全模型(v1)
|
||||
# 扩展安全模型
|
||||
|
||||
## 信任分级
|
||||
## 信任分级与进程边界
|
||||
|
||||
| 类型 | 说明 | 本版支持 |
|
||||
| 类型 | 说明 | 支持状态 |
|
||||
| --- | --- | --- |
|
||||
| 声明式 UI 扩展 | 只有页面,使用白名单存储 / 能力查询 | 是 |
|
||||
| 受信任本地代码扩展 | 后台是任意 Node 代码,可读写本机文件 | 是(安装即视为信任) |
|
||||
| 声明式 UI 扩展 | 仅页面,经 `postMessage` 白名单访问存储与能力查询 | 支持 |
|
||||
| 受信任本地代码扩展 | 后台为独立 Node 子进程(`ELECTRON_RUN_AS_NODE`),具备当前系统用户的 Node 权限 | 支持(安装即视为受信任本地代码) |
|
||||
|
||||
**独立进程不等于强沙箱。** 后台子进程(`ELECTRON_RUN_AS_NODE`)拥有运行用户的全部
|
||||
Node 能力,因此扩展作者可以读写本机文件、发起网络请求。本版不声称限制了这些——
|
||||
它限制的是**TraceMemo 内部能力**:
|
||||
**明确边界:独立 Node 子进程属于受信任本地代码,不构成强安全沙箱。** 我们不夸大进程隔离的安全性——子进程未受操作系统级 sandbox(如 seatbelt / AppContainer)约束。宿主边界保护的是 **TraceMemo 内部敏感资产与受控网关**:
|
||||
|
||||
- 拿不到数据库句柄、数据库密钥、授权凭据、Native Runtime 句柄;
|
||||
- 不能直接调用原生发送接口(dylib / 底层端口);
|
||||
- 不能 `require` 官方主进程模块;
|
||||
- 不能伪造宿主可信元数据(`origin` / `purpose` / `triggerType` / 幂等键)。
|
||||
- 扩展无法获取微信数据库句柄、数据库解密密钥、图片 AES/XOR 密钥、AI/TTS API Key 明文或原生发送 Runtime 句柄;
|
||||
- 扩展不能 `require` 主进程模块,也不能伪造宿主可信字段(`origin` / `purpose` / `triggerType` / 幂等键);
|
||||
- 扩展的后台代码崩溃、死循环或挂死不会拖垮主进程(具备启动超时、调用超时、退避重启与连续崩溃熔断)。
|
||||
|
||||
## 进程与权限
|
||||
## 主进程独立权限校验
|
||||
|
||||
```text
|
||||
主进程 ── fork ──▶ 扩展子进程(每扩展一个)
|
||||
│ 只注入 tm
|
||||
▼
|
||||
白名单 RPC(method + params)
|
||||
│
|
||||
宿主再次校验权限
|
||||
```
|
||||
子进程 SDK 侧的 `requirePermission` 仅用于提前给出可读错误提示;**所有 RPC 方法在主进程 `ExtensionHost`、`ExtensionManager`、`ExtensionMediaGateway` 与 `ExtensionSendGateway` 均独立校验权限、启用状态与暂停状态**,绝不信任子进程上报的数据。
|
||||
|
||||
两侧都检查权限:子进程提前失败给出明确错误码,宿主侧才是权威判定。
|
||||
子进程崩溃 / 挂死不影响主进程:宿主有启动超时、调用超时、退避重启与熔断。
|
||||
## 媒体 Gateway 安全与隔离
|
||||
|
||||
## 发送安全
|
||||
- **账号身份与签名防伪造**:实时事件与历史查询签发的 `messageRef` 均由主进程附加运行期 HMAC-SHA256 签名与账号世代标识;未签名伪造、篡改、跨账号(`ACCOUNT_MISMATCH`)或账号切换前的旧引用一律拒绝;若扩展声明了 `subscriptions.conversationIds`,查询与媒体读取同样强制校验会话范围(`PERMISSION_DENIED`)。
|
||||
- **跨扩展与跨账号缓存隔离**:图片、语音、视频副本严格落盘到 `<extensions-data>/<extensionId>/media-cache/<accountHash>/`,写入前经 `isPathInside` 与 `realpath` 双重校验,绝不返回微信原始目录或数据库路径。
|
||||
- **错误脱敏**:底层异常中的本地绝对路径与密钥键名在返回扩展前自动脱敏。
|
||||
- **资源保护**:全局并发上限、单扩展并发上限、单次批量项数上限(≤ 20)及单项超时(`ACTION_TIMEOUT`)防止扩展拖垮本地 OCR、语音转写队列或主进程 I/O。
|
||||
|
||||
```text
|
||||
扩展声明「发什么」
|
||||
↓
|
||||
宿主填 origin=extension / purpose=extension_send / recipient 类型 / 幂等键
|
||||
↓
|
||||
ExtensionSendGateway:权限 → 会话范围 → 频率 → 本机能力 → 授权校验
|
||||
↓
|
||||
WechatActionGateway:用途白名单 + `extension_*` 必须来自 origin=extension
|
||||
↓
|
||||
WechatSendGateway:真实发送 + Send Log
|
||||
```
|
||||
## 离线 HTML 渲染安全
|
||||
|
||||
- 扩展不能在请求里指定 `purpose`,因此无法借用 `manual_*` / `api_*` 等用途绕过白名单。
|
||||
- 自动化草稿里的 `extensionAction` 只保存扩展 id、动作 id 与静态输入;
|
||||
发送内容由扩展返回,发送动作由 runner 发起,幂等键由 `executionId` 派生。
|
||||
- 授权只在主进程判定:macOS 读 Native license(要求 `authorized === true`),
|
||||
Windows 探测 `/license/status` 只接受 `LICENSE_OK`。UI 上的 `ready` 不作为授权依据。
|
||||
- 扩展调用 `tm.render.htmlToImage` 仅允许静态 HTML/CSS:入口即拒绝 `<script>`、`<iframe>`、`<object>`、`<embed>`、`<meta http-equiv="refresh">`、内联事件(`on*=`)、`javascript:` 协议及任何 `http(s)/ws/ftp/file` 外链。
|
||||
- 渲染窗口强制 `sandbox: true`、`contextIsolation: true`、`nodeIntegration: false`、独立随机 `partition`、`will-navigate` 拦截、弹窗拒绝、严格响应头 CSP(`default-src 'none'; script-src 'none'; img-src data:; style-src 'unsafe-inline'`)与 `webRequest.onBeforeRequest` 单文件白名单。
|
||||
- 强制限制 HTML 体积、输出宽高、PNG 体积、渲染并发数与执行超时;无论成功或失败都在 `finally` 中销毁窗口、注销过滤器并删除临时 HTML 文件。
|
||||
- 输出文件名经 `isSafeRelativeEntryPath`、`isPathInside` 与 `realpath` 校验,杜绝 `../` 路径穿越与符号链接逃逸。
|
||||
|
||||
## 页面安全
|
||||
## 发送与授权安全
|
||||
|
||||
- 自定义协议 `tm-extension://<id>/<path>`,每次请求 realpath 复核目录归属;
|
||||
- iframe `sandbox="allow-scripts"`:无 same-origin、无 Node、无 preload、无 `window.api`;
|
||||
- 响应头 CSP:`default-src 'self'`、`script-src 'self'`、`connect-src 'none'`、
|
||||
`object-src 'none'`、`base-uri 'none'`、`form-action 'none'`;
|
||||
- 页面只能调用 `storage.*` / `capabilities.get` / `contacts.listGroups` / `extension.info`;
|
||||
`contacts.listGroups` 只返回群名称与会话 id,且要求 manifest 声明 `contacts.list`。
|
||||
- 所有扩展发送(文本、图片、视频、语音)均经 `ExtensionSendGateway` → `WechatActionGateway` → `WechatSendGateway`,不可绕过 Pro entitlement、频率限制、会话范围与 Action Audit。
|
||||
- 真实微信测试默认禁止自动发送;官方模板(如「AI 晨报」)默认关闭自动发送微信开关,仅在用户人工确认并显式开启或点击测试发送时才调用发送链路。
|
||||
|
||||
## 安装安全
|
||||
## 页面、导航与通知安全
|
||||
|
||||
ZIP 安装校验:
|
||||
|
||||
1. 包大小 ≤ 100MB、文件数 ≤ 2000、单文件 ≤ 20MB、解压总量 ≤ 50MB;
|
||||
2. 条目路径规范化后判重(大小写不敏感),拒绝 `..`、绝对路径、盘符、保留名;
|
||||
3. 拒绝 `SymbolicLink` 与非常规条目;
|
||||
4. 先解压到 `extensions-staging`,校验 manifest 与入口存在后才原子改名;
|
||||
5. 目标已存在时先改名备份,替换失败自动回滚。
|
||||
|
||||
目录安装同样拒绝符号链接与非普通文件,并遵守同样的体积 / 数量上限。
|
||||
|
||||
## 隐私
|
||||
|
||||
- 宿主日志只记录生命周期、错误摘要与数量,不写聊天正文、昵称、wxid、群名、路径;
|
||||
- `message.received` 只在扩展声明 `messages.subscribe` 且用户启用后才投递;
|
||||
- 扩展自己写 `tm.log.*` 的内容会落盘并展示,作者需自行遵守隐私约定;
|
||||
- 扩展存储按 id 隔离,路径来自已校验的 id,不接受任意目录。
|
||||
|
||||
## 已知边界(v1 未解决)
|
||||
|
||||
- 后台代码的文件 / 网络权限未做系统级限制(无 seatbelt / AppContainer);
|
||||
- 页面与后台共享 `storage`,因此页面能读到后台写入的任何配置;
|
||||
- 没有签名校验与来源可信度分级,安装来源完全依赖用户选择;
|
||||
- 事件投递是「至多一次」:进程重启或过载时可能丢事件,扩展需要用 `eventId` 自行幂等。
|
||||
- 扩展页面运行在 `tm-extension://<id>/<path>` 自定义协议与 `sandbox="allow-scripts"` iframe 中,固定到一级导航后仍复用同一个 `ExtensionPageHost`,不暴露 `window.api` 或 Node。
|
||||
- 扩展私有媒体预览仅开放 `tm-extension://<id>/_data/{rendered,media-cache}/` 白名单媒体扩展名(图片/音频/视频),禁止访问 `storage.json`、其他目录、符号链接与脚本/HTML 类型,不向扩展页面开放本地文件系统。
|
||||
- `contributions.navigation.icon` 仅允许预定义安全图标枚举,不加载扩展提供的原始 SVG 到主进程/主界面 DOM。
|
||||
- 停用扩展拒绝写入新通知;单扩展通知受滑动窗口限频保护防刷屏;卸载扩展自动清理固定导航项与通知持久化状态。
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: tracememo-reader
|
||||
version: 1.4.0
|
||||
version: 1.4.1
|
||||
description: 本机微信聊天记录的读取入口(TraceMemo 本地 HTTP API,默认 http://127.0.0.1:6131/api/v1)。凡是「看微信内容」的请求都必须先走本 Skill:某个群或某人今天聊了什么、刚刚聊了啥、最近消息、谁说了什么、总结聊天、翻历史记录、撤回的消息、图片内容、语音转文字、查找联系人或群聊、群成员、生成群聊总结、定时日报、给好友或群发微信消息、查看发送记录、查看未读。本 Skill 已处理鉴权、撤回归档、图片媒体、语音转写与压缩编码解码,当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。
|
||||
---
|
||||
|
||||
@@ -123,9 +123,10 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \
|
||||
| 字段 | 必填 | 说明 |
|
||||
| ---------------- | ------------------ | ------------------------------------------------------------------- |
|
||||
| `to` | 是 | wxid / `xxx@chatroom` / `filehelper`;以 `@chatroom` 结尾自动判为群 |
|
||||
| `type` | 否 | `text`(默认)/ `image` / `voice` |
|
||||
| `type` | 否 | `text`(默认)/ `image` / `voice` / `file` |
|
||||
| `text` | `type=text` 时必填 | **最多 2000 字符**,超限返回 `400`,不会自动截断 |
|
||||
| `filePath` | `type=image/voice` | 本机**绝对路径**且文件必须存在;**不接受 URL** |
|
||||
| `filePath` | `type=image/voice/file` | 本机**绝对路径**且文件必须存在;**不接受 URL** |
|
||||
| `fileName` | 否 | 仅 `type=file`:macOS 透传名称;Windows 当前可能忽略,按路径 basename 发送 |
|
||||
| `idempotencyKey` | 否 | 重试时原样带回,避免超时重发产生重复消息 |
|
||||
|
||||
几个必须遵守的限制:
|
||||
|
||||
@@ -63,6 +63,7 @@ win:
|
||||
nsis:
|
||||
oneClick: false
|
||||
allowToChangeInstallationDirectory: true
|
||||
include: build/installer.nsh
|
||||
artifactName: ${name}-${version}-setup.${ext}
|
||||
shortcutName: ${productName}
|
||||
uninstallDisplayName: ${productName}
|
||||
|
||||
@@ -49,6 +49,7 @@ extraResources:
|
||||
nsis:
|
||||
oneClick: false
|
||||
allowToChangeInstallationDirectory: true
|
||||
include: build/installer.nsh
|
||||
artifactName: ${name}-${version}-setup.${ext}
|
||||
shortcutName: ${productName}
|
||||
uninstallDisplayName: ${productName}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
# 扩展示例
|
||||
|
||||
三个可直接安装的官方模板示例,用来验证扩展中心从安装到发送的完整链路。
|
||||
四个可直接安装的官方模板示例,覆盖扩展中心从安装、媒体解析、离线渲染、通知中心到受控发送的完整链路。
|
||||
|
||||
| 目录 | 用途 | 申请权限 |
|
||||
| --- | --- | --- |
|
||||
| `keyword-bot/` | 消息事件、关键词匹配、Gateway 发送、自动化动作 | `messages.subscribe`、`contacts.list`、`wechat.send.text`、`storage`、`automation.action` |
|
||||
| `group-chat-bot/` | 多套群聊人格、单群长期与短期记忆、结合 TraceMemo 音色随机回复文字或发送语音 | `messages.subscribe`、`messages.query`、`contacts.list`、`wechat.send.text`、`wechat.send.voice`、`ai.chat`、`storage` |
|
||||
| `group-chat-bot/` | 多套群聊人格、单群长期与短期记忆、按需解析图片与语音、随机回复文字或语音 | `messages.subscribe`、`messages.query`、`media.ocr`、`media.transcribe`、`ai.vision`、`contacts.list`、`wechat.send.text`、`wechat.send.voice`、`ai.chat`、`notifications.create`、`storage` |
|
||||
| `morning-digest/` | AI 晨报:分页查询消息、批量媒体解析、AI 总结、离线 HTML 长图渲染、扩展通知与可选微信发送 | `messages.query`、`media.ocr`、`media.transcribe`、`ai.chat`、`ai.vision`、`render.html`、`notifications.create`、`contacts.list`、`wechat.send.image`、`automation.action`、`storage` |
|
||||
| `douyin-sender/` | @我 发抖音链接 → 解析 → 下载 → 发回视频;配置页可测试发送 | `messages.subscribe`、`contacts.list`、`wechat.send.video`、`wechat.send.text`、`storage` |
|
||||
|
||||
## 安装
|
||||
|
||||
@@ -1,32 +1,30 @@
|
||||
# 群聊机器人 (`com.example.group-chat-bot`)
|
||||
|
||||
TraceMemo 官方扩展模板。结合 TraceMemo 已配置的 AI 模型与文字转语音(TTS)音色,在指定微信群聊中按角色设定自然接话,支持单群长期记忆与随机回复文字 / 随机发送语音。
|
||||
> **这是模板壳,不是完整运行包。** 本目录不含 `lib/bot-engine.js` 运行时核心。直接把本目录打成 ZIP 安装,后台会走 `background/index.js` 的静默壳逻辑,页面可预览配置但不会执行自动回复。
|
||||
|
||||
TraceMemo 官方扩展模板。结合 TraceMemo 已配置的 AI 模型、文字转语音(TTS)音色、本地系统 OCR、AI 视觉理解与语音转写能力,在指定微信群聊中按角色设定自然接话,支持单群长期记忆、按需解析图片与语音内容,以及随机回复文字 / 发送语音。
|
||||
|
||||
## 核心特性
|
||||
|
||||
1. **多套群聊人格(Persona)**:内置「日常群友」「技术搭子」「温柔捧场王」「幽默气氛组」四套预设人格,支持新建、修改或删除自定义人格(独立配置人设背景、说话风格、字数上限与追问约束),并可为不同微信群绑定不同人格。
|
||||
2. **短期上下文 + 单群长期记忆(Memory)**:
|
||||
- **短期记忆**:接话时自动读取本群最近 N 条文本消息作为多轮对话上下文。
|
||||
- **长期记忆**:按群独立维护「固定背景记忆(手动置顶的群规、群友称呼偏好)」与「AI 自动提炼的互动摘要(常聊话题、近期约定)」。可按对话轮数自动更新,也可在配置页随时手动触发 AI 提炼或修订。
|
||||
3. **自然群聊节奏控制**:支持「仅 @我」「命中唤醒词」「@我 或唤醒词」「自然活跃接话(@我必回 + 普通群消息按概率随机搭话)」四种触发模式,区分直接唤醒冷却与环境闲聊冷却,并支持重复表达抑制。
|
||||
4. **随机回复文字 / 随机发送语音 + TraceMemo 音色同步展示**:
|
||||
- 配置页直接展示 TraceMemo「设置 → 文字转语音」中当前选定的音色(名称、ID、标签、合成模型与样本试听)。
|
||||
- 支持「随机混合(按概率随机回复文字或发送语音)」「仅回复文字」「仅发送语音」三种模式,单群可独立覆盖;当语音未就绪或发送失败时支持自动降级为发送文字。
|
||||
1. **多套群聊人格(Persona)**:内置四套预设人格并支持自定义编辑,可按群绑定不同人格。
|
||||
2. **短期上下文 + 单群长期记忆(Memory)**:按群维护固定备注与 AI 提炼的互动摘要。
|
||||
3. **按需图片与语音理解(v1.1 新增)**:
|
||||
- 订阅范围已扩展至 `text` / `image` / `voice`,通过统一的 `messageRef` 按需调用 `tm.media.ocrImage`、`tm.media.analyzeImage` 与 `tm.media.transcribeVoice`。
|
||||
- 图片优先走本地系统 OCR(零联网消耗),按需降级/切换视觉模型;语音复用主程序转写队列与缓存。
|
||||
4. **随机回复文字 / 发送语音 + 动态一级导航**:声明 `contributions.navigation`,支持在扩展详情页一键「固定到一级菜单」。
|
||||
|
||||
## 申请权限
|
||||
|
||||
| 权限 | 用途 |
|
||||
| --- | --- |
|
||||
| `messages.subscribe` | 接收微信群聊新文本消息事件 |
|
||||
| `messages.query` | 读取触发群聊最近的上下文消息 |
|
||||
| `messages.subscribe` | 接收微信群聊文本、图片与语音新消息事件 |
|
||||
| `messages.query` | 分页读取触发群聊最近的上下文消息 |
|
||||
| `media.ocr` | 按需识别群聊图片中的文字(纯本地,不联网) |
|
||||
| `media.transcribe` | 按需将群聊语音转为文字(复用主程序转写缓存) |
|
||||
| `ai.vision` | 按需调用已配置的视觉模型理解图片内容 |
|
||||
| `contacts.list` | 在配置页读取群聊列表供勾选生效范围 |
|
||||
| `wechat.send.text` | 经 TraceMemo Gateway 发送群聊文字回复 |
|
||||
| `wechat.send.voice` | 经 TraceMemo 文字转语音服务与 Gateway 发送群聊语音气泡 |
|
||||
| `ai.chat` | 调用 TraceMemo 已配置的 AI Provider 进行思考回复与记忆提炼 |
|
||||
| `notifications.create` | 在扩展通知中心汇报关键状态 |
|
||||
| `storage` | 保存机器人配置、单群长期记忆与今日统计 |
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
node --test examples/extensions/group-chat-bot/tests/bot-engine.test.mjs
|
||||
```
|
||||
@@ -1,6 +1,6 @@
|
||||
'use strict'
|
||||
|
||||
/** 群聊机器人后台入口壳:核心逻辑由 lib/bot-engine 承载,缺失时保持静默空操作且不报错。 */
|
||||
/** 群聊机器人后台入口壳:核心逻辑由 lib/bot-engine 承载,并内置按需图片/语音解析适配。 */
|
||||
|
||||
let engine = null
|
||||
try {
|
||||
@@ -9,6 +9,86 @@ try {
|
||||
engine = null
|
||||
}
|
||||
|
||||
function hasGrantedPermission(tm, permission) {
|
||||
const perms = tm && tm.extension && Array.isArray(tm.extension.permissions)
|
||||
? tm.extension.permissions
|
||||
: []
|
||||
return perms.includes(permission)
|
||||
}
|
||||
|
||||
/** 按需将图片或语音消息解析为可供机器人理解的纯文本摘要,缺权限或失败时安全降级为 null。 */
|
||||
async function resolveIncomingMediaText(tm, event, options = {}) {
|
||||
if (!event || typeof event !== 'object') return null
|
||||
if (event.type === 'text') {
|
||||
const text = String(event.text || '').trim()
|
||||
return text ? { text, source: 'text' } : null
|
||||
}
|
||||
const messageRef = String(event.messageRef || '').trim()
|
||||
if (!messageRef || !tm || !tm.media) return null
|
||||
|
||||
if (event.type === 'image') {
|
||||
const imageMode = options.imageMode || 'ocr'
|
||||
if (imageMode === 'off') return null
|
||||
|
||||
if (imageMode === 'vision' && hasGrantedPermission(tm, 'ai.vision')) {
|
||||
try {
|
||||
const analyzed = await tm.media.analyzeImage({ messageRef })
|
||||
const parts = [analyzed && analyzed.description, analyzed && analyzed.ocrText]
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
if (parts.length > 0) {
|
||||
return { text: `[图片内容] ${parts.join(';')}`, source: 'image_vision' }
|
||||
}
|
||||
} catch {
|
||||
// 视觉理解失败时降级到本地 OCR。
|
||||
}
|
||||
}
|
||||
|
||||
if (hasGrantedPermission(tm, 'media.ocr')) {
|
||||
try {
|
||||
const ocr = await tm.media.ocrImage({ messageRef })
|
||||
const ocrText = String((ocr && ocr.text) || '').trim()
|
||||
if (ocrText) {
|
||||
return { text: `[图片文字] ${ocrText}`, source: 'image_ocr' }
|
||||
}
|
||||
} catch {
|
||||
// 本地 OCR 不可用时继续尝试可选视觉回退。
|
||||
}
|
||||
}
|
||||
|
||||
if (options.visionFallback === true && hasGrantedPermission(tm, 'ai.vision')) {
|
||||
try {
|
||||
const analyzed = await tm.media.analyzeImage({ messageRef })
|
||||
const desc = String((analyzed && analyzed.description) || '').trim()
|
||||
if (desc) return { text: `[图片内容] ${desc}`, source: 'image_vision' }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
if (event.type === 'voice') {
|
||||
if (options.voiceTranscribeEnabled === false) return null
|
||||
if (!hasGrantedPermission(tm, 'media.transcribe')) return null
|
||||
try {
|
||||
const result = await tm.media.transcribeVoice({
|
||||
messageRef,
|
||||
waitMs: Number(options.voiceWaitMs) > 0 ? Number(options.voiceWaitMs) : 12_000
|
||||
})
|
||||
if (result && result.state === 'transcribed' && String(result.transcript || '').trim()) {
|
||||
return {
|
||||
text: `[语音转文字] ${String(result.transcript).trim()}`,
|
||||
source: 'voice_transcript'
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function registerFallbackHandlers(tm) {
|
||||
if (!tm || !tm.page || typeof tm.page.onRequest !== 'function') return
|
||||
const unavailable = async () => {
|
||||
@@ -19,9 +99,9 @@ function registerFallbackHandlers(tm) {
|
||||
tm.page.onRequest('testSend', unavailable)
|
||||
}
|
||||
|
||||
module.exports = function activate(api) {
|
||||
function activate(api) {
|
||||
if (engine && typeof engine.activateBotRuntime === 'function') {
|
||||
engine.activateBotRuntime(api)
|
||||
engine.activateBotRuntime(api, { resolveIncomingMediaText })
|
||||
} else {
|
||||
registerFallbackHandlers(api)
|
||||
}
|
||||
@@ -29,3 +109,6 @@ module.exports = function activate(api) {
|
||||
api.log.info('群聊机器人已启动')
|
||||
}
|
||||
}
|
||||
|
||||
activate.resolveIncomingMediaText = resolveIncomingMediaText
|
||||
module.exports = activate
|
||||
@@ -2,18 +2,22 @@
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.group-chat-bot",
|
||||
"name": "群聊机器人 - 模板(如需使用请找授权你的人",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.6.0",
|
||||
"description": "支持多套群聊人格设定、群聊长期与短期记忆、自然接话节奏,并可结合 TraceMemo 音色随机回复文字或发送语音。",
|
||||
"minAppVersion": "2.7.0",
|
||||
"description": "支持多套群聊人格设定、群聊长期与短期记忆、按需解析图片与语音内容,并可结合 TraceMemo 音色随机回复文字或发送语音。",
|
||||
"author": "TraceMemo Examples",
|
||||
"permissions": [
|
||||
"messages.subscribe",
|
||||
"messages.query",
|
||||
"media.ocr",
|
||||
"media.transcribe",
|
||||
"contacts.list",
|
||||
"wechat.send.text",
|
||||
"wechat.send.voice",
|
||||
"ai.chat",
|
||||
"ai.vision",
|
||||
"notifications.create",
|
||||
"storage"
|
||||
],
|
||||
"entrypoints": {
|
||||
@@ -22,7 +26,9 @@
|
||||
},
|
||||
"subscriptions": {
|
||||
"messageTypes": [
|
||||
"text"
|
||||
"text",
|
||||
"image",
|
||||
"voice"
|
||||
],
|
||||
"conversationIds": [],
|
||||
"requireMentionMe": false,
|
||||
@@ -34,6 +40,11 @@
|
||||
"id": "settings",
|
||||
"title": "群聊机器人设置"
|
||||
}
|
||||
]
|
||||
],
|
||||
"navigation": {
|
||||
"label": "群聊机器人",
|
||||
"icon": "bot",
|
||||
"pageId": "settings"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# AI 晨报 (`com.example.morning-digest`)
|
||||
|
||||
TraceMemo 官方示例模板,完整演示扩展系统第二阶段全链路能力:
|
||||
|
||||
1. **分页消息查询**:使用 `tm.messages.query({ order: 'asc', cursor, limit })` 稳定翻页读取多群历史记录。
|
||||
2. **按需媒体解析**:使用 `tm.media.batch` 按需触发图片本地 OCR、可选 AI 视觉理解与语音转写,自动复用主程序缓存。
|
||||
3. **AI 总结**:经 `tm.ai.chat` 提炼今日重点、待办事项与各群速览。
|
||||
4. **通用 HTML 长图渲染**:经 `tm.render.htmlToImage` 在隔离离线窗口中输出 PNG 长图至扩展私有目录。
|
||||
5. **扩展通知中心 & 一级导航固定**:声明 `contributions.navigation` 支持固定到左侧一级导航;生成完成后通过 `tm.notifications.create` 写入去重通知。
|
||||
6. **可选微信发送**:默认关闭自动发送,用户确认生成效果后可手动选择测试群聊发送长图,全链路仍经 TraceMemo Gateway 与授权校验。
|
||||
@@ -0,0 +1,240 @@
|
||||
'use strict'
|
||||
|
||||
/** AI 晨报后台:串联分页消息读取、批量媒体解析、AI 总结、离线长图渲染、通知中心与可选微信发送。 */
|
||||
|
||||
const {
|
||||
DIGEST_CSS,
|
||||
normalizeConfig,
|
||||
selectMediaBatchItems,
|
||||
buildDigestPromptMessages,
|
||||
parseDigestSummary,
|
||||
buildDigestHtml
|
||||
} = require('../lib/digest-builder')
|
||||
|
||||
const CONFIG_KEY = 'config'
|
||||
const LAST_DIGEST_KEY = 'lastDigest'
|
||||
|
||||
function localDateKey(timestamp = Date.now()) {
|
||||
const date = new Date(timestamp)
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${month}-${day}`
|
||||
}
|
||||
|
||||
async function queryAllGroupMessages(tm, conversationId, startTime, endTime, maxMessages) {
|
||||
const collected = []
|
||||
let cursor = undefined
|
||||
const pageSize = Math.min(100, maxMessages)
|
||||
|
||||
for (let pageIndex = 0; pageIndex < 20 && collected.length < maxMessages; pageIndex += 1) {
|
||||
const page = await tm.messages.query({
|
||||
conversationId,
|
||||
startTime,
|
||||
endTime,
|
||||
order: 'asc',
|
||||
limit: Math.min(pageSize, maxMessages - collected.length),
|
||||
...(cursor ? { cursor } : {})
|
||||
})
|
||||
const batch = Array.isArray(page && page.messages) ? page.messages : []
|
||||
collected.push(...batch)
|
||||
if (!page || !page.hasMore || !page.nextCursor) break
|
||||
cursor = page.nextCursor
|
||||
}
|
||||
return collected
|
||||
}
|
||||
|
||||
async function generateMorningDigest(tm, overrideConfig = null) {
|
||||
const stored = await tm.storage.get(CONFIG_KEY).catch(() => null)
|
||||
const config = normalizeConfig(overrideConfig ? { ...(stored || {}), ...overrideConfig } : stored)
|
||||
if (config.groupIds.length === 0) {
|
||||
throw new Error('请先在 AI 晨报配置页至少选择一个群聊')
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const startTime = now - config.windowHours * 60 * 60 * 1000
|
||||
const dateLabel = localDateKey(now)
|
||||
const grantedPermissions = (tm.extension && tm.extension.permissions) || []
|
||||
|
||||
const groupReports = []
|
||||
let totalMessages = 0
|
||||
let totalMediaResolved = 0
|
||||
|
||||
for (const groupId of config.groupIds) {
|
||||
const messages = await queryAllGroupMessages(
|
||||
tm,
|
||||
groupId,
|
||||
startTime,
|
||||
now,
|
||||
config.maxMessagesPerGroup
|
||||
)
|
||||
totalMessages += messages.length
|
||||
|
||||
const mediaByRef = new Map()
|
||||
const batchItems = selectMediaBatchItems(messages, config, grantedPermissions)
|
||||
if (batchItems.length > 0 && tm.media && typeof tm.media.batch === 'function') {
|
||||
try {
|
||||
const batchResult = await tm.media.batch({ items: batchItems, concurrency: 2 })
|
||||
for (const entry of (batchResult && batchResult.results) || []) {
|
||||
if (!entry || !entry.ok || !entry.result) continue
|
||||
if (entry.op === 'ocrImage' && entry.result.text) {
|
||||
mediaByRef.set(entry.messageRef, `[图片文字] ${entry.result.text}`)
|
||||
totalMediaResolved += 1
|
||||
} else if (entry.op === 'analyzeImage' && entry.result.description) {
|
||||
mediaByRef.set(entry.messageRef, `[图片理解] ${entry.result.description}`)
|
||||
totalMediaResolved += 1
|
||||
} else if (
|
||||
entry.op === 'transcribeVoice' &&
|
||||
entry.result.state === 'transcribed' &&
|
||||
entry.result.transcript
|
||||
) {
|
||||
mediaByRef.set(entry.messageRef, `[语音转文字] ${entry.result.transcript}`)
|
||||
totalMediaResolved += 1
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
tm.log.warn(`AI 晨报:媒体按需解析降级跳过(${error instanceof Error ? error.message : '未知错误'})`)
|
||||
}
|
||||
}
|
||||
|
||||
const lines = []
|
||||
for (const msg of messages) {
|
||||
const sender = msg.senderName || (msg.isSelf ? '我' : '群友')
|
||||
if (msg.text && msg.text.trim()) {
|
||||
lines.push(`${sender}:${msg.text.trim().slice(0, 180)}`)
|
||||
} else if (msg.messageRef && mediaByRef.has(msg.messageRef)) {
|
||||
lines.push(`${sender}:${String(mediaByRef.get(msg.messageRef)).slice(0, 180)}`)
|
||||
}
|
||||
}
|
||||
|
||||
groupReports.push({
|
||||
groupId,
|
||||
name: config.groupNames[groupId] || groupId,
|
||||
messageCount: messages.length,
|
||||
mediaResolvedCount: mediaByRef.size,
|
||||
lines
|
||||
})
|
||||
}
|
||||
|
||||
let summaryText = ''
|
||||
if (grantedPermissions.includes('ai.chat')) {
|
||||
const promptMessages = buildDigestPromptMessages({ dateLabel, groups: groupReports })
|
||||
const aiResp = await tm.ai.chat(promptMessages)
|
||||
summaryText = String((aiResp && aiResp.text) || '')
|
||||
}
|
||||
const summary = parseDigestSummary(summaryText, groupReports)
|
||||
|
||||
const html = buildDigestHtml({
|
||||
dateLabel,
|
||||
headline: summary.headline,
|
||||
highlights: summary.highlights,
|
||||
actionItems: summary.actionItems,
|
||||
groupBriefs: summary.groupBriefs,
|
||||
totalMessages,
|
||||
totalMediaResolved,
|
||||
groupCount: groupReports.length
|
||||
})
|
||||
|
||||
const rendered = await tm.render.htmlToImage({
|
||||
html,
|
||||
css: DIGEST_CSS,
|
||||
fileName: `morning-digest-${dateLabel}.png`,
|
||||
width: config.renderWidth
|
||||
})
|
||||
|
||||
const record = {
|
||||
dateLabel,
|
||||
generatedAt: now,
|
||||
headline: summary.headline,
|
||||
highlights: summary.highlights,
|
||||
actionItems: summary.actionItems,
|
||||
groupBriefs: summary.groupBriefs,
|
||||
totalMessages,
|
||||
totalMediaResolved,
|
||||
groupCount: groupReports.length,
|
||||
imagePath: rendered.path,
|
||||
previewUrl: rendered.previewUrl || '',
|
||||
width: rendered.width,
|
||||
height: rendered.height,
|
||||
pixelWidth: rendered.pixelWidth || rendered.width,
|
||||
pixelHeight: rendered.pixelHeight || rendered.height,
|
||||
deviceScaleFactor: rendered.deviceScaleFactor || 1,
|
||||
bytes: rendered.bytes
|
||||
}
|
||||
await tm.storage.set(LAST_DIGEST_KEY, record)
|
||||
|
||||
if (grantedPermissions.includes('notifications.create')) {
|
||||
try {
|
||||
await tm.notifications.create({
|
||||
title: `AI 晨报已生成 · ${dateLabel}`,
|
||||
body: `${summary.headline}(${groupReports.length} 个群 / ${totalMessages} 条消息)`,
|
||||
level: 'success',
|
||||
dedupeKey: `morning-digest:${dateLabel}`,
|
||||
pageId: 'digest'
|
||||
})
|
||||
} catch (error) {
|
||||
tm.log.warn(`AI 晨报:通知写入失败(${error instanceof Error ? error.message : '未知错误'})`)
|
||||
}
|
||||
}
|
||||
|
||||
let sentToWechat = false
|
||||
if (
|
||||
config.autoSendWechat &&
|
||||
config.wechatTargetGroupId &&
|
||||
grantedPermissions.includes('wechat.send.image')
|
||||
) {
|
||||
await tm.wechat.send({
|
||||
type: 'image',
|
||||
to: config.wechatTargetGroupId,
|
||||
path: rendered.path,
|
||||
dedupeKey: `morning-digest-send:${dateLabel}:${config.wechatTargetGroupId}`
|
||||
})
|
||||
sentToWechat = true
|
||||
}
|
||||
|
||||
tm.log.info(
|
||||
`AI 晨报已生成:${groupReports.length} 个群,${totalMessages} 条消息,解析媒体 ${totalMediaResolved} 条`
|
||||
)
|
||||
return { ...record, sentToWechat }
|
||||
}
|
||||
|
||||
module.exports = function activate(tm) {
|
||||
if (tm.page && typeof tm.page.onRequest === 'function') {
|
||||
tm.page.onRequest('generateDigest', async (params) => {
|
||||
return generateMorningDigest(tm, params && typeof params === 'object' ? params : null)
|
||||
})
|
||||
|
||||
tm.page.onRequest('sendLastDigest', async (params) => {
|
||||
const target = String((params && params.to) || '').trim()
|
||||
if (!target) throw new Error('请先选择发送目标群聊')
|
||||
const last = await tm.storage.get(LAST_DIGEST_KEY)
|
||||
if (!last || !last.imagePath) throw new Error('请先生成今日晨报长图')
|
||||
const sent = await tm.wechat.send({
|
||||
type: 'image',
|
||||
to: target,
|
||||
path: last.imagePath,
|
||||
dedupeKey: `morning-digest-manual:${last.dateLabel}:${target}:${Date.now()}`
|
||||
})
|
||||
return { ok: true, actionId: sent.actionId, to: target }
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
tm.automation &&
|
||||
typeof tm.automation.registerAction === 'function' &&
|
||||
tm.extension &&
|
||||
Array.isArray(tm.extension.permissions) &&
|
||||
tm.extension.permissions.includes('automation.action')
|
||||
) {
|
||||
tm.automation.registerAction({
|
||||
id: 'morning-digest.generate',
|
||||
title: '生成 AI 晨报',
|
||||
description: '汇总已配置群聊消息并渲染晨报长图',
|
||||
handler: async () => {
|
||||
const result = await generateMorningDigest(tm)
|
||||
return { success: true, output: { headline: result.headline, imagePath: result.imagePath } }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
tm.log.info('AI 晨报已启动')
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
'use strict'
|
||||
|
||||
/** AI 晨报纯逻辑模块:配置收敛、媒体批次编排、AI 摘要提示词与严格静态 HTML 渲染构建。 */
|
||||
|
||||
const DEFAULT_CONFIG = {
|
||||
groupIds: [],
|
||||
groupNames: {},
|
||||
windowHours: 24,
|
||||
maxMessagesPerGroup: 300,
|
||||
enableImageOcr: true,
|
||||
enableImageVision: false,
|
||||
enableVoiceTranscribe: true,
|
||||
maxMediaPerGroup: 6,
|
||||
renderWidth: 460,
|
||||
/** 默认禁止自动发微信,需用户显式开启或手动点击发送。 */
|
||||
autoSendWechat: false,
|
||||
wechatTargetGroupId: ''
|
||||
}
|
||||
|
||||
function clampInt(value, fallback, min, max) {
|
||||
const num = Number(value)
|
||||
if (!Number.isFinite(num)) return fallback
|
||||
return Math.max(min, Math.min(max, Math.round(num)))
|
||||
}
|
||||
|
||||
function normalizeConfig(raw) {
|
||||
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
||||
const groupIds = Array.isArray(src.groupIds)
|
||||
? Array.from(
|
||||
new Set(
|
||||
src.groupIds
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, 10)
|
||||
)
|
||||
)
|
||||
: []
|
||||
const groupNames = {}
|
||||
if (src.groupNames && typeof src.groupNames === 'object' && !Array.isArray(src.groupNames)) {
|
||||
for (const [id, name] of Object.entries(src.groupNames)) {
|
||||
const cleanId = String(id || '').trim()
|
||||
const cleanName = String(name || '').trim().slice(0, 64)
|
||||
if (cleanId && cleanName) groupNames[cleanId] = cleanName
|
||||
}
|
||||
}
|
||||
return {
|
||||
groupIds,
|
||||
groupNames,
|
||||
windowHours: clampInt(src.windowHours, DEFAULT_CONFIG.windowHours, 1, 168),
|
||||
maxMessagesPerGroup: clampInt(
|
||||
src.maxMessagesPerGroup,
|
||||
DEFAULT_CONFIG.maxMessagesPerGroup,
|
||||
20,
|
||||
1000
|
||||
),
|
||||
enableImageOcr: src.enableImageOcr !== false,
|
||||
enableImageVision: src.enableImageVision === true,
|
||||
enableVoiceTranscribe: src.enableVoiceTranscribe !== false,
|
||||
maxMediaPerGroup: clampInt(src.maxMediaPerGroup, DEFAULT_CONFIG.maxMediaPerGroup, 0, 15),
|
||||
renderWidth: clampInt(src.renderWidth, DEFAULT_CONFIG.renderWidth, 320, 960),
|
||||
autoSendWechat: src.autoSendWechat === true,
|
||||
wechatTargetGroupId: String(src.wechatTargetGroupId || '').trim().slice(0, 128)
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
/** 挑选待按需解析的图片与语音消息引用,单群总量受限以避免慢任务拖垮晨报生成。 */
|
||||
function selectMediaBatchItems(messages, config, grantedPermissions = []) {
|
||||
const limit = clampInt(config.maxMediaPerGroup, 6, 0, 15)
|
||||
if (limit === 0 || !Array.isArray(messages) || messages.length === 0) return []
|
||||
const perms = new Set(Array.isArray(grantedPermissions) ? grantedPermissions : [])
|
||||
const items = []
|
||||
const recent = [...messages].reverse()
|
||||
|
||||
for (const msg of recent) {
|
||||
if (items.length >= limit) break
|
||||
const messageRef = String((msg && msg.messageRef) || '').trim()
|
||||
if (!messageRef) continue
|
||||
if (msg.type === 'image') {
|
||||
if (config.enableImageVision && perms.has('ai.vision')) {
|
||||
items.push({ op: 'analyzeImage', messageRef })
|
||||
} else if (config.enableImageOcr && perms.has('media.ocr')) {
|
||||
items.push({ op: 'ocrImage', messageRef })
|
||||
}
|
||||
} else if (msg.type === 'voice') {
|
||||
if (config.enableVoiceTranscribe && perms.has('media.transcribe')) {
|
||||
items.push({ op: 'transcribeVoice', messageRef, options: { waitMs: 10_000 } })
|
||||
}
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
function buildDigestPromptMessages(input) {
|
||||
const dateLabel = String(input.dateLabel || '').trim() || new Date().toISOString().slice(0, 10)
|
||||
const sections = (input.groups || []).map((group) => {
|
||||
const lines = (group.lines || []).slice(0, 120).join('\n')
|
||||
return `【群聊:${group.name}】(共 ${group.messageCount} 条消息,解析媒体 ${group.mediaResolvedCount} 条)\n${lines || '(暂无有效内容)'}`
|
||||
})
|
||||
|
||||
return [
|
||||
{
|
||||
role: 'system',
|
||||
content: [
|
||||
'你是一名简洁高效的中文晨报编辑,负责根据多个微信群最近一天的聊天记录与图片/语音解析结果整理一份结构化「AI 晨报」。',
|
||||
'请严格输出纯 JSON,不要包含 Markdown 代码块包裹:',
|
||||
'{"headline":"一句话总览(<=28字)","highlights":["重点1","重点2"],"actionItems":["待办或约定1"],"groupBriefs":[{"groupName":"群名","summary":"该群简述(<=80字)"}]}'
|
||||
].join('\n')
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `日期:${dateLabel}\n\n${sections.join('\n\n')}`
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function parseDigestSummary(rawText, fallbackGroups = []) {
|
||||
const cleaned = String(rawText || '')
|
||||
.trim()
|
||||
.replace(/^```(?:json)?\s*/i, '')
|
||||
.replace(/\s*```$/i, '')
|
||||
.trim()
|
||||
try {
|
||||
const parsed = JSON.parse(cleaned)
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
const headline = String(parsed.headline || '今日群聊晨报').trim().slice(0, 60)
|
||||
const highlights = Array.isArray(parsed.highlights)
|
||||
? parsed.highlights.map((x) => String(x || '').trim()).filter(Boolean).slice(0, 6)
|
||||
: []
|
||||
const actionItems = Array.isArray(parsed.actionItems)
|
||||
? parsed.actionItems.map((x) => String(x || '').trim()).filter(Boolean).slice(0, 6)
|
||||
: []
|
||||
const groupBriefs = Array.isArray(parsed.groupBriefs)
|
||||
? parsed.groupBriefs
|
||||
.filter((item) => item && typeof item === 'object')
|
||||
.map((item) => ({
|
||||
groupName: String(item.groupName || '群聊').trim().slice(0, 48),
|
||||
summary: String(item.summary || '').trim().slice(0, 200)
|
||||
}))
|
||||
.filter((item) => item.summary)
|
||||
.slice(0, 10)
|
||||
: []
|
||||
if (headline || highlights.length > 0 || groupBriefs.length > 0) {
|
||||
return { headline, highlights, actionItems, groupBriefs }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 非 JSON 文本回退为单条摘要展示,不中断渲染。
|
||||
}
|
||||
return {
|
||||
headline: '今日群聊晨报',
|
||||
highlights: cleaned ? [cleaned.slice(0, 240)] : ['最近周期内暂无重点讨论'],
|
||||
actionItems: [],
|
||||
groupBriefs: fallbackGroups.map((g) => ({
|
||||
groupName: g.name,
|
||||
summary: `共采集 ${g.messageCount} 条消息,解析媒体 ${g.mediaResolvedCount} 条。`
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
const DIGEST_CSS = `
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
background: #f4f6f9;
|
||||
color: #18212f;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
.digest-card {
|
||||
background: #ffffff;
|
||||
border-radius: 16px;
|
||||
padding: 24px;
|
||||
border: 1px solid #e5e9f0;
|
||||
}
|
||||
.digest-kicker {
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.08em;
|
||||
color: #2563eb;
|
||||
font-weight: 700;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.digest-title {
|
||||
margin: 0 0 8px;
|
||||
font-size: 22px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
.digest-meta {
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
.digest-section {
|
||||
margin-top: 18px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid #edf0f5;
|
||||
}
|
||||
.digest-section h2 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 15px;
|
||||
color: #0f172a;
|
||||
}
|
||||
.digest-list {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
line-height: 1.65;
|
||||
font-size: 14px;
|
||||
}
|
||||
.digest-group {
|
||||
background: #f8fafc;
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.digest-group-name {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #1e293b;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.digest-group-summary {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: #334155;
|
||||
}
|
||||
.digest-footer {
|
||||
margin-top: 18px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px dashed #e2e8f0;
|
||||
font-size: 11px;
|
||||
color: #94a3b8;
|
||||
}
|
||||
`
|
||||
|
||||
/** 构建纯静态、无脚本、无外链的晨报 HTML,满足 HtmlRenderService 的严格安全校验。 */
|
||||
function buildDigestHtml(data) {
|
||||
const dateLabel = escapeHtml(data.dateLabel || '')
|
||||
const headline = escapeHtml(data.headline || '今日群聊晨报')
|
||||
const totalMessages = Number(data.totalMessages) || 0
|
||||
const totalMedia = Number(data.totalMediaResolved) || 0
|
||||
const groupCount = Number(data.groupCount) || 0
|
||||
|
||||
const highlightsHtml = (data.highlights || [])
|
||||
.map((item) => `<li>${escapeHtml(item)}</li>`)
|
||||
.join('')
|
||||
const actionsHtml = (data.actionItems || [])
|
||||
.map((item) => `<li>${escapeHtml(item)}</li>`)
|
||||
.join('')
|
||||
const briefsHtml = (data.groupBriefs || [])
|
||||
.map(
|
||||
(item) =>
|
||||
`<div class="digest-group"><div class="digest-group-name">${escapeHtml(item.groupName)}</div><p class="digest-group-summary">${escapeHtml(item.summary)}</p></div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
return `<main class="digest-card">
|
||||
<div class="digest-kicker">TRACEMEMO AI 晨报 · ${dateLabel}</div>
|
||||
<h1 class="digest-title">${headline}</h1>
|
||||
<div class="digest-meta">覆盖 ${groupCount} 个群聊 · 采样 ${totalMessages} 条消息 · 解析 ${totalMedia} 条图片/语音</div>
|
||||
${highlightsHtml ? `<section class="digest-section"><h2>今日重点</h2><ul class="digest-list">${highlightsHtml}</ul></section>` : ''}
|
||||
${actionsHtml ? `<section class="digest-section"><h2>待办与约定</h2><ul class="digest-list">${actionsHtml}</ul></section>` : ''}
|
||||
${briefsHtml ? `<section class="digest-section"><h2>各群速览</h2>${briefsHtml}</section>` : ''}
|
||||
<footer class="digest-footer">由 TraceMemo 扩展「AI 晨报」离线生成</footer>
|
||||
</main>`
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_CONFIG,
|
||||
DIGEST_CSS,
|
||||
normalizeConfig,
|
||||
escapeHtml,
|
||||
selectMediaBatchItems,
|
||||
buildDigestPromptMessages,
|
||||
parseDigestSummary,
|
||||
buildDigestHtml
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"manifestVersion": 1,
|
||||
"id": "com.example.morning-digest",
|
||||
"name": "AI 晨报",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": "1",
|
||||
"minAppVersion": "2.7.0",
|
||||
"description": "分页拉取指定群聊最近消息,按需解析图片与语音并经 AI 总结,离线渲染为晨报 PNG 长图、发送应用内通知,并支持人工确认后可选发送到微信。",
|
||||
"author": "TraceMemo Examples",
|
||||
"permissions": [
|
||||
"messages.query",
|
||||
"media.ocr",
|
||||
"media.transcribe",
|
||||
"ai.chat",
|
||||
"ai.vision",
|
||||
"render.html",
|
||||
"notifications.create",
|
||||
"contacts.list",
|
||||
"wechat.send.image",
|
||||
"automation.action",
|
||||
"storage"
|
||||
],
|
||||
"entrypoints": {
|
||||
"page": "ui/index.html",
|
||||
"background": "background/index.js"
|
||||
},
|
||||
"contributions": {
|
||||
"pages": [
|
||||
{
|
||||
"id": "digest",
|
||||
"title": "AI 晨报"
|
||||
}
|
||||
],
|
||||
"navigation": {
|
||||
"label": "AI 晨报",
|
||||
"icon": "digest",
|
||||
"pageId": "digest",
|
||||
"order": 10
|
||||
},
|
||||
"automationActions": [
|
||||
{
|
||||
"id": "morning-digest.generate",
|
||||
"title": "生成 AI 晨报",
|
||||
"description": "汇总已配置群聊的文字、图片与语音消息并渲染晨报长图"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const {
|
||||
normalizeConfig,
|
||||
selectMediaBatchItems,
|
||||
parseDigestSummary,
|
||||
buildDigestHtml
|
||||
} = require('../lib/digest-builder.js')
|
||||
|
||||
test('normalizeConfig 默认关闭自动发微信并收敛数值边界', () => {
|
||||
const cfg = normalizeConfig({ windowHours: 999, renderWidth: 100, groupIds: ['g1@chatroom', 'g1@chatroom'] })
|
||||
assert.equal(cfg.autoSendWechat, false)
|
||||
assert.equal(cfg.windowHours, 168)
|
||||
assert.equal(cfg.renderWidth, 320)
|
||||
assert.deepEqual(cfg.groupIds, ['g1@chatroom'])
|
||||
})
|
||||
|
||||
test('selectMediaBatchItems 按权限筛选图片 OCR/视觉与语音转写批次', () => {
|
||||
const messages = [
|
||||
{ type: 'text', messageRef: 'ref-1', text: '早安' },
|
||||
{ type: 'image', messageRef: 'ref-img' },
|
||||
{ type: 'voice', messageRef: 'ref-voice' }
|
||||
]
|
||||
const items = selectMediaBatchItems(
|
||||
messages,
|
||||
normalizeConfig({ enableImageOcr: true, enableVoiceTranscribe: true, maxMediaPerGroup: 5 }),
|
||||
['media.ocr', 'media.transcribe']
|
||||
)
|
||||
assert.equal(items.length, 2)
|
||||
assert.equal(items[0].op, 'transcribeVoice')
|
||||
assert.equal(items[1].op, 'ocrImage')
|
||||
})
|
||||
|
||||
test('buildDigestHtml 转义 HTML 特殊字符且不包含脚本或外链', () => {
|
||||
const summary = parseDigestSummary(
|
||||
JSON.stringify({
|
||||
headline: '今日<script>alert(1)</script>焦点',
|
||||
highlights: ['项目评审通过'],
|
||||
actionItems: ['张三跟进上线'],
|
||||
groupBriefs: [{ groupName: '产品测试群', summary: '讨论了发布排期' }]
|
||||
})
|
||||
)
|
||||
const html = buildDigestHtml({
|
||||
dateLabel: '2026-12-01',
|
||||
...summary,
|
||||
totalMessages: 42,
|
||||
totalMediaResolved: 3,
|
||||
groupCount: 1
|
||||
})
|
||||
assert.equal(/<script/i.test(html), false)
|
||||
assert.equal(html.includes('<script>'), true)
|
||||
assert.equal(html.includes('产品测试群'), true)
|
||||
})
|
||||
@@ -0,0 +1,251 @@
|
||||
'use strict'
|
||||
|
||||
const EXTENSION_ID = 'com.example.morning-digest'
|
||||
const PAGE_SOURCE = 'tracememo-extension-page'
|
||||
const HOST_SOURCE = 'tracememo-extension-host'
|
||||
const CONFIG_KEY = 'config'
|
||||
const LAST_DIGEST_KEY = 'lastDigest'
|
||||
|
||||
const pending = new Map()
|
||||
let seq = 0
|
||||
let groups = []
|
||||
let lastDigest = null
|
||||
let config = {
|
||||
groupIds: [],
|
||||
groupNames: {},
|
||||
windowHours: 24,
|
||||
enableImageOcr: true,
|
||||
enableImageVision: false,
|
||||
enableVoiceTranscribe: true,
|
||||
maxMediaPerGroup: 6,
|
||||
renderWidth: 460,
|
||||
autoSendWechat: false,
|
||||
wechatTargetGroupId: ''
|
||||
}
|
||||
|
||||
function callHost(method, params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const requestId = `req-${++seq}`
|
||||
pending.set(requestId, { resolve, reject })
|
||||
window.parent.postMessage(
|
||||
{ source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params: params || {} },
|
||||
'*'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
const data = event.data
|
||||
if (!data || data.source !== HOST_SOURCE) return
|
||||
const item = pending.get(data.requestId)
|
||||
if (!item) return
|
||||
pending.delete(data.requestId)
|
||||
if (data.ok) item.resolve(data.result)
|
||||
else item.reject(new Error((data.error && data.error.message) || '请求失败'))
|
||||
})
|
||||
|
||||
function setBanner(text, tone) {
|
||||
const el = document.getElementById('banner')
|
||||
el.textContent = text
|
||||
el.dataset.tone = tone || ''
|
||||
}
|
||||
|
||||
function renderGroupList() {
|
||||
const keyword = document.getElementById('group-search').value.trim().toLowerCase()
|
||||
const container = document.getElementById('group-list')
|
||||
container.textContent = ''
|
||||
const filtered = groups.filter((g) => !keyword || g.name.toLowerCase().includes(keyword))
|
||||
if (filtered.length === 0) {
|
||||
const empty = document.createElement('div')
|
||||
empty.className = 'group-item'
|
||||
empty.textContent = groups.length === 0 ? '暂无可选群聊(请先连接微信数据库)' : '没有匹配的群聊'
|
||||
container.appendChild(empty)
|
||||
return
|
||||
}
|
||||
const selectedSet = new Set(config.groupIds)
|
||||
for (const group of filtered) {
|
||||
const label = document.createElement('label')
|
||||
label.className = 'group-item'
|
||||
const input = document.createElement('input')
|
||||
input.type = 'checkbox'
|
||||
input.checked = selectedSet.has(group.id)
|
||||
input.addEventListener('change', () => {
|
||||
if (input.checked) {
|
||||
if (!config.groupIds.includes(group.id) && config.groupIds.length < 10) {
|
||||
config.groupIds.push(group.id)
|
||||
config.groupNames[group.id] = group.name
|
||||
} else {
|
||||
input.checked = false
|
||||
}
|
||||
} else {
|
||||
config.groupIds = config.groupIds.filter((id) => id !== group.id)
|
||||
}
|
||||
})
|
||||
const span = document.createElement('span')
|
||||
span.textContent = group.name
|
||||
label.appendChild(input)
|
||||
label.appendChild(span)
|
||||
container.appendChild(label)
|
||||
}
|
||||
}
|
||||
|
||||
function renderTargetSelect() {
|
||||
const select = document.getElementById('wechat-target')
|
||||
select.textContent = ''
|
||||
const none = document.createElement('option')
|
||||
none.value = ''
|
||||
none.textContent = '不自动发送'
|
||||
select.appendChild(none)
|
||||
for (const group of groups) {
|
||||
const opt = document.createElement('option')
|
||||
opt.value = group.id
|
||||
opt.textContent = group.name
|
||||
select.appendChild(opt)
|
||||
}
|
||||
select.value = config.wechatTargetGroupId || ''
|
||||
}
|
||||
|
||||
function syncForm() {
|
||||
document.getElementById('window-hours').value = String(config.windowHours || 24)
|
||||
document.getElementById('enable-ocr').checked = config.enableImageOcr !== false
|
||||
document.getElementById('enable-vision').checked = config.enableImageVision === true
|
||||
document.getElementById('enable-voice').checked = config.enableVoiceTranscribe !== false
|
||||
document.getElementById('max-media').value = String(config.maxMediaPerGroup ?? 6)
|
||||
document.getElementById('render-width').value = String(config.renderWidth ?? 460)
|
||||
document.getElementById('auto-send').checked = config.autoSendWechat === true
|
||||
renderGroupList()
|
||||
renderTargetSelect()
|
||||
}
|
||||
|
||||
function collectForm() {
|
||||
config.windowHours = Number(document.getElementById('window-hours').value) || 24
|
||||
config.enableImageOcr = document.getElementById('enable-ocr').checked
|
||||
config.enableImageVision = document.getElementById('enable-vision').checked
|
||||
config.enableVoiceTranscribe = document.getElementById('enable-voice').checked
|
||||
config.maxMediaPerGroup = Number(document.getElementById('max-media').value) || 0
|
||||
config.renderWidth = Number(document.getElementById('render-width').value) || 460
|
||||
config.wechatTargetGroupId = document.getElementById('wechat-target').value
|
||||
config.autoSendWechat = document.getElementById('auto-send').checked
|
||||
}
|
||||
|
||||
function renderDigestResult(record) {
|
||||
const el = document.getElementById('digest-result')
|
||||
const sendBtn = document.getElementById('send-last-btn')
|
||||
const previewWrap = document.getElementById('digest-preview-wrap')
|
||||
const previewImg = document.getElementById('digest-preview-img')
|
||||
const previewCaption = document.getElementById('digest-preview-caption')
|
||||
if (!record || !record.headline) {
|
||||
el.className = 'result-body empty'
|
||||
el.textContent = '尚未生成晨报,勾选群聊后点击右上角「立即生成今日晨报」。'
|
||||
previewWrap.hidden = true
|
||||
previewImg.removeAttribute('src')
|
||||
sendBtn.disabled = true
|
||||
return
|
||||
}
|
||||
el.className = 'result-body'
|
||||
const pixelMeta =
|
||||
record.pixelWidth && record.pixelHeight
|
||||
? `(实际像素 ${record.pixelWidth}×${record.pixelHeight}px,${record.deviceScaleFactor || 1}x)`
|
||||
: ''
|
||||
const lines = [
|
||||
`【标题】${record.headline}(${record.dateLabel})`,
|
||||
`【统计】覆盖 ${record.groupCount} 个群 · ${record.totalMessages} 条消息 · 解析 ${record.totalMediaResolved} 条媒体`,
|
||||
`【长图】逻辑 ${record.width}×${record.height}px${pixelMeta} · ${(Number(record.bytes || 0) / 1024).toFixed(1)}KB`,
|
||||
`【输出文件】${record.imagePath}`
|
||||
]
|
||||
if (Array.isArray(record.highlights) && record.highlights.length > 0) {
|
||||
lines.push('', '【今日重点】', ...record.highlights.map((item, idx) => `${idx + 1}. ${item}`))
|
||||
}
|
||||
if (Array.isArray(record.actionItems) && record.actionItems.length > 0) {
|
||||
lines.push('', '【待办与约定】', ...record.actionItems.map((item, idx) => `${idx + 1}. ${item}`))
|
||||
}
|
||||
el.textContent = lines.join('\n')
|
||||
if (record.previewUrl) {
|
||||
previewWrap.hidden = false
|
||||
previewCaption.textContent = `长图实时预览(受控扩展私有媒体协议):${record.previewUrl}`
|
||||
previewImg.src = `${record.previewUrl}?t=${record.generatedAt || Date.now()}`
|
||||
} else {
|
||||
previewWrap.hidden = true
|
||||
previewImg.removeAttribute('src')
|
||||
}
|
||||
sendBtn.disabled = false
|
||||
}
|
||||
|
||||
document.getElementById('group-search').addEventListener('input', renderGroupList)
|
||||
|
||||
document.getElementById('save-btn').addEventListener('click', async () => {
|
||||
collectForm()
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: config })
|
||||
setBanner('配置已保存。', 'ok')
|
||||
} catch (error) {
|
||||
setBanner(`保存失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('generate-btn').addEventListener('click', async () => {
|
||||
collectForm()
|
||||
if (config.groupIds.length === 0) {
|
||||
setBanner('请先勾选至少一个群聊。', 'error')
|
||||
return
|
||||
}
|
||||
const btn = document.getElementById('generate-btn')
|
||||
btn.disabled = true
|
||||
setBanner('正在分页拉取消息、按需解析图片/语音并离线渲染长图…')
|
||||
try {
|
||||
await callHost('storage.set', { key: CONFIG_KEY, value: config })
|
||||
const result = await callHost('extension.request', {
|
||||
method: 'generateDigest',
|
||||
params: config
|
||||
})
|
||||
lastDigest = result
|
||||
renderDigestResult(result)
|
||||
setBanner(
|
||||
result.sentToWechat
|
||||
? '今日晨报已生成、写入通知中心并已发送至目标群聊。'
|
||||
: '今日晨报已生成并写入扩展通知中心。',
|
||||
'ok'
|
||||
)
|
||||
} catch (error) {
|
||||
setBanner(`生成失败:${error.message}`, 'error')
|
||||
} finally {
|
||||
btn.disabled = false
|
||||
}
|
||||
})
|
||||
|
||||
document.getElementById('send-last-btn').addEventListener('click', async () => {
|
||||
collectForm()
|
||||
if (!config.wechatTargetGroupId) {
|
||||
setBanner('请先在「发送目标群聊」下拉框中选择一个群聊。', 'error')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await callHost('extension.request', {
|
||||
method: 'sendLastDigest',
|
||||
params: { to: config.wechatTargetGroupId }
|
||||
})
|
||||
setBanner('已通过 TraceMemo Gateway 发送晨报长图。', 'ok')
|
||||
} catch (error) {
|
||||
setBanner(`发送失败:${error.message}`, 'error')
|
||||
}
|
||||
})
|
||||
|
||||
async function init() {
|
||||
const [savedConfig, savedDigest, roster] = await Promise.all([
|
||||
callHost('storage.get', { key: CONFIG_KEY }).catch(() => null),
|
||||
callHost('storage.get', { key: LAST_DIGEST_KEY }).catch(() => null),
|
||||
callHost('contacts.listGroups', {}).catch(() => ({ groups: [] }))
|
||||
])
|
||||
if (savedConfig && typeof savedConfig === 'object') {
|
||||
config = { ...config, ...savedConfig }
|
||||
}
|
||||
groups = Array.isArray(roster && roster.groups) ? roster.groups : []
|
||||
lastDigest = savedDigest
|
||||
syncForm()
|
||||
renderDigestResult(lastDigest)
|
||||
setBanner('AI 晨报已就绪。建议先点击「立即生成今日晨报」离线预览。')
|
||||
}
|
||||
|
||||
init().catch((error) => {
|
||||
setBanner(`初始化失败:${error.message}`, 'error')
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AI 晨报</title>
|
||||
<link rel="stylesheet" href="./style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<header class="hero">
|
||||
<div>
|
||||
<div class="kicker">TraceMemo 官方模板 · com.example.morning-digest</div>
|
||||
<h1>AI 晨报</h1>
|
||||
<p class="subtitle">分页拉取群聊记录、按需解析图片与语音、AI 总结并离线生成 PNG 长图,支持通知提醒与可选微信发送。</p>
|
||||
</div>
|
||||
<div class="hero-actions">
|
||||
<button id="generate-btn" class="btn primary" type="button">立即生成今日晨报</button>
|
||||
<button id="save-btn" class="btn" type="button">保存配置</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="banner" class="banner" role="status">正在加载配置与群聊列表…</div>
|
||||
|
||||
<div class="grid">
|
||||
<section class="card">
|
||||
<h2>1. 选择采集群聊与时间窗</h2>
|
||||
<div class="field">
|
||||
<label for="window-hours">采集范围(小时)</label>
|
||||
<select id="window-hours">
|
||||
<option value="24">最近 24 小时</option>
|
||||
<option value="48">最近 48 小时</option>
|
||||
<option value="72">最近 72 小时</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="group-search">搜索并勾选目标群聊(最多 10 个)</label>
|
||||
<input id="group-search" type="search" placeholder="按群名筛选…">
|
||||
<div id="group-list" class="group-list"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>2. 按需媒体解析与长图渲染</h2>
|
||||
<label class="check-row">
|
||||
<input id="enable-ocr" type="checkbox" checked>
|
||||
<span>图片本地 OCR 文字识别(纯本地,优先复用索引缓存)</span>
|
||||
</label>
|
||||
<label class="check-row">
|
||||
<input id="enable-vision" type="checkbox">
|
||||
<span>图片 AI 视觉理解(需配置视觉模型)</span>
|
||||
</label>
|
||||
<label class="check-row">
|
||||
<input id="enable-voice" type="checkbox" checked>
|
||||
<span>语音本地转文字(复用本机语音转写服务)</span>
|
||||
</label>
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="max-media">每群最多解析媒体数</label>
|
||||
<input id="max-media" type="number" min="0" max="15" value="6">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="render-width">长图宽度(px)</label>
|
||||
<input id="render-width" type="number" min="320" max="960" value="460">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>3. 可选微信发送(默认关闭)</h3>
|
||||
<div class="field">
|
||||
<label for="wechat-target">发送目标群聊</label>
|
||||
<select id="wechat-target">
|
||||
<option value="">不自动发送</option>
|
||||
</select>
|
||||
</div>
|
||||
<label class="check-row">
|
||||
<input id="auto-send" type="checkbox">
|
||||
<span>生成后自动发送晨报长图到所选目标群(默认关闭,建议先预览)</span>
|
||||
</label>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="card result-card">
|
||||
<div class="result-head">
|
||||
<h2>最近一次晨报结果</h2>
|
||||
<button id="send-last-btn" class="btn" type="button" disabled>手动发送长图到目标群</button>
|
||||
</div>
|
||||
<div id="digest-result" class="result-body empty">尚未生成晨报,勾选群聊后点击右上角「立即生成今日晨报」。</div>
|
||||
<div id="digest-preview-wrap" class="preview-wrap" hidden>
|
||||
<div class="preview-caption" id="digest-preview-caption"></div>
|
||||
<img id="digest-preview-img" class="preview-img" alt="晨报长图预览">
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<script src="./app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,225 @@
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 24px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
background: #f5f7fa;
|
||||
color: #18212f;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.hero {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
background: #ffffff;
|
||||
border: 1px solid #e5e9f0;
|
||||
border-radius: 14px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.kicker {
|
||||
font-size: 12px;
|
||||
color: #2563eb;
|
||||
font-weight: 600;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.hero h1 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.hero-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 8px 14px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #cbd5e1;
|
||||
background: #ffffff;
|
||||
color: #1e293b;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn.primary {
|
||||
background: #2563eb;
|
||||
border-color: #2563eb;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.banner {
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
font-size: 13px;
|
||||
background: #eff6ff;
|
||||
color: #1d4ed8;
|
||||
border: 1px solid #bfdbfe;
|
||||
}
|
||||
|
||||
.banner[data-tone="error"] {
|
||||
background: #fef2f2;
|
||||
color: #b91c1c;
|
||||
border-color: #fecaca;
|
||||
}
|
||||
|
||||
.banner[data-tone="ok"] {
|
||||
background: #f0fdf4;
|
||||
color: #15803d;
|
||||
border-color: #bbf7d0;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: #ffffff;
|
||||
border: 1px solid #e5e9f0;
|
||||
border-radius: 14px;
|
||||
padding: 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.card h2 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.card h3 {
|
||||
margin: 8px 0 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select {
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #cbd5e1;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.field-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.check-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.group-list {
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
padding: 6px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.group-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.group-item:hover {
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.result-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.result-body {
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
white-space: pre-wrap;
|
||||
background: #f8fafc;
|
||||
border-radius: 10px;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.result-body.empty {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.preview-wrap {
|
||||
margin-top: 14px;
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
background: #f8fafc;
|
||||
border: 1px solid #e2e8f0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.preview-caption {
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
word-break: break-all;
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.preview-img {
|
||||
max-width: 100%;
|
||||
width: 460px;
|
||||
height: auto;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #cbd5e1;
|
||||
box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08);
|
||||
background: #ffffff;
|
||||
}
|
||||
@@ -14,8 +14,12 @@
|
||||
"bytes": 33471
|
||||
},
|
||||
"group-chat-bot@1.0.0": {
|
||||
"sha256": "122a4da7710cf882975f09440819e9dc1b619e4bd6f94153085a7d6fe8a33885",
|
||||
"bytes": 24981
|
||||
"sha256": "eb672f076710619dc363756d854319a8ded9b8f6a4833c258c1493c57bb89629",
|
||||
"bytes": 25231
|
||||
},
|
||||
"group-chat-bot@1.1.0": {
|
||||
"sha256": "be1fb28a2b8a20c95fccd19f6e2229f7166abfffefcf120309febcf3c882f437",
|
||||
"bytes": 25947
|
||||
},
|
||||
"keyword-bot@1.0.0": {
|
||||
"sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d",
|
||||
@@ -24,6 +28,10 @@
|
||||
"keyword-bot@1.0.1": {
|
||||
"sha256": "ae379a10dac553b60cc8c823186734d917b604b6dff27e2e7d2d62f5cf5e4d41",
|
||||
"bytes": 19517
|
||||
},
|
||||
"morning-digest@1.0.0": {
|
||||
"sha256": "3336d3c7739aad0d40919546ca7884581aaaf7e3487db5428041d6bc0f6bd992",
|
||||
"bytes": 14556
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+239
-9
@@ -1,4 +1,4 @@
|
||||
/** TraceMemo 扩展 SDK v1:仅类型定义,运行期由宿主注入全局 tm。 */
|
||||
/** TraceMemo 扩展 SDK v1(兼容扩展):仅类型定义,运行期由宿主注入全局 tm。 */
|
||||
|
||||
export type ExtensionMessageType =
|
||||
| 'text'
|
||||
@@ -11,9 +11,23 @@ export type ExtensionMessageType =
|
||||
| 'system'
|
||||
| 'other'
|
||||
|
||||
export type ExtensionNavigationIcon =
|
||||
| 'spark'
|
||||
| 'bot'
|
||||
| 'digest'
|
||||
| 'bell'
|
||||
| 'media'
|
||||
| 'puzzle'
|
||||
| 'compass'
|
||||
| 'message'
|
||||
|
||||
export type ExtensionNotificationLevel = 'info' | 'success' | 'warning' | 'error'
|
||||
|
||||
export interface TraceMemoMessageEvent {
|
||||
/** 同一条微信消息稳定不变:`message:<sha1(sessionId:localId)>`。 */
|
||||
eventId: string
|
||||
/** 跨实时事件与历史查询统一的不透明消息引用,可直接传给 tm.media.* 接口。 */
|
||||
messageRef: string
|
||||
accountId: string
|
||||
conversationId: string
|
||||
messageId: string
|
||||
@@ -31,6 +45,8 @@ export interface TraceMemoMessageEvent {
|
||||
|
||||
export interface TraceMemoQueriedMessage {
|
||||
messageId: string
|
||||
/** 跨实时事件与历史查询统一的不透明消息引用,可直接传给 tm.media.* 接口。 */
|
||||
messageRef: string
|
||||
conversationId: string
|
||||
senderId?: string
|
||||
senderName?: string
|
||||
@@ -41,6 +57,175 @@ export interface TraceMemoQueriedMessage {
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export interface TraceMemoMessagesQueryRequest {
|
||||
conversationId: string
|
||||
/** epoch 毫秒;默认最近 24 小时。 */
|
||||
startTime?: number
|
||||
/** epoch 毫秒;默认现在。 */
|
||||
endTime?: number
|
||||
limit?: number
|
||||
/** 上一页返回的 opaque 游标;同时间戳多条消息不漏不重。 */
|
||||
cursor?: string
|
||||
order?: 'asc' | 'desc'
|
||||
types?: ExtensionMessageType[]
|
||||
}
|
||||
|
||||
export interface TraceMemoMessagesQueryResult {
|
||||
messages: TraceMemoQueriedMessage[]
|
||||
nextCursor?: string
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaReadImageResult {
|
||||
messageRef: string
|
||||
mimeType: string
|
||||
bytes: number
|
||||
sha256: string
|
||||
/** 扩展私有数据目录内的可读副本路径。 */
|
||||
path: string
|
||||
/** 扩展沙箱页面可直接加载的受控只读预览 URL。 */
|
||||
previewUrl?: string
|
||||
quality: 'original' | 'thumbnail'
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaReadVoiceResult {
|
||||
messageRef: string
|
||||
mimeType: 'audio/wav'
|
||||
bytes: number
|
||||
sha256: string
|
||||
durationMs?: number
|
||||
path: string
|
||||
previewUrl?: string
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaReadVideoResult {
|
||||
messageRef: string
|
||||
mimeType: 'video/mp4'
|
||||
bytes: number
|
||||
sha256: string
|
||||
path: string
|
||||
previewUrl?: string
|
||||
posterPath?: string
|
||||
posterPreviewUrl?: string
|
||||
durationMs?: number
|
||||
width?: number
|
||||
height?: number
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaOcrImageResult {
|
||||
messageRef: string
|
||||
text: string
|
||||
language: string | null
|
||||
engine: string
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaTranscribeVoiceResult {
|
||||
messageRef: string
|
||||
state: 'transcribed' | 'pending' | 'failed'
|
||||
transcript?: string
|
||||
durationMs?: number
|
||||
cached: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaAnalyzeImageResult {
|
||||
messageRef: string
|
||||
description: string
|
||||
ocrText?: string
|
||||
tags?: string[]
|
||||
category?: string
|
||||
model?: string
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export type TraceMemoMediaBatchOperation =
|
||||
| 'readImage'
|
||||
| 'readVoice'
|
||||
| 'readVideo'
|
||||
| 'ocrImage'
|
||||
| 'transcribeVoice'
|
||||
| 'analyzeImage'
|
||||
|
||||
export interface TraceMemoMediaBatchItem {
|
||||
op: TraceMemoMediaBatchOperation
|
||||
messageRef: string
|
||||
options?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface TraceMemoMediaBatchItemResult {
|
||||
index: number
|
||||
op: TraceMemoMediaBatchOperation
|
||||
messageRef: string
|
||||
ok: boolean
|
||||
result?:
|
||||
| TraceMemoMediaReadImageResult
|
||||
| TraceMemoMediaReadVoiceResult
|
||||
| TraceMemoMediaReadVideoResult
|
||||
| TraceMemoMediaOcrImageResult
|
||||
| TraceMemoMediaTranscribeVoiceResult
|
||||
| TraceMemoMediaAnalyzeImageResult
|
||||
error?: { code: string; message: string }
|
||||
}
|
||||
|
||||
export interface TraceMemoRenderHtmlRequest {
|
||||
html: string
|
||||
css?: string
|
||||
/** 可选相对文件名(输出到扩展私有目录的 rendered/ 下)。 */
|
||||
fileName?: string
|
||||
width?: number
|
||||
maxHeight?: number
|
||||
backgroundColor?: string
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export interface TraceMemoRenderHtmlResult {
|
||||
path: string
|
||||
/** 扩展沙箱页面可直接加载的受控只读预览 URL。 */
|
||||
previewUrl?: string
|
||||
width: number
|
||||
height: number
|
||||
pixelWidth?: number
|
||||
pixelHeight?: number
|
||||
deviceScaleFactor?: number
|
||||
bytes: number
|
||||
mimeType: 'image/png'
|
||||
sha256: string
|
||||
}
|
||||
|
||||
export interface TraceMemoNotificationCreateRequest {
|
||||
title: string
|
||||
body?: string
|
||||
level?: ExtensionNotificationLevel
|
||||
/** 扩展内去重键;相同键更新既有通知而不重复叠加未读数。 */
|
||||
dedupeKey?: string
|
||||
/** 点击通知后跳转的本扩展页面 id。 */
|
||||
pageId?: string
|
||||
}
|
||||
|
||||
export interface TraceMemoNotificationCreateResult {
|
||||
id: string
|
||||
deduped: boolean
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
export interface TraceMemoNotificationItem {
|
||||
id: string
|
||||
extensionId: string
|
||||
extensionName: string
|
||||
title: string
|
||||
body?: string
|
||||
level: ExtensionNotificationLevel
|
||||
dedupeKey?: string
|
||||
pageId?: string
|
||||
read: boolean
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface TraceMemoSendTextRequest {
|
||||
/** 缺省为 text。 */
|
||||
type?: 'text'
|
||||
@@ -147,6 +332,18 @@ export interface TraceMemoApi {
|
||||
readonly dataDir: string
|
||||
readonly permissions: string[]
|
||||
}
|
||||
page: {
|
||||
onRequest(
|
||||
method: string,
|
||||
handler: (params: Record<string, unknown>) => unknown | Promise<unknown>
|
||||
): void
|
||||
}
|
||||
secrets: {
|
||||
get(key: string): Promise<string | null>
|
||||
set(key: string, value: string): Promise<void>
|
||||
delete(key: string): Promise<void>
|
||||
has(key: string): Promise<boolean>
|
||||
}
|
||||
events: {
|
||||
on(
|
||||
name: 'message.received',
|
||||
@@ -158,20 +355,53 @@ export interface TraceMemoApi {
|
||||
): void
|
||||
}
|
||||
messages: {
|
||||
query(request: {
|
||||
conversationId: string
|
||||
/** epoch 毫秒;默认最近 24 小时。 */
|
||||
startTime?: number
|
||||
/** epoch 毫秒;默认现在。 */
|
||||
endTime?: number
|
||||
limit?: number
|
||||
}): Promise<{ messages: TraceMemoQueriedMessage[] }>
|
||||
query(request: TraceMemoMessagesQueryRequest): Promise<TraceMemoMessagesQueryResult>
|
||||
}
|
||||
media: {
|
||||
readImage(request: {
|
||||
messageRef: string
|
||||
quality?: 'original' | 'thumbnail'
|
||||
}): Promise<TraceMemoMediaReadImageResult>
|
||||
readVoice(request: { messageRef: string }): Promise<TraceMemoMediaReadVoiceResult>
|
||||
readVideo(request: { messageRef: string }): Promise<TraceMemoMediaReadVideoResult>
|
||||
ocrImage(request: {
|
||||
messageRef: string
|
||||
language?: string
|
||||
force?: boolean
|
||||
}): Promise<TraceMemoMediaOcrImageResult>
|
||||
transcribeVoice(request: {
|
||||
messageRef: string
|
||||
force?: boolean
|
||||
waitMs?: number
|
||||
}): Promise<TraceMemoMediaTranscribeVoiceResult>
|
||||
analyzeImage(request: {
|
||||
messageRef: string
|
||||
prompt?: string
|
||||
force?: boolean
|
||||
}): Promise<TraceMemoMediaAnalyzeImageResult>
|
||||
batch(request: {
|
||||
items: TraceMemoMediaBatchItem[]
|
||||
concurrency?: number
|
||||
}): Promise<{ results: TraceMemoMediaBatchItemResult[] }>
|
||||
}
|
||||
render: {
|
||||
htmlToImage(request: TraceMemoRenderHtmlRequest): Promise<TraceMemoRenderHtmlResult>
|
||||
}
|
||||
notifications: {
|
||||
create(request: TraceMemoNotificationCreateRequest): Promise<TraceMemoNotificationCreateResult>
|
||||
list(): Promise<TraceMemoNotificationItem[]>
|
||||
markRead(request?: { id?: string; all?: boolean }): Promise<{ changed: number }>
|
||||
}
|
||||
wechat: {
|
||||
send(request: TraceMemoSendRequest): Promise<{ actionId: string; status: 'sent' }>
|
||||
}
|
||||
ai: {
|
||||
chat(messages: Array<{ role: string; content: string }>): Promise<{ text: string }>
|
||||
analyzeImage(request: {
|
||||
messageRef: string
|
||||
prompt?: string
|
||||
force?: boolean
|
||||
}): Promise<TraceMemoMediaAnalyzeImageResult>
|
||||
}
|
||||
storage: {
|
||||
get(key: string): Promise<unknown>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 152 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 478 KiB |
@@ -33,6 +33,16 @@ const TEMPLATE_SPECS = [
|
||||
},
|
||||
platforms: ['darwin', 'win32']
|
||||
},
|
||||
{
|
||||
id: 'morning-digest',
|
||||
dir: 'morning-digest',
|
||||
requires: {
|
||||
python: false,
|
||||
chrome: false,
|
||||
externalScript: false
|
||||
},
|
||||
platforms: ['darwin', 'win32']
|
||||
},
|
||||
{
|
||||
id: 'douyin-sender',
|
||||
dir: 'douyin-sender',
|
||||
|
||||
@@ -646,18 +646,245 @@ body {
|
||||
border-radius: 4px;
|
||||
object-fit: cover;
|
||||
}
|
||||
.forward-content details { margin-top: 2px; }
|
||||
.forward-content summary {
|
||||
color: var(--accent);
|
||||
.forward-content.is-clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
.forward-content.is-clickable:hover .forward-footer-action {
|
||||
color: var(--accent);
|
||||
}
|
||||
.forward-preview-list {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.forward-preview-line {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.forward-preview-line strong {
|
||||
color: var(--ink);
|
||||
font-weight: 600;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.forward-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 8px;
|
||||
padding-top: 7px;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
.forward-footer-action {
|
||||
transition: color .15s ease;
|
||||
}
|
||||
.forward-modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background: rgba(15, 23, 42, 0.36);
|
||||
}
|
||||
.forward-modal-window {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(560px, calc(100vw - 48px));
|
||||
max-height: min(78vh, 720px);
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
background: #ffffff;
|
||||
color: var(--ink);
|
||||
box-shadow: 0 20px 48px rgba(15, 23, 42, 0.22);
|
||||
}
|
||||
.forward-modal-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 14px 18px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: #f8fafc;
|
||||
}
|
||||
.forward-modal-header-text {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.forward-modal-title {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.forward-modal-subtitle {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.forward-modal-close {
|
||||
flex: 0 0 auto;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.forward-modal-close:hover {
|
||||
background: rgba(15, 23, 42, 0.08);
|
||||
color: var(--ink);
|
||||
}
|
||||
.forward-modal-body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 16px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
.forward-modal-row {
|
||||
display: grid;
|
||||
grid-template-columns: 36px minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
align-items: start;
|
||||
}
|
||||
.forward-modal-avatar {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: rgba(7, 193, 96, 0.14);
|
||||
color: var(--accent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.forward-list, .forward-list ol {
|
||||
.forward-modal-avatar img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.forward-modal-row-main {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.forward-modal-row:last-child .forward-modal-row-main {
|
||||
padding-bottom: 0;
|
||||
border-bottom: 0;
|
||||
}
|
||||
.forward-modal-row-meta {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.forward-modal-sender {
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
color: var(--ink);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.forward-modal-time {
|
||||
flex: 0 0 auto;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.forward-modal-text {
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
.forward-modal-link {
|
||||
margin-left: 8px;
|
||||
color: var(--accent);
|
||||
font-size: 12px;
|
||||
text-decoration: none;
|
||||
}
|
||||
.forward-modal-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.forward-modal-image {
|
||||
display: block;
|
||||
max-width: min(240px, 100%);
|
||||
max-height: 320px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--line);
|
||||
object-fit: contain;
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.forward-modal-image-missing {
|
||||
display: inline-block;
|
||||
padding: 6px 10px;
|
||||
border-radius: 8px;
|
||||
background: #f1f5f9;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.forward-modal-nested-card {
|
||||
width: min(320px, 100%);
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
background: #f8fafc;
|
||||
color: inherit;
|
||||
text-align: left;
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
margin: 8px 0 0;
|
||||
padding-left: 18px;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.forward-modal-nested-card:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.forward-modal-nested-title {
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
color: var(--ink);
|
||||
}
|
||||
.forward-modal-nested-line {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.forward-modal-nested-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding-top: 6px;
|
||||
border-top: 1px solid var(--line);
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.forward-modal-empty {
|
||||
padding: 32px 0;
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
.forward-item { color: var(--muted); font-size: 12px; line-height: 1.5; }
|
||||
.forward-item strong { color: var(--text); font-weight: 650; }
|
||||
@@ -687,7 +914,7 @@ body {
|
||||
display: none;
|
||||
place-items: center;
|
||||
background: #14231ddd;
|
||||
z-index: 10;
|
||||
z-index: 80;
|
||||
padding: 24px;
|
||||
overflow: auto;
|
||||
}
|
||||
@@ -705,7 +932,7 @@ body {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 11;
|
||||
z-index: 81;
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border: 1px solid #ffffff66;
|
||||
@@ -1121,27 +1348,26 @@ const renderExportScript = (name: string): string => `
|
||||
(iconUrl ? '<img class="mini-program-icon" src="' + iconUrl + '" alt="">' : '') +
|
||||
'<span>' + displayText(data.appName || '小程序') + '</span></div></div>'
|
||||
}
|
||||
const renderForwardItems = (items, depth = 0) => {
|
||||
if (!Array.isArray(items) || !items.length || depth > 4) return ''
|
||||
return '<ol class="forward-list">' + items.map((item) =>
|
||||
'<li class="forward-item">' +
|
||||
(item.sender ? '<strong>' + displayText(item.sender) + '</strong>' : '') +
|
||||
(item.sentAt ? '<time>' + displayText(item.sentAt) + '</time>' : '') +
|
||||
'<span>' + displayText(item.text || '[消息]') + '</span>' +
|
||||
renderForwardItems(item.nested, depth + 1) + '</li>'
|
||||
).join('') + '</ol>'
|
||||
}
|
||||
const renderForwardContent = (data) => {
|
||||
const renderForwardContent = (data, archiveIndex) => {
|
||||
const items = Array.isArray(data.items) ? data.items : []
|
||||
return '<div class="structured-content forward-content" data-rich-kind="forwardBundle">' +
|
||||
const previewItems = items.slice(0, 4)
|
||||
const previewHtml = previewItems.length
|
||||
? '<div class="forward-preview-list">' + previewItems.map((item) =>
|
||||
'<div class="forward-preview-line">' +
|
||||
(item.sender ? '<strong>' + displayText(item.sender) + ':</strong>' : '') +
|
||||
'<span>' + displayText(item.text || '[消息]') + '</span></div>'
|
||||
).join('') + '</div>'
|
||||
: (data.description
|
||||
? '<div class="structured-description">' + displayText(data.description) + '</div>'
|
||||
: '')
|
||||
return '<div class="structured-content forward-content is-clickable" data-rich-kind="forwardBundle" data-forward-open="' +
|
||||
archiveIndex + '" role="button" tabindex="0">' +
|
||||
'<div class="structured-kicker">聊天记录</div>' +
|
||||
'<div class="structured-title">' + displayText(data.title || '聊天记录') + '</div>' +
|
||||
(!items.length && data.description
|
||||
? '<div class="structured-description">' + displayText(data.description) + '</div>'
|
||||
: '') +
|
||||
(items.length
|
||||
? '<details><summary>展开 ' + items.length + ' 条消息</summary>' + renderForwardItems(items) + '</details>'
|
||||
: '') + '</div>'
|
||||
previewHtml +
|
||||
'<div class="forward-footer"><span>' +
|
||||
(items.length ? '共 ' + items.length + ' 条消息' : '聊天记录') +
|
||||
'</span><span class="forward-footer-action">查看详情</span></div></div>'
|
||||
}
|
||||
const renderLocationContent = (data) => {
|
||||
const latitude = Number(data.lat)
|
||||
@@ -1195,7 +1421,7 @@ const renderExportScript = (name: string): string => `
|
||||
displayText([data.status, durationText].filter(Boolean).join(' · ') || '通话消息') +
|
||||
'</div></div>'
|
||||
}
|
||||
const renderStructuredContent = (data) => {
|
||||
const renderStructuredContent = (data, archiveIndex) => {
|
||||
if (data.type === 'share') {
|
||||
const typeVal = String(data.typeVal || '')
|
||||
if (typeVal === '6' || typeVal === '74') return ''
|
||||
@@ -1203,7 +1429,7 @@ const renderExportScript = (name: string): string => `
|
||||
return renderShareContent(data)
|
||||
}
|
||||
if (data.type === 'miniProgram') return renderMiniProgramContent(data)
|
||||
if (data.type === 'forwardBundle') return renderForwardContent(data)
|
||||
if (data.type === 'forwardBundle') return renderForwardContent(data, archiveIndex)
|
||||
if (data.type === 'location') return renderLocationContent(data)
|
||||
if (data.type === 'redPacket') return renderPaymentContent(data, 'redPacket')
|
||||
if (data.type === 'voip') return renderVoipContent(data)
|
||||
@@ -1248,7 +1474,7 @@ const renderExportScript = (name: string): string => `
|
||||
const quote = data.type === 'quote'
|
||||
? '<div class="quote-reference"><strong>' + esc(data.quotedSender || '引用消息') + '</strong><span>' + esc(data.quotedContent || '[引用消息]') + '</span></div>'
|
||||
: ''
|
||||
const structured = renderStructuredContent(data)
|
||||
const structured = renderStructuredContent(data, archiveIndex)
|
||||
const isSystem = data.type === 'system'
|
||||
const sender = message.name || (message.isSender ? '我' : '联系人')
|
||||
const avatarFallback = esc(String(sender || '友').slice(0, 1))
|
||||
@@ -1803,25 +2029,174 @@ const renderExportScript = (name: string): string => `
|
||||
if (dayButton) jumpToDate(dayButton.dataset.date)
|
||||
})
|
||||
|
||||
const forwardModalRoot = document.getElementById('forward-modal-root')
|
||||
let forwardModalLayers = []
|
||||
|
||||
const formatForwardTime = (raw) => {
|
||||
const value = String(raw || '').trim()
|
||||
if (!value) return ''
|
||||
if (/^\\d{9,13}$/.test(value)) {
|
||||
const ms = value.length > 10 ? Number(value) : Number(value) * 1000
|
||||
const date = new Date(ms)
|
||||
if (!Number.isNaN(date.getTime())) {
|
||||
return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) +
|
||||
' ' + pad(date.getHours()) + ':' + pad(date.getMinutes())
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
const renderForwardModalRow = (item, layerIndex, itemIndex) => {
|
||||
const sender = item.sender || '未知发送者'
|
||||
const initial = esc(Array.from(String(sender).trim())[0] || '?')
|
||||
const headUrl = externalUrl(item.sourceHeadUrl || '')
|
||||
const avatarHtml = headUrl
|
||||
? '<div class="forward-modal-avatar"><img src="' + headUrl + '" alt="" loading="lazy" referrerpolicy="no-referrer" onerror="this.remove()"></div>'
|
||||
: '<div class="forward-modal-avatar">' + initial + '</div>'
|
||||
const timeText = formatForwardTime(item.sentAt)
|
||||
const isNested = item.messageType === 17 || (Array.isArray(item.nested) && item.nested.length > 0)
|
||||
const isImage = !isNested && (item.messageType === 2 || Boolean(item.exportMediaUrl || item.imageMd5 || item.thumbMd5 || item.imageDatName))
|
||||
let bodyHtml = ''
|
||||
if (isNested) {
|
||||
const nestedTitle = item.nestedTitle || item.title || '聊天记录'
|
||||
const nestedItems = Array.isArray(item.nested) ? item.nested : []
|
||||
const previewLines = nestedItems.slice(0, 3).map((child) =>
|
||||
'<div class="forward-modal-nested-line">' +
|
||||
(child.sender ? esc(child.sender) + ': ' : '') +
|
||||
displayText(child.text || '[消息]') + '</div>'
|
||||
).join('')
|
||||
bodyHtml = '<button type="button" class="forward-modal-nested-card" data-forward-nested-layer="' +
|
||||
layerIndex + '" data-forward-nested-item="' + itemIndex + '"' +
|
||||
(nestedItems.length ? '' : ' disabled') + '>' +
|
||||
'<div class="forward-modal-nested-title">' + displayText(nestedTitle) + '</div>' +
|
||||
(previewLines || '<div class="forward-modal-nested-line">' + displayText(item.text || '[聊天记录]') + '</div>') +
|
||||
'<div class="forward-modal-nested-footer"><span>聊天记录</span><span>' +
|
||||
(nestedItems.length ? '共 ' + nestedItems.length + ' 条 · 打开新窗口' : '') +
|
||||
'</span></div></button>'
|
||||
} else if (isImage) {
|
||||
bodyHtml = item.exportMediaUrl
|
||||
? '<img class="forward-modal-image" data-preview src="' + esc(item.exportMediaUrl) + '" alt="图片">'
|
||||
: '<span class="forward-modal-image-missing">[图片未导出到本地]</span>'
|
||||
} else {
|
||||
const linkHref = externalUrl(item.linkUrl || '')
|
||||
bodyHtml = '<div class="forward-modal-text">' + displayText(item.text || item.title || '[消息]') +
|
||||
(linkHref ? '<a class="forward-modal-link" href="' + linkHref + '" target="_blank" rel="noreferrer noopener">打开链接 ↗</a>' : '') +
|
||||
'</div>'
|
||||
}
|
||||
return '<article class="forward-modal-row">' + avatarHtml +
|
||||
'<div class="forward-modal-row-main"><header class="forward-modal-row-meta">' +
|
||||
'<span class="forward-modal-sender">' + displayText(sender) + '</span>' +
|
||||
(timeText ? '<time class="forward-modal-time">' + esc(timeText) + '</time>' : '') +
|
||||
'</header><div>' + bodyHtml + '</div></div></article>'
|
||||
}
|
||||
|
||||
const renderForwardModals = () => {
|
||||
if (!forwardModalRoot) return
|
||||
if (!forwardModalLayers.length) {
|
||||
forwardModalRoot.innerHTML = ''
|
||||
return
|
||||
}
|
||||
forwardModalRoot.innerHTML = forwardModalLayers.map((layer, index) => {
|
||||
const zIndex = Math.min(75, 30 + index)
|
||||
const offsetX = Math.min(index, 5) * 28
|
||||
const offsetY = Math.min(index, 5) * 24
|
||||
const items = Array.isArray(layer.items) ? layer.items : []
|
||||
const rowsHtml = items.length
|
||||
? items.map((item, itemIdx) => renderForwardModalRow(item, index, itemIdx)).join('')
|
||||
: '<div class="forward-modal-empty">暂未解析到可展示的记录</div>'
|
||||
return '<div class="forward-modal-backdrop" data-forward-backdrop="' + index + '" style="z-index:' + zIndex + '">' +
|
||||
'<section class="forward-modal-window" role="dialog" aria-modal="true" aria-label="' + esc(layer.title || '聊天记录') +
|
||||
'" style="transform:translate(' + offsetX + 'px,' + offsetY + 'px)">' +
|
||||
'<header class="forward-modal-header"><div class="forward-modal-header-text">' +
|
||||
'<h3 class="forward-modal-title">' + displayText(layer.title || '聊天记录') + '</h3>' +
|
||||
'<span class="forward-modal-subtitle">共 ' + items.length + ' 条消息' +
|
||||
(index > 0 ? ' · 嵌套窗口 #' + (index + 1) : '') + '</span></div>' +
|
||||
'<button type="button" class="forward-modal-close" data-forward-close="' + index + '" aria-label="关闭聊天记录窗口">×</button>' +
|
||||
'</header><div class="forward-modal-body">' + rowsHtml + '</div></section></div>'
|
||||
}).join('')
|
||||
}
|
||||
|
||||
const openForwardModal = (titleText, items) => {
|
||||
forwardModalLayers = [{ title: titleText || '聊天记录', items: Array.isArray(items) ? items : [] }]
|
||||
renderForwardModals()
|
||||
}
|
||||
|
||||
const pushNestedForwardModal = (layerIndex, itemIndex) => {
|
||||
const parentLayer = forwardModalLayers[layerIndex]
|
||||
const item = parentLayer && Array.isArray(parentLayer.items) ? parentLayer.items[itemIndex] : null
|
||||
if (!item || !Array.isArray(item.nested) || !item.nested.length) return
|
||||
forwardModalLayers = forwardModalLayers.slice(0, layerIndex + 1).concat([{
|
||||
title: item.nestedTitle || item.title || '聊天记录',
|
||||
items: item.nested
|
||||
}])
|
||||
renderForwardModals()
|
||||
}
|
||||
|
||||
const closeForwardModalFrom = (index) => {
|
||||
forwardModalLayers = forwardModalLayers.slice(0, index)
|
||||
renderForwardModals()
|
||||
}
|
||||
|
||||
const updateZoom = () => preview.style.setProperty('--zoom', zoom)
|
||||
const closeLightbox = () => {
|
||||
box.classList.remove('open')
|
||||
zoom = 1
|
||||
updateZoom()
|
||||
}
|
||||
const openLightbox = (src) => {
|
||||
preview.src = src
|
||||
zoom = 1
|
||||
updateZoom()
|
||||
box.classList.add('open')
|
||||
}
|
||||
list.addEventListener('click', (event) => {
|
||||
const locateButton = event.target.closest('[data-locate-index]')
|
||||
if (locateButton) {
|
||||
locateInAll(Number(locateButton.dataset.locateIndex))
|
||||
return
|
||||
}
|
||||
const forwardCard = event.target.closest('[data-forward-open]')
|
||||
if (forwardCard) {
|
||||
const msgIndex = Number(forwardCard.dataset.forwardOpen)
|
||||
// data-forward-open 写的是 filtered 下标(renderWindow 用 windowStart + index),
|
||||
// 不能用 allMessages[msgIndex]:切会话 / 搜索 / 按类型筛选后 filtered 会比全集短。
|
||||
const targetMessage = filtered[msgIndex]
|
||||
const bundle = targetMessage && targetMessage.contentData
|
||||
if (bundle && bundle.type === 'forwardBundle') {
|
||||
openForwardModal(bundle.title || '聊天记录', bundle.items || [])
|
||||
}
|
||||
return
|
||||
}
|
||||
const image = event.target.closest('img[data-preview]')
|
||||
if (!image) return
|
||||
preview.src = image.src
|
||||
zoom = 1
|
||||
updateZoom()
|
||||
box.classList.add('open')
|
||||
openLightbox(image.src)
|
||||
})
|
||||
if (forwardModalRoot) {
|
||||
forwardModalRoot.addEventListener('click', (event) => {
|
||||
const closeBtn = event.target.closest('[data-forward-close]')
|
||||
if (closeBtn) {
|
||||
closeForwardModalFrom(Number(closeBtn.dataset.forwardClose))
|
||||
return
|
||||
}
|
||||
const nestedBtn = event.target.closest('[data-forward-nested-layer]')
|
||||
if (nestedBtn) {
|
||||
pushNestedForwardModal(
|
||||
Number(nestedBtn.dataset.forwardNestedLayer),
|
||||
Number(nestedBtn.dataset.forwardNestedItem)
|
||||
)
|
||||
return
|
||||
}
|
||||
const img = event.target.closest('img[data-preview]')
|
||||
if (img) {
|
||||
openLightbox(img.src)
|
||||
return
|
||||
}
|
||||
const backdrop = event.target.closest('[data-forward-backdrop]')
|
||||
if (backdrop && event.target === backdrop) {
|
||||
closeForwardModalFrom(Number(backdrop.dataset.forwardBackdrop))
|
||||
}
|
||||
})
|
||||
}
|
||||
preview.addEventListener('wheel', (event) => {
|
||||
event.preventDefault()
|
||||
zoom = Math.min(5, Math.max(.5, zoom + (event.deltaY < 0 ? .2 : -.2)))
|
||||
@@ -1837,7 +2212,11 @@ const renderExportScript = (name: string): string => `
|
||||
closeButton.addEventListener('click', closeLightbox)
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape') {
|
||||
closeLightbox()
|
||||
if (box.classList.contains('open')) {
|
||||
closeLightbox()
|
||||
} else if (forwardModalLayers.length > 0) {
|
||||
closeForwardModalFrom(forwardModalLayers.length - 1)
|
||||
}
|
||||
setConversationMenuOpen(false)
|
||||
}
|
||||
})
|
||||
@@ -1940,6 +2319,7 @@ export function renderExportPage(name: string): string {
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
<div id="forward-modal-root"></div>
|
||||
<div class="lightbox" id="lightbox">
|
||||
<button class="lightbox-close" id="lightbox-close" type="button" aria-label="关闭图片预览">×</button>
|
||||
<img id="lightbox-image" alt="预览">
|
||||
|
||||
+377
-8
@@ -26,6 +26,21 @@ import type { VoiceRecognitionUseCase } from './voice-pipeline/voice-recognition
|
||||
import { imageFileQuality } from '../shared/image-quality'
|
||||
import { resolveMemberName } from '../shared/member-names'
|
||||
import { filesystemSafeName } from '../shared/contact-name'
|
||||
import { macWechatRuntimeManager } from './services/mac-wechat-runtime-manager'
|
||||
import { isReadOnlyMode } from './services/read-only-mode'
|
||||
|
||||
const unescapeXmlForExport = (text: string): string =>
|
||||
text
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, '&')
|
||||
|
||||
const extractXmlAttrForExport = (xmlText: string, attrName: string): string => {
|
||||
const match = new RegExp(`(?:\\s|^)${attrName}\\s*=\\s*["']([^"']*)["']`, 'i').exec(xmlText)
|
||||
return match?.[1]?.trim() || ''
|
||||
}
|
||||
|
||||
const jobs = new Set<string>()
|
||||
const activeArchives = new Map<string, Archiver>()
|
||||
@@ -524,11 +539,28 @@ export async function pruneHtmlArchiveResources(
|
||||
referenced[directory].add(fileName)
|
||||
}
|
||||
|
||||
const addForwardBundleReferences = (
|
||||
items?: Array<{ exportMediaUrl?: string; nested?: Array<{ exportMediaUrl?: string; nested?: unknown[] }> }>
|
||||
): void => {
|
||||
if (!Array.isArray(items)) return
|
||||
for (const item of items) {
|
||||
addReference(item.exportMediaUrl)
|
||||
if (Array.isArray(item.nested)) {
|
||||
addForwardBundleReferences(
|
||||
item.nested as Array<{ exportMediaUrl?: string; nested?: Array<{ exportMediaUrl?: string; nested?: unknown[] }> }>
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const conversation of archive.conversations) addReference(conversation.avatarUrl)
|
||||
for (const message of archive.messages) {
|
||||
addReference(message.voiceDataUrl)
|
||||
addReference(message.exportMediaUrl)
|
||||
addReference(message.exportAvatarUrl)
|
||||
if (message.contentData?.type === 'forwardBundle') {
|
||||
addForwardBundleReferences(message.contentData.items)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [directory, prefixes] of Object.entries(htmlArchiveResourcePrefixes) as [
|
||||
@@ -1352,6 +1384,11 @@ async function runSingleExport(
|
||||
})
|
||||
continue
|
||||
}
|
||||
const shouldDownloadOriginalMedia = Boolean(
|
||||
request.downloadOriginalMedia &&
|
||||
request.preferOriginal !== false &&
|
||||
process.platform === 'darwin'
|
||||
)
|
||||
const reusableMediaType =
|
||||
message.contentData.type === 'image' ||
|
||||
message.contentData.type === 'video' ||
|
||||
@@ -1363,6 +1400,8 @@ async function runSingleExport(
|
||||
const reusableImageQuality =
|
||||
previous?.exportMediaQuality === 'original' ||
|
||||
(request.preferOriginal === false && previous?.exportMediaQuality === 'thumbnail')
|
||||
const reusableVideoQuality =
|
||||
!shouldDownloadOriginalMedia || previous?.exportMediaQuality === 'original'
|
||||
let reusableMediaExists = false
|
||||
if (reusableMediaType && previous?.exportMediaUrl) {
|
||||
reusableMediaExists = await resourceExists(previous.exportMediaUrl)
|
||||
@@ -1384,6 +1423,7 @@ async function runSingleExport(
|
||||
previous?.exportMediaUrl &&
|
||||
(!previous.exportMediaType || previous.exportMediaType === reusableMediaType) &&
|
||||
(reusableMediaType !== 'image' || reusableImageQuality) &&
|
||||
(reusableMediaType !== 'video' || reusableVideoQuality) &&
|
||||
reusableMediaExists
|
||||
) {
|
||||
message.exportMediaUrl = previous.exportMediaUrl
|
||||
@@ -1435,6 +1475,69 @@ async function runSingleExport(
|
||||
decryptedImage = decrypted
|
||||
break
|
||||
}
|
||||
let downloadedOriginalImage = false
|
||||
let originalDownloadError = ''
|
||||
if (
|
||||
shouldDownloadOriginalMedia &&
|
||||
(!decryptedImage || imageFileQuality(decryptedImage.filePath) !== 'original') &&
|
||||
message.sessionId &&
|
||||
message.localId != null &&
|
||||
typeof client?.getRawMessageContent === 'function'
|
||||
) {
|
||||
try {
|
||||
const raw = client.getRawMessageContent(
|
||||
message.sessionId,
|
||||
message.localId,
|
||||
message.createTime || undefined
|
||||
)
|
||||
const xml = raw
|
||||
? raw.trim().includes('<')
|
||||
? raw.trim()
|
||||
: unescapeXmlForExport(raw.trim())
|
||||
: ''
|
||||
if (xml && /<img\b/i.test(xml)) {
|
||||
const saveDir = join(app.getPath('userData'), 'original-images')
|
||||
await fs.mkdir(saveDir, { recursive: true })
|
||||
const hostResult = await macWechatRuntimeManager.downloadOriginalImage({
|
||||
xml,
|
||||
...(message.contentData.md5 ? { md5: message.contentData.md5 } : {}),
|
||||
save_path: saveDir,
|
||||
timeout_ms: 45_000
|
||||
})
|
||||
if (
|
||||
hostResult.success &&
|
||||
hostResult.file_path &&
|
||||
(await pathExists(hostResult.file_path))
|
||||
) {
|
||||
const decryptedDl = await imageService.decryptImageToBase64WithFallbackAsync(
|
||||
hostResult.file_path,
|
||||
false
|
||||
)
|
||||
if (decryptedDl) {
|
||||
decryptedImage = decryptedDl
|
||||
fileFound = true
|
||||
downloadedOriginalImage = true
|
||||
} else {
|
||||
const rawBuf = await fs.readFile(hostResult.file_path)
|
||||
const ext = detectAssetExtension(rawBuf)
|
||||
if (ext) {
|
||||
const mime = ext === 'jpg' ? 'image/jpeg' : `image/${ext}`
|
||||
decryptedImage = {
|
||||
data: `data:${mime};base64,${rawBuf.toString('base64')}`,
|
||||
filePath: hostResult.file_path
|
||||
}
|
||||
fileFound = true
|
||||
downloadedOriginalImage = true
|
||||
}
|
||||
}
|
||||
} else if (hostResult.error) {
|
||||
originalDownloadError = hostResult.error
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
originalDownloadError = error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
const decoded = decryptedImage ? decodeDataUrl(decryptedImage.data) : null
|
||||
if (decoded) {
|
||||
const name = `image_${bufferHashPart(decoded.buffer)}.${decoded.extension}`
|
||||
@@ -1445,17 +1548,27 @@ async function runSingleExport(
|
||||
}
|
||||
message.exportMediaUrl = mediaUrl
|
||||
message.exportMediaType = 'image'
|
||||
message.exportMediaQuality = imageFileQuality(decryptedImage!.filePath)
|
||||
message.exportMediaQuality = downloadedOriginalImage
|
||||
? 'original'
|
||||
: imageFileQuality(decryptedImage!.filePath)
|
||||
if (request.preferOriginal !== false && message.exportMediaQuality === 'thumbnail') {
|
||||
keepMediaError(request, message, '原图不可用,已降级使用缩略图')
|
||||
keepMediaError(
|
||||
request,
|
||||
message,
|
||||
originalDownloadError
|
||||
? `原图下载失败(${originalDownloadError}),已降级使用缩略图`
|
||||
: '原图不可用,已降级使用缩略图'
|
||||
)
|
||||
}
|
||||
} else if (!fileFound) {
|
||||
keepMediaError(
|
||||
request,
|
||||
message,
|
||||
request.fallbackThumbnail === false
|
||||
? '原图文件缺失,未启用缩略图降级'
|
||||
: '原图和缩略图文件均缺失'
|
||||
originalDownloadError
|
||||
? `原图下载失败(${originalDownloadError}),且本地无图片缓存`
|
||||
: request.fallbackThumbnail === false
|
||||
? '原图文件缺失,未启用缩略图降级'
|
||||
: '原图和缩略图文件均缺失'
|
||||
)
|
||||
} else {
|
||||
keepMediaError(request, message, '图片解析失败或当前格式不支持')
|
||||
@@ -1477,9 +1590,144 @@ async function runSingleExport(
|
||||
width: message.contentData.width,
|
||||
height: message.contentData.height
|
||||
})
|
||||
const source = resolved.url ? videoService.pathForUrl(resolved.url) : undefined
|
||||
if (!resolved.success || !source) {
|
||||
keepMediaError(request, message, resolved.error || '视频文件缺失或已移动')
|
||||
let source = resolved.url ? videoService.pathForUrl(resolved.url) : undefined
|
||||
let videoDownloadError = ''
|
||||
if (
|
||||
shouldDownloadOriginalMedia &&
|
||||
(!source || !/_raw\.mp4$/i.test(source)) &&
|
||||
message.sessionId &&
|
||||
message.localId != null &&
|
||||
typeof client?.getRawMessageContent === 'function'
|
||||
) {
|
||||
try {
|
||||
const raw = client.getRawMessageContent(
|
||||
message.sessionId,
|
||||
message.localId,
|
||||
message.createTime || undefined
|
||||
)
|
||||
const xml = raw
|
||||
? raw.trim().includes('<')
|
||||
? raw.trim()
|
||||
: unescapeXmlForExport(raw.trim())
|
||||
: ''
|
||||
if (xml && /<videomsg\b/i.test(xml)) {
|
||||
const rawFileId = extractXmlAttrForExport(xml, 'cdnrawvideourl')
|
||||
const rawAesKey = extractXmlAttrForExport(xml, 'cdnrawvideoaeskey')
|
||||
const xmlRawMd5 =
|
||||
extractXmlAttrForExport(xml, 'rawmd5').toLowerCase() ||
|
||||
message.contentData.rawMd5
|
||||
const videoFileId = extractXmlAttrForExport(xml, 'cdnvideourl')
|
||||
const videoAesKey = extractXmlAttrForExport(xml, 'aeskey')
|
||||
const xmlMd5 =
|
||||
extractXmlAttrForExport(xml, 'md5').toLowerCase() || message.contentData.md5
|
||||
const xmlNewMd5 =
|
||||
extractXmlAttrForExport(xml, 'newmd5').toLowerCase() ||
|
||||
message.contentData.newMd5
|
||||
const baseHash =
|
||||
xmlMd5 ||
|
||||
xmlNewMd5 ||
|
||||
xmlRawMd5 ||
|
||||
`video_${message.localId || Date.now()}`
|
||||
|
||||
const candidates: Array<{
|
||||
fileId: string
|
||||
aesKey: string
|
||||
md5?: string
|
||||
isRaw: boolean
|
||||
targetFileName: string
|
||||
}> = []
|
||||
if (rawFileId && rawAesKey) {
|
||||
candidates.push({
|
||||
fileId: rawFileId,
|
||||
aesKey: rawAesKey,
|
||||
md5: xmlRawMd5 || baseHash,
|
||||
isRaw: true,
|
||||
targetFileName: `${baseHash}_raw.mp4`
|
||||
})
|
||||
}
|
||||
if (!source && videoFileId && videoAesKey) {
|
||||
candidates.push({
|
||||
fileId: videoFileId,
|
||||
aesKey: videoAesKey,
|
||||
md5: xmlMd5 || xmlNewMd5 || baseHash,
|
||||
isRaw: false,
|
||||
targetFileName: `${baseHash}.mp4`
|
||||
})
|
||||
}
|
||||
|
||||
if (candidates.length > 0) {
|
||||
const accountRoot = client.getAccountRoot() || ''
|
||||
const dateObj =
|
||||
message.createTime && message.createTime > 0
|
||||
? new Date(
|
||||
message.createTime > 10_000_000_000
|
||||
? message.createTime
|
||||
: message.createTime * 1000
|
||||
)
|
||||
: new Date()
|
||||
const monthFolder = Number.isNaN(dateObj.getTime())
|
||||
? 'downloaded'
|
||||
: `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}`
|
||||
let saveDir = join(app.getPath('userData'), 'downloaded-videos', monthFolder)
|
||||
if (accountRoot && !isReadOnlyMode()) {
|
||||
const accountVideoMonthDir = join(accountRoot, 'msg', 'video', monthFolder)
|
||||
try {
|
||||
await fs.mkdir(accountVideoMonthDir, { recursive: true })
|
||||
saveDir = accountVideoMonthDir
|
||||
} catch {
|
||||
await fs.mkdir(saveDir, { recursive: true })
|
||||
}
|
||||
} else {
|
||||
await fs.mkdir(saveDir, { recursive: true })
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const hostResult = await macWechatRuntimeManager.downloadVideo({
|
||||
fileid: candidate.fileId,
|
||||
aeskey: candidate.aesKey,
|
||||
md5: candidate.md5,
|
||||
save_dir: saveDir,
|
||||
target_file_name: candidate.targetFileName,
|
||||
timeout_ms: 90_000
|
||||
})
|
||||
if (
|
||||
hostResult.success &&
|
||||
hostResult.file_path &&
|
||||
(await pathExists(hostResult.file_path))
|
||||
) {
|
||||
const allVideoHashes = [
|
||||
xmlRawMd5,
|
||||
xmlNewMd5,
|
||||
xmlMd5,
|
||||
...hashes,
|
||||
hostResult.md5
|
||||
].filter((v): v is string => Boolean(v))
|
||||
videoService.registerDownloadedVideo(
|
||||
allVideoHashes,
|
||||
hostResult.file_path,
|
||||
candidate.isRaw
|
||||
)
|
||||
source = hostResult.file_path
|
||||
videoDownloadError = ''
|
||||
break
|
||||
} else if (hostResult.error) {
|
||||
videoDownloadError = hostResult.error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
videoDownloadError = error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
if (!source) {
|
||||
keepMediaError(
|
||||
request,
|
||||
message,
|
||||
videoDownloadError
|
||||
? `原视频下载失败(${videoDownloadError}),且${resolved.error || '本地未找到该视频文件'}`
|
||||
: resolved.error || '视频文件缺失或已移动'
|
||||
)
|
||||
} else if (extname(source).toLowerCase() !== '.mp4') {
|
||||
keepMediaError(request, message, '视频格式不支持,仅支持本地 MP4 文件')
|
||||
} else {
|
||||
@@ -1491,6 +1739,7 @@ async function runSingleExport(
|
||||
}
|
||||
message.exportMediaUrl = mediaUrl
|
||||
message.exportMediaType = 'video'
|
||||
message.exportMediaQuality = /_raw\.mp4$/i.test(source) ? 'original' : 'medium'
|
||||
}
|
||||
}
|
||||
} else if (message.contentData.type === 'sticker' && stickerService) {
|
||||
@@ -1513,6 +1762,126 @@ async function runSingleExport(
|
||||
} else {
|
||||
keepMediaError(request, message, result.error || '表情资源缺失或下载失败')
|
||||
}
|
||||
} else if (message.contentData.type === 'forwardBundle' && imageService) {
|
||||
const exportForwardItems = async (
|
||||
items: Array<{
|
||||
messageType: number
|
||||
imageMd5?: string
|
||||
thumbMd5?: string
|
||||
imageDatName?: string
|
||||
cdnFileId?: string
|
||||
cdnAesKey?: string
|
||||
exportMediaUrl?: string
|
||||
nested?: unknown[]
|
||||
}>,
|
||||
depth = 0
|
||||
): Promise<void> => {
|
||||
if (!Array.isArray(items) || depth > 8) return
|
||||
for (const item of items) {
|
||||
if (Array.isArray(item.nested) && item.nested.length > 0) {
|
||||
await exportForwardItems(
|
||||
item.nested as typeof items,
|
||||
depth + 1
|
||||
)
|
||||
continue
|
||||
}
|
||||
const isForwardImage =
|
||||
item.messageType === 2 ||
|
||||
Boolean(item.imageMd5 || item.thumbMd5 || item.imageDatName)
|
||||
if (!isForwardImage) continue
|
||||
if (
|
||||
!shouldDownloadOriginalMedia &&
|
||||
item.exportMediaUrl &&
|
||||
(await resourceExists(item.exportMediaUrl))
|
||||
) {
|
||||
continue
|
||||
}
|
||||
let decryptedImage: { data: string; filePath: string } | null = null
|
||||
for (const attempt of getImageExportAttempts(request)) {
|
||||
const file = await imageService.findImageFileAsync(
|
||||
item.imageMd5 || item.thumbMd5,
|
||||
item.imageDatName,
|
||||
{
|
||||
allowThumbnail: attempt.allowThumbnail,
|
||||
preferThumbnail: attempt.preferThumbnail,
|
||||
sessionId: message.sessionId,
|
||||
sessionMd5: conversationId,
|
||||
createTime: message.createTime
|
||||
}
|
||||
)
|
||||
if (!file) continue
|
||||
let decrypted = await imageService.decryptImageToBase64WithFallbackAsync(
|
||||
file,
|
||||
attempt.allowThumbnail
|
||||
)
|
||||
if (!decrypted) {
|
||||
decrypted = imageService.decryptImageToBase64WithFallback(
|
||||
file,
|
||||
attempt.allowThumbnail
|
||||
)
|
||||
}
|
||||
if (!decrypted) continue
|
||||
decryptedImage = decrypted
|
||||
break
|
||||
}
|
||||
if (
|
||||
shouldDownloadOriginalMedia &&
|
||||
(!decryptedImage || imageFileQuality(decryptedImage.filePath) !== 'original') &&
|
||||
item.cdnFileId &&
|
||||
item.cdnAesKey
|
||||
) {
|
||||
try {
|
||||
const saveDir = join(app.getPath('userData'), 'original-images')
|
||||
await fs.mkdir(saveDir, { recursive: true })
|
||||
const hostResult = await macWechatRuntimeManager.downloadOriginalImage({
|
||||
fileid: item.cdnFileId,
|
||||
aeskey: item.cdnAesKey,
|
||||
...(item.imageMd5 || item.thumbMd5
|
||||
? { md5: item.imageMd5 || item.thumbMd5 }
|
||||
: {}),
|
||||
save_path: saveDir,
|
||||
timeout_ms: 45_000
|
||||
})
|
||||
if (
|
||||
hostResult.success &&
|
||||
hostResult.file_path &&
|
||||
(await pathExists(hostResult.file_path))
|
||||
) {
|
||||
const decryptedDl = await imageService.decryptImageToBase64WithFallbackAsync(
|
||||
hostResult.file_path,
|
||||
false
|
||||
)
|
||||
if (decryptedDl) {
|
||||
decryptedImage = decryptedDl
|
||||
} else {
|
||||
const rawBuf = await fs.readFile(hostResult.file_path)
|
||||
const ext = detectAssetExtension(rawBuf)
|
||||
if (ext) {
|
||||
const mime = ext === 'jpg' ? 'image/jpeg' : `image/${ext}`
|
||||
decryptedImage = {
|
||||
data: `data:${mime};base64,${rawBuf.toString('base64')}`,
|
||||
filePath: hostResult.file_path
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore and fall back to local decryptedImage
|
||||
}
|
||||
}
|
||||
const decoded = decryptedImage ? decodeDataUrl(decryptedImage.data) : null
|
||||
if (decoded) {
|
||||
const name = `image_${bufferHashPart(decoded.buffer)}.${decoded.extension}`
|
||||
const mediaUrl = `media/${name}`
|
||||
if (!(await resourceExists(mediaUrl))) {
|
||||
await fs.writeFile(join(outputDir, 'media', name), decoded.buffer)
|
||||
markResourceExists(mediaUrl)
|
||||
}
|
||||
item.exportMediaUrl = mediaUrl
|
||||
}
|
||||
}
|
||||
}
|
||||
await exportForwardItems(message.contentData.items)
|
||||
} else if (message.contentData.type === 'share' && message.contentData.typeVal === '6') {
|
||||
if (!fileService) {
|
||||
keepMediaError(request, message, '数据库未连接,无法定位本地文件附件')
|
||||
|
||||
@@ -29,6 +29,17 @@ export async function checkExtensionSendEntitlement(
|
||||
const platform = dependencies.platform ?? process.platform
|
||||
if (platform === 'darwin') {
|
||||
try {
|
||||
if (!dependencies.getMacLicense) {
|
||||
const probe = dependencies.probeLicense
|
||||
? await dependencies.probeLicense()
|
||||
: await probeLicenseStatus()
|
||||
if (probe.ok) {
|
||||
const mapped = mapLicenseStatus(probe.status)
|
||||
if (mapped.entitlement === 'valid') {
|
||||
return { ok: true, message: '授权有效', source: 'mac_license' }
|
||||
}
|
||||
}
|
||||
}
|
||||
const status = dependencies.getMacLicense
|
||||
? await dependencies.getMacLicense()
|
||||
: await macWechatRuntimeManager.getMacLicenseStatus()
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
shouldDeliverExtensionEvent,
|
||||
type ExtensionMessageEvent
|
||||
} from '../../shared/extensions/events'
|
||||
import type { ExtensionMessageRef } from '../../shared/extensions/media'
|
||||
import type { ExtensionSubscriptions } from '../../shared/extensions/manifest'
|
||||
import type { NormalizedIncomingMessage } from '../services/message-listener-service'
|
||||
|
||||
@@ -22,6 +23,7 @@ export interface ExtensionEventBusDependencies {
|
||||
listSubscribers: () => ExtensionEventSubscriber[]
|
||||
getAccountId: () => string
|
||||
getSelfUsernames: () => string[]
|
||||
encodeMessageRef?: (ref: ExtensionMessageRef) => string
|
||||
now?: () => number
|
||||
onDelivered?: (extensionId: string, event: ExtensionMessageEvent) => void
|
||||
}
|
||||
@@ -71,21 +73,25 @@ export class ExtensionEventBus {
|
||||
return
|
||||
}
|
||||
const selfUsernames = new Set(this.dependencies.getSelfUsernames())
|
||||
const event = buildExtensionMessageEvent({
|
||||
eventId,
|
||||
accountId: this.accountId,
|
||||
conversationId: message.sessionId,
|
||||
messageId: message.serverId || message.localId,
|
||||
...(message.senderId ? { senderId: message.senderId } : {}),
|
||||
...(message.senderNickname ? { senderName: message.senderNickname } : {}),
|
||||
isGroup: message.isGroup,
|
||||
isSelf: message.isSelf,
|
||||
messageType: message.messageType,
|
||||
...(message.content !== undefined ? { content: message.content } : {}),
|
||||
// 只有 source 里真实出现当前账号 username 才算 @我;拿不到自身身份时一律 false。
|
||||
mentionsMe: message.mentionTargets.some((target) => selfUsernames.has(target)),
|
||||
createTimeSeconds: message.createTime
|
||||
})
|
||||
const event = buildExtensionMessageEvent(
|
||||
{
|
||||
eventId,
|
||||
accountId: this.accountId,
|
||||
conversationId: message.sessionId,
|
||||
messageId: message.serverId || message.localId,
|
||||
localId: message.localId,
|
||||
...(message.senderId ? { senderId: message.senderId } : {}),
|
||||
...(message.senderNickname ? { senderName: message.senderNickname } : {}),
|
||||
isGroup: message.isGroup,
|
||||
isSelf: message.isSelf,
|
||||
messageType: message.messageType,
|
||||
...(message.content !== undefined ? { content: message.content } : {}),
|
||||
// 只有 source 里真实出现当前账号 username 才算 @我;拿不到自身身份时一律 false。
|
||||
mentionsMe: message.mentionTargets.some((target) => selfUsernames.has(target)),
|
||||
createTimeSeconds: message.createTime
|
||||
},
|
||||
this.dependencies.encodeMessageRef
|
||||
)
|
||||
const envelope: ExtensionEventEnvelope = {
|
||||
version: EXTENSION_EVENT_PROTOCOL_VERSION,
|
||||
kind: 'message.received',
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { fork, spawn, type ChildProcess } from 'node:child_process'
|
||||
import { fork, type ChildProcess } from 'node:child_process'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { killProcessTree, type ProcessTreeKillResult } from '../process-tree'
|
||||
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
|
||||
import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types'
|
||||
import {
|
||||
sortPermissionsByRisk,
|
||||
type ExtensionPermission
|
||||
@@ -15,15 +17,42 @@ import {
|
||||
type ExtensionHostInboundMessage,
|
||||
type ExtensionHostOutboundMessage,
|
||||
type ExtensionMessagesQueryRequest,
|
||||
type ExtensionMessagesQueryResult,
|
||||
type ExtensionNotificationCreateRequest,
|
||||
type ExtensionNotificationCreateResult,
|
||||
type ExtensionNotificationMarkReadRequest,
|
||||
type ExtensionNotificationMarkReadResult,
|
||||
type ExtensionQueriedMessage,
|
||||
type ExtensionRenderHtmlToImageRequest,
|
||||
type ExtensionRenderHtmlToImageResult,
|
||||
type ExtensionSendImageRequest,
|
||||
type ExtensionSendTextRequest,
|
||||
type ExtensionSendTextResult,
|
||||
type ExtensionSendVideoRequest,
|
||||
type ExtensionSendVoiceRequest
|
||||
} from '../../shared/extensions/rpc'
|
||||
import type {
|
||||
ExtensionMediaAnalyzeImageRequest,
|
||||
ExtensionMediaAnalyzeImageResult,
|
||||
ExtensionMediaBatchRequest,
|
||||
ExtensionMediaBatchResult,
|
||||
ExtensionMediaOcrImageRequest,
|
||||
ExtensionMediaOcrImageResult,
|
||||
ExtensionMediaReadImageRequest,
|
||||
ExtensionMediaReadImageResult,
|
||||
ExtensionMediaReadVideoRequest,
|
||||
ExtensionMediaReadVideoResult,
|
||||
ExtensionMediaReadVoiceRequest,
|
||||
ExtensionMediaReadVoiceResult,
|
||||
ExtensionMediaTranscribeVoiceRequest,
|
||||
ExtensionMediaTranscribeVoiceResult
|
||||
} from '../../shared/extensions/media'
|
||||
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
|
||||
import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types'
|
||||
import type {
|
||||
ExtensionCapabilitySnapshot,
|
||||
ExtensionNotificationItem,
|
||||
ExtensionRuntimeSnapshot
|
||||
} from '../../shared/extensions/types'
|
||||
import {
|
||||
parseActionInputSchema,
|
||||
type ExtensionActionInputSchema
|
||||
@@ -92,6 +121,8 @@ export interface ExtensionHostDependencies {
|
||||
/** 扩展私有数据目录;媒体文件只允许从这里或临时目录发送。 */
|
||||
dataDir: string
|
||||
permissions: ExtensionPermission[]
|
||||
/** 实时权限检查(回查主进程最新状态),未提供时回退到启动快照 permissions。 */
|
||||
hasPermission?: (permission: ExtensionPermission) => boolean
|
||||
storage: ExtensionStorage
|
||||
secrets?: ExtensionSecretStore
|
||||
spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild
|
||||
@@ -101,7 +132,48 @@ export interface ExtensionHostDependencies {
|
||||
queryMessages?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMessagesQueryRequest
|
||||
) => Promise<ExtensionQueriedMessage[]>
|
||||
) => Promise<ExtensionQueriedMessage[] | ExtensionMessagesQueryResult>
|
||||
mediaReadImage?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadImageRequest
|
||||
) => Promise<ExtensionMediaReadImageResult>
|
||||
mediaReadVoice?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVoiceRequest
|
||||
) => Promise<ExtensionMediaReadVoiceResult>
|
||||
mediaReadVideo?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVideoRequest
|
||||
) => Promise<ExtensionMediaReadVideoResult>
|
||||
mediaOcrImage?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaOcrImageRequest
|
||||
) => Promise<ExtensionMediaOcrImageResult>
|
||||
mediaTranscribeVoice?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaTranscribeVoiceRequest
|
||||
) => Promise<ExtensionMediaTranscribeVoiceResult>
|
||||
mediaAnalyzeImage?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaAnalyzeImageRequest
|
||||
) => Promise<ExtensionMediaAnalyzeImageResult>
|
||||
mediaBatch?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaBatchRequest
|
||||
) => Promise<ExtensionMediaBatchResult>
|
||||
renderHtmlToImage?: (
|
||||
extensionId: string,
|
||||
request: ExtensionRenderHtmlToImageRequest
|
||||
) => Promise<ExtensionRenderHtmlToImageResult>
|
||||
createNotification?: (
|
||||
extensionId: string,
|
||||
request: ExtensionNotificationCreateRequest
|
||||
) => Promise<ExtensionNotificationCreateResult> | ExtensionNotificationCreateResult
|
||||
listNotifications?: (extensionId: string) => Promise<ExtensionNotificationItem[]> | ExtensionNotificationItem[]
|
||||
markNotificationsRead?: (
|
||||
extensionId: string,
|
||||
request: ExtensionNotificationMarkReadRequest
|
||||
) => Promise<ExtensionNotificationMarkReadResult> | ExtensionNotificationMarkReadResult
|
||||
sendText?: (
|
||||
extensionId: string,
|
||||
request: ExtensionSendTextRequest
|
||||
@@ -308,6 +380,7 @@ export class ExtensionHost {
|
||||
this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
|
||||
this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
|
||||
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
|
||||
this.failPendingPageRequests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
|
||||
this.actions.clear()
|
||||
if (!child) {
|
||||
this.setState('inactive')
|
||||
@@ -347,9 +420,14 @@ export class ExtensionHost {
|
||||
const result = await killProcessTree(pid, {
|
||||
timeoutMs: this.dependencies.forceExitMs ?? TASKKILL_TIMEOUT_MS
|
||||
})
|
||||
if (result === 'group') return
|
||||
if (result === 'group' || result === 'taskkill') return
|
||||
try {
|
||||
child.kill()
|
||||
} catch {
|
||||
// 进程已退出。
|
||||
}
|
||||
if (process.platform === 'win32') {
|
||||
this.dependencies.onLog?.('warn', '结束扩展进程树失败,可能有子进程仍在运行')
|
||||
this.dependencies.onLog?.('warn', '结束扩展进程树失败,已退化为直接结束扩展进程')
|
||||
return
|
||||
}
|
||||
this.dependencies.onLog?.('warn', '未能结束扩展进程组,已退化为只结束主进程')
|
||||
@@ -584,6 +662,9 @@ export class ExtensionHost {
|
||||
new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`)
|
||||
)
|
||||
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出'))
|
||||
this.failPendingPageRequests(
|
||||
new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`)
|
||||
)
|
||||
if (this.stopping) {
|
||||
this.setState('inactive')
|
||||
return
|
||||
@@ -767,12 +848,108 @@ export class ExtensionHost {
|
||||
case 'messages.query': {
|
||||
this.requirePermission('messages.query')
|
||||
if (!this.dependencies.queryMessages) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return {
|
||||
messages: await this.dependencies.queryMessages(
|
||||
extensionId,
|
||||
params as unknown as ExtensionMessagesQueryRequest
|
||||
)
|
||||
const queried = await this.dependencies.queryMessages(
|
||||
extensionId,
|
||||
params as unknown as ExtensionMessagesQueryRequest
|
||||
)
|
||||
if (Array.isArray(queried)) {
|
||||
return { messages: queried, hasMore: false }
|
||||
}
|
||||
return queried
|
||||
}
|
||||
case 'media.readImage': {
|
||||
this.requirePermission('media.read')
|
||||
if (!this.dependencies.mediaReadImage) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return this.dependencies.mediaReadImage(
|
||||
extensionId,
|
||||
params as unknown as ExtensionMediaReadImageRequest
|
||||
)
|
||||
}
|
||||
case 'media.readVoice': {
|
||||
this.requirePermission('media.read')
|
||||
if (!this.dependencies.mediaReadVoice) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return this.dependencies.mediaReadVoice(
|
||||
extensionId,
|
||||
params as unknown as ExtensionMediaReadVoiceRequest
|
||||
)
|
||||
}
|
||||
case 'media.readVideo': {
|
||||
this.requirePermission('media.read')
|
||||
if (!this.dependencies.mediaReadVideo) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return this.dependencies.mediaReadVideo(
|
||||
extensionId,
|
||||
params as unknown as ExtensionMediaReadVideoRequest
|
||||
)
|
||||
}
|
||||
case 'media.ocrImage': {
|
||||
this.requirePermission('media.ocr')
|
||||
if (!this.dependencies.mediaOcrImage) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return this.dependencies.mediaOcrImage(
|
||||
extensionId,
|
||||
params as unknown as ExtensionMediaOcrImageRequest
|
||||
)
|
||||
}
|
||||
case 'media.transcribeVoice': {
|
||||
this.requirePermission('media.transcribe')
|
||||
if (!this.dependencies.mediaTranscribeVoice) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
}
|
||||
return this.dependencies.mediaTranscribeVoice(
|
||||
extensionId,
|
||||
params as unknown as ExtensionMediaTranscribeVoiceRequest
|
||||
)
|
||||
}
|
||||
case 'media.analyzeImage': {
|
||||
this.requirePermission('ai.vision')
|
||||
if (!this.dependencies.mediaAnalyzeImage) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return this.dependencies.mediaAnalyzeImage(
|
||||
extensionId,
|
||||
params as unknown as ExtensionMediaAnalyzeImageRequest
|
||||
)
|
||||
}
|
||||
case 'media.batch': {
|
||||
if (!this.dependencies.mediaBatch) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
return this.dependencies.mediaBatch(
|
||||
extensionId,
|
||||
params as unknown as ExtensionMediaBatchRequest
|
||||
)
|
||||
}
|
||||
case 'render.htmlToImage': {
|
||||
this.requirePermission('render.html')
|
||||
if (!this.dependencies.renderHtmlToImage) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
}
|
||||
return this.dependencies.renderHtmlToImage(
|
||||
extensionId,
|
||||
params as unknown as ExtensionRenderHtmlToImageRequest
|
||||
)
|
||||
}
|
||||
case 'notifications.create': {
|
||||
this.requirePermission('notifications.create')
|
||||
if (!this.dependencies.createNotification) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
}
|
||||
return this.dependencies.createNotification(
|
||||
extensionId,
|
||||
params as unknown as ExtensionNotificationCreateRequest
|
||||
)
|
||||
}
|
||||
case 'notifications.list': {
|
||||
this.requirePermission('notifications.create')
|
||||
if (!this.dependencies.listNotifications) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
}
|
||||
return { items: await this.dependencies.listNotifications(extensionId) }
|
||||
}
|
||||
case 'notifications.markRead': {
|
||||
this.requirePermission('notifications.create')
|
||||
if (!this.dependencies.markNotificationsRead) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE')
|
||||
}
|
||||
return this.dependencies.markNotificationsRead(
|
||||
extensionId,
|
||||
params as unknown as ExtensionNotificationMarkReadRequest
|
||||
)
|
||||
}
|
||||
case 'wechat.send.text': {
|
||||
this.requirePermission('wechat.send.text')
|
||||
@@ -830,7 +1007,10 @@ export class ExtensionHost {
|
||||
}
|
||||
|
||||
private requirePermission(permission: ExtensionPermission): void {
|
||||
if (!this.dependencies.permissions.includes(permission)) {
|
||||
const allowed = this.dependencies.hasPermission
|
||||
? this.dependencies.hasPermission(permission)
|
||||
: this.dependencies.permissions.includes(permission)
|
||||
if (!allowed) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`)
|
||||
}
|
||||
}
|
||||
@@ -859,6 +1039,14 @@ export class ExtensionHost {
|
||||
}
|
||||
}
|
||||
|
||||
private failPendingPageRequests(error: Error): void {
|
||||
for (const [requestId, pending] of this.pendingPageRequests) {
|
||||
clearTimeout(pending.timer)
|
||||
this.pendingPageRequests.delete(requestId)
|
||||
pending.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
private refillTokens(): void {
|
||||
const now = this.now()
|
||||
const elapsed = Math.max(0, now - this.eventTokensAt)
|
||||
@@ -881,80 +1069,17 @@ export class ExtensionHost {
|
||||
}
|
||||
}
|
||||
|
||||
/** 结束进程树;taskkill 只在 exit 0 时算成功,发起成功不算。 */
|
||||
export type ProcessTreeKillResult = 'group' | 'taskkill' | 'fallback'
|
||||
|
||||
export async function killProcessTree(
|
||||
pid: number | undefined,
|
||||
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals; timeoutMs?: number } = {}
|
||||
): Promise<ProcessTreeKillResult> {
|
||||
if (!pid) return 'fallback'
|
||||
const platform = options.platform ?? process.platform
|
||||
const signal = options.signal ?? 'SIGKILL'
|
||||
|
||||
if (platform === 'win32') {
|
||||
return killWindowsProcessTree(pid, options.timeoutMs ?? TASKKILL_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
try {
|
||||
process.kill(-pid, signal)
|
||||
return 'group'
|
||||
} catch {
|
||||
try {
|
||||
process.kill(pid, signal)
|
||||
} catch {
|
||||
// 进程已经退出。
|
||||
}
|
||||
return 'fallback'
|
||||
}
|
||||
}
|
||||
|
||||
/** Windows:等 taskkill 真实退出,只认 exit code 0。 */
|
||||
function killWindowsProcessTree(
|
||||
pid: number,
|
||||
timeoutMs: number
|
||||
): Promise<'taskkill' | 'fallback'> {
|
||||
return new Promise((resolve) => {
|
||||
let killer: ChildProcess
|
||||
try {
|
||||
killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], {
|
||||
windowsHide: true,
|
||||
stdio: 'ignore'
|
||||
})
|
||||
} catch {
|
||||
// 无法启动 taskkill(极少数受限环境):只能退化为「主进程可能已退出」。
|
||||
resolve('fallback')
|
||||
return
|
||||
}
|
||||
|
||||
let settled = false
|
||||
const finish = (result: 'taskkill' | 'fallback'): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
resolve(result)
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
killer.kill()
|
||||
} catch {
|
||||
// 已经退出。
|
||||
}
|
||||
finish('fallback')
|
||||
}, timeoutMs)
|
||||
|
||||
killer.on('error', () => finish('fallback'))
|
||||
killer.on('exit', (code) => finish(code === 0 ? 'taskkill' : 'fallback'))
|
||||
})
|
||||
}
|
||||
export { killProcessTree, type ProcessTreeKillResult }
|
||||
|
||||
/** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */
|
||||
export function forkExtensionHost(
|
||||
scriptPath: string
|
||||
): (options: ExtensionHostSpawnOptions) => ExtensionHostChild {
|
||||
return (options) => {
|
||||
// 脱离应用安装目录作为 cwd,避免扩展及其孙进程在 Windows 更新时锁住安装目录。
|
||||
const cwd = existsSync(options.extensionDir) ? options.extensionDir : tmpdir()
|
||||
const child: ChildProcess = fork(scriptPath, [], {
|
||||
cwd,
|
||||
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
||||
serialization: 'advanced',
|
||||
// POSIX 上建立独立进程组,停止时才能一次覆盖扩展派生的子进程。
|
||||
|
||||
@@ -7,11 +7,14 @@ import type {
|
||||
ExtensionInstallResult,
|
||||
ExtensionProjectResult,
|
||||
ExtensionLogEntry,
|
||||
ExtensionNotificationItem,
|
||||
ExtensionNotificationSummary,
|
||||
ExtensionOperationResult,
|
||||
ExtensionPageDescriptor,
|
||||
ExtensionPageRequest,
|
||||
ExtensionPageResponse,
|
||||
InstalledExtension
|
||||
InstalledExtension,
|
||||
PinnedExtensionNavItem
|
||||
} from '../../shared/extensions/types'
|
||||
import type { ExtensionManager } from './extension-manager'
|
||||
import type { ExtensionPaths } from './extension-paths'
|
||||
@@ -368,6 +371,80 @@ export function registerExtensionIpc(options: ExtensionIpcOptions): void {
|
||||
return error ? { success: false, error } : { success: true }
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.pinnedNavigation,
|
||||
guard((): PinnedExtensionNavItem[] => manager().listPinnedNavigation())
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.pinNavigation,
|
||||
guard((payload: unknown): ExtensionOperationResult => {
|
||||
const input = (payload ?? {}) as { id?: unknown; pageId?: unknown }
|
||||
const pageId =
|
||||
typeof input.pageId === 'string' && input.pageId.trim() ? input.pageId.trim() : undefined
|
||||
return manager().pinNavigation(requireId(input.id), pageId)
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.unpinNavigation,
|
||||
guard((extensionId: unknown): ExtensionOperationResult =>
|
||||
manager().unpinNavigation(requireId(extensionId))
|
||||
)
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.reorderNavigation,
|
||||
guard((extensionIds: unknown): ExtensionOperationResult => {
|
||||
const ids = Array.isArray(extensionIds)
|
||||
? extensionIds.filter((item): item is string => typeof item === 'string')
|
||||
: []
|
||||
return manager().reorderPinnedNavigation(ids)
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.notificationsList,
|
||||
guard((extensionId?: unknown): ExtensionNotificationItem[] => {
|
||||
const id =
|
||||
typeof extensionId === 'string' && extensionId.trim() ? requireId(extensionId) : undefined
|
||||
return manager().listNotifications(id)
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.notificationsSummary,
|
||||
guard((): ExtensionNotificationSummary => manager().getNotificationSummary())
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.notificationsMarkRead,
|
||||
guard((payload: unknown): { changed: number } => {
|
||||
const input = (payload ?? {}) as { id?: unknown; extensionId?: unknown; all?: unknown }
|
||||
const id = typeof input.id === 'string' && input.id.trim() ? input.id.trim() : undefined
|
||||
const extensionId =
|
||||
typeof input.extensionId === 'string' && input.extensionId.trim()
|
||||
? requireId(input.extensionId)
|
||||
: undefined
|
||||
return {
|
||||
changed: manager().markNotificationsRead({
|
||||
...(id ? { id } : {}),
|
||||
...(extensionId ? { extensionId } : {}),
|
||||
all: input.all === true
|
||||
})
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
EXTENSION_IPC.notificationsClear,
|
||||
guard((extensionId?: unknown): { removed: number } => {
|
||||
const id =
|
||||
typeof extensionId === 'string' && extensionId.trim() ? requireId(extensionId) : undefined
|
||||
return { removed: manager().clearNotifications(id) }
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
function requireId(value: unknown): string {
|
||||
|
||||
@@ -24,6 +24,8 @@ import type {
|
||||
ExtensionCapabilitySnapshot,
|
||||
ExtensionInstallResult,
|
||||
ExtensionLogEntry,
|
||||
ExtensionNotificationItem,
|
||||
ExtensionNotificationSummary,
|
||||
ExtensionOperationResult,
|
||||
ExtensionPageDescriptor,
|
||||
ExtensionPageMethod,
|
||||
@@ -32,18 +34,45 @@ import type {
|
||||
ExtensionProjectResult,
|
||||
ExtensionSystemHealth,
|
||||
ExtensionTtsCapabilitySnapshot,
|
||||
InstalledExtension
|
||||
InstalledExtension,
|
||||
PinnedExtensionNavItem
|
||||
} from '../../shared/extensions/types'
|
||||
import type {
|
||||
ExtensionAutomationActionOutput,
|
||||
ExtensionMessagesQueryRequest,
|
||||
ExtensionMessagesQueryResult,
|
||||
ExtensionNotificationCreateRequest,
|
||||
ExtensionNotificationCreateResult,
|
||||
ExtensionNotificationMarkReadRequest,
|
||||
ExtensionNotificationMarkReadResult,
|
||||
ExtensionQueriedMessage,
|
||||
ExtensionRenderHtmlToImageRequest,
|
||||
ExtensionRenderHtmlToImageResult,
|
||||
ExtensionSendImageRequest,
|
||||
ExtensionSendTextRequest,
|
||||
ExtensionSendTextResult,
|
||||
ExtensionSendVideoRequest,
|
||||
ExtensionSendVoiceRequest
|
||||
} from '../../shared/extensions/rpc'
|
||||
import type {
|
||||
ExtensionMediaAnalyzeImageRequest,
|
||||
ExtensionMediaAnalyzeImageResult,
|
||||
ExtensionMediaBatchRequest,
|
||||
ExtensionMediaBatchResult,
|
||||
ExtensionMediaOcrImageRequest,
|
||||
ExtensionMediaOcrImageResult,
|
||||
ExtensionMediaReadImageRequest,
|
||||
ExtensionMediaReadImageResult,
|
||||
ExtensionMediaReadVideoRequest,
|
||||
ExtensionMediaReadVideoResult,
|
||||
ExtensionMediaReadVoiceRequest,
|
||||
ExtensionMediaReadVoiceResult,
|
||||
ExtensionMediaTranscribeVoiceRequest,
|
||||
ExtensionMediaTranscribeVoiceResult,
|
||||
ExtensionMessageRef
|
||||
} from '../../shared/extensions/media'
|
||||
import type { ExtensionMediaGateway } from './extension-media-gateway'
|
||||
import { buildExtensionPrivateMediaPreviewUrl } from './extension-protocol'
|
||||
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
|
||||
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
|
||||
import type { NormalizedIncomingMessage } from '../services/message-listener-service'
|
||||
@@ -67,6 +96,8 @@ import {
|
||||
type ExtensionTemplateStatus
|
||||
} from './extension-template-catalog'
|
||||
import { ExtensionLogStore } from './extension-log'
|
||||
import { ExtensionNavigationStore } from './extension-navigation-store'
|
||||
import { ExtensionNotificationStore } from './extension-notification-store'
|
||||
import { ExtensionRegistry, type ExtensionRegistryRecord } from './extension-registry'
|
||||
import { ExtensionSendGateway } from './extension-send-gateway'
|
||||
import { ExtensionStorage } from './extension-storage'
|
||||
@@ -80,7 +111,26 @@ export interface ExtensionManagerDependencies {
|
||||
getCapability: () => Promise<PersonalWechatSendCapability>
|
||||
checkEntitlement: () => Promise<ExtensionEntitlementResult>
|
||||
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
queryMessages: (request: ExtensionMessagesQueryRequest) => Promise<ExtensionQueriedMessage[]>
|
||||
queryMessages: (
|
||||
request: ExtensionMessagesQueryRequest
|
||||
) => Promise<ExtensionQueriedMessage[] | ExtensionMessagesQueryResult>
|
||||
/** 可选媒体网关工厂:在主进程独立校验权限与会话范围后按需读取/解析媒体。 */
|
||||
createMediaGateway?: (context: {
|
||||
hasPermission: (extensionId: string, permission: ExtensionPermission) => boolean
|
||||
isConversationAllowed: (extensionId: string, conversationId: string) => boolean
|
||||
getExtensionDataRoot: (extensionId: string) => string
|
||||
}) => ExtensionMediaGateway
|
||||
mediaGateway?: ExtensionMediaGateway
|
||||
/** 可选 messageRef 主进程签名函数;配置后事件总线与历史查询共用签名机制。 */
|
||||
encodeMessageRef?: (ref: ExtensionMessageRef) => string
|
||||
/** 账号切换回调,用于刷新 messageRef 签名世代。 */
|
||||
onAccountChanged?: (accountId: string) => void
|
||||
/** 离线静态 HTML 渲染实现(复用通用 HtmlRenderService)。 */
|
||||
renderHtmlToImage?: (
|
||||
extensionId: string,
|
||||
extensionDataRoot: string,
|
||||
request: ExtensionRenderHtmlToImageRequest
|
||||
) => Promise<ExtensionRenderHtmlToImageResult>
|
||||
/** 群列表(id + 显示名);用于扩展配置页选择发送目标。 */
|
||||
listGroups: () => Promise<Array<{ id: string; name: string }>>
|
||||
aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }>
|
||||
@@ -103,7 +153,15 @@ export interface ExtensionManagerDependencies {
|
||||
now?: () => number
|
||||
onChange?: (
|
||||
extensionId: string,
|
||||
reason: 'installed' | 'enabled' | 'disabled' | 'uninstalled' | 'runtime' | 'actions'
|
||||
reason:
|
||||
| 'installed'
|
||||
| 'enabled'
|
||||
| 'disabled'
|
||||
| 'uninstalled'
|
||||
| 'runtime'
|
||||
| 'actions'
|
||||
| 'navigation'
|
||||
| 'notifications'
|
||||
) => void
|
||||
}
|
||||
|
||||
@@ -129,13 +187,17 @@ export class ExtensionManager {
|
||||
private readonly installer: ExtensionInstaller
|
||||
private readonly storage: ExtensionStorage
|
||||
private readonly logs: ExtensionLogStore
|
||||
private readonly navigationStore: ExtensionNavigationStore
|
||||
private readonly notificationStore: ExtensionNotificationStore
|
||||
private readonly actions = new ExtensionActionRegistry()
|
||||
private readonly sendGateway: ExtensionSendGateway
|
||||
private readonly mediaGateway: ExtensionMediaGateway | null
|
||||
private readonly hosts = new Map<string, ExtensionHost>()
|
||||
private readonly manifests = new Map<string, ExtensionManifest | null>()
|
||||
private readonly eventBus: ExtensionEventBus
|
||||
private readonly now: () => number
|
||||
private initialized = false
|
||||
private disposed = false
|
||||
/** 代码与 Registry 版本不一致的扩展:值为面向用户的原因,存在即禁止启动。 */
|
||||
private readonly inconsistencies = new Map<string, string>()
|
||||
/** 配置从旧备份恢复、尚未被用户确认的扩展。 */
|
||||
@@ -182,6 +244,8 @@ export class ExtensionManager {
|
||||
onHealthChange: (extensionId, health) => this.handleStorageHealthChange(extensionId, health)
|
||||
})
|
||||
this.logs = new ExtensionLogStore(this.paths.logsDir)
|
||||
this.navigationStore = new ExtensionNavigationStore(this.paths.pinnedNavigationFile, this.now)
|
||||
this.notificationStore = new ExtensionNotificationStore(this.paths.notificationsFile, this.now)
|
||||
this.sendGateway = new ExtensionSendGateway({
|
||||
getCapability: dependencies.getCapability,
|
||||
checkEntitlement: dependencies.checkEntitlement,
|
||||
@@ -196,8 +260,19 @@ export class ExtensionManager {
|
||||
listSubscribers: () => this.listEventSubscribers(),
|
||||
getAccountId: dependencies.getAccountId,
|
||||
getSelfUsernames: dependencies.getSelfUsernames,
|
||||
...(dependencies.encodeMessageRef ? { encodeMessageRef: dependencies.encodeMessageRef } : {}),
|
||||
now: this.now
|
||||
})
|
||||
this.mediaGateway =
|
||||
dependencies.mediaGateway ??
|
||||
dependencies.createMediaGateway?.({
|
||||
hasPermission: (extensionId, permission) =>
|
||||
this.hasActivePermission(extensionId, permission),
|
||||
isConversationAllowed: (extensionId, conversationId) =>
|
||||
this.isConversationAllowed(extensionId, conversationId),
|
||||
getExtensionDataRoot: (extensionId) => this.paths.extensionDataDir(extensionId)
|
||||
}) ??
|
||||
null
|
||||
}
|
||||
|
||||
/** 建立目录、加载状态、拉起已启用的扩展。单个扩展失败不影响其他扩展。 */
|
||||
@@ -632,6 +707,8 @@ export class ExtensionManager {
|
||||
}
|
||||
} else {
|
||||
this.registry.remove(extensionId)
|
||||
this.navigationStore.remove(extensionId)
|
||||
this.notificationStore.removeByExtension(extensionId)
|
||||
}
|
||||
} catch (error) {
|
||||
return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
|
||||
@@ -1057,10 +1134,176 @@ export class ExtensionManager {
|
||||
return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
|
||||
}
|
||||
if (!keepData) this.logs.remove(extensionId)
|
||||
this.navigationStore.remove(extensionId)
|
||||
this.notificationStore.removeByExtension(extensionId)
|
||||
this.dependencies.onChange?.(extensionId, 'uninstalled')
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/** 返回用户固定到一级导航的扩展条目(自动过滤已卸载或无页面扩展)。 */
|
||||
listPinnedNavigation(): PinnedExtensionNavItem[] {
|
||||
const records = this.navigationStore.list()
|
||||
const result: PinnedExtensionNavItem[] = []
|
||||
for (const pinned of records) {
|
||||
const record = this.registry.get(pinned.extensionId)
|
||||
if (!record) continue
|
||||
const manifest = this.readManifest(pinned.extensionId)
|
||||
if (!manifest || !manifest.entrypoints.page) continue
|
||||
const nav = manifest.contributions.navigation
|
||||
const defaultPageId = nav?.pageId || manifest.contributions.pages[0]?.id
|
||||
const pageId = pinned.pageId || defaultPageId
|
||||
result.push({
|
||||
extensionId: record.id,
|
||||
extensionName: manifest.name,
|
||||
label: nav?.label || manifest.name,
|
||||
icon: nav?.icon || 'puzzle',
|
||||
...(pageId ? { pageId } : {}),
|
||||
order: pinned.order,
|
||||
enabled: record.enabled
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
pinNavigation(extensionId: string, pageId?: string): ExtensionOperationResult {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
|
||||
const manifest = this.readManifest(extensionId)
|
||||
if (!manifest || !manifest.entrypoints.page) {
|
||||
return failure(new ExtensionError('INVALID_REQUEST', '该扩展没有可固定的页面入口'))
|
||||
}
|
||||
const targetPageId = pageId || manifest.contributions.navigation?.pageId || manifest.contributions.pages[0]?.id
|
||||
if (
|
||||
targetPageId &&
|
||||
manifest.contributions.pages.length > 0 &&
|
||||
!manifest.contributions.pages.some((page) => page.id === targetPageId)
|
||||
) {
|
||||
return failure(new ExtensionError('INVALID_REQUEST', `扩展页面不存在:${targetPageId}`))
|
||||
}
|
||||
try {
|
||||
this.navigationStore.pin(extensionId, targetPageId)
|
||||
this.dependencies.onChange?.(extensionId, 'navigation')
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
|
||||
}
|
||||
}
|
||||
|
||||
unpinNavigation(extensionId: string): ExtensionOperationResult {
|
||||
this.navigationStore.unpin(extensionId)
|
||||
this.dependencies.onChange?.(extensionId, 'navigation')
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
reorderPinnedNavigation(extensionIds: string[]): ExtensionOperationResult {
|
||||
const sanitized = Array.isArray(extensionIds)
|
||||
? extensionIds.map((id) => String(id || '').trim()).filter((id) => isValidExtensionId(id))
|
||||
: []
|
||||
this.navigationStore.reorder(sanitized)
|
||||
this.dependencies.onChange?.(sanitized[0] || '', 'navigation')
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
createNotification(
|
||||
extensionId: string,
|
||||
request: ExtensionNotificationCreateRequest
|
||||
): ExtensionNotificationCreateResult {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
|
||||
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED', '扩展已停用,拒绝写入新通知')
|
||||
if (this.isSuspended(extensionId)) {
|
||||
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,拒绝写入新通知')
|
||||
}
|
||||
if (!hasExtensionPermission(record.grantedPermissions, 'notifications.create')) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 notifications.create 权限')
|
||||
}
|
||||
const manifest = this.readManifest(extensionId)
|
||||
const extensionName = manifest?.name || record.id
|
||||
const targetPageId = request?.pageId
|
||||
? String(request.pageId).trim()
|
||||
: manifest?.contributions.navigation?.pageId || manifest?.contributions.pages[0]?.id
|
||||
if (
|
||||
request?.pageId &&
|
||||
manifest &&
|
||||
manifest.contributions.pages.length > 0 &&
|
||||
!manifest.contributions.pages.some((page) => page.id === targetPageId)
|
||||
) {
|
||||
throw new ExtensionError('INVALID_REQUEST', `通知跳转页面不存在:${targetPageId}`)
|
||||
}
|
||||
const created = this.notificationStore.create(extensionId, extensionName, {
|
||||
...request,
|
||||
...(targetPageId ? { pageId: targetPageId } : {})
|
||||
})
|
||||
this.dependencies.onChange?.(extensionId, 'notifications')
|
||||
return created
|
||||
}
|
||||
|
||||
listNotifications(extensionId?: string): ExtensionNotificationItem[] {
|
||||
return this.notificationStore.list(extensionId)
|
||||
}
|
||||
|
||||
/** 扩展后台查询自身通知(强绑定调用方 extensionId,绝不跨扩展读取)。 */
|
||||
private listOwnNotifications(extensionId: string): ExtensionNotificationItem[] {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
|
||||
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
|
||||
if (this.isSuspended(extensionId)) {
|
||||
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停')
|
||||
}
|
||||
if (!hasExtensionPermission(record.grantedPermissions, 'notifications.create')) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 notifications.create 权限')
|
||||
}
|
||||
return this.notificationStore.list(extensionId)
|
||||
}
|
||||
|
||||
/** 扩展后台标记自身通知已读(强绑定调用方 extensionId,禁止修改其他扩展通知)。 */
|
||||
private markOwnNotificationsRead(
|
||||
extensionId: string,
|
||||
request: ExtensionNotificationMarkReadRequest
|
||||
): ExtensionNotificationMarkReadResult {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
|
||||
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
|
||||
if (this.isSuspended(extensionId)) {
|
||||
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停')
|
||||
}
|
||||
if (!hasExtensionPermission(record.grantedPermissions, 'notifications.create')) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 notifications.create 权限')
|
||||
}
|
||||
const id = typeof request?.id === 'string' && request.id.trim() ? request.id.trim() : undefined
|
||||
const all = request?.all === true || !id
|
||||
const changed = this.notificationStore.markRead({
|
||||
extensionId,
|
||||
...(id ? { id } : {}),
|
||||
...(all ? { all: true } : {})
|
||||
})
|
||||
if (changed > 0) {
|
||||
this.dependencies.onChange?.(extensionId, 'notifications')
|
||||
}
|
||||
return { changed }
|
||||
}
|
||||
|
||||
getNotificationSummary(): ExtensionNotificationSummary {
|
||||
const pinnedIds = new Set(this.listPinnedNavigation().map((item) => item.extensionId))
|
||||
return this.notificationStore.summary(pinnedIds)
|
||||
}
|
||||
|
||||
markNotificationsRead(options: { id?: string; extensionId?: string; all?: boolean }): number {
|
||||
const changed = this.notificationStore.markRead(options)
|
||||
if (changed > 0) {
|
||||
this.dependencies.onChange?.(options.extensionId || '', 'notifications')
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
clearNotifications(extensionId?: string): number {
|
||||
const removed = this.notificationStore.clear(extensionId)
|
||||
if (removed > 0) {
|
||||
this.dependencies.onChange?.(extensionId || '', 'notifications')
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
/** 页面地址。停用的扩展也允许打开自己的配置页(否则用户无法先配置再启用)。 */
|
||||
pageUrl(extensionId: string, pageId?: string): ExtensionPageDescriptor {
|
||||
const record = this.registry.get(extensionId)
|
||||
@@ -1175,12 +1418,15 @@ export class ExtensionManager {
|
||||
}
|
||||
|
||||
handleMessage(message: NormalizedIncomingMessage): void {
|
||||
this.eventBus.setAccountId(this.dependencies.getAccountId())
|
||||
const accountId = this.dependencies.getAccountId()
|
||||
this.eventBus.setAccountId(accountId)
|
||||
this.dependencies.onAccountChanged?.(accountId)
|
||||
this.eventBus.handleMessage(message)
|
||||
}
|
||||
|
||||
setAccountId(accountId: string): void {
|
||||
this.eventBus.setAccountId(accountId)
|
||||
this.dependencies.onAccountChanged?.(accountId)
|
||||
}
|
||||
|
||||
/** 自动化动作执行入口。由 `AutomationActionRunner` 调用。 */
|
||||
@@ -1251,6 +1497,7 @@ export class ExtensionManager {
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
this.disposed = true
|
||||
const ids = Array.from(this.hosts.keys())
|
||||
await Promise.all(ids.map((id) => this.stopHost(id)))
|
||||
}
|
||||
@@ -1361,6 +1608,7 @@ export class ExtensionManager {
|
||||
}
|
||||
|
||||
private async startHost(extensionId: string, manifest: ExtensionManifest): Promise<void> {
|
||||
if (this.disposed) return
|
||||
if (!manifest.entrypoints.background) return
|
||||
// 双保险:任何路径(含自动恢复、自动化触发)都不能绕过这两道闸。
|
||||
const drift = this.inconsistencies.get(extensionId)
|
||||
@@ -1377,6 +1625,7 @@ export class ExtensionManager {
|
||||
extensionDir: resolvedRoot.root,
|
||||
dataDir: this.paths.extensionDataDir(extensionId),
|
||||
permissions: this.registry.get(extensionId)?.grantedPermissions ?? [],
|
||||
hasPermission: (permission) => this.hasActivePermission(extensionId, permission),
|
||||
storage: this.storage,
|
||||
secrets: this.secrets,
|
||||
spawn: this.dependencies.spawn ?? this.defaultSpawn(),
|
||||
@@ -1390,6 +1639,17 @@ export class ExtensionManager {
|
||||
this.dependencies.onChange?.(extensionId, 'actions')
|
||||
},
|
||||
queryMessages: (id, request) => this.queryMessages(id, request),
|
||||
mediaReadImage: (id, request) => this.mediaReadImage(id, request),
|
||||
mediaReadVoice: (id, request) => this.mediaReadVoice(id, request),
|
||||
mediaReadVideo: (id, request) => this.mediaReadVideo(id, request),
|
||||
mediaOcrImage: (id, request) => this.mediaOcrImage(id, request),
|
||||
mediaTranscribeVoice: (id, request) => this.mediaTranscribeVoice(id, request),
|
||||
mediaAnalyzeImage: (id, request) => this.mediaAnalyzeImage(id, request),
|
||||
mediaBatch: (id, request) => this.mediaBatch(id, request),
|
||||
renderHtmlToImage: (id, request) => this.renderHtmlToImage(id, request),
|
||||
createNotification: (id, request) => this.createNotification(id, request),
|
||||
listNotifications: (id) => this.listOwnNotifications(id),
|
||||
markNotificationsRead: (id, request) => this.markOwnNotificationsRead(id, request),
|
||||
sendText: (id, request) => this.sendText(id, request),
|
||||
sendImage: (id, request) => this.sendImage(id, request),
|
||||
sendVideo: (id, request) => this.sendVideo(id, request),
|
||||
@@ -1456,10 +1716,112 @@ export class ExtensionManager {
|
||||
return subscribers
|
||||
}
|
||||
|
||||
private hasActivePermission(extensionId: string, permission: ExtensionPermission): boolean {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record?.enabled || this.isSuspended(extensionId)) return false
|
||||
return hasExtensionPermission(record.grantedPermissions, permission)
|
||||
}
|
||||
|
||||
/** 若 manifest.subscriptions.conversationIds 非空,则限制扩展只能访问声明范围内的会话。 */
|
||||
private isConversationAllowed(extensionId: string, conversationId: string): boolean {
|
||||
const manifest = this.readManifest(extensionId)
|
||||
const scope = manifest?.subscriptions?.conversationIds ?? []
|
||||
if (scope.length === 0) return true
|
||||
return scope.includes(conversationId)
|
||||
}
|
||||
|
||||
private requireMediaGateway(extensionId: string): ExtensionMediaGateway {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
|
||||
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
|
||||
if (this.isSuspended(extensionId)) {
|
||||
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,媒体调用被拒绝')
|
||||
}
|
||||
if (!this.mediaGateway) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前环境未启用扩展媒体能力')
|
||||
}
|
||||
return this.mediaGateway
|
||||
}
|
||||
|
||||
private async mediaReadImage(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadImageRequest
|
||||
): Promise<ExtensionMediaReadImageResult> {
|
||||
return this.requireMediaGateway(extensionId).readImage(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaReadVoice(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVoiceRequest
|
||||
): Promise<ExtensionMediaReadVoiceResult> {
|
||||
return this.requireMediaGateway(extensionId).readVoice(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaReadVideo(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVideoRequest
|
||||
): Promise<ExtensionMediaReadVideoResult> {
|
||||
return this.requireMediaGateway(extensionId).readVideo(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaOcrImage(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaOcrImageRequest
|
||||
): Promise<ExtensionMediaOcrImageResult> {
|
||||
return this.requireMediaGateway(extensionId).ocrImage(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaTranscribeVoice(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaTranscribeVoiceRequest
|
||||
): Promise<ExtensionMediaTranscribeVoiceResult> {
|
||||
return this.requireMediaGateway(extensionId).transcribeVoice(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaAnalyzeImage(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaAnalyzeImageRequest
|
||||
): Promise<ExtensionMediaAnalyzeImageResult> {
|
||||
return this.requireMediaGateway(extensionId).analyzeImage(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaBatch(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaBatchRequest
|
||||
): Promise<ExtensionMediaBatchResult> {
|
||||
return this.requireMediaGateway(extensionId).batch(extensionId, request)
|
||||
}
|
||||
|
||||
private async renderHtmlToImage(
|
||||
extensionId: string,
|
||||
request: ExtensionRenderHtmlToImageRequest
|
||||
): Promise<ExtensionRenderHtmlToImageResult> {
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
|
||||
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
|
||||
if (this.isSuspended(extensionId)) {
|
||||
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,渲染调用被拒绝')
|
||||
}
|
||||
if (!hasExtensionPermission(record.grantedPermissions, 'render.html')) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 render.html 权限')
|
||||
}
|
||||
if (!this.dependencies.renderHtmlToImage) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前环境未启用 HTML 渲染能力')
|
||||
}
|
||||
const dataRoot = this.paths.extensionDataDir(extensionId)
|
||||
const rendered = await this.dependencies.renderHtmlToImage(extensionId, dataRoot, request)
|
||||
const previewUrl =
|
||||
rendered.previewUrl ?? buildExtensionPrivateMediaPreviewUrl(extensionId, dataRoot, rendered.path)
|
||||
return {
|
||||
...rendered,
|
||||
...(previewUrl ? { previewUrl } : {})
|
||||
}
|
||||
}
|
||||
|
||||
private async queryMessages(
|
||||
extensionId: string,
|
||||
request: ExtensionMessagesQueryRequest
|
||||
): Promise<ExtensionQueriedMessage[]> {
|
||||
): Promise<ExtensionQueriedMessage[] | ExtensionMessagesQueryResult> {
|
||||
if (!this.dependencies.isDatabaseReady()) {
|
||||
throw new ExtensionError('DATABASE_NOT_READY')
|
||||
}
|
||||
@@ -1478,11 +1840,30 @@ export class ExtensionManager {
|
||||
}
|
||||
const record = this.registry.get(extensionId)
|
||||
if (!record?.enabled) throw new ExtensionError('EXTENSION_DISABLED')
|
||||
if (this.isSuspended(extensionId)) {
|
||||
throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,查询被拒绝')
|
||||
}
|
||||
if (!hasExtensionPermission(record.grantedPermissions, 'messages.query')) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 messages.query 权限')
|
||||
}
|
||||
if (!this.isConversationAllowed(extensionId, conversationId)) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的访问范围')
|
||||
}
|
||||
const order = request?.order === 'asc' || request?.order === 'desc' ? request.order : undefined
|
||||
const cursor = typeof request?.cursor === 'string' && request.cursor.trim()
|
||||
? request.cursor.trim()
|
||||
: undefined
|
||||
const types = Array.isArray(request?.types)
|
||||
? request.types.map((item) => String(item || '').trim()).filter(Boolean).slice(0, 16)
|
||||
: undefined
|
||||
return this.dependencies.queryMessages({
|
||||
conversationId,
|
||||
startTime,
|
||||
endTime,
|
||||
limit
|
||||
limit,
|
||||
...(cursor ? { cursor } : {}),
|
||||
...(order ? { order } : {}),
|
||||
...(types?.length ? { types } : {})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1675,6 +2056,10 @@ export class ExtensionManager {
|
||||
id: page.id,
|
||||
title: page.title
|
||||
})),
|
||||
...(manifest?.contributions.navigation
|
||||
? { navigation: manifest.contributions.navigation }
|
||||
: {}),
|
||||
pinnedToNav: this.navigationStore.isPinned(record.id),
|
||||
automationActions: this.actions.summariesFor(record.id),
|
||||
filesPresent: Boolean(manifest),
|
||||
storage: {
|
||||
|
||||
@@ -0,0 +1,935 @@
|
||||
import fs from 'fs-extra'
|
||||
import path from 'node:path'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
|
||||
import type { ExtensionPermission } from '../../shared/extensions/permissions'
|
||||
import {
|
||||
decodeExtensionMessageRef,
|
||||
decodeMessagesQueryCursor,
|
||||
encodeMessagesQueryCursor,
|
||||
type ExtensionMediaAnalyzeImageRequest,
|
||||
type ExtensionMediaAnalyzeImageResult,
|
||||
type ExtensionMediaBatchItem,
|
||||
type ExtensionMediaBatchItemResult,
|
||||
type ExtensionMediaBatchOperation,
|
||||
type ExtensionMediaBatchRequest,
|
||||
type ExtensionMediaBatchResult,
|
||||
type ExtensionMediaOcrImageRequest,
|
||||
type ExtensionMediaOcrImageResult,
|
||||
type ExtensionMediaReadImageRequest,
|
||||
type ExtensionMediaReadImageResult,
|
||||
type ExtensionMediaReadVideoRequest,
|
||||
type ExtensionMediaReadVideoResult,
|
||||
type ExtensionMediaReadVoiceRequest,
|
||||
type ExtensionMediaReadVoiceResult,
|
||||
type ExtensionMediaTranscribeVoiceRequest,
|
||||
type ExtensionMediaTranscribeVoiceResult,
|
||||
type ExtensionMessageRef
|
||||
} from '../../shared/extensions/media'
|
||||
import type {
|
||||
ExtensionMessagesQueryRequest,
|
||||
ExtensionMessagesQueryResult,
|
||||
ExtensionQueriedMessage
|
||||
} from '../../shared/extensions/rpc'
|
||||
import type { VoiceMessageReference } from '../../shared/voice-recognition'
|
||||
import type { VoiceTranscriptionOutcome } from '../voice-pipeline/voice-transcription-gateway'
|
||||
import { isPathInside } from './extension-paths'
|
||||
import { buildExtensionPrivateMediaPreviewUrl } from './extension-protocol'
|
||||
|
||||
const DEFAULT_GLOBAL_CONCURRENCY = 4
|
||||
const DEFAULT_PER_EXTENSION_CONCURRENCY = 2
|
||||
const DEFAULT_MAX_BATCH_ITEMS = 20
|
||||
const DEFAULT_MAX_VIDEO_BYTES = 100 * 1024 * 1024
|
||||
const DEFAULT_CACHE_ENTRIES = 128
|
||||
const DEFAULT_CACHE_TTL_MS = 10 * 60 * 1000
|
||||
const DEFAULT_TRANSCRIBE_WAIT_MS = 12_000
|
||||
const MAX_TRANSCRIBE_WAIT_MS = 25_000
|
||||
|
||||
const DEFAULT_TIMEOUTS_MS: Record<ExtensionMediaBatchOperation, number> = {
|
||||
readImage: 15_000,
|
||||
readVoice: 20_000,
|
||||
readVideo: 30_000,
|
||||
ocrImage: 25_000,
|
||||
transcribeVoice: 30_000,
|
||||
analyzeImage: 60_000
|
||||
}
|
||||
|
||||
const OP_REQUIRED_PERMISSION: Record<ExtensionMediaBatchOperation, ExtensionPermission> = {
|
||||
readImage: 'media.read',
|
||||
readVoice: 'media.read',
|
||||
readVideo: 'media.read',
|
||||
ocrImage: 'media.ocr',
|
||||
transcribeVoice: 'media.transcribe',
|
||||
analyzeImage: 'ai.vision'
|
||||
}
|
||||
|
||||
export interface ResolvedExtensionMediaMessage {
|
||||
messageId: string
|
||||
localId?: number
|
||||
serverId?: string
|
||||
conversationId: string
|
||||
senderName?: string
|
||||
type: 'image' | 'voice' | 'video' | 'other'
|
||||
/** epoch 秒。 */
|
||||
createTimeSeconds: number
|
||||
image?: { md5?: string; datName?: string }
|
||||
voice?: { durationSeconds?: number }
|
||||
video?: {
|
||||
hashes: string[]
|
||||
byteLength?: number
|
||||
duration?: number
|
||||
width?: number
|
||||
height?: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtensionMediaGatewayDependencies {
|
||||
isDatabaseReady: () => boolean
|
||||
getAccountId: () => string
|
||||
getExtensionDataRoot: (extensionId: string) => string
|
||||
hasPermission: (extensionId: string, permission: ExtensionPermission) => boolean
|
||||
/** 校验扩展是否允许访问目标会话(manifest.subscriptions.conversationIds 约束)。 */
|
||||
isConversationAllowed?: (extensionId: string, conversationId: string) => boolean
|
||||
/** messageRef 验签;不配置就退化为只解码不校验,伪造与切号前旧引用都会放行。 */
|
||||
verifySignedRef?: (rawRef: unknown, expectedAccountId: string) => ExtensionMessageRef | null
|
||||
resolveMessage: (ref: ExtensionMessageRef) => Promise<ResolvedExtensionMediaMessage | null>
|
||||
readImageData: (
|
||||
message: ResolvedExtensionMediaMessage,
|
||||
quality: 'original' | 'thumbnail'
|
||||
) => Promise<{
|
||||
buffer: Buffer
|
||||
mimeType: string
|
||||
imageHash?: string
|
||||
quality: 'original' | 'thumbnail'
|
||||
} | null>
|
||||
readVoiceData: (
|
||||
message: ResolvedExtensionMediaMessage
|
||||
) => Promise<{ wavBuffer: Buffer; durationMs?: number } | null>
|
||||
readVideoAsset: (message: ResolvedExtensionMediaMessage) => Promise<{
|
||||
filePath: string
|
||||
posterPath?: string
|
||||
durationMs?: number
|
||||
width?: number
|
||||
height?: number
|
||||
} | null>
|
||||
getCachedOcr?: (
|
||||
conversationId: string,
|
||||
messageId: string
|
||||
) => { text: string; language?: string | null; engine?: string } | null
|
||||
recognizeOcr: (
|
||||
imageDataUrl: string,
|
||||
language?: string
|
||||
) => Promise<{
|
||||
success: boolean
|
||||
text: string
|
||||
language: string | null
|
||||
engine: string
|
||||
error?: string
|
||||
}>
|
||||
transcribeVoice: (
|
||||
reference: VoiceMessageReference,
|
||||
options: { force?: boolean; waitMs: number }
|
||||
) => Promise<VoiceTranscriptionOutcome | null>
|
||||
analyzeImage: (input: {
|
||||
messageId: string
|
||||
conversationId: string
|
||||
senderName: string
|
||||
sentAt: number
|
||||
imageHash: string
|
||||
imageDataUrl: string
|
||||
prompt?: string
|
||||
force?: boolean
|
||||
}) => Promise<{
|
||||
description: string
|
||||
ocrText?: string
|
||||
tags?: string[]
|
||||
category?: string
|
||||
model?: string
|
||||
cached?: boolean
|
||||
}>
|
||||
maxGlobalConcurrent?: number
|
||||
maxPerExtensionConcurrent?: number
|
||||
maxBatchItems?: number
|
||||
maxVideoBytes?: number
|
||||
cacheTtlMs?: number
|
||||
timeoutsMs?: Partial<Record<ExtensionMediaBatchOperation, number>>
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
interface CacheEntry<T> {
|
||||
value: T
|
||||
at: number
|
||||
}
|
||||
|
||||
function sha256Hex(buffer: Buffer): string {
|
||||
return createHash('sha256').update(buffer).digest('hex')
|
||||
}
|
||||
|
||||
function extensionForImageMime(mimeType: string): string {
|
||||
const normalized = mimeType.toLowerCase()
|
||||
if (normalized.includes('png')) return '.png'
|
||||
if (normalized.includes('webp')) return '.webp'
|
||||
if (normalized.includes('gif')) return '.gif'
|
||||
if (normalized.includes('bmp')) return '.bmp'
|
||||
return '.jpg'
|
||||
}
|
||||
|
||||
/** 避免底层异常把本机目录或密钥原样回传给扩展。 */
|
||||
function sanitizeMediaErrorMessage(message: string): string {
|
||||
return String(message || '媒体处理失败')
|
||||
.replace(/[A-Za-z]:\\[^\s'"]+/g, '<path>')
|
||||
.replace(/\/(?:Users|home|var|tmp|private|Library|Volumes)\/[^\s'"]+/g, '<path>')
|
||||
.replace(/\b(aesKey|xorKey|apiKey|token|secret)\s*[:=]\s*\S+/gi, '$1=***')
|
||||
.slice(0, 200)
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
reject(new ExtensionError('ACTION_TIMEOUT', '媒体处理超时'))
|
||||
}, timeoutMs)
|
||||
promise.then(
|
||||
(value) => {
|
||||
clearTimeout(timer)
|
||||
resolve(value)
|
||||
},
|
||||
(error) => {
|
||||
clearTimeout(timer)
|
||||
reject(error)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 扩展媒体与按需解析入口:账号隔离、权限、缓存边界与并发上限一律在主进程校验,
|
||||
* 底层复用主程序已有的图片解密、语音转写、系统 OCR 与视觉模型。
|
||||
*/
|
||||
export class ExtensionMediaGateway {
|
||||
private readonly maxGlobal: number
|
||||
private readonly maxPerExtension: number
|
||||
private readonly maxBatchItems: number
|
||||
private readonly maxVideoBytes: number
|
||||
private readonly cacheTtlMs: number
|
||||
private readonly timeouts: Record<ExtensionMediaBatchOperation, number>
|
||||
private readonly now: () => number
|
||||
|
||||
private activeGlobal = 0
|
||||
private readonly activeByExtension = new Map<string, number>()
|
||||
private readonly inFlight = new Map<string, Promise<unknown>>()
|
||||
private readonly ocrCache = new Map<string, CacheEntry<Omit<ExtensionMediaOcrImageResult, 'messageRef' | 'cached'>>>()
|
||||
private readonly visionCache = new Map<
|
||||
string,
|
||||
CacheEntry<Omit<ExtensionMediaAnalyzeImageResult, 'messageRef' | 'cached'>>
|
||||
>()
|
||||
private lastAccountId = ''
|
||||
|
||||
constructor(private readonly deps: ExtensionMediaGatewayDependencies) {
|
||||
this.maxGlobal = Math.max(1, deps.maxGlobalConcurrent ?? DEFAULT_GLOBAL_CONCURRENCY)
|
||||
this.maxPerExtension = Math.max(
|
||||
1,
|
||||
deps.maxPerExtensionConcurrent ?? DEFAULT_PER_EXTENSION_CONCURRENCY
|
||||
)
|
||||
this.maxBatchItems = Math.max(1, deps.maxBatchItems ?? DEFAULT_MAX_BATCH_ITEMS)
|
||||
this.maxVideoBytes = Math.max(1024, deps.maxVideoBytes ?? DEFAULT_MAX_VIDEO_BYTES)
|
||||
this.cacheTtlMs = Math.max(1_000, deps.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS)
|
||||
this.timeouts = { ...DEFAULT_TIMEOUTS_MS, ...(deps.timeoutsMs ?? {}) }
|
||||
this.now = deps.now ?? (() => Date.now())
|
||||
}
|
||||
|
||||
async readImage(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadImageRequest
|
||||
): Promise<ExtensionMediaReadImageResult> {
|
||||
this.assertPermission(extensionId, 'media.read')
|
||||
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
|
||||
const quality: 'original' | 'thumbnail' =
|
||||
request?.quality === 'thumbnail' ? 'thumbnail' : 'original'
|
||||
|
||||
const dedupeKey = `${accountId}:${extensionId}:readImage:${ref.conversationId}:${ref.messageId}:${quality}`
|
||||
return this.runGuarded(extensionId, 'readImage', dedupeKey, async () => {
|
||||
const message = await this.requireTypedMessage(ref, 'image')
|
||||
const data = await this.deps.readImageData(message, quality)
|
||||
if (!data || data.buffer.length === 0) {
|
||||
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该图片消息的本地文件')
|
||||
}
|
||||
const sha256 = sha256Hex(data.buffer)
|
||||
const shortHash = sha256.slice(0, 32)
|
||||
const ext = extensionForImageMime(data.mimeType)
|
||||
const written = await this.writeCachedMediaFile(
|
||||
extensionId,
|
||||
accountId,
|
||||
'images',
|
||||
`${shortHash}_${data.quality}${ext}`,
|
||||
data.buffer
|
||||
)
|
||||
const previewUrl = buildExtensionPrivateMediaPreviewUrl(
|
||||
extensionId,
|
||||
this.deps.getExtensionDataRoot(extensionId),
|
||||
written.filePath
|
||||
)
|
||||
return {
|
||||
messageRef: request.messageRef,
|
||||
mimeType: data.mimeType,
|
||||
bytes: data.buffer.length,
|
||||
sha256,
|
||||
path: written.filePath,
|
||||
...(previewUrl ? { previewUrl } : {}),
|
||||
quality: data.quality,
|
||||
cached: written.cached
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async readVoice(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVoiceRequest
|
||||
): Promise<ExtensionMediaReadVoiceResult> {
|
||||
this.assertPermission(extensionId, 'media.read')
|
||||
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
|
||||
const dedupeKey = `${accountId}:${extensionId}:readVoice:${ref.conversationId}:${ref.messageId}`
|
||||
return this.runGuarded(extensionId, 'readVoice', dedupeKey, async () => {
|
||||
const message = await this.requireTypedMessage(ref, 'voice')
|
||||
const voice = await this.deps.readVoiceData(message)
|
||||
if (!voice || voice.wavBuffer.length === 0) {
|
||||
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该语音消息的音频数据')
|
||||
}
|
||||
const sha256 = sha256Hex(voice.wavBuffer)
|
||||
const shortHash = sha256.slice(0, 32)
|
||||
const written = await this.writeCachedMediaFile(
|
||||
extensionId,
|
||||
accountId,
|
||||
'voices',
|
||||
`${shortHash}.wav`,
|
||||
voice.wavBuffer
|
||||
)
|
||||
const previewUrl = buildExtensionPrivateMediaPreviewUrl(
|
||||
extensionId,
|
||||
this.deps.getExtensionDataRoot(extensionId),
|
||||
written.filePath
|
||||
)
|
||||
const durationMs =
|
||||
voice.durationMs ??
|
||||
(message.voice?.durationSeconds ? Math.round(message.voice.durationSeconds * 1000) : undefined)
|
||||
return {
|
||||
messageRef: request.messageRef,
|
||||
mimeType: 'audio/wav',
|
||||
bytes: voice.wavBuffer.length,
|
||||
sha256,
|
||||
...(durationMs !== undefined ? { durationMs } : {}),
|
||||
path: written.filePath,
|
||||
...(previewUrl ? { previewUrl } : {}),
|
||||
cached: written.cached
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async readVideo(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVideoRequest
|
||||
): Promise<ExtensionMediaReadVideoResult> {
|
||||
this.assertPermission(extensionId, 'media.read')
|
||||
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
|
||||
const dedupeKey = `${accountId}:${extensionId}:readVideo:${ref.conversationId}:${ref.messageId}`
|
||||
return this.runGuarded(extensionId, 'readVideo', dedupeKey, async () => {
|
||||
const message = await this.requireTypedMessage(ref, 'video')
|
||||
const asset = await this.deps.readVideoAsset(message)
|
||||
if (!asset?.filePath || !(await fs.pathExists(asset.filePath))) {
|
||||
throw new ExtensionError('MEDIA_NOT_FOUND', '本地未找到该视频文件')
|
||||
}
|
||||
const stat = await fs.stat(asset.filePath)
|
||||
if (!stat.isFile() || stat.size <= 0) {
|
||||
throw new ExtensionError('MEDIA_NOT_FOUND', '本地视频文件无效')
|
||||
}
|
||||
if (stat.size > this.maxVideoBytes) {
|
||||
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '视频体积超出单文件上限')
|
||||
}
|
||||
const videoBuffer = await fs.readFile(asset.filePath)
|
||||
const sha256 = sha256Hex(videoBuffer)
|
||||
const shortHash = sha256.slice(0, 32)
|
||||
const written = await this.writeCachedMediaFile(
|
||||
extensionId,
|
||||
accountId,
|
||||
'videos',
|
||||
`${shortHash}.mp4`,
|
||||
videoBuffer
|
||||
)
|
||||
const dataRoot = this.deps.getExtensionDataRoot(extensionId)
|
||||
const previewUrl = buildExtensionPrivateMediaPreviewUrl(extensionId, dataRoot, written.filePath)
|
||||
let posterPath: string | undefined
|
||||
let posterPreviewUrl: string | undefined
|
||||
if (asset.posterPath && (await fs.pathExists(asset.posterPath))) {
|
||||
try {
|
||||
const posterBuffer = await fs.readFile(asset.posterPath)
|
||||
if (posterBuffer.length > 0 && posterBuffer.length <= 10 * 1024 * 1024) {
|
||||
const posterWritten = await this.writeCachedMediaFile(
|
||||
extensionId,
|
||||
accountId,
|
||||
'videos',
|
||||
`${shortHash}_poster.jpg`,
|
||||
posterBuffer
|
||||
)
|
||||
posterPath = posterWritten.filePath
|
||||
posterPreviewUrl = buildExtensionPrivateMediaPreviewUrl(
|
||||
extensionId,
|
||||
dataRoot,
|
||||
posterWritten.filePath
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
posterPath = undefined
|
||||
posterPreviewUrl = undefined
|
||||
}
|
||||
}
|
||||
const durationMs =
|
||||
asset.durationMs ??
|
||||
(message.video?.duration ? Math.round(message.video.duration * 1000) : undefined)
|
||||
return {
|
||||
messageRef: request.messageRef,
|
||||
mimeType: 'video/mp4',
|
||||
bytes: videoBuffer.length,
|
||||
sha256,
|
||||
path: written.filePath,
|
||||
...(previewUrl ? { previewUrl } : {}),
|
||||
...(posterPath ? { posterPath } : {}),
|
||||
...(posterPreviewUrl ? { posterPreviewUrl } : {}),
|
||||
...(durationMs !== undefined ? { durationMs } : {}),
|
||||
...(asset.width ?? message.video?.width ? { width: asset.width ?? message.video?.width } : {}),
|
||||
...(asset.height ?? message.video?.height
|
||||
? { height: asset.height ?? message.video?.height }
|
||||
: {}),
|
||||
cached: written.cached
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async ocrImage(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaOcrImageRequest
|
||||
): Promise<ExtensionMediaOcrImageResult> {
|
||||
this.assertPermission(extensionId, 'media.ocr')
|
||||
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
|
||||
const language = typeof request?.language === 'string' ? request.language.trim().slice(0, 32) : ''
|
||||
const force = request?.force === true
|
||||
const cacheKey = `${accountId}:${ref.conversationId}:${ref.messageId}:${language || 'auto'}`
|
||||
|
||||
if (!force) {
|
||||
const memHit = this.readCache(this.ocrCache, cacheKey)
|
||||
if (memHit) {
|
||||
return { messageRef: request.messageRef, ...memHit, cached: true }
|
||||
}
|
||||
}
|
||||
|
||||
const dedupeKey = `${accountId}:ocrImage:${ref.conversationId}:${ref.messageId}:${language || 'auto'}:${force ? '1' : '0'}`
|
||||
return this.runGuarded(extensionId, 'ocrImage', dedupeKey, async () => {
|
||||
const message = await this.requireTypedMessage(ref, 'image')
|
||||
if (!force && !language && this.deps.getCachedOcr) {
|
||||
const indexed = this.deps.getCachedOcr(message.conversationId, message.messageId)
|
||||
if (indexed && typeof indexed.text === 'string') {
|
||||
const payload = {
|
||||
text: indexed.text,
|
||||
language: indexed.language ?? null,
|
||||
engine: indexed.engine || 'system-ocr'
|
||||
}
|
||||
this.writeCache(this.ocrCache, cacheKey, payload)
|
||||
return {
|
||||
messageRef: request.messageRef,
|
||||
...payload,
|
||||
cached: true
|
||||
}
|
||||
}
|
||||
}
|
||||
const data = await this.deps.readImageData(message, 'original')
|
||||
if (!data || data.buffer.length === 0) {
|
||||
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该图片消息的本地文件')
|
||||
}
|
||||
const dataUrl = `data:${data.mimeType};base64,${data.buffer.toString('base64')}`
|
||||
const ocr = await this.deps.recognizeOcr(dataUrl, language || undefined)
|
||||
if (!ocr.success) {
|
||||
throw new ExtensionError(
|
||||
'CAPABILITY_UNAVAILABLE',
|
||||
sanitizeMediaErrorMessage(ocr.error || '本地图片文字识别失败')
|
||||
)
|
||||
}
|
||||
const payload = {
|
||||
text: ocr.text,
|
||||
language: ocr.language,
|
||||
engine: ocr.engine
|
||||
}
|
||||
this.writeCache(this.ocrCache, cacheKey, payload)
|
||||
return {
|
||||
messageRef: request.messageRef,
|
||||
...payload,
|
||||
cached: false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async transcribeVoice(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaTranscribeVoiceRequest
|
||||
): Promise<ExtensionMediaTranscribeVoiceResult> {
|
||||
this.assertPermission(extensionId, 'media.transcribe')
|
||||
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
|
||||
const force = request?.force === true
|
||||
const waitMs = Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
Number.isFinite(Number(request?.waitMs))
|
||||
? Math.trunc(Number(request.waitMs))
|
||||
: DEFAULT_TRANSCRIBE_WAIT_MS,
|
||||
MAX_TRANSCRIBE_WAIT_MS
|
||||
)
|
||||
)
|
||||
const dedupeKey = `${accountId}:transcribeVoice:${ref.conversationId}:${ref.messageId}:${force ? '1' : '0'}`
|
||||
return this.runGuarded(extensionId, 'transcribeVoice', dedupeKey, async () => {
|
||||
const message = await this.requireTypedMessage(ref, 'voice')
|
||||
const localId =
|
||||
message.localId ?? (ref.localId && /^\d+$/.test(ref.localId) ? Number(ref.localId) : 0)
|
||||
const voiceRef: VoiceMessageReference = {
|
||||
sessionId: message.conversationId,
|
||||
localId,
|
||||
createTime: message.createTimeSeconds,
|
||||
...(message.serverId ? { svrId: message.serverId } : {}),
|
||||
...(message.voice?.durationSeconds
|
||||
? { durationSeconds: message.voice.durationSeconds }
|
||||
: {})
|
||||
}
|
||||
const outcome = await this.deps.transcribeVoice(voiceRef, { force, waitMs })
|
||||
if (!outcome) {
|
||||
throw new ExtensionError('CONCURRENCY_LIMITED', '语音转写队列已满,请稍后再试')
|
||||
}
|
||||
if (outcome.state === 'transcribed') {
|
||||
return {
|
||||
messageRef: request.messageRef,
|
||||
state: 'transcribed',
|
||||
transcript: outcome.transcript,
|
||||
...(outcome.durationMs !== undefined ? { durationMs: outcome.durationMs } : {}),
|
||||
cached: outcome.cached
|
||||
}
|
||||
}
|
||||
if (outcome.state === 'pending') {
|
||||
return {
|
||||
messageRef: request.messageRef,
|
||||
state: 'pending',
|
||||
cached: false
|
||||
}
|
||||
}
|
||||
return {
|
||||
messageRef: request.messageRef,
|
||||
state: 'failed',
|
||||
cached: false,
|
||||
error: sanitizeMediaErrorMessage(outcome.error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async analyzeImage(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaAnalyzeImageRequest
|
||||
): Promise<ExtensionMediaAnalyzeImageResult> {
|
||||
this.assertPermission(extensionId, 'ai.vision')
|
||||
const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef)
|
||||
const prompt = typeof request?.prompt === 'string' ? request.prompt.trim().slice(0, 1000) : ''
|
||||
const force = request?.force === true
|
||||
const promptHash = prompt ? createHash('sha256').update(prompt).digest('hex').slice(0, 16) : 'default'
|
||||
const cacheKey = `${accountId}:${ref.conversationId}:${ref.messageId}:${promptHash}`
|
||||
|
||||
if (!force) {
|
||||
const memHit = this.readCache(this.visionCache, cacheKey)
|
||||
if (memHit) {
|
||||
return { messageRef: request.messageRef, ...memHit, cached: true }
|
||||
}
|
||||
}
|
||||
|
||||
const dedupeKey = `${accountId}:analyzeImage:${ref.conversationId}:${ref.messageId}:${promptHash}:${force ? '1' : '0'}`
|
||||
return this.runGuarded(extensionId, 'analyzeImage', dedupeKey, async () => {
|
||||
const message = await this.requireTypedMessage(ref, 'image')
|
||||
const data = await this.deps.readImageData(message, 'original')
|
||||
if (!data || data.buffer.length === 0) {
|
||||
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该图片消息的本地文件')
|
||||
}
|
||||
const imageHash = data.imageHash || `sha256:${sha256Hex(data.buffer).slice(0, 32)}`
|
||||
const imageDataUrl = `data:${data.mimeType};base64,${data.buffer.toString('base64')}`
|
||||
const analyzed = await this.deps.analyzeImage({
|
||||
messageId: message.messageId,
|
||||
conversationId: message.conversationId,
|
||||
senderName: message.senderName || '联系人',
|
||||
sentAt: Math.round(message.createTimeSeconds * 1000),
|
||||
imageHash,
|
||||
imageDataUrl,
|
||||
...(prompt ? { prompt } : {}),
|
||||
force
|
||||
})
|
||||
const payload = {
|
||||
description: analyzed.description,
|
||||
...(analyzed.ocrText ? { ocrText: analyzed.ocrText } : {}),
|
||||
...(analyzed.tags?.length ? { tags: analyzed.tags } : {}),
|
||||
...(analyzed.category ? { category: analyzed.category } : {}),
|
||||
...(analyzed.model ? { model: analyzed.model } : {})
|
||||
}
|
||||
this.writeCache(this.visionCache, cacheKey, payload)
|
||||
return {
|
||||
messageRef: request.messageRef,
|
||||
...payload,
|
||||
cached: analyzed.cached === true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async batch(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaBatchRequest
|
||||
): Promise<ExtensionMediaBatchResult> {
|
||||
const items = Array.isArray(request?.items) ? request.items : null
|
||||
if (!items || items.length === 0) {
|
||||
throw new ExtensionError('INVALID_REQUEST', 'batch.items 不能为空')
|
||||
}
|
||||
if (items.length > this.maxBatchItems) {
|
||||
throw new ExtensionError(
|
||||
'INVALID_REQUEST',
|
||||
`单次批量处理最多支持 ${this.maxBatchItems} 项`
|
||||
)
|
||||
}
|
||||
const requestedConcurrency = Number(request?.concurrency)
|
||||
const workerLimit = Math.max(
|
||||
1,
|
||||
Math.min(
|
||||
Number.isFinite(requestedConcurrency) ? Math.trunc(requestedConcurrency) : 2,
|
||||
this.maxPerExtension,
|
||||
4
|
||||
)
|
||||
)
|
||||
|
||||
const results: ExtensionMediaBatchItemResult[] = new Array(items.length)
|
||||
let cursor = 0
|
||||
|
||||
const worker = async (): Promise<void> => {
|
||||
while (cursor < items.length) {
|
||||
const index = cursor
|
||||
cursor += 1
|
||||
const item = items[index]
|
||||
results[index] = await this.executeBatchItem(extensionId, index, item)
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(workerLimit, items.length) }, () => worker())
|
||||
)
|
||||
return { results }
|
||||
}
|
||||
|
||||
private async executeBatchItem(
|
||||
extensionId: string,
|
||||
index: number,
|
||||
item: ExtensionMediaBatchItem
|
||||
): Promise<ExtensionMediaBatchItemResult> {
|
||||
const op = item?.op
|
||||
const messageRef = typeof item?.messageRef === 'string' ? item.messageRef : ''
|
||||
const options =
|
||||
item?.options && typeof item.options === 'object' && !Array.isArray(item.options)
|
||||
? item.options
|
||||
: {}
|
||||
|
||||
if (!op || !(op in OP_REQUIRED_PERMISSION)) {
|
||||
return {
|
||||
index,
|
||||
op: (op || 'readImage') as ExtensionMediaBatchOperation,
|
||||
messageRef,
|
||||
ok: false,
|
||||
error: { code: 'INVALID_REQUEST', message: '不支持的批量媒体操作类型' }
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
let result: ExtensionMediaBatchItemResult['result']
|
||||
switch (op) {
|
||||
case 'readImage':
|
||||
result = await this.readImage(extensionId, {
|
||||
messageRef,
|
||||
quality: options.quality === 'thumbnail' ? 'thumbnail' : 'original'
|
||||
})
|
||||
break
|
||||
case 'readVoice':
|
||||
result = await this.readVoice(extensionId, { messageRef })
|
||||
break
|
||||
case 'readVideo':
|
||||
result = await this.readVideo(extensionId, { messageRef })
|
||||
break
|
||||
case 'ocrImage':
|
||||
result = await this.ocrImage(extensionId, {
|
||||
messageRef,
|
||||
...(typeof options.language === 'string' ? { language: options.language } : {}),
|
||||
force: options.force === true
|
||||
})
|
||||
break
|
||||
case 'transcribeVoice':
|
||||
result = await this.transcribeVoice(extensionId, {
|
||||
messageRef,
|
||||
force: options.force === true,
|
||||
...(typeof options.waitMs === 'number' ? { waitMs: options.waitMs } : {})
|
||||
})
|
||||
break
|
||||
case 'analyzeImage':
|
||||
result = await this.analyzeImage(extensionId, {
|
||||
messageRef,
|
||||
...(typeof options.prompt === 'string' ? { prompt: options.prompt } : {}),
|
||||
force: options.force === true
|
||||
})
|
||||
break
|
||||
}
|
||||
return { index, op, messageRef, ok: true, result }
|
||||
} catch (error) {
|
||||
return {
|
||||
index,
|
||||
op,
|
||||
messageRef,
|
||||
ok: false,
|
||||
error: toExtensionErrorPayload(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private assertPermission(extensionId: string, permission: ExtensionPermission): void {
|
||||
if (!this.deps.hasPermission(extensionId, permission)) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`)
|
||||
}
|
||||
}
|
||||
|
||||
private verifyRef(
|
||||
extensionId: string,
|
||||
rawRef: unknown
|
||||
): { ref: ExtensionMessageRef; accountId: string } {
|
||||
if (!this.deps.isDatabaseReady()) {
|
||||
throw new ExtensionError('DATABASE_NOT_READY', '微信数据库尚未连接')
|
||||
}
|
||||
const accountId = String(this.deps.getAccountId() || '').trim()
|
||||
if (!accountId) {
|
||||
throw new ExtensionError('DATABASE_NOT_READY', '当前未连接到有效微信账号')
|
||||
}
|
||||
if (this.lastAccountId && this.lastAccountId !== accountId) {
|
||||
this.ocrCache.clear()
|
||||
this.visionCache.clear()
|
||||
}
|
||||
this.lastAccountId = accountId
|
||||
|
||||
const ref = this.deps.verifySignedRef
|
||||
? this.deps.verifySignedRef(rawRef, accountId)
|
||||
: decodeExtensionMessageRef(rawRef)
|
||||
if (!ref) {
|
||||
// 保留跨账号明确错误码:若结构有效但账号不匹配,返回 ACCOUNT_MISMATCH。
|
||||
const parsed = decodeExtensionMessageRef(rawRef)
|
||||
if (parsed && parsed.accountId && parsed.accountId !== accountId) {
|
||||
throw new ExtensionError('ACCOUNT_MISMATCH', '消息引用不属于当前已连接账号')
|
||||
}
|
||||
throw new ExtensionError('INVALID_REQUEST', 'messageRef 无效、未签名或已失效')
|
||||
}
|
||||
if (!ref.accountId || ref.accountId !== accountId) {
|
||||
throw new ExtensionError('ACCOUNT_MISMATCH', '消息引用不属于当前已连接账号')
|
||||
}
|
||||
if (this.deps.isConversationAllowed && !this.deps.isConversationAllowed(extensionId, ref.conversationId)) {
|
||||
throw new ExtensionError('PERMISSION_DENIED', '消息所属会话超出扩展声明的访问范围')
|
||||
}
|
||||
return { ref, accountId }
|
||||
}
|
||||
|
||||
private async requireTypedMessage(
|
||||
ref: ExtensionMessageRef,
|
||||
expectedType: 'image' | 'voice' | 'video'
|
||||
): Promise<ResolvedExtensionMediaMessage> {
|
||||
const resolved = await this.deps.resolveMessage(ref)
|
||||
if (!resolved) {
|
||||
throw new ExtensionError('MEDIA_NOT_FOUND', '找不到对应的消息记录')
|
||||
}
|
||||
if (resolved.conversationId !== ref.conversationId) {
|
||||
throw new ExtensionError('ACCOUNT_MISMATCH', '消息所属会话与引用不一致')
|
||||
}
|
||||
if (resolved.type !== expectedType) {
|
||||
throw new ExtensionError('MEDIA_UNSUPPORTED', `该消息类型为 ${resolved.type},不支持此操作`)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
private async runGuarded<T>(
|
||||
extensionId: string,
|
||||
op: ExtensionMediaBatchOperation,
|
||||
dedupeKey: string,
|
||||
task: () => Promise<T>
|
||||
): Promise<T> {
|
||||
const existing = this.inFlight.get(dedupeKey)
|
||||
if (existing) return (await existing) as T
|
||||
|
||||
const extCount = this.activeByExtension.get(extensionId) ?? 0
|
||||
if (this.activeGlobal >= this.maxGlobal || extCount >= this.maxPerExtension) {
|
||||
throw new ExtensionError('CONCURRENCY_LIMITED', '媒体处理并发已达上限,请稍后再试')
|
||||
}
|
||||
|
||||
this.activeGlobal += 1
|
||||
this.activeByExtension.set(extensionId, extCount + 1)
|
||||
|
||||
const timeoutMs = this.timeouts[op]
|
||||
const promise = withTimeout(task(), timeoutMs)
|
||||
.catch((error) => {
|
||||
if (error instanceof ExtensionError) throw error
|
||||
throw new ExtensionError(
|
||||
'ACTION_FAILED',
|
||||
sanitizeMediaErrorMessage(error instanceof Error ? error.message : String(error))
|
||||
)
|
||||
})
|
||||
.finally(() => {
|
||||
this.inFlight.delete(dedupeKey)
|
||||
this.activeGlobal = Math.max(0, this.activeGlobal - 1)
|
||||
const current = this.activeByExtension.get(extensionId) ?? 1
|
||||
if (current <= 1) this.activeByExtension.delete(extensionId)
|
||||
else this.activeByExtension.set(extensionId, current - 1)
|
||||
})
|
||||
|
||||
this.inFlight.set(dedupeKey, promise)
|
||||
return promise
|
||||
}
|
||||
|
||||
/** 始终落盘到扩展私有数据目录且按账号哈希分桶,禁止跨扩展与跨账号共享缓存路径。 */
|
||||
private async writeCachedMediaFile(
|
||||
extensionId: string,
|
||||
accountId: string,
|
||||
bucket: 'images' | 'voices' | 'videos',
|
||||
fileName: string,
|
||||
data: Buffer
|
||||
): Promise<{ filePath: string; cached: boolean }> {
|
||||
const dataRoot = path.resolve(this.deps.getExtensionDataRoot(extensionId))
|
||||
const accountScope = createHash('sha256').update(accountId).digest('hex').slice(0, 16)
|
||||
const cacheDir = path.join(dataRoot, 'media-cache', accountScope, bucket)
|
||||
const filePath = path.join(cacheDir, fileName)
|
||||
if (!isPathInside(dataRoot, filePath)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', '媒体缓存路径越界')
|
||||
}
|
||||
await fs.ensureDir(cacheDir)
|
||||
const realRoot = await fs.realpath(dataRoot)
|
||||
const realDir = await fs.realpath(cacheDir)
|
||||
if (!isPathInside(realRoot, realDir)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', '媒体缓存目录存在非法符号链接')
|
||||
}
|
||||
if (await fs.pathExists(filePath)) {
|
||||
const stat = await fs.lstat(filePath)
|
||||
if (!stat.isSymbolicLink() && stat.isFile() && stat.size === data.length) {
|
||||
return { filePath, cached: true }
|
||||
}
|
||||
}
|
||||
const tempPath = `${filePath}.${Date.now().toString(36)}.tmp`
|
||||
await fs.writeFile(tempPath, data)
|
||||
await fs.move(tempPath, filePath, { overwrite: true })
|
||||
return { filePath, cached: false }
|
||||
}
|
||||
|
||||
private readCache<T>(map: Map<string, CacheEntry<T>>, key: string): T | null {
|
||||
const entry = map.get(key)
|
||||
if (!entry) return null
|
||||
if (this.now() - entry.at > this.cacheTtlMs) {
|
||||
map.delete(key)
|
||||
return null
|
||||
}
|
||||
return entry.value
|
||||
}
|
||||
|
||||
private writeCache<T>(map: Map<string, CacheEntry<T>>, key: string, value: T): void {
|
||||
map.set(key, { value, at: this.now() })
|
||||
if (map.size > DEFAULT_CACHE_ENTRIES) {
|
||||
const oldest = map.keys().next().value
|
||||
if (oldest) map.delete(oldest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function compareCodePoint(left: string, right: string): number {
|
||||
if (left === right) return 0
|
||||
return left < right ? -1 : 1
|
||||
}
|
||||
|
||||
/** 确定性游标分页:按 (timestamp, messageId) 排序,同时间戳多条消息不漏不重。 */
|
||||
export function paginateQueriedMessages(
|
||||
allMessages: ExtensionQueriedMessage[],
|
||||
request: ExtensionMessagesQueryRequest
|
||||
): ExtensionMessagesQueryResult {
|
||||
const limit = Math.max(1, Math.min(Number(request.limit) || 50, 500))
|
||||
const cursor = request.cursor ? decodeMessagesQueryCursor(request.cursor) : null
|
||||
if (request.cursor && !cursor) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '分页游标无效')
|
||||
}
|
||||
if (cursor && request.order && cursor.order !== request.order) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '分页游标与排序方向不一致')
|
||||
}
|
||||
if (cursor && request.order === undefined && cursor.order !== 'desc') {
|
||||
throw new ExtensionError('INVALID_REQUEST', '默认分页模式仅接受向更早历史续页的游标')
|
||||
}
|
||||
|
||||
const allowedTypes =
|
||||
Array.isArray(request.types) && request.types.length > 0
|
||||
? new Set(request.types.map((item) => String(item).trim()).filter(Boolean))
|
||||
: null
|
||||
|
||||
const filtered = allMessages.filter((item) => {
|
||||
if (allowedTypes && !allowedTypes.has(item.type)) return false
|
||||
if (request.startTime !== undefined && item.timestamp < request.startTime) return false
|
||||
if (request.endTime !== undefined && item.timestamp > request.endTime) return false
|
||||
return true
|
||||
})
|
||||
|
||||
const ascSorted = [...filtered].sort((left, right) => {
|
||||
const timeDelta = left.timestamp - right.timestamp
|
||||
return timeDelta !== 0 ? timeDelta : compareCodePoint(left.messageId, right.messageId)
|
||||
})
|
||||
|
||||
// 未显式指定 order 时保持 v1 默认语义(返回最新一页并按时间升序排列),同时支持向更早历史续页。
|
||||
if (request.order === undefined) {
|
||||
const olderPool = cursor
|
||||
? ascSorted.filter((item) => {
|
||||
const timeDelta = item.timestamp - cursor.timestamp
|
||||
const cmp = timeDelta !== 0 ? timeDelta : compareCodePoint(item.messageId, cursor.messageId)
|
||||
return cmp < 0
|
||||
})
|
||||
: ascSorted
|
||||
const hasMore = olderPool.length > limit
|
||||
const page = olderPool.slice(-limit)
|
||||
const oldest = page[0]
|
||||
return {
|
||||
messages: page,
|
||||
...(hasMore && oldest
|
||||
? {
|
||||
nextCursor: encodeMessagesQueryCursor({
|
||||
order: 'desc',
|
||||
timestamp: oldest.timestamp,
|
||||
messageId: oldest.messageId
|
||||
})
|
||||
}
|
||||
: {}),
|
||||
hasMore
|
||||
}
|
||||
}
|
||||
|
||||
const order: 'asc' | 'desc' = request.order === 'desc' ? 'desc' : 'asc'
|
||||
const sorted = order === 'desc' ? [...ascSorted].reverse() : ascSorted
|
||||
const afterCursor = cursor
|
||||
? sorted.filter((item) => {
|
||||
const timeDelta = item.timestamp - cursor.timestamp
|
||||
const cmp = timeDelta !== 0 ? timeDelta : compareCodePoint(item.messageId, cursor.messageId)
|
||||
return order === 'desc' ? cmp < 0 : cmp > 0
|
||||
})
|
||||
: sorted
|
||||
|
||||
const hasMore = afterCursor.length > limit
|
||||
const page = afterCursor.slice(0, limit)
|
||||
const last = page[page.length - 1]
|
||||
return {
|
||||
messages: page,
|
||||
...(hasMore && last
|
||||
? {
|
||||
nextCursor: encodeMessagesQueryCursor({
|
||||
order,
|
||||
timestamp: last.timestamp,
|
||||
messageId: last.messageId
|
||||
})
|
||||
}
|
||||
: {}),
|
||||
hasMore
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
|
||||
import {
|
||||
decodeExtensionMessageRef,
|
||||
encodeExtensionMessageRef,
|
||||
type ExtensionMessageRef
|
||||
} from '../../shared/extensions/media'
|
||||
|
||||
const SIGNATURE_BYTES = 16
|
||||
|
||||
/**
|
||||
* messageRef 用运行期密钥 + 账号世代签名,防止扩展伪造引用;
|
||||
* 世代随账号切换递增,切号前签发的旧引用必须全部失效。
|
||||
*/
|
||||
export class ExtensionMessageRefSigner {
|
||||
private readonly secret: Buffer
|
||||
private generation = 1
|
||||
private currentAccountId = ''
|
||||
|
||||
constructor(secret?: Buffer) {
|
||||
this.secret = secret && secret.length >= 16 ? secret : randomBytes(32)
|
||||
}
|
||||
|
||||
/** 账号变化时递增世代,让切号前签发的所有 messageRef 失效。 */
|
||||
syncAccount(accountId: string): void {
|
||||
const normalized = String(accountId || '').trim()
|
||||
if (!normalized) return
|
||||
if (this.currentAccountId && this.currentAccountId !== normalized) {
|
||||
this.generation += 1
|
||||
}
|
||||
this.currentAccountId = normalized
|
||||
}
|
||||
|
||||
sign(ref: ExtensionMessageRef): string {
|
||||
this.syncAccount(ref.accountId)
|
||||
const unsigned = encodeExtensionMessageRef(ref)
|
||||
const mac = this.computeMac(unsigned, this.generation)
|
||||
return `${unsigned}.${mac}`
|
||||
}
|
||||
|
||||
verify(rawRef: unknown, expectedAccountId: string): ExtensionMessageRef | null {
|
||||
if (typeof rawRef !== 'string') return null
|
||||
const trimmed = rawRef.trim()
|
||||
const dotIndex = trimmed.lastIndexOf('.')
|
||||
if (dotIndex <= 0 || dotIndex === trimmed.length - 1) return null
|
||||
|
||||
const unsigned = trimmed.slice(0, dotIndex)
|
||||
const providedSig = trimmed.slice(dotIndex + 1)
|
||||
if (!/^[A-Za-z0-9_-]{16,64}$/.test(providedSig)) return null
|
||||
|
||||
const normalizedAccount = String(expectedAccountId || '').trim()
|
||||
if (!normalizedAccount) return null
|
||||
this.syncAccount(normalizedAccount)
|
||||
|
||||
const expectedSig = this.computeMac(unsigned, this.generation)
|
||||
const providedBuf = Buffer.from(providedSig, 'utf8')
|
||||
const expectedBuf = Buffer.from(expectedSig, 'utf8')
|
||||
if (providedBuf.length !== expectedBuf.length || !timingSafeEqual(providedBuf, expectedBuf)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const decoded = decodeExtensionMessageRef(unsigned)
|
||||
if (!decoded || decoded.accountId !== normalizedAccount) return null
|
||||
return decoded
|
||||
}
|
||||
|
||||
private computeMac(unsigned: string, generation: number): string {
|
||||
return createHmac('sha256', this.secret)
|
||||
.update(`${generation}:${unsigned}`)
|
||||
.digest()
|
||||
.subarray(0, SIGNATURE_BYTES)
|
||||
.toString('base64url')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import fs from 'fs-extra'
|
||||
import path from 'node:path'
|
||||
import { isValidExtensionId } from '../../shared/extensions/manifest'
|
||||
|
||||
export interface PinnedNavigationRecord {
|
||||
extensionId: string
|
||||
pageId?: string
|
||||
order: number
|
||||
pinnedAt: number
|
||||
}
|
||||
|
||||
interface PinnedNavigationFile {
|
||||
version: number
|
||||
items: PinnedNavigationRecord[]
|
||||
}
|
||||
|
||||
const STORE_VERSION = 1
|
||||
const MAX_PINNED_ITEMS = 12
|
||||
|
||||
/** 宿主管理的一级导航固定项存储;独立于扩展自身配置,重启可恢复、卸载自动清理。 */
|
||||
export class ExtensionNavigationStore {
|
||||
private items: PinnedNavigationRecord[] = []
|
||||
|
||||
constructor(
|
||||
private readonly filePath: string,
|
||||
private readonly now: () => number = () => Date.now()
|
||||
) {
|
||||
this.items = this.load()
|
||||
}
|
||||
|
||||
list(): PinnedNavigationRecord[] {
|
||||
return [...this.items].sort((left, right) => {
|
||||
if (left.order !== right.order) return left.order - right.order
|
||||
return left.pinnedAt - right.pinnedAt
|
||||
})
|
||||
}
|
||||
|
||||
isPinned(extensionId: string): boolean {
|
||||
return this.items.some((item) => item.extensionId === extensionId)
|
||||
}
|
||||
|
||||
pin(extensionId: string, pageId?: string): PinnedNavigationRecord[] {
|
||||
const existing = this.items.find((item) => item.extensionId === extensionId)
|
||||
if (existing) {
|
||||
if (pageId !== undefined) existing.pageId = pageId || undefined
|
||||
this.save()
|
||||
return this.list()
|
||||
}
|
||||
if (this.items.length >= MAX_PINNED_ITEMS) {
|
||||
throw new Error(`最多固定 ${MAX_PINNED_ITEMS} 个扩展到一级导航`)
|
||||
}
|
||||
const maxOrder = this.items.reduce((acc, item) => Math.max(acc, item.order), -1)
|
||||
this.items.push({
|
||||
extensionId,
|
||||
...(pageId ? { pageId } : {}),
|
||||
order: maxOrder + 1,
|
||||
pinnedAt: this.now()
|
||||
})
|
||||
this.save()
|
||||
return this.list()
|
||||
}
|
||||
|
||||
unpin(extensionId: string): PinnedNavigationRecord[] {
|
||||
const before = this.items.length
|
||||
this.items = this.items.filter((item) => item.extensionId !== extensionId)
|
||||
if (this.items.length !== before) {
|
||||
this.reindex()
|
||||
this.save()
|
||||
}
|
||||
return this.list()
|
||||
}
|
||||
|
||||
remove(extensionId: string): boolean {
|
||||
const before = this.items.length
|
||||
this.items = this.items.filter((item) => item.extensionId !== extensionId)
|
||||
if (this.items.length === before) return false
|
||||
this.reindex()
|
||||
this.save()
|
||||
return true
|
||||
}
|
||||
|
||||
reorder(extensionIds: string[]): PinnedNavigationRecord[] {
|
||||
const byId = new Map(this.items.map((item) => [item.extensionId, item]))
|
||||
const ordered: PinnedNavigationRecord[] = []
|
||||
for (const id of extensionIds) {
|
||||
const found = byId.get(id)
|
||||
if (!found) continue
|
||||
ordered.push(found)
|
||||
byId.delete(id)
|
||||
}
|
||||
for (const remaining of byId.values()) {
|
||||
ordered.push(remaining)
|
||||
}
|
||||
this.items = ordered.map((item, index) => ({ ...item, order: index }))
|
||||
this.save()
|
||||
return this.list()
|
||||
}
|
||||
|
||||
private reindex(): void {
|
||||
this.items = this.list().map((item, index) => ({ ...item, order: index }))
|
||||
}
|
||||
|
||||
private load(): PinnedNavigationRecord[] {
|
||||
if (!fs.existsSync(this.filePath)) return []
|
||||
try {
|
||||
const parsed = fs.readJsonSync(this.filePath) as Partial<PinnedNavigationFile>
|
||||
if (!parsed || Number(parsed.version) !== STORE_VERSION || !Array.isArray(parsed.items)) {
|
||||
return []
|
||||
}
|
||||
const result: PinnedNavigationRecord[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const item of parsed.items) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
const extensionId = String(item.extensionId || '').trim()
|
||||
if (!isValidExtensionId(extensionId) || seen.has(extensionId)) continue
|
||||
seen.add(extensionId)
|
||||
const pageId =
|
||||
typeof item.pageId === 'string' && item.pageId.trim()
|
||||
? item.pageId.trim().slice(0, 32)
|
||||
: undefined
|
||||
const order = Number.isFinite(Number(item.order)) ? Math.round(Number(item.order)) : result.length
|
||||
const pinnedAt =
|
||||
Number.isFinite(Number(item.pinnedAt)) && Number(item.pinnedAt) > 0
|
||||
? Math.round(Number(item.pinnedAt))
|
||||
: this.now()
|
||||
result.push({ extensionId, ...(pageId ? { pageId } : {}), order, pinnedAt })
|
||||
}
|
||||
return result.sort((left, right) => left.order - right.order).slice(0, MAX_PINNED_ITEMS)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
fs.ensureDirSync(path.dirname(this.filePath))
|
||||
const temp = `${this.filePath}.${process.pid}.${Date.now().toString(36)}.tmp`
|
||||
const payload: PinnedNavigationFile = {
|
||||
version: STORE_VERSION,
|
||||
items: this.list()
|
||||
}
|
||||
fs.writeJsonSync(temp, payload, { spaces: 2 })
|
||||
fs.moveSync(temp, this.filePath, { overwrite: true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import fs from 'fs-extra'
|
||||
import path from 'node:path'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
import { isValidExtensionId } from '../../shared/extensions/manifest'
|
||||
import type {
|
||||
ExtensionNotificationCreateRequest,
|
||||
ExtensionNotificationCreateResult,
|
||||
ExtensionNotificationLevel
|
||||
} from '../../shared/extensions/rpc'
|
||||
import type {
|
||||
ExtensionNotificationItem,
|
||||
ExtensionNotificationSummary
|
||||
} from '../../shared/extensions/types'
|
||||
|
||||
interface NotificationFile {
|
||||
version: number
|
||||
items: ExtensionNotificationItem[]
|
||||
}
|
||||
|
||||
const STORE_VERSION = 1
|
||||
const MAX_TOTAL_NOTIFICATIONS = 200
|
||||
const MAX_PER_EXTENSION_NOTIFICATIONS = 50
|
||||
const RATE_WINDOW_MS = 60_000
|
||||
const DEFAULT_MAX_NEW_PER_WINDOW = 20
|
||||
const DEFAULT_MAX_UPDATES_PER_WINDOW = 60
|
||||
const VALID_LEVELS: readonly ExtensionNotificationLevel[] = ['info', 'success', 'warning', 'error']
|
||||
|
||||
export interface ExtensionNotificationStoreOptions {
|
||||
maxNewPerWindow?: number
|
||||
maxUpdatesPerWindow?: number
|
||||
rateWindowMs?: number
|
||||
}
|
||||
|
||||
function normalizeLevel(value: unknown): ExtensionNotificationLevel {
|
||||
return typeof value === 'string' && (VALID_LEVELS as readonly string[]).includes(value)
|
||||
? (value as ExtensionNotificationLevel)
|
||||
: 'info'
|
||||
}
|
||||
|
||||
/** 宿主管理的扩展通知中心持久化存储;支持扩展内去重、限频防刷屏、分级、未读统计与卸载清理。 */
|
||||
export class ExtensionNotificationStore {
|
||||
private items: ExtensionNotificationItem[] = []
|
||||
private readonly maxNewPerWindow: number
|
||||
private readonly maxUpdatesPerWindow: number
|
||||
private readonly rateWindowMs: number
|
||||
private readonly newHistory = new Map<string, number[]>()
|
||||
private readonly updateHistory = new Map<string, number[]>()
|
||||
|
||||
constructor(
|
||||
private readonly filePath: string,
|
||||
private readonly now: () => number = () => Date.now(),
|
||||
options: ExtensionNotificationStoreOptions = {}
|
||||
) {
|
||||
this.maxNewPerWindow = Math.max(1, options.maxNewPerWindow ?? DEFAULT_MAX_NEW_PER_WINDOW)
|
||||
this.maxUpdatesPerWindow = Math.max(1, options.maxUpdatesPerWindow ?? DEFAULT_MAX_UPDATES_PER_WINDOW)
|
||||
this.rateWindowMs = Math.max(1_000, options.rateWindowMs ?? RATE_WINDOW_MS)
|
||||
this.items = this.load()
|
||||
}
|
||||
|
||||
create(
|
||||
extensionId: string,
|
||||
extensionName: string,
|
||||
request: ExtensionNotificationCreateRequest
|
||||
): ExtensionNotificationCreateResult {
|
||||
const title = String(request?.title || '')
|
||||
.trim()
|
||||
.slice(0, 80)
|
||||
if (!title) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '通知标题不能为空')
|
||||
}
|
||||
const body =
|
||||
typeof request?.body === 'string' && request.body.trim()
|
||||
? request.body.trim().slice(0, 300)
|
||||
: undefined
|
||||
const level = normalizeLevel(request?.level)
|
||||
const dedupeKey =
|
||||
typeof request?.dedupeKey === 'string' && request.dedupeKey.trim()
|
||||
? request.dedupeKey.trim().slice(0, 128)
|
||||
: undefined
|
||||
const pageId =
|
||||
typeof request?.pageId === 'string' && request.pageId.trim()
|
||||
? request.pageId.trim().slice(0, 32)
|
||||
: undefined
|
||||
const at = this.now()
|
||||
|
||||
if (dedupeKey) {
|
||||
const existing = this.items.find(
|
||||
(item) => item.extensionId === extensionId && item.dedupeKey === dedupeKey
|
||||
)
|
||||
if (existing) {
|
||||
this.assertRateLimit(this.updateHistory, extensionId, this.maxUpdatesPerWindow, at)
|
||||
existing.extensionName = extensionName
|
||||
existing.title = title
|
||||
existing.body = body
|
||||
existing.level = level
|
||||
existing.pageId = pageId
|
||||
existing.updatedAt = at
|
||||
this.save()
|
||||
return { id: existing.id, deduped: true, createdAt: existing.createdAt }
|
||||
}
|
||||
}
|
||||
|
||||
this.assertRateLimit(this.newHistory, extensionId, this.maxNewPerWindow, at)
|
||||
const record: ExtensionNotificationItem = {
|
||||
id: `ext-ntf-${randomUUID()}`,
|
||||
extensionId,
|
||||
extensionName,
|
||||
title,
|
||||
...(body ? { body } : {}),
|
||||
level,
|
||||
...(dedupeKey ? { dedupeKey } : {}),
|
||||
...(pageId ? { pageId } : {}),
|
||||
read: false,
|
||||
createdAt: at,
|
||||
updatedAt: at
|
||||
}
|
||||
this.items.unshift(record)
|
||||
this.prune(extensionId)
|
||||
this.save()
|
||||
return { id: record.id, deduped: false, createdAt: record.createdAt }
|
||||
}
|
||||
|
||||
list(extensionId?: string): ExtensionNotificationItem[] {
|
||||
const filtered = extensionId
|
||||
? this.items.filter((item) => item.extensionId === extensionId)
|
||||
: this.items
|
||||
return [...filtered]
|
||||
.sort((left, right) => right.updatedAt - left.updatedAt)
|
||||
.map((item) => ({ ...item }))
|
||||
}
|
||||
|
||||
summary(pinnedExtensionIds: ReadonlySet<string>): ExtensionNotificationSummary {
|
||||
let totalUnread = 0
|
||||
let unpinnedUnread = 0
|
||||
const unreadByExtension: Record<string, number> = {}
|
||||
for (const item of this.items) {
|
||||
if (item.read) continue
|
||||
totalUnread += 1
|
||||
unreadByExtension[item.extensionId] = (unreadByExtension[item.extensionId] ?? 0) + 1
|
||||
if (!pinnedExtensionIds.has(item.extensionId)) {
|
||||
unpinnedUnread += 1
|
||||
}
|
||||
}
|
||||
return { totalUnread, unpinnedUnread, unreadByExtension }
|
||||
}
|
||||
|
||||
markRead(options: { id?: string; extensionId?: string; all?: boolean }): number {
|
||||
let changed = 0
|
||||
for (const item of this.items) {
|
||||
if (item.read) continue
|
||||
if (options.extensionId && item.extensionId !== options.extensionId) {
|
||||
continue
|
||||
}
|
||||
if (options.all) {
|
||||
item.read = true
|
||||
changed += 1
|
||||
} else if (options.id && item.id === options.id) {
|
||||
item.read = true
|
||||
changed += 1
|
||||
} else if (!options.id && options.extensionId && item.extensionId === options.extensionId) {
|
||||
item.read = true
|
||||
changed += 1
|
||||
}
|
||||
}
|
||||
if (changed > 0) this.save()
|
||||
return changed
|
||||
}
|
||||
|
||||
private assertRateLimit(
|
||||
bucket: Map<string, number[]>,
|
||||
extensionId: string,
|
||||
limit: number,
|
||||
at: number
|
||||
): void {
|
||||
const recent = (bucket.get(extensionId) ?? []).filter((ts) => at - ts < this.rateWindowMs)
|
||||
if (recent.length >= limit) {
|
||||
bucket.set(extensionId, recent)
|
||||
throw new ExtensionError('CONCURRENCY_LIMITED', '通知写入过于频繁,请稍后再试')
|
||||
}
|
||||
recent.push(at)
|
||||
bucket.set(extensionId, recent)
|
||||
}
|
||||
|
||||
clear(extensionId?: string): number {
|
||||
const before = this.items.length
|
||||
this.items = extensionId
|
||||
? this.items.filter((item) => item.extensionId !== extensionId)
|
||||
: []
|
||||
const removed = before - this.items.length
|
||||
if (removed > 0) this.save()
|
||||
return removed
|
||||
}
|
||||
|
||||
removeByExtension(extensionId: string): number {
|
||||
return this.clear(extensionId)
|
||||
}
|
||||
|
||||
private prune(extensionId: string): void {
|
||||
const perExt = this.items.filter((item) => item.extensionId === extensionId)
|
||||
if (perExt.length > MAX_PER_EXTENSION_NOTIFICATIONS) {
|
||||
const keepIds = new Set(
|
||||
perExt
|
||||
.sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
.slice(0, MAX_PER_EXTENSION_NOTIFICATIONS)
|
||||
.map((item) => item.id)
|
||||
)
|
||||
this.items = this.items.filter(
|
||||
(item) => item.extensionId !== extensionId || keepIds.has(item.id)
|
||||
)
|
||||
}
|
||||
if (this.items.length > MAX_TOTAL_NOTIFICATIONS) {
|
||||
this.items.sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
this.items = this.items.slice(0, MAX_TOTAL_NOTIFICATIONS)
|
||||
}
|
||||
}
|
||||
|
||||
private load(): ExtensionNotificationItem[] {
|
||||
if (!fs.existsSync(this.filePath)) return []
|
||||
try {
|
||||
const parsed = fs.readJsonSync(this.filePath) as Partial<NotificationFile>
|
||||
if (!parsed || Number(parsed.version) !== STORE_VERSION || !Array.isArray(parsed.items)) {
|
||||
return []
|
||||
}
|
||||
const result: ExtensionNotificationItem[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const raw of parsed.items) {
|
||||
if (!raw || typeof raw !== 'object') continue
|
||||
const id = String(raw.id || '').trim()
|
||||
const extensionId = String(raw.extensionId || '').trim()
|
||||
const title = String(raw.title || '').trim().slice(0, 80)
|
||||
if (!id || seen.has(id) || !isValidExtensionId(extensionId) || !title) continue
|
||||
seen.add(id)
|
||||
const createdAt = Number.isFinite(Number(raw.createdAt)) ? Number(raw.createdAt) : this.now()
|
||||
const updatedAt = Number.isFinite(Number(raw.updatedAt)) ? Number(raw.updatedAt) : createdAt
|
||||
result.push({
|
||||
id,
|
||||
extensionId,
|
||||
extensionName: String(raw.extensionName || extensionId).slice(0, 64),
|
||||
title,
|
||||
...(typeof raw.body === 'string' && raw.body.trim()
|
||||
? { body: raw.body.trim().slice(0, 300) }
|
||||
: {}),
|
||||
level: normalizeLevel(raw.level),
|
||||
...(typeof raw.dedupeKey === 'string' && raw.dedupeKey.trim()
|
||||
? { dedupeKey: raw.dedupeKey.trim().slice(0, 128) }
|
||||
: {}),
|
||||
...(typeof raw.pageId === 'string' && raw.pageId.trim()
|
||||
? { pageId: raw.pageId.trim().slice(0, 32) }
|
||||
: {}),
|
||||
read: raw.read === true,
|
||||
createdAt,
|
||||
updatedAt
|
||||
})
|
||||
}
|
||||
return result.sort((a, b) => b.updatedAt - a.updatedAt).slice(0, MAX_TOTAL_NOTIFICATIONS)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
fs.ensureDirSync(path.dirname(this.filePath))
|
||||
const temp = `${this.filePath}.${process.pid}.${Date.now().toString(36)}.tmp`
|
||||
fs.writeJsonSync(temp, { version: STORE_VERSION, items: this.items }, { spaces: 2 })
|
||||
fs.moveSync(temp, this.filePath, { overwrite: true })
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ export interface ExtensionPaths {
|
||||
stateDir: string
|
||||
stagingDir: string
|
||||
registryFile: string
|
||||
pinnedNavigationFile: string
|
||||
notificationsFile: string
|
||||
logsDir: string
|
||||
installDir: (extensionId: string) => string
|
||||
extensionDataDir: (extensionId: string) => string
|
||||
@@ -42,6 +44,8 @@ export function createExtensionPaths(userData: string): ExtensionPaths {
|
||||
stateDir,
|
||||
stagingDir,
|
||||
registryFile: path.join(stateDir, 'registry.json'),
|
||||
pinnedNavigationFile: path.join(stateDir, 'pinned-navigation.json'),
|
||||
notificationsFile: path.join(stateDir, 'notifications.json'),
|
||||
logsDir,
|
||||
installDir: (extensionId) => path.join(extensionsDir, extensionId),
|
||||
extensionDataDir: (extensionId) => path.join(dataDir, extensionId),
|
||||
|
||||
@@ -5,6 +5,9 @@ import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
|
||||
import { isPathInside, type ExtensionPaths } from './extension-paths'
|
||||
|
||||
export const EXTENSION_SCHEME = 'tm-extension'
|
||||
export const EXTENSION_PRIVATE_DATA_PREFIX = '_data/'
|
||||
|
||||
const ALLOWED_PRIVATE_DATA_DIRS = ['rendered/', 'media-cache/'] as const
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
@@ -25,6 +28,135 @@ const MIME_TYPES: Record<string, string> = {
|
||||
'.wasm': 'application/wasm'
|
||||
}
|
||||
|
||||
/** 扩展私有预览只放行静态媒体文件,禁止读取脚本、HTML 或 storage.json。 */
|
||||
const PRIVATE_MEDIA_MIME_TYPES: Record<string, string> = {
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.bmp': 'image/bmp',
|
||||
'.wav': 'audio/wav',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.m4a': 'audio/mp4',
|
||||
'.mp4': 'video/mp4'
|
||||
}
|
||||
|
||||
const MAX_CODE_FILE_BYTES = 20 * 1024 * 1024
|
||||
const MAX_PRIVATE_IMAGE_AUDIO_BYTES = 25 * 1024 * 1024
|
||||
const MAX_PRIVATE_VIDEO_BYTES = 100 * 1024 * 1024
|
||||
|
||||
const PAGE_CSP = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: https:",
|
||||
"media-src 'self' data: https:",
|
||||
"font-src 'self' data:",
|
||||
"connect-src 'none'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'"
|
||||
].join('; ')
|
||||
|
||||
const PRIVATE_MEDIA_CSP = "default-src 'none'; sandbox"
|
||||
|
||||
/** 为位于扩展私有目录 rendered/ 或 media-cache/ 下的媒体文件构造受控预览 URL。 */
|
||||
export function buildExtensionPrivateMediaPreviewUrl(
|
||||
extensionId: string,
|
||||
extensionDataRoot: string,
|
||||
filePath: string
|
||||
): string | undefined {
|
||||
const id = String(extensionId || '').trim().toLowerCase()
|
||||
if (!/^[a-z0-9.-]{3,128}$/.test(id)) return undefined
|
||||
const root = path.resolve(extensionDataRoot)
|
||||
const target = path.resolve(filePath)
|
||||
if (!isPathInside(root, target)) return undefined
|
||||
const relative = path.relative(root, target).replace(/\\/g, '/')
|
||||
if (!isSafeRelativeEntryPath(relative)) return undefined
|
||||
if (!ALLOWED_PRIVATE_DATA_DIRS.some((prefix) => relative.startsWith(prefix))) return undefined
|
||||
const ext = path.extname(relative).toLowerCase()
|
||||
if (!(ext in PRIVATE_MEDIA_MIME_TYPES)) return undefined
|
||||
const encodedPath = relative
|
||||
.split('/')
|
||||
.map((segment) => encodeURIComponent(segment))
|
||||
.join('/')
|
||||
return `${EXTENSION_SCHEME}://${id}/${EXTENSION_PRIVATE_DATA_PREFIX}${encodedPath}`
|
||||
}
|
||||
|
||||
export interface ResolvedExtensionProtocolFile {
|
||||
realFile: string
|
||||
contentType: string
|
||||
csp: string
|
||||
size: number
|
||||
isPrivateMedia: boolean
|
||||
}
|
||||
|
||||
/** 扩展协议统一解析器:支持扩展代码文件与受控的 `_data/{rendered,media-cache}/` 媒体只读预览。 */
|
||||
export async function resolveExtensionProtocolFile(
|
||||
requestUrl: string,
|
||||
dependencies: ExtensionProtocolDependencies
|
||||
): Promise<ResolvedExtensionProtocolFile | null> {
|
||||
const url = new URL(requestUrl)
|
||||
if (url.protocol !== `${EXTENSION_SCHEME}:`) return null
|
||||
const extensionId = url.hostname.toLowerCase()
|
||||
if (!/^[a-z0-9.-]{3,128}$/.test(extensionId)) return null
|
||||
const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '')
|
||||
if (!isSafeRelativeEntryPath(relative)) return null
|
||||
|
||||
const isPrivateMedia = relative.startsWith(EXTENSION_PRIVATE_DATA_PREFIX)
|
||||
if (isPrivateMedia) {
|
||||
// 只有已安装的扩展允许解析私有预览文件。
|
||||
if (!dependencies.resolveRoot(extensionId)) return null
|
||||
const subPath = relative.slice(EXTENSION_PRIVATE_DATA_PREFIX.length)
|
||||
if (!isSafeRelativeEntryPath(subPath)) return null
|
||||
if (!ALLOWED_PRIVATE_DATA_DIRS.some((prefix) => subPath.startsWith(prefix))) return null
|
||||
|
||||
const ext = path.extname(subPath).toLowerCase()
|
||||
const contentType = PRIVATE_MEDIA_MIME_TYPES[ext]
|
||||
if (!contentType) return null
|
||||
|
||||
const dataRoot = dependencies.paths.extensionDataDir(extensionId)
|
||||
const resolved = path.resolve(dataRoot, subPath)
|
||||
if (!isPathInside(dataRoot, resolved)) return null
|
||||
const lstat = await fs.lstat(resolved).catch(() => null)
|
||||
if (!lstat || lstat.isSymbolicLink() || !lstat.isFile()) return null
|
||||
const realRoot = await fs.realpath(dataRoot).catch(() => null)
|
||||
const realFile = await fs.realpath(resolved).catch(() => null)
|
||||
if (!realRoot || !realFile || !isPathInside(realRoot, realFile)) return null
|
||||
|
||||
const maxBytes = ext === '.mp4' ? MAX_PRIVATE_VIDEO_BYTES : MAX_PRIVATE_IMAGE_AUDIO_BYTES
|
||||
if (lstat.size <= 0 || lstat.size > maxBytes) return null
|
||||
return {
|
||||
realFile,
|
||||
contentType,
|
||||
csp: PRIVATE_MEDIA_CSP,
|
||||
size: lstat.size,
|
||||
isPrivateMedia: true
|
||||
}
|
||||
}
|
||||
|
||||
const root = dependencies.resolveRoot(extensionId)
|
||||
if (!root) return null
|
||||
const resolved = path.resolve(root, relative)
|
||||
if (!isPathInside(root, resolved)) return null
|
||||
const realRoot = await fs.realpath(root).catch(() => null)
|
||||
const realFile = await fs.realpath(resolved).catch(() => null)
|
||||
if (!realRoot || !realFile || !isPathInside(realRoot, realFile)) return null
|
||||
|
||||
const stat = await fs.stat(realFile).catch(() => null)
|
||||
if (!stat || !stat.isFile() || stat.size > MAX_CODE_FILE_BYTES) return null
|
||||
const contentType =
|
||||
MIME_TYPES[path.extname(realFile).toLowerCase()] || 'application/octet-stream'
|
||||
return {
|
||||
realFile,
|
||||
contentType,
|
||||
csp: PAGE_CSP,
|
||||
size: stat.size,
|
||||
isPrivateMedia: false
|
||||
}
|
||||
}
|
||||
|
||||
/** 扩展页面协议:只接受 `tm-extension://<extensionId>/<path>`,realpath 必须仍在。 */
|
||||
export function registerExtensionScheme(): void {
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
@@ -50,42 +182,14 @@ export interface ExtensionProtocolDependencies {
|
||||
export function installExtensionProtocolHandler(dependencies: ExtensionProtocolDependencies): void {
|
||||
protocol.handle(EXTENSION_SCHEME, async (request) => {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const extensionId = url.hostname.toLowerCase()
|
||||
if (!/^[a-z0-9.-]{3,128}$/.test(extensionId)) return notFound()
|
||||
const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '')
|
||||
if (!isSafeRelativeEntryPath(relative)) return notFound()
|
||||
|
||||
const root = dependencies.resolveRoot(extensionId)
|
||||
if (!root) return notFound()
|
||||
const resolved = path.resolve(root, relative)
|
||||
if (!isPathInside(root, resolved)) return notFound()
|
||||
const realRoot = await fs.realpath(root).catch(() => null)
|
||||
const realFile = await fs.realpath(resolved).catch(() => null)
|
||||
if (!realRoot || !realFile) return notFound()
|
||||
if (!isPathInside(realRoot, realFile)) return notFound()
|
||||
|
||||
const stat = await fs.stat(realFile)
|
||||
if (!stat.isFile() || stat.size > 20 * 1024 * 1024) return notFound()
|
||||
const body = await fs.readFile(realFile)
|
||||
const contentType =
|
||||
MIME_TYPES[path.extname(realFile).toLowerCase()] || 'application/octet-stream'
|
||||
const resolved = await resolveExtensionProtocolFile(request.url, dependencies)
|
||||
if (!resolved) return notFound()
|
||||
const body = await fs.readFile(resolved.realFile)
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Content-Security-Policy': [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: https:",
|
||||
"media-src 'self' data: https:",
|
||||
"font-src 'self' data:",
|
||||
"connect-src 'none'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'"
|
||||
].join('; '),
|
||||
'Content-Type': resolved.contentType,
|
||||
'Content-Security-Policy': resolved.csp,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Cache-Control': 'no-store'
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { app, safeStorage } from 'electron'
|
||||
import { createHash } from 'node:crypto'
|
||||
import path from 'node:path'
|
||||
import { AIProviderService } from '../services/ai-provider-service'
|
||||
import {
|
||||
@@ -7,18 +8,37 @@ import {
|
||||
isReady,
|
||||
listContacts,
|
||||
listMessagesAsync,
|
||||
resolveMd5
|
||||
resolveMd5,
|
||||
type FormattedMessage
|
||||
} from '../services/chat-service'
|
||||
import { imageInsightService } from '../services/image-insight-service'
|
||||
import { ImageKeyConfigService } from '../services/image-key-config-service'
|
||||
import { imageTextIndexService } from '../services/image-text-index-service'
|
||||
import { personalWechatCapabilityService } from '../services/personal-wechat-capability-service'
|
||||
import { htmlRenderService } from '../services/html-render-service'
|
||||
import { loadSettings } from '../services/settings-store'
|
||||
import { systemOcrService } from '../services/system-ocr-service'
|
||||
import { TextToSpeechSettingsService } from '../services/text-to-speech-settings-service'
|
||||
import { wechatActionGateway } from '../services/wechat-action-gateway'
|
||||
import { ImageDecryptService } from '../image-decrypt-service'
|
||||
import { VideoAssetService } from '../video-asset-service'
|
||||
import { VoiceService } from '../voice-service'
|
||||
import type { VoiceTranscriptionGateway } from '../voice-pipeline/voice-transcription-gateway'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
import type { ExtensionMessageRef } from '../../shared/extensions/media'
|
||||
import type {
|
||||
ExtensionMessagesQueryRequest,
|
||||
ExtensionMessagesQueryResult,
|
||||
ExtensionQueriedMessage
|
||||
} from '../../shared/extensions/rpc'
|
||||
import { checkExtensionSendEntitlement } from './extension-entitlement'
|
||||
import { ExtensionManager } from './extension-manager'
|
||||
import {
|
||||
ExtensionMediaGateway,
|
||||
paginateQueriedMessages,
|
||||
type ResolvedExtensionMediaMessage
|
||||
} from './extension-media-gateway'
|
||||
import { ExtensionMessageRefSigner } from './extension-message-ref-signer'
|
||||
import { getExtensionPaths } from './extension-paths'
|
||||
|
||||
let manager: ExtensionManager | null = null
|
||||
@@ -34,19 +54,281 @@ function resolveTemplateRoot(): string {
|
||||
export interface ExtensionSystemOptions {
|
||||
appVersion: string
|
||||
onChange: (extensionId: string, reason: string) => void
|
||||
getImageDecryptService?: () => ImageDecryptService | null
|
||||
voiceTranscriptionGateway?: Pick<VoiceTranscriptionGateway, 'transcribe' | 'snapshot'>
|
||||
}
|
||||
|
||||
function decodeBase64DataUrl(value: string): { buffer: Buffer; mimeType: string } | null {
|
||||
const match = /^data:(image\/[a-z0-9.+-]+);base64,([a-z0-9+/=]+)$/i.exec(value)
|
||||
if (!match) return null
|
||||
return { mimeType: match[1].toLowerCase(), buffer: Buffer.from(match[2], 'base64') }
|
||||
}
|
||||
|
||||
/** 扩展系统的主进程接线。 */
|
||||
export async function initExtensionSystem(options: ExtensionSystemOptions): Promise<void> {
|
||||
if (manager) return
|
||||
const ttsService = new TextToSpeechSettingsService()
|
||||
|
||||
let fallbackImageService: ImageDecryptService | null = null
|
||||
let fallbackImageKey = ''
|
||||
let fallbackImageClient: ReturnType<
|
||||
NonNullable<ReturnType<typeof getChatDb>>['getWcdb4Client']
|
||||
> | null = null
|
||||
let cachedVoiceService: {
|
||||
client: ReturnType<NonNullable<ReturnType<typeof getChatDb>>['getWcdb4Client']>
|
||||
service: VoiceService
|
||||
} | null = null
|
||||
let cachedVideoService: {
|
||||
client: ReturnType<NonNullable<ReturnType<typeof getChatDb>>['getWcdb4Client']>
|
||||
service: VideoAssetService
|
||||
} | null = null
|
||||
|
||||
const resolveImageDecryptService = (): ImageDecryptService | null => {
|
||||
const injected = options.getImageDecryptService?.()
|
||||
if (injected) return injected
|
||||
const imageConfig = new ImageKeyConfigService().getConfig()
|
||||
const aesKey = imageConfig.aesKey || ''
|
||||
const xorKey = imageConfig.xorKey || '0x40'
|
||||
if (!aesKey) return null
|
||||
const client = getChatDb()?.getWcdb4Client() || null
|
||||
const key = `${xorKey}:${aesKey}`
|
||||
if (
|
||||
!fallbackImageService ||
|
||||
fallbackImageKey !== key ||
|
||||
fallbackImageClient !== client
|
||||
) {
|
||||
fallbackImageService = new ImageDecryptService(xorKey, aesKey, client, loadSettings().dbRoot)
|
||||
fallbackImageKey = key
|
||||
fallbackImageClient = client
|
||||
}
|
||||
return fallbackImageService
|
||||
}
|
||||
|
||||
const resolveVoiceService = (): VoiceService | null => {
|
||||
const client = getChatDb()?.getWcdb4Client()
|
||||
if (!client) return null
|
||||
if (!cachedVoiceService || cachedVoiceService.client !== client) {
|
||||
cachedVoiceService = { client, service: new VoiceService(client) }
|
||||
}
|
||||
return cachedVoiceService.service
|
||||
}
|
||||
|
||||
const resolveVideoService = (): VideoAssetService | null => {
|
||||
const client = getChatDb()?.getWcdb4Client()
|
||||
if (!client) return null
|
||||
if (!cachedVideoService || cachedVideoService.client !== client) {
|
||||
cachedVideoService = { client, service: new VideoAssetService(client) }
|
||||
}
|
||||
return cachedVideoService.service
|
||||
}
|
||||
|
||||
const getAccountId = (): string => String(getSelfAccountInfo()?.wxid || '')
|
||||
const messageRefSigner = new ExtensionMessageRefSigner()
|
||||
|
||||
manager = new ExtensionManager({
|
||||
paths: getExtensionPaths(),
|
||||
appVersion: options.appVersion,
|
||||
getCapability: () => personalWechatCapabilityService.getPersonalWechatSendCapability(),
|
||||
checkEntitlement: () => checkExtensionSendEntitlement(),
|
||||
executeAction: (request) => wechatActionGateway.execute(request),
|
||||
queryMessages: queryConversationMessages,
|
||||
encodeMessageRef: (ref) => messageRefSigner.sign(ref),
|
||||
onAccountChanged: (accountId) => messageRefSigner.syncAccount(accountId),
|
||||
queryMessages: (request) =>
|
||||
queryConversationMessages(request, getAccountId(), (ref) => messageRefSigner.sign(ref)),
|
||||
createMediaGateway: ({ hasPermission, isConversationAllowed, getExtensionDataRoot }) =>
|
||||
new ExtensionMediaGateway({
|
||||
isDatabaseReady: () => {
|
||||
try {
|
||||
return isReady()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
},
|
||||
getAccountId,
|
||||
getExtensionDataRoot,
|
||||
hasPermission,
|
||||
isConversationAllowed,
|
||||
verifySignedRef: (rawRef, expectedAccountId) =>
|
||||
messageRefSigner.verify(rawRef, expectedAccountId),
|
||||
resolveMessage: resolveMediaMessageByRef,
|
||||
readImageData: async (message, quality) => {
|
||||
const service = resolveImageDecryptService()
|
||||
if (!service) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '尚未配置图片解密密钥')
|
||||
}
|
||||
const primaryPath = await service.findImageFileAsync(
|
||||
message.image?.md5,
|
||||
message.image?.datName,
|
||||
{
|
||||
allowThumbnail: quality === 'thumbnail',
|
||||
sessionId: message.conversationId,
|
||||
createTime: message.createTimeSeconds
|
||||
}
|
||||
)
|
||||
const resolvedQuality: 'original' | 'thumbnail' = primaryPath
|
||||
? quality
|
||||
: 'thumbnail'
|
||||
const filePath =
|
||||
primaryPath ||
|
||||
(quality === 'original'
|
||||
? await service.findImageFileAsync(message.image?.md5, message.image?.datName, {
|
||||
allowThumbnail: true,
|
||||
sessionId: message.conversationId,
|
||||
createTime: message.createTimeSeconds
|
||||
})
|
||||
: null)
|
||||
if (!filePath) return null
|
||||
const decoded = await service.decryptImageToBase64WithFallbackAsync(filePath, true)
|
||||
if (!decoded?.data) return null
|
||||
const parsed = decodeBase64DataUrl(decoded.data)
|
||||
if (!parsed) return null
|
||||
return {
|
||||
buffer: parsed.buffer,
|
||||
mimeType: parsed.mimeType,
|
||||
...(message.image?.md5 ? { imageHash: message.image.md5.toLowerCase() } : {}),
|
||||
quality: resolvedQuality
|
||||
}
|
||||
},
|
||||
readVoiceData: async (message) => {
|
||||
const service = resolveVoiceService()
|
||||
if (!service) {
|
||||
throw new ExtensionError('DATABASE_NOT_READY', '微信数据库尚未连接')
|
||||
}
|
||||
const resolved = await service.resolveVoice(
|
||||
message.conversationId,
|
||||
message.localId ?? 0,
|
||||
message.createTimeSeconds,
|
||||
message.serverId
|
||||
)
|
||||
if (!resolved.success || !resolved.data) return null
|
||||
return {
|
||||
wavBuffer: Buffer.from(resolved.data, 'base64'),
|
||||
...(message.voice?.durationSeconds
|
||||
? { durationMs: Math.round(message.voice.durationSeconds * 1000) }
|
||||
: {})
|
||||
}
|
||||
},
|
||||
readVideoAsset: async (message) => {
|
||||
const service = resolveVideoService()
|
||||
if (!service) {
|
||||
throw new ExtensionError('DATABASE_NOT_READY', '微信数据库尚未连接')
|
||||
}
|
||||
const resolved = await service.resolve(message.video?.hashes ?? [], {
|
||||
createTime: message.createTimeSeconds,
|
||||
byteLength: message.video?.byteLength,
|
||||
duration: message.video?.duration,
|
||||
width: message.video?.width,
|
||||
height: message.video?.height
|
||||
})
|
||||
if (!resolved.success || !resolved.url) return null
|
||||
const filePath = service.pathForUrl(resolved.url)
|
||||
if (!filePath) return null
|
||||
const posterPath = resolved.poster ? service.pathForUrl(resolved.poster) : undefined
|
||||
return {
|
||||
filePath,
|
||||
...(posterPath ? { posterPath } : {}),
|
||||
...(message.video?.duration
|
||||
? { durationMs: Math.round(message.video.duration * 1000) }
|
||||
: {}),
|
||||
...(message.video?.width ? { width: message.video.width } : {}),
|
||||
...(message.video?.height ? { height: message.video.height } : {})
|
||||
}
|
||||
},
|
||||
getCachedOcr: (conversationId, messageId) => {
|
||||
const entry = imageTextIndexService.getConversationOcr(conversationId).get(messageId)
|
||||
if (!entry) return null
|
||||
return { text: entry.text, language: null, engine: 'system-ocr' }
|
||||
},
|
||||
recognizeOcr: async (imageDataUrl, language) => {
|
||||
const result = await systemOcrService.recognize({
|
||||
imageDataUrl,
|
||||
...(language ? { language } : {})
|
||||
})
|
||||
return {
|
||||
success: result.success,
|
||||
text: result.text,
|
||||
language: result.language,
|
||||
engine: result.engine,
|
||||
...(result.error ? { error: result.error } : {})
|
||||
}
|
||||
},
|
||||
transcribeVoice: async (reference, opts) => {
|
||||
if (!options.voiceTranscriptionGateway) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '语音转写服务尚未初始化')
|
||||
}
|
||||
const outcomes = await options.voiceTranscriptionGateway.transcribe([reference], opts)
|
||||
if (!outcomes) return null
|
||||
return outcomes[0] ?? null
|
||||
},
|
||||
analyzeImage: async (input) => {
|
||||
const accountScope = createHash('sha256')
|
||||
.update(getAccountId() || 'unknown')
|
||||
.digest('hex')
|
||||
.slice(0, 12)
|
||||
if (!input.prompt) {
|
||||
const response = await imageInsightService.analyze({
|
||||
messageId: input.messageId,
|
||||
imageHash: `${accountScope}:${input.imageHash}`,
|
||||
imageDataUrl: input.imageDataUrl,
|
||||
sender: input.senderName,
|
||||
sentAt: input.sentAt,
|
||||
sessionId: input.conversationId,
|
||||
force: input.force
|
||||
})
|
||||
if (!response.success || !response.insight) {
|
||||
throw new ExtensionError(
|
||||
'CAPABILITY_UNAVAILABLE',
|
||||
response.error || 'AI 图片理解调用失败'
|
||||
)
|
||||
}
|
||||
return {
|
||||
description: response.insight.description,
|
||||
...(response.insight.ocrText ? { ocrText: response.insight.ocrText } : {}),
|
||||
...(response.insight.tags?.length ? { tags: response.insight.tags } : {}),
|
||||
...(response.insight.category ? { category: response.insight.category } : {}),
|
||||
...(response.insight.model ? { model: response.insight.model } : {}),
|
||||
cached: response.fromCache === true
|
||||
}
|
||||
}
|
||||
const provider = new AIProviderService()
|
||||
const runtime = provider.getVisionRuntimeConfig()
|
||||
if (!runtime.configured || !runtime.providerId || !runtime.model) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '尚未配置支持图片理解的 AI 模型')
|
||||
}
|
||||
const result = await provider.analyzeImage(
|
||||
[
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: input.prompt },
|
||||
{ type: 'image', dataUrl: input.imageDataUrl }
|
||||
]
|
||||
}
|
||||
],
|
||||
{ providerId: runtime.providerId, modelId: runtime.model }
|
||||
)
|
||||
if (!result.success || !result.data) {
|
||||
throw new ExtensionError('CAPABILITY_UNAVAILABLE', result.error || 'AI 图片理解调用失败')
|
||||
}
|
||||
return {
|
||||
description: result.data.trim(),
|
||||
model: runtime.modelName || runtime.model,
|
||||
cached: false
|
||||
}
|
||||
}
|
||||
}),
|
||||
renderHtmlToImage: (extensionId, extensionDataRoot, request) =>
|
||||
htmlRenderService.renderExtensionHtmlToPng({
|
||||
extensionId,
|
||||
html: request.html,
|
||||
css: request.css,
|
||||
extensionDataRoot,
|
||||
fileName: request.fileName,
|
||||
width: request.width,
|
||||
maxHeight: request.maxHeight,
|
||||
backgroundColor: request.backgroundColor,
|
||||
timeoutMs: request.timeoutMs
|
||||
}),
|
||||
listGroups: async () => {
|
||||
try {
|
||||
return listContacts()
|
||||
@@ -109,7 +391,7 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom
|
||||
cleanupVoice: (filePath) => {
|
||||
ttsService.removeGeneratedAudio(filePath)
|
||||
},
|
||||
getAccountId: () => String(getSelfAccountInfo()?.wxid || ''),
|
||||
getAccountId,
|
||||
getSelfUsernames: () => {
|
||||
try {
|
||||
return (getChatDb()?.getWcdb4Client()?.getMyUsernameCandidates?.() ?? []).filter(Boolean)
|
||||
@@ -169,24 +451,114 @@ function normalizeQueriedMessageType(rawType: string | undefined): {
|
||||
return { type: value || 'other', isTextLike: false }
|
||||
}
|
||||
|
||||
function toResolvedMediaMessage(
|
||||
conversationId: string,
|
||||
message: FormattedMessage
|
||||
): ResolvedExtensionMediaMessage {
|
||||
const normalized = normalizeQueriedMessageType(message.type)
|
||||
const contentData = message.contentData
|
||||
const mediaType: ResolvedExtensionMediaMessage['type'] =
|
||||
normalized.type === 'image' || contentData?.type === 'image'
|
||||
? 'image'
|
||||
: normalized.type === 'voice' || contentData?.type === 'voice'
|
||||
? 'voice'
|
||||
: normalized.type === 'video' || contentData?.type === 'video'
|
||||
? 'video'
|
||||
: 'other'
|
||||
|
||||
const videoHashes =
|
||||
contentData?.type === 'video'
|
||||
? [contentData.md5, contentData.newMd5, contentData.rawMd5]
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
: []
|
||||
|
||||
return {
|
||||
messageId: message.serverId || String(message.localId ?? message.id),
|
||||
...(message.localId !== undefined ? { localId: message.localId } : {}),
|
||||
...(message.serverId ? { serverId: message.serverId } : {}),
|
||||
conversationId,
|
||||
...(message.name ? { senderName: message.name } : {}),
|
||||
type: mediaType,
|
||||
createTimeSeconds: message.createTime ?? 0,
|
||||
...(contentData?.type === 'image'
|
||||
? { image: { md5: contentData.md5, datName: contentData.datName } }
|
||||
: {}),
|
||||
...(mediaType === 'voice'
|
||||
? {
|
||||
voice: {
|
||||
durationSeconds:
|
||||
message.voiceDuration ??
|
||||
(contentData?.type === 'voice' ? contentData.duration : undefined)
|
||||
}
|
||||
}
|
||||
: {}),
|
||||
...(contentData?.type === 'video'
|
||||
? {
|
||||
video: {
|
||||
hashes: videoHashes,
|
||||
byteLength: contentData.byteLength,
|
||||
duration: contentData.duration,
|
||||
width: contentData.width,
|
||||
height: contentData.height
|
||||
}
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
function matchesRef(message: FormattedMessage, ref: ExtensionMessageRef): boolean {
|
||||
const canonicalId = message.serverId || String(message.localId ?? message.id)
|
||||
if (canonicalId === ref.messageId) return true
|
||||
if (message.serverId && message.serverId === ref.messageId) return true
|
||||
if (ref.localId && message.localId !== undefined && String(message.localId) === ref.localId) {
|
||||
return true
|
||||
}
|
||||
if (message.localId !== undefined && String(message.localId) === ref.messageId) return true
|
||||
return message.id === ref.messageId
|
||||
}
|
||||
|
||||
/** 结合 messageRef 的时间戳先查窄窗口,未命中再回退宽窗口,避免扫描整个会话。 */
|
||||
async function resolveMediaMessageByRef(
|
||||
ref: ExtensionMessageRef
|
||||
): Promise<ResolvedExtensionMediaMessage | null> {
|
||||
const contact = resolveMd5(ref.conversationId)
|
||||
if (!contact?.md5) return null
|
||||
const nowSec = Math.floor(Date.now() / 1000)
|
||||
const centerSec = ref.timestamp ? Math.floor(ref.timestamp / 1000) : nowSec
|
||||
const windows: Array<[number, number]> = ref.timestamp
|
||||
? [
|
||||
[Math.max(0, centerSec - 15), centerSec + 15],
|
||||
[Math.max(0, centerSec - 300), centerSec + 300]
|
||||
]
|
||||
: [[Math.max(0, nowSec - 86_400), nowSec + 60]]
|
||||
|
||||
for (const [startSec, endSec] of windows) {
|
||||
const rows = await listMessagesAsync(contact.md5, startSec, endSec, undefined, '', 'unknown')
|
||||
const matched = rows.find((item) => matchesRef(item, ref))
|
||||
if (matched) return toResolvedMediaMessage(ref.conversationId, matched)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function queryConversationMessages(
|
||||
request: ExtensionMessagesQueryRequest
|
||||
): Promise<ExtensionQueriedMessage[]> {
|
||||
request: ExtensionMessagesQueryRequest,
|
||||
accountId: string,
|
||||
encodeRef: (ref: ExtensionMessageRef) => string
|
||||
): Promise<ExtensionMessagesQueryResult> {
|
||||
const contact = resolveMd5(request.conversationId)
|
||||
if (!contact?.md5) throw new ExtensionError('DATABASE_NOT_READY', '找不到该会话或数据库未连接')
|
||||
const limit = Math.max(1, Math.min(Number(request.limit) || 50, 500))
|
||||
const startMs = request.startTime ?? Date.now() - 86_400_000
|
||||
const endMs = request.endTime ?? Date.now()
|
||||
const rawMessages = await listMessagesAsync(
|
||||
contact.md5,
|
||||
Math.floor((request.startTime ?? Date.now() - 86_400_000) / 1000),
|
||||
Math.floor((request.endTime ?? Date.now()) / 1000),
|
||||
Math.floor(startMs / 1000),
|
||||
Math.ceil(endMs / 1000),
|
||||
undefined,
|
||||
'',
|
||||
'unknown'
|
||||
)
|
||||
const sorted = [...rawMessages]
|
||||
.sort((left, right) => (left.createTime ?? 0) - (right.createTime ?? 0))
|
||||
.slice(-limit)
|
||||
return sorted.map((message) => {
|
||||
const mapped: ExtensionQueriedMessage[] = rawMessages.map((message) => {
|
||||
const normalizedType = normalizeQueriedMessageType(message.type)
|
||||
const quoteText =
|
||||
message.contentData &&
|
||||
@@ -196,17 +568,28 @@ async function queryConversationMessages(
|
||||
? message.contentData.content
|
||||
: ''
|
||||
const resolvedText = String(message.content || quoteText || '').trim()
|
||||
const messageId = message.serverId || String(message.localId ?? message.id)
|
||||
const timestamp = Math.round((message.createTime ?? 0) * 1000)
|
||||
const messageRef = encodeRef({
|
||||
accountId,
|
||||
conversationId: request.conversationId,
|
||||
messageId,
|
||||
...(message.localId !== undefined ? { localId: String(message.localId) } : {}),
|
||||
timestamp
|
||||
})
|
||||
return {
|
||||
messageId: message.serverId || String(message.localId ?? message.id),
|
||||
messageId,
|
||||
messageRef,
|
||||
conversationId: request.conversationId,
|
||||
...(message.senderId ? { senderId: message.senderId } : {}),
|
||||
...(message.name ? { senderName: message.name } : {}),
|
||||
isSelf: message.isSender === true,
|
||||
type: normalizedType.type,
|
||||
...(normalizedType.isTextLike && resolvedText ? { text: resolvedText } : {}),
|
||||
timestamp: Math.round((message.createTime ?? 0) * 1000)
|
||||
timestamp
|
||||
}
|
||||
})
|
||||
return paginateQueriedMessages(mapped, request)
|
||||
}
|
||||
|
||||
async function chatWithConfiguredProvider(
|
||||
|
||||
@@ -146,14 +146,86 @@ const tm = {
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
limit?: number
|
||||
}): Promise<{ messages: unknown[] }> {
|
||||
cursor?: string
|
||||
order?: 'asc' | 'desc'
|
||||
types?: string[]
|
||||
}): Promise<{ messages: unknown[]; nextCursor?: string; hasMore?: boolean }> {
|
||||
requirePermission('messages.query')
|
||||
const result = (await callHost('messages.query', { ...request }, 25_000)) as {
|
||||
messages: unknown[]
|
||||
nextCursor?: string
|
||||
hasMore?: boolean
|
||||
}
|
||||
return result
|
||||
}
|
||||
},
|
||||
media: {
|
||||
async readImage(request: { messageRef: string; quality?: 'original' | 'thumbnail' }) {
|
||||
requirePermission('media.read')
|
||||
return callHost('media.readImage', { ...request }, 20_000)
|
||||
},
|
||||
async readVoice(request: { messageRef: string }) {
|
||||
requirePermission('media.read')
|
||||
return callHost('media.readVoice', { ...request }, 25_000)
|
||||
},
|
||||
async readVideo(request: { messageRef: string }) {
|
||||
requirePermission('media.read')
|
||||
return callHost('media.readVideo', { ...request }, 35_000)
|
||||
},
|
||||
async ocrImage(request: { messageRef: string; language?: string; force?: boolean }) {
|
||||
requirePermission('media.ocr')
|
||||
return callHost('media.ocrImage', { ...request }, 30_000)
|
||||
},
|
||||
async transcribeVoice(request: { messageRef: string; force?: boolean; waitMs?: number }) {
|
||||
requirePermission('media.transcribe')
|
||||
return callHost('media.transcribeVoice', { ...request }, 35_000)
|
||||
},
|
||||
async analyzeImage(request: { messageRef: string; prompt?: string; force?: boolean }) {
|
||||
requirePermission('ai.vision')
|
||||
return callHost('media.analyzeImage', { ...request }, 65_000)
|
||||
},
|
||||
async batch(request: {
|
||||
items: Array<{ op: string; messageRef: string; options?: Record<string, unknown> }>
|
||||
concurrency?: number
|
||||
}) {
|
||||
return callHost('media.batch', { ...request }, 120_000)
|
||||
}
|
||||
},
|
||||
render: {
|
||||
async htmlToImage(request: {
|
||||
html: string
|
||||
css?: string
|
||||
fileName?: string
|
||||
width?: number
|
||||
maxHeight?: number
|
||||
backgroundColor?: string
|
||||
timeoutMs?: number
|
||||
}) {
|
||||
requirePermission('render.html')
|
||||
return callHost('render.htmlToImage', { ...request }, 50_000)
|
||||
}
|
||||
},
|
||||
notifications: {
|
||||
async create(request: {
|
||||
title: string
|
||||
body?: string
|
||||
level?: 'info' | 'success' | 'warning' | 'error'
|
||||
dedupeKey?: string
|
||||
pageId?: string
|
||||
}) {
|
||||
requirePermission('notifications.create')
|
||||
return callHost('notifications.create', { ...request }, 8_000)
|
||||
},
|
||||
async list() {
|
||||
requirePermission('notifications.create')
|
||||
const result = (await callHost('notifications.list', {}, 8_000)) as { items?: unknown[] }
|
||||
return Array.isArray(result?.items) ? result.items : []
|
||||
},
|
||||
async markRead(request: { id?: string; all?: boolean } = {}) {
|
||||
requirePermission('notifications.create')
|
||||
return callHost('notifications.markRead', { ...request }, 8_000)
|
||||
}
|
||||
},
|
||||
wechat: {
|
||||
/** 发送文本、图片、视频或语音。 */
|
||||
async send(request: {
|
||||
@@ -222,6 +294,10 @@ const tm = {
|
||||
async chat(messages: Array<{ role: string; content: string }>) {
|
||||
requirePermission('ai.chat')
|
||||
return (await callHost('ai.chat', { messages }, 60_000)) as { text: string }
|
||||
},
|
||||
async analyzeImage(request: { messageRef: string; prompt?: string; force?: boolean }) {
|
||||
requirePermission('ai.vision')
|
||||
return callHost('media.analyzeImage', { ...request }, 65_000)
|
||||
}
|
||||
},
|
||||
storage: {
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { app, BrowserWindow } from 'electron'
|
||||
import crypto from 'node:crypto'
|
||||
import { appendFileSync } from 'node:fs'
|
||||
import fs from 'fs-extra'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
GroupReportExportRequest,
|
||||
GroupReportExportResult,
|
||||
@@ -23,6 +21,7 @@ import { getReportTemplate } from '../shared/report-templates'
|
||||
import type { ReportTemplateRef } from '../shared/report-template-package'
|
||||
import { injectReportTemplateFragmentContract } from '../shared/report-template-fragment-contract'
|
||||
import { reportTemplateService, validateReportTemplateHtml } from './report-template-service'
|
||||
import { htmlRenderService } from './services/html-render-service'
|
||||
|
||||
const LEGACY_TEMPLATE_FILES: Record<string, string> = {
|
||||
v1: 'mobile_daily_report_v1.html',
|
||||
@@ -1017,95 +1016,21 @@ const captureFullPage = async (
|
||||
const maxCaptureWidth = LEGACY_TEMPLATE_FILES[templateId || ''] ? 1200 : template.maxCaptureWidth
|
||||
const maxCaptureHeight = templateOverride?.maxCaptureHeight || 20000
|
||||
console.log(`[GroupReport] capture begin html=${htmlPath}`)
|
||||
const reportSessionPartition = `report-template-${crypto.randomUUID()}`
|
||||
const reportWindow = new BrowserWindow({
|
||||
show: false,
|
||||
opacity: 0,
|
||||
skipTaskbar: true,
|
||||
const result = await htmlRenderService.renderFileToPng({
|
||||
htmlPath,
|
||||
pngPath,
|
||||
width: captureWidth,
|
||||
height: 800,
|
||||
frame: false,
|
||||
maxWidth: maxCaptureWidth,
|
||||
minHeight: 800,
|
||||
maxHeight: maxCaptureHeight,
|
||||
backgroundColor: '#f3f5f7',
|
||||
webPreferences: {
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
partition: reportSessionPartition
|
||||
minPngBytes: 1000,
|
||||
onBlockedRequest: (details, reason) => {
|
||||
recordBlockedTemplateRequest(details as Electron.OnBeforeRequestListenerDetails, reason)
|
||||
}
|
||||
})
|
||||
const allowedDocumentPath = path.resolve(htmlPath)
|
||||
const requestHandler = (
|
||||
details: Electron.OnBeforeRequestListenerDetails,
|
||||
callback: (response: { cancel: boolean }) => void
|
||||
): void => {
|
||||
if (details.url.startsWith('file:')) {
|
||||
try {
|
||||
const requestedPath = path.resolve(fileURLToPath(details.url))
|
||||
if (requestedPath === allowedDocumentPath) {
|
||||
callback({ cancel: false })
|
||||
} else {
|
||||
recordBlockedTemplateRequest(details, 'file-path-not-allowed')
|
||||
callback({ cancel: true })
|
||||
}
|
||||
} catch {
|
||||
recordBlockedTemplateRequest(details, 'invalid-file-url')
|
||||
callback({ cancel: true })
|
||||
}
|
||||
return
|
||||
}
|
||||
recordBlockedTemplateRequest(details, 'scheme-not-allowed')
|
||||
callback({ cancel: true })
|
||||
}
|
||||
reportWindow.webContents.session.webRequest.onBeforeRequest(
|
||||
{ urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*', 'file://*/*'] },
|
||||
requestHandler
|
||||
)
|
||||
reportWindow.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
|
||||
reportWindow.webContents.on('will-navigate', (event) => event.preventDefault())
|
||||
|
||||
try {
|
||||
const readyToShow = new Promise<void>((resolve) => reportWindow.once('ready-to-show', resolve))
|
||||
await reportWindow.loadFile(htmlPath)
|
||||
await readyToShow
|
||||
console.log('[GroupReport] capture loaded html')
|
||||
await reportWindow.webContents.executeJavaScript(`Promise.all([
|
||||
document.fonts.ready,
|
||||
...Array.from(document.images).map((img) => img.complete ? Promise.resolve() : new Promise((resolve) => {
|
||||
img.addEventListener('load', resolve, { once: true });
|
||||
img.addEventListener('error', resolve, { once: true });
|
||||
}))
|
||||
])`)
|
||||
console.log('[GroupReport] capture assets ready')
|
||||
const metrics = (await reportWindow.webContents.executeJavaScript(`({
|
||||
width: Math.ceil(Math.max(document.documentElement.scrollWidth, document.body.scrollWidth, ${captureWidth})),
|
||||
height: Math.ceil(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, 800))
|
||||
})`)) as { width: number; height: number }
|
||||
const width = Math.max(captureWidth, Math.min(maxCaptureWidth, Math.ceil(metrics.width)))
|
||||
const height = Math.max(800, Math.min(maxCaptureHeight, Math.ceil(metrics.height)))
|
||||
const [currentWidth, currentHeight] = reportWindow.getContentSize()
|
||||
if (currentWidth !== width || currentHeight !== height) {
|
||||
const resized = new Promise<void>((resolve) => reportWindow.once('resize', resolve))
|
||||
reportWindow.setContentSize(width, height)
|
||||
await resized
|
||||
}
|
||||
await reportWindow.webContents.executeJavaScript(
|
||||
'new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))'
|
||||
)
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
console.log(`[GroupReport] capture native page width=${width} height=${height}`)
|
||||
const image = await reportWindow.webContents.capturePage(
|
||||
{ x: 0, y: 0, width, height },
|
||||
{ stayHidden: true }
|
||||
)
|
||||
const png = image.toPNG()
|
||||
if (png.length < 1000) throw new Error('生成的日报图片为空')
|
||||
await fs.writeFile(pngPath, png)
|
||||
console.log(`[GroupReport] capture ok bytes=${png.length} png=${pngPath}`)
|
||||
return `data:image/png;base64,${png.toString('base64')}`
|
||||
} finally {
|
||||
reportWindow.webContents.session.webRequest.onBeforeRequest(null)
|
||||
reportWindow.destroy()
|
||||
}
|
||||
console.log(`[GroupReport] capture ok bytes=${result.bytes} png=${pngPath}`)
|
||||
return result.imageDataUrl
|
||||
}
|
||||
|
||||
export const exportGroupReport = async (
|
||||
|
||||
+333
-3
@@ -39,6 +39,7 @@ import { LocalAgentApiError, LocalAgentApiService } from './services/local-agent
|
||||
import { wechatActionGateway } from './services/wechat-action-gateway'
|
||||
import type { WechatActionRequest, WechatActionResult } from '../shared/wechat-action'
|
||||
import type { PersonalWechatSendCapability } from '../shared/personal-wechat'
|
||||
import { WECHAT_SEND_TYPES, type WechatSendType } from '../shared/wechat-send'
|
||||
import type { GroupStatsService } from './services/group-stats-service'
|
||||
import { encodeMessageRef } from '../shared/local-query-api'
|
||||
import type {
|
||||
@@ -47,6 +48,15 @@ import type {
|
||||
VoiceTranscriptState
|
||||
} from '../shared/voice-recognition'
|
||||
import { voiceMessageReferenceOf } from './voice-pipeline/voice-message-identity'
|
||||
import type {
|
||||
MessageBackfillReport,
|
||||
MessageBrokerStatus,
|
||||
MessageEventBroker,
|
||||
MessageEventRecord,
|
||||
MessageGap,
|
||||
MessageSubscription
|
||||
} from './services/message-event-broker'
|
||||
import type { AgentTaskRecord, AgentTaskView } from '../shared/agent-task'
|
||||
|
||||
export const DEFAULT_HTTP_HOST = '127.0.0.1'
|
||||
export const DEFAULT_HTTP_PORT = 6131
|
||||
@@ -83,14 +93,41 @@ export interface HttpServerOptions {
|
||||
appVersionProvider?: () => string
|
||||
wechatSendCapabilityProvider?: () => Promise<PersonalWechatSendCapability>
|
||||
wechatSendExecutor?: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
/** 实时消息事件代理。未注入时 `/api/v1/events/messages` 返回 503。 */
|
||||
messageEventBroker?: MessageEventBroker
|
||||
/** SSE 心跳间隔(毫秒)。测试用;生产默认 15s。 */
|
||||
messageEventsHeartbeatMs?: number
|
||||
}
|
||||
|
||||
let configuredQueryApiService: LocalQueryApiService | undefined
|
||||
let configuredGroupStatsService: Pick<GroupStatsService, 'getMemberStats'> | undefined
|
||||
let configuredMessageEventBroker: MessageEventBroker | undefined
|
||||
export function setLocalQueryApiService(service: LocalQueryApiService | undefined): void {
|
||||
configuredQueryApiService = service
|
||||
}
|
||||
|
||||
/**
|
||||
* 注入实时消息事件代理。
|
||||
*
|
||||
* 刻意用模块级注入而不是每次 `startHttpServer` 传参:API server 可能在数据库
|
||||
* 初始化之前启动,事件代理必须在数据库就绪前就存在,才能在 SSE 里如实报告
|
||||
* `database: unavailable` 而不是把连接直接打回 503。
|
||||
*/
|
||||
export function setMessageEventBroker(broker: MessageEventBroker | undefined): void {
|
||||
configuredMessageEventBroker = broker
|
||||
}
|
||||
|
||||
export interface AgentTaskInspector {
|
||||
list(limit: number): AgentTaskRecord[]
|
||||
get(id: string): AgentTaskRecord | undefined
|
||||
}
|
||||
|
||||
let configuredAgentTaskInspector: AgentTaskInspector | undefined
|
||||
/** 注入只读任务视图。写入仍由 AgentTaskDispatcher 独占。 */
|
||||
export function setAgentTaskInspector(inspector: AgentTaskInspector | undefined): void {
|
||||
configuredAgentTaskInspector = inspector
|
||||
}
|
||||
|
||||
export function setLocalGroupStatsService(
|
||||
service: Pick<GroupStatsService, 'getMemberStats'> | undefined
|
||||
): void {
|
||||
@@ -587,8 +624,9 @@ 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', 'file'] as const
|
||||
type WechatSendContentType = (typeof WECHAT_SEND_CONTENT_TYPES)[number]
|
||||
// 白名单真源在 `shared/wechat-send.ts`;这里只做别名,避免第二份清单漂移。
|
||||
const WECHAT_SEND_CONTENT_TYPES = WECHAT_SEND_TYPES
|
||||
type WechatSendContentType = WechatSendType
|
||||
|
||||
interface WechatSendApiDependencies {
|
||||
getCapability: () => Promise<PersonalWechatSendCapability>
|
||||
@@ -1364,6 +1402,267 @@ function createAgentApiRoute(
|
||||
})
|
||||
}
|
||||
|
||||
const MESSAGE_EVENTS_ROUTE = '/api/v1/events/messages'
|
||||
const AGENT_TASKS_ROUTE = '/api/v1/agent-tasks'
|
||||
const DEFAULT_MESSAGE_EVENTS_HEARTBEAT_MS = 15_000
|
||||
const MESSAGE_EVENTS_MAX_FILTERS = 20
|
||||
|
||||
/** SSE 连接句柄:`close` 优雅结束,`destroy` 用于服务停止时强制释放。 */
|
||||
interface MessageEventStreamHandle {
|
||||
close(): void
|
||||
destroy(): void
|
||||
}
|
||||
|
||||
function writeSseFrame(
|
||||
res: ServerResponse,
|
||||
frame: { id?: string; event?: string; data?: unknown }
|
||||
): boolean {
|
||||
try {
|
||||
let text = ''
|
||||
if (frame.id) text += `id: ${frame.id}\n`
|
||||
if (frame.event) text += `event: ${frame.event}\n`
|
||||
if (frame.data !== undefined) text += `data: ${JSON.stringify(frame.data)}\n`
|
||||
res.write(`${text}\n`)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析会话过滤参数。
|
||||
*
|
||||
* 只接受 `conversation_id` / `conversation_ids`(可重复、可逗号分隔),
|
||||
* 值必须是会话 md5 —— 与 `messageRef.c` 同口径。username 不接受:
|
||||
* 事件层无法把 username 当作稳定会话标识交给下游。
|
||||
*/
|
||||
function parseConversationFilter(url: URL): string[] {
|
||||
const raw = [
|
||||
...url.searchParams.getAll('conversation_id'),
|
||||
...url.searchParams.getAll('conversation_ids')
|
||||
]
|
||||
const ids: string[] = []
|
||||
for (const value of raw) {
|
||||
for (const part of value.split(',')) {
|
||||
const trimmed = part.trim()
|
||||
if (!trimmed) continue
|
||||
if (!/^[A-Za-z0-9_-]{1,128}$/.test(trimmed)) {
|
||||
throw new Error('会话标识格式无效:需要 conversation md5')
|
||||
}
|
||||
if (!ids.includes(trimmed)) ids.push(trimmed)
|
||||
}
|
||||
}
|
||||
if (ids.length > MESSAGE_EVENTS_MAX_FILTERS) {
|
||||
throw new Error(`conversation_id 最多 ${MESSAGE_EVENTS_MAX_FILTERS} 个`)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
function createMessageEventsRoute(
|
||||
pathname: string,
|
||||
brokerProvider: () => MessageEventBroker | undefined,
|
||||
trackStream: (handle: MessageEventStreamHandle) => () => void,
|
||||
heartbeatMs: number
|
||||
): RouteHandler | undefined {
|
||||
if (pathname !== MESSAGE_EVENTS_ROUTE) return undefined
|
||||
|
||||
return withMethods(['GET'], async ({ req, res, url }) => {
|
||||
const broker = brokerProvider()
|
||||
if (!broker) {
|
||||
return sendJson(res, 503, {
|
||||
error: 'events_unavailable',
|
||||
message: '实时消息事件服务尚未就绪'
|
||||
})
|
||||
}
|
||||
|
||||
let conversationIds: string[]
|
||||
try {
|
||||
conversationIds = parseConversationFilter(url)
|
||||
} catch (error) {
|
||||
return sendError(res, 400, error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
|
||||
const headerLastEventId = req.headers['last-event-id']
|
||||
const lastEventId =
|
||||
(typeof headerLastEventId === 'string' ? headerLastEventId : undefined) ||
|
||||
url.searchParams.get('last_event_id') ||
|
||||
undefined
|
||||
const backfillEnabled = url.searchParams.get('backfill') !== '0'
|
||||
const filterMode = conversationIds.length > 0 ? 'conversation' : 'all'
|
||||
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Cache-Control': 'no-cache, no-transform',
|
||||
Connection: 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
'X-Request-Id': String(res.getHeader('X-Request-Id') || '')
|
||||
})
|
||||
res.flushHeaders?.()
|
||||
req.socket?.setNoDelay(true)
|
||||
// 重连间隔由服务端给出,客户端不必自己猜。
|
||||
res.write('retry: 3000\n\n')
|
||||
|
||||
let closed = false
|
||||
let subscription: MessageSubscription | null = null
|
||||
let heartbeat: ReturnType<typeof setInterval> | null = null
|
||||
let untrack: (() => void) | null = null
|
||||
|
||||
const cleanup = (): void => {
|
||||
if (closed) return
|
||||
closed = true
|
||||
if (heartbeat) {
|
||||
clearInterval(heartbeat)
|
||||
heartbeat = null
|
||||
}
|
||||
subscription?.close()
|
||||
untrack?.()
|
||||
try {
|
||||
res.end()
|
||||
} catch {
|
||||
// 连接可能已经被对端关掉,这里只是幂等收尾。
|
||||
}
|
||||
}
|
||||
|
||||
const destroy = (): void => {
|
||||
cleanup()
|
||||
try {
|
||||
res.destroy()
|
||||
} catch {
|
||||
// 同上。
|
||||
}
|
||||
}
|
||||
|
||||
untrack = trackStream({ close: cleanup, destroy })
|
||||
req.on('close', cleanup)
|
||||
res.on('close', cleanup)
|
||||
res.on('error', cleanup)
|
||||
|
||||
try {
|
||||
subscription = broker.subscribe(
|
||||
{ conversationIds, lastEventId, backfill: backfillEnabled },
|
||||
{
|
||||
onStatus(status: MessageBrokerStatus & { subscriptionId: string }) {
|
||||
writeSseFrame(res, {
|
||||
event: 'status',
|
||||
data: {
|
||||
...status,
|
||||
filter: filterMode,
|
||||
conversationCount: conversationIds.length,
|
||||
heartbeatMs,
|
||||
backfill: backfillEnabled ? 'enabled' : 'disabled'
|
||||
}
|
||||
})
|
||||
},
|
||||
onEvent(event: MessageEventRecord, origin: 'live' | 'replay' | 'db_backfill') {
|
||||
if (closed) return
|
||||
if (
|
||||
!writeSseFrame(res, {
|
||||
id: String(event.seq),
|
||||
event: 'message',
|
||||
data: { ...event, origin }
|
||||
})
|
||||
) {
|
||||
cleanup()
|
||||
}
|
||||
},
|
||||
onGap(gap: MessageGap) {
|
||||
writeSseFrame(res, { event: 'gap', data: gap })
|
||||
},
|
||||
onBackfill(report: MessageBackfillReport) {
|
||||
// 明确告知客户端这次回补是否被上限截断,不能把部分回补当成全部。
|
||||
writeSseFrame(res, { event: 'backfill', data: report })
|
||||
}
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
writeSseFrame(res, {
|
||||
event: 'error',
|
||||
data: {
|
||||
error: 'too_many_subscribers',
|
||||
message: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
})
|
||||
cleanup()
|
||||
return
|
||||
}
|
||||
|
||||
let lastDatabase = broker.status().database
|
||||
heartbeat = setInterval(() => {
|
||||
if (closed) return
|
||||
res.write(`: heartbeat ${Date.now()}\n\n`)
|
||||
/*
|
||||
* 数据库断开/重连不是错误,是订阅状态的一部分:
|
||||
* 只在这个状态真的变化时补发一条 status,避免每 15s 刷一次无信息事件。
|
||||
*/
|
||||
const nextDatabase = broker.status().database
|
||||
if (nextDatabase !== lastDatabase) {
|
||||
lastDatabase = nextDatabase
|
||||
writeSseFrame(res, {
|
||||
event: 'status',
|
||||
data: { ...broker.status(), subscriptionId: subscription?.id ?? '', filter: filterMode }
|
||||
})
|
||||
}
|
||||
}, heartbeatMs)
|
||||
heartbeat.unref?.()
|
||||
})
|
||||
}
|
||||
|
||||
/** 记录 → 对外视图。`triggerKey` 属于内部幂等键,不对外暴露。 */
|
||||
function toAgentTaskView(record: AgentTaskRecord): AgentTaskView {
|
||||
return {
|
||||
id: record.id,
|
||||
provider: record.provider,
|
||||
conversationId: record.conversationId,
|
||||
status: record.status,
|
||||
prompt: record.prompt,
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
...(record.submittedAt !== undefined ? { submittedAt: record.submittedAt } : {}),
|
||||
...(record.completedAt !== undefined ? { completedAt: record.completedAt } : {}),
|
||||
...(record.externalMessageId ? { externalMessageId: record.externalMessageId } : {}),
|
||||
...(record.errorKind ? { errorKind: record.errorKind } : {}),
|
||||
...(record.errorMessage ? { errorMessage: record.errorMessage } : {}),
|
||||
replies: record.replies
|
||||
}
|
||||
}
|
||||
|
||||
function createAgentTaskRoute(
|
||||
pathname: string,
|
||||
inspectorProvider: () => AgentTaskInspector | undefined
|
||||
): RouteHandler | undefined {
|
||||
if (pathname === AGENT_TASKS_ROUTE) {
|
||||
return withMethods(['GET'], ({ res, url }) => {
|
||||
const inspector = inspectorProvider()
|
||||
if (!inspector) return sendError(res, 503, '任务服务尚未就绪')
|
||||
const requested = Number(url.searchParams.get('limit') ?? '20')
|
||||
const limit = Number.isFinite(requested)
|
||||
? Math.max(1, Math.min(Math.floor(requested), 100))
|
||||
: 20
|
||||
const tasks = inspector.list(limit).map(toAgentTaskView)
|
||||
sendJson(res, 200, { count: tasks.length, tasks })
|
||||
})
|
||||
}
|
||||
|
||||
const prefix = `${AGENT_TASKS_ROUTE}/`
|
||||
if (!pathname.startsWith(prefix)) return undefined
|
||||
const rawId = pathname.slice(prefix.length)
|
||||
if (!rawId || rawId.includes('/')) return undefined
|
||||
|
||||
return withMethods(['GET'], ({ res }) => {
|
||||
const inspector = inspectorProvider()
|
||||
if (!inspector) return sendError(res, 503, '任务服务尚未就绪')
|
||||
let id: string
|
||||
try {
|
||||
id = decodeURIComponent(rawId)
|
||||
} catch {
|
||||
return sendError(res, 400, '任务 ID 无效')
|
||||
}
|
||||
const task = inspector.get(id)
|
||||
if (!task) return sendError(res, 404, '任务不存在')
|
||||
sendJson(res, 200, { task: toAgentTaskView(task) })
|
||||
})
|
||||
}
|
||||
|
||||
function requestIdFor(req: IncomingMessage): string {
|
||||
const incoming = req.headers['x-request-id']
|
||||
return typeof incoming === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(incoming)
|
||||
@@ -1396,6 +1695,13 @@ export function startHttpServer(
|
||||
(() => personalWechatCapabilityService.getPersonalWechatSendCapability()),
|
||||
execute: options.wechatSendExecutor || ((request) => wechatActionGateway.execute(request))
|
||||
}
|
||||
const messageEventBroker = options.messageEventBroker
|
||||
? () => options.messageEventBroker
|
||||
: () => configuredMessageEventBroker
|
||||
const messageEventsHeartbeatMs =
|
||||
options.messageEventsHeartbeatMs ?? DEFAULT_MESSAGE_EVENTS_HEARTBEAT_MS
|
||||
/** 活着的 SSE 连接。`server.close()` 会等长连接自然结束,必须先主动释放。 */
|
||||
const eventStreams = new Set<MessageEventStreamHandle>()
|
||||
return new Promise((resolve, reject) => {
|
||||
const server: Server = http.createServer(async (req, res) => {
|
||||
const requestId = requestIdFor(req)
|
||||
@@ -1419,6 +1725,16 @@ export function startHttpServer(
|
||||
createAgentApiRoute(url.pathname, agentApi) ||
|
||||
createWechatSendRoute(url.pathname, wechatSendApi) ||
|
||||
createScheduledReportRoute(url.pathname, scheduledReportApi) ||
|
||||
createMessageEventsRoute(
|
||||
url.pathname,
|
||||
messageEventBroker,
|
||||
(handle) => {
|
||||
eventStreams.add(handle)
|
||||
return () => eventStreams.delete(handle)
|
||||
},
|
||||
messageEventsHeartbeatMs
|
||||
) ||
|
||||
createAgentTaskRoute(url.pathname, () => configuredAgentTaskInspector) ||
|
||||
(url.pathname.startsWith(QUERY_ROUTE_PREFIX)
|
||||
? createQueryRoute(url.pathname, queryApi)
|
||||
: undefined) ||
|
||||
@@ -1494,7 +1810,21 @@ export function startHttpServer(
|
||||
port: actualPort,
|
||||
close: () =>
|
||||
new Promise<void>((res) => {
|
||||
server.close(() => res())
|
||||
let settled = false
|
||||
const finish = (): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
res()
|
||||
}
|
||||
// HTTP keep-alive 或长连接会阻塞 server.close(),退出时主动断开全部连接。
|
||||
const timer = setTimeout(finish, 1_500)
|
||||
// SSE 是长连接:先按订阅句柄释放,再交给 server.close 收尾。
|
||||
for (const stream of eventStreams) stream.destroy()
|
||||
eventStreams.clear()
|
||||
server.close(() => finish())
|
||||
server.closeIdleConnections?.()
|
||||
server.closeAllConnections?.()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -210,12 +210,16 @@ function normalizeDatBase(value) {
|
||||
|
||||
function isThumbnailName(fileName) {
|
||||
const lower = fileName.toLowerCase()
|
||||
if (!lower.endsWith('.dat')) {
|
||||
return /(?:_t(?:_m)?|_thumb|\.thumb)$/i.test(lower)
|
||||
}
|
||||
return /(?:_t(?:_m)?|_thumb|\.thumb|_b|_w|_c)\.dat$/i.test(lower)
|
||||
}
|
||||
|
||||
function imageQualityRank(fileName) {
|
||||
const lower = fileName.toLowerCase()
|
||||
if (/(?:_t(?:_m)?|_thumb|\.thumb|_b|_w|_c)\.dat$/i.test(lower)) return 1
|
||||
if (isThumbnailName(lower)) return 1
|
||||
if (!lower.endsWith('.dat')) return 3
|
||||
if (/(?:_hd|\.hd|_h_m|_h|\.h)\.dat$/i.test(lower)) return 3
|
||||
return 2
|
||||
}
|
||||
@@ -239,6 +243,20 @@ function buildPreferredDatNames(baseName) {
|
||||
]
|
||||
}
|
||||
|
||||
function buildExtensionlessVariantNames(baseName) {
|
||||
const base = normalizeDatBase(baseName)
|
||||
if (!base) return []
|
||||
return [
|
||||
base + '_hd',
|
||||
base + '_h_M',
|
||||
base + '_h',
|
||||
base + '_M',
|
||||
base,
|
||||
base + '_t_M',
|
||||
base + '_t'
|
||||
]
|
||||
}
|
||||
|
||||
function detectImageExtension(buffer) {
|
||||
if (buffer.length < 4) return null
|
||||
if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) return '.jpg'
|
||||
@@ -386,10 +404,6 @@ function decryptCandidate(filePath, aesKey, xorKey, ffmpegPath) {
|
||||
filePath
|
||||
}
|
||||
}
|
||||
if (!path.extname(filePath).toLowerCase().includes('dat')) {
|
||||
const extension = path.extname(filePath).toLowerCase()
|
||||
return { data: 'data:' + getMimeType(extension) + ';base64,' + bytes.toString('base64'), filePath }
|
||||
}
|
||||
if (
|
||||
bytes.length < 15 ||
|
||||
bytes[0] !== 0x07 ||
|
||||
@@ -440,10 +454,12 @@ function decryptCandidate(filePath, aesKey, xorKey, ffmpegPath) {
|
||||
|
||||
function collectCandidates(datPath, allowThumbnail) {
|
||||
const candidates = [datPath]
|
||||
if (!path.extname(datPath).toLowerCase().includes('dat')) return candidates
|
||||
const directory = path.dirname(datPath)
|
||||
const base = normalizeDatBase(path.basename(datPath))
|
||||
const siblings = buildPreferredDatNames(base)
|
||||
const names = path.extname(datPath).toLowerCase().includes('dat')
|
||||
? buildPreferredDatNames(base)
|
||||
: buildExtensionlessVariantNames(base).concat(buildPreferredDatNames(base))
|
||||
const siblings = names
|
||||
.filter((name) => allowThumbnail || !isThumbnailName(name))
|
||||
.map((name) => path.join(directory, name))
|
||||
.filter((candidate) => fs.existsSync(candidate))
|
||||
@@ -606,9 +622,23 @@ export class ImageDecryptService {
|
||||
})
|
||||
|
||||
const attachDir = join(accountDir, 'msg', 'attach')
|
||||
const recRef = this.parseForwardRecordImageRef(imageDatName)
|
||||
if (recRef && existsSync(attachDir)) {
|
||||
const recHit = this.findForwardRecordImage(
|
||||
attachDir,
|
||||
recRef.recordDir,
|
||||
recRef.fileIndex,
|
||||
allowThumbnail,
|
||||
options?.preferThumbnail,
|
||||
sessionDirectory,
|
||||
options?.createTime
|
||||
)
|
||||
if (recHit) return rememberPath(recHit)
|
||||
}
|
||||
|
||||
// The attach directory stores DAT filenames, while the message MD5 often
|
||||
// identifies the original image rather than the local file.
|
||||
const searchKeys = this.uniq([normalizedDatName, normalizedMd5])
|
||||
const searchKeys = this.uniq([recRef ? '' : normalizedDatName, normalizedMd5])
|
||||
|
||||
if (sessionDirectory && allowThumbnail && options?.preferThumbnail) {
|
||||
const bubblePreview = this.findBubblePreview(
|
||||
@@ -939,7 +969,21 @@ export class ImageDecryptService {
|
||||
if (!accountDir) return null
|
||||
|
||||
const attachDir = join(accountDir, 'msg', 'attach')
|
||||
const searchKeys = this.uniq([normalizedDatName, normalizedMd5])
|
||||
const recRef = this.parseForwardRecordImageRef(imageDatName)
|
||||
if (recRef && existsSync(attachDir)) {
|
||||
const recHit = await this.findForwardRecordImageAsync(
|
||||
attachDir,
|
||||
recRef.recordDir,
|
||||
recRef.fileIndex,
|
||||
allowThumbnail,
|
||||
options?.preferThumbnail,
|
||||
sessionDirectory,
|
||||
options?.createTime
|
||||
)
|
||||
if (recHit) return rememberPath(recHit)
|
||||
}
|
||||
|
||||
const searchKeys = this.uniq([recRef ? '' : normalizedDatName, normalizedMd5])
|
||||
if (allowThumbnail && options?.preferThumbnail) {
|
||||
const bubblePreview = await this.findBubblePreviewAsync(
|
||||
accountDir,
|
||||
@@ -1422,15 +1466,19 @@ export class ImageDecryptService {
|
||||
if (!extname(datPath).toLowerCase().includes('dat')) {
|
||||
try {
|
||||
const data = readFileSync(datPath)
|
||||
const ext = this.detectImageExtension(data) || extname(datPath).toLowerCase()
|
||||
const mimeType = this.getMimeType(ext)
|
||||
this.lastDecodeDiagnostic = {
|
||||
code: 'DIRECT_IMAGE',
|
||||
detail: '文件本身是可直接读取的图片',
|
||||
fileSize: data.length,
|
||||
imageFormat: ext.replace(/^\./, '').toUpperCase()
|
||||
const detectedExt = this.detectImageExtension(data)
|
||||
if (detectedExt) {
|
||||
const mimeType = this.getMimeType(detectedExt)
|
||||
this.lastDecodeDiagnostic = {
|
||||
code: 'DIRECT_IMAGE',
|
||||
detail: '文件本身是可直接读取的图片',
|
||||
fileSize: data.length,
|
||||
imageFormat: detectedExt.replace(/^\./, '').toUpperCase()
|
||||
}
|
||||
return `data:${mimeType};base64,${data.toString('base64')}`
|
||||
}
|
||||
return `data:${mimeType};base64,${data.toString('base64')}`
|
||||
// 合并转发 Rec/{token}/Img/{index} 文件没有 .dat 扩展名,但内部仍是 WeChat 4.0 V2 加密 DAT,
|
||||
// 若不是明文图片头则继续向下走 decryptImage 解密。
|
||||
} catch {
|
||||
this.lastDecodeDiagnostic = {
|
||||
code: 'FILE_NOT_FOUND',
|
||||
@@ -1798,6 +1846,108 @@ export class ImageDecryptService {
|
||||
]
|
||||
}
|
||||
|
||||
private parseForwardRecordImageRef(
|
||||
imageDatName?: string
|
||||
): { recordDir: string; fileIndex: string } | null {
|
||||
const raw = String(imageDatName || '').trim()
|
||||
const match = /^rec:([a-zA-Z0-9_-]+):(\d+)$/i.exec(raw)
|
||||
if (!match) return null
|
||||
return { recordDir: match[1], fileIndex: match[2] }
|
||||
}
|
||||
|
||||
private buildForwardRecordImageNames(fileIndex: string): string[] {
|
||||
return [
|
||||
`${fileIndex}_hd`,
|
||||
`${fileIndex}_h_M`,
|
||||
`${fileIndex}_h`,
|
||||
`${fileIndex}_M`,
|
||||
`${fileIndex}`,
|
||||
`${fileIndex}_t_M`,
|
||||
`${fileIndex}_t`,
|
||||
`${fileIndex}.dat`,
|
||||
`${fileIndex}_t.dat`
|
||||
]
|
||||
}
|
||||
|
||||
private findForwardRecordImage(
|
||||
attachDir: string,
|
||||
recordDir: string,
|
||||
fileIndex: string,
|
||||
allowThumbnail: boolean,
|
||||
preferThumbnail = false,
|
||||
sessionDirectory = '',
|
||||
createTime?: number
|
||||
): string | null {
|
||||
const candidateNames = this.buildForwardRecordImageNames(fileIndex)
|
||||
const sessionDirs = sessionDirectory
|
||||
? existsSync(join(attachDir, sessionDirectory))
|
||||
? [sessionDirectory]
|
||||
: []
|
||||
: readdirSync(attachDir).filter((name) => name.length === 32 && /^[a-f0-9]+$/i.test(name))
|
||||
|
||||
for (const sessDir of sessionDirs) {
|
||||
const sessionRoot = join(attachDir, sessDir)
|
||||
const months = sessionDirectory
|
||||
? this.getImageMonthDirectories(sessionRoot, createTime)
|
||||
: this.getRecentImageMonths(24)
|
||||
for (const month of months) {
|
||||
const recImgDir = join(sessionRoot, month, 'Rec', recordDir, 'Img')
|
||||
if (!existsSync(recImgDir)) continue
|
||||
const found = this.getLargestExistingPath(
|
||||
candidateNames.map((name) => join(recImgDir, name)),
|
||||
allowThumbnail,
|
||||
preferThumbnail
|
||||
)
|
||||
if (found) return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private async findForwardRecordImageAsync(
|
||||
attachDir: string,
|
||||
recordDir: string,
|
||||
fileIndex: string,
|
||||
allowThumbnail: boolean,
|
||||
preferThumbnail = false,
|
||||
sessionDirectory = '',
|
||||
createTime?: number
|
||||
): Promise<string | null> {
|
||||
if (!sessionDirectory) {
|
||||
return this.findForwardRecordImage(
|
||||
attachDir,
|
||||
recordDir,
|
||||
fileIndex,
|
||||
allowThumbnail,
|
||||
preferThumbnail,
|
||||
'',
|
||||
createTime
|
||||
)
|
||||
}
|
||||
const sessionRoot = join(attachDir, sessionDirectory)
|
||||
let months: string[]
|
||||
try {
|
||||
months = (await fsPromises.readdir(sessionRoot, { withFileTypes: true }))
|
||||
.filter((entry) => entry.isDirectory() && /^\d{4}-\d{2}$/.test(entry.name))
|
||||
.map((entry) => entry.name)
|
||||
.sort((left, right) => right.localeCompare(left))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
months = this.prioritizeImageMonth(months, createTime)
|
||||
const candidateNames = this.buildForwardRecordImageNames(fileIndex)
|
||||
for (const month of months) {
|
||||
const recImgDir = join(sessionRoot, month, 'Rec', recordDir, 'Img')
|
||||
const found = await this.getLargestExistingPathAsync(
|
||||
candidateNames.map((name) => join(recImgDir, name)),
|
||||
allowThumbnail,
|
||||
preferThumbnail
|
||||
)
|
||||
if (found) return found
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private getPreferredDatVariantPath(
|
||||
inputPath: string,
|
||||
allowThumbnail: boolean,
|
||||
@@ -1805,7 +1955,10 @@ export class ImageDecryptService {
|
||||
): string {
|
||||
const actualDir = dirname(inputPath)
|
||||
const base = this.normalizeDatBase(basename(inputPath))
|
||||
const variants = this.buildPreferredDatNames(base)
|
||||
const hasDatExtension = basename(inputPath).toLowerCase().endsWith('.dat')
|
||||
const variants = hasDatExtension
|
||||
? this.buildPreferredDatNames(base)
|
||||
: [...this.buildForwardRecordImageNames(base), ...this.buildPreferredDatNames(base)]
|
||||
const ordered = allowThumbnail
|
||||
? variants
|
||||
: variants.filter((name) => !this.isThumbnailName(name))
|
||||
|
||||
+737
-100
File diff suppressed because it is too large.
Load diff
@@ -64,25 +64,57 @@ export function chunkConversation(
|
||||
throw new Error('Conversation chunker received messages from multiple accounts or conversations')
|
||||
}
|
||||
|
||||
const chunks: KnowledgeChunk[] = []
|
||||
const streamer = createChunkStreamer(config)
|
||||
return [...streamer.push(sorted), ...streamer.drain()]
|
||||
}
|
||||
|
||||
export interface KnowledgeChunkStreamer {
|
||||
/** 追加一批有序消息,返回因此**收盘**的 chunk(不含尾部未完成段)。 */
|
||||
push(messages: KnowledgeNormalizedMessage[]): KnowledgeChunk[]
|
||||
/** 收盘尾部未完成段;之后再 `push` 会开启新段。 */
|
||||
drain(): KnowledgeChunk[]
|
||||
/** 尚未收盘的消息数;用于持久化续跑位置。 */
|
||||
pendingCount(): number
|
||||
}
|
||||
|
||||
/**
|
||||
* 切分只依赖相邻两条与累积长度,所以分批 push 与一次性切分逐字等价。
|
||||
*/
|
||||
export function createChunkStreamer(config: KnowledgeChunkerConfig): KnowledgeChunkStreamer {
|
||||
let current: KnowledgeNormalizedMessage[] = []
|
||||
let currentCharacters = 0
|
||||
for (const message of sorted) {
|
||||
const previous = current[current.length - 1]
|
||||
const nextCharacters = currentCharacters + message.searchableText.length
|
||||
const shouldSplit =
|
||||
current.length > 0 &&
|
||||
(message.createTime - previous.createTime > config.maxGapMs ||
|
||||
current.length >= config.maxMessages ||
|
||||
nextCharacters > config.maxCharacters)
|
||||
if (shouldSplit) {
|
||||
chunks.push(buildChunk(current, config))
|
||||
|
||||
return {
|
||||
push(messages) {
|
||||
const chunks: KnowledgeChunk[] = []
|
||||
for (const message of messages) {
|
||||
if (!isIndexableKnowledgeMessage(message)) continue
|
||||
const previous = current[current.length - 1]
|
||||
const nextCharacters = currentCharacters + message.searchableText.length
|
||||
const shouldSplit =
|
||||
current.length > 0 &&
|
||||
(message.createTime - previous.createTime > config.maxGapMs ||
|
||||
current.length >= config.maxMessages ||
|
||||
nextCharacters > config.maxCharacters)
|
||||
if (shouldSplit) {
|
||||
chunks.push(buildChunk(current, config))
|
||||
current = []
|
||||
currentCharacters = 0
|
||||
}
|
||||
current.push(message)
|
||||
currentCharacters += message.searchableText.length
|
||||
}
|
||||
return chunks
|
||||
},
|
||||
drain() {
|
||||
if (!current.length) return []
|
||||
const chunk = buildChunk(current, config)
|
||||
current = []
|
||||
currentCharacters = 0
|
||||
return [chunk]
|
||||
},
|
||||
pendingCount() {
|
||||
return current.length
|
||||
}
|
||||
current.push(message)
|
||||
currentCharacters += message.searchableText.length
|
||||
}
|
||||
if (current.length) chunks.push(buildChunk(current, config))
|
||||
return chunks
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import * as chat from '../services/chat-service'
|
||||
import type {
|
||||
ConversationMessageCountEntry,
|
||||
ConversationMessageCountSnapshot
|
||||
} from '../../shared/conversation-message-count'
|
||||
import { EMPTY_CONVERSATION_MESSAGE_COUNT } from '../../shared/conversation-message-count'
|
||||
|
||||
/** 成功结果的有效期。聊天记录会增长,缓存不能永久有效。 */
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000
|
||||
/** 失败结果只短暂记住,避免每次打开下拉框都对同一批坏分片重试。 */
|
||||
const FAILURE_TTL_MS = 60 * 1000
|
||||
/** 同时在跑的 `COUNT(*)` 条数上限。 */
|
||||
const MAX_CONCURRENT = 4
|
||||
/** 合并推送的窗口,避免上千个会话逐条打 IPC。 */
|
||||
const FLUSH_INTERVAL_MS = 80
|
||||
|
||||
/** 只读 COUNT(*):为排序去加载正文正是 #75 的写法;失败返回 null,不是 0。 */
|
||||
export class ConversationMessageCountService {
|
||||
private readonly cache = new Map<string, ConversationMessageCountEntry>()
|
||||
private readonly inFlight = new Set<string>()
|
||||
private readonly listeners = new Set<(entries: ConversationMessageCountEntry[]) => void>()
|
||||
private queue: string[] = []
|
||||
private active = 0
|
||||
private generation = 0
|
||||
private flushTimer: NodeJS.Timeout | null = null
|
||||
private readonly dirty = new Map<string, ConversationMessageCountEntry>()
|
||||
/** 统计按账号隔离:换账号后旧 md5 的条数一个都不能复用。 */
|
||||
private accountId = ''
|
||||
|
||||
onCountsChange(listener: (entries: ConversationMessageCountEntry[]) => void): () => void {
|
||||
this.listeners.add(listener)
|
||||
return () => this.listeners.delete(listener)
|
||||
}
|
||||
|
||||
/** 立即返回快照(含缓存与「尚未统计」占位),并把未知项排进后台队列。 */
|
||||
read(conversationIds: string[]): ConversationMessageCountSnapshot {
|
||||
this.syncAccount()
|
||||
const entries = conversationIds.map((id) => this.cached(id))
|
||||
this.enqueue(conversationIds.filter((id) => entries.find((e) => e.conversationId === id)?.measuredAt === 0))
|
||||
return { entries }
|
||||
}
|
||||
|
||||
/** 只读缓存,不触发统计。 */
|
||||
peek(conversationIds: string[]): ConversationMessageCountEntry[] {
|
||||
return conversationIds.map((id) => this.cached(id))
|
||||
}
|
||||
|
||||
enqueue(conversationIds: string[]): void {
|
||||
this.syncAccount()
|
||||
for (const id of conversationIds) {
|
||||
if (!id || this.inFlight.has(id)) continue
|
||||
const cached = this.cache.get(id)
|
||||
if (cached && Date.now() - cached.measuredAt < this.ttl(cached)) continue
|
||||
this.inFlight.add(id)
|
||||
this.queue.push(id)
|
||||
}
|
||||
this.pump()
|
||||
}
|
||||
|
||||
/** 停止推进并丢弃队列;已算出的结果保留(它们仍然有效)。 */
|
||||
cancel(): void {
|
||||
this.generation += 1
|
||||
this.queue = []
|
||||
this.inFlight.clear()
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.cancel()
|
||||
if (this.flushTimer) clearTimeout(this.flushTimer)
|
||||
this.flushTimer = null
|
||||
this.listeners.clear()
|
||||
this.dirty.clear()
|
||||
this.cache.clear()
|
||||
}
|
||||
|
||||
private syncAccount(): void {
|
||||
const next = chat.isReady() ? chat.getSelfAccountInfo()?.wxid || '' : ''
|
||||
if (next === this.accountId) return
|
||||
this.accountId = next
|
||||
this.cancel()
|
||||
this.cache.clear()
|
||||
this.dirty.clear()
|
||||
}
|
||||
|
||||
private ttl(entry: ConversationMessageCountEntry): number {
|
||||
return entry.count === null ? FAILURE_TTL_MS : CACHE_TTL_MS
|
||||
}
|
||||
|
||||
private cached(conversationId: string): ConversationMessageCountEntry {
|
||||
const hit = this.cache.get(conversationId)
|
||||
if (hit && Date.now() - hit.measuredAt < this.ttl(hit)) return hit
|
||||
return { ...EMPTY_CONVERSATION_MESSAGE_COUNT, conversationId }
|
||||
}
|
||||
|
||||
private pump(): void {
|
||||
while (this.active < MAX_CONCURRENT && this.queue.length) {
|
||||
const conversationId = this.queue.shift() as string
|
||||
const generation = this.generation
|
||||
this.active += 1
|
||||
void this.measure(conversationId)
|
||||
.then((result) => {
|
||||
if (generation !== this.generation) return
|
||||
this.publish({ conversationId, ...result, measuredAt: Date.now() })
|
||||
})
|
||||
.catch(() => {
|
||||
if (generation !== this.generation) return
|
||||
// 统计失败必须是「未知」:0 会让一个真有 57 万条的群排到最后并显示误导性数字。
|
||||
this.publish({ conversationId, count: null, approximate: false, measuredAt: Date.now() })
|
||||
})
|
||||
.finally(() => {
|
||||
this.inFlight.delete(conversationId)
|
||||
this.active -= 1
|
||||
this.pump()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private async measure(
|
||||
conversationId: string
|
||||
): Promise<{ count: number | null; approximate: boolean }> {
|
||||
if (!chat.isReady()) return { count: null, approximate: false }
|
||||
const result = await chat.countConversationMessagesAsync(conversationId)
|
||||
return { count: result.count, approximate: result.approximate }
|
||||
}
|
||||
|
||||
private publish(entry: ConversationMessageCountEntry): void {
|
||||
this.cache.set(entry.conversationId, entry)
|
||||
this.dirty.set(entry.conversationId, entry)
|
||||
if (this.flushTimer) return
|
||||
this.flushTimer = setTimeout(() => {
|
||||
this.flushTimer = null
|
||||
const batch = Array.from(this.dirty.values())
|
||||
this.dirty.clear()
|
||||
if (!batch.length) return
|
||||
for (const listener of this.listeners) listener(batch)
|
||||
}, FLUSH_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
@@ -23,14 +23,15 @@ import type {
|
||||
import {
|
||||
DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
DEFAULT_KNOWLEDGE_FTS_CONFIG,
|
||||
emptyKnowledgeSearchTimings
|
||||
emptyKnowledgeSearchTimings,
|
||||
normalizeKnowledgeIndexScope,
|
||||
type KnowledgeConversationIndexState,
|
||||
type KnowledgeIndexScope
|
||||
} from '../../shared/knowledge'
|
||||
import { KnowledgeService } from './knowledge-service'
|
||||
import { loadSettings } from '../services/settings-store'
|
||||
import { sourceMessageId } from './message-identity'
|
||||
import {
|
||||
voiceAccountIdentity,
|
||||
voiceMessageIdentity
|
||||
} from '../voice-pipeline/voice-message-identity'
|
||||
import { voiceAccountIdentity } from '../voice-pipeline/voice-message-identity'
|
||||
|
||||
const FALLBACK_LIMIT = 240
|
||||
const MAX_SENDER_NAME_CONVERSATIONS = 8
|
||||
@@ -50,6 +51,14 @@ const SENDER_ENRICHMENT_SESSION_TTL_MS = 5 * 60 * 1000
|
||||
*/
|
||||
const DELTA_OVERLAP_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
/**
|
||||
* 后台回填的单页消息数:调到更大能少走 IPC,但主进程驻留的上限也随之变大。
|
||||
*/
|
||||
const KNOWLEDGE_INDEX_PAGE_SIZE = 1500
|
||||
|
||||
/** 增量窗口超过这个条数就改为分批重建,否则一次读完会重演「整会话进内存」。 */
|
||||
const DELTA_STREAM_THRESHOLD = 20_000
|
||||
|
||||
/**
|
||||
* event-loop 滞后采样的分辨率(ms)。
|
||||
*
|
||||
@@ -99,6 +108,8 @@ function looksLikeOpaqueSenderId(value: string | undefined): boolean {
|
||||
return (
|
||||
normalized.startsWith('wxid_') ||
|
||||
normalized.endsWith('@chatroom') ||
|
||||
normalized.endsWith('@qy_u') ||
|
||||
normalized.endsWith('@qy_g') ||
|
||||
/^\d{6,}$/.test(normalized)
|
||||
)
|
||||
}
|
||||
@@ -321,6 +332,7 @@ export class KnowledgeSearchService {
|
||||
catchupConversations: 0,
|
||||
backfillConversations: 0,
|
||||
backfillCompletedConversations: 0,
|
||||
excludedConversations: 0,
|
||||
mainLoopLagMs: 0
|
||||
}
|
||||
const started: KnowledgeRuntimeStatus = {
|
||||
@@ -611,6 +623,13 @@ export class KnowledgeSearchService {
|
||||
return () => this.statusListeners.delete(listener)
|
||||
}
|
||||
|
||||
/** 会话级索引状态:覆盖度判断的依据,全局 indexLatestAt 不算证明。 */
|
||||
async getConversationIndexStates(): Promise<Record<string, KnowledgeConversationIndexState>> {
|
||||
const accountId = this.currentAccountId()
|
||||
if (!accountId) return {}
|
||||
return this.service.conversationStates({ accountId }).catch(() => ({}))
|
||||
}
|
||||
|
||||
async getStatus(): Promise<KnowledgeRuntimeStatus> {
|
||||
const accountId = this.currentAccountId()
|
||||
if (!accountId) return this.emptyStatus('')
|
||||
@@ -622,9 +641,102 @@ export class KnowledgeSearchService {
|
||||
return chat.getSelfAccountInfo()?.wxid || chat.getCurrentAccountRoot()
|
||||
}
|
||||
|
||||
/** 当前账号的索引范围;缺省(老用户/新账号)是全部会话。 */
|
||||
private resolveIndexScope(accountId: string): KnowledgeIndexScope {
|
||||
const scopes = loadSettings().knowledgeIndexScopes ?? {}
|
||||
return normalizeKnowledgeIndexScope(scopes[accountId])
|
||||
}
|
||||
|
||||
/** 后台重索引也要过这一关,否则排除掉的群会因一次 OCR 完成被整段建回来。 */
|
||||
private isIndexableConversation(accountId: string, conversationId: string): boolean {
|
||||
const scope = this.resolveIndexScope(accountId)
|
||||
return scope.mode === 'all' || scope.conversationIds.includes(conversationId)
|
||||
}
|
||||
|
||||
/** 分页读 + 分批写:已提交的批次连同续跑位置保留,下一遍从该边界继续。 */
|
||||
private async backfillConversation(
|
||||
accountId: string,
|
||||
contact: { md5: string },
|
||||
options: { sourceHighWaterHint?: number; fromScratch?: boolean },
|
||||
onProgress: (processed: number, chunks: number) => void
|
||||
): Promise<{ processed: number; scanned: number; latest: number; cancelled: boolean }> {
|
||||
const conversationId = contact.md5
|
||||
const start = await this.service.startConversationStream(
|
||||
{
|
||||
accountId,
|
||||
conversationId,
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG,
|
||||
completeSnapshot: true,
|
||||
// 后台重索引是「整段重建」,不能接上次断点 —— 否则只补半段还声明完整。
|
||||
...(options.fromScratch ? { resume: null } : {})
|
||||
},
|
||||
(progress) => onProgress(progress.processedMessages, progress.indexedChunks)
|
||||
)
|
||||
|
||||
let scanned = 0
|
||||
let latest = 0
|
||||
let cancelled = false
|
||||
try {
|
||||
for await (const page of chat.iterateMessagesAsync(conversationId, {
|
||||
pageSize: KNOWLEDGE_INDEX_PAGE_SIZE,
|
||||
// 续跑边界来自 `chunk.endTime`,单位是**毫秒**(消息 createTime),
|
||||
// 不能再乘 1000;分页层自己转秒。
|
||||
sinceMs: start.resumedFrom ?? undefined
|
||||
})) {
|
||||
if (this.cancelRequested) {
|
||||
cancelled = true
|
||||
break
|
||||
}
|
||||
await this.interactiveIdle
|
||||
if (page.failedStores.length) {
|
||||
throw new Error(`历史消息分片读取失败:${page.failedStores.join(', ')}`)
|
||||
}
|
||||
if (!page.messages.length) continue
|
||||
scanned += page.messages.length
|
||||
for (const message of page.messages) {
|
||||
const createTime = (message.createTime || 0) * 1000
|
||||
if (createTime > latest) latest = createTime
|
||||
}
|
||||
const sourceMessages = page.messages
|
||||
.map((message) => this.toSourceMessage(accountId, conversationId, message))
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
await this.service.pushConversationBatch({
|
||||
accountId,
|
||||
conversationId,
|
||||
messages: sourceMessages
|
||||
})
|
||||
}
|
||||
|
||||
if (cancelled) {
|
||||
await this.service.abortConversationStream({ accountId, conversationId })
|
||||
return { processed: 0, scanned, latest, cancelled: true }
|
||||
}
|
||||
|
||||
const result = await this.service.finishConversationStream({
|
||||
accountId,
|
||||
conversationId,
|
||||
sourceHighWaterTime: Math.max(options.sourceHighWaterHint ?? 0, latest)
|
||||
})
|
||||
return { processed: result.processedMessages, scanned, latest, cancelled: result.cancelled }
|
||||
} catch (error) {
|
||||
await this.service
|
||||
.abortConversationStream({ accountId, conversationId })
|
||||
.catch(() => undefined)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async indexAccount(accountId: string): Promise<void> {
|
||||
// 整遍后台索引走 background 通道:交互查询可以插到它前面,不至于被 pass 拖慢。
|
||||
const contacts = await this.listContacts('background')
|
||||
const allContacts = await this.listContacts('background')
|
||||
const scope = this.resolveIndexScope(accountId)
|
||||
// `selected` 且一个都没勾时结果是空集 —— 这是「不索引任何会话」,不是「全部」。
|
||||
const contacts =
|
||||
scope.mode === 'all'
|
||||
? allContacts
|
||||
: allContacts.filter((contact) => scope.conversationIds.includes(contact.md5))
|
||||
const excludedByScope = allContacts.length - contacts.length
|
||||
const startedAt = Date.now()
|
||||
// 源侧每会话最后活跃时间(零额外 WCDB 调用:直接来自 Session 列表)。
|
||||
const activity = chat.getConversationActivityMs()
|
||||
@@ -674,6 +786,7 @@ export class KnowledgeSearchService {
|
||||
|
||||
if (this.passProgress) {
|
||||
this.passProgress.totalConversations = contacts.length
|
||||
this.passProgress.excludedConversations = excludedByScope
|
||||
this.passProgress.startedAt = startedAt
|
||||
this.passProgress.skippedConversations = skippedConversations
|
||||
this.passProgress.catchupConversations = catchUpContacts.length
|
||||
@@ -716,75 +829,106 @@ export class KnowledgeSearchService {
|
||||
const sinceTime = isDelta
|
||||
? Math.max(0, Math.floor((mark - DELTA_OVERLAP_MS) / 1000))
|
||||
: undefined
|
||||
const messages = await this.listMessages(contact.md5, sinceTime, undefined, 'background')
|
||||
scannedMessages += messages.length
|
||||
// 这一遍扫到的源数据最新时间:用**未过滤**的原始消息计算,
|
||||
// 这样「不可建模」的消息(图片/空正文)不会让 freshness 口径偏旧。
|
||||
let conversationProcessed = 0
|
||||
let conversationScanned = 0
|
||||
let conversationLatest = 0
|
||||
for (const message of messages) {
|
||||
const createTime = (message.createTime || 0) * 1000
|
||||
if (createTime > conversationLatest) conversationLatest = createTime
|
||||
}
|
||||
if (conversationLatest > sourceLatestAt) sourceLatestAt = conversationLatest
|
||||
const sourceMessages = messages
|
||||
.map((message) => this.toSourceMessage(accountId, contact.md5, message))
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
// 记录**源侧**边界(而不是索引里最后一条可建模消息的时间):
|
||||
// 否则"最后一条恰好落在图片上"的会话会永远被判成有新消息,增量永远跳不过它。
|
||||
//
|
||||
// 安全阀:delta 范围读**空**、但源侧声称有新消息 → **不推进** checkpoint。
|
||||
// 宁可下一遍重试,也不让"一次可疑的空读"升级成"谎报已覆盖"(那会静默丢消息)。
|
||||
const suspiciousEmptyDelta =
|
||||
isDelta && messages.length === 0 && (previousActivity ?? 0) > (mark ?? 0)
|
||||
const sourceHighWaterTime = suspiciousEmptyDelta
|
||||
? undefined
|
||||
: Math.max(previousActivity ?? 0, conversationLatest)
|
||||
const result = await this.service.index(
|
||||
{
|
||||
accountId,
|
||||
conversations: [
|
||||
{
|
||||
conversationId: contact.md5,
|
||||
// delta 模式下绝不能声明"完整快照":否则 store 会把"不在 delta 里的历史消息"
|
||||
// 误判为被删除,从而整段重建这个会话,增量就白做了。
|
||||
completeSnapshot: !isDelta,
|
||||
messages: sourceMessages,
|
||||
...(sourceHighWaterTime && sourceHighWaterTime > 0 ? { sourceHighWaterTime } : {})
|
||||
}
|
||||
],
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG,
|
||||
// 只有「这一遍真的读完了全部会话」(没有任何跳过、没有取消)才写入总量口径,
|
||||
// 否则会把增量 pass 的部分计数冒充成全量。
|
||||
//
|
||||
// 这里数的是真正被建模进索引的源消息,不是"扫到的原始条数";后者(含不可建模的
|
||||
// 图片/空正文)另走 pass 进度里的 scannedMessages。两个数字回答不同问题。
|
||||
sourceMessageCount:
|
||||
index === orderedContacts.length - 1 && skippedConversations === 0
|
||||
? indexedMessages + sourceMessages.length
|
||||
: undefined,
|
||||
sourceLatestAt:
|
||||
index === orderedContacts.length - 1 && sourceLatestAt > 0 ? sourceLatestAt : undefined
|
||||
},
|
||||
(progress) => {
|
||||
const current = this.statusByAccount.get(accountId) || this.emptyStatus(accountId)
|
||||
this.publishStatus({
|
||||
...current,
|
||||
state: current.indexedMessageCount ? 'syncing' : 'building',
|
||||
processedMessages: indexedMessages + progress.processedMessages,
|
||||
totalMessages: null,
|
||||
currentConversationId: progress.conversationId,
|
||||
estimatedRemainingMs: null,
|
||||
pass: this.passSnapshot()
|
||||
})
|
||||
let conversationCancelled = false
|
||||
|
||||
// delta 窗口的规模由「上次 checkpoint 到现在的活跃度」决定,可能是一年。
|
||||
// 先只数一次(COUNT 不解码正文),超阈值就退回分批重建,而不是把几十万条读进数组。
|
||||
const deltaCount = isDelta
|
||||
? await chat
|
||||
.countConversationMessagesAsync(contact.md5, {
|
||||
sinceMs: (sinceTime ?? 0) * 1000
|
||||
})
|
||||
.catch(() => null)
|
||||
: null
|
||||
const deltaTooLarge =
|
||||
typeof deltaCount?.count === 'number' && deltaCount.count > DELTA_STREAM_THRESHOLD
|
||||
|
||||
if (isDelta && !deltaTooLarge) {
|
||||
const messages = await this.listMessages(contact.md5, sinceTime, undefined, 'background')
|
||||
conversationScanned = messages.length
|
||||
for (const message of messages) {
|
||||
const createTime = (message.createTime || 0) * 1000
|
||||
if (createTime > conversationLatest) conversationLatest = createTime
|
||||
}
|
||||
)
|
||||
if (result.cancelled) {
|
||||
const sourceMessages = messages
|
||||
.map((message) => this.toSourceMessage(accountId, contact.md5, message))
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
// 安全阀:delta 读空、但源侧声称有新消息 → 不推进 checkpoint。
|
||||
// 宁可下一遍重试,也不让"一次可疑的空读"升级成"谎报已覆盖"。
|
||||
const suspiciousEmptyDelta =
|
||||
messages.length === 0 && (previousActivity ?? 0) > (mark ?? 0)
|
||||
const sourceHighWaterTime = suspiciousEmptyDelta
|
||||
? undefined
|
||||
: Math.max(previousActivity ?? 0, conversationLatest)
|
||||
const result = await this.service.index(
|
||||
{
|
||||
accountId,
|
||||
conversations: [
|
||||
{
|
||||
conversationId: contact.md5,
|
||||
// delta 不能声明完整快照:否则不在 delta 里的历史会被判成已删除并整段重建。
|
||||
completeSnapshot: false,
|
||||
messages: sourceMessages,
|
||||
...(sourceHighWaterTime && sourceHighWaterTime > 0
|
||||
? { sourceHighWaterTime }
|
||||
: {})
|
||||
}
|
||||
],
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG
|
||||
},
|
||||
(progress) => {
|
||||
const current = this.statusByAccount.get(accountId) || this.emptyStatus(accountId)
|
||||
this.publishStatus({
|
||||
...current,
|
||||
state: current.indexedMessageCount ? 'syncing' : 'building',
|
||||
processedMessages: indexedMessages + progress.processedMessages,
|
||||
totalMessages: null,
|
||||
currentConversationId: progress.conversationId,
|
||||
estimatedRemainingMs: null,
|
||||
pass: this.passSnapshot()
|
||||
})
|
||||
}
|
||||
)
|
||||
conversationCancelled = result.cancelled
|
||||
conversationProcessed = result.cancelled ? result.processedMessages : sourceMessages.length
|
||||
} else {
|
||||
const backfill = await this.backfillConversation(
|
||||
accountId,
|
||||
contact,
|
||||
{ sourceHighWaterHint: previousActivity },
|
||||
(processed) => {
|
||||
if (this.passProgress) this.passProgress.currentConversationProcessed = processed
|
||||
const current = this.statusByAccount.get(accountId) || this.emptyStatus(accountId)
|
||||
this.publishStatus({
|
||||
...current,
|
||||
state: current.indexedMessageCount ? 'syncing' : 'building',
|
||||
processedMessages: indexedMessages + processed,
|
||||
totalMessages: null,
|
||||
currentConversationId: contact.md5,
|
||||
estimatedRemainingMs: null,
|
||||
pass: this.passSnapshot()
|
||||
})
|
||||
}
|
||||
)
|
||||
conversationCancelled = backfill.cancelled
|
||||
conversationProcessed = backfill.processed
|
||||
conversationScanned = backfill.scanned
|
||||
conversationLatest = backfill.latest
|
||||
}
|
||||
|
||||
scannedMessages += conversationScanned
|
||||
// 用未过滤的原始消息算 freshness,图片/空正文才不会让口径偏旧。
|
||||
if (conversationLatest > sourceLatestAt) sourceLatestAt = conversationLatest
|
||||
if (conversationCancelled) {
|
||||
cancelled = true
|
||||
indexedMessages += result.processedMessages
|
||||
indexedMessages += conversationProcessed
|
||||
break
|
||||
}
|
||||
indexedMessages += sourceMessages.length
|
||||
indexedMessages += conversationProcessed
|
||||
if (isBackfill) backfillCompletedConversations += 1
|
||||
if (this.passProgress) {
|
||||
this.passProgress.scannedMessages = scannedMessages
|
||||
@@ -804,12 +948,24 @@ export class KnowledgeSearchService {
|
||||
})
|
||||
}
|
||||
if (cancelled && this.passProgress) this.passProgress.phase = 'cancelled'
|
||||
// 全局源口径只在「读完全部会话」时可信:有跳过或取消时写进去,下一秒就会被
|
||||
// 当成"源侧总量"用来算覆盖率。
|
||||
if (!cancelled && skippedConversations === 0 && sourceLatestAt > 0) {
|
||||
await this.service
|
||||
.writeSourceTotals({
|
||||
accountId,
|
||||
sourceMessageCount: indexedMessages,
|
||||
sourceLatestAt
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
// 一遍 pass 一行汇总(低频、只在结束时输出一次)。这些数字同时喂给 UI 的 pass 进度;
|
||||
// lag 输出分位数而不是单点,因为"最大值看着还行"不能说明没有 stall。
|
||||
console.info(
|
||||
`[Knowledge] pass ${cancelled ? 'cancelled' : 'done'} conversations=${contacts.length} ` +
|
||||
`skipped=${skippedConversations} scanned=${scannedMessages} indexed=${indexedMessages} ` +
|
||||
`catchup=${catchUpContacts.length} backfill=${backfillContacts.length}/${backfillCompletedConversations} ` +
|
||||
`excludedByScope=${excludedByScope} ` +
|
||||
`elapsedMs=${Date.now() - startedAt} ` +
|
||||
`lagP50=${this.lagStats?.p50 ?? 0} lagP95=${this.lagStats?.p95 ?? 0} ` +
|
||||
`lagP99=${this.lagStats?.p99 ?? 0} lagMax=${this.lagStats?.max ?? this.lagMaxMs} ` +
|
||||
@@ -1187,23 +1343,14 @@ export class KnowledgeSearchService {
|
||||
if (!chat.isReady()) return
|
||||
const accountId = this.currentAccountId()
|
||||
if (!accountId) return
|
||||
// OCR 完成不是绕过索引范围的理由:被排除的会话不该因为一次识别又被整段建回来。
|
||||
if (!this.isIndexableConversation(accountId, conversationId)) return
|
||||
const activeIndex = this.indexing.get(accountId)
|
||||
if (activeIndex) await activeIndex
|
||||
const contacts = await this.listContacts()
|
||||
const contact = contacts.find((item) => item.md5 === conversationId)
|
||||
if (!contact) return
|
||||
const messages = await this.listMessages(contact.md5, undefined, undefined, 'background')
|
||||
const sourceMessages = messages
|
||||
.map((message) => this.toSourceMessage(accountId, contact.md5, message))
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
await this.service.index({
|
||||
accountId,
|
||||
conversations: [
|
||||
{ conversationId: contact.md5, completeSnapshot: true, messages: sourceMessages }
|
||||
],
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG
|
||||
})
|
||||
await this.backfillConversation(accountId, contact, { fromScratch: true }, () => undefined)
|
||||
await this.refreshStatus(accountId)
|
||||
}
|
||||
|
||||
@@ -1223,39 +1370,10 @@ export class KnowledgeSearchService {
|
||||
const contacts = await this.listContacts()
|
||||
const contact = contacts.find((item) => item.m_nsUsrName === update.reference.sessionId)
|
||||
if (!contact) return
|
||||
const messages = await this.listMessages(contact.md5)
|
||||
const sourceMessages = messages
|
||||
.map((message) => {
|
||||
const reference = this.voiceReferenceFromMessage(message)
|
||||
const transcriptOverride =
|
||||
reference && voiceMessageIdentity(reference) === update.messageIdentity
|
||||
? update.transcript
|
||||
: undefined
|
||||
const stateOverride =
|
||||
reference && voiceMessageIdentity(reference) === update.messageIdentity
|
||||
? update.state
|
||||
: undefined
|
||||
return this.toSourceMessage(
|
||||
accountId,
|
||||
contact.md5,
|
||||
message,
|
||||
transcriptOverride,
|
||||
stateOverride
|
||||
)
|
||||
})
|
||||
.filter((message): message is KnowledgeSourceMessage => Boolean(message))
|
||||
await this.service.index({
|
||||
accountId,
|
||||
conversations: [
|
||||
{
|
||||
conversationId: contact.md5,
|
||||
completeSnapshot: true,
|
||||
messages: sourceMessages
|
||||
}
|
||||
],
|
||||
chunker: DEFAULT_KNOWLEDGE_CHUNKER,
|
||||
fts: DEFAULT_KNOWLEDGE_FTS_CONFIG
|
||||
})
|
||||
// 转写结果已写进语音缓存,`toSourceMessage` 会通过 resolver 取到最新文本,
|
||||
// 所以这里不需要(也不应该)为了覆盖一条消息而重读整会话。
|
||||
if (!this.isIndexableConversation(accountId, contact.md5)) return
|
||||
await this.backfillConversation(accountId, contact, { fromScratch: true }, () => undefined)
|
||||
await this.refreshStatus(accountId)
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,15 @@ import type {
|
||||
KnowledgeRuntimeStatus,
|
||||
KnowledgeSearchRequest,
|
||||
KnowledgeSearchResult,
|
||||
KnowledgeStatusRequest
|
||||
KnowledgeStatusRequest,
|
||||
KnowledgeConversationIndexState,
|
||||
KnowledgeConversationStatesRequest,
|
||||
KnowledgeSourceTotalsRequest,
|
||||
KnowledgeStreamBatchRequest,
|
||||
KnowledgeStreamConversationRequest,
|
||||
KnowledgeStreamResult,
|
||||
KnowledgeStreamStartRequest,
|
||||
KnowledgeStreamStartResult
|
||||
} from '../../shared/knowledge'
|
||||
import { KnowledgeWorkerHost } from './knowledge-worker-host'
|
||||
|
||||
@@ -32,6 +40,39 @@ export class KnowledgeService {
|
||||
return this.worker.index({ ...request, databaseRoot: this.databaseRoot }, onProgress)
|
||||
}
|
||||
|
||||
/** 开始一个会话的分批索引:消息不随请求下发,由调用方逐批推送。 */
|
||||
startConversationStream(
|
||||
request: Omit<KnowledgeStreamStartRequest, 'databaseRoot'>,
|
||||
onProgress?: (progress: KnowledgeIndexProgress) => void
|
||||
): Promise<KnowledgeStreamStartResult> {
|
||||
return this.worker.startConversationStream(
|
||||
{ ...request, databaseRoot: this.databaseRoot },
|
||||
onProgress
|
||||
)
|
||||
}
|
||||
|
||||
pushConversationBatch(
|
||||
request: Omit<KnowledgeStreamBatchRequest, 'databaseRoot'>
|
||||
): Promise<void> {
|
||||
return this.worker.pushConversationBatch({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
finishConversationStream(
|
||||
request: Omit<KnowledgeStreamConversationRequest, 'databaseRoot'>
|
||||
): Promise<KnowledgeStreamResult> {
|
||||
return this.worker.finishConversationStream({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
abortConversationStream(
|
||||
request: Omit<KnowledgeStreamConversationRequest, 'databaseRoot'>
|
||||
): Promise<void> {
|
||||
return this.worker.abortConversationStream({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
writeSourceTotals(request: Omit<KnowledgeSourceTotalsRequest, 'databaseRoot'>): Promise<void> {
|
||||
return this.worker.writeSourceTotals({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
preflight(
|
||||
request: Omit<KnowledgeCapacityPreflightRequest, 'databaseRoot'>
|
||||
): Promise<KnowledgeCapacityPreflight> {
|
||||
@@ -50,6 +91,13 @@ export class KnowledgeService {
|
||||
return this.worker.status({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
/** 每个会话的索引状态(是否完整覆盖),查询侧据此判断覆盖度。 */
|
||||
conversationStates(
|
||||
request: Omit<KnowledgeConversationStatesRequest, 'databaseRoot'>
|
||||
): Promise<Record<string, KnowledgeConversationIndexState>> {
|
||||
return this.worker.conversationStates({ ...request, databaseRoot: this.databaseRoot })
|
||||
}
|
||||
|
||||
/** 每个会话已经索引到的源侧时刻(epoch ms);增量 pass 用它跳过没有变化的会话。 */
|
||||
highWaterMarks(request: Omit<KnowledgeStatusRequest, 'databaseRoot'>): Promise<Record<string, number>> {
|
||||
return this.worker.highWaterMarks({ ...request, databaseRoot: this.databaseRoot })
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
KnowledgeCapacityPreflight,
|
||||
KnowledgeCapacityPreflightRequest,
|
||||
KnowledgeChunk,
|
||||
KnowledgeChunkerConfig,
|
||||
KnowledgeConversationRetrieval,
|
||||
KnowledgeEvidence,
|
||||
KnowledgeVoiceCoverage,
|
||||
@@ -18,18 +19,29 @@ import type {
|
||||
KnowledgeNormalizedMessage,
|
||||
KnowledgeQuery,
|
||||
KnowledgeSearchTimings,
|
||||
KnowledgeSearchResult
|
||||
KnowledgeSearchResult,
|
||||
KnowledgeSourceMessage,
|
||||
KnowledgeConversationIndexState
|
||||
} from '../../shared/knowledge'
|
||||
import {
|
||||
emptyKnowledgeSearchTimings,
|
||||
KNOWLEDGE_SCHEMA_VERSION,
|
||||
toEvidenceDisplayText
|
||||
} from '../../shared/knowledge'
|
||||
import { chunkConversation } from './chunker'
|
||||
import { chunkConversation, createChunkStreamer } from './chunker'
|
||||
import { normalizeKnowledgeMessage } from './normalizer'
|
||||
|
||||
type DbRow = Record<string, unknown>
|
||||
|
||||
export interface KnowledgeStreamIndexResult {
|
||||
processedMessages: number
|
||||
chunkCount: number
|
||||
cancelled: boolean
|
||||
/** 最后一条已提交收盘 chunk 的结束秒;取消或失败后从这里续跑。 */
|
||||
resumeTime: number | null
|
||||
resumeMessageIds: string[]
|
||||
}
|
||||
|
||||
const YIELD_EVERY = 500
|
||||
const MAX_SAFE_ACCOUNT_SEGMENT = /^[a-f0-9]{32}$/
|
||||
const MAX_CONVERSATION_SUMMARY_SOURCE_MESSAGES = 2_000
|
||||
@@ -1048,7 +1060,10 @@ export class KnowledgeStore {
|
||||
indexed_message_count INTEGER NOT NULL DEFAULT 0,
|
||||
complete_snapshot INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT,
|
||||
updated_at INTEGER NOT NULL
|
||||
updated_at INTEGER NOT NULL,
|
||||
source_high_water_time INTEGER,
|
||||
backfill_resume_time INTEGER,
|
||||
backfill_resume_message_ids TEXT
|
||||
) STRICT;
|
||||
`)
|
||||
const stateColumns = new Set(asRows(this.database.prepare('PRAGMA table_info(knowledge_index_state)').all()).map((row) => String(row.name)))
|
||||
@@ -1058,6 +1073,16 @@ export class KnowledgeStore {
|
||||
if (!stateColumns.has('source_high_water_time')) {
|
||||
this.database.exec('ALTER TABLE knowledge_index_state ADD COLUMN source_high_water_time INTEGER')
|
||||
}
|
||||
// 分批回填的续跑位置:最后一条**已提交**收盘 chunk 的结束秒与它的消息 id。
|
||||
// 进程退出后从这里重读并跳过这些 id,重切结果才能与不间断运行一致。
|
||||
if (!stateColumns.has('backfill_resume_time')) {
|
||||
this.database.exec('ALTER TABLE knowledge_index_state ADD COLUMN backfill_resume_time INTEGER')
|
||||
}
|
||||
if (!stateColumns.has('backfill_resume_message_ids')) {
|
||||
this.database.exec(
|
||||
'ALTER TABLE knowledge_index_state ADD COLUMN backfill_resume_message_ids TEXT'
|
||||
)
|
||||
}
|
||||
const messageColumns = new Set(
|
||||
asRows(this.database.prepare('PRAGMA table_info(knowledge_messages)').all()).map((row) =>
|
||||
String(row.name)
|
||||
@@ -1074,7 +1099,19 @@ export class KnowledgeStore {
|
||||
if (!messageColumns.has('image_ocr_text')) {
|
||||
this.database.exec('ALTER TABLE knowledge_messages ADD COLUMN image_ocr_text TEXT')
|
||||
}
|
||||
this.writeMetaIfMissing('schema_version', String(KNOWLEDGE_SCHEMA_VERSION))
|
||||
const storedSchemaVersion = Number(this.readMeta('schema_version') ?? 0)
|
||||
if (storedSchemaVersion > 0 && storedSchemaVersion !== KNOWLEDGE_SCHEMA_VERSION) {
|
||||
// 身份规则变了:旧 message_id 与新身份完全失配,保留等于留下一堆指向错误消息的证据。
|
||||
// 索引是派生的、可重建,这里整体作废,让下一遍 pass 按新身份重建。
|
||||
this.database.exec(
|
||||
'DELETE FROM knowledge_chunks; DELETE FROM knowledge_messages; DELETE FROM knowledge_index_state;'
|
||||
)
|
||||
this.database.exec('DROP TABLE IF EXISTS knowledge_fts')
|
||||
this.createFtsTable()
|
||||
this.writeMeta('schema_version', String(KNOWLEDGE_SCHEMA_VERSION))
|
||||
} else {
|
||||
this.writeMetaIfMissing('schema_version', String(KNOWLEDGE_SCHEMA_VERSION))
|
||||
}
|
||||
const storedAccount = this.readMeta('account_id')
|
||||
if (storedAccount && storedAccount !== this.accountId) {
|
||||
throw new Error('Knowledge database account isolation check failed')
|
||||
@@ -1244,8 +1281,293 @@ export class KnowledgeStore {
|
||||
}
|
||||
}
|
||||
|
||||
private async writeMessageLedger(
|
||||
/** 分批索引:不持有整会话消息;旧 chunk 不预删,取消后原索引仍可用。 */
|
||||
async indexConversationStreaming(
|
||||
conversationId: string,
|
||||
batches: AsyncIterable<readonly KnowledgeSourceMessage[]>,
|
||||
chunker: KnowledgeChunkerConfig,
|
||||
options: {
|
||||
completeSnapshot: boolean
|
||||
sourceHighWaterTime?: number
|
||||
/** 上次中断位置;从该秒重读并跳过这些已提交消息。 */
|
||||
resume?: { time: number; messageIds: string[] }
|
||||
},
|
||||
signal: AbortSignal | undefined,
|
||||
onProgress: (processed: number, chunks: number) => void
|
||||
): Promise<KnowledgeStreamIndexResult> {
|
||||
if (!conversationId) throw new Error('Knowledge conversation id is required')
|
||||
const streamer = createChunkStreamer(chunker)
|
||||
const passStartedAt = Date.now()
|
||||
const skipIds = new Set(options.resume?.messageIds ?? [])
|
||||
// 续跑只重建边界之后的部分;边界那一秒已提交的消息必须整秒排除,
|
||||
// 否则重切出的 chunk 会与已提交的那一个重复。
|
||||
const rebuildFromTime = options.resume ? options.resume.time + 1 : 0
|
||||
if (options.resume) {
|
||||
const rows = asRows(
|
||||
this.database
|
||||
.prepare(
|
||||
'SELECT message_id FROM knowledge_messages WHERE conversation_id = ? AND create_time = ?'
|
||||
)
|
||||
.all(conversationId, options.resume.time)
|
||||
)
|
||||
for (const row of rows) skipIds.add(String(row.message_id))
|
||||
}
|
||||
let processed = 0
|
||||
let chunkCount = 0
|
||||
let resumeTime = options.resume?.time ?? null
|
||||
let resumeIds: string[] = options.resume?.messageIds?.slice() ?? []
|
||||
|
||||
const commitChunks = (chunks: KnowledgeChunk[], now: number): void => {
|
||||
for (const chunk of chunks) {
|
||||
this.upsertChunkIdempotent(chunk, now)
|
||||
chunkCount += 1
|
||||
resumeTime = chunk.endTime
|
||||
resumeIds = chunk.messageIds.slice()
|
||||
}
|
||||
}
|
||||
|
||||
const commitBatch = async (normalized: KnowledgeNormalizedMessage[]): Promise<void> => {
|
||||
this.database.exec('BEGIN IMMEDIATE')
|
||||
try {
|
||||
await this.writeMessageLedger(conversationId, normalized, false, signal, (count) => {
|
||||
onProgress(processed + count, chunkCount)
|
||||
})
|
||||
commitChunks(streamer.push(normalized), Date.now())
|
||||
this.writeBackfillCursor(
|
||||
conversationId,
|
||||
chunker.version,
|
||||
processed,
|
||||
resumeTime,
|
||||
resumeIds
|
||||
)
|
||||
this.database.exec('COMMIT')
|
||||
} catch (error) {
|
||||
this.database.exec('ROLLBACK')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
let cancelled = false
|
||||
try {
|
||||
for await (const batch of batches) {
|
||||
this.assertNotAborted(signal)
|
||||
if (!batch.length) continue
|
||||
const normalized: KnowledgeNormalizedMessage[] = []
|
||||
for (const message of batch) {
|
||||
if (message.accountId !== this.accountId) {
|
||||
throw new Error('Knowledge source account does not match database')
|
||||
}
|
||||
if (message.conversationId !== conversationId) {
|
||||
throw new Error('Knowledge source conversation does not match request')
|
||||
}
|
||||
const item = normalizeKnowledgeMessage(message)
|
||||
// 续跑重读到的已提交消息不能再进入切分,否则会产生内容重复的 chunk。
|
||||
if (skipIds.delete(item.messageId)) continue
|
||||
normalized.push(item)
|
||||
}
|
||||
processed += normalized.length
|
||||
// 空批次也要落一次游标:上游可能连续返回"全是已提交消息"的页。
|
||||
if (normalized.length) await commitBatch(normalized)
|
||||
onProgress(processed, chunkCount)
|
||||
}
|
||||
|
||||
this.database.exec('BEGIN IMMEDIATE')
|
||||
try {
|
||||
commitChunks(streamer.drain(), Date.now())
|
||||
await this.purgeStaleChunks(
|
||||
conversationId,
|
||||
chunker.version,
|
||||
rebuildFromTime,
|
||||
passStartedAt,
|
||||
signal
|
||||
)
|
||||
this.upsertState(
|
||||
conversationId,
|
||||
chunker.version,
|
||||
'ready',
|
||||
resumeTime,
|
||||
processed,
|
||||
null,
|
||||
options.completeSnapshot,
|
||||
options.sourceHighWaterTime ?? null
|
||||
)
|
||||
this.clearBackfillCursor(conversationId)
|
||||
this.database.exec('COMMIT')
|
||||
} catch (error) {
|
||||
this.database.exec('ROLLBACK')
|
||||
throw error
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal?.aborted) {
|
||||
cancelled = true
|
||||
} else {
|
||||
this.markBackfillFailed(conversationId, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
return { processedMessages: processed, chunkCount, cancelled, resumeTime, resumeMessageIds: resumeIds }
|
||||
}
|
||||
|
||||
/** 每个会话的索引状态快照:覆盖度判断只能看它,不能看全局最新时间。 */
|
||||
readConversationIndexStates(): Record<string, KnowledgeConversationIndexState> {
|
||||
const rows = asRows(
|
||||
this.database
|
||||
.prepare(
|
||||
`SELECT conversation_id, state, complete_snapshot, source_high_water_time, indexed_message_count
|
||||
FROM knowledge_index_state`
|
||||
)
|
||||
.all()
|
||||
)
|
||||
const result: Record<string, KnowledgeConversationIndexState> = {}
|
||||
for (const row of rows) {
|
||||
const highWater = Number(row.source_high_water_time)
|
||||
result[String(row.conversation_id)] = {
|
||||
state: String(row.state ?? ''),
|
||||
completeSnapshot: Number(row.complete_snapshot) === 1,
|
||||
sourceHighWaterTime: Number.isFinite(highWater) && highWater > 0 ? highWater : null,
|
||||
indexedMessageCount: Number(row.indexed_message_count) || 0
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** 分批回填结束后补写源侧边界;只前进,不回退。 */
|
||||
advanceSourceHighWater(conversationId: string, value: number): void {
|
||||
if (!Number.isFinite(value) || value <= 0) return
|
||||
this.database
|
||||
.prepare(
|
||||
`UPDATE knowledge_index_state
|
||||
SET source_high_water_time = MAX(COALESCE(source_high_water_time, 0), ?),
|
||||
updated_at = ?
|
||||
WHERE conversation_id = ?`
|
||||
)
|
||||
.run(Math.floor(value), Date.now(), conversationId)
|
||||
}
|
||||
|
||||
/** 整遍读完时才刷新的全局口径;分批 pass 不得调用。 */
|
||||
writeSourceTotals(sourceMessageCount: number, sourceLatestAt?: number): void {
|
||||
this.writeMeta('source_message_count', String(sourceMessageCount))
|
||||
this.refreshStatsSnapshot()
|
||||
if (typeof sourceLatestAt === 'number' && sourceLatestAt > 0) {
|
||||
this.writeMeta('source_latest_at', String(Math.floor(sourceLatestAt)))
|
||||
}
|
||||
}
|
||||
|
||||
/** 上次中断的分页位置;没有可复用的位置时返回 null。 */
|
||||
readBackfillResume(conversationId: string): { time: number; messageIds: string[] } | null {
|
||||
const row = this.database
|
||||
.prepare(
|
||||
'SELECT backfill_resume_time, backfill_resume_message_ids FROM knowledge_index_state WHERE conversation_id = ?'
|
||||
)
|
||||
.get(conversationId) as DbRow | undefined
|
||||
const time = Number(row?.backfill_resume_time)
|
||||
if (!Number.isFinite(time) || time <= 0) return null
|
||||
let messageIds: string[] = []
|
||||
try {
|
||||
const parsed = JSON.parse(String(row?.backfill_resume_message_ids || '[]'))
|
||||
if (Array.isArray(parsed)) messageIds = parsed.map((value) => String(value))
|
||||
} catch {
|
||||
messageIds = []
|
||||
}
|
||||
return { time, messageIds }
|
||||
}
|
||||
|
||||
private writeBackfillCursor(
|
||||
conversationId: string,
|
||||
chunkerVersion: string,
|
||||
messageCount: number,
|
||||
resumeTime: number | null,
|
||||
resumeMessageIds: string[]
|
||||
): void {
|
||||
this.database
|
||||
.prepare(
|
||||
`INSERT INTO knowledge_index_state (
|
||||
conversation_id, account_id, chunker_version, state, high_water_time,
|
||||
indexed_message_count, complete_snapshot, last_error, updated_at,
|
||||
backfill_resume_time, backfill_resume_message_ids
|
||||
) VALUES (?, ?, ?, 'backfilling', NULL, ?, 0, NULL, ?, ?, ?)
|
||||
ON CONFLICT(conversation_id) DO UPDATE SET
|
||||
chunker_version = excluded.chunker_version,
|
||||
state = 'backfilling',
|
||||
indexed_message_count = excluded.indexed_message_count,
|
||||
complete_snapshot = 0,
|
||||
updated_at = excluded.updated_at,
|
||||
backfill_resume_time = excluded.backfill_resume_time,
|
||||
backfill_resume_message_ids = excluded.backfill_resume_message_ids`
|
||||
)
|
||||
.run(
|
||||
conversationId,
|
||||
this.accountId,
|
||||
chunkerVersion,
|
||||
messageCount,
|
||||
Date.now(),
|
||||
resumeTime,
|
||||
encodedJson(resumeMessageIds)
|
||||
)
|
||||
}
|
||||
|
||||
private clearBackfillCursor(conversationId: string): void {
|
||||
this.database
|
||||
.prepare(
|
||||
`UPDATE knowledge_index_state
|
||||
SET backfill_resume_time = NULL, backfill_resume_message_ids = NULL
|
||||
WHERE conversation_id = ?`
|
||||
)
|
||||
.run(conversationId)
|
||||
}
|
||||
|
||||
private markBackfillFailed(conversationId: string, error: unknown): void {
|
||||
try {
|
||||
this.database
|
||||
.prepare(
|
||||
`UPDATE knowledge_index_state
|
||||
SET state = 'partial', last_error = ?, updated_at = ?
|
||||
WHERE conversation_id = ?`
|
||||
)
|
||||
.run(error instanceof Error ? error.message : String(error), Date.now(), conversationId)
|
||||
} catch {
|
||||
// 失败标记本身失败时保留原状态,调用方仍能从异常得知结果。
|
||||
}
|
||||
}
|
||||
|
||||
/** 两个条件缺一不可:漏掉 `end_time >= fromEndTime` 会把已提交的前半段整段删掉。 */
|
||||
private async purgeStaleChunks(
|
||||
conversationId: string,
|
||||
chunkerVersion: string,
|
||||
fromEndTime: number,
|
||||
beforeUpdatedAt: number,
|
||||
signal: AbortSignal | undefined
|
||||
): Promise<void> {
|
||||
const select = this.database.prepare(
|
||||
`SELECT rowid, text FROM knowledge_chunks
|
||||
WHERE conversation_id = ? AND chunker_version = ? AND updated_at < ? AND end_time >= ?
|
||||
LIMIT 200`
|
||||
)
|
||||
const remove = this.database.prepare('DELETE FROM knowledge_chunks WHERE rowid = ?')
|
||||
while (true) {
|
||||
this.assertNotAborted(signal)
|
||||
const rows = asRows(select.all(conversationId, chunkerVersion, beforeUpdatedAt, fromEndTime))
|
||||
if (!rows.length) break
|
||||
for (const row of rows) {
|
||||
this.deleteFtsRow(Number(row.rowid), String(row.text))
|
||||
remove.run(Number(row.rowid))
|
||||
}
|
||||
await waitForWorkerTurn()
|
||||
}
|
||||
}
|
||||
|
||||
private upsertChunkIdempotent(chunk: KnowledgeChunk, now: number): void {
|
||||
const existing = this.database
|
||||
.prepare('SELECT rowid FROM knowledge_chunks WHERE chunk_id = ?')
|
||||
.get(chunk.chunkId) as DbRow | undefined
|
||||
// chunk_id 由 messageIds 决定,同 id 即同正文;重读时先撤旧 FTS 行再插入,
|
||||
// 否则 FTS5 会对已存在的 rowid 报唯一约束。
|
||||
if (existing) this.deleteFtsRow(Number(existing.rowid), chunk.text)
|
||||
this.upsertChunk(chunk, now)
|
||||
}
|
||||
|
||||
private async writeMessageLedger( conversationId: string,
|
||||
messages: KnowledgeNormalizedMessage[],
|
||||
completeSnapshot: boolean,
|
||||
signal: AbortSignal | undefined,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { fork, type ChildProcess } from 'child_process'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { tmpdir } from 'os'
|
||||
import { terminateChildProcess, waitForChildExit } from '../process-tree'
|
||||
import type {
|
||||
KnowledgeCapacityPreflight,
|
||||
KnowledgeCapacityPreflightRequest,
|
||||
@@ -12,6 +14,14 @@ import type {
|
||||
KnowledgeSearchRequest,
|
||||
KnowledgeSearchResult,
|
||||
KnowledgeStatusRequest,
|
||||
KnowledgeConversationIndexState,
|
||||
KnowledgeConversationStatesRequest,
|
||||
KnowledgeSourceTotalsRequest,
|
||||
KnowledgeStreamBatchRequest,
|
||||
KnowledgeStreamConversationRequest,
|
||||
KnowledgeStreamResult,
|
||||
KnowledgeStreamStartRequest,
|
||||
KnowledgeStreamStartResult,
|
||||
KnowledgeWorkerRequest,
|
||||
KnowledgeWorkerResponse
|
||||
} from '../../shared/knowledge'
|
||||
@@ -22,7 +32,10 @@ type WorkerResult =
|
||||
| KnowledgeSearchResult
|
||||
| KnowledgeRuntimeStatus
|
||||
| KnowledgeMemberStatsResult
|
||||
| KnowledgeStreamStartResult
|
||||
| KnowledgeStreamResult
|
||||
| { marks: Record<string, number> }
|
||||
| { accepted: true }
|
||||
| { removed: true }
|
||||
type PendingRequest = {
|
||||
resolve: (result: WorkerResult) => void
|
||||
@@ -48,6 +61,8 @@ export class KnowledgeWorkerHost {
|
||||
* 精确地只中止索引,而**不会**影响任何并发进行的查询请求。
|
||||
*/
|
||||
private activeIndexRequestId: string | null = null
|
||||
/** 进度消息回带的是已 resolve 的 streamStart requestId,不能靠 `pending` 找回调。 */
|
||||
private readonly streamProgress = new Map<string, (progress: KnowledgeIndexProgress) => void>()
|
||||
|
||||
constructor(private readonly workerPath: string) {}
|
||||
|
||||
@@ -72,6 +87,16 @@ export class KnowledgeWorkerHost {
|
||||
return this.request('status', payload) as Promise<KnowledgeRuntimeStatus>
|
||||
}
|
||||
|
||||
/** 每个会话的索引状态;覆盖度判断的唯一依据。 */
|
||||
conversationStates(
|
||||
payload: KnowledgeConversationStatesRequest
|
||||
): Promise<Record<string, KnowledgeConversationIndexState>> {
|
||||
return this.request('conversationStates', payload).then(
|
||||
(result) =>
|
||||
(result as { states?: Record<string, KnowledgeConversationIndexState> }).states ?? {}
|
||||
)
|
||||
}
|
||||
|
||||
/** 每个会话已经索引到的源侧时刻;用于增量 pass 跳过没有变化的会话。 */
|
||||
highWaterMarks(payload: KnowledgeStatusRequest): Promise<Record<string, number>> {
|
||||
return this.request('highWater', payload as unknown as KnowledgeWorkerRequest['payload']).then(
|
||||
@@ -84,6 +109,46 @@ export class KnowledgeWorkerHost {
|
||||
return this.request('memberStats', payload) as Promise<KnowledgeMemberStatsResult>
|
||||
}
|
||||
|
||||
/** 开始一个会话的分批索引;消息由调用方逐批推送。 */
|
||||
async startConversationStream(
|
||||
payload: KnowledgeStreamStartRequest,
|
||||
onProgress?: (progress: KnowledgeIndexProgress) => void
|
||||
): Promise<KnowledgeStreamStartResult> {
|
||||
if (onProgress) this.streamProgress.set(payload.conversationId, onProgress)
|
||||
try {
|
||||
return (await this.request('streamStart', payload)) as KnowledgeStreamStartResult
|
||||
} catch (error) {
|
||||
this.streamProgress.delete(payload.conversationId)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async pushConversationBatch(payload: KnowledgeStreamBatchRequest): Promise<void> {
|
||||
await this.request('streamBatch', payload)
|
||||
}
|
||||
|
||||
async finishConversationStream(
|
||||
payload: KnowledgeStreamConversationRequest
|
||||
): Promise<KnowledgeStreamResult> {
|
||||
try {
|
||||
return (await this.request('streamFinish', payload)) as KnowledgeStreamResult
|
||||
} finally {
|
||||
this.streamProgress.delete(payload.conversationId)
|
||||
}
|
||||
}
|
||||
|
||||
async writeSourceTotals(payload: KnowledgeSourceTotalsRequest): Promise<void> {
|
||||
await this.request('sourceTotals', payload)
|
||||
}
|
||||
|
||||
async abortConversationStream(payload: KnowledgeStreamConversationRequest): Promise<void> {
|
||||
try {
|
||||
await this.request('streamAbort', payload)
|
||||
} finally {
|
||||
this.streamProgress.delete(payload.conversationId)
|
||||
}
|
||||
}
|
||||
|
||||
/** 只中止正在跑的索引任务,返回是否真的有任务被中止。 */
|
||||
async cancelActiveIndex(): Promise<boolean> {
|
||||
const target = this.activeIndexRequestId
|
||||
@@ -100,16 +165,30 @@ export class KnowledgeWorkerHost {
|
||||
return this.request('cancel', { targetRequestId }) as Promise<{ removed: true }>
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
async dispose(options: { closeTimeoutMs?: number; exitTimeoutMs?: number } = {}): Promise<void> {
|
||||
const child = this.child
|
||||
if (!child) return
|
||||
const closeTimeoutMs = options.closeTimeoutMs ?? 1_500
|
||||
const exitTimeoutMs = options.exitTimeoutMs ?? 2_000
|
||||
// close 请求必须有超时,避免同步 SQLite 事务把应用退出永久挂死。
|
||||
const closePromise = this.request('close', {}).catch(() => undefined)
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
try {
|
||||
await this.request('close', {})
|
||||
} catch {
|
||||
// The child is about to be stopped; its only job is a derived local index.
|
||||
await Promise.race([
|
||||
closePromise,
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, closeTimeoutMs)
|
||||
})
|
||||
])
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer)
|
||||
}
|
||||
if (this.child === child) this.child = null
|
||||
if (!child.killed) child.kill()
|
||||
const exited = await waitForChildExit(child, 300)
|
||||
if (!exited) {
|
||||
await terminateChildProcess(child, { timeoutMs: exitTimeoutMs })
|
||||
}
|
||||
this.failAll(new Error('Knowledge worker disposed'))
|
||||
}
|
||||
|
||||
private request(
|
||||
@@ -141,6 +220,7 @@ export class KnowledgeWorkerHost {
|
||||
private ensureChild(): ChildProcess {
|
||||
if (this.child?.connected) return this.child
|
||||
const child = fork(this.workerPath, [], {
|
||||
cwd: tmpdir(),
|
||||
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
||||
serialization: 'advanced',
|
||||
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
|
||||
@@ -148,9 +228,16 @@ export class KnowledgeWorkerHost {
|
||||
child.on('message', (message: KnowledgeWorkerResponse) => {
|
||||
if (message?.version !== 1) return
|
||||
if (message.type === 'progress') {
|
||||
const progress = message.payload as KnowledgeIndexProgress | undefined
|
||||
if (!progress) return
|
||||
const pending = this.pending.get(message.requestId)
|
||||
if (pending && message.payload)
|
||||
pending.onProgress?.(message.payload as KnowledgeIndexProgress)
|
||||
if (pending?.onProgress) {
|
||||
pending.onProgress(progress)
|
||||
return
|
||||
}
|
||||
if (progress.conversationId) {
|
||||
this.streamProgress.get(progress.conversationId)?.(progress)
|
||||
}
|
||||
return
|
||||
}
|
||||
this.finish(
|
||||
@@ -218,6 +305,7 @@ export class KnowledgeWorkerHost {
|
||||
}
|
||||
|
||||
private failAll(error: Error): void {
|
||||
this.streamProgress.clear()
|
||||
for (const requestId of this.pending.keys()) this.finish(requestId, undefined, error)
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,21 @@ import type {
|
||||
KnowledgeMemberStatsResult,
|
||||
KnowledgeRuntimeStatus,
|
||||
KnowledgeSearchRequest,
|
||||
KnowledgeSourceMessage,
|
||||
KnowledgeStatusRequest,
|
||||
KnowledgeStreamBatchRequest,
|
||||
KnowledgeStreamConversationRequest,
|
||||
KnowledgeStreamResult,
|
||||
KnowledgeConversationStatesRequest,
|
||||
KnowledgeSourceTotalsRequest,
|
||||
KnowledgeStreamStartRequest,
|
||||
KnowledgeWorkerRequest,
|
||||
KnowledgeWorkerResponse
|
||||
} from '../../shared/knowledge'
|
||||
import { emptyKnowledgeSearchTimings } from '../../shared/knowledge'
|
||||
import {
|
||||
DEFAULT_KNOWLEDGE_FTS_CONFIG,
|
||||
emptyKnowledgeSearchTimings
|
||||
} from '../../shared/knowledge'
|
||||
import {
|
||||
KnowledgeStore,
|
||||
estimateKnowledgeCapacityPreflight,
|
||||
@@ -22,6 +32,74 @@ import { serialize } from 'v8'
|
||||
const stores = new Map<string, KnowledgeStore>()
|
||||
const controllers = new Map<string, AbortController>()
|
||||
|
||||
/** 背压:主进程拉下一页前 Worker 已提交上一批,两侧同时驻留上限是「一页 × 2」。 */
|
||||
class StreamingBatchQueue {
|
||||
private readonly buffer: KnowledgeSourceMessage[][] = []
|
||||
private wake: (() => void) | null = null
|
||||
private closed = false
|
||||
private failure: Error | null = null
|
||||
|
||||
push(batch: KnowledgeSourceMessage[]): void {
|
||||
if (this.closed) return
|
||||
this.buffer.push(batch)
|
||||
this.release()
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.closed) return
|
||||
this.closed = true
|
||||
this.release()
|
||||
}
|
||||
|
||||
fail(error: Error): void {
|
||||
if (this.failure) return
|
||||
this.failure = error
|
||||
this.closed = true
|
||||
this.release()
|
||||
}
|
||||
|
||||
private release(): void {
|
||||
const resolve = this.wake
|
||||
this.wake = null
|
||||
resolve?.()
|
||||
}
|
||||
|
||||
async *iterate(): AsyncGenerator<readonly KnowledgeSourceMessage[], void, void> {
|
||||
while (true) {
|
||||
if (!this.buffer.length && !this.closed) {
|
||||
await new Promise<void>((resolve) => {
|
||||
this.wake = resolve
|
||||
})
|
||||
}
|
||||
const next = this.buffer.shift()
|
||||
if (next) {
|
||||
yield next
|
||||
continue
|
||||
}
|
||||
if (this.failure) throw this.failure
|
||||
if (this.closed) return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type StreamSession = {
|
||||
queue: StreamingBatchQueue
|
||||
controller: AbortController
|
||||
store: KnowledgeStore
|
||||
task: Promise<{
|
||||
processedMessages: number
|
||||
chunkCount: number
|
||||
cancelled: boolean
|
||||
resumeTime: number | null
|
||||
}>
|
||||
}
|
||||
|
||||
const streamSessions = new Map<string, StreamSession>()
|
||||
|
||||
function streamKey(payload: { databaseRoot: string; accountId: string; conversationId: string }): string {
|
||||
return `${payload.databaseRoot}|${payload.accountId}|${payload.conversationId}`
|
||||
}
|
||||
|
||||
function send(
|
||||
message: KnowledgeWorkerResponse,
|
||||
transport?: KnowledgeWorkerResponse['transport']
|
||||
@@ -91,8 +169,139 @@ async function handleIndex(
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePreflight(
|
||||
async function handleStreamStart(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeStreamStartRequest
|
||||
): Promise<void> {
|
||||
const key = streamKey(payload)
|
||||
if (streamSessions.has(key)) throw new Error('该会话已在建立索引')
|
||||
|
||||
const queue = new StreamingBatchQueue()
|
||||
const controller = new AbortController()
|
||||
const store = getStore(payload)
|
||||
// 续跑位置由 Worker 自己读:主进程只知道"这一遍要重建",不该关心分页细节。
|
||||
// 显式 `null` 表示从零重建,不能落到 `??` 的默认分支里。
|
||||
const explicitResume = payload.resume
|
||||
const resume =
|
||||
explicitResume === null
|
||||
? undefined
|
||||
: explicitResume ??
|
||||
(payload.completeSnapshot
|
||||
? store.readBackfillResume(payload.conversationId) ?? undefined
|
||||
: undefined)
|
||||
const task = store.indexConversationStreaming(
|
||||
payload.conversationId,
|
||||
queue.iterate(),
|
||||
payload.chunker,
|
||||
{
|
||||
completeSnapshot: payload.completeSnapshot,
|
||||
sourceHighWaterTime: payload.sourceHighWaterTime,
|
||||
resume
|
||||
},
|
||||
controller.signal,
|
||||
(processedMessages, indexedChunks) => {
|
||||
send({
|
||||
version: 1,
|
||||
type: 'progress',
|
||||
requestId: request.requestId,
|
||||
payload: {
|
||||
accountId: payload.accountId,
|
||||
phase: 'indexing',
|
||||
conversationId: payload.conversationId,
|
||||
processedMessages,
|
||||
// 流式回填的会话总量未知,进度只上报已处理条数。
|
||||
totalMessages: 0,
|
||||
indexedChunks
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
// 主进程可能在中途放弃这个会话;未消费的 rejection 会打崩 Worker 进程。
|
||||
task.catch(() => undefined)
|
||||
streamSessions.set(key, { queue, controller, store, task })
|
||||
|
||||
send({
|
||||
version: 1,
|
||||
type: 'result',
|
||||
requestId: request.requestId,
|
||||
payload: { started: true, resumedFrom: resume?.time ?? null }
|
||||
})
|
||||
}
|
||||
|
||||
async function handleStreamBatch(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeStreamBatchRequest
|
||||
): Promise<void> {
|
||||
const session = streamSessions.get(streamKey(payload))
|
||||
if (!session) throw new Error('该会话没有进行中的索引任务')
|
||||
session.queue.push(payload.messages)
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { accepted: true } })
|
||||
}
|
||||
|
||||
async function handleStreamFinish(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeStreamConversationRequest
|
||||
): Promise<void> {
|
||||
const key = streamKey(payload)
|
||||
const session = streamSessions.get(key)
|
||||
if (!session) throw new Error('该会话没有进行中的索引任务')
|
||||
streamSessions.delete(key)
|
||||
session.queue.close()
|
||||
const result = await session.task
|
||||
if (typeof payload.sourceHighWaterTime === 'number') {
|
||||
session.store.advanceSourceHighWater(payload.conversationId, payload.sourceHighWaterTime)
|
||||
}
|
||||
if (typeof payload.sourceMessageCount === 'number') {
|
||||
session.store.writeSourceTotals(payload.sourceMessageCount, payload.sourceLatestAt)
|
||||
}
|
||||
const streamResult: KnowledgeStreamResult = {
|
||||
conversationId: payload.conversationId,
|
||||
processedMessages: result.processedMessages,
|
||||
chunkCount: result.chunkCount,
|
||||
cancelled: result.cancelled,
|
||||
resumeTime: result.resumeTime
|
||||
}
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: streamResult })
|
||||
}
|
||||
|
||||
async function handleConversationStates(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeConversationStatesRequest
|
||||
): Promise<void> {
|
||||
const path = getKnowledgeDatabasePath(payload.databaseRoot, payload.accountId)
|
||||
const states = existsSync(path)
|
||||
? getStore({ ...payload, fts: DEFAULT_KNOWLEDGE_FTS_CONFIG }).readConversationIndexStates()
|
||||
: {}
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { states } })
|
||||
}
|
||||
|
||||
async function handleSourceTotals(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeSourceTotalsRequest
|
||||
): Promise<void> {
|
||||
// 没有已打开的库就说明这一遍没有真正写过索引,不新建空库来记口径。
|
||||
stores
|
||||
.get(storeKey(payload.databaseRoot, payload.accountId))
|
||||
?.writeSourceTotals(payload.sourceMessageCount, payload.sourceLatestAt)
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { accepted: true } })
|
||||
}
|
||||
|
||||
async function handleStreamAbort(
|
||||
request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeStreamConversationRequest
|
||||
): Promise<void> {
|
||||
const key = streamKey(payload)
|
||||
const session = streamSessions.get(key)
|
||||
streamSessions.delete(key)
|
||||
if (session) {
|
||||
session.controller.abort()
|
||||
session.queue.close()
|
||||
await session.task.catch(() => undefined)
|
||||
}
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { removed: true } })
|
||||
}
|
||||
|
||||
async function handlePreflight( request: KnowledgeWorkerRequest,
|
||||
payload: KnowledgeCapacityPreflightRequest
|
||||
): Promise<void> {
|
||||
const result = await estimateKnowledgeCapacityPreflight(payload)
|
||||
@@ -226,11 +435,21 @@ async function handle(request: KnowledgeWorkerRequest, messageReceivedAt: number
|
||||
if (request.type === 'cancel') {
|
||||
const payload = request.payload as { targetRequestId: string }
|
||||
controllers.get(payload.targetRequestId)?.abort()
|
||||
// 分批索引用的是自己的 controller:漏掉它,取消会一直等到整遍跑完才生效。
|
||||
for (const session of streamSessions.values()) {
|
||||
session.controller.abort()
|
||||
session.queue.close()
|
||||
}
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { removed: true } })
|
||||
return
|
||||
}
|
||||
if (request.type === 'close') {
|
||||
for (const controller of controllers.values()) controller.abort()
|
||||
for (const session of streamSessions.values()) {
|
||||
session.controller.abort()
|
||||
session.queue.close()
|
||||
}
|
||||
streamSessions.clear()
|
||||
for (const store of stores.values()) store.close()
|
||||
stores.clear()
|
||||
send({ version: 1, type: 'result', requestId: request.requestId, payload: { removed: true } })
|
||||
@@ -268,6 +487,30 @@ async function handle(request: KnowledgeWorkerRequest, messageReceivedAt: number
|
||||
await handleIndex(request, request.payload as KnowledgeIndexRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'streamStart') {
|
||||
await handleStreamStart(request, request.payload as KnowledgeStreamStartRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'streamBatch') {
|
||||
await handleStreamBatch(request, request.payload as KnowledgeStreamBatchRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'streamFinish') {
|
||||
await handleStreamFinish(request, request.payload as KnowledgeStreamConversationRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'streamAbort') {
|
||||
await handleStreamAbort(request, request.payload as KnowledgeStreamConversationRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'conversationStates') {
|
||||
await handleConversationStates(request, request.payload as KnowledgeConversationStatesRequest)
|
||||
return
|
||||
}
|
||||
if (request.type === 'sourceTotals') {
|
||||
await handleSourceTotals(request, request.payload as KnowledgeSourceTotalsRequest)
|
||||
return
|
||||
}
|
||||
throw new Error(`Unsupported knowledge worker request: ${String(request.type)}`)
|
||||
} catch (error) {
|
||||
send({
|
||||
@@ -279,7 +522,14 @@ async function handle(request: KnowledgeWorkerRequest, messageReceivedAt: number
|
||||
}
|
||||
}
|
||||
|
||||
// 必须串行:分批索引在批与批之间 await,新请求切入会把 BEGIN IMMEDIATE 嵌套起来。
|
||||
let requestChain: Promise<void> = Promise.resolve()
|
||||
|
||||
process.on('message', (message: KnowledgeWorkerRequest) => {
|
||||
if (message?.version !== 1) return
|
||||
void handle(message, Date.now())
|
||||
if (message.type === 'streamAbort' || message.type === 'cancel') {
|
||||
void handle(message, Date.now())
|
||||
return
|
||||
}
|
||||
requestChain = requestChain.then(() => handle(message, Date.now()))
|
||||
})
|
||||
@@ -1,24 +1,9 @@
|
||||
/**
|
||||
* 消息身份的**唯一真源**。
|
||||
*
|
||||
* 这个规则同时被三处需要:
|
||||
* - Knowledge 索引写入 `knowledge_messages.message_id`
|
||||
* - 图片文字索引的 binding(必须与 Knowledge 里的 message_id 完全一致,否则 OCR 文本贴不到消息上)
|
||||
* - Evidence → 档案跳转的 messageRef
|
||||
*
|
||||
* 任何一处各自复制一份,都会在 `local:` 前缀上静默失配(项目里已经有这个坑的历史注释),
|
||||
* 所以抽成一个模块,谁都不许再抄。
|
||||
*/
|
||||
/** 消息身份的唯一真源:Knowledge 索引、图片 OCR binding、messageRef 三处必须用同一份。 */
|
||||
import type * as chat from '../services/chat-service'
|
||||
|
||||
/**
|
||||
* 源消息 → 稳定消息 id。
|
||||
*
|
||||
* 降级顺序刻意保守:`localId` 是 WCDB 行内最稳的本地 id;其次用消息自带 id;
|
||||
* 最后才退化成「时间 + 服务端 id / 内容」的组合(仅在极端缺字段时命中)。
|
||||
*/
|
||||
/** localId 跨分片会重号,必须带上 create_time 才唯一;serverId 会被复用,不能当身份。 */
|
||||
export function sourceMessageId(message: chat.FormattedMessage): string {
|
||||
if (message.localId) return `local:${message.localId}`
|
||||
if (message.localId) return `local:${message.createTime || 0}:${message.localId}`
|
||||
if (message.id) return String(message.id)
|
||||
return `${message.createTime || 0}:${message.serverId || message.content}`
|
||||
}
|
||||
+240
-48
@@ -26,14 +26,31 @@ type ShareContent = {
|
||||
type ForwardedMessageItem = {
|
||||
messageType: number
|
||||
sender?: string
|
||||
sourceHeadUrl?: string
|
||||
sentAt?: string
|
||||
text: string
|
||||
title?: string
|
||||
dataId?: string
|
||||
dataIndex?: number
|
||||
imageMd5?: string
|
||||
thumbMd5?: string
|
||||
imageDatName?: string
|
||||
cdnFileId?: string
|
||||
cdnAesKey?: string
|
||||
rawXml?: string
|
||||
exportMediaUrl?: string
|
||||
dataSize?: number
|
||||
thumbSize?: number
|
||||
fileExt?: string
|
||||
linkUrl?: string
|
||||
nestedTitle?: string
|
||||
nested?: ForwardedMessageItem[]
|
||||
}
|
||||
type ForwardBundleContent = {
|
||||
type: 'forwardBundle'
|
||||
title: string
|
||||
description?: string
|
||||
recordDir?: string
|
||||
items: ForwardedMessageItem[]
|
||||
}
|
||||
type MiniProgramContent = {
|
||||
@@ -334,7 +351,12 @@ function parseImageMessage(content: string): ParsedContent {
|
||||
|
||||
const encrypVer = parseInt(encrypVerStr, 10)
|
||||
|
||||
if (!md5 && !datName) {
|
||||
// 企业微信插件的图片消息:message_content 解压后是 `<img aeskey="..." encryver="0"
|
||||
// cdnthumburl="..." cdnmidimgurl="..." cdnbigimgurl="..." length="..." hdlength="..."/>`,
|
||||
// **没有 md5 属性**(datName 也藏在 packed_info_data 的 protobuf 里,由
|
||||
// parseImageDatNameFromRow 从 row 提取)。普通微信图片的 <img> 带 md5,这里按 aeskey
|
||||
// 存在与否补判图片身份,避免这类消息被误判成「不支持的消息」。
|
||||
if (!md5 && !datName && !aeskey) {
|
||||
return { type: 'unknown', raw: content }
|
||||
}
|
||||
|
||||
@@ -601,58 +623,225 @@ function parseForwardBundle(content: string): ForwardBundleContent {
|
||||
const normalized = decodeXmlEntities(stripChatroomPrefix(content))
|
||||
const title = decodeXmlEntities(extractXmlValue(normalized, 'title')) || '聊天记录'
|
||||
const description = decodeXmlEntities(extractXmlValue(normalized, 'des')) || undefined
|
||||
const containers = Array.from(
|
||||
normalized.matchAll(/<recorditem\b[^>]*>([\s\S]*?)<\/recorditem>/gi),
|
||||
(match) => match[1] || ''
|
||||
)
|
||||
const containers = splitBalancedXmlTags(normalized, 'recorditem').map((node) => node.inner)
|
||||
const sources = containers.length ? containers : [normalized]
|
||||
const items = dedupeForwardedItems(sources.flatMap((source) => parseForwardedItems(source)))
|
||||
return { type: 'forwardBundle', title, description, items }
|
||||
}
|
||||
|
||||
function parseForwardedItems(container: string, depth = 0): ForwardedMessageItem[] {
|
||||
if (!container || depth > 4) return []
|
||||
const variants = new Set<string>([container, decodeXmlEntities(container)])
|
||||
for (const match of container.matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g)) {
|
||||
if (match[1]) variants.add(decodeXmlEntities(match[1]))
|
||||
}
|
||||
/**
|
||||
* 按标签嵌套深度提取顶层 XML 元素,避免合并转发套娃(<dataitem> 内嵌套 <recordxml><dataitem>)
|
||||
* 时被非贪婪正则在第一个内层 </dataitem> 处截断。
|
||||
*/
|
||||
function splitBalancedXmlTags(
|
||||
source: string,
|
||||
tagName: string
|
||||
): Array<{ attrs: string; inner: string }> {
|
||||
const xml = source || ''
|
||||
if (!xml) return []
|
||||
const pattern = new RegExp(`<(/?)${tagName}\\b([^>]*)>`, 'gi')
|
||||
const result: Array<{ attrs: string; inner: string }> = []
|
||||
let match: RegExpExecArray | null
|
||||
let depth = 0
|
||||
let openStart = -1
|
||||
let openEnd = -1
|
||||
let openAttrs = ''
|
||||
|
||||
const items: ForwardedMessageItem[] = []
|
||||
for (const variant of variants) {
|
||||
for (const match of variant.matchAll(/<dataitem\b([^>]*)>([\s\S]*?)<\/dataitem>/gi)) {
|
||||
const attributes = match[1] || ''
|
||||
const body = match[2] || ''
|
||||
const attrType = /datatype\s*=\s*["']?(\d+)/i.exec(attributes)?.[1]
|
||||
const messageType = Number.parseInt(attrType || extractXmlValue(body, 'datatype') || '0', 10)
|
||||
const sender = decodeXmlEntities(extractXmlValue(body, 'sourcename')) || undefined
|
||||
const sentAt = extractXmlValue(body, 'sourcetime') || undefined
|
||||
const title = decodeXmlEntities(extractXmlValue(body, 'datatitle'))
|
||||
const description = decodeXmlEntities(
|
||||
extractXmlValue(body, 'datadesc') || extractXmlValue(body, 'content')
|
||||
)
|
||||
const nestedXml = extractXmlBody(body, 'recordxml')
|
||||
const nested =
|
||||
messageType === 17 && nestedXml
|
||||
? parseForwardedItems(decodeXmlEntities(nestedXml), depth + 1)
|
||||
: undefined
|
||||
const text = description || title || forwardedTypeLabel(messageType)
|
||||
if (!sender && !text && !nested?.length) continue
|
||||
items.push({
|
||||
messageType: Number.isFinite(messageType) ? messageType : 0,
|
||||
sender,
|
||||
sentAt,
|
||||
text: text || '[消息]',
|
||||
nested: nested?.length ? nested : undefined
|
||||
while ((match = pattern.exec(xml)) !== null) {
|
||||
const isClosing = match[1] === '/'
|
||||
const attrs = match[2] || ''
|
||||
const rawTag = match[0] || ''
|
||||
const selfClosing = !isClosing && /\/\s*>$/.test(rawTag)
|
||||
|
||||
if (!isClosing) {
|
||||
if (depth === 0) {
|
||||
openStart = match.index
|
||||
openEnd = pattern.lastIndex
|
||||
openAttrs = attrs
|
||||
}
|
||||
if (!selfClosing) {
|
||||
depth += 1
|
||||
} else if (depth === 0 && openEnd >= 0) {
|
||||
result.push({ attrs: openAttrs, inner: '' })
|
||||
openStart = -1
|
||||
openEnd = -1
|
||||
openAttrs = ''
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (depth <= 0) continue
|
||||
depth -= 1
|
||||
if (depth === 0 && openEnd >= 0 && openStart >= 0) {
|
||||
result.push({
|
||||
attrs: openAttrs,
|
||||
inner: xml.slice(openEnd, match.index)
|
||||
})
|
||||
openStart = -1
|
||||
openEnd = -1
|
||||
openAttrs = ''
|
||||
}
|
||||
}
|
||||
return dedupeForwardedItems(items)
|
||||
return result
|
||||
}
|
||||
|
||||
function parseForwardedItems(container: string, depth = 0): ForwardedMessageItem[] {
|
||||
if (!container || depth > 8) return []
|
||||
const variants: string[] = []
|
||||
const pushVariant = (value: string): void => {
|
||||
const trimmed = String(value || '').trim()
|
||||
if (trimmed && !variants.includes(trimmed)) variants.push(trimmed)
|
||||
}
|
||||
|
||||
for (const match of container.matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g)) {
|
||||
if (match[1]) {
|
||||
pushVariant(match[1])
|
||||
pushVariant(decodeXmlEntities(match[1]))
|
||||
}
|
||||
}
|
||||
pushVariant(container)
|
||||
pushVariant(decodeXmlEntities(container))
|
||||
|
||||
for (const variant of variants) {
|
||||
const dataItemNodes = splitBalancedXmlTags(variant, 'dataitem')
|
||||
if (dataItemNodes.length === 0) continue
|
||||
|
||||
const items: ForwardedMessageItem[] = []
|
||||
dataItemNodes.forEach((node, index) => {
|
||||
const attributes = node.attrs || ''
|
||||
const body = node.inner || ''
|
||||
const nestedXml = splitBalancedXmlTags(body, 'recordxml')[0]?.inner || ''
|
||||
// 剥离嵌套 <recordxml> 后再提取外层字段,防止内层 <dataitem> 的 fullmd5/datadesc/sourcename 泄漏到外层 datatype=17 节点。
|
||||
const ownBody = nestedXml
|
||||
? body.replace(/<recordxml\b[^>]*>[\s\S]*<\/recordxml>/i, '')
|
||||
: body
|
||||
const attrType = /datatype\s*=\s*["']?(\d+)/i.exec(attributes)?.[1]
|
||||
const dataId = /dataid\s*=\s*["']([^"']+)["']/i.exec(attributes)?.[1] || undefined
|
||||
const messageType = Number.parseInt(
|
||||
attrType || extractXmlValue(ownBody, 'datatype') || '0',
|
||||
10
|
||||
)
|
||||
const normalizedType = Number.isFinite(messageType) ? messageType : 0
|
||||
const sender = decodeXmlEntities(extractXmlValue(ownBody, 'sourcename')) || undefined
|
||||
const sourceHeadUrl = decodeXmlUrl(extractXmlValue(ownBody, 'sourceheadurl')) || undefined
|
||||
const sentAt = extractXmlValue(ownBody, 'sourcetime') || undefined
|
||||
const title = decodeXmlEntities(extractXmlValue(ownBody, 'datatitle')) || undefined
|
||||
const description = decodeXmlEntities(
|
||||
extractXmlValue(ownBody, 'datadesc') || extractXmlValue(ownBody, 'content')
|
||||
)
|
||||
const isNestedRecord = normalizedType === 17
|
||||
const imageMd5 =
|
||||
!isNestedRecord && normalizedType === 2
|
||||
? normalizeMd5(
|
||||
extractXmlValue(ownBody, 'fullmd5') ||
|
||||
extractXmlValue(ownBody, 'md5') ||
|
||||
extractXmlValue(ownBody, 'datamd5')
|
||||
)
|
||||
: undefined
|
||||
const thumbMd5 =
|
||||
!isNestedRecord && normalizedType === 2
|
||||
? normalizeMd5(extractXmlValue(ownBody, 'thumbfullmd5'))
|
||||
: undefined
|
||||
const cdnFileId =
|
||||
!isNestedRecord && normalizedType === 2
|
||||
? extractXmlValue(ownBody, 'cdndataurl') ||
|
||||
extractXmlValue(ownBody, 'cdnthumburl') ||
|
||||
undefined
|
||||
: undefined
|
||||
const cdnAesKey =
|
||||
!isNestedRecord && normalizedType === 2
|
||||
? extractXmlValue(ownBody, 'cdndatakey') ||
|
||||
extractXmlValue(ownBody, 'cdnthumbkey') ||
|
||||
undefined
|
||||
: undefined
|
||||
const rawXml =
|
||||
!isNestedRecord && normalizedType === 2
|
||||
? `<dataitem${attributes ? ` ${attributes.trim()}` : ''}>${ownBody}</dataitem>`
|
||||
: undefined
|
||||
const dataSize =
|
||||
Number.parseInt(extractXmlValue(ownBody, 'datasize') || '0', 10) || undefined
|
||||
const thumbSize =
|
||||
Number.parseInt(extractXmlValue(ownBody, 'thumbsize') || '0', 10) || undefined
|
||||
const fileExt = extractXmlValue(ownBody, 'fileext') || undefined
|
||||
const linkUrl =
|
||||
decodeXmlUrl(extractXmlValue(ownBody, 'link') || extractXmlValue(ownBody, 'streamweburl')) ||
|
||||
undefined
|
||||
const nestedTitle = isNestedRecord
|
||||
? decodeXmlEntities((nestedXml && extractXmlValue(nestedXml, 'title')) || title || '') ||
|
||||
'聊天记录'
|
||||
: undefined
|
||||
const nested =
|
||||
isNestedRecord && nestedXml ? parseForwardedItems(nestedXml, depth + 1) : undefined
|
||||
const text =
|
||||
normalizedType === 2
|
||||
? '[图片]'
|
||||
: isNestedRecord
|
||||
? nestedTitle || '[聊天记录]'
|
||||
: description || title || forwardedTypeLabel(normalizedType)
|
||||
if (!sender && !text && !nested?.length && !imageMd5 && !thumbMd5) return
|
||||
items.push({
|
||||
messageType: normalizedType,
|
||||
sender,
|
||||
sourceHeadUrl,
|
||||
sentAt,
|
||||
text: text || '[消息]',
|
||||
title,
|
||||
dataId,
|
||||
dataIndex: index,
|
||||
imageMd5,
|
||||
thumbMd5,
|
||||
cdnFileId,
|
||||
cdnAesKey,
|
||||
rawXml,
|
||||
dataSize,
|
||||
thumbSize,
|
||||
fileExt,
|
||||
linkUrl,
|
||||
nestedTitle,
|
||||
nested: nested?.length ? nested : undefined
|
||||
})
|
||||
})
|
||||
if (items.length > 0) return dedupeForwardedItems(items)
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
export function attachForwardBundleRecordDir(
|
||||
bundle: ForwardBundleContent,
|
||||
recordDir?: string
|
||||
): ForwardBundleContent {
|
||||
const normalizedDir = String(recordDir || '').trim()
|
||||
if (!normalizedDir) return bundle
|
||||
const items = bundle.items.map((item, idx) => {
|
||||
const dataIndex = typeof item.dataIndex === 'number' ? item.dataIndex : idx
|
||||
if (item.messageType === 2 && !item.imageDatName) {
|
||||
return {
|
||||
...item,
|
||||
dataIndex,
|
||||
imageDatName: `rec:${normalizedDir}:${dataIndex}`
|
||||
}
|
||||
}
|
||||
return item
|
||||
})
|
||||
return {
|
||||
...bundle,
|
||||
recordDir: normalizedDir,
|
||||
items
|
||||
}
|
||||
}
|
||||
|
||||
function dedupeForwardedItems(items: ForwardedMessageItem[]): ForwardedMessageItem[] {
|
||||
const seen = new Set<string>()
|
||||
return items.filter((item) => {
|
||||
const key = `${item.messageType}|${item.sender || ''}|${item.sentAt || ''}|${item.text}`
|
||||
const key = [
|
||||
item.messageType,
|
||||
item.dataId || '',
|
||||
item.dataIndex ?? '',
|
||||
item.sender || '',
|
||||
item.sentAt || '',
|
||||
item.imageMd5 || '',
|
||||
item.text
|
||||
].join('|')
|
||||
if (seen.has(key)) return false
|
||||
seen.add(key)
|
||||
return true
|
||||
@@ -661,30 +850,33 @@ function dedupeForwardedItems(items: ForwardedMessageItem[]): ForwardedMessageIt
|
||||
|
||||
function forwardedTypeLabel(messageType: number): string {
|
||||
switch (messageType) {
|
||||
case 3:
|
||||
case 2:
|
||||
return '[图片]'
|
||||
case 3:
|
||||
case 34:
|
||||
return '[语音]'
|
||||
case 4:
|
||||
case 43:
|
||||
return '[视频]'
|
||||
case 47:
|
||||
return '[表情包]'
|
||||
case 5:
|
||||
return '[链接]'
|
||||
case 6:
|
||||
return '[位置]'
|
||||
case 8:
|
||||
case 49:
|
||||
return '[文件或分享]'
|
||||
case 17:
|
||||
return '[聊天记录]'
|
||||
case 22:
|
||||
return '[视频号]'
|
||||
case 37:
|
||||
case 47:
|
||||
return '[表情包]'
|
||||
default:
|
||||
return '[消息]'
|
||||
}
|
||||
}
|
||||
|
||||
function extractXmlBody(xml: string, tagName: string): string {
|
||||
const match = new RegExp(`<${tagName}[^>]*>([\\s\\S]*?)<\\/${tagName}>`, 'i').exec(xml)
|
||||
if (!match?.[1]) return ''
|
||||
return match[1].replace(/^<!\[CDATA\[([\s\S]*?)\]\]>$/, '$1').trim()
|
||||
}
|
||||
|
||||
function parseQuoteMessage(content: string): {
|
||||
content?: string
|
||||
sender?: string
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from 'node:path'
|
||||
import { app } from 'electron'
|
||||
|
||||
import { findResource } from './resource-paths'
|
||||
import { resolveExternalComponent } from './services/external-component-locator'
|
||||
|
||||
export type NativeRuntimeProfile = 'public' | 'native'
|
||||
|
||||
@@ -34,7 +35,10 @@ function getNativeRuntimeProfile(): NativeRuntimeProfile {
|
||||
}
|
||||
|
||||
export function hasMacNativeBundle(): boolean {
|
||||
return process.platform === 'darwin' && getNativeRuntimeProfile() === 'native'
|
||||
return (
|
||||
process.platform === 'darwin' &&
|
||||
(getNativeRuntimeProfile() === 'native' || resolveExternalComponent() !== null)
|
||||
)
|
||||
}
|
||||
|
||||
export function isMacNativeRuntimeUnavailable(): boolean {
|
||||
@@ -43,6 +47,11 @@ export function isMacNativeRuntimeUnavailable(): boolean {
|
||||
|
||||
export function resolveWcdbLibrary(): string | null {
|
||||
if (process.platform !== 'darwin') return null
|
||||
const external = resolveExternalComponent()
|
||||
if (external) {
|
||||
const candidate = path.join(external.dir, 'libwcdb_api.dylib')
|
||||
if (fs.existsSync(candidate)) return candidate
|
||||
}
|
||||
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||
return findResource(`wcdb/macos/${arch}/libwcdb_api.dylib`)
|
||||
}
|
||||
@@ -56,12 +65,18 @@ export function resolveWcdbDependency(): string | null {
|
||||
|
||||
export function resolveWcdbConfigHelper(): string | null {
|
||||
if (isMacNativeRuntimeUnavailable()) return null
|
||||
const external = resolveExternalComponent()
|
||||
if (external && fs.existsSync(external.helperPath)) return external.helperPath
|
||||
const arch = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||
return findResource(`wcdb/macos/${arch}/tm-wcdb-config-helper`)
|
||||
}
|
||||
|
||||
export function resolveWechatRuntimeDirectory(): string | null {
|
||||
if (!hasMacNativeBundle()) return null
|
||||
const external = resolveExternalComponent()
|
||||
if (external && fs.existsSync(path.join(external.dir, 'runtime-manifest.json'))) {
|
||||
return external.dir
|
||||
}
|
||||
const manifest =
|
||||
findResource(`${RUNTIME_RELATIVE}/runtime-manifest.json`) ||
|
||||
(!app.isPackaged ? findResource('runtime/darwin-arm64/runtime-manifest.json') : null)
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { spawn, type ChildProcess } from 'node:child_process'
|
||||
|
||||
const DEFAULT_TASKKILL_TIMEOUT_MS = 5_000
|
||||
const DEFAULT_EXIT_TIMEOUT_MS = 2_000
|
||||
|
||||
/** 结束进程树的结果;Windows 上仅 taskkill 退出码为 0 时视为成功。 */
|
||||
export type ProcessTreeKillResult = 'group' | 'taskkill' | 'fallback'
|
||||
|
||||
export interface TerminateChildProcessOptions {
|
||||
platform?: NodeJS.Platform
|
||||
signal?: NodeJS.Signals
|
||||
timeoutMs?: number
|
||||
killTree?: typeof killProcessTree
|
||||
}
|
||||
|
||||
export async function killProcessTree(
|
||||
pid: number | undefined,
|
||||
options: { platform?: NodeJS.Platform; signal?: NodeJS.Signals; timeoutMs?: number } = {}
|
||||
): Promise<ProcessTreeKillResult> {
|
||||
if (!pid) return 'fallback'
|
||||
const platform = options.platform ?? process.platform
|
||||
const signal = options.signal ?? 'SIGKILL'
|
||||
|
||||
if (platform === 'win32') {
|
||||
return killWindowsProcessTree(pid, options.timeoutMs ?? DEFAULT_TASKKILL_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
try {
|
||||
process.kill(-pid, signal)
|
||||
return 'group'
|
||||
} catch {
|
||||
try {
|
||||
process.kill(pid, signal)
|
||||
} catch {
|
||||
// 进程已退出。
|
||||
}
|
||||
return 'fallback'
|
||||
}
|
||||
}
|
||||
|
||||
function killWindowsProcessTree(
|
||||
pid: number,
|
||||
timeoutMs: number
|
||||
): Promise<'taskkill' | 'fallback'> {
|
||||
return new Promise((resolve) => {
|
||||
let killer: ChildProcess
|
||||
try {
|
||||
killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], {
|
||||
windowsHide: true,
|
||||
stdio: 'ignore'
|
||||
})
|
||||
} catch {
|
||||
resolve('fallback')
|
||||
return
|
||||
}
|
||||
|
||||
let settled = false
|
||||
const finish = (result: 'taskkill' | 'fallback'): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
resolve(result)
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
killer.kill()
|
||||
} catch {
|
||||
// 进程已退出。
|
||||
}
|
||||
finish('fallback')
|
||||
}, timeoutMs)
|
||||
|
||||
killer.on('error', () => finish('fallback'))
|
||||
killer.on('exit', (code) => finish(code === 0 ? 'taskkill' : 'fallback'))
|
||||
})
|
||||
}
|
||||
|
||||
export interface ExitObservableChild {
|
||||
exitCode: number | null
|
||||
signalCode: NodeJS.Signals | null
|
||||
once(event: 'exit', listener: (...args: unknown[]) => void): unknown
|
||||
removeListener(event: 'exit', listener: (...args: unknown[]) => void): unknown
|
||||
}
|
||||
|
||||
export interface TerminatableChild extends ExitObservableChild {
|
||||
pid?: number
|
||||
killed: boolean
|
||||
kill(signal?: NodeJS.Signals | number): boolean
|
||||
}
|
||||
|
||||
/** 等待子进程真实退出;仅发信号不等待会在 Windows 更新时残留文件锁与同名进程。 */
|
||||
export function waitForChildExit(
|
||||
child: ExitObservableChild,
|
||||
timeoutMs = DEFAULT_EXIT_TIMEOUT_MS
|
||||
): Promise<boolean> {
|
||||
if (child.exitCode !== null || child.signalCode !== null) {
|
||||
return Promise.resolve(true)
|
||||
}
|
||||
return new Promise<boolean>((resolve) => {
|
||||
let settled = false
|
||||
const onExit = (): void => finish(true)
|
||||
const finish = (exited: boolean): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
child.removeListener('exit', onExit)
|
||||
resolve(exited)
|
||||
}
|
||||
const timer = setTimeout(() => finish(false), Math.max(0, timeoutMs))
|
||||
child.once('exit', onExit)
|
||||
})
|
||||
}
|
||||
|
||||
export async function terminateChildProcess(
|
||||
child: TerminatableChild,
|
||||
options: TerminateChildProcessOptions = {}
|
||||
): Promise<boolean> {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return true
|
||||
|
||||
const timeoutMs = options.timeoutMs ?? DEFAULT_EXIT_TIMEOUT_MS
|
||||
const exitPromise = waitForChildExit(child, timeoutMs)
|
||||
const runKillTree = options.killTree ?? killProcessTree
|
||||
|
||||
let result: ProcessTreeKillResult = 'fallback'
|
||||
if (child.pid) {
|
||||
result = await runKillTree(child.pid, {
|
||||
platform: options.platform,
|
||||
signal: options.signal,
|
||||
timeoutMs
|
||||
})
|
||||
}
|
||||
|
||||
if (result === 'fallback' && !child.killed) {
|
||||
try {
|
||||
child.kill(options.signal ?? 'SIGKILL')
|
||||
} catch {
|
||||
// 进程已退出。
|
||||
}
|
||||
}
|
||||
|
||||
return exitPromise
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type { Contact, Message } from '../../shared/types'
|
||||
import type { GroupDailyReport, GroupReportMetadata } from '../../shared/group-report'
|
||||
import { exportGroupReport } from '../group-report-service'
|
||||
import { getGroupSnapshot, listMessages, resolveMd5 } from './chat-service'
|
||||
import { isGroupSession } from '../../shared/wechat-identities'
|
||||
import { AIProviderService } from './ai-provider-service'
|
||||
import type {
|
||||
ScheduledReportMemberNameMode,
|
||||
@@ -105,7 +106,7 @@ export async function generateAgentGroupReport(
|
||||
if (!query) return reportFailure('缺少群聊名称', 'data', 'CHAT_NOT_FOUND')
|
||||
const contact = resolveMd5(query)
|
||||
if (!contact) return reportFailure(`没有找到群聊“${query}”`, 'data', 'CHAT_NOT_FOUND')
|
||||
if (contact.type !== 'group' && !contact.m_nsUsrName.endsWith('@chatroom')) {
|
||||
if (contact.type !== 'group' && !isGroupSession(contact.m_nsUsrName)) {
|
||||
return reportFailure(`“${query}”不是群聊`, 'data', 'CHAT_NOT_FOUND')
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { app } from 'electron'
|
||||
|
||||
/**
|
||||
* WorkBuddy Agent 接入配置。
|
||||
*
|
||||
* **默认禁用**:`enabled` 为 false 时 dispatcher 不读任何消息,也不会做在线检测。
|
||||
*
|
||||
* 配置来源(只认这两种):
|
||||
* 1. `<userData>/workbuddy-agent.json` —— 非敏感开关;
|
||||
* 2. 环境变量 —— **只放凭证**,不落盘、不进 Git、不进日志。
|
||||
*
|
||||
* 配置文件里出现的 `accessToken` / `clientSecret` 等字段会被忽略:
|
||||
* 凭证的唯一合法入口是环境变量,避免用户把 secret 写进可同步的目录。
|
||||
*/
|
||||
|
||||
export interface WorkBuddyAgentSettings {
|
||||
enabled: boolean
|
||||
/** 允许触发 `/ai` 的会话 md5 白名单;为空 = 不触发任何会话。 */
|
||||
allowedConversations: string[]
|
||||
/** 命令前缀,默认 `/ai`。只接受「前缀 + 空白」或整条等于前缀。 */
|
||||
commandPrefix: string
|
||||
baseUrl: string
|
||||
timeoutMs: number
|
||||
pollIntervalMs: number
|
||||
/** 单任务最长等待回复时间(毫秒)。超时后状态置 `timeout`,不再轮询。 */
|
||||
maxPollDurationMs: number
|
||||
}
|
||||
|
||||
export interface WorkBuddyCredentials {
|
||||
accessToken?: string
|
||||
refreshToken?: string
|
||||
clientId?: string
|
||||
clientSecret?: string
|
||||
}
|
||||
|
||||
export const WORKBUDDY_AGENT_CONFIG_FILE = 'workbuddy-agent.json'
|
||||
|
||||
export const DEFAULT_WORKBUDDY_AGENT_SETTINGS: WorkBuddyAgentSettings = Object.freeze({
|
||||
enabled: false,
|
||||
allowedConversations: [],
|
||||
commandPrefix: '/ai',
|
||||
baseUrl: 'https://www.workbuddy.cn',
|
||||
timeoutMs: 15_000,
|
||||
pollIntervalMs: 3_000,
|
||||
maxPollDurationMs: 120_000
|
||||
})
|
||||
|
||||
function asString(value: unknown, fallback: string): string {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : fallback
|
||||
}
|
||||
|
||||
function asPositiveInt(value: unknown, fallback: number, max: number): number {
|
||||
const parsed = typeof value === 'number' ? value : Number(value)
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) return fallback
|
||||
return Math.min(Math.floor(parsed), max)
|
||||
}
|
||||
|
||||
function asConversationList(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
const ids: string[] = []
|
||||
for (const item of value) {
|
||||
if (typeof item !== 'string') continue
|
||||
const trimmed = item.trim()
|
||||
if (!trimmed || ids.includes(trimmed)) continue
|
||||
ids.push(trimmed)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
export function resolveWorkBuddyAgentConfigPath(userDataDir?: string): string {
|
||||
const root = userDataDir || app.getPath('userData')
|
||||
return path.join(root, WORKBUDDY_AGENT_CONFIG_FILE)
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取配置。文件不存在 / JSON 损坏 / 字段类型不对,一律回落到默认值(**禁用**),
|
||||
* 不抛错 —— 一个坏配置文件不应该让主进程启动失败。
|
||||
*/
|
||||
export function loadWorkBuddyAgentSettings(
|
||||
userDataDir?: string,
|
||||
defaults: WorkBuddyAgentSettings = DEFAULT_WORKBUDDY_AGENT_SETTINGS
|
||||
): WorkBuddyAgentSettings {
|
||||
let parsed: Record<string, unknown> = {}
|
||||
try {
|
||||
const filePath = resolveWorkBuddyAgentConfigPath(userDataDir)
|
||||
if (fs.existsSync(filePath)) {
|
||||
const raw = fs.readFileSync(filePath, 'utf8')
|
||||
const value = JSON.parse(raw) as unknown
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
parsed = value as Record<string, unknown>
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
parsed = {}
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: parsed.enabled === true,
|
||||
allowedConversations: asConversationList(parsed.allowedConversations),
|
||||
commandPrefix: asString(parsed.commandPrefix, defaults.commandPrefix),
|
||||
baseUrl: asString(parsed.baseUrl, defaults.baseUrl).replace(/\/+$/, ''),
|
||||
timeoutMs: asPositiveInt(parsed.timeoutMs, defaults.timeoutMs, 60_000),
|
||||
pollIntervalMs: asPositiveInt(parsed.pollIntervalMs, defaults.pollIntervalMs, 60_000),
|
||||
maxPollDurationMs: asPositiveInt(
|
||||
parsed.maxPollDurationMs,
|
||||
defaults.maxPollDurationMs,
|
||||
30 * 60_000
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 只从环境变量读取凭证。
|
||||
*
|
||||
* 返回值可能全部为空 —— 调用方必须把这种情况当作 `auth_missing` 处理,
|
||||
* 而不是回落到某个内置默认值。
|
||||
*/
|
||||
export function loadWorkBuddyCredentials(
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): WorkBuddyCredentials {
|
||||
const pick = (key: string): string | undefined => {
|
||||
const value = env[key]
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : undefined
|
||||
}
|
||||
return {
|
||||
accessToken: pick('TRACEMEMO_WORKBUDDY_ACCESS_TOKEN'),
|
||||
refreshToken: pick('TRACEMEMO_WORKBUDDY_REFRESH_TOKEN'),
|
||||
clientId: pick('TRACEMEMO_WORKBUDDY_CLIENT_ID'),
|
||||
clientSecret: pick('TRACEMEMO_WORKBUDDY_CLIENT_SECRET')
|
||||
}
|
||||
}
|
||||
|
||||
/** 是否具备可用的凭证组合(无需真的请求成功)。 */
|
||||
export function hasWorkBuddyCredentials(credentials: WorkBuddyCredentials): boolean {
|
||||
if (credentials.accessToken) return true
|
||||
return Boolean(credentials.refreshToken && credentials.clientId && credentials.clientSecret)
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { AgentTaskRecord, AgentTaskReply } from '../../shared/agent-task'
|
||||
import type { NormalizedIncomingMessage } from './message-listener-service'
|
||||
import { classifyProviderError, type AgentTaskProvider } from './agent-task-provider'
|
||||
import type { AgentTaskStore } from './agent-task-store'
|
||||
import type { WorkBuddyAgentSettings } from './agent-task-config'
|
||||
|
||||
/**
|
||||
* AgentTaskDispatcher —— `/ai` 命令闸门 + 任务投递 + 回复轮询。
|
||||
*
|
||||
* **默认关闭,且只认白名单会话**。这是刻意的产品边界:
|
||||
* 收到任意普通微信消息就唤醒 AI,等于把聊天记录变成无人监督的指令流。
|
||||
*
|
||||
* ```text
|
||||
* NormalizedIncomingMessage
|
||||
* ├─ enabled? no → 丢弃
|
||||
* ├─ 白名单会话? no → 丢弃
|
||||
* ├─ 自己发的? yes → 丢弃(防自触发循环)
|
||||
* ├─ 以 `/ai ` 开头? no → 丢弃
|
||||
* └─ triggerKey 已提交? yes → 丢弃(同一条消息只投一次)
|
||||
* ↓
|
||||
* AgentTaskProvider.submitTask
|
||||
* ↓
|
||||
* 状态持久化(submitting → submitted → completed / timeout / auth_failed ...)
|
||||
* ```
|
||||
*
|
||||
* **不做的事**:不执行 shell、不删文件、不推代码、不发微信。
|
||||
* 任务内容只是转交给远端助理的一段文本;本模块不解释、不放行任何高风险动作。
|
||||
*/
|
||||
|
||||
const MAX_REPLIES_PER_TASK = 50
|
||||
const MAX_PROMPT_CHARS = 4000
|
||||
|
||||
export type AgentTaskDispatchOutcome =
|
||||
| 'disabled'
|
||||
| 'ignored'
|
||||
| 'duplicate'
|
||||
| 'submitted'
|
||||
| 'offline'
|
||||
| 'auth_failed'
|
||||
| 'failed'
|
||||
|
||||
export interface AgentTaskDispatcherOptions {
|
||||
settings: WorkBuddyAgentSettings
|
||||
store: AgentTaskStore
|
||||
provider: AgentTaskProvider
|
||||
resolveConversationId: (sessionId: string) => string | undefined
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export class AgentTaskDispatcher {
|
||||
private readonly now: () => number
|
||||
private pollTimer: ReturnType<typeof setInterval> | null = null
|
||||
private polling = false
|
||||
|
||||
constructor(private readonly options: AgentTaskDispatcherOptions) {
|
||||
this.now = options.now ?? Date.now
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理一条已规范化的消息。
|
||||
*
|
||||
* 前置判断全部同步完成(没有 await),保证同一批事件里重复投递的同一条消息
|
||||
* 会在第二次调用时直接命中去重表。
|
||||
*/
|
||||
async handleMessage(message: NormalizedIncomingMessage): Promise<AgentTaskDispatchOutcome> {
|
||||
const settings = this.options.settings
|
||||
if (!settings.enabled) return 'disabled'
|
||||
if (message.isSelf) return 'ignored'
|
||||
|
||||
const prompt = matchCommand(message.content, settings.commandPrefix)
|
||||
if (!prompt) return 'ignored'
|
||||
|
||||
const conversationId = this.options.resolveConversationId(message.sessionId)
|
||||
if (!conversationId) return 'ignored'
|
||||
if (!settings.allowedConversations.includes(conversationId)) return 'ignored'
|
||||
|
||||
await this.options.store.load()
|
||||
|
||||
const triggerKey = `${message.sessionId}:${message.localId}`
|
||||
if (this.options.store.findByTrigger(triggerKey)) return 'duplicate'
|
||||
|
||||
const now = this.now()
|
||||
const record: AgentTaskRecord = {
|
||||
id: randomUUID(),
|
||||
provider: this.options.provider.id,
|
||||
conversationId,
|
||||
triggerKey,
|
||||
prompt: prompt.slice(0, MAX_PROMPT_CHARS),
|
||||
status: 'submitting',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
replies: []
|
||||
}
|
||||
this.options.store.upsert(record)
|
||||
/*
|
||||
* 必须在发请求前落盘。debounce 的写入不足以支撑「不重复提交」——
|
||||
* 崩溃窗口正是发生在这两步之间。
|
||||
*/
|
||||
await this.options.store.flush()
|
||||
|
||||
let online: boolean
|
||||
try {
|
||||
online = await this.options.provider.checkOnline()
|
||||
} catch (error) {
|
||||
return this.finishFailure(record, error, 'online_check')
|
||||
}
|
||||
if (!online) {
|
||||
this.update(record, {
|
||||
status: 'offline',
|
||||
errorKind: 'offline',
|
||||
errorMessage: 'WorkBuddy 本机助理不在线,未提交'
|
||||
})
|
||||
await this.options.store.flush()
|
||||
return 'offline'
|
||||
}
|
||||
|
||||
try {
|
||||
const { messageId } = await this.options.provider.submitTask({ content: record.prompt })
|
||||
this.update(record, {
|
||||
status: 'submitted',
|
||||
submittedAt: this.now(),
|
||||
externalMessageId: messageId,
|
||||
lastReplyId: messageId,
|
||||
errorKind: undefined,
|
||||
errorMessage: undefined
|
||||
})
|
||||
await this.options.store.flush()
|
||||
return 'submitted'
|
||||
} catch (error) {
|
||||
return this.finishFailure(record, error, 'submit')
|
||||
}
|
||||
}
|
||||
|
||||
/** 启动轮询。重复调用是幂等的。 */
|
||||
start(): void {
|
||||
if (this.pollTimer) return
|
||||
this.pollTimer = setInterval(() => {
|
||||
void this.pollOnce()
|
||||
}, this.options.settings.pollIntervalMs)
|
||||
this.pollTimer.unref?.()
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.pollTimer) {
|
||||
clearInterval(this.pollTimer)
|
||||
this.pollTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取所有 `submitted` 任务的增量回复。
|
||||
*
|
||||
* 返回本次处理的任务数(便于测试与诊断)。并发调用会被直接跳过。
|
||||
*/
|
||||
async pollOnce(): Promise<number> {
|
||||
if (this.polling) return 0
|
||||
this.polling = true
|
||||
try {
|
||||
await this.options.store.load()
|
||||
const pending = this.options.store
|
||||
.list(200)
|
||||
.filter((record) => record.status === 'submitted' && Boolean(record.externalMessageId))
|
||||
let processed = 0
|
||||
|
||||
for (const record of pending) {
|
||||
const startedAt = record.submittedAt ?? record.createdAt
|
||||
if (this.now() - startedAt > this.options.settings.maxPollDurationMs) {
|
||||
this.update(record, {
|
||||
status: 'timeout',
|
||||
errorKind: 'timeout',
|
||||
errorMessage: '等待 WorkBuddy 回复超时,已停止轮询'
|
||||
})
|
||||
processed += 1
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const replies = await this.options.provider.fetchReplies(
|
||||
record.lastReplyId ?? String(record.externalMessageId)
|
||||
)
|
||||
const merged = mergeReplies(record.replies, replies)
|
||||
const assistant = merged.find((reply) => reply.role === 'assistant')
|
||||
this.update(record, {
|
||||
replies: merged,
|
||||
lastReplyId:
|
||||
merged.length > 0 ? merged[merged.length - 1].messageId : record.lastReplyId,
|
||||
...(assistant
|
||||
? {
|
||||
status: 'completed' as const,
|
||||
completedAt: this.now(),
|
||||
errorKind: undefined,
|
||||
errorMessage: undefined
|
||||
}
|
||||
: {})
|
||||
})
|
||||
processed += 1
|
||||
} catch (error) {
|
||||
this.finishFailure(record, error, 'poll')
|
||||
}
|
||||
}
|
||||
|
||||
if (processed > 0) await this.options.store.flush()
|
||||
return processed
|
||||
} finally {
|
||||
this.polling = false
|
||||
}
|
||||
}
|
||||
|
||||
private finishFailure(
|
||||
record: AgentTaskRecord,
|
||||
error: unknown,
|
||||
stage: 'online_check' | 'submit' | 'poll'
|
||||
): AgentTaskDispatchOutcome {
|
||||
const info = classifyProviderError(error)
|
||||
const authFailure = info.kind === 'auth_expired' || info.kind === 'auth_missing'
|
||||
|
||||
/*
|
||||
* 投递阶段只要发生「可能已经到达远端」的失败(超时 / 可重试的 5xx / 网络错误),
|
||||
* 就必须记成 ambiguous_submission —— 自动重试会造成重复任务。
|
||||
*/
|
||||
const ambiguous =
|
||||
stage === 'submit' &&
|
||||
(info.kind === 'timeout' || (info.kind === 'http_error' && info.retryable))
|
||||
|
||||
if (ambiguous) {
|
||||
this.update(record, {
|
||||
status: 'failed',
|
||||
errorKind: 'ambiguous_submission',
|
||||
errorMessage: `投递结果未知:${info.message};不会自动重试`
|
||||
})
|
||||
void this.options.store.flush()
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
/*
|
||||
* 轮询阶段的普通失败(5xx / 网络抖动)不应把任务判死:
|
||||
* 远端可能仍在执行,下一轮继续拉取即可。只有鉴权失败才改状态。
|
||||
*/
|
||||
if (stage === 'poll' && !authFailure) {
|
||||
this.update(record, {
|
||||
status: record.status,
|
||||
errorKind: info.kind,
|
||||
errorMessage: info.message
|
||||
})
|
||||
void this.options.store.flush()
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
this.update(record, {
|
||||
status: authFailure ? 'auth_failed' : 'failed',
|
||||
errorKind: info.kind,
|
||||
errorMessage: info.message
|
||||
})
|
||||
void this.options.store.flush()
|
||||
return authFailure ? 'auth_failed' : 'failed'
|
||||
}
|
||||
|
||||
private update(record: AgentTaskRecord, patch: Partial<AgentTaskRecord>): void {
|
||||
Object.assign(record, patch, { updatedAt: this.now() })
|
||||
if (record.errorKind === undefined) delete record.errorKind
|
||||
if (record.errorMessage === undefined) delete record.errorMessage
|
||||
this.options.store.upsert(record)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 只接受「前缀 + 空白」或整条等于前缀。
|
||||
*
|
||||
* `/ai写日报` 不触发:没有分隔符时无法区分命令与普通文本,
|
||||
* 宁可漏触发也不要把正常聊天吞掉。
|
||||
*/
|
||||
export function matchCommand(content: string | undefined, prefix: string): string | null {
|
||||
const text = String(content ?? '').trim()
|
||||
if (!text || !prefix) return null
|
||||
if (!text.toLowerCase().startsWith(prefix.toLowerCase())) return null
|
||||
const rest = text.slice(prefix.length)
|
||||
if (rest && !/^\s/.test(rest)) return null
|
||||
return rest.trim()
|
||||
}
|
||||
|
||||
function mergeReplies(existing: AgentTaskReply[], incoming: AgentTaskReply[]): AgentTaskReply[] {
|
||||
if (incoming.length === 0) return existing
|
||||
const seen = new Set(existing.map((reply) => reply.messageId))
|
||||
const merged = [...existing]
|
||||
for (const reply of incoming) {
|
||||
if (seen.has(reply.messageId)) continue
|
||||
seen.add(reply.messageId)
|
||||
merged.push(reply)
|
||||
}
|
||||
return merged.slice(-MAX_REPLIES_PER_TASK)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { AgentTaskErrorKind, AgentTaskReply } from '../../shared/agent-task'
|
||||
|
||||
/**
|
||||
* AgentTaskProvider —— 可替换的任务投递接口。
|
||||
*
|
||||
* 第一版实现是 WorkBuddy;接口刻意只包含三件事:在线检测、投递、拉回复。
|
||||
* 任何「执行 shell / 发微信 / 改仓库」的能力都**不属于**这个接口。
|
||||
*/
|
||||
|
||||
export interface AgentTaskProviderRequestOptions {
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export interface AgentTaskProvider {
|
||||
readonly id: string
|
||||
/** 远端助理是否在线。false 时调用方必须放弃提交,不能降级成「假装已提交」。 */
|
||||
checkOnline(options?: AgentTaskProviderRequestOptions): Promise<boolean>
|
||||
/**
|
||||
* 投递一条指令,返回远端消息 id。
|
||||
*
|
||||
* 该调用**不是幂等的**:调用方负责按 `triggerKey` 去重,
|
||||
* 并在失败时区分「确定没提交」与「不确定是否提交」。
|
||||
*/
|
||||
submitTask(
|
||||
input: { content: string },
|
||||
options?: AgentTaskProviderRequestOptions
|
||||
): Promise<{ messageId: string }>
|
||||
/** 按游标增量拉取回复。 */
|
||||
fetchReplies(
|
||||
afterMessageId: string,
|
||||
options?: AgentTaskProviderRequestOptions & { limit?: number }
|
||||
): Promise<AgentTaskReply[]>
|
||||
}
|
||||
|
||||
export class AgentTaskProviderError extends Error {
|
||||
constructor(
|
||||
readonly kind: AgentTaskErrorKind,
|
||||
message: string,
|
||||
readonly retryable = false,
|
||||
readonly httpStatus?: number
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'AgentTaskProviderError'
|
||||
}
|
||||
}
|
||||
|
||||
/** 把任意异常归类成可持久化的错误类型;未知异常一律 `internal`,不猜。 */
|
||||
export function classifyProviderError(error: unknown): {
|
||||
kind: AgentTaskErrorKind
|
||||
message: string
|
||||
retryable: boolean
|
||||
} {
|
||||
if (error instanceof AgentTaskProviderError) {
|
||||
return { kind: error.kind, message: error.message, retryable: error.retryable }
|
||||
}
|
||||
return {
|
||||
kind: 'internal',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
retryable: false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import fs from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import type { AgentTaskRecord, AgentTaskReply } from '../../shared/agent-task'
|
||||
|
||||
/**
|
||||
* Agent 任务状态持久化。
|
||||
*
|
||||
* 目的只有一个:**重启后不重复提交**。
|
||||
* 因此写入顺序必须是「先落 `submitting`,再发请求」——崩溃发生时磁盘上留下的是
|
||||
* 「不确定是否已提交」,而不是一句「没提交过」。
|
||||
*
|
||||
* 文件为 JSON 数组,权限 0600,位于 `<userData>`;最多保留 `maxRecords` 条最新记录。
|
||||
*/
|
||||
|
||||
const DEFAULT_MAX_RECORDS = 200
|
||||
const DEFAULT_DEBOUNCE_MS = 200
|
||||
|
||||
export interface AgentTaskStoreOptions {
|
||||
filePath: string
|
||||
maxRecords?: number
|
||||
debounceMs?: number
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function sanitizeRecord(value: unknown): AgentTaskRecord | null {
|
||||
if (!isRecord(value)) return null
|
||||
const id = typeof value.id === 'string' ? value.id : ''
|
||||
const triggerKey = typeof value.triggerKey === 'string' ? value.triggerKey : ''
|
||||
const conversationId = typeof value.conversationId === 'string' ? value.conversationId : ''
|
||||
const prompt = typeof value.prompt === 'string' ? value.prompt : ''
|
||||
const status = typeof value.status === 'string' ? value.status : ''
|
||||
if (!id || !triggerKey || !conversationId || !status) return null
|
||||
return {
|
||||
id,
|
||||
provider: typeof value.provider === 'string' ? value.provider : 'workbuddy',
|
||||
conversationId,
|
||||
triggerKey,
|
||||
prompt,
|
||||
status: status as AgentTaskRecord['status'],
|
||||
createdAt: typeof value.createdAt === 'number' ? value.createdAt : 0,
|
||||
updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,
|
||||
...(typeof value.submittedAt === 'number' ? { submittedAt: value.submittedAt } : {}),
|
||||
...(typeof value.completedAt === 'number' ? { completedAt: value.completedAt } : {}),
|
||||
...(typeof value.externalMessageId === 'string'
|
||||
? { externalMessageId: value.externalMessageId }
|
||||
: {}),
|
||||
...(typeof value.lastReplyId === 'string' ? { lastReplyId: value.lastReplyId } : {}),
|
||||
...(typeof value.errorKind === 'string'
|
||||
? { errorKind: value.errorKind as AgentTaskRecord['errorKind'] }
|
||||
: {}),
|
||||
...(typeof value.errorMessage === 'string' ? { errorMessage: value.errorMessage } : {}),
|
||||
replies: Array.isArray(value.replies)
|
||||
? value.replies
|
||||
.filter(isRecord)
|
||||
.map(
|
||||
(reply): AgentTaskReply => ({
|
||||
messageId: typeof reply.messageId === 'string' ? reply.messageId : '',
|
||||
role:
|
||||
reply.role === 'assistant' || reply.role === 'user'
|
||||
? reply.role
|
||||
: ('other' as const),
|
||||
text: typeof reply.text === 'string' ? reply.text : '',
|
||||
...(typeof reply.createdAt === 'string' ? { createdAt: reply.createdAt } : {})
|
||||
})
|
||||
)
|
||||
.filter((reply) => Boolean(reply.messageId))
|
||||
: []
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentTaskStore {
|
||||
private readonly records = new Map<string, AgentTaskRecord>()
|
||||
private readonly maxRecords: number
|
||||
private readonly debounceMs: number
|
||||
private readonly now: () => number
|
||||
private loaded: Promise<void> | null = null
|
||||
private persistTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private writeChain: Promise<void> = Promise.resolve()
|
||||
|
||||
constructor(private readonly options: AgentTaskStoreOptions) {
|
||||
this.maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS)
|
||||
this.debounceMs = Math.max(0, options.debounceMs ?? DEFAULT_DEBOUNCE_MS)
|
||||
this.now = options.now ?? Date.now
|
||||
}
|
||||
|
||||
async load(): Promise<void> {
|
||||
if (!this.loaded) this.loaded = this.loadFromDisk()
|
||||
return this.loaded
|
||||
}
|
||||
|
||||
get(id: string): AgentTaskRecord | undefined {
|
||||
const record = this.records.get(id)
|
||||
return record ? { ...record, replies: [...record.replies] } : undefined
|
||||
}
|
||||
|
||||
findByTrigger(triggerKey: string): AgentTaskRecord | undefined {
|
||||
for (const record of this.records.values()) {
|
||||
if (record.triggerKey === triggerKey) return { ...record, replies: [...record.replies] }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
list(limit = 50): AgentTaskRecord[] {
|
||||
return Array.from(this.records.values())
|
||||
.sort((a, b) => b.createdAt - a.createdAt)
|
||||
.slice(0, Math.max(1, Math.min(limit, this.maxRecords)))
|
||||
.map((record) => ({ ...record, replies: [...record.replies] }))
|
||||
}
|
||||
|
||||
upsert(record: AgentTaskRecord): void {
|
||||
this.records.set(record.id, { ...record, replies: [...record.replies] })
|
||||
this.trim()
|
||||
this.schedulePersist()
|
||||
}
|
||||
|
||||
/** 强制写盘(测试与退出前调用)。 */
|
||||
async flush(): Promise<void> {
|
||||
if (this.persistTimer) {
|
||||
clearTimeout(this.persistTimer)
|
||||
this.persistTimer = null
|
||||
}
|
||||
const snapshot = JSON.stringify(this.list(this.maxRecords), null, 2)
|
||||
this.writeChain = this.writeChain.then(() => this.writeSnapshot(snapshot))
|
||||
await this.writeChain
|
||||
}
|
||||
|
||||
private async loadFromDisk(): Promise<void> {
|
||||
let raw = ''
|
||||
try {
|
||||
raw = await fs.readFile(this.options.filePath, 'utf8')
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(raw)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (!Array.isArray(parsed)) return
|
||||
|
||||
for (const item of parsed) {
|
||||
const record = sanitizeRecord(item)
|
||||
if (!record) continue
|
||||
/*
|
||||
* 恢复语义:`submitting` 表示「请求可能已经发出,但进程没等到响应」。
|
||||
* 这种情况绝不能重投,也不能谎称失败在本地 —— 标记为不可重试的
|
||||
* `ambiguous_submission`,让人工/后续阶段决定。
|
||||
*/
|
||||
if (record.status === 'submitting') {
|
||||
record.status = 'failed'
|
||||
record.errorKind = 'ambiguous_submission'
|
||||
record.errorMessage = '进程在投递过程中退出,无法确认远端是否已接收;不会自动重试'
|
||||
record.updatedAt = this.now()
|
||||
} else if (record.status === 'queued') {
|
||||
record.status = 'failed'
|
||||
record.errorKind = 'internal'
|
||||
record.errorMessage = '进程在投递前退出,未发送'
|
||||
record.updatedAt = this.now()
|
||||
}
|
||||
this.records.set(record.id, record)
|
||||
}
|
||||
this.trim()
|
||||
}
|
||||
|
||||
private trim(): void {
|
||||
if (this.records.size <= this.maxRecords) return
|
||||
const ordered = Array.from(this.records.values()).sort((a, b) => a.createdAt - b.createdAt)
|
||||
const overflow = this.records.size - this.maxRecords
|
||||
for (let index = 0; index < overflow; index += 1) {
|
||||
this.records.delete(ordered[index].id)
|
||||
}
|
||||
}
|
||||
|
||||
private schedulePersist(): void {
|
||||
if (this.persistTimer) return
|
||||
this.persistTimer = setTimeout(() => {
|
||||
this.persistTimer = null
|
||||
const snapshot = JSON.stringify(this.list(this.maxRecords), null, 2)
|
||||
this.writeChain = this.writeChain.then(() => this.writeSnapshot(snapshot))
|
||||
}, this.debounceMs)
|
||||
this.persistTimer.unref?.()
|
||||
}
|
||||
|
||||
private async writeSnapshot(snapshot: string): Promise<void> {
|
||||
const target = this.options.filePath
|
||||
const temp = `${target}.tmp`
|
||||
try {
|
||||
await fs.mkdir(path.dirname(target), { recursive: true })
|
||||
await fs.writeFile(temp, snapshot, { encoding: 'utf8', mode: 0o600 })
|
||||
await fs.rename(temp, target)
|
||||
await fs.chmod(target, 0o600).catch(() => undefined)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[AgentTaskStore] persist failed: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import path from 'path'
|
||||
import type {
|
||||
AIChatRequestOptions,
|
||||
AIConnectionTestResult,
|
||||
AIOpenAIProtocol,
|
||||
AIProviderConfig,
|
||||
AIProviderListResult,
|
||||
AIProviderSummary,
|
||||
@@ -64,6 +65,9 @@ interface OpenAIResponsesPayload {
|
||||
output_text?: string
|
||||
output?: Array<{
|
||||
type?: string
|
||||
call_id?: string
|
||||
name?: string
|
||||
arguments?: string
|
||||
content?: Array<{ type?: string; text?: string }>
|
||||
}>
|
||||
usage?: { input_tokens?: number; output_tokens?: number; total_tokens?: number }
|
||||
@@ -353,6 +357,7 @@ export class AIProviderService {
|
||||
success: boolean
|
||||
data?: string
|
||||
toolCalls?: AIChatToolCall[]
|
||||
replayItems?: Record<string, unknown>[]
|
||||
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
|
||||
error?: string
|
||||
errorStatus?: number
|
||||
@@ -366,10 +371,7 @@ export class AIProviderService {
|
||||
try {
|
||||
if (options?.apiKey) throw new Error('Tool Calling 不支持 legacy provider 配置')
|
||||
const resolved = this.resolveProvider(options)
|
||||
if (
|
||||
resolved.provider.type !== 'openai-compatible' ||
|
||||
resolved.provider.advanced.apiProtocol === 'responses'
|
||||
) {
|
||||
if (resolved.provider.type !== 'openai-compatible') {
|
||||
throw new Error('当前 Provider 协议暂不支持 Tool Calling POC')
|
||||
}
|
||||
const result = await requestOpenAICompatibleWithTools(
|
||||
@@ -867,6 +869,36 @@ function modelMaxTokens(provider: AIProviderSummary, model: string): number {
|
||||
)
|
||||
}
|
||||
|
||||
function openAIRequestParameters(
|
||||
provider: AIProviderSummary,
|
||||
model: string,
|
||||
protocol: AIOpenAIProtocol,
|
||||
testing = false
|
||||
): Record<string, unknown> {
|
||||
// Relays may namespace model IDs, e.g. openai/gpt-5-mini.
|
||||
const modelName = model.split('/').pop()?.toLowerCase() || ''
|
||||
const gptVersion = /^gpt-(\d+)(?:[.-]|$)/.exec(modelName)
|
||||
const reasoningModel = /^o\d+(?:[.-]|$)/.test(modelName) || Number(gptVersion?.[1]) >= 5
|
||||
// This adapter does not set reasoning effort. Omit sampling parameters for
|
||||
// reasoning families, including models that only allow them with effort=none.
|
||||
const temperature = reasoningModel ? {} : { temperature: provider.advanced.temperature }
|
||||
const officialOpenAI = new URL(provider.baseUrl).hostname === 'api.openai.com'
|
||||
const tokenParameter =
|
||||
protocol === 'responses'
|
||||
? 'max_output_tokens'
|
||||
: officialOpenAI || reasoningModel
|
||||
? 'max_completion_tokens'
|
||||
: 'max_tokens'
|
||||
return {
|
||||
...temperature,
|
||||
[tokenParameter]: testing
|
||||
? protocol === 'responses'
|
||||
? 128
|
||||
: 8
|
||||
: modelMaxTokens(provider, model)
|
||||
}
|
||||
}
|
||||
|
||||
async function requestOpenAICompatible(
|
||||
provider: AIProviderSummary,
|
||||
apiKey: string,
|
||||
@@ -887,8 +919,7 @@ async function requestOpenAICompatible(
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: toOpenAIMessages(messages),
|
||||
temperature: provider.advanced.temperature,
|
||||
max_tokens: testing ? 8 : modelMaxTokens(provider, model),
|
||||
...openAIRequestParameters(provider, model, 'chat-completions', testing),
|
||||
...(provider.advanced.thinking === 'disabled' ? { thinking: { type: 'disabled' } } : {}),
|
||||
...(provider.advanced.stream ? { stream: true } : {})
|
||||
})
|
||||
@@ -924,6 +955,15 @@ async function requestOpenAICompatible(
|
||||
)
|
||||
}
|
||||
|
||||
function responsesEndpoint(baseUrl: string): string {
|
||||
const normalizedBaseUrl = baseUrl.replace(/\/+$/, '')
|
||||
return normalizedBaseUrl.endsWith('/responses')
|
||||
? normalizedBaseUrl
|
||||
: normalizedBaseUrl.endsWith('/chat/completions')
|
||||
? `${normalizedBaseUrl.slice(0, -'/chat/completions'.length)}/responses`
|
||||
: `${normalizedBaseUrl}/responses`
|
||||
}
|
||||
|
||||
async function requestOpenAIResponses(
|
||||
provider: AIProviderSummary,
|
||||
apiKey: string,
|
||||
@@ -933,12 +973,7 @@ async function requestOpenAIResponses(
|
||||
signal?: AbortSignal,
|
||||
onDelta?: AIChatDeltaHandler
|
||||
): Promise<AIRequestResult> {
|
||||
const normalizedBaseUrl = provider.baseUrl.replace(/\/+$/, '')
|
||||
const endpoint = normalizedBaseUrl.endsWith('/responses')
|
||||
? normalizedBaseUrl
|
||||
: normalizedBaseUrl.endsWith('/chat/completions')
|
||||
? `${normalizedBaseUrl.slice(0, -'/chat/completions'.length)}/responses`
|
||||
: `${normalizedBaseUrl}/responses`
|
||||
const endpoint = responsesEndpoint(provider.baseUrl)
|
||||
const request = toOpenAIResponsesRequest(messages)
|
||||
const headers = buildHeaders(provider, apiKey)
|
||||
if (provider.advanced.stream && !hasHeader(headers, 'accept')) {
|
||||
@@ -953,8 +988,7 @@ async function requestOpenAIResponses(
|
||||
model,
|
||||
instructions: request.instructions,
|
||||
input: request.input,
|
||||
temperature: provider.advanced.temperature,
|
||||
max_output_tokens: testing ? 128 : modelMaxTokens(provider, model),
|
||||
...openAIRequestParameters(provider, model, 'responses', testing),
|
||||
store: false,
|
||||
...(provider.advanced.stream ? { stream: true } : {})
|
||||
})
|
||||
@@ -996,24 +1030,46 @@ async function requestOpenAICompatibleWithTools(
|
||||
): Promise<{
|
||||
data: string
|
||||
toolCalls: AIChatToolCall[]
|
||||
replayItems?: Record<string, unknown>[]
|
||||
usage?: AIRequestResult['usage']
|
||||
elapsedMs?: number
|
||||
}> {
|
||||
const endpoint = provider.baseUrl.endsWith('/chat/completions')
|
||||
? provider.baseUrl
|
||||
: `${provider.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
||||
const responses = provider.advanced.apiProtocol === 'responses'
|
||||
const endpoint = responses
|
||||
? responsesEndpoint(provider.baseUrl)
|
||||
: provider.baseUrl.endsWith('/chat/completions')
|
||||
? provider.baseUrl
|
||||
: `${provider.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
||||
const body = responses
|
||||
? {
|
||||
input: messages.map((message) =>
|
||||
message.role === 'tool'
|
||||
? {
|
||||
type: 'function_call_output',
|
||||
call_id: message.tool_call_id,
|
||||
output: message.content
|
||||
}
|
||||
: message
|
||||
),
|
||||
tools: tools.map((tool) => ({ type: tool.type, ...tool.function, strict: false })),
|
||||
store: false,
|
||||
include: ['reasoning.encrypted_content']
|
||||
}
|
||||
: {
|
||||
messages,
|
||||
tools: tools.length ? tools : undefined,
|
||||
...(provider.advanced.thinking === 'disabled' ? { thinking: { type: 'disabled' } } : {})
|
||||
}
|
||||
return fetchWithTimeout(
|
||||
endpoint,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: buildHeaders(provider, apiKey),
|
||||
body: JSON.stringify({
|
||||
...body,
|
||||
model,
|
||||
messages,
|
||||
...(tools.length ? { tools, tool_choice: 'auto' } : { tool_choice: 'none' }),
|
||||
temperature: provider.advanced.temperature,
|
||||
max_tokens: modelMaxTokens(provider, model),
|
||||
...(provider.advanced.thinking === 'disabled' ? { thinking: { type: 'disabled' } } : {})
|
||||
tool_choice: tools.length ? 'auto' : 'none',
|
||||
...openAIRequestParameters(provider, model, responses ? 'responses' : 'chat-completions')
|
||||
})
|
||||
},
|
||||
provider.advanced.timeoutMs,
|
||||
@@ -1021,10 +1077,10 @@ async function requestOpenAICompatibleWithTools(
|
||||
async (response, timing) => {
|
||||
// 先尝试解析 body:非 2xx 时上游可能返回 JSON 错误体,也可能是 HTML 错误页。
|
||||
// 无论哪种,都要把 status / content-type / elapsed 带进错误,避免丢失上下文。
|
||||
let payload: OpenAIResponsePayload | undefined
|
||||
let payload: (OpenAIResponsePayload & OpenAIResponsesPayload) | undefined
|
||||
let parseError: unknown
|
||||
try {
|
||||
payload = await parseJsonResponse<OpenAIResponsePayload>(response)
|
||||
payload = await parseJsonResponse<OpenAIResponsePayload & OpenAIResponsesPayload>(response)
|
||||
} catch (error) {
|
||||
parseError = error
|
||||
}
|
||||
@@ -1046,6 +1102,35 @@ async function requestOpenAICompatibleWithTools(
|
||||
// 2xx 但 body 无法解析:抛出原始解析错误(含清晰的中文提示)。
|
||||
if (!payload) throw parseError ?? new Error('AI 响应格式异常')
|
||||
if (parseError) throw parseError
|
||||
if (responses) {
|
||||
if (
|
||||
payload.error ||
|
||||
!Array.isArray(payload.output) ||
|
||||
(payload.status && payload.status !== 'completed')
|
||||
) {
|
||||
throw new Error(
|
||||
payload.error?.message ||
|
||||
payload.incomplete_details?.reason ||
|
||||
'Responses 工具调用未完成'
|
||||
)
|
||||
}
|
||||
const toolCalls = payload.output
|
||||
.filter((item) => item.type === 'function_call')
|
||||
.map((call) => {
|
||||
if (!call.call_id || !call.name || typeof call.arguments !== 'string') {
|
||||
throw new Error('Responses 返回的函数调用缺少必要字段')
|
||||
}
|
||||
return { id: call.call_id, name: call.name, arguments: call.arguments }
|
||||
})
|
||||
return {
|
||||
data: extractOpenAIResponsesText(payload),
|
||||
toolCalls,
|
||||
// store:false 时下一轮须回传完整输出,包括加密的推理项。
|
||||
replayItems: payload.output,
|
||||
usage: toOpenAIResponsesUsage(payload.usage),
|
||||
elapsedMs: timing.elapsedMs
|
||||
}
|
||||
}
|
||||
const message = payload.choices?.[0]?.message
|
||||
return {
|
||||
data: openAIMessageText(message?.content),
|
||||
|
||||
@@ -27,6 +27,7 @@ interface AppUpdateServiceOptions {
|
||||
platform?: NodeJS.Platform
|
||||
macAutoUpdateEnabled?: boolean
|
||||
broadcast?: (state: AppUpdateState) => void
|
||||
beforeQuitAndInstall?: () => Promise<void> | void
|
||||
}
|
||||
|
||||
export class AppUpdateService {
|
||||
@@ -36,6 +37,7 @@ export class AppUpdateService {
|
||||
private readonly simulationDurationMs: number
|
||||
private readonly delivery: AppUpdateDelivery
|
||||
private readonly broadcast?: (state: AppUpdateState) => void
|
||||
private beforeQuitAndInstall?: () => Promise<void> | void
|
||||
private state: AppUpdateState
|
||||
private listeners = new Set<(state: AppUpdateState) => void>()
|
||||
private activeCheckSource: AppUpdateCheckSource = 'manual'
|
||||
@@ -62,6 +64,7 @@ export class AppUpdateService {
|
||||
? 'release-page'
|
||||
: 'automatic'
|
||||
this.broadcast = options.broadcast
|
||||
this.beforeQuitAndInstall = options.beforeQuitAndInstall
|
||||
this.state = {
|
||||
status: 'idle',
|
||||
currentVersion: this.currentVersion(),
|
||||
@@ -238,6 +241,10 @@ export class AppUpdateService {
|
||||
}
|
||||
}
|
||||
|
||||
setBeforeQuitAndInstall(hook?: () => Promise<void> | void): void {
|
||||
this.beforeQuitAndInstall = hook
|
||||
}
|
||||
|
||||
install(): AppUpdateInstallResult {
|
||||
if (this.delivery !== 'automatic') {
|
||||
return { success: false, error: '当前 macOS 版本不支持自动安装,请前往 GitHub 下载更新。' }
|
||||
@@ -251,6 +258,17 @@ export class AppUpdateService {
|
||||
return { success: true, simulated: true, message }
|
||||
}
|
||||
this.setState({ status: 'installing', message: '正在重启并安装更新' })
|
||||
const beforeHook = this.beforeQuitAndInstall
|
||||
if (beforeHook) {
|
||||
// 先释放子进程与文件句柄再拉起安装器,避免 NSIS 检测到残留同名进程或目录锁。
|
||||
void Promise.resolve()
|
||||
.then(() => beforeHook())
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
autoUpdater.quitAndInstall()
|
||||
})
|
||||
return { success: true }
|
||||
}
|
||||
autoUpdater.quitAndInstall()
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
@@ -157,17 +157,27 @@ export class AskWechatService {
|
||||
reason: AskWechatFallbackReason,
|
||||
diagnostics: QueryAgentDiagnostics
|
||||
): Promise<AskWechatQueryResult> {
|
||||
if (!this.options.runLegacy) {
|
||||
const scopeKind = request.scope?.scope.kind
|
||||
// Legacy 表达不了「指定多个会话」:窄范围回退等于静默搜全库,宁可明确失败。
|
||||
const legacyScope: 'global' | 'groups' | null =
|
||||
!scopeKind || scopeKind === 'all' ? 'global' : scopeKind === 'groups' ? 'groups' : null
|
||||
if (!this.options.runLegacy || legacyScope === null) {
|
||||
return {
|
||||
engine: 'query-agent',
|
||||
status: 'error',
|
||||
message: RUNTIME_FAILURE_MESSAGE,
|
||||
diagnostics
|
||||
message:
|
||||
legacyScope === null
|
||||
? '本次查询没有完成。当前搜索范围(指定会话)不支持自动重试,请缩小时间范围或换一种问法。'
|
||||
: RUNTIME_FAILURE_MESSAGE,
|
||||
diagnostics: {
|
||||
...diagnostics,
|
||||
...(legacyScope === null ? { fallbackSkipped: 'scope_too_narrow_for_legacy' } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
const legacyResult = await this.options.runLegacy({
|
||||
scope: 'global',
|
||||
scope: legacyScope,
|
||||
range: 'all',
|
||||
...request.legacy,
|
||||
requestId: request.requestId,
|
||||
|
||||
@@ -761,7 +761,7 @@ export class AutomationActionRunner {
|
||||
* 定时日报的统一发送出口。
|
||||
*
|
||||
* **必须走 `WechatActionGateway`**:幂等 + 3 秒发送间隔 + 审计落盘都在那里。
|
||||
* Automation 层不允许知道 OneBot / WCHook / native host / Windows hook 的存在。
|
||||
* Automation 层不允许知道 native host 的存在。
|
||||
*/
|
||||
private async sendScheduledReportImage(
|
||||
input: ScheduledReportRunInput,
|
||||
@@ -879,7 +879,7 @@ export class AutomationActionRunner {
|
||||
*
|
||||
* **必须走 `WechatActionGateway`**:幂等 + 3 秒发送间隔 + 审计落盘都在那里,
|
||||
* 直接调个人微信发送会绕过全部三样。Automation 层也不允许知道
|
||||
* OneBot / WCHook / native host / Windows hook 的存在。
|
||||
* native host 的存在。
|
||||
*
|
||||
* 幂等键由 **eventId** 派生(不是 executionId):审计是落盘的,
|
||||
* 于是"重启后重复投递同一退群事件"会被持久层直接短路。
|
||||
|
||||
@@ -16,6 +16,7 @@ import { buildEventId } from '../extensions/extension-event-bus'
|
||||
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
|
||||
import type { Wcdb4Client } from '../wcdb4-client'
|
||||
import type { NormalizedIncomingMessage } from './message-listener-service'
|
||||
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
|
||||
import { getSelfAccountInfo, listContacts } from './chat-service'
|
||||
import { getPersonalWechatSendCapability } from './personal-wechat-capability-service'
|
||||
import {
|
||||
@@ -213,6 +214,10 @@ export class AutomationService {
|
||||
* 抛出去会影响后续监听者。
|
||||
*/
|
||||
async handleMessage(message: NormalizedIncomingMessage): Promise<void> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('自动化消息处理')
|
||||
return
|
||||
}
|
||||
let rules: AutomationRule[]
|
||||
try {
|
||||
rules = this.ruleStore.listRules()
|
||||
@@ -340,6 +345,10 @@ export class AutomationService {
|
||||
* 该事件的幂等位(用户随后真的补勾了那个群,反而发不出去)。
|
||||
*/
|
||||
async handleGroupExit(event: GroupMemberExitedEvent): Promise<void> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('退群自动化通知')
|
||||
return
|
||||
}
|
||||
const eventId = String(event?.eventId || '').trim()
|
||||
let rule: AutomationRule | undefined
|
||||
try {
|
||||
@@ -474,6 +483,10 @@ export class AutomationService {
|
||||
ruleId: string,
|
||||
options: { trigger: 'schedule' | 'manual'; scheduledSlot?: string }
|
||||
): Promise<ScheduledRuleRunOutcome> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('定时日报执行')
|
||||
return { executed: false, reason: 'read_only' }
|
||||
}
|
||||
const key = String(ruleId || '').trim()
|
||||
if (!key) return { executed: false, reason: 'missing_rule' }
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { WechatDb, WechatMessage } from '../wechat-db'
|
||||
import {
|
||||
attachForwardBundleRecordDir,
|
||||
parseImageBufferDataUrlFromRow,
|
||||
parseImageDatNameFromRow,
|
||||
parseMessageContent,
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
filterContactSearchIndex,
|
||||
type ContactSearchIndex
|
||||
} from '../../shared/contact-search'
|
||||
import { isGroupSession } from '../../shared/wechat-identities'
|
||||
|
||||
/**
|
||||
* 谁在读消息。
|
||||
@@ -265,12 +267,12 @@ export function getImageMessageReference(messageId: string): ImageMessageReferen
|
||||
return imageMessageReferences.get(normalizedId) || null
|
||||
}
|
||||
|
||||
export async function closeChatDbForQuit(): Promise<boolean> {
|
||||
export async function closeChatDbForQuit(timeoutMs?: number): Promise<boolean> {
|
||||
shutdownRequested = true
|
||||
const current = dbRef
|
||||
dbRef = null
|
||||
if (!current) return true
|
||||
return current.closeAsync()
|
||||
return current.closeAsync(timeoutMs)
|
||||
}
|
||||
|
||||
export function getChatDb(): WechatDb | null {
|
||||
@@ -347,7 +349,7 @@ export function listContacts(filter?: string): FormattedContact[] {
|
||||
|
||||
for (const user of userList) {
|
||||
const md5 = dbRef.md5(user.m_nsUsrName)
|
||||
const isGroup = user.m_nsUsrName.endsWith('@chatroom')
|
||||
const isGroup = isGroupSession(user.m_nsUsrName)
|
||||
existingMd5s.add(md5)
|
||||
contacts.push({
|
||||
m_nsUsrName: user.m_nsUsrName,
|
||||
@@ -436,7 +438,7 @@ export async function getGroupNamesAsync(): Promise<Record<string, string>> {
|
||||
const sessions = await dbRef.getWcdb4Client().getSessionsAsync({ hydrateDisplayNames: false })
|
||||
const names: Record<string, string> = {}
|
||||
for (const session of sessions) {
|
||||
if (!session.username.endsWith('@chatroom')) continue
|
||||
if (!isGroupSession(session.username)) continue
|
||||
const name = String(session.nickname || '').trim()
|
||||
if (name) names[session.username] = name
|
||||
}
|
||||
@@ -613,6 +615,9 @@ function listSourceMessages(
|
||||
thumbDatName: parsed.thumbDatName || parseImageDatNameFromRow(msg),
|
||||
thumbDataUrl: parsed.thumbDataUrl || parseImageBufferDataUrlFromRow(msg.raw || msg)
|
||||
}
|
||||
} else if (parsed.type === 'forwardBundle') {
|
||||
const recordDir = parseImageDatNameFromRow(msg.raw || msg)
|
||||
contentData = attachForwardBundleRecordDir(parsed, recordDir)
|
||||
} else if (parsed.type !== 'system') {
|
||||
if (parsed.type === 'sticker' && !parsed.url && parsed.md5) {
|
||||
parsed.url = wcdb4Client.resolveEmoticonCdnUrl(parsed.md5)
|
||||
@@ -847,6 +852,58 @@ export async function listMessagesAsync(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按页读取一个会话的消息:不把整个会话读进数组,格式化走同一个 `listSourceMessages`。
|
||||
*/
|
||||
export async function* iterateMessagesAsync(
|
||||
userMd5: string,
|
||||
options: { pageSize?: number; sinceMs?: number } = {}
|
||||
): AsyncGenerator<{ messages: FormattedMessage[]; failedStores: string[] }> {
|
||||
if (!dbRef) return
|
||||
const requestId = nextListMessagesRequestId()
|
||||
const client = dbRef.getWcdb4Client()
|
||||
for await (const page of client.iterateMessagePagesAsync(userMd5, {
|
||||
pageSize: options.pageSize,
|
||||
sinceSec: options.sinceMs ? Math.floor(options.sinceMs / 1000) : undefined,
|
||||
requestId
|
||||
})) {
|
||||
if (page.failedStores.length) {
|
||||
yield { messages: [], failedStores: page.failedStores }
|
||||
return
|
||||
}
|
||||
const messages = listSourceMessages(
|
||||
userMd5,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
page.messages,
|
||||
requestId
|
||||
)
|
||||
yield { messages, failedStores: [] }
|
||||
}
|
||||
}
|
||||
|
||||
/** 点查定位:前后文与单条语音都靠它,避免先读整个会话再 findIndex。 */
|
||||
export function locateMessageAsync(
|
||||
userMd5: string,
|
||||
messageId: string
|
||||
): Promise<
|
||||
| { status: 'found'; location: { createTime: number; localId: number } }
|
||||
| { status: 'not_found' | 'ambiguous' | 'unsupported' }
|
||||
> {
|
||||
if (!dbRef) return Promise.resolve({ status: 'not_found' as const })
|
||||
return dbRef.getWcdb4Client().locateMessageAsync(userMd5, messageId)
|
||||
}
|
||||
|
||||
/** 只读 COUNT(*);`count: null` 是有分片读不到,调用方必须显示「未知」而不是 0。 */
|
||||
export function countConversationMessagesAsync(
|
||||
userMd5: string,
|
||||
options: { sinceMs?: number } = {}
|
||||
): Promise<{ count: number | null; approximate: boolean; failedStores: string[] }> {
|
||||
if (!dbRef) return Promise.resolve({ count: null, approximate: false, failedStores: [] })
|
||||
return dbRef.getWcdb4Client().countConversationMessagesAsync(userMd5, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* 只取**图片消息**(图片文字索引专用)。
|
||||
*
|
||||
@@ -995,10 +1052,13 @@ export function getGroupSnapshot(userMd5: string): GroupSnapshot | null {
|
||||
if (!dbRef) return null
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
const roomId = wcdb4Client.getUsernameByMd5(userMd5)
|
||||
if (!roomId || !roomId.endsWith('@chatroom')) return null
|
||||
if (!roomId || !isGroupSession(roomId)) return null
|
||||
|
||||
const rawMembers = wcdb4Client.getGroupMembers(roomId)
|
||||
const members = (Array.isArray(rawMembers) ? rawMembers : [])
|
||||
const rawMembers = roomId.endsWith('@qy_g')
|
||||
? wcdb4Client.getEnterpriseGroupMembers(roomId)
|
||||
: wcdb4Client.getGroupMembers(roomId)
|
||||
if (!Array.isArray(rawMembers)) return null
|
||||
const members = rawMembers
|
||||
.filter((member) => member?.m_nsUsrName)
|
||||
.map((member) => ({
|
||||
wxid: member.m_nsUsrName,
|
||||
@@ -1016,10 +1076,13 @@ export async function getGroupSnapshotAsync(userMd5: string): Promise<GroupSnaps
|
||||
if (!dbRef) return null
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
const roomId = wcdb4Client.getUsernameByMd5(userMd5)
|
||||
if (!roomId || !roomId.endsWith('@chatroom')) return null
|
||||
if (!roomId || !isGroupSession(roomId)) return null
|
||||
|
||||
const rawMembers = await wcdb4Client.getGroupMembersAsync(roomId)
|
||||
const members = (Array.isArray(rawMembers) ? rawMembers : [])
|
||||
const rawMembers = roomId.endsWith('@qy_g')
|
||||
? await wcdb4Client.getEnterpriseGroupMembersAsync(roomId)
|
||||
: await wcdb4Client.getGroupMembersAsync(roomId)
|
||||
if (!Array.isArray(rawMembers)) return null
|
||||
const members = rawMembers
|
||||
.filter((member) => member?.m_nsUsrName)
|
||||
.map((member) => ({
|
||||
wxid: member.m_nsUsrName,
|
||||
@@ -1029,10 +1092,15 @@ export async function getGroupSnapshotAsync(userMd5: string): Promise<GroupSnaps
|
||||
remark: member.remark || '',
|
||||
avatar: member.m_nsHeadImgUrl || ''
|
||||
}))
|
||||
// 群名与调用顺序无关:企业群名优先走 bizchat 同步解析(会回填缓存),
|
||||
// 再退回会话昵称;否则冷启动时第一次取快照会把 raw username 当群名。
|
||||
const session = wcdb4Client.getSessions().find((item) => item.username === roomId)
|
||||
const enterpriseName = roomId.endsWith('@qy_g')
|
||||
? wcdb4Client.getEnterpriseGroupName(roomId)
|
||||
: ''
|
||||
return {
|
||||
roomId,
|
||||
groupName: session?.nickname || undefined,
|
||||
groupName: enterpriseName || session?.nickname || undefined,
|
||||
memberCount: members.length,
|
||||
members
|
||||
}
|
||||
@@ -1049,15 +1117,24 @@ export async function getGroupSnapshotAsync(userMd5: string): Promise<GroupSnaps
|
||||
export function resolveGroupRoomId(userMd5: string): string | null {
|
||||
if (!dbRef) return null
|
||||
const roomId = dbRef.getWcdb4Client().getUsernameByMd5(userMd5)
|
||||
return roomId && roomId.endsWith('@chatroom') ? roomId : null
|
||||
return roomId && isGroupSession(roomId) ? roomId : null
|
||||
}
|
||||
|
||||
/** 退群检测专用轻量读取,不执行成员名称或头像 hydration。 */
|
||||
export async function getGroupMemberIdsAsync(
|
||||
roomId: string
|
||||
): Promise<GroupMembershipSnapshot | null> {
|
||||
if (!dbRef || !roomId.endsWith('@chatroom')) return null
|
||||
const memberIds = await dbRef.getWcdb4Client().getGroupMemberIdsAsync(roomId)
|
||||
if (!dbRef) return null
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
// 企业群:成员清单走 bizchat.chat_group.user_list(native 只认 @chatroom)。
|
||||
if (roomId.endsWith('@qy_g')) {
|
||||
const members = await wcdb4Client.getEnterpriseGroupMembersAsync(roomId)
|
||||
if (!members) return null
|
||||
const memberIds = members.map((member) => member.m_nsUsrName).filter(Boolean)
|
||||
return { roomId, memberIds }
|
||||
}
|
||||
if (!roomId.endsWith('@chatroom')) return null
|
||||
const memberIds = await wcdb4Client.getGroupMemberIdsAsync(roomId)
|
||||
return memberIds ? { roomId, memberIds } : null
|
||||
}
|
||||
|
||||
@@ -1078,7 +1155,7 @@ export async function getGroupMemberNamesAsync(
|
||||
if (requested.length === 0) return []
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
const roomId = wcdb4Client.getUsernameByMd5(userMd5)
|
||||
if (!roomId || !roomId.endsWith('@chatroom')) return []
|
||||
if (!roomId || !isGroupSession(roomId)) return []
|
||||
const members = await wcdb4Client.getGroupMemberNamesAsync(roomId, requested)
|
||||
return members.map((member) => ({
|
||||
wxid: member.m_nsUsrName,
|
||||
@@ -1098,14 +1175,49 @@ export async function getGroupMemberIdsBatchAsync(
|
||||
roomIds: string[]
|
||||
): Promise<GroupMembershipBatchSnapshot[] | null> {
|
||||
if (!dbRef) return null
|
||||
const results = await dbRef.getWcdb4Client().getGroupMemberIdsBatchAsync(roomIds)
|
||||
return results
|
||||
? results.map((result) => ({
|
||||
const requested = Array.from(
|
||||
new Set(
|
||||
(Array.isArray(roomIds) ? roomIds : [])
|
||||
.map((roomId) => String(roomId || '').trim())
|
||||
.filter(Boolean)
|
||||
)
|
||||
)
|
||||
if (requested.length === 0) return []
|
||||
/*
|
||||
* native `wcdb_get_group_members_batch` 只认 `@chatroom`:只要请求里混进一个
|
||||
* `@qy_g`,整批查询就会失败(nativeCode -2001),连普通群的结果一起丢掉 ——
|
||||
* 而「微信内退群提示」开着时检测范围是全部群聊,企业群正好混在里面。
|
||||
*
|
||||
* 所以这里按通道拆分:普通群仍走一次批量 native 调用,企业群逐个走 bizchat
|
||||
* 成员通道,最后按调用方请求的顺序合并,保持接口契约不变。
|
||||
*/
|
||||
const nativeRoomIds = requested.filter((roomId) => !roomId.endsWith('@qy_g'))
|
||||
const enterpriseRoomIds = requested.filter((roomId) => roomId.endsWith('@qy_g'))
|
||||
const byRoomId = new Map<string, GroupMembershipBatchSnapshot>()
|
||||
|
||||
if (nativeRoomIds.length > 0) {
|
||||
const results = await dbRef.getWcdb4Client().getGroupMemberIdsBatchAsync(nativeRoomIds)
|
||||
if (!results) return null
|
||||
for (const result of results) {
|
||||
byRoomId.set(result.roomId, {
|
||||
roomId: result.roomId,
|
||||
status: result.status,
|
||||
memberIds: result.memberWxids
|
||||
}))
|
||||
: null
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for (const roomId of enterpriseRoomIds) {
|
||||
const snapshot = await getGroupMemberIdsAsync(roomId)
|
||||
byRoomId.set(roomId, {
|
||||
roomId,
|
||||
// 读取失败(null)不能伪装成「群已空」:用 not_found 让调用方保留上一份有效基线。
|
||||
status: snapshot ? 'ok' : 'not_found',
|
||||
memberIds: snapshot?.memberIds || []
|
||||
})
|
||||
}
|
||||
|
||||
return requested.map((roomId) => byRoomId.get(roomId)!)
|
||||
}
|
||||
|
||||
export function searchMessages(keyword: string): string | null {
|
||||
|
||||
@@ -21,7 +21,8 @@ interface ManifestFile {
|
||||
sha256?: unknown
|
||||
}
|
||||
|
||||
const HELPER_NAME = 'tm-wcdb-config-helper.exe'
|
||||
const WIN_HELPER_NAME = 'tm-wcdb-config-helper.exe'
|
||||
const MAC_HELPER_NAME = 'tm-wcdb-config-helper'
|
||||
|
||||
const verifyCache = new Map<string, { stamp: string; ok: boolean; dirty: boolean }>()
|
||||
|
||||
@@ -84,18 +85,30 @@ function verifyManifest(dir: string): { ok: boolean; dirty: boolean } {
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回发送能力组件位置;不存在、校验失败、非 Windows 一律返回 null。
|
||||
* 返回发送能力组件位置;不存在、校验失败或不支持平台一律返回 null。
|
||||
* 调用方拿到 null 时应当把它当作「组件没装」,而不是「没授权」。
|
||||
*/
|
||||
export function resolveExternalComponent(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
platform: NodeJS.Platform = process.platform
|
||||
): ComponentLocation | null {
|
||||
if (platform !== 'win32') return null
|
||||
const localAppData = env.LOCALAPPDATA
|
||||
if (!localAppData) return null
|
||||
|
||||
const root = path.join(localAppData, 'TraceMemo', 'Pro', 'windows-x64')
|
||||
if (platform !== 'win32' && platform !== 'darwin') return null
|
||||
let root = ''
|
||||
let helperName = ''
|
||||
if (platform === 'win32') {
|
||||
const localAppData = env.LOCALAPPDATA
|
||||
if (!env.TRACEMEMO_PRO_ROOT && !localAppData) return null
|
||||
root =
|
||||
env.TRACEMEMO_PRO_ROOT || path.join(localAppData || '', 'TraceMemo', 'Pro', 'windows-x64')
|
||||
helperName = WIN_HELPER_NAME
|
||||
} else {
|
||||
const home = env.HOME
|
||||
if (!env.TRACEMEMO_PRO_ROOT && !home) return null
|
||||
root =
|
||||
env.TRACEMEMO_PRO_ROOT ||
|
||||
path.join(home || '', 'Library', 'Application Support', 'TraceMemo', 'Pro', 'macos-arm64')
|
||||
helperName = MAC_HELPER_NAME
|
||||
}
|
||||
const pointerPath = path.join(root, 'current.json')
|
||||
if (!fs.existsSync(pointerPath)) return null
|
||||
|
||||
@@ -118,7 +131,7 @@ export function resolveExternalComponent(
|
||||
return null
|
||||
}
|
||||
|
||||
const helperPath = path.join(dir, HELPER_NAME)
|
||||
const helperPath = path.join(dir, helperName)
|
||||
if (!fs.existsSync(helperPath)) return null
|
||||
|
||||
const verified = verifyManifest(dir)
|
||||
|
||||
@@ -0,0 +1,594 @@
|
||||
import { BrowserWindow } from 'electron'
|
||||
import crypto from 'node:crypto'
|
||||
import fs from 'fs-extra'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { ExtensionError } from '../../shared/extensions/errors'
|
||||
import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
|
||||
import { isPathInside } from '../extensions/extension-paths'
|
||||
import { buildExtensionPrivateMediaPreviewUrl } from '../extensions/extension-protocol'
|
||||
|
||||
const DEFAULT_WIDTH = 430
|
||||
const MIN_WIDTH = 240
|
||||
const DEFAULT_MAX_WIDTH = 1600
|
||||
const DEFAULT_MIN_HEIGHT = 120
|
||||
const DEFAULT_MAX_HEIGHT = 16_000
|
||||
const DEFAULT_MAX_HTML_BYTES = 1024 * 1024
|
||||
const DEFAULT_MAX_PNG_BYTES = 20 * 1024 * 1024
|
||||
const DEFAULT_TIMEOUT_MS = 20_000
|
||||
const DEFAULT_MAX_CONCURRENT = 2
|
||||
const MIN_VALID_PNG_BYTES = 100
|
||||
|
||||
/** 禁止脚本、外链、表单与框架:只允许内联样式与 data: 图片/字体。 */
|
||||
export const STATIC_RENDER_CSP =
|
||||
"default-src 'none'; img-src data:; style-src 'unsafe-inline'; font-src data:; media-src 'none'; script-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none';"
|
||||
|
||||
const FORBIDDEN_HTML_PATTERNS: Array<{ pattern: RegExp; reason: string }> = [
|
||||
{ pattern: /<\s*script\b/i, reason: '不允许包含 script 标签' },
|
||||
{ pattern: /<\s*(?:iframe|frame|frameset|object|embed|applet|base)\b/i, reason: '不允许包含外部嵌入或重定向标签' },
|
||||
{ pattern: /<\s*meta\b[^>]*http-equiv\s*=\s*['"]?\s*refresh/i, reason: '不允许包含 meta refresh 跳转' },
|
||||
{ pattern: /\bon[a-z]{2,32}\s*=/i, reason: '不允许包含内联事件处理属性' },
|
||||
{ pattern: /\b(?:javascript|vbscript)\s*:/i, reason: '不允许包含脚本协议 URL' },
|
||||
{ pattern: /\b(?:src|href|xlink:href|srcset|action|poster)\s*=\s*['"]?\s*(?:https?:|wss?:|ftp:|file:|\/\/)/i, reason: '不允许引用外部网络或本地文件资源' },
|
||||
{ pattern: /@import\b/i, reason: '不允许在样式中使用 @import 加载外部资源' },
|
||||
{ pattern: /url\(\s*['"]?\s*(?:https?:|wss?:|ftp:|file:|\/\/)/i, reason: '不允许在样式中引用外部网络或本地文件 URL' }
|
||||
]
|
||||
|
||||
export interface RenderBlockedRequestDetails {
|
||||
url: string
|
||||
method: string
|
||||
resourceType: string
|
||||
}
|
||||
|
||||
export interface RenderWindowAdapter {
|
||||
loadFile: (filePath: string) => Promise<void>
|
||||
onceReadyToShow: (callback: () => void) => void
|
||||
onceResize: (callback: () => void) => void
|
||||
getContentSize: () => [number, number]
|
||||
setContentSize: (width: number, height: number) => void
|
||||
executeJavaScript: (code: string) => Promise<unknown>
|
||||
capturePage: (rect: { x: number; y: number; width: number; height: number }) => Promise<Buffer>
|
||||
installRequestFilter: (
|
||||
handler: (
|
||||
details: RenderBlockedRequestDetails,
|
||||
callback: (response: { cancel: boolean }) => void
|
||||
) => void
|
||||
) => void
|
||||
clearRequestFilter: () => void
|
||||
isDestroyed: () => boolean
|
||||
destroy: () => void
|
||||
}
|
||||
|
||||
export interface RenderFileToPngOptions {
|
||||
htmlPath: string
|
||||
pngPath: string
|
||||
width?: number
|
||||
maxWidth?: number
|
||||
minHeight?: number
|
||||
maxHeight?: number
|
||||
backgroundColor?: string
|
||||
timeoutMs?: number
|
||||
maxPngBytes?: number
|
||||
minPngBytes?: number
|
||||
/** 为 true 时在 HTTP 响应头追加严格 CSP,适合不可信静态 HTML。 */
|
||||
enforceStaticCsp?: boolean
|
||||
/** 捕获前的帧稳定等待(毫秒);真实 Electron 默认 100ms,单元测试注入窗口时为 0。 */
|
||||
settleMs?: number
|
||||
onBlockedRequest?: (details: RenderBlockedRequestDetails, reason: string) => void
|
||||
}
|
||||
|
||||
export interface RenderFileToPngResult {
|
||||
pngPath: string
|
||||
width: number
|
||||
height: number
|
||||
pixelWidth?: number
|
||||
pixelHeight?: number
|
||||
deviceScaleFactor?: number
|
||||
bytes: number
|
||||
sha256: string
|
||||
imageDataUrl: string
|
||||
}
|
||||
|
||||
export interface RenderExtensionHtmlOptions {
|
||||
extensionId?: string
|
||||
html: string
|
||||
css?: string
|
||||
/** 扩展私有数据根目录;生成的 PNG 必须落在此目录内。 */
|
||||
extensionDataRoot: string
|
||||
/** 可选相对文件名(默认 `rendered/render-<timestamp>.png`)。 */
|
||||
fileName?: string
|
||||
width?: number
|
||||
maxHeight?: number
|
||||
backgroundColor?: string
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export interface RenderExtensionHtmlResult {
|
||||
path: string
|
||||
previewUrl?: string
|
||||
width: number
|
||||
height: number
|
||||
pixelWidth?: number
|
||||
pixelHeight?: number
|
||||
deviceScaleFactor?: number
|
||||
bytes: number
|
||||
mimeType: 'image/png'
|
||||
sha256: string
|
||||
}
|
||||
|
||||
export interface HtmlRenderServiceDependencies {
|
||||
createWindow?: (options: {
|
||||
width: number
|
||||
height: number
|
||||
backgroundColor: string
|
||||
partition: string
|
||||
enforceStaticCsp: boolean
|
||||
}) => RenderWindowAdapter
|
||||
maxConcurrent?: number
|
||||
maxHtmlBytes?: number
|
||||
maxPngBytes?: number
|
||||
tempDir?: string
|
||||
}
|
||||
|
||||
function clampInt(value: unknown, fallback: number, min: number, max: number): number {
|
||||
const parsed = Number(value)
|
||||
if (!Number.isFinite(parsed)) return fallback
|
||||
return Math.max(min, Math.min(max, Math.round(parsed)))
|
||||
}
|
||||
|
||||
function normalizeBackgroundColor(value: unknown): string {
|
||||
const raw = String(value || '').trim()
|
||||
if (/^#[0-9a-fA-F]{3,8}$/.test(raw)) return raw
|
||||
return '#ffffff'
|
||||
}
|
||||
|
||||
/** 静态 HTML 安全校验:在进入 BrowserWindow 之前阻断脚本、事件处理器和外链。 */
|
||||
export function assertSafeStaticHtml(html: string, css = '', maxBytes = DEFAULT_MAX_HTML_BYTES): void {
|
||||
const htmlText = String(html ?? '')
|
||||
const cssText = String(css ?? '')
|
||||
if (!htmlText.trim()) {
|
||||
throw new ExtensionError('INVALID_REQUEST', 'html 内容不能为空')
|
||||
}
|
||||
const totalBytes = Buffer.byteLength(htmlText, 'utf8') + Buffer.byteLength(cssText, 'utf8')
|
||||
if (totalBytes > maxBytes) {
|
||||
throw new ExtensionError(
|
||||
'INVALID_REQUEST',
|
||||
`HTML 与 CSS 总大小不能超过 ${Math.floor(maxBytes / 1024)}KB`
|
||||
)
|
||||
}
|
||||
if (cssText && /<\s*\/?\s*style\b/i.test(cssText)) {
|
||||
throw new ExtensionError('INVALID_REQUEST', '静态 HTML 校验未通过:css 中不允许包含 style 标签')
|
||||
}
|
||||
for (const rule of FORBIDDEN_HTML_PATTERNS) {
|
||||
if (rule.pattern.test(htmlText) || (cssText && rule.pattern.test(cssText))) {
|
||||
throw new ExtensionError('INVALID_REQUEST', `静态 HTML 校验未通过:${rule.reason}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||
|
||||
function readPngPixelDimensions(png: Buffer): { pixelWidth: number; pixelHeight: number } | null {
|
||||
if (png.length < 24) return null
|
||||
if (!png.subarray(0, 8).equals(PNG_MAGIC)) return null
|
||||
const pixelWidth = png.readUInt32BE(16)
|
||||
const pixelHeight = png.readUInt32BE(20)
|
||||
if (!pixelWidth || !pixelHeight) return null
|
||||
return { pixelWidth, pixelHeight }
|
||||
}
|
||||
|
||||
/** 构造带严格 CSP 与隔离样式的完整静态 HTML 文档。 */
|
||||
export function buildIsolatedHtmlDocument(html: string, css = ''): string {
|
||||
const cspTag = `<meta http-equiv="Content-Security-Policy" content="${STATIC_RENDER_CSP}">`
|
||||
const styleTag = css.trim() ? `<style>${css}</style>` : ''
|
||||
const trimmed = html.trim()
|
||||
if (/<html\b/i.test(trimmed)) {
|
||||
if (/<head\b[^>]*>/i.test(trimmed)) {
|
||||
return trimmed.replace(/<head\b[^>]*>/i, (match) => `${match}\n${cspTag}\n${styleTag}`)
|
||||
}
|
||||
return trimmed.replace(/<html\b[^>]*>/i, (match) => `${match}\n<head>${cspTag}${styleTag}</head>`)
|
||||
}
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
${cspTag}
|
||||
<style>html,body{margin:0;padding:0;box-sizing:border-box;}</style>
|
||||
${styleTag}
|
||||
</head>
|
||||
<body>${trimmed}</body>
|
||||
</html>`
|
||||
}
|
||||
|
||||
function createElectronRenderWindow(options: {
|
||||
width: number
|
||||
height: number
|
||||
backgroundColor: string
|
||||
partition: string
|
||||
enforceStaticCsp: boolean
|
||||
}): RenderWindowAdapter {
|
||||
const win = new BrowserWindow({
|
||||
show: false,
|
||||
opacity: 0,
|
||||
skipTaskbar: true,
|
||||
width: options.width,
|
||||
height: options.height,
|
||||
frame: false,
|
||||
backgroundColor: options.backgroundColor,
|
||||
webPreferences: {
|
||||
sandbox: true,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webSecurity: true,
|
||||
allowRunningInsecureContent: false,
|
||||
partition: options.partition
|
||||
}
|
||||
})
|
||||
|
||||
win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
|
||||
win.webContents.on('will-navigate', (event) => event.preventDefault())
|
||||
|
||||
if (options.enforceStaticCsp) {
|
||||
win.webContents.session.webRequest.onHeadersReceived((details, callback) => {
|
||||
callback({
|
||||
responseHeaders: {
|
||||
...(details.responseHeaders ?? {}),
|
||||
'Content-Security-Policy': [STATIC_RENDER_CSP]
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
loadFile: (filePath) => win.loadFile(filePath),
|
||||
onceReadyToShow: (cb) => {
|
||||
win.once('ready-to-show', cb)
|
||||
},
|
||||
onceResize: (cb) => {
|
||||
win.once('resize', cb)
|
||||
},
|
||||
getContentSize: () => {
|
||||
const [w, h] = win.getContentSize()
|
||||
return [w, h]
|
||||
},
|
||||
setContentSize: (w, h) => win.setContentSize(w, h),
|
||||
executeJavaScript: (code) => win.webContents.executeJavaScript(code),
|
||||
capturePage: async (rect) => {
|
||||
const image = await win.webContents.capturePage(rect, { stayHidden: true })
|
||||
return image.toPNG()
|
||||
},
|
||||
installRequestFilter: (handler) => {
|
||||
win.webContents.session.webRequest.onBeforeRequest(
|
||||
{ urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*', 'ftp://*/*', 'file://*/*'] },
|
||||
(details, callback) => {
|
||||
handler(
|
||||
{
|
||||
url: details.url,
|
||||
method: details.method,
|
||||
resourceType: details.resourceType
|
||||
},
|
||||
callback
|
||||
)
|
||||
}
|
||||
)
|
||||
},
|
||||
clearRequestFilter: () => {
|
||||
win.webContents.session.webRequest.onBeforeRequest(null)
|
||||
if (options.enforceStaticCsp) {
|
||||
win.webContents.session.webRequest.onHeadersReceived(null)
|
||||
}
|
||||
},
|
||||
isDestroyed: () => win.isDestroyed(),
|
||||
destroy: () => {
|
||||
if (!win.isDestroyed()) win.destroy()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 构造文件级网络隔离拦截器:仅放行当前单个本地 HTML 文件,拒绝所有外链与其他 file:// 路径。 */
|
||||
export function createDocumentIsolationHandler(
|
||||
allowedDocumentPath: string,
|
||||
onBlocked?: (details: RenderBlockedRequestDetails, reason: string) => void
|
||||
): (
|
||||
details: RenderBlockedRequestDetails,
|
||||
callback: (response: { cancel: boolean }) => void
|
||||
) => void {
|
||||
const normalizedAllowed = path.resolve(allowedDocumentPath)
|
||||
return (details, callback) => {
|
||||
if (details.url.startsWith('file:')) {
|
||||
try {
|
||||
const requestedPath = path.resolve(fileURLToPath(details.url))
|
||||
const same =
|
||||
process.platform === 'win32'
|
||||
? requestedPath.toLowerCase() === normalizedAllowed.toLowerCase()
|
||||
: requestedPath === normalizedAllowed
|
||||
if (same) {
|
||||
callback({ cancel: false })
|
||||
} else {
|
||||
onBlocked?.(details, 'file-path-not-allowed')
|
||||
callback({ cancel: true })
|
||||
}
|
||||
} catch {
|
||||
onBlocked?.(details, 'invalid-file-url')
|
||||
callback({ cancel: true })
|
||||
}
|
||||
return
|
||||
}
|
||||
onBlocked?.(details, 'scheme-not-allowed')
|
||||
callback({ cancel: true })
|
||||
}
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
reject(new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时'))
|
||||
}, timeoutMs)
|
||||
promise.then(
|
||||
(value) => {
|
||||
clearTimeout(timer)
|
||||
resolve(value)
|
||||
},
|
||||
(error) => {
|
||||
clearTimeout(timer)
|
||||
reject(error)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 官方群聊日报与扩展 `tm.render.htmlToImage` 共用本服务:
|
||||
* 隔离窗口/Session、网络拦截、尺寸与并发上限必须两侧一致。
|
||||
*/
|
||||
export class HtmlRenderService {
|
||||
private readonly createWindow: NonNullable<HtmlRenderServiceDependencies['createWindow']>
|
||||
private readonly maxConcurrent: number
|
||||
private readonly maxHtmlBytes: number
|
||||
private readonly maxPngBytes: number
|
||||
private readonly tempDir: string
|
||||
private readonly defaultSettleMs: number
|
||||
private activeCount = 0
|
||||
|
||||
constructor(deps: HtmlRenderServiceDependencies = {}) {
|
||||
this.createWindow = deps.createWindow ?? createElectronRenderWindow
|
||||
this.defaultSettleMs = deps.createWindow ? 0 : 100
|
||||
this.maxConcurrent = Math.max(1, deps.maxConcurrent ?? DEFAULT_MAX_CONCURRENT)
|
||||
this.maxHtmlBytes = Math.max(1024, deps.maxHtmlBytes ?? DEFAULT_MAX_HTML_BYTES)
|
||||
this.maxPngBytes = Math.max(1024, deps.maxPngBytes ?? DEFAULT_MAX_PNG_BYTES)
|
||||
this.tempDir = deps.tempDir ?? path.join(os.tmpdir(), 'tracememo-html-render')
|
||||
}
|
||||
|
||||
get activeRenders(): number {
|
||||
return this.activeCount
|
||||
}
|
||||
|
||||
async renderFileToPng(options: RenderFileToPngOptions): Promise<RenderFileToPngResult> {
|
||||
if (this.activeCount >= this.maxConcurrent) {
|
||||
throw new ExtensionError('CONCURRENCY_LIMITED', '页面渲染并发已达上限,请稍后再试')
|
||||
}
|
||||
const captureWidth = clampInt(options.width, DEFAULT_WIDTH, MIN_WIDTH, 2400)
|
||||
const maxCaptureWidth = Math.max(
|
||||
captureWidth,
|
||||
clampInt(options.maxWidth, Math.max(captureWidth, DEFAULT_MAX_WIDTH), captureWidth, 2400)
|
||||
)
|
||||
const minCaptureHeight = clampInt(options.minHeight, DEFAULT_MIN_HEIGHT, 64, 4000)
|
||||
const maxCaptureHeight = Math.max(
|
||||
minCaptureHeight,
|
||||
clampInt(options.maxHeight, DEFAULT_MAX_HEIGHT, minCaptureHeight, 25_000)
|
||||
)
|
||||
const timeoutMs = clampInt(options.timeoutMs, DEFAULT_TIMEOUT_MS, 200, 60_000)
|
||||
const maxPngBytes = Math.max(1024, options.maxPngBytes ?? this.maxPngBytes)
|
||||
const minPngBytes = Math.max(1, options.minPngBytes ?? MIN_VALID_PNG_BYTES)
|
||||
const backgroundColor = normalizeBackgroundColor(options.backgroundColor ?? '#f3f5f7')
|
||||
|
||||
this.activeCount += 1
|
||||
let win: RenderWindowAdapter | null = null
|
||||
let wroteOutput = false
|
||||
let aborted = false
|
||||
|
||||
try {
|
||||
const partition = `html-render-${crypto.randomUUID()}`
|
||||
win = this.createWindow({
|
||||
width: captureWidth,
|
||||
height: Math.min(800, maxCaptureHeight),
|
||||
backgroundColor,
|
||||
partition,
|
||||
enforceStaticCsp: options.enforceStaticCsp === true
|
||||
})
|
||||
const currentWin = win
|
||||
const isolationHandler = createDocumentIsolationHandler(
|
||||
options.htmlPath,
|
||||
options.onBlockedRequest
|
||||
)
|
||||
currentWin.installRequestFilter(isolationHandler)
|
||||
|
||||
const run = async (): Promise<RenderFileToPngResult> => {
|
||||
const readyToShow = new Promise<void>((resolve) => currentWin.onceReadyToShow(resolve))
|
||||
await currentWin.loadFile(options.htmlPath)
|
||||
await readyToShow
|
||||
await currentWin.executeJavaScript(`Promise.all([
|
||||
document.fonts ? document.fonts.ready : Promise.resolve(),
|
||||
...Array.from(document.images || []).map((img) => img.complete ? Promise.resolve() : new Promise((resolve) => {
|
||||
img.addEventListener('load', resolve, { once: true });
|
||||
img.addEventListener('error', resolve, { once: true });
|
||||
}))
|
||||
])`)
|
||||
const metrics = (await currentWin.executeJavaScript(`({
|
||||
width: Math.ceil(Math.max(document.documentElement.scrollWidth, document.body ? document.body.scrollWidth : 0, ${captureWidth})),
|
||||
height: Math.ceil(Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0, ${minCaptureHeight}))
|
||||
})`)) as { width?: number; height?: number } | null
|
||||
|
||||
const width = Math.max(
|
||||
captureWidth,
|
||||
Math.min(maxCaptureWidth, Math.ceil(Number(metrics?.width) || captureWidth))
|
||||
)
|
||||
const height = Math.max(
|
||||
minCaptureHeight,
|
||||
Math.min(maxCaptureHeight, Math.ceil(Number(metrics?.height) || minCaptureHeight))
|
||||
)
|
||||
|
||||
const [currentWidth, currentHeight] = currentWin.getContentSize()
|
||||
if (currentWidth !== width || currentHeight !== height) {
|
||||
const resized = new Promise<void>((resolve) => {
|
||||
const fallback = setTimeout(resolve, 300)
|
||||
currentWin.onceResize(() => {
|
||||
clearTimeout(fallback)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
currentWin.setContentSize(width, height)
|
||||
await resized
|
||||
}
|
||||
|
||||
await currentWin.executeJavaScript(
|
||||
'new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))'
|
||||
)
|
||||
const settleMs = options.settleMs ?? this.defaultSettleMs
|
||||
if (settleMs > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, settleMs))
|
||||
}
|
||||
if (aborted) {
|
||||
throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时')
|
||||
}
|
||||
const png = await currentWin.capturePage({ x: 0, y: 0, width, height })
|
||||
if (aborted) {
|
||||
throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时')
|
||||
}
|
||||
if (!png || png.length < minPngBytes) {
|
||||
throw new ExtensionError('RENDER_FAILED', '渲染生成的 PNG 图片为空或过小')
|
||||
}
|
||||
if (png.length > maxPngBytes) {
|
||||
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '渲染生成的 PNG 图片超过体积上限')
|
||||
}
|
||||
await fs.ensureDir(path.dirname(options.pngPath))
|
||||
if (aborted) {
|
||||
throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时')
|
||||
}
|
||||
await fs.writeFile(options.pngPath, png)
|
||||
if (aborted) {
|
||||
await fs.remove(options.pngPath).catch(() => undefined)
|
||||
throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时')
|
||||
}
|
||||
wroteOutput = true
|
||||
const sha256 = crypto.createHash('sha256').update(png).digest('hex')
|
||||
const pixelDims = readPngPixelDimensions(png)
|
||||
const deviceScaleFactor =
|
||||
pixelDims && width > 0 ? Number((pixelDims.pixelWidth / width).toFixed(2)) : undefined
|
||||
return {
|
||||
pngPath: options.pngPath,
|
||||
width,
|
||||
height,
|
||||
...(pixelDims ? { pixelWidth: pixelDims.pixelWidth, pixelHeight: pixelDims.pixelHeight } : {}),
|
||||
...(deviceScaleFactor ? { deviceScaleFactor } : {}),
|
||||
bytes: png.length,
|
||||
sha256,
|
||||
imageDataUrl: `data:image/png;base64,${png.toString('base64')}`
|
||||
}
|
||||
}
|
||||
|
||||
return await withTimeout(run(), timeoutMs)
|
||||
} catch (error) {
|
||||
aborted = true
|
||||
if (!wroteOutput) {
|
||||
await fs.remove(options.pngPath).catch(() => undefined)
|
||||
}
|
||||
if (error instanceof ExtensionError) throw error
|
||||
throw new ExtensionError(
|
||||
'RENDER_FAILED',
|
||||
error instanceof Error ? error.message.slice(0, 200) : '页面渲染失败'
|
||||
)
|
||||
} finally {
|
||||
if (win) {
|
||||
try {
|
||||
win.clearRequestFilter()
|
||||
} catch {
|
||||
// 窗口已销毁时忽略清理钩子异常。
|
||||
}
|
||||
try {
|
||||
win.destroy()
|
||||
} catch {
|
||||
// 忽略重复销毁异常。
|
||||
}
|
||||
}
|
||||
this.activeCount = Math.max(0, this.activeCount - 1)
|
||||
}
|
||||
}
|
||||
|
||||
/** 为扩展渲染静态 HTML 长图,输出严格隔离在扩展私有数据目录中。 */
|
||||
async renderExtensionHtmlToPng(
|
||||
options: RenderExtensionHtmlOptions
|
||||
): Promise<RenderExtensionHtmlResult> {
|
||||
assertSafeStaticHtml(options.html, options.css, this.maxHtmlBytes)
|
||||
const dataRoot = path.resolve(options.extensionDataRoot)
|
||||
const relativeTarget = this.resolveExtensionOutputPath(options.fileName)
|
||||
const targetPath = path.resolve(dataRoot, relativeTarget)
|
||||
if (!isPathInside(dataRoot, targetPath)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', '渲染输出路径越界')
|
||||
}
|
||||
|
||||
await fs.ensureDir(dataRoot)
|
||||
await fs.ensureDir(path.dirname(targetPath))
|
||||
const realRoot = await fs.realpath(dataRoot)
|
||||
const realParent = await fs.realpath(path.dirname(targetPath))
|
||||
if (!isPathInside(realRoot, realParent)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', '渲染输出目录包含非法符号链接')
|
||||
}
|
||||
|
||||
await fs.ensureDir(this.tempDir)
|
||||
const tempHtmlPath = path.join(this.tempDir, `ext-render-${crypto.randomUUID()}.html`)
|
||||
const documentHtml = buildIsolatedHtmlDocument(options.html, options.css)
|
||||
|
||||
try {
|
||||
await fs.writeFile(tempHtmlPath, documentHtml, 'utf8')
|
||||
const rendered = await this.renderFileToPng({
|
||||
htmlPath: tempHtmlPath,
|
||||
pngPath: targetPath,
|
||||
width: clampInt(options.width, DEFAULT_WIDTH, MIN_WIDTH, DEFAULT_MAX_WIDTH),
|
||||
maxWidth: DEFAULT_MAX_WIDTH,
|
||||
minHeight: DEFAULT_MIN_HEIGHT,
|
||||
maxHeight: clampInt(options.maxHeight, DEFAULT_MAX_HEIGHT, DEFAULT_MIN_HEIGHT, DEFAULT_MAX_HEIGHT),
|
||||
backgroundColor: options.backgroundColor ?? '#ffffff',
|
||||
timeoutMs: clampInt(options.timeoutMs, DEFAULT_TIMEOUT_MS, 500, 45_000),
|
||||
maxPngBytes: this.maxPngBytes,
|
||||
enforceStaticCsp: true
|
||||
})
|
||||
const previewUrl = options.extensionId
|
||||
? buildExtensionPrivateMediaPreviewUrl(options.extensionId, dataRoot, rendered.pngPath)
|
||||
: undefined
|
||||
return {
|
||||
path: rendered.pngPath,
|
||||
...(previewUrl ? { previewUrl } : {}),
|
||||
width: rendered.width,
|
||||
height: rendered.height,
|
||||
...(rendered.pixelWidth !== undefined ? { pixelWidth: rendered.pixelWidth } : {}),
|
||||
...(rendered.pixelHeight !== undefined ? { pixelHeight: rendered.pixelHeight } : {}),
|
||||
...(rendered.deviceScaleFactor !== undefined
|
||||
? { deviceScaleFactor: rendered.deviceScaleFactor }
|
||||
: {}),
|
||||
bytes: rendered.bytes,
|
||||
mimeType: 'image/png',
|
||||
sha256: rendered.sha256
|
||||
}
|
||||
} finally {
|
||||
await fs.remove(tempHtmlPath).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
private resolveExtensionOutputPath(fileName: string | undefined): string {
|
||||
const raw = String(fileName || '').trim()
|
||||
if (!raw) {
|
||||
return path.join('rendered', `render-${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}.png`)
|
||||
}
|
||||
const normalized = raw.replace(/\\/g, '/')
|
||||
if (!isSafeRelativeEntryPath(normalized)) {
|
||||
throw new ExtensionError('EXTENSION_INVALID_PATH', '输出文件名包含非法路径片段')
|
||||
}
|
||||
const withExt = normalized.toLowerCase().endsWith('.png') ? normalized : `${normalized}.png`
|
||||
return withExt.startsWith('rendered/') ? withExt : `rendered/${withExt}`
|
||||
}
|
||||
}
|
||||
|
||||
export const htmlRenderService = new HtmlRenderService()
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type AutomationRuleType
|
||||
} from '../../shared/automation'
|
||||
import { resolveContact } from './contact-resolution-service'
|
||||
import { isGroupSession } from '../../shared/wechat-identities'
|
||||
import { validateAutomationDraftShape } from '../../shared/agent-api/automation-validation'
|
||||
import type {
|
||||
AgentAutomationExecution,
|
||||
@@ -459,7 +460,7 @@ export class LocalAgentApiService {
|
||||
if (contact.type !== 'group') {
|
||||
throw new LocalAgentApiError(422, 'NOT_GROUP_CONVERSATION', 'conversationId 不是群会话')
|
||||
}
|
||||
if (!contact.m_nsUsrName.endsWith('@chatroom')) {
|
||||
if (!isGroupSession(contact.m_nsUsrName)) {
|
||||
throw new LocalAgentApiError(422, 'NOT_GROUP_CONVERSATION', 'conversationId 不是有效的群会话 ID')
|
||||
}
|
||||
if (!this.deps.getGroupMemberStats) {
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { listContactsAsync, listMessagesAsync, isReady, type FormattedContact, type FormattedMessage } from './chat-service'
|
||||
import {
|
||||
isReady,
|
||||
iterateMessagesAsync,
|
||||
listContactsAsync,
|
||||
listMessagesAsync,
|
||||
locateMessageAsync,
|
||||
type FormattedContact,
|
||||
type FormattedMessage
|
||||
} from './chat-service'
|
||||
import { resolveContact } from './contact-resolution-service'
|
||||
import { sourceMessageId } from '../knowledge/message-identity'
|
||||
import type { KnowledgeSearchService } from '../knowledge/knowledge-search-service'
|
||||
@@ -311,6 +319,11 @@ interface ResolvedCorpus {
|
||||
function describeScope(scope: ResolvedCorpusScope): string {
|
||||
if (scope.kind === 'all') return '所有聊天记录'
|
||||
if (scope.kind === 'groups') return '群聊专属'
|
||||
if (scope.kind === 'selected') {
|
||||
const names = scope.displayNames ?? []
|
||||
const preview = names.slice(0, 3).join('、')
|
||||
return `指定的 ${scope.conversationCount} 个会话${preview ? `(${preview}${names.length > 3 ? ' 等' : ''})` : ''}`
|
||||
}
|
||||
return `${scope.kind === 'contact' ? '单聊专属' : '当前会话'}:${scope.displayName || '未知会话'}`
|
||||
}
|
||||
|
||||
@@ -444,6 +457,36 @@ export class LocalQueryApiService {
|
||||
const ids = contacts.filter((contact) => contact.type === 'group').map((contact) => contact.md5)
|
||||
return { conversationIds: ids, scope: { kind: 'groups', conversationCount: ids.length } }
|
||||
}
|
||||
if (scope.kind === 'selected') {
|
||||
const requested = Array.isArray(scope.conversationIds)
|
||||
? Array.from(new Set(scope.conversationIds.map((id) => String(id ?? '').trim()).filter(Boolean)))
|
||||
: []
|
||||
// 空选择必须是错误:把它当成"全部"就是最典型的静默扩大范围。
|
||||
if (!requested.length) {
|
||||
return {
|
||||
scope: { kind: 'selected', conversationCount: 0 },
|
||||
error: { status: 'scope_selection_empty' }
|
||||
}
|
||||
}
|
||||
const resolved = requested
|
||||
.map((id) => contacts.find((contact) => contact.md5 === id))
|
||||
.filter((contact): contact is FormattedContact => Boolean(contact))
|
||||
// 任何一个 id 不属于当前账号都直接拒绝:静默丢弃会让用户以为搜过那个群。
|
||||
if (resolved.length !== requested.length) {
|
||||
return {
|
||||
scope: { kind: 'selected', conversationCount: resolved.length },
|
||||
error: { status: 'scope_conversation_not_found', kind: 'selected' }
|
||||
}
|
||||
}
|
||||
return {
|
||||
conversationIds: resolved.map((contact) => contact.md5),
|
||||
scope: {
|
||||
kind: 'selected',
|
||||
conversationCount: resolved.length,
|
||||
displayNames: resolved.map((contact) => contactView(contact).displayName)
|
||||
}
|
||||
}
|
||||
}
|
||||
const contact = contacts.find((item) => item.md5 === scope.conversationId)
|
||||
if (!contact) {
|
||||
return { scope: { kind: scope.kind, conversationCount: 0 }, error: { status: 'scope_conversation_not_found', kind: scope.kind } }
|
||||
@@ -622,7 +665,7 @@ export class LocalQueryApiService {
|
||||
status: 'completed' as const,
|
||||
...(targetView ? { target: targetView } : {}),
|
||||
resolvedTimeRange: range,
|
||||
coverage: { state: this.searchCoverage(found, requestedEnd) },
|
||||
coverage: { state: await this.searchCoverage(found, requestedEnd, conversationIds) },
|
||||
probeCount: probes.length,
|
||||
evidenceCount: evidence.size,
|
||||
evidence: Array.from(evidence.values()).slice(0, limit),
|
||||
@@ -848,22 +891,32 @@ export class LocalQueryApiService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖度。
|
||||
*
|
||||
* 只有「派生索引可用 + 请求范围被索引完整覆盖」才是 `complete`。
|
||||
* `complete` 是 0 结果时允许说"没有找到"的唯一前提;索引落后时必须 `partial`。
|
||||
*/
|
||||
private searchCoverage(
|
||||
/** 按会话逐个判断:全局 indexLatestAt 不是证明,缺状态行的会话一律算 partial。 */
|
||||
private async searchCoverage(
|
||||
found: { indexLatestAt: number | null; sourceLatestAt: number | null; derivedReady: boolean; evidence: Map<string, QueryEvidenceItem> },
|
||||
requestedEnd: number
|
||||
): 'complete' | 'partial' | 'unknown' {
|
||||
requestedEnd: number,
|
||||
conversationIds?: string[]
|
||||
): Promise<'complete' | 'partial' | 'unknown'> {
|
||||
if (!found.derivedReady) {
|
||||
// 派生索引不可用(未建立 / 直读源数据的 fallback):有证据也只能算 partial。
|
||||
return found.evidence.size ? 'partial' : 'unknown'
|
||||
}
|
||||
// 索引可用但覆盖口径缺失时不能宣称完整;此时按 partial 处理(宁可保守)。
|
||||
if (found.indexLatestAt === null) return 'partial'
|
||||
if (!this.knowledge) return 'partial'
|
||||
|
||||
const states = await this.knowledge.getConversationIndexStates().catch(() => ({}))
|
||||
const targets = conversationIds?.length ? conversationIds : Object.keys(states)
|
||||
const incomplete = targets.filter((id) => {
|
||||
const state = states[id]
|
||||
// 没有状态行 = 这个会话从来没被索引过,不能算覆盖。
|
||||
if (!state) return true
|
||||
// 回填到一半、失败、取消:都不能当作完整。
|
||||
if (!state.completeSnapshot) return true
|
||||
if (state.state !== 'ready') return true
|
||||
return false
|
||||
})
|
||||
if (incomplete.length) return 'partial'
|
||||
return indexCovers(found.indexLatestAt, requestedEnd, found.sourceLatestAt) ? 'complete' : 'partial'
|
||||
}
|
||||
async context(request: MessageContextRequest) {
|
||||
@@ -876,9 +929,58 @@ export class LocalQueryApiService {
|
||||
return outsideScopeError(corpus.scope, '其他会话的消息') as { status: string }
|
||||
}
|
||||
}
|
||||
const before = Math.min(CONTEXT_MAX, Math.max(0, request.before ?? 10)); const after = Math.min(CONTEXT_MAX, Math.max(0, request.after ?? 10)); const messages = await listMessagesAsync(ref.conversationId); const index = messages.findIndex((message) => normalizeMessageIdentity(ref.conversationId, message.id)?.messageId === ref.messageId); if (index < 0) return { status: 'contact_not_found' as const }
|
||||
const contact = (await listContactsAsync()).find((item) => item.md5 === ref.conversationId); if (!contact) return { status: 'contact_not_found' as const }; const map = (message: FormattedMessage) => toQueryMessage(ref.conversationId, message, contact, undefined, this.voiceSnapshot(message))
|
||||
return { status: 'completed' as const, anchor: map(messages[index]), before: messages.slice(Math.max(0, index - before), index).map(map), after: messages.slice(index + 1, index + 1 + after).map(map) }
|
||||
const beforeCount = Math.min(CONTEXT_MAX, Math.max(0, request.before ?? 10))
|
||||
const afterCount = Math.min(CONTEXT_MAX, Math.max(0, request.after ?? 10))
|
||||
// 先点定位,再读窗口:整会话读进来再 findIndex,正是超大群内存失控的那条路径。
|
||||
const located = await locateMessageAsync(ref.conversationId, ref.messageId)
|
||||
if (located.status !== 'found') {
|
||||
// 身份不唯一或找不到都必须明确失败 —— 随便挑一条会给模型错误的上下文。
|
||||
return {
|
||||
status:
|
||||
located.status === 'ambiguous'
|
||||
? ('ambiguous_message' as const)
|
||||
: ('contact_not_found' as const)
|
||||
}
|
||||
}
|
||||
const anchorTime = located.location.createTime
|
||||
const isAnchor = (message: FormattedMessage): boolean =>
|
||||
message.createTime === anchorTime && message.localId === located.location.localId
|
||||
|
||||
const leading = beforeCount
|
||||
? await listMessagesAsync(ref.conversationId, undefined, anchorTime - 1, {
|
||||
limit: beforeCount
|
||||
})
|
||||
: []
|
||||
|
||||
let anchor: FormattedMessage | undefined
|
||||
const trailing: FormattedMessage[] = []
|
||||
for await (const page of iterateMessagesAsync(ref.conversationId, {
|
||||
pageSize: 300,
|
||||
sinceMs: anchorTime * 1000
|
||||
})) {
|
||||
if (page.failedStores.length) break
|
||||
for (const message of page.messages) {
|
||||
if (!anchor) {
|
||||
if (isAnchor(message)) anchor = message
|
||||
continue
|
||||
}
|
||||
if (trailing.length >= afterCount) break
|
||||
trailing.push(message)
|
||||
}
|
||||
if (anchor && trailing.length >= afterCount) break
|
||||
}
|
||||
if (!anchor) return { status: 'contact_not_found' as const }
|
||||
|
||||
const contact = (await listContactsAsync()).find((item) => item.md5 === ref.conversationId)
|
||||
if (!contact) return { status: 'contact_not_found' as const }
|
||||
const map = (message: FormattedMessage) =>
|
||||
toQueryMessage(ref.conversationId, message, contact, undefined, this.voiceSnapshot(message))
|
||||
return {
|
||||
status: 'completed' as const,
|
||||
anchor: map(anchor),
|
||||
before: leading.map(map),
|
||||
after: trailing.map(map)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 把指定语音消息转成文字。
|
||||
@@ -920,15 +1022,39 @@ export class LocalQueryApiService {
|
||||
group.push({ messageRef, messageId: identity.messageId })
|
||||
refsByConversation.set(identity.conversationId, group)
|
||||
}
|
||||
// 同一会话只读一次源消息;与 message-context 同样按会话读取后匹配消息身份。
|
||||
// 逐条点定位后只读它所在的那一秒:转写只需要这一条消息的引用,
|
||||
// 为了它把整个会话读进内存是 #75 那条路径的翻版。
|
||||
for (const [conversationId, wanted] of refsByConversation) {
|
||||
const messages = await listMessagesAsync(conversationId)
|
||||
const byId = new Map(messages.map((message) => [normalizeMessageIdentity(conversationId, message.id)?.messageId, message]))
|
||||
for (const { messageRef, messageId } of wanted) {
|
||||
const message = byId.get(messageId)
|
||||
const located = await locateMessageAsync(conversationId, messageId)
|
||||
if (located.status !== 'found') {
|
||||
problems.set(
|
||||
messageRef,
|
||||
voiceItemProblem(
|
||||
messageRef,
|
||||
'failed',
|
||||
located.status === 'ambiguous' ? 'ambiguous_message' : 'message_not_found'
|
||||
)
|
||||
)
|
||||
continue
|
||||
}
|
||||
const second = located.location.createTime
|
||||
const sameSecond = await listMessagesAsync(conversationId, second, second)
|
||||
const message = sameSecond.find(
|
||||
(item) => item.localId === located.location.localId
|
||||
)
|
||||
const reference = message ? voiceMessageReferenceOf(message) : undefined
|
||||
if (reference) references.set(messageRef, reference)
|
||||
else problems.set(messageRef, voiceItemProblem(messageRef, 'failed', message ? 'not_voice_message' : 'message_not_found'))
|
||||
else {
|
||||
problems.set(
|
||||
messageRef,
|
||||
voiceItemProblem(
|
||||
messageRef,
|
||||
'failed',
|
||||
message ? 'not_voice_message' : 'message_not_found'
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
|
||||
import { createECDH, createHash } from 'node:crypto'
|
||||
import { homedir } from 'node:os'
|
||||
import { promisify } from 'node:util'
|
||||
import { chmodSync, existsSync } from 'fs'
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
renameSync,
|
||||
writeFileSync
|
||||
} from 'fs'
|
||||
import { get, request as httpRequest } from 'http'
|
||||
import { join } from 'path'
|
||||
|
||||
@@ -63,6 +72,65 @@ const CRASH_RESTART_DELAY_MS = 1_500
|
||||
* real challenge->sign->check cycle inside the host, which is bounded at 15s. */
|
||||
const LICENSE_STATUS_TIMEOUT_MS = 8_000
|
||||
const LICENSE_REFRESH_TIMEOUT_MS = 20_000
|
||||
const P256_SPKI_PREFIX = Buffer.from('3059301306072a8648ce3d020106082a8648ce3d030107034200', 'hex')
|
||||
|
||||
export function ensureLocalMacDeviceId(baseHomeDir: string = homedir()): string | null {
|
||||
if (process.platform !== 'darwin') return null
|
||||
try {
|
||||
const cleanHome = baseHomeDir.includes('/Library/Containers/')
|
||||
? baseHomeDir.slice(0, baseHomeDir.indexOf('/Library/Containers/'))
|
||||
: baseHomeDir
|
||||
const nativeRoot = join(cleanHome, 'Library', 'Application Support', 'TraceMemoNative')
|
||||
const identityDir = join(nativeRoot, 'identity')
|
||||
const keyPath = join(identityDir, 'device-key.sec1')
|
||||
const cachePath = join(nativeRoot, 'identity.json')
|
||||
|
||||
if (existsSync(keyPath)) {
|
||||
const sec1 = readFileSync(keyPath)
|
||||
if (sec1.length === 97 && sec1[0] === 0x04) {
|
||||
const pubX963 = sec1.subarray(0, 65)
|
||||
const spki = Buffer.concat([P256_SPKI_PREFIX, pubX963])
|
||||
return `mac_${createHash('sha256').update(spki).digest('hex')}`
|
||||
}
|
||||
}
|
||||
|
||||
if (existsSync(cachePath)) {
|
||||
const cached = JSON.parse(readFileSync(cachePath, 'utf8')) as { device_id?: unknown }
|
||||
if (typeof cached.device_id === 'string' && /^mac_[0-9a-f]{64}$/.test(cached.device_id)) {
|
||||
return cached.device_id
|
||||
}
|
||||
}
|
||||
|
||||
mkdirSync(identityDir, { recursive: true, mode: 0o700 })
|
||||
chmodSync(identityDir, 0o700)
|
||||
const ecdh = createECDH('prime256v1')
|
||||
ecdh.generateKeys()
|
||||
const pub = ecdh.getPublicKey()
|
||||
const rawPriv = ecdh.getPrivateKey()
|
||||
const priv =
|
||||
rawPriv.length === 32
|
||||
? rawPriv
|
||||
: Buffer.concat([Buffer.alloc(Math.max(0, 32 - rawPriv.length)), rawPriv.subarray(-32)])
|
||||
const sec1 = Buffer.concat([pub, priv])
|
||||
writeFileSync(keyPath, sec1, { mode: 0o600 })
|
||||
chmodSync(keyPath, 0o600)
|
||||
|
||||
const spki = Buffer.concat([P256_SPKI_PREFIX, pub])
|
||||
const deviceId = `mac_${createHash('sha256').update(spki).digest('hex')}`
|
||||
const cachePayload = JSON.stringify({
|
||||
version: 1,
|
||||
device_id: deviceId,
|
||||
spki_base64: spki.toString('base64'),
|
||||
key_kind: 'file',
|
||||
exportable: true
|
||||
})
|
||||
writeFileSync(cachePath, cachePayload, { mode: 0o600 })
|
||||
chmodSync(cachePath, 0o600)
|
||||
return deviceId
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/* 仅地址占用可以通过切换端口恢复。 */
|
||||
function isPortConflictDiagnostic(diagnostic: string): boolean {
|
||||
@@ -839,37 +907,66 @@ export class MacWechatRuntimeManager {
|
||||
/** Local snapshot. Never attaches to WeChat, never forces a network refresh.
|
||||
* 404 means the host predates these endpoints — not "unlicensed". */
|
||||
async getMacLicenseStatus(): Promise<MacLicenseStatus> {
|
||||
const localDeviceId = ensureLocalMacDeviceId()
|
||||
const withDeviceId = (result: MacLicenseStatus): MacLicenseStatus => ({
|
||||
...result,
|
||||
deviceId: result.deviceId || localDeviceId
|
||||
})
|
||||
|
||||
const { status: directStatus, body: directBody } = await this.request(
|
||||
'GET',
|
||||
'/license/status',
|
||||
1_500
|
||||
)
|
||||
if (directStatus === 200) {
|
||||
try {
|
||||
return withDeviceId(parseMacLicenseStatus(JSON.parse(directBody)))
|
||||
} catch {
|
||||
// 继续走后续兜底
|
||||
}
|
||||
}
|
||||
|
||||
const availability = this.getSendRuntimeAvailability()
|
||||
if (availability.state === 'unavailable') {
|
||||
return offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力')
|
||||
return withDeviceId(
|
||||
offlineMacLicenseStatus('platform_unsupported', '当前构建不包含 Mac 发送能力')
|
||||
)
|
||||
}
|
||||
if (availability.state !== 'available') {
|
||||
return offlineMacLicenseStatus('runtime_missing', availability.message)
|
||||
return withDeviceId(offlineMacLicenseStatus('runtime_missing', availability.message))
|
||||
}
|
||||
if (this.manuallyStopped) {
|
||||
return offlineMacLicenseStatus(
|
||||
'runtime_missing',
|
||||
'Mac 发送组件已停止,请在发送页点击“绑定微信”重新启动。'
|
||||
return withDeviceId(
|
||||
offlineMacLicenseStatus(
|
||||
'runtime_missing',
|
||||
'Mac 发送组件已停止,请在发送页点击“绑定微信”重新启动。'
|
||||
)
|
||||
)
|
||||
}
|
||||
if (this.lifecycle === 'stopped') await this.ensureStarted()
|
||||
const { status, body } = await this.request('GET', '/license/status', LICENSE_STATUS_TIMEOUT_MS)
|
||||
if (status === null) {
|
||||
return offlineMacLicenseStatus('runtime_missing', 'Mac 发送组件未运行,请先启动发送组件')
|
||||
return withDeviceId(
|
||||
offlineMacLicenseStatus('runtime_missing', 'Mac 发送组件未运行,请先启动发送组件')
|
||||
)
|
||||
}
|
||||
if (status === 404) {
|
||||
return offlineMacLicenseStatus(
|
||||
'unsupported',
|
||||
'当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。'
|
||||
return withDeviceId(
|
||||
offlineMacLicenseStatus(
|
||||
'unsupported',
|
||||
'当前发送组件版本较旧,不支持授权检测。请升级或重启发送组件后再试。'
|
||||
)
|
||||
)
|
||||
}
|
||||
if (status !== 200) {
|
||||
return offlineMacLicenseStatus('runtime_missing', `授权状态查询失败(HTTP ${status})`)
|
||||
return withDeviceId(
|
||||
offlineMacLicenseStatus('runtime_missing', `授权状态查询失败(HTTP ${status})`)
|
||||
)
|
||||
}
|
||||
try {
|
||||
return parseMacLicenseStatus(JSON.parse(body))
|
||||
return withDeviceId(parseMacLicenseStatus(JSON.parse(body)))
|
||||
} catch {
|
||||
return offlineMacLicenseStatus('runtime_missing', '授权状态响应无法解析')
|
||||
return withDeviceId(offlineMacLicenseStatus('runtime_missing', '授权状态响应无法解析'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1163,6 +1260,202 @@ export class MacWechatRuntimeManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用原生运行时的 `POST /downloadOriginalImage`,让微信进程用原生下载器下载并解密原图。
|
||||
*/
|
||||
async downloadOriginalImage(payload: {
|
||||
xml?: string
|
||||
fileid?: string
|
||||
aeskey?: string
|
||||
md5?: string
|
||||
file_type?: number
|
||||
save_path: string
|
||||
task_id?: string
|
||||
timeout_ms?: number
|
||||
}): Promise<{
|
||||
success: boolean
|
||||
task_id?: string
|
||||
status?: string
|
||||
file_path?: string
|
||||
file_type?: string
|
||||
file_size?: number
|
||||
md5?: string
|
||||
width?: number
|
||||
height?: number
|
||||
is_original?: boolean
|
||||
byte_identical?: boolean
|
||||
verification?: string
|
||||
rendition?: string
|
||||
error_code?: string
|
||||
error?: string
|
||||
}> {
|
||||
if (process.platform !== 'darwin') {
|
||||
return {
|
||||
success: false,
|
||||
status: 'failed',
|
||||
error_code: 'PLATFORM_UNSUPPORTED',
|
||||
error: '当前仅支持 macOS 微信原图下载'
|
||||
}
|
||||
}
|
||||
if (this.lifecycle !== 'online') {
|
||||
const snapshot = await this.ensureStarted({ allowManualRestart: true })
|
||||
if (snapshot.lifecycle !== 'online' && !(await this.ping())) {
|
||||
return {
|
||||
success: false,
|
||||
status: 'failed',
|
||||
error_code: 'RUNTIME_OFFLINE',
|
||||
error: snapshot.error || '微信原生运行时未在线,无法下载原图'
|
||||
}
|
||||
}
|
||||
}
|
||||
let binding = (await this.getBindingStatus()) || (await this.refreshBinding().catch(() => null))
|
||||
if (!binding?.bound || !binding?.sessionAttached || !binding?.scriptLoaded) {
|
||||
const bindResult = await this.bind()
|
||||
if (!bindResult.ok) {
|
||||
const fallbackBind = await this.request('POST', '/bindWeChat')
|
||||
binding = await this.refreshBinding().catch(() => null)
|
||||
if (
|
||||
fallbackBind.status !== 200 ||
|
||||
!binding?.bound ||
|
||||
!binding?.sessionAttached ||
|
||||
!binding?.scriptLoaded
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
status: 'failed',
|
||||
error_code: bindResult.state || 'BIND_FAILED',
|
||||
error: bindResult.message || '绑定微信失败,无法下载原图'
|
||||
}
|
||||
}
|
||||
} else {
|
||||
binding = (await this.getBindingStatus()) || (await this.refreshBinding().catch(() => null))
|
||||
}
|
||||
}
|
||||
if (binding && !binding.wechatRunning) {
|
||||
return {
|
||||
success: false,
|
||||
status: 'failed',
|
||||
error_code: 'WECHAT_NOT_RUNNING',
|
||||
error: '微信未运行,请先启动并登录微信'
|
||||
}
|
||||
}
|
||||
|
||||
const timeoutMs =
|
||||
typeof payload.timeout_ms === 'number' && payload.timeout_ms > 0
|
||||
? payload.timeout_ms
|
||||
: 180_000
|
||||
const { status, body } = await this.request(
|
||||
'POST',
|
||||
'/downloadOriginalImage',
|
||||
timeoutMs + 10_000,
|
||||
JSON.stringify({ ...payload, timeout_ms: timeoutMs })
|
||||
)
|
||||
if (status === null || !body) {
|
||||
return {
|
||||
success: false,
|
||||
status: 'failed',
|
||||
error_code: 'HOST_UNREACHABLE',
|
||||
error: '原图下载服务无响应,请检查微信发送组件状态'
|
||||
}
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(body) as {
|
||||
success?: boolean
|
||||
task_id?: string
|
||||
status?: string
|
||||
file_path?: string
|
||||
file_type?: string
|
||||
file_size?: number
|
||||
md5?: string
|
||||
width?: number
|
||||
height?: number
|
||||
is_original?: boolean
|
||||
byte_identical?: boolean
|
||||
verification?: string
|
||||
rendition?: string
|
||||
error_code?: string
|
||||
error?: string | { code?: string; message?: string }
|
||||
}
|
||||
const errObj = parsed.error && typeof parsed.error === 'object' ? parsed.error : undefined
|
||||
return {
|
||||
...parsed,
|
||||
success: Boolean(parsed.success),
|
||||
error_code: parsed.error_code || errObj?.code,
|
||||
error: typeof parsed.error === 'string' ? parsed.error : errObj?.message
|
||||
}
|
||||
} catch {
|
||||
return {
|
||||
success: false,
|
||||
status: 'failed',
|
||||
error_code: 'BAD_RESPONSE',
|
||||
error: `媒体下载响应无法解析(HTTP ${status})`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 复用 `/downloadOriginalImage`(`file_type=4`)取视频,再 `rename` 成 `target_file_name`。
|
||||
* `rename` 要求与 host 落盘目录同卷,跨卷抛 EXDEV,调用方需保证同盘。
|
||||
*/
|
||||
async downloadVideo(payload: {
|
||||
fileid: string
|
||||
aeskey: string
|
||||
md5?: string
|
||||
save_dir: string
|
||||
target_file_name?: string
|
||||
task_id?: string
|
||||
timeout_ms?: number
|
||||
}): Promise<{
|
||||
success: boolean
|
||||
task_id?: string
|
||||
status?: string
|
||||
file_path?: string
|
||||
file_size?: number
|
||||
md5?: string
|
||||
error_code?: string
|
||||
error?: string
|
||||
}> {
|
||||
mkdirSync(payload.save_dir, { recursive: true })
|
||||
const result = await this.downloadOriginalImage({
|
||||
fileid: payload.fileid,
|
||||
aeskey: payload.aeskey,
|
||||
...(payload.md5 ? { md5: payload.md5 } : {}),
|
||||
file_type: 4,
|
||||
save_path: payload.save_dir,
|
||||
task_id: payload.task_id,
|
||||
timeout_ms: payload.timeout_ms
|
||||
})
|
||||
|
||||
if (!result.success || !result.file_path || !existsSync(result.file_path)) {
|
||||
return {
|
||||
success: false,
|
||||
task_id: result.task_id,
|
||||
status: result.status || 'failed',
|
||||
error_code: result.error_code || 'DOWNLOAD_FAILED',
|
||||
error: result.error || '视频下载失败'
|
||||
}
|
||||
}
|
||||
|
||||
let finalPath = result.file_path
|
||||
const targetName = String(payload.target_file_name || '').trim()
|
||||
if (targetName) {
|
||||
const targetPath = join(payload.save_dir, targetName)
|
||||
if (targetPath !== result.file_path) {
|
||||
renameSync(result.file_path, targetPath)
|
||||
finalPath = targetPath
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
task_id: result.task_id,
|
||||
status: result.status || 'completed',
|
||||
file_path: finalPath,
|
||||
file_size: result.file_size,
|
||||
md5: result.md5
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 重新加载发送组件:优雅停掉当前 host 进程,再启动一个新实例。
|
||||
* 用于:更新二进制后换新代码;或 host 卡死时的手动恢复。
|
||||
|
||||
@@ -0,0 +1,664 @@
|
||||
import { createHash, randomUUID } from 'node:crypto'
|
||||
import { encodeMessageRef } from '../../shared/local-query-api'
|
||||
import {
|
||||
normalizeIncomingMessage,
|
||||
type NormalizedIncomingMessage
|
||||
} from './message-listener-service'
|
||||
import type { Wcdb4Message } from '../wcdb4-client'
|
||||
|
||||
/**
|
||||
* MessageEventBroker —— 实时消息事件的唯一分发层。
|
||||
*
|
||||
* ```text
|
||||
* MessageListenerService.onMessage
|
||||
* ↓ NormalizedIncomingMessage
|
||||
* MessageEventBroker
|
||||
* ├─ 事件 ID / 规范化 / 有界环形缓冲 / 每订阅者游标
|
||||
* ├─ 已产生事件的重放(replay)
|
||||
* └─ 数据库消息回补(db_backfill,独立标记)
|
||||
* ```
|
||||
*
|
||||
* **刻意不做的事**:不监听数据库(监听只有 `MessageListenerService` 一套)、
|
||||
* 不触发自动化、不调用 AI、不发送微信消息。本模块只负责「把已经产生的事件可靠地交出去」。
|
||||
*
|
||||
* **两类补偿必须可区分**:
|
||||
* - `replay`:事件曾经真实产生过,仍在本进程的环形缓冲里;
|
||||
* - `db_backfill`:缓冲已经覆盖不到,只能从数据库按时间窗重读。它可能包含
|
||||
* 从未产生过事件的普通消息,也可能因为窗口/条数上限而不完整。
|
||||
*
|
||||
* **单位契约**:`timestamp` 是 epoch **秒**(与 WCDB `create_time`、`getMessagesAsync` 一致);
|
||||
* 缓冲 TTL / 去重 TTL 是毫秒。跨这条边界只允许在本文件里换算一次。
|
||||
*/
|
||||
|
||||
/** 单条事件的文本上限。超出时显式标记 `textTruncated`,不静默截断。 */
|
||||
const DEFAULT_MAX_TEXT_CHARS = 4000
|
||||
/** 环形缓冲默认容量(条)。 */
|
||||
const DEFAULT_BUFFER_SIZE = 500
|
||||
/** 环形缓冲默认存活时间(毫秒)。 */
|
||||
const DEFAULT_BUFFER_TTL_MS = 5 * 60 * 1000
|
||||
/** 发布去重表默认存活时间(毫秒)。 */
|
||||
const DEFAULT_SEEN_TTL_MS = 10 * 60 * 1000
|
||||
/** 发布去重表默认容量。 */
|
||||
const DEFAULT_SEEN_MAX_ENTRIES = 5000
|
||||
/** 单订阅者「已投递 ID」记忆容量,用于避免回补与实时重叠时重复投递。 */
|
||||
const DEFAULT_SUBSCRIBER_SEEN_MAX = 2000
|
||||
/** 数据库回补的时间窗默认值(秒)。 */
|
||||
const DEFAULT_BACKFILL_LOOKBACK_SEC = 300
|
||||
/** 单会话回补条数默认上限。 */
|
||||
const DEFAULT_BACKFILL_LIMIT = 100
|
||||
/** 单次回补最多涉及的会话数。 */
|
||||
const DEFAULT_BACKFILL_MAX_CONVERSATIONS = 20
|
||||
/** 单个进程允许的并发 SSE 订阅数。 */
|
||||
const DEFAULT_MAX_SUBSCRIBERS = 32
|
||||
|
||||
export type MessageEventOrigin = 'live' | 'replay' | 'db_backfill'
|
||||
|
||||
export interface MessageEventRecord {
|
||||
/** 确定性 ID:同一会话 + 同一条消息永远得到同一个值(跨进程稳定)。 */
|
||||
id: string
|
||||
/** 进程内单调序号,用于 SSE `Last-Event-ID` 的缓冲定位。 */
|
||||
seq: number
|
||||
/** **会话 md5**,与 `messageRef` 的 `c` 字段同口径(不是微信 username)。 */
|
||||
conversationId: string
|
||||
messageRef: string
|
||||
/** epoch 秒。 */
|
||||
timestamp: number
|
||||
messageType: number
|
||||
isSelf: boolean
|
||||
isGroup: boolean
|
||||
senderId?: string
|
||||
senderNickname?: string
|
||||
text?: string
|
||||
textTruncated?: boolean
|
||||
mentionTargets: string[]
|
||||
}
|
||||
|
||||
export type MessageRuntimeState = 'running' | 'stopped' | 'unknown'
|
||||
|
||||
export interface MessageBrokerStatus {
|
||||
/** TraceMemo 自己的数据库句柄是否可用;**不等于**微信进程在运行。 */
|
||||
database: 'ready' | 'unavailable'
|
||||
/** Native Monitor 是否已成功挂上。 */
|
||||
monitor: MessageRuntimeState
|
||||
/** 微信进程状态(缓存采样,非实时探针)。 */
|
||||
wechat: MessageRuntimeState
|
||||
subscribers: number
|
||||
buffered: number
|
||||
oldestSeq: number | null
|
||||
newestSeq: number | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次数据库回补的结果。
|
||||
*
|
||||
* `truncated=true` 表示**至少有一个上限命中**,客户端必须知道这段空档没有补全:
|
||||
* - `messageTruncated`:某会话返回行数达到 `perConversationLimit`;
|
||||
* - `conversationTruncated`:订阅的会话数超过 `maxConversations`,后面的被跳过。
|
||||
*/
|
||||
export interface MessageBackfillReport {
|
||||
requestedConversations: number
|
||||
processedConversations: number
|
||||
delivered: number
|
||||
failedConversations: number
|
||||
conversationTruncated: boolean
|
||||
messageTruncated: boolean
|
||||
truncated: boolean
|
||||
/** 是否完整:没有截断、没有会话读取失败。客户端应优先看这个字段。 */
|
||||
complete: boolean
|
||||
perConversationLimit: number
|
||||
maxConversations: number
|
||||
windowSec: number
|
||||
}
|
||||
|
||||
export interface MessageGap {
|
||||
reason: 'buffer_overflow' | 'invalid_cursor' | 'cursor_from_previous_process'
|
||||
requestedLastEventId: string
|
||||
oldestSeq: number | null
|
||||
newestSeq: number | null
|
||||
/** 是否触发了数据库回补。为 false 时必须让客户端知道这段空档没有补齐。 */
|
||||
backfill:
|
||||
| 'scheduled'
|
||||
| 'skipped_no_conversation_filter'
|
||||
| 'skipped_database_unavailable'
|
||||
| 'skipped_no_reader'
|
||||
| 'disabled'
|
||||
}
|
||||
|
||||
export interface MessageEventSink {
|
||||
onStatus(status: MessageBrokerStatus & { subscriptionId: string }): void
|
||||
onEvent(event: MessageEventRecord, origin: MessageEventOrigin): void
|
||||
onGap(gap: MessageGap): void
|
||||
/** 回补结束后的完整性报告;旧适配器可以不实现。 */
|
||||
onBackfill?(report: MessageBackfillReport): void
|
||||
}
|
||||
|
||||
export interface MessageSubscribeOptions {
|
||||
/** 会话 md5 白名单;空/省略 = 全部会话(此时无法做有界回补)。 */
|
||||
conversationIds?: string[]
|
||||
/** 上一次收到的 SSE id(`Last-Event-ID`)。 */
|
||||
lastEventId?: string
|
||||
/** 是否允许在缓冲覆盖不到时从数据库回补。默认 true。 */
|
||||
backfill?: boolean
|
||||
}
|
||||
|
||||
export interface MessageSubscription {
|
||||
readonly id: string
|
||||
/** 该订阅已经投递到的最新序号(诊断用)。 */
|
||||
readonly lastDeliveredSeq: number
|
||||
close(): void
|
||||
}
|
||||
|
||||
export interface MessageEventBrokerOptions {
|
||||
/**
|
||||
* username → 会话 md5。
|
||||
*
|
||||
* 事件必须携带与 `encodeMessageRef()` 同口径的 conversationId(md5),
|
||||
* 否则 `/query/message-context` 无法反查会话。返回 undefined 表示当前无法映射,
|
||||
* 该消息会被计入 `unmapped` 并**不投递**(避免发出不可用的 messageRef)。
|
||||
*/
|
||||
resolveConversationId: (sessionId: string) => string | undefined
|
||||
/** 数据库当前是否可用。用于 status 事件,不做连接管理。 */
|
||||
isDatabaseReady?: () => boolean
|
||||
/** Native Monitor 当前状态。未注入时 status 报 `unknown`。 */
|
||||
getMonitorState?: () => MessageRuntimeState
|
||||
/** 微信进程状态(调用方应缓存,避免 status 每次都 spawn 探针)。 */
|
||||
getWechatProcessState?: () => MessageRuntimeState
|
||||
/** 回补读取器。参数与 `getMessagesAsync(usernameOrMd5, startSec, endSec, {limit})` 一致。 */
|
||||
readMessages?: (
|
||||
sessionIdOrMd5: string,
|
||||
startTimeSec: number,
|
||||
endTimeSec: number,
|
||||
limit: number
|
||||
) => Promise<Wcdb4Message[]>
|
||||
/** md5 → username,仅回补时用于还原 `isGroup` 与 sender 语义。 */
|
||||
resolveSessionId?: (conversationId: string) => string | undefined
|
||||
bufferSize?: number
|
||||
bufferTtlMs?: number
|
||||
seenTtlMs?: number
|
||||
seenMaxEntries?: number
|
||||
backfillLookbackSec?: number
|
||||
backfillLimit?: number
|
||||
backfillMaxConversations?: number
|
||||
maxSubscribers?: number
|
||||
maxTextChars?: number
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
interface SubscriberState {
|
||||
id: string
|
||||
conversationIds: Set<string> | null
|
||||
sink: MessageEventSink
|
||||
deliveredIds: Map<string, number>
|
||||
lastDeliveredSeq: number
|
||||
delivered: number
|
||||
closed: boolean
|
||||
backfillEnabled: boolean
|
||||
}
|
||||
|
||||
export class MessageEventBroker {
|
||||
private readonly subscribers = new Map<string, SubscriberState>()
|
||||
private buffer: MessageEventRecord[] = []
|
||||
/** 事件 ID → 序号。只保留仍在缓冲里的条目。 */
|
||||
private readonly index = new Map<string, number>()
|
||||
private nextSeq = 1
|
||||
private disposed = false
|
||||
|
||||
private readonly seen = new Map<string, number>()
|
||||
private readonly bufferSize: number
|
||||
private readonly bufferTtlMs: number
|
||||
private readonly seenTtlMs: number
|
||||
private readonly seenMaxEntries: number
|
||||
private readonly backfillLookbackSec: number
|
||||
private readonly backfillLimit: number
|
||||
private readonly backfillMaxConversations: number
|
||||
private readonly maxSubscribers: number
|
||||
private readonly maxTextChars: number
|
||||
private readonly now: () => number
|
||||
|
||||
private counters = {
|
||||
published: 0,
|
||||
duplicates: 0,
|
||||
unmapped: 0,
|
||||
backfilled: 0,
|
||||
gaps: 0,
|
||||
rejected: 0
|
||||
}
|
||||
|
||||
constructor(private readonly options: MessageEventBrokerOptions) {
|
||||
this.bufferSize = Math.max(1, options.bufferSize ?? DEFAULT_BUFFER_SIZE)
|
||||
this.bufferTtlMs = Math.max(1000, options.bufferTtlMs ?? DEFAULT_BUFFER_TTL_MS)
|
||||
this.seenTtlMs = Math.max(1000, options.seenTtlMs ?? DEFAULT_SEEN_TTL_MS)
|
||||
this.seenMaxEntries = Math.max(1, options.seenMaxEntries ?? DEFAULT_SEEN_MAX_ENTRIES)
|
||||
this.backfillLookbackSec = Math.max(
|
||||
1,
|
||||
options.backfillLookbackSec ?? DEFAULT_BACKFILL_LOOKBACK_SEC
|
||||
)
|
||||
this.backfillLimit = Math.max(1, options.backfillLimit ?? DEFAULT_BACKFILL_LIMIT)
|
||||
this.backfillMaxConversations = Math.max(
|
||||
1,
|
||||
options.backfillMaxConversations ?? DEFAULT_BACKFILL_MAX_CONVERSATIONS
|
||||
)
|
||||
this.maxSubscribers = Math.max(1, options.maxSubscribers ?? DEFAULT_MAX_SUBSCRIBERS)
|
||||
this.maxTextChars = Math.max(64, options.maxTextChars ?? DEFAULT_MAX_TEXT_CHARS)
|
||||
this.now = options.now ?? Date.now
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布一条已经由 MessageListener 回读并规范化的消息。
|
||||
*
|
||||
* 返回 null 表示消息无法形成可用事件(会话未映射 / messageRef 构造失败),
|
||||
* 或命中去重表(同一条消息被重复回读)。
|
||||
*/
|
||||
publish(message: NormalizedIncomingMessage): MessageEventRecord | null {
|
||||
if (this.disposed) return null
|
||||
const record = this.toRecord(message)
|
||||
if (!record) return null
|
||||
|
||||
this.evictSeen(this.now())
|
||||
if (this.seen.has(record.id)) {
|
||||
this.counters.duplicates += 1
|
||||
return null
|
||||
}
|
||||
|
||||
this.seen.set(record.id, this.now())
|
||||
this.trimSeen()
|
||||
|
||||
record.seq = this.nextSeq
|
||||
this.nextSeq += 1
|
||||
|
||||
this.buffer.push(record)
|
||||
this.index.set(record.id, record.seq)
|
||||
this.trimBuffer()
|
||||
|
||||
this.counters.published += 1
|
||||
this.deliverLive(record)
|
||||
return record
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅消息事件。
|
||||
*
|
||||
* 订阅会立刻收到一条 `status`;随后按 `lastEventId` 决定重放还是回补。
|
||||
* 返回的句柄必须由调用方在连接关闭时 `close()`,否则会占用订阅配额。
|
||||
*/
|
||||
subscribe(options: MessageSubscribeOptions, sink: MessageEventSink): MessageSubscription {
|
||||
if (this.subscribers.size >= this.maxSubscribers) {
|
||||
throw new Error('消息事件订阅数已达上限')
|
||||
}
|
||||
|
||||
const state: SubscriberState = {
|
||||
id: randomUUID(),
|
||||
conversationIds:
|
||||
options.conversationIds && options.conversationIds.length > 0
|
||||
? new Set(options.conversationIds)
|
||||
: null,
|
||||
sink,
|
||||
deliveredIds: new Map(),
|
||||
lastDeliveredSeq: 0,
|
||||
delivered: 0,
|
||||
closed: false,
|
||||
backfillEnabled: options.backfill !== false
|
||||
}
|
||||
this.subscribers.set(state.id, state)
|
||||
sink.onStatus({ ...this.status(), subscriptionId: state.id })
|
||||
void this.resume(state, options.lastEventId)
|
||||
|
||||
return {
|
||||
id: state.id,
|
||||
get lastDeliveredSeq(): number {
|
||||
return state.lastDeliveredSeq
|
||||
},
|
||||
close: () => {
|
||||
state.closed = true
|
||||
this.subscribers.delete(state.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
status(): MessageBrokerStatus {
|
||||
return {
|
||||
database: this.options.isDatabaseReady?.() === false ? 'unavailable' : 'ready',
|
||||
monitor: this.options.getMonitorState?.() ?? 'unknown',
|
||||
wechat: this.options.getWechatProcessState?.() ?? 'unknown',
|
||||
subscribers: this.subscribers.size,
|
||||
buffered: this.buffer.length,
|
||||
oldestSeq: this.buffer[0]?.seq ?? null,
|
||||
newestSeq: this.buffer[this.buffer.length - 1]?.seq ?? null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空缓冲与去重表,但**保留订阅者与序号**。
|
||||
*
|
||||
* 用于数据库重开 / 切账号:旧事件不能再被重放,客户端的旧游标会自然落到
|
||||
* `oldestSeq` 之前,从而收到 gap;而已经连着的订阅者不需要断开重连。
|
||||
*/
|
||||
resetBuffer(): void {
|
||||
this.buffer = []
|
||||
this.index.clear()
|
||||
this.seen.clear()
|
||||
}
|
||||
|
||||
stats(): typeof this.counters & MessageBrokerStatus {
|
||||
return { ...this.counters, ...this.status() }
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.disposed = true
|
||||
for (const state of this.subscribers.values()) state.closed = true
|
||||
this.subscribers.clear()
|
||||
this.buffer = []
|
||||
this.index.clear()
|
||||
this.seen.clear()
|
||||
}
|
||||
|
||||
private async resume(state: SubscriberState, lastEventId?: string): Promise<void> {
|
||||
const raw = typeof lastEventId === 'string' ? lastEventId.trim() : ''
|
||||
// 没带游标 = 首次订阅,只接实时事件,不需要 gap。
|
||||
if (!raw) return
|
||||
if (state.closed) return
|
||||
|
||||
const oldest = this.buffer[0]?.seq ?? null
|
||||
const newest = this.buffer[this.buffer.length - 1]?.seq ?? null
|
||||
/** 本进程已经分配出去的最大序号(含未进缓冲的回补事件)。 */
|
||||
const maxAssigned = this.nextSeq - 1
|
||||
|
||||
const lastSeq = parseLastEventId(raw)
|
||||
/*
|
||||
* 带了游标但解析不了:不能当成「首次订阅」静默跳过 ——
|
||||
* 那等于把客户端明确声明的断点吞掉。
|
||||
*/
|
||||
if (lastSeq === null) {
|
||||
await this.emitGap(state, raw, 'invalid_cursor', oldest, newest)
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
* 序号只在**本进程内**单调。客户端如果拿着上一个进程的游标(重启后
|
||||
* 序号会从 1 重新开始),它可能大于本进程已分配的任何序号 —— 这时
|
||||
* 既不能当成「已经收到最新」,也不能假装能重放,只能走 gap。
|
||||
*/
|
||||
if (lastSeq > maxAssigned) {
|
||||
await this.emitGap(state, raw, 'cursor_from_previous_process', oldest, newest)
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
* 只有「游标落在缓冲区间内」或「游标正好是本进程最后一个被淘汰的序号」
|
||||
* 才能保证重放完整。`lastSeq < oldest - 1` 说明中间已经有事件被淘汰,
|
||||
* 必须显式报 gap,不能假装重放是连续的。
|
||||
*/
|
||||
if (oldest !== null && lastSeq >= oldest - 1) {
|
||||
for (const event of this.buffer) {
|
||||
if (state.closed) return
|
||||
if (event.seq <= lastSeq) continue
|
||||
this.deliver(state, event, 'replay')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
/*
|
||||
* 缓冲为空但有本进程分配过的序号:可能只发生过回补事件(不进缓冲),
|
||||
* 也可能事件已按 TTL 全部淘汰。前者没有漏消息,后者必须报 gap。
|
||||
*/
|
||||
if (oldest === null && lastSeq === maxAssigned) return
|
||||
|
||||
await this.emitGap(state, raw, 'buffer_overflow', oldest, newest)
|
||||
}
|
||||
|
||||
private async emitGap(
|
||||
state: SubscriberState,
|
||||
lastEventId: string,
|
||||
reason: MessageGap['reason'],
|
||||
oldest: number | null,
|
||||
newest: number | null
|
||||
): Promise<void> {
|
||||
this.counters.gaps += 1
|
||||
/*
|
||||
* 先发 gap,再回补。反过来会让客户端先收到一批「来源不明」的消息,
|
||||
* 然后才被告知中间有断档 —— 顺序本身就是语义的一部分。
|
||||
*/
|
||||
const plan = this.backfillPlan(state)
|
||||
state.sink.onGap({
|
||||
reason,
|
||||
requestedLastEventId: String(lastEventId),
|
||||
oldestSeq: oldest,
|
||||
newestSeq: newest,
|
||||
backfill: plan
|
||||
})
|
||||
if (plan === 'scheduled') await this.runBackfill(state)
|
||||
}
|
||||
|
||||
/**
|
||||
* 有界数据库回补的前置判定。
|
||||
*
|
||||
* 边界(全部不可协商):
|
||||
* - 只回补订阅时显式指定的会话;「全部会话」无法做有界回补;
|
||||
* - 时间窗 ≤ `backfillLookbackSec`,单会话 ≤ `backfillLimit` 条;
|
||||
* - 会话数 ≤ `backfillMaxConversations`;
|
||||
* - 数据库不可用 / 没有读取器时明确跳过,不伪造事件。
|
||||
*/
|
||||
private backfillPlan(state: SubscriberState): MessageGap['backfill'] {
|
||||
if (!state.backfillEnabled) return 'disabled'
|
||||
if (!state.conversationIds || state.conversationIds.size === 0) {
|
||||
return 'skipped_no_conversation_filter'
|
||||
}
|
||||
if (!this.options.readMessages) return 'skipped_no_reader'
|
||||
if (this.options.isDatabaseReady?.() === false) return 'skipped_database_unavailable'
|
||||
return 'scheduled'
|
||||
}
|
||||
|
||||
/** 执行已经通过 `backfillPlan` 判定的回补,并报告是否被上限截断。 */
|
||||
private async runBackfill(state: SubscriberState): Promise<void> {
|
||||
if (!state.conversationIds || !this.options.readMessages) return
|
||||
|
||||
const nowMs = this.now()
|
||||
const endSec = Math.floor(nowMs / 1000)
|
||||
const startSec = endSec - this.backfillLookbackSec
|
||||
const requestedConversations = state.conversationIds.size
|
||||
const conversations = Array.from(state.conversationIds).slice(0, this.backfillMaxConversations)
|
||||
const conversationTruncated = requestedConversations > conversations.length
|
||||
|
||||
let delivered = 0
|
||||
let failedConversations = 0
|
||||
let messageTruncated = false
|
||||
|
||||
for (const conversationId of conversations) {
|
||||
if (state.closed) return
|
||||
const sessionId = this.options.resolveSessionId?.(conversationId) ?? conversationId
|
||||
let rows: Wcdb4Message[]
|
||||
try {
|
||||
rows = await this.options.readMessages(sessionId, startSec, endSec, this.backfillLimit)
|
||||
} catch (error) {
|
||||
failedConversations += 1
|
||||
console.warn(
|
||||
`[MessageEventBroker] backfill read failed: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
continue
|
||||
}
|
||||
/*
|
||||
* 返回行数达到 limit 就按「可能被截断」上报:多读一条的代价没有必要,
|
||||
* 但把「正好读满」当成完整回补,会让客户端误以为没有漏消息。
|
||||
*/
|
||||
if (rows.length >= this.backfillLimit) messageTruncated = true
|
||||
for (const row of rows) {
|
||||
if (state.closed) return
|
||||
const normalized = normalizeIncomingMessage(sessionId, row)
|
||||
if (!normalized) continue
|
||||
const record = this.toRecord(normalized)
|
||||
if (!record) continue
|
||||
// 回补事件不进入环形缓冲:它是补偿,不是「本进程产生过」的事实。
|
||||
record.seq = this.nextSeq
|
||||
this.nextSeq += 1
|
||||
this.counters.backfilled += 1
|
||||
delivered += 1
|
||||
this.deliver(state, record, 'db_backfill')
|
||||
}
|
||||
}
|
||||
|
||||
if (state.closed) return
|
||||
const report: MessageBackfillReport = {
|
||||
requestedConversations,
|
||||
processedConversations: conversations.length,
|
||||
delivered,
|
||||
failedConversations,
|
||||
conversationTruncated,
|
||||
messageTruncated,
|
||||
truncated: conversationTruncated || messageTruncated,
|
||||
complete: !conversationTruncated && !messageTruncated && failedConversations === 0,
|
||||
perConversationLimit: this.backfillLimit,
|
||||
maxConversations: this.backfillMaxConversations,
|
||||
windowSec: this.backfillLookbackSec
|
||||
}
|
||||
try {
|
||||
state.sink.onBackfill?.(report)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[MessageEventBroker] backfill report sink threw: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private deliverLive(record: MessageEventRecord): void {
|
||||
for (const state of this.subscribers.values()) {
|
||||
if (state.closed) continue
|
||||
if (state.conversationIds && !state.conversationIds.has(record.conversationId)) continue
|
||||
this.deliver(state, record, 'live')
|
||||
}
|
||||
}
|
||||
|
||||
private deliver(
|
||||
state: SubscriberState,
|
||||
record: MessageEventRecord,
|
||||
origin: MessageEventOrigin
|
||||
): void {
|
||||
if (state.closed) return
|
||||
if (state.conversationIds && !state.conversationIds.has(record.conversationId)) return
|
||||
if (state.deliveredIds.has(record.id)) return
|
||||
|
||||
state.deliveredIds.set(record.id, this.now())
|
||||
this.trimSubscriberSeen(state)
|
||||
state.lastDeliveredSeq = record.seq
|
||||
state.delivered += 1
|
||||
try {
|
||||
state.sink.onEvent(record, origin)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[MessageEventBroker] subscriber sink threw: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private toRecord(message: NormalizedIncomingMessage): MessageEventRecord | null {
|
||||
const conversationId = this.options.resolveConversationId(message.sessionId)
|
||||
if (!conversationId) {
|
||||
this.counters.unmapped += 1
|
||||
return null
|
||||
}
|
||||
/*
|
||||
* 消息身份必须是 `create_time:local_id`:
|
||||
* `local_id` 只在单库/单分片内唯一,跨分片会重复;只带 localId 的 ref
|
||||
* 会让 `/query/message-context` 判 `ambiguous_message`。
|
||||
* `locateMessageAsync` 已经支持复合身份,这里与 Knowledge 的 `local:${time}:${id}` 同口径。
|
||||
*/
|
||||
const identity = `${message.createTime}:${message.localId}`
|
||||
let messageRef: string
|
||||
try {
|
||||
messageRef = encodeMessageRef(conversationId, identity)
|
||||
} catch (error) {
|
||||
this.counters.rejected += 1
|
||||
console.warn(
|
||||
`[MessageEventBroker] messageRef rejected: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
const rawText = message.content ?? ''
|
||||
const truncated = rawText.length > this.maxTextChars
|
||||
return {
|
||||
id: eventIdFor(conversationId, identity),
|
||||
seq: 0,
|
||||
conversationId,
|
||||
messageRef,
|
||||
timestamp: message.createTime,
|
||||
messageType: message.messageType,
|
||||
isSelf: message.isSelf,
|
||||
isGroup: message.isGroup,
|
||||
...(message.senderId ? { senderId: message.senderId } : {}),
|
||||
...(message.senderNickname ? { senderNickname: message.senderNickname } : {}),
|
||||
...(rawText ? { text: truncated ? rawText.slice(0, this.maxTextChars) : rawText } : {}),
|
||||
...(truncated ? { textTruncated: true } : {}),
|
||||
mentionTargets: message.mentionTargets
|
||||
}
|
||||
}
|
||||
|
||||
private trimBuffer(): void {
|
||||
const cutoff = this.now() - this.bufferTtlMs
|
||||
while (this.buffer.length > 0) {
|
||||
const oldest = this.buffer[0]
|
||||
const expired = oldest.timestamp * 1000 < cutoff
|
||||
if (this.buffer.length <= this.bufferSize && !expired) break
|
||||
this.buffer.shift()
|
||||
if (this.index.get(oldest.id) === oldest.seq) this.index.delete(oldest.id)
|
||||
}
|
||||
}
|
||||
|
||||
private evictSeen(now: number): void {
|
||||
for (const [id, seenAt] of this.seen) {
|
||||
if (now - seenAt <= this.seenTtlMs) break
|
||||
this.seen.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
private trimSeen(): void {
|
||||
if (this.seen.size <= this.seenMaxEntries) return
|
||||
const overflow = this.seen.size - this.seenMaxEntries
|
||||
let removed = 0
|
||||
for (const id of this.seen.keys()) {
|
||||
this.seen.delete(id)
|
||||
removed += 1
|
||||
if (removed >= overflow) break
|
||||
}
|
||||
}
|
||||
|
||||
private trimSubscriberSeen(state: SubscriberState): void {
|
||||
if (state.deliveredIds.size <= DEFAULT_SUBSCRIBER_SEEN_MAX) return
|
||||
const overflow = state.deliveredIds.size - DEFAULT_SUBSCRIBER_SEEN_MAX
|
||||
let removed = 0
|
||||
for (const id of state.deliveredIds.keys()) {
|
||||
state.deliveredIds.delete(id)
|
||||
removed += 1
|
||||
if (removed >= overflow) break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 同一会话 + 同一条消息的确定性事件 ID。`messageIdentity` 为 `createTime:localId`。 */
|
||||
export function eventIdFor(conversationId: string, messageIdentity: string): string {
|
||||
return `evt_${createHash('sha256')
|
||||
.update(`${conversationId}\u0000${messageIdentity}`, 'utf8')
|
||||
.digest('hex')
|
||||
.slice(0, 24)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 SSE `Last-Event-ID`。
|
||||
*
|
||||
* 只接受纯数字序号;其它形态(含上一版本客户端可能发来的任意字符串)
|
||||
* 一律当成「没有游标」而不是猜一个位置 —— 猜错会导致静默漏消息。
|
||||
*/
|
||||
export function parseLastEventId(value: unknown): number | null {
|
||||
if (typeof value !== 'string' || !value.trim()) return null
|
||||
const trimmed = value.trim()
|
||||
if (!/^\d{1,15}$/.test(trimmed)) return null
|
||||
const parsed = Number(trimmed)
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null
|
||||
}
|
||||
@@ -50,6 +50,10 @@ const DEFAULT_READ_LIMIT = 50
|
||||
const DEFAULT_DEDUP_TTL_MS = 5 * 60 * 1000
|
||||
/** dedup 容量上限,防止长时间运行后无限增长。 */
|
||||
const DEFAULT_DEDUP_MAX_ENTRIES = 5_000
|
||||
/** 未稳定发送行的重试间隔与最大等待时间,避免把写库中间态误判为对方来信。 */
|
||||
const DEFAULT_SETTLE_RETRY_MS = 400
|
||||
const DEFAULT_MAX_SETTLE_WAIT_MS = 2_000
|
||||
const SYSTEM_MESSAGE_TYPES = new Set([10000, 10002])
|
||||
|
||||
/**
|
||||
* 规范化后的入站消息。
|
||||
@@ -101,6 +105,8 @@ export interface MessageListenerStats {
|
||||
delivered: number
|
||||
/** 因 dedup 被丢弃的重复投递数。 */
|
||||
deduped: number
|
||||
/** 单个会话回读失败的次数(不中断同批其他会话)。 */
|
||||
failedReadbacks: number
|
||||
}
|
||||
|
||||
export interface MessageListenerOptions {
|
||||
@@ -110,6 +116,8 @@ export interface MessageListenerOptions {
|
||||
readLimit?: number
|
||||
dedupTtlMs?: number
|
||||
dedupMaxEntries?: number
|
||||
settleRetryMs?: number
|
||||
maxSettleWaitMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,6 +194,65 @@ export function decodeSourcePayload(value: unknown): string | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 WCDB 行规范化为克制的 DTO。返回 null 表示这条行缺关键标识,无法投递。
|
||||
*
|
||||
* 纯函数,**唯一**的规范化实现:实时回读与数据库回补都走这里,
|
||||
* 避免两条路径对同一条消息给出不同字段。
|
||||
*/
|
||||
export function normalizeIncomingMessage(
|
||||
sessionUsername: string,
|
||||
message: Wcdb4Message
|
||||
): NormalizedIncomingMessage | null {
|
||||
const localId = message.mesLocalID === undefined ? '' : String(message.mesLocalID)
|
||||
if (!localId) return null
|
||||
|
||||
const createTime = Number(message.msgCreateTime) || 0
|
||||
if (!createTime) return null
|
||||
|
||||
const raw = (message.raw ?? {}) as Record<string, unknown>
|
||||
const source = decodeSourcePayload(raw.source)
|
||||
const senderId = message.sender ? String(message.sender) : undefined
|
||||
|
||||
return {
|
||||
sessionId: sessionUsername,
|
||||
localId,
|
||||
serverId: message.serverId ? String(message.serverId) : undefined,
|
||||
createTime,
|
||||
messageType: Number(message.messageType) || 0,
|
||||
// `mesDes === 0` 是自己发送。不用昵称 / sender 文本 / content / username 前缀判断。
|
||||
isSelf: Number(message.mesDes) === 0,
|
||||
senderId,
|
||||
senderNickname: message.senderNickname ? String(message.senderNickname) : undefined,
|
||||
content: message.msgContent ? String(message.msgContent) : undefined,
|
||||
source,
|
||||
isGroup: sessionUsername.endsWith('@chatroom'),
|
||||
mentionTargets: extractMentionTargets(source)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断消息是否处于微信两阶段写库的中间态(发送中或尚未回填发送者与 server_id)。
|
||||
* 提前投递会把未稳定的本人发出行误判为 isSelf=false 并锁死去重键。
|
||||
*/
|
||||
export function isMessageIdentityUnsettled(
|
||||
message: Wcdb4Message,
|
||||
normalized: NormalizedIncomingMessage
|
||||
): boolean {
|
||||
if (normalized.isSelf) return false
|
||||
if (SYSTEM_MESSAGE_TYPES.has(normalized.messageType)) return false
|
||||
|
||||
const raw = (message.raw ?? {}) as Record<string, unknown>
|
||||
const status = raw.status !== undefined && raw.status !== null ? Number(raw.status) : NaN
|
||||
if (status === 1) return true
|
||||
|
||||
const serverId = String(normalized.serverId ?? '').trim()
|
||||
if (!serverId || serverId === '0') return true
|
||||
|
||||
if (!normalized.senderId) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时消息监听。
|
||||
*
|
||||
@@ -216,7 +283,10 @@ export class MessageListenerService {
|
||||
* 120ms 内收到 `A B A C B` 必须回读 A/B/C 三个,绝不能「最后一个 wins」。
|
||||
*/
|
||||
private readonly pendingSessions = new Set<string>()
|
||||
private readonly pendingUnsettled = new Map<string, number>()
|
||||
private readonly settleSessions = new Set<string>()
|
||||
private coalesceTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private settleTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private readbackInFlight = false
|
||||
private pendingReadback = false
|
||||
private disposed = false
|
||||
@@ -227,13 +297,16 @@ export class MessageListenerService {
|
||||
private readonly readLimit: number
|
||||
private readonly dedupTtlMs: number
|
||||
private readonly dedupMaxEntries: number
|
||||
private readonly settleRetryMs: number
|
||||
private readonly maxSettleWaitMs: number
|
||||
|
||||
private counters: MessageListenerStats = {
|
||||
nativeEvents: 0,
|
||||
coalescedEvents: 0,
|
||||
readbacks: 0,
|
||||
delivered: 0,
|
||||
deduped: 0
|
||||
deduped: 0,
|
||||
failedReadbacks: 0
|
||||
}
|
||||
|
||||
constructor(
|
||||
@@ -246,6 +319,8 @@ export class MessageListenerService {
|
||||
this.readLimit = options.readLimit ?? DEFAULT_READ_LIMIT
|
||||
this.dedupTtlMs = options.dedupTtlMs ?? DEFAULT_DEDUP_TTL_MS
|
||||
this.dedupMaxEntries = options.dedupMaxEntries ?? DEFAULT_DEDUP_MAX_ENTRIES
|
||||
this.settleRetryMs = options.settleRetryMs ?? DEFAULT_SETTLE_RETRY_MS
|
||||
this.maxSettleWaitMs = options.maxSettleWaitMs ?? DEFAULT_MAX_SETTLE_WAIT_MS
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -268,8 +343,14 @@ export class MessageListenerService {
|
||||
clearTimeout(this.coalesceTimer)
|
||||
this.coalesceTimer = null
|
||||
}
|
||||
if (this.settleTimer) {
|
||||
clearTimeout(this.settleTimer)
|
||||
this.settleTimer = null
|
||||
}
|
||||
this.listeners.clear()
|
||||
this.seen.clear()
|
||||
this.pendingUnsettled.clear()
|
||||
this.settleSessions.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -323,12 +404,27 @@ export class MessageListenerService {
|
||||
try {
|
||||
let delivered = 0
|
||||
let sessions = 0
|
||||
let failures = 0
|
||||
|
||||
if (preciseSessions.length > 0) {
|
||||
for (const sessionId of preciseSessions) {
|
||||
if (this.disposed) return
|
||||
delivered += await this.readbackSession(sessionId)
|
||||
sessions += 1
|
||||
try {
|
||||
delivered += await this.readbackSession(sessionId)
|
||||
sessions += 1
|
||||
} catch (error) {
|
||||
/*
|
||||
* 单个会话读失败不能中断整批:pending 已在批次开始时清空,
|
||||
* 跳出循环会让本批其余会话静默丢失。
|
||||
*/
|
||||
failures += 1
|
||||
this.counters.failedReadbacks += 1
|
||||
console.warn(
|
||||
`[MessageListener] session readback failed: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// legacy:旧 runtime 的 payload 不带会话,只能回读「最近活跃会话」。
|
||||
@@ -338,11 +434,12 @@ export class MessageListenerService {
|
||||
sessions = 1
|
||||
}
|
||||
|
||||
if (delivered > 0) {
|
||||
if (delivered > 0 || failures > 0) {
|
||||
// 日志只记录协议版本、数量与耗时 —— **不含** wxid / 群名 / 昵称 / 正文 / source / sessionId。
|
||||
console.log(
|
||||
`[MessageListener] protocol=${preciseSessions.length > 0 ? 'v2' : 'v1'}` +
|
||||
` sessions=${sessions} delivered=${delivered} readbackMs=${Date.now() - startedAt}` +
|
||||
` sessions=${sessions} delivered=${delivered} failures=${failures}` +
|
||||
` readbackMs=${Date.now() - startedAt}` +
|
||||
` events=${this.counters.nativeEvents} coalesced=${this.counters.coalescedEvents}`
|
||||
)
|
||||
}
|
||||
@@ -377,9 +474,21 @@ export class MessageListenerService {
|
||||
if (this.disposed) return 0
|
||||
|
||||
let delivered = 0
|
||||
let needsSettleRetry = false
|
||||
const now = Date.now()
|
||||
for (const message of messages) {
|
||||
const normalized = this.normalize(sessionId, message)
|
||||
if (!normalized) continue
|
||||
const key = `${normalized.sessionId}:${normalized.localId}`
|
||||
if (this.seen.has(key)) {
|
||||
this.counters.deduped += 1
|
||||
continue
|
||||
}
|
||||
if (this.shouldDeferUnsettled(key, message, normalized, now)) {
|
||||
needsSettleRetry = true
|
||||
continue
|
||||
}
|
||||
this.pendingUnsettled.delete(key)
|
||||
// dedup:同一条消息可能在多个读回窗口中反复出现(native 事件本身也可能重复)。
|
||||
if (!this.markSeen(normalized)) {
|
||||
this.counters.deduped += 1
|
||||
@@ -389,9 +498,55 @@ export class MessageListenerService {
|
||||
delivered += 1
|
||||
this.deliver(normalized)
|
||||
}
|
||||
if (needsSettleRetry) {
|
||||
this.scheduleSettleRetry(sessionId)
|
||||
}
|
||||
return delivered
|
||||
}
|
||||
|
||||
private shouldDeferUnsettled(
|
||||
key: string,
|
||||
message: Wcdb4Message,
|
||||
normalized: NormalizedIncomingMessage,
|
||||
now: number
|
||||
): boolean {
|
||||
if (this.maxSettleWaitMs <= 0 || !isMessageIdentityUnsettled(message, normalized)) {
|
||||
return false
|
||||
}
|
||||
const firstSeenAt = this.pendingUnsettled.get(key)
|
||||
if (firstSeenAt === undefined) {
|
||||
this.pendingUnsettled.set(key, now)
|
||||
if (this.pendingUnsettled.size > this.dedupMaxEntries) {
|
||||
this.evictUnsettled(now)
|
||||
}
|
||||
return true
|
||||
}
|
||||
return now - firstSeenAt < this.maxSettleWaitMs
|
||||
}
|
||||
|
||||
private scheduleSettleRetry(sessionId: string): void {
|
||||
if (this.disposed) return
|
||||
this.settleSessions.add(sessionId)
|
||||
if (this.settleTimer) return
|
||||
this.settleTimer = setTimeout(() => {
|
||||
this.settleTimer = null
|
||||
if (this.disposed) return
|
||||
for (const id of this.settleSessions) {
|
||||
this.pendingSessions.add(id)
|
||||
}
|
||||
this.settleSessions.clear()
|
||||
void this.readback()
|
||||
}, this.settleRetryMs)
|
||||
}
|
||||
|
||||
private evictUnsettled(now: number): void {
|
||||
for (const [key, firstSeenAt] of this.pendingUnsettled) {
|
||||
if (now - firstSeenAt >= this.maxSettleWaitMs) {
|
||||
this.pendingUnsettled.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private deliver(message: NormalizedIncomingMessage): void {
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
@@ -411,31 +566,7 @@ export class MessageListenerService {
|
||||
sessionUsername: string,
|
||||
message: Wcdb4Message
|
||||
): NormalizedIncomingMessage | null {
|
||||
const localId = message.mesLocalID === undefined ? '' : String(message.mesLocalID)
|
||||
if (!localId) return null
|
||||
|
||||
const createTime = Number(message.msgCreateTime) || 0
|
||||
if (!createTime) return null
|
||||
|
||||
const raw = (message.raw ?? {}) as Record<string, unknown>
|
||||
const source = decodeSourcePayload(raw.source)
|
||||
const senderId = message.sender ? String(message.sender) : undefined
|
||||
|
||||
return {
|
||||
sessionId: sessionUsername,
|
||||
localId,
|
||||
serverId: message.serverId ? String(message.serverId) : undefined,
|
||||
createTime,
|
||||
messageType: Number(message.messageType) || 0,
|
||||
// `mesDes === 0` 是自己发送。不用昵称 / sender 文本 / content / username 前缀判断。
|
||||
isSelf: Number(message.mesDes) === 0,
|
||||
senderId,
|
||||
senderNickname: message.senderNickname ? String(message.senderNickname) : undefined,
|
||||
content: message.msgContent ? String(message.msgContent) : undefined,
|
||||
source,
|
||||
isGroup: sessionUsername.endsWith('@chatroom'),
|
||||
mentionTargets: extractMentionTargets(source)
|
||||
}
|
||||
return normalizeIncomingMessage(sessionUsername, message)
|
||||
}
|
||||
|
||||
/** 登记并返回「是否是第一次见到」。同时做 TTL + 容量淘汰。 */
|
||||
|
||||
@@ -38,7 +38,7 @@ export const messagesAroundRadii = (
|
||||
): number[] => (anchorSeconds && anchorSeconds > 0 ? [baseRadius, widenRadius] : [])
|
||||
|
||||
/** 有界窗口 + 精确身份定位。窗口按上限截断,绝不返回整段历史。 */
|
||||
export const sliceMessagesAroundWindow = <T extends { id?: unknown }>(
|
||||
export const sliceMessagesAroundWindow = <T extends { id?: unknown; createTime?: number }>(
|
||||
messages: T[],
|
||||
conversationId: string,
|
||||
targetMessageId: string,
|
||||
@@ -46,9 +46,21 @@ export const sliceMessagesAroundWindow = <T extends { id?: unknown }>(
|
||||
): { window: T[]; index: number; truncated: boolean } => {
|
||||
const truncated = messages.length > maxWindowMessages
|
||||
const window = truncated ? messages.slice(0, maxWindowMessages) : messages
|
||||
const index = window.findIndex(
|
||||
(message) =>
|
||||
normalizeMessageIdentity(conversationId, String(message.id ?? ''))?.messageId === targetMessageId
|
||||
)
|
||||
const separator = targetMessageId.lastIndexOf(':')
|
||||
const wantedTime = separator > 0 ? targetMessageId.slice(0, separator) : ''
|
||||
const wantedLocalId = separator > 0 ? targetMessageId.slice(separator + 1) : ''
|
||||
const matchesTarget = (message: T): boolean => {
|
||||
const identity = normalizeMessageIdentity(conversationId, String(message.id ?? ''))
|
||||
if (!identity) return false
|
||||
// 裸 localId:旧调用方与 query API 的 `message.id` 都走这条。
|
||||
if (identity.messageId === targetMessageId) return true
|
||||
// 复合身份:SSE 的 messageRef 为 `createTime:localId`,必须同时比对时间。
|
||||
return (
|
||||
separator > 0 &&
|
||||
identity.messageId === wantedLocalId &&
|
||||
String(message.createTime ?? '') === wantedTime
|
||||
)
|
||||
}
|
||||
const index = window.findIndex(matchesTarget)
|
||||
return { window, index, truncated }
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import path from 'node:path'
|
||||
import { findResource } from '../resource-paths'
|
||||
import { isMacNativeRuntimeUnavailable, resolveWcdbConfigHelper } from '../native-runtime-paths'
|
||||
import { resolveExternalComponent } from './external-component-locator'
|
||||
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
|
||||
import type { Wcdb4Client } from '../wcdb4-client'
|
||||
import {
|
||||
MSG_INSERT_SWITCHES,
|
||||
@@ -205,6 +206,16 @@ function runHelper(
|
||||
request: { key: string; rooms: string[]; myWxid: string },
|
||||
timeoutMs = HELPER_TIMEOUT_MS
|
||||
): Promise<HelperRunResult> {
|
||||
// 只读测试模式:任何 helper 写入(开关 / ensure-rules)都不允许发生。
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('MsgInsert helper 写入')
|
||||
return Promise.resolve({
|
||||
ok: false,
|
||||
exitCode: null,
|
||||
errorCode: 'READ_ONLY_MODE',
|
||||
message: '只读测试模式:禁止写入微信数据库'
|
||||
})
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
let child: ReturnType<typeof spawn>
|
||||
try {
|
||||
@@ -730,6 +741,10 @@ export async function applyMsgInsertSwitch(
|
||||
export async function reconcileMsgInsertRules(
|
||||
input: MsgInsertScopeInput & { myWxid: string; databaseKey: string; extraRooms?: string[] }
|
||||
): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('MsgInsert reconciliation')
|
||||
return { done: false, rooms: 0, written: 0, errorCode: 'READ_ONLY_MODE' }
|
||||
}
|
||||
if (isMacNativeRuntimeUnavailable()) {
|
||||
return { done: false, rooms: 0, written: 0, errorCode: 'HELPER_NOT_FOUND' }
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
personalWechatSendService,
|
||||
type PersonalWechatSendService
|
||||
} from './personal-wechat-send-service'
|
||||
import { macWechatRuntimeManager } from './mac-wechat-runtime-manager'
|
||||
|
||||
/**
|
||||
* Converts the detailed sender diagnostics into a small contract that other
|
||||
@@ -22,7 +21,7 @@ export class PersonalWechatCapabilityService {
|
||||
private readonly sender: Pick<PersonalWechatSendService, 'getStatus'>,
|
||||
private readonly platform: NodeJS.Platform = process.platform,
|
||||
private readonly getMacStatus: () => Promise<PersonalWechatSenderStatus> = () =>
|
||||
macWechatRuntimeManager.buildSenderStatus()
|
||||
personalWechatSendService.getStatus()
|
||||
) {}
|
||||
|
||||
async getPersonalWechatSendCapability(): Promise<PersonalWechatSendCapability> {
|
||||
@@ -84,6 +83,7 @@ export class PersonalWechatCapabilityService {
|
||||
if (senderStatus.platform !== 'darwin' || senderStatus.state === 'unsupported_platform') {
|
||||
return 'unsupported'
|
||||
}
|
||||
if (!senderStatus.endpoint) return 'unconfigured'
|
||||
if (senderStatus.state === 'error') return 'error'
|
||||
if (senderStatus.state === 'runtime_missing') return 'unconfigured'
|
||||
const hasCurrentBinding = Boolean(
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
import { homedir, tmpdir } from 'os'
|
||||
import { delimiter, dirname, extname, join, sep, basename } from 'path'
|
||||
import { resolveBundledFfmpegPath } from '../ffmpeg-path'
|
||||
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
|
||||
import { promisify } from 'util'
|
||||
import type {
|
||||
PersonalWechatSendRequest,
|
||||
@@ -367,6 +368,9 @@ function prepareMacWechatImageFile(
|
||||
}
|
||||
}
|
||||
|
||||
const MAC_IMAGE_STAGE_PREFIX = 'tm-'
|
||||
const MAC_IMAGE_STAGE_RETENTION_MS = 10 * 60 * 1000
|
||||
|
||||
function stageMacWechatImageForMessageSourceSend(
|
||||
filePath: string,
|
||||
senderWxid: string,
|
||||
@@ -375,6 +379,29 @@ function stageMacWechatImageForMessageSourceSend(
|
||||
const temporaryRoot = findWechatImagePath(wechatFilesRoot, new Date(), senderWxid)
|
||||
if (!temporaryRoot) throw new Error('无法定位当前微信账号的图片临时目录')
|
||||
mkdirSync(temporaryRoot, { recursive: true })
|
||||
|
||||
/*
|
||||
* 暂存图**不能**在 /sendMsg 返回后立即删除:`ok: true` 只代表 Host 已接受请求,
|
||||
* 微信侧是异步读取这个文件的,删早了消息会静默丢失(API 仍回 sent)。
|
||||
* 改为按保留期回收,顺手清理超过 10 分钟的历史暂存图,防止异常退出残留。
|
||||
*/
|
||||
const now = Date.now()
|
||||
try {
|
||||
for (const entry of readdirSync(temporaryRoot)) {
|
||||
if (!entry.startsWith(MAC_IMAGE_STAGE_PREFIX)) continue
|
||||
const candidate = join(temporaryRoot, entry)
|
||||
try {
|
||||
if (now - statSync(candidate).mtimeMs > MAC_IMAGE_STAGE_RETENTION_MS) {
|
||||
unlinkSync(candidate)
|
||||
}
|
||||
} catch {
|
||||
// Best-effort stale image cleanup.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore directory listing errors.
|
||||
}
|
||||
|
||||
const extension = extname(filePath).toLowerCase()
|
||||
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.png'
|
||||
const stagedPath = join(
|
||||
@@ -385,6 +412,21 @@ function stageMacWechatImageForMessageSourceSend(
|
||||
return stagedPath
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟回收暂存图:微信在 `/sendMsg` 返回后才异步读取该文件,
|
||||
* 立即删除会让消息静默丢失;与视频/文件暂存保持同样的「延迟清理」策略。
|
||||
*/
|
||||
function scheduleStagedImageCleanup(stagedPath: string): void {
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
unlinkSync(stagedPath)
|
||||
} catch {
|
||||
// Best-effort delayed cleanup after WeChat finishes asynchronous image upload.
|
||||
}
|
||||
}, 120_000)
|
||||
timer.unref?.()
|
||||
}
|
||||
|
||||
const MAC_VIDEO_STAGE_PREFIX = 'tm-video-'
|
||||
const MAC_VIDEO_STAGE_RETENTION_MS = 10 * 60 * 1000
|
||||
|
||||
@@ -783,24 +825,39 @@ export class PersonalWechatSendService {
|
||||
constructor(private readonly wechatFilesRoot = WECHAT_FILES_ROOT) {}
|
||||
|
||||
async getStatus(): Promise<PersonalWechatSenderStatus> {
|
||||
// macOS 发送能力完全由 native runtime(tm-wechat-host)提供,
|
||||
// 这里保持同源,避免出现第二套状态判断。
|
||||
if (process.platform === 'darwin') return macWechatRuntimeManager.buildSenderStatus()
|
||||
if (process.platform === 'darwin') {
|
||||
const configuredPort = normalizeWindowsWechatPort(loadSettings().windowsWechatPort)
|
||||
if (!configuredPort) {
|
||||
const base = windowsStatusBase('')
|
||||
return {
|
||||
...base,
|
||||
platform: 'darwin',
|
||||
arch: process.arch,
|
||||
state: 'error',
|
||||
message: '尚未配置微信发送能力端口',
|
||||
error: '请先输入端口并检测后保存'
|
||||
}
|
||||
}
|
||||
return this.getMacPortStatus(configuredPort)
|
||||
}
|
||||
return this.getWindowsStatus()
|
||||
}
|
||||
|
||||
async checkWindowsStatus(port?: string): Promise<PersonalWechatSenderStatus> {
|
||||
if (process.platform !== 'win32') return this.getStatus()
|
||||
if (process.platform !== 'win32' && process.platform !== 'darwin') return this.getStatus()
|
||||
const normalizedPort = normalizeWindowsWechatPort(port)
|
||||
if (!normalizedPort) {
|
||||
const base = windowsStatusBase()
|
||||
return {
|
||||
...base,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
state: 'error',
|
||||
message: '请输入 1 到 65535 之间的微信发送能力端口',
|
||||
error: '端口格式无效或为空'
|
||||
}
|
||||
}
|
||||
if (process.platform === 'darwin') return this.getMacPortStatus(normalizedPort)
|
||||
return this.getWindowsStatus(normalizedPort)
|
||||
}
|
||||
|
||||
@@ -809,6 +866,14 @@ export class PersonalWechatSendService {
|
||||
}
|
||||
|
||||
async send(request: PersonalWechatSendRequest): Promise<PersonalWechatSendResult> {
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('个人微信发送')
|
||||
return {
|
||||
success: false,
|
||||
status: await this.getStatus(),
|
||||
error: '只读测试模式:不发送任何微信消息'
|
||||
}
|
||||
}
|
||||
if (process.platform === 'win32') return this.sendWindows(request)
|
||||
if (process.platform === 'darwin') {
|
||||
if (request.type === 'text') return this.sendMacText(request)
|
||||
@@ -825,7 +890,111 @@ export class PersonalWechatSendService {
|
||||
}
|
||||
|
||||
async rebind(): Promise<PersonalWechatSenderStatus> {
|
||||
return this.getWindowsStatus()
|
||||
return this.getStatus()
|
||||
}
|
||||
|
||||
private resolveMacHostPort(): number {
|
||||
const configured = normalizeWindowsWechatPort(loadSettings().windowsWechatPort)
|
||||
if (configured) return Number(configured)
|
||||
return macWechatRuntimeManager.getPort()
|
||||
}
|
||||
|
||||
private async ensureMacSenderReady(): Promise<PersonalWechatSenderStatus> {
|
||||
const configured = normalizeWindowsWechatPort(loadSettings().windowsWechatPort)
|
||||
if (configured) {
|
||||
return this.getMacPortStatus(configured)
|
||||
}
|
||||
await macWechatRuntimeManager.ensureStarted()
|
||||
return macWechatRuntimeManager.buildSenderStatus()
|
||||
}
|
||||
|
||||
private async resolveMacCurrentStatus(): Promise<PersonalWechatSenderStatus> {
|
||||
const configured = normalizeWindowsWechatPort(loadSettings().windowsWechatPort)
|
||||
if (configured) {
|
||||
return this.getMacPortStatus(configured)
|
||||
}
|
||||
return macWechatRuntimeManager.buildSenderStatus()
|
||||
}
|
||||
|
||||
private async resolveMacSendMechanism(versionHint?: string): Promise<string | undefined> {
|
||||
const configured = normalizeWindowsWechatPort(loadSettings().windowsWechatPort)
|
||||
if (!configured) {
|
||||
return macWechatRuntimeManager.getSendMechanism()
|
||||
}
|
||||
const ver = String(versionHint || '').trim()
|
||||
if (ver.startsWith('4.1.11.')) return 'legacy-req2buf'
|
||||
if (ver.startsWith('4.1.13.')) return 'native-msg-object'
|
||||
return 'tm-message-source-send'
|
||||
}
|
||||
|
||||
private async getMacPortStatus(port?: string): Promise<PersonalWechatSenderStatus> {
|
||||
const host = windowsHookHost(port)
|
||||
const base: PersonalWechatSenderStatus = {
|
||||
...windowsStatusBase(host || ''),
|
||||
platform: 'darwin',
|
||||
arch: process.arch
|
||||
}
|
||||
if (!host) {
|
||||
return {
|
||||
...base,
|
||||
state: 'error',
|
||||
message: '尚未配置微信发送能力端口',
|
||||
error: '请先输入端口并检测后保存'
|
||||
}
|
||||
}
|
||||
try {
|
||||
const result = await requestWindowsHook('/getLoginInfo', {}, 15_000, 'GET', host)
|
||||
const loggedIn = parseWindowsLoginStatus(result)
|
||||
const pid = typeof result.pid === 'number' && result.pid > 0 ? result.pid : 1
|
||||
const wechatVersion = typeof result.version === 'string' ? result.version : '4.1.15.55'
|
||||
const connected = {
|
||||
wechatRunning: true,
|
||||
wechatPid: pid,
|
||||
boundWechatPid: pid,
|
||||
wechatVersion,
|
||||
runtimeReady: true,
|
||||
endpointReady: true,
|
||||
attachReady: true,
|
||||
baseAddressReady: true,
|
||||
textHookInstalled: true,
|
||||
textHookReady: loggedIn,
|
||||
imageHookInstalled: loggedIn,
|
||||
imageHookReady: loggedIn,
|
||||
messageListenerReady: loggedIn
|
||||
}
|
||||
if (!loggedIn) {
|
||||
const msg =
|
||||
typeof result.message === 'string' && result.message.trim()
|
||||
? result.message.trim()
|
||||
: '微信发送能力已连接,但微信尚未登录或尚未完成绑定'
|
||||
return {
|
||||
...base,
|
||||
...connected,
|
||||
state: 'hook_not_ready',
|
||||
message: msg,
|
||||
error: typeof result.error === 'string' && result.error.trim() ? result.error.trim() : msg
|
||||
}
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
...connected,
|
||||
state: 'online' as const,
|
||||
canSend: true,
|
||||
canSendText: true,
|
||||
canSendImage: true,
|
||||
canSendVoice: true,
|
||||
canSendVideo: true,
|
||||
canSendFile: true,
|
||||
message: '微信发送能力已连接,可以发送消息'
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
...base,
|
||||
state: 'wechat_not_running',
|
||||
message: '未检测到微信发送能力,请先通过授权管理器注入并启动微信',
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async getWindowsStatus(port?: string): Promise<PersonalWechatSenderStatus> {
|
||||
@@ -890,8 +1059,7 @@ export class PersonalWechatSendService {
|
||||
private async sendMacText(
|
||||
request: Extract<PersonalWechatSendRequest, { type: 'text' }>
|
||||
): Promise<PersonalWechatSendResult> {
|
||||
await macWechatRuntimeManager.ensureStarted()
|
||||
const initialStatus = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const initialStatus = await this.ensureMacSenderReady()
|
||||
if (!initialStatus.canSendText) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -899,7 +1067,7 @@ export class PersonalWechatSendService {
|
||||
error: initialStatus.message || '微信发送能力未就绪'
|
||||
}
|
||||
}
|
||||
const sendMechanism = await macWechatRuntimeManager.getSendMechanism()
|
||||
const sendMechanism = await this.resolveMacSendMechanism(initialStatus.wechatVersion)
|
||||
if (request.at && sendMechanism !== 'tm-message-source-send') {
|
||||
return {
|
||||
success: false,
|
||||
@@ -919,7 +1087,7 @@ export class PersonalWechatSendService {
|
||||
},
|
||||
50_000
|
||||
)
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.resolveMacCurrentStatus()
|
||||
if (!result?.ok) {
|
||||
return { success: false, status, error: result?.message || '文字发送失败' }
|
||||
}
|
||||
@@ -931,7 +1099,7 @@ export class PersonalWechatSendService {
|
||||
text: request.text,
|
||||
isGroup: Boolean(request.isGroup)
|
||||
})
|
||||
const response = await fetch(`http://127.0.0.1:${macWechatRuntimeManager.getPort()}/sendText`, {
|
||||
const response = await fetch(`http://127.0.0.1:${this.resolveMacHostPort()}/sendText`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: payload,
|
||||
@@ -939,7 +1107,7 @@ export class PersonalWechatSendService {
|
||||
}).catch(() => null)
|
||||
|
||||
if (response === null || !response.ok) {
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.resolveMacCurrentStatus()
|
||||
return {
|
||||
success: false,
|
||||
status,
|
||||
@@ -948,7 +1116,7 @@ export class PersonalWechatSendService {
|
||||
}
|
||||
|
||||
const result = (await response.json()) as { code: number; ok: boolean; message: string }
|
||||
const resultStatus = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const resultStatus = await this.resolveMacCurrentStatus()
|
||||
if (!result.ok) {
|
||||
return { success: false, status: resultStatus, error: result.message || '发送失败' }
|
||||
}
|
||||
@@ -966,7 +1134,7 @@ export class PersonalWechatSendService {
|
||||
body: Record<string, unknown>,
|
||||
timeoutMs: number
|
||||
): Promise<{ code: number; ok: boolean; message: string } | null> {
|
||||
const response = await fetch(`http://127.0.0.1:${macWechatRuntimeManager.getPort()}${path}`, {
|
||||
const response = await fetch(`http://127.0.0.1:${this.resolveMacHostPort()}${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
@@ -991,8 +1159,7 @@ export class PersonalWechatSendService {
|
||||
private async sendMacVideo(
|
||||
request: Extract<PersonalWechatSendRequest, { type: 'video' }>
|
||||
): Promise<PersonalWechatSendResult> {
|
||||
await macWechatRuntimeManager.ensureStarted()
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.ensureMacSenderReady()
|
||||
if (!status.canSendVideo) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -1013,7 +1180,7 @@ export class PersonalWechatSendService {
|
||||
try {
|
||||
staged = stageMacWechatVideoForSend(filePath, this.wechatFilesRoot)
|
||||
} catch (error) {
|
||||
const latest = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const latest = await this.resolveMacCurrentStatus()
|
||||
return {
|
||||
success: false,
|
||||
status: latest,
|
||||
@@ -1027,7 +1194,7 @@ export class PersonalWechatSendService {
|
||||
{ toWxid: request.to, type: 'video', msg: staged.stagedPath },
|
||||
180_000
|
||||
)
|
||||
const latest = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const latest = await this.resolveMacCurrentStatus()
|
||||
if (!result?.ok) {
|
||||
return { success: false, status: latest, error: result?.message || '视频发送失败' }
|
||||
}
|
||||
@@ -1040,8 +1207,7 @@ export class PersonalWechatSendService {
|
||||
private async sendMacFile(
|
||||
request: Extract<PersonalWechatSendRequest, { type: 'file' }>
|
||||
): Promise<PersonalWechatSendResult> {
|
||||
await macWechatRuntimeManager.ensureStarted()
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.ensureMacSenderReady()
|
||||
if (!status.canSendFile) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -1063,7 +1229,7 @@ export class PersonalWechatSendService {
|
||||
try {
|
||||
staged = stageMacWechatFileForSend(filePath, this.wechatFilesRoot)
|
||||
} catch (error) {
|
||||
const latest = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const latest = await this.resolveMacCurrentStatus()
|
||||
return {
|
||||
success: false,
|
||||
status: latest,
|
||||
@@ -1077,7 +1243,7 @@ export class PersonalWechatSendService {
|
||||
{ to: request.to, type: 'file', path: staged.stagedPath, name: fileName },
|
||||
180_000
|
||||
)
|
||||
const latest = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const latest = await this.resolveMacCurrentStatus()
|
||||
if (!result?.ok) {
|
||||
return { success: false, status: latest, error: result?.message || '文件发送失败' }
|
||||
}
|
||||
@@ -1090,10 +1256,9 @@ export class PersonalWechatSendService {
|
||||
private async sendMacImage(
|
||||
request: Extract<PersonalWechatSendRequest, { type: 'image' }>
|
||||
): Promise<PersonalWechatSendResult> {
|
||||
await macWechatRuntimeManager.ensureStarted()
|
||||
const initialStatus = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const initialStatus = await this.ensureMacSenderReady()
|
||||
const fail = async (error: string): Promise<PersonalWechatSendResult> => {
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.resolveMacCurrentStatus()
|
||||
return { success: false, status, error }
|
||||
}
|
||||
if (!initialStatus.canSendImage) {
|
||||
@@ -1101,7 +1266,7 @@ export class PersonalWechatSendService {
|
||||
}
|
||||
const filePath = String(request.filePath || '').trim()
|
||||
if (!filePath || !existsSync(filePath)) return fail('请选择有效的图片文件')
|
||||
const sendMechanism = await macWechatRuntimeManager.getSendMechanism()
|
||||
const sendMechanism = await this.resolveMacSendMechanism(initialStatus.wechatVersion)
|
||||
const sender = await this.resolveMacSenderWxid()
|
||||
if (!sender) return fail('无法识别当前微信账号 wxid')
|
||||
if (sendMechanism === 'tm-message-source-send') {
|
||||
@@ -1114,22 +1279,20 @@ export class PersonalWechatSendService {
|
||||
{ type: 'image', to: request.to, path: stagedPath },
|
||||
55_000
|
||||
)
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.resolveMacCurrentStatus()
|
||||
if (!sent?.ok) {
|
||||
sourceError = sent?.message || '图片发送失败'
|
||||
} else {
|
||||
/*
|
||||
* 不能在这里 unlink:微信在 /sendMsg 返回后仍会异步读取该文件,
|
||||
* 删早了消息会静默丢失,而 API 已经返回 success。
|
||||
* 改为延迟回收(2 分钟)+ 下次发送时清扫过期文件。
|
||||
*/
|
||||
if (stagedPath) scheduleStagedImageCleanup(stagedPath)
|
||||
return { success: true, status }
|
||||
}
|
||||
} catch (error) {
|
||||
sourceError = error instanceof Error ? error.message : String(error)
|
||||
} finally {
|
||||
if (stagedPath) {
|
||||
try {
|
||||
unlinkSync(stagedPath)
|
||||
} catch {
|
||||
// Best-effort cleanup after WeChat has consumed the staged image.
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isDefinitiveImageSourcePreparationFailure(sourceError)) return fail(sourceError)
|
||||
}
|
||||
@@ -1150,7 +1313,7 @@ export class PersonalWechatSendService {
|
||||
if (!sent || !sent.ok) {
|
||||
return fail(sent?.message || '图片发送失败')
|
||||
}
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.resolveMacCurrentStatus()
|
||||
return { success: true, status }
|
||||
} catch (error) {
|
||||
return fail(error instanceof Error ? error.message : String(error))
|
||||
@@ -1169,14 +1332,13 @@ export class PersonalWechatSendService {
|
||||
request: Extract<PersonalWechatSendRequest, { type: 'voice' }>
|
||||
): Promise<PersonalWechatSendResult> {
|
||||
const requestId = randomUUID()
|
||||
await macWechatRuntimeManager.ensureStarted()
|
||||
const initialStatus = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const initialStatus = await this.ensureMacSenderReady()
|
||||
const fail = async (
|
||||
error: string,
|
||||
failurePhase = 'preflight'
|
||||
): Promise<PersonalWechatSendResult> => {
|
||||
logVoiceAttempt(requestId, 'failed', { failure_phase: failurePhase, error })
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.resolveMacCurrentStatus()
|
||||
return { success: false, status, error }
|
||||
}
|
||||
if (!initialStatus.canSendVoice) {
|
||||
@@ -1184,7 +1346,7 @@ export class PersonalWechatSendService {
|
||||
}
|
||||
const filePath = String(request.filePath || '').trim()
|
||||
if (!filePath || !existsSync(filePath)) return fail('请选择有效的语音文件')
|
||||
const sendMechanism = await macWechatRuntimeManager.getSendMechanism()
|
||||
const sendMechanism = await this.resolveMacSendMechanism(initialStatus.wechatVersion)
|
||||
let sender = ''
|
||||
if (sendMechanism !== 'tm-message-source-send') {
|
||||
sender = await this.resolveMacSenderWxid()
|
||||
@@ -1226,7 +1388,7 @@ export class PersonalWechatSendService {
|
||||
if (!sent?.ok) {
|
||||
return fail(sent?.message || '语音发送失败', 'send')
|
||||
}
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.resolveMacCurrentStatus()
|
||||
logVoiceAttempt(requestId, 'completed', { send_result: '0' })
|
||||
return { success: true, status }
|
||||
}
|
||||
@@ -1248,7 +1410,7 @@ export class PersonalWechatSendService {
|
||||
if (!sent || !sent.ok) {
|
||||
return fail(sent?.message || '语音发送失败', 'send')
|
||||
}
|
||||
const status = await macWechatRuntimeManager.buildSenderStatus()
|
||||
const status = await this.resolveMacCurrentStatus()
|
||||
logVoiceAttempt(requestId, 'completed', { send_result: '0' })
|
||||
return { success: true, status }
|
||||
} finally {
|
||||
|
||||
@@ -76,6 +76,7 @@ export interface QueryAgentProvider {
|
||||
success: boolean
|
||||
data?: string
|
||||
toolCalls?: AIChatToolCall[]
|
||||
replayItems?: Record<string, unknown>[]
|
||||
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
|
||||
error?: string
|
||||
/** 以下为诊断字段(additive,不参与业务语义) */
|
||||
@@ -1090,6 +1091,10 @@ function conversationScopeNote(input: QueryAgentConversationScope): string {
|
||||
rules.push(
|
||||
'范围是群聊专属:包含全部群会话以及群成员实际发送的消息。问"谁聊过某话题"时应省略 search_messages 的 target 做跨群检索,并在回答里保留群名与发送者。'
|
||||
)
|
||||
} else if (scope.kind === 'selected') {
|
||||
rules.push(
|
||||
'范围是用户手选的若干会话:可以在它们之间跨会话检索,但每个 target 都必须属于这个集合;用户只选了这些,不要暗示还有其他会话可选。'
|
||||
)
|
||||
} else if (scope.kind === 'contact' || scope.kind === 'current') {
|
||||
rules.push(
|
||||
'范围只有一个会话:所有工具都可以省略 target(query_messages 也可以),省略即在该会话内检索;不要猜会话名,也不要指定其他会话。'
|
||||
@@ -1395,15 +1400,19 @@ export class QueryAgentService {
|
||||
totalMs: Date.now() - startedAt
|
||||
}
|
||||
}
|
||||
messages.push({
|
||||
role: 'assistant',
|
||||
content: model.data || '',
|
||||
tool_calls: calls.map((call) => ({
|
||||
id: call.id,
|
||||
type: 'function',
|
||||
function: { name: call.name, arguments: call.arguments }
|
||||
}))
|
||||
})
|
||||
if (model.replayItems) {
|
||||
messages.push(...model.replayItems)
|
||||
} else {
|
||||
messages.push({
|
||||
role: 'assistant',
|
||||
content: model.data || '',
|
||||
tool_calls: calls.map((call) => ({
|
||||
id: call.id,
|
||||
type: 'function',
|
||||
function: { name: call.name, arguments: call.arguments }
|
||||
}))
|
||||
})
|
||||
}
|
||||
for (const call of calls) {
|
||||
const inputStartedAt = Date.now()
|
||||
let toolResult: QueryAgentToolResult | undefined
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 只读验收模式。
|
||||
*
|
||||
* 用于「接真实微信库、但不允许任何写副作用」的验收场景。启用后:
|
||||
* - 不执行 MsgInsert reconciliation / 规则写入;
|
||||
* - 不发送任何微信消息(网关直接 blocked);
|
||||
* - 不执行自动化与定时日报的发送步骤;
|
||||
* - 不写退群本地提示。
|
||||
*
|
||||
* 读取、SSE 订阅、数据库回补不受影响。
|
||||
*
|
||||
* 生产模式默认关闭:只有显式设置 `TRACEMEMO_READ_ONLY=1` 才生效。
|
||||
*/
|
||||
export const READ_ONLY_ENV = 'TRACEMEMO_READ_ONLY'
|
||||
|
||||
const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on'])
|
||||
|
||||
export function isReadOnlyMode(): boolean {
|
||||
const value = process.env[READ_ONLY_ENV]
|
||||
return typeof value === 'string' && TRUE_VALUES.has(value.trim().toLowerCase())
|
||||
}
|
||||
|
||||
/** 统一日志:只记录被跳过的操作名,不记录会话 / 消息内容。 */
|
||||
export function logReadOnlySkip(operation: string): void {
|
||||
console.log(`[ReadOnly] 已跳过 ${operation}`)
|
||||
}
|
||||
@@ -3,6 +3,10 @@ import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import type { TextToSpeechModel } from '../../shared/text-to-speech'
|
||||
import {
|
||||
normalizeKnowledgeIndexScopes,
|
||||
type KnowledgeIndexScope
|
||||
} from '../../shared/knowledge'
|
||||
|
||||
/**
|
||||
* 把 V3 时代的 "...\\Documents\\WeChat Files" 路径重定向到
|
||||
@@ -67,6 +71,8 @@ export interface AppSettings {
|
||||
* 始终展示最新版本 —— 忽略的是提示,不是版本本身。空串表示没有忽略任何版本。
|
||||
*/
|
||||
skippedUpdateVersion: string
|
||||
/** 按账号存;缺省 = 全部会话。不同账号的选择绝不能串用。 */
|
||||
knowledgeIndexScopes: Record<string, KnowledgeIndexScope>
|
||||
}
|
||||
|
||||
/** 只接受 `1.2.3` / `1.2.3-beta.1` 这类版本号;其它输入一律按"没有忽略"处理。 */
|
||||
@@ -161,7 +167,8 @@ const DEFAULT_SETTINGS: AppSettings = {
|
||||
reportImagePostfixText: '今日日报',
|
||||
queryAgentEnabled: true,
|
||||
closeAction: 'ask',
|
||||
skippedUpdateVersion: ''
|
||||
skippedUpdateVersion: '',
|
||||
knowledgeIndexScopes: {}
|
||||
}
|
||||
|
||||
const SETTINGS_FILE = path.join(
|
||||
@@ -217,6 +224,9 @@ export function loadSettings(): AppSettings {
|
||||
}
|
||||
// 版本号是拿来逐字比对的:脏值会让「忽略」永远命中不了同一条记录。
|
||||
cache.skippedUpdateVersion = normalizeSkippedUpdateVersion(cache.skippedUpdateVersion)
|
||||
// 索引范围来自磁盘,可能是旧版本/手改过的脏值:收敛成合法形状,
|
||||
// 尤其不能把 `selected + 空数组` 悄悄升级成"全部"。
|
||||
cache.knowledgeIndexScopes = normalizeKnowledgeIndexScopes(cache.knowledgeIndexScopes)
|
||||
// 防撤回已下线(设置入口已隐藏):历史版本可能把它持久化为 true。
|
||||
// 这里强制收敛为 false 并回写磁盘,确保旧的撤回监听与撤回日志不会继续运行。
|
||||
if (cache.recallProtectionEnabled || retiredKeepProcess !== undefined) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { app } from 'electron'
|
||||
import { createHash, randomUUID } from 'crypto'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import { isReadOnlyMode } from './read-only-mode'
|
||||
import type {
|
||||
PersonalWechatSendCapability,
|
||||
PersonalWechatSendRequest,
|
||||
@@ -186,6 +187,22 @@ export class WechatActionGateway {
|
||||
}
|
||||
|
||||
async execute(request: WechatActionRequest): Promise<WechatActionResult> {
|
||||
/*
|
||||
* 只读闸门必须在幂等查表**之前**:否则同一个 idempotencyKey 命中历史
|
||||
* 已发送记录时,会直接返回旧的 sent 结果,看似没发、实际绕过了闸门。
|
||||
*/
|
||||
if (isReadOnlyMode()) {
|
||||
const startedAt = this.deps.now().toISOString()
|
||||
return {
|
||||
actionId: String(request?.id || '').trim() || randomUUID(),
|
||||
status: 'blocked',
|
||||
decision: 'block',
|
||||
errorCode: 'READ_ONLY_MODE',
|
||||
reason: '只读测试模式:不发送任何微信消息',
|
||||
startedAt,
|
||||
finishedAt: startedAt
|
||||
}
|
||||
}
|
||||
const normalized = normalizeActionRequest(request)
|
||||
const idempotencyKey = normalized ? this.idempotencyKey(normalized) : undefined
|
||||
if (idempotencyKey) {
|
||||
|
||||
@@ -35,6 +35,7 @@ import { renderLeaveNotificationText } from '../../shared/group-exit-event'
|
||||
import { GROUP_EXIT_NOTIFICATION_TEMPLATE } from '../../shared/group-exit-monitor'
|
||||
import { resolveWcdbConfigHelper } from '../native-runtime-paths'
|
||||
import { msgInsertCapabilityService } from './msg-insert-capability-service'
|
||||
import { isReadOnlyMode, logReadOnlySkip } from './read-only-mode'
|
||||
import { resolveHelperPath } from './msg-insert-switch-service'
|
||||
|
||||
export type LocalExitNoticeOutcome =
|
||||
@@ -140,6 +141,10 @@ export class WechatLocalExitNoticeService {
|
||||
eventId: event.eventId,
|
||||
conversationId: event.conversationId
|
||||
}
|
||||
if (isReadOnlyMode()) {
|
||||
logReadOnlySkip('退群本地提示写入')
|
||||
return { ...base, outcome: 'disabled', code: 'READ_ONLY_MODE' }
|
||||
}
|
||||
try {
|
||||
this.ensureLoaded()
|
||||
if (!this.enabled) return this.finish({ ...base, outcome: 'disabled', code: 'DISABLED' })
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
import type { AgentTaskReply, AgentTaskReplyRole } from '../../shared/agent-task'
|
||||
import {
|
||||
AgentTaskProvider,
|
||||
AgentTaskProviderError,
|
||||
type AgentTaskProviderRequestOptions
|
||||
} from './agent-task-provider'
|
||||
import type { WorkBuddyCredentials } from './agent-task-config'
|
||||
|
||||
/**
|
||||
* WorkBuddy Local Assistant 适配器。
|
||||
*
|
||||
* 契约来源(未在本仓库实测的部分会在下方逐条标注):
|
||||
* - `GET /openapi/v2/localassistant` → `data.online`
|
||||
* - `POST /openapi/v2/localassistant/message` → `data.message_id`
|
||||
* - `GET /openapi/v2/localassistant/message?message_id=...` → 增量回复
|
||||
* - `POST /openapi/v2/token` → refresh
|
||||
*
|
||||
* **未实测**:
|
||||
* 1. assistant 回复是否一定出现在 `message_id` 之后、是否保证只出现一次;
|
||||
* 2. 真实账号下 refresh_token 是否轮换;
|
||||
* 3. `content[]` 里除 `text` 之外的实际片段类型。
|
||||
* 因此第一版把「看到任意一条 assistant 回复」当作任务完成,而不是猜更细的状态机。
|
||||
*
|
||||
* **安全边界**:
|
||||
* - 凭证只从构造参数来(由 `loadWorkBuddyCredentials()` 读环境变量),本文件零硬编码;
|
||||
* - 错误信息里只放 HTTP 状态与业务 `code`,不回显请求头或 token。
|
||||
*/
|
||||
|
||||
const LOCAL_ASSISTANT_PATH = '/openapi/v2/localassistant'
|
||||
const LOCAL_ASSISTANT_MESSAGE_PATH = '/openapi/v2/localassistant/message'
|
||||
const TOKEN_PATH = '/openapi/v2/token'
|
||||
/** 提前 60 秒刷新,避免边界上刚好过期。 */
|
||||
const TOKEN_EXPIRY_SKEW_MS = 60_000
|
||||
|
||||
interface WorkBuddyEnvelope<T> {
|
||||
code?: number
|
||||
msg?: string
|
||||
request_id?: string
|
||||
data?: T
|
||||
}
|
||||
|
||||
export interface WorkBuddyProviderOptions {
|
||||
baseUrl: string
|
||||
timeoutMs: number
|
||||
credentials: WorkBuddyCredentials
|
||||
fetchImpl?: typeof fetch
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export class WorkBuddyAccessTokenSource {
|
||||
private cached: { token: string; expiresAt: number } | null = null
|
||||
private readonly fetchImpl: typeof fetch
|
||||
private readonly now: () => number
|
||||
|
||||
constructor(private readonly options: WorkBuddyProviderOptions) {
|
||||
this.fetchImpl = options.fetchImpl ?? fetch
|
||||
this.now = options.now ?? Date.now
|
||||
}
|
||||
|
||||
/** 丢弃缓存。收到 401 时由 provider 调用,下一次会强制 refresh。 */
|
||||
invalidate(): void {
|
||||
this.cached = null
|
||||
}
|
||||
|
||||
async getAccessToken(forceRefresh = false): Promise<string> {
|
||||
const credentials = this.options.credentials
|
||||
|
||||
if (!forceRefresh && this.cached && this.now() < this.cached.expiresAt) {
|
||||
return this.cached.token
|
||||
}
|
||||
|
||||
if (!forceRefresh && credentials.accessToken) {
|
||||
// 静态 token 没有过期信息:先用,遇到 401 再走 refresh。
|
||||
this.cached = { token: credentials.accessToken, expiresAt: Number.POSITIVE_INFINITY }
|
||||
return credentials.accessToken
|
||||
}
|
||||
|
||||
if (credentials.refreshToken && credentials.clientId && credentials.clientSecret) {
|
||||
const token = await this.refresh(credentials)
|
||||
this.cached = {
|
||||
token: token.accessToken,
|
||||
expiresAt: this.now() + Math.max(60, token.expiresIn) * 1000 - TOKEN_EXPIRY_SKEW_MS
|
||||
}
|
||||
return token.accessToken
|
||||
}
|
||||
|
||||
if (credentials.accessToken) {
|
||||
throw new AgentTaskProviderError(
|
||||
'auth_expired',
|
||||
'WorkBuddy access_token 已失效,且没有配置 refresh_token',
|
||||
false,
|
||||
401
|
||||
)
|
||||
}
|
||||
throw new AgentTaskProviderError('auth_missing', '未配置 WorkBuddy 访问凭证', false)
|
||||
}
|
||||
|
||||
private async refresh(
|
||||
credentials: WorkBuddyCredentials
|
||||
): Promise<{ accessToken: string; expiresIn: number }> {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: String(credentials.refreshToken),
|
||||
client_id: String(credentials.clientId),
|
||||
client_secret: String(credentials.clientSecret)
|
||||
})
|
||||
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), this.options.timeoutMs)
|
||||
let response: Response
|
||||
try {
|
||||
response = await this.fetchImpl(`${this.options.baseUrl}${TOKEN_PATH}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body,
|
||||
signal: controller.signal
|
||||
})
|
||||
} catch (error) {
|
||||
throw classifyTokenFailure(error)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
|
||||
const envelope = await readEnvelope(response)
|
||||
if (!response.ok || (typeof envelope.code === 'number' && envelope.code !== 0)) {
|
||||
throw new AgentTaskProviderError(
|
||||
'auth_expired',
|
||||
`WorkBuddy 凭证刷新失败(HTTP ${response.status}${envelope.msg ? `:${envelope.msg}` : ''})`,
|
||||
false,
|
||||
response.status
|
||||
)
|
||||
}
|
||||
|
||||
const data = envelope.data as { access_token?: unknown; expires_in?: unknown } | undefined
|
||||
if (!data || typeof data.access_token !== 'string' || !data.access_token) {
|
||||
throw new AgentTaskProviderError('invalid_response', 'WorkBuddy 刷新响应缺少 access_token')
|
||||
}
|
||||
return {
|
||||
accessToken: data.access_token,
|
||||
expiresIn: typeof data.expires_in === 'number' ? data.expires_in : 3600
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkBuddyAgentTaskProvider implements AgentTaskProvider {
|
||||
readonly id = 'workbuddy'
|
||||
private readonly tokenSource: WorkBuddyAccessTokenSource
|
||||
private readonly fetchImpl: typeof fetch
|
||||
|
||||
constructor(private readonly options: WorkBuddyProviderOptions) {
|
||||
this.tokenSource = new WorkBuddyAccessTokenSource(options)
|
||||
this.fetchImpl = options.fetchImpl ?? fetch
|
||||
}
|
||||
|
||||
async checkOnline(options: AgentTaskProviderRequestOptions = {}): Promise<boolean> {
|
||||
const data = await this.request<{ online?: unknown }>(
|
||||
'GET',
|
||||
LOCAL_ASSISTANT_PATH,
|
||||
undefined,
|
||||
options
|
||||
)
|
||||
return data?.online === true
|
||||
}
|
||||
|
||||
async submitTask(
|
||||
input: { content: string },
|
||||
options: AgentTaskProviderRequestOptions = {}
|
||||
): Promise<{ messageId: string }> {
|
||||
const data = await this.request<{ message_id?: unknown }>(
|
||||
'POST',
|
||||
`${LOCAL_ASSISTANT_PATH}/message`,
|
||||
{ content: input.content, msg_type: 'text' },
|
||||
options
|
||||
)
|
||||
if (!data || typeof data.message_id !== 'string' || !data.message_id) {
|
||||
throw new AgentTaskProviderError('invalid_response', 'WorkBuddy 投递响应缺少 message_id')
|
||||
}
|
||||
return { messageId: data.message_id }
|
||||
}
|
||||
|
||||
async fetchReplies(
|
||||
afterMessageId: string,
|
||||
options: AgentTaskProviderRequestOptions & { limit?: number } = {}
|
||||
): Promise<AgentTaskReply[]> {
|
||||
const query = new URLSearchParams({
|
||||
message_id: afterMessageId,
|
||||
limit: String(Math.max(1, Math.min(options.limit ?? 20, 100)))
|
||||
})
|
||||
const data = await this.request<unknown>(
|
||||
'GET',
|
||||
`${LOCAL_ASSISTANT_MESSAGE_PATH}?${query.toString()}`,
|
||||
undefined,
|
||||
options
|
||||
)
|
||||
return parseReplies(data)
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
method: 'GET' | 'POST',
|
||||
path: string,
|
||||
body: unknown | undefined,
|
||||
options: AgentTaskProviderRequestOptions,
|
||||
retried = false
|
||||
): Promise<T> {
|
||||
const token = await this.tokenSource.getAccessToken(retried)
|
||||
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), this.options.timeoutMs)
|
||||
const signal = options.signal
|
||||
? AbortSignal.any([controller.signal, options.signal])
|
||||
: controller.signal
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
response = await this.fetchImpl(`${this.options.baseUrl}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(body !== undefined ? { 'Content-Type': 'application/json' } : {})
|
||||
},
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
signal
|
||||
})
|
||||
} catch (error) {
|
||||
throw classifyRequestFailure(error, options.signal)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
|
||||
if (response.status === 401) {
|
||||
if (!retried) {
|
||||
this.tokenSource.invalidate()
|
||||
return this.request<T>(method, path, body, options, true)
|
||||
}
|
||||
throw new AgentTaskProviderError('auth_expired', 'WorkBuddy 鉴权失败(HTTP 401)', false, 401)
|
||||
}
|
||||
if (response.status === 403) {
|
||||
throw new AgentTaskProviderError(
|
||||
'auth_expired',
|
||||
'WorkBuddy 授权不足(HTTP 403,检查 scope)',
|
||||
false,
|
||||
403
|
||||
)
|
||||
}
|
||||
|
||||
const envelope = await readEnvelope(response)
|
||||
if (!response.ok) {
|
||||
const retryable = response.status === 429 || response.status >= 500
|
||||
throw new AgentTaskProviderError(
|
||||
'http_error',
|
||||
`WorkBuddy 请求失败(HTTP ${response.status}${envelope.msg ? `:${envelope.msg}` : ''})`,
|
||||
retryable,
|
||||
response.status
|
||||
)
|
||||
}
|
||||
if (typeof envelope.code === 'number' && envelope.code !== 0) {
|
||||
throw new AgentTaskProviderError(
|
||||
'http_error',
|
||||
`WorkBuddy 业务错误(code=${envelope.code}${envelope.msg ? `:${envelope.msg}` : ''})`
|
||||
)
|
||||
}
|
||||
return envelope.data as T
|
||||
}
|
||||
}
|
||||
|
||||
async function readEnvelope(response: Response): Promise<WorkBuddyEnvelope<unknown>> {
|
||||
let text = ''
|
||||
try {
|
||||
text = await response.text()
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
if (!text) return {}
|
||||
try {
|
||||
const parsed = JSON.parse(text) as unknown
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as WorkBuddyEnvelope<unknown>
|
||||
}
|
||||
} catch {
|
||||
// 非 JSON 响应:保留 HTTP 状态,交给调用方按 invalid_response 处理。
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
function classifyTokenFailure(error: unknown): AgentTaskProviderError {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return new AgentTaskProviderError('timeout', 'WorkBuddy 凭证刷新超时', true)
|
||||
}
|
||||
return new AgentTaskProviderError(
|
||||
'http_error',
|
||||
`WorkBuddy 凭证刷新请求失败:${error instanceof Error ? error.message : String(error)}`,
|
||||
true
|
||||
)
|
||||
}
|
||||
|
||||
function classifyRequestFailure(
|
||||
error: unknown,
|
||||
externalSignal?: AbortSignal
|
||||
): AgentTaskProviderError {
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
if (externalSignal?.aborted) {
|
||||
return new AgentTaskProviderError('internal', 'WorkBuddy 请求已取消')
|
||||
}
|
||||
return new AgentTaskProviderError('timeout', 'WorkBuddy 请求超时', true)
|
||||
}
|
||||
return new AgentTaskProviderError(
|
||||
'http_error',
|
||||
`WorkBuddy 请求失败:${error instanceof Error ? error.message : String(error)}`,
|
||||
true
|
||||
)
|
||||
}
|
||||
|
||||
function roleOf(value: unknown): AgentTaskReplyRole {
|
||||
if (value === 'assistant') return 'assistant'
|
||||
if (value === 'user') return 'user'
|
||||
return 'other'
|
||||
}
|
||||
|
||||
function extractText(content: unknown): string {
|
||||
if (typeof content === 'string') return content
|
||||
if (!Array.isArray(content)) return ''
|
||||
const parts: string[] = []
|
||||
for (const part of content) {
|
||||
if (typeof part === 'string') {
|
||||
parts.push(part)
|
||||
continue
|
||||
}
|
||||
if (part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string') {
|
||||
parts.push((part as { text: string }).text)
|
||||
}
|
||||
}
|
||||
return parts.join('\n').trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 `messages[]`。
|
||||
*
|
||||
* 兼容 `data.messages` 与 `data` 直接是数组两种形态(契约文档只写了前者,
|
||||
* 但历史接口在分页/增量下出现过裸数组,这里不做假设性拒绝)。
|
||||
*/
|
||||
export function parseReplies(data: unknown): AgentTaskReply[] {
|
||||
const list = Array.isArray(data)
|
||||
? data
|
||||
: data && typeof data === 'object' && Array.isArray((data as { messages?: unknown }).messages)
|
||||
? (data as { messages: unknown[] }).messages
|
||||
: []
|
||||
|
||||
const replies: AgentTaskReply[] = []
|
||||
for (const item of list) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
const record = item as Record<string, unknown>
|
||||
const messageId =
|
||||
typeof record.message_id === 'string'
|
||||
? record.message_id
|
||||
: typeof record.messageId === 'string'
|
||||
? record.messageId
|
||||
: ''
|
||||
if (!messageId) continue
|
||||
replies.push({
|
||||
messageId,
|
||||
role: roleOf(record.role),
|
||||
text: extractText(record.content),
|
||||
...(typeof record.created_at === 'string' ? { createdAt: record.created_at } : {})
|
||||
})
|
||||
}
|
||||
return replies
|
||||
}
|
||||
@@ -34,6 +34,7 @@ export class VideoAssetService {
|
||||
private readonly fileHashes = new Map<string, Promise<string | undefined>>()
|
||||
private readonly videoDurations = new Map<string, number | undefined>()
|
||||
private readonly imageDimensions = new Map<string, ImageDimensions | undefined>()
|
||||
private readonly posterIndex = new Map<string, string>()
|
||||
private index: Map<string, VideoAsset> | null = null
|
||||
|
||||
constructor(private readonly client: Wcdb4Client) {}
|
||||
@@ -77,12 +78,15 @@ export class VideoAssetService {
|
||||
|
||||
const index = this.getIndex()
|
||||
for (const key of lookupKeys) {
|
||||
const asset = index.get(key) || index.get(`${key}_raw`)
|
||||
const rawAsset = index.get(`${key}_raw`)
|
||||
const compressedAsset = index.get(key)
|
||||
const asset = rawAsset || compressedAsset
|
||||
if (!asset) continue
|
||||
const posterPath = asset.posterPath || compressedAsset?.posterPath
|
||||
return {
|
||||
success: true,
|
||||
url: this.createLocalMediaUrl(asset.filePath),
|
||||
poster: asset.posterPath ? this.createLocalMediaUrl(asset.posterPath) : undefined
|
||||
poster: posterPath ? this.createLocalMediaUrl(posterPath) : undefined
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +98,56 @@ export class VideoAssetService {
|
||||
poster: fallback.posterPath ? this.createLocalMediaUrl(fallback.posterPath) : undefined
|
||||
}
|
||||
}
|
||||
return { success: false, error: '本地未找到该视频文件' }
|
||||
let posterOnlyPath: string | undefined
|
||||
for (const key of lookupKeys) {
|
||||
posterOnlyPath = this.posterIndex.get(`${key}_raw`) || this.posterIndex.get(key)
|
||||
if (posterOnlyPath) break
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
...(posterOnlyPath ? { poster: this.createLocalMediaUrl(posterOnlyPath) } : {}),
|
||||
error: '本地未找到该视频文件'
|
||||
}
|
||||
}
|
||||
|
||||
/** raw 版本写入 `_raw` 键;同时补齐空着的普通键,否则只有原视频的消息仍会被判为无视频。 */
|
||||
registerDownloadedVideo(
|
||||
hashes: string[],
|
||||
filePath: string,
|
||||
isRaw = false
|
||||
): { url: string; poster?: string } {
|
||||
const index = this.getIndex()
|
||||
const normalizedHashes = Array.from(
|
||||
new Set(
|
||||
hashes
|
||||
.map((value) =>
|
||||
String(value || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
)
|
||||
.filter((value) => /^[a-f0-9]{32}$/.test(value))
|
||||
)
|
||||
)
|
||||
let posterPath: string | undefined
|
||||
for (const hash of normalizedHashes) {
|
||||
posterPath =
|
||||
index.get(`${hash}_raw`)?.posterPath ||
|
||||
index.get(hash)?.posterPath ||
|
||||
this.posterIndex.get(`${hash}_raw`) ||
|
||||
this.posterIndex.get(hash)
|
||||
if (posterPath) break
|
||||
}
|
||||
const asset: VideoAsset = { filePath, ...(posterPath ? { posterPath } : {}) }
|
||||
for (const hash of normalizedHashes) {
|
||||
index.set(isRaw ? `${hash}_raw` : hash, asset)
|
||||
if (!index.has(hash)) {
|
||||
index.set(hash, asset)
|
||||
}
|
||||
}
|
||||
return {
|
||||
url: this.createLocalMediaUrl(filePath),
|
||||
...(posterPath ? { poster: this.createLocalMediaUrl(posterPath) } : {})
|
||||
}
|
||||
}
|
||||
|
||||
pathForToken(token: string): string | undefined {
|
||||
@@ -162,6 +215,9 @@ export class VideoAssetService {
|
||||
|
||||
const assets: VideoAsset[] = []
|
||||
for (const [key, asset] of monthly) {
|
||||
if (asset.posterPath) {
|
||||
this.posterIndex.set(key, asset.posterPath)
|
||||
}
|
||||
if (!asset.filePath) continue
|
||||
result.set(key, asset)
|
||||
assets.push(asset)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { fork, type ChildProcess } from 'child_process'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { tmpdir } from 'os'
|
||||
import { terminateChildProcess } from '../process-tree'
|
||||
import type {
|
||||
PipelineAudio,
|
||||
RecognitionMetadata,
|
||||
@@ -73,8 +75,16 @@ export class RecognitionHost {
|
||||
})
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
this.terminate(new Error('Voice recognition host disposed'))
|
||||
async dispose(exitTimeoutMs = 2_000): Promise<void> {
|
||||
if (this.idleTimer) {
|
||||
clearTimeout(this.idleTimer)
|
||||
this.idleTimer = null
|
||||
}
|
||||
const child = this.child
|
||||
this.child = null
|
||||
this.rejectAll(new Error('Voice recognition host disposed'))
|
||||
if (!child) return
|
||||
await terminateChildProcess(child, { timeoutMs: exitTimeoutMs })
|
||||
}
|
||||
|
||||
private ensureChild(): ChildProcess {
|
||||
@@ -84,6 +94,7 @@ export class RecognitionHost {
|
||||
}
|
||||
if (this.child?.connected) return this.child
|
||||
const child = fork(this.workerPath, [], {
|
||||
cwd: tmpdir(),
|
||||
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
||||
serialization: 'advanced',
|
||||
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
|
||||
|
||||
+1026
-53
File diff suppressed because it is too large.
Load diff
+18
-7
@@ -1,5 +1,6 @@
|
||||
import { Wcdb4Client, Wcdb4MessageQueryOptions } from './wcdb4-client'
|
||||
import { Wcdb4Client, Wcdb4GroupMember, Wcdb4MessageQueryOptions } from './wcdb4-client'
|
||||
import { wcdbDebugLog } from './wcdb-debug'
|
||||
import { isGroupSession } from '../shared/wechat-identities'
|
||||
|
||||
export interface UserContact {
|
||||
m_nsUsrName: string
|
||||
@@ -140,10 +141,20 @@ export class WechatDb {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一读取群成员:@chatroom 走 native getGroupMembers,@qy_g 走 bizchat 企业群成员。
|
||||
*/
|
||||
private readGroupMembers(roomId: string): Wcdb4GroupMember[] {
|
||||
// 这里是「尽力而为的名称映射」路径:企业群读取失败(null)退化为空集合,
|
||||
// 由调用方继续用 username 兜底;需要区分失败与空群的地方走 chat-service。
|
||||
if (roomId.endsWith('@qy_g')) return this.wcdb4Client.getEnterpriseGroupMembers(roomId) || []
|
||||
return this.wcdb4Client.getGroupMembers(roomId)
|
||||
}
|
||||
|
||||
public getAllGroupContacts(): Record<string, string> {
|
||||
const groupContacts: Record<string, string> = {}
|
||||
for (const session of this.wcdb4Client.getSessions()) {
|
||||
if (session.username.endsWith('@chatroom')) {
|
||||
if (isGroupSession(session.username)) {
|
||||
groupContacts[this.md5(session.username)] = session.nickname || session.username
|
||||
}
|
||||
}
|
||||
@@ -153,8 +164,8 @@ export class WechatDb {
|
||||
public getAllGroupMembers(): Record<string, string> {
|
||||
const members: Record<string, string> = {}
|
||||
for (const session of this.wcdb4Client.getSessions()) {
|
||||
if (!session.username.endsWith('@chatroom')) continue
|
||||
for (const member of this.wcdb4Client.getGroupMembers(session.username)) {
|
||||
if (!isGroupSession(session.username)) continue
|
||||
for (const member of this.readGroupMembers(session.username)) {
|
||||
if (member.m_nsUsrName) {
|
||||
members[member.m_nsUsrName] = member.nickname || member.m_nsUsrName
|
||||
}
|
||||
@@ -166,10 +177,10 @@ export class WechatDb {
|
||||
public getGroupMembersForChat(userMd5: string): Record<string, string> {
|
||||
this.ensureChatTableMapping()
|
||||
const username = this.chatMd5ToUsername.get(userMd5)
|
||||
if (!username || !username.endsWith('@chatroom')) return {}
|
||||
if (!username || !isGroupSession(username)) return {}
|
||||
|
||||
const members: Record<string, string> = {}
|
||||
for (const member of this.wcdb4Client.getGroupMembers(username)) {
|
||||
for (const member of this.readGroupMembers(username)) {
|
||||
if (member.m_nsUsrName) {
|
||||
members[member.m_nsUsrName] = member.nickname || member.m_nsUsrName
|
||||
}
|
||||
@@ -180,7 +191,7 @@ export class WechatDb {
|
||||
public getGroupMember(wxid: string, chatroomId?: string): GroupMemberInfo | null {
|
||||
if (!chatroomId) return null
|
||||
return (
|
||||
this.wcdb4Client.getGroupMembers(chatroomId).find((member) => member.m_nsUsrName === wxid) ||
|
||||
this.readGroupMembers(chatroomId).find((member) => member.m_nsUsrName === wxid) ||
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
Vendored
+43
-2
@@ -7,13 +7,16 @@ import type {
|
||||
import type {
|
||||
ExtensionInstallResult,
|
||||
ExtensionLogEntry,
|
||||
ExtensionNotificationItem,
|
||||
ExtensionNotificationSummary,
|
||||
ExtensionOperationResult,
|
||||
ExtensionPageDescriptor,
|
||||
ExtensionPageResponse,
|
||||
ExtensionActionInfo,
|
||||
ExtensionProjectResult,
|
||||
ExtensionSystemHealth,
|
||||
InstalledExtension
|
||||
InstalledExtension,
|
||||
PinnedExtensionNavItem
|
||||
} from '../shared/extensions/types'
|
||||
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
|
||||
import {
|
||||
@@ -56,7 +59,14 @@ 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 {
|
||||
DownloadOriginalImageRequest,
|
||||
DownloadOriginalImageResult,
|
||||
DownloadVideoRequest,
|
||||
DownloadVideoResult,
|
||||
ImageMessageXmlRequest,
|
||||
ImageMessageXmlResult
|
||||
} from '../shared/image-message-xml'
|
||||
import type {
|
||||
AIChatRequestOptions,
|
||||
AiSearchExternalAuthorizationRequest,
|
||||
@@ -168,10 +178,15 @@ import type {
|
||||
QueryAgentProgressEvent
|
||||
} from '../shared/query-agent'
|
||||
import type {
|
||||
KnowledgeIndexScope,
|
||||
KnowledgeRuntimeStatus,
|
||||
KnowledgeSearchIpcRequest,
|
||||
KnowledgeSearchIpcResult
|
||||
} from '../shared/knowledge'
|
||||
import type {
|
||||
ConversationMessageCountEntry,
|
||||
ConversationMessageCountSnapshot
|
||||
} from '../shared/conversation-message-count'
|
||||
import type {
|
||||
PublishWechatShareCardRequest,
|
||||
PublishWechatShareCardResult,
|
||||
@@ -389,9 +404,19 @@ declare global {
|
||||
) => () => void
|
||||
forgetAskWechatConversation: () => Promise<void>
|
||||
getKnowledgeStatus: () => Promise<KnowledgeRuntimeStatus>
|
||||
getConversationActivity: () => Promise<Record<string, number>>
|
||||
getKnowledgeIndexScope: () => Promise<KnowledgeIndexScope>
|
||||
setKnowledgeIndexScope: (scope: KnowledgeIndexScope) => Promise<KnowledgeIndexScope>
|
||||
startKnowledgeIndex: () => Promise<KnowledgeRuntimeStatus>
|
||||
cancelKnowledgeIndex: () => Promise<{ cancellable: boolean; cancelled: boolean }>
|
||||
onKnowledgeStatus: (callback: (status: KnowledgeRuntimeStatus) => void) => () => void
|
||||
getConversationMessageCounts: (
|
||||
conversationIds: string[]
|
||||
) => Promise<ConversationMessageCountSnapshot>
|
||||
cancelConversationMessageCounts: () => Promise<void>
|
||||
onConversationMessageCounts: (
|
||||
callback: (entries: ConversationMessageCountEntry[]) => void
|
||||
) => () => void
|
||||
aiChat: (
|
||||
messages: { role: string; content: string }[],
|
||||
options?: AIChatRequestOptions
|
||||
@@ -487,6 +512,10 @@ declare global {
|
||||
}>
|
||||
getImageDebugInfo: (request: ImageDebugInfoRequest) => Promise<ImageDebugInfoResult>
|
||||
getImageMessageXml: (request: ImageMessageXmlRequest) => Promise<ImageMessageXmlResult>
|
||||
downloadOriginalImage: (
|
||||
request: DownloadOriginalImageRequest
|
||||
) => Promise<DownloadOriginalImageResult>
|
||||
downloadVideo: (request: DownloadVideoRequest) => Promise<DownloadVideoResult>
|
||||
getVideo: (
|
||||
hashes: string[],
|
||||
options?: {
|
||||
@@ -898,6 +927,18 @@ declare global {
|
||||
) => Promise<ExtensionPageDescriptor>
|
||||
extensionPageRequest: (request: ExtensionPageRequest) => Promise<ExtensionPageResponse>
|
||||
openExtensionDataDir: (extensionId: string) => Promise<{ success: boolean; error?: string }>
|
||||
listPinnedExtensionNav: () => Promise<PinnedExtensionNavItem[]>
|
||||
pinExtensionNav: (extensionId: string, pageId?: string) => Promise<ExtensionOperationResult>
|
||||
unpinExtensionNav: (extensionId: string) => Promise<ExtensionOperationResult>
|
||||
reorderPinnedExtensionNav: (extensionIds: string[]) => Promise<ExtensionOperationResult>
|
||||
listExtensionNotifications: (extensionId?: string) => Promise<ExtensionNotificationItem[]>
|
||||
getExtensionNotificationSummary: () => Promise<ExtensionNotificationSummary>
|
||||
markExtensionNotificationsRead: (payload: {
|
||||
id?: string
|
||||
extensionId?: string
|
||||
all?: boolean
|
||||
}) => Promise<{ changed: number }>
|
||||
clearExtensionNotifications: (extensionId?: string) => Promise<{ removed: number }>
|
||||
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => () => void
|
||||
}
|
||||
}
|
||||
|
||||
+64
-2
@@ -91,7 +91,14 @@ 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 {
|
||||
DownloadOriginalImageRequest,
|
||||
DownloadOriginalImageResult,
|
||||
DownloadVideoRequest,
|
||||
DownloadVideoResult,
|
||||
ImageMessageXmlRequest,
|
||||
ImageMessageXmlResult
|
||||
} from '../shared/image-message-xml'
|
||||
import type { AccountDiscoveryResult } from '../shared/database-key'
|
||||
import type {
|
||||
VoiceBatchConversationSummary,
|
||||
@@ -118,10 +125,15 @@ import type {
|
||||
QueryAgentProgressEvent
|
||||
} from '../shared/query-agent'
|
||||
import type {
|
||||
KnowledgeIndexScope,
|
||||
KnowledgeRuntimeStatus,
|
||||
KnowledgeSearchIpcRequest,
|
||||
KnowledgeSearchIpcResult
|
||||
} from '../shared/knowledge'
|
||||
import type {
|
||||
ConversationMessageCountEntry,
|
||||
ConversationMessageCountSnapshot
|
||||
} from '../shared/conversation-message-count'
|
||||
import type {
|
||||
PublishWechatShareCardRequest,
|
||||
WechatShareServiceConfig
|
||||
@@ -135,6 +147,8 @@ import type { ExtensionChangedEvent } from '../shared/extensions/ipc'
|
||||
import type {
|
||||
ExtensionInstallResult,
|
||||
ExtensionLogEntry,
|
||||
ExtensionNotificationItem,
|
||||
ExtensionNotificationSummary,
|
||||
ExtensionOperationResult,
|
||||
ExtensionPageDescriptor,
|
||||
ExtensionPageRequest,
|
||||
@@ -142,7 +156,8 @@ import type {
|
||||
ExtensionActionInfo,
|
||||
ExtensionProjectResult,
|
||||
ExtensionSystemHealth,
|
||||
InstalledExtension
|
||||
InstalledExtension,
|
||||
PinnedExtensionNavItem
|
||||
} from '../shared/extensions/types'
|
||||
import type { ExtensionTemplateStatus } from '../shared/extensions/templates'
|
||||
|
||||
@@ -178,6 +193,8 @@ const api = {
|
||||
getBootstrapCache: () => ipcRenderer.invoke('db:getBootstrapCache'),
|
||||
getStartupCache: () => ipcRenderer.invoke('db:getStartupCache'),
|
||||
getContacts: (filter?: string) => ipcRenderer.invoke('db:getContacts', filter),
|
||||
getConversationActivity: (): Promise<Record<string, number>> =>
|
||||
ipcRenderer.invoke('db:conversationActivity'),
|
||||
getContactAvatars: (usernames: string[], options?: { refresh?: boolean }) =>
|
||||
ipcRenderer.invoke('db:getContactAvatars', usernames, options),
|
||||
getCachedMessages: (userMd5: string, startTime?: number, endTime?: number) =>
|
||||
@@ -361,6 +378,25 @@ const api = {
|
||||
ipcRenderer.invoke('extension:pageRequest', request),
|
||||
openExtensionDataDir: (extensionId: string): Promise<{ success: boolean; error?: string }> =>
|
||||
ipcRenderer.invoke('extension:openDataDir', extensionId),
|
||||
listPinnedExtensionNav: (): Promise<PinnedExtensionNavItem[]> =>
|
||||
ipcRenderer.invoke('extension:pinnedNavigation'),
|
||||
pinExtensionNav: (extensionId: string, pageId?: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:pinNavigation', { id: extensionId, pageId }),
|
||||
unpinExtensionNav: (extensionId: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:unpinNavigation', extensionId),
|
||||
reorderPinnedExtensionNav: (extensionIds: string[]): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:reorderNavigation', extensionIds),
|
||||
listExtensionNotifications: (extensionId?: string): Promise<ExtensionNotificationItem[]> =>
|
||||
ipcRenderer.invoke('extension:notificationsList', extensionId),
|
||||
getExtensionNotificationSummary: (): Promise<ExtensionNotificationSummary> =>
|
||||
ipcRenderer.invoke('extension:notificationsSummary'),
|
||||
markExtensionNotificationsRead: (payload: {
|
||||
id?: string
|
||||
extensionId?: string
|
||||
all?: boolean
|
||||
}): Promise<{ changed: number }> => ipcRenderer.invoke('extension:notificationsMarkRead', payload),
|
||||
clearExtensionNotifications: (extensionId?: string): Promise<{ removed: number }> =>
|
||||
ipcRenderer.invoke('extension:notificationsClear', extensionId),
|
||||
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, payload: ExtensionChangedEvent): void =>
|
||||
callback(payload)
|
||||
@@ -421,6 +457,25 @@ const api = {
|
||||
ipcRenderer.on('knowledge:status', listener)
|
||||
return () => ipcRenderer.removeListener('knowledge:status', listener)
|
||||
},
|
||||
/** 立即返回已知快照,未知项由 `onConversationMessageCounts` 补齐;null 是未知不是 0。 */
|
||||
getConversationMessageCounts: (conversationIds: string[]): Promise<ConversationMessageCountSnapshot> =>
|
||||
ipcRenderer.invoke('knowledge:getConversationCounts', conversationIds),
|
||||
cancelConversationMessageCounts: (): Promise<void> =>
|
||||
ipcRenderer.invoke('knowledge:cancelConversationCounts'),
|
||||
getKnowledgeIndexScope: (): Promise<KnowledgeIndexScope> =>
|
||||
ipcRenderer.invoke('knowledge:getIndexScope'),
|
||||
setKnowledgeIndexScope: (scope: KnowledgeIndexScope): Promise<KnowledgeIndexScope> =>
|
||||
ipcRenderer.invoke('knowledge:setIndexScope', scope),
|
||||
onConversationMessageCounts: (
|
||||
callback: (entries: ConversationMessageCountEntry[]) => void
|
||||
) => {
|
||||
const listener = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
entries: ConversationMessageCountEntry[]
|
||||
): void => callback(entries)
|
||||
ipcRenderer.on('knowledge:conversationCounts', listener)
|
||||
return () => ipcRenderer.removeListener('knowledge:conversationCounts', listener)
|
||||
},
|
||||
aiChat: (messages: { role: string; content: string }[], options?: AIChatRequestOptions) =>
|
||||
ipcRenderer.invoke('ai:chat', messages, options),
|
||||
listAIProviders: () => ipcRenderer.invoke('ai:listProviders'),
|
||||
@@ -515,6 +570,13 @@ const api = {
|
||||
/** 图片消息原始 XML。 */
|
||||
getImageMessageXml: (request: ImageMessageXmlRequest): Promise<ImageMessageXmlResult> =>
|
||||
ipcRenderer.invoke('image:getMessageXml', request),
|
||||
/** 触发微信进程下载图片原图并刷新缓存。 */
|
||||
downloadOriginalImage: (
|
||||
request: DownloadOriginalImageRequest
|
||||
): Promise<DownloadOriginalImageResult> => ipcRenderer.invoke('image:downloadOriginal', request),
|
||||
/** 触发微信进程下载聊天视频并刷新本地视频索引。 */
|
||||
downloadVideo: (request: DownloadVideoRequest): Promise<DownloadVideoResult> =>
|
||||
ipcRenderer.invoke('video:download', request),
|
||||
getVideo: (
|
||||
hashes: string[],
|
||||
options?: {
|
||||
|
||||
@@ -53,7 +53,12 @@ import {
|
||||
type AutomationOpenRuleRequest
|
||||
} from './features/automation/AutomationWorkspace'
|
||||
import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace'
|
||||
import type { ExtensionDeepLink } from '../../shared/extensions/types'
|
||||
import { ExtensionPageHost } from './features/extensions/ExtensionPageHost'
|
||||
import type {
|
||||
ExtensionDeepLink,
|
||||
ExtensionPageDescriptor,
|
||||
PinnedExtensionNavItem
|
||||
} from '../../shared/extensions/types'
|
||||
import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar'
|
||||
import {
|
||||
buildContactSearchIndex,
|
||||
@@ -267,6 +272,10 @@ function App(): React.ReactElement {
|
||||
const [activePage, setActivePage] = useState<AppPage>('archive')
|
||||
/** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */
|
||||
const [extensionDeepLink, setExtensionDeepLink] = useState<ExtensionDeepLink | null>(null)
|
||||
/** 通过一级导航固定入口直接打开的扩展页面,复用同一个 ExtensionPageHost 容器。 */
|
||||
const [pinnedExtensionPage, setPinnedExtensionPage] = useState<ExtensionPageDescriptor | null>(
|
||||
null
|
||||
)
|
||||
/** 「退群监控 ⇄ 自动化」之间的跨页深链。 */
|
||||
const [automationOpenRuleRequest, setAutomationOpenRuleRequest] =
|
||||
React.useState<AutomationOpenRuleRequest | null>(null)
|
||||
@@ -1604,11 +1613,36 @@ function App(): React.ReactElement {
|
||||
|
||||
/** 跳到扩展中心并带上定位目标(模板 / 扩展)。 */
|
||||
const openExtensionDeepLink = (target: ExtensionDeepLink): void => {
|
||||
setPinnedExtensionPage(null)
|
||||
setExtensionDeepLink(target)
|
||||
handlePageChange('extensions')
|
||||
}
|
||||
|
||||
const openPinnedExtensionNav = (item: PinnedExtensionNavItem): void => {
|
||||
void window.api.markExtensionNotificationsRead?.({ extensionId: item.extensionId }).catch(() => undefined)
|
||||
void window.api
|
||||
.getExtensionPageUrl(item.extensionId, item.pageId)
|
||||
.then((descriptor) => {
|
||||
setPinnedExtensionPage(descriptor)
|
||||
})
|
||||
.catch(() => {
|
||||
setPinnedExtensionPage(null)
|
||||
openExtensionDeepLink({ extensionId: item.extensionId })
|
||||
})
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
if (typeof window === 'undefined' || typeof window.api?.onExtensionChanged !== 'function') return
|
||||
return window.api.onExtensionChanged((event) => {
|
||||
if (event.reason !== 'uninstalled') return
|
||||
setPinnedExtensionPage((current) =>
|
||||
current && current.extensionId === event.extensionId ? null : current
|
||||
)
|
||||
})
|
||||
}, [])
|
||||
|
||||
const handlePageChange = (page: AppPage): void => {
|
||||
setPinnedExtensionPage(null)
|
||||
setActivePage(page)
|
||||
if (page === 'archive' && selectedContact) void handleSelectContact(selectedContact)
|
||||
if (page === 'settings') setSettingsCategory('account-database')
|
||||
@@ -2085,6 +2119,19 @@ function App(): React.ReactElement {
|
||||
)
|
||||
|
||||
const renderCurrentWorkspace = (): React.ReactElement => {
|
||||
if (pinnedExtensionPage) {
|
||||
return (
|
||||
<div className="extension-page-wrapper">
|
||||
<ExtensionPageHost
|
||||
descriptor={pinnedExtensionPage}
|
||||
onBack={() => {
|
||||
setPinnedExtensionPage(null)
|
||||
setActivePage('extensions')
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
switch (activePage) {
|
||||
case 'archive':
|
||||
return renderArchiveWorkspace()
|
||||
@@ -2205,6 +2252,7 @@ function App(): React.ReactElement {
|
||||
dbReady={isDatabaseConnected}
|
||||
loadPreviewMessages={loadExportPreviewMessages}
|
||||
onOpenSettings={openSettings}
|
||||
onOpenSendSettings={openWechatSendSettings}
|
||||
exportTasks={exportTasks}
|
||||
onStartExport={handleStartExport}
|
||||
onCancelExport={handleCancelExport}
|
||||
@@ -2381,6 +2429,8 @@ function App(): React.ReactElement {
|
||||
dbReady={isDatabaseConnected}
|
||||
dbConnecting={isDatabaseConnecting}
|
||||
onPageChange={handlePageChange}
|
||||
activePinnedExtensionId={pinnedExtensionPage?.extensionId ?? null}
|
||||
onOpenPinnedExtension={openPinnedExtensionNav}
|
||||
onOpenSettings={openSettings}
|
||||
onOpenGuide={openFirstUseGuide}
|
||||
appearanceTheme={appearanceSettings.theme}
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Message, Contact } from '../../../shared/types'
|
||||
import { ChatHeader } from './chat/ChatHeader'
|
||||
import { ChatImageViewer } from './chat/ChatImageViewer'
|
||||
import type { ImagePreviewOptions } from './ImageBubble'
|
||||
import { ChatStatusBar } from './chat/ChatStatusBar'
|
||||
import { DataTrustBar } from './chat/DataTrustBar'
|
||||
import { EmptyConversationState } from './chat/EmptyConversationState'
|
||||
@@ -54,7 +55,11 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
)
|
||||
const messageListRef = useRef<HTMLDivElement>(null)
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null)
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null)
|
||||
const [previewImage, setPreviewImage] = useState<{
|
||||
url: string
|
||||
onDownloadOriginal?: ImagePreviewOptions['onDownloadOriginal']
|
||||
} | null>(null)
|
||||
const [hasMacHookMediaDownload, setHasMacHookMediaDownload] = useState(false)
|
||||
const [showAvatar, setShowAvatar] = useState(true)
|
||||
const [isAtLatest, setIsAtLatest] = useState(true)
|
||||
const [isReloadingAvatars, setIsReloadingAvatars] = useState(false)
|
||||
@@ -83,6 +88,31 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
setIsAtLatest(true)
|
||||
}, [contact?.md5])
|
||||
|
||||
const isPreviewOpen = previewImage !== null
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
void Promise.all([
|
||||
window.api.getPersonalWechatSendCapability?.().catch(() => null),
|
||||
window.api.getMacSendRuntimeAvailability?.().catch(() => null)
|
||||
]).then(([capability, runtimeAvailability]) => {
|
||||
if (!active) return
|
||||
const isMacHookCapable =
|
||||
runtimeAvailability?.state === 'available' ||
|
||||
(capability?.senderStatus?.platform === 'darwin' &&
|
||||
Boolean(
|
||||
capability.ready ||
|
||||
capability.senderStatus.runtimeReady ||
|
||||
capability.senderStatus.attachReady ||
|
||||
capability.senderStatus.canSend
|
||||
))
|
||||
setHasMacHookMediaDownload(Boolean(isMacHookCapable))
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [isPreviewOpen])
|
||||
|
||||
// 一次跳转 = 有精确目标或有时间目标。用统一判据,避免"只带了 messageId 但没带时间"
|
||||
// 时自动滚到底把跳转结果顶掉(那会让用户看到"跳过去了但又被弹回最新")。
|
||||
const hasJumpTarget =
|
||||
@@ -108,8 +138,11 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
return () => observer.disconnect()
|
||||
}, [contact?.md5, isAtLatest, hasJumpTarget, scrollToBottom])
|
||||
|
||||
const openImagePreview = (imageUrl: string): void => {
|
||||
setPreviewImage(imageUrl)
|
||||
const openImagePreview = (imageUrl: string, options?: ImagePreviewOptions): void => {
|
||||
setPreviewImage({
|
||||
url: imageUrl,
|
||||
onDownloadOriginal: options?.onDownloadOriginal
|
||||
})
|
||||
}
|
||||
|
||||
const closeImagePreview = (): void => {
|
||||
@@ -168,17 +201,6 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
setSendDialogOpen(true)
|
||||
}, [onOpenPersonalWechatSettings])
|
||||
|
||||
const handleSendFile = useCallback(async (): Promise<void> => {
|
||||
try {
|
||||
const picked = await window.api.selectPersonalWechatFile()
|
||||
if (picked.canceled || !picked.path || !picked.name) return
|
||||
setPendingFile({ path: picked.path, name: picked.name })
|
||||
setSendDialogOpen(true)
|
||||
} catch {
|
||||
// 选择器本身失败(无窗口、无权限)时什么都不做,不要弹出一个空对话框。
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (!contact) return <EmptyConversationState />
|
||||
|
||||
return (
|
||||
@@ -193,7 +215,6 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
onContentFilterChange={onContentFilterChange || (() => undefined)}
|
||||
onRefresh={onRefresh}
|
||||
onTestSend={() => void handleOpenPersonalWechatSend()}
|
||||
onSendFile={() => void handleSendFile()}
|
||||
onOpenAiSettings={onCreateGroupReport || (() => undefined)}
|
||||
onOpenLocalIndexSettings={onOpenLocalIndexSettings}
|
||||
/>
|
||||
@@ -238,7 +259,16 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
/>
|
||||
)}
|
||||
|
||||
{previewImage && <ChatImageViewer imageUrl={previewImage} onClose={closeImagePreview} />}
|
||||
{previewImage && (
|
||||
<ChatImageViewer
|
||||
imageUrl={previewImage.url}
|
||||
onDownloadOriginal={hasMacHookMediaDownload ? previewImage.onDownloadOriginal : undefined}
|
||||
onImageChange={(nextUrl) =>
|
||||
setPreviewImage((prev) => (prev ? { ...prev, url: nextUrl } : prev))
|
||||
}
|
||||
onClose={closeImagePreview}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import type { JSX, MouseEvent } from 'react'
|
||||
import type { ForwardedMessageItem } from '../../../shared/types'
|
||||
import { renderWechatEmojiText } from '../utils/wechatEmojiText'
|
||||
import { ImageBubble, type ImageClickHandler } from './ImageBubble'
|
||||
|
||||
export interface ForwardBundleWindowLayer {
|
||||
id: string
|
||||
title: string
|
||||
items: ForwardedMessageItem[]
|
||||
}
|
||||
|
||||
interface ForwardBundleModalStackProps {
|
||||
layers: ForwardBundleWindowLayer[]
|
||||
sessionId?: string
|
||||
onOpenNested: (title: string, items: ForwardedMessageItem[]) => void
|
||||
onCloseFromIndex: (index: number) => void
|
||||
onImageClick?: ImageClickHandler
|
||||
}
|
||||
|
||||
function formatSentAt(value?: string): string {
|
||||
const raw = String(value || '').trim()
|
||||
if (!raw) return ''
|
||||
if (/^\d{9,13}$/.test(raw)) {
|
||||
const ms = raw.length > 10 ? Number(raw) : Number(raw) * 1000
|
||||
const date = new Date(ms)
|
||||
if (!Number.isNaN(date.getTime())) {
|
||||
const yyyy = date.getFullYear()
|
||||
const mm = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const dd = String(date.getDate()).padStart(2, '0')
|
||||
const hh = String(date.getHours()).padStart(2, '0')
|
||||
const min = String(date.getMinutes()).padStart(2, '0')
|
||||
return `${yyyy}-${mm}-${dd} ${hh}:${min}`
|
||||
}
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
function ForwardAvatar({ src, name }: { src?: string; name?: string }): JSX.Element {
|
||||
const [failed, setFailed] = useState(false)
|
||||
const initial = Array.from(String(name || '?').trim())[0] || '?'
|
||||
|
||||
if (src && !failed) {
|
||||
return (
|
||||
<div className="forward-modal-avatar">
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return <div className="forward-modal-avatar forward-modal-avatar-fallback">{initial}</div>
|
||||
}
|
||||
|
||||
function ForwardModalItemRow({
|
||||
item,
|
||||
sessionId,
|
||||
onOpenNested,
|
||||
onImageClick
|
||||
}: {
|
||||
item: ForwardedMessageItem
|
||||
sessionId?: string
|
||||
onOpenNested: (title: string, items: ForwardedMessageItem[]) => void
|
||||
onImageClick?: ImageClickHandler
|
||||
}): JSX.Element {
|
||||
const isNested = item.messageType === 17 || Boolean(item.nested?.length)
|
||||
const isImage =
|
||||
!isNested &&
|
||||
(item.messageType === 2 || Boolean(item.imageMd5 || item.thumbMd5 || item.imageDatName))
|
||||
const senderName = item.sender || '未知发送者'
|
||||
const formattedTime = formatSentAt(item.sentAt)
|
||||
|
||||
const handleOpenNested = (event: MouseEvent<HTMLButtonElement>): void => {
|
||||
event.stopPropagation()
|
||||
if (!item.nested?.length) return
|
||||
onOpenNested(item.nestedTitle || item.title || '聊天记录', item.nested)
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="forward-modal-row">
|
||||
<ForwardAvatar src={item.sourceHeadUrl} name={senderName} />
|
||||
<div className="forward-modal-row-main">
|
||||
<header className="forward-modal-row-meta">
|
||||
<span className="forward-modal-sender">{senderName}</span>
|
||||
{formattedTime ? <time className="forward-modal-time">{formattedTime}</time> : null}
|
||||
</header>
|
||||
<div className="forward-modal-row-body">
|
||||
{isImage ? (
|
||||
<div className="forward-modal-image-wrap">
|
||||
<ImageBubble
|
||||
imageMd5={item.imageMd5 || item.thumbMd5}
|
||||
imageDatName={item.imageDatName}
|
||||
fileId={item.cdnFileId}
|
||||
aesKey={item.cdnAesKey}
|
||||
rawXml={item.rawXml}
|
||||
sessionId={sessionId}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
</div>
|
||||
) : isNested ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`forward-modal-nested-card${item.nested?.length ? ' is-clickable' : ''}`}
|
||||
disabled={!item.nested?.length}
|
||||
onClick={handleOpenNested}
|
||||
>
|
||||
<div className="forward-modal-nested-title">
|
||||
{item.nestedTitle || item.title || '聊天记录'}
|
||||
</div>
|
||||
{item.nested?.length ? (
|
||||
<div className="forward-modal-nested-preview">
|
||||
{item.nested.slice(0, 3).map((child, idx) => (
|
||||
<div
|
||||
key={`${child.dataId || ''}-${child.sender || ''}-${idx}`}
|
||||
className="forward-modal-nested-line"
|
||||
>
|
||||
{child.sender ? `${child.sender}: ` : ''}
|
||||
{child.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="forward-modal-nested-empty">{item.text || '[聊天记录]'}</div>
|
||||
)}
|
||||
<div className="forward-modal-nested-footer">
|
||||
<span>聊天记录</span>
|
||||
{item.nested?.length ? <span>共 {item.nested.length} 条 · 打开新窗口</span> : null}
|
||||
</div>
|
||||
</button>
|
||||
) : (
|
||||
<div className="forward-modal-text">
|
||||
{renderWechatEmojiText(item.text || item.title || '[消息]', 22)}
|
||||
{item.linkUrl && /^https?:\/\//i.test(item.linkUrl) ? (
|
||||
<a
|
||||
className="forward-modal-link"
|
||||
href={item.linkUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
打开链接 ↗
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
export function ForwardBundleModalStack({
|
||||
layers,
|
||||
sessionId,
|
||||
onOpenNested,
|
||||
onCloseFromIndex,
|
||||
onImageClick
|
||||
}: ForwardBundleModalStackProps): JSX.Element | null {
|
||||
useEffect(() => {
|
||||
if (layers.length === 0) return
|
||||
const handleKeyDown = (event: KeyboardEvent): void => {
|
||||
if (event.key !== 'Escape') return
|
||||
// 若此时已打开更上层的 Radix Dialog(例如 ChatImageViewer),优先交由其处理 Escape。
|
||||
if (document.querySelector('[role="dialog"][data-state="open"]')) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onCloseFromIndex(layers.length - 1)
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [layers.length, onCloseFromIndex])
|
||||
|
||||
if (layers.length === 0 || typeof document === 'undefined') return null
|
||||
|
||||
return createPortal(
|
||||
<>
|
||||
{layers.map((layer, index) => {
|
||||
const zIndex = Math.min(58, 45 + index)
|
||||
const offsetX = Math.min(index, 5) * 28
|
||||
const offsetY = Math.min(index, 5) * 24
|
||||
|
||||
return (
|
||||
<div
|
||||
key={layer.id}
|
||||
className="forward-modal-backdrop"
|
||||
style={{ zIndex }}
|
||||
onClick={() => onCloseFromIndex(index)}
|
||||
>
|
||||
<section
|
||||
className="forward-modal-window"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={layer.title || '聊天记录'}
|
||||
style={{
|
||||
transform: `translate(${offsetX}px, ${offsetY}px)`
|
||||
}}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<header className="forward-modal-header">
|
||||
<div className="forward-modal-header-text">
|
||||
<h3 className="forward-modal-title">{layer.title || '聊天记录'}</h3>
|
||||
<span className="forward-modal-subtitle">
|
||||
共 {layer.items.length} 条消息
|
||||
{index > 0 ? ` · 嵌套窗口 #${index + 1}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="forward-modal-close"
|
||||
aria-label="关闭聊天记录窗口"
|
||||
onClick={() => onCloseFromIndex(index)}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
<div className="forward-modal-body">
|
||||
{layer.items.length > 0 ? (
|
||||
layer.items.map((item, itemIdx) => (
|
||||
<ForwardModalItemRow
|
||||
key={`${layer.id}-${item.dataId || ''}-${item.dataIndex ?? itemIdx}-${itemIdx}`}
|
||||
item={item}
|
||||
sessionId={sessionId}
|
||||
onOpenNested={onOpenNested}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<div className="forward-modal-empty">暂未解析到可展示的记录</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</>,
|
||||
document.body
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,19 @@
|
||||
import { useState, useCallback, useEffect, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import type { JSX, KeyboardEvent, MouseEvent } from 'react'
|
||||
import { getCachedLoadedImage, requestImage } from './image-loader'
|
||||
import { getCachedLoadedImage, requestImage, setCachedLoadedImage } from './image-loader'
|
||||
|
||||
export interface ImageOriginalDownloadOutcome {
|
||||
success: boolean
|
||||
data?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface ImagePreviewOptions {
|
||||
onDownloadOriginal?: () => Promise<ImageOriginalDownloadOutcome>
|
||||
}
|
||||
|
||||
export type ImageClickHandler = (imageUrl: string, options?: ImagePreviewOptions) => void
|
||||
|
||||
interface ImageBubbleProps {
|
||||
imageMd5?: string
|
||||
@@ -9,9 +22,12 @@ interface ImageBubbleProps {
|
||||
localId?: number
|
||||
serverId?: string
|
||||
createTime?: number
|
||||
fileId?: string
|
||||
aesKey?: string
|
||||
rawXml?: string
|
||||
isThumb?: boolean
|
||||
fallbackUrl?: string
|
||||
onImageClick?: (imageUrl: string) => void
|
||||
onImageClick?: ImageClickHandler
|
||||
}
|
||||
|
||||
export function ImageBubble({
|
||||
@@ -21,6 +37,9 @@ export function ImageBubble({
|
||||
localId,
|
||||
serverId,
|
||||
createTime,
|
||||
fileId,
|
||||
aesKey,
|
||||
rawXml,
|
||||
fallbackUrl,
|
||||
onImageClick
|
||||
}: ImageBubbleProps): JSX.Element {
|
||||
@@ -30,9 +49,13 @@ export function ImageBubble({
|
||||
const [imageUrl, setImageUrl] = useState<string | null>(initialCachedImage?.data || null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [upgrading, setUpgrading] = useState(false)
|
||||
const [downloadingOriginal, setDownloadingOriginal] = useState(false)
|
||||
const [originalReadyNotice, setOriginalReadyNotice] = useState(false)
|
||||
const [contextMenuPos, setContextMenuPos] = useState<{ x: number; y: number } | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [usingFallback, setUsingFallback] = useState(false)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const menuRef = useRef<HTMLDivElement>(null)
|
||||
const mountedRef = useRef(true)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -42,6 +65,30 @@ export function ImageBubble({
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!contextMenuPos) return
|
||||
const handlePointerDown = (event: globalThis.MouseEvent): void => {
|
||||
if (menuRef.current && menuRef.current.contains(event.target as Node)) return
|
||||
setContextMenuPos(null)
|
||||
}
|
||||
const handleKeyDown = (event: globalThis.KeyboardEvent): void => {
|
||||
if (event.key === 'Escape') {
|
||||
setContextMenuPos(null)
|
||||
}
|
||||
}
|
||||
const handleScroll = (): void => {
|
||||
setContextMenuPos(null)
|
||||
}
|
||||
window.addEventListener('mousedown', handlePointerDown, true)
|
||||
window.addEventListener('keydown', handleKeyDown, true)
|
||||
window.addEventListener('scroll', handleScroll, true)
|
||||
return () => {
|
||||
window.removeEventListener('mousedown', handlePointerDown, true)
|
||||
window.removeEventListener('keydown', handleKeyDown, true)
|
||||
window.removeEventListener('scroll', handleScroll, true)
|
||||
}
|
||||
}, [contextMenuPos])
|
||||
|
||||
const loadImage = useCallback(
|
||||
async (priority = 0) => {
|
||||
if (imageUrl) return
|
||||
@@ -131,11 +178,117 @@ export function ImageBubble({
|
||||
alert('图片已复制')
|
||||
}
|
||||
|
||||
/** 右键复制消息原始 XML。 */
|
||||
/** 右键打开图片操作菜单(下载原图 / 复制 XML)。 */
|
||||
const handleOpenContextMenu = (event: MouseEvent): void => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const menuWidth = 152
|
||||
const menuHeight = 88
|
||||
const maxX =
|
||||
typeof window !== 'undefined'
|
||||
? Math.max(8, window.innerWidth - menuWidth - 8)
|
||||
: event.clientX
|
||||
const maxY =
|
||||
typeof window !== 'undefined'
|
||||
? Math.max(8, window.innerHeight - menuHeight - 8)
|
||||
: event.clientY
|
||||
setContextMenuPos({
|
||||
x: Math.min(Math.max(8, event.clientX), maxX),
|
||||
y: Math.min(Math.max(8, event.clientY), maxY)
|
||||
})
|
||||
}
|
||||
|
||||
/** 副作用:无论谁调用,都会写图片缓存并替换气泡里的图。 */
|
||||
const downloadOriginalImageCore = useCallback(async (): Promise<ImageOriginalDownloadOutcome> => {
|
||||
if (downloadingOriginal) {
|
||||
return { success: false, error: '正在下载原图,请稍候' }
|
||||
}
|
||||
|
||||
setDownloadingOriginal(true)
|
||||
setOriginalReadyNotice(false)
|
||||
try {
|
||||
const result = await window.api.downloadOriginalImage({
|
||||
sessionId,
|
||||
localId,
|
||||
serverId,
|
||||
createTime,
|
||||
imageMd5,
|
||||
imageDatName,
|
||||
fileId,
|
||||
aesKey,
|
||||
rawXml
|
||||
})
|
||||
if (!result.success || !result.data) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.error || '原图下载失败'
|
||||
}
|
||||
}
|
||||
setCachedLoadedImage(imageMd5, imageDatName, {
|
||||
data: result.data,
|
||||
isThumbnail: false
|
||||
})
|
||||
if (result.md5 && result.md5 !== imageMd5) {
|
||||
setCachedLoadedImage(result.md5, imageDatName, {
|
||||
data: result.data,
|
||||
isThumbnail: false
|
||||
})
|
||||
}
|
||||
if (mountedRef.current) {
|
||||
setImageUrl(result.data)
|
||||
setUsingFallback(false)
|
||||
setError(null)
|
||||
setOriginalReadyNotice(true)
|
||||
window.setTimeout(() => {
|
||||
if (mountedRef.current) setOriginalReadyNotice(false)
|
||||
}, 2500)
|
||||
}
|
||||
return { success: true, data: result.data }
|
||||
} catch (err) {
|
||||
return {
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : '原图下载失败'
|
||||
}
|
||||
} finally {
|
||||
if (mountedRef.current) setDownloadingOriginal(false)
|
||||
}
|
||||
}, [
|
||||
aesKey,
|
||||
createTime,
|
||||
downloadingOriginal,
|
||||
fileId,
|
||||
imageDatName,
|
||||
imageMd5,
|
||||
localId,
|
||||
rawXml,
|
||||
serverId,
|
||||
sessionId
|
||||
])
|
||||
|
||||
const handleDownloadOriginalImage = async (event: MouseEvent): Promise<void> => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
setContextMenuPos(null)
|
||||
if (downloadingOriginal) return
|
||||
|
||||
const outcome = await downloadOriginalImageCore()
|
||||
if (!mountedRef.current) return
|
||||
if (!outcome.success) {
|
||||
alert(outcome.error ? `原图下载失败:${outcome.error}` : '原图下载失败')
|
||||
}
|
||||
}
|
||||
|
||||
/** 复制消息原始 XML。 */
|
||||
const handleCopyMessageXml = async (event: MouseEvent): Promise<void> => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
setContextMenuPos(null)
|
||||
try {
|
||||
if ((!sessionId || !localId) && rawXml) {
|
||||
await navigator.clipboard.writeText(rawXml)
|
||||
alert('图片消息 XML 已复制')
|
||||
return
|
||||
}
|
||||
const result = await window.api.getImageMessageXml({
|
||||
sessionId,
|
||||
localId,
|
||||
@@ -143,6 +296,11 @@ export function ImageBubble({
|
||||
createTime
|
||||
})
|
||||
if (!result.success || !result.xml) {
|
||||
if (rawXml) {
|
||||
await navigator.clipboard.writeText(rawXml)
|
||||
alert('图片消息 XML 已复制')
|
||||
return
|
||||
}
|
||||
alert(result.error ? `XML 获取失败:${result.error}` : 'XML 获取失败')
|
||||
return
|
||||
}
|
||||
@@ -153,15 +311,65 @@ export function ImageBubble({
|
||||
}
|
||||
}
|
||||
|
||||
const renderContextMenu = (): JSX.Element | null => {
|
||||
if (!contextMenuPos || typeof document === 'undefined') return null
|
||||
return createPortal(
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="image-bubble-context-menu"
|
||||
role="menu"
|
||||
aria-label="图片右键菜单"
|
||||
style={{ left: `${contextMenuPos.x}px`, top: `${contextMenuPos.y}px` }}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className="image-bubble-context-item"
|
||||
disabled={downloadingOriginal}
|
||||
onClick={(event) => void handleDownloadOriginalImage(event)}
|
||||
>
|
||||
{downloadingOriginal ? '正在下载原图...' : '下载原图'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className="image-bubble-context-item"
|
||||
onClick={(event) => void handleCopyMessageXml(event)}
|
||||
>
|
||||
复制 XML
|
||||
</button>
|
||||
</div>,
|
||||
document.body
|
||||
)
|
||||
}
|
||||
|
||||
const canDownloadOriginal =
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.api?.downloadOriginalImage === 'function' &&
|
||||
Boolean((sessionId && (localId || serverId)) || (fileId && aesKey) || rawXml)
|
||||
|
||||
const openPreview = (url: string): void => {
|
||||
if (canDownloadOriginal) {
|
||||
onImageClick?.(url, { onDownloadOriginal: downloadOriginalImageCore })
|
||||
} else {
|
||||
onImageClick?.(url)
|
||||
}
|
||||
}
|
||||
|
||||
const handleClick = async (): Promise<void> => {
|
||||
if (!imageUrl && !error) return
|
||||
if (!imageMd5 && !imageDatName) {
|
||||
if (imageUrl) onImageClick?.(imageUrl)
|
||||
if (imageUrl) openPreview(imageUrl)
|
||||
return
|
||||
}
|
||||
|
||||
if (upgrading) {
|
||||
if (imageUrl) onImageClick?.(imageUrl)
|
||||
if (imageUrl) openPreview(imageUrl)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -172,7 +380,7 @@ export function ImageBubble({
|
||||
setImageUrl(result.data)
|
||||
setUsingFallback(false)
|
||||
setError(null)
|
||||
onImageClick?.(result.data)
|
||||
openPreview(result.data)
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
@@ -181,7 +389,7 @@ export function ImageBubble({
|
||||
setUpgrading(false)
|
||||
}
|
||||
|
||||
if (imageUrl) onImageClick?.(imageUrl)
|
||||
if (imageUrl) openPreview(imageUrl)
|
||||
}
|
||||
|
||||
const handlePreviewKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
|
||||
@@ -201,10 +409,19 @@ export function ImageBubble({
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="image-bubble image-error" onClick={() => void loadImage(0)}>
|
||||
<div className="image-error-text">{error || '图片未缓存'}</div>
|
||||
<div className="image-quality-badge">加载失败</div>
|
||||
</div>
|
||||
<>
|
||||
<div
|
||||
className="image-bubble image-error"
|
||||
onClick={() => void loadImage(0)}
|
||||
onContextMenu={handleOpenContextMenu}
|
||||
>
|
||||
<div className="image-error-text">{error || '图片未缓存'}</div>
|
||||
<div className="image-quality-badge">
|
||||
{downloadingOriginal ? '正在下载原图...' : '加载失败'}
|
||||
</div>
|
||||
</div>
|
||||
{renderContextMenu()}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -218,26 +435,35 @@ export function ImageBubble({
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="image-bubble image-loaded"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="查看图片"
|
||||
onClick={handleClick}
|
||||
onContextMenu={handleCopyMessageXml}
|
||||
onKeyDown={handlePreviewKeyDown}
|
||||
>
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt="图片"
|
||||
className={`image-content ${usingFallback ? 'image-fallback' : ''}`}
|
||||
/>
|
||||
{upgrading && <div className="image-quality-badge">正在查找原图</div>}
|
||||
<div className="image-actions">
|
||||
<button className="image-action-btn" onClick={handleCopy} title="复制图片">
|
||||
复制
|
||||
</button>
|
||||
<>
|
||||
<div
|
||||
className="image-bubble image-loaded"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="查看图片"
|
||||
onClick={handleClick}
|
||||
onContextMenu={handleOpenContextMenu}
|
||||
onKeyDown={handlePreviewKeyDown}
|
||||
>
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt="图片"
|
||||
className={`image-content ${usingFallback ? 'image-fallback' : ''}`}
|
||||
/>
|
||||
{downloadingOriginal ? (
|
||||
<div className="image-quality-badge">正在下载原图...</div>
|
||||
) : originalReadyNotice ? (
|
||||
<div className="image-quality-badge">已加载原图</div>
|
||||
) : (
|
||||
upgrading && <div className="image-quality-badge">正在查找原图</div>
|
||||
)}
|
||||
<div className="image-actions">
|
||||
<button className="image-action-btn" onClick={handleCopy} title="复制图片">
|
||||
复制
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{renderContextMenu()}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,20 +1,27 @@
|
||||
import { ParsedContent } from '../../../shared/types'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ParsedContent, type ForwardedMessageItem } from '../../../shared/types'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import type { JSX, MouseEvent } from 'react'
|
||||
import { renderWechatEmojiText } from '../utils/wechatEmojiText'
|
||||
import { ImageBubble } from './ImageBubble'
|
||||
import { ImageBubble, type ImageClickHandler } from './ImageBubble'
|
||||
import { ForwardBundleModalStack, type ForwardBundleWindowLayer } from './ForwardBundleModal'
|
||||
|
||||
const stickerDataUrlCache = new Map<string, string>()
|
||||
|
||||
interface RichMessageBubbleProps {
|
||||
contentData: ParsedContent
|
||||
sessionId?: string
|
||||
onImageClick?: (imageUrl: string) => void
|
||||
localId?: number
|
||||
serverId?: string
|
||||
createTime?: number
|
||||
onImageClick?: ImageClickHandler
|
||||
}
|
||||
|
||||
export function RichMessageBubble({
|
||||
contentData,
|
||||
sessionId,
|
||||
localId,
|
||||
serverId,
|
||||
createTime,
|
||||
onImageClick
|
||||
}: RichMessageBubbleProps): JSX.Element {
|
||||
switch (contentData.type) {
|
||||
@@ -25,7 +32,13 @@ export function RichMessageBubble({
|
||||
case 'share':
|
||||
return <ShareBubble data={contentData} />
|
||||
case 'forwardBundle':
|
||||
return <ForwardBundleBubble data={contentData} />
|
||||
return (
|
||||
<ForwardBundleBubble
|
||||
data={contentData}
|
||||
sessionId={sessionId}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
)
|
||||
case 'miniProgram':
|
||||
return (
|
||||
<MiniProgramBubble data={contentData} sessionId={sessionId} onImageClick={onImageClick} />
|
||||
@@ -37,7 +50,16 @@ export function RichMessageBubble({
|
||||
case 'sticker':
|
||||
return <StickerBubble data={contentData} />
|
||||
case 'quote':
|
||||
return <QuoteBubble data={contentData} sessionId={sessionId} onImageClick={onImageClick} />
|
||||
return (
|
||||
<QuoteBubble
|
||||
data={contentData}
|
||||
sessionId={sessionId}
|
||||
localId={localId}
|
||||
serverId={serverId}
|
||||
createTime={createTime}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
)
|
||||
case 'system':
|
||||
return <SystemBubble data={contentData} />
|
||||
case 'unknown':
|
||||
@@ -55,52 +77,97 @@ export function RichMessageBubble({
|
||||
}
|
||||
|
||||
function ForwardBundleBubble({
|
||||
data
|
||||
data,
|
||||
sessionId,
|
||||
onImageClick
|
||||
}: {
|
||||
data: Extract<ParsedContent, { type: 'forwardBundle' }>
|
||||
sessionId?: string
|
||||
onImageClick?: ImageClickHandler
|
||||
}): JSX.Element {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const visibleItems = expanded ? data.items : data.items.slice(0, 3)
|
||||
const hiddenCount = Math.max(0, data.items.length - visibleItems.length)
|
||||
const [modalLayers, setModalLayers] = useState<ForwardBundleWindowLayer[]>([])
|
||||
const previewItems = data.items.slice(0, 4)
|
||||
|
||||
const openRootModal = useCallback((): void => {
|
||||
setModalLayers([
|
||||
{
|
||||
id: `forward-root-${Date.now()}`,
|
||||
title: data.title || '聊天记录',
|
||||
items: data.items
|
||||
}
|
||||
])
|
||||
}, [data.items, data.title])
|
||||
|
||||
const openNestedModal = useCallback(
|
||||
(title: string, items: ForwardedMessageItem[]): void => {
|
||||
setModalLayers((current) => [
|
||||
...current,
|
||||
{
|
||||
id: `forward-nested-${current.length}-${Date.now()}`,
|
||||
title: title || '聊天记录',
|
||||
items
|
||||
}
|
||||
])
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
const closeFromIndex = useCallback((index: number): void => {
|
||||
setModalLayers((current) => current.slice(0, index))
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="forward-bundle-message">
|
||||
<button
|
||||
type="button"
|
||||
className="forward-bundle-header"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
<>
|
||||
<div
|
||||
className="forward-bundle-message is-clickable"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={openRootModal}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
openRootModal()
|
||||
}
|
||||
}}
|
||||
title="点击弹窗查看完整聊天记录"
|
||||
>
|
||||
<span>{data.title || '聊天记录'}</span>
|
||||
<small>
|
||||
{data.items.length ? `${data.items.length} 条消息` : data.description || '聊天记录'}
|
||||
</small>
|
||||
</button>
|
||||
<div className="forward-bundle-list">
|
||||
{visibleItems.length ? (
|
||||
visibleItems.map((item, index) => (
|
||||
<div
|
||||
className="forward-bundle-item"
|
||||
key={`${item.sender || ''}-${item.sentAt || ''}-${index}`}
|
||||
>
|
||||
{item.sender && <b>{item.sender}</b>}
|
||||
<span>{renderWechatEmojiText(item.text, 24)}</span>
|
||||
{item.nested?.length ? <small>包含 {item.nested.length} 条聊天记录</small> : null}
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="forward-bundle-empty">暂未解析到可展示的记录</div>
|
||||
)}
|
||||
<div className="forward-bundle-header">
|
||||
<span>{data.title || '聊天记录'}</span>
|
||||
<small>
|
||||
{data.items.length ? `${data.items.length} 条消息` : data.description || '聊天记录'}
|
||||
</small>
|
||||
</div>
|
||||
<div className="forward-bundle-list">
|
||||
{previewItems.length ? (
|
||||
previewItems.map((item, index) => (
|
||||
<div
|
||||
className="forward-bundle-item"
|
||||
key={`${item.dataId || ''}-${item.sender || ''}-${item.sentAt || ''}-${index}`}
|
||||
>
|
||||
{item.sender && <b>{item.sender}</b>}
|
||||
<span>{renderWechatEmojiText(item.text, 24)}</span>
|
||||
{item.nested?.length ? (
|
||||
<small>包含 {item.nested.length} 条嵌套聊天记录</small>
|
||||
) : null}
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="forward-bundle-empty">暂未解析到可展示的记录</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="forward-bundle-footer">
|
||||
<span>聊天记录</span>
|
||||
<span className="forward-bundle-footer-action">查看详情</span>
|
||||
</div>
|
||||
</div>
|
||||
{(hiddenCount > 0 || expanded) && data.items.length > 3 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="forward-bundle-toggle"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
>
|
||||
{expanded ? '收起' : `展开其余 ${hiddenCount} 条`}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<ForwardBundleModalStack
|
||||
layers={modalLayers}
|
||||
sessionId={sessionId}
|
||||
onOpenNested={openNestedModal}
|
||||
onCloseFromIndex={closeFromIndex}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -209,7 +276,7 @@ function MiniProgramBubble({
|
||||
}: {
|
||||
data: Extract<ParsedContent, { type: 'miniProgram' }>
|
||||
sessionId?: string
|
||||
onImageClick?: (imageUrl: string) => void
|
||||
onImageClick?: ImageClickHandler
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<div className="mini-program-message">
|
||||
@@ -374,11 +441,17 @@ function StickerBubble({
|
||||
function QuoteBubble({
|
||||
data,
|
||||
sessionId,
|
||||
localId,
|
||||
serverId,
|
||||
createTime,
|
||||
onImageClick
|
||||
}: {
|
||||
data: Extract<ParsedContent, { type: 'quote' }>
|
||||
sessionId?: string
|
||||
onImageClick?: (imageUrl: string) => void
|
||||
localId?: number
|
||||
serverId?: string
|
||||
createTime?: number
|
||||
onImageClick?: ImageClickHandler
|
||||
}): JSX.Element {
|
||||
const quotedText = data.quotedContent || data.content || '[引用消息]'
|
||||
const replyText = data.content || data.title || ''
|
||||
@@ -400,6 +473,9 @@ function QuoteBubble({
|
||||
imageMd5={data.quotedImageMd5}
|
||||
imageDatName={data.quotedImageDatName}
|
||||
sessionId={sessionId}
|
||||
localId={localId}
|
||||
serverId={serverId}
|
||||
createTime={createTime}
|
||||
isThumb
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import type { JSX, MouseEvent } from 'react'
|
||||
|
||||
interface VideoBubbleProps {
|
||||
md5?: string
|
||||
newMd5?: string
|
||||
rawMd5?: string
|
||||
sessionId?: string
|
||||
localId?: number
|
||||
serverId?: string
|
||||
createTime?: number
|
||||
byteLength?: number
|
||||
duration?: number
|
||||
@@ -15,6 +20,9 @@ export function VideoBubble({
|
||||
md5,
|
||||
newMd5,
|
||||
rawMd5,
|
||||
sessionId,
|
||||
localId,
|
||||
serverId,
|
||||
createTime,
|
||||
byteLength,
|
||||
duration,
|
||||
@@ -26,13 +34,50 @@ export function VideoBubble({
|
||||
[md5, newMd5, rawMd5]
|
||||
)
|
||||
const [media, setMedia] = useState<{ url?: string; poster?: string; error?: string }>({})
|
||||
const [downloadingVideo, setDownloadingVideo] = useState(false)
|
||||
const [contextMenuPos, setContextMenuPos] = useState<{ x: number; y: number } | null>(null)
|
||||
const menuRef = useRef<HTMLDivElement>(null)
|
||||
const mountedRef = useRef(true)
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!contextMenuPos) return
|
||||
const handlePointerDown = (event: globalThis.MouseEvent): void => {
|
||||
if (menuRef.current && menuRef.current.contains(event.target as Node)) return
|
||||
setContextMenuPos(null)
|
||||
}
|
||||
const handleKeyDown = (event: globalThis.KeyboardEvent): void => {
|
||||
if (event.key === 'Escape') {
|
||||
setContextMenuPos(null)
|
||||
}
|
||||
}
|
||||
const handleScroll = (): void => {
|
||||
setContextMenuPos(null)
|
||||
}
|
||||
window.addEventListener('mousedown', handlePointerDown, true)
|
||||
window.addEventListener('keydown', handleKeyDown, true)
|
||||
window.addEventListener('scroll', handleScroll, true)
|
||||
return () => {
|
||||
window.removeEventListener('mousedown', handlePointerDown, true)
|
||||
window.removeEventListener('keydown', handleKeyDown, true)
|
||||
window.removeEventListener('scroll', handleScroll, true)
|
||||
}
|
||||
}, [contextMenuPos])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
window.api
|
||||
.getVideo(hashes, { createTime, byteLength, duration, width, height })
|
||||
.then((result) => {
|
||||
if (!cancelled) setMedia(result.success ? result : { error: result.error })
|
||||
if (!cancelled) {
|
||||
setMedia(result.success ? result : { poster: result.poster, error: result.error })
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!cancelled) setMedia({ error: error instanceof Error ? error.message : String(error) })
|
||||
@@ -42,20 +87,150 @@ export function VideoBubble({
|
||||
}
|
||||
}, [byteLength, createTime, duration, hashes, height, width])
|
||||
|
||||
const handleOpenContextMenu = (event: MouseEvent): void => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const menuWidth = 152
|
||||
const menuHeight = 88
|
||||
const maxX =
|
||||
typeof window !== 'undefined'
|
||||
? Math.max(8, window.innerWidth - menuWidth - 8)
|
||||
: event.clientX
|
||||
const maxY =
|
||||
typeof window !== 'undefined'
|
||||
? Math.max(8, window.innerHeight - menuHeight - 8)
|
||||
: event.clientY
|
||||
setContextMenuPos({
|
||||
x: Math.min(Math.max(8, event.clientX), maxX),
|
||||
y: Math.min(Math.max(8, event.clientY), maxY)
|
||||
})
|
||||
}
|
||||
|
||||
const handleDownloadVideo = async (event?: MouseEvent): Promise<void> => {
|
||||
event?.preventDefault()
|
||||
event?.stopPropagation()
|
||||
setContextMenuPos(null)
|
||||
if (downloadingVideo) return
|
||||
|
||||
setDownloadingVideo(true)
|
||||
try {
|
||||
const result = await window.api.downloadVideo({
|
||||
sessionId,
|
||||
localId,
|
||||
serverId,
|
||||
createTime,
|
||||
md5,
|
||||
newMd5,
|
||||
rawMd5
|
||||
})
|
||||
if (!mountedRef.current) return
|
||||
if (!result.success || !result.url) {
|
||||
alert(result.error ? `视频下载失败:${result.error}` : '视频下载失败')
|
||||
return
|
||||
}
|
||||
setMedia({
|
||||
url: result.url,
|
||||
poster: result.poster || media.poster
|
||||
})
|
||||
} catch (error) {
|
||||
if (!mountedRef.current) return
|
||||
alert(error instanceof Error ? `视频下载失败:${error.message}` : '视频下载失败')
|
||||
} finally {
|
||||
if (mountedRef.current) setDownloadingVideo(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopyMessageXml = async (event: MouseEvent): Promise<void> => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
setContextMenuPos(null)
|
||||
try {
|
||||
const result = await window.api.getImageMessageXml({
|
||||
sessionId,
|
||||
localId,
|
||||
serverId,
|
||||
createTime
|
||||
})
|
||||
if (!result.success || !result.xml) {
|
||||
alert(result.error ? `XML 获取失败:${result.error}` : 'XML 获取失败')
|
||||
return
|
||||
}
|
||||
await navigator.clipboard.writeText(result.xml)
|
||||
alert('视频消息 XML 已复制')
|
||||
} catch (error) {
|
||||
alert(error instanceof Error ? `XML 复制失败:${error.message}` : 'XML 复制失败')
|
||||
}
|
||||
}
|
||||
|
||||
const renderContextMenu = (): JSX.Element | null => {
|
||||
if (!contextMenuPos || typeof document === 'undefined') return null
|
||||
return createPortal(
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="image-bubble-context-menu"
|
||||
role="menu"
|
||||
aria-label="视频右键菜单"
|
||||
style={{ left: `${contextMenuPos.x}px`, top: `${contextMenuPos.y}px` }}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className="image-bubble-context-item"
|
||||
disabled={downloadingVideo}
|
||||
onClick={(event) => void handleDownloadVideo(event)}
|
||||
>
|
||||
{downloadingVideo ? '正在下载视频...' : '下载视频'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
className="image-bubble-context-item"
|
||||
onClick={(event) => void handleCopyMessageXml(event)}
|
||||
>
|
||||
复制 XML
|
||||
</button>
|
||||
</div>,
|
||||
document.body
|
||||
)
|
||||
}
|
||||
|
||||
if (!media.url) {
|
||||
return <div className="video-placeholder">{media.error || '视频加载中…'}</div>
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className="video-placeholder"
|
||||
onContextMenu={handleOpenContextMenu}
|
||||
title="右键可下载视频或复制 XML"
|
||||
>
|
||||
{downloadingVideo ? '正在从微信下载视频…' : media.error || '视频加载中…'}
|
||||
</div>
|
||||
{renderContextMenu()}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="video-message">
|
||||
<video
|
||||
className="video-content"
|
||||
src={media.url}
|
||||
poster={media.poster}
|
||||
controls
|
||||
preload="metadata"
|
||||
/>
|
||||
{duration ? <span className="video-duration">{duration} 秒</span> : null}
|
||||
</div>
|
||||
<>
|
||||
<div className="video-message" onContextMenu={handleOpenContextMenu}>
|
||||
<video
|
||||
className="video-content"
|
||||
src={media.url}
|
||||
poster={media.poster}
|
||||
controls
|
||||
preload="metadata"
|
||||
/>
|
||||
{downloadingVideo ? (
|
||||
<span className="video-duration">正在下载视频…</span>
|
||||
) : duration ? (
|
||||
<span className="video-duration">{duration} 秒</span>
|
||||
) : null}
|
||||
</div>
|
||||
{renderContextMenu()}
|
||||
</>
|
||||
)
|
||||
}
|
||||
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user