Merge pull request #326 from SnowLuma/dev
chore: promote dev → main (f968687)
This commit is contained in:
27 files changed
+458
-190
No files matched your search
@@ -12,19 +12,26 @@
|
||||
|
||||
<p align="center">
|
||||
<a href="#快速开始">快速开始</a> ·
|
||||
<a href="#运行链路">运行链路</a> ·
|
||||
<a href="./docs/onebot-actions.md">动作参考</a> ·
|
||||
<a href="./packages/sdk/README.md">SDK</a> ·
|
||||
<a href="./packages/mcp/README.md">MCP</a> ·
|
||||
<a href="https://github.com/SnowLuma/SnowLuma/issues">问题反馈</a>
|
||||
</p>
|
||||
|
||||
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时。它把 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口;每个账号拥有独立会话,适合机器人开发、自动化与协议研究。
|
||||
SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生会话转换为 [OneBot v11](https://github.com/botuniverse/onebot-11) 动作与事件,并通过 WebSocket、HTTP、WebUI、SDK 和 MCP 提供统一入口。
|
||||
|
||||
> [!CAUTION]
|
||||
> **使用边界**:SnowLuma 是独立的第三方互操作项目,**与腾讯 / QQ 无任何隶属或授权关系**。本项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供、不附带任何担保,使用风险自负。详见 [`EULA.md`](EULA.md)。
|
||||
> SnowLuma 是独立的第三方项目,与腾讯 / QQ 无隶属或授权关系。项目仅供学习与技术研究,请遵守《QQ 用户协议》及适用法律;软件按“现状”提供,使用风险自负。详见 [`EULA.md`](EULA.md)。
|
||||
>
|
||||
> **Disclaimer**: SnowLuma is an independent third-party interoperability project with no affiliation with or endorsement by Tencent / QQ. It is provided for study and research only, “as is” and without warranty. See [`EULA.md`](EULA.md).
|
||||
> **Disclaimer:** SnowLuma is independent of Tencent / QQ and is provided for study and research only, “as is” and without warranty.
|
||||
|
||||
## 核心能力
|
||||
|
||||
| 场景 | 能力 |
|
||||
| --- | --- |
|
||||
| OneBot 接入 | OneBot v11 动作与事件;WebSocket 服务端 / 客户端及 HTTP 服务端 / 上报 |
|
||||
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及常见卡片 |
|
||||
| 多账号运行 | 各账号独立维护会话、身份映射、消息存储和网络配置 |
|
||||
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试和存储管理 |
|
||||
| 开发者工具 | [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
|
||||
|
||||
## 运行链路
|
||||
|
||||
@@ -32,94 +39,33 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时。它把 QQ 原
|
||||
<img src="./assets/readme/runtime-map.svg" width="100%" alt="QQ 会话经过协议桥接与 OneBot 标准化后连接到 WebSocket、HTTP、WebUI、SDK 和 MCP" />
|
||||
</p>
|
||||
|
||||
SnowLuma 将会话接入、协议解析、身份映射、OneBot 转换和网络适配拆成清晰边界。多个 QQ 账号可以并行运行,同时保持独立状态、日志与连接配置。
|
||||
|
||||
## 核心能力
|
||||
|
||||
| 场景 | SnowLuma 提供 |
|
||||
| --- | --- |
|
||||
| OneBot 接入 | OneBot v11 动作与事件,支持 WebSocket 服务端 / 客户端、HTTP 服务端 / 上报及同端口复用 |
|
||||
| 消息与媒体 | 文本、图片、语音、视频、文件、回复、提及、转发及 JSON / XML 卡片等常见消息元素 |
|
||||
| 多账号运行 | 每个 QQ 账号独立维护会话、身份映射、消息存储与网络适配器 |
|
||||
| WebUI 管理 | 账号状态、实时日志、连接配置、动作调试、存储管理、密码管理与可定制总览 |
|
||||
| 开发者工具 | 提供 [`@snowluma/sdk`](packages/sdk/README.md) 与 [`@snowluma/mcp`](packages/mcp/README.md) |
|
||||
| 可观察错误 | 关键解析与执行失败会留下明确上下文,不以静默丢弃掩盖问题 |
|
||||
会话接入、协议解析、身份映射、OneBot 转换和网络适配保持独立边界;多个 QQ 账号可并行运行。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 选择发行包
|
||||
1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载对应平台的完整发行包并解压。Lite 版需 Node.js 22.13+(23 系需 23.4+)。
|
||||
2. Windows 运行 `launcher.bat`;Linux 执行:
|
||||
|
||||
前往 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载与你的平台匹配的版本:
|
||||
```bash
|
||||
chmod +x launcher.sh
|
||||
./launcher.sh
|
||||
```
|
||||
|
||||
| 平台 | 完整版(内置 Node.js,推荐) | Lite(Node.js 22.13+;23 系需 23.4+) |
|
||||
| --- | --- | --- |
|
||||
| Windows x64 | `SnowLuma-vX.Y.Z-win-x64.zip` | `SnowLuma-vX.Y.Z-win-x64-lite.zip` |
|
||||
| Linux x64 | `SnowLuma-vX.Y.Z-linux-x64.tar.gz` | `SnowLuma-vX.Y.Z-linux-x64-lite.tar.gz` |
|
||||
| Linux arm64 | `SnowLuma-vX.Y.Z-linux-arm64.tar.gz` | `SnowLuma-vX.Y.Z-linux-arm64-lite.tar.gz` |
|
||||
3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。
|
||||
|
||||
完整版适合直接解压运行;Lite 版只移除了内置 Node.js,其余运行时依赖与 WebUI 静态资源保持一致。
|
||||
## 接入与文档
|
||||
|
||||
### 2. 启动 SnowLuma
|
||||
| 入口 | 文档 |
|
||||
| --- | --- |
|
||||
| WebSocket / HTTP | [OneBot 动作参考](docs/onebot-actions.md) |
|
||||
| TypeScript SDK | [`packages/sdk/README.md`](packages/sdk/README.md) |
|
||||
| MCP | [`packages/mcp/README.md`](packages/mcp/README.md) |
|
||||
|
||||
Windows 运行 `launcher.bat`。Linux 在解压目录执行:
|
||||
JSON 消息段接受标准的 `data.data` 字符串,也兼容 `data.data` 非数组对象和 `{ type: "json", data: "..." }` 简写;`data` 必填,最终内容必须是 JSON 对象。
|
||||
|
||||
```bash
|
||||
chmod +x launcher.sh
|
||||
./launcher.sh
|
||||
```
|
||||
## 开发
|
||||
|
||||
### 3. 打开 WebUI
|
||||
|
||||
浏览器访问 [`http://localhost:5099`](http://localhost:5099)。初始账号为 `admin`,随机密码会显示在启动日志中;首次登录后,WebUI 会在同一个引导流程中完成协议确认与访问密码设置,随后即可接入已启动的 QQ 进程并配置 OneBot 连接。
|
||||
|
||||
<details>
|
||||
<summary><strong>无人值守部署:通过环境变量确认协议</strong></summary>
|
||||
|
||||
同时设置以下两个变量可跳过 WebUI 首次使用引导中的协议确认步骤:
|
||||
|
||||
```bash
|
||||
SNOWLUMA_ACCEPT_EULA=1
|
||||
SNOWLUMA_ACCEPT_PRIVACY=1
|
||||
```
|
||||
|
||||
两项必须同时设置,且环境变量确认不会写入持久化同意记录。设置变量即表示运营者已阅读并同意 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md)。
|
||||
|
||||
全新无人值守部署还可以使用 `SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD` 预设 WebUI 密码(至少 8 位);由该变量初始化的密码不再要求进入强制修改步骤。已有 `config/webui.json` 时仍以现有凭据为准。
|
||||
|
||||
</details>
|
||||
|
||||
## 可选:登录时补齐云端历史
|
||||
|
||||
WebUI 的账号“通用设置”可开启登录历史补齐,默认关闭,并在下次登录或重启后生效。该功能只把缺失的 QQ 云端漫游消息静默写入 SnowLuma 本地历史库,不重放 OneBot 事件,也不改变 QQ 已读状态。
|
||||
|
||||
花名册预热完成后会等待 30 秒,且进程内一次只为一个账号执行自动补齐。每次登录最多扫描 100 个群和 100 位好友,优先续补本地已知缺口,每类最多处理 3 个会话;每个会话最多读取 20 条消息,自动请求之间至少间隔 2 秒,失败后本次登录不重试。
|
||||
|
||||
## 日志与存储管理
|
||||
|
||||
WebUI 的“系统设置 → 存储管理”可查看受管数据占用、调整日志策略,并清理日志、非活动传输临时文件或离线账号的消息、媒体和表情回应数据库。清理范围固定,不包含配置、凭据或其他文件。
|
||||
|
||||
| 设置 | 默认值 | 环境变量 |
|
||||
| --- | --- | --- |
|
||||
| 日志树总量上限 | 1024 MB | `SNOWLUMA_LOG_MAX_TOTAL_MB` |
|
||||
| 日志保留天数 | 7 天;`0` 表示关闭按日期清理 | `SNOWLUMA_LOG_RETAIN_DAYS` |
|
||||
| 按账号额外写日志 | 关闭 | `SNOWLUMA_LOG_PER_UIN` |
|
||||
|
||||
以上环境变量优先于 `config/runtime.json`,对应字段会在 WebUI 中显示为锁定。`SNOWLUMA_LOG_MAX_MB` 仅控制单个日志分卷大小,不是日志树总量上限。
|
||||
|
||||
文件日志等级可通过 `SNOWLUMA_LOG_FILE_LEVEL` 单独设置为 `debug`、`info`、`success`、`warn` 或 `error`,默认为 `debug`。该启动参数不写入 `config/runtime.json`,也不受 WebUI 实时日志等级影响;TRACE 始终不落盘。
|
||||
|
||||
## 选择接入方式
|
||||
|
||||
| 入口 | 适合场景 | 参考 |
|
||||
| --- | --- | --- |
|
||||
| WebSocket / HTTP | 对接现有 OneBot 机器人框架 | [OneBot 动作参考](docs/onebot-actions.md) |
|
||||
| TypeScript SDK | 编写类型安全的客户端与消息逻辑 | [`packages/sdk`](packages/sdk/README.md) |
|
||||
| MCP | 让支持 MCP 的工具查询或调用 SnowLuma 动作 | [`packages/mcp`](packages/mcp/README.md) |
|
||||
| WebUI | 管理运行状态、日志、账号与连接 | 启动后访问 `http://localhost:5099` |
|
||||
|
||||
## 开发与贡献
|
||||
|
||||
本地开发需要 Node.js 22.13+(23 系需 23.4+)与项目锁定的 pnpm 10.28.0。所有日常开发基于 `dev` 分支:
|
||||
需要 Node.js 22.13+(23 系需 23.4+)与 pnpm 10.28.0,日常开发基于 `dev` 分支:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SnowLuma/SnowLuma.git
|
||||
@@ -127,51 +73,26 @@ cd SnowLuma
|
||||
git checkout dev
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
pnpm test
|
||||
pnpm run build:all
|
||||
```
|
||||
|
||||
`pnpm test` 会运行所有声明了常规测试的 workspace;`pnpm test:all` 是兼容别名,`pnpm test:core` 只运行 Core 测试。原生模块测试需单独运行 `pnpm test:native`。`pnpm coverage` 会生成各常规测试 workspace 的覆盖率报告,但不设置覆盖率阻断阈值。
|
||||
|
||||
- 先读 [`CONTEXT.md`](CONTEXT.md) 了解模块边界与项目词汇。
|
||||
- 提交代码前阅读 [`CONTRIBUTING.md`](CONTRIBUTING.md) 与 [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md)。
|
||||
- 开发方向与已完成事项见 [`RoadMap.md`](RoadMap.md)。
|
||||
|
||||
<details>
|
||||
<summary><strong>主要目录</strong></summary>
|
||||
|
||||
| 路径 | 作用 |
|
||||
| --- | --- |
|
||||
| `packages/protocol` | QQ 协议定义、数据包解析、消息推送与 OIDB 服务 |
|
||||
| `packages/onebot` | OneBot 动作执行、事件转换与网络适配 |
|
||||
| `packages/core` | 运行时编排、QQ 会话桥接与 WebUI 服务端 |
|
||||
| `packages/webui` | React 管理界面 |
|
||||
| `packages/sdk` | 对外发布的 TypeScript SDK |
|
||||
| `packages/mcp` | 面向 MCP 客户端的动作目录与执行入口 |
|
||||
|
||||
</details>
|
||||
贡献流程见 [`CONTRIBUTING.md`](CONTRIBUTING.md);模块边界与项目词汇见 [`CONTEXT.md`](CONTEXT.md);开发方向见 [`RoadMap.md`](RoadMap.md)。
|
||||
|
||||
## 使用边界与许可
|
||||
|
||||
> [!IMPORTANT]
|
||||
> SnowLuma 使用 **源码可见非商业许可**,**不是 OSI 开源许可**。源码可用于查看、学习、非商业自托管及私下修改;任何商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。
|
||||
> SnowLuma 使用**源码可见非商业许可**,不是 OSI 开源许可。源码可用于查看、学习、非商业自托管及私下修改;商业使用,以及公开发布修改版或衍生版,均需事先取得书面授权。
|
||||
|
||||
- 完整条款见 [`LICENSE`](LICENSE)。
|
||||
- 随附的原生附加组件为专有组件,不在源码许可范围内。
|
||||
- 二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束。
|
||||
- 商业授权请联系 `motricseven@foxmail.com`。
|
||||
完整条款见 [`LICENSE`](LICENSE);二进制发行包另受 [`EULA.md`](EULA.md) 与 [`PRIVACY.md`](PRIVACY.md) 约束;商业授权请联系 `motricseven@foxmail.com`。随附的原生附加组件为专有组件,不在源码许可范围内。
|
||||
|
||||
SnowLuma is source-available for study and non-commercial self-hosting, but it is **not OSI open source**. Commercial use and public distribution of modified or derivative versions require prior written permission. Bundled native components are proprietary and excluded from the source license.
|
||||
SnowLuma is source-available for study and non-commercial self-hosting, but it is not OSI open source. Commercial use and public distribution of modified or derivative versions require prior written permission.
|
||||
|
||||
## 社区与支持
|
||||
## 社区与鸣谢
|
||||
|
||||
- [提交问题](https://github.com/SnowLuma/SnowLuma/issues)
|
||||
- [QQ 群](https://qm.qq.com/q/g3UMLpWALe)
|
||||
- [Telegram](https://t.me/napcatqq)
|
||||
|
||||
## 鸣谢
|
||||
|
||||
项目参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。
|
||||
|
||||
<p align="center">
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
|
||||
@@ -27,7 +27,7 @@ const nullableString = { type: ['string', 'null'] };
|
||||
const faceSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
q_sid: { type: 'string', description: '表情编号' },
|
||||
q_sid: { type: 'string', description: 'QQ 表情目录标识(部分 emoji 为 Unicode 表情字符串)' },
|
||||
q_des: { type: 'string', description: '表情描述' },
|
||||
em_code: { type: 'string' },
|
||||
q_cid: nullableInteger,
|
||||
|
||||
@@ -318,11 +318,14 @@ export const ELEMENT_CODECS = {
|
||||
return { type: 'json', data: { data: element.text ?? '' } };
|
||||
},
|
||||
async fromSegment(data) {
|
||||
const text = data.data;
|
||||
const raw = data.data;
|
||||
const text = typeof raw === 'object' && raw !== null && !Array.isArray(raw)
|
||||
? JSON.stringify(raw)
|
||||
: raw;
|
||||
if (typeof text !== 'string' || !text.trim()) {
|
||||
throw new MessageElementValidationError(
|
||||
'INVALID_FIELD',
|
||||
'message segment "json" field "data" must be a non-empty JSON string',
|
||||
'message segment "json" field "data" must be a JSON object or non-empty JSON string',
|
||||
'json',
|
||||
'data',
|
||||
);
|
||||
|
||||
@@ -53,7 +53,7 @@ export function parseCQParams(raw: string): Record<string, string> {
|
||||
|
||||
interface MessageSegment {
|
||||
type: string;
|
||||
data?: Record<string, unknown>;
|
||||
data?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -152,12 +152,18 @@ function validatedOutboundElement(element: MessageElement): MessageElement {
|
||||
|
||||
function assertScalarSegmentData(type: string, data: Record<string, unknown>): void {
|
||||
for (const [field, value] of Object.entries(data)) {
|
||||
const isJsonObjectField = type === 'json'
|
||||
&& (field === 'data' || field === 'config')
|
||||
&& typeof value === 'object'
|
||||
&& value !== null
|
||||
&& !Array.isArray(value);
|
||||
if (
|
||||
value === undefined
|
||||
|| value === null
|
||||
|| typeof value === 'string'
|
||||
|| typeof value === 'number'
|
||||
|| typeof value === 'boolean'
|
||||
|| isJsonObjectField
|
||||
) continue;
|
||||
throw new MessageElementValidationError(
|
||||
'INVALID_FIELD',
|
||||
@@ -207,11 +213,11 @@ function requireCoordinate(
|
||||
export async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
|
||||
const normalizedType = normalizeSegmentType(type);
|
||||
|
||||
// Ordinary OneBot segment fields are scalar. Reject objects/arrays before
|
||||
// codecs can stringify them into "[object Object]" and alter caller intent.
|
||||
// Forward nodes deliberately own nested content but are rejected by their
|
||||
// dedicated normal-send branch below; anonymous is rejected regardless of
|
||||
// payload, so neither needs the scalar guard.
|
||||
// Ordinary OneBot segment fields are scalar. JSON deliberately accepts its
|
||||
// object-valued data/config compatibility fields; every other object/array
|
||||
// is rejected before a codec can coerce it and alter caller intent. Forward
|
||||
// nodes own nested content but are rejected by their dedicated normal-send
|
||||
// branch below; anonymous is rejected regardless of payload.
|
||||
if (normalizedType !== 'node' && normalizedType !== 'anonymous') {
|
||||
assertScalarSegmentData(normalizedType, data);
|
||||
}
|
||||
@@ -248,12 +254,19 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
const musicType = requireNonEmptyStringField(normalizedType, data, 'type');
|
||||
// Non-custom platform names are deliberately open: musicSignUrl is
|
||||
// configurable and private signers may support platforms beyond the
|
||||
// built-in NapCat set. Their executable contract is non-empty type+id.
|
||||
if (musicType === 'custom') {
|
||||
// built-in NapCat set. NapCat also treats an id-less platform-labelled
|
||||
// segment as custom music data, so presence of id selects platform mode.
|
||||
const hasMusicId = data.id !== undefined
|
||||
&& data.id !== null
|
||||
&& String(data.id).trim() !== '';
|
||||
const hasCustomMusicData = ['url', 'audio', 'title', 'image', 'content']
|
||||
.some((field) => Object.prototype.hasOwnProperty.call(data, field));
|
||||
const usesCustomMusicData = musicType === 'custom' || (!hasMusicId && hasCustomMusicData);
|
||||
if (usesCustomMusicData) {
|
||||
requireNonEmptyStringField(normalizedType, data, 'url');
|
||||
requireNonEmptyStringField(normalizedType, data, 'audio');
|
||||
requireNonEmptyStringField(normalizedType, data, 'title');
|
||||
} else if (data.id === undefined || data.id === null || String(data.id).trim() === '') {
|
||||
} else if (!hasMusicId) {
|
||||
throw new MessageElementValidationError(
|
||||
'MISSING_FIELD',
|
||||
'message segment "music" requires field "id" for a platform card',
|
||||
@@ -264,9 +277,9 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
const signUrl = options?.musicSignUrl || 'https://ss.xingzhige.com/music_card/card';
|
||||
try {
|
||||
let postData: Record<string, unknown>;
|
||||
if (musicType === 'custom') {
|
||||
if (usesCustomMusicData) {
|
||||
postData = {
|
||||
type: 'custom',
|
||||
type: musicType,
|
||||
id: undefined,
|
||||
url: String(data.url ?? ''),
|
||||
audio: String(data.audio ?? ''),
|
||||
@@ -408,6 +421,9 @@ function segmentPayload(seg: MessageSegment): Record<string, unknown> {
|
||||
const topLevel = { ...seg } as Record<string, unknown>;
|
||||
delete topLevel.type;
|
||||
delete topLevel.data;
|
||||
if (normalizeSegmentType(seg.type) === 'json' && typeof seg.data === 'string') {
|
||||
return { ...topLevel, data: seg.data };
|
||||
}
|
||||
const nested = (seg.data && typeof seg.data === 'object' && !Array.isArray(seg.data))
|
||||
? seg.data
|
||||
: {};
|
||||
|
||||
@@ -88,6 +88,33 @@ describe('outbound message validation at the Action boundary', () => {
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sends object-valued JSON cards from AstrBot-compatible clients', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
const ref = instanceContext(bridgeSend);
|
||||
const api = new ApiHandler({
|
||||
sendGroupMessage: (groupId, message, autoEscape) =>
|
||||
sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
} as ApiActionContext);
|
||||
|
||||
const response = await api.handle('send_group_msg', {
|
||||
group_id: 12345,
|
||||
message: [{
|
||||
type: 'json',
|
||||
data: {
|
||||
data: { app: 'com.tencent.music.lua', meta: { music: { title: '晴天' } } },
|
||||
config: { token: 'signed-token' },
|
||||
},
|
||||
}],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({ status: 'ok', retcode: 0 });
|
||||
expect(bridgeSend).toHaveBeenCalledOnce();
|
||||
expect(bridgeSend.mock.calls[0]?.[1]).toEqual([{
|
||||
type: 'json',
|
||||
text: '{"app":"com.tencent.music.lua","meta":{"music":{"title":"晴天"}}}',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('reports the public data field when a JSON segment uses data.text', async () => {
|
||||
const bridgeSend = vi.fn();
|
||||
const ref = instanceContext(bridgeSend);
|
||||
@@ -107,7 +134,7 @@ describe('outbound message validation at the Action boundary', () => {
|
||||
expect(response).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
wording: 'message segment "json" field "data" must be a non-empty JSON string',
|
||||
wording: 'message segment "json" field "data" must be a JSON object or non-empty JSON string',
|
||||
});
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -168,7 +168,7 @@ describe('parseMessage', () => {
|
||||
)).resolves.toEqual([{ type: 'text', text: ' ' }]);
|
||||
});
|
||||
|
||||
it('rejects object-valued fields instead of stringifying caller input', async () => {
|
||||
it('rejects object-valued fields for scalar-only segments', async () => {
|
||||
await expect(parseMessage(
|
||||
[{ type: 'text', data: { text: { bad: true } } }] as any,
|
||||
false,
|
||||
@@ -177,14 +177,6 @@ describe('parseMessage', () => {
|
||||
elementType: 'text',
|
||||
field: 'text',
|
||||
});
|
||||
await expect(parseMessage(
|
||||
[{ type: 'json', data: { data: { app: 'unexpected-object' } } }] as any,
|
||||
false,
|
||||
)).rejects.toMatchObject({
|
||||
code: 'INVALID_FIELD',
|
||||
elementType: 'json',
|
||||
field: 'data',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses face segment', async () => {
|
||||
@@ -586,6 +578,52 @@ describe('parseMessage', () => {
|
||||
expect(result[0].text).toBe('{"app":"test"}');
|
||||
});
|
||||
|
||||
it('accepts an object JSON payload produced by AstrBot-compatible clients', async () => {
|
||||
const result = await parseMessage(
|
||||
[{
|
||||
type: 'json',
|
||||
data: {
|
||||
data: {
|
||||
app: 'com.tencent.music.lua',
|
||||
meta: { music: { title: '晴天' } },
|
||||
},
|
||||
config: { token: 'signed-token' },
|
||||
},
|
||||
}] as any,
|
||||
false,
|
||||
);
|
||||
|
||||
expect(result).toEqual([{
|
||||
type: 'json',
|
||||
text: '{"app":"com.tencent.music.lua","meta":{"music":{"title":"晴天"}}}',
|
||||
}]);
|
||||
});
|
||||
|
||||
it('accepts the JSON raw-string segment shorthand used by compatible clients', async () => {
|
||||
await expect(parseMessage(
|
||||
[{ type: 'json', data: '{"app":"com.tencent.music.lua"}' }] as any,
|
||||
false,
|
||||
)).resolves.toEqual([{
|
||||
type: 'json',
|
||||
text: '{"app":"com.tencent.music.lua"}',
|
||||
}]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ label: 'array', value: [] },
|
||||
{ label: 'null', value: null },
|
||||
{ label: 'number', value: 1 },
|
||||
])('rejects a $label JSON payload instead of sending a non-object card', async ({ value }) => {
|
||||
await expect(parseMessage(
|
||||
[{ type: 'json', data: { data: value } }] as any,
|
||||
false,
|
||||
)).rejects.toMatchObject({
|
||||
code: 'INVALID_FIELD',
|
||||
elementType: 'json',
|
||||
field: 'data',
|
||||
});
|
||||
});
|
||||
|
||||
it('reads canonical xml resid and file_size fields', async () => {
|
||||
const xml = await parseMessage(
|
||||
[{ type: 'xml', data: { data: '<msg/>', resid: '35' } }] as any,
|
||||
@@ -729,6 +767,48 @@ describe('parseMessage', () => {
|
||||
expect(parsed.meta.contact.type).toBe('group');
|
||||
});
|
||||
|
||||
it('accepts id-less custom music data with a platform type for NapCat compatibility', async () => {
|
||||
const card = JSON.stringify({
|
||||
app: 'com.tencent.structmsg',
|
||||
view: 'music',
|
||||
prompt: '[音乐]光',
|
||||
});
|
||||
const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => ({
|
||||
ok: true,
|
||||
text: async () => card,
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
try {
|
||||
const result = await parseMessage(
|
||||
[{
|
||||
type: 'music',
|
||||
data: {
|
||||
type: '163',
|
||||
url: 'https://music.example/song/3402687142',
|
||||
audio: 'https://cdn.example/3402687142.mp3',
|
||||
title: '光',
|
||||
image: 'https://cdn.example/3402687142.jpg',
|
||||
content: '陈粒',
|
||||
},
|
||||
}] as any,
|
||||
false,
|
||||
);
|
||||
|
||||
expect(result).toEqual([{ type: 'json', text: card }]);
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
|
||||
type: '163',
|
||||
url: 'https://music.example/song/3402687142',
|
||||
audio: 'https://cdn.example/3402687142.mp3',
|
||||
title: '光',
|
||||
image: 'https://cdn.example/3402687142.jpg',
|
||||
singer: '陈粒',
|
||||
});
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it('parses signed music cards and buildSendElems preserves non-ASCII JSON', async () => {
|
||||
const card = JSON.stringify({
|
||||
app: 'com.tencent.structmsg',
|
||||
|
||||
@@ -31,6 +31,32 @@ describe('system face actions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves Unicode catalog identifiers in the public catalog response', async () => {
|
||||
const unicodeFace = {
|
||||
...FACE,
|
||||
qSid: '😊',
|
||||
qDes: '/嘿嘿',
|
||||
qCid: 128522,
|
||||
emCode: '400832',
|
||||
aniStickerType: null,
|
||||
aniStickerPackId: null,
|
||||
aniStickerId: null,
|
||||
};
|
||||
const fetchCatalog = vi.fn(async () => [{ packName: 'emoji', emojis: [unicodeFace] }]);
|
||||
|
||||
const response = await handler({ fetchCatalog }).handle('fetch_sys_faces', {});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'ok',
|
||||
data: {
|
||||
packs: [{
|
||||
pack_name: 'emoji',
|
||||
emojis: [{ q_sid: '😊', q_des: '/嘿嘿', q_cid: 128522, em_code: '400832' }],
|
||||
}],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('looks up one id without redownloading a fresh catalog', async () => {
|
||||
const fetchFace = vi.fn(async () => FACE);
|
||||
const response = await handler({ fetchFace }).handle('fetch_face_entity', { face_id: '392' });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/proto-defs",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
// 0x9154_1 — system face / emoji catalog (sysface) protobuf shapes.
|
||||
//
|
||||
// Mirrors Lagrange.Core's FetchFullSysFacesService response: one round-trip
|
||||
// returns every pack — common faces, "big"/super animated faces, and the
|
||||
// magic-face pack. Each emoji carries its `aniSticker*` metadata, which the
|
||||
// send path uses to pick the right wire encoding for a face id (classic
|
||||
// FaceElem vs CommonElem 37/33). See protocol/oidb-services/sys-faces.
|
||||
// 0x9154_1 — QQ system face / emoji catalog protobuf shapes.
|
||||
|
||||
import type { pb, pb_repeated, int_32 } from '@snowluma/proton';
|
||||
|
||||
@@ -47,10 +41,15 @@ export interface OidbFaceMagicContent {
|
||||
resourceUrl?: pb<2, OidbFaceResourceUrl>;
|
||||
}
|
||||
|
||||
export interface OidbFetchSysFacesExpInfo {
|
||||
field1?: pb<1, string>;
|
||||
}
|
||||
|
||||
export interface OidbFetchSysFacesReq {
|
||||
field1?: pb<1, int_32>;
|
||||
field2?: pb<2, int_32>;
|
||||
field3?: pb<3, string>;
|
||||
field3?: pb<3, int_32>;
|
||||
field4?: pb<4, OidbFetchSysFacesExpInfo>;
|
||||
}
|
||||
|
||||
export interface OidbFetchSysFacesResp {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
// 0x9154_1 — fetch the bot's system face / emoji catalog.
|
||||
//
|
||||
// Mirrors Lagrange.Core's `FetchFullSysFacesService`. One server round-trip
|
||||
// returns the entire pack list — common faces, "big"/super faces (the giant
|
||||
// animated emoji), and the magic-face pack. The send path uses each emoji's
|
||||
// `aniSticker*` metadata to pick the right wire encoding for a face id (see
|
||||
// element-builder's makeFaceElem + sys-face-store).
|
||||
// QQ returns the common, special-big, and magic-face panels in one response.
|
||||
// The send path uses the catalog metadata to select the corresponding face
|
||||
// element encoding (see element-builder and sys-face-store).
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
protobuf_decode,
|
||||
protobuf_encode,
|
||||
protobuf_getUnknownFieldMetadata,
|
||||
} from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbFaceEmoji,
|
||||
@@ -15,8 +18,11 @@ import type {
|
||||
} from '@snowluma/proto-defs/oidb-actions/sys-faces';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
|
||||
/** A single system face / emoji. Field names match Lagrange's `SysFaceEntry`;
|
||||
* `qSid` is the numeric face ID as a string. */
|
||||
const log = createLogger('SysFace');
|
||||
|
||||
/** A single system face / emoji. `qSid` is QQ's opaque catalog identifier:
|
||||
* numeric system faces use decimal strings, while emoji groups may use a
|
||||
* Unicode emoji string. */
|
||||
export interface SysFaceEntry {
|
||||
qSid: string;
|
||||
qDes: string;
|
||||
@@ -37,9 +43,44 @@ export interface SysFacePackEntry {
|
||||
emojis: SysFaceEntry[];
|
||||
}
|
||||
|
||||
function emojiToEntry(e: OidbFaceEmoji): SysFaceEntry {
|
||||
interface FaceLocation {
|
||||
source: 'common' | 'special-big' | 'magic';
|
||||
packIndex: number;
|
||||
faceIndex: number;
|
||||
}
|
||||
|
||||
function emojiToEntry(e: OidbFaceEmoji, location: FaceLocation): SysFaceEntry | null {
|
||||
const qSid = e.qSid;
|
||||
if (qSid == null || qSid === '') {
|
||||
const metadata = protobuf_getUnknownFieldMetadata(e);
|
||||
const unexpectedIdFields = metadata.fields.filter((field) => field.fieldNumber === 1);
|
||||
if (unexpectedIdFields.length > 0) {
|
||||
throw new Error(
|
||||
`system face id uses unsupported wire encoding at source ${location.source}, `
|
||||
+ `pack ${location.packIndex}, face ${location.faceIndex}: `
|
||||
+ `wireTypes=${unexpectedIdFields.map((field) => field.wireType).join(',')}`,
|
||||
);
|
||||
}
|
||||
log.warn(
|
||||
'system face catalog skipped entry without id: source=%s pack=%d face=%d '
|
||||
+ 'hasDescription=%s hasCode=%s unknownFields=%d',
|
||||
location.source,
|
||||
location.packIndex,
|
||||
location.faceIndex,
|
||||
Boolean(e.qDes),
|
||||
Boolean(e.emCode),
|
||||
metadata.totalOccurrences,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (typeof qSid !== 'string') {
|
||||
throw new Error(
|
||||
`system face id has invalid decoded type at source ${location.source}, `
|
||||
+ `pack ${location.packIndex}, face ${location.faceIndex}: ${typeof qSid}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
qSid: e.qSid ?? '',
|
||||
qSid,
|
||||
qDes: e.qDes ?? '',
|
||||
emCode: e.emCode ?? '',
|
||||
qCid: e.qCid ?? null,
|
||||
@@ -53,6 +94,19 @@ function emojiToEntry(e: OidbFaceEmoji): SysFaceEntry {
|
||||
};
|
||||
}
|
||||
|
||||
function emojisToEntries(
|
||||
emojis: OidbFaceEmoji[],
|
||||
source: FaceLocation['source'],
|
||||
packIndex: number,
|
||||
): SysFaceEntry[] {
|
||||
const entries: SysFaceEntry[] = [];
|
||||
for (const [faceIndex, emoji] of emojis.entries()) {
|
||||
const entry = emojiToEntry(emoji, { source, packIndex, faceIndex });
|
||||
if (entry) entries.push(entry);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
export namespace FetchSysFaces {
|
||||
export const command = 0x9154;
|
||||
export const subCommand = 1;
|
||||
@@ -63,27 +117,35 @@ export namespace FetchSysFaces {
|
||||
export const serialize = (_ctx: Deps, _p: Params): OidbFetchSysFacesReq => ({
|
||||
field1: 0,
|
||||
field2: 7,
|
||||
field3: '0',
|
||||
field3: 0,
|
||||
});
|
||||
|
||||
export const deserialize = (_ctx: Deps, body: OidbFetchSysFacesResp): SysFacePackEntry[] => {
|
||||
const packs: SysFacePackEntry[] = [];
|
||||
|
||||
// common + special-big share the same content shape.
|
||||
for (const content of [body.commonFace, body.specialBigFace]) {
|
||||
for (const [source, content] of [
|
||||
['common', body.commonFace],
|
||||
['special-big', body.specialBigFace],
|
||||
] as const) {
|
||||
for (const list of content?.emojiList ?? []) {
|
||||
const packIndex = packs.length;
|
||||
packs.push({
|
||||
packName: list.emojiPackName ?? '',
|
||||
emojis: (list.emojiDetail ?? []).map(emojiToEntry),
|
||||
emojis: emojisToEntries(list.emojiDetail ?? [], source, packIndex),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Magic faces arrive as a single un-named bundle — Lagrange tags it
|
||||
// "MagicFace" client-side, so we match for parity.
|
||||
// QQ returns magic faces as a single unnamed bundle. Keep a stable local
|
||||
// name so callers can identify the group across refreshes.
|
||||
const magicEmojis = body.specialMagicFace?.field1?.emojiList ?? [];
|
||||
if (magicEmojis.length > 0) {
|
||||
packs.push({ packName: 'MagicFace', emojis: magicEmojis.map(emojiToEntry) });
|
||||
const packIndex = packs.length;
|
||||
packs.push({
|
||||
packName: 'MagicFace',
|
||||
emojis: emojisToEntries(magicEmojis, 'magic', packIndex),
|
||||
});
|
||||
}
|
||||
|
||||
return packs;
|
||||
@@ -110,10 +172,7 @@ export function findFaceEntity(packs: SysFacePackEntry[], faceId: number): SysFa
|
||||
return null;
|
||||
}
|
||||
|
||||
/** True when `faceId` is an animated "super face" — has both aniStickerType
|
||||
* and aniStickerPackId set, and is NOT the (1,1) pack (the regular static
|
||||
* emojis). Matches Lagrange's `GetUniqueSuperQSids` filter. Super faces ride
|
||||
* CommonElem serviceType 37 (QFaceExtra); the (1,1) ones ride serviceType 33. */
|
||||
/** True when the catalog metadata selects the existing super-face send path. */
|
||||
export function isSuperFaceEntry(emoji: SysFaceEntry): boolean {
|
||||
if (emoji.aniStickerType == null || emoji.aniStickerPackId == null) return false;
|
||||
return !(emoji.aniStickerType === 1 && emoji.aniStickerPackId === 1);
|
||||
|
||||
@@ -295,9 +295,11 @@ function validateCatalog(packs: SysFacePackEntry[]): SysFacePackEntry[] {
|
||||
throw new Error(`invalid system face pack at index ${packIndex}`);
|
||||
}
|
||||
for (const [faceIndex, face] of pack.emojis.entries()) {
|
||||
if (!face || typeof face.qSid !== 'string' || !/^(?:0|[1-9]\d*)$/.test(face.qSid)
|
||||
|| !Number.isSafeInteger(Number(face.qSid)) || Number(face.qSid) < 0) {
|
||||
throw new Error(`invalid system face id at pack ${packIndex}, face ${faceIndex}`);
|
||||
if (!face || typeof face.qSid !== 'string' || face.qSid.length === 0) {
|
||||
throw new Error(
|
||||
`invalid system face id at pack ${packIndex}, face ${faceIndex}: `
|
||||
+ `value=${JSON.stringify(face?.qSid)}`,
|
||||
);
|
||||
}
|
||||
if (seen.has(face.qSid)) {
|
||||
throw new Error(`duplicate system face id ${face.qSid}`);
|
||||
|
||||
@@ -2,7 +2,10 @@ import { describe, it, expect } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbFetchSysFacesResp } from '@snowluma/proto-defs/oidb-actions/sys-faces';
|
||||
import type {
|
||||
OidbFetchSysFacesReq,
|
||||
OidbFetchSysFacesResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/sys-faces';
|
||||
import {
|
||||
FetchSysFaces,
|
||||
findFaceEntity,
|
||||
@@ -100,6 +103,27 @@ describe('faceWireFor — classification', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('FetchSysFaces protocol contract', () => {
|
||||
it('encodes the native 0x9154_1 request layout', () => {
|
||||
const body = FetchSysFaces.serialize({} as never, {});
|
||||
expect(body).toEqual({
|
||||
field1: 0,
|
||||
field2: 7,
|
||||
field3: 0,
|
||||
});
|
||||
|
||||
const decoded = protobuf_decode<OidbBase<OidbFetchSysFacesReq>>(
|
||||
FetchSysFaces.encode({ body }),
|
||||
);
|
||||
expect(decoded.body).toEqual({
|
||||
field1: null,
|
||||
field2: 7,
|
||||
field3: null,
|
||||
field4: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('FetchSysFaces.deserialize', () => {
|
||||
it('flattens common + big + magic packs', () => {
|
||||
const packs = FetchSysFaces.deserialize({} as never, {
|
||||
@@ -110,6 +134,43 @@ describe('FetchSysFaces.deserialize', () => {
|
||||
expect(packs.map((p) => p.packName)).toEqual(['经典', '超级', 'MagicFace']);
|
||||
expect(packs[1].emojis[0].aniStickerType).toBe(3);
|
||||
});
|
||||
|
||||
it('preserves Unicode catalog identifiers returned by QQ', () => {
|
||||
const packs = FetchSysFaces.deserialize({} as never, {
|
||||
commonFace: {
|
||||
emojiList: [{
|
||||
emojiPackName: 'emoji',
|
||||
emojiDetail: [{ qSid: '😊', qDes: '/嘿嘿', qCid: 128522, emCode: '400832' }],
|
||||
}],
|
||||
},
|
||||
} as never);
|
||||
|
||||
expect(packs).toEqual([{
|
||||
packName: 'emoji',
|
||||
emojis: [expect.objectContaining({
|
||||
qSid: '😊',
|
||||
qDes: '/嘿嘿',
|
||||
qCid: 128522,
|
||||
emCode: '400832',
|
||||
})],
|
||||
}]);
|
||||
});
|
||||
|
||||
it('fails closed when an id field uses an unsupported wire encoding', () => {
|
||||
const driftedFace = { qDes: '/未知表情' };
|
||||
Object.defineProperty(driftedFace, Symbol.for('snowluma.proton.unknownFields'), {
|
||||
value: {
|
||||
fields: [{ fieldNumber: 1, wireType: 0, count: 1, totalByteLength: 1 }],
|
||||
totalOccurrences: 1,
|
||||
omittedOccurrences: 0,
|
||||
omittedByteLength: 0,
|
||||
},
|
||||
});
|
||||
|
||||
expect(() => FetchSysFaces.deserialize({} as never, {
|
||||
specialMagicFace: { field1: { emojiList: [driftedFace] } },
|
||||
} as never)).toThrow(/unsupported wire encoding.*wireTypes=0/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SysFaceStore — persistent catalog and query seam', () => {
|
||||
@@ -151,6 +212,37 @@ describe('SysFaceStore — persistent catalog and query seam', () => {
|
||||
expect(store.search('经典').map((face) => face.qSid)).toEqual(['14']);
|
||||
});
|
||||
|
||||
it('persists and searches Unicode catalog ids without exposing them as numeric face ids', async () => {
|
||||
const unicodeFace = entry('😊', null, null, null, '/嘿嘿');
|
||||
unicodeFace.qCid = 128522;
|
||||
unicodeFace.emCode = '400832';
|
||||
const catalog: SysFacePackEntry[] = [{ packName: 'emoji', emojis: [unicodeFace] }];
|
||||
const storage = new MemoryCatalogStorage();
|
||||
const store = new SysFaceStore({
|
||||
storage,
|
||||
now: () => 456,
|
||||
fetchCatalog: async () => catalog,
|
||||
});
|
||||
|
||||
await expect(store.refresh(sender)).resolves.toEqual(catalog);
|
||||
|
||||
expect(storage.saved[0]?.packs).toEqual(catalog);
|
||||
expect(store.search('😊').map((face) => face.qSid)).toEqual(['😊']);
|
||||
expect(store.search('嘿嘿').map((face) => face.qSid)).toEqual(['😊']);
|
||||
expect(store.lookup(128522)).toBeNull();
|
||||
});
|
||||
|
||||
it('still rejects empty and duplicate catalog identifiers', () => {
|
||||
const store = new SysFaceStore();
|
||||
|
||||
expect(() => store.load([{ packName: 'emoji', emojis: [entry('', null, null, null)] }]))
|
||||
.toThrow(/invalid system face id/);
|
||||
expect(() => store.load([{
|
||||
packName: 'emoji',
|
||||
emojis: [entry('😊', null, null, null), entry('😊', null, null, null)],
|
||||
}])).toThrow(/duplicate system face id/);
|
||||
});
|
||||
|
||||
it('coalesces concurrent refreshes and persists the authoritative result once', async () => {
|
||||
const storage = new MemoryCatalogStorage();
|
||||
let fetches = 0;
|
||||
@@ -178,6 +270,42 @@ describe('SysFaceStore — persistent catalog and query seam', () => {
|
||||
}]);
|
||||
});
|
||||
|
||||
it('keeps usable faces when a server pack contains an id-less record', async () => {
|
||||
const storage = new MemoryCatalogStorage();
|
||||
const response = FetchSysFaces.deserialize(sender, {
|
||||
commonFace: {
|
||||
emojiList: [
|
||||
{ emojiPackName: '经典', emojiDetail: [{ qSid: '14', qDes: '/微笑' }] },
|
||||
{ emojiPackName: '小表情', emojiDetail: [{ qSid: '424', qDes: '/比心' }] },
|
||||
],
|
||||
},
|
||||
specialBigFace: {
|
||||
emojiList: [{
|
||||
emojiPackName: '超级表情',
|
||||
emojiDetail: [{ qSid: '392', qDes: '/龙年快乐' }],
|
||||
}],
|
||||
},
|
||||
specialMagicFace: {
|
||||
field1: {
|
||||
emojiList: [
|
||||
{ qDes: '/目录占位' },
|
||||
{ qSid: '999', qDes: '/魔法表情' },
|
||||
],
|
||||
},
|
||||
},
|
||||
} as never);
|
||||
const store = new SysFaceStore({
|
||||
storage,
|
||||
now: () => 456,
|
||||
fetchCatalog: async () => response,
|
||||
});
|
||||
|
||||
await expect(store.refresh(sender)).resolves.toHaveLength(4);
|
||||
expect(store.lookup(14)?.qDes).toBe('/微笑');
|
||||
expect(store.lookup(999)?.qDes).toBe('/魔法表情');
|
||||
expect(storage.saved[0]?.packs[3]?.emojis.map((face) => face.qSid)).toEqual(['999']);
|
||||
});
|
||||
|
||||
it('refreshes a cache miss once, then keeps an authoritative not-found result', async () => {
|
||||
const storage = new MemoryCatalogStorage({
|
||||
schemaVersion: 1,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/proton",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/runtime",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "@snowluma/websocket",
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"name": "webui",
|
||||
"private": true,
|
||||
"version": "1.14.1",
|
||||
"version": "1.14.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -139,11 +139,14 @@ function AuthBoundary({ onboardingSteps }: { onboardingSteps: AdditionalOnboardi
|
||||
if (ok) {
|
||||
setAuthed(true);
|
||||
setStatus('已连接');
|
||||
setMustChange(await client.mustChangePassword());
|
||||
const [nextMustChange] = await Promise.all([
|
||||
client.mustChangePassword(),
|
||||
refreshAgreements(),
|
||||
]);
|
||||
setMustChange(nextMustChange);
|
||||
// Carry the URL password into the forced change-password gate so it
|
||||
// needn't re-prompt for the old password (matches the login flow).
|
||||
if (urlPassword) setLoginPassword(urlPassword);
|
||||
await refreshAgreements();
|
||||
}
|
||||
setAuthChecked(true);
|
||||
})();
|
||||
|
||||
@@ -55,7 +55,11 @@ export function useOneBotInstanceConfig(
|
||||
): UseOneBotInstanceConfig {
|
||||
const api = useApi();
|
||||
const { runAction } = useActionFeedback();
|
||||
const { selectedUin, onSelectedUinChange } = options;
|
||||
const { onSelectedUinChange } = options;
|
||||
// Start the first config request in the same render that receives the account
|
||||
// list; publishing the selection upward remains an effect, but no longer adds
|
||||
// an otherwise unnecessary render before the network request can begin.
|
||||
const selectedUin = options.selectedUin ?? accounts[0]?.uin ?? null;
|
||||
const [config, setConfigState] = useState<OneBotConfig | null>(null);
|
||||
const [loadedUin, setLoadedUin] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -71,10 +75,10 @@ export function useOneBotInstanceConfig(
|
||||
const selectedUinRef = useRef(selectedUin);
|
||||
selectedUinRef.current = selectedUin;
|
||||
|
||||
// Auto-select first account when none is selected yet.
|
||||
// Publish the derived first selection so the sidebar and later routes retain it.
|
||||
useEffect(() => {
|
||||
if (!selectedUin && accounts.length > 0) onSelectedUinChange(accounts[0].uin);
|
||||
}, [accounts, selectedUin, onSelectedUinChange]);
|
||||
if (options.selectedUin === null && selectedUin) onSelectedUinChange(selectedUin);
|
||||
}, [options.selectedUin, selectedUin, onSelectedUinChange]);
|
||||
|
||||
// Load on UIN change. The api client already runs normalizeOneBotConfig.
|
||||
useEffect(() => {
|
||||
|
||||
Reference in new issue
Block a user